inventory.py 128 KB

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