test_inventory_csv.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. """Integration tests for inventory CSV import/export (#1576).
  2. Covers the export → import round-trip, dry-run preview (no writes), real
  3. import (only valid rows persisted, atomically), and Color Catalog resolution
  4. of brand + color_name → rgba.
  5. """
  6. import pytest
  7. from httpx import AsyncClient
  8. from sqlalchemy import select
  9. from sqlalchemy.ext.asyncio import AsyncSession
  10. from backend.app.models.color_catalog import ColorCatalogEntry
  11. from backend.app.models.spool import Spool
  12. def _csv_upload(text: str):
  13. """Build the multipart `files=` payload for the import endpoint."""
  14. return {"file": ("inventory.csv", text.encode("utf-8"), "text/csv")}
  15. @pytest.mark.asyncio
  16. @pytest.mark.integration
  17. class TestInventoryCsvExport:
  18. async def test_export_returns_csv_with_header_and_rows(self, async_client: AsyncClient, db_session: AsyncSession):
  19. db_session.add(
  20. Spool(material="PLA", brand="Polymaker", color_name="Jade White", rgba="e8e8e8ff", label_weight=1000)
  21. )
  22. await db_session.commit()
  23. response = await async_client.get("/api/v1/inventory/spools/export")
  24. assert response.status_code == 200, response.text
  25. assert response.headers["content-type"].startswith("text/csv")
  26. body = response.text
  27. lines = body.strip().splitlines()
  28. # Header row uses the fixed schema.
  29. assert lines[0].split(",")[:2] == ["id", "material"]
  30. assert "rgba" in lines[0]
  31. # Data row present, rgba written without leading '#'.
  32. assert "Polymaker" in body
  33. assert "e8e8e8ff" in body
  34. assert "#e8e8e8ff" not in body
  35. async def test_export_excludes_archived(self, async_client: AsyncClient, db_session: AsyncSession):
  36. from datetime import datetime, timezone
  37. db_session.add(Spool(material="PLA", brand="Active", color_name="A", rgba="ffffffff"))
  38. db_session.add(
  39. Spool(
  40. material="PETG",
  41. brand="Archived",
  42. color_name="B",
  43. rgba="000000ff",
  44. archived_at=datetime.now(timezone.utc),
  45. )
  46. )
  47. await db_session.commit()
  48. response = await async_client.get("/api/v1/inventory/spools/export")
  49. assert response.status_code == 200, response.text
  50. assert "Active" in response.text
  51. assert "Archived" not in response.text
  52. @pytest.mark.asyncio
  53. @pytest.mark.integration
  54. class TestInventoryCsvImportDryRun:
  55. async def test_dry_run_classifies_rows_and_writes_nothing(
  56. self, async_client: AsyncClient, db_session: AsyncSession
  57. ):
  58. csv_text = (
  59. "material,brand,color_name,rgba,label_weight\n"
  60. "PLA,Polymaker,Jade White,e8e8e8ff,1000\n" # valid
  61. ",Polymaker,No Material,ffffffff,1000\n" # error: material missing
  62. "PETG,Brand,Bad Hex,zzzz,1000\n" # error: invalid rgba
  63. "\n" # skipped: blank
  64. "ABS,Brand,Color,#00ff00,500\n" # valid: 6-char + '#' tolerated
  65. )
  66. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  67. assert response.status_code == 200, response.text
  68. data = response.json()
  69. assert data["valid_count"] == 2
  70. assert data["error_count"] == 2
  71. assert data["skipped_count"] == 1
  72. # 6-char hex got normalised to 8-char.
  73. valid_rows = [r for r in data["rows"] if r["status"] == "valid"]
  74. green = next(r for r in valid_rows if r["color_name"] == "Color")
  75. assert green["rgba"] == "00ff00ff"
  76. # Nothing was written.
  77. result = await db_session.execute(select(Spool))
  78. assert result.scalars().first() is None
  79. async def test_missing_material_column_fails_whole_file(self, async_client: AsyncClient):
  80. csv_text = "brand,color_name\nPolymaker,Jade White\n"
  81. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  82. assert response.status_code == 200, response.text
  83. data = response.json()
  84. assert data["valid_count"] == 0
  85. assert any("material" in w for w in data["warnings"])
  86. @pytest.mark.asyncio
  87. @pytest.mark.integration
  88. class TestInventoryCsvImportReal:
  89. async def test_import_persists_only_valid_rows(self, async_client: AsyncClient, db_session: AsyncSession):
  90. csv_text = (
  91. "material,brand,color_name,rgba\n"
  92. "PLA,Polymaker,White,ffffffff\n" # valid
  93. ",Polymaker,No Material,ffffffff\n" # error
  94. "PETG,Brand,Color,ff0000ff\n" # valid
  95. )
  96. response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  97. assert response.status_code == 200, response.text
  98. data = response.json()
  99. assert data["created"] == 2
  100. assert data["errors"] == 1
  101. assert len(data["error_rows"]) == 1
  102. result = await db_session.execute(select(Spool).order_by(Spool.material))
  103. spools = result.scalars().all()
  104. assert len(spools) == 2
  105. assert {s.material for s in spools} == {"PLA", "PETG"}
  106. async def test_case_and_space_tolerant_headers(self, async_client: AsyncClient, db_session: AsyncSession):
  107. csv_text = "Material, Color Name ,RGBA\nPLA,Snow,ffffffff\n"
  108. response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  109. assert response.status_code == 200, response.text
  110. assert response.json()["created"] == 1
  111. result = await db_session.execute(select(Spool))
  112. spool = result.scalars().one()
  113. assert spool.color_name == "Snow"
  114. async def test_semicolon_file_with_decimal_commas(self, async_client: AsyncClient, db_session: AsyncSession):
  115. # What Excel saves as CSV in a comma-decimal locale (de, fr, nl, ...).
  116. csv_text = "material;brand;color_name;label_weight;cost_per_kg\r\nPLA;Polymaker;Jade White;1000;24,99\r\n"
  117. response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  118. assert response.status_code == 200, response.text
  119. assert response.json()["created"] == 1
  120. result = await db_session.execute(select(Spool))
  121. spool = result.scalars().one()
  122. assert (spool.brand, spool.color_name, spool.label_weight) == ("Polymaker", "Jade White", 1000)
  123. assert spool.cost_per_kg == 24.99
  124. @pytest.mark.asyncio
  125. @pytest.mark.integration
  126. class TestInventoryCsvColorResolution:
  127. async def test_brand_and_color_resolve_rgba_from_catalog(self, async_client: AsyncClient, db_session: AsyncSession):
  128. db_session.add(
  129. ColorCatalogEntry(
  130. manufacturer="Polymaker",
  131. color_name="Jade White",
  132. hex_color="#E8E8E8",
  133. material="PLA",
  134. is_default=False,
  135. )
  136. )
  137. await db_session.commit()
  138. # No rgba in CSV — resolved from catalog (case-insensitive match).
  139. csv_text = "material,brand,color_name\nPLA,polymaker,jade white\n"
  140. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  141. assert response.status_code == 200, response.text
  142. data = response.json()
  143. assert data["valid_count"] == 1
  144. row = data["rows"][0]
  145. assert row["resolved_color"] is True
  146. assert row["rgba"] == "e8e8e8ff"
  147. async def test_explicit_rgba_wins_over_catalog(self, async_client: AsyncClient, db_session: AsyncSession):
  148. db_session.add(
  149. ColorCatalogEntry(manufacturer="Polymaker", color_name="Jade White", hex_color="#E8E8E8", material="PLA")
  150. )
  151. await db_session.commit()
  152. csv_text = "material,brand,color_name,rgba\nPLA,Polymaker,Jade White,123456ff\n"
  153. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  154. assert response.status_code == 200, response.text
  155. row = response.json()["rows"][0]
  156. assert row["rgba"] == "123456ff"
  157. assert row["resolved_color"] is False
  158. async def test_cross_material_fallback_is_flagged(self, async_client: AsyncClient, db_session: AsyncSession):
  159. # Catalog only has a PLA variant of this colour; a PETG row resolves it
  160. # via cross-material fallback and must be flagged.
  161. db_session.add(
  162. ColorCatalogEntry(manufacturer="Polymaker", color_name="Jade White", hex_color="#E8E8E8", material="PLA")
  163. )
  164. await db_session.commit()
  165. csv_text = "material,brand,color_name\nPETG,Polymaker,Jade White\n"
  166. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  167. assert response.status_code == 200, response.text
  168. row = response.json()["rows"][0]
  169. assert row["resolved_color"] is True
  170. assert row["cross_material_color"] is True
  171. assert row["rgba"] == "e8e8e8ff"
  172. async def test_exact_material_match_not_flagged(self, async_client: AsyncClient, db_session: AsyncSession):
  173. db_session.add(
  174. ColorCatalogEntry(manufacturer="Polymaker", color_name="Jade White", hex_color="#E8E8E8", material="PETG")
  175. )
  176. await db_session.commit()
  177. csv_text = "material,brand,color_name\nPETG,Polymaker,Jade White\n"
  178. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  179. assert response.status_code == 200, response.text
  180. row = response.json()["rows"][0]
  181. assert row["resolved_color"] is True
  182. assert row["cross_material_color"] is False
  183. async def test_generic_material_catalog_entry_not_flagged(
  184. self, async_client: AsyncClient, db_session: AsyncSession
  185. ):
  186. # A NULL-material catalog entry is the project's "matches any material"
  187. # convention — resolving a PLA row from it is an exact match, not a
  188. # cross-material fallback, so it must not raise the yellow warning.
  189. db_session.add(
  190. ColorCatalogEntry(manufacturer="Polymaker", color_name="Jade White", hex_color="#E8E8E8", material=None)
  191. )
  192. await db_session.commit()
  193. csv_text = "material,brand,color_name\nPLA,Polymaker,Jade White\n"
  194. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  195. assert response.status_code == 200, response.text
  196. row = response.json()["rows"][0]
  197. assert row["resolved_color"] is True
  198. assert row["cross_material_color"] is False
  199. assert row["rgba"] == "e8e8e8ff"
  200. @pytest.mark.asyncio
  201. @pytest.mark.integration
  202. class TestInventoryCsvReviewFollowups:
  203. """Covers the maintainer-requested hardening (PR #1659 review)."""
  204. async def test_oversized_upload_rejected_413(self, async_client: AsyncClient):
  205. # Build a body just over the 5 MB cap.
  206. from backend.app.services.spool_csv import MAX_CSV_IMPORT_BYTES
  207. header = "material\n"
  208. filler = "PLA\n" * ((MAX_CSV_IMPORT_BYTES // 4) + 10)
  209. big = header + filler
  210. response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(big))
  211. assert response.status_code == 413, response.text
  212. detail = response.json()["detail"]
  213. assert detail["code"] == "csv_import_too_large"
  214. async def test_weight_used_negative_is_error(self, async_client: AsyncClient):
  215. csv_text = "material,color_name,rgba,weight_used\nPLA,X,ffffffff,-5\n"
  216. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  217. assert response.status_code == 200, response.text
  218. data = response.json()
  219. assert data["error_count"] == 1
  220. assert "weight_used" in data["rows"][0]["reason"]
  221. async def test_weight_used_exceeds_label_is_error(self, async_client: AsyncClient):
  222. csv_text = "material,color_name,rgba,label_weight,weight_used\nPLA,X,ffffffff,1000,1500\n"
  223. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  224. assert response.status_code == 200, response.text
  225. data = response.json()
  226. assert data["error_count"] == 1
  227. assert "exceeds" in data["rows"][0]["reason"]
  228. async def test_export_neutralises_formula_injection(self, async_client: AsyncClient, db_session: AsyncSession):
  229. # A note starting with '=' must be prefixed with a quote on export so
  230. # spreadsheets don't evaluate it as a formula.
  231. db_session.add(Spool(material="PLA", color_name="X", rgba="ffffffff", note="=SUM(A1:A9)"))
  232. await db_session.commit()
  233. response = await async_client.get("/api/v1/inventory/spools/export")
  234. assert response.status_code == 200, response.text
  235. assert "'=SUM(A1:A9)" in response.text
  236. async def test_formula_injection_round_trips_without_quote_accumulation(
  237. self, async_client: AsyncClient, db_session: AsyncSession
  238. ):
  239. # The export quote-guard must be undone on import so a formula-looking
  240. # note survives export → import unchanged (no accumulating leading ').
  241. db_session.add(Spool(material="PLA", color_name="X", rgba="ffffffff", note="=SUM(A1)"))
  242. await db_session.commit()
  243. export = await async_client.get("/api/v1/inventory/spools/export")
  244. assert export.status_code == 200, export.text
  245. assert "'=SUM(A1)" in export.text # guarded on export
  246. # Wipe, re-import the exact export, and confirm the note is restored
  247. # to its original value (not "'=SUM(A1)").
  248. existing = await db_session.execute(select(Spool))
  249. for spool in existing.scalars().all():
  250. await db_session.delete(spool)
  251. await db_session.commit()
  252. response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(export.text))
  253. assert response.status_code == 200, response.text
  254. assert response.json()["created"] == 1
  255. result = await db_session.execute(select(Spool))
  256. spool = result.scalars().one()
  257. assert spool.note == "=SUM(A1)" # original value, no leading quote
  258. async def test_export_filename_is_date_stamped(self, async_client: AsyncClient):
  259. response = await async_client.get("/api/v1/inventory/spools/export")
  260. assert response.status_code == 200, response.text
  261. disposition = response.headers.get("content-disposition", "")
  262. assert "bambuddy_inventory_" in disposition
  263. assert disposition.rstrip('"').endswith(".csv")
  264. @pytest.mark.asyncio
  265. @pytest.mark.integration
  266. class TestInventoryCsvRoundTrip:
  267. async def test_export_then_import_recreates_spools(self, async_client: AsyncClient, db_session: AsyncSession):
  268. db_session.add(
  269. Spool(
  270. material="PLA",
  271. brand="Polymaker",
  272. subtype="Matte",
  273. color_name="Jade White",
  274. rgba="e8e8e8ff",
  275. label_weight=1000,
  276. weight_used=250,
  277. cost_per_kg=24.99,
  278. note="batch order",
  279. )
  280. )
  281. await db_session.commit()
  282. export = await async_client.get("/api/v1/inventory/spools/export")
  283. assert export.status_code == 200, export.text
  284. csv_text = export.text
  285. # Wipe and re-import the exact export.
  286. existing = await db_session.execute(select(Spool))
  287. for spool in existing.scalars().all():
  288. await db_session.delete(spool)
  289. await db_session.commit()
  290. response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  291. assert response.status_code == 200, response.text
  292. assert response.json()["created"] == 1
  293. result = await db_session.execute(select(Spool))
  294. spool = result.scalars().one()
  295. assert spool.material == "PLA"
  296. assert spool.brand == "Polymaker"
  297. assert spool.subtype == "Matte"
  298. assert spool.color_name == "Jade White"
  299. assert spool.rgba == "e8e8e8ff"
  300. assert spool.label_weight == 1000
  301. assert spool.weight_used == 250 # usage round-trips
  302. assert spool.cost_per_kg == 24.99
  303. assert spool.note == "batch order"
  304. @pytest.mark.asyncio
  305. @pytest.mark.integration
  306. class TestInventoryCsvUsageColumns:
  307. async def test_export_writes_weight_used_and_derived_remaining(
  308. self, async_client: AsyncClient, db_session: AsyncSession
  309. ):
  310. from datetime import datetime, timezone
  311. db_session.add(
  312. Spool(
  313. material="PLA",
  314. brand="Polymaker",
  315. color_name="White",
  316. rgba="ffffffff",
  317. label_weight=1000,
  318. weight_used=300,
  319. last_used=datetime(2026, 6, 1, 12, 30, tzinfo=timezone.utc),
  320. )
  321. )
  322. await db_session.commit()
  323. response = await async_client.get("/api/v1/inventory/spools/export")
  324. assert response.status_code == 200, response.text
  325. header, row = response.text.strip().splitlines()[:2]
  326. cols = header.split(",")
  327. cells = row.split(",")
  328. record = dict(zip(cols, cells, strict=False))
  329. assert record["weight_used"] == "300"
  330. assert record["remaining"] == "700" # 1000 - 300, derived
  331. assert record["last_used"].startswith("2026-06-01T12:30")
  332. async def test_import_reads_weight_used_ignores_remaining(
  333. self, async_client: AsyncClient, db_session: AsyncSession
  334. ):
  335. # remaining is intentionally contradictory — it must be ignored; only
  336. # weight_used is read back.
  337. csv_text = (
  338. "material,brand,color_name,rgba,label_weight,weight_used,remaining\nPLA,Brand,White,ffffffff,1000,400,999\n"
  339. )
  340. response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  341. assert response.status_code == 200, response.text
  342. assert response.json()["created"] == 1
  343. result = await db_session.execute(select(Spool))
  344. spool = result.scalars().one()
  345. assert spool.weight_used == 400 # from CSV
  346. assert spool.label_weight == 1000 # remaining=999 ignored, not used to back-compute
  347. async def test_import_parses_last_used_iso(self, async_client: AsyncClient, db_session: AsyncSession):
  348. csv_text = "material,color_name,rgba,last_used\nPLA,White,ffffffff,2026-06-01T12:30:00+00:00\n"
  349. response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  350. assert response.status_code == 200, response.text
  351. assert response.json()["created"] == 1
  352. result = await db_session.execute(select(Spool))
  353. spool = result.scalars().one()
  354. assert spool.last_used is not None
  355. assert spool.last_used.year == 2026 and spool.last_used.month == 6 and spool.last_used.day == 1
  356. @pytest.mark.parametrize(
  357. ("written", "stored"),
  358. [("2026-10-01T10:00:00+02:00", "2026-10-01 08:00:00"), ("2026-10-01T10:00:00", "2026-10-01 10:00:00")],
  359. )
  360. async def test_import_stores_last_used_in_utc(
  361. self, async_client: AsyncClient, db_session: AsyncSession, written, stored
  362. ):
  363. """LU-1: an offset was dropped on SQLite, keeping the wall time. A time
  364. without one is UTC, as export writes it."""
  365. csv_text = f"material,color_name,rgba,last_used\nPLA,White,ffffffff,{written}\n"
  366. response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  367. assert response.status_code == 200, response.text
  368. spool = (await db_session.execute(select(Spool))).scalars().one()
  369. assert str(spool.last_used.replace(tzinfo=None)) == stored
  370. async def test_import_rejects_bad_last_used(self, async_client: AsyncClient):
  371. csv_text = "material,color_name,rgba,last_used\nPLA,White,ffffffff,not-a-date\n"
  372. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  373. assert response.status_code == 200, response.text
  374. data = response.json()
  375. assert data["error_count"] == 1
  376. assert "last_used" in data["rows"][0]["reason"]
  377. @pytest.mark.asyncio
  378. @pytest.mark.integration
  379. class TestInventoryCsvExtraColumns:
  380. async def test_storage_category_threshold_round_trip(self, async_client: AsyncClient, db_session: AsyncSession):
  381. # storage_location / category / low_stock_threshold_pct must survive an
  382. # export → import cycle (would otherwise be silently lost).
  383. db_session.add(
  384. Spool(
  385. material="PLA",
  386. brand="Polymaker",
  387. color_name="White",
  388. rgba="ffffffff",
  389. storage_location="Shelf B3",
  390. category="Production",
  391. low_stock_threshold_pct=20,
  392. )
  393. )
  394. await db_session.commit()
  395. csv_text = (await async_client.get("/api/v1/inventory/spools/export")).text
  396. for spool in (await db_session.execute(select(Spool))).scalars().all():
  397. await db_session.delete(spool)
  398. await db_session.commit()
  399. response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  400. assert response.status_code == 200, response.text
  401. assert response.json()["created"] == 1
  402. spool = (await db_session.execute(select(Spool))).scalars().one()
  403. assert spool.storage_location == "Shelf B3"
  404. assert spool.category == "Production"
  405. assert spool.low_stock_threshold_pct == 20
  406. async def test_low_stock_threshold_out_of_range_is_error(self, async_client: AsyncClient):
  407. # SpoolCreate bounds low_stock_threshold_pct to 1..99; the CSV path must
  408. # reject an out-of-range value rather than persist it.
  409. csv_text = "material,color_name,rgba,low_stock_threshold_pct\nPLA,White,ffffffff,150\n"
  410. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  411. assert response.status_code == 200, response.text
  412. data = response.json()
  413. assert data["error_count"] == 1
  414. assert "low_stock_threshold_pct" in data["rows"][0]["reason"]
  415. @pytest.mark.asyncio
  416. @pytest.mark.integration
  417. class TestInventoryCsvDuplicateWarning:
  418. async def test_existing_spool_flags_duplicate_but_still_imports(
  419. self, async_client: AsyncClient, db_session: AsyncSession
  420. ):
  421. db_session.add(Spool(material="PLA", brand="Polymaker", color_name="Jade White", rgba="e8e8e8ff"))
  422. await db_session.commit()
  423. # Row 1 matches the existing spool (case-insensitively); row 2 is new.
  424. csv_text = (
  425. "material,brand,color_name,rgba\n"
  426. "pla,polymaker,jade white,e8e8e8ff\n" # duplicate of existing
  427. "PETG,OtherBrand,Black,000000ff\n" # new
  428. )
  429. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  430. assert response.status_code == 200, response.text
  431. rows = response.json()["rows"]
  432. assert rows[0]["duplicate_of_existing"] is True
  433. assert rows[1]["duplicate_of_existing"] is False
  434. # Soft-warn only: a real import still creates the duplicate row.
  435. real = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  436. assert real.json()["created"] == 2
  437. all_spools = (await db_session.execute(select(Spool))).scalars().all()
  438. assert len(all_spools) == 3 # 1 pre-existing + 2 imported
  439. @pytest.mark.asyncio
  440. @pytest.mark.integration
  441. class TestInventoryCsvKeepsIds:
  442. """A moved inventory keeps its spool ids: printed labels' QR codes carry them (#3520)."""
  443. async def _base(self, db_session: AsyncSession) -> int:
  444. from backend.app.services.spool_csv import highest_spool_id_given_out
  445. return await highest_spool_id_given_out(db_session)
  446. async def _ids_by_color(self, db_session: AsyncSession) -> dict[str, int]:
  447. db_session.expire_all()
  448. rows = (await db_session.execute(select(Spool))).scalars().all()
  449. return {s.color_name: s.id for s in rows}
  450. async def test_export_writes_the_id(self, async_client: AsyncClient, db_session: AsyncSession):
  451. spool = Spool(material="PLA", brand="B", color_name="Red", rgba="ff0000ff")
  452. db_session.add(spool)
  453. await db_session.commit()
  454. response = await async_client.get("/api/v1/inventory/spools/export")
  455. header, row = response.text.strip().splitlines()[:2]
  456. assert header.split(",")[0] == "id"
  457. assert row.split(",")[0] == str(spool.id)
  458. async def test_import_keeps_ids_and_their_gaps(self, async_client: AsyncClient, db_session: AsyncSession):
  459. base = await self._base(db_session)
  460. # Out of order, with gaps, and a row without an id ahead of them: it
  461. # must not take an id a later row still needs.
  462. csv_text = f"id,material,color_name\n,PLA,New\n{base + 5},PLA,Five\n{base + 1},PETG,One\n{base + 3},PLA,Three\n"
  463. response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  464. assert response.status_code == 200, response.text
  465. assert response.json()["created"] == 4
  466. ids = await self._ids_by_color(db_session)
  467. assert ids["Five"] == base + 5
  468. assert ids["One"] == base + 1
  469. assert ids["Three"] == base + 3
  470. assert ids["New"] == base + 6
  471. async def test_the_next_spool_continues_after_the_kept_ids(
  472. self, async_client: AsyncClient, db_session: AsyncSession
  473. ):
  474. """Only kept ids in the file: the next spool still gets a fresh id (PostgreSQL's sequence)."""
  475. base = await self._base(db_session)
  476. csv_text = f"id,material,color_name\n{base + 4},PLA,Four\n"
  477. await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  478. response = await async_client.post("/api/v1/inventory/spools", json={"material": "PLA", "color_name": "Later"})
  479. assert response.status_code == 200, response.text
  480. assert response.json()["id"] == base + 5
  481. async def test_dry_run_shows_the_id_each_spool_keeps(self, async_client: AsyncClient, db_session: AsyncSession):
  482. base = await self._base(db_session)
  483. csv_text = f"id,material\n{base + 2},PLA\n,PETG\n"
  484. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  485. rows = response.json()["rows"]
  486. assert [r["keeps_id"] for r in rows] == [base + 2, None]
  487. assert response.json()["warnings"] == []
  488. async def test_an_id_in_use_gets_a_new_one(self, async_client: AsyncClient, db_session: AsyncSession):
  489. existing = Spool(material="PLA", color_name="Existing")
  490. db_session.add(existing)
  491. await db_session.commit()
  492. csv_text = f"id,material,color_name\n{existing.id},PETG,Imported\n"
  493. preview = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  494. await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  495. assert preview.json()["rows"][0]["keeps_id"] is None
  496. assert any("1 spool(s) get a new id" in w for w in preview.json()["warnings"])
  497. ids = await self._ids_by_color(db_session)
  498. assert ids["Existing"] == existing.id
  499. assert ids["Imported"] > existing.id
  500. async def test_a_deleted_spools_id_is_not_reused(self, async_client: AsyncClient, db_session: AsyncSession):
  501. """Old print logs and usage records may still name it."""
  502. gone = Spool(material="PLA", color_name="Gone")
  503. db_session.add(gone)
  504. await db_session.commit()
  505. gone_id = gone.id
  506. await db_session.delete(gone)
  507. await db_session.commit()
  508. csv_text = f"id,material,color_name\n{gone_id},PLA,Imported\n"
  509. await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  510. assert (await self._ids_by_color(db_session))["Imported"] > gone_id
  511. async def test_an_id_named_twice_is_kept_once(self, async_client: AsyncClient, db_session: AsyncSession):
  512. base = await self._base(db_session)
  513. csv_text = f"id,material,color_name\n{base + 2},PLA,First\n{base + 2},PLA,Second\n"
  514. response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
  515. assert response.json()["created"] == 2
  516. ids = await self._ids_by_color(db_session)
  517. assert ids["First"] == base + 2
  518. assert ids["Second"] == base + 3
  519. @pytest.mark.parametrize("bad", ["abc", "0", "-3", "1.5"])
  520. async def test_a_bad_id_is_a_row_error(self, async_client: AsyncClient, bad: str):
  521. csv_text = f"id,material\n{bad},PLA\n"
  522. response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
  523. row = response.json()["rows"][0]
  524. assert row["status"] == "error"
  525. assert "id must be a positive whole number" in row["reason"]
  526. async def test_a_csv_without_an_id_column_still_imports(self, async_client: AsyncClient, db_session: AsyncSession):
  527. response = await async_client.post(
  528. "/api/v1/inventory/spools/import", files=_csv_upload("material,color_name\nPLA,Plain\n")
  529. )
  530. assert response.json()["created"] == 1
  531. assert response.json()["errors"] == 0