inventory.py 127 KB

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