inventory.py 134 KB

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