inventory.py 150 KB

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