inventory.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974
  1. import json
  2. import logging
  3. import httpx
  4. from fastapi import APIRouter, Depends, HTTPException
  5. from fastapi.responses import StreamingResponse
  6. from pydantic import BaseModel, Field, field_validator
  7. from sqlalchemy import delete, func, select
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from sqlalchemy.orm import selectinload
  10. from backend.app.core.auth import (
  11. RequireAnyPermissionIfAuthEnabled,
  12. RequirePermissionIfAuthEnabled,
  13. require_auth_if_enabled,
  14. )
  15. from backend.app.core.catalog_defaults import DEFAULT_COLOR_CATALOG, DEFAULT_SPOOL_CATALOG
  16. from backend.app.core.database import get_db
  17. from backend.app.core.permissions import Permission
  18. from backend.app.core.websocket import ws_manager
  19. from backend.app.models.ams_label import AmsLabel
  20. from backend.app.models.color_catalog import ColorCatalogEntry
  21. from backend.app.models.spool import Spool
  22. from backend.app.models.spool_assignment import SpoolAssignment
  23. from backend.app.models.spool_catalog import SpoolCatalogEntry
  24. from backend.app.models.spool_k_profile import SpoolKProfile
  25. from backend.app.models.user import User
  26. from backend.app.schemas.spool import (
  27. SpoolAssignmentCreate,
  28. SpoolAssignmentResponse,
  29. SpoolBulkCreate,
  30. SpoolCreate,
  31. SpoolKProfileBase,
  32. SpoolKProfileResponse,
  33. SpoolResponse,
  34. SpoolUpdate,
  35. normalize_effect_type,
  36. normalize_extra_colors,
  37. )
  38. from backend.app.schemas.spool_usage import SpoolUsageHistoryResponse
  39. from backend.app.utils.filament_ids import (
  40. GENERIC_FILAMENT_IDS,
  41. MATERIAL_TEMPS,
  42. filament_id_to_setting_id,
  43. normalize_slicer_filament,
  44. )
  45. from backend.app.utils.tag_normalization import normalize_tag_uid, normalize_tray_uuid
  46. logger = logging.getLogger(__name__)
  47. _GENERIC_ID_VALUES = set(GENERIC_FILAMENT_IDS.values())
  48. router = APIRouter(prefix="/inventory", tags=["inventory"])
  49. # FilamentColors.xyz API
  50. FILAMENT_COLORS_API = "https://filamentcolors.xyz/api"
  51. # Generic Bambu filament IDs by material — fallback when no specific
  52. # preset is resolvable. Keep aligned with the inline table in
  53. # apply_spool_to_slot_via_mqtt below; both paths must produce the same
  54. # value for a given material.
  55. _GENERIC_FILAMENT_IDS: dict[str, str] = {
  56. "PLA": "GFL99",
  57. "PETG": "GFG99",
  58. "ABS": "GFB99",
  59. "ASA": "GFB98",
  60. "PC": "GFC99",
  61. "PA": "GFN99",
  62. "NYLON": "GFN99",
  63. "TPU": "GFU99",
  64. "PVA": "GFS99",
  65. "HIPS": "GFS98",
  66. "PLA-CF": "GFL98",
  67. "PETG-CF": "GFG98",
  68. "PA-CF": "GFN98",
  69. "PETG HF": "GFG96",
  70. }
  71. async def apply_spool_to_slot_via_mqtt(
  72. *,
  73. db: AsyncSession,
  74. current_user: User | None,
  75. spool: Spool,
  76. printer_id: int,
  77. ams_id: int,
  78. tray_id: int,
  79. current_tray_info_idx: str = "",
  80. current_tray_type: str = "",
  81. ) -> bool:
  82. """Publish ams_filament_setting + extrusion_cali_sel for a spool on a slot.
  83. Shared by `assign_spool` (initial assign for a loaded slot) and
  84. `on_ams_change` (re-fire when a SpoolBuddy-pre-assigned slot transitions
  85. empty → loaded). Returns True when MQTT commands were published, False if
  86. no client was available or setup failed mid-way.
  87. `current_tray_info_idx` / `current_tray_type` describe the live tray state
  88. used as fallback hints when the spool's slicer_filament can't be resolved.
  89. Caller should not pass these for the empty-slot re-fire path (they'll be
  90. the freshly-loaded values, which is the intended fallback).
  91. """
  92. from backend.app.services.printer_manager import printer_manager
  93. client = printer_manager.get_client(printer_id)
  94. if client is None:
  95. return False
  96. state = printer_manager.get_status(printer_id)
  97. tray_type = spool.material
  98. tray_sub_brands = (
  99. f"{spool.brand} {spool.material} {spool.subtype}".strip()
  100. if spool.brand
  101. else f"{spool.material} {spool.subtype}"
  102. if spool.subtype
  103. else spool.material
  104. )
  105. tray_color = spool.rgba or "FFFFFFFF"
  106. _generic_id_values = set(_GENERIC_FILAMENT_IDS.values())
  107. tray_info_idx = ""
  108. setting_id = ""
  109. sf = spool.slicer_filament or ""
  110. if sf:
  111. base_sf = sf.split("_")[0] if "_" in sf else sf
  112. if base_sf.startswith("GFS") or base_sf.startswith("PFUS"):
  113. setting_id = base_sf
  114. try:
  115. from backend.app.api.routes.cloud import build_authenticated_cloud
  116. cloud = await build_authenticated_cloud(db, current_user)
  117. if cloud is not None and cloud.is_authenticated:
  118. try:
  119. detail = await cloud.get_setting_detail(base_sf)
  120. if detail.get("filament_id"):
  121. tray_info_idx = detail["filament_id"]
  122. cloud_name = detail.get("name", "")
  123. if cloud_name:
  124. tray_sub_brands = cloud_name.replace(r"@.*$", "").split("@")[0].strip()
  125. elif detail.get("base_id"):
  126. bid = detail["base_id"].split("_")[0]
  127. if bid.startswith("GFS") and len(bid) >= 5:
  128. tray_info_idx = f"GF{bid[3:]}"
  129. else:
  130. tray_info_idx = bid
  131. finally:
  132. await cloud.close()
  133. elif cloud is not None:
  134. await cloud.close()
  135. except Exception as e:
  136. logger.warning("Spool assign: cloud lookup failed for %r: %s", sf, e)
  137. if not tray_info_idx:
  138. tray_info_idx, setting_id = normalize_slicer_filament(sf)
  139. elif base_sf.startswith("GF"):
  140. tray_info_idx, setting_id = normalize_slicer_filament(sf)
  141. else:
  142. try:
  143. local_id = int(sf)
  144. from backend.app.models.local_preset import LocalPreset as LP
  145. lp_result = await db.execute(select(LP).where(LP.id == local_id, LP.preset_type == "filament"))
  146. lp = lp_result.scalar_one_or_none()
  147. if lp:
  148. # Local preset's setting JSON carries the printer-recognized
  149. # filament_id (e.g. "P4d64437") — use that directly so the
  150. # slicer can resolve the specific preset. Falls through to
  151. # generic material id only when the JSON doesn't carry one.
  152. lp_filament_id = ""
  153. if lp.setting:
  154. try:
  155. setting_data = json.loads(lp.setting)
  156. raw_fid = setting_data.get("filament_id")
  157. if isinstance(raw_fid, str) and raw_fid:
  158. lp_filament_id = raw_fid
  159. except (json.JSONDecodeError, AttributeError):
  160. pass
  161. if lp_filament_id:
  162. tray_info_idx = lp_filament_id
  163. setting_id = filament_id_to_setting_id(lp_filament_id)
  164. else:
  165. mat = (spool.material or lp.filament_type or "").upper().strip()
  166. tray_info_idx = (
  167. _GENERIC_FILAMENT_IDS.get(mat)
  168. or _GENERIC_FILAMENT_IDS.get(mat.split("-")[0].split(" ")[0])
  169. or ""
  170. )
  171. if lp.name:
  172. tray_sub_brands = lp.name.split("@")[0].strip()
  173. except (ValueError, TypeError):
  174. tray_info_idx, setting_id = normalize_slicer_filament(sf)
  175. if tray_info_idx and spool.slicer_filament_name:
  176. from backend.app.api.routes.cloud import _BUILTIN_FILAMENT_NAMES
  177. expected_name = _BUILTIN_FILAMENT_NAMES.get(tray_info_idx, "")
  178. if expected_name and expected_name != spool.slicer_filament_name:
  179. for fid, fname in _BUILTIN_FILAMENT_NAMES.items():
  180. if fname == spool.slicer_filament_name:
  181. tray_info_idx = fid
  182. setting_id = filament_id_to_setting_id(fid)
  183. break
  184. # Defend against tray_info_idx values the slicer cannot resolve. Two
  185. # shapes leak through and must be discarded so the generic-material
  186. # fallback below can rescue the slot:
  187. # 1. Literal material names ("PLA", "PETG-CF") that pass through
  188. # normalize_slicer_filament unchanged when the spool's slicer_filament
  189. # is free-text rather than a real preset ID.
  190. # 2. PFUS-prefix cloud setting_ids — valid as setting_id but rejected
  191. # by the slicer as tray_info_idx (the printer's calibration table
  192. # indexes by filament_id, and a PFUS isn't one). This normally gets
  193. # realigned to a P-prefix local id via printer_kp lookup, but the
  194. # replay path in main.py.on_ams_change passes current_user=None,
  195. # which skips cloud auth and leaves the raw PFUS in tray_info_idx —
  196. # overwriting the correctly-configured slot from the original assign.
  197. # Valid tray_info_idx values: "GF" + letter + digits (Bambu official) or
  198. # "P" followed by hex (user/local presets, NOT "PFUS").
  199. _known_materials = set(MATERIAL_TEMPS.keys()) | set(_GENERIC_FILAMENT_IDS.keys())
  200. if tray_info_idx and (tray_info_idx.upper() in _known_materials or tray_info_idx.startswith("PFUS")):
  201. tray_info_idx = ""
  202. setting_id = ""
  203. if not tray_info_idx:
  204. if (
  205. current_tray_info_idx
  206. and current_tray_info_idx not in _generic_id_values
  207. and not current_tray_info_idx.startswith("PFUS")
  208. and current_tray_info_idx.upper() not in _known_materials
  209. and current_tray_type
  210. and current_tray_type.upper() == tray_type.upper()
  211. ):
  212. tray_info_idx = current_tray_info_idx
  213. elif tray_type:
  214. material = tray_type.upper().strip()
  215. generic = (
  216. _GENERIC_FILAMENT_IDS.get(material)
  217. or _GENERIC_FILAMENT_IDS.get(material.split("-")[0].split(" ")[0])
  218. or ""
  219. )
  220. if generic:
  221. tray_info_idx = generic
  222. # Ensure setting_id is always derivable from tray_info_idx. The local-preset
  223. # path above sets tray_info_idx to a generic ID (e.g. "GFL99") but leaves
  224. # setting_id empty — without this fallback the slicer gets a half-configured
  225. # slot (filament id without setting id) and shows empty fields in the slot
  226. # detail modal.
  227. if tray_info_idx and not setting_id:
  228. setting_id = filament_id_to_setting_id(tray_info_idx)
  229. temp_min, temp_max = MATERIAL_TEMPS.get((spool.material or "").upper(), (200, 240))
  230. if spool.nozzle_temp_min is not None:
  231. temp_min = spool.nozzle_temp_min
  232. if spool.nozzle_temp_max is not None:
  233. temp_max = spool.nozzle_temp_max
  234. nozzle_diameter = "0.4"
  235. if state and state.nozzles:
  236. nd = state.nozzles[0].nozzle_diameter
  237. if nd:
  238. nozzle_diameter = nd
  239. slot_extruder = None
  240. if state and state.ams_extruder_map:
  241. if ams_id == 255:
  242. slot_extruder = 1 - tray_id # ext-L (tray 0) → extruder 1, ext-R (tray 1) → extruder 0
  243. else:
  244. slot_extruder = state.ams_extruder_map.get(str(ams_id))
  245. # Prefer exact extruder match, fall back to extruder-agnostic kp for the
  246. # same nozzle. Hard-skipping on mismatch silently drops valid stored
  247. # profiles when the AMS-extruder mapping has shifted.
  248. exact_kp = None
  249. fallback_kp = None
  250. for kp in spool.k_profiles:
  251. if kp.printer_id != printer_id or kp.nozzle_diameter != nozzle_diameter:
  252. continue
  253. if slot_extruder is not None and kp.extruder is not None and kp.extruder == slot_extruder:
  254. exact_kp = kp
  255. break
  256. if fallback_kp is None:
  257. fallback_kp = kp
  258. matching_kp = exact_kp or fallback_kp
  259. # Resolve the printer-side calibration entry by looking up the cali_idx
  260. # in state.kprofiles. The printer keys its calibration table by
  261. # (filament_id, cali_idx) — for the cali_idx to stick, the slot's
  262. # filament_id must match the kp's. PFUS-prefix cloud user presets are
  263. # rejected by the slicer in tray_info_idx; the printer-reported
  264. # filament_id is typically a P-prefix local preset which is valid.
  265. printer_kp = None
  266. if matching_kp and matching_kp.cali_idx is not None and state and getattr(state, "kprofiles", None):
  267. for pkp in state.kprofiles:
  268. if pkp.slot_id == matching_kp.cali_idx and pkp.nozzle_diameter == nozzle_diameter:
  269. printer_kp = pkp
  270. break
  271. effective_tray_info_idx = tray_info_idx
  272. effective_setting_id = setting_id
  273. if printer_kp and printer_kp.filament_id:
  274. effective_tray_info_idx = printer_kp.filament_id
  275. target_setting_id = (printer_kp.setting_id if printer_kp else None) or (
  276. matching_kp.setting_id if matching_kp else None
  277. )
  278. if target_setting_id:
  279. effective_setting_id = target_setting_id
  280. if effective_tray_info_idx != tray_info_idx or effective_setting_id != setting_id:
  281. logger.info(
  282. "Spool assign: realigning tray_info_idx %r → %r, setting_id %r → %r (source=%s)",
  283. tray_info_idx,
  284. effective_tray_info_idx,
  285. setting_id,
  286. effective_setting_id,
  287. "printer" if printer_kp else "stored",
  288. )
  289. client.ams_set_filament_setting(
  290. ams_id=ams_id,
  291. tray_id=tray_id,
  292. tray_info_idx=effective_tray_info_idx,
  293. tray_type=tray_type,
  294. tray_sub_brands=tray_sub_brands,
  295. tray_color=tray_color,
  296. nozzle_temp_min=temp_min,
  297. nozzle_temp_max=temp_max,
  298. setting_id=effective_setting_id,
  299. )
  300. if matching_kp and matching_kp.cali_idx is not None:
  301. # filament_id for cali_sel must match the preset under which the kp
  302. # was registered. Priority: live printer kp > stored kp.setting_id >
  303. # spool.slicer_filament > realigned tray_info_idx.
  304. if printer_kp and printer_kp.filament_id:
  305. cali_filament_id = printer_kp.filament_id
  306. elif matching_kp.setting_id:
  307. cali_filament_id = normalize_slicer_filament(matching_kp.setting_id)[0] or matching_kp.setting_id
  308. else:
  309. cali_filament_id = spool.slicer_filament or effective_tray_info_idx
  310. client.extrusion_cali_sel(
  311. ams_id=ams_id,
  312. tray_id=tray_id,
  313. cali_idx=matching_kp.cali_idx,
  314. filament_id=cali_filament_id,
  315. nozzle_diameter=nozzle_diameter,
  316. )
  317. else:
  318. # No stored K-profile for this spool — always reset the slot to Default
  319. # K (cali_idx=-1). The live cali_idx on the slot belongs to whatever
  320. # filament was there before, so preserving it would apply the wrong
  321. # filament's calibration to the new spool. Default K is the firmware's
  322. # documented "no specific profile" value (see BambuClient.extrusion_cali_sel
  323. # docstring).
  324. cali_filament_id = spool.slicer_filament or effective_tray_info_idx
  325. client.extrusion_cali_sel(
  326. ams_id=ams_id,
  327. tray_id=tray_id,
  328. cali_idx=-1,
  329. filament_id=cali_filament_id,
  330. nozzle_diameter=nozzle_diameter,
  331. )
  332. logger.info(
  333. "No stored K-profile for spool %d — reset slot to Default K (cali_idx=-1)",
  334. spool.id,
  335. )
  336. # Persist slot preset mapping for UI display (preset_name on hover card).
  337. try:
  338. from backend.app.models.slot_preset import SlotPresetMapping
  339. preset_name = spool.slicer_filament_name or tray_sub_brands or tray_type
  340. preset_source = "cloud"
  341. if sf:
  342. base_sf_mapping = sf.split("_")[0] if "_" in sf else sf
  343. try:
  344. int(base_sf_mapping)
  345. preset_id_to_save = f"local_{base_sf_mapping}"
  346. preset_source = "local"
  347. except (ValueError, TypeError):
  348. preset_id_to_save = filament_id_to_setting_id(tray_info_idx) if tray_info_idx else setting_id
  349. else:
  350. preset_id_to_save = filament_id_to_setting_id(tray_info_idx) if tray_info_idx else ""
  351. if preset_id_to_save:
  352. existing_mapping = await db.execute(
  353. select(SlotPresetMapping).where(
  354. SlotPresetMapping.printer_id == printer_id,
  355. SlotPresetMapping.ams_id == ams_id,
  356. SlotPresetMapping.tray_id == tray_id,
  357. )
  358. )
  359. mapping = existing_mapping.scalar_one_or_none()
  360. if mapping:
  361. mapping.preset_id = preset_id_to_save
  362. mapping.preset_name = preset_name
  363. mapping.preset_source = preset_source
  364. else:
  365. mapping = SlotPresetMapping(
  366. printer_id=printer_id,
  367. ams_id=ams_id,
  368. tray_id=tray_id,
  369. preset_id=preset_id_to_save,
  370. preset_name=preset_name,
  371. preset_source=preset_source,
  372. )
  373. db.add(mapping)
  374. await db.commit()
  375. except Exception as e:
  376. logger.warning("Failed to save slot preset mapping for spool %d: %s", spool.id, e)
  377. logger.info(
  378. "Auto-configured AMS slot ams=%d tray=%d for spool %d on printer %d",
  379. ams_id,
  380. tray_id,
  381. spool.id,
  382. printer_id,
  383. )
  384. return True
  385. # ── Spool Catalog Schemas ──────────────────────────────────────────────────
  386. class CatalogEntryResponse(BaseModel):
  387. id: int
  388. name: str
  389. weight: int
  390. is_default: bool
  391. class Config:
  392. from_attributes = True
  393. class CatalogEntryCreate(BaseModel):
  394. name: str
  395. weight: int
  396. class CatalogEntryUpdate(BaseModel):
  397. name: str
  398. weight: int
  399. class BulkDeleteIdsRequest(BaseModel):
  400. ids: list[int]
  401. # ── Color Catalog Schemas ──────────────────────────────────────────────────
  402. class ColorEntryResponse(BaseModel):
  403. id: int
  404. manufacturer: str
  405. color_name: str
  406. hex_color: str
  407. material: str | None
  408. is_default: bool
  409. extra_colors: str | None = None
  410. effect_type: str | None = None
  411. class Config:
  412. from_attributes = True
  413. _HEX_COLOR_PATTERN = r"^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$"
  414. class ColorEntryCreate(BaseModel):
  415. manufacturer: str
  416. color_name: str
  417. hex_color: str = Field(..., pattern=_HEX_COLOR_PATTERN)
  418. material: str | None = None
  419. extra_colors: str | None = None
  420. effect_type: str | None = None
  421. @field_validator("extra_colors")
  422. @classmethod
  423. def _validate_extra_colors(cls, v: str | None) -> str | None:
  424. return normalize_extra_colors(v)
  425. @field_validator("effect_type")
  426. @classmethod
  427. def _validate_effect_type(cls, v: str | None) -> str | None:
  428. return normalize_effect_type(v)
  429. class ColorEntryUpdate(BaseModel):
  430. manufacturer: str
  431. color_name: str
  432. hex_color: str = Field(..., pattern=_HEX_COLOR_PATTERN)
  433. material: str | None = None
  434. extra_colors: str | None = None
  435. effect_type: str | None = None
  436. @field_validator("extra_colors")
  437. @classmethod
  438. def _validate_extra_colors(cls, v: str | None) -> str | None:
  439. return normalize_extra_colors(v)
  440. @field_validator("effect_type")
  441. @classmethod
  442. def _validate_effect_type(cls, v: str | None) -> str | None:
  443. return normalize_effect_type(v)
  444. class ColorLookupResult(BaseModel):
  445. found: bool
  446. hex_color: str | None = None
  447. material: str | None = None
  448. # ── Spool Catalog CRUD ─────────────────────────────────────────────────────
  449. @router.get("/catalog", response_model=list[CatalogEntryResponse])
  450. async def get_spool_catalog(
  451. db: AsyncSession = Depends(get_db),
  452. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  453. ):
  454. """Get all spool catalog entries."""
  455. result = await db.execute(select(SpoolCatalogEntry).order_by(SpoolCatalogEntry.name))
  456. return list(result.scalars().all())
  457. @router.post("/catalog", response_model=CatalogEntryResponse)
  458. async def add_catalog_entry(
  459. entry: CatalogEntryCreate,
  460. db: AsyncSession = Depends(get_db),
  461. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  462. ):
  463. """Add a new spool catalog entry."""
  464. row = SpoolCatalogEntry(name=entry.name, weight=entry.weight, is_default=False)
  465. db.add(row)
  466. await db.commit()
  467. await db.refresh(row)
  468. return row
  469. @router.put("/catalog/{entry_id}", response_model=CatalogEntryResponse)
  470. async def update_catalog_entry(
  471. entry_id: int,
  472. entry: CatalogEntryUpdate,
  473. db: AsyncSession = Depends(get_db),
  474. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  475. ):
  476. """Update a spool catalog entry."""
  477. result = await db.execute(select(SpoolCatalogEntry).where(SpoolCatalogEntry.id == entry_id))
  478. row = result.scalar_one_or_none()
  479. if not row:
  480. raise HTTPException(404, "Entry not found")
  481. row.name = entry.name
  482. row.weight = entry.weight
  483. await db.commit()
  484. await db.refresh(row)
  485. return row
  486. @router.delete("/catalog/{entry_id}")
  487. async def delete_catalog_entry(
  488. entry_id: int,
  489. db: AsyncSession = Depends(get_db),
  490. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  491. ):
  492. """Delete a spool catalog entry."""
  493. result = await db.execute(select(SpoolCatalogEntry).where(SpoolCatalogEntry.id == entry_id))
  494. row = result.scalar_one_or_none()
  495. if not row:
  496. raise HTTPException(404, "Entry not found")
  497. await db.delete(row)
  498. await db.commit()
  499. return {"status": "deleted"}
  500. @router.post("/catalog/bulk-delete")
  501. async def bulk_delete_catalog_entries(
  502. data: BulkDeleteIdsRequest,
  503. db: AsyncSession = Depends(get_db),
  504. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  505. ):
  506. """Delete multiple spool catalog entries by ID."""
  507. if not data.ids:
  508. return {"deleted": 0}
  509. result = await db.execute(select(SpoolCatalogEntry).where(SpoolCatalogEntry.id.in_(data.ids)))
  510. rows = result.scalars().all()
  511. for row in rows:
  512. await db.delete(row)
  513. await db.commit()
  514. return {"deleted": len(rows)}
  515. @router.post("/catalog/reset")
  516. async def reset_spool_catalog(
  517. db: AsyncSession = Depends(get_db),
  518. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  519. ):
  520. """Reset spool catalog to defaults."""
  521. await db.execute(select(SpoolCatalogEntry)) # ensure table loaded
  522. # Delete all
  523. result = await db.execute(select(SpoolCatalogEntry))
  524. for row in result.scalars().all():
  525. await db.delete(row)
  526. # Re-seed defaults
  527. for name, weight in DEFAULT_SPOOL_CATALOG:
  528. db.add(SpoolCatalogEntry(name=name, weight=weight, is_default=True))
  529. await db.commit()
  530. return {"status": "reset"}
  531. # ── Color Catalog CRUD ─────────────────────────────────────────────────────
  532. @router.get("/colors", response_model=list[ColorEntryResponse])
  533. async def get_color_catalog(
  534. db: AsyncSession = Depends(get_db),
  535. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  536. ):
  537. """Get all color catalog entries."""
  538. result = await db.execute(
  539. select(ColorCatalogEntry).order_by(
  540. ColorCatalogEntry.manufacturer, ColorCatalogEntry.material, ColorCatalogEntry.color_name
  541. )
  542. )
  543. return list(result.scalars().all())
  544. @router.get("/colors/map")
  545. async def get_color_name_map(
  546. db: AsyncSession = Depends(get_db),
  547. _: User | None = Depends(require_auth_if_enabled),
  548. ):
  549. """Compact {hex: name} map for frontend color-name resolution.
  550. Not gated on INVENTORY_READ — every page that renders a spool color needs
  551. this, including read-only views available to users without inventory access.
  552. Normalized to lowercase 6-char hex without '#'. When multiple catalog entries
  553. share the same hex (different materials or manufacturers), Bambu Lab wins,
  554. then default entries, then the first encountered.
  555. """
  556. result = await db.execute(
  557. select(
  558. ColorCatalogEntry.hex_color,
  559. ColorCatalogEntry.color_name,
  560. ColorCatalogEntry.manufacturer,
  561. ColorCatalogEntry.is_default,
  562. )
  563. )
  564. mapping: dict[str, tuple[str, int]] = {} # hex → (name, priority); higher priority wins
  565. for hex_color, color_name, manufacturer, is_default in result.all():
  566. if not hex_color or not color_name:
  567. continue
  568. key = hex_color.lstrip("#").lower()[:6]
  569. if len(key) != 6:
  570. continue
  571. priority = 0
  572. if manufacturer and manufacturer.strip().lower() == "bambu lab":
  573. priority += 2
  574. if is_default:
  575. priority += 1
  576. existing = mapping.get(key)
  577. if existing is None or priority > existing[1]:
  578. mapping[key] = (color_name, priority)
  579. return {"colors": {k: v[0] for k, v in mapping.items()}}
  580. @router.post("/colors", response_model=ColorEntryResponse)
  581. async def add_color_entry(
  582. entry: ColorEntryCreate,
  583. db: AsyncSession = Depends(get_db),
  584. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  585. ):
  586. """Add a new color catalog entry."""
  587. row = ColorCatalogEntry(
  588. manufacturer=entry.manufacturer,
  589. color_name=entry.color_name,
  590. hex_color=entry.hex_color,
  591. material=entry.material,
  592. is_default=False,
  593. extra_colors=entry.extra_colors,
  594. effect_type=entry.effect_type,
  595. )
  596. db.add(row)
  597. await db.commit()
  598. await db.refresh(row)
  599. return row
  600. @router.put("/colors/{entry_id}", response_model=ColorEntryResponse)
  601. async def update_color_entry(
  602. entry_id: int,
  603. entry: ColorEntryUpdate,
  604. db: AsyncSession = Depends(get_db),
  605. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  606. ):
  607. """Update a color catalog entry."""
  608. result = await db.execute(select(ColorCatalogEntry).where(ColorCatalogEntry.id == entry_id))
  609. row = result.scalar_one_or_none()
  610. if not row:
  611. raise HTTPException(404, "Entry not found")
  612. row.manufacturer = entry.manufacturer
  613. row.color_name = entry.color_name
  614. row.hex_color = entry.hex_color
  615. row.material = entry.material
  616. row.extra_colors = entry.extra_colors
  617. row.effect_type = entry.effect_type
  618. await db.commit()
  619. await db.refresh(row)
  620. return row
  621. @router.delete("/colors/{entry_id}")
  622. async def delete_color_entry(
  623. entry_id: int,
  624. db: AsyncSession = Depends(get_db),
  625. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  626. ):
  627. """Delete a color catalog entry."""
  628. result = await db.execute(select(ColorCatalogEntry).where(ColorCatalogEntry.id == entry_id))
  629. row = result.scalar_one_or_none()
  630. if not row:
  631. raise HTTPException(404, "Entry not found")
  632. await db.delete(row)
  633. await db.commit()
  634. return {"status": "deleted"}
  635. @router.post("/colors/bulk-delete")
  636. async def bulk_delete_color_entries(
  637. data: BulkDeleteIdsRequest,
  638. db: AsyncSession = Depends(get_db),
  639. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  640. ):
  641. """Delete multiple color catalog entries by ID."""
  642. if not data.ids:
  643. return {"deleted": 0}
  644. result = await db.execute(select(ColorCatalogEntry).where(ColorCatalogEntry.id.in_(data.ids)))
  645. rows = result.scalars().all()
  646. for row in rows:
  647. await db.delete(row)
  648. await db.commit()
  649. return {"deleted": len(rows)}
  650. @router.post("/colors/reset")
  651. async def reset_color_catalog(
  652. db: AsyncSession = Depends(get_db),
  653. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  654. ):
  655. """Reset color catalog to defaults."""
  656. result = await db.execute(select(ColorCatalogEntry))
  657. for row in result.scalars().all():
  658. await db.delete(row)
  659. for manufacturer, color_name, hex_color, material in DEFAULT_COLOR_CATALOG:
  660. db.add(
  661. ColorCatalogEntry(
  662. manufacturer=manufacturer,
  663. color_name=color_name,
  664. hex_color=hex_color,
  665. material=material,
  666. is_default=True,
  667. )
  668. )
  669. await db.commit()
  670. return {"status": "reset"}
  671. @router.get("/colors/lookup", response_model=ColorLookupResult)
  672. async def lookup_color(
  673. manufacturer: str,
  674. color_name: str,
  675. material: str | None = None,
  676. db: AsyncSession = Depends(get_db),
  677. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  678. ):
  679. """Look up a color by manufacturer and color name."""
  680. query = select(ColorCatalogEntry).where(
  681. ColorCatalogEntry.manufacturer == manufacturer,
  682. ColorCatalogEntry.color_name == color_name,
  683. )
  684. if material:
  685. query = query.where(ColorCatalogEntry.material == material)
  686. query = query.limit(1)
  687. result = await db.execute(query)
  688. row = result.scalar_one_or_none()
  689. if row:
  690. return ColorLookupResult(found=True, hex_color=row.hex_color, material=row.material)
  691. return ColorLookupResult(found=False)
  692. @router.get("/colors/search", response_model=list[ColorEntryResponse])
  693. async def search_colors(
  694. manufacturer: str | None = None,
  695. material: str | None = None,
  696. db: AsyncSession = Depends(get_db),
  697. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  698. ):
  699. """Search colors by manufacturer and/or material."""
  700. query = select(ColorCatalogEntry)
  701. if manufacturer:
  702. query = query.where(func.lower(ColorCatalogEntry.manufacturer).contains(manufacturer.lower()))
  703. if material:
  704. query = query.where(func.lower(ColorCatalogEntry.material).contains(material.lower()))
  705. query = query.order_by(ColorCatalogEntry.manufacturer, ColorCatalogEntry.color_name).limit(100)
  706. result = await db.execute(query)
  707. return list(result.scalars().all())
  708. @router.post("/colors/sync")
  709. async def sync_from_filamentcolors(
  710. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  711. ):
  712. """Sync colors from FilamentColors.xyz API with progress streaming."""
  713. async def generate():
  714. from backend.app.core.database import async_session
  715. added = 0
  716. skipped = 0
  717. total_fetched = 0
  718. total_available = 0
  719. try:
  720. async with httpx.AsyncClient(timeout=120.0) as client:
  721. page = 1
  722. while True:
  723. response = await client.get(
  724. f"{FILAMENT_COLORS_API}/swatch/",
  725. params={"page": page},
  726. )
  727. response.raise_for_status()
  728. data = response.json()
  729. total_available = data.get("count", total_available)
  730. results = data.get("results", [])
  731. if not results:
  732. break
  733. async with async_session() as db:
  734. for swatch in results:
  735. total_fetched += 1
  736. manufacturer_data = swatch.get("manufacturer")
  737. manufacturer_name = (
  738. manufacturer_data.get("name", "") if isinstance(manufacturer_data, dict) else ""
  739. )
  740. filament_type_data = swatch.get("filament_type")
  741. mat = filament_type_data.get("name", "") if isinstance(filament_type_data, dict) else None
  742. color_name_val = swatch.get("color_name", "")
  743. hex_color_val = swatch.get("hex_color", "")
  744. if not manufacturer_name or not color_name_val or not hex_color_val:
  745. skipped += 1
  746. continue
  747. if not hex_color_val.startswith("#"):
  748. hex_color_val = f"#{hex_color_val}"
  749. # Check if entry already exists
  750. existing = await db.execute(
  751. select(ColorCatalogEntry)
  752. .where(
  753. ColorCatalogEntry.manufacturer == manufacturer_name,
  754. ColorCatalogEntry.color_name == color_name_val,
  755. ColorCatalogEntry.material == mat,
  756. )
  757. .limit(1)
  758. )
  759. if existing.scalar_one_or_none():
  760. skipped += 1
  761. else:
  762. db.add(
  763. ColorCatalogEntry(
  764. manufacturer=manufacturer_name,
  765. color_name=color_name_val,
  766. hex_color=hex_color_val.upper(),
  767. material=mat,
  768. is_default=False,
  769. )
  770. )
  771. added += 1
  772. await db.commit()
  773. progress = {
  774. "type": "progress",
  775. "added": added,
  776. "skipped": skipped,
  777. "total_fetched": total_fetched,
  778. "total_available": total_available,
  779. }
  780. yield f"data: {json.dumps(progress)}\n\n"
  781. if not data.get("next") or total_fetched >= total_available:
  782. break
  783. page += 1
  784. result = {
  785. "type": "complete",
  786. "added": added,
  787. "skipped": skipped,
  788. "total_fetched": total_fetched,
  789. "total_available": total_available,
  790. }
  791. yield f"data: {json.dumps(result)}\n\n"
  792. except httpx.HTTPError as e:
  793. logger.error("HTTP error syncing from FilamentColors.xyz: %s", e)
  794. yield f"data: {json.dumps({'type': 'error', 'error': str(e)})}\n\n"
  795. except Exception as e:
  796. logger.error("Error syncing from FilamentColors.xyz: %s", e)
  797. yield f"data: {json.dumps({'type': 'error', 'error': 'Unexpected error during sync'})}\n\n"
  798. return StreamingResponse(generate(), media_type="text/event-stream")
  799. # ── Spool CRUD ───────────────────────────────────────────────────────────────
  800. @router.get("/spools", response_model=list[SpoolResponse])
  801. async def list_spools(
  802. include_archived: bool = False,
  803. db: AsyncSession = Depends(get_db),
  804. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  805. ):
  806. """List all spools, excluding archived by default."""
  807. query = select(Spool).options(selectinload(Spool.k_profiles))
  808. if not include_archived:
  809. query = query.where(Spool.archived_at.is_(None))
  810. query = query.order_by(Spool.material, Spool.brand, Spool.color_name)
  811. result = await db.execute(query)
  812. return list(result.scalars().all())
  813. @router.get("/spools/{spool_id}", response_model=SpoolResponse)
  814. async def get_spool(
  815. spool_id: int,
  816. db: AsyncSession = Depends(get_db),
  817. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  818. ):
  819. """Get a single spool with k_profiles."""
  820. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id == spool_id))
  821. spool = result.scalar_one_or_none()
  822. if not spool:
  823. raise HTTPException(404, "Spool not found")
  824. return spool
  825. @router.post("/spools", response_model=SpoolResponse)
  826. async def create_spool(
  827. spool_data: SpoolCreate,
  828. db: AsyncSession = Depends(get_db),
  829. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  830. ):
  831. """Create a new spool."""
  832. spool = Spool(**spool_data.model_dump())
  833. db.add(spool)
  834. await db.commit()
  835. await db.refresh(spool)
  836. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id == spool.id))
  837. await ws_manager.broadcast({"type": "inventory_changed"})
  838. return result.scalar_one()
  839. @router.post("/spools/bulk", response_model=list[SpoolResponse])
  840. async def bulk_create_spools(
  841. data: SpoolBulkCreate,
  842. db: AsyncSession = Depends(get_db),
  843. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  844. ):
  845. """Create multiple identical spools."""
  846. spools = []
  847. for _ in range(data.quantity):
  848. spool = Spool(**data.spool.model_dump())
  849. db.add(spool)
  850. spools.append(spool)
  851. await db.commit()
  852. ids = [s.id for s in spools]
  853. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id.in_(ids)))
  854. await ws_manager.broadcast({"type": "inventory_changed"})
  855. return list(result.scalars().all())
  856. @router.patch("/spools/{spool_id}", response_model=SpoolResponse)
  857. async def update_spool(
  858. spool_id: int,
  859. spool_data: SpoolUpdate,
  860. db: AsyncSession = Depends(get_db),
  861. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  862. ):
  863. """Update a spool."""
  864. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  865. spool = result.scalar_one_or_none()
  866. if not spool:
  867. raise HTTPException(404, "Spool not found")
  868. update_data = spool_data.model_dump(exclude_unset=True)
  869. # Auto-lock weight when user explicitly sets weight_used
  870. if "weight_used" in update_data and "weight_locked" not in update_data:
  871. update_data["weight_locked"] = True
  872. for field, value in update_data.items():
  873. setattr(spool, field, value)
  874. await db.commit()
  875. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id == spool_id))
  876. await ws_manager.broadcast({"type": "inventory_changed"})
  877. return result.scalar_one()
  878. @router.delete("/spools/{spool_id}")
  879. async def delete_spool(
  880. spool_id: int,
  881. db: AsyncSession = Depends(get_db),
  882. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  883. ):
  884. """Hard delete a spool."""
  885. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  886. spool = result.scalar_one_or_none()
  887. if not spool:
  888. raise HTTPException(404, "Spool not found")
  889. await db.delete(spool)
  890. await db.commit()
  891. await ws_manager.broadcast({"type": "inventory_changed"})
  892. return {"status": "deleted"}
  893. @router.post("/spools/{spool_id}/archive", response_model=SpoolResponse)
  894. async def archive_spool(
  895. spool_id: int,
  896. db: AsyncSession = Depends(get_db),
  897. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  898. ):
  899. """Soft-delete a spool by setting archived_at."""
  900. from datetime import datetime, timezone
  901. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  902. spool = result.scalar_one_or_none()
  903. if not spool:
  904. raise HTTPException(404, "Spool not found")
  905. spool.archived_at = datetime.now(timezone.utc)
  906. await db.commit()
  907. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id == spool_id))
  908. await ws_manager.broadcast({"type": "inventory_changed"})
  909. return result.scalar_one()
  910. @router.post("/spools/{spool_id}/restore", response_model=SpoolResponse)
  911. async def restore_spool(
  912. spool_id: int,
  913. db: AsyncSession = Depends(get_db),
  914. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  915. ):
  916. """Restore an archived spool."""
  917. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  918. spool = result.scalar_one_or_none()
  919. if not spool:
  920. raise HTTPException(404, "Spool not found")
  921. spool.archived_at = None
  922. await db.commit()
  923. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id == spool_id))
  924. await ws_manager.broadcast({"type": "inventory_changed"})
  925. return result.scalar_one()
  926. @router.post("/spools/{spool_id}/reset-usage", response_model=SpoolResponse)
  927. async def reset_spool_usage(
  928. spool_id: int,
  929. db: AsyncSession = Depends(get_db),
  930. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  931. ):
  932. """Zero the displayed "Total Consumed" counter without touching remaining.
  933. Stamps `weight_used_baseline = weight_used` so the Inventory page's
  934. `weight_used - baseline` display reads 0, while `label_weight -
  935. weight_used` (remaining) is unchanged. weight_locked is also left
  936. alone — the spool keeps receiving AMS auto-sync updates. Matches
  937. Spoolman's split between used_weight and remaining_weight (#1390).
  938. """
  939. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  940. spool = result.scalar_one_or_none()
  941. if not spool:
  942. raise HTTPException(404, "Spool not found")
  943. spool.weight_used_baseline = spool.weight_used or 0
  944. await db.commit()
  945. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id == spool_id))
  946. await ws_manager.broadcast({"type": "inventory_changed"})
  947. return result.scalar_one()
  948. @router.post("/spools/reset-usage-bulk")
  949. async def bulk_reset_spool_usage(
  950. payload: dict,
  951. db: AsyncSession = Depends(get_db),
  952. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  953. ):
  954. """Bulk-stamp baseline = weight_used across the given spool IDs.
  955. Caller passes an explicit list of IDs — no "reset all" shortcut, since
  956. a typo on a wildcard would wipe the entire inventory's tracking.
  957. Same semantics as the per-spool endpoint: remaining is preserved,
  958. weight_locked is left alone.
  959. """
  960. spool_ids = payload.get("spool_ids")
  961. if not isinstance(spool_ids, list) or not spool_ids:
  962. raise HTTPException(400, "spool_ids must be a non-empty list")
  963. if not all(isinstance(sid, int) for sid in spool_ids):
  964. raise HTTPException(400, "spool_ids must contain integers")
  965. result = await db.execute(select(Spool).where(Spool.id.in_(spool_ids)))
  966. spools = list(result.scalars().all())
  967. for spool in spools:
  968. spool.weight_used_baseline = spool.weight_used or 0
  969. await db.commit()
  970. await ws_manager.broadcast({"type": "inventory_changed"})
  971. return {"reset": len(spools)}
  972. # ── K-Profiles ───────────────────────────────────────────────────────────────
  973. @router.get("/spools/{spool_id}/k-profiles", response_model=list[SpoolKProfileResponse])
  974. async def list_k_profiles(
  975. spool_id: int,
  976. db: AsyncSession = Depends(get_db),
  977. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  978. ):
  979. """List K-profiles for a spool."""
  980. result = await db.execute(select(SpoolKProfile).where(SpoolKProfile.spool_id == spool_id))
  981. return list(result.scalars().all())
  982. @router.put("/spools/{spool_id}/k-profiles", response_model=list[SpoolKProfileResponse])
  983. async def replace_k_profiles(
  984. spool_id: int,
  985. profiles: list[SpoolKProfileBase],
  986. db: AsyncSession = Depends(get_db),
  987. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  988. ):
  989. """Replace all K-profiles for a spool (batch save)."""
  990. # Verify spool exists
  991. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  992. if not result.scalar_one_or_none():
  993. raise HTTPException(404, "Spool not found")
  994. # Delete existing
  995. existing = await db.execute(select(SpoolKProfile).where(SpoolKProfile.spool_id == spool_id))
  996. for old in existing.scalars().all():
  997. await db.delete(old)
  998. # Create new
  999. new_profiles = []
  1000. for p in profiles:
  1001. kp = SpoolKProfile(spool_id=spool_id, **p.model_dump())
  1002. db.add(kp)
  1003. new_profiles.append(kp)
  1004. await db.commit()
  1005. for kp in new_profiles:
  1006. await db.refresh(kp)
  1007. return new_profiles
  1008. # ── Spool Assignments ────────────────────────────────────────────────────────
  1009. @router.get("/assignments", response_model=list[SpoolAssignmentResponse])
  1010. async def list_assignments(
  1011. printer_id: int | None = None,
  1012. db: AsyncSession = Depends(get_db),
  1013. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_VIEW_ASSIGNMENTS),
  1014. ):
  1015. """List spool assignments, optionally filtered by printer."""
  1016. from backend.app.services.printer_manager import printer_manager
  1017. query = select(SpoolAssignment).options(
  1018. selectinload(SpoolAssignment.spool).selectinload(Spool.k_profiles),
  1019. selectinload(SpoolAssignment.printer),
  1020. )
  1021. if printer_id is not None:
  1022. query = query.where(SpoolAssignment.printer_id == printer_id)
  1023. result = await db.execute(query)
  1024. assignments = list(result.scalars().all())
  1025. # Build (printer_id, ams_id) -> ams_serial map from live printer states.
  1026. # Fetch all statuses in one call rather than one get_status() call per printer.
  1027. serial_map: dict[tuple[int, int], str] = {}
  1028. seen_printer_ids: set[int] = {a.printer_id for a in assignments}
  1029. all_statuses = printer_manager.get_all_statuses()
  1030. for pid in seen_printer_ids:
  1031. state = all_statuses.get(pid)
  1032. if state and state.raw_data:
  1033. for ams_unit in state.raw_data.get("ams", []):
  1034. sn = str(ams_unit.get("sn") or ams_unit.get("serial_number") or "")
  1035. if sn:
  1036. try:
  1037. serial_map[(pid, int(ams_unit.get("id", 0)))] = sn
  1038. except (ValueError, TypeError):
  1039. continue
  1040. # Fetch all relevant AMS labels keyed by serial number
  1041. all_serials = set(serial_map.values())
  1042. # Also include synthetic fallback keys for assignments without a known serial
  1043. synthetic_keys: dict[str, tuple[int, int]] = {}
  1044. for a in assignments:
  1045. if (a.printer_id, a.ams_id) not in serial_map:
  1046. synthetic = f"p{a.printer_id}a{a.ams_id}"
  1047. synthetic_keys[synthetic] = (a.printer_id, a.ams_id)
  1048. all_serials.add(synthetic)
  1049. label_by_serial: dict[str, str] = {}
  1050. if all_serials:
  1051. lbl_result = await db.execute(select(AmsLabel).where(AmsLabel.ams_serial_number.in_(all_serials)))
  1052. for lbl in lbl_result.scalars().all():
  1053. label_by_serial[lbl.ams_serial_number] = lbl.label
  1054. # Build response objects, attaching ams_label where available
  1055. responses: list[SpoolAssignmentResponse] = []
  1056. for a in assignments:
  1057. resp = SpoolAssignmentResponse.model_validate(a)
  1058. sn = serial_map.get((a.printer_id, a.ams_id))
  1059. if sn and sn in label_by_serial:
  1060. resp.ams_label = label_by_serial[sn]
  1061. elif not sn:
  1062. synthetic = f"p{a.printer_id}a{a.ams_id}"
  1063. resp.ams_label = label_by_serial.get(synthetic)
  1064. responses.append(resp)
  1065. return responses
  1066. @router.post("/assignments", response_model=SpoolAssignmentResponse)
  1067. async def assign_spool(
  1068. data: SpoolAssignmentCreate,
  1069. db: AsyncSession = Depends(get_db),
  1070. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1071. ):
  1072. """Assign a spool to an AMS slot and auto-configure via MQTT."""
  1073. from backend.app.services.printer_manager import printer_manager
  1074. # 1. Validate spool exists and is not archived
  1075. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id == data.spool_id))
  1076. spool = result.scalar_one_or_none()
  1077. if not spool:
  1078. raise HTTPException(404, "Spool not found")
  1079. if spool.archived_at:
  1080. raise HTTPException(400, "Cannot assign an archived spool")
  1081. # 2. Get current AMS tray state for fingerprint + existing filament ID.
  1082. # tray_state: Bambu firmware reports 11=loaded, 9=empty, 10=spool present
  1083. # but filament not in feeder. Captured here so the empty-slot heuristic
  1084. # below can prefer it over tray_type — a manual "Reset slot" clears
  1085. # tray_type to "" while leaving state at 11 (filament still physically
  1086. # present), which would otherwise mislead the heuristic into the
  1087. # pending-config branch and skip MQTT forever (#1228 follow-up).
  1088. fingerprint_color = None
  1089. fingerprint_type = None
  1090. current_tray_info_idx = ""
  1091. tray_state: int | None = None
  1092. state = printer_manager.get_status(data.printer_id)
  1093. if state and state.raw_data:
  1094. if data.ams_id == 255:
  1095. # External slot: look up tray from vt_tray by global ID
  1096. vt_tray = state.raw_data.get("vt_tray") or []
  1097. ext_id = data.tray_id + 254 # 0→254, 1→255
  1098. for vt in vt_tray:
  1099. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1100. fingerprint_color = vt.get("tray_color", "")
  1101. fingerprint_type = vt.get("tray_type", "")
  1102. current_tray_info_idx = vt.get("tray_info_idx", "")
  1103. raw_state = vt.get("state")
  1104. if isinstance(raw_state, int):
  1105. tray_state = raw_state
  1106. break
  1107. else:
  1108. ams_data = state.raw_data.get("ams", {})
  1109. ams_list = (
  1110. ams_data.get("ams", [])
  1111. if isinstance(ams_data, dict)
  1112. else ams_data
  1113. if isinstance(ams_data, list)
  1114. else []
  1115. )
  1116. tray = _find_tray_in_ams_data(
  1117. ams_list,
  1118. data.ams_id,
  1119. data.tray_id,
  1120. )
  1121. if tray:
  1122. fingerprint_color = tray.get("tray_color", "")
  1123. fingerprint_type = tray.get("tray_type", "")
  1124. current_tray_info_idx = tray.get("tray_info_idx", "")
  1125. raw_state = tray.get("state")
  1126. if isinstance(raw_state, int):
  1127. tray_state = raw_state
  1128. # 3. Upsert assignment (replace if same printer+ams+tray)
  1129. existing = await db.execute(
  1130. select(SpoolAssignment).where(
  1131. SpoolAssignment.printer_id == data.printer_id,
  1132. SpoolAssignment.ams_id == data.ams_id,
  1133. SpoolAssignment.tray_id == data.tray_id,
  1134. )
  1135. )
  1136. old = existing.scalar_one_or_none()
  1137. if old:
  1138. await db.delete(old)
  1139. await db.flush()
  1140. assignment = SpoolAssignment(
  1141. spool_id=data.spool_id,
  1142. printer_id=data.printer_id,
  1143. ams_id=data.ams_id,
  1144. tray_id=data.tray_id,
  1145. fingerprint_color=fingerprint_color,
  1146. fingerprint_type=fingerprint_type,
  1147. )
  1148. db.add(assignment)
  1149. await db.commit()
  1150. await db.refresh(assignment)
  1151. # 4. Auto-configure AMS slot via MQTT.
  1152. #
  1153. # Only suppress the publish when the firmware's *explicit* empty signal
  1154. # (state ∈ {9, 10}) is set — "no spool" / "spool present but no feed".
  1155. # Every other state, including state=3 (the default idle on A1 Mini BMCU /
  1156. # P1S Standard AMS for both loaded and unconfigured slots) and missing
  1157. # state (older firmwares), is treated as the user's assertion that a
  1158. # spool is in the slot and we attempt the MQTT push.
  1159. #
  1160. # The pre-existing "skip when slot looks empty" guard read state=3 +
  1161. # tray_type="" as "empty" and skipped MQTT. On these firmwares that
  1162. # combination is the post-"Reset Slot" state with the spool still
  1163. # physically inserted — there is NO AMS signal that distinguishes it
  1164. # from a truly-empty slot, so the guard created a deadlock: MQTT never
  1165. # fired, the AMS never reported any change (because nothing changed
  1166. # physically), and on_ams_change replay therefore never re-fired the
  1167. # config either. Reporter (#1322 follow-up by @RosdasHH) verified
  1168. # empirically that removing the guard makes the slot configure
  1169. # correctly because Bambu firmware DOES accept the push for a
  1170. # physically-loaded slot, even when tray_type is "" and state is 3.
  1171. #
  1172. # Trade-off for the truly-empty slot case: firmware drops the push
  1173. # silently (per Bambu's documented behavior), the SpoolAssignment row
  1174. # still has empty fingerprint_type because nothing in the assign path
  1175. # updates that column, and on_ams_change at main.py:1031-1054 still
  1176. # fires the deferred config when a spool eventually appears. So the
  1177. # SpoolBuddy weigh-then-assign-before-insert workflow continues to
  1178. # work — just without the optimization of skipping a no-op MQTT call.
  1179. #
  1180. # state ∈ {9, 10} stays as an explicit short-circuit so we don't churn
  1181. # a doomed MQTT push when the firmware has positively confirmed "no
  1182. # spool" — and to keep the on_ams_change replay path as the single
  1183. # source of truth for those slots.
  1184. slot_is_definitely_empty = tray_state == 9 or tray_state == 10
  1185. configured = False
  1186. if not slot_is_definitely_empty:
  1187. try:
  1188. configured = await apply_spool_to_slot_via_mqtt(
  1189. db=db,
  1190. current_user=current_user,
  1191. spool=spool,
  1192. printer_id=data.printer_id,
  1193. ams_id=data.ams_id,
  1194. tray_id=data.tray_id,
  1195. current_tray_info_idx=current_tray_info_idx,
  1196. current_tray_type=fingerprint_type or "",
  1197. )
  1198. except Exception as e:
  1199. logger.warning("MQTT auto-configure failed for spool %d: %s", spool.id, e)
  1200. # pending_config is the "config not landed yet" UI marker. True when the
  1201. # firmware said empty, OR when MQTT couldn't actually publish (printer
  1202. # offline, no client, transient failure). on_ams_change replay re-fires
  1203. # the config in either case once the AMS reports a non-empty fingerprint.
  1204. pending_config = slot_is_definitely_empty or not configured
  1205. # Return assignment with spool data
  1206. result = await db.execute(
  1207. select(SpoolAssignment)
  1208. .options(
  1209. selectinload(SpoolAssignment.spool).selectinload(Spool.k_profiles),
  1210. selectinload(SpoolAssignment.printer),
  1211. )
  1212. .where(SpoolAssignment.id == assignment.id)
  1213. )
  1214. resp = result.scalar_one()
  1215. response = SpoolAssignmentResponse.model_validate(resp)
  1216. response.configured = configured
  1217. response.pending_config = pending_config
  1218. if pending_config:
  1219. logger.info(
  1220. "Pre-configured assignment: spool %d → printer %d AMS%d-T%d (slot empty, will configure on insert)",
  1221. spool.id,
  1222. data.printer_id,
  1223. data.ams_id,
  1224. data.tray_id,
  1225. )
  1226. await ws_manager.broadcast(
  1227. {
  1228. "type": "spool_assignment_changed",
  1229. "printer_id": data.printer_id,
  1230. "ams_id": data.ams_id,
  1231. "tray_id": data.tray_id,
  1232. }
  1233. )
  1234. return response
  1235. @router.delete("/assignments/{printer_id}/{ams_id}/{tray_id}")
  1236. async def unassign_spool(
  1237. printer_id: int,
  1238. ams_id: int,
  1239. tray_id: int,
  1240. db: AsyncSession = Depends(get_db),
  1241. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1242. ):
  1243. """Unassign a spool from an AMS slot."""
  1244. result = await db.execute(
  1245. select(SpoolAssignment).where(
  1246. SpoolAssignment.printer_id == printer_id,
  1247. SpoolAssignment.ams_id == ams_id,
  1248. SpoolAssignment.tray_id == tray_id,
  1249. )
  1250. )
  1251. assignment = result.scalar_one_or_none()
  1252. if not assignment:
  1253. raise HTTPException(404, "Assignment not found")
  1254. await db.delete(assignment)
  1255. await db.commit()
  1256. await ws_manager.broadcast(
  1257. {
  1258. "type": "spool_assignment_changed",
  1259. "printer_id": printer_id,
  1260. "ams_id": ams_id,
  1261. "tray_id": tray_id,
  1262. }
  1263. )
  1264. return {"status": "deleted"}
  1265. # ── Tag Linking ───────────────────────────────────────────────────────────────
  1266. class LinkTagRequest(BaseModel):
  1267. tag_uid: str | None = None
  1268. tray_uuid: str | None = None
  1269. tag_type: str | None = None
  1270. data_origin: str | None = "nfc_link"
  1271. def _validate_tag_input(
  1272. raw_value: str | None, normalized_value: str | None, field_name: str, exact_len: int | None = None
  1273. ) -> None:
  1274. if raw_value is None:
  1275. return
  1276. raw = str(raw_value).strip()
  1277. if not raw:
  1278. return
  1279. if normalized_value is None:
  1280. raise HTTPException(422, f"{field_name} must contain hexadecimal characters")
  1281. if len(normalized_value) % 2 != 0:
  1282. raise HTTPException(422, f"{field_name} must have an even number of hex characters")
  1283. if exact_len is not None and len(normalized_value) != exact_len:
  1284. raise HTTPException(422, f"{field_name} must be exactly {exact_len} hex characters")
  1285. @router.patch("/spools/{spool_id}/link-tag", response_model=SpoolResponse)
  1286. async def link_tag_to_spool(
  1287. spool_id: int,
  1288. data: LinkTagRequest,
  1289. db: AsyncSession = Depends(get_db),
  1290. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1291. ):
  1292. """Link an RFID tag_uid/tray_uuid to an existing spool."""
  1293. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id == spool_id))
  1294. spool = result.scalar_one_or_none()
  1295. if not spool:
  1296. raise HTTPException(404, "Spool not found")
  1297. if spool.archived_at:
  1298. raise HTTPException(400, "Cannot link tag to archived spool")
  1299. normalized_tag_uid = (normalize_tag_uid(data.tag_uid) or None) if data.tag_uid is not None else None
  1300. normalized_tray_uuid = (normalize_tray_uuid(data.tray_uuid) or None) if data.tray_uuid is not None else None
  1301. _validate_tag_input(data.tag_uid, normalized_tag_uid, "tag_uid")
  1302. _validate_tag_input(data.tray_uuid, normalized_tray_uuid, "tray_uuid", exact_len=32)
  1303. # Check for conflicts: tag already linked to another active spool
  1304. if normalized_tag_uid:
  1305. conflict = await db.execute(
  1306. select(Spool).where(
  1307. func.upper(Spool.tag_uid) == normalized_tag_uid,
  1308. Spool.id != spool_id,
  1309. Spool.archived_at.is_(None),
  1310. )
  1311. )
  1312. if conflict.scalar_one_or_none():
  1313. raise HTTPException(409, "Tag UID already linked to another active spool")
  1314. # Auto-clear from archived spools (tag recycling)
  1315. archived_with_tag = await db.execute(
  1316. select(Spool).where(
  1317. func.upper(Spool.tag_uid) == normalized_tag_uid,
  1318. Spool.id != spool_id,
  1319. Spool.archived_at.is_not(None),
  1320. )
  1321. )
  1322. for old_spool in archived_with_tag.scalars().all():
  1323. old_spool.tag_uid = None
  1324. if normalized_tray_uuid:
  1325. conflict = await db.execute(
  1326. select(Spool).where(
  1327. func.upper(Spool.tray_uuid) == normalized_tray_uuid,
  1328. Spool.id != spool_id,
  1329. Spool.archived_at.is_(None),
  1330. )
  1331. )
  1332. if conflict.scalar_one_or_none():
  1333. raise HTTPException(409, "Tray UUID already linked to another active spool")
  1334. archived_with_uuid = await db.execute(
  1335. select(Spool).where(
  1336. func.upper(Spool.tray_uuid) == normalized_tray_uuid,
  1337. Spool.id != spool_id,
  1338. Spool.archived_at.is_not(None),
  1339. )
  1340. )
  1341. for old_spool in archived_with_uuid.scalars().all():
  1342. old_spool.tray_uuid = None
  1343. if data.tag_uid is not None:
  1344. spool.tag_uid = normalized_tag_uid
  1345. if data.tray_uuid is not None:
  1346. spool.tray_uuid = normalized_tray_uuid
  1347. if data.tag_type is not None:
  1348. spool.tag_type = data.tag_type
  1349. if data.data_origin is not None:
  1350. spool.data_origin = data.data_origin
  1351. await db.commit()
  1352. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id == spool_id))
  1353. return result.scalar_one()
  1354. # ── Usage History ─────────────────────────────────────────────────────────────
  1355. @router.get("/spools/{spool_id}/usage", response_model=list[SpoolUsageHistoryResponse])
  1356. async def get_spool_usage_history(
  1357. spool_id: int,
  1358. limit: int = 50,
  1359. db: AsyncSession = Depends(get_db),
  1360. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1361. ):
  1362. """Get usage history for a specific spool."""
  1363. from backend.app.models.spool_usage_history import SpoolUsageHistory
  1364. # Verify spool exists
  1365. spool_result = await db.execute(select(Spool).where(Spool.id == spool_id))
  1366. if not spool_result.scalar_one_or_none():
  1367. raise HTTPException(404, "Spool not found")
  1368. result = await db.execute(
  1369. select(SpoolUsageHistory)
  1370. .where(SpoolUsageHistory.spool_id == spool_id)
  1371. .order_by(SpoolUsageHistory.created_at.desc())
  1372. .limit(limit)
  1373. )
  1374. return list(result.scalars().all())
  1375. @router.get("/usage", response_model=list[SpoolUsageHistoryResponse])
  1376. async def get_all_usage_history(
  1377. limit: int = 100,
  1378. printer_id: int | None = None,
  1379. db: AsyncSession = Depends(get_db),
  1380. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1381. ):
  1382. """Get global usage history, optionally filtered by printer."""
  1383. from backend.app.models.spool_usage_history import SpoolUsageHistory
  1384. query = select(SpoolUsageHistory).order_by(SpoolUsageHistory.created_at.desc()).limit(limit)
  1385. if printer_id is not None:
  1386. query = query.where(SpoolUsageHistory.printer_id == printer_id)
  1387. result = await db.execute(query)
  1388. return list(result.scalars().all())
  1389. @router.delete("/spools/{spool_id}/usage")
  1390. async def clear_spool_usage_history(
  1391. spool_id: int,
  1392. db: AsyncSession = Depends(get_db),
  1393. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1394. ):
  1395. """Clear usage history for a spool."""
  1396. from backend.app.models.spool_usage_history import SpoolUsageHistory
  1397. result = await db.execute(select(SpoolUsageHistory).where(SpoolUsageHistory.spool_id == spool_id))
  1398. for row in result.scalars().all():
  1399. await db.delete(row)
  1400. await db.commit()
  1401. return {"status": "cleared"}
  1402. # ── AMS Weight Sync ──────────────────────────────────────────────────────────
  1403. @router.post("/sync-ams-weights")
  1404. async def sync_weights_from_ams(
  1405. db: AsyncSession = Depends(get_db),
  1406. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1407. ):
  1408. """Force-sync spool weight_used from live AMS remain% data.
  1409. Overwrites the database weight_used for every assigned spool using the
  1410. current AMS remain% from connected printers. This is a manual recovery
  1411. tool — it bypasses the normal "only increase" guard.
  1412. """
  1413. from backend.app.services.printer_manager import printer_manager
  1414. result = await db.execute(select(SpoolAssignment).options(selectinload(SpoolAssignment.spool)))
  1415. assignments = list(result.scalars().all())
  1416. logger.info("AMS weight sync: found %d assignments", len(assignments))
  1417. synced = 0
  1418. skipped = 0
  1419. for assignment in assignments:
  1420. spool = assignment.spool
  1421. if not spool:
  1422. logger.debug("AMS weight sync: assignment %d has no spool", assignment.id)
  1423. skipped += 1
  1424. continue
  1425. if spool.weight_locked:
  1426. logger.debug("AMS weight sync: spool %d is weight-locked, skipping", spool.id)
  1427. skipped += 1
  1428. continue
  1429. state = printer_manager.get_status(assignment.printer_id)
  1430. if not state or not state.raw_data:
  1431. logger.info(
  1432. "AMS weight sync: printer %d not connected, skipping spool %d",
  1433. assignment.printer_id,
  1434. spool.id,
  1435. )
  1436. skipped += 1
  1437. continue
  1438. ams_raw = state.raw_data.get("ams", [])
  1439. if isinstance(ams_raw, dict):
  1440. ams_raw = ams_raw.get("ams", [])
  1441. tray = _find_tray_in_ams_data(ams_raw, assignment.ams_id, assignment.tray_id)
  1442. if not tray:
  1443. logger.info(
  1444. "AMS weight sync: no tray data for spool %d (printer %d AMS%d-T%d)",
  1445. spool.id,
  1446. assignment.printer_id,
  1447. assignment.ams_id,
  1448. assignment.tray_id,
  1449. )
  1450. skipped += 1
  1451. continue
  1452. remain_raw = tray.get("remain")
  1453. if remain_raw is None:
  1454. logger.debug("AMS weight sync: no remain value for spool %d", spool.id)
  1455. skipped += 1
  1456. continue
  1457. try:
  1458. remain_val = int(remain_raw)
  1459. except (TypeError, ValueError):
  1460. skipped += 1
  1461. continue
  1462. if remain_val < 0 or remain_val > 100:
  1463. logger.debug("AMS weight sync: invalid remain=%s for spool %d", remain_raw, spool.id)
  1464. skipped += 1
  1465. continue
  1466. lw = spool.label_weight or 1000
  1467. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  1468. old_used = spool.weight_used or 0
  1469. if round(old_used, 1) != new_used:
  1470. logger.info(
  1471. "AMS weight sync: spool %d weight_used %s -> %s (remain=%d%%)",
  1472. spool.id,
  1473. old_used,
  1474. new_used,
  1475. remain_val,
  1476. )
  1477. spool.weight_used = new_used
  1478. synced += 1
  1479. else:
  1480. skipped += 1
  1481. await db.commit()
  1482. return {"synced": synced, "skipped": skipped}
  1483. # ── Helpers ──────────────────────────────────────────────────────────────────
  1484. def _find_tray_in_ams_data(ams_data: list, ams_id: int, tray_id: int) -> dict | None:
  1485. """Find a specific tray in the AMS data structure."""
  1486. if not ams_data:
  1487. return None
  1488. for ams_unit in ams_data:
  1489. if int(ams_unit.get("id", -1)) != ams_id:
  1490. continue
  1491. for tray in ams_unit.get("tray", []):
  1492. if int(tray.get("id", -1)) == tray_id:
  1493. return tray
  1494. return None
  1495. # ── Filament SKU Settings (reorder forecasting) ───────────────────────────────
  1496. class FilamentSkuSettingsResponse(BaseModel):
  1497. id: int
  1498. material: str
  1499. subtype: str | None
  1500. brand: str | None
  1501. lead_time_days: int
  1502. safety_margin_value: int
  1503. safety_margin_unit: str
  1504. alerts_snoozed: bool = False
  1505. class Config:
  1506. from_attributes = True
  1507. class FilamentSkuSettingsUpsert(BaseModel):
  1508. material: str
  1509. subtype: str | None = None
  1510. brand: str | None = None
  1511. lead_time_days: int = 0
  1512. safety_margin_value: int = 14
  1513. safety_margin_unit: str = "days"
  1514. alerts_snoozed: bool = False
  1515. @router.get("/sku-settings", response_model=list[FilamentSkuSettingsResponse])
  1516. async def list_sku_settings(
  1517. db: AsyncSession = Depends(get_db),
  1518. _: User | None = RequireAnyPermissionIfAuthEnabled(Permission.INVENTORY_READ, Permission.INVENTORY_FORECAST_READ),
  1519. ):
  1520. """List all filament SKU reorder settings."""
  1521. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  1522. result = await db.execute(
  1523. select(FilamentSkuSettings).order_by(FilamentSkuSettings.material, FilamentSkuSettings.brand)
  1524. )
  1525. return list(result.scalars().all())
  1526. @router.post("/sku-settings", response_model=FilamentSkuSettingsResponse)
  1527. async def upsert_sku_settings(
  1528. data: FilamentSkuSettingsUpsert,
  1529. db: AsyncSession = Depends(get_db),
  1530. _: User | None = RequireAnyPermissionIfAuthEnabled(
  1531. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  1532. ),
  1533. ):
  1534. """Create or update reorder settings for a filament SKU (material/subtype/brand)."""
  1535. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  1536. result = await db.execute(
  1537. select(FilamentSkuSettings).where(
  1538. FilamentSkuSettings.material == data.material,
  1539. FilamentSkuSettings.subtype == data.subtype,
  1540. FilamentSkuSettings.brand == data.brand,
  1541. )
  1542. )
  1543. row = result.scalar_one_or_none()
  1544. if row:
  1545. row.lead_time_days = data.lead_time_days
  1546. row.safety_margin_value = data.safety_margin_value
  1547. row.safety_margin_unit = data.safety_margin_unit
  1548. row.alerts_snoozed = data.alerts_snoozed
  1549. else:
  1550. row = FilamentSkuSettings(
  1551. material=data.material,
  1552. subtype=data.subtype,
  1553. brand=data.brand,
  1554. lead_time_days=data.lead_time_days,
  1555. safety_margin_value=data.safety_margin_value,
  1556. safety_margin_unit=data.safety_margin_unit,
  1557. alerts_snoozed=data.alerts_snoozed,
  1558. )
  1559. db.add(row)
  1560. await db.commit()
  1561. await db.refresh(row)
  1562. return row
  1563. # ── Shopping List ─────────────────────────────────────────────────────────────
  1564. class ShoppingListItemResponse(BaseModel):
  1565. id: int
  1566. material: str
  1567. subtype: str | None
  1568. brand: str | None
  1569. quantity_spools: int
  1570. note: str | None
  1571. status: str
  1572. purchased_at: str | None
  1573. added_at: str
  1574. class Config:
  1575. from_attributes = True
  1576. class ShoppingListItemCreate(BaseModel):
  1577. material: str
  1578. subtype: str | None = None
  1579. brand: str | None = None
  1580. quantity_spools: int = 1
  1581. note: str | None = None
  1582. class ShoppingListItemStatusUpdate(BaseModel):
  1583. status: str # pending | purchased | received
  1584. @router.get("/shopping-list", response_model=list[ShoppingListItemResponse])
  1585. async def get_shopping_list(
  1586. db: AsyncSession = Depends(get_db),
  1587. _: User | None = RequireAnyPermissionIfAuthEnabled(Permission.INVENTORY_READ, Permission.INVENTORY_FORECAST_READ),
  1588. ):
  1589. """Get the filament shopping list."""
  1590. from backend.app.models.shopping_list import ShoppingListItem
  1591. result = await db.execute(select(ShoppingListItem).order_by(ShoppingListItem.added_at.desc()))
  1592. items = result.scalars().all()
  1593. return [
  1594. ShoppingListItemResponse(
  1595. id=i.id,
  1596. material=i.material,
  1597. subtype=i.subtype,
  1598. brand=i.brand,
  1599. quantity_spools=i.quantity_spools,
  1600. note=i.note,
  1601. status=i.status or "pending",
  1602. purchased_at=i.purchased_at.isoformat() if i.purchased_at else None,
  1603. added_at=i.added_at.isoformat() if i.added_at else "",
  1604. )
  1605. for i in items
  1606. ]
  1607. @router.post("/shopping-list", response_model=ShoppingListItemResponse)
  1608. async def add_to_shopping_list(
  1609. data: ShoppingListItemCreate,
  1610. db: AsyncSession = Depends(get_db),
  1611. _: User | None = RequireAnyPermissionIfAuthEnabled(
  1612. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  1613. ),
  1614. ):
  1615. """Add a filament SKU to the shopping list."""
  1616. from backend.app.models.shopping_list import ShoppingListItem
  1617. item = ShoppingListItem(
  1618. material=data.material,
  1619. subtype=data.subtype,
  1620. brand=data.brand,
  1621. quantity_spools=data.quantity_spools,
  1622. note=data.note,
  1623. )
  1624. db.add(item)
  1625. await db.commit()
  1626. await db.refresh(item)
  1627. return ShoppingListItemResponse(
  1628. id=item.id,
  1629. material=item.material,
  1630. subtype=item.subtype,
  1631. brand=item.brand,
  1632. quantity_spools=item.quantity_spools,
  1633. note=item.note,
  1634. status=item.status or "pending",
  1635. purchased_at=item.purchased_at.isoformat() if item.purchased_at else None,
  1636. added_at=item.added_at.isoformat() if item.added_at else "",
  1637. )
  1638. @router.patch("/shopping-list/{item_id}/status", response_model=ShoppingListItemResponse)
  1639. async def update_shopping_list_status(
  1640. item_id: int,
  1641. data: ShoppingListItemStatusUpdate,
  1642. db: AsyncSession = Depends(get_db),
  1643. _: User | None = RequireAnyPermissionIfAuthEnabled(
  1644. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  1645. ),
  1646. ):
  1647. """Update the purchase status of a shopping list item."""
  1648. from datetime import datetime, timezone
  1649. from backend.app.models.shopping_list import ShoppingListItem
  1650. if data.status not in ("pending", "purchased", "received"):
  1651. raise HTTPException(400, "Invalid status")
  1652. result = await db.execute(select(ShoppingListItem).where(ShoppingListItem.id == item_id))
  1653. item = result.scalar_one_or_none()
  1654. if not item:
  1655. raise HTTPException(404, "Item not found")
  1656. item.status = data.status
  1657. if data.status in ("purchased", "received") and item.purchased_at is None:
  1658. item.purchased_at = datetime.now(timezone.utc)
  1659. elif data.status == "pending":
  1660. item.purchased_at = None
  1661. await db.commit()
  1662. await db.refresh(item)
  1663. return ShoppingListItemResponse(
  1664. id=item.id,
  1665. material=item.material,
  1666. subtype=item.subtype,
  1667. brand=item.brand,
  1668. quantity_spools=item.quantity_spools,
  1669. note=item.note,
  1670. status=item.status or "pending",
  1671. purchased_at=item.purchased_at.isoformat() if item.purchased_at else None,
  1672. added_at=item.added_at.isoformat() if item.added_at else "",
  1673. )
  1674. @router.delete("/shopping-list/{item_id}")
  1675. async def remove_from_shopping_list(
  1676. item_id: int,
  1677. db: AsyncSession = Depends(get_db),
  1678. _: User | None = RequireAnyPermissionIfAuthEnabled(
  1679. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  1680. ),
  1681. ):
  1682. """Remove a single item from the shopping list."""
  1683. from backend.app.models.shopping_list import ShoppingListItem
  1684. result = await db.execute(select(ShoppingListItem).where(ShoppingListItem.id == item_id))
  1685. item = result.scalar_one_or_none()
  1686. if not item:
  1687. raise HTTPException(404, "Item not found")
  1688. await db.delete(item)
  1689. await db.commit()
  1690. return {"status": "deleted"}
  1691. @router.delete("/shopping-list")
  1692. async def clear_shopping_list(
  1693. db: AsyncSession = Depends(get_db),
  1694. _: User | None = RequireAnyPermissionIfAuthEnabled(
  1695. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  1696. ),
  1697. ):
  1698. """Clear all items from the shopping list."""
  1699. from backend.app.models.shopping_list import ShoppingListItem
  1700. result = await db.execute(delete(ShoppingListItem).returning(ShoppingListItem.id))
  1701. deleted = len(result.fetchall())
  1702. await db.commit()
  1703. return {"deleted": deleted}