test_cost_tracking.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. """Unit tests for cost tracking in usage_tracker.py.
  2. Tests cost calculation scenarios:
  3. - Spool-specific cost_per_kg
  4. - Default fallback cost from settings
  5. - Spools without cost (None)
  6. - Completed prints
  7. - Failed/partial prints
  8. - Cost aggregation to archives
  9. """
  10. import os
  11. import tempfile
  12. from datetime import datetime, timezone
  13. from types import SimpleNamespace
  14. from unittest.mock import AsyncMock, MagicMock, patch
  15. import pytest
  16. from backend.app.services.usage_tracker import (
  17. PrintSession,
  18. _active_sessions,
  19. _track_from_3mf,
  20. on_print_complete,
  21. )
  22. def _make_spool(spool_id=1, label_weight=1000, weight_used=0, cost_per_kg=None):
  23. """Create a mock Spool object with cost fields."""
  24. spool = MagicMock()
  25. spool.id = spool_id
  26. spool.label_weight = label_weight
  27. spool.weight_used = weight_used
  28. spool.cost_per_kg = cost_per_kg
  29. spool.last_used = None
  30. spool.material = "PLA"
  31. return spool
  32. def _make_assignment(spool_id=1, printer_id=1, ams_id=0, tray_id=0):
  33. """Create a mock SpoolAssignment object."""
  34. assignment = MagicMock()
  35. assignment.spool_id = spool_id
  36. assignment.printer_id = printer_id
  37. assignment.ams_id = ams_id
  38. assignment.tray_id = tray_id
  39. return assignment
  40. def _make_archive(archive_id=1, file_path=None):
  41. """Create a mock PrintArchive object with a temp file, and register cleanup."""
  42. if file_path is None:
  43. with tempfile.NamedTemporaryFile(delete=False, suffix=".3mf", prefix="test_print_") as tmp:
  44. file_path = tmp.name
  45. # Register cleanup for this file after the test
  46. import pytest
  47. frame = None
  48. try:
  49. raise Exception
  50. except Exception:
  51. import sys
  52. frame = sys._getframe(1)
  53. request = frame.f_locals.get("request")
  54. if request is not None:
  55. def cleanup():
  56. try:
  57. os.remove(file_path)
  58. except Exception:
  59. pass
  60. request.addfinalizer(cleanup)
  61. archive = MagicMock()
  62. archive.id = archive_id
  63. archive.file_path = file_path
  64. # Explicit numeric default so the #1344 top-up logic (archive_grams -
  65. # tracked_grams) doesn't compare a MagicMock to a float. Tests that
  66. # exercise the top-up path overwrite this with a real number.
  67. archive.filament_used_grams = 0
  68. return archive
  69. @pytest.fixture(autouse=True)
  70. def cleanup_temp_archives():
  71. yield
  72. # Cleanup any temp .3mf files created by _make_archive
  73. import glob
  74. for f in glob.glob("test_print_*.3mf"):
  75. try:
  76. os.remove(f)
  77. except Exception:
  78. pass
  79. @pytest.fixture(autouse=True)
  80. def cleanup_test_print_gcode():
  81. yield
  82. import os
  83. path = "archives/test/test_print.gcode.3mf"
  84. if os.path.exists(path):
  85. try:
  86. os.remove(path)
  87. except Exception:
  88. pass
  89. @pytest.fixture
  90. def archive_factory_temp():
  91. import tempfile
  92. def _factory(*args, **kwargs):
  93. with tempfile.NamedTemporaryFile(delete=False, suffix=".3mf", prefix="test_print_", dir="archives/test") as tmp:
  94. kwargs["file_path"] = tmp.name
  95. return kwargs["file_path"]
  96. yield _factory
  97. # Cleanup
  98. import glob
  99. import os
  100. for f in glob.glob("archives/test/test_print_*.3mf"):
  101. try:
  102. os.remove(f)
  103. except Exception:
  104. pass
  105. def _mock_db_sequential(responses):
  106. """Create mock db that returns responses in order."""
  107. db = AsyncMock()
  108. call_count = [0]
  109. async def mock_execute(*args, **kwargs):
  110. idx = call_count[0]
  111. call_count[0] += 1
  112. result = MagicMock()
  113. if idx < len(responses):
  114. result.scalar_one_or_none.return_value = responses[idx]
  115. else:
  116. result.scalar_one_or_none.return_value = None
  117. return result
  118. db.execute = mock_execute
  119. return db
  120. class TestCostCalculation:
  121. """Tests for cost calculation in usage tracking."""
  122. @pytest.fixture(autouse=True)
  123. def _clear_sessions(self):
  124. _active_sessions.clear()
  125. yield
  126. _active_sessions.clear()
  127. @pytest.mark.asyncio
  128. async def test_cost_with_spool_specific_cost_per_kg(self):
  129. """Cost is calculated using spool-specific cost_per_kg when available."""
  130. # Spool with cost_per_kg = 25.00 USD/kg
  131. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=25.0)
  132. assignment = _make_assignment(spool_id=1)
  133. archive = _make_archive(archive_id=10)
  134. _active_sessions[1] = PrintSession(
  135. printer_id=1,
  136. print_name="Test",
  137. started_at=datetime.now(timezone.utc),
  138. tray_remain_start={(0, 0): 80},
  139. tray_now_at_start=0,
  140. )
  141. printer_manager = MagicMock()
  142. printer_manager.get_status.return_value = SimpleNamespace(
  143. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  144. progress=100,
  145. layer_num=50,
  146. tray_now=0,
  147. )
  148. # db returns: archive, queue_item(None), assignment, spool
  149. db = _mock_db_sequential([archive, None, assignment, spool])
  150. # 20g used from 3MF
  151. filament_usage = [{"slot_id": 1, "used_g": 20.0, "type": "PLA", "color": "#FF0000"}]
  152. with (
  153. patch("backend.app.core.config.settings") as mock_settings,
  154. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"), # default cost
  155. patch(
  156. "backend.app.utils.threemf_tools.extract_filament_usage_from_3mf",
  157. return_value=filament_usage,
  158. ),
  159. ):
  160. mock_settings.base_dir = MagicMock()
  161. mock_path = MagicMock()
  162. mock_path.exists.return_value = True
  163. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  164. results = await on_print_complete(
  165. printer_id=1,
  166. data={"status": "completed"},
  167. printer_manager=printer_manager,
  168. db=db,
  169. archive_id=10,
  170. )
  171. assert len(results) == 1
  172. assert results[0]["spool_id"] == 1
  173. assert results[0]["weight_used"] == 20.0
  174. # Cost = 20g / 1000 * 25.0 = 0.50
  175. assert results[0]["cost"] == 0.50
  176. @pytest.mark.asyncio
  177. async def test_cost_with_default_fallback(self):
  178. """Cost uses default_filament_cost from settings when spool cost is None."""
  179. # Spool without cost_per_kg
  180. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=None)
  181. assignment = _make_assignment(spool_id=1)
  182. archive = _make_archive(archive_id=10)
  183. _active_sessions[1] = PrintSession(
  184. printer_id=1,
  185. print_name="Test",
  186. started_at=datetime.now(timezone.utc),
  187. tray_remain_start={(0, 0): 80},
  188. tray_now_at_start=0,
  189. )
  190. printer_manager = MagicMock()
  191. printer_manager.get_status.return_value = SimpleNamespace(
  192. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  193. progress=100,
  194. layer_num=50,
  195. tray_now=0,
  196. )
  197. # db returns: archive, queue_item(None), assignment, spool
  198. db = _mock_db_sequential([archive, None, assignment, spool])
  199. # 30g used from 3MF
  200. filament_usage = [{"slot_id": 1, "used_g": 30.0, "type": "PLA", "color": "#FF0000"}]
  201. with (
  202. patch("backend.app.core.config.settings") as mock_settings,
  203. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"), # default: 15.0/kg
  204. patch(
  205. "backend.app.utils.threemf_tools.extract_filament_usage_from_3mf",
  206. return_value=filament_usage,
  207. ),
  208. ):
  209. mock_settings.base_dir = MagicMock()
  210. mock_path = MagicMock()
  211. mock_path.exists.return_value = True
  212. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  213. results = await on_print_complete(
  214. printer_id=1,
  215. data={"status": "completed"},
  216. printer_manager=printer_manager,
  217. db=db,
  218. archive_id=10,
  219. )
  220. assert len(results) == 1
  221. assert results[0]["spool_id"] == 1
  222. assert results[0]["weight_used"] == 30.0
  223. # Cost = 30g / 1000 * 15.0 = 0.45
  224. assert results[0]["cost"] == 0.45
  225. @pytest.mark.asyncio
  226. async def test_cost_uses_the_settings_default_when_none_is_saved(self):
  227. """Never saved, the default is the 25/kg the Settings page shows, as for
  228. every other reader of it; not 0, which left unpriced spools uncosted."""
  229. # Spool without cost_per_kg
  230. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=None)
  231. assignment = _make_assignment(spool_id=1)
  232. archive = _make_archive(archive_id=10)
  233. _active_sessions[1] = PrintSession(
  234. printer_id=1,
  235. print_name="Test",
  236. started_at=datetime.now(timezone.utc),
  237. tray_remain_start={(0, 0): 80},
  238. tray_now_at_start=0,
  239. )
  240. printer_manager = MagicMock()
  241. printer_manager.get_status.return_value = SimpleNamespace(
  242. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  243. progress=100,
  244. layer_num=50,
  245. tray_now=0,
  246. )
  247. # db returns: archive, queue_item(None), assignment, spool
  248. db = _mock_db_sequential([archive, None, assignment, spool])
  249. # 30g used from 3MF
  250. filament_usage = [{"slot_id": 1, "used_g": 30.0, "type": "PLA", "color": "#FF0000"}]
  251. with (
  252. patch("backend.app.core.config.settings") as mock_settings,
  253. patch("backend.app.api.routes.settings.get_setting", return_value=None),
  254. patch(
  255. "backend.app.utils.threemf_tools.extract_filament_usage_from_3mf",
  256. return_value=filament_usage,
  257. ),
  258. ):
  259. mock_settings.base_dir = MagicMock()
  260. mock_path = MagicMock()
  261. mock_path.exists.return_value = True
  262. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  263. results = await on_print_complete(
  264. printer_id=1,
  265. data={"status": "completed"},
  266. printer_manager=printer_manager,
  267. db=db,
  268. archive_id=10,
  269. )
  270. assert len(results) == 1
  271. assert results[0]["spool_id"] == 1
  272. assert results[0]["weight_used"] == 30.0
  273. # Cost = 30g / 1000 * 25.0 = 0.75
  274. assert results[0]["cost"] == 0.75
  275. @pytest.mark.asyncio
  276. async def test_cost_zero_when_default_cost_is_zero(self):
  277. """Cost is None when both spool cost and default cost are 0."""
  278. # Spool without cost_per_kg
  279. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=None)
  280. assignment = _make_assignment(spool_id=1)
  281. archive = _make_archive(archive_id=10)
  282. _active_sessions[1] = PrintSession(
  283. printer_id=1,
  284. print_name="Test",
  285. started_at=datetime.now(timezone.utc),
  286. tray_remain_start={(0, 0): 80},
  287. tray_now_at_start=0,
  288. )
  289. printer_manager = MagicMock()
  290. printer_manager.get_status.return_value = SimpleNamespace(
  291. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  292. progress=100,
  293. layer_num=50,
  294. tray_now=0,
  295. )
  296. # db returns: archive, queue_item(None), assignment, spool
  297. db = _mock_db_sequential([archive, None, assignment, spool])
  298. filament_usage = [{"slot_id": 1, "used_g": 10.0, "type": "PLA", "color": "#FF0000"}]
  299. with (
  300. patch("backend.app.core.config.settings") as mock_settings,
  301. patch("backend.app.api.routes.settings.get_setting", return_value="0.0"), # no default cost
  302. patch(
  303. "backend.app.utils.threemf_tools.extract_filament_usage_from_3mf",
  304. return_value=filament_usage,
  305. ),
  306. ):
  307. mock_settings.base_dir = MagicMock()
  308. mock_path = MagicMock()
  309. mock_path.exists.return_value = True
  310. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  311. results = await on_print_complete(
  312. printer_id=1,
  313. data={"status": "completed"},
  314. printer_manager=printer_manager,
  315. db=db,
  316. archive_id=10,
  317. )
  318. assert len(results) == 1
  319. assert results[0]["cost"] is None
  320. @pytest.mark.asyncio
  321. async def test_cost_for_failed_print_uses_actual_usage(self):
  322. """Failed print at 50% progress calculates cost from actual usage."""
  323. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=20.0)
  324. assignment = _make_assignment(spool_id=1)
  325. archive = _make_archive(archive_id=10)
  326. _active_sessions[1] = PrintSession(
  327. printer_id=1,
  328. print_name="Test",
  329. started_at=datetime.now(timezone.utc),
  330. tray_remain_start={(0, 0): 80},
  331. tray_now_at_start=0,
  332. )
  333. # Failed at 50% progress
  334. printer_manager = MagicMock()
  335. printer_manager.get_status.return_value = SimpleNamespace(
  336. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  337. progress=50,
  338. layer_num=25,
  339. tray_now=0,
  340. )
  341. # db returns: archive, queue_item(None), assignment, spool
  342. db = _mock_db_sequential([archive, None, assignment, spool])
  343. # 40g total, but only 50% used
  344. filament_usage = [{"slot_id": 1, "used_g": 40.0, "type": "PLA", "color": "#FF0000"}]
  345. with (
  346. patch("backend.app.core.config.settings") as mock_settings,
  347. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"),
  348. patch(
  349. "backend.app.utils.threemf_tools.extract_filament_usage_from_3mf",
  350. return_value=filament_usage,
  351. ),
  352. patch(
  353. "backend.app.utils.threemf_tools.extract_layer_filament_usage_from_3mf",
  354. return_value=None, # No layer data, use linear scaling
  355. ),
  356. ):
  357. mock_settings.base_dir = MagicMock()
  358. mock_path = MagicMock()
  359. mock_path.exists.return_value = True
  360. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  361. results = await on_print_complete(
  362. printer_id=1,
  363. data={"status": "failed", "last_progress": 50.0},
  364. printer_manager=printer_manager,
  365. db=db,
  366. archive_id=10,
  367. )
  368. assert len(results) == 1
  369. # 50% of 40g = 20g
  370. assert results[0]["weight_used"] == 20.0
  371. # Cost = 20g / 1000 * 20.0 = 0.40
  372. assert results[0]["cost"] == 0.40
  373. async def _failed_after_firmware_reset(self, *, last_progress=0.0, last_layer_num=0, layer_usage=None):
  374. """A failed print whose printer already reset progress and layer to 0."""
  375. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=20.0)
  376. _active_sessions[1] = PrintSession(
  377. printer_id=1,
  378. print_name="Test",
  379. started_at=datetime.now(timezone.utc),
  380. tray_remain_start={(0, 0): 80},
  381. tray_now_at_start=0,
  382. )
  383. printer_manager = MagicMock()
  384. printer_manager.get_status.return_value = SimpleNamespace(
  385. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]}, progress=0, layer_num=0, tray_now=0
  386. )
  387. db = _mock_db_sequential([_make_archive(archive_id=10), None, _make_assignment(spool_id=1), spool])
  388. cumulative = MagicMock(return_value={0: 1000.0}) # filament 0 = slot 1
  389. with (
  390. patch("backend.app.core.config.settings") as mock_settings,
  391. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"),
  392. patch(
  393. "backend.app.utils.threemf_tools.extract_filament_usage_from_3mf",
  394. return_value=[{"slot_id": 1, "used_g": 40.0, "type": "PLA", "color": "#FF0000"}],
  395. ),
  396. patch("backend.app.utils.threemf_tools.extract_layer_filament_usage_from_3mf", return_value=layer_usage),
  397. patch("backend.app.utils.threemf_tools.get_cumulative_usage_at_layer", cumulative),
  398. patch("backend.app.utils.threemf_tools.extract_filament_properties_from_3mf", return_value={}),
  399. patch("backend.app.utils.threemf_tools.mm_to_grams", return_value=7.0),
  400. ):
  401. mock_settings.base_dir = MagicMock()
  402. mock_path = MagicMock()
  403. mock_path.exists.return_value = True
  404. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  405. results = await on_print_complete(
  406. printer_id=1,
  407. data={"status": "failed", "last_progress": last_progress, "last_layer_num": last_layer_num},
  408. printer_manager=printer_manager,
  409. db=db,
  410. archive_id=10,
  411. )
  412. return results, cumulative
  413. @pytest.mark.asyncio
  414. async def test_a_progress_reset_to_zero_falls_back_to_the_last_progress(self):
  415. """Firmware zeroes progress on cancel; 0 % would charge nothing."""
  416. results, _ = await self._failed_after_firmware_reset(last_progress=40.0)
  417. # 40 % of 40 g
  418. assert results[0]["weight_used"] == 16.0
  419. @pytest.mark.asyncio
  420. async def test_a_layer_reset_to_zero_falls_back_to_the_last_layer(self):
  421. results, cumulative = await self._failed_after_firmware_reset(
  422. last_progress=40.0, last_layer_num=12, layer_usage={1: {12: 1000.0}}
  423. )
  424. assert cumulative.call_args.args[1] == 12
  425. # The per-layer grams, not the 40 % estimate
  426. assert results[0]["weight_used"] == 7.0
  427. @pytest.mark.asyncio
  428. async def test_cost_with_ams_fallback_tracking(self):
  429. """AMS fallback tracking also calculates cost correctly."""
  430. spool = _make_spool(spool_id=2, label_weight=1000, cost_per_kg=30.0)
  431. assignment = _make_assignment(spool_id=2)
  432. _active_sessions[1] = PrintSession(
  433. printer_id=1,
  434. print_name="Test",
  435. started_at=datetime.now(timezone.utc),
  436. tray_remain_start={(0, 0): 80},
  437. )
  438. printer_manager = MagicMock()
  439. printer_manager.get_status.return_value = SimpleNamespace(
  440. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  441. tray_now=0,
  442. last_loaded_tray=-1,
  443. )
  444. # Pad 2 Nones for _find_3mf_by_filename DB queries (library + archive search),
  445. # then assignment and spool for the AMS fallback path
  446. db = _mock_db_sequential([None, None, assignment, spool])
  447. with patch("backend.app.api.routes.settings.get_setting", return_value="15.0"):
  448. results = await on_print_complete(
  449. printer_id=1,
  450. data={"status": "completed"},
  451. printer_manager=printer_manager,
  452. db=db,
  453. archive_id=None, # No archive = AMS fallback
  454. )
  455. assert len(results) == 1
  456. assert results[0]["spool_id"] == 2
  457. # 10% of 1000g = 100g
  458. assert results[0]["weight_used"] == 100.0
  459. # Cost = 100g / 1000 * 30.0 = 3.00
  460. assert results[0]["cost"] == 3.0
  461. @pytest.mark.asyncio
  462. async def test_multi_filament_cost_aggregation(self):
  463. """Multiple spools in one print have their costs tracked separately."""
  464. spool1 = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=20.0)
  465. spool2 = _make_spool(spool_id=2, label_weight=1000, cost_per_kg=25.0)
  466. assignment1 = _make_assignment(spool_id=1, ams_id=0, tray_id=0)
  467. assignment2 = _make_assignment(spool_id=2, ams_id=0, tray_id=1)
  468. archive = _make_archive(archive_id=10)
  469. _active_sessions[1] = PrintSession(
  470. printer_id=1,
  471. print_name="Test",
  472. started_at=datetime.now(timezone.utc),
  473. tray_remain_start={(0, 0): 80, (0, 1): 90},
  474. tray_now_at_start=0,
  475. )
  476. printer_manager = MagicMock()
  477. printer_manager.get_status.return_value = SimpleNamespace(
  478. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}, {"id": 1, "remain": 80}]}]},
  479. progress=100,
  480. layer_num=50,
  481. tray_now=0,
  482. )
  483. # Mock slot-to-tray mapping: slot 1 -> tray 0, slot 2 -> tray 1
  484. ams_mapping = [0, 1]
  485. # db returns: archive, assignment1, spool1, assignment2, spool2
  486. # db: archive, queue item for the plate (None), then assignments and
  487. # spools; the given ams_mapping skips only the mapping fallback
  488. db = _mock_db_sequential([archive, None, assignment1, spool1, assignment2, spool2])
  489. # Two filaments used
  490. filament_usage = [
  491. {"slot_id": 1, "used_g": 15.0, "type": "PLA", "color": "#FF0000"},
  492. {"slot_id": 2, "used_g": 25.0, "type": "PLA", "color": "#00FF00"},
  493. ]
  494. with (
  495. patch("backend.app.core.config.settings") as mock_settings,
  496. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"),
  497. patch(
  498. "backend.app.utils.threemf_tools.extract_filament_usage_from_3mf",
  499. return_value=filament_usage,
  500. ),
  501. ):
  502. mock_settings.base_dir = MagicMock()
  503. mock_path = MagicMock()
  504. mock_path.exists.return_value = True
  505. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  506. results = await on_print_complete(
  507. printer_id=1,
  508. data={"status": "completed"},
  509. printer_manager=printer_manager,
  510. db=db,
  511. archive_id=10,
  512. ams_mapping=ams_mapping,
  513. )
  514. assert len(results) == 2
  515. # First spool: 15g at 20/kg = 0.30
  516. spool1_result = next(r for r in results if r["spool_id"] == 1)
  517. assert spool1_result["weight_used"] == 15.0
  518. assert spool1_result["cost"] == 0.30
  519. # Second spool: 25g at 25/kg = 0.625, rounded to 0.62
  520. spool2_result = next(r for r in results if r["spool_id"] == 2)
  521. assert spool2_result["weight_used"] == 25.0
  522. assert spool2_result["cost"] == 0.62
  523. class TestCostAggregation:
  524. """Tests for cost aggregation to PrintArchive."""
  525. @pytest.mark.asyncio
  526. async def test_costs_summed_in_results(self):
  527. """Multiple spool costs are correctly summed from result dicts."""
  528. results = [
  529. {"spool_id": 1, "weight_used": 20.0, "cost": 0.50},
  530. {"spool_id": 2, "weight_used": 30.0, "cost": 0.75},
  531. ]
  532. total_cost = sum(r.get("cost", 0) or 0 for r in results)
  533. assert total_cost == 1.25
  534. @pytest.mark.asyncio
  535. async def test_null_costs_handled_in_aggregation(self):
  536. """None costs don't break aggregation."""
  537. results = [
  538. {"spool_id": 1, "weight_used": 20.0, "cost": 0.50},
  539. {"spool_id": 2, "weight_used": 30.0, "cost": None}, # No cost
  540. {"spool_id": 3, "weight_used": 10.0, "cost": 0.25},
  541. ]
  542. total_cost = sum(r.get("cost", 0) or 0 for r in results)
  543. assert total_cost == 0.75 # Only spools 1 and 3
  544. @pytest.mark.asyncio
  545. async def test_archive_cost_not_overwritten_with_zero(self):
  546. """archive.cost is preserved when no spool usage has cost data."""
  547. # Spool without cost_per_kg, default_filament_cost also 0 → cost=None per usage
  548. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=None)
  549. assignment = _make_assignment(spool_id=1)
  550. archive = _make_archive(archive_id=10)
  551. archive.cost = 5.00 # Pre-existing cost from catalog
  552. archive.print_name = "TestPrint"
  553. archive.printer_id = 1
  554. _active_sessions[1] = PrintSession(
  555. printer_id=1,
  556. print_name="TestPrint",
  557. started_at=datetime.now(timezone.utc),
  558. tray_remain_start={(0, 0): 80},
  559. tray_now_at_start=0,
  560. )
  561. printer_manager = MagicMock()
  562. printer_manager.get_status.return_value = SimpleNamespace(
  563. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  564. progress=100,
  565. layer_num=50,
  566. tray_now=0,
  567. )
  568. # Build mock db that returns proper scalars for the aggregation queries
  569. responses = []
  570. # 1. select(PrintArchive) → archive
  571. responses.append(("scalar_one_or_none", archive))
  572. # 2. select(PrintQueueItem) → None
  573. responses.append(("scalar_one_or_none", None))
  574. # 3. select(SpoolAssignment) → assignment
  575. responses.append(("scalar_one_or_none", assignment))
  576. # 4. select(Spool) → spool
  577. responses.append(("scalar_one_or_none", spool))
  578. # 5. cost aggregation: select archive to update cost
  579. responses.append(("scalar_one_or_none", archive))
  580. db = AsyncMock()
  581. call_count = [0]
  582. async def mock_execute(*args, **kwargs):
  583. idx = call_count[0]
  584. call_count[0] += 1
  585. result = MagicMock()
  586. if idx < len(responses):
  587. method, value = responses[idx]
  588. if method == "scalar":
  589. result.scalar.return_value = value
  590. result.scalar_one_or_none.return_value = value
  591. else:
  592. result.scalar_one_or_none.return_value = value
  593. result.scalar.return_value = value
  594. else:
  595. result.scalar_one_or_none.return_value = None
  596. result.scalar.return_value = None
  597. return result
  598. db.execute = mock_execute
  599. filament_usage = [{"slot_id": 1, "used_g": 10.0, "type": "PLA", "color": "#FF0000"}]
  600. with (
  601. patch("backend.app.core.config.settings") as mock_settings,
  602. patch("backend.app.api.routes.settings.get_setting", return_value="0.0"), # no default cost
  603. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=filament_usage),
  604. ):
  605. mock_settings.base_dir = MagicMock()
  606. mock_path = MagicMock()
  607. mock_path.exists.return_value = True
  608. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  609. results = await on_print_complete(
  610. printer_id=1,
  611. data={"status": "completed"},
  612. printer_manager=printer_manager,
  613. db=db,
  614. archive_id=10,
  615. )
  616. # Usage tracked but cost is None (no cost_per_kg, no default)
  617. assert len(results) == 1
  618. assert results[0]["cost"] is None
  619. # Archive cost should NOT have been overwritten — still 5.00
  620. assert archive.cost == 5.00
  621. @pytest.mark.asyncio
  622. async def test_archive_cost_set_when_spool_has_cost(self):
  623. """archive.cost is set from spool usage when cost data exists."""
  624. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=25.0)
  625. assignment = _make_assignment(spool_id=1)
  626. archive = _make_archive(archive_id=10)
  627. archive.cost = None # No pre-existing cost
  628. archive.print_name = "TestPrint"
  629. archive.printer_id = 1
  630. _active_sessions[1] = PrintSession(
  631. printer_id=1,
  632. print_name="TestPrint",
  633. started_at=datetime.now(timezone.utc),
  634. tray_remain_start={(0, 0): 80},
  635. tray_now_at_start=0,
  636. )
  637. printer_manager = MagicMock()
  638. printer_manager.get_status.return_value = SimpleNamespace(
  639. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  640. progress=100,
  641. layer_num=50,
  642. tray_now=0,
  643. )
  644. # 20g at 25/kg = 0.50
  645. expected_cost = 0.50
  646. responses = []
  647. responses.append(("scalar_one_or_none", archive))
  648. responses.append(("scalar_one_or_none", None)) # queue item
  649. responses.append(("scalar_one_or_none", assignment))
  650. responses.append(("scalar_one_or_none", spool))
  651. # cost aggregation: select archive to update cost
  652. responses.append(("scalar_one_or_none", archive))
  653. db = AsyncMock()
  654. call_count = [0]
  655. async def mock_execute(*args, **kwargs):
  656. idx = call_count[0]
  657. call_count[0] += 1
  658. result = MagicMock()
  659. if idx < len(responses):
  660. method, value = responses[idx]
  661. result.scalar.return_value = value
  662. result.scalar_one_or_none.return_value = value
  663. else:
  664. result.scalar_one_or_none.return_value = None
  665. result.scalar.return_value = None
  666. return result
  667. db.execute = mock_execute
  668. filament_usage = [{"slot_id": 1, "used_g": 20.0, "type": "PLA", "color": "#FF0000"}]
  669. with (
  670. # The first run of this archive
  671. patch("backend.app.services.print_log.other_runs_of", AsyncMock(return_value=0)),
  672. patch("backend.app.core.config.settings") as mock_settings,
  673. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"),
  674. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=filament_usage),
  675. ):
  676. mock_settings.base_dir = MagicMock()
  677. mock_path = MagicMock()
  678. mock_path.exists.return_value = True
  679. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  680. results = await on_print_complete(
  681. printer_id=1,
  682. data={"status": "completed"},
  683. printer_manager=printer_manager,
  684. db=db,
  685. archive_id=10,
  686. )
  687. assert len(results) == 1
  688. assert results[0]["cost"] == expected_cost
  689. # Archive cost should have been updated
  690. assert archive.cost == expected_cost
  691. @pytest.mark.asyncio
  692. async def test_archive_cost_includes_untracked_filament_at_default_rate(self):
  693. """#1344: when only some AMS trays have inventory spools, the untracked
  694. filament weight is charged at the global default rate so the total
  695. archive cost still reflects the whole print."""
  696. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=10.0)
  697. assignment = _make_assignment(spool_id=1)
  698. archive = _make_archive(archive_id=10)
  699. archive.cost = None
  700. archive.print_name = "TestPrint"
  701. archive.printer_id = 1
  702. archive.filament_used_grams = 110.0 # whole-print weight from slicer
  703. _active_sessions[1] = PrintSession(
  704. printer_id=1,
  705. print_name="TestPrint",
  706. started_at=datetime.now(timezone.utc),
  707. tray_remain_start={(0, 0): 80},
  708. tray_now_at_start=0,
  709. )
  710. printer_manager = MagicMock()
  711. printer_manager.get_status.return_value = SimpleNamespace(
  712. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  713. progress=100,
  714. layer_num=50,
  715. tray_now=0,
  716. )
  717. responses = [
  718. ("scalar_one_or_none", archive),
  719. ("scalar_one_or_none", None), # queue item
  720. ("scalar_one_or_none", assignment),
  721. ("scalar_one_or_none", spool),
  722. ("scalar_one_or_none", archive), # cost-update select
  723. ]
  724. db = AsyncMock()
  725. call_count = [0]
  726. async def mock_execute(*args, **kwargs):
  727. idx = call_count[0]
  728. call_count[0] += 1
  729. result = MagicMock()
  730. if idx < len(responses):
  731. _, value = responses[idx]
  732. result.scalar.return_value = value
  733. result.scalar_one_or_none.return_value = value
  734. else:
  735. result.scalar_one_or_none.return_value = None
  736. result.scalar.return_value = None
  737. return result
  738. db.execute = mock_execute
  739. # 3MF reports a single slot using 10g, but archive.filament_used_grams
  740. # says the whole print was 110g -- the other 100g came from spools that
  741. # aren't in inventory.
  742. filament_usage = [{"slot_id": 1, "used_g": 10.0, "type": "PLA", "color": "#FF0000"}]
  743. with (
  744. # The first run of this archive
  745. patch("backend.app.services.print_log.other_runs_of", AsyncMock(return_value=0)),
  746. patch("backend.app.core.config.settings") as mock_settings,
  747. patch("backend.app.api.routes.settings.get_setting", return_value="10.0"),
  748. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=filament_usage),
  749. ):
  750. mock_settings.base_dir = MagicMock()
  751. mock_path = MagicMock()
  752. mock_path.exists.return_value = True
  753. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  754. results = await on_print_complete(
  755. printer_id=1,
  756. data={"status": "completed"},
  757. printer_manager=printer_manager,
  758. db=db,
  759. archive_id=10,
  760. )
  761. # Tracked slot: 10g * $10/kg = $0.10
  762. assert len(results) == 1
  763. assert results[0]["cost"] == 0.10
  764. # Untracked: 110g - 10g = 100g at $10/kg default = $1.00
  765. # Archive total: $0.10 + $1.00 = $1.10 (was $0.01 pre-fix because only
  766. # the tracked slot's tiny share was kept)
  767. assert archive.cost == 1.10
  768. @pytest.mark.asyncio
  769. async def test_archive_cost_fully_tracked_unchanged_by_topup(self):
  770. """When every gram is covered by inventory spools, the default-rate
  771. top-up adds nothing -- the archive cost is just the sum of tracked
  772. costs, same as before #1344."""
  773. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=25.0)
  774. assignment = _make_assignment(spool_id=1)
  775. archive = _make_archive(archive_id=10)
  776. archive.cost = None
  777. archive.print_name = "TestPrint"
  778. archive.printer_id = 1
  779. archive.filament_used_grams = 20.0 # exactly what the slot reports
  780. _active_sessions[1] = PrintSession(
  781. printer_id=1,
  782. print_name="TestPrint",
  783. started_at=datetime.now(timezone.utc),
  784. tray_remain_start={(0, 0): 80},
  785. tray_now_at_start=0,
  786. )
  787. printer_manager = MagicMock()
  788. printer_manager.get_status.return_value = SimpleNamespace(
  789. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  790. progress=100,
  791. layer_num=50,
  792. tray_now=0,
  793. )
  794. responses = [
  795. ("scalar_one_or_none", archive),
  796. ("scalar_one_or_none", None),
  797. ("scalar_one_or_none", assignment),
  798. ("scalar_one_or_none", spool),
  799. ("scalar_one_or_none", archive),
  800. ]
  801. db = AsyncMock()
  802. call_count = [0]
  803. async def mock_execute(*args, **kwargs):
  804. idx = call_count[0]
  805. call_count[0] += 1
  806. result = MagicMock()
  807. if idx < len(responses):
  808. _, value = responses[idx]
  809. result.scalar.return_value = value
  810. result.scalar_one_or_none.return_value = value
  811. else:
  812. result.scalar_one_or_none.return_value = None
  813. result.scalar.return_value = None
  814. return result
  815. db.execute = mock_execute
  816. filament_usage = [{"slot_id": 1, "used_g": 20.0, "type": "PLA", "color": "#FF0000"}]
  817. with (
  818. # The first run of this archive
  819. patch("backend.app.services.print_log.other_runs_of", AsyncMock(return_value=0)),
  820. patch("backend.app.core.config.settings") as mock_settings,
  821. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"),
  822. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=filament_usage),
  823. ):
  824. mock_settings.base_dir = MagicMock()
  825. mock_path = MagicMock()
  826. mock_path.exists.return_value = True
  827. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  828. results = await on_print_complete(
  829. printer_id=1,
  830. data={"status": "completed"},
  831. printer_manager=printer_manager,
  832. db=db,
  833. archive_id=10,
  834. )
  835. # 20g at $25/kg = $0.50 -- no top-up because tracked >= archive grams
  836. assert len(results) == 1
  837. assert results[0]["cost"] == 0.50
  838. assert archive.cost == 0.50
  839. @pytest.mark.asyncio
  840. async def test_cost_with_archive_id(self):
  841. """Test cost aggregation using archive_id (3MF path)."""
  842. spool_new = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=25.0)
  843. assignment_new = _make_assignment(spool_id=1)
  844. archive_new = _make_archive(archive_id=20)
  845. filament_usage_new = [{"slot_id": 1, "used_g": 20.0, "type": "PLA", "color": "#FF0000"}]
  846. printer_manager = MagicMock()
  847. printer_manager.get_status.return_value = SimpleNamespace(
  848. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  849. progress=100,
  850. layer_num=50,
  851. tray_now=0,
  852. )
  853. db = _mock_db_sequential([archive_new, None, assignment_new, spool_new])
  854. with (
  855. patch("backend.app.core.config.settings") as mock_settings,
  856. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"),
  857. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=filament_usage_new),
  858. ):
  859. mock_settings.base_dir = MagicMock()
  860. mock_path = MagicMock()
  861. mock_path.exists.return_value = True
  862. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  863. results_new = await on_print_complete(
  864. printer_id=1,
  865. data={"status": "completed"},
  866. printer_manager=printer_manager,
  867. db=db,
  868. archive_id=20,
  869. )
  870. assert len(results_new) == 1
  871. assert results_new[0]["spool_id"] == 1
  872. assert results_new[0]["cost"] == 0.50 # 20g / 1000 * 25.0
  873. @pytest.mark.asyncio
  874. async def test_cost_with_print_name_ams_fallback(self):
  875. """Test cost aggregation using print_name (AMS fallback, legacy path)."""
  876. spool_old = _make_spool(spool_id=2, label_weight=1000, cost_per_kg=15.0)
  877. assignment_old = _make_assignment(spool_id=2, ams_id=0, tray_id=0)
  878. legacy_print_name = "LegacyPrint"
  879. _active_sessions[1] = PrintSession(
  880. printer_id=1,
  881. print_name=legacy_print_name,
  882. started_at=datetime.now(timezone.utc),
  883. tray_remain_start={(0, 0): 80},
  884. tray_now_at_start=0,
  885. )
  886. printer_manager = MagicMock()
  887. printer_manager.get_status.return_value = SimpleNamespace(
  888. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  889. progress=100,
  890. layer_num=50,
  891. tray_now=0,
  892. )
  893. # Pad 2 Nones for _find_3mf_by_filename DB queries (library + archive search),
  894. # then assignment and spool for the AMS fallback path
  895. db = _mock_db_sequential([None, None, assignment_old, spool_old])
  896. with (
  897. patch("backend.app.core.config.settings") as mock_settings,
  898. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"),
  899. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=None),
  900. ):
  901. mock_settings.base_dir = MagicMock()
  902. mock_path = MagicMock()
  903. mock_path.exists.return_value = True
  904. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  905. results_old = await on_print_complete(
  906. printer_id=1,
  907. data={"status": "completed", "subtask_name": legacy_print_name, "filename": legacy_print_name},
  908. printer_manager=printer_manager,
  909. db=db,
  910. archive_id=None,
  911. )
  912. assert len(results_old) == 1
  913. assert results_old[0]["spool_id"] == 2
  914. assert results_old[0]["cost"] == 1.5 # 100g / 1000 * 15.0