Skip to content

feat: add validated offline merchant template import/export - #477

Merged
khaira777 merged 10 commits into
mainfrom
fm/flocafe-448-import-export
Aug 23, 2026
Merged

khaira777 merged 10 commits into
mainfrom
fm/flocafe-448-import-export

Conversation

@khaira777

Copy link
Copy Markdown
Contributor

Intent

Implement FloCafe issue #448 (child of epic #438): validated offline import/export for merchant print templates, building strictly on the landed #447 contracts (shared/print/merchant-template.ts fail-closed validator with schema_version major gate + allowed-blocks whitelist, main/services/merchant-print-templates.ts CRUD lifecycle draft->activate->archive with checksum column and rollback, main/routes/print-templates.ts owner CRUD API) WITHOUT forking the validation logic.

Requirements accepted from the captain brief:

  1. Export: owner can download an active or archived template as a self-describing portable file (.json wrapper carrying format discriminator, schema_version, payload, checksum, origin metadata). The exact envelope format was our decision and is documented as a public contract in docs/merchant-print-templates.md.
  2. Import: upload path validates against the same fail-closed rules as create - unknown schema majors rejected, allowed-blocks whitelist, per-block property whitelists, ~256 KB cap enforced on the raw envelope bytes, checksum verified. Imported templates land as draft with derived_from provenance recording the source file (sha256 digest of the exact envelope text plus sanitized file name).
  3. Owner-role authorization on both endpoints; multi-tenant scoping preserved.
  4. Golden fixtures under tests/fixtures/merchant-templates/transfer/: a valid round-trip file plus negative fixtures per validation rule.
  5. PR body carries 'Fixes feat(printing): add validated offline import/export for merchant templates #448 Refs refactor(printing): establish multilingual semantic print architecture and extensible templates #438'; title is a descriptive conventional-commit title.

Binding constraints from issue #448: treat every imported file as untrusted input; declarative-only payload vocabulary exactly equal to the validated block set from #447 (no JavaScript, eval, SQL, shell, filesystem paths, network fetches, arbitrary URLs, or executable HTML); unknown-field policy on import = reject (stricter than render tolerance); imports never auto-activate and never overwrite an existing identity; duplicate names are allowed because identity is a fresh uuid; no zips/binaries in v1 (text-only JSON); no visual editor; no compliance-template convergence (#445 escpos-line-template-v1 is a different format on purpose); the import/export code path is fully offline (zero network APIs, verified by npm run test:url-allowlist).

Deliberate design decisions and prior pipeline fix rounds to NOT re-litigate as mistakes: drafts are deliberately NOT exportable (only active/archived pass activation); envelope checksum is sha256 over serializeMerchantTemplatePayload output (recursively key-sorted canonical serialization), used for persisted payload_json too; migration v73 normalizes pre-canonicalization stored payloads once, idempotently, leaving checksum-mismatching or invalid rows untouched for fail-closed paths; export enforces the SAME 256 KB raw-byte cap as import so an install never mints a transfer file it would refuse to read back (this resolves the previously-raised size-symmetry question - if review still wants to challenge this contract decision as ask-user, park it rather than fixing silently: captain will rule under key f2-size-symmetry); imports always mint a NEW row id so no uuid-collision replace flow is needed in v1; settings-page Export/Import buttons are deferred because no merchant template management list UI exists yet.

Verification expected: npx ts-node --transpile-only -P tests/tsconfig.json tests/merchant-template-import-export.test.ts (new suite, registered as test:merchant-template-transfer in package.json), regression-clean tests/merchant-print-templates.test.ts, npm run build && npm run lint, npm run test:url-allowlist.

What Changed

  • Added owner-only export/import APIs for self-describing .flocafe-template.json envelopes, with active/archived export support and fresh-draft imports carrying sanitized offline provenance.
  • Added fail-closed envelope validation, canonical payload checksums, shared payload validation, 256 KB size enforcement, and migration v73 normalization for stored templates.
  • Added public transfer documentation, golden/negative fixtures, and a dedicated import/export test suite.

Fixes #448
Refs #438

Risk Assessment

⚠️ Medium: The change is source-clean on review, but it spans an irreversible schema migration and untrusted-input import/printing paths, warranting broader pipeline validation.

Testing

The prescribed transfer suite initially hit TS5107 because dependencies were absent; after installing the lockfile-resolved dependencies without lifecycle scripts, it passed end-to-end. Merchant-template regression and URL-allowlist tests also passed. No linters, formatters, full-suite tests, or static-analysis commands were run.

Evidence: Merchant template import/export end-to-end transcript

▶ Envelope validation: golden fixture
  ✓ golden-envelope-v1.json passes structural envelope validation
  ✓ checksum convention verified against the golden fixture
  ✓ canonical digest is insensitive to object key order

▶ Envelope validation: negative fixtures
  ✓ unknown majors, wrong formats, and unknown fields rejected with pointers
  ✓ non-ISO exportedAt values fail closed
  ✓ calendar-valid leap-year dates are enforced
  ✓ printer tokens and control characters are rejected from labels
  ✓ disallowed block kinds reject through the shared payload validator, not a fork
  ✓ tampered checksum fixture is detectable at the verification step
  ✓ envelopes above 262144 bytes are rejected on byte length
  ✓ malformed JSON and non-object roots fail closed
[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-transfer-OL23ha/flo.db
[DB] Schema: v0 → v73
[DB] Triggering auto-backup before migrating v0 → v73...
[DB] Auto-backup before migrating v0 → v73 created at /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-transfer-OL23ha/backups/flo-backup-2026-08-23T09-03-58-023Z-pre-v0-to-v73.db
[DB] Applying migration v1: initial_schema
[DB] Install defaults loaded; first-run setup pending
[DB] Migration v1 complete
[DB] Applying migration v2: hash_plaintext_pins
[DB] Migration v2 complete
[DB] Applying migration v3: cloud_identity_and_outbox
[DB] Migration v3 complete
[DB] Applying migration v4: add_notes_limits_settings
[DB] Migration v4 complete
[DB] Applying migration v5: add_print_logs_table
[DB] Migration v5 complete
[DB] Applying migration v6: add_loyalty_settings
[DB] Migration v6 complete
[DB] Applying migration v7: add_discount_settings
[DB] Migration v7 complete
[DB] Applying migration v8: add_loyalty_index
[DB] Migration v8 complete
[DB] Applying migration v9: add_sequences_table
[DB] Migration v9 complete
[DB] Applying migration v10: fix_sequences_composite_key
[DB] Migration v10 complete
[DB] Applying migration v11: first_run_setup_uses_welcome_form
[DB] Migration v11 complete
[DB] Applying migration v12: fix_table_integer_ids
[DB] Migration v12 complete
[DB] Applying migration v13: fix_null_table_ids
[DB] Migration v13 complete
[DB] Applying migration v14: simplify_loyalty_settings
[DB] Migration v14 complete
[DB] Applying migration v15: add_instagram_handle_setting
[DB] Migration v15 complete
[DB] Applying migration v16: add_terms_accepted_at_to_users
[DB] Migration v16 complete
[DB] Applying migration v17: add_held_orders_table
[DB] Migration v17 complete
[DB] Applying migration v18: fix_null_category_ids
[DB] Migration v18 complete
[DB] Applying migration v19: backfill_product_cb_percent_and_tags
[DB] Migration v19 complete
[DB] Applying migration v20: add_tables_is_active
[DB] Migration v20 complete
[DB] Applying migration v21: clear_legacy_loyalty_expiry
[DB] Migration v21 complete
[DB] Applying migration v22: add_customers_phone_digits
[DB] Migration v22 complete
[DB] Applying migration v23: normalize_customer_phones
[MIGRATION v23] normalized: 0, unparseable: 0
[MIGRATION v23] merged 0 duplicate customer(s)
[MIGRATION v23] verification: 0 customers, 0 still non-E.164
[DB] Migration v23 complete
[DB] Applying migration v24: normalize_customer_phones_retry
[MIGRATION v24] normalized: 0, unparseable: 0
[DB] Migration v24 complete
[DB] Applying migration v25: add_order_item_addons_table
[MIGRATION v25] backfilled addons for 0 order items (0 unparseable, skipped)
[DB] Migration v25 complete
[DB] Applying migration v26: add_kds_default_view
[DB] Migration v26 complete
[DB] Applying migration v27: add_station_printer_link_and_user_stations
[DB] Migration v27 complete
[DB] Applying migration v28: seed_telemetry_settings
[DB] Migration v28 complete
[DB] Applying migration v29: whatsapp_messaging
[DB] Migration v29 complete
[DB] Applying migration v30: drop_order_items_addons_json_column
[MIGRATION v30] backfilled 0 order_item(s) still missing a normalized addons snapshot
[MIGRATION v30] Dropped order_items.addons — order_item_addons is now the only place selected addons live.
[DB] Migration v30 complete
[DB] Applying migration v31: add_customers_tag_counts_column
[DB] Migration v31 complete
[DB] Applying migration v32: add_kds_and_kot_printing_toggles
[DB] Migration v32 complete
[DB] Applying migration v33: add_addon_groups_allow_multiple_quantities
[DB] Migration v33 complete
[DB] Applying migration v34: add_order_items_voided_at
[DB] Migration v34 complete
[DB] Applying migration v35: add_tax_pack_configuration_tables
[DB] Migration v35 complete
[DB] Applying migration v36: add_product_and_addon_tax_categories
[DB] Migration v36 complete
[DB] Applying migration v37: add_transaction_tax_snapshots_and_charge_categories
[DB] Migration v37 complete
[DB] Applying migration v38: register_bundled_tax_pack_versions
[DB] Migration v38 complete
[DB] Applying migration v39: add_users_tokens_valid_after
[DB] Migration v39 complete
[DB] Applying migration v40: v2_cloud_defaults_and_tax_toggle
[DB] Migration v40 complete
[DB] Applying migration v41: support_ticket_outbox
[DB] Migration v41 complete
[DB] Applying migration v42: add_global_cashback_percent
[DB] Migration v42 complete
[DB] Applying migration v43: telemetry_default_on_for_new_installs
[DB] Migration v43 complete
[DB] Applying migration v44: store_diagnostics_outbox
[DB] Migration v44 complete
[DB] Applying migration v45: add_performance_indexes_and_normalize_timestamps
[DB] Migration v45 complete
[DB] Applying migration v46: normalize_cloud_enabled_flags_to_01
[DB] Migration v46 complete
[DB] Applying migration v47: store_diagnostics_enabled_by_default
[DB] Migration v47 complete
[DB] Applying migration v48: deactivate_reusable_demo_credentials
[DB] Migration v48 complete
[DB] Applying migration v49: add_payment_idempotency_records
[DB] Migration v49 complete
[DB] Applying migration v50: add_order_idempotency_records
[DB] Migration v50 complete
[DB] Applying migration v51: enforce_global_payment_transaction_refs
[DB] Migration v51 complete
[DB] Applying migration v52: restore_method_scoped_transaction_refs
[DB] Migration v52 complete
[DB] Applying migration v53: scope_idempotency_records_to_user
[DB] Migration v53 complete
[DB] Applying migration v54: repair_retry_ownership_and_payment_reference_history
[DB] Migration v54 complete
[DB] Applying migration v55: durable_token_revocations
[DB] Migration v55 complete
[DB] Applying migration v56: persist_station_assignment_scope
[DB] Migration v56 complete
[DB] Applying migration v57: rename_gstin_to_generic_tax_registration_number
[DB] Migration v57 complete
[DB] Applying migration v58: configurable_manual_payment_methods
[DB] Migration v58 complete
[DB] Applying migration v59: split_checks_by_item_quantity
[DB] Migration v59 complete
[DB] Applying migration v60: seed_split_checks_disabled_setting
[DB] Migration v60 complete
[DB] Applying migration v61: seed_server_app_enabled_setting
[DB] Migration v61 complete
[DB] Applying migration v62: normalize_cloud_last_error
[DB] Migration v62 complete
[DB] Applying migration v63: seed_printer_trim_decimals_setting
[DB] Migration v63 complete
[DB] Applying migration v64: drop_unused_printer_usb_device_path
[DB] Migration v64 complete
[DB] Applying migration v65: seed_bill_content_visibility_settings
[DB] Migration v65 complete
[DB] Applying migration v66: seed_bill_template_settings
[DB] Migration v66 complete
[DB] Applying migration v67: persist_order_item_inventory_deductions
[DB] Migration v67 complete
[DB] Applying migration v68: add_invoice_numbering_settings
[DB] Migration v68 complete
[DB] Applying migration v69: installed_plugin_print_templates
[DB] Migration v69 complete
[DB] Applying migration v70: rename_waiter_role_to_server
[DB] Migration v70 complete
[DB] Applying migration v71: repair_durable_token_revocations
[DB] Migration v71 complete
[DB] Applying migration v72: merchant_print_templates
[DB] Migration v72 complete
[DB] Applying migration v73: normalize_merchant_template_payloads
[MIGRATION v73] normalized 0 merchant template payload(s); 0 already canonical or left untouched
[DB] Migration v73 complete
[DB] integrity_check: ok
[DB] foreign_key_check: clean

▶ Export API
  ✓ export is owner-role only
  ✓ draft templates are refused (only active/archived export)
  ✓ active template exports a self-describing envelope carrying origin metadata

▶ Export hardening: tamper detection + filename sanitization
  ✓ tampered or invalid rows can never be distributed as trusted-looking files
  ✓ hostile names sanitize to traversal-proof filenames ("etc-passwd-recept.flocafe-template.json")
  ✓ export holds its output to the same byte cap import enforces

▶ Import API: fail-closed pipeline
  ✓ import is owner-role only
  ✓ every rejection class tested: bad version, wrong format, unknown fields, disallowed block, tampered checksum, oversize, malformed JSON
  ✓ invalid templates never partially install

▶ Import API: landing as draft + provenance
  ✓ imported templates land as new drafts with offline-import provenance
  ✓ export -> import round-trip is lossless
  ✓ duplicate names are permitted (identity is the uuid, never the source id)

▶ Reformat tolerance: whitespace/key-order edits still verify
  ✓ whitespace/key-order reformatting does not break verification

▶ Round-trip render parity + lifecycle intact after import
[Printer] formatReceipt - template: {"source":"merchant","id":"b4cb8fbc-1544-4eae-9d94-2382903751e0"}
[Printer] formatReceipt - order: ORD-PARITY-001 bill: INV-PARITY-001
[Printer] formatReceipt - items count: 3 cols: 42
[Printer] formatReceipt - template: {"source":"merchant","id":"0d70887b-5e35-4ae8-b8a8-0ce0dc7e3f6e"}
[Printer] formatReceipt - order: ORD-PARITY-001 bill: INV-PARITY-001
[Printer] formatReceipt - items count: 3 cols: 42
  ✓ render parity holds across the export/import boundary
  ✓ draft -> active -> archive lifecycle intact after import; archived rows remain portable

▶ Storage normalization: pre-canonicalization rows become transferable
[DB] Database closed
[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-transfer-OL23ha/flo.db
[DB] Schema: v72 → v73
[DB] Triggering auto-backup before migrating v72 → v73...
[DB] Auto-backup before migrating v72 → v73 created at /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-transfer-OL23ha/backups/flo-backup-2026-08-23T09-03-58-381Z-pre-v72-to-v73.db
[DB] Applying migration v73: normalize_merchant_template_payloads
[MIGRATION v73] normalized 2 merchant template payload(s); 7 already canonical or left untouched
[DB] Migration v73 complete
[DB] integrity_check: ok
[DB] foreign_key_check: clean
  ✓ legacy payloads and rollback points normalize once; integrity-unknown rows stay untouched
[DB] Database closed
[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-transfer-OL23ha/flo.db
[DB] Schema: v72 → v73
[DB] Triggering auto-backup before migrating v72 → v73...
[DB] Auto-backup before migrating v72 → v73 created at /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-transfer-OL23ha/backups/flo-backup-2026-08-23T09-03-58-401Z-pre-v72-to-v73.db
[DB] Applying migration v73: normalize_merchant_template_payloads
[MIGRATION v73] normalized 0 merchant template payload(s); 9 already canonical or left untouched
[DB] Migration v73 complete
[DB] integrity_check: ok
[DB] foreign_key_check: clean
  ✓ normalization is idempotent across repeated upgrade runs
  ✓ templates stored by earlier builds now survive the export -> import round trip

Merchant template import/export tests: 29 checks passed.
[DB] Database closed
Evidence: Merchant template regression transcript

> [email protected] test:merchant-print-templates
> ts-node --transpile-only -P tests/tsconfig.json tests/merchant-print-templates.test.ts


▶ Validation: golden fixtures
  ✓ golden-receipt-v1.json validates
  ✓ golden-receipt-labeled-v1.json validates

▶ Validation: negative fixtures
  ✓ per-rule negative fixtures all rejected with actionable errors
  ✓ internal translation keys are never accepted as template label fields

▶ Validation: size cap and misc
  ✓ payloads above 262144 bytes are rejected
  ✓ non-object roots and malformed JSON fail closed

▶ applyMerchantTemplate
  ✓ canonical all-blocks template is an identity transform
  ✓ reordering, visibility, and label variants apply semantically
  ✓ input document is never mutated (purity)

▶ Ordered block composition in renderBillDocumentToClassicLines
  ✓ reordered template renders every block segment at its template position
  ✓ canonical-relative-order subsets keep byte-stable legacy arrangement
[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-templates-89YeZa/flo.db
[DB] Schema: v0 → v73
[DB] Triggering auto-backup before migrating v0 → v73...
[DB] Auto-backup before migrating v0 → v73 created at /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-templates-89YeZa/backups/flo-backup-2026-08-23T09-04-15-120Z-pre-v0-to-v73.db
[DB] Applying migration v1: initial_schema
[DB] Install defaults loaded; first-run setup pending
[DB] Migration v1 complete
[DB] Applying migration v2: hash_plaintext_pins
[DB] Migration v2 complete
[DB] Applying migration v3: cloud_identity_and_outbox
[DB] Migration v3 complete
[DB] Applying migration v4: add_notes_limits_settings
[DB] Migration v4 complete
[DB] Applying migration v5: add_print_logs_table
[DB] Migration v5 complete
[DB] Applying migration v6: add_loyalty_settings
[DB] Migration v6 complete
[DB] Applying migration v7: add_discount_settings
[DB] Migration v7 complete
[DB] Applying migration v8: add_loyalty_index
[DB] Migration v8 complete
[DB] Applying migration v9: add_sequences_table
[DB] Migration v9 complete
[DB] Applying migration v10: fix_sequences_composite_key
[DB] Migration v10 complete
[DB] Applying migration v11: first_run_setup_uses_welcome_form
[DB] Migration v11 complete
[DB] Applying migration v12: fix_table_integer_ids
[DB] Migration v12 complete
[DB] Applying migration v13: fix_null_table_ids
[DB] Migration v13 complete
[DB] Applying migration v14: simplify_loyalty_settings
[DB] Migration v14 complete
[DB] Applying migration v15: add_instagram_handle_setting
[DB] Migration v15 complete
[DB] Applying migration v16: add_terms_accepted_at_to_users
[DB] Migration v16 complete
[DB] Applying migration v17: add_held_orders_table
[DB] Migration v17 complete
[DB] Applying migration v18: fix_null_category_ids
[DB] Migration v18 complete
[DB] Applying migration v19: backfill_product_cb_percent_and_tags
[DB] Migration v19 complete
[DB] Applying migration v20: add_tables_is_active
[DB] Migration v20 complete
[DB] Applying migration v21: clear_legacy_loyalty_expiry
[DB] Migration v21 complete
[DB] Applying migration v22: add_customers_phone_digits
[DB] Migration v22 complete
[DB] Applying migration v23: normalize_customer_phones
[MIGRATION v23] normalized: 0, unparseable: 0
[MIGRATION v23] merged 0 duplicate customer(s)
[MIGRATION v23] verification: 0 customers, 0 still non-E.164
[DB] Migration v23 complete
[DB] Applying migration v24: normalize_customer_phones_retry
[MIGRATION v24] normalized: 0, unparseable: 0
[DB] Migration v24 complete
[DB] Applying migration v25: add_order_item_addons_table
[MIGRATION v25] backfilled addons for 0 order items (0 unparseable, skipped)
[DB] Migration v25 complete
[DB] Applying migration v26: add_kds_default_view
[DB] Migration v26 complete
[DB] Applying migration v27: add_station_printer_link_and_user_stations
[DB] Migration v27 complete
[DB] Applying migration v28: seed_telemetry_settings
[DB] Migration v28 complete
[DB] Applying migration v29: whatsapp_messaging
[DB] Migration v29 complete
[DB] Applying migration v30: drop_order_items_addons_json_column
[MIGRATION v30] backfilled 0 order_item(s) still missing a normalized addons snapshot
[MIGRATION v30] Dropped order_items.addons — order_item_addons is now the only place selected addons live.
[DB] Migration v30 complete
[DB] Applying migration v31: add_customers_tag_counts_column
[DB] Migration v31 complete
[DB] Applying migration v32: add_kds_and_kot_printing_toggles
[DB] Migration v32 complete
[DB] Applying migration v33: add_addon_groups_allow_multiple_quantities
[DB] Migration v33 complete
[DB] Applying migration v34: add_order_items_voided_at
[DB] Migration v34 complete
[DB] Applying migration v35: add_tax_pack_configuration_tables
[DB] Migration v35 complete
[DB] Applying migration v36: add_product_and_addon_tax_categories
[DB] Migration v36 complete
[DB] Applying migration v37: add_transaction_tax_snapshots_and_charge_categories
[DB] Migration v37 complete
[DB] Applying migration v38: register_bundled_tax_pack_versions
[DB] Migration v38 complete
[DB] Applying migration v39: add_users_tokens_valid_after
[DB] Migration v39 complete
[DB] Applying migration v40: v2_cloud_defaults_and_tax_toggle
[DB] Migration v40 complete
[DB] Applying migration v41: support_ticket_outbox
[DB] Migration v41 complete
[DB] Applying migration v42: add_global_cashback_percent
[DB] Migration v42 complete
[DB] Applying migration v43: telemetry_default_on_for_new_installs
[DB] Migration v43 complete
[DB] Applying migration v44: store_diagnostics_outbox
[DB] Migration v44 complete
[DB] Applying migration v45: add_performance_indexes_and_normalize_timestamps
[DB] Migration v45 complete
[DB] Applying migration v46: normalize_cloud_enabled_flags_to_01
[DB] Migration v46 complete
[DB] Applying migration v47: store_diagnostics_enabled_by_default
[DB] Migration v47 complete
[DB] Applying migration v48: deactivate_reusable_demo_credentials
[DB] Migration v48 complete
[DB] Applying migration v49: add_payment_idempotency_records
[DB] Migration v49 complete
[DB] Applying migration v50: add_order_idempotency_records
[DB] Migration v50 complete
[DB] Applying migration v51: enforce_global_payment_transaction_refs
[DB] Migration v51 complete
[DB] Applying migration v52: restore_method_scoped_transaction_refs
[DB] Migration v52 complete
[DB] Applying migration v53: scope_idempotency_records_to_user
[DB] Migration v53 complete
[DB] Applying migration v54: repair_retry_ownership_and_payment_reference_history
[DB] Migration v54 complete
[DB] Applying migration v55: durable_token_revocations
[DB] Migration v55 complete
[DB] Applying migration v56: persist_station_assignment_scope
[DB] Migration v56 complete
[DB] Applying migration v57: rename_gstin_to_generic_tax_registration_number
[DB] Migration v57 complete
[DB] Applying migration v58: configurable_manual_payment_methods
[DB] Migration v58 complete
[DB] Applying migration v59: split_checks_by_item_quantity
[DB] Migration v59 complete
[DB] Applying migration v60: seed_split_checks_disabled_setting
[DB] Migration v60 complete
[DB] Applying migration v61: seed_server_app_enabled_setting
[DB] Migration v61 complete
[DB] Applying migration v62: normalize_cloud_last_error
[DB] Migration v62 complete
[DB] Applying migration v63: seed_printer_trim_decimals_setting
[DB] Migration v63 complete
[DB] Applying migration v64: drop_unused_printer_usb_device_path
[DB] Migration v64 complete
[DB] Applying migration v65: seed_bill_content_visibility_settings
[DB] Migration v65 complete
[DB] Applying migration v66: seed_bill_template_settings
[DB] Migration v66 complete
[DB] Applying migration v67: persist_order_item_inventory_deductions
[DB] Migration v67 complete
[DB] Applying migration v68: add_invoice_numbering_settings
[DB] Migration v68 complete
[DB] Applying migration v69: installed_plugin_print_templates
[DB] Migration v69 complete
[DB] Applying migration v70: rename_waiter_role_to_server
[DB] Migration v70 complete
[DB] Applying migration v71: repair_durable_token_revocations
[DB] Migration v71 complete
[DB] Applying migration v72: merchant_print_templates
[DB] Migration v72 complete
[DB] Applying migration v73: normalize_merchant_template_payloads
[MIGRATION v73] normalized 0 merchant template payload(s); 0 already canonical or left untouched
[DB] Migration v73 complete
[DB] integrity_check: ok
[DB] foreign_key_check: clean

▶ Migration v72: fresh install
  ✓ table schema matches the ideal fresh-install shape (both paths share MIGRATIONS)
  ✓ bill_template setting upgraded to structured JSON on fresh installs

▶ Migration v72: legacy value upgrade (idempotent rerun)
[DB] Database closed
[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-templates-89YeZa/flo.db
[DB] Schema: v71 → v73
[DB] Triggering auto-backup before migrating v71 → v73...
[DB] Auto-backup before migrating v71 → v73 created at /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-templates-89YeZa/backups/flo-backup-2026-08-23T09-04-15-166Z-pre-v71-to-v73.db
[DB] Applying migration v72: merchant_print_templates
[DB] Migration v72 complete
[DB] Applying migration v73: normalize_merchant_template_payloads
[MIGRATION v73] normalized 0 merchant template payload(s); 0 already canonical or left untouched
[DB] Migration v73 complete
[DB] integrity_check: ok
[DB] foreign_key_check: clean
  ✓ legacy bare core value upgraded transparently
[DB] Database closed
[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-templates-89YeZa/flo.db
[DB] Schema: v71 → v73
[DB] Triggering auto-backup before migrating v71 → v73...
[DB] Auto-backup before migrating v71 → v73 created at /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-templates-89YeZa/backups/flo-backup-2026-08-23T09-04-15-184Z-pre-v71-to-v73.db
[DB] Applying migration v72: merchant_print_templates
[DB] Migration v72 complete
[DB] Applying migration v73: normalize_merchant_template_payloads
[MIGRATION v73] normalized 0 merchant template payload(s); 0 already canonical or left untouched
[DB] Migration v73 complete
[DB] integrity_check: ok
[DB] foreign_key_check: clean
  ✓ legacy bare pack template id upgraded to the structured pack selection
[DB] Database closed
[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-templates-89YeZa/flo.db
[DB] Schema: v71 → v73
[DB] Triggering auto-backup before migrating v71 → v73...
[DB] Auto-backup before migrating v71 → v73 created at /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-merchant-templates-89YeZa/backups/flo-backup-2026-08-23T09-04-15-196Z-pre-v71-to-v73.db
[DB] Applying migration v72: merchant_print_templates
[DB] Migration v72 complete
[DB] Applying migration v73: normalize_merchant_template_payloads
[MIGRATION v73] normalized 0 merchant template payload(s); 0 already canonical or left untouched
[DB] Migration v73 complete
[DB] integrity_check: ok
[DB] foreign_key_check: clean
  ✓ migration is idempotent for already-structured values

▶ Selection identity (structured, legacy-compatible)
  ✓ legacy bare values, structured forms, and rejection cases behave
  ✓ serialize -> parse roundtrips
  ✓ writer-side upgrade produces canonical persistence form
  ✓ unknown merchant ids do not resolve

▶ CRUD API: validation gate
  ✓ write-time validation rejects unknown shapes with details
  ✓ CRUD is owner-role only
  ✓ draft creation records informational compliance provenance without trust claims

▶ CRUD API: draft → active → rollback → archive
  ✓ activate promotes a draft
  ✓ checksum verification passes after activation
  ✓ checksum mismatch is detected before any state change
  ✓ single-step rollback point captured on active edit
  ✓ rollback restores the previous payload and clears the rollback point
  ✓ rollback without a previous payload is rejected
  ✓ archive terminalizes the lifecycle

▶ CRUD API: merchant availability in selection identity
  ✓ merchant availability follows the lifecycle (active only)

▶ Render path: merchant templates through the document pipeline
[Printer] formatReceipt - template: {"source":"merchant","id":"42a42db5-8062-4bf4-9071-45f212b2d1b3"}
[Printer] formatReceipt - order: ORD-PARITY-001 bill: INV-PARITY-001
[Printer] formatReceipt - items count: 3 cols: 32
[Printer] formatReceipt - template: {"source":"merchant","id":"42a42db5-8062-4bf4-9071-45f212b2d1b3"}
[Printer] formatReceipt - order: ORD-PARITY-001 bill: INV-PARITY-001
[Printer] formatReceipt - items count: 3 cols: 42
[Printer] formatReceipt - template: {"source":"merchant","id":"42a42db5-8062-4bf4-9071-45f212b2d1b3"}
[Printer] formatReceipt - order: ORD-PARITY-001 bill: INV-PARITY-001
[Printer] formatReceipt - items count: 3 cols: 48
  ✓ byte-identical to the plain classic document pipeline at 32/42/48 columns
[Printer] formatReceipt - template: {"source":"merchant","id":"7c34d991-758d-4f42-b0be-3f37066e172d"}
[Printer] formatReceipt - order: ORD-PARITY-001 bill: INV-PARITY-001
[Printer] formatReceipt - items count: 3 cols: 42
  ✓ semantic overrides change rendered output exactly where configured
[Printer] formatReceipt - template: {"source":"merchant","id":"424408d3-4fea-4df5-b51f-0c60eb9d56d1"}
[Printer] formatReceipt - order: ORD-PARITY-001 bill: INV-PARITY-001
[Printer] formatReceipt - items count: 3 cols: 42
  ✓ reordered and omitted blocks render semantically through the document pipeline
[Printer] formatReceipt - template: {"source":"merchant","id":"0073fa32-e0a2-47e1-969b-06018b53a777"}
[Printer] formatReceipt - order: ORD-PARITY-001 bill: INV-PARITY-001
[Printer] formatReceipt - items count: 3 cols: 42
  ✓ standalone tax-breakdown blocks remain renderable
[Printer] formatReceipt - template: classic
[Printer] formatReceipt - order: ORD-PARITY-001 bill: INV-PARITY-001
[Printer] formatReceipt - items count: 3 cols: 42
  ✓ legacy bare-string selections keep rendering during transition
[Printer] formatReceipt - template: {"source":"merchant","id":"missing-id"}
[Printer] formatReceipt - order: ORD-PARITY-001 bill: INV-PARITY-001
[Printer] formatReceipt - items count: 3 cols: 42
  ✓ render fails closed with an explicit warning, never garbage

Merchant print template tests: 37 checks passed.
[DB] Database closed
Evidence: Offline URL allowlist transcript

> [email protected] test:url-allowlist
> ts-node --transpile-only -P tests/tsconfig.json tests/url-allowlist.test.ts

URL allowlist tests passed
- Outcome: 🔧 1 issue found → auto-fixed ✅ across 2 runs (8m56s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 4 issues found → auto-fixed (4) ✅
  • ⚠️ shared/print/merchant-template.ts:180 - Date.parse accepts non-ISO inputs such as "0", so invalid exportedAt values pass despite the documented ISO-8601 contract. Use an explicit ISO/RFC3339 check or confirm broader parsing is intentional.
  • ⚠️ main/services/merchant-print-templates.ts:401 - Export verifies only the stored hash, not payload validity. A migrated invalid row with a matching checksum can return 500 for malformed JSON or export a file the importer rejects. Validate row.payload_json with the shared validator before constructing the envelope.
  • ⚠️ main/db.ts:4033 - The intent requires v73 to leave “checksum-mismatching or invalid rows untouched,” but this rewrites a row when its current payload is valid while previous_payload_json is invalid. Decide whether invalid rollback state makes the row invalid under that requirement.
  • ⚠️ tests/merchant-template-import-export.test.ts:347 - The required transfer fixture set says “negative fixtures per validation rule,” but the added transfer tests omit import-boundary cases for unknown payload fields, duplicate blocks, wrong types, empty blocks, and invalid label fields. Existing feat(printing): add versioned semantic merchant print template model #447 pure-validator fixtures do not cover these through import.

🔧 Fix: Guard export against invalid stored payloads; test dependency unavailable
3 warnings still open:

  • ⚠️ shared/print/merchant-template.ts:180 - The contract documents exportedAt as an ISO-8601 date-time, but Date.parse accepts non-ISO inputs such as "0"; an envelope with that value, otherwise valid payload, and matching checksum is imported successfully. Use an explicit ISO/RFC3339 date-time check or confirm broader parsing is intentional.
  • ⚠️ main/db.ts:4033 - The stated migration invariant requires v73 to leave “checksum-mismatching or invalid rows untouched,” but this path rewrites a row when its current payload/checksum are valid while previous_payload_json is malformed or otherwise invalid. Either skip the whole row when rollback state is invalid or clarify that only the current payload defines row validity.
  • ⚠️ tests/merchant-template-import-export.test.ts:354 - The required fixture contract says transfer fixtures must include “negative fixtures per validation rule,” but the transfer suite only adds envelope-level cases plus one disallowed-block payload case. It omits transfer/import-boundary fixtures for unknown payload fields, duplicate blocks, wrong types, empty blocks, and invalid label fields; the existing feat(printing): add versioned semantic merchant print template model #447 fixtures are outside the transfer fixture set and are not exercised through import.

🔧 Fix: Enforce strict RFC3339 exportedAt validation
3 issues (2 errors, 1 warning) still open:

  • 🚨 main/services/merchant-print-templates.ts:477 - Imported label strings can contain printer commands such as {CUT} or ASCII ESC controls. They pass the shared validator, then reach applyMerchantTemplate and buildEscPos, where {CUT} executes a physical cut instead of printing text. Reject/sanitize printer tokens and control characters at the shared validation or render boundary.
  • ⚠️ shared/print/merchant-template.ts:154 - The RFC3339 check still accepts invalid calendar values such as 2024-02-30T00:00:00Z because Date.parse normalizes them. Enforce calendar-valid date-time components for the strict ISO-8601 contract.
  • 🚨 tests/merchant-template-import-export.test.ts:340 - Buffer.byteLength receives the numeric .length of the probe result instead of the probe string, so this new required test throws ERR_INVALID_ARG_TYPE before exercising the export size-cap behavior. Pass the canonical string to Buffer.byteLength.

🔧 Fix: Reject printer controls in merchant labels; clarify size-cap test
1 warning still open:

  • ⚠️ shared/print/merchant-template.ts:158 - The strict ISO-8601 check still accepts nonexistent calendar dates such as 2024-02-30T00:00:00Z: Date.parse normalizes them instead of rejecting them, so import accepts malformed envelope metadata. Validate calendar components explicitly before accepting the timestamp.

🔧 Fix: Validate RFC3339 calendar components before envelope import
✅ Re-checked - no issues remain.

🔧 **Test** - 1 issue found → auto-fixed ✅
  • 🚨 tests/merchant-template-import-export.test.ts:313 - Fixed the focused test’s tamper-cleanup query to restore the saved checksum correctly.
  • npm ci --no-audit --no-fund
  • npx ts-node --transpile-only -P tests/tsconfig.json tests/merchant-template-import-export.test.ts
  • npx ts-node --transpile-only -P tests/tsconfig.json tests/merchant-print-templates.test.ts
  • npm run test:url-allowlist

🔧 Fix: Fix transfer test checksum cleanup; 29 focused checks pass
✅ Re-checked - no issues remain.

  • npm ci --ignore-scripts
  • npx --no-install ts-node --transpile-only -P tests/tsconfig.json tests/merchant-template-import-export.test.ts
  • npm run test:merchant-print-templates
  • npm run test:url-allowlist
  • git status --porcelain=v1 and transient dependency cleanup verification
✅ **Document** - passed

✅ No issues found.

🔧 **Lint** - 1 issue found → auto-fixed ✅
  • ⚠️ eslint.config.mjs:1 - Targeted ESLint could not run because the configured TypeScript ESLint packages are missing from this worktree.

🔧 Fix: Targeted lint and source typecheck are clean
✅ Re-checked - no issues remain.

✅ **Push** - passed

✅ No issues found.

…lates

Portable transfer envelopes (#448, epic #438) on top of the #447 model:

- Shared kernel: 'flocafe-merchant-template' envelope contract (format
  discriminator, fail-closed schema major, ISO exportedAt, informational
  origin metadata, checksum field) with pure structural validation that
  reuses the single #447 payload validator — no forked rules.
- Service: export active/archived rows as self-describing .json envelopes
  (checksum verified BEFORE export so tampered payloads never ship);
  import runs the full untrusted-input pipeline (256 KB byte cap, single
  JSON document, envelope whitelist, shared payload validator, checksum
  verify) and always lands a NEW draft with origin 'imported' plus
  offline-import provenance (source-file digest + sanitized file name).
  Duplicate names allowed; imports never overwrite or auto-activate.
- Routes: GET /:id/export (attachment download with sanitized,
  traversal-proof filename) and POST /import, both owner-role only and
  rate-limited; multi-tenant scoping unchanged.
- Fixtures: golden round-trip envelope plus per-rule negatives (tampered
  checksum, unknown envelope major, oversized, disallowed block, wrong
  root format, unknown envelope field).
- Tests: tests/merchant-template-import-export.test.ts covering every
  rejection class, no partial installs, lossless round-trip, render parity
  across the transfer boundary, lifecycle intact after import.
- Docs: envelope format documented as a public contract in
  docs/merchant-print-templates.md.
@greptile-apps

greptile-apps Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR adds owner-only, offline import and export of validated merchant print-template envelopes while preserving draft lifecycle and tenant scoping.

  • Introduces a versioned transfer envelope with canonical checksums, strict structural validation, and raw-byte limits.
  • Adds active/archived export and fresh-draft import routes with sanitized provenance.
  • Canonicalizes eligible legacy template payloads through schema migration v73.
  • Documents and tests transfer validation, integrity checks, lifecycle behavior, and rendering parity.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
shared/print/merchant-template.ts Adds the versioned envelope contract, canonical serialization, strict timestamp validation, and shared fail-closed validation.
main/services/merchant-print-templates.ts Implements checksum-verified export and validated fresh-draft import with sanitized offline provenance.
main/routes/print-templates.ts Exposes owner-only import and export endpoints through the existing merchant-template API.
main/db.ts Adds migration v73 to canonicalize eligible stored current and rollback payloads.
tests/merchant-template-import-export.test.ts Exercises envelope validation, authorization, integrity checks, round trips, rendering parity, lifecycle behavior, and migration normalization.

Sequence Diagram

sequenceDiagram
    actor Owner
    participant API as Print Template API
    participant Validator as Shared Validator
    participant Service as Template Service
    participant DB as SQLite

    Owner->>API: POST /api/print-templates/import
    API->>Service: Raw envelope text + metadata
    Service->>Validator: Validate envelope and payload
    Validator-->>Service: Canonical validated payload
    Service->>Service: Verify canonical checksum
    Service->>DB: Insert fresh draft with provenance
    DB-->>Owner: Imported template metadata

    Owner->>API: GET /api/print-templates/:id/export
    API->>Service: Export active/archived template
    Service->>DB: Load tenant-scoped row
    Service->>Validator: Revalidate stored payload
    Service->>Service: Verify checksum and size cap
    Service-->>Owner: Portable JSON attachment
Loading

Reviews (2): Last reviewed commit: "no-mistakes: apply CI fixes" | Re-trigger Greptile

@khaira777
khaira777 merged commit f2ef629 into main Aug 23, 2026
13 checks passed
@khaira777
khaira777 deleted the fm/flocafe-448-import-export branch August 23, 2026 09:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(printing): add validated offline import/export for merchant templates

2 participants