spoolman_inventory.py 113 KB

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