inventory.py 103 KB

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