inventory.py 106 KB

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