spool_csv.py 24 KB

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