_spoolman_helpers.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. """Pure helper functions for Spoolman spool mapping.
  2. No heavy dependencies — importable in unit tests without the full backend stack.
  3. """
  4. from __future__ import annotations
  5. import json
  6. import logging
  7. import math
  8. import re
  9. from typing import Any
  10. from typing_extensions import TypedDict
  11. from backend.app.api.routes._url_safety import assert_safe_lan_service_url
  12. from backend.app.utils.filament_finish import KNOWN_FINISHES, finishes
  13. logger = logging.getLogger(__name__)
  14. class MappedSpoolFields(TypedDict):
  15. """Full shape of the dict returned by _map_spoolman_spool (InventorySpool-compatible)."""
  16. id: int
  17. material: str | None
  18. subtype: str | None
  19. brand: str | None
  20. color_name: str | None
  21. color_name_is_synthesized: bool
  22. rgba: str | None
  23. extra_colors: str | None
  24. effect_type: None
  25. label_weight: int | None
  26. core_weight: int | None
  27. core_weight_is_inherited: bool
  28. core_weight_catalog_id: None
  29. weight_used: float | None
  30. weight_used_baseline: float | None
  31. weight_locked: bool
  32. last_scale_weight: None
  33. last_weighed_at: None
  34. slicer_filament: None
  35. slicer_filament_name: str | None
  36. nozzle_temp_min: int | None
  37. nozzle_temp_max: None
  38. note: str | None
  39. added_full: None
  40. last_used: str | None
  41. # Last drying (#2863), stored under the bambu_last_dried_* extra keys.
  42. last_dried_at: str | None
  43. last_dried_temp: int | None
  44. last_dried_hours: float | None
  45. encode_time: str | None
  46. tag_uid: str | None
  47. tray_uuid: str | None
  48. data_origin: str | None
  49. tag_type: str | None
  50. archived_at: str | None
  51. created_at: str | None # None when Spoolman spool has no registered timestamp
  52. updated_at: str | None
  53. cost_per_kg: float | None
  54. # What prints are charged per kg: the spool's own price, else its
  55. # filament's catalogue price (SM-C8). Display only; the form edits
  56. # cost_per_kg, so the catalogue price is never written onto the spool.
  57. effective_cost_per_kg: float | None
  58. # Spoolman's native filament.article_number, surfaced as the internal
  59. # material number (#2870). Read-only in Spoolman mode — the number is
  60. # filament-level there and maintained in Spoolman itself.
  61. material_number: str | None
  62. storage_location: str | None
  63. location_id: int | None
  64. k_profiles: list[Any]
  65. class NormalizedVendorRef(TypedDict):
  66. """Vendor reference embedded in a NormalizedFilament."""
  67. id: int
  68. name: str
  69. class NormalizedFilament(TypedDict):
  70. """Normalised Spoolman filament dict returned by the /filaments catalog endpoint."""
  71. id: int
  72. name: str
  73. material: str | None
  74. color_hex: str | None
  75. color_name: str | None
  76. weight: int | None
  77. spool_weight: float | None
  78. vendor: NormalizedVendorRef | None
  79. def assert_safe_spoolman_url(url: str) -> None:
  80. """Raise ValueError if the Spoolman *url* should be blocked as an SSRF risk.
  81. Thin wrapper over the shared LAN-service policy — see
  82. ``_url_safety.assert_safe_lan_service_url`` for what is and isn't
  83. rejected, and why loopback/RFC-1918 are deliberately permitted (running
  84. Spoolman on the same host or home LAN is THE normal topology).
  85. Kept as a named function because the "Spoolman URL …" wording in its
  86. errors is user-facing and asserted by existing tests.
  87. """
  88. assert_safe_lan_service_url(url, label="Spoolman URL")
  89. # Six characters, or eight when the filament carries an alpha byte. The write
  90. # side stores eight only for genuinely translucent spools (#2912); rejecting
  91. # them here turned every clear spool into neutral grey on read.
  92. # Spoolman has no subtype or colour-name field, only the filament's name, so
  93. # both are read out of it. Finish phrases longest first, so "Dual Color" is
  94. # taken before anything inside it.
  95. _FINISH_PHRASES: tuple[tuple[str, ...], ...] = tuple(
  96. sorted((tuple(f.split()) for f in KNOWN_FINISHES), key=len, reverse=True)
  97. )
  98. # Punctuation that only separates parts of a name: "Gold - Basic PLA".
  99. _NAME_PUNCT = "-\u2013\u2014,/|()[]:;"
  100. def split_spoolman_filament_name(material: str | None, name: str | None) -> tuple[str | None, str | None]:
  101. """(subtype, colour name) from a Spoolman filament's name (#3561).
  102. Bambuddy writes a filament as ``"<material> <subtype>"`` ("PLA Matte"), and
  103. that is all this used to read: the material came off the front and the
  104. rest was the subtype. Spoolman users name a filament after the product --
  105. "Matte Scarlet Red", "Silk+ Baby Blue", "Gold - Basic PLA" -- and then the
  106. whole name became the subtype and the colour was left unnamed.
  107. The material is removed wherever it stands. The finishes Bambuddy knows
  108. (``KNOWN_FINISHES``: Basic, Matte, Silk, ...) are the subtype, as written,
  109. and the rest is the colour. A name with no finish keeps the old reading
  110. when it starts with the material, so a subtype Bambuddy wrote that is no
  111. finish ("PLA Engineering") still comes back as the subtype -- unless the
  112. material already carries the finish ("PLA Matte" / "PLA Matte Grey"), where
  113. what follows can only be the colour.
  114. """
  115. mat = (material or "").strip()
  116. text = (name or "").strip()
  117. starts_with_material = bool(mat) and bool(re.match(rf"{re.escape(mat)}(?![\w-])", text, flags=re.IGNORECASE))
  118. if starts_with_material:
  119. rest = text[len(mat) :]
  120. elif mat:
  121. rest = re.sub(rf"(?<![\w-]){re.escape(mat)}(?![\w-])", " ", text, count=1, flags=re.IGNORECASE)
  122. else:
  123. rest = text
  124. tokens = [t.strip(_NAME_PUNCT) for t in rest.split()]
  125. tokens = [t for t in tokens if t and any(ch.isalnum() for ch in t)]
  126. finish_words: list[str] = []
  127. colour_words: list[str] = []
  128. i = 0
  129. while i < len(tokens):
  130. for phrase in _FINISH_PHRASES:
  131. window = tokens[i : i + len(phrase)]
  132. if tuple(t.lower().rstrip("+") for t in window) == phrase:
  133. finish_words.extend(window)
  134. i += len(phrase)
  135. break
  136. else:
  137. colour_words.append(tokens[i])
  138. i += 1
  139. if finish_words:
  140. return " ".join(finish_words), " ".join(colour_words) or None
  141. if starts_with_material and not finishes(mat):
  142. return rest.strip() or None, None
  143. return None, " ".join(colour_words) or None
  144. _COLOR_HEX_RE = re.compile(r"^[0-9A-Fa-f]{6}(?:[0-9A-Fa-f]{2})?$")
  145. _TAG_HEX_RE = re.compile(r"^[0-9A-F]+$")
  146. def _safe_int(value: object, fallback: int) -> int:
  147. """Convert value to int, returning fallback for None/NaN/Inf/non-numeric."""
  148. try:
  149. f = float(value) # type: ignore[arg-type]
  150. if math.isfinite(f):
  151. return int(f)
  152. except (TypeError, ValueError):
  153. pass
  154. return fallback
  155. def _safe_float(value: object, fallback: float) -> float:
  156. """Convert value to float, returning fallback for None/NaN/Inf/non-numeric."""
  157. try:
  158. f = float(value) # type: ignore[arg-type]
  159. if math.isfinite(f):
  160. return f
  161. except (TypeError, ValueError):
  162. pass
  163. return fallback
  164. def _safe_optional_float(value: object) -> float | None:
  165. """Convert value to finite float, or None if missing/NaN/Infinite/non-numeric.
  166. Used for optional monetary fields (price) to prevent Infinity/NaN from
  167. reaching JSON serialisation, which raises ValueError with allow_nan=False.
  168. """
  169. if value is None:
  170. return None
  171. try:
  172. f = float(value) # type: ignore[arg-type]
  173. if math.isfinite(f):
  174. return f
  175. except (TypeError, ValueError):
  176. pass
  177. return None
  178. # Used only when Spoolman has no empty-spool weight at any level.
  179. SPOOLMAN_FALLBACK_TARE = 250.0
  180. def spoolman_tare(spool: dict) -> tuple[float, str]:
  181. """The empty-spool weight of a Spoolman spool, and where it came from.
  182. Spoolman resolves the tare as the spool's own ``spool_weight``, then the
  183. filament's ``spool_weight``, then the vendor's ``empty_spool_weight``, and
  184. its own ``/measure`` endpoint follows that order. Skipping the vendor
  185. level made a spool whose tare lives only on its vendor weigh against
  186. 250 g instead (#3195). Every Spoolman-mode tare in Bambuddy goes through
  187. here so the weigh endpoints and the displayed core weight cannot drift
  188. apart again.
  189. Returns ``(grams, source)`` with source one of ``"spool"``,
  190. ``"filament"``, ``"vendor"`` or ``"fallback"``. 0 is a real tare, not a
  191. missing one; a value that is not a finite number counts as missing.
  192. """
  193. filament = spool.get("filament") or {}
  194. vendor = filament.get("vendor") or {}
  195. for source, raw in (
  196. ("spool", spool.get("spool_weight")),
  197. ("filament", filament.get("spool_weight")),
  198. ("vendor", vendor.get("empty_spool_weight")),
  199. ):
  200. value = _safe_optional_float(raw)
  201. if value is not None:
  202. return value, source
  203. return SPOOLMAN_FALLBACK_TARE, "fallback"
  204. def spoolman_net_weight(spool: dict) -> float | None:
  205. """The net filament weight of a full Spoolman spool (its label weight).
  206. Spoolman keeps it on the spool as ``initial_weight`` and falls back to the
  207. filament's catalogue ``weight``, so one filament can have spools of
  208. different sizes. Reading only the filament made a 250 g spool of a 1000 g
  209. filament look four times its size (#3194). Like Spoolman, an
  210. ``initial_weight`` of 0 counts as unset.
  211. Returns None when neither level has a finite number (a bool is not
  212. one); the filament's value is otherwise returned as stored, 0 included,
  213. so callers keep their own handling of a filament without a weight.
  214. """
  215. initial = _weight_or_none(spool.get("initial_weight"))
  216. if initial is not None and initial > 0:
  217. return initial
  218. filament = spool.get("filament")
  219. return _weight_or_none(filament.get("weight")) if isinstance(filament, dict) else None
  220. def _weight_or_none(value: object) -> float | None:
  221. # A bool is an int in Python; True must not read as a 1 g spool.
  222. return None if isinstance(value, bool) else _safe_optional_float(value)
  223. def spoolman_price_to_cost_per_kg(price: object, net_weight: float) -> float | None:
  224. """A Spoolman spool price as a price per kilogram.
  225. Spoolman's ``price`` on a spool is what that spool cost, not a rate; the
  226. spool form edits a rate, so the two are converted at the spool's net
  227. weight. They agree only for 1000 g spools (#3194). Rounded to 4 places so
  228. a round trip through the form doesn't drift by float noise.
  229. """
  230. value = _safe_optional_float(price)
  231. if value is None or net_weight <= 0:
  232. return None
  233. return round(value * 1000.0 / net_weight, 4)
  234. def cost_per_kg_to_spoolman_price(cost_per_kg: float, net_weight: float) -> float:
  235. """Inverse of spoolman_price_to_cost_per_kg: the price of a spool of ``net_weight`` grams."""
  236. return round(cost_per_kg * net_weight / 1000.0, 4)
  237. def spoolman_price_weight(spool: dict) -> float:
  238. """The weight a Spoolman spool's price is converted at.
  239. The spool's exact net weight, not the whole-gram label weight, so a
  240. 250.7 g spool is not re-priced by a no-op edit. A spool with no usable
  241. weight keeps the old 1:1 reading of its price as a per-kg rate.
  242. """
  243. net = spoolman_net_weight(spool)
  244. return net if net is not None and net > 0 else 1000.0
  245. def spoolman_cost_per_kg(spool: dict) -> float | None:
  246. """The spool form's cost per kg for a Spoolman spool (#3194)."""
  247. return spoolman_price_to_cost_per_kg(spool.get("price"), spoolman_price_weight(spool))
  248. def _charged_cost_per_kg(spool: dict) -> float | None:
  249. """The per-kg rate a print off this spool is charged at, from the same
  250. function the charge uses, so the Inventory shows what prints cost."""
  251. from backend.app.services.spoolman_tracking import _spool_cost_per_gram
  252. per_gram = _spool_cost_per_gram(spool)
  253. return round(per_gram * 1000.0, 4) if per_gram is not None else None
  254. def _extract_extra_str(extra: dict, key: str) -> str:
  255. """Extract a JSON-encoded string from a Spoolman extra dict.
  256. Spoolman stores extra values as JSON-stringified text — a stored string
  257. "GFL05" appears as `'"GFL05"'` (six chars including the quotes). This
  258. unwraps that, returning the bare string. Returns "" for missing keys,
  259. non-strings, or invalid JSON.
  260. """
  261. raw = extra.get(key)
  262. if not isinstance(raw, str):
  263. return ""
  264. try:
  265. decoded = json.loads(raw)
  266. except (json.JSONDecodeError, ValueError):
  267. # Tolerate bare-string values written without JSON encoding.
  268. return raw
  269. return decoded if isinstance(decoded, str) else ""
  270. # Spool.extra key holding the consumed-counter baseline: the value Spoolman's
  271. # used_weight had when the user last pressed "Reset usage to 0". Displayed
  272. # consumed is used_weight minus this, which is what internal mode has always
  273. # done with its own weight_used_baseline column (#1644). See #2906.
  274. BAMBU_WEIGHT_USED_BASELINE_KEY = "bambu_weight_used_baseline"
  275. # Spool.extra keys holding when the spool was last dried, the target °C and the
  276. # hours the cycle ran (#2863). Written by services/spool_drying.py and the
  277. # spool update route; an empty string means unknown or cleared.
  278. BAMBU_LAST_DRIED_AT_KEY = "bambu_last_dried_at"
  279. BAMBU_LAST_DRIED_TEMP_KEY = "bambu_last_dried_temp"
  280. BAMBU_LAST_DRIED_HOURS_KEY = "bambu_last_dried_hours"
  281. def _extract_extra_float(extra: dict, key: str) -> float | None:
  282. """Extract a JSON-encoded number from a Spoolman extra dict.
  283. Same storage convention as :func:`_extract_extra_str` — Spoolman keeps
  284. extra values as JSON text, so 250.0 is stored as ``"250.0"``. Returns
  285. ``None`` for missing keys, non-finite values, or anything that does not
  286. decode to a number, so the caller can tell "no baseline recorded" from
  287. "a baseline of zero".
  288. """
  289. raw = extra.get(key)
  290. if raw is None:
  291. return None
  292. if isinstance(raw, (int, float)) and not isinstance(raw, bool):
  293. value = float(raw)
  294. elif isinstance(raw, str):
  295. try:
  296. decoded = json.loads(raw)
  297. except (json.JSONDecodeError, ValueError):
  298. return None
  299. if isinstance(decoded, str):
  300. # Spoolman's extra fields default to field_type "text", which only
  301. # accepts values that decode to a str, so numbers written through
  302. # it arrive as '"263.0"' rather than '263.0'. Both spellings have
  303. # to read back the same, or a baseline written by the reset would
  304. # be invisible to the code that subtracts it.
  305. try:
  306. value = float(decoded)
  307. except ValueError:
  308. return None
  309. elif isinstance(decoded, (int, float)) and not isinstance(decoded, bool):
  310. value = float(decoded)
  311. else:
  312. return None
  313. else:
  314. return None
  315. return value if math.isfinite(value) else None
  316. def parse_spoolman_multi_colors(filament: dict) -> list[str]:
  317. """Spoolman's ``multi_color_hexes`` as a list of bare 6/8-char hex tokens.
  318. Spoolman stores the extra stops of a gradient / dual / multi-colour
  319. filament here, and writes the field as a comma-separated string in some
  320. releases and a list in others -- both shapes are accepted. Tokens keep the
  321. case they arrived in and lose any leading ``#``, which is the form
  322. ``Spool.extra_colors`` stores and ``parseStops`` on the client expects.
  323. Shared with the label renderer rather than parsed twice: the two read the
  324. same field for the same purpose, and a swatch on a printer card that
  325. disagreed with the swatch on the printed label would be worse than either
  326. being wrong on its own.
  327. """
  328. raw = filament.get("multi_color_hexes")
  329. if isinstance(raw, str):
  330. tokens = raw.split(",")
  331. elif isinstance(raw, list):
  332. tokens = [str(token) for token in raw]
  333. else:
  334. return []
  335. return [cleaned for token in tokens if (cleaned := token.strip().lstrip("#"))]
  336. def _last_dried_temp(extra: dict) -> int | None:
  337. value = _extract_extra_float(extra, BAMBU_LAST_DRIED_TEMP_KEY)
  338. return int(round(value)) if value is not None and value > 0 else None
  339. def _map_spoolman_spool(spool: dict) -> MappedSpoolFields:
  340. """Convert a raw Spoolman spool dict to the InventorySpool-compatible format.
  341. Fields not supported by Spoolman (k_profiles, slicer_filament, …) are
  342. returned as None / empty so the frontend can still render them without
  343. errors. The ``data_origin`` field is set to ``"spoolman"`` so UI code can
  344. distinguish these spools from local ones.
  345. """
  346. raw_id = spool.get("id")
  347. if raw_id is None:
  348. raise ValueError("Spoolman spool is missing required 'id' field")
  349. try:
  350. spool_id: int = int(raw_id)
  351. except (TypeError, ValueError):
  352. raise ValueError(f"Spoolman spool 'id' is not a valid integer: {raw_id!r}")
  353. if spool_id <= 0:
  354. raise ValueError(f"Spoolman spool 'id' must be a positive integer, got {spool_id}")
  355. filament: dict = spool.get("filament") or {}
  356. if not filament:
  357. logger.warning(
  358. "Spoolman spool %s has no filament data — all filament fields will use defaults",
  359. spool_id,
  360. )
  361. vendor: dict = filament.get("vendor") or {}
  362. extra: dict = spool.get("extra") or {}
  363. # RFID tag stored as JSON-encoded string in Spoolman extra.tag.
  364. # 32-char hex → Bambu Lab tray UUID; 8–30-char hex → NFC tag UID.
  365. # Accepting the full realistic UID range (4-byte = 8 chars, 7-byte = 14 chars,
  366. # 10-byte = 20 chars) avoids silently dropping valid SpoolBuddy-written tags.
  367. raw_tag: str = (extra.get("tag") or "").strip('"').upper()
  368. _raw_is_hex = bool(_TAG_HEX_RE.match(raw_tag))
  369. tag_uid = raw_tag if _raw_is_hex and 8 <= len(raw_tag) <= 30 else None
  370. tray_uuid = raw_tag if _raw_is_hex and len(raw_tag) == 32 else None
  371. # Spoolman 0.27+ native tags fill whichever of the two extra.tag left empty,
  372. # so a spool linked there shows as tagged here as well.
  373. for native in spool.get("tags") or []:
  374. uid = str(native.get("uid") or "").upper()
  375. if not _TAG_HEX_RE.match(uid):
  376. continue
  377. if len(uid) == 32:
  378. tray_uuid = tray_uuid or uid
  379. elif 8 <= len(uid) <= 30:
  380. tag_uid = tag_uid or uid
  381. # Subtype and colour from the filament's name (#3561).
  382. material: str = (filament.get("material") or "").strip()
  383. filament_name: str = (filament.get("name") or "").strip()
  384. subtype, name_color = split_spoolman_filament_name(material, filament_name)
  385. # Colour: validate as 6- or 8-char hex; fall back to neutral grey for invalid
  386. # values. An 8-char value already carries its alpha, so appending the opaque
  387. # byte would push it to ten and lose the translucency it was stored to keep.
  388. raw_color = (filament.get("color_hex") or "").upper().removeprefix("#")
  389. color_hex: str = raw_color if _COLOR_HEX_RE.match(raw_color) else "808080"
  390. rgba: str = color_hex if len(color_hex) == 8 else color_hex + "FF"
  391. # Spoolman carries the extra stops but has no concept of a surface effect
  392. # -- its only neighbouring field is `multi_color_direction`, which says how
  393. # the stops are laid out, not that the filament is silk or glitter. So a
  394. # Spoolman spool can render its gradient and never an effect overlay, and
  395. # `effect_type` is pinned to None rather than guessed at.
  396. extra_stops = parse_spoolman_multi_colors(filament)
  397. extra_colors: str | None = ",".join(extra_stops) if extra_stops else None
  398. label_weight: int = _safe_int(spoolman_net_weight(spool), 1000)
  399. real_used_weight: float = _safe_float(spool.get("used_weight"), 0.0)
  400. # Parity with internal mode (#1390): the InventorySpool shape lets the
  401. # frontend compute `remaining = label_weight - weight_used` and
  402. # `consumed = weight_used - weight_used_baseline`. Map Spoolman's two
  403. # independent fields (used_weight, remaining_weight) onto that shape:
  404. # weight_used = label_weight - remaining_weight (so remaining matches)
  405. # baseline = weight_used - used_weight (so consumed matches)
  406. # When remaining_weight is unset (legacy spools, or filament linked but
  407. # never primed), fall back to the old behaviour: weight_used =
  408. # used_weight, baseline = 0.
  409. #
  410. # A "Reset usage to 0" records the then-current used_weight under
  411. # BAMBU_WEIGHT_USED_BASELINE_KEY in spool.extra and touches nothing else,
  412. # so displayed consumed is used_weight minus that. It is folded into the
  413. # baseline here because the frontend's arithmetic is fixed: it always shows
  414. # `weight_used - weight_used_baseline`. The reset used to PATCH Spoolman's
  415. # used_weight to 0 instead, and Spoolman recomputes remaining from initial
  416. # minus used, so the spool jumped back to full (#2906).
  417. # `or 0.0` would collapse None and 0.0, which is the one distinction
  418. # _extract_extra_float exists to preserve; spell the absent case out.
  419. # Clamp the low end too: the write side already refuses a negative
  420. # baseline, and without the same rule here a negative value stored by hand
  421. # would be subtracted, inflating the displayed counter. min() below only
  422. # bounds the other end.
  423. stored = _extract_extra_float(extra, BAMBU_WEIGHT_USED_BASELINE_KEY)
  424. stored_baseline = 0.0 if stored is None else max(0.0, stored)
  425. remaining_raw = spool.get("remaining_weight")
  426. if remaining_raw is not None:
  427. remaining_weight: float = _safe_float(remaining_raw, 0.0)
  428. used_weight: float = max(0.0, float(label_weight) - remaining_weight)
  429. weight_used_baseline: float = max(0.0, used_weight - real_used_weight + stored_baseline)
  430. else:
  431. used_weight = real_used_weight
  432. weight_used_baseline = stored_baseline # already clamped to >= 0 above
  433. # Never let the displayed counter read negative. used_weight can fall below
  434. # the baseline after a reset without anyone touching it: the AMS sync
  435. # writes remaining_weight from the tray percentage, and Spoolman derives
  436. # used_weight from that. The counter then reads 0 until consumption climbs
  437. # past the baseline again. Internal mode behaves the same way, and it is
  438. # far better than before #2906, when the next sync undid the reset outright.
  439. weight_used_baseline = min(weight_used_baseline, used_weight)
  440. # Archived state – Spoolman uses a boolean ``archived`` field
  441. archived: bool = spool.get("archived", False)
  442. archived_at: str | None = None
  443. if archived:
  444. archived_at = spool.get("last_used") or spool.get("registered") or None
  445. created_at: str | None = spool.get("registered") or None
  446. # Spoolman has no `color_name` field on Filament — confirmed against the
  447. # FilamentUpdateParameters schema in 0.23.1: name/vendor_id/material/price/
  448. # density/diameter/weight/spool_weight/article_number/comment/extruder_temp/
  449. # bed_temp/color_hex/multi_color_hexes/multi_color_direction/external_id/
  450. # extra, no color_name (#1357). The previous attempt (b8e350c3) was
  451. # PATCHing a key Spoolman silently discards, which is why color_name
  452. # never actually persisted from the user's edits.
  453. #
  454. # We persist it ourselves under spool.extra.bambu_color_name (JSON-encoded
  455. # string, same pattern as bambu_slicer_filament). Read order:
  456. # 1. spool.extra.bambu_color_name (the canonical store)
  457. # 2. filament.color_name (forward-compat — picks up the value if a
  458. # future Spoolman release adds the field, or if an admin populated
  459. # it via a custom extra-field they registered themselves)
  460. # 3. the colour named in the filament's name ("Matte Scarlet Red" ->
  461. # "Scarlet Red", #3561). The user wrote it, so it counts as set.
  462. # 4. subtype (synth fallback so the inventory list isn't a sea of
  463. # "Unknown color" entries on installs with neither field set)
  464. #
  465. # color_name_is_synthesized = True only when we fell back to subtype.
  466. # The edit form uses it to leave the input blank, so the user doesn't
  467. # round-trip the synth value back as if they had set it.
  468. extra_color_name = _extract_extra_str(extra, "bambu_color_name") or None
  469. stored_color_name = extra_color_name or (filament.get("color_name") or None) or name_color
  470. color_name: str | None = stored_color_name or subtype or None
  471. color_name_is_synthesized: bool = stored_color_name is None and color_name is not None
  472. nozzle_temp_raw = filament.get("settings_extruder_temp")
  473. nozzle_temp_min: int | None = _safe_int(nozzle_temp_raw, 0) or None
  474. return {
  475. "id": spool_id,
  476. "material": material,
  477. "subtype": subtype,
  478. "color_name": color_name,
  479. "color_name_is_synthesized": color_name_is_synthesized,
  480. "rgba": rgba,
  481. "extra_colors": extra_colors,
  482. "effect_type": None,
  483. "brand": vendor.get("name") or None,
  484. "label_weight": label_weight,
  485. "core_weight": _safe_int(spoolman_tare(spool)[0], 250),
  486. # True when the spool has no spool_weight of its own and core_weight is
  487. # the filament type's, the vendor's or the 250 g fallback. The spool form needs it
  488. # to copy a spool without dropping an own tare or stamping an
  489. # inherited one (#2908).
  490. "core_weight_is_inherited": spool.get("spool_weight") is None,
  491. "core_weight_catalog_id": None,
  492. "weight_used": used_weight,
  493. "weight_used_baseline": weight_used_baseline,
  494. "weight_locked": False,
  495. "last_scale_weight": None,
  496. "last_weighed_at": None,
  497. # BambuStudio slicer preset — Spoolman has no native field, so the
  498. # update endpoint persists these under bambu_slicer_filament[_name]
  499. # in the spool's extra dict. Values are JSON-encoded strings; an
  500. # empty string ("") means cleared. Falls back to Spoolman's
  501. # filament_name for slicer_filament_name when nothing is stored.
  502. "slicer_filament": (_extract_extra_str(extra, "bambu_slicer_filament") or None),
  503. "slicer_filament_name": (_extract_extra_str(extra, "bambu_slicer_filament_name") or (filament_name or None)),
  504. "nozzle_temp_min": nozzle_temp_min,
  505. "nozzle_temp_max": None,
  506. "note": spool.get("comment") or None,
  507. "added_full": None,
  508. "last_used": spool.get("last_used"),
  509. # When the spool was first printed with; the stock forecast spreads
  510. # its consumption from here (#3407).
  511. "first_used": spool.get("first_used"),
  512. "last_dried_at": _extract_extra_str(extra, BAMBU_LAST_DRIED_AT_KEY) or None,
  513. "last_dried_temp": _last_dried_temp(extra),
  514. "last_dried_hours": _extract_extra_float(extra, BAMBU_LAST_DRIED_HOURS_KEY),
  515. # encode_time semantics differ: local records NFC write time; Spoolman first_used
  516. # records first print use — different events; using first_used as best available proxy.
  517. "encode_time": spool.get("first_used"),
  518. "tag_uid": tag_uid,
  519. "tray_uuid": tray_uuid,
  520. "data_origin": "spoolman",
  521. "tag_type": "spoolman",
  522. "archived_at": archived_at,
  523. "created_at": created_at,
  524. # Spoolman has no updated_at field; use registered timestamp as best available proxy
  525. "updated_at": created_at,
  526. # Spoolman's spool price is what the whole spool cost (#3194).
  527. "cost_per_kg": spoolman_cost_per_kg(spool),
  528. "effective_cost_per_kg": _charged_cost_per_kg(spool),
  529. # Spoolman's filament.article_number maps 1:1 onto the internal
  530. # material number (#2870): both identify the purchasable product.
  531. # Trimmed for the same reason the schema validator trims the internal
  532. # one — the filter chip builds its options from trimmed values and
  533. # matches exactly, so a padded number would list and match nothing.
  534. "material_number": ((filament.get("article_number") or "").strip() or None),
  535. "storage_location": spool.get("location") or None,
  536. "location_id": None,
  537. "k_profiles": [],
  538. }