spoolman_inventory.py 115 KB

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