spoolman_tracking.py 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100
  1. """Spoolman per-filament usage tracking for active prints.
  2. Captures AMS tray state and G-code data at print start, then reports
  3. per-filament usage to the correct Spoolman spools at print completion.
  4. Supports accurate partial usage reporting for failed/cancelled prints.
  5. """
  6. import json
  7. import logging
  8. import math
  9. from dataclasses import dataclass
  10. from typing import cast
  11. from sqlalchemy import delete, select
  12. from sqlalchemy.engine import CursorResult
  13. from backend.app.api.routes._spoolman_helpers import spoolman_net_weight
  14. from backend.app.core.config import settings as app_settings
  15. from backend.app.core.database import async_session
  16. from backend.app.services.spoolman import (
  17. SpoolmanClientError,
  18. SpoolmanNotFoundError,
  19. SpoolmanUnavailableError,
  20. get_spoolman_client,
  21. init_spoolman_client,
  22. )
  23. logger = logging.getLogger(__name__)
  24. # Zero UUID used by Bambu printers for empty/unset tray_uuid
  25. _ZERO_UUID = "00000000000000000000000000000000"
  26. _ZERO_TAG_UID = "0000000000000000"
  27. # Highest global tray id that names a real slot. 255 does not: it is
  28. # ``PrinterState.tray_now``'s initial value, what an unparseable reading falls
  29. # back to, and what the field reads while nothing is loaded. The external spool
  30. # reports 254 when it is actually in use, and ``bambu_mqtt`` applies the same
  31. # cut-off when it seeds the tray-change log. Treating 255 as a slot would put
  32. # ``(255, 1)`` into the "slots this print used" evidence and exclude every real
  33. # one -- silently disabling the very fallback this guard protects (#1820).
  34. #
  35. # Applied to ``tray_now`` only. A 255 in the print's mapping or its tray-change
  36. # log was written there by a print and is evidence, however odd; a 255 in
  37. # ``tray_now`` is the field at rest, which is the absence of evidence.
  38. _MAX_REAL_TRAY_ID = 254
  39. def _is_real_tray_id(value) -> bool:
  40. """True when ``value`` names a physical slot rather than "nothing loaded"."""
  41. return isinstance(value, int) and not isinstance(value, bool) and 0 <= value <= _MAX_REAL_TRAY_ID
  42. def _is_non_zero_identifier(value: str) -> bool:
  43. """Return True when identifier is non-empty and not all zeros."""
  44. if not value:
  45. return False
  46. return set(value) != {"0"}
  47. def _to_fixed_hex(value: int, width: int) -> str:
  48. """Mirror frontend toFixedHex(): uppercase, zero-padded, fixed width."""
  49. safe = max(0, int(value))
  50. return format(safe, "X").zfill(width)[-width:]
  51. def _hash_serial_to_hex32(serial: str) -> str:
  52. """Mirror frontend hashSerialToHex32() exactly (32-bit FNV-1a)."""
  53. input_str = (serial or "").strip().upper()
  54. hash_value = 0x811C9DC5
  55. for char in input_str:
  56. hash_value ^= ord(char)
  57. hash_value = (hash_value * 0x01000193) & 0xFFFFFFFF
  58. return format(hash_value, "X").zfill(8)
  59. def _global_tray_id_to_ams_slot(global_tray_id: int) -> tuple[int, int]:
  60. """Convert global tray id to (ams_id, tray_id) tuple for fallback tag generation."""
  61. # External spool slots use IDs 254/255 and map to ams_id=255 tray_id=0/1.
  62. if global_tray_id >= 254:
  63. return 255, max(0, global_tray_id - 254)
  64. # AMS-HT units are addressed by ams_id directly and have a single tray.
  65. if global_tray_id >= 128:
  66. return global_tray_id, 0
  67. # Standard AMS units: four trays each.
  68. return global_tray_id // 4, global_tray_id % 4
  69. def _get_fallback_spool_tag(printer_serial: str, global_tray_id: int) -> str:
  70. """Mirror frontend getFallbackSpoolTag(serial, amsId, trayId) exactly."""
  71. if not printer_serial:
  72. return ""
  73. ams_id, tray_id = _global_tray_id_to_ams_slot(global_tray_id)
  74. return get_fallback_spool_tag_for_slot(printer_serial, ams_id, tray_id)
  75. def get_fallback_spool_tag_for_slot(printer_serial: str, ams_id: int, tray_id: int) -> str:
  76. """Public helper matching frontend getFallbackSpoolTag(serial, amsId, trayId).
  77. Used by stale-tag cleanup (#1457) to detect Spoolman spools still holding
  78. this slot's deterministic fallback tag in extra.tag.
  79. """
  80. if not printer_serial:
  81. return ""
  82. return f"{_hash_serial_to_hex32(printer_serial)}{_to_fixed_hex(ams_id, 4)}{_to_fixed_hex(tray_id, 4)}"
  83. def is_slot_fallback_tag(tag: str, printer_serials) -> bool:
  84. """Whether a tag is an AMS slot's generated fallback ID rather than a physical tag.
  85. Fallback IDs are 16 hex characters that start with the printer serial's hash
  86. (see get_fallback_spool_tag_for_slot). They identify a slot, not a spool, and
  87. have no place among Spoolman's native tags.
  88. """
  89. tag = (tag or "").strip('"').upper()
  90. if len(tag) != 16:
  91. return False
  92. return any(tag[:8] == _hash_serial_to_hex32(s) for s in printer_serials if s)
  93. def _resolve_spool_tag(tray_info: dict, printer_serial: str = "", global_tray_id: int | None = None) -> str:
  94. """Get the best spool identifier from tray info (prefer tray_uuid over tag_uid).
  95. Returns empty string if no usable identifier is found.
  96. """
  97. tray_uuid = str(tray_info.get("tray_uuid", "") or "")
  98. tag_uid = str(tray_info.get("tag_uid", "") or "")
  99. if tray_uuid and tray_uuid != _ZERO_UUID and _is_non_zero_identifier(tray_uuid):
  100. return tray_uuid
  101. if tag_uid and tag_uid != _ZERO_TAG_UID and _is_non_zero_identifier(tag_uid):
  102. return tag_uid
  103. if global_tray_id is not None:
  104. return _get_fallback_spool_tag(printer_serial, global_tray_id)
  105. return ""
  106. async def _get_printer_serial(printer_id: int) -> str:
  107. """Get printer serial for deterministic fallback tag generation."""
  108. from backend.app.models.printer import Printer
  109. from backend.app.services.printer_manager import printer_manager
  110. printer_info = printer_manager.get_printer(printer_id)
  111. if printer_info and printer_info.serial_number:
  112. return printer_info.serial_number
  113. async with async_session() as db:
  114. result = await db.execute(select(Printer.serial_number).where(Printer.id == printer_id))
  115. serial_number = result.scalar_one_or_none()
  116. return serial_number or ""
  117. def _resolve_global_tray_id(slot_id: int, slot_to_tray: list | None, ams_trays: dict | None = None) -> int:
  118. """Map a 1-based slot_id to a global_tray_id using optional custom mapping.
  119. Custom mapping: slot_to_tray[slot_id - 1] is used when >= 0. A negative
  120. value means the slot feeds nothing and answers -1, which no tray has: the
  121. flat ams_mapping writes an external spool as -1 on the wire, but the
  122. captured mapping puts its 254/255 back from ams_mapping2 (#3166), so a -1
  123. left in it is unmapped. Never the position-based default for such a slot,
  124. which would credit an unrelated spool (#1276, regression of #853).
  125. Position-based default: uses sorted ams_trays keys so external spools (ID 254/255)
  126. naturally follow standard AMS trays, matching the slicer's slot numbering.
  127. Final fallback: slot_id - 1 (legacy, works for pure AMS without external spools).
  128. """
  129. if slot_to_tray and slot_id <= len(slot_to_tray):
  130. mapped_tray = slot_to_tray[slot_id - 1]
  131. if mapped_tray >= 0:
  132. return mapped_tray
  133. # A negative value is a slot the print does not feed: the captured
  134. # mapping already names an external spool 254/255 (#3166), and the
  135. # built-in tracker charges nothing for it either. No tray has this id,
  136. # so the slot is skipped rather than guessed by position.
  137. return -1
  138. # Position-based default: sort available tray IDs so external spools (254/255)
  139. # come after standard AMS trays, matching the slicer's slot assignment order.
  140. if ams_trays:
  141. sorted_tray_ids = sorted(ams_trays.keys())
  142. if slot_id <= len(sorted_tray_ids):
  143. return sorted_tray_ids[slot_id - 1]
  144. return slot_id - 1
  145. def _single_slot_tray_from_state(
  146. state,
  147. filament_usage: list[dict],
  148. tray_now_at_start: int | None = None,
  149. ) -> tuple[int, int] | None:
  150. """The tray a single-slot print actually drew from, read off the printer.
  151. A1, A1 mini, P1S and P2S publish no ``mapping`` field and drop the MQTT
  152. connection when we subscribe to their request topic, so neither of the
  153. other two fallbacks can answer for them. What they do report is which tray
  154. the extruder is fed from, and for a print that uses exactly one filament
  155. slot that is the same question: the one slot came from the one tray.
  156. The ladder mirrors ``usage_tracker.on_print_complete`` step 5, which has
  157. consulted these same fields since it started resolving mappings at
  158. completion. Spoolman users were the only ones not getting them (#2953).
  159. Gated on exactly one slot with usage, like the internal writer: on a
  160. multi-colour print every filament change moves ``tray_now``, so a single
  161. tray reading says nothing about which slot it belongs to.
  162. More than one tray-change entry means the print switched trays mid-run
  163. (AMS backup on runout, #957). ``report_usage`` splits those per segment
  164. and must not be handed a single-tray mapping instead, so this declines.
  165. Returns ``(slot_id, global_tray_id)``, or None when the printer offered no
  166. usable reading and the positional default stands.
  167. """
  168. nonzero = [u for u in filament_usage or [] if u.get("used_g", 0) > 0]
  169. if len(nonzero) != 1:
  170. return None
  171. slot_id = nonzero[0].get("slot_id", 0)
  172. if slot_id <= 0:
  173. return None
  174. changes = list(getattr(state, "tray_change_log", None) or [])
  175. if len(changes) > 1:
  176. return None
  177. if len(changes) == 1:
  178. entry = changes[0]
  179. if isinstance(entry, (tuple, list)) and entry and _is_real_tray_id(entry[0]):
  180. # Strongest evidence there is: the printer announced this switch
  181. # while the job was running, so it describes this print and no
  182. # other. On the reporter's A1 it read (3, 0) -- tray 3 at layer 0
  183. # -- while the positional default was charging tray 0.
  184. return slot_id, entry[0]
  185. # No mid-print switch recorded. Fall back to the standing tray readings,
  186. # newest evidence first. ``tray_now`` is 255 both at rest and while
  187. # nothing is loaded, which is why _MAX_REAL_TRAY_ID excludes it; A1
  188. # firmware parks there the moment a print ends, leaving last_loaded_tray
  189. # as the only survivor.
  190. for candidate in (
  191. tray_now_at_start,
  192. getattr(state, "tray_now", None),
  193. getattr(state, "last_loaded_tray", None),
  194. ):
  195. if _is_real_tray_id(candidate):
  196. return slot_id, candidate
  197. return None
  198. def _resolve_slot_to_tray_fallback(
  199. printer_id: int,
  200. filament_usage: list[dict],
  201. tray_now_at_start: int | None = None,
  202. ) -> tuple[list[int] | None, str]:
  203. """Recover a slot-to-tray mapping at completion when print start captured none.
  204. ``store_print_data`` can only learn the mapping from two sources: the
  205. ``ams_mapping`` Bambuddy intercepts on the printer's local request topic, and
  206. a queue item's stored mapping. Neither exists for a print dispatched from
  207. Bambu Studio while the printer is cloud-bound — the command travels through
  208. Bambu's broker and never appears on the local topic we subscribe to. With
  209. ``slot_to_tray`` left NULL, ``_resolve_global_tray_id`` guesses by position:
  210. slicer slot 1 to the first loaded tray, slot 2 to the second, and so on. An
  211. AMS that isn't loaded in slicer order then charges every slot to the wrong
  212. spool, and the archive's filament is rewritten to match, so the print
  213. silently changes colour when it finishes (#2768).
  214. The printer knows the real answer. Its ``mapping`` field carries the actual
  215. slot-to-tray assignment for the running job, and for the models that never
  216. publish it (A1, P1S, P2S) the 3MF's per-slot colours can be matched against
  217. the loaded trays instead. Failing both, a print that used a single filament
  218. slot can be pinned to the tray the printer reported feeding from
  219. (``_single_slot_tray_from_state``).
  220. The built-in inventory writer has consulted all three for as long as it has
  221. resolved mappings at completion. The first version of this function offered
  222. only the first two, which left A1-class printers -- no ``mapping`` field, no
  223. request topic -- with nothing but the colour match, and that needs the
  224. slicer's filament colour to equal the tray's exactly. A generic black
  225. profile against a tray set to #111111 does not match, and the print is
  226. charged to whichever spool happens to sit in the first tray (#2953).
  227. Deliberately at completion rather than inside ``store_print_data``: the
  228. printer keeps publishing ``mapping`` long after a job ends — it is still in
  229. the status payload while the printer sits idle — so reading it at print start
  230. risks stamping the *previous* job's mapping onto this one before the printer
  231. has pushed the update. At completion the field unambiguously describes the
  232. job that just ran.
  233. Args:
  234. printer_id: Printer whose live state is consulted.
  235. filament_usage: The 3MF's per-slot estimates. The colour match reads
  236. ``slot_id``/``color``; the tray-state fallback reads
  237. ``slot_id``/``used_g``.
  238. tray_now_at_start: The tray the printer was feeding from when the print
  239. began, as captured by ``store_print_data``. Only consulted by the
  240. tray-state fallback.
  241. Returns:
  242. ``(mapping, source)``, or ``(None, "none")`` when no fallback produced
  243. anything and the positional default stands.
  244. """
  245. from backend.app.services.printer_manager import printer_manager
  246. from backend.app.services.usage_tracker import _decode_mqtt_mapping, _match_slots_by_color
  247. state = printer_manager.get_status(printer_id)
  248. raw_data = getattr(state, "raw_data", None) if state else None
  249. # Both of the first two fallbacks read the status payload; the third reads
  250. # fields ``bambu_mqtt`` maintains on the state object itself, so an empty
  251. # payload must not short-circuit past it.
  252. if raw_data:
  253. decoded = _decode_mqtt_mapping(raw_data.get("mapping"))
  254. if decoded:
  255. return decoded, "mqtt"
  256. matched = _match_slots_by_color(filament_usage, raw_data.get("ams"))
  257. if matched:
  258. return matched, "color_match"
  259. single = _single_slot_tray_from_state(state, filament_usage, tray_now_at_start)
  260. if single is not None:
  261. slot_id, global_tray_id = single
  262. # Only the one slot is claimed. The -1 padding is the array's existing
  263. # "not an AMS tray" value, and the slots carrying it consumed nothing,
  264. # so no caller resolves them: ``_report_spool_usage_for_slots`` skips
  265. # zero-gram slots before resolving, ``_print_used_tray_keys`` skips
  266. # negatives, and report_usage's handled-set skips them too.
  267. mapping = [-1] * slot_id
  268. mapping[slot_id - 1] = global_tray_id
  269. return mapping, "tray_state"
  270. return None, "none"
  271. def build_ams_tray_lookup(raw_data: dict) -> dict[int, dict]:
  272. """Build lookup of global_tray_id -> tray info from printer state.
  273. Returns: {0: {"tray_uuid": "...", "tag_uid": "...", "tray_type": "..."}, ...}
  274. """
  275. lookup = {}
  276. ams_data = raw_data.get("ams", [])
  277. for ams_unit in ams_data:
  278. ams_id = int(ams_unit.get("id", 0))
  279. for tray in ams_unit.get("tray", []):
  280. tray_id = int(tray.get("id", 0))
  281. # AMS-HT units have IDs starting at 128 with a single tray
  282. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  283. lookup[global_tray_id] = {
  284. "tray_uuid": tray.get("tray_uuid", ""),
  285. "tag_uid": tray.get("tag_uid", ""),
  286. "tray_type": tray.get("tray_type", ""),
  287. }
  288. # External spool(s) (vt_tray is a list, global_tray_id from each entry's "id")
  289. for vt in raw_data.get("vt_tray") or []:
  290. if vt.get("tray_type"):
  291. tray_id = int(vt.get("id", 254))
  292. lookup[tray_id] = {
  293. "tray_uuid": vt.get("tray_uuid", ""),
  294. "tag_uid": vt.get("tag_uid", ""),
  295. "tray_type": vt.get("tray_type", ""),
  296. }
  297. return lookup
  298. def _snapshot_tray_remain(raw_data: dict, skipped_out: list[str] | None = None) -> dict[str, dict]:
  299. """Capture per-slot ``remain%`` + ``tray_uuid`` at print start so the
  300. completion path can compute a remain-delta when 3MF data doesn't cover
  301. the slot (or there's no 3MF at all — #1820).
  302. Returns ``{"<ams_id>-<tray_id>": {"remain": int, "tray_uuid": str}}``.
  303. Only slots whose ``remain`` is a valid 0..100 int are included; invalid
  304. values mean the AMS hasn't read the spool yet and a delta would be
  305. meaningless. Mirrors the gate in
  306. ``usage_tracker.on_print_start:309``.
  307. A rejected slot is appended to *skipped_out* when one is supplied, so the
  308. caller can say which slots this print will not be able to charge. That is
  309. not hypothetical: an AMS reports a negative ``remain`` on a nearly empty
  310. spool, so the gate can drop the one slot that is about to do the printing
  311. (#1820).
  312. """
  313. snapshot: dict[str, dict] = {}
  314. ams_raw = raw_data.get("ams", [])
  315. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  316. for ams_unit in ams_data:
  317. if not isinstance(ams_unit, dict):
  318. continue
  319. ams_id = int(ams_unit.get("id", 0))
  320. for tray in ams_unit.get("tray", []):
  321. if not isinstance(tray, dict):
  322. continue
  323. tray_id = int(tray.get("id", 0))
  324. remain = tray.get("remain", -1)
  325. if isinstance(remain, int) and 0 <= remain <= 100:
  326. snapshot[f"{ams_id}-{tray_id}"] = {
  327. "remain": remain,
  328. "tray_uuid": tray.get("tray_uuid", "") or "",
  329. }
  330. elif skipped_out is not None:
  331. skipped_out.append(f"AMS{ams_id}-T{tray_id}(remain={remain})")
  332. vt_tray_raw = raw_data.get("vt_tray") or []
  333. if isinstance(vt_tray_raw, dict):
  334. vt_tray_raw = [vt_tray_raw]
  335. for vt in vt_tray_raw:
  336. if not isinstance(vt, dict):
  337. continue
  338. vt_id = int(vt.get("id", 254))
  339. # 254 → (255, 0), 255 → (255, 1) — matches usage_tracker's encoding.
  340. vt_tray_id = vt_id - 254
  341. remain = vt.get("remain", -1)
  342. if isinstance(remain, int) and 0 <= remain <= 100:
  343. snapshot[f"255-{vt_tray_id}"] = {
  344. "remain": remain,
  345. "tray_uuid": vt.get("tray_uuid", "") or "",
  346. }
  347. elif skipped_out is not None:
  348. skipped_out.append(f"VT{vt_id}(remain={remain})")
  349. return snapshot
  350. def _extract_3mf_tracking(full_path, plate_id: int | None) -> tuple[list | None, dict | None, dict | None]:
  351. """What Spoolman's tracking reads from a print's 3MF: the per-filament
  352. grams, the per-layer usage (JSON keys) and the filament properties."""
  353. from backend.app.utils.threemf_tools import (
  354. extract_filament_properties_from_3mf,
  355. extract_filament_usage_from_3mf,
  356. extract_layer_filament_usage_from_3mf,
  357. )
  358. filament_usage = extract_filament_usage_from_3mf(full_path, plate_id) or None
  359. layer_usage_json: dict | None = None
  360. layer_usage = extract_layer_filament_usage_from_3mf(full_path, plate_id)
  361. if layer_usage:
  362. # Convert int keys to string for JSON serialization
  363. layer_usage_json = {str(k): v for k, v in layer_usage.items()}
  364. logger.debug("[SPOOLMAN] Parsed %s layers from G-code", len(layer_usage))
  365. return filament_usage, layer_usage_json, extract_filament_properties_from_3mf(full_path)
  366. async def attach_recovered_3mf(
  367. printer_id: int,
  368. archive_id: int,
  369. file_path: str,
  370. db,
  371. printer_manager,
  372. *,
  373. plate_id: int | None = None,
  374. may_start: bool = True,
  375. ) -> None:
  376. """Add a fallback archive's recovered 3MF to Spoolman's tracking of its print.
  377. Print start found no 3MF, so it stored only the AMS remain% snapshot and
  378. completion would charge the remain% change. Only the 3MF's own data is
  379. added: the snapshot was taken at print start, and replacing it from the
  380. mid-print state now would charge the wrong change for a slot the 3MF does
  381. not cover. Usage already tracked is left alone.
  382. When print start stored nothing (no slot had a remain%), the 3MF is
  383. tracked on its own if ``may_start``: from the recovery inside the print's
  384. close-out, which runs before the charge, or from any other while the print
  385. runs and is not being closed. During a close-out another recovery's row
  386. could follow the charge that already deleted the print's tracking, and be
  387. left behind.
  388. """
  389. from backend.app.api.routes.settings import get_setting
  390. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  391. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  392. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  393. return
  394. full_path = (
  395. app_settings.base_dir / file_path
  396. ) # SEC-PATH-OK: file_path is archive.file_path — DB-stored, internally generated
  397. if not file_path or not full_path.exists():
  398. return
  399. row = (
  400. await db.execute(
  401. select(ActivePrintSpoolman)
  402. .where(ActivePrintSpoolman.printer_id == printer_id)
  403. .where(ActivePrintSpoolman.archive_id == archive_id)
  404. )
  405. ).scalar_one_or_none()
  406. if row is not None and row.filament_usage:
  407. return
  408. if row is None and not may_start:
  409. return
  410. filament_usage, layer_usage_json, filament_properties = _extract_3mf_tracking(full_path, plate_id)
  411. if not filament_usage:
  412. return
  413. if row is None:
  414. state = printer_manager.get_status(printer_id)
  415. row = ActivePrintSpoolman(
  416. printer_id=printer_id,
  417. archive_id=archive_id,
  418. ams_trays=build_ams_tray_lookup(state.raw_data) if state and state.raw_data else {},
  419. )
  420. db.add(row)
  421. row.filament_usage = filament_usage
  422. row.layer_usage = layer_usage_json
  423. row.filament_properties = filament_properties
  424. await db.commit()
  425. logger.info(
  426. "[SPOOLMAN] Archive %s: tracking now has the recovered 3MF's usage (%d filament(s))",
  427. archive_id,
  428. len(filament_usage),
  429. )
  430. async def store_print_data(
  431. printer_id: int,
  432. archive_id: int,
  433. file_path: str,
  434. db,
  435. printer_manager,
  436. ams_mapping: list[int] | None = None,
  437. plate_id: int | None = None,
  438. ):
  439. """Store Spoolman tracking data at print start (persisted to database).
  440. Per-print tracking is the primary weight-update path for Spoolman, mirroring
  441. how the internal Filament Inventory works. The legacy AMS-remain%-based sync
  442. is no longer used as a weight writer (#1119), so this runs whenever Spoolman
  443. is enabled regardless of the deprecated `spoolman_disable_weight_sync` flag.
  444. ``plate_id``, when set, scopes the 3MF filament extract to a single plate so
  445. queue / direct-Print dispatch of plate N of a multi-plate file doesn't
  446. attribute every plate's filament to the printed spool (#1697). When unset,
  447. the queue item's plate_id (if any) is used; otherwise the whole-file sum is
  448. extracted, which is correct for direct prints that target the first/only
  449. plate of a single-plate file.
  450. """
  451. from backend.app.api.routes.settings import get_setting
  452. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  453. from backend.app.models.print_queue import PrintQueueItem
  454. # Check if Spoolman is enabled
  455. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  456. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  457. return
  458. # Get current AMS tray state up front — needed both for the 3MF path's
  459. # ams_trays field and for the remain%-delta snapshot (#1820 fallback for
  460. # no-3MF "Untitled" prints, mirroring usage_tracker.on_print_start).
  461. state = printer_manager.get_status(printer_id)
  462. ams_trays: dict[int, dict] = {}
  463. tray_remain_start: dict[str, dict] = {}
  464. if state and state.raw_data:
  465. ams_trays = build_ams_tray_lookup(state.raw_data)
  466. skipped_slots: list[str] = []
  467. tray_remain_start = _snapshot_tray_remain(state.raw_data, skipped_slots)
  468. if skipped_slots:
  469. # Matches what usage_tracker.on_print_start reports for the
  470. # internal inventory, so both backends name the slots that this
  471. # print will not be able to charge at AMS granularity.
  472. logger.info(
  473. "[SPOOLMAN] Printer %s: slots with no usable remain%% at print start: %s",
  474. printer_id,
  475. ", ".join(skipped_slots),
  476. )
  477. # Try to read per-slot filament estimates from the 3MF. Two paths can
  478. # leave ``filament_usage`` empty: (1) fallback archive (no .gcode.3mf
  479. # was downloadable from the printer — "Untitled" prints, see #1820),
  480. # (2) 3MF present but slice_info missing per-filament estimates.
  481. # Both fall through to the remain%-delta path at completion.
  482. filament_usage: list | None = None
  483. layer_usage_json: dict | None = None
  484. filament_properties: dict | None = None
  485. full_path = (
  486. app_settings.base_dir / file_path
  487. ) # SEC-PATH-OK: file_path is archive.file_path / library_file.file_path — DB-stored, internally generated
  488. threemf_available = bool(file_path) and full_path.exists()
  489. queue_item = None
  490. if threemf_available:
  491. # Resolve the queue item once — used both for the plate-scoped 3MF parsing
  492. # fallback (#1697: multi-plate file dispatched for one plate must only count
  493. # that plate's filament) and for the ams_mapping fallback below.
  494. # This printer's: a batch prints one archive as several queue items,
  495. # on several printers at once.
  496. queue_result = await db.execute(
  497. select(PrintQueueItem)
  498. .where(PrintQueueItem.archive_id == archive_id)
  499. .where(PrintQueueItem.printer_id == printer_id)
  500. .where(PrintQueueItem.status == "printing")
  501. .order_by(PrintQueueItem.id.desc())
  502. )
  503. queue_item = queue_result.scalars().first()
  504. # Caller-supplied plate_id wins (direct-Print path); fall back to the queue
  505. # item's plate_id (queue dispatch path).
  506. effective_plate_id = (
  507. plate_id if plate_id is not None else (queue_item.plate_id if queue_item is not None else None)
  508. )
  509. filament_usage, layer_usage_json, filament_properties = _extract_3mf_tracking(full_path, effective_plate_id)
  510. else:
  511. # No 3MF on disk — common for "Untitled" prints whose .gcode.3mf
  512. # was never on the printer's FTP. Logged at debug since the
  513. # fallback path below picks up the slack when remain% is available.
  514. logger.debug("[SPOOLMAN] 3MF file not available: %s", full_path)
  515. # If neither path has anything useful, there's nothing to track.
  516. if not filament_usage and not tray_remain_start:
  517. if threemf_available:
  518. logger.debug("[SPOOLMAN] No filament usage data in 3MF for archive %s", archive_id)
  519. return
  520. # Prefer the explicit mapping captured from the print command, then fall back
  521. # to any queue mapping stored for scheduled/reprint jobs.
  522. slot_to_tray = ams_mapping if ams_mapping is not None else None
  523. mapping_source = "print_cmd" if slot_to_tray else None
  524. if not slot_to_tray and queue_item and queue_item.ams_mapping:
  525. try:
  526. slot_to_tray = json.loads(queue_item.ams_mapping)
  527. mapping_source = "queue"
  528. except json.JSONDecodeError:
  529. pass # Ignore malformed AMS mapping; fall back to default slot assignment
  530. # Delete any existing row for this printer/archive (shouldn't exist, but just in case)
  531. await db.execute(
  532. delete(ActivePrintSpoolman)
  533. .where(ActivePrintSpoolman.printer_id == printer_id)
  534. .where(ActivePrintSpoolman.archive_id == archive_id)
  535. )
  536. # Insert new tracking data. ``filament_usage`` may be None for the
  537. # no-3MF case; report_usage falls back to ``tray_remain_start``.
  538. tracking = ActivePrintSpoolman(
  539. printer_id=printer_id,
  540. archive_id=archive_id,
  541. filament_usage=filament_usage,
  542. ams_trays=ams_trays,
  543. slot_to_tray=slot_to_tray,
  544. layer_usage=layer_usage_json,
  545. filament_properties=filament_properties,
  546. tray_remain_start=tray_remain_start or None,
  547. # Which slot the printer was drawing from when this print began. For a
  548. # print with no ams_mapping -- one started from the printer's own
  549. # screen, which is the case this whole fallback exists for -- it is the
  550. # only evidence of which slot the print used (#1820).
  551. tray_now_at_start=getattr(state, "tray_now", None) if state else None,
  552. )
  553. db.add(tracking)
  554. await db.commit()
  555. logger.info(
  556. "[SPOOLMAN] Stored tracking data for print: printer=%s, archive=%s (3mf=%s, remain_snapshot=%d slot(s))",
  557. printer_id,
  558. archive_id,
  559. "yes" if filament_usage else "no",
  560. len(tray_remain_start),
  561. )
  562. logger.debug("[SPOOLMAN] Filament usage: %s", filament_usage)
  563. logger.debug("[SPOOLMAN] AMS trays: %s", list(ams_trays.keys()))
  564. # Logged at info even when there is no mapping: "source: none" here is the
  565. # signal that completion will have to fall back, which is the single most
  566. # useful line in the log when a print is charged to the wrong spool (#2768).
  567. logger.info(
  568. "[SPOOLMAN] Print start: archive %s slot_to_tray=%s (source: %s)",
  569. archive_id,
  570. slot_to_tray,
  571. mapping_source or "none",
  572. )
  573. if layer_usage_json:
  574. logger.debug("[SPOOLMAN] Layer usage data available for partial tracking")
  575. async def cleanup_tracking(
  576. printer_id: int,
  577. archive_id: int,
  578. db,
  579. last_layer_num: int | None = None,
  580. last_progress: int | None = None,
  581. ) -> float | None:
  582. """Report partial usage and clean up Spoolman tracking data for failed/aborted prints.
  583. Returns what the charged spools' prices make the run cost, or None when
  584. none of them carries a price (or nothing was tracked)."""
  585. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  586. # Get tracking data first (needed for partial usage reporting)
  587. result = await db.execute(
  588. select(ActivePrintSpoolman)
  589. .where(ActivePrintSpoolman.printer_id == printer_id)
  590. .where(ActivePrintSpoolman.archive_id == archive_id)
  591. )
  592. tracking = result.scalar_one_or_none()
  593. if not tracking:
  594. logger.debug("[SPOOLMAN] No tracking data to clean up for printer=%s, archive=%s", printer_id, archive_id)
  595. return None
  596. # Try to report partial usage before cleanup, pricing each charge as it
  597. # is made: the run's own cost, as the built-in inventory logs it.
  598. print_cost = _PrintCost()
  599. try:
  600. await _report_partial_usage(
  601. printer_id,
  602. tracking,
  603. last_layer_num=last_layer_num,
  604. last_progress=last_progress,
  605. cost_out=print_cost,
  606. )
  607. except Exception as e:
  608. logger.warning("[SPOOLMAN] Partial usage report failed: %s", e)
  609. # Delete tracking data
  610. await db.execute(
  611. delete(ActivePrintSpoolman)
  612. .where(ActivePrintSpoolman.printer_id == printer_id)
  613. .where(ActivePrintSpoolman.archive_id == archive_id)
  614. )
  615. await db.commit()
  616. logger.debug("[SPOOLMAN] Cleaned up tracking data for printer=%s, archive=%s", printer_id, archive_id)
  617. # A charged spool without a price at the default rate, as the built-in
  618. # inventory prices its own (usage_tracker's cost_per_kg fallback).
  619. run_cost = print_cost.cost
  620. if print_cost.unpriced_grams > 0:
  621. from backend.app.services.print_cost_estimate import default_cost_per_kg
  622. run_cost += print_cost.unpriced_grams / 1000.0 * await default_cost_per_kg(db)
  623. return round(run_cost, 2) or None
  624. async def release_archived_slot_rows(printer_id: int) -> None:
  625. """Unassign the printer's slots whose Spoolman spool is archived or gone.
  626. Archiving a spool through Bambuddy keeps the slot of a printer whose print
  627. it may be feeding: usage is charged at completion by the slot's spool, and
  628. only the slot row knows it for a spool without a tag. Run once that print's
  629. usage is reported. Also catches spools archived or deleted in Spoolman.
  630. Best-effort: a failure leaves the rows for the next print to try again.
  631. """
  632. from backend.app.api.routes.settings import get_setting
  633. from backend.app.core.websocket import ws_manager
  634. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  635. try:
  636. async with async_session() as db:
  637. enabled = await get_setting(db, "spoolman_enabled")
  638. if not enabled or enabled.lower() != "true":
  639. return
  640. rows = (
  641. (
  642. await db.execute(
  643. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  644. )
  645. )
  646. .scalars()
  647. .all()
  648. )
  649. if not rows:
  650. return
  651. client = await _get_spoolman_client_with_fallback()
  652. if not client:
  653. return
  654. live = {
  655. spool["id"]
  656. for spool in await client.get_all_spools(allow_archived=True)
  657. if spool.get("id") is not None and not spool.get("archived")
  658. }
  659. freed: list[tuple[int, int]] = []
  660. for row in rows:
  661. if row.spoolman_spool_id in live:
  662. continue
  663. # Keyed on the spool too: the slot may have been given another
  664. # spool since the rows were read.
  665. result = cast(
  666. CursorResult,
  667. await db.execute(
  668. delete(SpoolmanSlotAssignment).where(
  669. SpoolmanSlotAssignment.id == row.id,
  670. SpoolmanSlotAssignment.spoolman_spool_id == row.spoolman_spool_id,
  671. )
  672. ),
  673. )
  674. if result.rowcount:
  675. freed.append((row.ams_id, row.tray_id))
  676. if not freed:
  677. return
  678. await db.commit()
  679. for ams_id, tray_id in freed:
  680. await ws_manager.broadcast(
  681. {"type": "spool_assignment_changed", "printer_id": printer_id, "ams_id": ams_id, "tray_id": tray_id}
  682. )
  683. except Exception as e: # noqa: BLE001 — best-effort cleanup after completion
  684. logger.warning("[SPOOLMAN] Could not release archived spools' slots on printer %s: %s", printer_id, e)
  685. async def _get_spoolman_client_with_fallback():
  686. """Get Spoolman client, initializing from settings if needed.
  687. Returns (client, is_healthy) tuple. Client may be None.
  688. """
  689. client = await get_spoolman_client()
  690. if not client:
  691. async with async_session() as db:
  692. from backend.app.api.routes.settings import get_setting
  693. spoolman_url = await get_setting(db, "spoolman_url")
  694. if spoolman_url:
  695. try:
  696. client = await init_spoolman_client(spoolman_url)
  697. except ValueError as exc:
  698. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  699. return None
  700. if not client:
  701. return None
  702. if not await client.health_check():
  703. logger.warning("Spoolman health check failed; skipping usage reporting")
  704. return None
  705. return client
  706. async def _resolve_spool_id_via_slot_assignment(printer_id: int, ams_id: int, tray_id: int) -> int | None:
  707. """Look up the Spoolman spool ID locally bound to (printer, ams, tray).
  708. Fallback path for #1459: when a tag-less spool was assigned via the
  709. Bambuddy UI, the user's deterministic fallback tag is intentionally NOT
  710. written to Spoolman's extra.tag (kept clean per #1457), so
  711. find_spool_by_tag misses. The local spoolman_slot_assignments table is
  712. the authoritative binding for those spools.
  713. """
  714. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  715. async with async_session() as db:
  716. result = await db.execute(
  717. select(SpoolmanSlotAssignment.spoolman_spool_id).where(
  718. SpoolmanSlotAssignment.printer_id == printer_id,
  719. SpoolmanSlotAssignment.ams_id == ams_id,
  720. SpoolmanSlotAssignment.tray_id == tray_id,
  721. )
  722. )
  723. return result.scalar_one_or_none()
  724. def _as_positive_number(value) -> float | None:
  725. """``value`` as a float when it is a usable positive quantity, else None.
  726. Rejects bools (``True`` is an int in Python, and ``float(True)`` is 1.0 --
  727. a weight of 1 g would price a spool per-gram at its whole cost), and
  728. rejects NaN and infinity, which compare False against every bound and would
  729. otherwise reach the archive as a NaN cost that no later comparison can
  730. clear.
  731. """
  732. if isinstance(value, bool):
  733. return None
  734. try:
  735. number = float(value)
  736. except (TypeError, ValueError):
  737. return None
  738. if not math.isfinite(number) or number <= 0:
  739. return None
  740. return number
  741. def _spool_cost_per_gram(spool: dict | None) -> float | None:
  742. """What one gram off this Spoolman spool costs, or None if it can't be said.
  743. Spoolman prices a spool in two places. ``filament.price`` is the catalogue
  744. figure for a full spool of that filament, and ``price`` on the spool itself
  745. overrides it when a particular purchase cost something else -- a sale, a
  746. different vendor, import duty. The spool's own value wins, which is the
  747. order the Spoolman UI presents them in.
  748. Each price is divided by the net weight it was paid for, excluding the
  749. core: the spool's price by the spool's own ``initial_weight`` (falling
  750. back to the filament's), the catalogue price by ``filament.weight``. A
  751. 250 g spool of a 1000 g filament was otherwise charged at a quarter of
  752. its rate (#3194).
  753. A missing or non-positive price is not a free spool, it is an unpriced one,
  754. and returns None so the caller can fall back to the global default rate
  755. rather than silently recording that this print cost nothing. Mirrors the
  756. ``cost_per_kg > 0`` guard the built-in inventory writer applies to its own
  757. per-spool rate.
  758. """
  759. if not isinstance(spool, dict):
  760. return None
  761. filament = spool.get("filament")
  762. if not isinstance(filament, dict):
  763. filament = {}
  764. # A spool-level 0 is treated as "not overridden" rather than "this roll was
  765. # free": Spoolman leaves the field null when unset, but an import or an API
  766. # client that writes 0 instead is common enough that reading it as free
  767. # would price a whole print at the default rate while a perfectly good
  768. # catalogue price sat one level down.
  769. price = _as_positive_number(spool.get("price"))
  770. if price is not None:
  771. weight = _as_positive_number(spoolman_net_weight(spool))
  772. else:
  773. price = _as_positive_number(filament.get("price"))
  774. weight = _as_positive_number(filament.get("weight"))
  775. if price is None or weight is None:
  776. return None
  777. # Both operands can be finite and the quotient still overflow. A non-finite
  778. # rate would reach the archive as a NaN or inf cost, and every later
  779. # comparison against it is False, so nothing downstream would correct it.
  780. rate = price / weight
  781. return rate if math.isfinite(rate) else None
  782. @dataclass
  783. class _PrintCost:
  784. """What a print cost, accumulated as each slot is actually charged.
  785. Only grams that were both charged to a spool *and* priced from it are
  786. counted. Everything else -- a slot whose spool has no price, a tray with no
  787. Spoolman row at all, filament the 3MF never attributed -- is left for the
  788. caller to cover at the global default rate, in one subtraction against the
  789. archive's own total. That is the same shape as the built-in inventory
  790. writer's untracked-grams top-up (#1344), and it means a partially priced
  791. print reports a whole-print figure rather than only the priced share.
  792. """
  793. cost: float = 0.0
  794. priced_grams: float = 0.0
  795. unpriced_grams: float = 0.0
  796. priced: int = 0
  797. unpriced: int = 0
  798. def add(self, grams: float, spool: dict | None, label: str) -> None:
  799. """Price ``grams`` off ``spool``. Call only after the charge succeeded."""
  800. if grams <= 0:
  801. return
  802. rate = _spool_cost_per_gram(spool)
  803. if rate is None:
  804. self.unpriced += 1
  805. self.unpriced_grams += grams
  806. logger.debug("[SPOOLMAN] %s: spool has no usable price, will fall back to the default rate", label)
  807. return
  808. self.cost += grams * rate
  809. self.priced_grams += grams
  810. self.priced += 1
  811. async def _report_spool_usage_for_slots(
  812. client,
  813. filament_usage_items: list[tuple[int, float]],
  814. ams_trays: dict[int, dict],
  815. slot_to_tray: list | None,
  816. method_label: str,
  817. printer_serial: str = "",
  818. printer_id: int | None = None,
  819. slot_colors_out: dict[int, str] | None = None,
  820. slot_materials_out: dict[int, str] | None = None,
  821. cost_out: _PrintCost | None = None,
  822. ) -> int:
  823. """Report usage to Spoolman for a list of (slot_id, grams) pairs.
  824. Resolution order per slot: (1) Spoolman extra.tag match against the
  825. tray's RFID or deterministic fallback tag, (2) #1459 fallback —
  826. local spoolman_slot_assignments table keyed by (printer_id, ams_id,
  827. tray_id). Without (2), tag-less spools assigned via the Bambuddy UI
  828. never get their weight decremented because their extra.tag is empty
  829. on the Spoolman side.
  830. When ``slot_colors_out`` is provided it is populated with
  831. ``{slot_id: color_hex}`` for every resolved spool — used by
  832. :func:`report_usage` to stamp the archive's filament colour from the
  833. Spoolman spool rather than the slicer's 3MF value (#1494).
  834. Returns number of spools successfully updated.
  835. """
  836. spools_updated = 0
  837. for slot_id, grams_used in filament_usage_items:
  838. if grams_used <= 0:
  839. continue
  840. global_tray_id = _resolve_global_tray_id(slot_id, slot_to_tray, ams_trays)
  841. tray_info = ams_trays.get(global_tray_id)
  842. if not tray_info:
  843. logger.debug("[SPOOLMAN] Slot %s: no tray at global_tray_id %s", slot_id, global_tray_id)
  844. continue
  845. is_external = global_tray_id >= 254
  846. tray_type = tray_info.get("tray_type", "")
  847. logger.debug(
  848. "[SPOOLMAN] Slot %s resolved to global_tray_id %s (tray_type=%s, external=%s)",
  849. slot_id,
  850. global_tray_id,
  851. tray_type or "unknown",
  852. is_external,
  853. )
  854. spool_id_to_use: int | None = None
  855. resolution_path = ""
  856. # color_hex + material of the resolved spool's filament, for the #1494
  857. # archive colour rewrite and the #2563 type rewrite. The tag path
  858. # already has the full spool object; the slot-assignment path only
  859. # yields an id and is fetched below.
  860. spool_color_hex: str | None = None
  861. spool_material: str | None = None
  862. # Full spool row, kept so the price fields (#2591) can be read from the
  863. # same fetch the colour and material already pay for.
  864. spool_obj: dict | None = None
  865. spool_tag = _resolve_spool_tag(tray_info, printer_serial, global_tray_id)
  866. if spool_tag:
  867. spool = await client.find_spool_by_tag(spool_tag)
  868. if spool:
  869. spool_id_to_use = spool["id"]
  870. resolution_path = "tag"
  871. spool_obj = spool
  872. spool_color_hex = (spool.get("filament") or {}).get("color_hex")
  873. spool_material = (spool.get("filament") or {}).get("material")
  874. if spool_id_to_use is None and printer_id is not None:
  875. ams_id, tray_id = _global_tray_id_to_ams_slot(global_tray_id)
  876. spool_id_to_use = await _resolve_spool_id_via_slot_assignment(printer_id, ams_id, tray_id)
  877. if spool_id_to_use is not None:
  878. resolution_path = "slot-assignment"
  879. if spool_id_to_use is None:
  880. logger.debug(
  881. "[SPOOLMAN] Slot %s: no spool resolved (tag=%s, no slot-assignment)",
  882. slot_id,
  883. spool_tag[:16] if spool_tag else "none",
  884. )
  885. continue
  886. # Record the spool's filament colour + material for the archive
  887. # rewrites (#1494, #2563). The slot-assignment path resolved only an
  888. # id, so fetch the spool once for whichever value is still missing.
  889. # Strictly best-effort: a fetch failure must never abort the weight
  890. # reporting for the remaining slots, so the catch is broad.
  891. if slot_colors_out is not None or slot_materials_out is not None or cost_out is not None:
  892. need_color = slot_colors_out is not None and spool_color_hex is None
  893. need_material = slot_materials_out is not None and spool_material is None
  894. need_price = cost_out is not None and spool_obj is None
  895. if need_color or need_material or need_price:
  896. try:
  897. spool_obj = await client.get_spool(spool_id_to_use)
  898. _fil = spool_obj.get("filament") or {}
  899. if need_color:
  900. spool_color_hex = _fil.get("color_hex")
  901. if need_material:
  902. spool_material = _fil.get("material")
  903. except Exception as exc: # noqa: BLE001 — colour/material/price are non-critical
  904. logger.debug("[SPOOLMAN] Slot %s: could not fetch spool filament: %s", slot_id, exc)
  905. if slot_colors_out is not None and spool_color_hex:
  906. slot_colors_out[slot_id] = spool_color_hex
  907. if slot_materials_out is not None and spool_material:
  908. slot_materials_out[slot_id] = spool_material
  909. try:
  910. await client.use_spool(spool_id_to_use, grams_used)
  911. logger.info(
  912. "[SPOOLMAN] %s: slot %s: %sg -> spool %s (via %s)",
  913. method_label,
  914. slot_id,
  915. grams_used,
  916. spool_id_to_use,
  917. resolution_path,
  918. )
  919. spools_updated += 1
  920. # Priced only after the charge landed, so a spool Spoolman refused
  921. # cannot contribute to what the print is said to have cost.
  922. if cost_out is not None:
  923. cost_out.add(grams_used, spool_obj, f"Slot {slot_id}")
  924. except (SpoolmanNotFoundError, SpoolmanClientError, SpoolmanUnavailableError) as exc:
  925. logger.warning("[SPOOLMAN] Failed to record usage for spool %s: %s", spool_id_to_use, exc)
  926. return spools_updated
  927. async def _report_spool_usage_split_by_tray_changes(
  928. client,
  929. filament_usage: list[dict],
  930. tray_changes: list[tuple[int, int]],
  931. ams_trays: dict[int, dict],
  932. layer_usage: dict[int, dict[int, float]] | None,
  933. filament_properties: dict | None,
  934. total_layers: int,
  935. last_layer_num: int,
  936. method_label: str,
  937. printer_serial: str,
  938. printer_id: int,
  939. slot_colors_out: dict[int, str] | None = None,
  940. slot_materials_out: dict[int, str] | None = None,
  941. cost_out: _PrintCost | None = None,
  942. ) -> tuple[int, set[int]]:
  943. """Split each slot's grams across ``tray_changes`` and charge per-segment.
  944. Mirrors ``usage_tracker`` Path 1's tray-switch branch so Spoolman and
  945. the internal Spool inventory attribute mid-print AMS-backup switches
  946. identically (#1793 — reporter's origin spool was over-charged the
  947. whole print because this path didn't exist). ``compute_tray_split_grams``
  948. holds the shared segment-math; this function wraps the per-segment
  949. spool resolution + ``use_spool`` sink for the Spoolman side.
  950. Returns ``(spools_updated, handled_global_tray_ids)`` — the caller
  951. passes ``handled_global_tray_ids`` into the remain-delta fallback so
  952. a tray attributed here is not double-charged there.
  953. """
  954. from backend.app.utils.tray_split import compute_tray_split_grams
  955. spools_updated = 0
  956. handled_global_tray_ids: set[int] = set()
  957. for usage in filament_usage:
  958. slot_id = usage.get("slot_id", 0)
  959. total_weight = usage.get("used_g", 0)
  960. if total_weight <= 0 or slot_id <= 0:
  961. continue
  962. props = (filament_properties or {}).get(str(slot_id)) or (filament_properties or {}).get(slot_id) or {}
  963. segments = compute_tray_split_grams(
  964. tray_changes=tray_changes,
  965. total_weight=float(total_weight),
  966. slot_id=slot_id,
  967. layer_usage=layer_usage,
  968. density=float(props.get("density", 1.24)),
  969. diameter=float(props.get("diameter", 1.75)),
  970. total_layers=total_layers,
  971. last_layer_num=last_layer_num,
  972. )
  973. for seg_idx, tray_global, segment_grams in segments:
  974. if segment_grams <= 0:
  975. continue
  976. # Mark this tray as handled BEFORE the resolution attempt so
  977. # remain-delta doesn't double-charge it, even if we fail to
  978. # find a spool below. Matches usage_tracker behaviour: the
  979. # tray was physically fed from during this print, whether or
  980. # not Spoolman happens to have a matching row.
  981. handled_global_tray_ids.add(tray_global)
  982. tray_info = ams_trays.get(tray_global) or {}
  983. spool_id_to_use: int | None = None
  984. resolution_path = ""
  985. spool_color_hex: str | None = None
  986. spool_material: str | None = None
  987. spool_obj: dict | None = None
  988. spool_tag = _resolve_spool_tag(tray_info, printer_serial, tray_global) if tray_info else ""
  989. if spool_tag:
  990. spool = await client.find_spool_by_tag(spool_tag)
  991. if spool:
  992. spool_id_to_use = spool["id"]
  993. resolution_path = "tag"
  994. spool_obj = spool
  995. spool_color_hex = (spool.get("filament") or {}).get("color_hex")
  996. spool_material = (spool.get("filament") or {}).get("material")
  997. if spool_id_to_use is None:
  998. seg_ams_id, seg_tray_id = _global_tray_id_to_ams_slot(tray_global)
  999. spool_id_to_use = await _resolve_spool_id_via_slot_assignment(printer_id, seg_ams_id, seg_tray_id)
  1000. if spool_id_to_use is not None:
  1001. resolution_path = "slot-assignment"
  1002. if spool_id_to_use is None:
  1003. logger.info(
  1004. "[SPOOLMAN] Split slot %s seg %s tray=%d: no spool resolved — %.2fg lost from split accounting",
  1005. slot_id,
  1006. seg_idx,
  1007. tray_global,
  1008. segment_grams,
  1009. )
  1010. continue
  1011. # Colour (#1494) + material (#2563) rewrite — first segment for a
  1012. # slot wins. The UI displays a single colour/type per slot, so
  1013. # later segments on the same slot don't overwrite (a backup swap
  1014. # can differ but the archive card stays consistent with the origin).
  1015. need_color = slot_colors_out is not None and slot_id not in slot_colors_out and spool_color_hex is None
  1016. need_material = (
  1017. slot_materials_out is not None and slot_id not in slot_materials_out and spool_material is None
  1018. )
  1019. # Unlike the colour, every segment needs its own price: each was
  1020. # charged to its own spool, and a backup roll can have cost
  1021. # something different from the one it replaced.
  1022. need_price = cost_out is not None and spool_obj is None
  1023. if need_color or need_material or need_price:
  1024. try:
  1025. spool_obj = await client.get_spool(spool_id_to_use)
  1026. _fil = spool_obj.get("filament") or {}
  1027. if need_color:
  1028. spool_color_hex = _fil.get("color_hex")
  1029. if need_material:
  1030. spool_material = _fil.get("material")
  1031. except Exception as exc: # noqa: BLE001 — colour/material/price are non-critical
  1032. logger.debug("[SPOOLMAN] Split slot %s: could not fetch spool filament: %s", slot_id, exc)
  1033. if slot_colors_out is not None and slot_id not in slot_colors_out and spool_color_hex:
  1034. slot_colors_out[slot_id] = spool_color_hex
  1035. if slot_materials_out is not None and slot_id not in slot_materials_out and spool_material:
  1036. slot_materials_out[slot_id] = spool_material
  1037. try:
  1038. await client.use_spool(spool_id_to_use, round(segment_grams, 2))
  1039. logger.info(
  1040. "[SPOOLMAN] %s: slot %s seg %s tray=%d: %.2fg -> spool %s (via %s)",
  1041. method_label,
  1042. slot_id,
  1043. seg_idx,
  1044. tray_global,
  1045. segment_grams,
  1046. spool_id_to_use,
  1047. resolution_path,
  1048. )
  1049. spools_updated += 1
  1050. if cost_out is not None:
  1051. cost_out.add(round(segment_grams, 2), spool_obj, f"Split slot {slot_id} seg {seg_idx}")
  1052. except (SpoolmanNotFoundError, SpoolmanClientError, SpoolmanUnavailableError) as exc:
  1053. logger.warning(
  1054. "[SPOOLMAN] Split slot %s seg %s: failed to record usage for spool %s: %s",
  1055. slot_id,
  1056. seg_idx,
  1057. spool_id_to_use,
  1058. exc,
  1059. )
  1060. return spools_updated, handled_global_tray_ids
  1061. async def _report_partial_usage(
  1062. printer_id: int,
  1063. tracking,
  1064. last_layer_num: int | None = None,
  1065. last_progress: int | None = None,
  1066. cost_out: _PrintCost | None = None,
  1067. ):
  1068. """Report partial filament usage based on actual G-code layer data.
  1069. Uses per-layer cumulative extrusion from G-code parsing for accurate
  1070. multi-material tracking. Falls back to linear interpolation if G-code
  1071. data is unavailable.
  1072. """
  1073. from backend.app.services.printer_manager import printer_manager
  1074. from backend.app.utils.threemf_tools import get_cumulative_usage_at_layer, mm_to_grams
  1075. async with async_session() as db:
  1076. from backend.app.api.routes.settings import get_setting
  1077. # Check if partial usage reporting is enabled (default: true)
  1078. report_partial = await get_setting(db, "spoolman_report_partial_usage")
  1079. if report_partial and report_partial.lower() == "false":
  1080. logger.debug("[SPOOLMAN] Partial usage reporting disabled by setting")
  1081. return
  1082. # Check if Spoolman is enabled
  1083. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1084. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  1085. return
  1086. # Get current printer state for layer progress.
  1087. # On failed/aborted prints the firmware may already reset to IDLE with layer=0,
  1088. # so we fall back to completion-time hints captured from MQTT.
  1089. state = printer_manager.get_status(printer_id)
  1090. current_layer = state.layer_num if state else None
  1091. total_layers = state.total_layers if state else None
  1092. if (not current_layer or current_layer <= 0) and last_layer_num and last_layer_num > 0:
  1093. current_layer = last_layer_num
  1094. logger.debug("[SPOOLMAN] Using captured last_layer_num=%s for partial usage", current_layer)
  1095. progress_ratio_from_event = None
  1096. if last_progress is not None:
  1097. try:
  1098. progress_ratio_from_event = min(max(float(last_progress), 0.0), 100.0) / 100.0
  1099. except (TypeError, ValueError):
  1100. progress_ratio_from_event = None
  1101. if (not current_layer or current_layer <= 0) and progress_ratio_from_event and total_layers and total_layers > 0:
  1102. current_layer = max(1, int(round(total_layers * progress_ratio_from_event)))
  1103. logger.debug(
  1104. "[SPOOLMAN] Estimated layer from last_progress=%s%% and total_layers=%s -> %s",
  1105. last_progress,
  1106. total_layers,
  1107. current_layer,
  1108. )
  1109. if not current_layer or current_layer <= 0:
  1110. logger.debug(
  1111. "[SPOOLMAN] No progress to report (layer 0/unknown, last_layer_num=%s, last_progress=%s)",
  1112. last_layer_num,
  1113. last_progress,
  1114. )
  1115. return
  1116. logger.info("[SPOOLMAN] Reporting partial usage at layer %s/%s", current_layer, total_layers or "?")
  1117. # Get tracking data
  1118. layer_usage = tracking.layer_usage
  1119. filament_properties = tracking.filament_properties or {}
  1120. filament_usage = tracking.filament_usage or []
  1121. ams_trays = {int(k): v for k, v in (tracking.ams_trays or {}).items()}
  1122. slot_to_tray = tracking.slot_to_tray
  1123. tray_remain_start = tracking.tray_remain_start or {}
  1124. printer_serial = await _get_printer_serial(printer_id)
  1125. client = await _get_spoolman_client_with_fallback()
  1126. if not client:
  1127. logger.warning("[SPOOLMAN] Not reachable for partial usage reporting")
  1128. return
  1129. # No-3MF aborted print (#1820 mirror of the completion path): nothing in
  1130. # filament_usage or layer_usage to base partial estimates on, but the
  1131. # remain%-delta snapshot we captured at start still describes consumption
  1132. # up to the abort moment. Write it the same way report_usage's fallback
  1133. # does, then return — there's no 3MF-derived partial to layer on top.
  1134. # ``state`` was already fetched at the top of the function for current_layer.
  1135. if not filament_usage and not layer_usage and tray_remain_start:
  1136. current_lookup = _snapshot_tray_remain(state.raw_data) if state and state.raw_data else {}
  1137. await _report_remain_delta_for_slots(
  1138. client,
  1139. printer_id=printer_id,
  1140. tray_remain_start=tray_remain_start,
  1141. current_lookup=current_lookup,
  1142. handled_global_tray_ids=set(),
  1143. archive_id=getattr(tracking, "archive_id", -1),
  1144. print_used_keys=_print_used_tray_keys(slot_to_tray, getattr(tracking, "tray_now_at_start", None), state),
  1145. cost_out=cost_out,
  1146. )
  1147. return
  1148. # Same recovery the completion path does, for the same reason: a print
  1149. # dispatched from Studio over the cloud left print start with no mapping to
  1150. # store, and both paths below feed ``slot_to_tray`` to
  1151. # ``_resolve_global_tray_id`` (#2768). An aborted print charges the wrong
  1152. # spool just as readily as a finished one.
  1153. if not slot_to_tray:
  1154. slot_to_tray, _partial_mapping_source = _resolve_slot_to_tray_fallback(
  1155. printer_id,
  1156. filament_usage,
  1157. getattr(tracking, "tray_now_at_start", None),
  1158. )
  1159. logger.info(
  1160. "[SPOOLMAN] Partial usage: slot_to_tray=%s (source: %s)",
  1161. slot_to_tray,
  1162. _partial_mapping_source,
  1163. )
  1164. # A single-filament print that switched trays (AMS backup on a runout)
  1165. # charges each tray its share of the partial grams, by layer up to where
  1166. # the print stopped, as the built-in inventory and the completion path do
  1167. # (#1793). The G-code split is not used here: its last segment runs to the
  1168. # end of the whole print. A multi-material print keeps the mapping.
  1169. tray_changes = list(getattr(state, "tray_change_log", None) or []) if state else []
  1170. async def _charge(usage_items: list[tuple[int, float]], method_label: str) -> int:
  1171. used = [(slot_id, grams) for slot_id, grams in usage_items if grams > 0]
  1172. if len(used) == 1 and len(tray_changes) > 1:
  1173. # Never short of a logged switch: a stop layer estimated from
  1174. # progress could otherwise give a segment more than the total.
  1175. split_layers = max([current_layer] + [layer for _, layer in tray_changes])
  1176. updated, _ = await _report_spool_usage_split_by_tray_changes(
  1177. client,
  1178. [{"slot_id": used[0][0], "used_g": used[0][1]}],
  1179. tray_changes,
  1180. ams_trays,
  1181. None,
  1182. filament_properties,
  1183. split_layers,
  1184. split_layers,
  1185. f"{method_label} split",
  1186. printer_serial,
  1187. printer_id=printer_id,
  1188. cost_out=cost_out,
  1189. )
  1190. return updated
  1191. return await _report_spool_usage_for_slots(
  1192. client,
  1193. usage_items,
  1194. ams_trays,
  1195. slot_to_tray,
  1196. method_label,
  1197. printer_serial,
  1198. printer_id=printer_id,
  1199. cost_out=cost_out,
  1200. )
  1201. # Try to use accurate G-code parsed data
  1202. if layer_usage:
  1203. layer_usage_int = {
  1204. int(layer): {int(fid): mm for fid, mm in filaments.items()} for layer, filaments in layer_usage.items()
  1205. }
  1206. usage_mm = get_cumulative_usage_at_layer(layer_usage_int, current_layer)
  1207. if usage_mm:
  1208. logger.info("[SPOOLMAN] Using G-code parsed data for layer %s", current_layer)
  1209. # Build (slot_id, grams) list using Spoolman densities with 3MF fallback
  1210. usage_items = []
  1211. for filament_id, mm_used in usage_mm.items():
  1212. slot_id = filament_id + 1 # filament_id is 0-based, slot_id is 1-based
  1213. # Get density from Spoolman (most accurate), fall back to 3MF, then PLA default
  1214. global_tray_id = _resolve_global_tray_id(slot_id, slot_to_tray, ams_trays)
  1215. tray_info = ams_trays.get(global_tray_id)
  1216. density = None
  1217. diameter = 1.75
  1218. if tray_info:
  1219. spool_tag = _resolve_spool_tag(tray_info, printer_serial, global_tray_id)
  1220. if spool_tag:
  1221. spool = await client.find_spool_by_tag(spool_tag)
  1222. if spool:
  1223. filament_data = spool.get("filament", {})
  1224. density = filament_data.get("density")
  1225. diameter = filament_data.get("diameter", 1.75)
  1226. if not density:
  1227. props = filament_properties.get(str(slot_id), filament_properties.get(slot_id, {}))
  1228. density = props.get("density", 1.24)
  1229. logger.debug("[SPOOLMAN] Using fallback density %s for slot %s", density, slot_id)
  1230. grams_used = round(mm_to_grams(mm_used, diameter, density), 2)
  1231. usage_items.append((slot_id, grams_used))
  1232. spools_updated = await _charge(usage_items, "Partial (G-code)")
  1233. if spools_updated > 0:
  1234. logger.info("[SPOOLMAN] Reported partial usage to %s spool(s) using G-code data", spools_updated)
  1235. return
  1236. # Fallback: linear interpolation (if no G-code data available)
  1237. progress_ratio = None
  1238. if total_layers and total_layers > 0:
  1239. progress_ratio = min(current_layer / total_layers, 1.0)
  1240. elif progress_ratio_from_event is not None:
  1241. progress_ratio = progress_ratio_from_event
  1242. if progress_ratio is None:
  1243. logger.debug(
  1244. "[SPOOLMAN] Cannot use linear fallback: total_layers=%s, last_progress=%s",
  1245. total_layers,
  1246. last_progress,
  1247. )
  1248. return
  1249. logger.info("[SPOOLMAN] Falling back to linear interpolation (%s)", progress_ratio)
  1250. usage_items = []
  1251. for usage in filament_usage:
  1252. slot_id = usage.get("slot_id", 0)
  1253. total_used_g = usage.get("used_g", 0)
  1254. if total_used_g > 0:
  1255. partial_used_g = round(total_used_g * progress_ratio, 2)
  1256. usage_items.append((slot_id, partial_used_g))
  1257. spools_updated = await _charge(usage_items, "Partial (linear)")
  1258. if spools_updated > 0:
  1259. logger.info("[SPOOLMAN] Reported partial usage to %s spool(s) using linear interpolation", spools_updated)
  1260. async def report_usage(printer_id: int, archive_id: int):
  1261. """Report filament usage to Spoolman after print completion.
  1262. Two writers, mirroring the internal-inventory split in usage_tracker:
  1263. 1. **3MF path (primary)** — per-filament slice estimates captured at
  1264. print start drive a precise per-slot ``use_spool`` call.
  1265. 2. **AMS remain%-delta (fallback)** — for slots the 3MF path didn't
  1266. handle (including the no-3MF "Untitled" case from #1820): compute
  1267. ``start_remain - current_remain``, multiply by the resolved
  1268. Spoolman filament's reference weight, and write the delta. Mirrors
  1269. ``usage_tracker.on_print_complete`` Path 2 (line 517).
  1270. """
  1271. async with async_session() as db:
  1272. from backend.app.api.routes.settings import get_setting
  1273. from backend.app.models.active_print_spoolman import ActivePrintSpoolman
  1274. # Get tracking data stored at print start
  1275. result = await db.execute(
  1276. select(ActivePrintSpoolman)
  1277. .where(ActivePrintSpoolman.printer_id == printer_id)
  1278. .where(ActivePrintSpoolman.archive_id == archive_id)
  1279. )
  1280. tracking = result.scalar_one_or_none()
  1281. if not tracking:
  1282. logger.info("[SPOOLMAN] No tracking data for print (printer=%s, archive=%s)", printer_id, archive_id)
  1283. return
  1284. filament_usage = tracking.filament_usage or []
  1285. ams_trays = {int(k): v for k, v in (tracking.ams_trays or {}).items()}
  1286. slot_to_tray = tracking.slot_to_tray
  1287. tray_remain_start = tracking.tray_remain_start or {}
  1288. # ``layer_usage`` and ``filament_properties`` were added later than
  1289. # the base tracking fields; use ``getattr`` so tests that stub
  1290. # ``tracking`` as a lightweight SimpleNamespace stay valid, and
  1291. # historic ORM rows loaded without these columns can't AttributeError
  1292. # on read.
  1293. layer_usage_raw = getattr(tracking, "layer_usage", None) or {}
  1294. filament_properties = getattr(tracking, "filament_properties", None) or {}
  1295. tray_now_at_start = getattr(tracking, "tray_now_at_start", None)
  1296. printer_serial = await _get_printer_serial(printer_id)
  1297. # Delete tracking row (we're done with it)
  1298. await db.delete(tracking)
  1299. await db.commit()
  1300. if not filament_usage and not tray_remain_start:
  1301. logger.debug("[SPOOLMAN] No usage data or remain-snapshot for archive %s", archive_id)
  1302. return
  1303. # Check if Spoolman is enabled
  1304. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1305. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  1306. return
  1307. client = await _get_spoolman_client_with_fallback()
  1308. if not client:
  1309. logger.warning(
  1310. "[SPOOLMAN] Not reachable for usage reporting (printer=%s, archive=%s): "
  1311. "this print's usage is not sent, correct the spools in Spoolman by hand",
  1312. printer_id,
  1313. archive_id,
  1314. )
  1315. return
  1316. # Consult the live printer state for the tray-change log written by
  1317. # ``bambu_mqtt.py`` on every mid-print ``tray_now`` change (#957).
  1318. # When there's more than one entry, the print traversed >1 AMS tray
  1319. # and the split path attributes each segment to the tray that was
  1320. # loaded at the time — matches the internal Spool inventory writer
  1321. # in ``usage_tracker.py``. Without this, an AMS-backup runout switch
  1322. # charges the whole slot to the origin spool and pushes it past
  1323. # ``initial_weight`` (#1793).
  1324. #
  1325. # Split only for SINGLE-slot prints — same gate as
  1326. # ``usage_tracker.py:1002``. Multi-slot (multi-colour) prints
  1327. # naturally cycle trays for every colour change, so splitting each
  1328. # slot's grams across ALL tray_change_log entries would attribute
  1329. # slot 1's grams to the segments where slot 2's tray was loaded and
  1330. # vice versa. Multi-slot prints fall through to the existing
  1331. # single-tray path (which uses the stable ``slot_to_tray`` mapping).
  1332. nonzero_slots = [u for u in filament_usage if u.get("used_g", 0) > 0]
  1333. tray_changes: list[tuple[int, int]] = []
  1334. _state = None
  1335. if len(nonzero_slots) == 1:
  1336. from backend.app.services.printer_manager import printer_manager as _pm
  1337. _state = _pm.get_status(printer_id)
  1338. if _state is not None:
  1339. tray_changes = list(getattr(_state, "tray_change_log", []) or [])
  1340. _total_layers = int(getattr(_state, "total_layers", 0) or 0) if _state else 0
  1341. _current_layer = int(getattr(_state, "layer_num", 0) or 0) if _state else 0
  1342. # For the linear-fallback denominator when total_layers is 0 (P1S
  1343. # firmware resets it at print end). At completion the current layer
  1344. # is the print's last valid layer.
  1345. _layer_denom_hint = _total_layers or _current_layer
  1346. # Recover the mapping when print start had nothing to store — the
  1347. # cloud-dispatched Studio print of #2768. Only the 3MF path consumes
  1348. # ``slot_to_tray``; the remain-delta path below resolves spools from the
  1349. # AMS slot directly, so there is nothing to recover for it.
  1350. mapping_source = "stored" if slot_to_tray else "none"
  1351. if filament_usage and not slot_to_tray:
  1352. slot_to_tray, mapping_source = _resolve_slot_to_tray_fallback(printer_id, filament_usage, tray_now_at_start)
  1353. logger.info(
  1354. "[SPOOLMAN] Archive %s: slot_to_tray=%s (source: %s)",
  1355. archive_id,
  1356. slot_to_tray,
  1357. mapping_source,
  1358. )
  1359. # Nothing named a tray for this print and no fallback could recover
  1360. # one, so every slot is about to be resolved by position -- slicer slot
  1361. # 1 to the first loaded tray, and so on. That guess is right for an AMS
  1362. # loaded in slicer order and wrong for any other, and the caller has no
  1363. # way to tell which it got. Say so at a level that survives the default
  1364. # log filter, so a support bundle carries the reason (#2953).
  1365. #
  1366. # Excludes the tray-split path. It never reads ``slot_to_tray`` at all:
  1367. # it charges each segment to the tray the printer announced switching
  1368. # to, which is the same evidence the tray-state fallback is built on and
  1369. # is not a guess. Calling it one would suppress the archive rewrite for
  1370. # exactly the prints -- an AMS-backup runout on a Studio job (#1793 in
  1371. # #2768's conditions) -- whose attribution is best supported.
  1372. mapping_is_guess = bool(filament_usage) and mapping_source == "none" and len(tray_changes) <= 1
  1373. if mapping_is_guess:
  1374. logger.warning(
  1375. "[SPOOLMAN] Archive %s: no slot-to-tray mapping from any source -- "
  1376. "charging by tray position, which is a guess. Verify the spool weights "
  1377. "if the AMS is not loaded in slicer order.",
  1378. archive_id,
  1379. )
  1380. slot_colors: dict[int, str] = {}
  1381. slot_materials: dict[int, str] = {}
  1382. # Priced as each charge lands, so the figure the archive ends up with
  1383. # describes the same grams Spoolman actually had deducted (#2591).
  1384. print_cost = _PrintCost()
  1385. handled_global_tray_ids: set[int] = set()
  1386. spools_updated = 0
  1387. # --- Path 1: 3MF per-slot estimates -----------------------------
  1388. if filament_usage:
  1389. if len(tray_changes) > 1:
  1390. # Tray-split path — attribute per-segment to the tray that
  1391. # was loaded at that time.
  1392. logger.info(
  1393. "[SPOOLMAN] Reporting per-filament usage for archive %s with tray-split "
  1394. "(tray_change_log=%s, denom_layers=%d)",
  1395. archive_id,
  1396. tray_changes,
  1397. _layer_denom_hint,
  1398. )
  1399. # ``tracking.layer_usage`` was serialized to JSON so int keys
  1400. # come back as strings. Restore them for the split math.
  1401. layer_usage = None
  1402. if layer_usage_raw:
  1403. try:
  1404. layer_usage = {
  1405. int(layer): {int(fid): mm for fid, mm in filaments.items()}
  1406. for layer, filaments in layer_usage_raw.items()
  1407. }
  1408. except (TypeError, ValueError, AttributeError):
  1409. # AttributeError catches ``inner.items()`` when the
  1410. # inner value isn't dict-shaped (corrupt JSON row).
  1411. # Missing gcode falls through to the linear-ratio
  1412. # branch inside ``compute_tray_split_grams`` — still
  1413. # gives a correct split, just less precise.
  1414. layer_usage = None
  1415. split_updated, split_handled = await _report_spool_usage_split_by_tray_changes(
  1416. client,
  1417. filament_usage,
  1418. tray_changes,
  1419. ams_trays,
  1420. layer_usage,
  1421. filament_properties,
  1422. _total_layers,
  1423. _layer_denom_hint,
  1424. f"Archive {archive_id}",
  1425. printer_serial,
  1426. printer_id=printer_id,
  1427. slot_colors_out=slot_colors,
  1428. slot_materials_out=slot_materials,
  1429. cost_out=print_cost,
  1430. )
  1431. spools_updated += split_updated
  1432. handled_global_tray_ids |= split_handled
  1433. else:
  1434. logger.info("[SPOOLMAN] Reporting per-filament usage for archive %s", archive_id)
  1435. usage_items = [(u.get("slot_id", 0), u.get("used_g", 0)) for u in filament_usage]
  1436. spools_updated = await _report_spool_usage_for_slots(
  1437. client,
  1438. usage_items,
  1439. ams_trays,
  1440. slot_to_tray,
  1441. f"Archive {archive_id}",
  1442. printer_serial,
  1443. printer_id=printer_id,
  1444. slot_colors_out=slot_colors,
  1445. slot_materials_out=slot_materials,
  1446. cost_out=print_cost,
  1447. )
  1448. # Track which physical slots the 3MF path already covered so
  1449. # Path 2 doesn't double-charge them.
  1450. for u in filament_usage:
  1451. if u.get("used_g", 0) <= 0:
  1452. # ``_report_spool_usage_for_slots`` skipped this slot
  1453. # before resolving a tray for it, so nothing was
  1454. # charged and Path 2 is free to cover the slot from
  1455. # remain% -- claiming it here would suppress a real
  1456. # drop on the strength of a zero-gram estimate.
  1457. continue
  1458. slot_id = u.get("slot_id", 0)
  1459. handled_global_tray_ids.add(_resolve_global_tray_id(slot_id, slot_to_tray, ams_trays))
  1460. # --- Path 2: AMS remain%-delta for slots 3MF didn't cover -------
  1461. # Triggered for no-3MF "Untitled" prints (#1820) AND for partial
  1462. # 3MF coverage (slots whose filament_id wasn't in slice_info).
  1463. if tray_remain_start:
  1464. from backend.app.services.printer_manager import printer_manager
  1465. current = printer_manager.get_status(printer_id)
  1466. current_lookup = _snapshot_tray_remain(current.raw_data) if current and current.raw_data else {}
  1467. fallback_updates = await _report_remain_delta_for_slots(
  1468. client,
  1469. printer_id=printer_id,
  1470. tray_remain_start=tray_remain_start,
  1471. current_lookup=current_lookup,
  1472. handled_global_tray_ids=handled_global_tray_ids,
  1473. archive_id=archive_id,
  1474. print_used_keys=_print_used_tray_keys(slot_to_tray, tray_now_at_start, current),
  1475. slot_colors_out=slot_colors,
  1476. slot_materials_out=slot_materials,
  1477. cost_out=print_cost,
  1478. )
  1479. spools_updated += fallback_updates
  1480. if spools_updated == 0:
  1481. logger.info("[SPOOLMAN] Archive %s: no spools updated", archive_id)
  1482. else:
  1483. logger.info("[SPOOLMAN] Archive %s: updated %s spool(s)", archive_id, spools_updated)
  1484. # Stamp the archive's filament colour from the matched Spoolman spools
  1485. # so it reflects the curated inventory colour, not the slicer's 3MF
  1486. # value (#1494) — mirrors the built-in inventory path in usage_tracker.
  1487. #
  1488. # Skipped when the mapping was a positional guess. Charging the wrong
  1489. # spool costs grams the owner can put back; rewriting the archive's
  1490. # colour and material on top of it overwrites what the slicer actually
  1491. # recorded, and the print then reads as a different filament than the
  1492. # one that made it, with nothing left to compare against (#2953).
  1493. if mapping_is_guess:
  1494. if slot_colors or slot_materials:
  1495. logger.info(
  1496. "[SPOOLMAN] Archive %s: leaving filament colour/type as sliced — "
  1497. "the spools were matched by position, not by a known mapping",
  1498. archive_id,
  1499. )
  1500. else:
  1501. await _apply_spool_colors_to_archive(db, archive_id, filament_usage, slot_colors)
  1502. # Same for the material: a slot mapped to a differently-typed spool
  1503. # than it was sliced for otherwise records the sliced type (#2563).
  1504. await _apply_spool_types_to_archive(db, archive_id, filament_usage, slot_materials)
  1505. # Cost is applied whether or not the mapping was a guess, unlike the
  1506. # colour and material above. Those overwrite what the slicer recorded,
  1507. # which is why a guess must not touch them; the cost has no such
  1508. # original -- archive.py's figure is itself derived from a default rate
  1509. # -- and the grams have already been deducted from these spools, so the
  1510. # archive should say what that deduction was worth.
  1511. await _apply_spool_cost_to_archive(db, archive_id, print_cost)
  1512. def _print_used_tray_keys(
  1513. slot_to_tray: list | None,
  1514. tray_now_at_start: int | None,
  1515. state,
  1516. ) -> set[tuple[int, int]]:
  1517. """Which AMS slots this print actually drew from, as far as we can tell.
  1518. Mirrors the guard the internal tracker has carried since #1269. Without
  1519. it, swapping a spool in a slot the print never touched drops that slot's
  1520. ``remain%``, and the remain-delta path reads the drop as consumption and
  1521. charges it to whoever the slot is assigned to. That is a phantom write to
  1522. an uninvolved spool, and it is likeliest on exactly the prints this
  1523. fallback serves -- ones with no 3MF, where nothing else limits which slots
  1524. are considered.
  1525. Three sources, matching the internal tracker's:
  1526. - the print's ``ams_mapping``, stored here as ``slot_to_tray``;
  1527. - every tray the printer switched to mid-print;
  1528. - the tray it was drawing from at the start.
  1529. An empty result means no evidence, not "no slots" -- callers must then
  1530. consider every slot, as before, or a printer that reports none of the
  1531. three would silently stop being tracked at all.
  1532. Takes the two stored values rather than the tracking row: the caller
  1533. deletes that row before it gets this far, and everything read off it is
  1534. read into locals beforehand.
  1535. """
  1536. keys: set[tuple[int, int]] = set()
  1537. for global_tray_id in list(slot_to_tray or []):
  1538. if isinstance(global_tray_id, int) and global_tray_id >= 0:
  1539. keys.add(_global_tray_id_to_ams_slot(global_tray_id))
  1540. for change in getattr(state, "tray_change_log", None) or []:
  1541. if isinstance(change, (tuple, list)) and change:
  1542. global_tray_id = change[0]
  1543. if isinstance(global_tray_id, int) and global_tray_id >= 0:
  1544. keys.add(_global_tray_id_to_ams_slot(global_tray_id))
  1545. if isinstance(tray_now_at_start, int) and 0 <= tray_now_at_start <= _MAX_REAL_TRAY_ID:
  1546. keys.add(_global_tray_id_to_ams_slot(tray_now_at_start))
  1547. return keys
  1548. async def _report_remain_delta_for_slots(
  1549. client,
  1550. *,
  1551. printer_id: int,
  1552. tray_remain_start: dict[str, dict],
  1553. current_lookup: dict[str, dict],
  1554. handled_global_tray_ids: set[int],
  1555. archive_id: int,
  1556. print_used_keys: set[tuple[int, int]] | None = None,
  1557. slot_colors_out: dict[int, str] | None = None,
  1558. slot_materials_out: dict[int, str] | None = None,
  1559. cost_out: _PrintCost | None = None,
  1560. ) -> int:
  1561. """AMS remain%-delta path: write ``(start - current) * filament.weight``
  1562. grams to Spoolman for slots the 3MF path didn't cover.
  1563. Mirrors ``usage_tracker.on_print_complete`` Path 2: per-slot, gated on a
  1564. valid current ``remain%``, skipped on spool swap (``tray_uuid`` changed),
  1565. using the resolved spool's filament reference weight rather than MQTT's
  1566. unreliable ``tray_weight`` (which is the failure mode #1119 documented).
  1567. """
  1568. spools_updated = 0
  1569. not_in_print: list[str] = []
  1570. for slot_key, start in tray_remain_start.items():
  1571. try:
  1572. ams_id_str, tray_id_str = slot_key.split("-", 1)
  1573. ams_id, tray_id = int(ams_id_str), int(tray_id_str)
  1574. except (ValueError, AttributeError):
  1575. continue
  1576. # Skip slots already handled by the 3MF path. Encoding mirrors
  1577. # build_ams_tray_lookup: VT trays land at 254/255, AMS-HT keeps
  1578. # its native id (>=128), regular AMS slots are ams_id*4+tray_id.
  1579. if ams_id == 255:
  1580. global_tray_id = 254 + tray_id
  1581. elif ams_id >= 128:
  1582. global_tray_id = ams_id
  1583. else:
  1584. global_tray_id = ams_id * 4 + tray_id
  1585. if global_tray_id in handled_global_tray_ids:
  1586. continue
  1587. # Slots the print never touched (#1269's guard, see _print_used_tray_keys).
  1588. # Only enforced when there is evidence of which slots it did use.
  1589. # Collected rather than logged per slot: on a four-AMS farm a
  1590. # single-colour print leaves fifteen of these, and they are the
  1591. # expected case, unlike the "consumed but charged nothing" lines below.
  1592. if print_used_keys and (ams_id, tray_id) not in print_used_keys:
  1593. not_in_print.append(f"AMS{ams_id}-T{tray_id}")
  1594. continue
  1595. current = current_lookup.get(slot_key)
  1596. if not current:
  1597. # Reported at info, like the internal tracker's equivalent: on a
  1598. # near-empty spool the AMS reports a negative remain%, which the
  1599. # snapshot gate rejects, and the slot that was actually printing
  1600. # disappears from this path entirely (#1820).
  1601. logger.info(
  1602. "[SPOOLMAN] AMS%d-T%d: no valid remain%% at completion, nothing charged for this slot", ams_id, tray_id
  1603. )
  1604. continue
  1605. # Spool swap mid-print — tray_uuid changed. We don't know how much
  1606. # of the print went to which spool; skip rather than mis-attribute.
  1607. start_uuid = (start.get("tray_uuid") or "").lower()
  1608. cur_uuid = (current.get("tray_uuid") or "").lower()
  1609. if start_uuid and cur_uuid and start_uuid != cur_uuid:
  1610. logger.info(
  1611. "[SPOOLMAN] AMS%d-T%d: spool swapped mid-print (uuid changed), skipping remain-delta", ams_id, tray_id
  1612. )
  1613. continue
  1614. delta_pct = start["remain"] - current["remain"]
  1615. if delta_pct <= 0:
  1616. # A fresh spool reads 100% for the first tens of grams and the AMS
  1617. # estimate drifts upward on its own, so this covers a real print
  1618. # that simply left no trace at AMS granularity -- not only a refill.
  1619. # Said out loud so it can be told apart from having nothing to
  1620. # charge, which is what "no spools updated" alone looked like.
  1621. logger.info(
  1622. "[SPOOLMAN] AMS%d-T%d: remain%% did not fall over the print (%d%% -> %d%%), nothing charged",
  1623. ams_id,
  1624. tray_id,
  1625. start["remain"],
  1626. current["remain"],
  1627. )
  1628. continue # No consumption captured at AMS granularity, or refilled
  1629. spool_id = await _resolve_spool_id_via_slot_assignment(printer_id, ams_id, tray_id)
  1630. if spool_id is None:
  1631. logger.info(
  1632. "[SPOOLMAN] AMS%d-T%d: consumed %d%% but has no Spoolman slot assignment, nothing charged",
  1633. ams_id,
  1634. tray_id,
  1635. delta_pct,
  1636. )
  1637. continue
  1638. # Look up the spool's net weight (#3194). Use a fresh GET so
  1639. # we don't depend on a stale cached_spools list. Failure here is
  1640. # silent-skip rather than fatal — other slots can still be written.
  1641. try:
  1642. spool = await client.get_spool(spool_id)
  1643. except Exception as exc: # noqa: BLE001
  1644. logger.debug("[SPOOLMAN] AMS%d-T%d: get_spool(%s) failed: %s", ams_id, tray_id, spool_id, exc)
  1645. continue
  1646. filament = spool.get("filament") or {}
  1647. ref_weight = _as_positive_number(spoolman_net_weight(spool))
  1648. if ref_weight is None:
  1649. logger.debug(
  1650. "[SPOOLMAN] AMS%d-T%d: spool %s has no initial_weight or filament.weight, skipping remain-delta",
  1651. ams_id,
  1652. tray_id,
  1653. spool_id,
  1654. )
  1655. continue
  1656. grams_used = round((delta_pct / 100.0) * ref_weight, 2)
  1657. if grams_used <= 0:
  1658. continue
  1659. try:
  1660. await client.use_spool(spool_id, grams_used)
  1661. except Exception as exc: # noqa: BLE001
  1662. logger.warning(
  1663. "[SPOOLMAN] AMS%d-T%d: use_spool(%s, %.2fg) failed: %s", ams_id, tray_id, spool_id, grams_used, exc
  1664. )
  1665. continue
  1666. spools_updated += 1
  1667. # ``spool`` here is the full row fetched above for its net weight,
  1668. # so the price is already in hand (#2591).
  1669. if cost_out is not None:
  1670. cost_out.add(grams_used, spool, f"AMS{ams_id}-T{tray_id}")
  1671. # No 3MF slot_id for this path — use the AMS slot key so the maps can
  1672. # still be inspected by callers if needed. The archive rewrites
  1673. # (#1494 colour, #2563 type) key on 3MF slot_ids, so remain-delta-only
  1674. # prints intentionally don't participate (matches usage_tracker's
  1675. # slot_id=None).
  1676. if slot_colors_out is not None:
  1677. color = filament.get("color_hex")
  1678. if color:
  1679. slot_colors_out[-(global_tray_id + 1)] = color
  1680. if slot_materials_out is not None:
  1681. material = filament.get("material")
  1682. if material:
  1683. slot_materials_out[-(global_tray_id + 1)] = material
  1684. logger.info(
  1685. "[SPOOLMAN] Archive %s AMS%d-T%d: %.2fg via remain-delta (%d%% of %.0fg) -> spool %s",
  1686. archive_id,
  1687. ams_id,
  1688. tray_id,
  1689. grams_used,
  1690. delta_pct,
  1691. ref_weight,
  1692. spool_id,
  1693. )
  1694. if not_in_print:
  1695. logger.info(
  1696. "[SPOOLMAN] Archive %s: slots not part of this print, left alone: %s",
  1697. archive_id,
  1698. ", ".join(not_in_print),
  1699. )
  1700. return spools_updated
  1701. async def _apply_spool_cost_to_archive(db, archive_id: int, print_cost: _PrintCost) -> None:
  1702. """Set an archive's cost from what the Spoolman spools that fed it are worth (#2591).
  1703. Until now this was the one thing the Spoolman integration was asked for by
  1704. name and did not do. ``archive.py`` prices a print once, at archive time,
  1705. from the built-in Filament catalogue matched on the primary type, falling
  1706. back to the global default rate -- and in Spoolman mode nothing ever
  1707. revisited that figure, because the per-spool recompute in
  1708. ``usage_tracker.on_print_complete`` only runs over rows the built-in
  1709. inventory wrote and Spoolman mode writes none. An install with an empty
  1710. catalogue therefore priced every print at the default no matter what the
  1711. linked spool actually cost.
  1712. Multi-material was wrong twice over there: the primary type's rate applied
  1713. to the *whole* print's grams, so a slot of expensive PA came out at the
  1714. price of the PLA next to it. Summing per charged slot is what fixes that,
  1715. and it falls out of pricing each charge as it is made rather than pricing a
  1716. total afterwards.
  1717. Grams that could not be priced are covered at the global default rate in a
  1718. single subtraction against the archive's own total -- a slot whose spool has
  1719. no price, a tray with no Spoolman row, and filament the 3MF never attributed
  1720. are all the same case. Without it a print with one priced slot out of four
  1721. would report a quarter of its cost, which is #1344 in a different inventory
  1722. mode.
  1723. Only on the first run, matching the built-in writer (#1378): reprint actuals
  1724. live in ``PrintLogEntry``, and the archive card keeps the first run's figure
  1725. so a failed 10 g reprint doesn't visually clobber a successful 100 g print.
  1726. Does nothing when no slot could be priced, leaving whatever ``archive.py``
  1727. recorded. That keeps an install with prices in neither place exactly where
  1728. it was.
  1729. """
  1730. if print_cost.priced == 0:
  1731. if print_cost.unpriced:
  1732. logger.info(
  1733. "[SPOOLMAN] Archive %s: %d charged spool(s) carry no price -- "
  1734. "leaving the cost as recorded at archive time",
  1735. archive_id,
  1736. print_cost.unpriced,
  1737. )
  1738. return
  1739. from backend.app.api.routes.settings import get_setting
  1740. from backend.app.models.archive import PrintArchive
  1741. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  1742. if archive is None:
  1743. return
  1744. total = print_cost.cost
  1745. archive_grams = archive.filament_used_grams or 0
  1746. unpriced_grams = max(0.0, archive_grams - print_cost.priced_grams)
  1747. if unpriced_grams > 0:
  1748. # Malformed settings must not cost the whole usage report; the rate is
  1749. # the least important thing this pass produces.
  1750. try:
  1751. _setting = await get_setting(db, "default_filament_cost")
  1752. default_cost_per_kg = float(_setting) if _setting else 25.0
  1753. except (TypeError, ValueError):
  1754. default_cost_per_kg = 25.0
  1755. if default_cost_per_kg > 0:
  1756. total += (unpriced_grams / 1000.0) * default_cost_per_kg
  1757. if total <= 0:
  1758. return
  1759. from backend.app.services.print_log import other_runs_of
  1760. if await other_runs_of(db, archive):
  1761. return
  1762. new_cost = round(total, 2)
  1763. if new_cost != archive.cost:
  1764. logger.info(
  1765. "[SPOOLMAN] Archive %s cost %s -> %s (%d slot(s) priced from Spoolman over %.2fg, "
  1766. "%.2fg at the default rate)",
  1767. archive_id,
  1768. archive.cost,
  1769. new_cost,
  1770. print_cost.priced,
  1771. print_cost.priced_grams,
  1772. unpriced_grams,
  1773. )
  1774. archive.cost = new_cost
  1775. await db.commit()
  1776. async def _apply_spool_colors_to_archive(
  1777. db,
  1778. archive_id: int,
  1779. filament_usage: list[dict],
  1780. slot_colors: dict[int, str],
  1781. ) -> None:
  1782. """Overwrite an archive's ``filament_color`` with the colours of the
  1783. Spoolman spools that fed the print (#1494).
  1784. All-or-nothing, exactly like the built-in inventory path: the colour is
  1785. only rewritten when every used slot resolved to a spool that carries a
  1786. colour, so a partial match never drops slots from the archive.
  1787. """
  1788. if not slot_colors:
  1789. return
  1790. from backend.app.models.archive import PrintArchive
  1791. from backend.app.services.usage_tracker import (
  1792. _archive_colors_from_spools,
  1793. _spool_color_to_hex,
  1794. )
  1795. results = [{"slot_id": sid, "color": _spool_color_to_hex(hex_)} for sid, hex_ in slot_colors.items()]
  1796. colors = _archive_colors_from_spools(filament_usage, results)
  1797. if not colors:
  1798. return
  1799. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  1800. if archive is None:
  1801. return
  1802. joined = ",".join(colors)
  1803. if joined != archive.filament_color:
  1804. logger.info(
  1805. "[SPOOLMAN] Archive %s filament_color %r -> %r (from Spoolman spools)",
  1806. archive_id,
  1807. archive.filament_color,
  1808. joined,
  1809. )
  1810. archive.filament_color = joined
  1811. await db.commit()
  1812. async def _apply_spool_types_to_archive(
  1813. db,
  1814. archive_id: int,
  1815. filament_usage: list[dict],
  1816. slot_materials: dict[int, str],
  1817. ) -> None:
  1818. """Overwrite an archive's ``filament_type`` with the materials of the
  1819. Spoolman spools that fed the print (#2563).
  1820. All-or-nothing, exactly like the colour path and the built-in inventory
  1821. path: the type is only rewritten when every used slot resolved to a spool
  1822. that carries a material, so a partial match never drops slots from the
  1823. archive or the material statistics.
  1824. """
  1825. if not slot_materials:
  1826. return
  1827. from backend.app.models.archive import PrintArchive
  1828. from backend.app.services.usage_tracker import _archive_types_from_spools
  1829. results = [{"slot_id": sid, "material": material} for sid, material in slot_materials.items()]
  1830. types = _archive_types_from_spools(filament_usage, results)
  1831. if not types:
  1832. return
  1833. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  1834. if archive is None:
  1835. return
  1836. joined = ",".join(types)
  1837. if joined != archive.filament_type:
  1838. logger.info(
  1839. "[SPOOLMAN] Archive %s filament_type %r -> %r (from Spoolman spools)",
  1840. archive_id,
  1841. archive.filament_type,
  1842. joined,
  1843. )
  1844. archive.filament_type = joined
  1845. await db.commit()