spoolman_inventory.py 79 KB

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