inventory.py 94 KB

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