inventory.py 144 KB

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