inventory.py 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634
  1. import json
  2. import logging
  3. from contextlib import AsyncExitStack
  4. from datetime import date, datetime, timezone
  5. import httpx
  6. from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
  7. from fastapi.responses import Response, StreamingResponse
  8. from pydantic import BaseModel, Field, field_validator
  9. from sqlalchemy import case, delete, func, select
  10. from sqlalchemy.exc import IntegrityError
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from sqlalchemy.orm import selectinload
  13. from backend.app.core.auth import (
  14. ApiKeyActor,
  15. RequestActor,
  16. RequestPrinterScope,
  17. RequireAnyPermissionIfAuthEnabled,
  18. RequirePermissionIfAuthEnabled,
  19. RequirePrinterPermissionIfAuthEnabled,
  20. require_auth_if_enabled,
  21. )
  22. from backend.app.core.catalog_defaults import DEFAULT_COLOR_CATALOG, DEFAULT_SPOOL_CATALOG
  23. from backend.app.core.database import get_db
  24. from backend.app.core.permissions import Permission
  25. from backend.app.core.printer_scope import PrinterScope
  26. from backend.app.core.websocket import ws_manager
  27. from backend.app.models.ams_label import AmsLabel
  28. from backend.app.models.color_catalog import ColorCatalogEntry
  29. from backend.app.models.filament_profile_default import FilamentProfileDefault
  30. from backend.app.models.location import Location
  31. from backend.app.models.printer import Printer
  32. from backend.app.models.settings import Settings
  33. from backend.app.models.spool import Spool
  34. from backend.app.models.spool_assignment import SpoolAssignment
  35. from backend.app.models.spool_catalog import SpoolCatalogEntry
  36. from backend.app.models.spool_filament_preset import SpoolFilamentPreset
  37. from backend.app.models.spool_k_profile import SpoolKProfile
  38. from backend.app.models.supplier import SpoolmanSpoolSupplier, SpoolSupplier, Supplier, supplier_name_key
  39. from backend.app.models.user import User
  40. from backend.app.schemas.filament_profile_default import (
  41. FilamentProfileDefaultResponse,
  42. FilamentProfileDefaultWrite,
  43. ProfileDefaultApplyResult,
  44. ResolvedProfileDefault,
  45. )
  46. from backend.app.schemas.location import LocationCreate, LocationResponse, LocationUpdate
  47. from backend.app.schemas.not_null import IgnoresNullForRequiredColumns
  48. from backend.app.schemas.spool import (
  49. MaterialNumberStats,
  50. SpoolAssignmentCreate,
  51. SpoolAssignmentResponse,
  52. SpoolBulkCreate,
  53. SpoolCreate,
  54. SpoolFilamentPresetBase,
  55. SpoolFilamentPresetResponse,
  56. SpoolKProfileBase,
  57. SpoolKProfileResponse,
  58. SpoolResponse,
  59. SpoolUpdate,
  60. normalize_effect_type,
  61. normalize_extra_colors,
  62. )
  63. from backend.app.schemas.spool_usage import SpoolUsageHistoryResponse
  64. from backend.app.schemas.supplier import (
  65. SpoolSupplierLinkInput,
  66. SpoolSupplierResponse,
  67. SupplierCreate,
  68. SupplierResponse,
  69. SupplierStats,
  70. SupplierUpdate,
  71. )
  72. from backend.app.services import filament_profile_default as profile_defaults, slot_unlink_grace, spool_swaps
  73. from backend.app.services.ams_assignment_lock import get_ams_assignment_lock, get_spool_move_lock
  74. from backend.app.services.ams_slot_presence import spool_present
  75. from backend.app.services.location_service import (
  76. DUPLICATE_LOCATION_NAME,
  77. assign_location_name,
  78. count_internal_spools_at_location,
  79. get_location_by_id,
  80. get_location_by_name,
  81. location_name_key,
  82. prepare_internal_spool_payload,
  83. rename_location as rename_location_record,
  84. )
  85. from backend.app.services.material_number import apply_material_number_inheritance
  86. from backend.app.services.slicer_filament_resolver import resolve_slicer_filament, reusable_slot_filament_id
  87. from backend.app.services.slot_nozzle import resolve_slot_nozzle
  88. from backend.app.services.spool_csv import (
  89. MAX_CSV_IMPORT_BYTES,
  90. ImportPreview,
  91. ImportResult,
  92. parse_and_validate,
  93. serialize,
  94. )
  95. from backend.app.services.spool_filament_preset import resolve_spool_preset
  96. from backend.app.services.spoolman import SpoolmanClient, get_spoolman_client, init_spoolman_client
  97. from backend.app.services.supplier_links import apply_supplier_inheritance, apply_supplier_inheritance_to_batch
  98. from backend.app.services.tag_conflict import tag_already_linked
  99. from backend.app.utils.filament_finish import finish_generic_id
  100. from backend.app.utils.filament_ids import (
  101. GENERIC_FILAMENT_IDS,
  102. filament_id_to_setting_id,
  103. normalize_slicer_filament,
  104. )
  105. from backend.app.utils.filament_types import nozzle_temp_range, printer_filament_type
  106. from backend.app.utils.local_time import day_zone, local_date_end, local_date_start
  107. from backend.app.utils.natural_sort import natural_sort_key
  108. from backend.app.utils.tag_normalization import normalize_tag_uid, normalize_tray_uuid
  109. from backend.app.utils.tray_ids import external_tray_id
  110. logger = logging.getLogger(__name__)
  111. router = APIRouter(prefix="/inventory", tags=["inventory"])
  112. def spool_response_loads():
  113. """Loader options for every query that answers with a ``SpoolResponse``.
  114. Both relationships the schema reads carry the default loader, so the ~50
  115. other ``select(Spool)`` call sites across the usage tracker, AMS sync,
  116. labels and backup pay nothing for them (#2988).
  117. """
  118. return (
  119. selectinload(Spool.k_profiles),
  120. selectinload(Spool.supplier_links).selectinload(SpoolSupplier.supplier),
  121. )
  122. async def load_preset_lookup_user(db: AsyncSession, user_id: int | None) -> User | None:
  123. """The user whose cloud sign-in resolves a spool's preset, by id (#3519).
  124. For callers that have no signed-in user of their own: an API key (its
  125. owner) and the replay on insert (whoever made the assignment). Without
  126. one, a custom cloud preset (PFUS/PFCN) can't be looked up when each user
  127. signs in to the cloud separately, and the slot gets a generic filament.
  128. None for no id or a deactivated user. Groups are loaded because the
  129. resolver asks the user for permissions.
  130. """
  131. if user_id is None:
  132. return None
  133. result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
  134. user = result.scalar_one_or_none()
  135. return user if user is not None and user.is_active else None
  136. # Bounded read size for the CSV import body so a chunked upload with no
  137. # Content-Length can't stream past the cap into memory before we notice.
  138. _CSV_UPLOAD_CHUNK_BYTES = 64 * 1024
  139. # FilamentColors.xyz API
  140. FILAMENT_COLORS_API = "https://filamentcolors.xyz/api"
  141. async def apply_spool_to_slot_via_mqtt(
  142. *,
  143. db: AsyncSession,
  144. current_user: User | None,
  145. spool: Spool,
  146. printer_id: int,
  147. ams_id: int,
  148. tray_id: int,
  149. current_tray_info_idx: str = "",
  150. current_tray_type: str = "",
  151. current_tray_sub_brands: str = "",
  152. ) -> bool:
  153. """Publish ams_filament_setting + extrusion_cali_sel for a spool on a slot.
  154. Shared by `assign_spool` (initial assign for a loaded slot) and
  155. `on_ams_change` (re-fire when a SpoolBuddy-pre-assigned slot transitions
  156. empty → loaded). Returns True when MQTT commands were published, False if
  157. no client was available or setup failed mid-way.
  158. `current_tray_info_idx` / `current_tray_type` describe the live tray state
  159. used as fallback hints when the spool's slicer_filament can't be resolved.
  160. Caller should not pass these for the empty-slot re-fire path (they'll be
  161. the freshly-loaded values, which is the intended fallback).
  162. """
  163. from backend.app.services.printer_manager import printer_manager
  164. client = printer_manager.get_client(printer_id)
  165. if client is None:
  166. return False
  167. state = printer_manager.get_status(printer_id)
  168. # The slot carries the material type; the product line the material column
  169. # may actually hold ("PLA+", "HTPLA") stays in tray_sub_brands below, which
  170. # is where Bambu puts it too (issue #2902).
  171. tray_type = printer_filament_type(spool.material)
  172. # Join only the parts that exist. The previous shape interpolated
  173. # `spool.subtype` into the branded string without checking it, so a spool
  174. # with a brand and no subtype went to the printer as
  175. # "Sunlu PLA Matte None" -- the string "None", on the wire (#2987). The
  176. # unbranded branch guarded subtype; the branded one did not.
  177. tray_sub_brands = " ".join(p for p in (spool.brand, spool.material, spool.subtype) if p) or spool.material
  178. tray_color = spool.rgba or "FFFFFFFF"
  179. # Which nozzle this slot feeds, and how wide it is. One resolution shared
  180. # with every other path that configures a slot (see services.slot_nozzle),
  181. # and used twice below -- for the spool's per-model preset override and for
  182. # its K profile -- so the two lookups cannot answer for different nozzles.
  183. slot_nozzle = resolve_slot_nozzle(state, ams_id, tray_id, printer_manager.get_model(printer_id))
  184. nozzle_diameter = slot_nozzle.diameter
  185. # A cloud or Orca preset is bound to a printer MODEL ("@BBL X1C"), so the
  186. # spool's single slicer_filament stops being right the moment the same
  187. # spool is used on a second model. resolve_spool_preset returns the
  188. # spool's own value unless the user has set an override for this model,
  189. # so a spool nobody has configured behaves exactly as it did before.
  190. slot_slicer_filament, slot_slicer_filament_name = await resolve_spool_preset(
  191. db,
  192. spool_id=spool.id,
  193. printer_model=printer_manager.get_model(printer_id),
  194. nozzle_diameter=nozzle_diameter,
  195. fallback_filament=spool.slicer_filament,
  196. fallback_name=spool.slicer_filament_name,
  197. )
  198. # slicer_filament → (tray_info_idx, setting_id) resolution is shared with
  199. # the Spoolman-mode route via this helper (#1713). The helper handles
  200. # GFS/PFUS/PFCN cloud lookup, GF normalize, integer LocalPreset id,
  201. # the builtin-name realignment, AND the defensive PFUS/PFCN/material-name
  202. # sanitization. When it returns an empty tray_info_idx the local
  203. # current-tray-state + generic-material fallback below rescues the slot.
  204. tray_info_idx, setting_id, sub_brand_override, type_override = await resolve_slicer_filament(
  205. db=db,
  206. current_user=current_user,
  207. slicer_filament=slot_slicer_filament,
  208. slicer_filament_name=slot_slicer_filament_name,
  209. material=spool.material,
  210. )
  211. if sub_brand_override:
  212. tray_sub_brands = sub_brand_override
  213. # A preset says what its material is; the reduction above only infers it
  214. # from whatever wording the spool's material column happens to carry. When
  215. # the spool has a preset, its answer wins (issue #2902, @doncaruana).
  216. if type_override:
  217. tray_type = printer_filament_type(type_override)
  218. if not tray_info_idx:
  219. reused = reusable_slot_filament_id(
  220. current_tray_info_idx,
  221. current_tray_type,
  222. current_tray_sub_brands,
  223. tray_type,
  224. f"{spool.material or ''} {spool.subtype or ''}",
  225. )
  226. if reused:
  227. tray_info_idx = reused
  228. elif tray_type:
  229. # The spool's own wording is tried first and the reduced type only
  230. # as a further fallback, so a material that already resolves keeps
  231. # resolving to the same id: "PETG HF" has its own generic preset
  232. # (GFG96) that reducing it to "PETG" would trade away for GFG99.
  233. material = (spool.material or "").upper().strip()
  234. generic = (
  235. finish_generic_id(tray_type, f"{spool.material or ''} {spool.subtype or ''}")
  236. or GENERIC_FILAMENT_IDS.get(material)
  237. or GENERIC_FILAMENT_IDS.get(material.split("-")[0].split(" ")[0])
  238. or GENERIC_FILAMENT_IDS.get(tray_type.upper())
  239. or ""
  240. )
  241. if generic:
  242. tray_info_idx = generic
  243. # Ensure setting_id is always derivable from tray_info_idx. The local-preset
  244. # path above sets tray_info_idx to a generic ID (e.g. "GFL99") but leaves
  245. # setting_id empty — without this fallback the slicer gets a half-configured
  246. # slot (filament id without setting id) and shows empty fields in the slot
  247. # detail modal.
  248. if tray_info_idx and not setting_id:
  249. setting_id = filament_id_to_setting_id(tray_info_idx)
  250. # Same order as the generic-id lookup above: the spool's own wording wins,
  251. # the reduced type rescues what it does not cover. Without the second
  252. # lookup a PLA+ spool took the 200/240 catch-all instead of PLA's 190/230.
  253. temp_min, temp_max = nozzle_temp_range(spool.material, tray_type)
  254. if spool.nozzle_temp_min is not None:
  255. temp_min = spool.nozzle_temp_min
  256. if spool.nozzle_temp_max is not None:
  257. temp_max = spool.nozzle_temp_max
  258. slot_extruder = slot_nozzle.extruder
  259. # Prefer exact extruder match, fall back to extruder-agnostic kp for the
  260. # same nozzle. Hard-skipping on mismatch silently drops valid stored
  261. # profiles when the AMS-extruder mapping has shifted.
  262. exact_kp = None
  263. fallback_kp = None
  264. for kp in spool.k_profiles:
  265. if kp.printer_id != printer_id or kp.nozzle_diameter != nozzle_diameter:
  266. continue
  267. # A profile measured on a high-flow nozzle is not a fact about a
  268. # standard one. Rows with no stored flow -- everything saved before
  269. # this, and everything from a printer whose table declares none --
  270. # still match, see SlotNozzle.flow_matches.
  271. if not slot_nozzle.flow_matches(kp.nozzle_type):
  272. continue
  273. if slot_extruder is not None and kp.extruder is not None and kp.extruder == slot_extruder:
  274. exact_kp = kp
  275. break
  276. if fallback_kp is None:
  277. fallback_kp = kp
  278. matching_kp = exact_kp or fallback_kp
  279. # Resolve the printer-side calibration entry by looking up the cali_idx
  280. # in state.kprofiles. The printer keys its calibration table by
  281. # (filament_id, cali_idx) — for the cali_idx to stick, the slot's
  282. # filament_id must match the kp's. PFUS-prefix cloud user presets are
  283. # rejected by the slicer in tray_info_idx; the printer-reported
  284. # filament_id is typically a P-prefix local preset which is valid.
  285. printer_kp = None
  286. if matching_kp and matching_kp.cali_idx is not None and state and getattr(state, "kprofiles", None):
  287. for pkp in state.kprofiles:
  288. if pkp.slot_id == matching_kp.cali_idx and pkp.nozzle_diameter == nozzle_diameter:
  289. printer_kp = pkp
  290. break
  291. effective_tray_info_idx = tray_info_idx
  292. effective_setting_id = setting_id
  293. if printer_kp and printer_kp.filament_id:
  294. effective_tray_info_idx = printer_kp.filament_id
  295. target_setting_id = (printer_kp.setting_id if printer_kp else None) or (
  296. matching_kp.setting_id if matching_kp else None
  297. )
  298. if target_setting_id:
  299. effective_setting_id = target_setting_id
  300. if effective_tray_info_idx != tray_info_idx or effective_setting_id != setting_id:
  301. logger.info(
  302. "Spool assign: realigning tray_info_idx %r → %r, setting_id %r → %r (source=%s)",
  303. tray_info_idx,
  304. effective_tray_info_idx,
  305. setting_id,
  306. effective_setting_id,
  307. "printer" if printer_kp else "stored",
  308. )
  309. client.ams_set_filament_setting(
  310. ams_id=ams_id,
  311. tray_id=tray_id,
  312. tray_info_idx=effective_tray_info_idx,
  313. tray_type=tray_type,
  314. tray_sub_brands=tray_sub_brands,
  315. tray_color=tray_color,
  316. nozzle_temp_min=temp_min,
  317. nozzle_temp_max=temp_max,
  318. setting_id=effective_setting_id,
  319. )
  320. if matching_kp and matching_kp.cali_idx is not None:
  321. # filament_id for cali_sel must match the preset under which the kp
  322. # was registered. Priority: live printer kp > stored kp.setting_id >
  323. # spool.slicer_filament > realigned tray_info_idx.
  324. if printer_kp and printer_kp.filament_id:
  325. cali_filament_id = printer_kp.filament_id
  326. elif matching_kp.setting_id:
  327. cali_filament_id = normalize_slicer_filament(matching_kp.setting_id)[0] or matching_kp.setting_id
  328. else:
  329. cali_filament_id = spool.slicer_filament or effective_tray_info_idx
  330. client.extrusion_cali_sel(
  331. ams_id=ams_id,
  332. tray_id=tray_id,
  333. cali_idx=matching_kp.cali_idx,
  334. filament_id=cali_filament_id,
  335. nozzle_diameter=nozzle_diameter,
  336. )
  337. else:
  338. # No stored K-profile for this spool — always reset the slot to Default
  339. # K (cali_idx=-1). The live cali_idx on the slot belongs to whatever
  340. # filament was there before, so preserving it would apply the wrong
  341. # filament's calibration to the new spool. Default K is the firmware's
  342. # documented "no specific profile" value (see BambuClient.extrusion_cali_sel
  343. # docstring).
  344. cali_filament_id = spool.slicer_filament or effective_tray_info_idx
  345. client.extrusion_cali_sel(
  346. ams_id=ams_id,
  347. tray_id=tray_id,
  348. cali_idx=-1,
  349. filament_id=cali_filament_id,
  350. nozzle_diameter=nozzle_diameter,
  351. )
  352. logger.info(
  353. "No stored K-profile for spool %d — reset slot to Default K (cali_idx=-1)",
  354. spool.id,
  355. )
  356. # Register a read-back verification so the next AMS pushes can confirm the
  357. # tray actually accepted this assignment (#2582). We record the same
  358. # effective filament id we pushed plus the cali_idx we selected (or -1 for
  359. # the Default-K reset above), and the client fires on_assignment_verified
  360. # on match/timeout. Colour is informational only — the match keys on the
  361. # filament id the slicer echoes back.
  362. verify_cali_idx = matching_kp.cali_idx if (matching_kp and matching_kp.cali_idx is not None) else -1
  363. client.register_assignment_verification(
  364. ams_id=ams_id,
  365. tray_id=tray_id,
  366. tray_info_idx=effective_tray_info_idx,
  367. tray_color=tray_color,
  368. cali_idx=verify_cali_idx,
  369. )
  370. # Persist slot preset mapping for UI display (preset_name on hover card).
  371. # Shared with the RFID auto-assign path — both must keep this row in sync
  372. # with the currently-assigned spool, otherwise the slot card surfaces the
  373. # previous spool's preset name (the PrintersPage display chain consults
  374. # slot_preset_mappings.preset_name first).
  375. from backend.app.services.slot_preset_writer import upsert_slot_preset_for_spool
  376. await upsert_slot_preset_for_spool(
  377. db=db,
  378. spool=spool,
  379. printer_id=printer_id,
  380. ams_id=ams_id,
  381. tray_id=tray_id,
  382. tray_info_idx=tray_info_idx,
  383. tray_sub_brands=tray_sub_brands,
  384. tray_type=tray_type,
  385. setting_id=setting_id,
  386. configured_tray_info_idx=effective_tray_info_idx,
  387. )
  388. logger.info(
  389. "Auto-configured AMS slot ams=%d tray=%d for spool %d on printer %d",
  390. ams_id,
  391. tray_id,
  392. spool.id,
  393. printer_id,
  394. )
  395. return True
  396. # ── Spool Catalog Schemas ──────────────────────────────────────────────────
  397. class CatalogEntryResponse(BaseModel):
  398. id: int
  399. name: str
  400. weight: int
  401. is_default: bool
  402. class Config:
  403. from_attributes = True
  404. class CatalogEntryCreate(BaseModel):
  405. name: str
  406. weight: int
  407. class CatalogEntryUpdate(IgnoresNullForRequiredColumns):
  408. __orm_table__ = "spool_catalog"
  409. name: str
  410. weight: int
  411. class BulkDeleteIdsRequest(BaseModel):
  412. ids: list[int]
  413. # ── Color Catalog Schemas ──────────────────────────────────────────────────
  414. class ColorEntryResponse(BaseModel):
  415. id: int
  416. manufacturer: str
  417. color_name: str
  418. hex_color: str
  419. material: str | None
  420. is_default: bool
  421. extra_colors: str | None = None
  422. effect_type: str | None = None
  423. class Config:
  424. from_attributes = True
  425. _HEX_COLOR_PATTERN = r"^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$"
  426. class ColorEntryCreate(BaseModel):
  427. manufacturer: str
  428. color_name: str
  429. hex_color: str = Field(..., pattern=_HEX_COLOR_PATTERN)
  430. material: str | None = None
  431. extra_colors: str | None = None
  432. effect_type: str | None = None
  433. @field_validator("extra_colors")
  434. @classmethod
  435. def _validate_extra_colors(cls, v: str | None) -> str | None:
  436. return normalize_extra_colors(v)
  437. @field_validator("effect_type")
  438. @classmethod
  439. def _validate_effect_type(cls, v: str | None) -> str | None:
  440. return normalize_effect_type(v)
  441. class ColorEntryUpdate(IgnoresNullForRequiredColumns):
  442. __orm_table__ = "color_catalog"
  443. manufacturer: str
  444. color_name: str
  445. hex_color: str = Field(..., pattern=_HEX_COLOR_PATTERN)
  446. material: str | None = None
  447. extra_colors: str | None = None
  448. effect_type: str | None = None
  449. @field_validator("extra_colors")
  450. @classmethod
  451. def _validate_extra_colors(cls, v: str | None) -> str | None:
  452. return normalize_extra_colors(v)
  453. @field_validator("effect_type")
  454. @classmethod
  455. def _validate_effect_type(cls, v: str | None) -> str | None:
  456. return normalize_effect_type(v)
  457. class ColorLookupResult(BaseModel):
  458. found: bool
  459. hex_color: str | None = None
  460. material: str | None = None
  461. class ColorByMaterialResult(BaseModel):
  462. color_name: str | None = None
  463. # ── Spool Catalog CRUD ─────────────────────────────────────────────────────
  464. @router.get("/catalog", response_model=list[CatalogEntryResponse])
  465. async def get_spool_catalog(
  466. db: AsyncSession = Depends(get_db, scope="function"),
  467. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  468. ):
  469. """Get all spool catalog entries."""
  470. result = await db.execute(select(SpoolCatalogEntry).order_by(SpoolCatalogEntry.name))
  471. return list(result.scalars().all())
  472. @router.post("/catalog", response_model=CatalogEntryResponse)
  473. async def add_catalog_entry(
  474. entry: CatalogEntryCreate,
  475. db: AsyncSession = Depends(get_db, scope="function"),
  476. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  477. ):
  478. """Add a new spool catalog entry."""
  479. row = SpoolCatalogEntry(name=entry.name, weight=entry.weight, is_default=False)
  480. db.add(row)
  481. await db.commit()
  482. await db.refresh(row)
  483. return row
  484. @router.put("/catalog/{entry_id}", response_model=CatalogEntryResponse)
  485. async def update_catalog_entry(
  486. entry_id: int,
  487. entry: CatalogEntryUpdate,
  488. db: AsyncSession = Depends(get_db, scope="function"),
  489. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  490. ):
  491. """Update a spool catalog entry."""
  492. result = await db.execute(select(SpoolCatalogEntry).where(SpoolCatalogEntry.id == entry_id))
  493. row = result.scalar_one_or_none()
  494. if not row:
  495. raise HTTPException(404, "Entry not found")
  496. row.name = entry.name
  497. row.weight = entry.weight
  498. await db.commit()
  499. await db.refresh(row)
  500. return row
  501. @router.delete("/catalog/{entry_id}")
  502. async def delete_catalog_entry(
  503. entry_id: int,
  504. db: AsyncSession = Depends(get_db, scope="function"),
  505. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  506. ):
  507. """Delete a spool catalog entry."""
  508. result = await db.execute(select(SpoolCatalogEntry).where(SpoolCatalogEntry.id == entry_id))
  509. row = result.scalar_one_or_none()
  510. if not row:
  511. raise HTTPException(404, "Entry not found")
  512. await db.delete(row)
  513. await db.commit()
  514. return {"status": "deleted"}
  515. @router.post("/catalog/bulk-delete")
  516. async def bulk_delete_catalog_entries(
  517. data: BulkDeleteIdsRequest,
  518. db: AsyncSession = Depends(get_db, scope="function"),
  519. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  520. ):
  521. """Delete multiple spool catalog entries by ID."""
  522. if not data.ids:
  523. return {"deleted": 0}
  524. result = await db.execute(select(SpoolCatalogEntry).where(SpoolCatalogEntry.id.in_(data.ids)))
  525. rows = result.scalars().all()
  526. for row in rows:
  527. await db.delete(row)
  528. await db.commit()
  529. return {"deleted": len(rows)}
  530. @router.post("/catalog/reset")
  531. async def reset_spool_catalog(
  532. db: AsyncSession = Depends(get_db, scope="function"),
  533. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  534. ):
  535. """Reset spool catalog to defaults."""
  536. await db.execute(select(SpoolCatalogEntry)) # ensure table loaded
  537. # Delete all
  538. result = await db.execute(select(SpoolCatalogEntry))
  539. for row in result.scalars().all():
  540. await db.delete(row)
  541. # Re-seed defaults
  542. for name, weight in DEFAULT_SPOOL_CATALOG:
  543. db.add(SpoolCatalogEntry(name=name, weight=weight, is_default=True))
  544. await db.commit()
  545. return {"status": "reset"}
  546. # ── Storage Locations (#1004) ───────────────────────────────────────────────
  547. async def _load_settings_map(db: AsyncSession) -> dict[str, str]:
  548. result = await db.execute(select(Settings))
  549. return {s.key: s.value for s in result.scalars().all()}
  550. def _spoolman_is_enabled(settings: dict[str, str]) -> bool:
  551. return settings.get("spoolman_enabled", "false").lower() == "true"
  552. async def _ensure_spoolman_client(settings: dict[str, str]) -> SpoolmanClient | None:
  553. if not _spoolman_is_enabled(settings):
  554. return None
  555. url = settings.get("spoolman_url", "").strip()
  556. if not url:
  557. return None
  558. from backend.app.api.routes._spoolman_helpers import assert_safe_spoolman_url
  559. try:
  560. assert_safe_spoolman_url(url)
  561. except ValueError:
  562. return None
  563. client = await get_spoolman_client()
  564. if not client or client.base_url != url.rstrip("/"):
  565. client = await init_spoolman_client(url)
  566. return client
  567. async def _spool_counts_for_locations(
  568. db: AsyncSession,
  569. locations: list[Location],
  570. settings: dict[str, str],
  571. *,
  572. strict: bool = False,
  573. ) -> dict[int, int]:
  574. """Spools at each location. In Spoolman mode they are Spoolman's; when it
  575. can't be read the built-in counts are shown instead, which ``strict``
  576. refuses with a 503 (SM-C13): the built-in table holds no Spoolman spools,
  577. so a location still in use would count as empty and could be deleted."""
  578. if _spoolman_is_enabled(settings):
  579. client = await _ensure_spoolman_client(settings)
  580. if not client and strict:
  581. raise HTTPException(status_code=503, detail="Spoolman is unavailable")
  582. if client:
  583. try:
  584. spools = await client.get_all_spools(allow_archived=False)
  585. except Exception as exc:
  586. logger.warning("Failed to fetch Spoolman spools for location counts", exc_info=True)
  587. if strict:
  588. raise HTTPException(status_code=503, detail="Spoolman is unavailable") from exc
  589. else:
  590. # Use the canonical key helper so this matches what the
  591. # migration backfill, Location.name_key, and every other
  592. # codepath store as the case-insensitive lookup key. Plain
  593. # str.lower() drifts for non-ASCII (Turkish ı/İ, German ß)
  594. # and caused mismatched delete-block counts in Spoolman mode.
  595. by_key: dict[str, int] = {}
  596. for spool in spools:
  597. raw = spool.get("location")
  598. if not raw or not isinstance(raw, str) or not raw.strip():
  599. continue
  600. try:
  601. key = location_name_key(raw)
  602. except ValueError:
  603. continue
  604. by_key[key] = by_key.get(key, 0) + 1
  605. return {loc.id: by_key.get(loc.name_key, 0) for loc in locations}
  606. counts: dict[int, int] = {}
  607. for loc in locations:
  608. counts[loc.id] = await count_internal_spools_at_location(db, loc.id)
  609. return counts
  610. def _location_to_response(location: Location, spool_count: int) -> LocationResponse:
  611. return LocationResponse(
  612. id=location.id,
  613. name=location.name,
  614. identifier=location.identifier,
  615. spool_count=spool_count,
  616. created_at=location.created_at,
  617. updated_at=location.updated_at,
  618. )
  619. @router.get("/locations", response_model=list[LocationResponse])
  620. async def list_locations(
  621. db: AsyncSession = Depends(get_db, scope="function"),
  622. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  623. ):
  624. """List all storage locations with spool counts."""
  625. settings = await _load_settings_map(db)
  626. result = await db.execute(select(Location))
  627. # Sorted in Python, not SQL: "Drybox 2" belongs before "Drybox 10", and
  628. # ORDER BY name gives the opposite (plain lexicographic) order.
  629. locations = sorted(result.scalars().all(), key=lambda loc: natural_sort_key(loc.name))
  630. counts = await _spool_counts_for_locations(db, locations, settings)
  631. return [_location_to_response(loc, counts.get(loc.id, 0)) for loc in locations]
  632. @router.post("/locations", response_model=LocationResponse, status_code=201)
  633. async def create_location(
  634. data: LocationCreate,
  635. db: AsyncSession = Depends(get_db, scope="function"),
  636. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  637. ):
  638. """Create a storage location."""
  639. existing = await get_location_by_name(db, data.name)
  640. if existing:
  641. raise HTTPException(status_code=409, detail=DUPLICATE_LOCATION_NAME)
  642. location = Location(identifier=data.identifier)
  643. assign_location_name(location, data.name)
  644. db.add(location)
  645. try:
  646. await db.commit()
  647. except IntegrityError as exc:
  648. await db.rollback()
  649. raise HTTPException(status_code=409, detail=DUPLICATE_LOCATION_NAME) from exc
  650. await db.refresh(location)
  651. await ws_manager.broadcast({"type": "inventory_changed"})
  652. return _location_to_response(location, 0)
  653. @router.patch("/locations/{location_id}", response_model=LocationResponse)
  654. async def update_location(
  655. location_id: int,
  656. data: LocationUpdate,
  657. db: AsyncSession = Depends(get_db, scope="function"),
  658. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  659. ):
  660. """Update a storage location (rename propagates to assigned spools)."""
  661. location = await get_location_by_id(db, location_id)
  662. if not location:
  663. raise HTTPException(status_code=404, detail="Location not found")
  664. old_name = location.name
  665. if data.identifier is not None:
  666. location.identifier = data.identifier or None
  667. if data.name is not None and data.name != old_name:
  668. try:
  669. await rename_location_record(db, location, data.name)
  670. except ValueError as exc:
  671. raise HTTPException(status_code=409, detail=str(exc)) from exc
  672. # Cascade to Spoolman BEFORE the local commit so a Spoolman failure
  673. # rolls back the local rename instead of leaving the catalog and
  674. # Spoolman's per-spool `location` field permanently diverged. Without
  675. # this ordering, a partial failure makes the next location-sync recreate
  676. # the old name as a duplicate catalog row (#1505 review blocker).
  677. settings = await _load_settings_map(db)
  678. client = await _ensure_spoolman_client(settings)
  679. if client:
  680. try:
  681. await client.rename_location(old_name, location.name)
  682. except Exception as exc:
  683. logger.warning(
  684. "Spoolman location rename failed for %s -> %s: %s",
  685. old_name,
  686. location.name,
  687. exc,
  688. )
  689. await db.rollback()
  690. raise HTTPException(
  691. status_code=502,
  692. detail="Spoolman rename failed; local rename rolled back",
  693. ) from exc
  694. try:
  695. await db.commit()
  696. except IntegrityError as exc:
  697. await db.rollback()
  698. raise HTTPException(status_code=409, detail=DUPLICATE_LOCATION_NAME) from exc
  699. await db.refresh(location)
  700. settings = await _load_settings_map(db)
  701. counts = await _spool_counts_for_locations(db, [location], settings)
  702. await ws_manager.broadcast({"type": "inventory_changed"})
  703. return _location_to_response(location, counts.get(location.id, 0))
  704. @router.delete("/locations/{location_id}")
  705. async def delete_location(
  706. location_id: int,
  707. db: AsyncSession = Depends(get_db, scope="function"),
  708. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  709. ):
  710. """Delete a storage location when no spools are assigned."""
  711. location = await get_location_by_id(db, location_id)
  712. if not location:
  713. raise HTTPException(status_code=404, detail="Location not found")
  714. settings = await _load_settings_map(db)
  715. counts = await _spool_counts_for_locations(db, [location], settings, strict=True)
  716. if counts.get(location.id, 0) > 0:
  717. raise HTTPException(status_code=409, detail="Location has spools assigned and cannot be deleted")
  718. await db.delete(location)
  719. await db.commit()
  720. await ws_manager.broadcast({"type": "inventory_changed"})
  721. return {"status": "deleted"}
  722. # ── Supplier master list (#2988) ───────────────────────────────────────────
  723. #
  724. # Inventory master data that spools reference, exactly like Locations — so it
  725. # lives here, gated by the inventory permissions, not behind its own
  726. # permission set or a Settings page. Suppliers are *where filament is bought*,
  727. # distinct from ``Spool.brand`` (who made it).
  728. DUPLICATE_SUPPLIER_NAME = "A supplier with this name already exists"
  729. async def _supplier_by_name(db: AsyncSession, name: str, *, exclude_id: int | None = None) -> Supplier | None:
  730. """Case-insensitive name lookup behind the duplicate guard (#2988).
  731. Matches on the stored ``name_key``, so the comparison is the Python fold
  732. the CSV import also uses — ``func.lower()`` would have folded ASCII only
  733. on SQLite and let an umlaut'd case variant past the check.
  734. """
  735. query = select(Supplier).where(Supplier.name_key == supplier_name_key(name))
  736. if exclude_id is not None:
  737. query = query.where(Supplier.id != exclude_id)
  738. return (await db.execute(query)).scalars().first()
  739. async def _supplier_reference_counts(db: AsyncSession) -> dict[int, int]:
  740. """Spools referencing each supplier, across BOTH inventories.
  741. The delete guard has to see Spoolman-mode assignments too — a supplier
  742. used only by Spoolman spools must not be deletable just because the
  743. built-in inventory has no reference to it.
  744. """
  745. counts: dict[int, int] = {}
  746. for model in (SpoolSupplier, SpoolmanSpoolSupplier):
  747. result = await db.execute(select(model.supplier_id, func.count(model.id)).group_by(model.supplier_id))
  748. for supplier_id, count in result.all():
  749. counts[supplier_id] = counts.get(supplier_id, 0) + count
  750. return counts
  751. async def _prune_orphaned_spoolman_supplier_rows(db: AsyncSession) -> int:
  752. """Drop twin rows whose Spoolman spool no longer exists (#2988).
  753. ``_purge_local_rows_for_spool`` covers the deletes Bambuddy performs, but
  754. Spoolman is a separate application with its own UI: a spool deleted there
  755. — or a Spoolman instance that was rebuilt or replaced — leaves
  756. ``spoolman_spool_suppliers`` rows behind that keep the supplier's
  757. reference count non-zero, and nothing in Bambuddy can show or remove the
  758. phantom reference. Without this, that 409 is permanent.
  759. Reconciled on the delete attempt rather than on every listing: it costs
  760. one Spoolman call, and only the route that is about to refuse needs the
  761. answer. Archived spools count as live — archiving is a soft delete and the
  762. assignment has to survive it. Returns the number of rows removed; 0 when
  763. Spoolman is off or unreachable, which leaves the 409 standing rather than
  764. dropping rows on the strength of a failed lookup.
  765. """
  766. settings = await _load_settings_map(db)
  767. if not _spoolman_is_enabled(settings):
  768. return 0
  769. local_ids = set((await db.execute(select(SpoolmanSpoolSupplier.spoolman_spool_id).distinct())).scalars().all())
  770. if not local_ids:
  771. return 0
  772. client = await _ensure_spoolman_client(settings)
  773. if not client:
  774. return 0
  775. try:
  776. spools = await client.get_all_spools(allow_archived=True)
  777. except Exception:
  778. logger.warning("Failed to fetch Spoolman spools to reconcile supplier assignments", exc_info=True)
  779. return 0
  780. stale = local_ids - {s.get("id") for s in spools if isinstance(s, dict)}
  781. if not stale:
  782. return 0
  783. await db.execute(delete(SpoolmanSpoolSupplier).where(SpoolmanSpoolSupplier.spoolman_spool_id.in_(stale)))
  784. await db.commit()
  785. logger.info("Dropped supplier assignments for %d Spoolman spool(s) that no longer exist", len(stale))
  786. return len(stale)
  787. @router.get("/suppliers", response_model=list[SupplierResponse])
  788. async def list_suppliers(
  789. db: AsyncSession = Depends(get_db, scope="function"),
  790. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  791. ):
  792. """List all suppliers with their spool-usage counts."""
  793. # name_key, not name: the list should read the way it looks, so "extrudr"
  794. # sorts next to "Extrudr" rather than after "Zultrat".
  795. result = await db.execute(select(Supplier).order_by(Supplier.name_key))
  796. suppliers = result.scalars().all()
  797. counts = await _supplier_reference_counts(db)
  798. responses = []
  799. for supplier in suppliers:
  800. response = SupplierResponse.model_validate(supplier)
  801. response.spool_count = counts.get(supplier.id, 0)
  802. responses.append(response)
  803. return responses
  804. @router.post("/suppliers", response_model=SupplierResponse, status_code=201)
  805. async def create_supplier(
  806. data: SupplierCreate,
  807. db: AsyncSession = Depends(get_db, scope="function"),
  808. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  809. ):
  810. """Create a supplier (mirrors create_location, duplicate name included)."""
  811. if await _supplier_by_name(db, data.name):
  812. raise HTTPException(status_code=409, detail=DUPLICATE_SUPPLIER_NAME)
  813. supplier = Supplier(**data.model_dump())
  814. db.add(supplier)
  815. try:
  816. await db.commit()
  817. except IntegrityError as exc:
  818. # The unique index behind the check above, for the concurrent case.
  819. await db.rollback()
  820. raise HTTPException(status_code=409, detail=DUPLICATE_SUPPLIER_NAME) from exc
  821. await db.refresh(supplier)
  822. await ws_manager.broadcast({"type": "inventory_changed"})
  823. return SupplierResponse.model_validate(supplier)
  824. @router.patch("/suppliers/{supplier_id}", response_model=SupplierResponse)
  825. async def update_supplier(
  826. supplier_id: int,
  827. data: SupplierUpdate,
  828. db: AsyncSession = Depends(get_db, scope="function"),
  829. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  830. ):
  831. """Update a supplier."""
  832. result = await db.execute(select(Supplier).where(Supplier.id == supplier_id))
  833. supplier = result.scalar_one_or_none()
  834. if not supplier:
  835. raise HTTPException(status_code=404, detail="Supplier not found")
  836. fields = data.model_dump(exclude_unset=True)
  837. if "name" in fields and await _supplier_by_name(db, fields["name"], exclude_id=supplier_id):
  838. raise HTTPException(status_code=409, detail=DUPLICATE_SUPPLIER_NAME)
  839. for field, value in fields.items():
  840. setattr(supplier, field, value)
  841. try:
  842. await db.commit()
  843. except IntegrityError as exc:
  844. await db.rollback()
  845. raise HTTPException(status_code=409, detail=DUPLICATE_SUPPLIER_NAME) from exc
  846. await db.refresh(supplier)
  847. await ws_manager.broadcast({"type": "inventory_changed"})
  848. response = SupplierResponse.model_validate(supplier)
  849. response.spool_count = (await _supplier_reference_counts(db)).get(supplier.id, 0)
  850. return response
  851. @router.delete("/suppliers/{supplier_id}")
  852. async def delete_supplier(
  853. supplier_id: int,
  854. db: AsyncSession = Depends(get_db, scope="function"),
  855. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  856. ):
  857. """Delete a supplier when no spools reference it (mirrors delete_location)."""
  858. result = await db.execute(select(Supplier).where(Supplier.id == supplier_id))
  859. supplier = result.scalar_one_or_none()
  860. if not supplier:
  861. raise HTTPException(status_code=404, detail="Supplier not found")
  862. if (await _supplier_reference_counts(db)).get(supplier_id, 0) > 0:
  863. # Last chance before refusing: the reference may be a Spoolman spool
  864. # that was deleted in Spoolman itself, which Bambuddy never hears about.
  865. await _prune_orphaned_spoolman_supplier_rows(db)
  866. if (await _supplier_reference_counts(db)).get(supplier_id, 0) > 0:
  867. raise HTTPException(status_code=409, detail="Supplier has spools assigned and cannot be deleted")
  868. await db.delete(supplier)
  869. await db.commit()
  870. await ws_manager.broadcast({"type": "inventory_changed"})
  871. return {"status": "deleted"}
  872. # ── Color Catalog CRUD ─────────────────────────────────────────────────────
  873. @router.get("/colors", response_model=list[ColorEntryResponse])
  874. async def get_color_catalog(
  875. db: AsyncSession = Depends(get_db, scope="function"),
  876. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  877. ):
  878. """Get all color catalog entries."""
  879. result = await db.execute(
  880. select(ColorCatalogEntry).order_by(
  881. ColorCatalogEntry.manufacturer, ColorCatalogEntry.material, ColorCatalogEntry.color_name
  882. )
  883. )
  884. return list(result.scalars().all())
  885. @router.get("/colors/map")
  886. async def get_color_name_map(
  887. db: AsyncSession = Depends(get_db, scope="function"),
  888. _: User | None = Depends(require_auth_if_enabled),
  889. ):
  890. """Compact {hex: name} map for frontend color-name resolution.
  891. Not gated on INVENTORY_READ — every page that renders a spool color needs
  892. this, including read-only views available to users without inventory access.
  893. Normalized to lowercase 6-char hex without '#'. When multiple catalog entries
  894. share the same hex (different materials or manufacturers), Bambu Lab wins,
  895. then default entries, then the first encountered.
  896. ``by_material`` carries the names that collapsing loses. A hex is not one
  897. colour in Bambu's range: #FFFFFF is Jade White in PLA Basic, Ivory White in
  898. PLA Matte and plain White in six more, and #000000 is Black except in PLA
  899. Matte where it is Charcoal. A caller that knows the material — an AMS slot
  900. knows it as ``tray_sub_brands`` — looks up ``"<material>|<hex>"`` there
  901. first and falls back to ``colors`` (#2875).
  902. An entry is included only when it recovers a name the *same manufacturer's*
  903. own range lost. Two conditions, both load-bearing: a name equal to the
  904. collapsed one is pure weight, and a name from a different manufacturer is
  905. not a recovery at all — it would put Prusament's "Pristine White" on every
  906. generic white PLA slot in place of Bambu's "Jade White", trading one
  907. arbitrary answer for another. What survives is the handful of cases this
  908. exists for.
  909. ``bambu`` lists every Bambu Lab row as ``{hex, name, material}`` for naming
  910. a colour by its nearest Bambu entry (#3279). A colour picked on the
  911. printer's touchscreen is reported a step or two off the catalogue's hex
  912. (5A657B for Blue Grey 5B6579), which no exact lookup finds. Only Bambu's
  913. rows: that is the printer's palette, and another brand's name for a
  914. neighbouring hex would be a guess.
  915. ``preset_materials`` maps each Bambu preset id to its product line
  916. (``GFA00`` -> ``PLA Basic``). A slot without RFID reports the preset picked
  917. on the printer's screen but an empty ``tray_sub_brands``, and the product
  918. line is what the nearest search looks in first.
  919. """
  920. from backend.app.api.routes.cloud import _BUILTIN_FILAMENT_NAMES
  921. result = await db.execute(
  922. select(
  923. ColorCatalogEntry.hex_color,
  924. ColorCatalogEntry.color_name,
  925. ColorCatalogEntry.manufacturer,
  926. ColorCatalogEntry.is_default,
  927. ColorCatalogEntry.material,
  928. )
  929. )
  930. # hex → (name, priority, manufacturer); higher priority wins, first on a tie
  931. mapping: dict[str, tuple[str, int, str]] = {}
  932. by_material: dict[str, tuple[str, int, str]] = {} # "material|hex" → same
  933. bambu: list[dict[str, str]] = []
  934. for hex_color, color_name, manufacturer, is_default, material in result.all():
  935. if not hex_color or not color_name:
  936. continue
  937. key = hex_color.lstrip("#").lower()[:6]
  938. if len(key) != 6:
  939. continue
  940. brand = (manufacturer or "").strip().lower()
  941. if brand == "bambu lab":
  942. bambu.append({"hex": key, "name": color_name, "material": (material or "").strip()})
  943. priority = 0
  944. if brand == "bambu lab":
  945. priority += 2
  946. if is_default:
  947. priority += 1
  948. existing = mapping.get(key)
  949. if existing is None or priority > existing[1]:
  950. mapping[key] = (color_name, priority, brand)
  951. material_key = (material or "").strip().lower()
  952. if material_key:
  953. # Split on the LAST separator when reading these back: a material is
  954. # free text and may itself contain a '|'.
  955. qualified = f"{material_key}|{key}"
  956. existing = by_material.get(qualified)
  957. if existing is None or priority > existing[1]:
  958. by_material[qualified] = (color_name, priority, brand)
  959. colors = {k: v[0] for k, v in mapping.items()}
  960. qualified_colors = {}
  961. for qualified, (name, _, brand) in by_material.items():
  962. flat = mapping.get(qualified.rsplit("|", 1)[1])
  963. if flat and flat[0] != name and flat[2] == brand:
  964. qualified_colors[qualified] = name
  965. preset_materials = {
  966. preset: name.removeprefix("Bambu ").strip()
  967. for preset, name in _BUILTIN_FILAMENT_NAMES.items()
  968. if name.startswith("Bambu ")
  969. }
  970. return {
  971. "colors": colors,
  972. "by_material": qualified_colors,
  973. "bambu": bambu,
  974. "preset_materials": preset_materials,
  975. }
  976. @router.post("/colors", response_model=ColorEntryResponse)
  977. async def add_color_entry(
  978. entry: ColorEntryCreate,
  979. db: AsyncSession = Depends(get_db, scope="function"),
  980. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  981. ):
  982. """Add a new color catalog entry."""
  983. row = ColorCatalogEntry(
  984. manufacturer=entry.manufacturer,
  985. color_name=entry.color_name,
  986. hex_color=entry.hex_color,
  987. material=entry.material,
  988. is_default=False,
  989. extra_colors=entry.extra_colors,
  990. effect_type=entry.effect_type,
  991. )
  992. db.add(row)
  993. await db.commit()
  994. await db.refresh(row)
  995. return row
  996. @router.put("/colors/{entry_id}", response_model=ColorEntryResponse)
  997. async def update_color_entry(
  998. entry_id: int,
  999. entry: ColorEntryUpdate,
  1000. db: AsyncSession = Depends(get_db, scope="function"),
  1001. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1002. ):
  1003. """Update a color catalog entry."""
  1004. result = await db.execute(select(ColorCatalogEntry).where(ColorCatalogEntry.id == entry_id))
  1005. row = result.scalar_one_or_none()
  1006. if not row:
  1007. raise HTTPException(404, "Entry not found")
  1008. row.manufacturer = entry.manufacturer
  1009. row.color_name = entry.color_name
  1010. row.hex_color = entry.hex_color
  1011. row.material = entry.material
  1012. row.extra_colors = entry.extra_colors
  1013. row.effect_type = entry.effect_type
  1014. await db.commit()
  1015. await db.refresh(row)
  1016. return row
  1017. @router.delete("/colors/{entry_id}")
  1018. async def delete_color_entry(
  1019. entry_id: int,
  1020. db: AsyncSession = Depends(get_db, scope="function"),
  1021. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1022. ):
  1023. """Delete a color catalog entry."""
  1024. result = await db.execute(select(ColorCatalogEntry).where(ColorCatalogEntry.id == entry_id))
  1025. row = result.scalar_one_or_none()
  1026. if not row:
  1027. raise HTTPException(404, "Entry not found")
  1028. await db.delete(row)
  1029. await db.commit()
  1030. return {"status": "deleted"}
  1031. @router.post("/colors/bulk-delete")
  1032. async def bulk_delete_color_entries(
  1033. data: BulkDeleteIdsRequest,
  1034. db: AsyncSession = Depends(get_db, scope="function"),
  1035. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1036. ):
  1037. """Delete multiple color catalog entries by ID."""
  1038. if not data.ids:
  1039. return {"deleted": 0}
  1040. result = await db.execute(select(ColorCatalogEntry).where(ColorCatalogEntry.id.in_(data.ids)))
  1041. rows = result.scalars().all()
  1042. for row in rows:
  1043. await db.delete(row)
  1044. await db.commit()
  1045. return {"deleted": len(rows)}
  1046. @router.post("/colors/reset")
  1047. async def reset_color_catalog(
  1048. db: AsyncSession = Depends(get_db, scope="function"),
  1049. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1050. ):
  1051. """Reset color catalog to defaults."""
  1052. result = await db.execute(select(ColorCatalogEntry))
  1053. for row in result.scalars().all():
  1054. await db.delete(row)
  1055. for manufacturer, color_name, hex_color, material in DEFAULT_COLOR_CATALOG:
  1056. db.add(
  1057. ColorCatalogEntry(
  1058. manufacturer=manufacturer,
  1059. color_name=color_name,
  1060. hex_color=hex_color,
  1061. material=material,
  1062. is_default=True,
  1063. )
  1064. )
  1065. await db.commit()
  1066. return {"status": "reset"}
  1067. @router.get("/colors/lookup", response_model=ColorLookupResult)
  1068. async def lookup_color(
  1069. manufacturer: str,
  1070. color_name: str,
  1071. material: str | None = None,
  1072. db: AsyncSession = Depends(get_db, scope="function"),
  1073. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1074. ):
  1075. """Look up a color by manufacturer and color name."""
  1076. query = select(ColorCatalogEntry).where(
  1077. ColorCatalogEntry.manufacturer == manufacturer,
  1078. ColorCatalogEntry.color_name == color_name,
  1079. )
  1080. if material:
  1081. query = query.where(ColorCatalogEntry.material == material)
  1082. query = query.limit(1)
  1083. result = await db.execute(query)
  1084. row = result.scalar_one_or_none()
  1085. if row:
  1086. return ColorLookupResult(found=True, hex_color=row.hex_color, material=row.material)
  1087. return ColorLookupResult(found=False)
  1088. @router.get("/colors/by-material", response_model=ColorByMaterialResult)
  1089. async def get_color_by_material(
  1090. hex: str,
  1091. material: str | None = None,
  1092. db: AsyncSession = Depends(get_db, scope="function"),
  1093. _: User | None = Depends(require_auth_if_enabled),
  1094. ):
  1095. """Disambiguated hex→name lookup that respects material context.
  1096. ``/colors/map`` collapses every catalog entry sharing a hex to a single
  1097. name with "Bambu Lab > is_default > first" priority — that loses, e.g.,
  1098. "PLA Matte Charcoal" (#000000) behind "PLA Basic Black" (also #000000).
  1099. This endpoint preserves the material context so the queue scheduler's
  1100. Filament Override label can show the actually-sliced sub-brand colour
  1101. instead of the generic bucket. #1718.
  1102. Returns ``color_name=None`` when the hex isn't in the catalog at all.
  1103. When the hex IS in the catalog but no entry matches the requested
  1104. material (or none was supplied), falls back to the same priority order
  1105. as ``/colors/map`` so callers without a material hint don't regress.
  1106. Not gated on INVENTORY_READ for the same reason ``/colors/map`` isn't —
  1107. every queue / archive view that renders a sliced filament colour needs
  1108. this, including read-only roles.
  1109. """
  1110. key = hex.lstrip("#").lower()[:6]
  1111. if len(key) != 6:
  1112. return ColorByMaterialResult(color_name=None)
  1113. material_norm = (material or "").strip().lower()
  1114. # Catalog rows are stored as ``#RRGGBB`` (verified at write time and
  1115. # against production); lookup uses lower-cased hex equality so mixed-case
  1116. # writes from older imports still match.
  1117. result = await db.execute(
  1118. select(
  1119. ColorCatalogEntry.color_name,
  1120. ColorCatalogEntry.manufacturer,
  1121. ColorCatalogEntry.material,
  1122. ColorCatalogEntry.is_default,
  1123. ).where(func.lower(ColorCatalogEntry.hex_color) == f"#{key}")
  1124. )
  1125. candidates = [(name, mfg, mat, is_default) for name, mfg, mat, is_default in result.all() if name]
  1126. if not candidates:
  1127. return ColorByMaterialResult(color_name=None)
  1128. if material_norm:
  1129. for name, _mfg, mat, _is_default in candidates:
  1130. if mat and mat.strip().lower() == material_norm:
  1131. return ColorByMaterialResult(color_name=name)
  1132. # Same priority order as ``/colors/map`` so a caller passing no (or an
  1133. # unrecognised) material gets the existing answer, not a degraded one.
  1134. best_name: str | None = None
  1135. best_priority = -1
  1136. for name, mfg, _mat, is_default in candidates:
  1137. priority = 0
  1138. if mfg and mfg.strip().lower() == "bambu lab":
  1139. priority += 2
  1140. if is_default:
  1141. priority += 1
  1142. if priority > best_priority:
  1143. best_name = name
  1144. best_priority = priority
  1145. return ColorByMaterialResult(color_name=best_name)
  1146. @router.get("/colors/search", response_model=list[ColorEntryResponse])
  1147. async def search_colors(
  1148. manufacturer: str | None = None,
  1149. material: str | None = None,
  1150. db: AsyncSession = Depends(get_db, scope="function"),
  1151. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1152. ):
  1153. """Search colors by manufacturer and/or material."""
  1154. query = select(ColorCatalogEntry)
  1155. if manufacturer:
  1156. query = query.where(func.lower(ColorCatalogEntry.manufacturer).contains(manufacturer.lower()))
  1157. if material:
  1158. query = query.where(func.lower(ColorCatalogEntry.material).contains(material.lower()))
  1159. query = query.order_by(ColorCatalogEntry.manufacturer, ColorCatalogEntry.color_name).limit(100)
  1160. result = await db.execute(query)
  1161. return list(result.scalars().all())
  1162. @router.post("/colors/sync")
  1163. async def sync_from_filamentcolors(
  1164. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1165. ):
  1166. """Sync colors from FilamentColors.xyz API with progress streaming."""
  1167. async def generate():
  1168. from backend.app.core.database import async_session
  1169. added = 0
  1170. skipped = 0
  1171. total_fetched = 0
  1172. total_available = 0
  1173. try:
  1174. # Identify honestly as Bambuddy rather than leaking httpx's
  1175. # default "python-httpx/x.y" UA — consistent with every other
  1176. # outbound client (bambu_cloud, makerworld, firmware_check).
  1177. async with httpx.AsyncClient(
  1178. timeout=120.0,
  1179. headers={"User-Agent": "Bambuddy/1.0 (+https://github.com/maziggy/bambuddy)"},
  1180. ) as client:
  1181. page = 1
  1182. while True:
  1183. response = await client.get(
  1184. f"{FILAMENT_COLORS_API}/swatch/",
  1185. params={"page": page},
  1186. )
  1187. response.raise_for_status()
  1188. data = response.json()
  1189. total_available = data.get("count", total_available)
  1190. results = data.get("results", [])
  1191. if not results:
  1192. break
  1193. async with async_session() as db:
  1194. for swatch in results:
  1195. total_fetched += 1
  1196. manufacturer_data = swatch.get("manufacturer")
  1197. manufacturer_name = (
  1198. manufacturer_data.get("name", "") if isinstance(manufacturer_data, dict) else ""
  1199. )
  1200. filament_type_data = swatch.get("filament_type")
  1201. mat = filament_type_data.get("name", "") if isinstance(filament_type_data, dict) else None
  1202. color_name_val = swatch.get("color_name", "")
  1203. hex_color_val = swatch.get("hex_color", "")
  1204. if not manufacturer_name or not color_name_val or not hex_color_val:
  1205. skipped += 1
  1206. continue
  1207. if not hex_color_val.startswith("#"):
  1208. hex_color_val = f"#{hex_color_val}"
  1209. # Check if entry already exists
  1210. existing = await db.execute(
  1211. select(ColorCatalogEntry)
  1212. .where(
  1213. ColorCatalogEntry.manufacturer == manufacturer_name,
  1214. ColorCatalogEntry.color_name == color_name_val,
  1215. ColorCatalogEntry.material == mat,
  1216. )
  1217. .limit(1)
  1218. )
  1219. if existing.scalar_one_or_none():
  1220. skipped += 1
  1221. else:
  1222. db.add(
  1223. ColorCatalogEntry(
  1224. manufacturer=manufacturer_name,
  1225. color_name=color_name_val,
  1226. hex_color=hex_color_val.upper(),
  1227. material=mat,
  1228. is_default=False,
  1229. )
  1230. )
  1231. added += 1
  1232. await db.commit()
  1233. progress = {
  1234. "type": "progress",
  1235. "added": added,
  1236. "skipped": skipped,
  1237. "total_fetched": total_fetched,
  1238. "total_available": total_available,
  1239. }
  1240. yield f"data: {json.dumps(progress)}\n\n"
  1241. if not data.get("next") or total_fetched >= total_available:
  1242. break
  1243. page += 1
  1244. result = {
  1245. "type": "complete",
  1246. "added": added,
  1247. "skipped": skipped,
  1248. "total_fetched": total_fetched,
  1249. "total_available": total_available,
  1250. }
  1251. yield f"data: {json.dumps(result)}\n\n"
  1252. except httpx.HTTPError as e:
  1253. logger.error("HTTP error syncing from FilamentColors.xyz: %s", e)
  1254. yield f"data: {json.dumps({'type': 'error', 'error': str(e)})}\n\n"
  1255. except Exception as e:
  1256. logger.error("Error syncing from FilamentColors.xyz: %s", e)
  1257. yield f"data: {json.dumps({'type': 'error', 'error': 'Unexpected error during sync'})}\n\n"
  1258. return StreamingResponse(generate(), media_type="text/event-stream")
  1259. # ── Spool CRUD ───────────────────────────────────────────────────────────────
  1260. @router.get("/spools", response_model=list[SpoolResponse])
  1261. async def list_spools(
  1262. include_archived: bool = False,
  1263. db: AsyncSession = Depends(get_db, scope="function"),
  1264. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1265. ):
  1266. """List all spools, excluding archived by default."""
  1267. query = select(Spool).options(*spool_response_loads())
  1268. if not include_archived:
  1269. query = query.where(Spool.archived_at.is_(None))
  1270. query = query.order_by(Spool.material, Spool.brand, Spool.color_name)
  1271. result = await db.execute(query)
  1272. return list(result.scalars().all())
  1273. # ── CSV import / export (#1576) ──────────────────────────────────────────────
  1274. # Declared before the dynamic `/spools/{spool_id}` route below so the literal
  1275. # `export` / `import` segments match here instead of being parsed as an int id.
  1276. @router.get("/spools/export")
  1277. async def export_spools_csv(
  1278. db: AsyncSession = Depends(get_db, scope="function"),
  1279. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1280. ):
  1281. """Export the active inventory as CSV (same schema the importer accepts)."""
  1282. query = (
  1283. select(Spool)
  1284. # The supplier columns (#2988) read the assignments off each row.
  1285. .options(selectinload(Spool.supplier_links).selectinload(SpoolSupplier.supplier))
  1286. .where(Spool.archived_at.is_(None))
  1287. .order_by(Spool.material, Spool.brand, Spool.color_name)
  1288. )
  1289. result = await db.execute(query)
  1290. spools = list(result.scalars().all())
  1291. content = serialize(spools)
  1292. # Date-stamp the filename so repeat exports don't overwrite each other in
  1293. # the browser's default download folder.
  1294. filename = f"bambuddy_inventory_{datetime.now(timezone.utc).strftime('%Y%m%d')}.csv"
  1295. return Response(
  1296. content=content,
  1297. media_type="text/csv",
  1298. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  1299. )
  1300. @router.post("/spools/import", response_model=ImportPreview | ImportResult)
  1301. async def import_spools_csv(
  1302. file: UploadFile = File(...),
  1303. dry_run: bool = Query(False),
  1304. db: AsyncSession = Depends(get_db, scope="function"),
  1305. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1306. ):
  1307. """Import spools from a CSV file.
  1308. With ``dry_run=true`` returns an ImportPreview (per-row valid/error/skipped,
  1309. colours resolved) and writes nothing — the UI shows this before the user
  1310. confirms. With ``dry_run=false`` it validates the same way and then persists
  1311. only the valid rows in a single transaction (invalid rows are skipped, the
  1312. user fixes the CSV and re-uploads), returning an ImportResult summary.
  1313. """
  1314. def _too_large() -> HTTPException:
  1315. return HTTPException(
  1316. status_code=413,
  1317. detail={
  1318. "code": "csv_import_too_large",
  1319. "message": f"CSV file exceeds the {MAX_CSV_IMPORT_BYTES // (1024 * 1024)} MB limit.",
  1320. },
  1321. )
  1322. # Reject by declared size first (fast path when Content-Length is set), then
  1323. # read in bounded chunks and bail the moment the accumulated body crosses the
  1324. # cap — file.size is None for chunked uploads, so the loop is what actually
  1325. # keeps an oversized stream from filling memory.
  1326. if file.size is not None and file.size > MAX_CSV_IMPORT_BYTES:
  1327. raise _too_large()
  1328. raw = bytearray()
  1329. while chunk := await file.read(_CSV_UPLOAD_CHUNK_BYTES):
  1330. raw.extend(chunk)
  1331. if len(raw) > MAX_CSV_IMPORT_BYTES:
  1332. raise _too_large()
  1333. preview = await parse_and_validate(bytes(raw), db)
  1334. if dry_run:
  1335. return preview
  1336. created = 0
  1337. for row in preview.rows:
  1338. if row.status == "valid" and row.spool is not None:
  1339. # Deliberately no material-number inheritance here (#2870), unlike
  1340. # the other create paths: the file is authoritative. A CSV that
  1341. # leaves the column blank is stating "no number", not asking for
  1342. # one to be guessed from whatever else is in the inventory.
  1343. # The file has no lock column: a used weight in it is locked.
  1344. spool = Spool(**_lock_entered_weight(dict(row.spool), set()))
  1345. db.add(spool)
  1346. # Supplier assignments resolved by name during parsing (#2988).
  1347. # Flush first so the spool has an id to hang the links on.
  1348. if row.supplier_ids:
  1349. await db.flush()
  1350. for supplier_id in row.supplier_ids:
  1351. db.add(
  1352. SpoolSupplier(
  1353. spool_id=spool.id,
  1354. supplier_id=supplier_id,
  1355. is_purchase_source=supplier_id == row.purchase_supplier_id,
  1356. )
  1357. )
  1358. created += 1
  1359. if created:
  1360. await db.commit()
  1361. await ws_manager.broadcast({"type": "inventory_changed"})
  1362. return ImportResult(
  1363. created=created,
  1364. skipped=preview.skipped_count,
  1365. errors=preview.error_count,
  1366. error_rows=[r for r in preview.rows if r.status == "error"],
  1367. )
  1368. @router.get("/spools/by-tag", response_model=SpoolResponse)
  1369. async def get_spool_by_tag(
  1370. tray_uuid: str | None = None,
  1371. tag_uid: str | None = None,
  1372. include_archived: bool = False,
  1373. db: AsyncSession = Depends(get_db, scope="function"),
  1374. _: User | None = RequireAnyPermissionIfAuthEnabled(Permission.INVENTORY_READ, Permission.INVENTORY_UPDATE),
  1375. ):
  1376. """Find a single spool by its NFC ``tray_uuid`` and/or ``tag_uid``.
  1377. Lets NFC inventory integrations dedupe a scan without listing the whole
  1378. inventory. ``tray_uuid`` is the primary identifier (it matches the value the
  1379. AMS reports over MQTT), so it is tried first; ``tag_uid`` is the fallback.
  1380. At least one identifier must be supplied. Returns 404 when nothing matches.
  1381. Accepts ``inventory:read`` OR ``inventory:update`` so a Manage-Inventory API
  1382. key (which has ``inventory:update`` via ``can_manage_inventory``) can read a
  1383. spool back without widening the global ``INVENTORY_READ`` scope mapping (#1663).
  1384. """
  1385. normalized_tray_uuid = normalize_tray_uuid(tray_uuid) or None
  1386. normalized_tag_uid = normalize_tag_uid(tag_uid) or None
  1387. if not normalized_tray_uuid and not normalized_tag_uid:
  1388. raise HTTPException(400, "Provide tray_uuid and/or tag_uid")
  1389. base_query = select(Spool).options(*spool_response_loads())
  1390. if not include_archived:
  1391. base_query = base_query.where(Spool.archived_at.is_(None))
  1392. for column, value in (
  1393. (Spool.tray_uuid, normalized_tray_uuid),
  1394. (Spool.tag_uid, normalized_tag_uid),
  1395. ):
  1396. if not value:
  1397. continue
  1398. result = await db.execute(base_query.where(func.upper(column) == value).order_by(Spool.id))
  1399. spool = result.scalars().first()
  1400. if spool:
  1401. return spool
  1402. raise HTTPException(404, "Spool not found")
  1403. @router.get("/spools/{spool_id}", response_model=SpoolResponse)
  1404. async def get_spool(
  1405. spool_id: int,
  1406. db: AsyncSession = Depends(get_db, scope="function"),
  1407. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1408. ):
  1409. """Get a single spool with k_profiles."""
  1410. result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id == spool_id))
  1411. spool = result.scalar_one_or_none()
  1412. if not spool:
  1413. raise HTTPException(404, "Spool not found")
  1414. return spool
  1415. def _lock_entered_weight(payload: dict, fields_set: set[str]) -> dict:
  1416. """A used weight entered for a new spool is locked, as an edited one is:
  1417. otherwise the AMS remain% sync can overwrite it on its first pass. An
  1418. explicit ``weight_locked`` from the client wins."""
  1419. if (payload.get("weight_used") or 0) > 0 and "weight_locked" not in fields_set:
  1420. payload["weight_locked"] = True
  1421. return payload
  1422. @router.post("/spools", response_model=SpoolResponse)
  1423. async def create_spool(
  1424. spool_data: SpoolCreate,
  1425. db: AsyncSession = Depends(get_db, scope="function"),
  1426. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1427. ):
  1428. """Create a new spool."""
  1429. try:
  1430. payload = await prepare_internal_spool_payload(db, spool_data.model_dump(), set(spool_data.model_fields_set))
  1431. except ValueError as exc:
  1432. raise HTTPException(status_code=400, detail=str(exc)) from exc
  1433. payload = _lock_entered_weight(payload, set(spool_data.model_fields_set))
  1434. # A new spool of an already-numbered product inherits its material number (#2870).
  1435. payload = await apply_material_number_inheritance(db, payload)
  1436. spool = Spool(**payload)
  1437. db.add(spool)
  1438. await db.flush()
  1439. # A new spool of a product that already carries supplier assignments
  1440. # inherits the source list (#2988).
  1441. await apply_supplier_inheritance(db, spool)
  1442. # ...and the product's profile default, where the request brought none (#1326).
  1443. await profile_defaults.fill_internal_spool(db, spool)
  1444. await db.commit()
  1445. await db.refresh(spool)
  1446. result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id == spool.id))
  1447. await ws_manager.broadcast({"type": "inventory_changed"})
  1448. return result.scalar_one()
  1449. @router.post("/spools/bulk", response_model=list[SpoolResponse])
  1450. async def bulk_create_spools(
  1451. data: SpoolBulkCreate,
  1452. db: AsyncSession = Depends(get_db, scope="function"),
  1453. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1454. ):
  1455. """Create multiple identical spools."""
  1456. spools = []
  1457. fields_set = set(data.spool.model_fields_set)
  1458. try:
  1459. payload = await prepare_internal_spool_payload(db, data.spool.model_dump(), fields_set)
  1460. except ValueError as exc:
  1461. raise HTTPException(status_code=400, detail=str(exc)) from exc
  1462. payload = _lock_entered_weight(payload, fields_set)
  1463. # A new spool of an already-numbered product inherits its material number (#2870).
  1464. payload = await apply_material_number_inheritance(db, payload)
  1465. for _ in range(data.quantity):
  1466. spool = Spool(**payload)
  1467. db.add(spool)
  1468. spools.append(spool)
  1469. await db.flush()
  1470. # Every copy gets its own link rows, from one donor lookup (#2988).
  1471. await apply_supplier_inheritance_to_batch(db, spools)
  1472. # Every copy is the same product, so one profile default for all (#1326).
  1473. if spools:
  1474. first = spools[0]
  1475. resolved = await profile_defaults.resolve_profile_default(
  1476. db, brand=first.brand, material=first.material, subtype=first.subtype, color_name=first.color_name
  1477. )
  1478. for spool in spools:
  1479. await profile_defaults.fill_internal_spool(db, spool, resolved=resolved)
  1480. await db.commit()
  1481. ids = [s.id for s in spools]
  1482. result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id.in_(ids)))
  1483. await ws_manager.broadcast({"type": "inventory_changed"})
  1484. return list(result.scalars().all())
  1485. @router.patch("/spools/{spool_id}", response_model=SpoolResponse)
  1486. async def update_spool(
  1487. spool_id: int,
  1488. spool_data: SpoolUpdate,
  1489. db: AsyncSession = Depends(get_db, scope="function"),
  1490. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1491. ):
  1492. """Update a spool."""
  1493. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  1494. spool = result.scalar_one_or_none()
  1495. if not spool:
  1496. raise HTTPException(404, "Spool not found")
  1497. update_data = spool_data.model_dump(exclude_unset=True)
  1498. try:
  1499. update_data = await prepare_internal_spool_payload(db, update_data, set(spool_data.model_fields_set))
  1500. except ValueError as exc:
  1501. raise HTTPException(status_code=400, detail=str(exc)) from exc
  1502. # Auto-lock weight when user explicitly sets weight_used
  1503. if "weight_used" in update_data and "weight_locked" not in update_data:
  1504. update_data["weight_locked"] = True
  1505. # A drying date set by hand is not the AMS cycle the temperature and
  1506. # hours describe, so they go with it (#2863).
  1507. if "last_dried_at" in update_data:
  1508. update_data["last_dried_temp"] = None
  1509. update_data["last_dried_hours"] = None
  1510. for field, value in update_data.items():
  1511. setattr(spool, field, value)
  1512. await db.commit()
  1513. result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id == spool_id))
  1514. await ws_manager.broadcast({"type": "inventory_changed"})
  1515. return result.scalar_one()
  1516. @router.delete("/spools/{spool_id}")
  1517. async def delete_spool(
  1518. spool_id: int,
  1519. db: AsyncSession = Depends(get_db, scope="function"),
  1520. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1521. ):
  1522. """Hard delete a spool."""
  1523. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  1524. spool = result.scalar_one_or_none()
  1525. if not spool:
  1526. raise HTTPException(404, "Spool not found")
  1527. freed = await _release_slots(db, [spool.id])
  1528. await db.delete(spool)
  1529. await db.commit()
  1530. await ws_manager.broadcast({"type": "inventory_changed"})
  1531. await _announce_freed_slots(freed)
  1532. return {"status": "deleted"}
  1533. async def _release_slots(db: AsyncSession, spool_ids: list[int]) -> list[tuple[int, int, int]]:
  1534. """Unassign archived or deleted spools from their AMS slots; returns the
  1535. freed slots.
  1536. Assigning refuses an archived spool and nothing downstream checks the flag,
  1537. so a slot left pointing at one would keep showing it and charge it the next
  1538. print's usage. A deleted spool's slots go with it, but other tabs refresh
  1539. their slot views only when the slots are announced. The caller commits,
  1540. then announces the slots.
  1541. """
  1542. if not spool_ids:
  1543. return []
  1544. rows = (await db.execute(select(SpoolAssignment).where(SpoolAssignment.spool_id.in_(spool_ids)))).scalars().all()
  1545. freed = [(a.printer_id, a.ams_id, a.tray_id) for a in rows]
  1546. for assignment in rows:
  1547. await db.delete(assignment)
  1548. return freed
  1549. async def _announce_freed_slots(freed: list[tuple[int, int, int]]) -> None:
  1550. for printer_id, ams_id, tray_id in freed:
  1551. await ws_manager.broadcast(
  1552. {"type": "spool_assignment_changed", "printer_id": printer_id, "ams_id": ams_id, "tray_id": tray_id}
  1553. )
  1554. @router.post("/spools/{spool_id}/archive", response_model=SpoolResponse)
  1555. async def archive_spool(
  1556. spool_id: int,
  1557. db: AsyncSession = Depends(get_db, scope="function"),
  1558. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1559. ):
  1560. """Soft-delete a spool by setting archived_at."""
  1561. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  1562. spool = result.scalar_one_or_none()
  1563. if not spool:
  1564. raise HTTPException(404, "Spool not found")
  1565. spool.archived_at = datetime.now(timezone.utc)
  1566. freed = await _release_slots(db, [spool.id])
  1567. await db.commit()
  1568. result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id == spool_id))
  1569. await ws_manager.broadcast({"type": "inventory_changed"})
  1570. await _announce_freed_slots(freed)
  1571. return result.scalar_one()
  1572. @router.post("/spools/{spool_id}/restore", response_model=SpoolResponse)
  1573. async def restore_spool(
  1574. spool_id: int,
  1575. db: AsyncSession = Depends(get_db, scope="function"),
  1576. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1577. ):
  1578. """Restore an archived spool."""
  1579. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  1580. spool = result.scalar_one_or_none()
  1581. if not spool:
  1582. raise HTTPException(404, "Spool not found")
  1583. spool.archived_at = None
  1584. await db.commit()
  1585. result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id == spool_id))
  1586. await ws_manager.broadcast({"type": "inventory_changed"})
  1587. return result.scalar_one()
  1588. @router.post("/spools/{spool_id}/reset-consumed-counter", response_model=SpoolResponse)
  1589. async def reset_spool_consumed_counter(
  1590. spool_id: int,
  1591. db: AsyncSession = Depends(get_db, scope="function"),
  1592. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1593. ):
  1594. """Zero the displayed "Total Consumed" counter without touching remaining.
  1595. Stamps `weight_used_baseline = weight_used` so the Inventory page's
  1596. `weight_used - baseline` display reads 0, while `label_weight -
  1597. weight_used` (remaining) is unchanged. weight_locked is also left
  1598. alone — the spool keeps receiving AMS auto-sync updates. Matches
  1599. Spoolman's split between used_weight and remaining_weight (#1390).
  1600. The earlier name `/reset-usage` was misleading: callers reasonably
  1601. expected `weight_used` itself to drop to 0 and were surprised when
  1602. the response showed it unchanged. The current name describes what
  1603. the endpoint actually does — reset the "Total Consumed" counter
  1604. widget, not the lifetime weight_used field.
  1605. """
  1606. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  1607. spool = result.scalar_one_or_none()
  1608. if not spool:
  1609. raise HTTPException(404, "Spool not found")
  1610. spool.weight_used_baseline = spool.weight_used or 0
  1611. await db.commit()
  1612. result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id == spool_id))
  1613. await ws_manager.broadcast({"type": "inventory_changed"})
  1614. return result.scalar_one()
  1615. @router.post("/spools/reset-consumed-counter-bulk")
  1616. async def bulk_reset_spool_consumed_counter(
  1617. payload: dict,
  1618. db: AsyncSession = Depends(get_db, scope="function"),
  1619. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1620. ):
  1621. """Bulk-stamp baseline = weight_used across the given spool IDs.
  1622. Caller passes an explicit list of IDs — no "reset all" shortcut, since
  1623. a typo on a wildcard would wipe the entire inventory's tracking.
  1624. Same semantics as the per-spool endpoint: remaining is preserved,
  1625. weight_locked is left alone.
  1626. """
  1627. spool_ids = payload.get("spool_ids")
  1628. if not isinstance(spool_ids, list) or not spool_ids:
  1629. raise HTTPException(400, "spool_ids must be a non-empty list")
  1630. if not all(isinstance(sid, int) for sid in spool_ids):
  1631. raise HTTPException(400, "spool_ids must contain integers")
  1632. result = await db.execute(select(Spool).where(Spool.id.in_(spool_ids)))
  1633. spools = list(result.scalars().all())
  1634. for spool in spools:
  1635. spool.weight_used_baseline = spool.weight_used or 0
  1636. await db.commit()
  1637. await ws_manager.broadcast({"type": "inventory_changed"})
  1638. found = {spool.id for spool in spools}
  1639. return {"reset": len(spools), "not_found": [sid for sid in spool_ids if sid not in found]}
  1640. class BulkUpdateRequest(BaseModel):
  1641. ids: list[int] = Field(..., min_length=1, max_length=500)
  1642. update: SpoolUpdate
  1643. class BulkIdsRequest(BaseModel):
  1644. ids: list[int] = Field(..., min_length=1, max_length=500)
  1645. @router.post("/spools/bulk-update")
  1646. async def bulk_update_spools(
  1647. payload: BulkUpdateRequest,
  1648. db: AsyncSession = Depends(get_db, scope="function"),
  1649. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1650. ):
  1651. """Apply the same partial update to every listed spool.
  1652. Per-spool errors are collected and returned alongside the success count so
  1653. a single bad ID doesn't abort the whole batch. Unknown IDs are reported
  1654. in the ``not_found`` list.
  1655. """
  1656. update_data = payload.update.model_dump(exclude_unset=True)
  1657. fields_set = set(payload.update.model_fields_set)
  1658. if not update_data:
  1659. raise HTTPException(status_code=400, detail="update must include at least one field")
  1660. try:
  1661. prepared = await prepare_internal_spool_payload(db, update_data, fields_set)
  1662. except ValueError as exc:
  1663. raise HTTPException(status_code=400, detail=str(exc)) from exc
  1664. # Auto-lock weight when the user explicitly sets weight_used — mirrors the
  1665. # per-spool PATCH behaviour so bulk edits don't desync the lock state.
  1666. if "weight_used" in prepared and "weight_locked" not in prepared:
  1667. prepared["weight_locked"] = True
  1668. # Same rule as the per-spool PATCH: a hand-set drying date drops the
  1669. # temperature and hours of the AMS cycle it replaces (#2863).
  1670. if "last_dried_at" in prepared:
  1671. prepared["last_dried_temp"] = None
  1672. prepared["last_dried_hours"] = None
  1673. result = await db.execute(select(Spool).where(Spool.id.in_(payload.ids)))
  1674. spools = {s.id: s for s in result.scalars().all()}
  1675. not_found = [sid for sid in payload.ids if sid not in spools]
  1676. updated_ids: list[int] = []
  1677. for sid, spool in spools.items():
  1678. for field, value in prepared.items():
  1679. setattr(spool, field, value)
  1680. updated_ids.append(sid)
  1681. await db.commit()
  1682. if updated_ids:
  1683. await ws_manager.broadcast({"type": "inventory_changed"})
  1684. return {"updated": len(updated_ids), "not_found": not_found}
  1685. @router.post("/spools/bulk-delete")
  1686. async def bulk_delete_spools(
  1687. payload: BulkIdsRequest,
  1688. db: AsyncSession = Depends(get_db, scope="function"),
  1689. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1690. ):
  1691. """Hard-delete every listed spool. Unknown IDs are returned in not_found."""
  1692. result = await db.execute(select(Spool).where(Spool.id.in_(payload.ids)))
  1693. spools = list(result.scalars().all())
  1694. found_ids = {s.id for s in spools}
  1695. not_found = [sid for sid in payload.ids if sid not in found_ids]
  1696. freed = await _release_slots(db, list(found_ids))
  1697. for spool in spools:
  1698. await db.delete(spool)
  1699. await db.commit()
  1700. if spools:
  1701. await ws_manager.broadcast({"type": "inventory_changed"})
  1702. await _announce_freed_slots(freed)
  1703. return {"deleted": len(spools), "not_found": not_found}
  1704. @router.post("/spools/bulk-archive")
  1705. async def bulk_archive_spools(
  1706. payload: BulkIdsRequest,
  1707. db: AsyncSession = Depends(get_db, scope="function"),
  1708. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1709. ):
  1710. """Soft-archive every listed spool (sets archived_at). Already-archived spools are left alone and counted in already_archived."""
  1711. result = await db.execute(select(Spool).where(Spool.id.in_(payload.ids)))
  1712. spools = list(result.scalars().all())
  1713. found_ids = {s.id for s in spools}
  1714. not_found = [sid for sid in payload.ids if sid not in found_ids]
  1715. archived: list[int] = []
  1716. already: list[int] = []
  1717. now = datetime.now(timezone.utc)
  1718. for spool in spools:
  1719. if spool.archived_at is not None:
  1720. already.append(spool.id)
  1721. continue
  1722. spool.archived_at = now
  1723. archived.append(spool.id)
  1724. # Already-archived ones too: archived before archiving released slots.
  1725. freed = await _release_slots(db, archived + already)
  1726. await db.commit()
  1727. if archived:
  1728. await ws_manager.broadcast({"type": "inventory_changed"})
  1729. await _announce_freed_slots(freed)
  1730. return {"archived": len(archived), "already_archived": already, "not_found": not_found}
  1731. @router.post("/spools/bulk-restore")
  1732. async def bulk_restore_spools(
  1733. payload: BulkIdsRequest,
  1734. db: AsyncSession = Depends(get_db, scope="function"),
  1735. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1736. ):
  1737. """Restore every listed archived spool. Non-archived rows are no-ops counted in already_active."""
  1738. result = await db.execute(select(Spool).where(Spool.id.in_(payload.ids)))
  1739. spools = list(result.scalars().all())
  1740. found_ids = {s.id for s in spools}
  1741. not_found = [sid for sid in payload.ids if sid not in found_ids]
  1742. restored: list[int] = []
  1743. already: list[int] = []
  1744. for spool in spools:
  1745. if spool.archived_at is None:
  1746. already.append(spool.id)
  1747. continue
  1748. spool.archived_at = None
  1749. restored.append(spool.id)
  1750. await db.commit()
  1751. if restored:
  1752. await ws_manager.broadcast({"type": "inventory_changed"})
  1753. return {"restored": len(restored), "already_active": already, "not_found": not_found}
  1754. # ── K-Profiles ───────────────────────────────────────────────────────────────
  1755. @router.get("/spools/{spool_id}/k-profiles", response_model=list[SpoolKProfileResponse])
  1756. async def list_k_profiles(
  1757. spool_id: int,
  1758. db: AsyncSession = Depends(get_db, scope="function"),
  1759. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1760. ):
  1761. """List K-profiles for a spool."""
  1762. result = await db.execute(select(SpoolKProfile).where(SpoolKProfile.spool_id == spool_id))
  1763. return list(result.scalars().all())
  1764. @router.put("/spools/{spool_id}/k-profiles", response_model=list[SpoolKProfileResponse])
  1765. async def replace_k_profiles(
  1766. spool_id: int,
  1767. profiles: list[SpoolKProfileBase],
  1768. db: AsyncSession = Depends(get_db, scope="function"),
  1769. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1770. printer_scope: PrinterScope = RequestPrinterScope,
  1771. ):
  1772. """Replace all K-profiles for a spool (batch save).
  1773. A caller limited to some printers (#1727) replaces only theirs: the
  1774. profiles of printers it cannot see -- which its form never showed, a new
  1775. spool's from its product's profile default (#1326) among them -- stay.
  1776. """
  1777. # Verify spool exists
  1778. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  1779. if not result.scalar_one_or_none():
  1780. raise HTTPException(404, "Spool not found")
  1781. # Delete existing
  1782. existing = await db.execute(select(SpoolKProfile).where(SpoolKProfile.spool_id == spool_id))
  1783. for old in existing.scalars().all():
  1784. if printer_scope.allows(old.printer_id):
  1785. await db.delete(old)
  1786. # Create new
  1787. new_profiles = []
  1788. for p in profiles:
  1789. if not printer_scope.allows(p.printer_id):
  1790. continue
  1791. kp = SpoolKProfile(spool_id=spool_id, **p.model_dump())
  1792. db.add(kp)
  1793. new_profiles.append(kp)
  1794. await db.commit()
  1795. for kp in new_profiles:
  1796. await db.refresh(kp)
  1797. return new_profiles
  1798. @router.put("/spools/{spool_id}/suppliers", response_model=list[SpoolSupplierResponse])
  1799. async def replace_spool_suppliers(
  1800. spool_id: int,
  1801. links: list[SpoolSupplierLinkInput],
  1802. db: AsyncSession = Depends(get_db, scope="function"),
  1803. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1804. ):
  1805. """Replace a spool's supplier assignments (#2988, batch save).
  1806. Same replace-all shape as the k-profiles endpoint. At most one assignment
  1807. may be the purchase source — the record of where this concrete spool was
  1808. actually bought; the rest read as alternative sources.
  1809. """
  1810. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  1811. if not result.scalar_one_or_none():
  1812. raise HTTPException(404, "Spool not found")
  1813. supplier_ids = [link.supplier_id for link in links]
  1814. if len(set(supplier_ids)) != len(supplier_ids):
  1815. raise HTTPException(400, "Duplicate supplier in assignment list")
  1816. if sum(1 for link in links if link.is_purchase_source) > 1:
  1817. raise HTTPException(400, "Only one assignment can be the purchase source")
  1818. if supplier_ids:
  1819. found = await db.execute(select(Supplier.id).where(Supplier.id.in_(supplier_ids)))
  1820. missing = set(supplier_ids) - {row[0] for row in found.all()}
  1821. if missing:
  1822. raise HTTPException(404, f"Supplier(s) not found: {sorted(missing)}")
  1823. existing = await db.execute(select(SpoolSupplier).where(SpoolSupplier.spool_id == spool_id))
  1824. for old in existing.scalars().all():
  1825. await db.delete(old)
  1826. await db.flush()
  1827. new_links = []
  1828. for link in links:
  1829. row = SpoolSupplier(spool_id=spool_id, **link.model_dump())
  1830. db.add(row)
  1831. new_links.append(row)
  1832. await db.commit()
  1833. refreshed = await db.execute(
  1834. select(SpoolSupplier)
  1835. .options(selectinload(SpoolSupplier.supplier))
  1836. .where(SpoolSupplier.id.in_([row.id for row in new_links]))
  1837. .order_by(SpoolSupplier.id)
  1838. )
  1839. await ws_manager.broadcast({"type": "inventory_changed"})
  1840. return list(refreshed.scalars().all())
  1841. @router.get("/spools/{spool_id}/filament-presets", response_model=list[SpoolFilamentPresetResponse])
  1842. async def list_filament_presets(
  1843. spool_id: int,
  1844. db: AsyncSession = Depends(get_db, scope="function"),
  1845. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1846. ):
  1847. """List per-printer-model preset overrides for a spool.
  1848. A dedicated endpoint rather than a field on ``SpoolResponse``: the
  1849. inventory list returns every spool the user owns, and only the spool form
  1850. and the assign path ever need this list, one spool at a time.
  1851. """
  1852. result = await db.execute(select(SpoolFilamentPreset).where(SpoolFilamentPreset.spool_id == spool_id))
  1853. return list(result.scalars().all())
  1854. @router.put("/spools/{spool_id}/filament-presets", response_model=list[SpoolFilamentPresetResponse])
  1855. async def replace_filament_presets(
  1856. spool_id: int,
  1857. presets: list[SpoolFilamentPresetBase],
  1858. db: AsyncSession = Depends(get_db, scope="function"),
  1859. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1860. ):
  1861. """Replace all per-printer-model preset overrides for a spool.
  1862. Replace rather than merge, matching the K-profile endpoint next door: the
  1863. spool form always holds the complete set, and an empty list is how the
  1864. user clears every override back to the spool's own preset.
  1865. """
  1866. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  1867. if not result.scalar_one_or_none():
  1868. raise HTTPException(404, "Spool not found")
  1869. # (model, diameter) is UNIQUE, so a payload that names one twice would
  1870. # fail on flush with an IntegrityError the client cannot act on. Reject it
  1871. # by name instead -- and reject it BEFORE deleting the existing rows, so a
  1872. # bad request cannot wipe overrides it then fails to replace.
  1873. seen: set[tuple[str, str]] = set()
  1874. for p in presets:
  1875. key = (p.printer_model, p.nozzle_diameter)
  1876. if key in seen:
  1877. raise HTTPException(
  1878. 422,
  1879. f"Duplicate override for model {p.printer_model!r} nozzle {p.nozzle_diameter or 'any'!r}",
  1880. )
  1881. seen.add(key)
  1882. existing = await db.execute(select(SpoolFilamentPreset).where(SpoolFilamentPreset.spool_id == spool_id))
  1883. for old in existing.scalars().all():
  1884. await db.delete(old)
  1885. # Land the deletes before the inserts: within one transaction SQLAlchemy is
  1886. # free to order the INSERTs first, which trips the UNIQUE constraint
  1887. # against rows this call is about to remove.
  1888. await db.flush()
  1889. new_presets = []
  1890. for p in presets:
  1891. row = SpoolFilamentPreset(spool_id=spool_id, **p.model_dump())
  1892. db.add(row)
  1893. new_presets.append(row)
  1894. await db.commit()
  1895. for row in new_presets:
  1896. await db.refresh(row)
  1897. return new_presets
  1898. # ── Profile defaults (#1326) ─────────────────────────────────────────────────
  1899. #
  1900. # Shared by both inventory modes: a default is keyed on the product, not on a
  1901. # spool. Applying one to existing spools is the only mode-specific part, so
  1902. # the Spoolman twin of the apply route lives in spoolman_inventory.py.
  1903. def _profile_default_response(row: FilamentProfileDefault, scope: PrinterScope) -> FilamentProfileDefaultResponse:
  1904. return FilamentProfileDefaultResponse(
  1905. id=row.id,
  1906. brand=row.brand,
  1907. material=row.material,
  1908. subtype=row.subtype,
  1909. color_name=row.color_name,
  1910. slicer_filament=row.slicer_filament,
  1911. slicer_filament_name=row.slicer_filament_name,
  1912. presets=[SpoolFilamentPresetBase.model_validate(p, from_attributes=True) for p in row.presets],
  1913. # A caller limited to some printers (#1727) sees only theirs.
  1914. k_profiles=[
  1915. SpoolKProfileBase.model_validate(k, from_attributes=True)
  1916. for k in row.k_profiles
  1917. if scope.allows(k.printer_id)
  1918. ],
  1919. updated_at=row.updated_at,
  1920. )
  1921. @router.get("/profile-defaults", response_model=list[FilamentProfileDefaultResponse])
  1922. async def list_profile_defaults(
  1923. db: AsyncSession = Depends(get_db, scope="function"),
  1924. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1925. printer_scope: PrinterScope = RequestPrinterScope,
  1926. ):
  1927. """Every profile default, ordered by product."""
  1928. result = await db.execute(
  1929. select(FilamentProfileDefault)
  1930. .options(selectinload(FilamentProfileDefault.presets), selectinload(FilamentProfileDefault.k_profiles))
  1931. .order_by(
  1932. func.lower(FilamentProfileDefault.brand),
  1933. func.lower(FilamentProfileDefault.material),
  1934. func.lower(FilamentProfileDefault.subtype),
  1935. func.lower(FilamentProfileDefault.color_name),
  1936. )
  1937. )
  1938. return [_profile_default_response(row, printer_scope) for row in result.scalars().all()]
  1939. @router.get("/profile-defaults/resolve", response_model=ResolvedProfileDefault | None)
  1940. async def resolve_profile_default(
  1941. material: str,
  1942. brand: str = "",
  1943. subtype: str = "",
  1944. color_name: str = "",
  1945. db: AsyncSession = Depends(get_db, scope="function"),
  1946. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1947. printer_scope: PrinterScope = RequestPrinterScope,
  1948. ):
  1949. """What a new spool of this product starts with; null when it has no default.
  1950. The spool form fills its Printers tab from this, so the user sees what the
  1951. create will apply before saving.
  1952. """
  1953. resolved = await profile_defaults.resolve_profile_default(
  1954. db, brand=brand, material=material, subtype=subtype, color_name=color_name
  1955. )
  1956. if resolved is None:
  1957. return None
  1958. return ResolvedProfileDefault(
  1959. slicer_filament=resolved.slicer_filament,
  1960. slicer_filament_name=resolved.slicer_filament_name,
  1961. presets=[SpoolFilamentPresetBase(**p) for p in resolved.presets],
  1962. k_profiles=[SpoolKProfileBase(**k) for k in resolved.k_profiles if printer_scope.allows(k["printer_id"])],
  1963. default_ids=resolved.default_ids,
  1964. )
  1965. @router.put("/profile-defaults", response_model=FilamentProfileDefaultResponse)
  1966. async def save_profile_default(
  1967. data: FilamentProfileDefaultWrite,
  1968. db: AsyncSession = Depends(get_db, scope="function"),
  1969. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1970. printer_scope: PrinterScope = RequestPrinterScope,
  1971. ):
  1972. """Create or replace the default for the product in the body.
  1973. A full replacement, like the spool's own K-profile and preset endpoints:
  1974. the body is everything the default holds. K profiles of printers the
  1975. caller cannot see are kept rather than cleared, and the body's rows for
  1976. them are ignored.
  1977. """
  1978. # Duplicates rejected by name, before anything is written.
  1979. seen_presets: set[tuple[str, str]] = set()
  1980. for p in data.presets:
  1981. key = (p.printer_model, p.nozzle_diameter)
  1982. if key in seen_presets:
  1983. raise HTTPException(
  1984. 422, f"Duplicate override for model {p.printer_model!r} nozzle {p.nozzle_diameter or 'any'!r}"
  1985. )
  1986. seen_presets.add(key)
  1987. seen_hotends: set[tuple[int, int, str]] = set()
  1988. for k in data.k_profiles:
  1989. key = profile_defaults.hotend_key(k.printer_id, k.extruder, k.nozzle_diameter)
  1990. if key in seen_hotends:
  1991. raise HTTPException(422, f"Duplicate K profile for printer {k.printer_id} extruder {k.extruder}")
  1992. seen_hotends.add(key)
  1993. # Rows for printers the caller cannot see are ignored, as the spool's own
  1994. # K-profile save does: a form opened on a spool shows them all, and saving
  1995. # it as the default must not fail over rows the caller cannot change.
  1996. k_profiles = [k for k in data.k_profiles if printer_scope.allows(k.printer_id)]
  1997. printer_ids = {k.printer_id for k in k_profiles}
  1998. if printer_ids:
  1999. found = set((await db.execute(select(Printer.id).where(Printer.id.in_(printer_ids)))).scalars().all())
  2000. if printer_ids - found:
  2001. raise HTTPException(404, "Printer not found")
  2002. key = profile_defaults.product_key(
  2003. brand=data.brand, material=data.material, subtype=data.subtype, color_name=data.color_name
  2004. )
  2005. existing = await profile_defaults.find_default(db, key)
  2006. keep = (
  2007. {k.printer_id for k in existing.k_profiles if not printer_scope.allows(k.printer_id)}
  2008. if existing is not None
  2009. else set()
  2010. )
  2011. row = await profile_defaults.save_default(
  2012. db,
  2013. key,
  2014. slicer_filament=data.slicer_filament,
  2015. slicer_filament_name=data.slicer_filament_name,
  2016. presets=[p.model_dump() for p in data.presets],
  2017. k_profiles=[k.model_dump() for k in k_profiles],
  2018. keep_printer_ids=keep,
  2019. )
  2020. await db.commit()
  2021. row = await profile_defaults.load_default(db, row.id)
  2022. assert row is not None
  2023. return _profile_default_response(row, printer_scope)
  2024. @router.delete("/profile-defaults/{default_id}")
  2025. async def delete_profile_default(
  2026. default_id: int,
  2027. db: AsyncSession = Depends(get_db, scope="function"),
  2028. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  2029. printer_scope: PrinterScope = RequestPrinterScope,
  2030. ):
  2031. """Delete a default. Spools that already got its profiles keep them."""
  2032. row = await profile_defaults.load_default(db, default_id)
  2033. if row is None:
  2034. raise HTTPException(404, "Profile default not found")
  2035. if any(not printer_scope.allows(k.printer_id) for k in row.k_profiles):
  2036. raise HTTPException(403, "This default holds K profiles for printers you cannot access")
  2037. await db.delete(row)
  2038. await db.commit()
  2039. return {"status": "deleted"}
  2040. @router.post("/profile-defaults/{default_id}/apply", response_model=ProfileDefaultApplyResult)
  2041. async def apply_profile_default(
  2042. default_id: int,
  2043. db: AsyncSession = Depends(get_db, scope="function"),
  2044. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  2045. ):
  2046. """Fill in what active spools of this default's product do not have yet.
  2047. Never overwrites: a spool keeps its own preset, its preset per model and
  2048. nozzle, and its K profile per hotend.
  2049. """
  2050. row = await profile_defaults.load_default(db, default_id)
  2051. if row is None:
  2052. raise HTTPException(404, "Profile default not found")
  2053. updated = await profile_defaults.apply_to_internal_spools(db, row)
  2054. await db.commit()
  2055. if updated:
  2056. await ws_manager.broadcast({"type": "inventory_changed"})
  2057. return ProfileDefaultApplyResult(updated=updated)
  2058. # ── Spool Assignments ────────────────────────────────────────────────────────
  2059. @router.get("/assignments", response_model=list[SpoolAssignmentResponse])
  2060. async def list_assignments(
  2061. printer_id: int | None = None,
  2062. db: AsyncSession = Depends(get_db, scope="function"),
  2063. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_VIEW_ASSIGNMENTS),
  2064. printer_scope: PrinterScope = RequestPrinterScope,
  2065. ):
  2066. """List spool assignments, optionally filtered by printer."""
  2067. from backend.app.services.printer_manager import printer_manager
  2068. query = select(SpoolAssignment).options(
  2069. selectinload(SpoolAssignment.spool).options(*spool_response_loads()),
  2070. selectinload(SpoolAssignment.printer),
  2071. )
  2072. if printer_id is not None:
  2073. query = query.where(SpoolAssignment.printer_id == printer_id)
  2074. if (clause := printer_scope.where_strict(SpoolAssignment.printer_id)) is not None:
  2075. query = query.where(clause)
  2076. result = await db.execute(query)
  2077. assignments = list(result.scalars().all())
  2078. # Build (printer_id, ams_id) -> ams_serial map from live printer states.
  2079. # Fetch all statuses in one call rather than one get_status() call per printer.
  2080. serial_map: dict[tuple[int, int], str] = {}
  2081. seen_printer_ids: set[int] = {a.printer_id for a in assignments}
  2082. all_statuses = printer_manager.get_all_statuses()
  2083. for pid in seen_printer_ids:
  2084. state = all_statuses.get(pid)
  2085. if state and state.raw_data:
  2086. for ams_unit in state.raw_data.get("ams", []):
  2087. sn = str(ams_unit.get("sn") or ams_unit.get("serial_number") or "")
  2088. if sn:
  2089. try:
  2090. serial_map[(pid, int(ams_unit.get("id", 0)))] = sn
  2091. except (ValueError, TypeError):
  2092. continue
  2093. # Fetch all relevant AMS labels keyed by serial number
  2094. all_serials = set(serial_map.values())
  2095. # Also include the synthetic position keys: a label saved before the unit
  2096. # reported its serial (the AMS Lite before #3348) is still under one, and
  2097. # is shown until it is saved again, as on the printer card.
  2098. for a in assignments:
  2099. all_serials.add(f"p{a.printer_id}a{a.ams_id}")
  2100. label_by_serial: dict[str, str] = {}
  2101. if all_serials:
  2102. lbl_result = await db.execute(select(AmsLabel).where(AmsLabel.ams_serial_number.in_(all_serials)))
  2103. for lbl in lbl_result.scalars().all():
  2104. label_by_serial[lbl.ams_serial_number] = lbl.label
  2105. # Build response objects, attaching ams_label where available
  2106. responses: list[SpoolAssignmentResponse] = []
  2107. for a in assignments:
  2108. resp = SpoolAssignmentResponse.model_validate(a)
  2109. sn = serial_map.get((a.printer_id, a.ams_id))
  2110. if sn and sn in label_by_serial:
  2111. resp.ams_label = label_by_serial[sn]
  2112. else:
  2113. resp.ams_label = label_by_serial.get(f"p{a.printer_id}a{a.ams_id}")
  2114. responses.append(resp)
  2115. return responses
  2116. async def _printers_holding_spool(db: AsyncSession, spool_id: int, printer_scope: PrinterScope) -> set[int]:
  2117. """The printers in the caller's scope with a slot assigned to the spool."""
  2118. held = await db.execute(select(SpoolAssignment.printer_id).where(SpoolAssignment.spool_id == spool_id).distinct())
  2119. return {pid for pid in held.scalars() if printer_scope.allows(pid)}
  2120. @router.post("/assignments", response_model=SpoolAssignmentResponse)
  2121. async def assign_spool(
  2122. data: SpoolAssignmentCreate,
  2123. db: AsyncSession = Depends(get_db, scope="function"),
  2124. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  2125. printer_scope: PrinterScope = RequestPrinterScope,
  2126. actor: User | ApiKeyActor | None = RequestActor,
  2127. ):
  2128. """Assign a spool to an AMS slot and auto-configure via MQTT."""
  2129. from backend.app.services.printer_manager import printer_manager
  2130. printer_scope.ensure(data.printer_id)
  2131. # An API key (a SpoolBuddy client) has no signed-in user, so its owner's
  2132. # cloud sign-in resolves a custom preset; without it the slot got Generic
  2133. # PLA where the web UI got the preset's own filament (#3519).
  2134. preset_user = current_user
  2135. if preset_user is None and isinstance(actor, ApiKeyActor):
  2136. preset_user = await load_preset_lookup_user(db, actor.id)
  2137. # 1. Validate spool exists and is not archived
  2138. result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id == data.spool_id))
  2139. spool = result.scalar_one_or_none()
  2140. if not spool:
  2141. raise HTTPException(404, "Spool not found")
  2142. if spool.archived_at:
  2143. raise HTTPException(400, "Cannot assign an archived spool")
  2144. # 2. Get current AMS tray state for fingerprint + existing filament ID.
  2145. # tray_state: Bambu firmware reports 11=loaded, 9=empty, 10=spool present
  2146. # but filament not in feeder. Captured here so the empty-slot heuristic
  2147. # below can prefer it over tray_type — a manual "Reset slot" clears
  2148. # tray_type to "" while leaving state at 11 (filament still physically
  2149. # present), which would otherwise mislead the heuristic into the
  2150. # pending-config branch and skip MQTT forever (#1228 follow-up).
  2151. fingerprint_color = None
  2152. fingerprint_type = None
  2153. current_tray_info_idx = ""
  2154. current_tray_sub_brands = ""
  2155. tray_state: int | None = None
  2156. # Firmware's tray_exist_bits answer for this slot, when the payload carries
  2157. # one. Outranks tray_state below — see services/ams_slot_presence.py.
  2158. tray_has_spool: bool | None = None
  2159. state = printer_manager.get_status(data.printer_id)
  2160. if state and state.raw_data:
  2161. if data.ams_id == 255:
  2162. # External slot: look up tray from vt_tray by global ID
  2163. vt_tray = state.raw_data.get("vt_tray") or []
  2164. ext_id = external_tray_id(data.tray_id) # 0→254, 1→255, rack 2-8→247-253
  2165. for vt in vt_tray:
  2166. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2167. fingerprint_color = vt.get("tray_color", "")
  2168. fingerprint_type = vt.get("tray_type", "")
  2169. current_tray_info_idx = vt.get("tray_info_idx", "")
  2170. current_tray_sub_brands = vt.get("tray_sub_brands", "")
  2171. raw_state = vt.get("state")
  2172. if isinstance(raw_state, int):
  2173. tray_state = raw_state
  2174. tray_has_spool = spool_present(vt)
  2175. break
  2176. else:
  2177. ams_data = state.raw_data.get("ams", {})
  2178. ams_list = (
  2179. ams_data.get("ams", [])
  2180. if isinstance(ams_data, dict)
  2181. else ams_data
  2182. if isinstance(ams_data, list)
  2183. else []
  2184. )
  2185. tray = _find_tray_in_ams_data(
  2186. ams_list,
  2187. data.ams_id,
  2188. data.tray_id,
  2189. )
  2190. if tray:
  2191. fingerprint_color = tray.get("tray_color", "")
  2192. fingerprint_type = tray.get("tray_type", "")
  2193. current_tray_info_idx = tray.get("tray_info_idx", "")
  2194. current_tray_sub_brands = tray.get("tray_sub_brands", "")
  2195. raw_state = tray.get("state")
  2196. if isinstance(raw_state, int):
  2197. tray_state = raw_state
  2198. tray_has_spool = spool_present(tray)
  2199. # 3. Upsert assignment (replace if same printer+ams+tray), under the lock
  2200. # the AMS change handler writes the printer's slots with.
  2201. #
  2202. # A move (#1574) also takes the spool out of every other slot it holds, in
  2203. # the same commit, so a failed move leaves it where it was instead of in no
  2204. # slot. Moves of one spool take turns (get_spool_move_lock): two at once
  2205. # would each read where the spool is before the other committed, and both
  2206. # assign it. The slots' printers are locked as well, in id order so two
  2207. # moves can't take the same two locks the other way round. Which printers
  2208. # those are is read again once the locks are held: a move served first, a
  2209. # plain assign or an AMS change may have put the spool on one more, and
  2210. # then this one lets go and locks the larger set. A slot on a printer
  2211. # outside the caller's scope stays assigned, as unassigning leaves it
  2212. # (#1727).
  2213. locked_printer_ids = {data.printer_id}
  2214. if data.move:
  2215. locked_printer_ids |= await _printers_holding_spool(db, data.spool_id, printer_scope)
  2216. vacated: list[tuple[int, int, int]] = []
  2217. while True:
  2218. async with AsyncExitStack() as locks:
  2219. if data.move:
  2220. await locks.enter_async_context(get_spool_move_lock("inventory", data.spool_id))
  2221. for pid in sorted(locked_printer_ids):
  2222. await locks.enter_async_context(get_ams_assignment_lock(pid))
  2223. if data.move:
  2224. holding = await _printers_holding_spool(db, data.spool_id, printer_scope)
  2225. if not holding <= locked_printer_ids:
  2226. locked_printer_ids |= holding
  2227. continue
  2228. others = await db.execute(
  2229. select(SpoolAssignment).where(
  2230. SpoolAssignment.spool_id == data.spool_id,
  2231. SpoolAssignment.printer_id.in_(locked_printer_ids),
  2232. )
  2233. )
  2234. for row in others.scalars().all():
  2235. if (row.printer_id, row.ams_id, row.tray_id) != (data.printer_id, data.ams_id, data.tray_id):
  2236. vacated.append((row.printer_id, row.ams_id, row.tray_id))
  2237. await db.delete(row)
  2238. existing = await db.execute(
  2239. select(SpoolAssignment).where(
  2240. SpoolAssignment.printer_id == data.printer_id,
  2241. SpoolAssignment.ams_id == data.ams_id,
  2242. SpoolAssignment.tray_id == data.tray_id,
  2243. )
  2244. )
  2245. old = existing.scalar_one_or_none()
  2246. if old:
  2247. await db.delete(old)
  2248. await db.flush()
  2249. assignment = SpoolAssignment(
  2250. spool_id=data.spool_id,
  2251. printer_id=data.printer_id,
  2252. ams_id=data.ams_id,
  2253. tray_id=data.tray_id,
  2254. fingerprint_color=fingerprint_color,
  2255. fingerprint_type=fingerprint_type,
  2256. assigned_by_user_id=preset_user.id if preset_user is not None else None,
  2257. )
  2258. db.add(assignment)
  2259. await spool_swaps.record_assignment(
  2260. db, data.printer_id, data.ams_id, data.tray_id, data.spool_id, spool_swaps.INVENTORY
  2261. )
  2262. await db.commit()
  2263. break
  2264. await db.refresh(assignment)
  2265. slot_unlink_grace.forget_slot(data.printer_id, data.ams_id, data.tray_id)
  2266. if vacated:
  2267. logger.info(
  2268. "Moved spool %d to printer %d AMS%d-T%d from %s",
  2269. spool.id,
  2270. data.printer_id,
  2271. data.ams_id,
  2272. data.tray_id,
  2273. ", ".join(f"printer {p} AMS{a}-T{t}" for p, a, t in vacated),
  2274. )
  2275. # 4. Auto-configure AMS slot via MQTT.
  2276. #
  2277. # Only suppress the publish when the firmware's *explicit* empty signal
  2278. # (state ∈ {9, 10}) is set — "no spool" / "spool present but no feed".
  2279. # Every other state, including state=3 (the default idle on A1 Mini BMCU /
  2280. # P1S Standard AMS for both loaded and unconfigured slots) and missing
  2281. # state (older firmwares), is treated as the user's assertion that a
  2282. # spool is in the slot and we attempt the MQTT push.
  2283. #
  2284. # The pre-existing "skip when slot looks empty" guard read state=3 +
  2285. # tray_type="" as "empty" and skipped MQTT. On these firmwares that
  2286. # combination is the post-"Reset Slot" state with the spool still
  2287. # physically inserted — there is NO AMS signal that distinguishes it
  2288. # from a truly-empty slot, so the guard created a deadlock: MQTT never
  2289. # fired, the AMS never reported any change (because nothing changed
  2290. # physically), and on_ams_change replay therefore never re-fired the
  2291. # config either. Reporter (#1322 follow-up by @RosdasHH) verified
  2292. # empirically that removing the guard makes the slot configure
  2293. # correctly because Bambu firmware DOES accept the push for a
  2294. # physically-loaded slot, even when tray_type is "" and state is 3.
  2295. #
  2296. # Trade-off for the truly-empty slot case: firmware drops the push
  2297. # silently (per Bambu's documented behavior), the SpoolAssignment row
  2298. # still has empty fingerprint_type because nothing in the assign path
  2299. # updates that column, and on_ams_change at main.py:1031-1054 still
  2300. # fires the deferred config when a spool eventually appears. So the
  2301. # SpoolBuddy weigh-then-assign-before-insert workflow continues to
  2302. # work — just without the optimization of skipping a no-op MQTT call.
  2303. #
  2304. # state ∈ {9, 10} stays as an explicit short-circuit so we don't churn
  2305. # a doomed MQTT push when the firmware has positively confirmed "no
  2306. # spool" — and to keep the on_ams_change replay path as the single
  2307. # source of truth for those slots.
  2308. #
  2309. # ...except that `state` cannot carry that meaning. Two independent ways
  2310. # a loaded slot reads 9 here:
  2311. #
  2312. # - an AMS-HT reports its LOADED tray as 9, not 11, because it does not
  2313. # feed into a shared buffer the way a 4-slot AMS does (#2594, and the
  2314. # merge above skips its own state heuristic for HT units for exactly
  2315. # this reason). So this branch called every HT slot empty on sight.
  2316. # - apply_tray_exist_bits stamps state=9 on any slot whose tray_exist_bits
  2317. # bit is 0 and never takes it back when the bit returns, so a slot that
  2318. # was briefly emptied keeps the 9 until something configures it.
  2319. #
  2320. # Either way the slot sits at exists=True, state=9, this branch took the
  2321. # pending path, nothing was published, and the printer kept showing "?"
  2322. # (#3084 — reported against an H2C's AMS-HT, where both apply). Firmware's
  2323. # presence bit is what actually answers "is a spool in this slot", and the
  2324. # printer card has read it ahead of `state` since #2527.
  2325. #
  2326. # It is allowed to overrule the 9 and nothing else. A bit reading *empty*
  2327. # deliberately does NOT start suppressing pushes that go out today: the
  2328. # cost of being wrong there is a slot that silently stops configuring, on
  2329. # whichever AMS variant we compute the bit position wrong for, against a
  2330. # saving of one MQTT message the firmware would have dropped anyway.
  2331. slot_is_definitely_empty = tray_has_spool is not True and (tray_state == 9 or tray_state == 10)
  2332. configured = False
  2333. if not slot_is_definitely_empty:
  2334. try:
  2335. configured = await apply_spool_to_slot_via_mqtt(
  2336. db=db,
  2337. current_user=preset_user,
  2338. spool=spool,
  2339. printer_id=data.printer_id,
  2340. ams_id=data.ams_id,
  2341. tray_id=data.tray_id,
  2342. current_tray_info_idx=current_tray_info_idx,
  2343. current_tray_type=fingerprint_type or "",
  2344. current_tray_sub_brands=current_tray_sub_brands,
  2345. )
  2346. except Exception as e:
  2347. logger.warning("MQTT auto-configure failed for spool %d: %s", spool.id, e)
  2348. else:
  2349. # Nudge a fresh pushall so the read-back verification registered in
  2350. # apply_spool_to_slot_via_mqtt (#2582) has current tray telemetry to
  2351. # compare against within its window, instead of waiting for the next
  2352. # idle push. Best-effort — the periodic push is the fallback.
  2353. if configured:
  2354. try:
  2355. client = printer_manager.get_client(data.printer_id)
  2356. if client:
  2357. client.request_status_update()
  2358. except Exception:
  2359. pass
  2360. # pending_config is the "config not landed yet" UI marker. True when the
  2361. # firmware said empty, OR when MQTT couldn't actually publish (printer
  2362. # offline, no client, transient failure). on_ams_change replay re-fires
  2363. # the config in either case once the AMS reports a non-empty fingerprint.
  2364. pending_config = slot_is_definitely_empty or not configured
  2365. # Return assignment with spool data
  2366. result = await db.execute(
  2367. select(SpoolAssignment)
  2368. .options(
  2369. selectinload(SpoolAssignment.spool).options(*spool_response_loads()),
  2370. selectinload(SpoolAssignment.printer),
  2371. )
  2372. .where(SpoolAssignment.id == assignment.id)
  2373. )
  2374. resp = result.scalar_one()
  2375. response = SpoolAssignmentResponse.model_validate(resp)
  2376. response.configured = configured
  2377. response.pending_config = pending_config
  2378. if pending_config:
  2379. logger.info(
  2380. "Pre-configured assignment: spool %d → printer %d AMS%d-T%d (slot empty, will configure on insert)",
  2381. spool.id,
  2382. data.printer_id,
  2383. data.ams_id,
  2384. data.tray_id,
  2385. )
  2386. for printer_id, ams_id, tray_id in [*vacated, (data.printer_id, data.ams_id, data.tray_id)]:
  2387. await ws_manager.broadcast(
  2388. {
  2389. "type": "spool_assignment_changed",
  2390. "printer_id": printer_id,
  2391. "ams_id": ams_id,
  2392. "tray_id": tray_id,
  2393. }
  2394. )
  2395. return response
  2396. @router.delete("/assignments/{printer_id}/{ams_id}/{tray_id}")
  2397. async def unassign_spool(
  2398. printer_id: int,
  2399. ams_id: int,
  2400. tray_id: int,
  2401. db: AsyncSession = Depends(get_db, scope="function"),
  2402. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  2403. ):
  2404. """Unassign a spool from an AMS slot."""
  2405. async with get_ams_assignment_lock(printer_id):
  2406. result = await db.execute(
  2407. select(SpoolAssignment).where(
  2408. SpoolAssignment.printer_id == printer_id,
  2409. SpoolAssignment.ams_id == ams_id,
  2410. SpoolAssignment.tray_id == tray_id,
  2411. )
  2412. )
  2413. assignment = result.scalar_one_or_none()
  2414. if not assignment:
  2415. raise HTTPException(404, "Assignment not found")
  2416. await db.delete(assignment)
  2417. await db.commit()
  2418. await ws_manager.broadcast(
  2419. {
  2420. "type": "spool_assignment_changed",
  2421. "printer_id": printer_id,
  2422. "ams_id": ams_id,
  2423. "tray_id": tray_id,
  2424. }
  2425. )
  2426. return {"status": "deleted"}
  2427. # ── Tag Linking ───────────────────────────────────────────────────────────────
  2428. class LinkTagRequest(BaseModel):
  2429. tag_uid: str | None = None
  2430. tray_uuid: str | None = None
  2431. tag_type: str | None = None
  2432. data_origin: str | None = "nfc_link"
  2433. def _validate_tag_input(
  2434. raw_value: str | None, normalized_value: str | None, field_name: str, exact_len: int | None = None
  2435. ) -> None:
  2436. if raw_value is None:
  2437. return
  2438. raw = str(raw_value).strip()
  2439. if not raw:
  2440. return
  2441. if normalized_value is None:
  2442. raise HTTPException(422, f"{field_name} must contain hexadecimal characters")
  2443. if len(normalized_value) % 2 != 0:
  2444. raise HTTPException(422, f"{field_name} must have an even number of hex characters")
  2445. if exact_len is not None and len(normalized_value) != exact_len:
  2446. raise HTTPException(422, f"{field_name} must be exactly {exact_len} hex characters")
  2447. @router.patch("/spools/{spool_id}/link-tag", response_model=SpoolResponse)
  2448. async def link_tag_to_spool(
  2449. spool_id: int,
  2450. data: LinkTagRequest,
  2451. db: AsyncSession = Depends(get_db, scope="function"),
  2452. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  2453. ):
  2454. """Link an RFID tag_uid/tray_uuid to an existing spool.
  2455. A tag another active spool already carries is refused with the shared
  2456. ``tag_already_linked`` 409, which names that spool so a caller can offer
  2457. to move the tag instead of only reporting that it is taken (#3110).
  2458. """
  2459. result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id == spool_id))
  2460. spool = result.scalar_one_or_none()
  2461. if not spool:
  2462. raise HTTPException(404, "Spool not found")
  2463. if spool.archived_at:
  2464. raise HTTPException(400, "Cannot link tag to archived spool")
  2465. normalized_tag_uid = (normalize_tag_uid(data.tag_uid) or None) if data.tag_uid is not None else None
  2466. normalized_tray_uuid = (normalize_tray_uuid(data.tray_uuid) or None) if data.tray_uuid is not None else None
  2467. _validate_tag_input(data.tag_uid, normalized_tag_uid, "tag_uid")
  2468. _validate_tag_input(data.tray_uuid, normalized_tray_uuid, "tray_uuid", exact_len=32)
  2469. # Check for conflicts: tag already linked to another active spool.
  2470. #
  2471. # Ordered, and read with first() rather than scalar_one_or_none(), because
  2472. # two active spools really can carry one tag: neither column has a unique
  2473. # index, PATCH /spools/{id} writes them with no conflict check, and
  2474. # POST /spools/bulk copies a single payload -- tag included -- into every
  2475. # row it creates. scalar_one_or_none() answered that with MultipleResultsFound,
  2476. # which escapes into the auth middleware's fail-closed handler and reaches
  2477. # the caller as 503 "Authentication service temporarily unavailable" -- a
  2478. # wrong answer pointing at the wrong subsystem, where a 409 was owed
  2479. # (#3110). get_spool_by_tag above already resolves duplicates this way.
  2480. if normalized_tag_uid:
  2481. conflict = await db.execute(
  2482. select(Spool)
  2483. .where(
  2484. func.upper(Spool.tag_uid) == normalized_tag_uid,
  2485. Spool.id != spool_id,
  2486. Spool.archived_at.is_(None),
  2487. )
  2488. .order_by(Spool.id)
  2489. )
  2490. holder = conflict.scalars().first()
  2491. if holder:
  2492. raise tag_already_linked("tag_uid", holder.id)
  2493. # Auto-clear from archived spools (tag recycling)
  2494. archived_with_tag = await db.execute(
  2495. select(Spool).where(
  2496. func.upper(Spool.tag_uid) == normalized_tag_uid,
  2497. Spool.id != spool_id,
  2498. Spool.archived_at.is_not(None),
  2499. )
  2500. )
  2501. for old_spool in archived_with_tag.scalars().all():
  2502. old_spool.tag_uid = None
  2503. if normalized_tray_uuid:
  2504. conflict = await db.execute(
  2505. select(Spool)
  2506. .where(
  2507. func.upper(Spool.tray_uuid) == normalized_tray_uuid,
  2508. Spool.id != spool_id,
  2509. Spool.archived_at.is_(None),
  2510. )
  2511. .order_by(Spool.id)
  2512. )
  2513. holder = conflict.scalars().first()
  2514. if holder:
  2515. raise tag_already_linked("tray_uuid", holder.id)
  2516. archived_with_uuid = await db.execute(
  2517. select(Spool).where(
  2518. func.upper(Spool.tray_uuid) == normalized_tray_uuid,
  2519. Spool.id != spool_id,
  2520. Spool.archived_at.is_not(None),
  2521. )
  2522. )
  2523. for old_spool in archived_with_uuid.scalars().all():
  2524. old_spool.tray_uuid = None
  2525. if data.tag_uid is not None:
  2526. spool.tag_uid = normalized_tag_uid
  2527. if data.tray_uuid is not None:
  2528. spool.tray_uuid = normalized_tray_uuid
  2529. if data.tag_type is not None:
  2530. spool.tag_type = data.tag_type
  2531. if data.data_origin is not None:
  2532. spool.data_origin = data.data_origin
  2533. await db.commit()
  2534. result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id == spool_id))
  2535. return result.scalar_one()
  2536. # ── Usage History ─────────────────────────────────────────────────────────────
  2537. @router.get("/spools/{spool_id}/usage", response_model=list[SpoolUsageHistoryResponse])
  2538. async def get_spool_usage_history(
  2539. spool_id: int,
  2540. limit: int = 50,
  2541. db: AsyncSession = Depends(get_db, scope="function"),
  2542. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  2543. ):
  2544. """Get usage history for a specific spool."""
  2545. from backend.app.models.spool_usage_history import SpoolUsageHistory
  2546. # Verify spool exists
  2547. spool_result = await db.execute(select(Spool).where(Spool.id == spool_id))
  2548. if not spool_result.scalar_one_or_none():
  2549. raise HTTPException(404, "Spool not found")
  2550. result = await db.execute(
  2551. select(SpoolUsageHistory)
  2552. .where(SpoolUsageHistory.spool_id == spool_id)
  2553. .order_by(SpoolUsageHistory.created_at.desc())
  2554. .limit(limit)
  2555. )
  2556. return list(result.scalars().all())
  2557. @router.get("/stats/suppliers", response_model=list[SupplierStats])
  2558. async def get_supplier_stats(
  2559. date_from: date | None = Query(None, description="Start date (inclusive), YYYY-MM-DD"),
  2560. date_to: date | None = Query(None, description="End date (inclusive), YYYY-MM-DD"),
  2561. tz: str | None = Query(
  2562. None, max_length=64, description="IANA zone the dates are calendar days in; the server's when omitted"
  2563. ),
  2564. db: AsyncSession = Depends(get_db, scope="function"),
  2565. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  2566. ):
  2567. """Aggregate the inventory by purchase-source supplier (#2988).
  2568. Groups by the supplier a spool was actually bought from (the
  2569. ``is_purchase_source`` assignment), so "how much did we run through
  2570. supplier X" reads directly. Stock comes from active spools; consumption
  2571. and cost from the recorded usage history, archived spools included —
  2572. their consumption happened. Sorted by consumption, heaviest first, then by name.
  2573. ``date_from`` / ``date_to`` scope the usage half only, so the widget can
  2574. honour the dashboard timeframe like every other one on that page. Stock is
  2575. point-in-time by nature and is never windowed.
  2576. """
  2577. from backend.app.models.spool_usage_history import SpoolUsageHistory
  2578. purchase_link = (SpoolSupplier.spool_id == Spool.id) & SpoolSupplier.is_purchase_source.is_(True)
  2579. usage_window = []
  2580. if date_from:
  2581. usage_window.append(SpoolUsageHistory.created_at >= local_date_start(date_from, day_zone(tz)))
  2582. if date_to:
  2583. usage_window.append(SpoolUsageHistory.created_at <= local_date_end(date_to, day_zone(tz)))
  2584. remaining = Spool.label_weight - Spool.weight_used
  2585. inventory_rows = await db.execute(
  2586. select(
  2587. SpoolSupplier.supplier_id,
  2588. func.count(Spool.id),
  2589. # Clamp each spool before summing: an over-consumed spool counts as
  2590. # empty, not as negative stock that eats into its neighbours.
  2591. func.sum(case((remaining > 0, remaining), else_=0.0)),
  2592. )
  2593. .select_from(Spool)
  2594. .join(SpoolSupplier, purchase_link)
  2595. .where(Spool.archived_at.is_(None))
  2596. .group_by(SpoolSupplier.supplier_id)
  2597. )
  2598. usage_rows = await db.execute(
  2599. select(
  2600. SpoolSupplier.supplier_id,
  2601. func.sum(SpoolUsageHistory.weight_used),
  2602. func.sum(SpoolUsageHistory.cost),
  2603. )
  2604. .select_from(SpoolUsageHistory)
  2605. .join(Spool, SpoolUsageHistory.spool_id == Spool.id)
  2606. .join(SpoolSupplier, purchase_link)
  2607. .where(*usage_window)
  2608. .group_by(SpoolSupplier.supplier_id)
  2609. )
  2610. names = dict((await db.execute(select(Supplier.id, Supplier.name))).all())
  2611. stats: dict[int, SupplierStats] = {}
  2612. for supplier_id, count, remaining_g in inventory_rows.all():
  2613. stats[supplier_id] = SupplierStats(
  2614. supplier_id=supplier_id,
  2615. supplier_name=names.get(supplier_id, f"#{supplier_id}"),
  2616. spool_count=count,
  2617. remaining_g=float(remaining_g or 0),
  2618. consumed_g=0.0,
  2619. cost=0.0,
  2620. )
  2621. for supplier_id, consumed, cost in usage_rows.all():
  2622. entry = stats.get(supplier_id)
  2623. if entry is None:
  2624. entry = SupplierStats(
  2625. supplier_id=supplier_id,
  2626. supplier_name=names.get(supplier_id, f"#{supplier_id}"),
  2627. spool_count=0,
  2628. remaining_g=0.0,
  2629. consumed_g=0.0,
  2630. cost=0.0,
  2631. )
  2632. stats[supplier_id] = entry
  2633. entry.consumed_g = float(consumed or 0)
  2634. entry.cost = float(cost or 0)
  2635. # Name breaks ties: a narrow date range leaves most rows at 0 g consumed,
  2636. # and those would otherwise come back in GROUP BY order.
  2637. return sorted(stats.values(), key=lambda s: (-s.consumed_g, supplier_name_key(s.supplier_name)))
  2638. @router.get("/stats/material-numbers", response_model=list[MaterialNumberStats])
  2639. async def get_material_number_stats(
  2640. date_from: date | None = Query(None),
  2641. date_to: date | None = Query(None),
  2642. tz: str | None = Query(
  2643. None, max_length=64, description="IANA zone the dates are calendar days in; the server's when omitted"
  2644. ),
  2645. db: AsyncSession = Depends(get_db, scope="function"),
  2646. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  2647. ):
  2648. """Aggregate the inventory by material number (#2870).
  2649. The material number is the internal purchasing identifier shared by all
  2650. spools of a product, so this is the grouping the business actually costs
  2651. by — unlike brand+material+colour. Two queries: active-spool counts and
  2652. remaining weight from the spool table, consumption and cost from the
  2653. recorded usage history (archived spools included — their consumption
  2654. happened).
  2655. ``date_from``/``date_to`` narrow the usage half only, so the widget can
  2656. follow the dashboard timeframe the rest of the stats page uses. Stock is
  2657. point-in-time by nature and stays unfiltered — "how much do I hold" has
  2658. no date range. Sorted by consumption, heaviest first, then by number so
  2659. a range where nothing was consumed still lists in a stable order.
  2660. """
  2661. from backend.app.models.spool_usage_history import SpoolUsageHistory
  2662. # material_number is normalised to NULL-or-non-empty by the schema
  2663. # validator, so NULL is the only "unset" state to exclude here.
  2664. has_number = Spool.material_number.is_not(None)
  2665. from sqlalchemy import ColumnElement
  2666. usage_filters: list[ColumnElement[bool]] = [has_number]
  2667. if date_from:
  2668. usage_filters.append(SpoolUsageHistory.created_at >= local_date_start(date_from, day_zone(tz)))
  2669. if date_to:
  2670. usage_filters.append(SpoolUsageHistory.created_at <= local_date_end(date_to, day_zone(tz)))
  2671. # Clamped PER SPOOL, like every other remaining-weight computation in the
  2672. # codebase: a spool whose weight_used overshot its label_weight holds 0 g,
  2673. # it does not subtract from the other spools sharing the number.
  2674. per_spool_remaining = func.coalesce(Spool.label_weight, 0) - func.coalesce(Spool.weight_used, 0)
  2675. inventory_rows = await db.execute(
  2676. select(
  2677. Spool.material_number,
  2678. func.count(Spool.id),
  2679. func.sum(case((per_spool_remaining > 0, per_spool_remaining), else_=0.0)),
  2680. )
  2681. .where(has_number, Spool.archived_at.is_(None))
  2682. .group_by(Spool.material_number)
  2683. )
  2684. usage_rows = await db.execute(
  2685. select(
  2686. Spool.material_number,
  2687. func.sum(SpoolUsageHistory.weight_used),
  2688. func.sum(SpoolUsageHistory.cost),
  2689. )
  2690. .join(Spool, SpoolUsageHistory.spool_id == Spool.id)
  2691. .where(*usage_filters)
  2692. .group_by(Spool.material_number)
  2693. )
  2694. stats: dict[str, MaterialNumberStats] = {}
  2695. for number, count, remaining in inventory_rows.all():
  2696. stats[number] = MaterialNumberStats(
  2697. material_number=number,
  2698. spool_count=count,
  2699. remaining_g=float(remaining or 0),
  2700. consumed_g=0.0,
  2701. cost=0.0,
  2702. )
  2703. for number, consumed, cost in usage_rows.all():
  2704. entry = stats.get(number)
  2705. if entry is None:
  2706. entry = MaterialNumberStats(
  2707. material_number=number, spool_count=0, remaining_g=0.0, consumed_g=0.0, cost=0.0
  2708. )
  2709. stats[number] = entry
  2710. entry.consumed_g = float(consumed or 0)
  2711. entry.cost = float(cost or 0)
  2712. return sorted(stats.values(), key=lambda s: (-s.consumed_g, s.material_number))
  2713. @router.get("/usage", response_model=list[SpoolUsageHistoryResponse])
  2714. async def get_all_usage_history(
  2715. limit: int = 100,
  2716. printer_id: int | None = None,
  2717. spoolman: bool = False,
  2718. db: AsyncSession = Depends(get_db, scope="function"),
  2719. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  2720. printer_scope: PrinterScope = RequestPrinterScope,
  2721. ):
  2722. """Get global usage history, optionally filtered by printer.
  2723. One inventory's at a time: ``spoolman`` for the Spoolman spools'
  2724. (#3407), otherwise the built-in ones'. Each keys its spools by its own ids.
  2725. """
  2726. from backend.app.models.spool_usage_history import SpoolUsageHistory
  2727. query = (
  2728. select(SpoolUsageHistory)
  2729. .where(
  2730. SpoolUsageHistory.spoolman_spool_id.is_not(None)
  2731. if spoolman
  2732. else SpoolUsageHistory.spoolman_spool_id.is_(None)
  2733. )
  2734. .order_by(SpoolUsageHistory.created_at.desc())
  2735. .limit(limit)
  2736. )
  2737. if printer_id is not None:
  2738. query = query.where(SpoolUsageHistory.printer_id == printer_id)
  2739. if (clause := printer_scope.where(SpoolUsageHistory.printer_id)) is not None:
  2740. query = query.where(clause)
  2741. result = await db.execute(query)
  2742. return list(result.scalars().all())
  2743. @router.delete("/spools/{spool_id}/usage")
  2744. async def clear_spool_usage_history(
  2745. spool_id: int,
  2746. db: AsyncSession = Depends(get_db, scope="function"),
  2747. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  2748. ):
  2749. """Clear usage history for a spool."""
  2750. from backend.app.models.spool_usage_history import SpoolUsageHistory
  2751. result = await db.execute(select(SpoolUsageHistory).where(SpoolUsageHistory.spool_id == spool_id))
  2752. for row in result.scalars().all():
  2753. await db.delete(row)
  2754. await db.commit()
  2755. return {"status": "cleared"}
  2756. # ── AMS Weight Sync ──────────────────────────────────────────────────────────
  2757. @router.post("/sync-ams-weights")
  2758. async def sync_weights_from_ams(
  2759. db: AsyncSession = Depends(get_db, scope="function"),
  2760. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  2761. printer_scope: PrinterScope = RequestPrinterScope,
  2762. ):
  2763. """Force-sync spool weight_used from live AMS remain% data.
  2764. Overwrites the database weight_used for every assigned spool using the
  2765. current AMS remain% from connected printers. This is a manual recovery
  2766. tool — it bypasses the normal "only increase" guard, and the weight lock
  2767. a hand-set or weighed figure carries, which it releases.
  2768. A printer that is printing is left alone: its print's usage is charged
  2769. when it completes, on top of whatever weight the spool has by then.
  2770. """
  2771. from backend.app.services.printer_manager import PrinterManager, printer_manager
  2772. from backend.app.services.usage_tracker import printer_is_charging
  2773. result = await db.execute(select(SpoolAssignment).options(selectinload(SpoolAssignment.spool)))
  2774. # Only slots on printers the caller may see (#1727)
  2775. assignments = [a for a in result.scalars().all() if printer_scope.allows(a.printer_id)]
  2776. logger.info("AMS weight sync: found %d assignments", len(assignments))
  2777. synced = 0
  2778. skipped = 0
  2779. printing = 0
  2780. for assignment in assignments:
  2781. spool = assignment.spool
  2782. if not spool:
  2783. logger.debug("AMS weight sync: assignment %d has no spool", assignment.id)
  2784. skipped += 1
  2785. continue
  2786. state = printer_manager.get_status(assignment.printer_id)
  2787. # A disconnected printer keeps its last report, which is not a reading.
  2788. if not state or not state.raw_data or getattr(state, "connected", True) is False:
  2789. logger.info(
  2790. "AMS weight sync: printer %d not connected, skipping spool %d",
  2791. assignment.printer_id,
  2792. spool.id,
  2793. )
  2794. skipped += 1
  2795. continue
  2796. # Until completion has charged the print the printer counts as printing,
  2797. # also after it has reported the print finished.
  2798. printer_state = str(getattr(state, "state", "") or "").upper()
  2799. if printer_state in PrinterManager.ACTIVE_PRINT_STATES or printer_is_charging(assignment.printer_id):
  2800. logger.info("AMS weight sync: printer %d is printing, skipping spool %d", assignment.printer_id, spool.id)
  2801. skipped += 1
  2802. printing += 1
  2803. continue
  2804. ams_raw = state.raw_data.get("ams", [])
  2805. if isinstance(ams_raw, dict):
  2806. ams_raw = ams_raw.get("ams", [])
  2807. tray = _find_tray_in_ams_data(ams_raw, assignment.ams_id, assignment.tray_id)
  2808. if not tray:
  2809. logger.info(
  2810. "AMS weight sync: no tray data for spool %d (printer %d AMS%d-T%d)",
  2811. spool.id,
  2812. assignment.printer_id,
  2813. assignment.ams_id,
  2814. assignment.tray_id,
  2815. )
  2816. skipped += 1
  2817. continue
  2818. remain_raw = tray.get("remain")
  2819. if remain_raw is None:
  2820. logger.debug("AMS weight sync: no remain value for spool %d", spool.id)
  2821. skipped += 1
  2822. continue
  2823. try:
  2824. remain_val = int(remain_raw)
  2825. except (TypeError, ValueError):
  2826. skipped += 1
  2827. continue
  2828. if remain_val < 0 or remain_val > 100:
  2829. logger.debug("AMS weight sync: invalid remain=%s for spool %d", remain_raw, spool.id)
  2830. skipped += 1
  2831. continue
  2832. lw = spool.label_weight or 1000
  2833. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2834. old_used = spool.weight_used or 0
  2835. if round(old_used, 1) != new_used:
  2836. logger.info(
  2837. "AMS weight sync: spool %d weight_used %s -> %s (remain=%d%%)",
  2838. spool.id,
  2839. old_used,
  2840. new_used,
  2841. remain_val,
  2842. )
  2843. spool.weight_used = new_used
  2844. spool.weight_locked = False
  2845. synced += 1
  2846. else:
  2847. if spool.weight_locked:
  2848. # The figure already agrees with the AMS; the override still applies.
  2849. spool.weight_locked = False
  2850. skipped += 1
  2851. await db.commit()
  2852. if synced:
  2853. await ws_manager.broadcast({"type": "inventory_changed"})
  2854. return {"synced": synced, "skipped": skipped, "printing": printing}
  2855. # ── Helpers ──────────────────────────────────────────────────────────────────
  2856. def _find_tray_in_ams_data(ams_data: list, ams_id: int, tray_id: int) -> dict | None:
  2857. """Find a specific tray in the AMS data structure."""
  2858. if not ams_data:
  2859. return None
  2860. for ams_unit in ams_data:
  2861. if int(ams_unit.get("id", -1)) != ams_id:
  2862. continue
  2863. for tray in ams_unit.get("tray", []):
  2864. if int(tray.get("id", -1)) == tray_id:
  2865. return tray
  2866. return None
  2867. # ── Filament SKU Settings (reorder forecasting) ───────────────────────────────
  2868. class FilamentSkuSettingsResponse(BaseModel):
  2869. id: int
  2870. material: str
  2871. subtype: str | None
  2872. brand: str | None
  2873. color_name: str | None
  2874. lead_time_days: int
  2875. safety_margin_value: int
  2876. safety_margin_unit: str
  2877. alerts_snoozed: bool = False
  2878. class Config:
  2879. from_attributes = True
  2880. class FilamentSkuSettingsUpsert(BaseModel):
  2881. material: str
  2882. subtype: str | None = None
  2883. brand: str | None = None
  2884. color_name: str | None = None
  2885. lead_time_days: int = 0
  2886. safety_margin_value: int = 14
  2887. safety_margin_unit: str = "days"
  2888. alerts_snoozed: bool = False
  2889. @router.get("/sku-settings", response_model=list[FilamentSkuSettingsResponse])
  2890. async def list_sku_settings(
  2891. db: AsyncSession = Depends(get_db, scope="function"),
  2892. _: User | None = RequireAnyPermissionIfAuthEnabled(Permission.INVENTORY_READ, Permission.INVENTORY_FORECAST_READ),
  2893. ):
  2894. """List all filament SKU reorder settings."""
  2895. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  2896. result = await db.execute(
  2897. select(FilamentSkuSettings).order_by(FilamentSkuSettings.material, FilamentSkuSettings.brand)
  2898. )
  2899. return list(result.scalars().all())
  2900. @router.post("/sku-settings", response_model=FilamentSkuSettingsResponse)
  2901. async def upsert_sku_settings(
  2902. data: FilamentSkuSettingsUpsert,
  2903. db: AsyncSession = Depends(get_db, scope="function"),
  2904. _: User | None = RequireAnyPermissionIfAuthEnabled(
  2905. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  2906. ),
  2907. ):
  2908. """Create or update reorder settings for a filament SKU (material/subtype/brand)."""
  2909. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  2910. result = await db.execute(
  2911. select(FilamentSkuSettings).where(
  2912. FilamentSkuSettings.material == data.material,
  2913. FilamentSkuSettings.subtype == data.subtype,
  2914. FilamentSkuSettings.brand == data.brand,
  2915. FilamentSkuSettings.color_name == data.color_name,
  2916. )
  2917. )
  2918. row = result.scalar_one_or_none()
  2919. if row:
  2920. row.lead_time_days = data.lead_time_days
  2921. row.safety_margin_value = data.safety_margin_value
  2922. row.safety_margin_unit = data.safety_margin_unit
  2923. row.alerts_snoozed = data.alerts_snoozed
  2924. else:
  2925. row = FilamentSkuSettings(
  2926. material=data.material,
  2927. subtype=data.subtype,
  2928. brand=data.brand,
  2929. color_name=data.color_name,
  2930. lead_time_days=data.lead_time_days,
  2931. safety_margin_value=data.safety_margin_value,
  2932. safety_margin_unit=data.safety_margin_unit,
  2933. alerts_snoozed=data.alerts_snoozed,
  2934. )
  2935. db.add(row)
  2936. await db.commit()
  2937. await db.refresh(row)
  2938. return row
  2939. # ── Shopping List ─────────────────────────────────────────────────────────────
  2940. class ShoppingListItemResponse(BaseModel):
  2941. id: int
  2942. material: str
  2943. subtype: str | None
  2944. brand: str | None
  2945. color_name: str | None
  2946. quantity_spools: int
  2947. note: str | None
  2948. status: str
  2949. purchased_at: str | None
  2950. added_at: str
  2951. class Config:
  2952. from_attributes = True
  2953. class ShoppingListItemCreate(BaseModel):
  2954. material: str
  2955. subtype: str | None = None
  2956. brand: str | None = None
  2957. color_name: str | None = None
  2958. quantity_spools: int = 1
  2959. note: str | None = None
  2960. class ShoppingListItemStatusUpdate(BaseModel):
  2961. status: str # pending | purchased | received
  2962. @router.get("/shopping-list", response_model=list[ShoppingListItemResponse])
  2963. async def get_shopping_list(
  2964. db: AsyncSession = Depends(get_db, scope="function"),
  2965. _: User | None = RequireAnyPermissionIfAuthEnabled(Permission.INVENTORY_READ, Permission.INVENTORY_FORECAST_READ),
  2966. ):
  2967. """Get the filament shopping list."""
  2968. from backend.app.models.shopping_list import ShoppingListItem
  2969. result = await db.execute(select(ShoppingListItem).order_by(ShoppingListItem.added_at.desc()))
  2970. items = result.scalars().all()
  2971. return [
  2972. ShoppingListItemResponse(
  2973. id=i.id,
  2974. material=i.material,
  2975. subtype=i.subtype,
  2976. brand=i.brand,
  2977. color_name=i.color_name,
  2978. quantity_spools=i.quantity_spools,
  2979. note=i.note,
  2980. status=i.status or "pending",
  2981. purchased_at=i.purchased_at.isoformat() if i.purchased_at else None,
  2982. added_at=i.added_at.isoformat() if i.added_at else "",
  2983. )
  2984. for i in items
  2985. ]
  2986. @router.post("/shopping-list", response_model=ShoppingListItemResponse)
  2987. async def add_to_shopping_list(
  2988. data: ShoppingListItemCreate,
  2989. db: AsyncSession = Depends(get_db, scope="function"),
  2990. _: User | None = RequireAnyPermissionIfAuthEnabled(
  2991. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  2992. ),
  2993. ):
  2994. """Add a filament SKU to the shopping list."""
  2995. from backend.app.models.shopping_list import ShoppingListItem
  2996. item = ShoppingListItem(
  2997. material=data.material,
  2998. subtype=data.subtype,
  2999. brand=data.brand,
  3000. color_name=data.color_name,
  3001. quantity_spools=data.quantity_spools,
  3002. note=data.note,
  3003. )
  3004. db.add(item)
  3005. await db.commit()
  3006. await db.refresh(item)
  3007. return ShoppingListItemResponse(
  3008. id=item.id,
  3009. material=item.material,
  3010. subtype=item.subtype,
  3011. brand=item.brand,
  3012. color_name=item.color_name,
  3013. quantity_spools=item.quantity_spools,
  3014. note=item.note,
  3015. status=item.status or "pending",
  3016. purchased_at=item.purchased_at.isoformat() if item.purchased_at else None,
  3017. added_at=item.added_at.isoformat() if item.added_at else "",
  3018. )
  3019. @router.patch("/shopping-list/{item_id}/status", response_model=ShoppingListItemResponse)
  3020. async def update_shopping_list_status(
  3021. item_id: int,
  3022. data: ShoppingListItemStatusUpdate,
  3023. db: AsyncSession = Depends(get_db, scope="function"),
  3024. _: User | None = RequireAnyPermissionIfAuthEnabled(
  3025. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  3026. ),
  3027. ):
  3028. """Update the purchase status of a shopping list item."""
  3029. from backend.app.models.shopping_list import ShoppingListItem
  3030. if data.status not in ("pending", "purchased", "received"):
  3031. raise HTTPException(400, "Invalid status")
  3032. result = await db.execute(select(ShoppingListItem).where(ShoppingListItem.id == item_id))
  3033. item = result.scalar_one_or_none()
  3034. if not item:
  3035. raise HTTPException(404, "Item not found")
  3036. item.status = data.status
  3037. if data.status in ("purchased", "received") and item.purchased_at is None:
  3038. item.purchased_at = datetime.now(timezone.utc)
  3039. elif data.status == "pending":
  3040. item.purchased_at = None
  3041. await db.commit()
  3042. await db.refresh(item)
  3043. return ShoppingListItemResponse(
  3044. id=item.id,
  3045. material=item.material,
  3046. subtype=item.subtype,
  3047. brand=item.brand,
  3048. color_name=item.color_name,
  3049. quantity_spools=item.quantity_spools,
  3050. note=item.note,
  3051. status=item.status or "pending",
  3052. purchased_at=item.purchased_at.isoformat() if item.purchased_at else None,
  3053. added_at=item.added_at.isoformat() if item.added_at else "",
  3054. )
  3055. @router.delete("/shopping-list/{item_id}")
  3056. async def remove_from_shopping_list(
  3057. item_id: int,
  3058. db: AsyncSession = Depends(get_db, scope="function"),
  3059. _: User | None = RequireAnyPermissionIfAuthEnabled(
  3060. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  3061. ),
  3062. ):
  3063. """Remove a single item from the shopping list."""
  3064. from backend.app.models.shopping_list import ShoppingListItem
  3065. result = await db.execute(select(ShoppingListItem).where(ShoppingListItem.id == item_id))
  3066. item = result.scalar_one_or_none()
  3067. if not item:
  3068. raise HTTPException(404, "Item not found")
  3069. await db.delete(item)
  3070. await db.commit()
  3071. return {"status": "deleted"}
  3072. @router.delete("/shopping-list")
  3073. async def clear_shopping_list(
  3074. db: AsyncSession = Depends(get_db, scope="function"),
  3075. _: User | None = RequireAnyPermissionIfAuthEnabled(
  3076. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  3077. ),
  3078. ):
  3079. """Clear all items from the shopping list."""
  3080. from backend.app.models.shopping_list import ShoppingListItem
  3081. result = await db.execute(delete(ShoppingListItem).returning(ShoppingListItem.id))
  3082. deleted = len(result.fetchall())
  3083. await db.commit()
  3084. return {"deleted": deleted}
  3085. class CreateSpoolFromSlotRequest(BaseModel):
  3086. printer_id: int
  3087. ams_id: int
  3088. tray_id: int
  3089. @router.post("/spools/from-slot", response_model=SpoolResponse)
  3090. async def create_spool_from_slot(
  3091. req: CreateSpoolFromSlotRequest,
  3092. db: AsyncSession = Depends(get_db, scope="function"),
  3093. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  3094. printer_scope: PrinterScope = RequestPrinterScope,
  3095. ):
  3096. """Explicit user action: create an inventory spool from an AMS slot's current tray data.
  3097. Used by the "+ Add to inventory" affordance when auto_add_unknown_rfid is disabled —
  3098. the user looked at the slot and chose to register it. Also assigns the new spool
  3099. to the slot in the same call.
  3100. """
  3101. from backend.app.services.printer_manager import printer_manager
  3102. from backend.app.services.spool_tag_matcher import auto_assign_spool, create_spool_from_tray
  3103. printer_scope.ensure(req.printer_id)
  3104. state = printer_manager.get_status(req.printer_id)
  3105. if not state or not state.raw_data:
  3106. raise HTTPException(status_code=404, detail="Printer not connected or no state available")
  3107. ams_data = state.raw_data.get("ams")
  3108. ams_units: list[dict] = []
  3109. if isinstance(ams_data, list):
  3110. ams_units = ams_data
  3111. elif isinstance(ams_data, dict):
  3112. if "ams" in ams_data and isinstance(ams_data["ams"], list):
  3113. ams_units = ams_data["ams"]
  3114. elif "tray" in ams_data:
  3115. ams_units = [{"id": 0, "tray": ams_data.get("tray", [])}]
  3116. tray: dict | None = None
  3117. for unit in ams_units:
  3118. if not isinstance(unit, dict):
  3119. continue
  3120. if int(unit.get("id", -1)) != req.ams_id:
  3121. continue
  3122. for t in unit.get("tray", []):
  3123. if isinstance(t, dict) and int(t.get("id", -1)) == req.tray_id:
  3124. tray = t
  3125. break
  3126. if tray:
  3127. break
  3128. if not tray or not tray.get("tray_type"):
  3129. raise HTTPException(status_code=400, detail="Slot is empty or has no readable tray data")
  3130. # Guard against ghost-spool creation: a slot without any RFID tag has no
  3131. # stable identity, so creating an inventory row would just duplicate on
  3132. # every confirm and never re-link to the physical spool.
  3133. from backend.app.services.spool_tag_matcher import is_valid_tag
  3134. if not is_valid_tag(tray.get("tag_uid", ""), tray.get("tray_uuid", "")):
  3135. raise HTTPException(status_code=400, detail="Slot has no RFID tag")
  3136. # Under the slot lock from the first write: on SQLite the spool insert takes
  3137. # the write lock, which an AMS update holding the slot lock would wait for.
  3138. async with get_ams_assignment_lock(req.printer_id):
  3139. spool = await create_spool_from_tray(db, tray)
  3140. await auto_assign_spool(
  3141. req.printer_id,
  3142. req.ams_id,
  3143. req.tray_id,
  3144. spool,
  3145. printer_manager,
  3146. db,
  3147. tray_info_idx=tray.get("tray_info_idx", ""),
  3148. )
  3149. await db.commit()
  3150. await ws_manager.broadcast({"type": "inventory_changed"})
  3151. await ws_manager.broadcast(
  3152. {
  3153. "type": "spool_auto_assigned",
  3154. "printer_id": req.printer_id,
  3155. "ams_id": req.ams_id,
  3156. "tray_id": req.tray_id,
  3157. "spool_id": spool.id,
  3158. }
  3159. )
  3160. # populate_existing because `spool` is the same identity-mapped instance
  3161. # create_spool_from_tray built: it pre-initialises `supplier_links` to []
  3162. # so the flush can't lazy-load it, and SQLAlchemy will not overwrite an
  3163. # already-loaded collection on a plain re-select — the inherited
  3164. # assignments (#2988) would be in the table but missing from the response.
  3165. result = await db.execute(
  3166. select(Spool)
  3167. .options(*spool_response_loads())
  3168. .where(Spool.id == spool.id)
  3169. .execution_options(populate_existing=True)
  3170. )
  3171. return result.scalar_one()