inventory.py 75 KB

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