Files
wiggleverse-ecomm/docs/products-domain.md

8.0 KiB
Raw Permalink Blame History

products domain — developer notes

DOC-4 (SD-0002 §11): the import/export spine as built in SLICE-5, extended by SLICE-68. Operator-facing material is in OPERATIONS.md; the spec is SD-0002 in the content repo.

Layout and pipeline

backend/app/domains/products/ is layered like the rest of the app (main → domains → platform, enforced by import-linter):

  • models.py — canonical row model + the column registry.
  • codec.py — bytes → ParsedFile; file-level gates only.
  • validate.py — rows → CanonicalProduct blocks + per-row errors.
  • diff.py — catalog × canonical products → apply plan + preview records.
  • serialize.py — the export half: CatalogProduct snapshot → canonical CSV (the inverse of codec/validate). DB-free, like diff.py.
  • repo.py — SQL only: catalog snapshot, draft/run CRUD, apply primitives. Never commits or rolls back.
  • service.py — use-case orchestration; owns every transaction boundary and emits the TEL events via backend/app/platform/telemetry.py.
flowchart LR
    subgraph validate_path [import_validate]
        A[parse_csv] --> B[build_products] --> D[compute_diff] --> E[(import_draft)]
        C[load_catalog] --> D
    end
    subgraph confirm_path [confirm_draft]
        E --> F[re-derive: parse → build → diff] --> G{fingerprint match?}
        G -- yes --> H[one-transaction apply<br/>run + products + delete draft]
        G -- no --> I[PreviewStale<br/>draft kept]
    end

Confirm re-derives everything from the draft's stored file_bytes against the live catalog, then checks the fingerprint — so what lands is exactly what the preview showed, or the confirm refuses (preview_stale). A confirm with no adds and no updates refuses with nothing_to_apply.

Canonical model and blank-vs-absent

models.py is the one model every dialect maps to (INV-17). KNOWN_COLUMNS is the registry header detection, unknown-column warnings, and validation all read; CLEAR_DEFAULTS holds the reset values for clearable fields (status, published, product_type, tags).

The §6.5.1 cell semantics, as implemented:

  • Absent column → the field never enters fields{} → untouched by diff and apply (never a change).
  • Present-but-empty cellfields[name] = None (an explicit clear) → resolved at diff time to its CLEAR_DEFAULTS entry, or NULL where none exists.
  • The position exception: a cleared Variant Position has no CLEAR_DEFAULTS entry — diff.resolved_variant_fields resolves it to the variant's 1-based file order within its product, never to NULL.

Option names live both in CanonicalProduct.option_names (the values) and in fields{} (the file-presence marker the diff needs for the absent-vs-clear distinction).

Error granularity

validate.py never raises on a row problem: every violation is recorded as a merchant-language RowError and poisons its whole product block — the product previews as kind="error" and is excluded from apply, while parsing continues so one pass yields a complete accounting (BUC-1a). On apply, error rows are recorded per line in import_run_error; rows_errored on the run is the error-row count, while the preview's errors tile counts error products — the two numbers legitimately differ.

File-level problems (not_csv, missing_required_column, too_many_rows, file_too_large) raise FileRejected in codec.py instead: no draft is created. The BFF adds an early 413 for oversized uploads (main.py).

INV-11 mechanics

compute_diff makes one walk that produces two views of the same computation: the typed apply plan (resolved natives — Decimal, bool, lists) that confirm_draft executes, and the JSON-safe preview records stored as draft JSONB and served verbatim to the SPA. Because both derive from the same walk they cannot diverge. The fingerprint is sha256(json.dumps(records, sort_keys=True, separators=(",", ":"))); a mismatch at confirm means the catalog drifted since preview → PreviewStale (409 preview_stale, draft kept for re-validation). The whole apply — run row, product/variant/image writes, error rows, draft delete — is one transaction; any exception rolls it back and emits TEL-6.

Export & the round-trip (SLICE-6)

serialize.py is the export half of "one codec, two directions": it turns the CatalogProduct snapshot (the same one repo.load_catalog builds for the diff engine) back into canonical CSV, writing exactly the columns codec.py / validate.py parse, in the §6.5.1 row grammar — HEADER is the full canonical column set; product fields + option names sit on the first row; one variant per row; images interleave; a product with more images than variants emits image-only rows.

repo.export_catalog returns the status-filtered snapshot list (sorted by handle, deterministic); the service.export_catalog generator streams serialize.catalog_to_csv over it and emits TEL-3 (catalog_exported) once the stream is exhausted. The BFF wraps it in a StreamingResponse; an empty (filtered) catalog raises EmptyCatalog eagerly409 empty_catalog before any bytes stream.

INV-12 (diff(catalog, import(export(catalog))) = ∅) is locked two ways: a property test (test_products_serialize.py) runs the real export→parse→diff loop over 200 generated text-field catalogs and asserts every product is unchanged; the e2e_roundtrip_noop browser scenario does the same through the UI (export download → re-upload → all-unchanged preview, import disabled). Numeric/Decimal fields — the property test's deliberate blind spot (string-form vs value-identity) — get explicit round-trip unit tests.

Named seams (what later slices replace)

  • import_draft.file_bytes → objectstore key (SLICE-7). The upload currently lives as BYTEA on the draft row (0002_products.sql); SLICE-7 moves the bytes to object storage and stores a key.
  • codec.detect_dialect → Shopify (SLICE-8). Today it always returns "canonical"; SLICE-8 recognizes Shopify's exact header set here (INV-17).
  • Run-status complete shortcut → fetching_images (SLICE-7). confirm_draft inserts the run with status="complete" directly; SLICE-7 inserts it as fetching_images and hands off to the image-fetch task. Relatedly, image rows are created with the schema default status='pending' today and stay pending — placeholder behavior until SLICE-7's fetch phase (the run-detail payload already carries the stable image_progress / image_outcomes shape, zeroed).

Test map

File Covers
backend/tests/test_products_codec.py file-level gates: parse, caps (INV-18), required columns, dialect
backend/tests/test_products_validate.py every §6.5.1 row-error rule, one fixture each
backend/tests/test_products_diff.py classification, blank-vs-absent, option matching, fingerprint
backend/tests/test_products_serialize.py serializer grammar + INV-12 property test (round-trip no-op over generated catalogs) + decimal round-trip
backend/tests/test_products_export.py status-filtered snapshot, streamed export, EmptyCatalog, TEL-3
backend/tests/test_products_service.py draft lifecycle: validate/preview/discard, expiry, TEL-1
backend/tests/test_products_invariants.py INV-10 (never deletes), INV-14 (storefront isolation), apply transactionality, TEL-6
backend/tests/test_products_endpoints.py §6.4 API scenarios + auth/storefront gates
e2e/tests/import-preview-confirm.spec.ts happy path: upload → preview → confirm → history
e2e/tests/import-errors.spec.ts actionable row errors at preview and on the run report
e2e/tests/import-file-rejected.spec.ts file-level rejection, picker stays live, no trace
e2e/tests/import-cancel.spec.ts cancel at preview leaves no trace
e2e/tests/export-download.spec.ts export downloads canonical CSV, status filter respected
e2e/tests/roundtrip-noop.spec.ts export → re-import → all-unchanged, import disabled (PUC-10)