inventory.py 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920
  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. # ── K-Profiles ───────────────────────────────────────────────────────────────
  927. @router.get("/spools/{spool_id}/k-profiles", response_model=list[SpoolKProfileResponse])
  928. async def list_k_profiles(
  929. spool_id: int,
  930. db: AsyncSession = Depends(get_db),
  931. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  932. ):
  933. """List K-profiles for a spool."""
  934. result = await db.execute(select(SpoolKProfile).where(SpoolKProfile.spool_id == spool_id))
  935. return list(result.scalars().all())
  936. @router.put("/spools/{spool_id}/k-profiles", response_model=list[SpoolKProfileResponse])
  937. async def replace_k_profiles(
  938. spool_id: int,
  939. profiles: list[SpoolKProfileBase],
  940. db: AsyncSession = Depends(get_db),
  941. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  942. ):
  943. """Replace all K-profiles for a spool (batch save)."""
  944. # Verify spool exists
  945. result = await db.execute(select(Spool).where(Spool.id == spool_id))
  946. if not result.scalar_one_or_none():
  947. raise HTTPException(404, "Spool not found")
  948. # Delete existing
  949. existing = await db.execute(select(SpoolKProfile).where(SpoolKProfile.spool_id == spool_id))
  950. for old in existing.scalars().all():
  951. await db.delete(old)
  952. # Create new
  953. new_profiles = []
  954. for p in profiles:
  955. kp = SpoolKProfile(spool_id=spool_id, **p.model_dump())
  956. db.add(kp)
  957. new_profiles.append(kp)
  958. await db.commit()
  959. for kp in new_profiles:
  960. await db.refresh(kp)
  961. return new_profiles
  962. # ── Spool Assignments ────────────────────────────────────────────────────────
  963. @router.get("/assignments", response_model=list[SpoolAssignmentResponse])
  964. async def list_assignments(
  965. printer_id: int | None = None,
  966. db: AsyncSession = Depends(get_db),
  967. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_VIEW_ASSIGNMENTS),
  968. ):
  969. """List spool assignments, optionally filtered by printer."""
  970. from backend.app.services.printer_manager import printer_manager
  971. query = select(SpoolAssignment).options(
  972. selectinload(SpoolAssignment.spool).selectinload(Spool.k_profiles),
  973. selectinload(SpoolAssignment.printer),
  974. )
  975. if printer_id is not None:
  976. query = query.where(SpoolAssignment.printer_id == printer_id)
  977. result = await db.execute(query)
  978. assignments = list(result.scalars().all())
  979. # Build (printer_id, ams_id) -> ams_serial map from live printer states.
  980. # Fetch all statuses in one call rather than one get_status() call per printer.
  981. serial_map: dict[tuple[int, int], str] = {}
  982. seen_printer_ids: set[int] = {a.printer_id for a in assignments}
  983. all_statuses = printer_manager.get_all_statuses()
  984. for pid in seen_printer_ids:
  985. state = all_statuses.get(pid)
  986. if state and state.raw_data:
  987. for ams_unit in state.raw_data.get("ams", []):
  988. sn = str(ams_unit.get("sn") or ams_unit.get("serial_number") or "")
  989. if sn:
  990. try:
  991. serial_map[(pid, int(ams_unit.get("id", 0)))] = sn
  992. except (ValueError, TypeError):
  993. continue
  994. # Fetch all relevant AMS labels keyed by serial number
  995. all_serials = set(serial_map.values())
  996. # Also include synthetic fallback keys for assignments without a known serial
  997. synthetic_keys: dict[str, tuple[int, int]] = {}
  998. for a in assignments:
  999. if (a.printer_id, a.ams_id) not in serial_map:
  1000. synthetic = f"p{a.printer_id}a{a.ams_id}"
  1001. synthetic_keys[synthetic] = (a.printer_id, a.ams_id)
  1002. all_serials.add(synthetic)
  1003. label_by_serial: dict[str, str] = {}
  1004. if all_serials:
  1005. lbl_result = await db.execute(select(AmsLabel).where(AmsLabel.ams_serial_number.in_(all_serials)))
  1006. for lbl in lbl_result.scalars().all():
  1007. label_by_serial[lbl.ams_serial_number] = lbl.label
  1008. # Build response objects, attaching ams_label where available
  1009. responses: list[SpoolAssignmentResponse] = []
  1010. for a in assignments:
  1011. resp = SpoolAssignmentResponse.model_validate(a)
  1012. sn = serial_map.get((a.printer_id, a.ams_id))
  1013. if sn and sn in label_by_serial:
  1014. resp.ams_label = label_by_serial[sn]
  1015. elif not sn:
  1016. synthetic = f"p{a.printer_id}a{a.ams_id}"
  1017. resp.ams_label = label_by_serial.get(synthetic)
  1018. responses.append(resp)
  1019. return responses
  1020. @router.post("/assignments", response_model=SpoolAssignmentResponse)
  1021. async def assign_spool(
  1022. data: SpoolAssignmentCreate,
  1023. db: AsyncSession = Depends(get_db),
  1024. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1025. ):
  1026. """Assign a spool to an AMS slot and auto-configure via MQTT."""
  1027. from backend.app.services.printer_manager import printer_manager
  1028. # 1. Validate spool exists and is not archived
  1029. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id == data.spool_id))
  1030. spool = result.scalar_one_or_none()
  1031. if not spool:
  1032. raise HTTPException(404, "Spool not found")
  1033. if spool.archived_at:
  1034. raise HTTPException(400, "Cannot assign an archived spool")
  1035. # 2. Get current AMS tray state for fingerprint + existing filament ID.
  1036. # tray_state: Bambu firmware reports 11=loaded, 9=empty, 10=spool present
  1037. # but filament not in feeder. Captured here so the empty-slot heuristic
  1038. # below can prefer it over tray_type — a manual "Reset slot" clears
  1039. # tray_type to "" while leaving state at 11 (filament still physically
  1040. # present), which would otherwise mislead the heuristic into the
  1041. # pending-config branch and skip MQTT forever (#1228 follow-up).
  1042. fingerprint_color = None
  1043. fingerprint_type = None
  1044. current_tray_info_idx = ""
  1045. tray_state: int | None = None
  1046. state = printer_manager.get_status(data.printer_id)
  1047. if state and state.raw_data:
  1048. if data.ams_id == 255:
  1049. # External slot: look up tray from vt_tray by global ID
  1050. vt_tray = state.raw_data.get("vt_tray") or []
  1051. ext_id = data.tray_id + 254 # 0→254, 1→255
  1052. for vt in vt_tray:
  1053. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1054. fingerprint_color = vt.get("tray_color", "")
  1055. fingerprint_type = vt.get("tray_type", "")
  1056. current_tray_info_idx = vt.get("tray_info_idx", "")
  1057. raw_state = vt.get("state")
  1058. if isinstance(raw_state, int):
  1059. tray_state = raw_state
  1060. break
  1061. else:
  1062. ams_data = state.raw_data.get("ams", {})
  1063. ams_list = (
  1064. ams_data.get("ams", [])
  1065. if isinstance(ams_data, dict)
  1066. else ams_data
  1067. if isinstance(ams_data, list)
  1068. else []
  1069. )
  1070. tray = _find_tray_in_ams_data(
  1071. ams_list,
  1072. data.ams_id,
  1073. data.tray_id,
  1074. )
  1075. if tray:
  1076. fingerprint_color = tray.get("tray_color", "")
  1077. fingerprint_type = tray.get("tray_type", "")
  1078. current_tray_info_idx = tray.get("tray_info_idx", "")
  1079. raw_state = tray.get("state")
  1080. if isinstance(raw_state, int):
  1081. tray_state = raw_state
  1082. # 3. Upsert assignment (replace if same printer+ams+tray)
  1083. existing = await db.execute(
  1084. select(SpoolAssignment).where(
  1085. SpoolAssignment.printer_id == data.printer_id,
  1086. SpoolAssignment.ams_id == data.ams_id,
  1087. SpoolAssignment.tray_id == data.tray_id,
  1088. )
  1089. )
  1090. old = existing.scalar_one_or_none()
  1091. if old:
  1092. await db.delete(old)
  1093. await db.flush()
  1094. assignment = SpoolAssignment(
  1095. spool_id=data.spool_id,
  1096. printer_id=data.printer_id,
  1097. ams_id=data.ams_id,
  1098. tray_id=data.tray_id,
  1099. fingerprint_color=fingerprint_color,
  1100. fingerprint_type=fingerprint_type,
  1101. )
  1102. db.add(assignment)
  1103. await db.commit()
  1104. await db.refresh(assignment)
  1105. # 4. Auto-configure AMS slot via MQTT.
  1106. #
  1107. # Only suppress the publish when the firmware's *explicit* empty signal
  1108. # (state ∈ {9, 10}) is set — "no spool" / "spool present but no feed".
  1109. # Every other state, including state=3 (the default idle on A1 Mini BMCU /
  1110. # P1S Standard AMS for both loaded and unconfigured slots) and missing
  1111. # state (older firmwares), is treated as the user's assertion that a
  1112. # spool is in the slot and we attempt the MQTT push.
  1113. #
  1114. # The pre-existing "skip when slot looks empty" guard read state=3 +
  1115. # tray_type="" as "empty" and skipped MQTT. On these firmwares that
  1116. # combination is the post-"Reset Slot" state with the spool still
  1117. # physically inserted — there is NO AMS signal that distinguishes it
  1118. # from a truly-empty slot, so the guard created a deadlock: MQTT never
  1119. # fired, the AMS never reported any change (because nothing changed
  1120. # physically), and on_ams_change replay therefore never re-fired the
  1121. # config either. Reporter (#1322 follow-up by @RosdasHH) verified
  1122. # empirically that removing the guard makes the slot configure
  1123. # correctly because Bambu firmware DOES accept the push for a
  1124. # physically-loaded slot, even when tray_type is "" and state is 3.
  1125. #
  1126. # Trade-off for the truly-empty slot case: firmware drops the push
  1127. # silently (per Bambu's documented behavior), the SpoolAssignment row
  1128. # still has empty fingerprint_type because nothing in the assign path
  1129. # updates that column, and on_ams_change at main.py:1031-1054 still
  1130. # fires the deferred config when a spool eventually appears. So the
  1131. # SpoolBuddy weigh-then-assign-before-insert workflow continues to
  1132. # work — just without the optimization of skipping a no-op MQTT call.
  1133. #
  1134. # state ∈ {9, 10} stays as an explicit short-circuit so we don't churn
  1135. # a doomed MQTT push when the firmware has positively confirmed "no
  1136. # spool" — and to keep the on_ams_change replay path as the single
  1137. # source of truth for those slots.
  1138. slot_is_definitely_empty = tray_state == 9 or tray_state == 10
  1139. configured = False
  1140. if not slot_is_definitely_empty:
  1141. try:
  1142. configured = await apply_spool_to_slot_via_mqtt(
  1143. db=db,
  1144. current_user=current_user,
  1145. spool=spool,
  1146. printer_id=data.printer_id,
  1147. ams_id=data.ams_id,
  1148. tray_id=data.tray_id,
  1149. current_tray_info_idx=current_tray_info_idx,
  1150. current_tray_type=fingerprint_type or "",
  1151. )
  1152. except Exception as e:
  1153. logger.warning("MQTT auto-configure failed for spool %d: %s", spool.id, e)
  1154. # pending_config is the "config not landed yet" UI marker. True when the
  1155. # firmware said empty, OR when MQTT couldn't actually publish (printer
  1156. # offline, no client, transient failure). on_ams_change replay re-fires
  1157. # the config in either case once the AMS reports a non-empty fingerprint.
  1158. pending_config = slot_is_definitely_empty or not configured
  1159. # Return assignment with spool data
  1160. result = await db.execute(
  1161. select(SpoolAssignment)
  1162. .options(
  1163. selectinload(SpoolAssignment.spool).selectinload(Spool.k_profiles),
  1164. selectinload(SpoolAssignment.printer),
  1165. )
  1166. .where(SpoolAssignment.id == assignment.id)
  1167. )
  1168. resp = result.scalar_one()
  1169. response = SpoolAssignmentResponse.model_validate(resp)
  1170. response.configured = configured
  1171. response.pending_config = pending_config
  1172. if pending_config:
  1173. logger.info(
  1174. "Pre-configured assignment: spool %d → printer %d AMS%d-T%d (slot empty, will configure on insert)",
  1175. spool.id,
  1176. data.printer_id,
  1177. data.ams_id,
  1178. data.tray_id,
  1179. )
  1180. await ws_manager.broadcast(
  1181. {
  1182. "type": "spool_assignment_changed",
  1183. "printer_id": data.printer_id,
  1184. "ams_id": data.ams_id,
  1185. "tray_id": data.tray_id,
  1186. }
  1187. )
  1188. return response
  1189. @router.delete("/assignments/{printer_id}/{ams_id}/{tray_id}")
  1190. async def unassign_spool(
  1191. printer_id: int,
  1192. ams_id: int,
  1193. tray_id: int,
  1194. db: AsyncSession = Depends(get_db),
  1195. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1196. ):
  1197. """Unassign a spool from an AMS slot."""
  1198. result = await db.execute(
  1199. select(SpoolAssignment).where(
  1200. SpoolAssignment.printer_id == printer_id,
  1201. SpoolAssignment.ams_id == ams_id,
  1202. SpoolAssignment.tray_id == tray_id,
  1203. )
  1204. )
  1205. assignment = result.scalar_one_or_none()
  1206. if not assignment:
  1207. raise HTTPException(404, "Assignment not found")
  1208. await db.delete(assignment)
  1209. await db.commit()
  1210. await ws_manager.broadcast(
  1211. {
  1212. "type": "spool_assignment_changed",
  1213. "printer_id": printer_id,
  1214. "ams_id": ams_id,
  1215. "tray_id": tray_id,
  1216. }
  1217. )
  1218. return {"status": "deleted"}
  1219. # ── Tag Linking ───────────────────────────────────────────────────────────────
  1220. class LinkTagRequest(BaseModel):
  1221. tag_uid: str | None = None
  1222. tray_uuid: str | None = None
  1223. tag_type: str | None = None
  1224. data_origin: str | None = "nfc_link"
  1225. def _validate_tag_input(
  1226. raw_value: str | None, normalized_value: str | None, field_name: str, exact_len: int | None = None
  1227. ) -> None:
  1228. if raw_value is None:
  1229. return
  1230. raw = str(raw_value).strip()
  1231. if not raw:
  1232. return
  1233. if normalized_value is None:
  1234. raise HTTPException(422, f"{field_name} must contain hexadecimal characters")
  1235. if len(normalized_value) % 2 != 0:
  1236. raise HTTPException(422, f"{field_name} must have an even number of hex characters")
  1237. if exact_len is not None and len(normalized_value) != exact_len:
  1238. raise HTTPException(422, f"{field_name} must be exactly {exact_len} hex characters")
  1239. @router.patch("/spools/{spool_id}/link-tag", response_model=SpoolResponse)
  1240. async def link_tag_to_spool(
  1241. spool_id: int,
  1242. data: LinkTagRequest,
  1243. db: AsyncSession = Depends(get_db),
  1244. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1245. ):
  1246. """Link an RFID tag_uid/tray_uuid to an existing spool."""
  1247. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id == spool_id))
  1248. spool = result.scalar_one_or_none()
  1249. if not spool:
  1250. raise HTTPException(404, "Spool not found")
  1251. if spool.archived_at:
  1252. raise HTTPException(400, "Cannot link tag to archived spool")
  1253. normalized_tag_uid = (normalize_tag_uid(data.tag_uid) or None) if data.tag_uid is not None else None
  1254. normalized_tray_uuid = (normalize_tray_uuid(data.tray_uuid) or None) if data.tray_uuid is not None else None
  1255. _validate_tag_input(data.tag_uid, normalized_tag_uid, "tag_uid")
  1256. _validate_tag_input(data.tray_uuid, normalized_tray_uuid, "tray_uuid", exact_len=32)
  1257. # Check for conflicts: tag already linked to another active spool
  1258. if normalized_tag_uid:
  1259. conflict = await db.execute(
  1260. select(Spool).where(
  1261. func.upper(Spool.tag_uid) == normalized_tag_uid,
  1262. Spool.id != spool_id,
  1263. Spool.archived_at.is_(None),
  1264. )
  1265. )
  1266. if conflict.scalar_one_or_none():
  1267. raise HTTPException(409, "Tag UID already linked to another active spool")
  1268. # Auto-clear from archived spools (tag recycling)
  1269. archived_with_tag = await db.execute(
  1270. select(Spool).where(
  1271. func.upper(Spool.tag_uid) == normalized_tag_uid,
  1272. Spool.id != spool_id,
  1273. Spool.archived_at.is_not(None),
  1274. )
  1275. )
  1276. for old_spool in archived_with_tag.scalars().all():
  1277. old_spool.tag_uid = None
  1278. if normalized_tray_uuid:
  1279. conflict = await db.execute(
  1280. select(Spool).where(
  1281. func.upper(Spool.tray_uuid) == normalized_tray_uuid,
  1282. Spool.id != spool_id,
  1283. Spool.archived_at.is_(None),
  1284. )
  1285. )
  1286. if conflict.scalar_one_or_none():
  1287. raise HTTPException(409, "Tray UUID already linked to another active spool")
  1288. archived_with_uuid = await db.execute(
  1289. select(Spool).where(
  1290. func.upper(Spool.tray_uuid) == normalized_tray_uuid,
  1291. Spool.id != spool_id,
  1292. Spool.archived_at.is_not(None),
  1293. )
  1294. )
  1295. for old_spool in archived_with_uuid.scalars().all():
  1296. old_spool.tray_uuid = None
  1297. if data.tag_uid is not None:
  1298. spool.tag_uid = normalized_tag_uid
  1299. if data.tray_uuid is not None:
  1300. spool.tray_uuid = normalized_tray_uuid
  1301. if data.tag_type is not None:
  1302. spool.tag_type = data.tag_type
  1303. if data.data_origin is not None:
  1304. spool.data_origin = data.data_origin
  1305. await db.commit()
  1306. result = await db.execute(select(Spool).options(selectinload(Spool.k_profiles)).where(Spool.id == spool_id))
  1307. return result.scalar_one()
  1308. # ── Usage History ─────────────────────────────────────────────────────────────
  1309. @router.get("/spools/{spool_id}/usage", response_model=list[SpoolUsageHistoryResponse])
  1310. async def get_spool_usage_history(
  1311. spool_id: int,
  1312. limit: int = 50,
  1313. db: AsyncSession = Depends(get_db),
  1314. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1315. ):
  1316. """Get usage history for a specific spool."""
  1317. from backend.app.models.spool_usage_history import SpoolUsageHistory
  1318. # Verify spool exists
  1319. spool_result = await db.execute(select(Spool).where(Spool.id == spool_id))
  1320. if not spool_result.scalar_one_or_none():
  1321. raise HTTPException(404, "Spool not found")
  1322. result = await db.execute(
  1323. select(SpoolUsageHistory)
  1324. .where(SpoolUsageHistory.spool_id == spool_id)
  1325. .order_by(SpoolUsageHistory.created_at.desc())
  1326. .limit(limit)
  1327. )
  1328. return list(result.scalars().all())
  1329. @router.get("/usage", response_model=list[SpoolUsageHistoryResponse])
  1330. async def get_all_usage_history(
  1331. limit: int = 100,
  1332. printer_id: int | None = None,
  1333. db: AsyncSession = Depends(get_db),
  1334. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1335. ):
  1336. """Get global usage history, optionally filtered by printer."""
  1337. from backend.app.models.spool_usage_history import SpoolUsageHistory
  1338. query = select(SpoolUsageHistory).order_by(SpoolUsageHistory.created_at.desc()).limit(limit)
  1339. if printer_id is not None:
  1340. query = query.where(SpoolUsageHistory.printer_id == printer_id)
  1341. result = await db.execute(query)
  1342. return list(result.scalars().all())
  1343. @router.delete("/spools/{spool_id}/usage")
  1344. async def clear_spool_usage_history(
  1345. spool_id: int,
  1346. db: AsyncSession = Depends(get_db),
  1347. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1348. ):
  1349. """Clear usage history for a spool."""
  1350. from backend.app.models.spool_usage_history import SpoolUsageHistory
  1351. result = await db.execute(select(SpoolUsageHistory).where(SpoolUsageHistory.spool_id == spool_id))
  1352. for row in result.scalars().all():
  1353. await db.delete(row)
  1354. await db.commit()
  1355. return {"status": "cleared"}
  1356. # ── AMS Weight Sync ──────────────────────────────────────────────────────────
  1357. @router.post("/sync-ams-weights")
  1358. async def sync_weights_from_ams(
  1359. db: AsyncSession = Depends(get_db),
  1360. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1361. ):
  1362. """Force-sync spool weight_used from live AMS remain% data.
  1363. Overwrites the database weight_used for every assigned spool using the
  1364. current AMS remain% from connected printers. This is a manual recovery
  1365. tool — it bypasses the normal "only increase" guard.
  1366. """
  1367. from backend.app.services.printer_manager import printer_manager
  1368. result = await db.execute(select(SpoolAssignment).options(selectinload(SpoolAssignment.spool)))
  1369. assignments = list(result.scalars().all())
  1370. logger.info("AMS weight sync: found %d assignments", len(assignments))
  1371. synced = 0
  1372. skipped = 0
  1373. for assignment in assignments:
  1374. spool = assignment.spool
  1375. if not spool:
  1376. logger.debug("AMS weight sync: assignment %d has no spool", assignment.id)
  1377. skipped += 1
  1378. continue
  1379. if spool.weight_locked:
  1380. logger.debug("AMS weight sync: spool %d is weight-locked, skipping", spool.id)
  1381. skipped += 1
  1382. continue
  1383. state = printer_manager.get_status(assignment.printer_id)
  1384. if not state or not state.raw_data:
  1385. logger.info(
  1386. "AMS weight sync: printer %d not connected, skipping spool %d",
  1387. assignment.printer_id,
  1388. spool.id,
  1389. )
  1390. skipped += 1
  1391. continue
  1392. ams_raw = state.raw_data.get("ams", [])
  1393. if isinstance(ams_raw, dict):
  1394. ams_raw = ams_raw.get("ams", [])
  1395. tray = _find_tray_in_ams_data(ams_raw, assignment.ams_id, assignment.tray_id)
  1396. if not tray:
  1397. logger.info(
  1398. "AMS weight sync: no tray data for spool %d (printer %d AMS%d-T%d)",
  1399. spool.id,
  1400. assignment.printer_id,
  1401. assignment.ams_id,
  1402. assignment.tray_id,
  1403. )
  1404. skipped += 1
  1405. continue
  1406. remain_raw = tray.get("remain")
  1407. if remain_raw is None:
  1408. logger.debug("AMS weight sync: no remain value for spool %d", spool.id)
  1409. skipped += 1
  1410. continue
  1411. try:
  1412. remain_val = int(remain_raw)
  1413. except (TypeError, ValueError):
  1414. skipped += 1
  1415. continue
  1416. if remain_val < 0 or remain_val > 100:
  1417. logger.debug("AMS weight sync: invalid remain=%s for spool %d", remain_raw, spool.id)
  1418. skipped += 1
  1419. continue
  1420. lw = spool.label_weight or 1000
  1421. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  1422. old_used = spool.weight_used or 0
  1423. if round(old_used, 1) != new_used:
  1424. logger.info(
  1425. "AMS weight sync: spool %d weight_used %s -> %s (remain=%d%%)",
  1426. spool.id,
  1427. old_used,
  1428. new_used,
  1429. remain_val,
  1430. )
  1431. spool.weight_used = new_used
  1432. synced += 1
  1433. else:
  1434. skipped += 1
  1435. await db.commit()
  1436. return {"synced": synced, "skipped": skipped}
  1437. # ── Helpers ──────────────────────────────────────────────────────────────────
  1438. def _find_tray_in_ams_data(ams_data: list, ams_id: int, tray_id: int) -> dict | None:
  1439. """Find a specific tray in the AMS data structure."""
  1440. if not ams_data:
  1441. return None
  1442. for ams_unit in ams_data:
  1443. if int(ams_unit.get("id", -1)) != ams_id:
  1444. continue
  1445. for tray in ams_unit.get("tray", []):
  1446. if int(tray.get("id", -1)) == tray_id:
  1447. return tray
  1448. return None
  1449. # ── Filament SKU Settings (reorder forecasting) ───────────────────────────────
  1450. class FilamentSkuSettingsResponse(BaseModel):
  1451. id: int
  1452. material: str
  1453. subtype: str | None
  1454. brand: str | None
  1455. lead_time_days: int
  1456. safety_margin_value: int
  1457. safety_margin_unit: str
  1458. alerts_snoozed: bool = False
  1459. class Config:
  1460. from_attributes = True
  1461. class FilamentSkuSettingsUpsert(BaseModel):
  1462. material: str
  1463. subtype: str | None = None
  1464. brand: str | None = None
  1465. lead_time_days: int = 0
  1466. safety_margin_value: int = 14
  1467. safety_margin_unit: str = "days"
  1468. alerts_snoozed: bool = False
  1469. @router.get("/sku-settings", response_model=list[FilamentSkuSettingsResponse])
  1470. async def list_sku_settings(
  1471. db: AsyncSession = Depends(get_db),
  1472. _: User | None = RequireAnyPermissionIfAuthEnabled(Permission.INVENTORY_READ, Permission.INVENTORY_FORECAST_READ),
  1473. ):
  1474. """List all filament SKU reorder settings."""
  1475. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  1476. result = await db.execute(
  1477. select(FilamentSkuSettings).order_by(FilamentSkuSettings.material, FilamentSkuSettings.brand)
  1478. )
  1479. return list(result.scalars().all())
  1480. @router.post("/sku-settings", response_model=FilamentSkuSettingsResponse)
  1481. async def upsert_sku_settings(
  1482. data: FilamentSkuSettingsUpsert,
  1483. db: AsyncSession = Depends(get_db),
  1484. _: User | None = RequireAnyPermissionIfAuthEnabled(
  1485. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  1486. ),
  1487. ):
  1488. """Create or update reorder settings for a filament SKU (material/subtype/brand)."""
  1489. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  1490. result = await db.execute(
  1491. select(FilamentSkuSettings).where(
  1492. FilamentSkuSettings.material == data.material,
  1493. FilamentSkuSettings.subtype == data.subtype,
  1494. FilamentSkuSettings.brand == data.brand,
  1495. )
  1496. )
  1497. row = result.scalar_one_or_none()
  1498. if row:
  1499. row.lead_time_days = data.lead_time_days
  1500. row.safety_margin_value = data.safety_margin_value
  1501. row.safety_margin_unit = data.safety_margin_unit
  1502. row.alerts_snoozed = data.alerts_snoozed
  1503. else:
  1504. row = FilamentSkuSettings(
  1505. material=data.material,
  1506. subtype=data.subtype,
  1507. brand=data.brand,
  1508. lead_time_days=data.lead_time_days,
  1509. safety_margin_value=data.safety_margin_value,
  1510. safety_margin_unit=data.safety_margin_unit,
  1511. alerts_snoozed=data.alerts_snoozed,
  1512. )
  1513. db.add(row)
  1514. await db.commit()
  1515. await db.refresh(row)
  1516. return row
  1517. # ── Shopping List ─────────────────────────────────────────────────────────────
  1518. class ShoppingListItemResponse(BaseModel):
  1519. id: int
  1520. material: str
  1521. subtype: str | None
  1522. brand: str | None
  1523. quantity_spools: int
  1524. note: str | None
  1525. status: str
  1526. purchased_at: str | None
  1527. added_at: str
  1528. class Config:
  1529. from_attributes = True
  1530. class ShoppingListItemCreate(BaseModel):
  1531. material: str
  1532. subtype: str | None = None
  1533. brand: str | None = None
  1534. quantity_spools: int = 1
  1535. note: str | None = None
  1536. class ShoppingListItemStatusUpdate(BaseModel):
  1537. status: str # pending | purchased | received
  1538. @router.get("/shopping-list", response_model=list[ShoppingListItemResponse])
  1539. async def get_shopping_list(
  1540. db: AsyncSession = Depends(get_db),
  1541. _: User | None = RequireAnyPermissionIfAuthEnabled(Permission.INVENTORY_READ, Permission.INVENTORY_FORECAST_READ),
  1542. ):
  1543. """Get the filament shopping list."""
  1544. from backend.app.models.shopping_list import ShoppingListItem
  1545. result = await db.execute(select(ShoppingListItem).order_by(ShoppingListItem.added_at.desc()))
  1546. items = result.scalars().all()
  1547. return [
  1548. ShoppingListItemResponse(
  1549. id=i.id,
  1550. material=i.material,
  1551. subtype=i.subtype,
  1552. brand=i.brand,
  1553. quantity_spools=i.quantity_spools,
  1554. note=i.note,
  1555. status=i.status or "pending",
  1556. purchased_at=i.purchased_at.isoformat() if i.purchased_at else None,
  1557. added_at=i.added_at.isoformat() if i.added_at else "",
  1558. )
  1559. for i in items
  1560. ]
  1561. @router.post("/shopping-list", response_model=ShoppingListItemResponse)
  1562. async def add_to_shopping_list(
  1563. data: ShoppingListItemCreate,
  1564. db: AsyncSession = Depends(get_db),
  1565. _: User | None = RequireAnyPermissionIfAuthEnabled(
  1566. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  1567. ),
  1568. ):
  1569. """Add a filament SKU to the shopping list."""
  1570. from backend.app.models.shopping_list import ShoppingListItem
  1571. item = ShoppingListItem(
  1572. material=data.material,
  1573. subtype=data.subtype,
  1574. brand=data.brand,
  1575. quantity_spools=data.quantity_spools,
  1576. note=data.note,
  1577. )
  1578. db.add(item)
  1579. await db.commit()
  1580. await db.refresh(item)
  1581. return ShoppingListItemResponse(
  1582. id=item.id,
  1583. material=item.material,
  1584. subtype=item.subtype,
  1585. brand=item.brand,
  1586. quantity_spools=item.quantity_spools,
  1587. note=item.note,
  1588. status=item.status or "pending",
  1589. purchased_at=item.purchased_at.isoformat() if item.purchased_at else None,
  1590. added_at=item.added_at.isoformat() if item.added_at else "",
  1591. )
  1592. @router.patch("/shopping-list/{item_id}/status", response_model=ShoppingListItemResponse)
  1593. async def update_shopping_list_status(
  1594. item_id: int,
  1595. data: ShoppingListItemStatusUpdate,
  1596. db: AsyncSession = Depends(get_db),
  1597. _: User | None = RequireAnyPermissionIfAuthEnabled(
  1598. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  1599. ),
  1600. ):
  1601. """Update the purchase status of a shopping list item."""
  1602. from datetime import datetime, timezone
  1603. from backend.app.models.shopping_list import ShoppingListItem
  1604. if data.status not in ("pending", "purchased", "received"):
  1605. raise HTTPException(400, "Invalid status")
  1606. result = await db.execute(select(ShoppingListItem).where(ShoppingListItem.id == item_id))
  1607. item = result.scalar_one_or_none()
  1608. if not item:
  1609. raise HTTPException(404, "Item not found")
  1610. item.status = data.status
  1611. if data.status in ("purchased", "received") and item.purchased_at is None:
  1612. item.purchased_at = datetime.now(timezone.utc)
  1613. elif data.status == "pending":
  1614. item.purchased_at = None
  1615. await db.commit()
  1616. await db.refresh(item)
  1617. return ShoppingListItemResponse(
  1618. id=item.id,
  1619. material=item.material,
  1620. subtype=item.subtype,
  1621. brand=item.brand,
  1622. quantity_spools=item.quantity_spools,
  1623. note=item.note,
  1624. status=item.status or "pending",
  1625. purchased_at=item.purchased_at.isoformat() if item.purchased_at else None,
  1626. added_at=item.added_at.isoformat() if item.added_at else "",
  1627. )
  1628. @router.delete("/shopping-list/{item_id}")
  1629. async def remove_from_shopping_list(
  1630. item_id: int,
  1631. db: AsyncSession = Depends(get_db),
  1632. _: User | None = RequireAnyPermissionIfAuthEnabled(
  1633. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  1634. ),
  1635. ):
  1636. """Remove a single item from the shopping list."""
  1637. from backend.app.models.shopping_list import ShoppingListItem
  1638. result = await db.execute(select(ShoppingListItem).where(ShoppingListItem.id == item_id))
  1639. item = result.scalar_one_or_none()
  1640. if not item:
  1641. raise HTTPException(404, "Item not found")
  1642. await db.delete(item)
  1643. await db.commit()
  1644. return {"status": "deleted"}
  1645. @router.delete("/shopping-list")
  1646. async def clear_shopping_list(
  1647. db: AsyncSession = Depends(get_db),
  1648. _: User | None = RequireAnyPermissionIfAuthEnabled(
  1649. Permission.INVENTORY_FORECAST_WRITE, Permission.INVENTORY_UPDATE
  1650. ),
  1651. ):
  1652. """Clear all items from the shopping list."""
  1653. from backend.app.models.shopping_list import ShoppingListItem
  1654. result = await db.execute(delete(ShoppingListItem).returning(ShoppingListItem.id))
  1655. deleted = len(result.fetchall())
  1656. await db.commit()
  1657. return {"deleted": deleted}