inventory.py 98 KB

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