inventory.py 122 KB

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