inventory.py 127 KB

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