spoolman_inventory.py 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111
  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 fastapi import APIRouter, Body, Depends, HTTPException, Path, Query, Response
  14. from fastapi.responses import JSONResponse
  15. from pydantic import BaseModel, Field, field_validator, model_validator
  16. from sqlalchemy import delete, select, text
  17. from sqlalchemy.exc import IntegrityError
  18. from sqlalchemy.ext.asyncio import AsyncSession
  19. from sqlalchemy.orm import selectinload
  20. from backend.app.api.routes._spoolman_helpers import (
  21. NormalizedFilament,
  22. NormalizedVendorRef,
  23. _map_spoolman_spool,
  24. _safe_float,
  25. _safe_int,
  26. _safe_optional_float,
  27. assert_safe_spoolman_url,
  28. )
  29. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  30. from backend.app.core.database import get_db
  31. from backend.app.core.permissions import Permission
  32. from backend.app.core.websocket import ws_manager
  33. from backend.app.models.ams_label import AmsLabel
  34. from backend.app.models.printer import Printer
  35. from backend.app.models.settings import Settings
  36. from backend.app.models.spool_filament_preset import SpoolmanFilamentPreset
  37. from backend.app.models.spoolman_k_profile import SpoolmanKProfile
  38. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  39. from backend.app.models.user import User
  40. from backend.app.schemas.spool import SpoolFilamentPresetBase, SpoolKProfileBase
  41. from backend.app.schemas.spoolman import SpoolmanFilamentPatch, SpoolmanSlotAssignmentEnriched
  42. from backend.app.services.location_service import (
  43. enrich_spool_dicts_with_location_id,
  44. maybe_sync_spoolman_locations,
  45. resolve_spoolman_location_string,
  46. )
  47. from backend.app.services.printer_manager import printer_manager
  48. from backend.app.services.slicer_filament_resolver import resolve_slicer_filament
  49. from backend.app.services.slot_nozzle import resolve_slot_nozzle
  50. from backend.app.services.spool_filament_preset import resolve_spoolman_preset
  51. from backend.app.services.spoolman import (
  52. SpoolmanClient,
  53. SpoolmanClientError,
  54. SpoolmanNotFoundError,
  55. SpoolmanUnavailableError,
  56. get_spoolman_client,
  57. init_spoolman_client,
  58. )
  59. from backend.app.services.spoolman_tracking import get_fallback_spool_tag_for_slot
  60. from backend.app.utils.color_utils import spoolman_color_hex
  61. from backend.app.utils.filament_ids import (
  62. GENERIC_FILAMENT_IDS,
  63. filament_id_to_setting_id,
  64. normalize_slicer_filament,
  65. )
  66. from backend.app.utils.filament_types import nozzle_temp_range, printer_filament_type
  67. logger = logging.getLogger(__name__)
  68. router = APIRouter(prefix="/spoolman/inventory", tags=["spoolman-inventory"])
  69. # Cache the last successful health-check timestamp to avoid a round-trip on
  70. # every request. A failed check clears the cache immediately.
  71. _health_check_cache: dict[str, float] = {}
  72. _HEALTH_CHECK_TTL = 30.0 # seconds
  73. def _tag_cleared(val: str | None) -> bool:
  74. """Return True when a PATCH field explicitly removes a tag (null)."""
  75. return val is None
  76. async def _clear_stale_tag_links(
  77. client: SpoolmanClient,
  78. *,
  79. tag: str,
  80. keep_spool_id: int,
  81. log_context: str,
  82. ) -> int:
  83. """Clear extra.tag on OTHER spools still claiming the given tag (#1457).
  84. A given AMS slot tag — whether a real RFID (tray_uuid/tag_uid) or the
  85. deterministic fallback derived from (printer_serial, ams_id, tray_id) for
  86. non-RFID slots — uniquely identifies one physical slot. When a spool is
  87. (re)bound to that slot via Assign or Link, any other Spoolman spool whose
  88. extra.tag still holds the same value is stale and would resurface in the
  89. hover card / fill-level lookup.
  90. Best-effort: per-spool patch failures are logged and skipped, never raised.
  91. Returns the number of spools cleared.
  92. """
  93. if not tag:
  94. return 0
  95. tag_upper = tag.upper()
  96. try:
  97. spools = await client.get_spools()
  98. except (SpoolmanClientError, SpoolmanUnavailableError) as exc:
  99. logger.warning("Could not enumerate spools for stale-tag cleanup: %s", exc)
  100. return 0
  101. cleared = 0
  102. for spool in spools:
  103. spool_id = spool.get("id")
  104. if not spool_id or spool_id == keep_spool_id:
  105. continue
  106. extra = spool.get("extra") or {}
  107. raw_tag = extra.get("tag", "")
  108. if not raw_tag:
  109. continue
  110. clean_tag = raw_tag.strip('"').upper()
  111. if clean_tag != tag_upper:
  112. continue
  113. try:
  114. await client.merge_spool_extra(spool_id, {"tag": json.dumps("")})
  115. cleared += 1
  116. logger.info(
  117. "Cleared stale tag '%s' from Spoolman spool %s (%s; reassigned to spool %s)",
  118. tag_upper[:16],
  119. spool_id,
  120. log_context,
  121. keep_spool_id,
  122. )
  123. except (SpoolmanClientError, SpoolmanUnavailableError, SpoolmanNotFoundError) as exc:
  124. logger.warning(
  125. "Failed to clear stale tag on Spoolman spool %s: %s",
  126. spool_id,
  127. exc,
  128. )
  129. return cleared
  130. async def _clear_stale_slot_fallback_tag_links(
  131. client: SpoolmanClient,
  132. *,
  133. printer_serial: str,
  134. ams_id: int,
  135. tray_id: int,
  136. keep_spool_id: int,
  137. ) -> int:
  138. """Convenience wrapper: compute the slot's fallback tag and clear it from
  139. other spools. Used by the assign route, which identifies the slot by
  140. (printer, ams, tray) rather than by an explicit tag value.
  141. """
  142. fallback_tag = get_fallback_spool_tag_for_slot(printer_serial, ams_id, tray_id)
  143. if not fallback_tag:
  144. return 0
  145. return await _clear_stale_tag_links(
  146. client,
  147. tag=fallback_tag,
  148. keep_spool_id=keep_spool_id,
  149. log_context=f"printer={printer_serial} ams={ams_id} tray={tray_id}",
  150. )
  151. async def _get_client(db: AsyncSession) -> SpoolmanClient:
  152. """Return a validated Spoolman client (URL checked, health-checked) or raise an HTTP error."""
  153. result = await db.execute(select(Settings))
  154. settings: dict[str, str] = {s.key: s.value for s in result.scalars().all()}
  155. enabled = settings.get("spoolman_enabled", "false").lower() == "true"
  156. url = settings.get("spoolman_url", "").strip()
  157. if not enabled:
  158. raise HTTPException(status_code=400, detail="Spoolman integration is not enabled")
  159. if not url:
  160. raise HTTPException(status_code=400, detail="Spoolman URL is not configured")
  161. # SSRF guard: reject dangerous schemes, cloud-metadata IPs (169.254.169.254, 100.100.100.200,
  162. # fd00:ec2::254), multicast and unspecified addresses — loopback and RFC-1918 ranges are
  163. # intentionally permitted (Spoolman commonly runs on the same host or home LAN).
  164. # Raises ValueError with a descriptive message on any violation.
  165. try:
  166. assert_safe_spoolman_url(url)
  167. except ValueError as exc:
  168. raise HTTPException(status_code=400, detail=str(exc)) from exc
  169. # Re-use the cached client when URL is unchanged; reinitialise on URL change (cache invalidation).
  170. client = await get_spoolman_client()
  171. if not client or client.base_url != url.rstrip("/"):
  172. try:
  173. client = await init_spoolman_client(url)
  174. except ValueError as exc:
  175. raise HTTPException(status_code=400, detail=str(exc)) from exc
  176. # Only call health_check() when the cached result has expired.
  177. # Evict stale entries when URL changes (only one Spoolman URL is active at a time).
  178. if url not in _health_check_cache and _health_check_cache:
  179. _health_check_cache.clear()
  180. now = time.monotonic()
  181. last_ok = _health_check_cache.get(url, 0.0)
  182. if now - last_ok > _HEALTH_CHECK_TTL:
  183. if not await client.health_check():
  184. _health_check_cache.pop(url, None)
  185. raise HTTPException(status_code=503, detail="Spoolman server is not reachable")
  186. _health_check_cache[url] = now
  187. return client
  188. @asynccontextmanager
  189. async def _translate_spoolman_errors():
  190. """Translate Spoolman typed exceptions to HTTP errors for all inventory endpoints."""
  191. try:
  192. yield
  193. except SpoolmanNotFoundError as exc:
  194. raise HTTPException(status_code=404, detail="Spool not found in Spoolman") from exc
  195. except SpoolmanClientError as exc:
  196. raise HTTPException(
  197. status_code=502,
  198. detail={
  199. "message": "Spoolman rejected the request",
  200. "upstream_status": exc.status_code,
  201. "upstream_body": getattr(exc, "response_text", ""),
  202. },
  203. ) from exc
  204. except SpoolmanUnavailableError as exc:
  205. raise HTTPException(status_code=503, detail="Spoolman server is not reachable") from exc
  206. def _raise_if_partial_failure(spools: list[dict], results: list, operation: str) -> None:
  207. """Raise HTTP 502 if any gather result is an exception, logging each failure."""
  208. failures = [(s["id"], r) for s, r in zip(spools, results, strict=True) if isinstance(r, BaseException)]
  209. if failures:
  210. logger.error(
  211. "Partial %s failure: %d/%d spools failed: %s",
  212. operation,
  213. len(failures),
  214. len(spools),
  215. [(sid, type(exc).__name__) for sid, exc in failures],
  216. )
  217. raise HTTPException(
  218. status_code=502,
  219. detail=f"{operation} partially applied: {len(spools) - len(failures)}/{len(spools)} spools updated",
  220. )
  221. async def _apply_price_if_set(client: SpoolmanClient, spool: dict, cost_per_kg: float | None) -> tuple[dict, list[str]]:
  222. """Patch the spool price; return (updated_spool, warnings).
  223. Returns the original spool and a non-empty warnings list when the price
  224. update fails, so the caller can return HTTP 207 instead of silently
  225. discarding the price.
  226. """
  227. if cost_per_kg is None:
  228. return spool, []
  229. try:
  230. async with _translate_spoolman_errors():
  231. updated = await client.update_spool_full(spool["id"], price=cost_per_kg)
  232. return updated, []
  233. except HTTPException as exc:
  234. if exc.status_code >= 500:
  235. raise # Propagate network/server errors — don't swallow Spoolman outages
  236. logger.warning(
  237. "Price update failed for spool %d; spool created without price (cost_per_kg=%s, status=%d)",
  238. spool["id"],
  239. cost_per_kg,
  240. exc.status_code,
  241. )
  242. return spool, [f"price_not_set: Spoolman rejected the price update (HTTP {exc.status_code})"]
  243. # ---------------------------------------------------------------------------
  244. # Request / response schemas
  245. # ---------------------------------------------------------------------------
  246. _HEX_RE = re.compile(r"^[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$")
  247. def _validate_rgba(v: str | None) -> str | None:
  248. if v is None:
  249. return v
  250. clean = v.removeprefix("#")
  251. if not _HEX_RE.match(clean):
  252. raise ValueError("rgba must be a 6 or 8 character hex string (RRGGBB or RRGGBBAA)")
  253. return clean.upper()
  254. def _validate_storage_location(v: str | None) -> str | None:
  255. if v is not None and any(c in v for c in ("\r", "\n", "\x00")):
  256. raise ValueError("storage_location must not contain control characters")
  257. return v
  258. class SpoolmanInventoryCreate(BaseModel):
  259. # When spoolman_filament_id is provided the caller has already chosen a filament from the
  260. # Spoolman catalog, so material (and other metadata) are optional — the backend skips
  261. # find_or_create_filament() and uses the supplied ID directly.
  262. spoolman_filament_id: int | None = Field(None, gt=0)
  263. material: str | None = Field(None, min_length=1, max_length=64)
  264. subtype: str | None = Field(None, max_length=64)
  265. brand: str | None = Field(None, max_length=128)
  266. color_name: str | None = Field(None, max_length=64)
  267. rgba: str | None = Field(None, max_length=8, description="6-digit hex (RRGGBB) or 8-digit (RRGGBBAA)")
  268. label_weight: int = Field(1000, ge=1, le=100_000)
  269. core_weight: int = Field(
  270. 250, ge=0, le=10_000
  271. ) # Accepted for schema parity but not persisted to Spoolman (stored on filament type, not spool)
  272. weight_used: float = Field(0.0, ge=0.0, le=100_000.0)
  273. note: str | None = Field(None, max_length=1000)
  274. cost_per_kg: float | None = Field(None, ge=0.0, le=1_000_000.0)
  275. storage_location: str | None = Field(None, max_length=255)
  276. location_id: int | None = Field(None, gt=0)
  277. # BambuStudio slicer preset for this spool. Spoolman has no native field
  278. # for this, so we persist it under the bambu_slicer_filament[_name] keys
  279. # in the spool's extra dict and read it back in _map_spoolman_spool.
  280. slicer_filament: str | None = Field(None, max_length=128)
  281. slicer_filament_name: str | None = Field(None, max_length=255)
  282. @field_validator("rgba")
  283. @classmethod
  284. def validate_rgba(cls, v: str | None) -> str | None:
  285. return _validate_rgba(v)
  286. @field_validator("storage_location")
  287. @classmethod
  288. def validate_storage_location(cls, v: str | None) -> str | None:
  289. return _validate_storage_location(v)
  290. @model_validator(mode="after")
  291. def validate_weight_consistency(self) -> SpoolmanInventoryCreate:
  292. # material is required only when the caller has not pre-selected a Spoolman filament
  293. if self.spoolman_filament_id is None and not self.material:
  294. raise ValueError("material is required when spoolman_filament_id is not provided")
  295. if self.weight_used > self.label_weight:
  296. raise ValueError("weight_used must not exceed label_weight")
  297. return self
  298. class SpoolmanInventoryUpdate(BaseModel):
  299. material: str | None = Field(None, min_length=1, max_length=64)
  300. subtype: str | None = Field(None, max_length=64)
  301. brand: str | None = Field(None, max_length=128)
  302. color_name: str | None = Field(None, max_length=64)
  303. rgba: str | None = Field(None, max_length=8, description="6-digit hex (RRGGBB) or 8-digit (RRGGBBAA)")
  304. label_weight: int | None = Field(None, ge=1, le=100_000)
  305. core_weight: int | None = Field(
  306. None, ge=0, le=10_000
  307. ) # Accepted for schema parity but not persisted to Spoolman (stored on filament type, not spool)
  308. weight_used: float | None = Field(None, ge=0.0, le=100_000.0)
  309. note: str | None = Field(None, max_length=1000)
  310. cost_per_kg: float | None = Field(None, ge=0.0, le=1_000_000.0)
  311. tag_uid: str | None = Field(None, min_length=8, max_length=30, pattern=r"^[0-9A-Fa-f]+$")
  312. tray_uuid: str | None = Field(None, min_length=32, max_length=32, pattern=r"^[0-9A-Fa-f]+$")
  313. storage_location: str | None = Field(None, max_length=255)
  314. location_id: int | None = Field(None, gt=0)
  315. # BambuStudio slicer preset — persisted to Spoolman extra dict (see Create
  316. # schema). Pass an empty string to clear; null/omitted leaves unchanged.
  317. slicer_filament: str | None = Field(None, max_length=128)
  318. slicer_filament_name: str | None = Field(None, max_length=255)
  319. @field_validator("rgba")
  320. @classmethod
  321. def validate_rgba(cls, v: str | None) -> str | None:
  322. return _validate_rgba(v)
  323. @field_validator("storage_location")
  324. @classmethod
  325. def validate_storage_location(cls, v: str | None) -> str | None:
  326. return _validate_storage_location(v)
  327. @model_validator(mode="after")
  328. def validate_tag_fields(self) -> SpoolmanInventoryUpdate:
  329. # null = remove tag; non-null values rejected (use /tag endpoint to write tags)
  330. if self.tag_uid is not None:
  331. raise ValueError("tag_uid cannot be set via this endpoint; use PATCH /spools/{id}/tag to write tags")
  332. if self.tray_uuid is not None:
  333. raise ValueError("tray_uuid cannot be set via this endpoint; use PATCH /spools/{id}/tag to write tags")
  334. return self
  335. @model_validator(mode="after")
  336. def validate_weight_consistency(self) -> SpoolmanInventoryUpdate:
  337. if self.weight_used is not None and self.label_weight is not None:
  338. if self.weight_used > self.label_weight:
  339. raise ValueError("weight_used must not exceed label_weight")
  340. return self
  341. class SpoolmanInventoryBulkCreate(BaseModel):
  342. spool: SpoolmanInventoryCreate
  343. quantity: int = Field(1, ge=1, le=50)
  344. class SpoolWeightUpdate(BaseModel):
  345. weight_grams: float = Field(..., ge=0.0, le=100_000.0)
  346. class SpoolTagLinkRequest(BaseModel):
  347. # Minimum 8 hex chars = 4-byte NFC UID (Bambu Lab hardware tags use 4-byte UIDs).
  348. tag_uid: str | None = Field(None, min_length=8, max_length=30, pattern=r"^[0-9A-Fa-f]+$")
  349. tray_uuid: str | None = Field(None, min_length=32, max_length=32, pattern=r"^[0-9A-Fa-f]+$")
  350. @field_validator("tag_uid")
  351. @classmethod
  352. def tag_uid_not_all_zeros(cls, v: str | None) -> str | None:
  353. if v is not None and all(c in "0" for c in v):
  354. raise ValueError("tag_uid must not be all-zero bytes")
  355. return v
  356. @model_validator(mode="after")
  357. def at_least_one(self) -> SpoolTagLinkRequest:
  358. if not self.tag_uid and not self.tray_uuid:
  359. raise ValueError("tag_uid or tray_uuid is required")
  360. return self
  361. class SpoolSlotAssignmentRequest(BaseModel):
  362. spoolman_spool_id: int = Field(..., gt=0)
  363. printer_id: int = Field(..., gt=0)
  364. # ams_id 0–7 for physical AMS units; 255 = external/virtual spool extruder slot
  365. ams_id: int = Field(..., ge=0, le=255)
  366. tray_id: int = Field(..., ge=0, le=3)
  367. # ---------------------------------------------------------------------------
  368. # Endpoints
  369. # ---------------------------------------------------------------------------
  370. @router.get("/spools")
  371. async def list_spools(
  372. include_archived: bool = Query(False),
  373. db: AsyncSession = Depends(get_db),
  374. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  375. ) -> list[dict]:
  376. """Return all Spoolman spools in the InventorySpool format."""
  377. client = await _get_client(db)
  378. # Sync after we have the route-resolved client so tests that patch the
  379. # route module's get_spoolman_client/init_spoolman_client also catch the
  380. # sync's client lookup — otherwise the location_service path imports from
  381. # backend.app.services.spoolman directly and bypasses the patch.
  382. if await maybe_sync_spoolman_locations(db, client=client):
  383. await db.commit()
  384. async with _translate_spoolman_errors():
  385. spools = await client.get_all_spools(allow_archived=include_archived)
  386. mapped: list[dict] = []
  387. spool_ids: list[int] = []
  388. for s in spools:
  389. try:
  390. m = _map_spoolman_spool(s)
  391. mapped.append(m)
  392. spool_ids.append(m["id"])
  393. except ValueError as exc:
  394. logger.warning("Skipping malformed Spoolman spool (id=%r): %s", s.get("id"), exc)
  395. if spool_ids:
  396. kp_result = await db.execute(select(SpoolmanKProfile).where(SpoolmanKProfile.spoolman_spool_id.in_(spool_ids)))
  397. kp_by_spool: dict[int, list[dict]] = {}
  398. for kp in kp_result.scalars().all():
  399. kp_by_spool.setdefault(kp.spoolman_spool_id, []).append(_k_profile_to_dict(kp))
  400. for m in mapped:
  401. m["k_profiles"] = kp_by_spool.get(m["id"], [])
  402. await enrich_spool_dicts_with_location_id(db, mapped)
  403. return mapped
  404. @router.get("/spools/{spool_id}")
  405. async def get_spool(
  406. spool_id: int = Path(..., gt=0),
  407. db: AsyncSession = Depends(get_db),
  408. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  409. ) -> dict:
  410. """Return a single Spoolman spool in the InventorySpool format."""
  411. client = await _get_client(db)
  412. async with _translate_spoolman_errors():
  413. spool = await client.get_spool(spool_id)
  414. try:
  415. mapped = _map_spoolman_spool(spool)
  416. except ValueError as exc:
  417. logger.warning("Malformed Spoolman spool (id=%r): %s", spool_id, exc)
  418. raise HTTPException(status_code=502, detail="Spoolman returned malformed spool data") from exc
  419. kp_result = await db.execute(select(SpoolmanKProfile).where(SpoolmanKProfile.spoolman_spool_id == spool_id))
  420. mapped["k_profiles"] = [_k_profile_to_dict(kp) for kp in kp_result.scalars().all()]
  421. await enrich_spool_dicts_with_location_id(db, [mapped])
  422. return mapped
  423. async def _resolve_filament_id(data: SpoolmanInventoryCreate, client: SpoolmanClient) -> int:
  424. """Return the Spoolman filament ID for this spool creation request.
  425. If spoolman_filament_id is set the caller pre-selected a catalog entry,
  426. so find_or_create_filament() is skipped and the ID is used directly.
  427. """
  428. if data.spoolman_filament_id is not None:
  429. return data.spoolman_filament_id
  430. # Validator guarantees material is non-None when spoolman_filament_id is None
  431. assert data.material is not None # noqa: S101
  432. # `or "808080"` on the result rather than on the input: spoolman_color_hex
  433. # returns None only for a missing value, so this is the same neutral grey the
  434. # old inline default produced, without handing an Optional to a str parameter.
  435. color_hex = spoolman_color_hex(data.rgba) or "808080"
  436. async with _translate_spoolman_errors():
  437. return await client.find_or_create_filament(
  438. material=data.material,
  439. subtype=data.subtype or "",
  440. brand=data.brand,
  441. color_hex=color_hex,
  442. label_weight=data.label_weight,
  443. color_name=data.color_name,
  444. )
  445. @router.post("/spools")
  446. async def create_spool(
  447. data: SpoolmanInventoryCreate,
  448. db: AsyncSession = Depends(get_db),
  449. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  450. ) -> dict:
  451. """Create a new spool in Spoolman, auto-creating vendor and filament as needed."""
  452. client = await _get_client(db)
  453. filament_id = await _resolve_filament_id(data, client)
  454. storage_location = data.storage_location
  455. if "location_id" in data.model_fields_set or "storage_location" in data.model_fields_set:
  456. try:
  457. storage_location, _ = await resolve_spoolman_location_string(
  458. db,
  459. location_id=data.location_id,
  460. storage_location=data.storage_location,
  461. fields_set=set(data.model_fields_set),
  462. )
  463. except ValueError as exc:
  464. raise HTTPException(status_code=400, detail=str(exc)) from exc
  465. remaining = max(0.0, data.label_weight - data.weight_used)
  466. try:
  467. async with _translate_spoolman_errors():
  468. spool = await client.create_spool(
  469. filament_id=filament_id,
  470. remaining_weight=remaining,
  471. comment=data.note or None,
  472. location=storage_location or None,
  473. )
  474. except HTTPException as exc:
  475. if exc.status_code == 404 and data.spoolman_filament_id is not None:
  476. raise HTTPException(
  477. status_code=404,
  478. detail=f"Filament {data.spoolman_filament_id} not found in Spoolman",
  479. ) from exc
  480. raise
  481. spool, price_warnings = await _apply_price_if_set(client, spool, data.cost_per_kg)
  482. # Persist slicer_filament AND color_name under the spool's extra dict
  483. # (mirror update_spool). Spoolman has no `color_name` field on filament
  484. # (#1357) so we own the round-trip ourselves.
  485. if data.slicer_filament is not None or data.slicer_filament_name is not None or data.color_name is not None:
  486. # Ensure extra fields are registered before write.
  487. if data.slicer_filament is not None:
  488. await client.ensure_extra_field("bambu_slicer_filament")
  489. if data.slicer_filament_name is not None:
  490. await client.ensure_extra_field("bambu_slicer_filament_name")
  491. if data.color_name is not None:
  492. await client.ensure_extra_field("bambu_color_name")
  493. new_extra: dict = {}
  494. if data.slicer_filament is not None:
  495. new_extra["bambu_slicer_filament"] = json.dumps(data.slicer_filament)
  496. if data.slicer_filament_name is not None:
  497. new_extra["bambu_slicer_filament_name"] = json.dumps(data.slicer_filament_name)
  498. if data.color_name is not None:
  499. new_extra["bambu_color_name"] = json.dumps(data.color_name)
  500. if new_extra:
  501. try:
  502. async with _translate_spoolman_errors():
  503. spool = await client.merge_spool_extra(spool["id"], new_extra)
  504. except HTTPException:
  505. # Best-effort — the spool already exists, log and continue.
  506. logger.warning(
  507. "Failed to persist slicer_filament/color_name for spool %s",
  508. spool.get("id"),
  509. )
  510. result = _map_spoolman_spool(spool)
  511. await ws_manager.broadcast({"type": "inventory_changed"})
  512. if price_warnings:
  513. return JSONResponse(status_code=207, content={**result, "warnings": price_warnings})
  514. return result
  515. @router.post("/spools/bulk")
  516. async def bulk_create_spools(
  517. payload: SpoolmanInventoryBulkCreate,
  518. db: AsyncSession = Depends(get_db),
  519. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  520. ) -> Response:
  521. """Create multiple identical spools in Spoolman."""
  522. client = await _get_client(db)
  523. data = payload.spool
  524. try:
  525. filament_id = await _resolve_filament_id(data, client)
  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. storage_location = data.storage_location
  534. if "location_id" in data.model_fields_set or "storage_location" in data.model_fields_set:
  535. try:
  536. storage_location, _ = await resolve_spoolman_location_string(
  537. db,
  538. location_id=data.location_id,
  539. storage_location=data.storage_location,
  540. fields_set=set(data.model_fields_set),
  541. )
  542. except ValueError as exc:
  543. raise HTTPException(status_code=400, detail=str(exc)) from exc
  544. remaining = max(0.0, data.label_weight - data.weight_used)
  545. created: list[dict] = []
  546. failures: list[str] = []
  547. for _ in range(payload.quantity):
  548. try:
  549. spool = await client.create_spool(
  550. filament_id=filament_id,
  551. remaining_weight=remaining,
  552. comment=data.note or None,
  553. location=storage_location or None,
  554. )
  555. except (SpoolmanUnavailableError, SpoolmanClientError, SpoolmanNotFoundError) as exc:
  556. logger.warning("Bulk spool creation: one spool failed: %s", exc)
  557. failures.append("spool creation failed")
  558. continue
  559. try:
  560. spool, price_warnings = await _apply_price_if_set(client, spool, data.cost_per_kg)
  561. except HTTPException as exc:
  562. logger.warning(
  563. "Bulk spool %d: price update failed (HTTP %d); spool not added to created list",
  564. spool.get("id", 0),
  565. exc.status_code,
  566. )
  567. failures.append("spool created but price update failed")
  568. continue
  569. if price_warnings:
  570. logger.warning("Bulk spool %s created without price: %s", spool.get("id"), price_warnings)
  571. created.append(_map_spoolman_spool(spool))
  572. if not created:
  573. raise HTTPException(status_code=500, detail="Failed to create any spools in Spoolman")
  574. await ws_manager.broadcast({"type": "inventory_changed"})
  575. if len(created) < payload.quantity:
  576. # Some spool creations failed — return 207 Multi-Status so the caller
  577. # can distinguish a full success from a partial one and show a useful message.
  578. return JSONResponse(
  579. status_code=207,
  580. content={
  581. "created": created,
  582. "requested_count": payload.quantity,
  583. "failed_count": payload.quantity - len(created),
  584. "failures": failures,
  585. },
  586. )
  587. return JSONResponse(status_code=200, content=created)
  588. @router.patch("/spools/{spool_id}")
  589. async def update_spool(
  590. *,
  591. spool_id: int = Path(..., gt=0),
  592. data: SpoolmanInventoryUpdate,
  593. db: AsyncSession = Depends(get_db),
  594. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  595. ) -> dict:
  596. """Update an existing Spoolman spool, re-linking the filament if metadata changed."""
  597. client = await _get_client(db)
  598. async with _translate_spoolman_errors():
  599. current = await client.get_spool(spool_id)
  600. cur_filament: dict = current.get("filament") or {}
  601. cur_vendor: dict = cur_filament.get("vendor") or {}
  602. cur_mat: str = (cur_filament.get("material") or "").strip()
  603. cur_name: str = (cur_filament.get("name") or "").strip()
  604. if cur_mat and cur_name.upper().startswith(cur_mat.upper()):
  605. cur_subtype: str = cur_name[len(cur_mat) :].strip()
  606. else:
  607. cur_subtype = cur_name
  608. # Resolve final values: use request value if provided, else keep current
  609. material = data.material if data.material is not None else cur_mat
  610. subtype = data.subtype if data.subtype is not None else cur_subtype
  611. brand = data.brand if data.brand is not None else (cur_vendor.get("name") or None)
  612. # color_name uses model_fields_set so explicit null (clear) is distinguishable
  613. # from "field omitted" (don't touch). find_or_create_filament's convention:
  614. # None = don't touch, "" = explicit clear, "value" = set.
  615. if "color_name" in data.model_fields_set:
  616. color_name = data.color_name if data.color_name is not None else ""
  617. else:
  618. color_name = cur_filament.get("color_name") or None
  619. cur_color = (cur_filament.get("color_hex") or "808080").upper().removeprefix("#")
  620. # Handed over as stored. The opaque alpha this used to append was folded
  621. # straight back off by `spoolman_color_hex` below, so the two paths landed on
  622. # the same string and the append only obscured which shape was in hand (#2912).
  623. rgba = data.rgba if data.rgba is not None else cur_color
  624. label_weight = data.label_weight if data.label_weight is not None else int(cur_filament.get("weight") or 1000)
  625. # Default weight_used from the synthetic mapping (label - remaining) so an
  626. # edit that doesn't touch the weight field preserves Spoolman's real
  627. # remaining_weight after a "Reset usage to 0" — the previous code read
  628. # Spoolman's used_weight directly, which is 0 post-reset, so
  629. # `remaining = label - 0 = 1000` would overwrite the real remaining
  630. # the next time the user edited any other field (#1390).
  631. cur_remaining_raw = current.get("remaining_weight")
  632. if cur_remaining_raw is not None:
  633. synthetic_used = max(0.0, float(label_weight) - float(cur_remaining_raw))
  634. else:
  635. synthetic_used = float(current.get("used_weight") or 0)
  636. weight_used = data.weight_used if data.weight_used is not None else synthetic_used
  637. note = data.note if data.note is not None else current.get("comment")
  638. storage_location_changed = "storage_location" in data.model_fields_set or "location_id" in data.model_fields_set
  639. storage_location = data.storage_location if "storage_location" in data.model_fields_set else None
  640. if storage_location_changed:
  641. try:
  642. storage_location, _ = await resolve_spoolman_location_string(
  643. db,
  644. location_id=data.location_id,
  645. storage_location=storage_location,
  646. fields_set=set(data.model_fields_set),
  647. )
  648. except ValueError as exc:
  649. raise HTTPException(status_code=400, detail=str(exc)) from exc
  650. color_hex = spoolman_color_hex(rgba) or rgba
  651. # Resolve which filament this spool should be linked to AFTER the edit.
  652. #
  653. # The old behaviour was always `find_or_create_filament`, which proliferated
  654. # duplicate Spoolman filaments whenever the user changed any field that
  655. # made up the match key (material/subtype/brand/color) — every edit minted
  656. # a fresh row and orphaned the previous one (#1357 follow-up). To match
  657. # internal-mode behaviour ([[feedback_inventory_modes_parity]]: editing a
  658. # spool does not proliferate new entities), prefer PATCHing the current
  659. # filament in place when it's a singleton.
  660. cur_filament_id = cur_filament.get("id")
  661. desired_name = f"{material} {subtype}".strip() if subtype else material
  662. # Compare the stored shapes, not raw strings and not bare RGB prefixes. Raw
  663. # strings make an opaque spool's six characters differ from an incoming eight
  664. # and PATCH the filament on every no-op edit; bare prefixes make an
  665. # alpha-only edit invisible so the change never lands (#2912).
  666. cur_color_norm = spoolman_color_hex(cur_filament.get("color_hex")) or ""
  667. cur_vendor_name = (cur_vendor.get("name") or "").strip()
  668. cur_weight_int = int(cur_filament.get("weight") or 0)
  669. metadata_unchanged = (
  670. cur_filament_id
  671. and (cur_filament.get("name") or "").strip() == desired_name
  672. and (cur_filament.get("material") or "").upper() == material.upper()
  673. and cur_color_norm == (color_hex or "").upper()
  674. and cur_vendor_name.lower() == ((brand or "").strip().lower())
  675. and cur_weight_int == int(label_weight)
  676. )
  677. if metadata_unchanged:
  678. # No filament-side change at all — re-use the existing link, skip
  679. # find_or_create entirely so a no-op edit (e.g. just changing
  680. # weight_used or note) never even touches the filament catalogue.
  681. filament_id = cur_filament_id
  682. else:
  683. async with _translate_spoolman_errors():
  684. shared = await client.is_filament_shared(cur_filament_id, spool_id) if cur_filament_id else False
  685. if cur_filament_id and not shared:
  686. # Singleton filament — PATCH it in place so the user's edit lands
  687. # on the row their spool already points at instead of orphaning it.
  688. patch_body: dict = {
  689. "name": desired_name,
  690. "material": material,
  691. "color_hex": color_hex,
  692. "weight": float(label_weight),
  693. }
  694. if brand:
  695. vendor_id = await client.find_or_create_vendor(brand)
  696. patch_body["vendor_id"] = vendor_id
  697. async with _translate_spoolman_errors():
  698. await client.patch_filament(cur_filament_id, patch_body)
  699. filament_id = cur_filament_id
  700. else:
  701. # Filament is shared with other spools — PATCHing it in place would
  702. # silently rewrite their metadata too. Fall back to find-or-create
  703. # so only this spool's link moves.
  704. async with _translate_spoolman_errors():
  705. filament_id = await client.find_or_create_filament(
  706. material=material,
  707. subtype=subtype or "",
  708. brand=brand,
  709. color_hex=color_hex,
  710. label_weight=label_weight,
  711. color_name=color_name,
  712. )
  713. if not filament_id:
  714. raise HTTPException(status_code=500, detail="Failed to find or create filament in Spoolman")
  715. remaining = max(0.0, label_weight - weight_used)
  716. # Tag removal: clear only the "tag" key so other custom Spoolman extra fields
  717. # set outside Bambuddy are preserved.
  718. tag_nulled = (
  719. ("tag_uid" in data.model_fields_set or "tray_uuid" in data.model_fields_set)
  720. and _tag_cleared(data.tag_uid)
  721. and _tag_cleared(data.tray_uuid)
  722. )
  723. # Serialise tag-clear + PATCH under the per-spool extra lock to prevent a
  724. # concurrent merge_spool_extra call (e.g. NFC write-back) from overwriting
  725. # the tag key between our read and our write.
  726. #
  727. # Spoolman PATCHes extra dicts by MERGING — popping "tag" from a re-fetched
  728. # dict and sending the rest doesn't clear the key (Spoolman keeps the old
  729. # value because the key wasn't in the payload). Explicitly set the tag to
  730. # a JSON-encoded empty string; read-side filters strip the quotes.
  731. async with client.extra_lock(spool_id):
  732. if tag_nulled:
  733. # Re-fetch inside the lock so we work with fresh extra data.
  734. async with _translate_spoolman_errors():
  735. fresh = await client.get_spool(spool_id)
  736. cur_extra = dict(fresh.get("extra") or {})
  737. cur_extra["tag"] = json.dumps("")
  738. extra: dict | None = cur_extra
  739. else:
  740. extra = None
  741. async with _translate_spoolman_errors():
  742. updated = await client.update_spool_full(
  743. spool_id=spool_id,
  744. filament_id=filament_id,
  745. remaining_weight=remaining,
  746. comment=note or "",
  747. price=data.cost_per_kg,
  748. extra=extra,
  749. location=storage_location or None,
  750. clear_location=storage_location_changed and not storage_location,
  751. )
  752. # Persist BambuStudio slicer preset AND color_name under spool.extra.
  753. # Spoolman has no native fields for these — color_name was confirmed
  754. # absent from the FilamentUpdateParameters schema in 0.23.1 (#1357), so
  755. # writing `filament.color_name` was a silent no-op that left every
  756. # edit looking "not saved". They all round-trip via extra and get
  757. # unpacked in _map_spoolman_spool. Only writes when the request
  758. # explicitly set the field — passing null/omitting leaves the existing
  759. # extra entry untouched (write empty string to clear).
  760. sf_set = "slicer_filament" in data.model_fields_set
  761. sfn_set = "slicer_filament_name" in data.model_fields_set
  762. cn_set = "color_name" in data.model_fields_set
  763. if sf_set or sfn_set or cn_set:
  764. # Ensure extra fields are registered (Spoolman rejects PATCHes with
  765. # unknown keys with HTTP 400). Idempotent if startup already ran this.
  766. if sf_set:
  767. await client.ensure_extra_field("bambu_slicer_filament")
  768. if sfn_set:
  769. await client.ensure_extra_field("bambu_slicer_filament_name")
  770. if cn_set:
  771. await client.ensure_extra_field("bambu_color_name")
  772. new_extra: dict = {}
  773. if sf_set:
  774. new_extra["bambu_slicer_filament"] = json.dumps(data.slicer_filament or "")
  775. if sfn_set:
  776. new_extra["bambu_slicer_filament_name"] = json.dumps(data.slicer_filament_name or "")
  777. if cn_set:
  778. new_extra["bambu_color_name"] = json.dumps(data.color_name or "")
  779. async with _translate_spoolman_errors():
  780. updated = await client.merge_spool_extra(spool_id, new_extra)
  781. await ws_manager.broadcast({"type": "inventory_changed"})
  782. return _map_spoolman_spool(updated)
  783. @router.delete("/spools/{spool_id}")
  784. async def delete_spool(
  785. spool_id: int = Path(..., gt=0),
  786. db: AsyncSession = Depends(get_db),
  787. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  788. ) -> dict:
  789. """Permanently delete a spool from Spoolman."""
  790. client = await _get_client(db)
  791. async with _translate_spoolman_errors():
  792. await client.delete_spool(spool_id)
  793. await ws_manager.broadcast({"type": "inventory_changed"})
  794. return {"status": "deleted"}
  795. @router.post("/spools/{spool_id}/archive")
  796. async def archive_spool(
  797. spool_id: int = Path(..., gt=0),
  798. db: AsyncSession = Depends(get_db),
  799. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  800. ) -> dict:
  801. """Archive a spool in Spoolman (soft-delete)."""
  802. client = await _get_client(db)
  803. async with _translate_spoolman_errors():
  804. spool = await client.set_spool_archived(spool_id, archived=True)
  805. try:
  806. mapped = _map_spoolman_spool(spool)
  807. except ValueError as exc:
  808. logger.warning("Malformed Spoolman spool (id=%r): %s", spool_id, exc)
  809. raise HTTPException(status_code=502, detail="Spoolman returned malformed spool data") from exc
  810. await ws_manager.broadcast({"type": "inventory_changed"})
  811. return mapped
  812. @router.post("/spools/{spool_id}/restore")
  813. async def restore_spool(
  814. spool_id: int = Path(..., gt=0),
  815. db: AsyncSession = Depends(get_db),
  816. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  817. ) -> dict:
  818. """Restore an archived spool in Spoolman."""
  819. client = await _get_client(db)
  820. async with _translate_spoolman_errors():
  821. spool = await client.set_spool_archived(spool_id, archived=False)
  822. try:
  823. mapped = _map_spoolman_spool(spool)
  824. except ValueError as exc:
  825. logger.warning("Malformed Spoolman spool (id=%r): %s", spool_id, exc)
  826. raise HTTPException(status_code=502, detail="Spoolman returned malformed spool data") from exc
  827. await ws_manager.broadcast({"type": "inventory_changed"})
  828. return mapped
  829. @router.post("/spools/{spool_id}/reset-consumed-counter")
  830. async def reset_spool_consumed_counter(
  831. spool_id: int = Path(..., gt=0),
  832. db: AsyncSession = Depends(get_db),
  833. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  834. ) -> dict:
  835. """Zero the displayed "Total Consumed" counter for a Spoolman spool.
  836. Spoolman doesn't have a native "baseline" field, so the implementation
  837. reaches for the closest equivalent: PATCH `used_weight=0` upstream.
  838. The read mapping in ``_map_spoolman_spool`` then derives Bambuddy's
  839. `weight_used = label - remaining_weight` and `baseline = weight_used -
  840. real_used_weight`, so the Inventory page's `weight_used - baseline`
  841. display lands at 0 while remaining (= label - weight_used) is preserved
  842. — parity with the internal-mode endpoint (#1390, see also
  843. ``backend/app/api/routes/inventory.py::reset_spool_consumed_counter``).
  844. """
  845. client = await _get_client(db)
  846. async with _translate_spoolman_errors():
  847. spool = await client.reset_spool_usage(spool_id)
  848. try:
  849. mapped = _map_spoolman_spool(spool)
  850. except ValueError as exc:
  851. logger.warning("Malformed Spoolman spool (id=%r): %s", spool_id, exc)
  852. raise HTTPException(status_code=502, detail="Spoolman returned malformed spool data") from exc
  853. await ws_manager.broadcast({"type": "inventory_changed"})
  854. return mapped
  855. class SpoolmanBulkUpdateRequest(BaseModel):
  856. ids: list[int] = Field(..., min_length=1, max_length=500)
  857. update: SpoolmanInventoryUpdate
  858. class SpoolmanBulkIdsRequest(BaseModel):
  859. ids: list[int] = Field(..., min_length=1, max_length=500)
  860. @router.post("/spools/bulk-update")
  861. async def bulk_update_spools(
  862. payload: SpoolmanBulkUpdateRequest,
  863. db: AsyncSession = Depends(get_db),
  864. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  865. ) -> dict:
  866. """Apply the same partial update to every listed Spoolman spool.
  867. Loops the per-spool ``update_spool`` route so the filament re-linking +
  868. extra-dict + location-resolution rules stay in sync with the single-spool
  869. PATCH path. Per-spool errors are collected; one bad ID doesn't abort the
  870. batch.
  871. """
  872. update_fields = payload.update.model_dump(exclude_unset=True)
  873. if not update_fields:
  874. raise HTTPException(status_code=400, detail="update must include at least one field")
  875. updated = 0
  876. errors: list[dict] = []
  877. for sid in payload.ids:
  878. try:
  879. await update_spool(spool_id=sid, data=payload.update, db=db, _=None)
  880. updated += 1
  881. except HTTPException as exc:
  882. errors.append({"id": sid, "status": exc.status_code, "detail": exc.detail})
  883. except Exception as exc: # noqa: BLE001 — surface unexpected failures per-row
  884. logger.exception("Spoolman bulk-update failed for spool %s", sid)
  885. errors.append({"id": sid, "status": 500, "detail": str(exc)})
  886. if updated:
  887. await ws_manager.broadcast({"type": "inventory_changed"})
  888. return {"updated": updated, "errors": errors}
  889. @router.post("/spools/bulk-delete")
  890. async def bulk_delete_spools(
  891. payload: SpoolmanBulkIdsRequest,
  892. db: AsyncSession = Depends(get_db),
  893. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  894. ) -> dict:
  895. """Hard-delete every listed Spoolman spool. Per-spool failures are collected."""
  896. client = await _get_client(db)
  897. deleted = 0
  898. errors: list[dict] = []
  899. for sid in payload.ids:
  900. try:
  901. async with _translate_spoolman_errors():
  902. await client.delete_spool(sid)
  903. deleted += 1
  904. except HTTPException as exc:
  905. errors.append({"id": sid, "status": exc.status_code, "detail": exc.detail})
  906. except Exception as exc: # noqa: BLE001 — surface unexpected failures per-row
  907. logger.exception("Spoolman bulk-delete failed for spool %s", sid)
  908. errors.append({"id": sid, "status": 500, "detail": str(exc)})
  909. if deleted:
  910. await ws_manager.broadcast({"type": "inventory_changed"})
  911. return {"deleted": deleted, "errors": errors}
  912. @router.post("/spools/bulk-archive")
  913. async def bulk_archive_spools(
  914. payload: SpoolmanBulkIdsRequest,
  915. db: AsyncSession = Depends(get_db),
  916. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  917. ) -> dict:
  918. """Archive every listed Spoolman spool. Per-spool failures are collected."""
  919. client = await _get_client(db)
  920. archived = 0
  921. errors: list[dict] = []
  922. for sid in payload.ids:
  923. try:
  924. async with _translate_spoolman_errors():
  925. await client.set_spool_archived(sid, archived=True)
  926. archived += 1
  927. except HTTPException as exc:
  928. errors.append({"id": sid, "status": exc.status_code, "detail": exc.detail})
  929. except Exception as exc: # noqa: BLE001 — surface unexpected failures per-row
  930. logger.exception("Spoolman bulk-archive failed for spool %s", sid)
  931. errors.append({"id": sid, "status": 500, "detail": str(exc)})
  932. if archived:
  933. await ws_manager.broadcast({"type": "inventory_changed"})
  934. return {"archived": archived, "errors": errors}
  935. @router.post("/spools/bulk-restore")
  936. async def bulk_restore_spools(
  937. payload: SpoolmanBulkIdsRequest,
  938. db: AsyncSession = Depends(get_db),
  939. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  940. ) -> dict:
  941. """Restore every listed archived Spoolman spool. Per-spool failures are collected."""
  942. client = await _get_client(db)
  943. restored = 0
  944. errors: list[dict] = []
  945. for sid in payload.ids:
  946. try:
  947. async with _translate_spoolman_errors():
  948. await client.set_spool_archived(sid, archived=False)
  949. restored += 1
  950. except HTTPException as exc:
  951. errors.append({"id": sid, "status": exc.status_code, "detail": exc.detail})
  952. except Exception as exc: # noqa: BLE001 — surface unexpected failures per-row
  953. logger.exception("Spoolman bulk-restore failed for spool %s", sid)
  954. errors.append({"id": sid, "status": 500, "detail": str(exc)})
  955. if restored:
  956. await ws_manager.broadcast({"type": "inventory_changed"})
  957. return {"restored": restored, "errors": errors}
  958. @router.post("/spools/reset-consumed-counter-bulk")
  959. async def bulk_reset_spool_consumed_counter(
  960. payload: dict = Body(...),
  961. db: AsyncSession = Depends(get_db),
  962. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  963. ) -> dict:
  964. """Bulk reset the "Total Consumed" counter across the given Spoolman spool IDs.
  965. Caller passes an explicit list of IDs — no "reset all" shortcut, since
  966. a typo on a wildcard would wipe the entire inventory's tracking.
  967. Returns the count of spools successfully reset; individual failures are
  968. logged but do not abort the batch.
  969. """
  970. spool_ids = payload.get("spool_ids")
  971. if not isinstance(spool_ids, list) or not spool_ids:
  972. raise HTTPException(status_code=400, detail="spool_ids must be a non-empty list")
  973. if not all(isinstance(sid, int) for sid in spool_ids):
  974. raise HTTPException(status_code=400, detail="spool_ids must contain integers")
  975. client = await _get_client(db)
  976. reset_count = 0
  977. for spool_id in spool_ids:
  978. try:
  979. async with _translate_spoolman_errors():
  980. await client.reset_spool_usage(spool_id)
  981. reset_count += 1
  982. except HTTPException as exc:
  983. logger.warning("Spoolman reset-consumed-counter failed for spool %s: %s", spool_id, exc.detail)
  984. if reset_count:
  985. await ws_manager.broadcast({"type": "inventory_changed"})
  986. return {"reset": reset_count}
  987. @router.patch("/spools/{spool_id}/weight")
  988. async def sync_spool_weight(
  989. *,
  990. spool_id: int = Path(..., gt=0),
  991. data: SpoolWeightUpdate,
  992. db: AsyncSession = Depends(get_db),
  993. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  994. ) -> dict:
  995. """Update a spool's remaining weight from a measured gross weight.
  996. Computes remaining = gross_weight - tare, where tare = spool.spool_weight
  997. if set, else filament.spool_weight; falls back to 250 g when both unset.
  998. """
  999. client = await _get_client(db)
  1000. async with _translate_spoolman_errors():
  1001. current = await client.get_spool(spool_id)
  1002. cur_filament = current.get("filament") or {}
  1003. spool_tare = current.get("spool_weight")
  1004. raw_tare = spool_tare if spool_tare is not None else cur_filament.get("spool_weight")
  1005. core_weight = _safe_float(raw_tare, 250.0)
  1006. remaining = max(0.0, data.weight_grams - core_weight)
  1007. async with _translate_spoolman_errors():
  1008. updated = await client.update_spool_full(spool_id=spool_id, remaining_weight=remaining)
  1009. upd_filament = updated.get("filament") or {}
  1010. label_weight = _safe_int(upd_filament.get("weight"), 1000)
  1011. weight_used = max(0.0, label_weight - remaining)
  1012. await ws_manager.broadcast({"type": "inventory_changed"})
  1013. return {"status": "ok", "weight_used": weight_used}
  1014. @router.patch("/spools/{spool_id}/tag")
  1015. async def link_tag_to_spoolman_spool(
  1016. *,
  1017. spool_id: int = Path(..., gt=0),
  1018. data: SpoolTagLinkRequest,
  1019. db: AsyncSession = Depends(get_db),
  1020. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1021. ) -> dict:
  1022. """Write an NFC tag UID or Bambu tray UUID into Spoolman's extra.tag for a spool.
  1023. tray_uuid takes precedence over tag_uid when both are supplied.
  1024. Returns 409 if another spool already carries the same tag.
  1025. Uses extra_lock to serialise against concurrent extra-field writes.
  1026. """
  1027. client = await _get_client(db)
  1028. tag = (data.tray_uuid or data.tag_uid).upper()
  1029. tag_json = json.dumps(tag)
  1030. async with client.extra_lock(spool_id):
  1031. # Duplicate check: scan all spools for the same tag on a different spool.
  1032. async with _translate_spoolman_errors():
  1033. all_spools = await client.get_all_spools()
  1034. for s in all_spools:
  1035. s_tag = (s.get("extra") or {}).get("tag", "")
  1036. if s_tag.strip('"').upper() == tag and s.get("id") != spool_id:
  1037. raise HTTPException(
  1038. status_code=409,
  1039. detail=f"Tag is already assigned to spool {s['id']}",
  1040. )
  1041. # Re-fetch inside the lock so cur_extra reflects any concurrent update.
  1042. async with _translate_spoolman_errors():
  1043. current = await client.get_spool(spool_id)
  1044. cur_extra = dict(current.get("extra") or {})
  1045. cur_extra["tag"] = tag_json
  1046. async with _translate_spoolman_errors():
  1047. updated = await client.update_spool_full(spool_id=spool_id, extra=cur_extra)
  1048. logger.info("Linked tag %s to Spoolman spool %s", tag, spool_id)
  1049. await ws_manager.broadcast({"type": "inventory_changed"})
  1050. return _map_spoolman_spool(updated)
  1051. @router.get("/slot-assignments/all", response_model=list[SpoolmanSlotAssignmentEnriched])
  1052. async def get_all_spoolman_slot_assignments(
  1053. printer_id: int | None = Query(None, gt=0),
  1054. db: AsyncSession = Depends(get_db),
  1055. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1056. ) -> list[SpoolmanSlotAssignmentEnriched]:
  1057. """Return all Spoolman slot assignments enriched with printer_name and ams_label.
  1058. ``printer_name`` is null only when the printer relation is missing
  1059. (cascade-deleted edge case). ``ams_label`` is null when no AmsLabel row
  1060. matches the slot's MQTT serial (or the synthetic ``f"p{pid}a{ams_id}"``
  1061. fallback key).
  1062. """
  1063. query = select(SpoolmanSlotAssignment).options(selectinload(SpoolmanSlotAssignment.printer))
  1064. if printer_id is not None:
  1065. query = query.where(SpoolmanSlotAssignment.printer_id == printer_id)
  1066. result = await db.execute(query)
  1067. slots = list(result.scalars().all())
  1068. # Build (printer_id, ams_id) -> ams_serial map from live printer states.
  1069. # Same pattern as inventory.py:765-806 for the local /assignments endpoint.
  1070. printer_ids = {s.printer_id for s in slots}
  1071. serial_map: dict[tuple[int, int], str] = {}
  1072. all_statuses = printer_manager.get_all_statuses()
  1073. for pid in printer_ids:
  1074. state = all_statuses.get(pid)
  1075. if not (state and state.raw_data):
  1076. continue
  1077. # Some printer firmware variants wrap the AMS list in an outer dict
  1078. # (`{"ams": [...]}`). Mirror the defense used in sync_spoolman_ams_weights
  1079. # (line 842-844) so a wrapped payload still resolves to a list.
  1080. ams_raw = state.raw_data.get("ams", [])
  1081. if isinstance(ams_raw, dict):
  1082. ams_raw = ams_raw.get("ams", [])
  1083. if not isinstance(ams_raw, list):
  1084. continue
  1085. for ams_unit in ams_raw:
  1086. if not isinstance(ams_unit, dict):
  1087. continue
  1088. sn = str(ams_unit.get("sn") or ams_unit.get("serial_number") or "")
  1089. if not sn:
  1090. continue
  1091. try:
  1092. serial_map[(pid, int(ams_unit.get("id", 0)))] = sn
  1093. except (ValueError, TypeError):
  1094. continue
  1095. # Add synthetic fallback key (f"p{pid}a{ams_id}") for slots without a serial.
  1096. all_serials: set[str] = set(serial_map.values())
  1097. for s in slots:
  1098. if (s.printer_id, s.ams_id) not in serial_map:
  1099. all_serials.add(f"p{s.printer_id}a{s.ams_id}")
  1100. label_by_serial: dict[str, str] = {}
  1101. if all_serials:
  1102. lbl_result = await db.execute(select(AmsLabel).where(AmsLabel.ams_serial_number.in_(all_serials)))
  1103. for lbl in lbl_result.scalars().all():
  1104. label_by_serial[lbl.ams_serial_number] = lbl.label
  1105. def _ams_label_for(pid: int, ams_id: int) -> str | None:
  1106. sn = serial_map.get((pid, ams_id))
  1107. if sn and sn in label_by_serial:
  1108. return label_by_serial[sn]
  1109. if not sn:
  1110. return label_by_serial.get(f"p{pid}a{ams_id}")
  1111. return None
  1112. enriched: list[SpoolmanSlotAssignmentEnriched] = []
  1113. for s in slots:
  1114. if s.printer is None:
  1115. # FK is ondelete=CASCADE so this should be unreachable in normal
  1116. # operation; surface it loudly if a stale row ever appears.
  1117. logger.warning(
  1118. "Orphaned Spoolman slot assignment: printer_id=%d (ams=%d, tray=%d, spoolman_spool_id=%d) has no Printer row",
  1119. s.printer_id,
  1120. s.ams_id,
  1121. s.tray_id,
  1122. s.spoolman_spool_id,
  1123. )
  1124. enriched.append(
  1125. SpoolmanSlotAssignmentEnriched(
  1126. printer_id=s.printer_id,
  1127. printer_name=s.printer.name if s.printer else None,
  1128. ams_id=s.ams_id,
  1129. tray_id=s.tray_id,
  1130. spoolman_spool_id=s.spoolman_spool_id,
  1131. ams_label=_ams_label_for(s.printer_id, s.ams_id),
  1132. )
  1133. )
  1134. return enriched
  1135. @router.post("/sync-ams-weights")
  1136. async def sync_spoolman_ams_weights(
  1137. db: AsyncSession = Depends(get_db),
  1138. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1139. ):
  1140. """Sync remaining weight back to Spoolman for all slot-assigned spools.
  1141. Reads live AMS remain% from connected printers, computes
  1142. remaining = label_weight * remain% / 100, and PATCHes Spoolman.
  1143. """
  1144. client = await _get_client(db)
  1145. # Fetch all non-archived Spoolman spools once for label_weight lookup
  1146. async with _translate_spoolman_errors():
  1147. raw_spools = await client.get_all_spools(allow_archived=False)
  1148. spool_lookup: dict[int, dict] = {s["id"]: s for s in raw_spools if s.get("id") is not None}
  1149. result = await db.execute(select(SpoolmanSlotAssignment))
  1150. assignments = list(result.scalars().all())
  1151. synced = 0
  1152. skipped = 0
  1153. def _find_tray(ams_data: list, ams_id: int, tray_id: int) -> dict | None:
  1154. if not ams_data:
  1155. return None
  1156. for ams_unit in ams_data:
  1157. if _safe_int(ams_unit.get("id"), -1) != ams_id:
  1158. continue
  1159. for tray in ams_unit.get("tray", []):
  1160. if _safe_int(tray.get("id"), -1) == tray_id:
  1161. return tray
  1162. return None
  1163. for assignment in assignments:
  1164. spool_dict = spool_lookup.get(assignment.spoolman_spool_id)
  1165. if not spool_dict:
  1166. logger.debug("Spoolman AMS sync: spool %d not found in Spoolman, skipping", assignment.spoolman_spool_id)
  1167. skipped += 1
  1168. continue
  1169. label_weight = _safe_int((spool_dict.get("filament") or {}).get("weight"), 1000)
  1170. if label_weight <= 0:
  1171. logger.debug("Spoolman AMS sync: spool %d has no label_weight, skipping", assignment.spoolman_spool_id)
  1172. skipped += 1
  1173. continue
  1174. state = printer_manager.get_status(assignment.printer_id)
  1175. if not state or not state.raw_data:
  1176. logger.info(
  1177. "Spoolman AMS sync: printer %d not connected, skipping spool %d",
  1178. assignment.printer_id,
  1179. assignment.spoolman_spool_id,
  1180. )
  1181. skipped += 1
  1182. continue
  1183. ams_raw = state.raw_data.get("ams", [])
  1184. if isinstance(ams_raw, dict):
  1185. ams_raw = ams_raw.get("ams", [])
  1186. tray = _find_tray(ams_raw, assignment.ams_id, assignment.tray_id)
  1187. if not tray:
  1188. logger.info(
  1189. "Spoolman AMS sync: no tray data for spool %d (printer %d AMS%d-T%d)",
  1190. assignment.spoolman_spool_id,
  1191. assignment.printer_id,
  1192. assignment.ams_id,
  1193. assignment.tray_id,
  1194. )
  1195. skipped += 1
  1196. continue
  1197. remain_raw = tray.get("remain")
  1198. if remain_raw is None:
  1199. logger.debug(
  1200. "Spoolman AMS sync: no remain value for spool %d (tray %d/%d), skipping",
  1201. assignment.spoolman_spool_id,
  1202. assignment.ams_id,
  1203. assignment.tray_id,
  1204. )
  1205. skipped += 1
  1206. continue
  1207. try:
  1208. remain_val = int(remain_raw)
  1209. except (TypeError, ValueError):
  1210. logger.debug(
  1211. "Spoolman AMS sync: non-numeric remain=%r for spool %d, skipping",
  1212. remain_raw,
  1213. assignment.spoolman_spool_id,
  1214. )
  1215. skipped += 1
  1216. continue
  1217. if remain_val < 0 or remain_val > 100:
  1218. logger.debug("Spoolman AMS sync: invalid remain=%s for spool %d", remain_raw, assignment.spoolman_spool_id)
  1219. skipped += 1
  1220. continue
  1221. remaining = round(label_weight * remain_val / 100.0, 1)
  1222. try:
  1223. async with _translate_spoolman_errors():
  1224. await client.update_spool_full(assignment.spoolman_spool_id, remaining_weight=remaining)
  1225. logger.info(
  1226. "Spoolman AMS sync: spool %d remaining set to %s g (remain=%d%%)",
  1227. assignment.spoolman_spool_id,
  1228. remaining,
  1229. remain_val,
  1230. )
  1231. synced += 1
  1232. except HTTPException as exc:
  1233. if exc.status_code == 404:
  1234. logger.warning(
  1235. "Spoolman AMS sync: spool %d not found in Spoolman (404), skipping",
  1236. assignment.spoolman_spool_id,
  1237. )
  1238. else:
  1239. logger.warning(
  1240. "Spoolman AMS sync: failed to update spool %d (HTTP %d)",
  1241. assignment.spoolman_spool_id,
  1242. exc.status_code,
  1243. )
  1244. skipped += 1
  1245. return {"synced": synced, "skipped": skipped}
  1246. @router.post("/slot-assignments")
  1247. async def assign_spoolman_slot(
  1248. body: SpoolSlotAssignmentRequest,
  1249. db: AsyncSession = Depends(get_db),
  1250. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1251. ) -> dict:
  1252. """Assign a Spoolman spool to a printer AMS slot (stored in local DB only).
  1253. Raises 404 if the printer does not exist or the spool is not found in Spoolman.
  1254. Spoolman's own ``spool.location`` field is NOT touched — it is user-managed.
  1255. """
  1256. client = await _get_client(db)
  1257. result = await db.execute(select(Printer).where(Printer.id == body.printer_id))
  1258. printer = result.scalar_one_or_none()
  1259. if not printer:
  1260. raise HTTPException(status_code=404, detail="Printer not found")
  1261. # Verify the Spoolman spool exists before committing to local DB.
  1262. # This prevents ghost rows pointing at non-existent spool IDs.
  1263. async with _translate_spoolman_errors():
  1264. spool = await client.get_spool(body.spoolman_spool_id)
  1265. # Spool confirmed in Spoolman — upsert into local slot-assignment table
  1266. # assigned_at is intentionally not refreshed on re-assign (original timestamp preserved)
  1267. try:
  1268. await db.execute(
  1269. text(
  1270. "INSERT INTO spoolman_slot_assignments"
  1271. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  1272. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  1273. " ON CONFLICT(printer_id, ams_id, tray_id)"
  1274. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  1275. ),
  1276. {
  1277. "printer_id": body.printer_id,
  1278. "ams_id": body.ams_id,
  1279. "tray_id": body.tray_id,
  1280. "spool_id": body.spoolman_spool_id,
  1281. },
  1282. )
  1283. await db.commit()
  1284. except Exception as exc:
  1285. await db.rollback()
  1286. logger.error("Failed to persist slot assignment: %s", exc)
  1287. raise HTTPException(status_code=500, detail="Failed to save slot assignment") from exc
  1288. # #1457: clear stale fallback-tag links on OTHER spools still bound to this
  1289. # slot. Without this, a non-RFID slot's deterministic fallback tag stays
  1290. # attached to the previous spool in Spoolman's extra.tag and re-surfaces in
  1291. # the hover card whenever the local slot assignment is removed.
  1292. if printer.serial_number:
  1293. await _clear_stale_slot_fallback_tag_links(
  1294. client,
  1295. printer_serial=printer.serial_number,
  1296. ams_id=body.ams_id,
  1297. tray_id=body.tray_id,
  1298. keep_spool_id=body.spoolman_spool_id,
  1299. )
  1300. mapped = _map_spoolman_spool(spool)
  1301. # Fetch K-profiles before the MQTT try block so we can use async DB access.
  1302. kp_rows_result = await db.execute(
  1303. select(SpoolmanKProfile).where(
  1304. SpoolmanKProfile.spoolman_spool_id == body.spoolman_spool_id,
  1305. SpoolmanKProfile.printer_id == body.printer_id,
  1306. )
  1307. )
  1308. kp_rows = kp_rows_result.scalars().all()
  1309. # Auto-configure AMS slot via MQTT (best-effort; slot assignment is already persisted)
  1310. try:
  1311. mqtt_client = printer_manager.get_client(body.printer_id)
  1312. if mqtt_client:
  1313. # Spoolman's material is free text, so it arrives as whatever the
  1314. # user typed there -- "PLA+", "PolyTerra PLA". The sub-brand keeps
  1315. # that wording; the slot's type has to be one the printer and the
  1316. # slicer know (issue #2902).
  1317. material = mapped.get("material") or ""
  1318. tray_type = printer_filament_type(material)
  1319. brand = mapped.get("brand") or ""
  1320. subtype = mapped.get("subtype") or ""
  1321. if brand:
  1322. tray_sub_brands = f"{brand} {material} {subtype}".strip()
  1323. elif subtype:
  1324. tray_sub_brands = f"{material} {subtype}".strip()
  1325. else:
  1326. tray_sub_brands = material
  1327. tray_color = (mapped.get("rgba") or "808080FF").upper()
  1328. if len(tray_color) == 6:
  1329. tray_color = tray_color + "FF"
  1330. # Printer state, read here rather than further down because the
  1331. # per-model preset override below needs the slot's nozzle
  1332. # diameter and the K-profile cascade further down needs the same
  1333. # value -- one read, so they cannot disagree. (The previous
  1334. # `mqtt_client.printer_state` access via hasattr always returned
  1335. # None -- the attribute is `state`, not `printer_state` -- so the
  1336. # K-profile cascade silently skipped state.kprofiles, defaulted
  1337. # nozzle_diameter to 0.4, and left slot_extruder unset.)
  1338. state = printer_manager.get_status(body.printer_id)
  1339. slot_nozzle = resolve_slot_nozzle(
  1340. state, body.ams_id, body.tray_id, printer_manager.get_model(body.printer_id)
  1341. )
  1342. nozzle_diameter = slot_nozzle.diameter
  1343. # Per-printer-model preset override, same cascade as internal
  1344. # mode: a cloud/Orca preset is bound to a model, so one stored
  1345. # preset per spool is wrong across two models. Returns Spoolman's
  1346. # own value when no override is set.
  1347. slot_slicer_filament, slot_slicer_filament_name = await resolve_spoolman_preset(
  1348. db,
  1349. spoolman_spool_id=body.spoolman_spool_id,
  1350. printer_model=printer_manager.get_model(body.printer_id),
  1351. nozzle_diameter=nozzle_diameter,
  1352. fallback_filament=mapped.get("slicer_filament"),
  1353. fallback_name=mapped.get("slicer_filament_name"),
  1354. )
  1355. # #1713: resolve the spool's stored slicer_filament reference
  1356. # (cloud preset, local preset, GF-prefix builtin, or numeric
  1357. # LocalPreset id) to the printer-side tray_info_idx + setting_id.
  1358. # Previously the Spoolman path dropped slicer_filament on the
  1359. # floor and only the generic-material fallback fired; the user-
  1360. # configured profile never reached the printer. Shared with the
  1361. # internal-mode route via the same helper so the two flows can't
  1362. # drift again.
  1363. tray_info_idx, setting_id, sub_brand_override, type_override = await resolve_slicer_filament(
  1364. db=db,
  1365. current_user=current_user,
  1366. slicer_filament=slot_slicer_filament,
  1367. slicer_filament_name=slot_slicer_filament_name,
  1368. material=material,
  1369. )
  1370. if sub_brand_override:
  1371. tray_sub_brands = sub_brand_override
  1372. # A preset carries its own type; the reduction above only infers
  1373. # one from Spoolman's free-text material. The preset wins when the
  1374. # spool has one (issue #2902, @doncaruana).
  1375. if type_override:
  1376. tray_type = printer_filament_type(type_override)
  1377. material_upper = material.upper().strip()
  1378. # Fall back to generic-material id when slicer_filament is empty
  1379. # or the resolver discarded an unresolvable value. Matches the
  1380. # internal-mode tail in inventory.py:_apply_spool_to_slot_inner,
  1381. # including the order: the spool's own wording first and the
  1382. # reduced type only after it, so "PETG HF" keeps its own generic
  1383. # preset (GFG96) rather than trading it for "PETG"'s GFG99.
  1384. if not tray_info_idx:
  1385. tray_info_idx = (
  1386. GENERIC_FILAMENT_IDS.get(material_upper)
  1387. or GENERIC_FILAMENT_IDS.get(material_upper.split("-")[0].split(" ")[0])
  1388. or GENERIC_FILAMENT_IDS.get(tray_type.upper())
  1389. or ""
  1390. )
  1391. # Ensure setting_id is always derivable from tray_info_idx. The
  1392. # local-preset path can leave it empty when the LP's setting JSON
  1393. # has no filament_id and falls through to the generic material id;
  1394. # without this fallback the slicer gets a half-configured slot
  1395. # (filament id without setting id) and the slot detail modal
  1396. # renders empty fields. Same pattern as the internal-mode tail.
  1397. if tray_info_idx and not setting_id:
  1398. setting_id = filament_id_to_setting_id(tray_info_idx)
  1399. temp_defaults = nozzle_temp_range(material, tray_type)
  1400. temp_min = mapped.get("nozzle_temp_min") or temp_defaults[0]
  1401. temp_max = temp_defaults[1]
  1402. # Pull printer state from printer_manager. The previous
  1403. # `mqtt_client.printer_state` access via hasattr always returned
  1404. # None (the attribute is `state`, not `printer_state`), so the
  1405. # K-profile cascade silently skipped state.kprofiles, defaulted
  1406. # nozzle_diameter to 0.4, and left slot_extruder unset.
  1407. slot_extruder = slot_nozzle.extruder
  1408. # Prefer exact extruder match, fall back to extruder-agnostic kp
  1409. # for the same nozzle. Hard-skipping on mismatch silently dropped
  1410. # valid stored profiles when the AMS-extruder mapping had shifted.
  1411. exact_kp = None
  1412. fallback_kp = None
  1413. for kp in kp_rows:
  1414. if kp.nozzle_diameter != nozzle_diameter or kp.cali_idx is None:
  1415. continue
  1416. if not slot_nozzle.flow_matches(kp.nozzle_type):
  1417. continue
  1418. if slot_extruder is not None and kp.extruder is not None and kp.extruder == slot_extruder:
  1419. exact_kp = kp
  1420. break
  1421. if fallback_kp is None:
  1422. fallback_kp = kp
  1423. matching_kp = exact_kp or fallback_kp
  1424. # Resolve the printer-side calibration entry by cali_idx so we
  1425. # know the authoritative filament_id (the printer indexes its
  1426. # calibration table by filament_id, not setting_id).
  1427. printer_kp = None
  1428. if matching_kp and state and state.kprofiles:
  1429. for pkp in state.kprofiles:
  1430. if pkp.slot_id == matching_kp.cali_idx and pkp.nozzle_diameter == nozzle_diameter:
  1431. printer_kp = pkp
  1432. break
  1433. if printer_kp is None:
  1434. logger.warning(
  1435. "Spoolman assign: cali_idx=%d not present in printer's "
  1436. "calibration table — stored kp may be stale.",
  1437. matching_kp.cali_idx,
  1438. )
  1439. # Realign the slot's filament context (tray_info_idx + setting_id)
  1440. # to the kp's calibration context. Without this, ams_filament_setting
  1441. # declares the slot under generic PLA while extrusion_cali_sel points
  1442. # the cali_idx at a different preset — the printer can't link them
  1443. # and falls back to the default profile. P-prefix local presets are
  1444. # valid for tray_info_idx; PFUS-prefix cloud-user presets are not
  1445. # (the slicer rejects them).
  1446. effective_tray_info_idx = tray_info_idx
  1447. effective_setting_id = setting_id
  1448. if printer_kp and printer_kp.filament_id:
  1449. if not printer_kp.filament_id.startswith("PFUS"):
  1450. effective_tray_info_idx = printer_kp.filament_id
  1451. if printer_kp.setting_id:
  1452. effective_setting_id = printer_kp.setting_id
  1453. elif matching_kp and matching_kp.setting_id:
  1454. derived = normalize_slicer_filament(matching_kp.setting_id)[0]
  1455. if derived and not derived.startswith("PFUS"):
  1456. effective_tray_info_idx = derived
  1457. effective_setting_id = matching_kp.setting_id
  1458. if effective_tray_info_idx != tray_info_idx or effective_setting_id != setting_id:
  1459. logger.info(
  1460. "Spoolman assign: realigning tray_info_idx %r → %r, setting_id %r → %r (kp_id=%s, source=%s)",
  1461. tray_info_idx,
  1462. effective_tray_info_idx,
  1463. setting_id,
  1464. effective_setting_id,
  1465. matching_kp.id if matching_kp else None,
  1466. "printer" if printer_kp else "stored",
  1467. )
  1468. mqtt_client.ams_set_filament_setting(
  1469. ams_id=body.ams_id,
  1470. tray_id=body.tray_id,
  1471. tray_info_idx=effective_tray_info_idx,
  1472. tray_type=tray_type,
  1473. tray_sub_brands=tray_sub_brands,
  1474. tray_color=tray_color,
  1475. nozzle_temp_min=temp_min,
  1476. nozzle_temp_max=temp_max,
  1477. setting_id=effective_setting_id,
  1478. )
  1479. if matching_kp and matching_kp.cali_idx is not None:
  1480. # Use printer-reported filament_id when available, otherwise
  1481. # fall back to the realigned tray_info_idx so both commands
  1482. # reference the same filament context.
  1483. cali_filament_id = (
  1484. printer_kp.filament_id if printer_kp and printer_kp.filament_id else None
  1485. ) or effective_tray_info_idx
  1486. mqtt_client.extrusion_cali_sel(
  1487. ams_id=body.ams_id,
  1488. tray_id=body.tray_id,
  1489. cali_idx=matching_kp.cali_idx,
  1490. filament_id=cali_filament_id,
  1491. nozzle_diameter=nozzle_diameter,
  1492. )
  1493. logger.info(
  1494. "Spoolman assign: applied K-profile cali_idx=%d "
  1495. "(kp_id=%d, filament_id=%s) for spool %d on printer %d AMS%d-T%d",
  1496. matching_kp.cali_idx,
  1497. matching_kp.id,
  1498. cali_filament_id,
  1499. body.spoolman_spool_id,
  1500. body.printer_id,
  1501. body.ams_id,
  1502. body.tray_id,
  1503. )
  1504. else:
  1505. # No stored K-profile for this spool — always reset the slot to
  1506. # Default K (cali_idx=-1). The live cali_idx belongs to whatever
  1507. # filament was there before, so preserving it would apply the
  1508. # wrong filament's calibration to the new spool.
  1509. mqtt_client.extrusion_cali_sel(
  1510. ams_id=body.ams_id,
  1511. tray_id=body.tray_id,
  1512. cali_idx=-1,
  1513. filament_id=effective_tray_info_idx,
  1514. nozzle_diameter=nozzle_diameter,
  1515. )
  1516. logger.info(
  1517. "No stored K-profile for Spoolman spool %d — reset slot to Default K (cali_idx=-1)",
  1518. body.spoolman_spool_id,
  1519. )
  1520. logger.info(
  1521. "Auto-configured AMS slot ams=%d tray=%d for Spoolman spool %d on printer %d",
  1522. body.ams_id,
  1523. body.tray_id,
  1524. body.spoolman_spool_id,
  1525. body.printer_id,
  1526. )
  1527. except Exception:
  1528. logger.exception(
  1529. "Failed to auto-configure AMS slot for Spoolman spool %d (printer=%d, ams=%d, tray=%d)",
  1530. body.spoolman_spool_id,
  1531. body.printer_id,
  1532. body.ams_id,
  1533. body.tray_id,
  1534. )
  1535. return mapped
  1536. @router.delete("/slot-assignments/{spoolman_spool_id}")
  1537. async def unassign_spoolman_slot(
  1538. spoolman_spool_id: int = Path(..., gt=0),
  1539. db: AsyncSession = Depends(get_db),
  1540. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1541. ) -> dict:
  1542. """Remove the local slot assignment for a Spoolman spool.
  1543. Spoolman's own ``spool.location`` field is NOT touched — it is user-managed.
  1544. """
  1545. client = await _get_client(db)
  1546. try:
  1547. await db.execute(
  1548. delete(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.spoolman_spool_id == spoolman_spool_id)
  1549. )
  1550. await db.commit()
  1551. except Exception as exc:
  1552. await db.rollback()
  1553. logger.error("Failed to delete slot assignment: %s", exc)
  1554. raise HTTPException(status_code=500, detail="Failed to remove slot assignment") from exc
  1555. # Fetch the spool from Spoolman to return in InventorySpool format.
  1556. # If the spool no longer exists in Spoolman, the local unassignment still succeeded.
  1557. try:
  1558. async with _translate_spoolman_errors():
  1559. spool = await client.get_spool(spoolman_spool_id)
  1560. return _map_spoolman_spool(spool)
  1561. except HTTPException as exc:
  1562. if exc.status_code != 404:
  1563. raise
  1564. # Spool no longer exists in Spoolman; unassignment still succeeded.
  1565. return {"id": spoolman_spool_id}
  1566. @router.get("/slot-assignments")
  1567. async def get_spoolman_slot_assignment(
  1568. printer_id: int = Query(..., gt=0),
  1569. ams_id: int = Query(..., ge=0, le=7),
  1570. tray_id: int = Query(..., ge=0, le=3),
  1571. db: AsyncSession = Depends(get_db),
  1572. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1573. ) -> dict | None:
  1574. """Return the Spoolman spool assigned to a specific printer slot, or null if unassigned."""
  1575. client = await _get_client(db)
  1576. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1577. printer = result.scalar_one_or_none()
  1578. if not printer:
  1579. raise HTTPException(status_code=404, detail="Printer not found")
  1580. slot_result = await db.execute(
  1581. select(SpoolmanSlotAssignment).where(
  1582. SpoolmanSlotAssignment.printer_id == printer_id,
  1583. SpoolmanSlotAssignment.ams_id == ams_id,
  1584. SpoolmanSlotAssignment.tray_id == tray_id,
  1585. )
  1586. )
  1587. slot = slot_result.scalar_one_or_none()
  1588. if not slot:
  1589. return None
  1590. try:
  1591. async with _translate_spoolman_errors():
  1592. spool = await client.get_spool(slot.spoolman_spool_id)
  1593. return _map_spoolman_spool(spool)
  1594. except HTTPException as exc:
  1595. if exc.status_code != 404:
  1596. raise
  1597. # Spool deleted in Spoolman — clean up stale assignment.
  1598. # Include spoolman_spool_id in WHERE to avoid a TOCTOU race where a
  1599. # concurrent re-assign changed the slot to a different spool between
  1600. # the GET and this DELETE.
  1601. try:
  1602. await db.execute(
  1603. delete(SpoolmanSlotAssignment).where(
  1604. SpoolmanSlotAssignment.id == slot.id,
  1605. SpoolmanSlotAssignment.spoolman_spool_id == slot.spoolman_spool_id,
  1606. )
  1607. )
  1608. await db.commit()
  1609. except Exception as cleanup_exc:
  1610. await db.rollback()
  1611. logger.warning(
  1612. "Failed to remove stale slot assignment for spool %s: %s",
  1613. slot.spoolman_spool_id,
  1614. cleanup_exc,
  1615. )
  1616. return None
  1617. def _k_profile_to_dict(p: SpoolmanKProfile) -> dict:
  1618. """Manually map SpoolmanKProfile → SpoolKProfileResponse-compatible dict."""
  1619. return {
  1620. "id": p.id,
  1621. "spool_id": p.spoolman_spool_id,
  1622. "printer_id": p.printer_id,
  1623. "extruder": p.extruder,
  1624. "nozzle_diameter": p.nozzle_diameter,
  1625. "nozzle_type": p.nozzle_type,
  1626. "k_value": p.k_value,
  1627. "name": p.name,
  1628. "cali_idx": p.cali_idx,
  1629. "setting_id": p.setting_id,
  1630. "created_at": p.created_at,
  1631. }
  1632. def _filament_preset_to_dict(p: SpoolmanFilamentPreset) -> dict:
  1633. """Manually map SpoolmanFilamentPreset → SpoolFilamentPresetResponse-compatible dict."""
  1634. return {
  1635. "id": p.id,
  1636. "spool_id": p.spoolman_spool_id,
  1637. "printer_model": p.printer_model,
  1638. "nozzle_diameter": p.nozzle_diameter,
  1639. "slicer_filament": p.slicer_filament,
  1640. "slicer_filament_name": p.slicer_filament_name,
  1641. "created_at": p.created_at,
  1642. }
  1643. @router.get("/spools/{spool_id}/filament-presets")
  1644. async def get_spoolman_filament_presets(
  1645. spool_id: int = Path(..., gt=0),
  1646. db: AsyncSession = Depends(get_db),
  1647. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1648. ) -> list[dict]:
  1649. """Return all per-printer-model preset overrides for a Spoolman spool."""
  1650. await _get_client(db)
  1651. result = await db.execute(
  1652. select(SpoolmanFilamentPreset).where(SpoolmanFilamentPreset.spoolman_spool_id == spool_id)
  1653. )
  1654. return [_filament_preset_to_dict(p) for p in result.scalars().all()]
  1655. @router.put("/spools/{spool_id}/filament-presets")
  1656. async def save_spoolman_filament_presets(
  1657. spool_id: int = Path(..., gt=0),
  1658. presets: list[SpoolFilamentPresetBase] = Body(...),
  1659. db: AsyncSession = Depends(get_db),
  1660. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1661. ) -> list[dict]:
  1662. """Replace all per-printer-model preset overrides for a Spoolman spool."""
  1663. client = await _get_client(db)
  1664. async with _translate_spoolman_errors():
  1665. await client.get_spool(spool_id)
  1666. # Same as the internal route: reject a duplicated (model, diameter) before
  1667. # touching the stored rows, so a bad payload cannot clear what it fails to
  1668. # replace.
  1669. seen: set[tuple[str, str]] = set()
  1670. for preset in presets:
  1671. key = (preset.printer_model, preset.nozzle_diameter)
  1672. if key in seen:
  1673. raise HTTPException(
  1674. 422,
  1675. f"Duplicate override for model {preset.printer_model!r} nozzle {preset.nozzle_diameter or 'any'!r}",
  1676. )
  1677. seen.add(key)
  1678. saved: list[SpoolmanFilamentPreset] = []
  1679. try:
  1680. await db.execute(delete(SpoolmanFilamentPreset).where(SpoolmanFilamentPreset.spoolman_spool_id == spool_id))
  1681. await db.flush()
  1682. for preset in presets:
  1683. obj = SpoolmanFilamentPreset(
  1684. spoolman_spool_id=spool_id,
  1685. printer_model=preset.printer_model,
  1686. nozzle_diameter=preset.nozzle_diameter,
  1687. slicer_filament=preset.slicer_filament,
  1688. slicer_filament_name=preset.slicer_filament_name,
  1689. )
  1690. db.add(obj)
  1691. saved.append(obj)
  1692. await db.commit()
  1693. except IntegrityError as exc:
  1694. await db.rollback()
  1695. raise HTTPException(422, "Duplicate or invalid preset override (check model and nozzle uniqueness)") from exc
  1696. except HTTPException:
  1697. raise
  1698. except Exception as exc:
  1699. await db.rollback()
  1700. logger.error("Filament preset save for spool %d failed: %s", spool_id, exc)
  1701. raise HTTPException(500, "Failed to save filament presets") from exc
  1702. for obj in saved:
  1703. await db.refresh(obj)
  1704. return [_filament_preset_to_dict(p) for p in saved]
  1705. def _normalize_filament(raw: dict) -> NormalizedFilament | None:
  1706. """Normalise a raw Spoolman filament dict for the frontend catalog picker.
  1707. Returns None for entries with missing/zero IDs — those are malformed and
  1708. must be filtered out before returning to the client.
  1709. weight=0 is collapsed to None — 0g is not a valid filament weight.
  1710. """
  1711. filament_id = _safe_int(raw.get("id"), 0)
  1712. if filament_id <= 0:
  1713. logger.warning("Skipping Spoolman filament with missing or invalid id: %r", raw.get("name"))
  1714. return None
  1715. vendor = raw.get("vendor") or {}
  1716. vendor_ref: NormalizedVendorRef | None = None
  1717. if vendor:
  1718. vendor_id = _safe_int(vendor.get("id"), 0)
  1719. if vendor_id <= 0:
  1720. logger.warning("Spoolman filament %d has vendor without valid id — vendor omitted", filament_id)
  1721. else:
  1722. vendor_ref = {"id": vendor_id, "name": str(vendor.get("name") or "").strip() or "Unknown"}
  1723. return NormalizedFilament(
  1724. id=filament_id,
  1725. name=str(raw.get("name") or ""),
  1726. material=raw.get("material") or None,
  1727. color_hex=raw.get("color_hex") or None,
  1728. color_name=raw.get("color_name") or None,
  1729. weight=_safe_int(raw.get("weight"), 0) or None, # 0g is not a valid weight
  1730. spool_weight=_safe_optional_float(raw.get("spool_weight")),
  1731. vendor=vendor_ref,
  1732. )
  1733. @router.get("/filaments")
  1734. async def list_spoolman_filaments(
  1735. db: AsyncSession = Depends(get_db),
  1736. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1737. ) -> list[NormalizedFilament]:
  1738. """Return all filaments from Spoolman, normalised for the frontend catalog picker."""
  1739. client = await _get_client(db)
  1740. async with _translate_spoolman_errors():
  1741. raw_filaments = await client.get_filaments()
  1742. if not isinstance(raw_filaments, list):
  1743. logger.warning("Spoolman get_filaments() returned non-list type: %s", type(raw_filaments).__name__)
  1744. return []
  1745. return [f for raw in raw_filaments if (f := _normalize_filament(raw)) is not None]
  1746. @router.patch("/filaments/{filament_id}")
  1747. async def patch_spoolman_filament(
  1748. *,
  1749. filament_id: int = Path(..., gt=0),
  1750. body: SpoolmanFilamentPatch = Body(...),
  1751. db: AsyncSession = Depends(get_db),
  1752. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1753. ) -> NormalizedFilament:
  1754. """Update a Spoolman filament's name and/or spool_weight.
  1755. When spool_weight changes, Option A (keep_existing_spools=True) stamps the old
  1756. weight onto spools currently inheriting it (spool.spool_weight is None) so their
  1757. tare calculations are unaffected by the filament change.
  1758. Option B (keep_existing_spools=False, the default): when spool_weight is a
  1759. concrete value, stamps it onto every affected spool explicitly; when spool_weight
  1760. is null, clears per-spool overrides so spools fall back to the filament value.
  1761. """
  1762. client = await _get_client(db)
  1763. async with _translate_spoolman_errors():
  1764. current = await client.get_filament(filament_id)
  1765. patch_data = {k: v for k, v in body.model_dump(exclude_unset=True).items() if k != "keep_existing_spools"}
  1766. if not patch_data:
  1767. normalized = _normalize_filament(current)
  1768. if normalized is None:
  1769. raise HTTPException(status_code=404, detail="Filament not found")
  1770. return normalized
  1771. async with _translate_spoolman_errors():
  1772. updated = await client.patch_filament(filament_id, patch_data)
  1773. if "spool_weight" in body.model_fields_set:
  1774. async with _translate_spoolman_errors():
  1775. all_spools = await client.get_all_spools()
  1776. affected_spools = [s for s in all_spools if (s.get("filament") or {}).get("id") == filament_id]
  1777. if affected_spools:
  1778. if body.keep_existing_spools:
  1779. old_weight = _safe_optional_float(current.get("spool_weight"))
  1780. if old_weight is not None:
  1781. spools_to_fix = [s for s in affected_spools if s.get("spool_weight") is None]
  1782. if spools_to_fix:
  1783. async with _translate_spoolman_errors():
  1784. results = await asyncio.gather(
  1785. *(
  1786. client.update_spool_full(spool_id=s["id"], spool_weight=old_weight)
  1787. for s in spools_to_fix
  1788. ),
  1789. return_exceptions=True,
  1790. )
  1791. _raise_if_partial_failure(spools_to_fix, results, "spool_weight stamp (option A)")
  1792. else:
  1793. new_weight = body.spool_weight
  1794. if new_weight is not None:
  1795. # Stamp the new weight onto every spool of this filament type so
  1796. # each spool carries the value explicitly rather than inheriting.
  1797. async with _translate_spoolman_errors():
  1798. results = await asyncio.gather(
  1799. *(
  1800. client.update_spool_full(spool_id=s["id"], spool_weight=new_weight)
  1801. for s in affected_spools
  1802. ),
  1803. return_exceptions=True,
  1804. )
  1805. _raise_if_partial_failure(affected_spools, results, "spool_weight stamp (option B)")
  1806. else:
  1807. # Filament weight is being cleared — remove any per-spool override
  1808. # so spools fall back to whatever the filament now provides.
  1809. spools_to_clear = [s for s in affected_spools if s.get("spool_weight") is not None]
  1810. if spools_to_clear:
  1811. async with _translate_spoolman_errors():
  1812. results = await asyncio.gather(
  1813. *(
  1814. client.update_spool_full(spool_id=s["id"], clear_spool_weight=True)
  1815. for s in spools_to_clear
  1816. ),
  1817. return_exceptions=True,
  1818. )
  1819. _raise_if_partial_failure(spools_to_clear, results, "spool_weight clear (option B null)")
  1820. normalized = _normalize_filament(updated)
  1821. if normalized is None:
  1822. raise HTTPException(status_code=502, detail="Spoolman returned malformed filament data")
  1823. return normalized
  1824. @router.get("/spools/{spool_id}/k-profiles")
  1825. async def get_spoolman_k_profiles(
  1826. spool_id: int = Path(..., gt=0),
  1827. db: AsyncSession = Depends(get_db),
  1828. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  1829. ) -> list[dict]:
  1830. """Return all local K-value calibration profiles for a Spoolman spool."""
  1831. await _get_client(db)
  1832. result = await db.execute(select(SpoolmanKProfile).where(SpoolmanKProfile.spoolman_spool_id == spool_id))
  1833. profiles = result.scalars().all()
  1834. return [_k_profile_to_dict(p) for p in profiles]
  1835. @router.put("/spools/{spool_id}/k-profiles")
  1836. async def save_spoolman_k_profiles(
  1837. spool_id: int = Path(..., gt=0),
  1838. profiles: list[SpoolKProfileBase] = Body(...),
  1839. db: AsyncSession = Depends(get_db),
  1840. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
  1841. ) -> list[dict]:
  1842. """Replace all K-value calibration profiles for a Spoolman spool."""
  1843. client = await _get_client(db)
  1844. async with _translate_spoolman_errors():
  1845. await client.get_spool(spool_id)
  1846. saved: list[SpoolmanKProfile] = []
  1847. try:
  1848. await db.execute(delete(SpoolmanKProfile).where(SpoolmanKProfile.spoolman_spool_id == spool_id))
  1849. for profile in profiles:
  1850. obj = SpoolmanKProfile(
  1851. spoolman_spool_id=spool_id,
  1852. printer_id=profile.printer_id,
  1853. extruder=profile.extruder,
  1854. nozzle_diameter=profile.nozzle_diameter,
  1855. nozzle_type=profile.nozzle_type,
  1856. k_value=profile.k_value,
  1857. name=profile.name,
  1858. cali_idx=profile.cali_idx,
  1859. setting_id=profile.setting_id,
  1860. )
  1861. db.add(obj)
  1862. saved.append(obj)
  1863. await db.commit()
  1864. except IntegrityError as exc:
  1865. await db.rollback()
  1866. raise HTTPException(422, "Duplicate or invalid K-profile (check printer_id and nozzle uniqueness)") from exc
  1867. except Exception as exc:
  1868. await db.rollback()
  1869. logger.error("K-profile save for spool %d failed: %s", spool_id, exc)
  1870. raise HTTPException(500, "Failed to save K-profiles") from exc
  1871. for obj in saved:
  1872. await db.refresh(obj)
  1873. return [_k_profile_to_dict(p) for p in saved]