spool_csv.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. """CSV import/export for the spool inventory (#1576).
  2. One module owns the round-trip: the same fixed column schema is used to
  3. serialise existing spools out and to parse + validate a user-supplied CSV
  4. back in. Validation reuses the `SpoolCreate` Pydantic model so the CSV path
  5. and the form path share a single source of truth — anything the form rejects,
  6. the import rejects too, with the same rules.
  7. The import flow is two-phase by design: `parse_and_validate()` never writes.
  8. The route calls it once for the dry-run preview (so the user sees per-row
  9. valid/error/skipped before committing) and again on confirm, then persists
  10. only the rows that came back `valid`.
  11. """
  12. import csv
  13. import io
  14. from datetime import datetime
  15. from pydantic import BaseModel, ValidationError
  16. from sqlalchemy import select
  17. from sqlalchemy.ext.asyncio import AsyncSession
  18. from backend.app.models.color_catalog import ColorCatalogEntry
  19. from backend.app.models.spool import Spool
  20. from backend.app.schemas.spool import SpoolCreate
  21. # Fixed CSV header, in output order. Round-trips cleanly: export writes these
  22. # columns, import expects them. `material` is the only required field; the rest
  23. # are optional. Keep aligned with the SpoolCreate fields referenced below.
  24. #
  25. # `remaining` is a derived, export-only column (= label_weight - weight_used).
  26. # It's written out for human readability and round-trip clarity, but ignored on
  27. # import — `weight_used` is the source of truth, and accepting both would let
  28. # them contradict. `last_used` is a timestamp the model carries but SpoolCreate
  29. # does not, so import applies it to the ORM object directly (see persist path).
  30. # `storage_location`, `category` and `low_stock_threshold_pct` are SpoolCreate
  31. # fields included so a round-trip preserves them (they'd otherwise be lost).
  32. CSV_COLUMNS = [
  33. "material",
  34. "brand",
  35. "subtype",
  36. "color_name",
  37. "rgba",
  38. "extra_colors",
  39. "effect_type",
  40. "label_weight",
  41. "weight_used",
  42. "remaining",
  43. "cost_per_kg",
  44. "nozzle_temp_min",
  45. "nozzle_temp_max",
  46. "last_used",
  47. "note",
  48. "storage_location",
  49. "category",
  50. "low_stock_threshold_pct",
  51. ]
  52. # Upload ceiling for the import endpoint. A spool inventory CSV is a few KB
  53. # even with thousands of rows; 5 MB is a generous cap that still refuses an
  54. # OOM-sized body before it's read into memory.
  55. MAX_CSV_IMPORT_BYTES = 5 * 1024 * 1024
  56. # Spreadsheet formula-injection guard. A cell whose first character is one of
  57. # these is treated as a formula by Excel / LibreOffice / Sheets; we prefix it
  58. # with a single quote on export so the value renders as literal text.
  59. _FORMULA_INJECTION_PREFIXES = ("=", "+", "-", "@", "\t", "\r")
  60. # Columns whose CSV cell must be coerced to a number before SpoolCreate sees it.
  61. # DictReader hands us strings; SpoolCreate wants int/float. Empty cell → omit
  62. # the field (falls back to the schema default / None).
  63. _INT_COLUMNS = {"label_weight", "nozzle_temp_min", "nozzle_temp_max", "low_stock_threshold_pct"}
  64. _FLOAT_COLUMNS = {"cost_per_kg", "weight_used"}
  65. # label_weight default, pulled from the schema so the weight_used bounds check
  66. # stays in sync if the schema default ever changes.
  67. _DEFAULT_LABEL_WEIGHT = SpoolCreate.model_fields["label_weight"].default
  68. class ImportRowResult(BaseModel):
  69. """Per-row outcome of a parse+validate pass.
  70. `spool` carries the validated, SpoolCreate-shaped dict for `valid` rows so
  71. the route can persist without re-parsing. `resolved_color` flags rows whose
  72. rgba/extra_colors/effect_type were filled in from the Color Catalog rather
  73. than supplied in the CSV — surfaced in the preview so the user knows a
  74. colour was inferred.
  75. """
  76. row_number: int # 1-based data row (header is not counted)
  77. status: str # "valid" | "error" | "skipped"
  78. reason: str | None = None
  79. material: str | None = None
  80. brand: str | None = None
  81. color_name: str | None = None
  82. rgba: str | None = None
  83. resolved_color: bool = False
  84. # True when the colour was resolved from a catalog entry of a DIFFERENT
  85. # material (no exact material match existed). Surfaced so the preview can
  86. # warn the user the colour came from another material's variant.
  87. cross_material_color: bool = False
  88. # True when an active spool with the same material+brand+color_name already
  89. # exists. Informational only — the import still creates the row (there's no
  90. # unique constraint); the preview warns so a double-click / re-upload of the
  91. # same CSV doesn't silently duplicate the inventory.
  92. duplicate_of_existing: bool = False
  93. spool: dict | None = None
  94. class ImportPreview(BaseModel):
  95. """Result of a dry-run (or the pre-write pass of a real import)."""
  96. columns: list[str]
  97. total: int
  98. valid_count: int
  99. error_count: int
  100. skipped_count: int
  101. rows: list[ImportRowResult]
  102. warnings: list[str] = []
  103. class ImportResult(BaseModel):
  104. """Summary returned after a real (non-dry-run) import."""
  105. created: int
  106. skipped: int
  107. errors: int
  108. error_rows: list[ImportRowResult] = []
  109. def _normalize_header(name: str) -> str:
  110. """Map a CSV header cell to a canonical field name.
  111. Case- and space-tolerant: "Color Name", "color-name", " COLOR_NAME "
  112. all collapse to "color_name".
  113. """
  114. return name.strip().lower().replace(" ", "_").replace("-", "_")
  115. def _normalize_rgba(value: str) -> str | None:
  116. """Coerce a user-supplied colour cell to 8-char RRGGBBAA hex, or None.
  117. Accepts an optional leading `#` and a 6-char RRGGBB form (alpha defaults to
  118. `ff`). Returns None if the value isn't valid hex of length 6 or 8 — the
  119. caller turns that into a row error so it isn't silently dropped.
  120. """
  121. raw = value.strip().lstrip("#")
  122. if len(raw) not in (6, 8):
  123. return None
  124. try:
  125. int(raw, 16)
  126. except ValueError:
  127. return None
  128. if len(raw) == 6:
  129. raw += "ff"
  130. return raw.lower()
  131. def _parse_datetime(value: str) -> datetime | None:
  132. """Parse an ISO-8601 timestamp, or None if it isn't valid.
  133. Accepts what `datetime.isoformat()` produces (what export writes) plus a
  134. trailing 'Z' for UTC, which `fromisoformat` rejects before Python 3.11.
  135. """
  136. raw = value.strip()
  137. if not raw:
  138. return None
  139. if raw.endswith("Z"):
  140. raw = raw[:-1] + "+00:00"
  141. try:
  142. return datetime.fromisoformat(raw)
  143. except ValueError:
  144. return None
  145. async def _load_color_catalog(db: AsyncSession) -> list[ColorCatalogEntry]:
  146. """Load the whole Color Catalog once so per-row resolution is in-memory.
  147. A CSV can hold hundreds of rows; resolving each with its own SELECT would
  148. be an N+1 against a small, rarely-changing table. We pull it once here and
  149. let `_resolve_color` match against the list.
  150. """
  151. result = await db.execute(select(ColorCatalogEntry))
  152. return list(result.scalars().all())
  153. def _spool_key(material: str | None, brand: str | None, color_name: str | None) -> tuple[str, str, str]:
  154. """Case/space-insensitive identity used for the duplicate soft-warn."""
  155. return (
  156. (material or "").strip().lower(),
  157. (brand or "").strip().lower(),
  158. (color_name or "").strip().lower(),
  159. )
  160. async def _load_existing_spool_keys(db: AsyncSession) -> set[tuple[str, str, str]]:
  161. """Load material+brand+color_name keys of active spools for the dup warning.
  162. Spool has no unique constraint, so a double-click or re-upload of the same
  163. CSV would silently duplicate the inventory. We pull the active spools' keys
  164. once and let the preview flag matching rows — informational only, the import
  165. still creates them.
  166. """
  167. result = await db.execute(select(Spool.material, Spool.brand, Spool.color_name).where(Spool.archived_at.is_(None)))
  168. return {_spool_key(m, b, c) for m, b, c in result.all()}
  169. def _resolve_color(
  170. catalog: list[ColorCatalogEntry], brand: str | None, color_name: str | None, material: str | None
  171. ) -> tuple[str, str | None, str | None, bool] | None:
  172. """Match brand + color_name against the preloaded catalog (case-insensitive).
  173. Returns (rgba, extra_colors, effect_type, cross_material) on a match, else
  174. None. Prefers an entry whose material matches the row; a catalog entry with
  175. a NULL material is the project's "matches any material" convention and counts
  176. as an exact match too. Only when neither exists does it fall back to another
  177. material's entry and set cross_material=True so the caller can warn that the
  178. colour came from a different material's variant.
  179. """
  180. if not brand or not color_name:
  181. return None
  182. brand_l = brand.strip().lower()
  183. name_l = color_name.strip().lower()
  184. material_l = material.strip().lower() if material else None
  185. matches = [
  186. entry
  187. for entry in catalog
  188. if entry.hex_color and entry.manufacturer.lower() == brand_l and entry.color_name.lower() == name_l
  189. ]
  190. if not matches:
  191. return None
  192. exact = next(
  193. (e for e in matches if e.material is None or (material_l and e.material.lower() == material_l)),
  194. None,
  195. )
  196. row = exact or matches[0]
  197. cross_material = exact is None
  198. rgba = _normalize_rgba(row.hex_color)
  199. if rgba is None:
  200. return None
  201. return rgba, row.extra_colors, row.effect_type, cross_material
  202. def _readable_validation_error(exc: ValidationError) -> str:
  203. """Flatten a Pydantic ValidationError into one short, user-facing line."""
  204. parts = []
  205. for err in exc.errors():
  206. loc = ".".join(str(p) for p in err.get("loc", ())) or "value"
  207. parts.append(f"{loc}: {err.get('msg', 'invalid')}")
  208. return "; ".join(parts)
  209. def _empty_preview(warnings: list[str]) -> ImportPreview:
  210. """A preview with no rows — used for the early-exit cases (bad/empty file)."""
  211. return ImportPreview(
  212. columns=CSV_COLUMNS,
  213. total=0,
  214. valid_count=0,
  215. error_count=0,
  216. skipped_count=0,
  217. rows=[],
  218. warnings=warnings,
  219. )
  220. async def parse_and_validate(raw_bytes: bytes, db: AsyncSession) -> ImportPreview:
  221. """Parse a CSV blob, validate + colour-resolve each row. Never writes.
  222. Decodes UTF-8 (BOM tolerant), reads with DictReader against the fixed
  223. schema, and classifies each row as valid / error / skipped. Valid rows
  224. carry a SpoolCreate-shaped `spool` dict ready to persist.
  225. """
  226. warnings: list[str] = []
  227. try:
  228. text = raw_bytes.decode("utf-8-sig")
  229. except UnicodeDecodeError:
  230. return _empty_preview(["File is not valid UTF-8 text."])
  231. reader = csv.reader(io.StringIO(text))
  232. try:
  233. header = next(reader)
  234. except StopIteration:
  235. return _empty_preview(["CSV is empty."])
  236. norm_header = [_normalize_header(h) for h in header]
  237. known = set(CSV_COLUMNS)
  238. unknown = [h for h in norm_header if h and h not in known]
  239. if unknown:
  240. warnings.append(f"Ignoring unknown columns: {', '.join(unknown)}")
  241. # Map canonical field name → column index in this file (first occurrence).
  242. col_index: dict[str, int] = {}
  243. for idx, h in enumerate(norm_header):
  244. if h in known and h not in col_index:
  245. col_index[h] = idx
  246. if "material" not in col_index:
  247. return _empty_preview(warnings + ["Required column 'material' is missing from the header."])
  248. # Pull the catalog and the existing-spool keys once; per-row colour
  249. # resolution and the duplicate soft-warn both match in memory rather than
  250. # issuing a SELECT per row.
  251. catalog = await _load_color_catalog(db)
  252. existing_keys = await _load_existing_spool_keys(db)
  253. def cell(row: list[str], field: str) -> str:
  254. idx = col_index.get(field)
  255. if idx is None or idx >= len(row):
  256. return ""
  257. # Strip whitespace, then undo any export-side formula-injection quoting
  258. # so export → import round-trips without accumulating a leading quote.
  259. return _desanitize_cell(row[idx].strip())
  260. rows: list[ImportRowResult] = []
  261. valid = error = skipped = 0
  262. for row_number, raw_row in enumerate(reader, start=1):
  263. # Fully blank row (no non-empty cell) → skip silently.
  264. if not any(c.strip() for c in raw_row):
  265. rows.append(ImportRowResult(row_number=row_number, status="skipped", reason="Empty row"))
  266. skipped += 1
  267. continue
  268. material = cell(raw_row, "material")
  269. brand = cell(raw_row, "brand") or None
  270. color_name = cell(raw_row, "color_name") or None
  271. if not material:
  272. rows.append(
  273. ImportRowResult(
  274. row_number=row_number,
  275. status="error",
  276. reason="material is required",
  277. brand=brand,
  278. color_name=color_name,
  279. )
  280. )
  281. error += 1
  282. continue
  283. data: dict = {"material": material}
  284. if brand:
  285. data["brand"] = brand
  286. if color_name:
  287. data["color_name"] = color_name
  288. row_error: str | None = None
  289. # Plain text passthrough columns.
  290. for field in ("subtype", "effect_type", "extra_colors", "note", "storage_location", "category"):
  291. value = cell(raw_row, field)
  292. if value:
  293. data[field] = value
  294. # Numeric columns: parse only if present, else leave to schema defaults.
  295. for field in _INT_COLUMNS:
  296. value = cell(raw_row, field)
  297. if value:
  298. try:
  299. data[field] = int(value)
  300. except ValueError:
  301. row_error = f"{field} must be a whole number (got '{value}')"
  302. break
  303. if row_error is None:
  304. for field in _FLOAT_COLUMNS:
  305. value = cell(raw_row, field)
  306. if value:
  307. try:
  308. data[field] = float(value)
  309. except ValueError:
  310. row_error = f"{field} must be a number (got '{value}')"
  311. break
  312. # Bounds check: weight_used must be within [0, label_weight]. The schema
  313. # accepts any float, so a negative or over-full value would otherwise be
  314. # imported silently. label_weight falls back to the schema default when
  315. # the CSV omits it.
  316. if row_error is None and "weight_used" in data:
  317. used = data["weight_used"]
  318. label = data.get("label_weight", _DEFAULT_LABEL_WEIGHT)
  319. if used < 0:
  320. row_error = f"weight_used cannot be negative (got {used})"
  321. elif used > label:
  322. row_error = f"weight_used ({used}) exceeds label_weight ({label})"
  323. # `last_used` is an ORM-only timestamp (not on SpoolCreate); parse it
  324. # here and apply it to the validated dict after the SpoolCreate gate.
  325. last_used: datetime | None = None
  326. if row_error is None:
  327. last_used_cell = cell(raw_row, "last_used")
  328. if last_used_cell:
  329. last_used = _parse_datetime(last_used_cell)
  330. if last_used is None:
  331. row_error = f"last_used must be an ISO date/time (got '{last_used_cell}')"
  332. resolved_color = False
  333. cross_material_color = False
  334. if row_error is None:
  335. # Colour precedence: explicit rgba wins; else resolve brand+name
  336. # from the catalog; else leave blank.
  337. rgba_cell = cell(raw_row, "rgba")
  338. if rgba_cell:
  339. normalized = _normalize_rgba(rgba_cell)
  340. if normalized is None:
  341. row_error = f"rgba must be 6- or 8-char hex (got '{rgba_cell}')"
  342. else:
  343. data["rgba"] = normalized
  344. else:
  345. resolved = _resolve_color(catalog, brand, color_name, material)
  346. if resolved is not None:
  347. rgba_val, extra_val, effect_val, cross_material_color = resolved
  348. data["rgba"] = rgba_val
  349. # CSV-supplied extra_colors/effect_type take precedence over
  350. # the catalog's; only fill from catalog when absent.
  351. if extra_val and "extra_colors" not in data:
  352. data["extra_colors"] = extra_val
  353. if effect_val and "effect_type" not in data:
  354. data["effect_type"] = effect_val
  355. resolved_color = True
  356. if row_error is not None:
  357. rows.append(
  358. ImportRowResult(
  359. row_number=row_number,
  360. status="error",
  361. reason=row_error,
  362. material=material,
  363. brand=brand,
  364. color_name=color_name,
  365. )
  366. )
  367. error += 1
  368. continue
  369. # Final gate: SpoolCreate runs the same validators the form uses
  370. # (rgba pattern, extra_colors/effect_type normalisation, bounds).
  371. try:
  372. spool = SpoolCreate(**data)
  373. except ValidationError as exc:
  374. rows.append(
  375. ImportRowResult(
  376. row_number=row_number,
  377. status="error",
  378. reason=_readable_validation_error(exc),
  379. material=material,
  380. brand=brand,
  381. color_name=color_name,
  382. )
  383. )
  384. error += 1
  385. continue
  386. spool_data = spool.model_dump()
  387. if last_used is not None:
  388. # last_used isn't a SpoolCreate field; graft it onto the persisted
  389. # dict so the ORM object carries it.
  390. spool_data["last_used"] = last_used
  391. rows.append(
  392. ImportRowResult(
  393. row_number=row_number,
  394. status="valid",
  395. material=material,
  396. brand=brand,
  397. color_name=color_name,
  398. rgba=spool.rgba,
  399. resolved_color=resolved_color,
  400. cross_material_color=cross_material_color,
  401. duplicate_of_existing=_spool_key(material, brand, color_name) in existing_keys,
  402. spool=spool_data,
  403. )
  404. )
  405. valid += 1
  406. return ImportPreview(
  407. columns=CSV_COLUMNS,
  408. total=valid + error + skipped,
  409. valid_count=valid,
  410. error_count=error,
  411. skipped_count=skipped,
  412. rows=rows,
  413. warnings=warnings,
  414. )
  415. def serialize(spools: list[Spool]) -> bytes:
  416. """Render spools to CSV bytes using the fixed schema (export side).
  417. rgba is written without a leading `#`, matching the import-side
  418. normalisation, so export → import round-trips without transformation.
  419. `remaining` is derived (label_weight - weight_used) and `last_used` is
  420. written as ISO-8601; empty/None fields become empty cells.
  421. """
  422. output = io.StringIO()
  423. writer = csv.writer(output)
  424. writer.writerow(CSV_COLUMNS)
  425. for spool in spools:
  426. writer.writerow([_sanitize_cell(_cell_value(spool, col)) for col in CSV_COLUMNS])
  427. return output.getvalue().encode("utf-8")
  428. def _sanitize_cell(value: str) -> str:
  429. """Neutralise spreadsheet formula injection.
  430. A free-text field (note, color_name) starting with =, +, -, @, tab, or CR
  431. is evaluated as a formula by Excel/Sheets/LibreOffice when the CSV is
  432. opened. Prefixing with a single quote forces it to render as literal text.
  433. `_desanitize_cell` is the exact inverse, applied on import.
  434. """
  435. if value and value[0] in _FORMULA_INJECTION_PREFIXES:
  436. return "'" + value
  437. return value
  438. def _desanitize_cell(value: str) -> str:
  439. """Undo `_sanitize_cell` on import so the round-trip is lossless.
  440. Export prefixes formula-looking cells with a single quote; strip exactly
  441. that quote back off when the next character is one of the guarded prefixes,
  442. so `'=SUM(A1)` reads back as `=SUM(A1)` and the value doesn't accumulate a
  443. leading quote on every export→import cycle. A quote followed by anything
  444. else is left untouched — only the prefix `_sanitize_cell` could have added
  445. is removed.
  446. """
  447. if len(value) >= 2 and value[0] == "'" and value[1] in _FORMULA_INJECTION_PREFIXES:
  448. return value[1:]
  449. return value
  450. def _cell_value(spool: Spool, col: str) -> str:
  451. """Render one spool field for export. Handles the derived `remaining`
  452. column and ISO-formats `last_used`; everything else is str() of the value."""
  453. if col == "remaining":
  454. # Derived for display: label_weight - weight_used, clamped at 0.
  455. return str(max(0, round((spool.label_weight or 0) - (spool.weight_used or 0))))
  456. value = getattr(spool, col, None)
  457. if value is None:
  458. return ""
  459. if isinstance(value, datetime):
  460. return value.isoformat()
  461. # Whole-number floats (weight_used, cost_per_kg) export as ints — "300",
  462. # not "300.0" — for a cleaner, human-friendly CSV. import re-parses fine.
  463. if isinstance(value, float) and value.is_integer():
  464. return str(int(value))
  465. return str(value)