inventory.py 78 KB

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