inventory.py 133 KB

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