test_cost_tracking.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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. @pytest.mark.asyncio
  374. async def test_cost_with_ams_fallback_tracking(self):
  375. """AMS fallback tracking also calculates cost correctly."""
  376. spool = _make_spool(spool_id=2, label_weight=1000, cost_per_kg=30.0)
  377. assignment = _make_assignment(spool_id=2)
  378. _active_sessions[1] = PrintSession(
  379. printer_id=1,
  380. print_name="Test",
  381. started_at=datetime.now(timezone.utc),
  382. tray_remain_start={(0, 0): 80},
  383. )
  384. printer_manager = MagicMock()
  385. printer_manager.get_status.return_value = SimpleNamespace(
  386. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  387. tray_now=0,
  388. last_loaded_tray=-1,
  389. )
  390. # Pad 2 Nones for _find_3mf_by_filename DB queries (library + archive search),
  391. # then assignment and spool for the AMS fallback path
  392. db = _mock_db_sequential([None, None, assignment, spool])
  393. with patch("backend.app.api.routes.settings.get_setting", return_value="15.0"):
  394. results = await on_print_complete(
  395. printer_id=1,
  396. data={"status": "completed"},
  397. printer_manager=printer_manager,
  398. db=db,
  399. archive_id=None, # No archive = AMS fallback
  400. )
  401. assert len(results) == 1
  402. assert results[0]["spool_id"] == 2
  403. # 10% of 1000g = 100g
  404. assert results[0]["weight_used"] == 100.0
  405. # Cost = 100g / 1000 * 30.0 = 3.00
  406. assert results[0]["cost"] == 3.0
  407. @pytest.mark.asyncio
  408. async def test_multi_filament_cost_aggregation(self):
  409. """Multiple spools in one print have their costs tracked separately."""
  410. spool1 = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=20.0)
  411. spool2 = _make_spool(spool_id=2, label_weight=1000, cost_per_kg=25.0)
  412. assignment1 = _make_assignment(spool_id=1, ams_id=0, tray_id=0)
  413. assignment2 = _make_assignment(spool_id=2, ams_id=0, tray_id=1)
  414. archive = _make_archive(archive_id=10)
  415. _active_sessions[1] = PrintSession(
  416. printer_id=1,
  417. print_name="Test",
  418. started_at=datetime.now(timezone.utc),
  419. tray_remain_start={(0, 0): 80, (0, 1): 90},
  420. tray_now_at_start=0,
  421. )
  422. printer_manager = MagicMock()
  423. printer_manager.get_status.return_value = SimpleNamespace(
  424. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}, {"id": 1, "remain": 80}]}]},
  425. progress=100,
  426. layer_num=50,
  427. tray_now=0,
  428. )
  429. # Mock slot-to-tray mapping: slot 1 -> tray 0, slot 2 -> tray 1
  430. ams_mapping = [0, 1]
  431. # db returns: archive, assignment1, spool1, assignment2, spool2
  432. # db: archive, queue item for the plate (None), then assignments and
  433. # spools; the given ams_mapping skips only the mapping fallback
  434. db = _mock_db_sequential([archive, None, assignment1, spool1, assignment2, spool2])
  435. # Two filaments used
  436. filament_usage = [
  437. {"slot_id": 1, "used_g": 15.0, "type": "PLA", "color": "#FF0000"},
  438. {"slot_id": 2, "used_g": 25.0, "type": "PLA", "color": "#00FF00"},
  439. ]
  440. with (
  441. patch("backend.app.core.config.settings") as mock_settings,
  442. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"),
  443. patch(
  444. "backend.app.utils.threemf_tools.extract_filament_usage_from_3mf",
  445. return_value=filament_usage,
  446. ),
  447. ):
  448. mock_settings.base_dir = MagicMock()
  449. mock_path = MagicMock()
  450. mock_path.exists.return_value = True
  451. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  452. results = await on_print_complete(
  453. printer_id=1,
  454. data={"status": "completed"},
  455. printer_manager=printer_manager,
  456. db=db,
  457. archive_id=10,
  458. ams_mapping=ams_mapping,
  459. )
  460. assert len(results) == 2
  461. # First spool: 15g at 20/kg = 0.30
  462. spool1_result = next(r for r in results if r["spool_id"] == 1)
  463. assert spool1_result["weight_used"] == 15.0
  464. assert spool1_result["cost"] == 0.30
  465. # Second spool: 25g at 25/kg = 0.625, rounded to 0.62
  466. spool2_result = next(r for r in results if r["spool_id"] == 2)
  467. assert spool2_result["weight_used"] == 25.0
  468. assert spool2_result["cost"] == 0.62
  469. class TestCostAggregation:
  470. """Tests for cost aggregation to PrintArchive."""
  471. @pytest.mark.asyncio
  472. async def test_costs_summed_in_results(self):
  473. """Multiple spool costs are correctly summed from result dicts."""
  474. results = [
  475. {"spool_id": 1, "weight_used": 20.0, "cost": 0.50},
  476. {"spool_id": 2, "weight_used": 30.0, "cost": 0.75},
  477. ]
  478. total_cost = sum(r.get("cost", 0) or 0 for r in results)
  479. assert total_cost == 1.25
  480. @pytest.mark.asyncio
  481. async def test_null_costs_handled_in_aggregation(self):
  482. """None costs don't break aggregation."""
  483. results = [
  484. {"spool_id": 1, "weight_used": 20.0, "cost": 0.50},
  485. {"spool_id": 2, "weight_used": 30.0, "cost": None}, # No cost
  486. {"spool_id": 3, "weight_used": 10.0, "cost": 0.25},
  487. ]
  488. total_cost = sum(r.get("cost", 0) or 0 for r in results)
  489. assert total_cost == 0.75 # Only spools 1 and 3
  490. @pytest.mark.asyncio
  491. async def test_archive_cost_not_overwritten_with_zero(self):
  492. """archive.cost is preserved when no spool usage has cost data."""
  493. # Spool without cost_per_kg, default_filament_cost also 0 → cost=None per usage
  494. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=None)
  495. assignment = _make_assignment(spool_id=1)
  496. archive = _make_archive(archive_id=10)
  497. archive.cost = 5.00 # Pre-existing cost from catalog
  498. archive.print_name = "TestPrint"
  499. archive.printer_id = 1
  500. _active_sessions[1] = PrintSession(
  501. printer_id=1,
  502. print_name="TestPrint",
  503. started_at=datetime.now(timezone.utc),
  504. tray_remain_start={(0, 0): 80},
  505. tray_now_at_start=0,
  506. )
  507. printer_manager = MagicMock()
  508. printer_manager.get_status.return_value = SimpleNamespace(
  509. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  510. progress=100,
  511. layer_num=50,
  512. tray_now=0,
  513. )
  514. # Build mock db that returns proper scalars for the aggregation queries
  515. responses = []
  516. # 1. select(PrintArchive) → archive
  517. responses.append(("scalar_one_or_none", archive))
  518. # 2. select(PrintQueueItem) → None
  519. responses.append(("scalar_one_or_none", None))
  520. # 3. select(SpoolAssignment) → assignment
  521. responses.append(("scalar_one_or_none", assignment))
  522. # 4. select(Spool) → spool
  523. responses.append(("scalar_one_or_none", spool))
  524. # 5. cost aggregation: select archive to update cost
  525. responses.append(("scalar_one_or_none", archive))
  526. db = AsyncMock()
  527. call_count = [0]
  528. async def mock_execute(*args, **kwargs):
  529. idx = call_count[0]
  530. call_count[0] += 1
  531. result = MagicMock()
  532. if idx < len(responses):
  533. method, value = responses[idx]
  534. if method == "scalar":
  535. result.scalar.return_value = value
  536. result.scalar_one_or_none.return_value = value
  537. else:
  538. result.scalar_one_or_none.return_value = value
  539. result.scalar.return_value = value
  540. else:
  541. result.scalar_one_or_none.return_value = None
  542. result.scalar.return_value = None
  543. return result
  544. db.execute = mock_execute
  545. filament_usage = [{"slot_id": 1, "used_g": 10.0, "type": "PLA", "color": "#FF0000"}]
  546. with (
  547. patch("backend.app.core.config.settings") as mock_settings,
  548. patch("backend.app.api.routes.settings.get_setting", return_value="0.0"), # no default cost
  549. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=filament_usage),
  550. ):
  551. mock_settings.base_dir = MagicMock()
  552. mock_path = MagicMock()
  553. mock_path.exists.return_value = True
  554. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  555. results = await on_print_complete(
  556. printer_id=1,
  557. data={"status": "completed"},
  558. printer_manager=printer_manager,
  559. db=db,
  560. archive_id=10,
  561. )
  562. # Usage tracked but cost is None (no cost_per_kg, no default)
  563. assert len(results) == 1
  564. assert results[0]["cost"] is None
  565. # Archive cost should NOT have been overwritten — still 5.00
  566. assert archive.cost == 5.00
  567. @pytest.mark.asyncio
  568. async def test_archive_cost_set_when_spool_has_cost(self):
  569. """archive.cost is set from spool usage when cost data exists."""
  570. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=25.0)
  571. assignment = _make_assignment(spool_id=1)
  572. archive = _make_archive(archive_id=10)
  573. archive.cost = None # No pre-existing cost
  574. archive.print_name = "TestPrint"
  575. archive.printer_id = 1
  576. _active_sessions[1] = PrintSession(
  577. printer_id=1,
  578. print_name="TestPrint",
  579. started_at=datetime.now(timezone.utc),
  580. tray_remain_start={(0, 0): 80},
  581. tray_now_at_start=0,
  582. )
  583. printer_manager = MagicMock()
  584. printer_manager.get_status.return_value = SimpleNamespace(
  585. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  586. progress=100,
  587. layer_num=50,
  588. tray_now=0,
  589. )
  590. # 20g at 25/kg = 0.50
  591. expected_cost = 0.50
  592. responses = []
  593. responses.append(("scalar_one_or_none", archive))
  594. responses.append(("scalar_one_or_none", None)) # queue item
  595. responses.append(("scalar_one_or_none", assignment))
  596. responses.append(("scalar_one_or_none", spool))
  597. # cost aggregation: select archive to update cost
  598. responses.append(("scalar_one_or_none", archive))
  599. db = AsyncMock()
  600. call_count = [0]
  601. async def mock_execute(*args, **kwargs):
  602. idx = call_count[0]
  603. call_count[0] += 1
  604. result = MagicMock()
  605. if idx < len(responses):
  606. method, value = responses[idx]
  607. result.scalar.return_value = value
  608. result.scalar_one_or_none.return_value = value
  609. else:
  610. result.scalar_one_or_none.return_value = None
  611. result.scalar.return_value = None
  612. return result
  613. db.execute = mock_execute
  614. filament_usage = [{"slot_id": 1, "used_g": 20.0, "type": "PLA", "color": "#FF0000"}]
  615. with (
  616. patch("backend.app.core.config.settings") as mock_settings,
  617. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"),
  618. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=filament_usage),
  619. ):
  620. mock_settings.base_dir = MagicMock()
  621. mock_path = MagicMock()
  622. mock_path.exists.return_value = True
  623. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  624. results = await on_print_complete(
  625. printer_id=1,
  626. data={"status": "completed"},
  627. printer_manager=printer_manager,
  628. db=db,
  629. archive_id=10,
  630. )
  631. assert len(results) == 1
  632. assert results[0]["cost"] == expected_cost
  633. # Archive cost should have been updated
  634. assert archive.cost == expected_cost
  635. @pytest.mark.asyncio
  636. async def test_archive_cost_includes_untracked_filament_at_default_rate(self):
  637. """#1344: when only some AMS trays have inventory spools, the untracked
  638. filament weight is charged at the global default rate so the total
  639. archive cost still reflects the whole print."""
  640. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=10.0)
  641. assignment = _make_assignment(spool_id=1)
  642. archive = _make_archive(archive_id=10)
  643. archive.cost = None
  644. archive.print_name = "TestPrint"
  645. archive.printer_id = 1
  646. archive.filament_used_grams = 110.0 # whole-print weight from slicer
  647. _active_sessions[1] = PrintSession(
  648. printer_id=1,
  649. print_name="TestPrint",
  650. started_at=datetime.now(timezone.utc),
  651. tray_remain_start={(0, 0): 80},
  652. tray_now_at_start=0,
  653. )
  654. printer_manager = MagicMock()
  655. printer_manager.get_status.return_value = SimpleNamespace(
  656. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  657. progress=100,
  658. layer_num=50,
  659. tray_now=0,
  660. )
  661. responses = [
  662. ("scalar_one_or_none", archive),
  663. ("scalar_one_or_none", None), # queue item
  664. ("scalar_one_or_none", assignment),
  665. ("scalar_one_or_none", spool),
  666. ("scalar_one_or_none", archive), # cost-update select
  667. ]
  668. db = AsyncMock()
  669. call_count = [0]
  670. async def mock_execute(*args, **kwargs):
  671. idx = call_count[0]
  672. call_count[0] += 1
  673. result = MagicMock()
  674. if idx < len(responses):
  675. _, value = responses[idx]
  676. result.scalar.return_value = value
  677. result.scalar_one_or_none.return_value = value
  678. else:
  679. result.scalar_one_or_none.return_value = None
  680. result.scalar.return_value = None
  681. return result
  682. db.execute = mock_execute
  683. # 3MF reports a single slot using 10g, but archive.filament_used_grams
  684. # says the whole print was 110g -- the other 100g came from spools that
  685. # aren't in inventory.
  686. filament_usage = [{"slot_id": 1, "used_g": 10.0, "type": "PLA", "color": "#FF0000"}]
  687. with (
  688. patch("backend.app.core.config.settings") as mock_settings,
  689. patch("backend.app.api.routes.settings.get_setting", return_value="10.0"),
  690. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=filament_usage),
  691. ):
  692. mock_settings.base_dir = MagicMock()
  693. mock_path = MagicMock()
  694. mock_path.exists.return_value = True
  695. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  696. results = await on_print_complete(
  697. printer_id=1,
  698. data={"status": "completed"},
  699. printer_manager=printer_manager,
  700. db=db,
  701. archive_id=10,
  702. )
  703. # Tracked slot: 10g * $10/kg = $0.10
  704. assert len(results) == 1
  705. assert results[0]["cost"] == 0.10
  706. # Untracked: 110g - 10g = 100g at $10/kg default = $1.00
  707. # Archive total: $0.10 + $1.00 = $1.10 (was $0.01 pre-fix because only
  708. # the tracked slot's tiny share was kept)
  709. assert archive.cost == 1.10
  710. @pytest.mark.asyncio
  711. async def test_archive_cost_fully_tracked_unchanged_by_topup(self):
  712. """When every gram is covered by inventory spools, the default-rate
  713. top-up adds nothing -- the archive cost is just the sum of tracked
  714. costs, same as before #1344."""
  715. spool = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=25.0)
  716. assignment = _make_assignment(spool_id=1)
  717. archive = _make_archive(archive_id=10)
  718. archive.cost = None
  719. archive.print_name = "TestPrint"
  720. archive.printer_id = 1
  721. archive.filament_used_grams = 20.0 # exactly what the slot reports
  722. _active_sessions[1] = PrintSession(
  723. printer_id=1,
  724. print_name="TestPrint",
  725. started_at=datetime.now(timezone.utc),
  726. tray_remain_start={(0, 0): 80},
  727. tray_now_at_start=0,
  728. )
  729. printer_manager = MagicMock()
  730. printer_manager.get_status.return_value = SimpleNamespace(
  731. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  732. progress=100,
  733. layer_num=50,
  734. tray_now=0,
  735. )
  736. responses = [
  737. ("scalar_one_or_none", archive),
  738. ("scalar_one_or_none", None),
  739. ("scalar_one_or_none", assignment),
  740. ("scalar_one_or_none", spool),
  741. ("scalar_one_or_none", archive),
  742. ]
  743. db = AsyncMock()
  744. call_count = [0]
  745. async def mock_execute(*args, **kwargs):
  746. idx = call_count[0]
  747. call_count[0] += 1
  748. result = MagicMock()
  749. if idx < len(responses):
  750. _, value = responses[idx]
  751. result.scalar.return_value = value
  752. result.scalar_one_or_none.return_value = value
  753. else:
  754. result.scalar_one_or_none.return_value = None
  755. result.scalar.return_value = None
  756. return result
  757. db.execute = mock_execute
  758. filament_usage = [{"slot_id": 1, "used_g": 20.0, "type": "PLA", "color": "#FF0000"}]
  759. with (
  760. patch("backend.app.core.config.settings") as mock_settings,
  761. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"),
  762. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=filament_usage),
  763. ):
  764. mock_settings.base_dir = MagicMock()
  765. mock_path = MagicMock()
  766. mock_path.exists.return_value = True
  767. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  768. results = await on_print_complete(
  769. printer_id=1,
  770. data={"status": "completed"},
  771. printer_manager=printer_manager,
  772. db=db,
  773. archive_id=10,
  774. )
  775. # 20g at $25/kg = $0.50 -- no top-up because tracked >= archive grams
  776. assert len(results) == 1
  777. assert results[0]["cost"] == 0.50
  778. assert archive.cost == 0.50
  779. @pytest.mark.asyncio
  780. async def test_cost_with_archive_id(self):
  781. """Test cost aggregation using archive_id (3MF path)."""
  782. spool_new = _make_spool(spool_id=1, label_weight=1000, cost_per_kg=25.0)
  783. assignment_new = _make_assignment(spool_id=1)
  784. archive_new = _make_archive(archive_id=20)
  785. filament_usage_new = [{"slot_id": 1, "used_g": 20.0, "type": "PLA", "color": "#FF0000"}]
  786. printer_manager = MagicMock()
  787. printer_manager.get_status.return_value = SimpleNamespace(
  788. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  789. progress=100,
  790. layer_num=50,
  791. tray_now=0,
  792. )
  793. db = _mock_db_sequential([archive_new, None, assignment_new, spool_new])
  794. with (
  795. patch("backend.app.core.config.settings") as mock_settings,
  796. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"),
  797. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=filament_usage_new),
  798. ):
  799. mock_settings.base_dir = MagicMock()
  800. mock_path = MagicMock()
  801. mock_path.exists.return_value = True
  802. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  803. results_new = await on_print_complete(
  804. printer_id=1,
  805. data={"status": "completed"},
  806. printer_manager=printer_manager,
  807. db=db,
  808. archive_id=20,
  809. )
  810. assert len(results_new) == 1
  811. assert results_new[0]["spool_id"] == 1
  812. assert results_new[0]["cost"] == 0.50 # 20g / 1000 * 25.0
  813. @pytest.mark.asyncio
  814. async def test_cost_with_print_name_ams_fallback(self):
  815. """Test cost aggregation using print_name (AMS fallback, legacy path)."""
  816. spool_old = _make_spool(spool_id=2, label_weight=1000, cost_per_kg=15.0)
  817. assignment_old = _make_assignment(spool_id=2, ams_id=0, tray_id=0)
  818. legacy_print_name = "LegacyPrint"
  819. _active_sessions[1] = PrintSession(
  820. printer_id=1,
  821. print_name=legacy_print_name,
  822. started_at=datetime.now(timezone.utc),
  823. tray_remain_start={(0, 0): 80},
  824. tray_now_at_start=0,
  825. )
  826. printer_manager = MagicMock()
  827. printer_manager.get_status.return_value = SimpleNamespace(
  828. raw_data={"ams": [{"id": 0, "tray": [{"id": 0, "remain": 70}]}]},
  829. progress=100,
  830. layer_num=50,
  831. tray_now=0,
  832. )
  833. # Pad 2 Nones for _find_3mf_by_filename DB queries (library + archive search),
  834. # then assignment and spool for the AMS fallback path
  835. db = _mock_db_sequential([None, None, assignment_old, spool_old])
  836. with (
  837. patch("backend.app.core.config.settings") as mock_settings,
  838. patch("backend.app.api.routes.settings.get_setting", return_value="15.0"),
  839. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=None),
  840. ):
  841. mock_settings.base_dir = MagicMock()
  842. mock_path = MagicMock()
  843. mock_path.exists.return_value = True
  844. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  845. results_old = await on_print_complete(
  846. printer_id=1,
  847. data={"status": "completed", "subtask_name": legacy_print_name, "filename": legacy_print_name},
  848. printer_manager=printer_manager,
  849. db=db,
  850. archive_id=None,
  851. )
  852. assert len(results_old) == 1
  853. assert results_old[0]["spool_id"] == 2
  854. assert results_old[0]["cost"] == 1.5 # 100g / 1000 * 15.0