inventory.py 95 KB

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