inventory.py 99 KB

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