inventory.py 147 KB

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