inventory.py 132 KB

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