inventory.py 84 KB

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