usage_tracker.py 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210
  1. """Automatic filament consumption tracking.
  2. Captures AMS tray remain% at print start, then computes consumption
  3. deltas at print complete to update spool weight_used and last_used.
  4. Primary tracking uses 3MF slicer estimates (precise per-filament data).
  5. AMS remain% delta is the fallback for trays not covered by 3MF data.
  6. """
  7. import asyncio
  8. import json
  9. import logging
  10. import re
  11. from dataclasses import dataclass, field
  12. from datetime import datetime, timezone
  13. from sqlalchemy import func, select, update
  14. from sqlalchemy.ext.asyncio import AsyncSession
  15. from backend.app.models.spool import Spool
  16. from backend.app.models.spool_assignment import SpoolAssignment
  17. from backend.app.models.spool_usage_history import SpoolUsageHistory
  18. from backend.app.services import spool_swaps
  19. from backend.app.utils.tray_ids import EXTERNAL_AMS_ID, TrayLayout, decode_wire_slot, external_slot_index
  20. logger = logging.getLogger(__name__)
  21. def has_second_external_holder(raw_data: dict | None) -> bool:
  22. """Whether the printer has a second external holder (vt_tray 255).
  23. ``tray_now`` 255 means "nothing loaded" on a printer with one external
  24. holder, and the right-hand external spool on one with two (H2D, X2D),
  25. which lists it in ``vt_tray``. Both inventory modes read it this way
  26. (#3405). Not on a nozzle-rack printer (H3C): it lists an external input
  27. per hotend, 247-255, and its ``tray_now`` 255 is "nothing loaded".
  28. """
  29. vt_trays = (raw_data or {}).get("vt_tray") or []
  30. if isinstance(vt_trays, list) and TrayLayout.from_units(None, vt_trays).rack:
  31. return False
  32. for vt in vt_trays:
  33. if not isinstance(vt, dict):
  34. continue
  35. try:
  36. if int(vt.get("id", 0)) == 255:
  37. return True
  38. except (TypeError, ValueError):
  39. continue
  40. return False
  41. def mapping_names_no_used_tray(slot_to_tray: list | None, filament_usage: list[dict] | None) -> bool:
  42. """Whether a slot-to-tray mapping names no tray for any slot the print used.
  43. Such a mapping carries no evidence at all: typically a flat ams_mapping
  44. whose external spool is -1 and came without an ams_mapping2 to resolve it
  45. (#3166). Both inventory modes drop it, so the printer's own readings
  46. (``tray_now``, the tray-change log) decide which tray fed the print
  47. instead of every slot reading as unfed (#3405).
  48. """
  49. if not slot_to_tray:
  50. return False
  51. used_slots = [u.get("slot_id", 0) for u in filament_usage or [] if u.get("used_g", 0) > 0]
  52. return bool(used_slots) and all(
  53. not (0 < s <= len(slot_to_tray) and isinstance(slot_to_tray[s - 1], int) and slot_to_tray[s - 1] >= 0)
  54. for s in used_slots
  55. )
  56. def _decode_mqtt_mapping(mapping_raw: list | None, layout: TrayLayout | None = None) -> list[int] | None:
  57. """Decode MQTT mapping field (snow-encoded) to bambuddy global tray IDs.
  58. The printer's MQTT mapping field is an array indexed by slicer filament slot
  59. (0-based). Each value uses snow encoding: ams_hw_id * 256 + local_slot.
  60. 65535 means unmapped.
  61. Returns a list of bambuddy global tray IDs (or -1 for unmapped), or None if
  62. no valid mappings found.
  63. """
  64. if not isinstance(mapping_raw, list) or not mapping_raw:
  65. return None
  66. result = []
  67. for value in mapping_raw:
  68. tray = decode_wire_slot(value, layout) if isinstance(value, int) else None
  69. result.append(-1 if tray is None else tray)
  70. # Only return if at least one valid mapping exists
  71. if all(v < 0 for v in result):
  72. return None
  73. return result
  74. def _spool_color_to_hex(rgba: str | None) -> str | None:
  75. """Normalise a ``Spool.rgba`` value (``RRGGBBAA`` hex, no ``#``) to the
  76. ``#RRGGBB`` form archives store in ``filament_color``.
  77. Alpha is dropped — the archive colour list and the Color Distribution
  78. graph treat filament colour as opaque. Returns ``None`` for a missing or
  79. too-short value so the caller can fall back to the 3MF colour.
  80. """
  81. if not rgba:
  82. return None
  83. h = rgba.strip().lstrip("#")
  84. if len(h) < 6:
  85. return None
  86. return "#" + h[:6].upper()
  87. def _archive_colors_from_spools(filament_usage: list[dict], results: list[dict]) -> list[str] | None:
  88. """Slot-ordered, de-duplicated hex colours for an archive's ``filament_color``,
  89. taken from the inventory spools that actually fed the print (#1494).
  90. The slicer's 3MF carries its own ``filament_colour`` per slot — a value
  91. picked independently of the colour the user curates on the matched
  92. inventory spool. So an archive printed from a ``#000000`` inventory spool
  93. would otherwise show the slicer's near-black ``#161616``. Once usage
  94. tracking has resolved the used slots to spools, the spool colours are the
  95. authoritative source and replace the 3MF values.
  96. Returns ``None`` — leave the 3MF colour untouched — unless *every* slot
  97. with non-zero usage was matched to a spool that carries a colour. A
  98. partial rewrite would silently drop the unmatched slots' colours from the
  99. archive (and the Color Distribution graph), so it is all-or-nothing.
  100. """
  101. used_slots = {u["slot_id"] for u in filament_usage if u.get("used_g", 0) > 0 and u.get("slot_id") is not None}
  102. if not used_slots:
  103. return None
  104. slot_color: dict[int, str] = {}
  105. for r in results:
  106. slot_id = r.get("slot_id")
  107. color = r.get("color")
  108. if slot_id is not None and color:
  109. slot_color.setdefault(slot_id, color)
  110. if not used_slots.issubset(slot_color):
  111. return None
  112. ordered: list[str] = []
  113. for slot_id in sorted(used_slots):
  114. color = slot_color[slot_id]
  115. if color not in ordered:
  116. ordered.append(color)
  117. return ordered
  118. def _archive_types_from_spools(filament_usage: list[dict], results: list[dict]) -> list[str] | None:
  119. """Slot-ordered, de-duplicated materials for an archive's ``filament_type``,
  120. taken from the inventory spools that actually fed the print (#2563).
  121. The slicer's 3MF records the filament type it was *sliced for*. When the
  122. user manually maps a slot to a differently-typed loaded spool in the Print
  123. dialog — a PLA slice routed to the only loaded PETG slot — that sliced type
  124. misclassifies the run in the archive card, the Print Log and the material
  125. statistics, even though the deduction correctly hit the PETG spool. Once
  126. usage tracking has resolved every used slot to an inventory spool, the
  127. spool's declared material is the authoritative record of what was consumed,
  128. the same reasoning that already adopts the spool colour (#1494).
  129. Returns ``None`` — leave the 3MF type untouched — unless *every* slot with
  130. non-zero usage was matched to a spool that carries a material. All-or-
  131. nothing, exactly like ``_archive_colors_from_spools``: a partial rewrite
  132. would silently drop the unmatched slots' types from the archive (and the
  133. material stats).
  134. """
  135. used_slots = {u["slot_id"] for u in filament_usage if u.get("used_g", 0) > 0 and u.get("slot_id") is not None}
  136. if not used_slots:
  137. return None
  138. slot_material: dict[int, str] = {}
  139. for r in results:
  140. slot_id = r.get("slot_id")
  141. material = (r.get("material") or "").strip()
  142. if slot_id is not None and material:
  143. slot_material.setdefault(slot_id, material)
  144. if not used_slots.issubset(slot_material):
  145. return None
  146. ordered: list[str] = []
  147. for slot_id in sorted(used_slots):
  148. material = slot_material[slot_id]
  149. if material not in ordered:
  150. ordered.append(material)
  151. return ordered
  152. def _match_slots_by_color(
  153. filament_usage: list[dict],
  154. ams_raw: dict | list | None,
  155. ) -> list[int] | None:
  156. """Match 3MF filament slots to AMS trays by color.
  157. Fallback mapping for printers that don't provide the MQTT mapping field
  158. or request topic subscription (e.g. A1, A1 Mini, P1S, P2S).
  159. Compares the 3MF slicer filament color (per slot) against each AMS tray's
  160. color to find a unique match. Only returns a mapping if every used slot
  161. matches exactly one tray (no ambiguity).
  162. Args:
  163. filament_usage: List of 3MF slot dicts with 'slot_id', 'color', 'type'
  164. ams_raw: raw_data["ams"] dict or list from printer state
  165. Returns:
  166. List of global tray IDs indexed by slicer slot (0-based), or None.
  167. """
  168. if not filament_usage or not ams_raw:
  169. return None
  170. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  171. if not ams_data:
  172. return None
  173. # Build map of normalized color → list of global tray IDs
  174. color_to_trays: dict[str, list[int]] = {}
  175. layout = TrayLayout.from_units(ams_data if isinstance(ams_data, list) else None)
  176. for ams_unit in ams_data:
  177. ams_id = int(ams_unit.get("id", 0))
  178. for tray in ams_unit.get("tray", []):
  179. tray_id = int(tray.get("id", 0))
  180. tray_color = tray.get("tray_color", "")
  181. tray_type = tray.get("tray_type", "")
  182. if not tray_color or not tray_type:
  183. continue
  184. # Normalize AMS color: strip alpha (last 2 chars), lowercase
  185. norm = tray_color[:6].lower() if len(tray_color) >= 6 else tray_color.lower()
  186. color_to_trays.setdefault(norm, []).append(layout.global_tray_id(ams_id, tray_id))
  187. if not color_to_trays:
  188. return None
  189. # Find max slot_id to size the result array
  190. max_slot = max(u.get("slot_id", 0) for u in filament_usage)
  191. if max_slot <= 0:
  192. return None
  193. result = [-1] * max_slot
  194. used_trays: set[int] = set()
  195. for usage in filament_usage:
  196. slot_id = usage.get("slot_id", 0)
  197. if slot_id <= 0:
  198. continue
  199. slot_color = usage.get("color", "").lstrip("#").lower()
  200. if len(slot_color) < 6:
  201. return None # Can't match without a valid color
  202. slot_color = slot_color[:6] # Strip alpha if present
  203. candidates = color_to_trays.get(slot_color, [])
  204. # Filter out trays already claimed by another slot
  205. available = [t for t in candidates if t not in used_trays]
  206. if len(available) != 1:
  207. # Ambiguous (multiple trays with same color) or no match
  208. return None
  209. result[slot_id - 1] = available[0]
  210. used_trays.add(available[0])
  211. # Only return if at least one valid mapping exists
  212. if all(v < 0 for v in result):
  213. return None
  214. logger.info("[UsageTracker] Color-matched slot_to_tray: %s", result)
  215. return result
  216. @dataclass
  217. class PrintSession:
  218. printer_id: int
  219. print_name: str
  220. started_at: datetime
  221. tray_remain_start: dict[tuple[int, int], int] = field(default_factory=dict)
  222. # tray_now at print start (correct value, unlike at completion where it's 255)
  223. tray_now_at_start: int = -1
  224. # Snapshot of spool assignments at print start: {(ams_id, tray_id): spool_id}
  225. # Prevents usage loss when on_ams_change unlinks a spool mid-print
  226. spool_assignments: dict[tuple[int, int], int] = field(default_factory=dict)
  227. # AMS mapping from print command (captured at start, needed when auto-archive is off)
  228. ams_mapping: list[int] | None = None
  229. # Queue item's plate_id when this print is a multi-plate 3MF dispatched for a
  230. # single plate (#1697). None for non-queue prints — the file's first/only plate
  231. # is the default and the 3MF parser already returns the full file in that case.
  232. plate_id: int | None = None
  233. # Module-level storage, keyed by printer_id. Mirrored to the
  234. # ``active_print_sessions`` table so a restart mid-print doesn't lose the
  235. # context — see ``persist_session`` / ``restore_session``.
  236. _active_sessions: dict[int, PrintSession] = {}
  237. # Printers whose finished print is being closed out. on_print_complete takes the
  238. # session first and charges the usage several awaits later; the printer already
  239. # reports FINISH, so without this mark the AMS remain% weight sync would run in
  240. # between and the print would be charged twice (WU-3).
  241. _completing: set[int] = set()
  242. def mark_completing(printer_id: int) -> None:
  243. """The completion path's first step: hold the weight sync off until the
  244. usage is booked (discard_session) or the completion ends."""
  245. _completing.add(printer_id)
  246. def done_completing(printer_id: int) -> None:
  247. _completing.discard(printer_id)
  248. def is_completing(printer_id: int) -> bool:
  249. """The printer's finished print is being closed out (on_print_complete runs)."""
  250. return printer_id in _completing
  251. def printer_is_charging(printer_id: int) -> bool:
  252. """A print's usage is still to be charged: it runs, or it ended and its
  253. completion has not booked it yet. The AMS remain% sync leaves the
  254. printer's spools alone meanwhile (#880)."""
  255. return printer_id in _active_sessions or printer_id in _completing
  256. # Serialises the read-modify-write on the persisted tray-change log, per printer.
  257. _tray_change_locks: dict[int, asyncio.Lock] = {}
  258. def _tray_key_to_str(key: tuple[int, int]) -> str:
  259. return f"{key[0]}-{key[1]}"
  260. def _tray_key_from_str(key: str) -> tuple[int, int] | None:
  261. ams_str, _, tray_str = key.partition("-")
  262. try:
  263. return int(ams_str), int(tray_str)
  264. except ValueError:
  265. return None
  266. def _tray_map_to_json(mapping: dict[tuple[int, int], int]) -> dict[str, int]:
  267. return {_tray_key_to_str(k): v for k, v in mapping.items()}
  268. def _tray_map_from_json(mapping: dict | None) -> dict[tuple[int, int], int]:
  269. result: dict[tuple[int, int], int] = {}
  270. for raw_key, value in (mapping or {}).items():
  271. key = _tray_key_from_str(str(raw_key))
  272. if key is not None and isinstance(value, int):
  273. result[key] = value
  274. return result
  275. async def _charge_spool(db: AsyncSession, spool: Spool, grams: float) -> bool:
  276. """Add *grams* to the spool's usage in the database itself (WU-4).
  277. The spool was loaded several awaits earlier; a weight set by hand or
  278. weighed on the scale since then would be lost to a write of the value
  279. computed from that copy. The loaded copy is set to the stored result: from
  280. this statement until the commit, the transaction holds the row (the write
  281. lock on SQLite), so writing it back on flush changes nothing.
  282. False when the spool was deleted meanwhile: the caller skips it, since a
  283. usage row for it would break its foreign key on PostgreSQL and roll back
  284. the whole completion.
  285. """
  286. now = datetime.now(timezone.utc)
  287. stored = await db.scalar(
  288. update(Spool)
  289. .where(Spool.id == spool.id)
  290. .values(weight_used=func.coalesce(Spool.weight_used, 0) + grams, last_used=now)
  291. .returning(Spool.weight_used)
  292. .execution_options(synchronize_session=False)
  293. )
  294. if stored is None:
  295. return False
  296. spool.weight_used = stored
  297. spool.last_used = now
  298. return True
  299. async def persist_session(
  300. db: AsyncSession,
  301. session: PrintSession,
  302. tray_change_log: list | None = None,
  303. spool_change_log: list | None = None,
  304. ) -> None:
  305. """Mirror ``session`` into ``active_print_sessions`` for restart recovery.
  306. Overwrites any existing row for the printer: a printer runs one print at a
  307. time, and a row left behind by a completion we never saw must not outlive
  308. the next print start.
  309. """
  310. from backend.app.models.active_print_session import ActivePrintSession
  311. row = await db.get(ActivePrintSession, session.printer_id)
  312. if row is None:
  313. row = ActivePrintSession(printer_id=session.printer_id)
  314. db.add(row)
  315. row.print_name = session.print_name or ""
  316. row.started_at = session.started_at.replace(tzinfo=None)
  317. row.tray_now_at_start = session.tray_now_at_start
  318. row.plate_id = session.plate_id
  319. row.ams_mapping = list(session.ams_mapping) if session.ams_mapping else None
  320. row.spool_assignments = _tray_map_to_json(session.spool_assignments) or None
  321. row.tray_remain_start = _tray_map_to_json(session.tray_remain_start) or None
  322. row.tray_change_log = [list(entry) for entry in (tray_change_log or [])] or None
  323. row.spool_change_log = list(spool_change_log or []) or None
  324. await db.commit()
  325. async def record_tray_change(db: AsyncSession, printer_id: int, tray_global: int, layer_num: int) -> None:
  326. """Append one tray change to the persisted log.
  327. No-op when no print-start row exists — a tray change outside a tracked
  328. print has nothing to attribute.
  329. """
  330. from backend.app.models.active_print_session import ActivePrintSession
  331. # Read-modify-write on a JSON column: two changes close together (a runout
  332. # parks the extruder and the backup tray loads moments later) would
  333. # otherwise race and drop a segment boundary.
  334. async with _tray_change_locks.setdefault(printer_id, asyncio.Lock()):
  335. row = await db.get(ActivePrintSession, printer_id)
  336. if row is None:
  337. return
  338. log = [list(entry) for entry in (row.tray_change_log or [])]
  339. entry = [tray_global, layer_num]
  340. if log and log[-1] == entry:
  341. # print-start seeds the log from PrinterState, which may already
  342. # hold a change this callback is also reporting.
  343. return
  344. log.append(entry)
  345. row.tray_change_log = log
  346. await db.commit()
  347. async def get_persisted_print_name(db: AsyncSession, printer_id: int) -> str | None:
  348. """Print name on the persisted row, for identity-checking a restored session."""
  349. from backend.app.models.active_print_session import ActivePrintSession
  350. row = await db.get(ActivePrintSession, printer_id)
  351. return row.print_name if row is not None else None
  352. async def get_persisted_spool_change_log(db: AsyncSession, printer_id: int) -> list[dict]:
  353. """The mid-print spool assignments on the persisted row (services.spool_swaps)."""
  354. from backend.app.models.active_print_session import ActivePrintSession
  355. row = await db.get(ActivePrintSession, printer_id)
  356. return [item for item in (row.spool_change_log or []) if isinstance(item, dict)] if row is not None else []
  357. async def get_persisted_ams_mapping(db: AsyncSession, printer_id: int) -> list[int] | None:
  358. """AMS mapping on the persisted row: the one captured from the print command."""
  359. from backend.app.models.active_print_session import ActivePrintSession
  360. row = await db.get(ActivePrintSession, printer_id)
  361. return list(row.ams_mapping) if row is not None and row.ams_mapping else None
  362. async def restore_session(db: AsyncSession, printer_id: int, register_active: bool = True) -> list[list[int]] | None:
  363. """Rebuild the in-memory session for ``printer_id`` from the persisted row.
  364. Returns the persisted tray-change log so the caller can put it back on
  365. ``PrinterState``, or None when there is nothing to restore.
  366. ``register_active=False`` returns the log without publishing the session to
  367. ``_active_sessions`` — for Spoolman users, who need the tray-change log
  368. restored but whose remain%-sync must not be suppressed by it (see
  369. ``on_print_start``).
  370. """
  371. from backend.app.models.active_print_session import ActivePrintSession
  372. row = await db.get(ActivePrintSession, printer_id)
  373. if row is None:
  374. return None
  375. started_at = row.started_at
  376. if started_at.tzinfo is None:
  377. started_at = started_at.replace(tzinfo=timezone.utc)
  378. session = PrintSession(
  379. printer_id=printer_id,
  380. print_name=row.print_name or "",
  381. started_at=started_at,
  382. tray_remain_start=_tray_map_from_json(row.tray_remain_start),
  383. tray_now_at_start=row.tray_now_at_start,
  384. spool_assignments=_tray_map_from_json(row.spool_assignments),
  385. ams_mapping=list(row.ams_mapping) if row.ams_mapping else None,
  386. plate_id=row.plate_id,
  387. )
  388. if register_active:
  389. _active_sessions[printer_id] = session
  390. log = [list(entry) for entry in (row.tray_change_log or [])]
  391. logger.info(
  392. "[UsageTracker] Restored print session for printer %d: plate_id=%s, ams_mapping=%s, "
  393. "%d assignments, tray_change_log=%s",
  394. printer_id,
  395. row.plate_id,
  396. row.ams_mapping,
  397. len(row.spool_assignments or {}),
  398. log,
  399. )
  400. return log
  401. async def clear_persisted_session(db: AsyncSession, printer_id: int) -> None:
  402. """Drop the persisted print-start row once the print is closed out."""
  403. from backend.app.models.active_print_session import ActivePrintSession
  404. row = await db.get(ActivePrintSession, printer_id)
  405. if row is not None:
  406. await db.delete(row)
  407. await db.commit()
  408. def forget_printer(printer_id: int) -> None:
  409. """A deleted printer's print-start context in memory (the row goes with the printer)."""
  410. _active_sessions.pop(printer_id, None)
  411. _completing.discard(printer_id)
  412. _tray_change_locks.pop(printer_id, None)
  413. async def discard_session(db: AsyncSession, printer_id: int) -> None:
  414. """Forget a printer's print-start context, in memory and on disk.
  415. The completion path calls this for every print, including the ones whose
  416. usage Spoolman owns: the context is captured for both backends, but only
  417. the internal tracker's ``on_print_complete`` consumes (and pops) it.
  418. """
  419. _active_sessions.pop(printer_id, None)
  420. _completing.discard(printer_id)
  421. _tray_change_locks.pop(printer_id, None)
  422. await clear_persisted_session(db, printer_id)
  423. def _to_epoch_seconds(value: datetime | None) -> float | None:
  424. """Convert datetime to epoch seconds, assuming UTC for naive values."""
  425. if value is None:
  426. return None
  427. dt = value
  428. if dt.tzinfo is None:
  429. dt = dt.replace(tzinfo=timezone.utc)
  430. return dt.timestamp()
  431. async def _resolve_spool_id_for_tray(
  432. printer_id: int,
  433. ams_id: int,
  434. tray_id: int,
  435. db: AsyncSession,
  436. spool_assignments_snapshot: dict[tuple[int, int], int] | None = None,
  437. print_started_at: datetime | None = None,
  438. ) -> int | None:
  439. """Resolve spool ID for a tray with safe support for mid-print reassignment.
  440. Resolution order:
  441. 1. If snapshot exists and live assignment changed *during this print*, use live spool.
  442. 2. Otherwise use snapshot spool when available.
  443. 3. Fall back to live assignment.
  444. """
  445. key = (ams_id, tray_id)
  446. snapshot_spool_id = spool_assignments_snapshot.get(key) if spool_assignments_snapshot else None
  447. # Backward-compatible fast path: if we have a snapshot but no print-start
  448. # timestamp, preserve legacy behavior and avoid extra DB lookups.
  449. if snapshot_spool_id is not None and print_started_at is None:
  450. return snapshot_spool_id
  451. result = await db.execute(
  452. select(SpoolAssignment).where(
  453. SpoolAssignment.printer_id == printer_id,
  454. SpoolAssignment.ams_id == ams_id,
  455. SpoolAssignment.tray_id == tray_id,
  456. )
  457. )
  458. live_assignment = result.scalar_one_or_none()
  459. if snapshot_spool_id is not None:
  460. if live_assignment and live_assignment.spool_id != snapshot_spool_id:
  461. live_created_ts = _to_epoch_seconds(getattr(live_assignment, "created_at", None))
  462. started_ts = _to_epoch_seconds(print_started_at)
  463. if live_created_ts is not None and started_ts is not None and live_created_ts >= started_ts:
  464. logger.info(
  465. "[UsageTracker] Assignment changed during print for printer %d AMS%d-T%d: snapshot spool %d -> live spool %d",
  466. printer_id,
  467. ams_id,
  468. tray_id,
  469. snapshot_spool_id,
  470. live_assignment.spool_id,
  471. )
  472. return live_assignment.spool_id
  473. return snapshot_spool_id
  474. if live_assignment:
  475. return live_assignment.spool_id
  476. return None
  477. async def on_print_start(
  478. printer_id: int,
  479. data: dict,
  480. printer_manager,
  481. db: AsyncSession | None = None,
  482. spoolman_owns_usage: bool = False,
  483. ) -> None:
  484. """Capture AMS tray remain% and spool assignments at print start.
  485. The capture runs for both inventory backends — the persisted row carries
  486. the tray-change log, which is the only record of which spool fed which
  487. layers when AMS Filament Backup swaps trays, and Spoolman's own durable
  488. row (#1820) does not hold it.
  489. ``spoolman_owns_usage`` keeps the in-memory session out of
  490. ``_active_sessions`` when Spoolman is writing the usage. That dict doubles
  491. as ``on_ams_change``'s "a print is running, so skip the remain%-based
  492. weight sync because the internal tracker will deduct precisely" flag
  493. (#880); registering a session the internal tracker will never complete
  494. would suppress a sync those users still need.
  495. """
  496. # A new print: whatever the last completion left marked is over.
  497. _completing.discard(printer_id)
  498. state = printer_manager.get_status(printer_id)
  499. if not state or not state.raw_data:
  500. logger.debug("[UsageTracker] No state for printer %d, skipping", printer_id)
  501. return
  502. ams_raw = state.raw_data.get("ams", [])
  503. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  504. tray_remain_start: dict[tuple[int, int], int] = {}
  505. skipped_invalid: list[str] = []
  506. for ams_unit in ams_data:
  507. ams_id = int(ams_unit.get("id", 0))
  508. for tray in ams_unit.get("tray", []):
  509. tray_id = int(tray.get("id", 0))
  510. remain = tray.get("remain", -1)
  511. if isinstance(remain, int) and 0 <= remain <= 100:
  512. tray_remain_start[(ams_id, tray_id)] = remain
  513. else:
  514. skipped_invalid.append(f"AMS{ams_id}-T{tray_id}(remain={remain})")
  515. # Also capture VT (external) tray remain% — these are separate from AMS units
  516. vt_tray_raw = state.raw_data.get("vt_tray") or []
  517. if isinstance(vt_tray_raw, dict):
  518. vt_tray_raw = [vt_tray_raw]
  519. for vt in vt_tray_raw:
  520. if not isinstance(vt, dict):
  521. continue
  522. vt_id = int(vt.get("id", 254))
  523. # VT tray id 254 → (ams_id=255, tray_id=0), id 255 → (ams_id=255, tray_id=1), 247-253 → 2-8
  524. vt_tray_id = external_slot_index(vt_id)
  525. remain = vt.get("remain", -1)
  526. if isinstance(remain, int) and 0 <= remain <= 100:
  527. tray_remain_start[(EXTERNAL_AMS_ID, vt_tray_id)] = remain
  528. else:
  529. skipped_invalid.append(f"VT{vt_id}(remain={remain})")
  530. if skipped_invalid:
  531. logger.info(
  532. "[UsageTracker] Skipped trays with invalid remain%% for printer %d: %s",
  533. printer_id,
  534. ", ".join(skipped_invalid),
  535. )
  536. if not ams_data and not vt_tray_raw:
  537. logger.debug("[UsageTracker] No AMS or VT tray data for printer %d, skipping", printer_id)
  538. return
  539. print_name = data.get("subtask_name", "") or data.get("filename", "unknown")
  540. # Capture tray_now at print start (reliable, unlike at completion where it's 255)
  541. tray_now_at_start = state.tray_now if state else -1
  542. # --- Diagnostic logging: dump mapping-related MQTT fields at print start ---
  543. # This helps us understand what each printer model reports for slot-to-tray mapping.
  544. mapping_field = state.raw_data.get("mapping")
  545. logger.info(
  546. "[UsageTracker] PRINT START printer %d: mapping=%s, tray_now=%d, last_loaded_tray=%s",
  547. printer_id,
  548. mapping_field,
  549. tray_now_at_start,
  550. getattr(state, "last_loaded_tray", "N/A"),
  551. )
  552. # Log all raw_data keys containing "map" or "ams" for discovery
  553. map_keys = {k: state.raw_data[k] for k in state.raw_data if "map" in k.lower()}
  554. if map_keys:
  555. logger.info("[UsageTracker] PRINT START printer %d: mapping-related keys: %s", printer_id, map_keys)
  556. # Log per-tray summary: tray_now, tray_tar, tray_type, tray_color for each slot
  557. for ams_unit in ams_data:
  558. ams_id = int(ams_unit.get("id", 0))
  559. tray_summary = []
  560. for tray in ams_unit.get("tray", []):
  561. tray_summary.append(
  562. f"T{tray.get('id', '?')}(type={tray.get('tray_type', '')}, "
  563. f"color={tray.get('tray_color', '')}, "
  564. f"now={ams_raw.get('tray_now', '?') if isinstance(ams_raw, dict) else '?'}, "
  565. f"tar={ams_raw.get('tray_tar', '?') if isinstance(ams_raw, dict) else '?'})"
  566. )
  567. logger.info("[UsageTracker] PRINT START printer %d AMS %d: %s", printer_id, ams_id, ", ".join(tray_summary))
  568. # Snapshot spool assignments so usage isn't lost if on_ams_change unlinks mid-print
  569. spool_assignments: dict[tuple[int, int], int] = {}
  570. if db:
  571. assign_result = await db.execute(select(SpoolAssignment).where(SpoolAssignment.printer_id == printer_id))
  572. for assignment in assign_result.scalars().all():
  573. spool_assignments[(assignment.ams_id, assignment.tray_id)] = assignment.spool_id
  574. if spool_assignments:
  575. logger.info(
  576. "[UsageTracker] Snapshotted %d spool assignments for printer %d: %s",
  577. len(spool_assignments),
  578. printer_id,
  579. {f"{k[0]}-{k[1]}": v for k, v in spool_assignments.items()},
  580. )
  581. # The spool each assigned tray starts the print with, in the backend that
  582. # writes the usage: a spool swapped on a tray mid-print is split against it
  583. # (#3325).
  584. if spoolman_owns_usage and db:
  585. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  586. spoolman_slots = {
  587. (row.ams_id, row.tray_id): row.spoolman_spool_id
  588. for row in (
  589. await db.execute(select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id))
  590. ).scalars()
  591. }
  592. state.spool_change_log = spool_swaps.start_entries(spool_swaps.SPOOLMAN, spoolman_slots)
  593. else:
  594. state.spool_change_log = spool_swaps.start_entries(spool_swaps.INVENTORY, spool_assignments)
  595. # Capture the queue item's plate_id so 3MF parsing at completion is scoped to
  596. # the plate that actually ran, not the whole multi-plate file (#1697).
  597. plate_id: int | None = None
  598. if db:
  599. from backend.app.models.print_queue import PrintQueueItem
  600. queue_result = await db.execute(
  601. select(PrintQueueItem)
  602. .where(PrintQueueItem.printer_id == printer_id)
  603. .where(PrintQueueItem.status == "printing")
  604. )
  605. queue_item = queue_result.scalars().first()
  606. if queue_item is not None:
  607. plate_id = queue_item.plate_id
  608. # Always create session (even without valid remain data) so print_name
  609. # is available at completion for 3MF-based tracking
  610. session = PrintSession(
  611. printer_id=printer_id,
  612. print_name=print_name,
  613. started_at=datetime.now(timezone.utc),
  614. tray_remain_start=tray_remain_start,
  615. tray_now_at_start=tray_now_at_start,
  616. spool_assignments=spool_assignments,
  617. ams_mapping=data.get("ams_mapping"),
  618. plate_id=plate_id,
  619. )
  620. if spoolman_owns_usage:
  621. _active_sessions.pop(printer_id, None)
  622. else:
  623. _active_sessions[printer_id] = session
  624. # Mirror to the DB so a restart mid-print doesn't lose the context. The
  625. # tray-change log has already been cleared and seeded with the starting
  626. # tray by bambu_mqtt before this callback fires.
  627. if db:
  628. try:
  629. await persist_session(
  630. db,
  631. session,
  632. getattr(state, "tray_change_log", None),
  633. getattr(state, "spool_change_log", None),
  634. )
  635. except Exception:
  636. logger.exception("[UsageTracker] Failed to persist print session for printer %d", printer_id)
  637. if tray_remain_start:
  638. logger.info(
  639. "[UsageTracker] Captured start remain%% for printer %d (%d trays): %s",
  640. printer_id,
  641. len(tray_remain_start),
  642. {f"{k[0]}-{k[1]}": v for k, v in tray_remain_start.items()},
  643. )
  644. else:
  645. logger.debug("[UsageTracker] No valid remain%% for printer %d, 3MF fallback available", printer_id)
  646. async def on_print_complete(
  647. printer_id: int,
  648. data: dict,
  649. printer_manager,
  650. db: AsyncSession,
  651. archive_id: int | None = None,
  652. ams_mapping: list[int] | None = None,
  653. ) -> list[dict]:
  654. """Compute consumption deltas and update spool weight_used/last_used.
  655. Uses two tracking strategies in priority order:
  656. 1. 3MF per-filament estimates (primary) — precise slicer data for all spools
  657. 2. AMS remain% delta (fallback) — only for trays not already handled by 3MF
  658. Returns a list of dicts describing what was logged (for WebSocket broadcast).
  659. """
  660. from sqlalchemy import select
  661. from backend.app.models.spool_usage_history import SpoolUsageHistory
  662. session = _active_sessions.pop(printer_id, None)
  663. if session is None:
  664. # Restart mid-print: the in-memory session is gone but the print-start
  665. # row survived. Without this the completion path loses the plate, the
  666. # dispatched mapping and the assignment snapshot, and attributes the
  667. # whole print to whichever tray happened to finish it.
  668. try:
  669. await restore_session(db, printer_id)
  670. except Exception:
  671. logger.exception("[UsageTracker] Failed to restore print session for printer %d", printer_id)
  672. session = _active_sessions.pop(printer_id, None)
  673. status = data.get("status", "completed")
  674. results = []
  675. handled_trays: set[tuple[int, int]] = set()
  676. # Fetch default filament cost from settings for fallback
  677. from backend.app.services.print_cost_estimate import default_cost_per_kg
  678. default_filament_cost = await default_cost_per_kg(db)
  679. # Fall back to ams_mapping captured at print start (needed when auto-archive is off
  680. # and the caller can't retrieve the mapping from _print_ams_mappings without archive_id)
  681. if not ams_mapping and session and session.ams_mapping:
  682. ams_mapping = session.ams_mapping
  683. logger.info(
  684. "[UsageTracker] on_print_complete: printer=%d, archive=%s, session=%s, ams_mapping=%s",
  685. printer_id,
  686. archive_id,
  687. "yes" if session else "no",
  688. ams_mapping,
  689. )
  690. # --- Diagnostic logging: dump mapping-related MQTT fields at print completion ---
  691. state = printer_manager.get_status(printer_id)
  692. if state and state.raw_data:
  693. logger.info(
  694. "[UsageTracker] PRINT COMPLETE printer %d: mapping=%s, tray_now=%s, last_loaded_tray=%s",
  695. printer_id,
  696. state.raw_data.get("mapping"),
  697. state.tray_now,
  698. getattr(state, "last_loaded_tray", "N/A"),
  699. )
  700. # --- Path 1 (PRIMARY): 3MF per-filament estimates ---
  701. print_name = (
  702. (session.print_name if session else None) or data.get("subtask_name", "") or data.get("filename", "unknown")
  703. )
  704. # When auto-archive is disabled (archive_id=None), try to find a 3MF by filename
  705. # from the library or previous archives so we can still track filament usage.
  706. threemf_path = None
  707. if not archive_id:
  708. from backend.app.core.config import settings as app_settings
  709. search_filename = data.get("filename") or data.get("subtask_name") or (session.print_name if session else "")
  710. if search_filename:
  711. threemf_path = await _find_3mf_by_filename(
  712. printer_id,
  713. search_filename,
  714. db,
  715. app_settings.base_dir,
  716. print_name=data.get("subtask_name") or (session.print_name if session else None),
  717. )
  718. if archive_id or threemf_path:
  719. threemf_results = await _track_from_3mf(
  720. printer_id,
  721. archive_id,
  722. status,
  723. print_name,
  724. handled_trays,
  725. printer_manager,
  726. db,
  727. ams_mapping=ams_mapping,
  728. tray_now_at_start=session.tray_now_at_start if session else -1,
  729. last_progress=data.get("last_progress", 0.0),
  730. last_layer_num=data.get("last_layer_num", 0),
  731. default_filament_cost=default_filament_cost,
  732. spool_assignments=session.spool_assignments if session else None,
  733. print_started_at=session.started_at if session else None,
  734. threemf_path=threemf_path,
  735. plate_id=session.plate_id if session else None,
  736. )
  737. results.extend(threemf_results)
  738. # --- Path 2 (FALLBACK): AMS remain% delta (only for trays not handled by 3MF) ---
  739. if session and session.tray_remain_start:
  740. state = printer_manager.get_status(printer_id)
  741. if state and state.raw_data:
  742. ams_raw = state.raw_data.get("ams", [])
  743. ams_data = (
  744. ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  745. )
  746. # Build set of trays actually involved in this print (#1269).
  747. # Without this guard, swapping a spool in an UNUSED slot mid-print
  748. # makes that slot's remain% drop to 0, which the fallback below
  749. # would otherwise charge to the originally-assigned spool.
  750. _global_to_ams_key = TrayLayout.from_state(state).slot_key
  751. print_used_keys: set[tuple[int, int]] = set()
  752. if ams_mapping:
  753. for gid in ams_mapping:
  754. if isinstance(gid, int) and gid >= 0:
  755. print_used_keys.add(_global_to_ams_key(gid))
  756. for change in getattr(state, "tray_change_log", None) or []:
  757. if isinstance(change, (tuple, list)) and len(change) >= 1:
  758. gid = change[0]
  759. if isinstance(gid, int) and gid >= 0:
  760. print_used_keys.add(_global_to_ams_key(gid))
  761. # 255 is not a slot: it is what ``tray_now`` reads at rest, before
  762. # the printer has reported one and while nothing is loaded, and an
  763. # unparseable reading falls back to it too. Mapped as a tray id it
  764. # becomes (255, 1), and if it were the only evidence every real
  765. # slot would be excluded and the fallback would charge nothing at
  766. # all (#1820). The external spool reports 254 when in use.
  767. if session.tray_now_at_start is not None and 0 <= session.tray_now_at_start <= 254:
  768. print_used_keys.add(_global_to_ams_key(session.tray_now_at_start))
  769. # Collect all trays to check: AMS trays + VT (external) trays
  770. # Each entry: (ams_id_for_assignment, tray_id_for_assignment, current_remain, label)
  771. trays_to_check: list[tuple[int, int, int, str]] = []
  772. for ams_unit in ams_data:
  773. ams_id = int(ams_unit.get("id", 0))
  774. for tray in ams_unit.get("tray", []):
  775. tray_id = int(tray.get("id", 0))
  776. remain = tray.get("remain", -1)
  777. trays_to_check.append((ams_id, tray_id, remain, f"AMS{ams_id}-T{tray_id}"))
  778. # VT (external) trays — same remain% delta logic
  779. vt_tray_raw = state.raw_data.get("vt_tray") or []
  780. if isinstance(vt_tray_raw, dict):
  781. vt_tray_raw = [vt_tray_raw]
  782. for vt in vt_tray_raw:
  783. if not isinstance(vt, dict):
  784. continue
  785. vt_id = int(vt.get("id", 254))
  786. vt_tray_id = external_slot_index(vt_id) # 254→0, 255→1, rack 247-253→2-8
  787. remain = vt.get("remain", -1)
  788. trays_to_check.append((EXTERNAL_AMS_ID, vt_tray_id, remain, f"VT{vt_id}"))
  789. for assign_ams_id, assign_tray_id, current_remain, tray_label in trays_to_check:
  790. key = (assign_ams_id, assign_tray_id)
  791. if key in handled_trays:
  792. continue # Already tracked via 3MF
  793. if key not in session.tray_remain_start:
  794. # No usable remain% when the print began, so there is no delta
  795. # to charge. Said out loud for the same reason as the branches
  796. # below: a slot the print used, holding a spool the operator
  797. # assigned, otherwise vanished from the accounting without a
  798. # word. Common on non-RFID spools, which report remain = -1
  799. # until a remaining amount is set by hand.
  800. if not print_used_keys or key in print_used_keys:
  801. logger.info(
  802. "[UsageTracker] %s: no valid remain%% at print start, nothing to charge for printer %d",
  803. tray_label,
  804. printer_id,
  805. )
  806. continue
  807. # Skip trays the print never touched. Only enforce when we have
  808. # evidence of which trays the print used; if print_used_keys is
  809. # empty (no mapping, no change log, no tray_now_at_start) keep
  810. # the legacy behavior of scanning every tray.
  811. if print_used_keys and key not in print_used_keys:
  812. logger.info(
  813. "[UsageTracker] %s: not in print mapping/tray_change_log — skipping fallback for printer %d",
  814. tray_label,
  815. printer_id,
  816. )
  817. continue
  818. if not isinstance(current_remain, int) or current_remain < 0 or current_remain > 100:
  819. logger.info(
  820. "[UsageTracker] %s: invalid remain%% at completion (%s), skipping fallback for printer %d",
  821. tray_label,
  822. current_remain,
  823. printer_id,
  824. )
  825. continue
  826. start_remain = session.tray_remain_start[key]
  827. delta_pct = start_remain - current_remain
  828. if delta_pct <= 0:
  829. # Not necessarily "nothing was printed". A fresh spool sits
  830. # at 100% for the first tens of grams, and the AMS estimate
  831. # drifts upward on its own, so a real print can end with the
  832. # same or a higher reading than it started with. Said out
  833. # loud because the alternative -- charging nothing, silently
  834. # -- is indistinguishable from having nothing to charge, and
  835. # the operator has no other way to find the prints that went
  836. # uncounted (#1820).
  837. logger.info(
  838. "[UsageTracker] %s: remain%% did not fall over the print (%d%% -> %d%%), "
  839. "nothing charged for printer %d",
  840. tray_label,
  841. start_remain,
  842. current_remain,
  843. printer_id,
  844. )
  845. continue
  846. swap_segs = spool_swaps.segments(
  847. getattr(state, "spool_change_log", None), spool_swaps.INVENTORY, assign_ams_id, assign_tray_id
  848. )
  849. if any(layer > 0 for _, layer in swap_segs[1:]):
  850. # Start and end remain% belong to two different spools: the
  851. # difference is neither one's usage (#3325). An assignment
  852. # corrected before the first layer is not a swap; the live
  853. # spool takes the delta below, as it always did.
  854. logger.warning(
  855. "[UsageTracker] %s: spool swapped during the print, remain%% delta not charged for printer %d",
  856. tray_label,
  857. printer_id,
  858. )
  859. continue
  860. spool_id = await _resolve_spool_id_for_tray(
  861. printer_id=printer_id,
  862. ams_id=assign_ams_id,
  863. tray_id=assign_tray_id,
  864. db=db,
  865. spool_assignments_snapshot=session.spool_assignments,
  866. print_started_at=session.started_at,
  867. )
  868. if spool_id is None:
  869. logger.info(
  870. "[UsageTracker] %s: no spool assigned, skipping fallback for printer %d",
  871. tray_label,
  872. printer_id,
  873. )
  874. continue
  875. # Load spool
  876. spool_result = await db.execute(select(Spool).where(Spool.id == spool_id))
  877. spool = spool_result.scalar_one_or_none()
  878. if not spool:
  879. continue
  880. # Compute weight consumed
  881. weight_grams = (delta_pct / 100.0) * spool.label_weight
  882. # Update spool
  883. if not await _charge_spool(db, spool, weight_grams):
  884. continue
  885. # Calculate cost for this usage
  886. cost = None
  887. cost_per_kg = spool.cost_per_kg if spool.cost_per_kg is not None else default_filament_cost
  888. if cost_per_kg > 0:
  889. cost = round((weight_grams / 1000.0) * cost_per_kg, 2)
  890. # Insert usage history record
  891. history = SpoolUsageHistory(
  892. spool_id=spool.id,
  893. printer_id=printer_id,
  894. print_name=session.print_name,
  895. weight_used=round(weight_grams, 1),
  896. percent_used=delta_pct,
  897. status=status,
  898. cost=cost,
  899. archive_id=archive_id,
  900. )
  901. db.add(history)
  902. handled_trays.add(key)
  903. results.append(
  904. {
  905. "spool_id": spool.id,
  906. "weight_used": round(weight_grams, 1),
  907. "percent_used": delta_pct,
  908. "ams_id": assign_ams_id,
  909. "tray_id": assign_tray_id,
  910. "material": spool.material,
  911. "cost": cost,
  912. # AMS remain%-delta fallback has no 3MF slot — slot_id
  913. # stays None so it is excluded from the colour rewrite.
  914. "slot_id": None,
  915. "color": _spool_color_to_hex(spool.rgba),
  916. }
  917. )
  918. logger.info(
  919. "[UsageTracker] Spool %d consumed %.1fg (%d%%) on printer %d %s (AMS fallback, %s)",
  920. spool.id,
  921. weight_grams,
  922. delta_pct,
  923. printer_id,
  924. tray_label,
  925. status,
  926. )
  927. if results:
  928. await db.commit()
  929. # --- Update PrintArchive.cost from THIS print session only ---
  930. #
  931. # Cover any filament weight that wasn't tracked by an inventory spool with
  932. # the global default rate (#1344). Without this, a multi-color print where
  933. # only some AMS trays are mapped to inventory spools would record only the
  934. # mapped slots' share — e.g. $0.01 for a 110g print when 3 of 4 trays had
  935. # no spool record. The initial cost set by archive.py (total grams *
  936. # primary cost_per_kg) is fine on its own, but this block overwrites it,
  937. # so the overwrite must reconstruct the whole-print cost.
  938. if archive_id and results:
  939. from sqlalchemy import select
  940. from backend.app.models.archive import PrintArchive
  941. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  942. archive = archive_result.scalar_one_or_none()
  943. if archive:
  944. total_cost = sum(r.get("cost", 0) or 0 for r in results)
  945. tracked_grams = sum(r.get("weight_used", 0) or 0 for r in results)
  946. archive_grams = archive.filament_used_grams or 0
  947. untracked_grams = max(0.0, archive_grams - tracked_grams)
  948. if untracked_grams > 0 and default_filament_cost > 0:
  949. total_cost += (untracked_grams / 1000.0) * default_filament_cost
  950. if total_cost > 0:
  951. # Only overwrite archive.cost on the first run. Reprint actuals
  952. # live in PrintLogEntry; the archive card keeps the first run's
  953. # cost so a failed reprint doesn't visually clobber a successful
  954. # 100 g/$X print with a 10 g/$X/10 partial (#1378).
  955. from backend.app.services.print_log import other_runs_of
  956. # Nor from a run that did not finish: the archive's cost is one
  957. # full print of the file -- the queue estimate, plate scaling and
  958. # billing read it so -- and a failed run's partial cost already
  959. # lands on its own Print Log entry. Spoolman mode never wrote it
  960. # either (COST-3).
  961. if status == "completed" and not await other_runs_of(db, archive):
  962. archive.cost = round(total_cost, 2)
  963. await db.commit()
  964. return results
  965. # A running print's ``filename`` is the path the printer is executing, and on a
  966. # sliced job that is always ``…/Metadata/plate_<N>.gcode``. Its stem names the
  967. # *plate*, not the model, and every Bambu print in existence has one — so it
  968. # identifies nothing and must never be used to match a 3MF. It reached the
  969. # matcher for real on H2-series and P2S prints, where the file goes to internal
  970. # eMMC, no 3MF can be fetched, and the archive keeps the gcode path as its
  971. # filename: `plate_1` then matched an unrelated `lid_plate_1.gcode.3mf` and that
  972. # print's filament figures were read off a different model entirely.
  973. _GENERIC_PLATE_STEM = re.compile(r"^plate_?\d+$", re.IGNORECASE)
  974. def _like_escape(value: str) -> str:
  975. """Escape LIKE metacharacters so a stem matches literally.
  976. ``_`` is a single-character wildcard, and model names are full of them.
  977. """
  978. return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
  979. def _threemf_search_stem(*candidates: str | None) -> str | None:
  980. """First candidate that names a model, or None if none of them do.
  981. Candidates are tried in order and the generic plate name is skipped rather
  982. than accepted, so a print that only has one falls through to "no match"
  983. instead of matching everything.
  984. """
  985. for raw in candidates:
  986. if not raw:
  987. continue
  988. stem = raw.split("/")[-1].strip()
  989. for suffix in (".gcode.3mf", ".gcode", ".3mf"):
  990. if stem.lower().endswith(suffix):
  991. stem = stem[: -len(suffix)]
  992. break
  993. # Stripped only to judge the stem, never to change it: a real archive
  994. # here is named "…Face Down .gcode.3mf", and a stem trimmed to
  995. # "…Face Down" no longer matches the file it came from.
  996. probe = stem.strip()
  997. if probe and not _GENERIC_PLATE_STEM.match(probe):
  998. return stem
  999. return None
  1000. def _stem_matches(column, stem: str):
  1001. """Filter matching *stem* at a filename boundary rather than anywhere.
  1002. ``ilike("%<stem>.%")`` also matched a *suffix* of a longer name, which is how
  1003. `plate_1` reached `lid_plate_1.gcode.3mf`. A name is either the whole
  1004. basename or the basename after a directory separator.
  1005. """
  1006. escaped = _like_escape(stem)
  1007. return column.ilike(f"{escaped}.%", escape="\\") | column.ilike(f"%/{escaped}.%", escape="\\")
  1008. def _expected_plate_for_print(plate_id: int | None, gcode_file: str | None) -> int | None:
  1009. """The plate a running print is on, from whatever was recorded about it.
  1010. ``plate_id`` is the reliable source, and the archives that need a donor 3MF
  1011. have none: the no-3MF fallback row is created before any 3MF is read, so
  1012. the column is never filled. The gcode path the printer echoed is the other
  1013. source, exact on the firmwares that echo ``Metadata/plate_N.gcode``. Some
  1014. P1S builds echo only the 3MF filename, and then the plate is simply not
  1015. knowable at print start (#2957).
  1016. """
  1017. from backend.app.services.printer_manager import parse_plate_id
  1018. if plate_id is not None:
  1019. return plate_id
  1020. return parse_plate_id(gcode_file)
  1021. def _donor_3mf_conflicts(candidate, expected_plate: int | None) -> str | None:
  1022. """Why *candidate* cannot be this print's 3MF, or None if nothing rules it out.
  1023. A same-name 3MF is not the same print. Bambu Studio writes the printer-side
  1024. filename from the project's ``Title`` metadata, so every plate of a project
  1025. arrives under one name however the user renamed the file on disk, and a
  1026. donor chosen on the name alone hands one plate's slicer estimates to another
  1027. plate's print. A reporter's single-filament job was charged against three
  1028. spools that way, and nothing about the deduction said it was a guess
  1029. (#2957).
  1030. The plate is the one thing that can settle this. It is the same comparison
  1031. #1204 already makes against a freshly downloaded 3MF, so a single-plate
  1032. export is known to carry its original index rather than a renumbered 1.
  1033. Filament *count* deliberately is not checked, however tempting: the slicer's
  1034. ``ams_mapping`` is indexed by the project's filament slot -- see
  1035. ``slot_to_tray[slot_id - 1]`` below -- not by the plate's, so a real
  1036. single-filament print reports ``[0, -1, -1, -1]`` and its length says
  1037. nothing about how many filaments the plate uses.
  1038. """
  1039. from backend.app.services.archive import plate_indexes_in_3mf
  1040. if expected_plate is None:
  1041. return None
  1042. plates = plate_indexes_in_3mf(candidate)
  1043. if not plates or any(plate is None for plate in plates):
  1044. # Nothing was read, or not all of it was, and neither is evidence about
  1045. # the plate. Refusing here would drop the fallback for every 3MF variant
  1046. # this parser does not understand; downstream reports that honestly as
  1047. # "no filament usage data".
  1048. return None
  1049. if len(plates) == 1 and plates[0] != expected_plate:
  1050. return f"it holds plate {plates[0]}, this print is plate {expected_plate}"
  1051. if expected_plate not in plates:
  1052. # An all-plates export is a good donor precisely when it carries the
  1053. # plate that is running. Without this the plate is looked for
  1054. # downstream, found missing, and the whole file's filaments are summed
  1055. # onto one plate's print.
  1056. return f"it has no plate {expected_plate}"
  1057. return None
  1058. async def _resolve_3mf_fallback(archive, db: AsyncSession, base_dir):
  1059. """Try to find a 3MF file from library or a previous archive when the current archive has none.
  1060. This handles fallback archives (FTP download failed) where the 3MF may already exist
  1061. locally from a library upload or a previous successful print of the same file.
  1062. A name match alone does not make a candidate this print's file, so every
  1063. candidate is put through :func:`_donor_3mf_conflicts` before it is handed
  1064. back (#2957).
  1065. """
  1066. from pathlib import Path
  1067. from backend.app.models.archive import PrintArchive
  1068. from backend.app.models.library import LibraryFile
  1069. # Derive search name from archive filename (e.g. "benchy.3mf" or "benchy.gcode.3mf"),
  1070. # falling back to the print name when the filename is only a plate path.
  1071. search_base = _threemf_search_stem(archive.filename, archive.print_name)
  1072. if not search_base:
  1073. return None
  1074. print_data = (getattr(archive, "extra_data", None) or {}).get("_print_data") or {}
  1075. expected_plate = _expected_plate_for_print(
  1076. getattr(archive, "plate_id", None),
  1077. archive.filename or print_data.get("filename"),
  1078. )
  1079. if expected_plate is None:
  1080. # Worth saying out loud. On the firmwares that echo only the 3MF
  1081. # filename there is nothing to check a donor against, so whatever is
  1082. # accepted below is accepted on its name alone -- which is how the
  1083. # reporter's spools were debited for another plate's filament. The
  1084. # deduction being silent was half the bug (#2957).
  1085. logger.warning(
  1086. "[UsageTracker] 3MF fallback: archive %s does not know its plate (%r), so a same-named "
  1087. "3MF can only be matched on its name",
  1088. archive.id,
  1089. archive.filename,
  1090. )
  1091. # 1. Try library files matching the name (match base name at file boundary)
  1092. try:
  1093. lib_result = await db.execute(
  1094. LibraryFile.active()
  1095. .where(_stem_matches(LibraryFile.file_path, search_base))
  1096. .where(LibraryFile.file_path.ilike("%.3mf"))
  1097. .order_by(LibraryFile.created_at.desc())
  1098. .limit(3)
  1099. )
  1100. for lib_file in lib_result.scalars().all():
  1101. lib_path = Path(lib_file.file_path)
  1102. candidate = lib_path if lib_path.is_absolute() else base_dir / lib_file.file_path
  1103. if candidate.exists() and candidate.suffix == ".3mf":
  1104. conflict = _donor_3mf_conflicts(candidate, expected_plate)
  1105. if conflict:
  1106. logger.warning(
  1107. "[UsageTracker] 3MF fallback: not using library file %s for archive %s — %s",
  1108. candidate,
  1109. archive.id,
  1110. conflict,
  1111. )
  1112. continue
  1113. logger.info(
  1114. "[UsageTracker] 3MF fallback: found library file %s for archive %s (expected plate=%s)",
  1115. candidate,
  1116. archive.id,
  1117. expected_plate,
  1118. )
  1119. return candidate
  1120. except Exception as e:
  1121. logger.debug("[UsageTracker] 3MF fallback: library lookup failed: %s", e)
  1122. # 2. Try previous archives with the same filename that have a valid file_path
  1123. try:
  1124. prev_result = await db.execute(
  1125. select(PrintArchive)
  1126. .where(PrintArchive.id != archive.id)
  1127. .where(PrintArchive.printer_id == archive.printer_id)
  1128. .where(PrintArchive.file_path != "")
  1129. .where(PrintArchive.file_path.isnot(None))
  1130. .where(_stem_matches(PrintArchive.filename, search_base))
  1131. .order_by(PrintArchive.created_at.desc())
  1132. .limit(3)
  1133. )
  1134. for prev_archive in prev_result.scalars().all():
  1135. candidate = base_dir / prev_archive.file_path
  1136. if candidate.exists() and candidate.suffix == ".3mf":
  1137. conflict = _donor_3mf_conflicts(candidate, expected_plate)
  1138. if conflict:
  1139. logger.warning(
  1140. "[UsageTracker] 3MF fallback: not using archive %s's file for archive %s — %s",
  1141. prev_archive.id,
  1142. archive.id,
  1143. conflict,
  1144. )
  1145. continue
  1146. logger.info(
  1147. "[UsageTracker] 3MF fallback: found previous archive %s file for archive %s (expected plate=%s)",
  1148. prev_archive.id,
  1149. archive.id,
  1150. expected_plate,
  1151. )
  1152. return candidate
  1153. except Exception as e:
  1154. logger.debug("[UsageTracker] 3MF fallback: previous archive lookup failed: %s", e)
  1155. return None
  1156. async def _find_3mf_by_filename(
  1157. printer_id: int,
  1158. filename: str,
  1159. db: AsyncSession,
  1160. base_dir,
  1161. print_name: str | None = None,
  1162. ):
  1163. """Find a 3MF file by filename from library or previous archives.
  1164. Used when auto-archive is disabled and there's no archive_id, but we still
  1165. need the 3MF slicer data for filament usage tracking.
  1166. ``print_name`` is the model name to fall back to when ``filename`` is the
  1167. printer's plate path, which names no model at all -- and when it is that
  1168. plate path, it is also what keeps a same-named file for a different plate
  1169. from being adopted (#2957); see :func:`_donor_3mf_conflicts`.
  1170. """
  1171. from pathlib import Path
  1172. from backend.app.models.archive import PrintArchive
  1173. from backend.app.models.library import LibraryFile
  1174. search_base = _threemf_search_stem(filename, print_name)
  1175. if not search_base:
  1176. return None
  1177. expected_plate = _expected_plate_for_print(None, filename)
  1178. # 1. Try library files matching the name
  1179. try:
  1180. lib_result = await db.execute(
  1181. LibraryFile.active()
  1182. .where(_stem_matches(LibraryFile.file_path, search_base))
  1183. .where(LibraryFile.file_path.ilike("%.3mf"))
  1184. .order_by(LibraryFile.created_at.desc())
  1185. .limit(3)
  1186. )
  1187. for lib_file in lib_result.scalars().all():
  1188. lib_path = Path(lib_file.file_path)
  1189. candidate = lib_path if lib_path.is_absolute() else base_dir / lib_file.file_path
  1190. if candidate.exists() and candidate.suffix == ".3mf":
  1191. conflict = _donor_3mf_conflicts(candidate, expected_plate)
  1192. if conflict:
  1193. logger.warning(
  1194. "[UsageTracker] 3MF (no-archive): not using library file %s for '%s' — %s",
  1195. candidate,
  1196. filename,
  1197. conflict,
  1198. )
  1199. continue
  1200. logger.info("[UsageTracker] 3MF (no-archive): found library file %s for '%s'", candidate, filename)
  1201. return candidate
  1202. except Exception as e:
  1203. logger.debug("[UsageTracker] 3MF (no-archive): library lookup failed: %s", e)
  1204. # 2. Try previous archives with a valid 3MF file_path
  1205. try:
  1206. prev_result = await db.execute(
  1207. select(PrintArchive)
  1208. .where(PrintArchive.printer_id == printer_id)
  1209. .where(PrintArchive.file_path != "")
  1210. .where(PrintArchive.file_path.isnot(None))
  1211. .where(_stem_matches(PrintArchive.filename, search_base))
  1212. .order_by(PrintArchive.created_at.desc())
  1213. .limit(3)
  1214. )
  1215. for prev_archive in prev_result.scalars().all():
  1216. candidate = base_dir / prev_archive.file_path
  1217. if candidate.exists() and candidate.suffix == ".3mf":
  1218. conflict = _donor_3mf_conflicts(candidate, expected_plate)
  1219. if conflict:
  1220. logger.warning(
  1221. "[UsageTracker] 3MF (no-archive): not using archive %s's file for '%s' — %s",
  1222. prev_archive.id,
  1223. filename,
  1224. conflict,
  1225. )
  1226. continue
  1227. logger.info(
  1228. "[UsageTracker] 3MF (no-archive): found previous archive %s file for '%s'",
  1229. prev_archive.id,
  1230. filename,
  1231. )
  1232. return candidate
  1233. except Exception as e:
  1234. logger.debug("[UsageTracker] 3MF (no-archive): previous archive lookup failed: %s", e)
  1235. return None
  1236. async def _track_from_3mf(
  1237. printer_id: int,
  1238. archive_id: int | None,
  1239. status: str,
  1240. print_name: str,
  1241. handled_trays: set[tuple[int, int]],
  1242. printer_manager,
  1243. db: AsyncSession,
  1244. ams_mapping: list[int] | None = None,
  1245. tray_now_at_start: int = -1,
  1246. last_progress: float = 0.0,
  1247. last_layer_num: int = 0,
  1248. default_filament_cost: float = 0.0,
  1249. spool_assignments: dict[tuple[int, int], int] | None = None,
  1250. print_started_at: datetime | None = None,
  1251. threemf_path=None,
  1252. plate_id: int | None = None,
  1253. ) -> list[dict]:
  1254. """Track usage from 3MF per-filament slicer data (primary path).
  1255. Uses slicer-estimated filament weight for all spools (BL and non-BL).
  1256. For partial prints (failed/aborted), tries per-layer gcode data first,
  1257. then falls back to linear scaling by progress.
  1258. When archive_id is None (auto-archive disabled), a pre-resolved threemf_path
  1259. can be provided to still track filament usage from slicer data.
  1260. When ``plate_id`` is set (queue prints of a single plate from a multi-plate
  1261. 3MF), only that plate's filaments contribute. Without it the 3MF parser sums
  1262. every plate, which is correct for direct/library Print flows that always
  1263. target the first or only plate (#1697).
  1264. Slot-to-tray mapping priority:
  1265. 1. Stored ams_mapping from print command (reprints/direct prints)
  1266. 2. MQTT mapping field from printer state (universal, all print sources)
  1267. 3. Queue item ams_mapping (for queue-initiated prints)
  1268. 4. tray_now from printer state (for single-filament non-queue prints)
  1269. 5. Position-based default using sorted available tray IDs (handles external spools)
  1270. 6. Default mapping: slot_id - 1 = global_tray_id (last resort)
  1271. """
  1272. from pathlib import Path
  1273. from backend.app.core.config import settings as app_settings
  1274. from backend.app.models.archive import PrintArchive
  1275. from backend.app.models.print_queue import PrintQueueItem
  1276. from backend.app.services.printer_manager import printer_tray_layout
  1277. from backend.app.utils.threemf_tools import extract_filament_usage_from_3mf
  1278. file_path: Path | None = threemf_path
  1279. archive: PrintArchive | None = None
  1280. tray_layout = printer_tray_layout(printer_id, printer_manager)
  1281. if file_path is None and archive_id:
  1282. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1283. archive = result.scalar_one_or_none()
  1284. if not archive:
  1285. logger.info("[UsageTracker] 3MF: archive %s not found, skipping", archive_id)
  1286. return []
  1287. # Try archive's own file_path first
  1288. if archive.file_path:
  1289. candidate = app_settings.base_dir / archive.file_path
  1290. if candidate.exists():
  1291. file_path = candidate
  1292. # Fallback: find 3MF from library or a previous archive with the same filename
  1293. if file_path is None:
  1294. file_path = await _resolve_3mf_fallback(archive, db, app_settings.base_dir)
  1295. if file_path is None:
  1296. logger.info("[UsageTracker] 3MF: no file available for archive %s, skipping", archive_id)
  1297. return []
  1298. # The queue item carries both the plate and the dispatched mapping; look it
  1299. # up at most once. A batch dispatches one archive as several queue items,
  1300. # on several printers at once: only this printer's newest is this run.
  1301. # Completion has already closed it, as cancelled for an aborted print.
  1302. _queue_item_lookup: list = []
  1303. async def _dispatch_queue_item():
  1304. if not _queue_item_lookup:
  1305. if not archive_id:
  1306. _queue_item_lookup.append(None)
  1307. else:
  1308. queue_result = await db.execute(
  1309. select(PrintQueueItem)
  1310. .where(PrintQueueItem.archive_id == archive_id)
  1311. .where(PrintQueueItem.printer_id == printer_id)
  1312. .where(PrintQueueItem.status.in_(["printing", "completed", "failed", "cancelled"]))
  1313. .order_by(PrintQueueItem.id.desc())
  1314. )
  1315. _queue_item_lookup.append(queue_result.scalars().first())
  1316. return _queue_item_lookup[0]
  1317. # The caller's plate_id comes from the in-memory session, which a restart
  1318. # mid-print destroys. Both the archive and the queue item recorded the
  1319. # plate at dispatch — without falling back to them the parser sums every
  1320. # plate of a multi-plate file and charges the lot to one spool. The
  1321. # newest queue item goes first: the archive keeps the plate of its first
  1322. # print, so a reprint of another plate is only on the queue item.
  1323. if plate_id is None:
  1324. plate_queue_item = await _dispatch_queue_item()
  1325. if plate_queue_item is not None and plate_queue_item.plate_id is not None:
  1326. plate_id = plate_queue_item.plate_id
  1327. logger.info(
  1328. "[UsageTracker] 3MF: plate_id=%s recovered from queue item %s",
  1329. plate_id,
  1330. plate_queue_item.id,
  1331. )
  1332. elif archive is not None and archive.plate_id is not None:
  1333. plate_id = archive.plate_id
  1334. logger.info("[UsageTracker] 3MF: plate_id=%s recovered from archive %s", plate_id, archive_id)
  1335. filament_usage = extract_filament_usage_from_3mf(file_path, plate_id)
  1336. if not filament_usage and plate_id is not None:
  1337. # The plate isn't in this file. That happens when the archive's own 3MF
  1338. # is gone and `_resolve_3mf_fallback` substituted a same-named file from
  1339. # the library that was sliced with different plates. Summing the whole
  1340. # file is wrong for a single-plate run, but it is closer than recording
  1341. # nothing at all — and unlike the silent whole-file sum this replaces,
  1342. # it says so.
  1343. filament_usage = extract_filament_usage_from_3mf(file_path, None)
  1344. if filament_usage:
  1345. logger.warning(
  1346. "[UsageTracker] 3MF: plate %s not present in %s — falling back to the whole-file total",
  1347. plate_id,
  1348. file_path,
  1349. )
  1350. plate_id = None
  1351. if not filament_usage:
  1352. logger.info("[UsageTracker] 3MF: no filament usage data in %s", file_path)
  1353. return []
  1354. logger.info("[UsageTracker] 3MF: archive %s, plate_id=%s, filament_usage=%s", archive_id, plate_id, filament_usage)
  1355. # --- Resolve slot-to-tray mapping ---
  1356. mapping_source = None
  1357. # 1. Use stored ams_mapping from the print command (reprints/direct prints)
  1358. slot_to_tray = ams_mapping
  1359. if slot_to_tray:
  1360. mapping_source = "print_cmd"
  1361. # 2. Try queue item ams_mapping (queue-initiated prints store the exact mapping)
  1362. #
  1363. # Ranked above the live MQTT field on purpose: `mapping` reports the tray
  1364. # the printer is feeding from *now*, and AMS filament backup rewrites it to
  1365. # the substitute tray when a spool runs dry. Read at completion it names
  1366. # the tray that finished the print, not the one the slicer assigned — the
  1367. # queue item's copy is the mapping the print was actually dispatched with.
  1368. if not slot_to_tray and archive_id:
  1369. queue_item = await _dispatch_queue_item()
  1370. if queue_item and queue_item.ams_mapping:
  1371. try:
  1372. slot_to_tray = json.loads(queue_item.ams_mapping)
  1373. mapping_source = "queue"
  1374. except (json.JSONDecodeError, TypeError):
  1375. pass
  1376. # 3. Try MQTT mapping field from printer state (universal, all print sources)
  1377. if not slot_to_tray:
  1378. state = printer_manager.get_status(printer_id)
  1379. raw_data = getattr(state, "raw_data", None) if state else None
  1380. if raw_data:
  1381. mqtt_mapping = raw_data.get("mapping")
  1382. decoded = _decode_mqtt_mapping(mqtt_mapping, TrayLayout.from_state(state))
  1383. if decoded:
  1384. slot_to_tray = decoded
  1385. mapping_source = "mqtt"
  1386. # 4. Color-match 3MF filament slots to AMS trays (for printers without mapping field)
  1387. if not slot_to_tray:
  1388. state = printer_manager.get_status(printer_id)
  1389. raw_data = getattr(state, "raw_data", None) if state else None
  1390. if raw_data:
  1391. matched = _match_slots_by_color(filament_usage, raw_data.get("ams"))
  1392. if matched:
  1393. slot_to_tray = matched
  1394. mapping_source = "color_match"
  1395. logger.info(
  1396. "[UsageTracker] 3MF: slot_to_tray=%s (source: %s)",
  1397. slot_to_tray,
  1398. mapping_source or "none",
  1399. )
  1400. # A mapping that names no tray for any slot the print used carries no
  1401. # evidence at all; see mapping_names_no_used_tray. Drop it so the tray_now
  1402. # evidence below decides, rather than leaving every slot unfed.
  1403. if mapping_names_no_used_tray(slot_to_tray, filament_usage):
  1404. logger.info(
  1405. "[UsageTracker] 3MF: mapping %s names no tray for the used slots — ignoring it",
  1406. slot_to_tray,
  1407. )
  1408. slot_to_tray = None
  1409. mapping_source = None
  1410. # 5. For single-filament non-queue prints, use tray_now from printer state
  1411. # Priority: tray_change_log (multi-tray split) > tray_now_at_start > current tray_now
  1412. # > last_loaded_tray > vt_tray check
  1413. #
  1414. # tray_change_log evidence wins over slot_to_tray when present: if the
  1415. # printer fed from multiple trays mid-print (AMS auto-fallback when one
  1416. # spool runs out, #957), the slicer's mapping captured at print start
  1417. # is stale and needs to be replaced with per-layer split attribution.
  1418. nonzero_slots = [u for u in filament_usage if u.get("used_g", 0) > 0]
  1419. tray_now_override: int | None = None
  1420. tray_changes: list[tuple[int, int]] = [] # [(global_tray_id, layer_num), ...]
  1421. state = printer_manager.get_status(printer_id) if len(nonzero_slots) == 1 else None
  1422. if state is not None:
  1423. tray_changes = getattr(state, "tray_change_log", []) or []
  1424. elif len(nonzero_slots) > 1:
  1425. # Multi-material print: every filament change moves tray_now, so the
  1426. # log can't be read as "this slot moved to that tray" and splitting
  1427. # would attribute worse than the mapping does. Say so rather than
  1428. # silently dropping the evidence — a runout mid-print on a
  1429. # multi-material job still lands entirely on the mapped tray.
  1430. _multi_state = printer_manager.get_status(printer_id)
  1431. if len(getattr(_multi_state, "tray_change_log", []) or []) > 1:
  1432. logger.warning(
  1433. "[UsageTracker] 3MF: %d tray changes observed but %d filament slots used — "
  1434. "splitting needs a single slot, attributing by mapping alone (printer %d, archive %s)",
  1435. len(_multi_state.tray_change_log),
  1436. len(nonzero_slots),
  1437. printer_id,
  1438. archive_id,
  1439. )
  1440. if len(tray_changes) > 1:
  1441. # Multi-tray usage detected — splitting takes over regardless of slot_to_tray.
  1442. logger.info("[UsageTracker] 3MF: tray change log: %s (will split weight)", tray_changes)
  1443. elif not slot_to_tray and len(nonzero_slots) == 1:
  1444. if 0 <= tray_now_at_start <= 254:
  1445. tray_now_override = tray_now_at_start
  1446. logger.info("[UsageTracker] 3MF: using tray_now_at_start=%d (single-filament fallback)", tray_now_at_start)
  1447. elif state and 0 <= state.tray_now <= 254:
  1448. tray_now_override = state.tray_now
  1449. logger.info("[UsageTracker] 3MF: using current tray_now=%d", state.tray_now)
  1450. elif (
  1451. state
  1452. and state.tray_now == 255
  1453. and has_second_external_holder(getattr(state, "raw_data", None))
  1454. and not any(isinstance(c, (tuple, list)) and c and 0 <= c[0] <= 254 for c in tray_changes)
  1455. ):
  1456. # 255 = "no filament" on legacy printers, but valid 2nd external
  1457. # spool on H2-series. Ahead of last_loaded_tray: a print from that
  1458. # holder never updates it, so it still names the tray an earlier
  1459. # print used (#3405). A tray the printer switched to during this
  1460. # print says the 255 is an unload after it, not the feed.
  1461. tray_now_override = state.tray_now
  1462. logger.info("[UsageTracker] 3MF: using tray_now=255 (H2-series external spool)")
  1463. elif state and 0 <= state.last_loaded_tray <= 253:
  1464. tray_now_override = state.last_loaded_tray
  1465. logger.info("[UsageTracker] 3MF: using last_loaded_tray=%d (post-retract fallback)", state.last_loaded_tray)
  1466. if tray_now_override is None:
  1467. logger.info(
  1468. "[UsageTracker] 3MF: no valid tray_now (at_start=%d, current=%s, last_loaded=%s)",
  1469. tray_now_at_start,
  1470. state.tray_now if state else "N/A",
  1471. state.last_loaded_tray if state else "N/A",
  1472. )
  1473. # Scale factor for partial prints (failed/aborted)
  1474. if status == "completed":
  1475. scale = 1.0
  1476. else:
  1477. from backend.app.utils.printer_models import usage_progress
  1478. state = printer_manager.get_status(printer_id)
  1479. progress = (
  1480. usage_progress(
  1481. printer_manager.get_model(printer_id),
  1482. state.progress,
  1483. getattr(state, "layer_num", None),
  1484. getattr(state, "total_layers", None),
  1485. )
  1486. if state
  1487. else 0
  1488. )
  1489. # Firmware resets progress to 0 on cancel — use last valid progress captured during print
  1490. if progress <= 0 and last_progress > 0:
  1491. progress = last_progress
  1492. logger.info("[UsageTracker] 3MF: using last_progress=%.1f (firmware reset current to 0)", last_progress)
  1493. scale = max(0.0, min(progress / 100.0, 1.0))
  1494. # Per-layer gcode accuracy for partial prints
  1495. layer_grams: dict[int, float] | None = None
  1496. # The same in the G-code's own grams, which the tray split weighs segments in.
  1497. layer_gcode_grams: dict[int, float] = {}
  1498. if status != "completed":
  1499. state = printer_manager.get_status(printer_id)
  1500. current_layer = state.layer_num if state else 0
  1501. # Firmware resets layer_num to 0 on cancel — use last valid layer captured during print
  1502. if current_layer <= 0 and last_layer_num > 0:
  1503. current_layer = last_layer_num
  1504. logger.info("[UsageTracker] 3MF: using last_layer_num=%d (firmware reset current to 0)", last_layer_num)
  1505. if current_layer > 0:
  1506. try:
  1507. from backend.app.utils.threemf_tools import (
  1508. extract_filament_properties_from_3mf,
  1509. extract_layer_filament_usage_from_3mf,
  1510. get_cumulative_usage_at_layer,
  1511. mm_to_grams,
  1512. slicer_grams_at_layer,
  1513. )
  1514. layer_usage = extract_layer_filament_usage_from_3mf(file_path, plate_id)
  1515. if layer_usage:
  1516. cumulative_mm = get_cumulative_usage_at_layer(layer_usage, current_layer)
  1517. filament_props = extract_filament_properties_from_3mf(file_path)
  1518. # On the slicer's weights, as a finished print is (#3317).
  1519. layer_grams = slicer_grams_at_layer(layer_usage, current_layer, filament_usage)
  1520. for filament_id, mm_used in cumulative_mm.items():
  1521. slot_id = filament_id + 1 # 0-based to 1-based
  1522. props = filament_props.get(slot_id, {})
  1523. density = props.get("density", 1.24)
  1524. diameter = props.get("diameter", 1.75)
  1525. layer_gcode_grams[slot_id] = mm_to_grams(mm_used, diameter, density)
  1526. layer_grams.setdefault(slot_id, layer_gcode_grams[slot_id])
  1527. except Exception:
  1528. pass # Fall back to linear scaling
  1529. results = []
  1530. # Trays this print drew from that no longer have an assignment to charge.
  1531. # Collected rather than acted on inline so one notification covers the whole
  1532. # print instead of one per slot (#2812).
  1533. unassigned_global_trays: list[int] = []
  1534. # Deduplicated by slicer slot, not by tray (#3230). Several slots mapped to
  1535. # one tray, or a single-slot print that returns to an earlier tray, each
  1536. # consume filament of their own. A slot only repeats when the plate is
  1537. # unknown and every plate of the file is listed, and that must not charge
  1538. # the same slot once per plate. Only a tray the caller had already covered
  1539. # before this pass is skipped.
  1540. charged_slots: set[int] = set()
  1541. covered_before = frozenset(handled_trays)
  1542. # Spools swapped by hand on one tray mid-print (#3325). The G-code's
  1543. # per-layer usage is read only when a tray was actually swapped.
  1544. _swap_state = printer_manager.get_status(printer_id)
  1545. _swap_total = getattr(_swap_state, "total_layers", 0)
  1546. _swap_layer = getattr(_swap_state, "layer_num", 0)
  1547. if status == "completed":
  1548. _swap_end = max(_swap_total if isinstance(_swap_total, int) else 0, last_layer_num)
  1549. else:
  1550. _swap_end = _swap_layer if isinstance(_swap_layer, int) and _swap_layer > 0 else last_layer_num
  1551. def _read_layer_usage():
  1552. from backend.app.utils.threemf_tools import extract_layer_filament_usage_from_3mf
  1553. return extract_layer_filament_usage_from_3mf(file_path, plate_id)
  1554. _swap_shares = spool_swaps.Splitter(
  1555. getattr(_swap_state, "spool_change_log", None) if _swap_state else None,
  1556. spool_swaps.INVENTORY,
  1557. _read_layer_usage,
  1558. _swap_end,
  1559. completed=status == "completed",
  1560. ).shares
  1561. for usage in filament_usage:
  1562. slot_id = usage.get("slot_id", 0)
  1563. used_g = usage.get("used_g", 0)
  1564. if used_g <= 0:
  1565. continue
  1566. if slot_id in charged_slots:
  1567. continue
  1568. charged_slots.add(slot_id)
  1569. # --- Mid-print tray switch: split weight across trays ---
  1570. # Split math is shared with the Spoolman writer via
  1571. # ``utils.tray_split.compute_tray_split_grams`` (#1793) — both
  1572. # inventory backends must attribute segments identically or a
  1573. # user running dual-mode sees divergent totals.
  1574. if len(tray_changes) > 1:
  1575. # Compute total weight for this slot (same logic as normal path)
  1576. if layer_grams and slot_id in layer_grams:
  1577. total_weight = layer_grams[slot_id]
  1578. else:
  1579. total_weight = used_g * scale
  1580. if total_weight <= 0:
  1581. continue
  1582. # Extract per-layer gcode for segment splitting
  1583. split_layer_usage = None
  1584. split_props: dict = {}
  1585. try:
  1586. from backend.app.utils.threemf_tools import (
  1587. extract_filament_properties_from_3mf,
  1588. extract_layer_filament_usage_from_3mf,
  1589. )
  1590. split_layer_usage = extract_layer_filament_usage_from_3mf(file_path, plate_id)
  1591. filament_props = extract_filament_properties_from_3mf(file_path)
  1592. split_props = filament_props.get(slot_id, {})
  1593. except Exception:
  1594. pass # Fall back to linear splitting
  1595. from backend.app.utils.tray_split import compute_tray_split_grams
  1596. # The split prices segments in the G-code's grams and gives the last
  1597. # the rest, so it is run on the G-code's total and scaled to the
  1598. # slicer's after (#3317); a slicer total would leave the backup
  1599. # spool short, or with nothing.
  1600. split_total = layer_gcode_grams.get(slot_id) or total_weight
  1601. segments = compute_tray_split_grams(
  1602. tray_changes=tray_changes,
  1603. total_weight=split_total,
  1604. slot_id=slot_id,
  1605. layer_usage=split_layer_usage,
  1606. density=split_props.get("density", 1.24),
  1607. diameter=split_props.get("diameter", 1.75),
  1608. total_layers=(state.total_layers if state else 0) or 0,
  1609. last_layer_num=last_layer_num,
  1610. )
  1611. segments = [(i, tray, grams * total_weight / split_total) for i, tray, grams in segments]
  1612. for seg_idx, tray_global, segment_grams in segments:
  1613. if segment_grams <= 0:
  1614. continue
  1615. # Convert global tray ID to (ams_id, tray_id)
  1616. seg_ams_id, seg_tray_id = tray_layout.slot_key(tray_global)
  1617. seg_key = (seg_ams_id, seg_tray_id)
  1618. if seg_key in covered_before:
  1619. continue
  1620. seg_start_layer = tray_changes[seg_idx][1]
  1621. is_last = seg_idx + 1 >= len(tray_changes)
  1622. logger.info(
  1623. "[UsageTracker] 3MF split: segment %d tray=%d (AMS%d-T%d) layers %d-%s -> %.1fg",
  1624. seg_idx,
  1625. tray_global,
  1626. seg_ams_id,
  1627. seg_tray_id,
  1628. seg_start_layer,
  1629. tray_changes[seg_idx + 1][1] if not is_last else "end",
  1630. segment_grams,
  1631. )
  1632. # A spool swapped by hand on this tray within the segment (#3325).
  1633. seg_shares = _swap_shares(
  1634. seg_ams_id,
  1635. seg_tray_id,
  1636. slot_id,
  1637. segment_grams,
  1638. seg_start_layer,
  1639. None if is_last else tray_changes[seg_idx + 1][1],
  1640. )
  1641. seg_spool_id = await _resolve_spool_id_for_tray(
  1642. printer_id=printer_id,
  1643. ams_id=seg_ams_id,
  1644. tray_id=seg_tray_id,
  1645. db=db,
  1646. spool_assignments_snapshot=spool_assignments,
  1647. print_started_at=print_started_at,
  1648. )
  1649. if seg_shares is None and seg_spool_id is None:
  1650. logger.info(
  1651. "[UsageTracker] 3MF split: no spool at printer %d AMS%d-T%d, skipping segment",
  1652. printer_id,
  1653. seg_ams_id,
  1654. seg_tray_id,
  1655. )
  1656. continue
  1657. for share_spool_id, share_grams in seg_shares or [(seg_spool_id, segment_grams)]:
  1658. spool_result = await db.execute(select(Spool).where(Spool.id == share_spool_id))
  1659. spool = spool_result.scalar_one_or_none()
  1660. if not spool:
  1661. continue
  1662. if not await _charge_spool(db, spool, share_grams):
  1663. continue
  1664. percent = round(share_grams / (spool.label_weight or 1000) * 100)
  1665. cost = None
  1666. cost_per_kg = spool.cost_per_kg if spool.cost_per_kg is not None else default_filament_cost
  1667. if cost_per_kg > 0:
  1668. cost = round((share_grams / 1000.0) * cost_per_kg, 2)
  1669. history = SpoolUsageHistory(
  1670. spool_id=spool.id,
  1671. printer_id=printer_id,
  1672. print_name=print_name,
  1673. weight_used=round(share_grams, 1),
  1674. percent_used=percent,
  1675. status=status,
  1676. cost=cost,
  1677. archive_id=archive_id,
  1678. )
  1679. db.add(history)
  1680. handled_trays.add(seg_key)
  1681. results.append(
  1682. {
  1683. "spool_id": spool.id,
  1684. "weight_used": round(share_grams, 1),
  1685. "percent_used": percent,
  1686. "ams_id": seg_ams_id,
  1687. "tray_id": seg_tray_id,
  1688. "material": spool.material,
  1689. "cost": cost,
  1690. "slot_id": slot_id,
  1691. "color": _spool_color_to_hex(spool.rgba),
  1692. }
  1693. )
  1694. logger.info(
  1695. "[UsageTracker] Spool %d consumed %.1fg (3MF split seg%d) on printer %d AMS%d-T%d (%s)",
  1696. spool.id,
  1697. share_grams,
  1698. seg_idx,
  1699. printer_id,
  1700. seg_ams_id,
  1701. seg_tray_id,
  1702. status,
  1703. )
  1704. continue # Skip normal single-tray processing for this slot
  1705. # Map 3MF slot_id to physical (ams_id, tray_id) using resolved mapping
  1706. tray_is_guessed = False
  1707. if tray_now_override is not None:
  1708. # Single-filament non-queue print: use actual tray from printer state
  1709. global_tray_id = tray_now_override
  1710. else:
  1711. # Explicit mapping (print command, MQTT, queue, color match)
  1712. global_tray_id = None
  1713. if slot_to_tray and slot_id <= len(slot_to_tray):
  1714. mapped = slot_to_tray[slot_id - 1]
  1715. if isinstance(mapped, int) and mapped >= 0:
  1716. global_tray_id = mapped
  1717. elif mapped == -1:
  1718. # The mapping says this slot isn't fed from any tray. The
  1719. # position-based guess below would hand it the Nth loaded
  1720. # tray anyway -- an AMS spool that never moved (#3166), or
  1721. # the tray another slot really used, which that slot then
  1722. # finds already handled and drops (#2880).
  1723. logger.info(
  1724. "[UsageTracker] 3MF: slot_id=%d is unmapped (-1) — nothing charged (used_g=%.1f)",
  1725. slot_id,
  1726. used_g,
  1727. )
  1728. continue
  1729. # Position-based default: sort available tray IDs so external spools (254/255)
  1730. # naturally follow standard AMS trays, matching slicer slot numbering.
  1731. #
  1732. # Filter out AMS slots that have no spool loaded (empty `tray_type`) —
  1733. # BambuStudio/OrcaSlicer compact the slot list when assigning filaments
  1734. # and don't expose empty AMS slots to the user, so the slicer's 3MF
  1735. # slot N maps to the Nth *loaded* tray, not the Nth physical position.
  1736. # Without this filter a "3 AMS slots loaded + 1 empty + external"
  1737. # layout routes the slicer's 4th filament to the empty AMS slot
  1738. # instead of the external (#1607), and the external's spool usage
  1739. # never gets recorded. vt_tray entries are already filtered the
  1740. # same way inside `build_ams_tray_lookup` (line 174 checks
  1741. # `tray_type`), so this just mirrors that for the AMS side.
  1742. tray_is_guessed = global_tray_id is None
  1743. if global_tray_id is None:
  1744. _state = printer_manager.get_status(printer_id)
  1745. _raw = getattr(_state, "raw_data", None) if _state else None
  1746. if _raw:
  1747. from backend.app.services.spoolman_tracking import build_ams_tray_lookup
  1748. _lookup = build_ams_tray_lookup(_raw)
  1749. available_trays = sorted(gid for gid, info in _lookup.items() if info.get("tray_type"))
  1750. if slot_id <= len(available_trays):
  1751. global_tray_id = available_trays[slot_id - 1]
  1752. # Final fallback: slot_id - 1 (legacy, works for pure AMS without external spools)
  1753. if global_tray_id is None:
  1754. global_tray_id = slot_id - 1
  1755. ams_id, tray_id = tray_layout.slot_key(global_tray_id)
  1756. logger.info(
  1757. "[UsageTracker] 3MF: slot_id=%d -> global_tray=%d -> AMS%d-T%d (used_g=%.1f, tray_now_override=%s)",
  1758. slot_id,
  1759. global_tray_id,
  1760. ams_id,
  1761. tray_id,
  1762. used_g,
  1763. tray_now_override,
  1764. )
  1765. key = (ams_id, tray_id)
  1766. if key in covered_before:
  1767. continue
  1768. if tray_is_guessed and key in handled_trays:
  1769. # A guess by position can land a second slot on a tray another slot
  1770. # was charged for. That says nothing about which spool fed it, so
  1771. # it is not charged to that tray's spool as well.
  1772. continue
  1773. spool_id = await _resolve_spool_id_for_tray(
  1774. printer_id=printer_id,
  1775. ams_id=ams_id,
  1776. tray_id=tray_id,
  1777. db=db,
  1778. spool_assignments_snapshot=spool_assignments,
  1779. print_started_at=print_started_at,
  1780. )
  1781. # Use per-layer grams if available, otherwise linear scale
  1782. if layer_grams and slot_id in layer_grams:
  1783. slot_grams = layer_grams[slot_id]
  1784. else:
  1785. slot_grams = used_g * scale
  1786. # A spool swapped by hand on this tray mid-print shares it (#3325).
  1787. shares = _swap_shares(ams_id, tray_id, slot_id, slot_grams) if slot_grams > 0 else None
  1788. if shares is None and spool_id is None:
  1789. # WARNING, not INFO: everything upstream of this line succeeded --
  1790. # the 3MF was found, the grams were read, the tray resolved -- and
  1791. # the print will still report success while this filament is never
  1792. # deducted. At INFO it was invisible under the default log level and
  1793. # absent from the reasoning in support bundles (#2812).
  1794. logger.warning(
  1795. "[UsageTracker] 3MF: no spool assignment at printer %d AMS%d-T%d — %.1fg not deducted",
  1796. printer_id,
  1797. ams_id,
  1798. tray_id,
  1799. used_g,
  1800. )
  1801. unassigned_global_trays.append(global_tray_id)
  1802. continue
  1803. if slot_grams <= 0:
  1804. continue
  1805. for share_spool_id, weight_grams in shares or [(spool_id, slot_grams)]:
  1806. # Load spool
  1807. spool_result = await db.execute(select(Spool).where(Spool.id == share_spool_id))
  1808. spool = spool_result.scalar_one_or_none()
  1809. if not spool:
  1810. continue
  1811. # Update spool
  1812. if not await _charge_spool(db, spool, weight_grams):
  1813. continue
  1814. percent = round(weight_grams / (spool.label_weight or 1000) * 100)
  1815. # Calculate cost for this usage
  1816. cost = None
  1817. cost_per_kg = spool.cost_per_kg if spool.cost_per_kg is not None else default_filament_cost
  1818. if cost_per_kg > 0:
  1819. cost = round((weight_grams / 1000.0) * cost_per_kg, 2)
  1820. # Insert usage history record
  1821. history = SpoolUsageHistory(
  1822. spool_id=spool.id,
  1823. printer_id=printer_id,
  1824. print_name=print_name,
  1825. weight_used=round(weight_grams, 1),
  1826. percent_used=percent,
  1827. status=status,
  1828. cost=cost,
  1829. archive_id=archive_id,
  1830. )
  1831. db.add(history)
  1832. handled_trays.add(key)
  1833. results.append(
  1834. {
  1835. "spool_id": spool.id,
  1836. "weight_used": round(weight_grams, 1),
  1837. "percent_used": percent,
  1838. "ams_id": ams_id,
  1839. "tray_id": tray_id,
  1840. "material": spool.material,
  1841. "cost": cost,
  1842. "slot_id": slot_id,
  1843. "color": _spool_color_to_hex(spool.rgba),
  1844. }
  1845. )
  1846. # Determine mapping source for debug logging
  1847. if tray_now_override is not None:
  1848. map_src = ", tray_now"
  1849. elif mapping_source:
  1850. map_src = f", {mapping_source}_map"
  1851. else:
  1852. map_src = ""
  1853. logger.info(
  1854. "[UsageTracker] Spool %d consumed %.1fg (3MF%s%s) on printer %d AMS%d-T%d (%s)",
  1855. spool.id,
  1856. weight_grams,
  1857. " per-layer"
  1858. if (layer_grams and slot_id in layer_grams)
  1859. else (f" scaled {scale:.0%}" if scale < 1 else ""),
  1860. map_src,
  1861. printer_id,
  1862. ams_id,
  1863. tray_id,
  1864. status,
  1865. )
  1866. # --- Adopt the matched inventory spools' colours for the archive (#1494) ---
  1867. # The archive's filament_color was set from the slicer's 3MF at creation
  1868. # time; now that every used slot has been resolved to an inventory spool,
  1869. # the curated spool colour is authoritative. Committed by the caller's
  1870. # `if results: await db.commit()`.
  1871. if archive is not None:
  1872. spool_colors = _archive_colors_from_spools(filament_usage, results)
  1873. if spool_colors:
  1874. joined = ",".join(spool_colors)
  1875. if joined != archive.filament_color:
  1876. logger.info(
  1877. "[UsageTracker] 3MF: archive %s filament_color %r -> %r (from inventory spools)",
  1878. archive_id,
  1879. archive.filament_color,
  1880. joined,
  1881. )
  1882. archive.filament_color = joined
  1883. # Adopt the matched spools' materials too (#2563) — a slot mapped to a
  1884. # differently-typed spool than it was sliced for otherwise records the
  1885. # sliced type in the archive, Print Log and material stats.
  1886. spool_types = _archive_types_from_spools(filament_usage, results)
  1887. if spool_types:
  1888. joined_types = ",".join(spool_types)
  1889. if joined_types != archive.filament_type:
  1890. logger.info(
  1891. "[UsageTracker] 3MF: archive %s filament_type %r -> %r (from inventory spools)",
  1892. archive_id,
  1893. archive.filament_type,
  1894. joined_types,
  1895. )
  1896. archive.filament_type = joined_types
  1897. if unassigned_global_trays:
  1898. from backend.app.services.spool_assignment_notifications import (
  1899. notify_missing_spool_assignments_on_print_complete,
  1900. )
  1901. await notify_missing_spool_assignments_on_print_complete(printer_id, unassigned_global_trays, db, logger)
  1902. return results