inventory.py 102 KB

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