spoolman_inventory.py 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583
  1. """Spoolman inventory proxy endpoints.
  2. Translates between Spoolman's data model and Bambuddy's internal
  3. InventorySpool format so the frontend can use a single unified inventory UI
  4. regardless of whether data comes from the local database or Spoolman.
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. import json
  9. import logging
  10. import re
  11. import time
  12. from contextlib import asynccontextmanager
  13. from datetime import datetime
  14. from fastapi import APIRouter, Body, Depends, HTTPException, Path, Query, Response
  15. from fastapi.responses import JSONResponse
  16. from pydantic import BaseModel, Field, field_validator, model_validator
  17. from sqlalchemy import delete, select, text
  18. from sqlalchemy.exc import IntegrityError
  19. from sqlalchemy.ext.asyncio import AsyncSession
  20. from sqlalchemy.orm import selectinload
  21. from backend.app.api.routes._spoolman_helpers import (
  22. BAMBU_LAST_DRIED_AT_KEY,
  23. BAMBU_LAST_DRIED_HOURS_KEY,
  24. BAMBU_LAST_DRIED_TEMP_KEY,
  25. NormalizedFilament,
  26. NormalizedVendorRef,
  27. _map_spoolman_spool,
  28. _safe_int,
  29. _safe_optional_float,
  30. assert_safe_spoolman_url,
  31. cost_per_kg_to_spoolman_price,
  32. spoolman_cost_per_kg,
  33. spoolman_net_weight,
  34. spoolman_price_weight,
  35. spoolman_tare,
  36. )
  37. from backend.app.core.auth import RequestPrinterScope, RequirePermissionIfAuthEnabled
  38. from backend.app.core.database import get_db
  39. from backend.app.core.permissions import Permission
  40. from backend.app.core.printer_scope import PrinterScope
  41. from backend.app.core.websocket import ws_manager
  42. from backend.app.models.ams_label import AmsLabel
  43. from backend.app.models.printer import Printer
  44. from backend.app.models.settings import Settings
  45. from backend.app.models.spool_filament_preset import SpoolmanFilamentPreset
  46. from backend.app.models.spoolman_k_profile import SpoolmanKProfile
  47. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  48. from backend.app.models.supplier import SpoolmanSpoolSupplier, Supplier
  49. from backend.app.models.user import User
  50. from backend.app.schemas.spool import SpoolFilamentPresetBase, SpoolKProfileBase, naive_utc
  51. from backend.app.schemas.spoolman import SlotAmsId, SlotTrayId, SpoolmanFilamentPatch, SpoolmanSlotAssignmentEnriched
  52. from backend.app.schemas.supplier import SpoolSupplierLinkInput
  53. from backend.app.services import slot_unlink_grace
  54. from backend.app.services.location_service import (
  55. enrich_spool_dicts_with_location_id,
  56. maybe_sync_spoolman_locations,
  57. resolve_spoolman_location_string,
  58. )
  59. from backend.app.services.printer_manager import PrinterManager, printer_manager
  60. from backend.app.services.slicer_filament_resolver import resolve_slicer_filament
  61. from backend.app.services.slot_nozzle import resolve_slot_nozzle
  62. from backend.app.services.spool_filament_preset import forget_spoolman_spool_own_preset, resolve_spoolman_preset
  63. from backend.app.services.spoolman import (
  64. SpoolmanClient,
  65. SpoolmanClientError,
  66. SpoolmanNotFoundError,
  67. SpoolmanUnavailableError,
  68. get_spoolman_client,
  69. init_spoolman_client,
  70. )
  71. from backend.app.services.spoolman_tracking import get_fallback_spool_tag_for_slot, is_slot_fallback_tag
  72. from backend.app.services.tag_conflict import tag_already_linked
  73. from backend.app.utils.color_utils import spoolman_color_hex
  74. from backend.app.utils.filament_finish import finish_generic_id
  75. from backend.app.utils.filament_ids import (
  76. GENERIC_FILAMENT_IDS,
  77. filament_id_to_setting_id,
  78. normalize_slicer_filament,
  79. )
  80. from backend.app.utils.filament_types import nozzle_temp_range, printer_filament_type
  81. logger = logging.getLogger(__name__)
  82. router = APIRouter(prefix="/spoolman/inventory", tags=["spoolman-inventory"])
  83. # Cache the last successful health-check timestamp to avoid a round-trip on
  84. # every request. A failed check clears the cache immediately.
  85. _health_check_cache: dict[str, float] = {}
  86. _HEALTH_CHECK_TTL = 30.0 # seconds
  87. def _tag_cleared(val: str | None) -> bool:
  88. """Return True when a PATCH field explicitly removes a tag (null)."""
  89. return val is None
  90. async def _clear_stale_tag_links(
  91. client: SpoolmanClient,
  92. *,
  93. tag: str,
  94. keep_spool_id: int,
  95. log_context: str,
  96. ) -> int:
  97. """Clear extra.tag on OTHER spools still claiming the given tag (#1457).
  98. A given AMS slot tag — whether a real RFID (tray_uuid/tag_uid) or the
  99. deterministic fallback derived from (printer_serial, ams_id, tray_id) for
  100. non-RFID slots — uniquely identifies one physical slot. When a spool is
  101. (re)bound to that slot via Assign or Link, any other Spoolman spool whose
  102. extra.tag still holds the same value is stale and would resurface in the
  103. hover card / fill-level lookup.
  104. Best-effort: per-spool patch failures are logged and skipped, never raised.
  105. Returns the number of spools cleared.
  106. """
  107. if not tag:
  108. return 0
  109. tag_upper = tag.upper()
  110. try:
  111. spools = await client.get_spools()
  112. except (SpoolmanClientError, SpoolmanUnavailableError) as exc:
  113. logger.warning("Could not enumerate spools for stale-tag cleanup: %s", exc)
  114. return 0
  115. cleared = 0
  116. for spool in spools:
  117. spool_id = spool.get("id")
  118. if not spool_id or spool_id == keep_spool_id:
  119. continue
  120. extra = spool.get("extra") or {}
  121. raw_tag = extra.get("tag", "")
  122. if not raw_tag:
  123. continue
  124. clean_tag = raw_tag.strip('"').upper()
  125. if clean_tag != tag_upper:
  126. continue
  127. try:
  128. await client.merge_spool_extra(spool_id, {"tag": json.dumps("")})
  129. cleared += 1
  130. logger.info(
  131. "Cleared stale tag '%s' from Spoolman spool %s (%s; reassigned to spool %s)",
  132. tag_upper[:16],
  133. spool_id,
  134. log_context,
  135. keep_spool_id,
  136. )
  137. except (SpoolmanClientError, SpoolmanUnavailableError, SpoolmanNotFoundError) as exc:
  138. logger.warning(
  139. "Failed to clear stale tag on Spoolman spool %s: %s",
  140. spool_id,
  141. exc,
  142. )
  143. return cleared
  144. async def _clear_stale_slot_fallback_tag_links(
  145. client: SpoolmanClient,
  146. *,
  147. printer_serial: str,
  148. ams_id: int,
  149. tray_id: int,
  150. keep_spool_id: int,
  151. ) -> int:
  152. """Convenience wrapper: compute the slot's fallback tag and clear it from
  153. other spools. Used by the assign route, which identifies the slot by
  154. (printer, ams, tray) rather than by an explicit tag value.
  155. """
  156. fallback_tag = get_fallback_spool_tag_for_slot(printer_serial, ams_id, tray_id)
  157. if not fallback_tag:
  158. return 0
  159. return await _clear_stale_tag_links(
  160. client,
  161. tag=fallback_tag,
  162. keep_spool_id=keep_spool_id,
  163. log_context=f"printer={printer_serial} ams={ams_id} tray={tray_id}",
  164. )
  165. async def _get_client(db: AsyncSession) -> SpoolmanClient:
  166. """Return a validated Spoolman client (URL checked, health-checked) or raise an HTTP error."""
  167. result = await db.execute(select(Settings))
  168. settings: dict[str, str] = {s.key: s.value for s in result.scalars().all()}
  169. enabled = settings.get("spoolman_enabled", "false").lower() == "true"
  170. url = settings.get("spoolman_url", "").strip()
  171. if not enabled:
  172. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  173. if not url:
  174. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  175. # SSRF guard: reject dangerous schemes, cloud-metadata IPs (169.254.169.254, 100.100.100.200,
  176. # fd00:ec2::254), multicast and unspecified addresses — loopback and RFC-1918 ranges are
  177. # intentionally permitted (Spoolman commonly runs on the same host or home LAN).
  178. # Raises ValueError with a descriptive message on any violation.
  179. try:
  180. assert_safe_spoolman_url(url)
  181. except ValueError as exc:
  182. raise HTTPException(status_code=400, detail=str(exc)) from exc
  183. # Re-use the cached client when URL is unchanged; reinitialise on URL change (cache invalidation).
  184. client = await get_spoolman_client()
  185. if not client or client.base_url != url.rstrip("/"):
  186. try:
  187. client = await init_spoolman_client(url)
  188. except ValueError as exc:
  189. raise HTTPException(status_code=400, detail=str(exc)) from exc
  190. # Only call health_check() when the cached result has expired.
  191. # Evict stale entries when URL changes (only one Spoolman URL is active at a time).
  192. if url not in _health_check_cache and _health_check_cache:
  193. _health_check_cache.clear()
  194. now = time.monotonic()
  195. last_ok = _health_check_cache.get(url, 0.0)
  196. if now - last_ok > _HEALTH_CHECK_TTL:
  197. if not await client.health_check():
  198. _health_check_cache.pop(url, None)
  199. raise HTTPException(status_code=503, detail="Spoolman server is not reachable")
  200. _health_check_cache[url] = now
  201. return client
  202. @asynccontextmanager
  203. async def _translate_spoolman_errors():
  204. """Translate Spoolman typed exceptions to HTTP errors for all inventory endpoints."""
  205. try:
  206. yield
  207. except SpoolmanNotFoundError as exc:
  208. raise HTTPException(status_code=404, detail="Spool not found in Spoolman") from exc
  209. except SpoolmanClientError as exc:
  210. raise HTTPException(
  211. status_code=502,
  212. detail={
  213. "message": "Spoolman rejected the request",
  214. "upstream_status": exc.status_code,
  215. "upstream_body": getattr(exc, "response_text", ""),
  216. },
  217. ) from exc
  218. except SpoolmanUnavailableError as exc:
  219. raise HTTPException(status_code=503, detail="Spoolman server is not reachable") from exc
  220. def _raise_if_partial_failure(spools: list[dict], results: list, operation: str) -> None:
  221. """Raise HTTP 502 if any gather result is an exception, logging each failure."""
  222. failures = [(s["id"], r) for s, r in zip(spools, results, strict=True) if isinstance(r, BaseException)]
  223. if failures:
  224. logger.error(
  225. "Partial %s failure: %d/%d spools failed: %s",
  226. operation,
  227. len(failures),
  228. len(spools),
  229. [(sid, type(exc).__name__) for sid, exc in failures],
  230. )
  231. raise HTTPException(
  232. status_code=502,
  233. detail=f"{operation} partially applied: {len(spools) - len(failures)}/{len(spools)} spools updated",
  234. )
  235. async def _apply_price_if_set(client: SpoolmanClient, spool: dict, cost_per_kg: float | None) -> tuple[dict, list[str]]:
  236. """Patch the spool price; return (updated_spool, warnings).
  237. Spoolman's spool price is what the whole spool cost, so the per-kg rate is
  238. converted at the net weight of the spool Spoolman just created (#3194).
  239. Returns the original spool and a non-empty warnings list when the price
  240. update fails, so the caller can return HTTP 207 instead of silently
  241. discarding the price.
  242. """
  243. if cost_per_kg is None:
  244. return spool, []
  245. try:
  246. async with _translate_spoolman_errors():
  247. updated = await client.update_spool_full(
  248. spool["id"], price=cost_per_kg_to_spoolman_price(cost_per_kg, spoolman_price_weight(spool))
  249. )
  250. return updated, []
  251. except HTTPException as exc:
  252. if exc.status_code >= 500:
  253. raise # Propagate network/server errors — don't swallow Spoolman outages
  254. logger.warning(
  255. "Price update failed for spool %d; spool created without price (cost_per_kg=%s, status=%d)",
  256. spool["id"],
  257. cost_per_kg,
  258. exc.status_code,
  259. )
  260. return spool, [f"price_not_set: Spoolman rejected the price update (HTTP {exc.status_code})"]
  261. # ---------------------------------------------------------------------------
  262. # Request / response schemas
  263. # ---------------------------------------------------------------------------
  264. _HEX_RE = re.compile(r"^[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$")
  265. def _validate_rgba(v: str | None) -> str | None:
  266. if v is None:
  267. return v
  268. clean = v.removeprefix("#")
  269. if not _HEX_RE.match(clean):
  270. raise ValueError("rgba must be a 6 or 8 character hex string (RRGGBB or RRGGBBAA)")
  271. return clean.upper()
  272. def _validate_storage_location(v: str | None) -> str | None:
  273. if v is not None and any(c in v for c in ("\r", "\n", "\x00")):
  274. raise ValueError("storage_location must not contain control characters")
  275. return v
  276. class SpoolmanInventoryCreate(BaseModel):
  277. # When spoolman_filament_id is provided the caller has already chosen a filament from the
  278. # Spoolman catalog, so material (and other metadata) are optional — the backend skips
  279. # find_or_create_filament() and uses the supplied ID directly.
  280. spoolman_filament_id: int | None = Field(None, gt=0)
  281. material: str | None = Field(None, min_length=1, max_length=64)
  282. subtype: str | None = Field(None, max_length=64)
  283. brand: str | None = Field(None, max_length=128)
  284. color_name: str | None = Field(None, max_length=64)
  285. rgba: str | None = Field(None, max_length=8, description="6-digit hex (RRGGBB) or 8-digit (RRGGBBAA)")
  286. label_weight: int = Field(1000, ge=1, le=100_000)
  287. # Persisted to the Spoolman spool's own `spool_weight` (tare), which takes
  288. # priority over the filament-level value both in _map_spoolman_spool and in
  289. # the weigh endpoint. Only written when the request actually sets it: the
  290. # 250 default is the display fallback, and writing it on every create would
  291. # stamp an explicit tare on spools that should keep inheriting one (#2908).
  292. core_weight: int = Field(250, ge=0, le=10_000)
  293. weight_used: float = Field(0.0, ge=0.0, le=100_000.0)
  294. note: str | None = Field(None, max_length=1000)
  295. cost_per_kg: float | None = Field(None, ge=0.0, le=1_000_000.0)
  296. storage_location: str | None = Field(None, max_length=255)
  297. location_id: int | None = Field(None, gt=0)
  298. # BambuStudio slicer preset for this spool. Spoolman has no native field
  299. # for this, so we persist it under the bambu_slicer_filament[_name] keys
  300. # in the spool's extra dict and read it back in _map_spoolman_spool.
  301. slicer_filament: str | None = Field(None, max_length=128)
  302. slicer_filament_name: str | None = Field(None, max_length=255)
  303. @field_validator("rgba")
  304. @classmethod
  305. def validate_rgba(cls, v: str | None) -> str | None:
  306. return _validate_rgba(v)
  307. @field_validator("storage_location")
  308. @classmethod
  309. def validate_storage_location(cls, v: str | None) -> str | None:
  310. return _validate_storage_location(v)
  311. @model_validator(mode="after")
  312. def validate_weight_consistency(self) -> SpoolmanInventoryCreate:
  313. # material is required only when the caller has not pre-selected a Spoolman filament
  314. if self.spoolman_filament_id is None and not self.material:
  315. raise ValueError("material is required when spoolman_filament_id is not provided")
  316. if self.weight_used > self.label_weight:
  317. raise ValueError("weight_used must not exceed label_weight")
  318. return self
  319. class SpoolmanInventoryUpdate(BaseModel):
  320. material: str | None = Field(None, min_length=1, max_length=64)
  321. subtype: str | None = Field(None, max_length=64)
  322. brand: str | None = Field(None, max_length=128)
  323. color_name: str | None = Field(None, max_length=64)
  324. rgba: str | None = Field(None, max_length=8, description="6-digit hex (RRGGBB) or 8-digit (RRGGBBAA)")
  325. label_weight: int | None = Field(None, ge=1, le=100_000)
  326. # Persisted to the spool's own `spool_weight` (see the Create schema).
  327. # Omitted / null leaves the current value alone, as with every other field
  328. # here. There is no per-spool "go back to inheriting" through this route;
  329. # the filament-level route already owns that decision (#2908).
  330. core_weight: int | None = Field(None, ge=0, le=10_000)
  331. weight_used: float | None = Field(None, ge=0.0, le=100_000.0)
  332. note: str | None = Field(None, max_length=1000)
  333. cost_per_kg: float | None = Field(None, ge=0.0, le=1_000_000.0)
  334. tag_uid: str | None = Field(None, min_length=8, max_length=30, pattern=r"^[0-9A-Fa-f]+$")
  335. tray_uuid: str | None = Field(None, min_length=32, max_length=32, pattern=r"^[0-9A-Fa-f]+$")
  336. storage_location: str | None = Field(None, max_length=255)
  337. location_id: int | None = Field(None, gt=0)
  338. # BambuStudio slicer preset — persisted to Spoolman extra dict (see Create
  339. # schema). Pass an empty string to clear; null/omitted leaves unchanged.
  340. slicer_filament: str | None = Field(None, max_length=128)
  341. slicer_filament_name: str | None = Field(None, max_length=255)
  342. # Set by hand for a drying done outside an AMS; null clears it. Persisted
  343. # to the spool's extra dict like the slicer preset (#2863).
  344. last_dried_at: datetime | None = None
  345. @field_validator("rgba")
  346. @classmethod
  347. def validate_rgba(cls, v: str | None) -> str | None:
  348. return _validate_rgba(v)
  349. @field_validator("storage_location")
  350. @classmethod
  351. def validate_storage_location(cls, v: str | None) -> str | None:
  352. return _validate_storage_location(v)
  353. @field_validator("last_dried_at")
  354. @classmethod
  355. def validate_last_dried_at(cls, v: datetime | None) -> datetime | None:
  356. return naive_utc(v)
  357. @model_validator(mode="after")
  358. def validate_tag_fields(self) -> SpoolmanInventoryUpdate:
  359. # null = remove tag; non-null values rejected (use /tag endpoint to write tags)
  360. if self.tag_uid is not None:
  361. raise ValueError("tag_uid cannot be set via this endpoint; use PATCH /spools/{id}/tag to write tags")
  362. if self.tray_uuid is not None:
  363. raise ValueError("tray_uuid cannot be set via this endpoint; use PATCH /spools/{id}/tag to write tags")
  364. return self
  365. @model_validator(mode="after")
  366. def validate_weight_consistency(self) -> SpoolmanInventoryUpdate:
  367. if self.weight_used is not None and self.label_weight is not None:
  368. if self.weight_used > self.label_weight:
  369. raise ValueError("weight_used must not exceed label_weight")
  370. return self
  371. class SpoolmanInventoryBulkCreate(BaseModel):
  372. spool: SpoolmanInventoryCreate
  373. quantity: int = Field(1, ge=1, le=50)
  374. class SpoolWeightUpdate(BaseModel):
  375. weight_grams: float = Field(..., ge=0.0, le=100_000.0)
  376. class SpoolTagLinkRequest(BaseModel):
  377. # Minimum 8 hex chars = 4-byte NFC UID (Bambu Lab hardware tags use 4-byte UIDs).
  378. tag_uid: str | None = Field(None, min_length=8, max_length=30, pattern=r"^[0-9A-Fa-f]+$")
  379. tray_uuid: str | None = Field(None, min_length=32, max_length=32, pattern=r"^[0-9A-Fa-f]+$")
  380. @field_validator("tag_uid")
  381. @classmethod
  382. def tag_uid_not_all_zeros(cls, v: str | None) -> str | None:
  383. if v is not None and all(c in "0" for c in v):
  384. raise ValueError("tag_uid must not be all-zero bytes")
  385. return v
  386. @model_validator(mode="after")
  387. def at_least_one(self) -> SpoolTagLinkRequest:
  388. if not self.tag_uid and not self.tray_uuid:
  389. raise ValueError("tag_uid or tray_uuid is required")
  390. return self
  391. class SpoolSlotAssignmentRequest(BaseModel):
  392. spoolman_spool_id: int = Field(..., gt=0)
  393. printer_id: int = Field(..., gt=0)
  394. ams_id: SlotAmsId
  395. tray_id: SlotTrayId
  396. # ---------------------------------------------------------------------------
  397. # Endpoints
  398. # ---------------------------------------------------------------------------
  399. @router.get("/spools")
  400. async def list_spools(
  401. include_archived: bool = Query(False),
  402. db: AsyncSession = Depends(get_db),
  403. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  404. ) -> list[dict]:
  405. """Return all Spoolman spools in the InventorySpool format."""
  406. client = await _get_client(db)
  407. # Sync after we have the route-resolved client so tests that patch the
  408. # route module's get_spoolman_client/init_spoolman_client also catch the
  409. # sync's client lookup — otherwise the location_service path imports from
  410. # backend.app.services.spoolman directly and bypasses the patch.
  411. if await maybe_sync_spoolman_locations(db, client=client):
  412. await db.commit()
  413. async with _translate_spoolman_errors():
  414. spools = await client.get_all_spools(allow_archived=include_archived)
  415. mapped: list[dict] = []
  416. spool_ids: list[int] = []
  417. for s in spools:
  418. try:
  419. m = _map_spoolman_spool(s)
  420. mapped.append(m)
  421. spool_ids.append(m["id"])
  422. except ValueError as exc:
  423. logger.warning("Skipping malformed Spoolman spool (id=%r): %s", s.get("id"), exc)
  424. if spool_ids:
  425. kp_result = await db.execute(select(SpoolmanKProfile).where(SpoolmanKProfile.spoolman_spool_id.in_(spool_ids)))
  426. kp_by_spool: dict[int, list[dict]] = {}
  427. for kp in kp_result.scalars().all():
  428. kp_by_spool.setdefault(kp.spoolman_spool_id, []).append(_k_profile_to_dict(kp))
  429. for m in mapped:
  430. m["k_profiles"] = kp_by_spool.get(m["id"], [])
  431. # Supplier assignments (#2988) live Bambuddy-side even for Spoolman
  432. # spools, so the list carries them in both modes identically.
  433. link_result = await db.execute(
  434. select(SpoolmanSpoolSupplier)
  435. .options(selectinload(SpoolmanSpoolSupplier.supplier))
  436. .where(SpoolmanSpoolSupplier.spoolman_spool_id.in_(spool_ids))
  437. )
  438. links_by_spool: dict[int, list[dict]] = {}
  439. for link in link_result.scalars().all():
  440. links_by_spool.setdefault(link.spoolman_spool_id, []).append(_supplier_link_to_dict(link))
  441. for m in mapped:
  442. m["suppliers"] = links_by_spool.get(m["id"], [])
  443. await enrich_spool_dicts_with_location_id(db, mapped)
  444. return mapped
  445. @router.get("/spools/{spool_id}")
  446. async def get_spool(
  447. spool_id: int = Path(..., gt=0),
  448. db: AsyncSession = Depends(get_db),
  449. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  450. ) -> dict:
  451. """Return a single Spoolman spool in the InventorySpool format."""
  452. client = await _get_client(db)
  453. async with _translate_spoolman_errors():
  454. spool = await client.get_spool(spool_id)
  455. try:
  456. mapped = _map_spoolman_spool(spool)
  457. except ValueError as exc:
  458. logger.warning("Malformed Spoolman spool (id=%r): %s", spool_id, exc)
  459. raise HTTPException(status_code=502, detail="Spoolman returned malformed spool data") from exc
  460. kp_result = await db.execute(select(SpoolmanKProfile).where(SpoolmanKProfile.spoolman_spool_id == spool_id))
  461. mapped["k_profiles"] = [_k_profile_to_dict(kp) for kp in kp_result.scalars().all()]
  462. link_result = await db.execute(
  463. select(SpoolmanSpoolSupplier)
  464. .options(selectinload(SpoolmanSpoolSupplier.supplier))
  465. .where(SpoolmanSpoolSupplier.spoolman_spool_id == spool_id)
  466. )
  467. mapped["suppliers"] = [_supplier_link_to_dict(link) for link in link_result.scalars().all()]
  468. await enrich_spool_dicts_with_location_id(db, [mapped])
  469. return mapped
  470. async def _resolve_filament_id(data: SpoolmanInventoryCreate, client: SpoolmanClient) -> int:
  471. """Return the Spoolman filament ID for this spool creation request.
  472. If spoolman_filament_id is set the caller pre-selected a catalog entry,
  473. so find_or_create_filament() is skipped and the ID is used directly.
  474. """
  475. if data.spoolman_filament_id is not None:
  476. return data.spoolman_filament_id
  477. # Validator guarantees material is non-None when spoolman_filament_id is None
  478. assert data.material is not None # noqa: S101
  479. # `or "808080"` on the result rather than on the input: spoolman_color_hex
  480. # returns None only for a missing value, so this is the same neutral grey the
  481. # old inline default produced, without handing an Optional to a str parameter.
  482. color_hex = spoolman_color_hex(data.rgba) or "808080"
  483. async with _translate_spoolman_errors():
  484. return await client.find_or_create_filament(
  485. material=data.material,
  486. subtype=data.subtype or "",
  487. brand=data.brand,
  488. color_hex=color_hex,
  489. label_weight=data.label_weight,
  490. color_name=data.color_name,
  491. )
  492. @router.post("/spools")
  493. async def create_spool(
  494. data: SpoolmanInventoryCreate,
  495. db: AsyncSession = Depends(get_db),
  496. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  497. ) -> dict:
  498. """Create a new spool in Spoolman, auto-creating vendor and filament as needed."""
  499. client = await _get_client(db)
  500. filament_id = await _resolve_filament_id(data, client)
  501. storage_location = data.storage_location
  502. if "location_id" in data.model_fields_set or "storage_location" in data.model_fields_set:
  503. try:
  504. storage_location, _ = await resolve_spoolman_location_string(
  505. db,
  506. location_id=data.location_id,
  507. storage_location=data.storage_location,
  508. fields_set=set(data.model_fields_set),
  509. )
  510. except ValueError as exc:
  511. raise HTTPException(status_code=400, detail=str(exc)) from exc
  512. remaining = max(0.0, data.label_weight - data.weight_used)
  513. try:
  514. async with _translate_spoolman_errors():
  515. spool = await client.create_spool(
  516. filament_id=filament_id,
  517. remaining_weight=remaining,
  518. comment=data.note or None,
  519. location=storage_location or None,
  520. spool_weight=(data.core_weight if "core_weight" in data.model_fields_set else None),
  521. # Only a label weight the caller gave: left off, Spoolman uses
  522. # the filament's weight, which is the right size for a caller
  523. # that didn't say (#3194).
  524. initial_weight=(float(data.label_weight) if "label_weight" in data.model_fields_set else None),
  525. )
  526. except HTTPException as exc:
  527. if exc.status_code == 404 and data.spoolman_filament_id is not None:
  528. raise HTTPException(
  529. status_code=404,
  530. detail=f"Filament {data.spoolman_filament_id} not found in Spoolman",
  531. ) from exc
  532. raise
  533. spool, price_warnings = await _apply_price_if_set(client, spool, data.cost_per_kg)
  534. # Persist slicer_filament AND color_name under the spool's extra dict
  535. # (mirror update_spool). Spoolman has no `color_name` field on filament
  536. # (#1357) so we own the round-trip ourselves.
  537. if data.slicer_filament is not None or data.slicer_filament_name is not None or data.color_name is not None:
  538. # Ensure extra fields are registered before write.
  539. if data.slicer_filament is not None:
  540. await client.ensure_extra_field("bambu_slicer_filament")
  541. if data.slicer_filament_name is not None:
  542. await client.ensure_extra_field("bambu_slicer_filament_name")
  543. if data.color_name is not None:
  544. await client.ensure_extra_field("bambu_color_name")
  545. new_extra: dict = {}
  546. if data.slicer_filament is not None:
  547. new_extra["bambu_slicer_filament"] = json.dumps(data.slicer_filament)
  548. if data.slicer_filament_name is not None:
  549. new_extra["bambu_slicer_filament_name"] = json.dumps(data.slicer_filament_name)
  550. if data.color_name is not None:
  551. new_extra["bambu_color_name"] = json.dumps(data.color_name)
  552. if new_extra:
  553. try:
  554. async with _translate_spoolman_errors():
  555. spool = await client.merge_spool_extra(spool["id"], new_extra)
  556. except HTTPException:
  557. # Best-effort — the spool already exists, log and continue.
  558. logger.warning(
  559. "Failed to persist slicer_filament/color_name for spool %s",
  560. spool.get("id"),
  561. )
  562. result = _map_spoolman_spool(spool)
  563. await ws_manager.broadcast({"type": "inventory_changed"})
  564. if price_warnings:
  565. return JSONResponse(status_code=207, content={**result, "warnings": price_warnings})
  566. return result
  567. @router.post("/spools/bulk")
  568. async def bulk_create_spools(
  569. payload: SpoolmanInventoryBulkCreate,
  570. db: AsyncSession = Depends(get_db),
  571. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  572. ) -> Response:
  573. """Create multiple identical spools in Spoolman."""
  574. client = await _get_client(db)
  575. data = payload.spool
  576. try:
  577. filament_id = await _resolve_filament_id(data, client)
  578. except HTTPException as exc:
  579. if exc.status_code == 404 and data.spoolman_filament_id is not None:
  580. raise HTTPException(
  581. status_code=404,
  582. detail=f"Filament {data.spoolman_filament_id} not found in Spoolman",
  583. ) from exc
  584. raise
  585. storage_location = data.storage_location
  586. if "location_id" in data.model_fields_set or "storage_location" in data.model_fields_set:
  587. try:
  588. storage_location, _ = await resolve_spoolman_location_string(
  589. db,
  590. location_id=data.location_id,
  591. storage_location=data.storage_location,
  592. fields_set=set(data.model_fields_set),
  593. )
  594. except ValueError as exc:
  595. raise HTTPException(status_code=400, detail=str(exc)) from exc
  596. remaining = max(0.0, data.label_weight - data.weight_used)
  597. created: list[dict] = []
  598. failures: list[str] = []
  599. for _ in range(payload.quantity):
  600. try:
  601. spool = await client.create_spool(
  602. filament_id=filament_id,
  603. remaining_weight=remaining,
  604. comment=data.note or None,
  605. location=storage_location or None,
  606. spool_weight=(data.core_weight if "core_weight" in data.model_fields_set else None),
  607. # Only a label weight the caller gave: left off, Spoolman uses
  608. # the filament's weight, which is the right size for a caller
  609. # that didn't say (#3194).
  610. initial_weight=(float(data.label_weight) if "label_weight" in data.model_fields_set else None),
  611. )
  612. except (SpoolmanUnavailableError, SpoolmanClientError, SpoolmanNotFoundError) as exc:
  613. logger.warning("Bulk spool creation: one spool failed: %s", exc)
  614. failures.append("spool creation failed")
  615. continue
  616. try:
  617. spool, price_warnings = await _apply_price_if_set(client, spool, data.cost_per_kg)
  618. except HTTPException as exc:
  619. logger.warning(
  620. "Bulk spool %d: price update failed (HTTP %d); spool not added to created list",
  621. spool.get("id", 0),
  622. exc.status_code,
  623. )
  624. failures.append("spool created but price update failed")
  625. continue
  626. if price_warnings:
  627. logger.warning("Bulk spool %s created without price: %s", spool.get("id"), price_warnings)
  628. created.append(_map_spoolman_spool(spool))
  629. if not created:
  630. raise HTTPException(status_code=500, detail="Failed to create any spools in Spoolman")
  631. await ws_manager.broadcast({"type": "inventory_changed"})
  632. if len(created) < payload.quantity:
  633. # Some spool creations failed — return 207 Multi-Status so the caller
  634. # can distinguish a full success from a partial one and show a useful message.
  635. return JSONResponse(
  636. status_code=207,
  637. content={
  638. "created": created,
  639. "requested_count": payload.quantity,
  640. "failed_count": payload.quantity - len(created),
  641. "failures": failures,
  642. },
  643. )
  644. return JSONResponse(status_code=200, content=created)
  645. @router.patch("/spools/{spool_id}")
  646. async def update_spool(
  647. *,
  648. spool_id: int = Path(..., gt=0),
  649. data: SpoolmanInventoryUpdate,
  650. db: AsyncSession = Depends(get_db),
  651. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  652. ) -> dict:
  653. """Update an existing Spoolman spool, re-linking the filament if metadata changed."""
  654. client = await _get_client(db)
  655. async with _translate_spoolman_errors():
  656. current = await client.get_spool(spool_id)
  657. cur_filament: dict = current.get("filament") or {}
  658. cur_vendor: dict = cur_filament.get("vendor") or {}
  659. cur_mat: str = (cur_filament.get("material") or "").strip()
  660. cur_name: str = (cur_filament.get("name") or "").strip()
  661. if cur_mat and cur_name.upper().startswith(cur_mat.upper()):
  662. cur_subtype: str = cur_name[len(cur_mat) :].strip()
  663. else:
  664. cur_subtype = cur_name
  665. # Resolve final values: use request value if provided, else keep current
  666. material = data.material if data.material is not None else cur_mat
  667. subtype = data.subtype if data.subtype is not None else cur_subtype
  668. brand = data.brand if data.brand is not None else (cur_vendor.get("name") or None)
  669. # color_name uses model_fields_set so explicit null (clear) is distinguishable
  670. # from "field omitted" (don't touch). find_or_create_filament's convention:
  671. # None = don't touch, "" = explicit clear, "value" = set.
  672. if "color_name" in data.model_fields_set:
  673. color_name = data.color_name if data.color_name is not None else ""
  674. else:
  675. color_name = cur_filament.get("color_name") or None
  676. cur_color = (cur_filament.get("color_hex") or "808080").upper().removeprefix("#")
  677. # Handed over as stored. The opaque alpha this used to append was folded
  678. # straight back off by `spoolman_color_hex` below, so the two paths landed on
  679. # the same string and the append only obscured which shape was in hand (#2912).
  680. rgba = data.rgba if data.rgba is not None else cur_color
  681. # The label weight is the spool's own net weight (initial_weight), not the
  682. # filament's: one filament can have spools of different sizes (#3194).
  683. # The form shows it in whole grams, so it only counts as changed when it
  684. # differs from that; the exact stored value is otherwise left alone. A
  685. # spool with no size at either level takes the one it is given: Spoolman
  686. # refuses a remaining_weight until the spool has one.
  687. cur_net_weight = spoolman_net_weight(current)
  688. cur_has_size = cur_net_weight is not None and cur_net_weight > 0
  689. cur_label_weight = _safe_int(cur_net_weight, 1000) or 1000
  690. label_weight = data.label_weight if data.label_weight is not None else cur_label_weight
  691. label_weight_changed = data.label_weight is not None and (not cur_has_size or data.label_weight != cur_label_weight)
  692. # Default weight_used from the synthetic mapping (label - remaining) so an
  693. # edit that doesn't touch the weight field preserves Spoolman's real
  694. # remaining_weight after a "Reset usage to 0" — the previous code read
  695. # Spoolman's used_weight directly, which is 0 post-reset, so
  696. # `remaining = label - 0 = 1000` would overwrite the real remaining
  697. # the next time the user edited any other field (#1390).
  698. cur_remaining_raw = current.get("remaining_weight")
  699. if cur_remaining_raw is not None:
  700. synthetic_used = max(0.0, float(label_weight) - float(cur_remaining_raw))
  701. else:
  702. synthetic_used = float(current.get("used_weight") or 0)
  703. weight_used = data.weight_used if data.weight_used is not None else synthetic_used
  704. note = data.note if data.note is not None else current.get("comment")
  705. storage_location_changed = "storage_location" in data.model_fields_set or "location_id" in data.model_fields_set
  706. storage_location = data.storage_location if "storage_location" in data.model_fields_set else None
  707. if storage_location_changed:
  708. try:
  709. storage_location, _ = await resolve_spoolman_location_string(
  710. db,
  711. location_id=data.location_id,
  712. storage_location=storage_location,
  713. fields_set=set(data.model_fields_set),
  714. )
  715. except ValueError as exc:
  716. raise HTTPException(status_code=400, detail=str(exc)) from exc
  717. color_hex = spoolman_color_hex(rgba) or rgba
  718. # Resolve which filament this spool should be linked to AFTER the edit.
  719. #
  720. # The old behaviour was always `find_or_create_filament`, which proliferated
  721. # duplicate Spoolman filaments whenever the user changed any field that
  722. # made up the match key (material/subtype/brand/color) — every edit minted
  723. # a fresh row and orphaned the previous one (#1357 follow-up). To match
  724. # internal-mode behaviour ([[feedback_inventory_modes_parity]]: editing a
  725. # spool does not proliferate new entities), prefer PATCHing the current
  726. # filament in place when it's a singleton.
  727. cur_filament_id = cur_filament.get("id")
  728. desired_name = f"{material} {subtype}".strip() if subtype else material
  729. # Compare the stored shapes, not raw strings and not bare RGB prefixes. Raw
  730. # strings make an opaque spool's six characters differ from an incoming eight
  731. # and PATCH the filament on every no-op edit; bare prefixes make an
  732. # alpha-only edit invisible so the change never lands (#2912).
  733. cur_color_norm = spoolman_color_hex(cur_filament.get("color_hex")) or ""
  734. cur_vendor_name = (cur_vendor.get("name") or "").strip()
  735. # The label weight is not part of this: it is written to the spool's
  736. # initial_weight below. Comparing it against the filament's weight PATCHed
  737. # the filament for every spool of another size, or on a shared filament
  738. # relinked the spool to a new duplicate one (#3194).
  739. metadata_unchanged = (
  740. cur_filament_id
  741. and (cur_filament.get("name") or "").strip() == desired_name
  742. and (cur_filament.get("material") or "").upper() == material.upper()
  743. and cur_color_norm == (color_hex or "").upper()
  744. and cur_vendor_name.lower() == ((brand or "").strip().lower())
  745. )
  746. if metadata_unchanged:
  747. # No filament-side change at all — re-use the existing link, skip
  748. # find_or_create entirely so a no-op edit (e.g. just changing
  749. # weight_used or note) never even touches the filament catalogue.
  750. filament_id = cur_filament_id
  751. else:
  752. async with _translate_spoolman_errors():
  753. shared = await client.is_filament_shared(cur_filament_id, spool_id) if cur_filament_id else False
  754. if cur_filament_id and not shared:
  755. # Singleton filament — PATCH it in place so the user's edit lands
  756. # on the row their spool already points at instead of orphaning it.
  757. patch_body: dict = {
  758. "name": desired_name,
  759. "material": material,
  760. "color_hex": color_hex,
  761. }
  762. if brand:
  763. vendor_id = await client.find_or_create_vendor(brand)
  764. patch_body["vendor_id"] = vendor_id
  765. async with _translate_spoolman_errors():
  766. await client.patch_filament(cur_filament_id, patch_body)
  767. filament_id = cur_filament_id
  768. else:
  769. # Filament is shared with other spools — PATCHing it in place would
  770. # silently rewrite their metadata too. Fall back to find-or-create
  771. # so only this spool's link moves.
  772. async with _translate_spoolman_errors():
  773. filament_id = await client.find_or_create_filament(
  774. material=material,
  775. subtype=subtype or "",
  776. brand=brand,
  777. color_hex=color_hex,
  778. label_weight=label_weight,
  779. color_name=color_name,
  780. )
  781. if not filament_id:
  782. raise HTTPException(status_code=500, detail="Failed to find or create filament in Spoolman")
  783. remaining = max(0.0, label_weight - weight_used)
  784. # The spool's size lives on the spool (initial_weight), never the filament
  785. # (#3194). A relink also sends the current size: Spoolman stamps the new
  786. # filament's weight on a spool without an initial_weight of its own.
  787. new_initial_weight: float | None = None
  788. if label_weight_changed:
  789. new_initial_weight = float(label_weight)
  790. elif filament_id != cur_filament_id and cur_has_size:
  791. new_initial_weight = cur_net_weight
  792. # Spoolman's price is per spool, the form's per kg (#3194). An unchanged
  793. # rate on an unchanged size is not written, so a no-op edit cannot move the
  794. # price by rounding. On a resize the rate is kept, as in internal mode.
  795. cur_cost_per_kg = spoolman_cost_per_kg(current)
  796. cost_per_kg = data.cost_per_kg if data.cost_per_kg is not None else cur_cost_per_kg
  797. new_price: float | None = None
  798. if cost_per_kg is not None and (label_weight_changed or cost_per_kg != cur_cost_per_kg):
  799. price_weight = float(label_weight) if label_weight_changed else spoolman_price_weight(current)
  800. new_price = cost_per_kg_to_spoolman_price(cost_per_kg, price_weight)
  801. # Tag removal: clear only the "tag" key so other custom Spoolman extra fields
  802. # set outside Bambuddy are preserved.
  803. tag_nulled = (
  804. ("tag_uid" in data.model_fields_set or "tray_uuid" in data.model_fields_set)
  805. and _tag_cleared(data.tag_uid)
  806. and _tag_cleared(data.tray_uuid)
  807. )
  808. # Serialise tag-clear + PATCH under the per-spool extra lock to prevent a
  809. # concurrent merge_spool_extra call (e.g. NFC write-back) from overwriting
  810. # the tag key between our read and our write.
  811. #
  812. # Spoolman PATCHes extra dicts by MERGING — popping "tag" from a re-fetched
  813. # dict and sending the rest doesn't clear the key (Spoolman keeps the old
  814. # value because the key wasn't in the payload). Explicitly set the tag to
  815. # a JSON-encoded empty string; read-side filters strip the quotes.
  816. async with client.extra_lock(spool_id):
  817. if tag_nulled:
  818. # Re-fetch inside the lock so we work with fresh extra data.
  819. async with _translate_spoolman_errors():
  820. fresh = await client.get_spool(spool_id)
  821. cur_extra = dict(fresh.get("extra") or {})
  822. cur_extra["tag"] = json.dumps("")
  823. extra: dict | None = cur_extra
  824. else:
  825. extra = None
  826. async with _translate_spoolman_errors():
  827. updated = await client.update_spool_full(
  828. spool_id=spool_id,
  829. filament_id=filament_id,
  830. # Without a size Spoolman rejects the whole PATCH (HTTP 400),
  831. # so a spool that still has none gets no remaining_weight.
  832. remaining_weight=(remaining if new_initial_weight is not None or cur_has_size else None),
  833. comment=note or "",
  834. price=new_price,
  835. initial_weight=new_initial_weight,
  836. extra=extra,
  837. location=storage_location or None,
  838. clear_location=storage_location_changed and not storage_location,
  839. # No model_fields_set guard here, unlike create: this schema
  840. # already defaults core_weight to None, and None is what
  841. # update_spool_full reads as "leave the tare alone". A guard
  842. # would be a second spelling of the same condition.
  843. spool_weight=data.core_weight,
  844. )
  845. # Spoolman 0.27+: the native tags go as well, or the spool would still be
  846. # found by every one of them after "Clear RFID Tag". Only once the update
  847. # went through, so a failed one leaves the spool as it was; a failure here
  848. # is reported, and clearing again removes what is left.
  849. if tag_nulled:
  850. async with _translate_spoolman_errors():
  851. await client.unlink_all_native_tags(fresh)
  852. updated = {**updated, "tags": []}
  853. # Persist BambuStudio slicer preset AND color_name under spool.extra.
  854. # Spoolman has no native fields for these — color_name was confirmed
  855. # absent from the FilamentUpdateParameters schema in 0.23.1 (#1357), so
  856. # writing `filament.color_name` was a silent no-op that left every
  857. # edit looking "not saved". They all round-trip via extra and get
  858. # unpacked in _map_spoolman_spool. Only writes when the request
  859. # explicitly set the field — passing null/omitting leaves the existing
  860. # extra entry untouched (write empty string to clear).
  861. sf_set = "slicer_filament" in data.model_fields_set
  862. sfn_set = "slicer_filament_name" in data.model_fields_set
  863. cn_set = "color_name" in data.model_fields_set
  864. dried_set = "last_dried_at" in data.model_fields_set
  865. if sf_set or sfn_set or cn_set or dried_set:
  866. # Ensure extra fields are registered (Spoolman rejects PATCHes with
  867. # unknown keys with HTTP 400). Idempotent if startup already ran this.
  868. if sf_set:
  869. await client.ensure_extra_field("bambu_slicer_filament")
  870. if sfn_set:
  871. await client.ensure_extra_field("bambu_slicer_filament_name")
  872. if cn_set:
  873. await client.ensure_extra_field("bambu_color_name")
  874. new_extra: dict = {}
  875. if sf_set:
  876. new_extra["bambu_slicer_filament"] = json.dumps(data.slicer_filament or "")
  877. if sfn_set:
  878. new_extra["bambu_slicer_filament_name"] = json.dumps(data.slicer_filament_name or "")
  879. if cn_set:
  880. new_extra["bambu_color_name"] = json.dumps(data.color_name or "")
  881. if dried_set:
  882. # A hand-set date is not the AMS cycle the temperature and hours
  883. # describe, so they are cleared with it, as in internal mode.
  884. dried_at = data.last_dried_at.isoformat(timespec="seconds") if data.last_dried_at else ""
  885. new_extra[BAMBU_LAST_DRIED_AT_KEY] = json.dumps(dried_at)
  886. new_extra[BAMBU_LAST_DRIED_TEMP_KEY] = json.dumps("")
  887. new_extra[BAMBU_LAST_DRIED_HOURS_KEY] = json.dumps("")
  888. async with _translate_spoolman_errors():
  889. updated = await client.merge_spool_extra(spool_id, new_extra)
  890. if sf_set or sfn_set:
  891. forget_spoolman_spool_own_preset(spool_id)
  892. await ws_manager.broadcast({"type": "inventory_changed"})
  893. return _map_spoolman_spool(updated)
  894. async def _release_spool_slots(db: AsyncSession, spool_id: int, *, keep_tracked: bool) -> list[tuple[int, int, int]]:
  895. """Delete a spool's slot rows; returns the freed (printer, ams, tray) slots.
  896. ``keep_tracked`` keeps the rows of a printer with a print being tracked:
  897. its usage is charged at completion by the slot's spool, which only the row
  898. knows for a spool without a tag. ``release_archived_slot_rows`` frees them
  899. once that print is reported. The caller commits, then announces.
  900. """
  901. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  902. query = select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.spoolman_spool_id == spool_id)
  903. if keep_tracked:
  904. query = query.where(SpoolmanSlotAssignment.printer_id.not_in(select(ActivePrintSpoolman.printer_id)))
  905. rows = (await db.execute(query)).scalars().all()
  906. freed = [(r.printer_id, r.ams_id, r.tray_id) for r in rows]
  907. for row in rows:
  908. await db.delete(row)
  909. return freed
  910. async def _announce_freed_slots(freed: list[tuple[int, int, int]]) -> None:
  911. for printer_id, ams_id, tray_id in freed:
  912. await ws_manager.broadcast(
  913. {"type": "spool_assignment_changed", "printer_id": printer_id, "ams_id": ams_id, "tray_id": tray_id}
  914. )
  915. async def _purge_local_rows_for_spool(db: AsyncSession, spool_id: int) -> None:
  916. """Drop the Bambuddy-side rows a deleted Spoolman spool leaves behind.
  917. Spoolman owns the spool; Bambuddy owns the K profiles, the filament preset
  918. overrides and the supplier assignments, each keyed by the remote id with no
  919. foreign key that could cascade. The K-profile and preset leaks are inert,
  920. but a leaked ``spoolman_spool_suppliers`` row keeps the supplier's
  921. reference count non-zero, so deleting that supplier answers 409 forever
  922. with no way for the user to find the phantom reference (#2988).
  923. The caller commits.
  924. """
  925. for model in (SpoolmanKProfile, SpoolmanFilamentPreset, SpoolmanSpoolSupplier):
  926. await db.execute(delete(model).where(model.spoolman_spool_id == spool_id))
  927. @router.delete("/spools/{spool_id}")
  928. async def delete_spool(
  929. spool_id: int = Path(..., gt=0),
  930. db: AsyncSession = Depends(get_db),
  931. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  932. ) -> dict:
  933. """Permanently delete a spool from Spoolman."""
  934. client = await _get_client(db)
  935. async with _translate_spoolman_errors():
  936. await client.delete_spool(spool_id)
  937. await _purge_local_rows_for_spool(db, spool_id)
  938. # Its slots go too: a row left behind points tracking and the scheduler
  939. # at an id Spoolman no longer has.
  940. freed = await _release_spool_slots(db, spool_id, keep_tracked=False)
  941. await db.commit()
  942. await ws_manager.broadcast({"type": "inventory_changed"})
  943. await _announce_freed_slots(freed)
  944. return {"status": "deleted"}
  945. @router.post("/spools/{spool_id}/archive")
  946. async def archive_spool(
  947. spool_id: int = Path(..., gt=0),
  948. db: AsyncSession = Depends(get_db),
  949. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  950. ) -> dict:
  951. """Archive a spool in Spoolman (soft-delete)."""
  952. client = await _get_client(db)
  953. async with _translate_spoolman_errors():
  954. spool = await client.set_spool_archived(spool_id, archived=True)
  955. # An archived spool gives its slots up, as in the built-in inventory.
  956. freed = await _release_spool_slots(db, spool_id, keep_tracked=True)
  957. await db.commit()
  958. await ws_manager.broadcast({"type": "inventory_changed"})
  959. await _announce_freed_slots(freed)
  960. try:
  961. mapped = _map_spoolman_spool(spool)
  962. except ValueError as exc:
  963. logger.warning("Malformed Spoolman spool (id=%r): %s", spool_id, exc)
  964. raise HTTPException(status_code=502, detail="Spoolman returned malformed spool data") from exc
  965. return mapped
  966. @router.post("/spools/{spool_id}/restore")
  967. async def restore_spool(
  968. spool_id: int = Path(..., gt=0),
  969. db: AsyncSession = Depends(get_db),
  970. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  971. ) -> dict:
  972. """Restore an archived spool in Spoolman."""
  973. client = await _get_client(db)
  974. async with _translate_spoolman_errors():
  975. spool = await client.set_spool_archived(spool_id, archived=False)
  976. try:
  977. mapped = _map_spoolman_spool(spool)
  978. except ValueError as exc:
  979. logger.warning("Malformed Spoolman spool (id=%r): %s", spool_id, exc)
  980. raise HTTPException(status_code=502, detail="Spoolman returned malformed spool data") from exc
  981. await ws_manager.broadcast({"type": "inventory_changed"})
  982. return mapped
  983. @router.post("/spools/{spool_id}/reset-consumed-counter")
  984. async def reset_spool_consumed_counter(
  985. spool_id: int = Path(..., gt=0),
  986. db: AsyncSession = Depends(get_db),
  987. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  988. ) -> dict:
  989. """Zero the displayed "Total Consumed" counter for a Spoolman spool.
  990. Spoolman has no native baseline field, so the baseline lives in
  991. ``spool.extra`` — the same mechanism internal mode uses for its
  992. ``weight_used_baseline`` column. ``_map_spoolman_spool`` folds it back in,
  993. so the Inventory page's ``weight_used - baseline`` reads 0 while every
  994. native Spoolman field is left exactly as it was.
  995. It used to PATCH ``used_weight = 0`` upstream, which is not the same thing:
  996. Spoolman recomputes ``remaining_weight`` from initial minus used, so the
  997. spool jumped back to full and the measured remaining filament was gone
  998. (#2906). Parity with the internal-mode endpoint (#1644, #1390, see also
  999. ``backend/app/api/routes/inventory.py::reset_spool_consumed_counter``).
  1000. """
  1001. client = await _get_client(db)
  1002. async with _translate_spoolman_errors():
  1003. spool = await client.reset_spool_consumed_counter(spool_id)
  1004. try:
  1005. mapped = _map_spoolman_spool(spool)
  1006. except ValueError as exc:
  1007. logger.warning("Malformed Spoolman spool (id=%r): %s", spool_id, exc)
  1008. raise HTTPException(status_code=502, detail="Spoolman returned malformed spool data") from exc
  1009. await ws_manager.broadcast({"type": "inventory_changed"})
  1010. return mapped
  1011. class SpoolmanBulkUpdateRequest(BaseModel):
  1012. ids: list[int] = Field(..., min_length=1, max_length=500)
  1013. update: SpoolmanInventoryUpdate
  1014. class SpoolmanBulkIdsRequest(BaseModel):
  1015. ids: list[int] = Field(..., min_length=1, max_length=500)
  1016. @router.post("/spools/bulk-update")
  1017. async def bulk_update_spools(
  1018. payload: SpoolmanBulkUpdateRequest,
  1019. db: AsyncSession = Depends(get_db),
  1020. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1021. ) -> dict:
  1022. """Apply the same partial update to every listed Spoolman spool.
  1023. Loops the per-spool ``update_spool`` route so the filament re-linking +
  1024. extra-dict + location-resolution rules stay in sync with the single-spool
  1025. PATCH path. Per-spool errors are collected; one bad ID doesn't abort the
  1026. batch.
  1027. """
  1028. update_fields = payload.update.model_dump(exclude_unset=True)
  1029. if not update_fields:
  1030. raise HTTPException(status_code=400, detail="update must include at least one field")
  1031. updated = 0
  1032. errors: list[dict] = []
  1033. for sid in payload.ids:
  1034. try:
  1035. await update_spool(spool_id=sid, data=payload.update, db=db, _=None)
  1036. updated += 1
  1037. except HTTPException as exc:
  1038. errors.append({"id": sid, "status": exc.status_code, "detail": exc.detail})
  1039. except Exception as exc: # noqa: BLE001 — surface unexpected failures per-row
  1040. logger.exception("Spoolman bulk-update failed for spool %s", sid)
  1041. errors.append({"id": sid, "status": 500, "detail": str(exc)})
  1042. if updated:
  1043. await ws_manager.broadcast({"type": "inventory_changed"})
  1044. return {"updated": updated, "errors": errors}
  1045. @router.post("/spools/bulk-delete")
  1046. async def bulk_delete_spools(
  1047. payload: SpoolmanBulkIdsRequest,
  1048. db: AsyncSession = Depends(get_db),
  1049. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1050. ) -> dict:
  1051. """Hard-delete every listed Spoolman spool. Per-spool failures are collected."""
  1052. client = await _get_client(db)
  1053. deleted = 0
  1054. freed: list[tuple[int, int, int]] = []
  1055. errors: list[dict] = []
  1056. for sid in payload.ids:
  1057. try:
  1058. async with _translate_spoolman_errors():
  1059. await client.delete_spool(sid)
  1060. await _purge_local_rows_for_spool(db, sid)
  1061. freed += await _release_spool_slots(db, sid, keep_tracked=False)
  1062. deleted += 1
  1063. except HTTPException as exc:
  1064. errors.append({"id": sid, "status": exc.status_code, "detail": exc.detail})
  1065. except Exception as exc: # noqa: BLE001 — surface unexpected failures per-row
  1066. logger.exception("Spoolman bulk-delete failed for spool %s", sid)
  1067. errors.append({"id": sid, "status": 500, "detail": str(exc)})
  1068. if deleted:
  1069. await db.commit()
  1070. await ws_manager.broadcast({"type": "inventory_changed"})
  1071. await _announce_freed_slots(freed)
  1072. return {"deleted": deleted, "errors": errors}
  1073. @router.post("/spools/bulk-archive")
  1074. async def bulk_archive_spools(
  1075. payload: SpoolmanBulkIdsRequest,
  1076. db: AsyncSession = Depends(get_db),
  1077. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1078. ) -> dict:
  1079. """Archive every listed Spoolman spool. Per-spool failures are collected."""
  1080. client = await _get_client(db)
  1081. archived = 0
  1082. freed: list[tuple[int, int, int]] = []
  1083. errors: list[dict] = []
  1084. for sid in payload.ids:
  1085. try:
  1086. async with _translate_spoolman_errors():
  1087. await client.set_spool_archived(sid, archived=True)
  1088. freed += await _release_spool_slots(db, sid, keep_tracked=True)
  1089. archived += 1
  1090. except HTTPException as exc:
  1091. errors.append({"id": sid, "status": exc.status_code, "detail": exc.detail})
  1092. except Exception as exc: # noqa: BLE001 — surface unexpected failures per-row
  1093. logger.exception("Spoolman bulk-archive failed for spool %s", sid)
  1094. errors.append({"id": sid, "status": 500, "detail": str(exc)})
  1095. if archived:
  1096. await db.commit()
  1097. await ws_manager.broadcast({"type": "inventory_changed"})
  1098. await _announce_freed_slots(freed)
  1099. return {"archived": archived, "errors": errors}
  1100. @router.post("/spools/bulk-restore")
  1101. async def bulk_restore_spools(
  1102. payload: SpoolmanBulkIdsRequest,
  1103. db: AsyncSession = Depends(get_db),
  1104. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1105. ) -> dict:
  1106. """Restore every listed archived Spoolman spool. Per-spool failures are collected."""
  1107. client = await _get_client(db)
  1108. restored = 0
  1109. errors: list[dict] = []
  1110. for sid in payload.ids:
  1111. try:
  1112. async with _translate_spoolman_errors():
  1113. await client.set_spool_archived(sid, archived=False)
  1114. restored += 1
  1115. except HTTPException as exc:
  1116. errors.append({"id": sid, "status": exc.status_code, "detail": exc.detail})
  1117. except Exception as exc: # noqa: BLE001 — surface unexpected failures per-row
  1118. logger.exception("Spoolman bulk-restore failed for spool %s", sid)
  1119. errors.append({"id": sid, "status": 500, "detail": str(exc)})
  1120. if restored:
  1121. await ws_manager.broadcast({"type": "inventory_changed"})
  1122. return {"restored": restored, "errors": errors}
  1123. @router.post("/spools/reset-consumed-counter-bulk")
  1124. async def bulk_reset_spool_consumed_counter(
  1125. payload: dict = Body(...),
  1126. db: AsyncSession = Depends(get_db),
  1127. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1128. ) -> dict:
  1129. """Bulk reset the "Total Consumed" counter across the given Spoolman spool IDs.
  1130. Caller passes an explicit list of IDs — no "reset all" shortcut, since
  1131. a typo on a wildcard would wipe the entire inventory's tracking.
  1132. Returns the count of spools reset and, like the other bulk actions, the
  1133. ones Spoolman refused in ``errors``: an individual failure does not abort
  1134. the batch, and a batch where every reset failed is not reported as a
  1135. success (FO-C8).
  1136. """
  1137. spool_ids = payload.get("spool_ids")
  1138. if not isinstance(spool_ids, list) or not spool_ids:
  1139. raise HTTPException(status_code=400, detail="spool_ids must be a non-empty list")
  1140. if not all(isinstance(sid, int) for sid in spool_ids):
  1141. raise HTTPException(status_code=400, detail="spool_ids must contain integers")
  1142. client = await _get_client(db)
  1143. reset_count = 0
  1144. errors: list[dict] = []
  1145. for spool_id in spool_ids:
  1146. try:
  1147. async with _translate_spoolman_errors():
  1148. await client.reset_spool_consumed_counter(spool_id)
  1149. reset_count += 1
  1150. except HTTPException as exc:
  1151. logger.warning("Spoolman reset-consumed-counter failed for spool %s: %s", spool_id, exc.detail)
  1152. errors.append({"id": spool_id, "status": exc.status_code, "detail": exc.detail})
  1153. if reset_count:
  1154. await ws_manager.broadcast({"type": "inventory_changed"})
  1155. return {"reset": reset_count, "errors": errors}
  1156. @router.patch("/spools/{spool_id}/weight")
  1157. async def sync_spool_weight(
  1158. *,
  1159. spool_id: int = Path(..., gt=0),
  1160. data: SpoolWeightUpdate,
  1161. db: AsyncSession = Depends(get_db),
  1162. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1163. ) -> dict:
  1164. """Update a spool's remaining weight from a measured gross weight.
  1165. Computes remaining = gross_weight - tare, with the tare resolved the way
  1166. Spoolman does it (spool, filament, vendor, then 250 g; see spoolman_tare).
  1167. """
  1168. client = await _get_client(db)
  1169. async with _translate_spoolman_errors():
  1170. current = await client.get_spool(spool_id)
  1171. core_weight, _source = spoolman_tare(current)
  1172. remaining = max(0.0, data.weight_grams - core_weight)
  1173. async with _translate_spoolman_errors():
  1174. updated = await client.update_spool_full(spool_id=spool_id, remaining_weight=remaining)
  1175. label_weight = _safe_int(spoolman_net_weight(updated), 1000)
  1176. weight_used = max(0.0, label_weight - remaining)
  1177. await ws_manager.broadcast({"type": "inventory_changed"})
  1178. return {"status": "ok", "weight_used": weight_used}
  1179. def _extra_tag(spool: dict) -> str:
  1180. """The tag stored in a Spoolman spool's ``extra``, normalised for comparison.
  1181. Anything that is not a string reads as no tag. ``extra`` is free-form and
  1182. edited outside Bambuddy, and ``.get("tag", "")`` does not default a key
  1183. that is present and null -- that returns None, which has no ``.strip``.
  1184. """
  1185. extra = spool.get("extra")
  1186. raw = extra.get("tag") if isinstance(extra, dict) else None
  1187. return raw.strip('"').upper() if isinstance(raw, str) else ""
  1188. @router.patch("/spools/{spool_id}/tag")
  1189. async def link_tag_to_spoolman_spool(
  1190. *,
  1191. spool_id: int = Path(..., gt=0),
  1192. data: SpoolTagLinkRequest,
  1193. db: AsyncSession = Depends(get_db),
  1194. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1195. ) -> dict:
  1196. """Write an NFC tag UID or Bambu tray UUID into Spoolman's extra.tag for a spool.
  1197. tray_uuid takes precedence over tag_uid when both are supplied.
  1198. Uses extra_lock to serialise against concurrent extra-field writes.
  1199. A tag another active spool already carries is refused with the shared
  1200. ``tag_already_linked`` 409, identical to the built-in route's (#3110).
  1201. """
  1202. client = await _get_client(db)
  1203. tag = (data.tray_uuid or data.tag_uid).upper()
  1204. tag_json = json.dumps(tag)
  1205. async with client.extra_lock(spool_id):
  1206. # Duplicate check: scan all spools for the same tag on a different spool.
  1207. # Sorted, because Spoolman has no unique constraint on extra.tag either,
  1208. # and a caller offered whichever row the scan happened to reach first
  1209. # could not tell two holders apart. The built-in route names the lowest
  1210. # id for the same reason (#3110).
  1211. #
  1212. # Sorting means every row is read, where the old loop stopped at its
  1213. # first match, so one malformed row after the holder must not be able
  1214. # to take the whole request down: _extra_tag refuses a non-string, and
  1215. # a row without an integer id cannot be named and so is not treated as
  1216. # a holder. Bambuddy only ever writes a JSON string here; a third party
  1217. # editing extra.tag in Spoolman is what puts anything else in reach.
  1218. async with _translate_spoolman_errors():
  1219. all_spools = await client.get_all_spools()
  1220. holders = sorted(
  1221. (s for s in all_spools if _extra_tag(s) == tag and isinstance(s.get("id"), int) and s["id"] != spool_id),
  1222. key=lambda s: s["id"],
  1223. )
  1224. if holders:
  1225. raise tag_already_linked("tray_uuid" if data.tray_uuid else "tag_uid", holders[0]["id"])
  1226. # Re-fetch inside the lock so cur_extra reflects any concurrent update.
  1227. async with _translate_spoolman_errors():
  1228. current = await client.get_spool(spool_id)
  1229. # Spoolman 0.27+: both identifiers become native tags of the spool, added to
  1230. # what it already carries rather than replacing it. Spoolman refuses a UID
  1231. # another spool holds with a 409 naming that spool, the same answer as above.
  1232. # Whatever this request added is taken back if anything after it fails, a
  1233. # refused second identifier or the extra.tag write, so the spool is left as
  1234. # it was found.
  1235. added: list[str] = []
  1236. try:
  1237. if await client.has_tag_api():
  1238. had = {t.get("uid") for t in current.get("tags") or []}
  1239. for field, uid in (("tray_uuid", data.tray_uuid), ("tag_uid", data.tag_uid)):
  1240. if not uid:
  1241. continue
  1242. async with _translate_spoolman_errors():
  1243. holder = await client.claim_native_tag(
  1244. spool_id, uid.upper(), "bambu" if data.tray_uuid else None
  1245. )
  1246. if holder is not None and holder != spool_id:
  1247. if holder < 0:
  1248. # A filament or a location holds it: no spool to name or move it from.
  1249. raise HTTPException(
  1250. status_code=409,
  1251. detail={
  1252. "code": "tag_linked_elsewhere",
  1253. "message": f"{field} is linked to a filament or location in Spoolman",
  1254. "field": field,
  1255. },
  1256. )
  1257. raise tag_already_linked(field, holder)
  1258. if uid.upper() not in had:
  1259. added.append(uid.upper())
  1260. cur_extra = dict(current.get("extra") or {})
  1261. cur_extra["tag"] = tag_json
  1262. async with _translate_spoolman_errors():
  1263. updated = await client.update_spool_full(spool_id=spool_id, extra=cur_extra)
  1264. except HTTPException:
  1265. for uid_added in added:
  1266. try:
  1267. await client.unlink_native_tag(spool_id, uid_added)
  1268. except (SpoolmanClientError, SpoolmanUnavailableError) as exc:
  1269. logger.warning("Could not take back native tag %s from spool %s: %s", uid_added, spool_id, exc)
  1270. raise
  1271. logger.info("Linked tag %s to Spoolman spool %s", tag, spool_id)
  1272. await ws_manager.broadcast({"type": "inventory_changed"})
  1273. return _map_spoolman_spool(updated)
  1274. _HEX_TAG_RE = re.compile(r"^[0-9A-F]{8,64}$")
  1275. _AMS_CHIP_UID_PADDING = "00000100"
  1276. @router.post("/tags/migrate")
  1277. async def migrate_tags_to_native(
  1278. dry_run: bool = Query(True, description="Only count what would move, change nothing"),
  1279. db: AsyncSession = Depends(get_db),
  1280. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1281. ) -> dict:
  1282. """Move tags from Spoolman's extra.tag into its native tags (Spoolman 0.27+).
  1283. extra.tag itself is left as it is, so older readers keep working and a
  1284. downgrade loses nothing. A slot's fallback ID is not a physical tag and
  1285. stays behind. Archived spools are skipped, and a tag an archived spool still
  1286. holds moves to the active one. A tag Spoolman holds on another active spool
  1287. is reported as a conflict for the user to settle, never moved by guessing.
  1288. """
  1289. client = await _get_client(db)
  1290. if not await client.has_tag_api():
  1291. raise HTTPException(
  1292. status_code=409,
  1293. detail={"code": "spoolman_without_tags", "message": "Spoolman 0.27 or later is required"},
  1294. )
  1295. serials = (await db.execute(select(Printer.serial_number))).scalars().all()
  1296. async with _translate_spoolman_errors():
  1297. spools = await client.get_all_spools(allow_archived=True)
  1298. # Who holds which native tag, from the listing: the dry run sees the same
  1299. # conflicts the real one would, and two spools sharing one extra.tag are
  1300. # caught on the second, with no request spent on either. Archived spools are
  1301. # listed only for this: nothing looks an archived spool up, so they get no
  1302. # tags, and one that still holds a tag gives it up to the active spool.
  1303. archived = {spool["id"] for spool in spools if spool.get("archived")}
  1304. native_holder = {t.get("uid"): spool["id"] for spool in spools for t in spool.get("tags") or []}
  1305. report: dict = {"dry_run": dry_run, "moved": [], "already": 0, "slot_ids": 0, "conflicts": []}
  1306. for spool in spools:
  1307. if spool["id"] in archived:
  1308. continue
  1309. tag = _extra_tag(spool)
  1310. if not _HEX_TAG_RE.match(tag) or set(tag) == {"0"}:
  1311. continue
  1312. if is_slot_fallback_tag(tag, serials):
  1313. report["slot_ids"] += 1
  1314. continue
  1315. # The AMS pads a Bambu chip's 4-byte UID to 8 bytes ("D3E68F32" arrives as
  1316. # "D3E68F3200000100"). The native tag is the chip's own UID, as the AMS
  1317. # sync stores it, so it matches what a reader sees.
  1318. bambu = len(tag) == 32
  1319. if len(tag) == 16 and tag.endswith(_AMS_CHIP_UID_PADDING):
  1320. tag, bambu = tag[:8], True
  1321. holder = native_holder.get(tag)
  1322. if holder == spool["id"]:
  1323. report["already"] += 1
  1324. continue
  1325. if holder in archived:
  1326. holder = None
  1327. if holder is None and not dry_run:
  1328. async with _translate_spoolman_errors():
  1329. holder = await client.claim_native_tag(spool["id"], tag, "bambu" if bambu else None)
  1330. if holder is not None:
  1331. report["conflicts"].append({"spool_id": spool["id"], "tag": tag, "holder": holder})
  1332. continue
  1333. native_holder[tag] = spool["id"]
  1334. report["moved"].append(spool["id"])
  1335. logger.info(
  1336. "Native tag migration (dry_run=%s): %d moved, %d already, %d slot ids, %d conflicts",
  1337. dry_run,
  1338. len(report["moved"]),
  1339. report["already"],
  1340. report["slot_ids"],
  1341. len(report["conflicts"]),
  1342. )
  1343. if not dry_run and report["moved"]:
  1344. await ws_manager.broadcast({"type": "inventory_changed"})
  1345. return report
  1346. @router.get("/slot-assignments/all", response_model=list[SpoolmanSlotAssignmentEnriched])
  1347. async def get_all_spoolman_slot_assignments(
  1348. printer_id: int | None = Query(None, gt=0),
  1349. db: AsyncSession = Depends(get_db),
  1350. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1351. printer_scope: PrinterScope = RequestPrinterScope,
  1352. ) -> list[SpoolmanSlotAssignmentEnriched]:
  1353. """Return all Spoolman slot assignments enriched with printer_name and ams_label.
  1354. ``printer_name`` is null only when the printer relation is missing
  1355. (cascade-deleted edge case). ``ams_label`` is null when no AmsLabel row
  1356. matches the slot's MQTT serial (or the synthetic ``f"p{pid}a{ams_id}"``
  1357. fallback key).
  1358. """
  1359. query = select(SpoolmanSlotAssignment).options(selectinload(SpoolmanSlotAssignment.printer))
  1360. if printer_id is not None:
  1361. query = query.where(SpoolmanSlotAssignment.printer_id == printer_id)
  1362. if (clause := printer_scope.where_strict(SpoolmanSlotAssignment.printer_id)) is not None:
  1363. query = query.where(clause)
  1364. result = await db.execute(query)
  1365. slots = list(result.scalars().all())
  1366. # Build (printer_id, ams_id) -> ams_serial map from live printer states.
  1367. # Same pattern as inventory.py:765-806 for the local /assignments endpoint.
  1368. printer_ids = {s.printer_id for s in slots}
  1369. serial_map: dict[tuple[int, int], str] = {}
  1370. all_statuses = printer_manager.get_all_statuses()
  1371. for pid in printer_ids:
  1372. state = all_statuses.get(pid)
  1373. if not (state and state.raw_data):
  1374. continue
  1375. # Some printer firmware variants wrap the AMS list in an outer dict
  1376. # (`{"ams": [...]}`). Mirror the defense used in sync_spoolman_ams_weights
  1377. # (line 842-844) so a wrapped payload still resolves to a list.
  1378. ams_raw = state.raw_data.get("ams", [])
  1379. if isinstance(ams_raw, dict):
  1380. ams_raw = ams_raw.get("ams", [])
  1381. if not isinstance(ams_raw, list):
  1382. continue
  1383. for ams_unit in ams_raw:
  1384. if not isinstance(ams_unit, dict):
  1385. continue
  1386. sn = str(ams_unit.get("sn") or ams_unit.get("serial_number") or "")
  1387. if not sn:
  1388. continue
  1389. try:
  1390. serial_map[(pid, int(ams_unit.get("id", 0)))] = sn
  1391. except (ValueError, TypeError):
  1392. continue
  1393. # Add synthetic fallback key (f"p{pid}a{ams_id}") for slots without a serial.
  1394. all_serials: set[str] = set(serial_map.values())
  1395. for s in slots:
  1396. if (s.printer_id, s.ams_id) not in serial_map:
  1397. all_serials.add(f"p{s.printer_id}a{s.ams_id}")
  1398. label_by_serial: dict[str, str] = {}
  1399. if all_serials:
  1400. lbl_result = await db.execute(select(AmsLabel).where(AmsLabel.ams_serial_number.in_(all_serials)))
  1401. for lbl in lbl_result.scalars().all():
  1402. label_by_serial[lbl.ams_serial_number] = lbl.label
  1403. def _ams_label_for(pid: int, ams_id: int) -> str | None:
  1404. sn = serial_map.get((pid, ams_id))
  1405. if sn and sn in label_by_serial:
  1406. return label_by_serial[sn]
  1407. if not sn:
  1408. return label_by_serial.get(f"p{pid}a{ams_id}")
  1409. return None
  1410. enriched: list[SpoolmanSlotAssignmentEnriched] = []
  1411. for s in slots:
  1412. if s.printer is None:
  1413. # FK is ondelete=CASCADE so this should be unreachable in normal
  1414. # operation; surface it loudly if a stale row ever appears.
  1415. logger.warning(
  1416. "Orphaned Spoolman slot assignment: printer_id=%d (ams=%d, tray=%d, spoolman_spool_id=%d) has no Printer row",
  1417. s.printer_id,
  1418. s.ams_id,
  1419. s.tray_id,
  1420. s.spoolman_spool_id,
  1421. )
  1422. enriched.append(
  1423. SpoolmanSlotAssignmentEnriched(
  1424. printer_id=s.printer_id,
  1425. printer_name=s.printer.name if s.printer else None,
  1426. ams_id=s.ams_id,
  1427. tray_id=s.tray_id,
  1428. spoolman_spool_id=s.spoolman_spool_id,
  1429. ams_label=_ams_label_for(s.printer_id, s.ams_id),
  1430. )
  1431. )
  1432. return enriched
  1433. @router.post("/sync-ams-weights")
  1434. async def sync_spoolman_ams_weights(
  1435. db: AsyncSession = Depends(get_db),
  1436. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1437. printer_scope: PrinterScope = RequestPrinterScope,
  1438. ):
  1439. """Sync remaining weight back to Spoolman for all slot-assigned spools.
  1440. Reads live AMS remain% from connected printers, computes
  1441. remaining = label_weight * remain% / 100, and PATCHes Spoolman.
  1442. """
  1443. client = await _get_client(db)
  1444. # Fetch all non-archived Spoolman spools once for label_weight lookup
  1445. async with _translate_spoolman_errors():
  1446. raw_spools = await client.get_all_spools(allow_archived=False)
  1447. spool_lookup: dict[int, dict] = {s["id"]: s for s in raw_spools if s.get("id") is not None}
  1448. result = await db.execute(select(SpoolmanSlotAssignment))
  1449. # Only slots on printers the caller may see (#1727)
  1450. assignments = [a for a in result.scalars().all() if printer_scope.allows(a.printer_id)]
  1451. from backend.app.services.usage_tracker import _active_sessions
  1452. synced = 0
  1453. skipped = 0
  1454. # A printing printer is left alone: its print's usage is charged when it
  1455. # completes, on top of whatever remaining weight the spool has by then.
  1456. printing = 0
  1457. def _find_tray(ams_data: list, ams_id: int, tray_id: int) -> dict | None:
  1458. if not ams_data:
  1459. return None
  1460. for ams_unit in ams_data:
  1461. if _safe_int(ams_unit.get("id"), -1) != ams_id:
  1462. continue
  1463. for tray in ams_unit.get("tray", []):
  1464. if _safe_int(tray.get("id"), -1) == tray_id:
  1465. return tray
  1466. return None
  1467. for assignment in assignments:
  1468. spool_dict = spool_lookup.get(assignment.spoolman_spool_id)
  1469. if not spool_dict:
  1470. logger.debug("Spoolman AMS sync: spool %d not found in Spoolman, skipping", assignment.spoolman_spool_id)
  1471. skipped += 1
  1472. continue
  1473. label_weight = _safe_int(spoolman_net_weight(spool_dict), 1000)
  1474. if label_weight <= 0:
  1475. logger.debug("Spoolman AMS sync: spool %d has no label_weight, skipping", assignment.spoolman_spool_id)
  1476. skipped += 1
  1477. continue
  1478. state = printer_manager.get_status(assignment.printer_id)
  1479. # A disconnected printer keeps its last report, which is not a reading.
  1480. if not state or not state.raw_data or getattr(state, "connected", True) is False:
  1481. logger.info(
  1482. "Spoolman AMS sync: printer %d not connected, skipping spool %d",
  1483. assignment.printer_id,
  1484. assignment.spoolman_spool_id,
  1485. )
  1486. skipped += 1
  1487. continue
  1488. # Until completion has charged the print its session stays open, also
  1489. # after the printer has reported the print finished.
  1490. if (
  1491. str(getattr(state, "state", "") or "").upper() in PrinterManager.ACTIVE_PRINT_STATES
  1492. or assignment.printer_id in _active_sessions
  1493. ):
  1494. logger.info(
  1495. "Spoolman AMS sync: printer %d is printing, skipping spool %d",
  1496. assignment.printer_id,
  1497. assignment.spoolman_spool_id,
  1498. )
  1499. skipped += 1
  1500. printing += 1
  1501. continue
  1502. ams_raw = state.raw_data.get("ams", [])
  1503. if isinstance(ams_raw, dict):
  1504. ams_raw = ams_raw.get("ams", [])
  1505. tray = _find_tray(ams_raw, assignment.ams_id, assignment.tray_id)
  1506. if not tray:
  1507. logger.info(
  1508. "Spoolman AMS sync: no tray data for spool %d (printer %d AMS%d-T%d)",
  1509. assignment.spoolman_spool_id,
  1510. assignment.printer_id,
  1511. assignment.ams_id,
  1512. assignment.tray_id,
  1513. )
  1514. skipped += 1
  1515. continue
  1516. remain_raw = tray.get("remain")
  1517. if remain_raw is None:
  1518. logger.debug(
  1519. "Spoolman AMS sync: no remain value for spool %d (tray %d/%d), skipping",
  1520. assignment.spoolman_spool_id,
  1521. assignment.ams_id,
  1522. assignment.tray_id,
  1523. )
  1524. skipped += 1
  1525. continue
  1526. try:
  1527. remain_val = int(remain_raw)
  1528. except (TypeError, ValueError):
  1529. logger.debug(
  1530. "Spoolman AMS sync: non-numeric remain=%r for spool %d, skipping",
  1531. remain_raw,
  1532. assignment.spoolman_spool_id,
  1533. )
  1534. skipped += 1
  1535. continue
  1536. if remain_val < 0 or remain_val > 100:
  1537. logger.debug("Spoolman AMS sync: invalid remain=%s for spool %d", remain_raw, assignment.spoolman_spool_id)
  1538. skipped += 1
  1539. continue
  1540. remaining = round(label_weight * remain_val / 100.0, 1)
  1541. try:
  1542. async with _translate_spoolman_errors():
  1543. await client.update_spool_full(assignment.spoolman_spool_id, remaining_weight=remaining)
  1544. logger.info(
  1545. "Spoolman AMS sync: spool %d remaining set to %s g (remain=%d%%)",
  1546. assignment.spoolman_spool_id,
  1547. remaining,
  1548. remain_val,
  1549. )
  1550. synced += 1
  1551. except HTTPException as exc:
  1552. if exc.status_code == 404:
  1553. logger.warning(
  1554. "Spoolman AMS sync: spool %d not found in Spoolman (404), skipping",
  1555. assignment.spoolman_spool_id,
  1556. )
  1557. else:
  1558. logger.warning(
  1559. "Spoolman AMS sync: failed to update spool %d (HTTP %d)",
  1560. assignment.spoolman_spool_id,
  1561. exc.status_code,
  1562. )
  1563. skipped += 1
  1564. return {"synced": synced, "skipped": skipped, "printing": printing}
  1565. @router.post("/slot-assignments")
  1566. async def assign_spoolman_slot(
  1567. body: SpoolSlotAssignmentRequest,
  1568. db: AsyncSession = Depends(get_db),
  1569. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1570. printer_scope: PrinterScope = RequestPrinterScope,
  1571. ) -> dict:
  1572. """Assign a Spoolman spool to a printer AMS slot (stored in local DB only).
  1573. Raises 404 if the printer does not exist or the spool is not found in Spoolman.
  1574. Spoolman's own ``spool.location`` field is NOT touched — it is user-managed.
  1575. """
  1576. client = await _get_client(db)
  1577. printer_scope.ensure(body.printer_id)
  1578. result = await db.execute(select(Printer).where(Printer.id == body.printer_id))
  1579. printer = result.scalar_one_or_none()
  1580. if not printer:
  1581. raise HTTPException(status_code=404, detail="Printer not found")
  1582. # Verify the Spoolman spool exists before committing to local DB.
  1583. # This prevents ghost rows pointing at non-existent spool IDs.
  1584. async with _translate_spoolman_errors():
  1585. spool = await client.get_spool(body.spoolman_spool_id)
  1586. # As the built-in inventory refuses it: an archived spool on a slot would
  1587. # be charged the next print's usage (SSA-8).
  1588. if spool.get("archived"):
  1589. raise HTTPException(status_code=400, detail="Cannot assign an archived spool")
  1590. # Spool confirmed in Spoolman — upsert into local slot-assignment table
  1591. # assigned_at is intentionally not refreshed on re-assign (original timestamp preserved)
  1592. try:
  1593. await db.execute(
  1594. text(
  1595. "INSERT INTO spoolman_slot_assignments"
  1596. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  1597. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  1598. " ON CONFLICT(printer_id, ams_id, tray_id)"
  1599. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  1600. ),
  1601. {
  1602. "printer_id": body.printer_id,
  1603. "ams_id": body.ams_id,
  1604. "tray_id": body.tray_id,
  1605. "spool_id": body.spoolman_spool_id,
  1606. },
  1607. )
  1608. await db.commit()
  1609. slot_unlink_grace.forget_slot(body.printer_id, body.ams_id, body.tray_id)
  1610. except Exception as exc:
  1611. await db.rollback()
  1612. logger.error("Failed to persist slot assignment: %s", exc)
  1613. raise HTTPException(status_code=500, detail="Failed to save slot assignment") from exc
  1614. # #1457: clear stale fallback-tag links on OTHER spools still bound to this
  1615. # slot. Without this, a non-RFID slot's deterministic fallback tag stays
  1616. # attached to the previous spool in Spoolman's extra.tag and re-surfaces in
  1617. # the hover card whenever the local slot assignment is removed.
  1618. if printer.serial_number:
  1619. await _clear_stale_slot_fallback_tag_links(
  1620. client,
  1621. printer_serial=printer.serial_number,
  1622. ams_id=body.ams_id,
  1623. tray_id=body.tray_id,
  1624. keep_spool_id=body.spoolman_spool_id,
  1625. )
  1626. mapped = _map_spoolman_spool(spool)
  1627. # Fetch K-profiles before the MQTT try block so we can use async DB access.
  1628. kp_rows_result = await db.execute(
  1629. select(SpoolmanKProfile).where(
  1630. SpoolmanKProfile.spoolman_spool_id == body.spoolman_spool_id,
  1631. SpoolmanKProfile.printer_id == body.printer_id,
  1632. )
  1633. )
  1634. kp_rows = kp_rows_result.scalars().all()
  1635. # Auto-configure AMS slot via MQTT (best-effort; slot assignment is already persisted)
  1636. try:
  1637. mqtt_client = printer_manager.get_client(body.printer_id)
  1638. if mqtt_client:
  1639. # Spoolman's material is free text, so it arrives as whatever the
  1640. # user typed there -- "PLA+", "PolyTerra PLA". The sub-brand keeps
  1641. # that wording; the slot's type has to be one the printer and the
  1642. # slicer know (issue #2902).
  1643. material = mapped.get("material") or ""
  1644. tray_type = printer_filament_type(material)
  1645. brand = mapped.get("brand") or ""
  1646. subtype = mapped.get("subtype") or ""
  1647. if brand:
  1648. tray_sub_brands = f"{brand} {material} {subtype}".strip()
  1649. elif subtype:
  1650. tray_sub_brands = f"{material} {subtype}".strip()
  1651. else:
  1652. tray_sub_brands = material
  1653. tray_color = (mapped.get("rgba") or "808080FF").upper()
  1654. if len(tray_color) == 6:
  1655. tray_color = tray_color + "FF"
  1656. # Printer state, read here rather than further down because the
  1657. # per-model preset override below needs the slot's nozzle
  1658. # diameter and the K-profile cascade further down needs the same
  1659. # value -- one read, so they cannot disagree. (The previous
  1660. # `mqtt_client.printer_state` access via hasattr always returned
  1661. # None -- the attribute is `state`, not `printer_state` -- so the
  1662. # K-profile cascade silently skipped state.kprofiles, defaulted
  1663. # nozzle_diameter to 0.4, and left slot_extruder unset.)
  1664. state = printer_manager.get_status(body.printer_id)
  1665. slot_nozzle = resolve_slot_nozzle(
  1666. state, body.ams_id, body.tray_id, printer_manager.get_model(body.printer_id)
  1667. )
  1668. nozzle_diameter = slot_nozzle.diameter
  1669. # Per-printer-model preset override, same cascade as internal
  1670. # mode: a cloud/Orca preset is bound to a model, so one stored
  1671. # preset per spool is wrong across two models. Returns Spoolman's
  1672. # own value when no override is set.
  1673. slot_slicer_filament, slot_slicer_filament_name = await resolve_spoolman_preset(
  1674. db,
  1675. spoolman_spool_id=body.spoolman_spool_id,
  1676. printer_model=printer_manager.get_model(body.printer_id),
  1677. nozzle_diameter=nozzle_diameter,
  1678. fallback_filament=mapped.get("slicer_filament"),
  1679. fallback_name=mapped.get("slicer_filament_name"),
  1680. )
  1681. # #1713: resolve the spool's stored slicer_filament reference
  1682. # (cloud preset, local preset, GF-prefix builtin, or numeric
  1683. # LocalPreset id) to the printer-side tray_info_idx + setting_id.
  1684. # Previously the Spoolman path dropped slicer_filament on the
  1685. # floor and only the generic-material fallback fired; the user-
  1686. # configured profile never reached the printer. Shared with the
  1687. # internal-mode route via the same helper so the two flows can't
  1688. # drift again.
  1689. tray_info_idx, setting_id, sub_brand_override, type_override = await resolve_slicer_filament(
  1690. db=db,
  1691. current_user=current_user,
  1692. slicer_filament=slot_slicer_filament,
  1693. slicer_filament_name=slot_slicer_filament_name,
  1694. material=material,
  1695. )
  1696. if sub_brand_override:
  1697. tray_sub_brands = sub_brand_override
  1698. # A preset carries its own type; the reduction above only infers
  1699. # one from Spoolman's free-text material. The preset wins when the
  1700. # spool has one (issue #2902, @doncaruana).
  1701. if type_override:
  1702. tray_type = printer_filament_type(type_override)
  1703. material_upper = material.upper().strip()
  1704. # Fall back to generic-material id when slicer_filament is empty
  1705. # or the resolver discarded an unresolvable value. Matches the
  1706. # internal-mode tail in inventory.py:_apply_spool_to_slot_inner,
  1707. # including the order: the spool's own wording first and the
  1708. # reduced type only after it, so "PETG HF" keeps its own generic
  1709. # preset (GFG96) rather than trading it for "PETG"'s GFG99.
  1710. if not tray_info_idx:
  1711. tray_info_idx = (
  1712. # The finish first, as in internal mode: a Silk spool
  1713. # gets Generic PLA Silk.
  1714. finish_generic_id(tray_type, f"{material} {subtype}")
  1715. or GENERIC_FILAMENT_IDS.get(material_upper)
  1716. or GENERIC_FILAMENT_IDS.get(material_upper.split("-")[0].split(" ")[0])
  1717. or GENERIC_FILAMENT_IDS.get(tray_type.upper())
  1718. or ""
  1719. )
  1720. # Ensure setting_id is always derivable from tray_info_idx. The
  1721. # local-preset path can leave it empty when the LP's setting JSON
  1722. # has no filament_id and falls through to the generic material id;
  1723. # without this fallback the slicer gets a half-configured slot
  1724. # (filament id without setting id) and the slot detail modal
  1725. # renders empty fields. Same pattern as the internal-mode tail.
  1726. if tray_info_idx and not setting_id:
  1727. setting_id = filament_id_to_setting_id(tray_info_idx)
  1728. temp_defaults = nozzle_temp_range(material, tray_type)
  1729. temp_min = mapped.get("nozzle_temp_min") or temp_defaults[0]
  1730. temp_max = temp_defaults[1]
  1731. # Pull printer state from printer_manager. The previous
  1732. # `mqtt_client.printer_state` access via hasattr always returned
  1733. # None (the attribute is `state`, not `printer_state`), so the
  1734. # K-profile cascade silently skipped state.kprofiles, defaulted
  1735. # nozzle_diameter to 0.4, and left slot_extruder unset.
  1736. slot_extruder = slot_nozzle.extruder
  1737. # Prefer exact extruder match, fall back to extruder-agnostic kp
  1738. # for the same nozzle. Hard-skipping on mismatch silently dropped
  1739. # valid stored profiles when the AMS-extruder mapping had shifted.
  1740. exact_kp = None
  1741. fallback_kp = None
  1742. for kp in kp_rows:
  1743. if kp.nozzle_diameter != nozzle_diameter or kp.cali_idx is None:
  1744. continue
  1745. if not slot_nozzle.flow_matches(kp.nozzle_type):
  1746. continue
  1747. if slot_extruder is not None and kp.extruder is not None and kp.extruder == slot_extruder:
  1748. exact_kp = kp
  1749. break
  1750. if fallback_kp is None:
  1751. fallback_kp = kp
  1752. matching_kp = exact_kp or fallback_kp
  1753. # Resolve the printer-side calibration entry by cali_idx so we
  1754. # know the authoritative filament_id (the printer indexes its
  1755. # calibration table by filament_id, not setting_id).
  1756. printer_kp = None
  1757. if matching_kp and state and state.kprofiles:
  1758. for pkp in state.kprofiles:
  1759. if pkp.slot_id == matching_kp.cali_idx and pkp.nozzle_diameter == nozzle_diameter:
  1760. printer_kp = pkp
  1761. break
  1762. if printer_kp is None:
  1763. logger.warning(
  1764. "Spoolman assign: cali_idx=%d not present in printer's "
  1765. "calibration table — stored kp may be stale.",
  1766. matching_kp.cali_idx,
  1767. )
  1768. # Realign the slot's filament context (tray_info_idx + setting_id)
  1769. # to the kp's calibration context. Without this, ams_filament_setting
  1770. # declares the slot under generic PLA while extrusion_cali_sel points
  1771. # the cali_idx at a different preset — the printer can't link them
  1772. # and falls back to the default profile. P-prefix local presets are
  1773. # valid for tray_info_idx; PFUS-prefix cloud-user presets are not
  1774. # (the slicer rejects them).
  1775. effective_tray_info_idx = tray_info_idx
  1776. effective_setting_id = setting_id
  1777. if printer_kp and printer_kp.filament_id:
  1778. if not printer_kp.filament_id.startswith("PFUS"):
  1779. effective_tray_info_idx = printer_kp.filament_id
  1780. if printer_kp.setting_id:
  1781. effective_setting_id = printer_kp.setting_id
  1782. elif matching_kp and matching_kp.setting_id:
  1783. derived = normalize_slicer_filament(matching_kp.setting_id)[0]
  1784. if derived and not derived.startswith("PFUS"):
  1785. effective_tray_info_idx = derived
  1786. effective_setting_id = matching_kp.setting_id
  1787. if effective_tray_info_idx != tray_info_idx or effective_setting_id != setting_id:
  1788. logger.info(
  1789. "Spoolman assign: realigning tray_info_idx %r → %r, setting_id %r → %r (kp_id=%s, source=%s)",
  1790. tray_info_idx,
  1791. effective_tray_info_idx,
  1792. setting_id,
  1793. effective_setting_id,
  1794. matching_kp.id if matching_kp else None,
  1795. "printer" if printer_kp else "stored",
  1796. )
  1797. mqtt_client.ams_set_filament_setting(
  1798. ams_id=body.ams_id,
  1799. tray_id=body.tray_id,
  1800. tray_info_idx=effective_tray_info_idx,
  1801. tray_type=tray_type,
  1802. tray_sub_brands=tray_sub_brands,
  1803. tray_color=tray_color,
  1804. nozzle_temp_min=temp_min,
  1805. nozzle_temp_max=temp_max,
  1806. setting_id=effective_setting_id,
  1807. )
  1808. if matching_kp and matching_kp.cali_idx is not None:
  1809. # Use printer-reported filament_id when available, otherwise
  1810. # fall back to the realigned tray_info_idx so both commands
  1811. # reference the same filament context.
  1812. cali_filament_id = (
  1813. printer_kp.filament_id if printer_kp and printer_kp.filament_id else None
  1814. ) or effective_tray_info_idx
  1815. mqtt_client.extrusion_cali_sel(
  1816. ams_id=body.ams_id,
  1817. tray_id=body.tray_id,
  1818. cali_idx=matching_kp.cali_idx,
  1819. filament_id=cali_filament_id,
  1820. nozzle_diameter=nozzle_diameter,
  1821. )
  1822. logger.info(
  1823. "Spoolman assign: applied K-profile cali_idx=%d "
  1824. "(kp_id=%d, filament_id=%s) for spool %d on printer %d AMS%d-T%d",
  1825. matching_kp.cali_idx,
  1826. matching_kp.id,
  1827. cali_filament_id,
  1828. body.spoolman_spool_id,
  1829. body.printer_id,
  1830. body.ams_id,
  1831. body.tray_id,
  1832. )
  1833. else:
  1834. # No stored K-profile for this spool — always reset the slot to
  1835. # Default K (cali_idx=-1). The live cali_idx belongs to whatever
  1836. # filament was there before, so preserving it would apply the
  1837. # wrong filament's calibration to the new spool.
  1838. mqtt_client.extrusion_cali_sel(
  1839. ams_id=body.ams_id,
  1840. tray_id=body.tray_id,
  1841. cali_idx=-1,
  1842. filament_id=effective_tray_info_idx,
  1843. nozzle_diameter=nozzle_diameter,
  1844. )
  1845. logger.info(
  1846. "No stored K-profile for Spoolman spool %d — reset slot to Default K (cali_idx=-1)",
  1847. body.spoolman_spool_id,
  1848. )
  1849. # Read-back verification, as the built-in assign registers it (#2582):
  1850. # the AMS pushes that follow confirm the tray took what was sent.
  1851. # Not for a slot the firmware calls empty, which echoes nothing
  1852. # back until a spool goes in (the built-in check, inventory.py).
  1853. from backend.app.api.routes.inventory import _find_tray_in_ams_data # noqa: PLC0415
  1854. from backend.app.services.ams_slot_presence import spool_present # noqa: PLC0415
  1855. live_tray = None
  1856. if state and state.raw_data:
  1857. ams_raw = state.raw_data.get("ams", [])
  1858. if isinstance(ams_raw, dict):
  1859. ams_raw = ams_raw.get("ams", [])
  1860. live_tray = _find_tray_in_ams_data(ams_raw, body.ams_id, body.tray_id)
  1861. tray_state = (live_tray or {}).get("state")
  1862. if not (spool_present(live_tray) is not True and tray_state in (9, 10)):
  1863. mqtt_client.register_assignment_verification(
  1864. ams_id=body.ams_id,
  1865. tray_id=body.tray_id,
  1866. tray_info_idx=effective_tray_info_idx,
  1867. tray_color=tray_color,
  1868. cali_idx=matching_kp.cali_idx if matching_kp and matching_kp.cali_idx is not None else -1,
  1869. )
  1870. # Fresh telemetry for the check to compare against.
  1871. mqtt_client.request_status_update()
  1872. logger.info(
  1873. "Auto-configured AMS slot ams=%d tray=%d for Spoolman spool %d on printer %d",
  1874. body.ams_id,
  1875. body.tray_id,
  1876. body.spoolman_spool_id,
  1877. body.printer_id,
  1878. )
  1879. except Exception:
  1880. logger.exception(
  1881. "Failed to auto-configure AMS slot for Spoolman spool %d (printer=%d, ams=%d, tray=%d)",
  1882. body.spoolman_spool_id,
  1883. body.printer_id,
  1884. body.ams_id,
  1885. body.tray_id,
  1886. )
  1887. return mapped
  1888. @router.delete("/slot-assignments/{spoolman_spool_id}")
  1889. async def unassign_spoolman_slot(
  1890. spoolman_spool_id: int = Path(..., gt=0),
  1891. db: AsyncSession = Depends(get_db),
  1892. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1893. printer_scope: PrinterScope = RequestPrinterScope,
  1894. ) -> dict:
  1895. """Remove the local slot assignment for a Spoolman spool.
  1896. Spoolman's own ``spool.location`` field is NOT touched — it is user-managed.
  1897. """
  1898. client = await _get_client(db)
  1899. try:
  1900. # A slot on a printer the caller can't see stays assigned (#1727)
  1901. unassign = delete(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.spoolman_spool_id == spoolman_spool_id)
  1902. if (clause := printer_scope.where_strict(SpoolmanSlotAssignment.printer_id)) is not None:
  1903. unassign = unassign.where(clause)
  1904. await db.execute(unassign)
  1905. await db.commit()
  1906. except Exception as exc:
  1907. await db.rollback()
  1908. logger.error("Failed to delete slot assignment: %s", exc)
  1909. raise HTTPException(status_code=500, detail="Failed to remove slot assignment") from exc
  1910. # Fetch the spool from Spoolman to return in InventorySpool format.
  1911. # If the spool no longer exists in Spoolman, the local unassignment still succeeded.
  1912. try:
  1913. async with _translate_spoolman_errors():
  1914. spool = await client.get_spool(spoolman_spool_id)
  1915. return _map_spoolman_spool(spool)
  1916. except HTTPException as exc:
  1917. if exc.status_code != 404:
  1918. raise
  1919. # Spool no longer exists in Spoolman; unassignment still succeeded.
  1920. return {"id": spoolman_spool_id}
  1921. @router.get("/slot-assignments")
  1922. async def get_spoolman_slot_assignment(
  1923. printer_id: int = Query(..., gt=0),
  1924. ams_id: int = Query(..., ge=0, le=7),
  1925. tray_id: int = Query(..., ge=0, le=3),
  1926. db: AsyncSession = Depends(get_db),
  1927. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1928. printer_scope: PrinterScope = RequestPrinterScope,
  1929. ) -> dict | None:
  1930. """Return the Spoolman spool assigned to a specific printer slot, or null if unassigned."""
  1931. client = await _get_client(db)
  1932. printer_scope.ensure(printer_id)
  1933. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1934. printer = result.scalar_one_or_none()
  1935. if not printer:
  1936. raise HTTPException(status_code=404, detail="Printer not found")
  1937. slot_result = await db.execute(
  1938. select(SpoolmanSlotAssignment).where(
  1939. SpoolmanSlotAssignment.printer_id == printer_id,
  1940. SpoolmanSlotAssignment.ams_id == ams_id,
  1941. SpoolmanSlotAssignment.tray_id == tray_id,
  1942. )
  1943. )
  1944. slot = slot_result.scalar_one_or_none()
  1945. if not slot:
  1946. return None
  1947. try:
  1948. async with _translate_spoolman_errors():
  1949. spool = await client.get_spool(slot.spoolman_spool_id)
  1950. return _map_spoolman_spool(spool)
  1951. except HTTPException as exc:
  1952. if exc.status_code != 404:
  1953. raise
  1954. # Spool deleted in Spoolman — clean up stale assignment.
  1955. # Include spoolman_spool_id in WHERE to avoid a TOCTOU race where a
  1956. # concurrent re-assign changed the slot to a different spool between
  1957. # the GET and this DELETE.
  1958. try:
  1959. await db.execute(
  1960. delete(SpoolmanSlotAssignment).where(
  1961. SpoolmanSlotAssignment.id == slot.id,
  1962. SpoolmanSlotAssignment.spoolman_spool_id == slot.spoolman_spool_id,
  1963. )
  1964. )
  1965. await db.commit()
  1966. except Exception as cleanup_exc:
  1967. await db.rollback()
  1968. logger.warning(
  1969. "Failed to remove stale slot assignment for spool %s: %s",
  1970. slot.spoolman_spool_id,
  1971. cleanup_exc,
  1972. )
  1973. return None
  1974. def _k_profile_to_dict(p: SpoolmanKProfile) -> dict:
  1975. """Manually map SpoolmanKProfile → SpoolKProfileResponse-compatible dict."""
  1976. return {
  1977. "id": p.id,
  1978. "spool_id": p.spoolman_spool_id,
  1979. "printer_id": p.printer_id,
  1980. "extruder": p.extruder,
  1981. "nozzle_diameter": p.nozzle_diameter,
  1982. "nozzle_type": p.nozzle_type,
  1983. "k_value": p.k_value,
  1984. "name": p.name,
  1985. "cali_idx": p.cali_idx,
  1986. "setting_id": p.setting_id,
  1987. "created_at": p.created_at,
  1988. }
  1989. def _filament_preset_to_dict(p: SpoolmanFilamentPreset) -> dict:
  1990. """Manually map SpoolmanFilamentPreset → SpoolFilamentPresetResponse-compatible dict."""
  1991. return {
  1992. "id": p.id,
  1993. "spool_id": p.spoolman_spool_id,
  1994. "printer_model": p.printer_model,
  1995. "nozzle_diameter": p.nozzle_diameter,
  1996. "slicer_filament": p.slicer_filament,
  1997. "slicer_filament_name": p.slicer_filament_name,
  1998. "created_at": p.created_at,
  1999. }
  2000. @router.get("/spools/{spool_id}/filament-presets")
  2001. async def get_spoolman_filament_presets(
  2002. spool_id: int = Path(..., gt=0),
  2003. db: AsyncSession = Depends(get_db),
  2004. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  2005. ) -> list[dict]:
  2006. """Return all per-printer-model preset overrides for a Spoolman spool."""
  2007. await _get_client(db)
  2008. result = await db.execute(
  2009. select(SpoolmanFilamentPreset).where(SpoolmanFilamentPreset.spoolman_spool_id == spool_id)
  2010. )
  2011. return [_filament_preset_to_dict(p) for p in result.scalars().all()]
  2012. @router.put("/spools/{spool_id}/filament-presets")
  2013. async def save_spoolman_filament_presets(
  2014. spool_id: int = Path(..., gt=0),
  2015. presets: list[SpoolFilamentPresetBase] = Body(...),
  2016. db: AsyncSession = Depends(get_db),
  2017. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  2018. ) -> list[dict]:
  2019. """Replace all per-printer-model preset overrides for a Spoolman spool."""
  2020. client = await _get_client(db)
  2021. async with _translate_spoolman_errors():
  2022. await client.get_spool(spool_id)
  2023. # Same as the internal route: reject a duplicated (model, diameter) before
  2024. # touching the stored rows, so a bad payload cannot clear what it fails to
  2025. # replace.
  2026. seen: set[tuple[str, str]] = set()
  2027. for preset in presets:
  2028. key = (preset.printer_model, preset.nozzle_diameter)
  2029. if key in seen:
  2030. raise HTTPException(
  2031. 422,
  2032. f"Duplicate override for model {preset.printer_model!r} nozzle {preset.nozzle_diameter or 'any'!r}",
  2033. )
  2034. seen.add(key)
  2035. saved: list[SpoolmanFilamentPreset] = []
  2036. try:
  2037. await db.execute(delete(SpoolmanFilamentPreset).where(SpoolmanFilamentPreset.spoolman_spool_id == spool_id))
  2038. await db.flush()
  2039. for preset in presets:
  2040. obj = SpoolmanFilamentPreset(
  2041. spoolman_spool_id=spool_id,
  2042. printer_model=preset.printer_model,
  2043. nozzle_diameter=preset.nozzle_diameter,
  2044. slicer_filament=preset.slicer_filament,
  2045. slicer_filament_name=preset.slicer_filament_name,
  2046. )
  2047. db.add(obj)
  2048. saved.append(obj)
  2049. await db.commit()
  2050. except IntegrityError as exc:
  2051. await db.rollback()
  2052. raise HTTPException(422, "Duplicate or invalid preset override (check model and nozzle uniqueness)") from exc
  2053. except HTTPException:
  2054. raise
  2055. except Exception as exc:
  2056. await db.rollback()
  2057. logger.error("Filament preset save for spool %d failed: %s", spool_id, exc)
  2058. raise HTTPException(500, "Failed to save filament presets") from exc
  2059. for obj in saved:
  2060. await db.refresh(obj)
  2061. return [_filament_preset_to_dict(p) for p in saved]
  2062. def _normalize_filament(raw: dict) -> NormalizedFilament | None:
  2063. """Normalise a raw Spoolman filament dict for the frontend catalog picker.
  2064. Returns None for entries with missing/zero IDs — those are malformed and
  2065. must be filtered out before returning to the client.
  2066. weight=0 is collapsed to None — 0g is not a valid filament weight.
  2067. """
  2068. filament_id = _safe_int(raw.get("id"), 0)
  2069. if filament_id <= 0:
  2070. logger.warning("Skipping Spoolman filament with missing or invalid id: %r", raw.get("name"))
  2071. return None
  2072. vendor = raw.get("vendor") or {}
  2073. vendor_ref: NormalizedVendorRef | None = None
  2074. if vendor:
  2075. vendor_id = _safe_int(vendor.get("id"), 0)
  2076. if vendor_id <= 0:
  2077. logger.warning("Spoolman filament %d has vendor without valid id — vendor omitted", filament_id)
  2078. else:
  2079. vendor_ref = {"id": vendor_id, "name": str(vendor.get("name") or "").strip() or "Unknown"}
  2080. return NormalizedFilament(
  2081. id=filament_id,
  2082. name=str(raw.get("name") or ""),
  2083. material=raw.get("material") or None,
  2084. color_hex=raw.get("color_hex") or None,
  2085. color_name=raw.get("color_name") or None,
  2086. weight=_safe_int(raw.get("weight"), 0) or None, # 0g is not a valid weight
  2087. spool_weight=_safe_optional_float(raw.get("spool_weight")),
  2088. vendor=vendor_ref,
  2089. )
  2090. @router.get("/filaments")
  2091. async def list_spoolman_filaments(
  2092. db: AsyncSession = Depends(get_db),
  2093. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  2094. ) -> list[NormalizedFilament]:
  2095. """Return all filaments from Spoolman, normalised for the frontend catalog picker."""
  2096. client = await _get_client(db)
  2097. async with _translate_spoolman_errors():
  2098. raw_filaments = await client.get_filaments()
  2099. if not isinstance(raw_filaments, list):
  2100. logger.warning("Spoolman get_filaments() returned non-list type: %s", type(raw_filaments).__name__)
  2101. return []
  2102. return [f for raw in raw_filaments if (f := _normalize_filament(raw)) is not None]
  2103. @router.patch("/filaments/{filament_id}")
  2104. async def patch_spoolman_filament(
  2105. *,
  2106. filament_id: int = Path(..., gt=0),
  2107. body: SpoolmanFilamentPatch = Body(...),
  2108. db: AsyncSession = Depends(get_db),
  2109. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  2110. ) -> NormalizedFilament:
  2111. """Update a Spoolman filament's name and/or spool_weight.
  2112. When spool_weight changes, Option A (keep_existing_spools=True) stamps the old
  2113. weight (the filament's, or its vendor's empty_spool_weight when the filament had
  2114. none) onto spools currently inheriting it (spool.spool_weight is None) so their
  2115. tare calculations are unaffected by the filament change.
  2116. Option B (keep_existing_spools=False, the default): when spool_weight is a
  2117. concrete value, stamps it onto every affected spool explicitly; when spool_weight
  2118. is null, clears per-spool overrides so spools fall back to the filament value.
  2119. """
  2120. client = await _get_client(db)
  2121. async with _translate_spoolman_errors():
  2122. current = await client.get_filament(filament_id)
  2123. patch_data = {k: v for k, v in body.model_dump(exclude_unset=True).items() if k != "keep_existing_spools"}
  2124. if not patch_data:
  2125. normalized = _normalize_filament(current)
  2126. if normalized is None:
  2127. raise HTTPException(status_code=404, detail="Filament not found")
  2128. return normalized
  2129. async with _translate_spoolman_errors():
  2130. updated = await client.patch_filament(filament_id, patch_data)
  2131. if "spool_weight" in body.model_fields_set:
  2132. async with _translate_spoolman_errors():
  2133. all_spools = await client.get_all_spools()
  2134. affected_spools = [s for s in all_spools if (s.get("filament") or {}).get("id") == filament_id]
  2135. if affected_spools:
  2136. if body.keep_existing_spools:
  2137. # What the inheriting spools weigh against today: the filament's
  2138. # own value, or when it has none, its vendor's (#3195). With
  2139. # neither they sit on the 250 g fallback, which is Bambuddy's
  2140. # alone, so there is nothing real to keep.
  2141. old_weight = _safe_optional_float(current.get("spool_weight"))
  2142. if old_weight is None:
  2143. old_weight = _safe_optional_float((current.get("vendor") or {}).get("empty_spool_weight"))
  2144. if old_weight is not None:
  2145. spools_to_fix = [s for s in affected_spools if s.get("spool_weight") is None]
  2146. if spools_to_fix:
  2147. async with _translate_spoolman_errors():
  2148. results = await asyncio.gather(
  2149. *(
  2150. client.update_spool_full(spool_id=s["id"], spool_weight=old_weight)
  2151. for s in spools_to_fix
  2152. ),
  2153. return_exceptions=True,
  2154. )
  2155. _raise_if_partial_failure(spools_to_fix, results, "spool_weight stamp (option A)")
  2156. else:
  2157. new_weight = body.spool_weight
  2158. if new_weight is not None:
  2159. # Stamp the new weight onto every spool of this filament type so
  2160. # each spool carries the value explicitly rather than inheriting.
  2161. async with _translate_spoolman_errors():
  2162. results = await asyncio.gather(
  2163. *(
  2164. client.update_spool_full(spool_id=s["id"], spool_weight=new_weight)
  2165. for s in affected_spools
  2166. ),
  2167. return_exceptions=True,
  2168. )
  2169. _raise_if_partial_failure(affected_spools, results, "spool_weight stamp (option B)")
  2170. else:
  2171. # Filament weight is being cleared — remove any per-spool override
  2172. # so spools fall back to the vendor's empty_spool_weight, or 250 g.
  2173. spools_to_clear = [s for s in affected_spools if s.get("spool_weight") is not None]
  2174. if spools_to_clear:
  2175. async with _translate_spoolman_errors():
  2176. results = await asyncio.gather(
  2177. *(
  2178. client.update_spool_full(spool_id=s["id"], clear_spool_weight=True)
  2179. for s in spools_to_clear
  2180. ),
  2181. return_exceptions=True,
  2182. )
  2183. _raise_if_partial_failure(spools_to_clear, results, "spool_weight clear (option B null)")
  2184. normalized = _normalize_filament(updated)
  2185. if normalized is None:
  2186. raise HTTPException(status_code=502, detail="Spoolman returned malformed filament data")
  2187. return normalized
  2188. @router.get("/spools/{spool_id}/k-profiles")
  2189. async def get_spoolman_k_profiles(
  2190. spool_id: int = Path(..., gt=0),
  2191. db: AsyncSession = Depends(get_db),
  2192. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  2193. ) -> list[dict]:
  2194. """Return all local K-value calibration profiles for a Spoolman spool."""
  2195. await _get_client(db)
  2196. result = await db.execute(select(SpoolmanKProfile).where(SpoolmanKProfile.spoolman_spool_id == spool_id))
  2197. profiles = result.scalars().all()
  2198. return [_k_profile_to_dict(p) for p in profiles]
  2199. @router.put("/spools/{spool_id}/k-profiles")
  2200. async def save_spoolman_k_profiles(
  2201. spool_id: int = Path(..., gt=0),
  2202. profiles: list[SpoolKProfileBase] = Body(...),
  2203. db: AsyncSession = Depends(get_db),
  2204. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  2205. ) -> list[dict]:
  2206. """Replace all K-value calibration profiles for a Spoolman spool."""
  2207. client = await _get_client(db)
  2208. async with _translate_spoolman_errors():
  2209. await client.get_spool(spool_id)
  2210. saved: list[SpoolmanKProfile] = []
  2211. try:
  2212. await db.execute(delete(SpoolmanKProfile).where(SpoolmanKProfile.spoolman_spool_id == spool_id))
  2213. for profile in profiles:
  2214. obj = SpoolmanKProfile(
  2215. spoolman_spool_id=spool_id,
  2216. printer_id=profile.printer_id,
  2217. extruder=profile.extruder,
  2218. nozzle_diameter=profile.nozzle_diameter,
  2219. nozzle_type=profile.nozzle_type,
  2220. k_value=profile.k_value,
  2221. name=profile.name,
  2222. cali_idx=profile.cali_idx,
  2223. setting_id=profile.setting_id,
  2224. )
  2225. db.add(obj)
  2226. saved.append(obj)
  2227. await db.commit()
  2228. except IntegrityError as exc:
  2229. await db.rollback()
  2230. raise HTTPException(422, "Duplicate or invalid K-profile (check printer_id and nozzle uniqueness)") from exc
  2231. except Exception as exc:
  2232. await db.rollback()
  2233. logger.error("K-profile save for spool %d failed: %s", spool_id, exc)
  2234. raise HTTPException(500, "Failed to save K-profiles") from exc
  2235. for obj in saved:
  2236. await db.refresh(obj)
  2237. return [_k_profile_to_dict(p) for p in saved]
  2238. def _supplier_link_to_dict(link: SpoolmanSpoolSupplier) -> dict:
  2239. """Same shape as ``SpoolSupplierResponse`` so the frontend renders both
  2240. inventories with one component."""
  2241. return {
  2242. "id": link.id,
  2243. "supplier_id": link.supplier_id,
  2244. "supplier_name": link.supplier_name,
  2245. "supplier_article_number": link.supplier_article_number,
  2246. "quoted_price_per_kg": link.quoted_price_per_kg,
  2247. "is_purchase_source": link.is_purchase_source,
  2248. }
  2249. @router.get("/spools/{spool_id}/suppliers")
  2250. async def get_spoolman_spool_suppliers(
  2251. spool_id: int = Path(..., gt=0),
  2252. db: AsyncSession = Depends(get_db),
  2253. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  2254. ) -> list[dict]:
  2255. """Supplier assignments for a Spoolman spool (#2988, Bambuddy-side rows)."""
  2256. await _get_client(db)
  2257. result = await db.execute(
  2258. select(SpoolmanSpoolSupplier)
  2259. .options(selectinload(SpoolmanSpoolSupplier.supplier))
  2260. .where(SpoolmanSpoolSupplier.spoolman_spool_id == spool_id)
  2261. )
  2262. return [_supplier_link_to_dict(link) for link in result.scalars().all()]
  2263. @router.put("/spools/{spool_id}/suppliers")
  2264. async def save_spoolman_spool_suppliers(
  2265. spool_id: int = Path(..., gt=0),
  2266. links: list[SpoolSupplierLinkInput] = Body(...),
  2267. db: AsyncSession = Depends(get_db),
  2268. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  2269. ) -> list[dict]:
  2270. """Replace a Spoolman spool's supplier assignments (#2988).
  2271. Mirror of the built-in inventory's replace-all endpoint — Spoolman owns
  2272. the spool, Bambuddy owns the assignment (``SpoolmanKProfile`` precedent),
  2273. so the rows are local and the spool is only verified to exist remotely.
  2274. """
  2275. client = await _get_client(db)
  2276. async with _translate_spoolman_errors():
  2277. await client.get_spool(spool_id)
  2278. supplier_ids = [link.supplier_id for link in links]
  2279. if len(set(supplier_ids)) != len(supplier_ids):
  2280. raise HTTPException(400, "Duplicate supplier in assignment list")
  2281. if sum(1 for link in links if link.is_purchase_source) > 1:
  2282. raise HTTPException(400, "Only one assignment can be the purchase source")
  2283. if supplier_ids:
  2284. found = await db.execute(select(Supplier.id).where(Supplier.id.in_(supplier_ids)))
  2285. missing = set(supplier_ids) - {row[0] for row in found.all()}
  2286. if missing:
  2287. raise HTTPException(404, f"Supplier(s) not found: {sorted(missing)}")
  2288. await db.execute(delete(SpoolmanSpoolSupplier).where(SpoolmanSpoolSupplier.spoolman_spool_id == spool_id))
  2289. saved: list[SpoolmanSpoolSupplier] = []
  2290. for link in links:
  2291. row = SpoolmanSpoolSupplier(spoolman_spool_id=spool_id, **link.model_dump())
  2292. db.add(row)
  2293. saved.append(row)
  2294. await db.commit()
  2295. refreshed = await db.execute(
  2296. select(SpoolmanSpoolSupplier)
  2297. .options(selectinload(SpoolmanSpoolSupplier.supplier))
  2298. .where(SpoolmanSpoolSupplier.id.in_([row.id for row in saved]))
  2299. .order_by(SpoolmanSpoolSupplier.id)
  2300. )
  2301. await ws_manager.broadcast({"type": "inventory_changed"})
  2302. return [_supplier_link_to_dict(link) for link in refreshed.scalars().all()]