inventory.py 150 KB

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