# PRD — Invoice Template Designer Preview Workspace

- Slug: `invoice-template-designer-preview-workspace`
- Date: `2026-02-09`
- Status: Draft

## Summary

Add a first-class preview workspace to the Invoice Template Designer where preview output is generated by the same rendering logic used for real invoices.

This is not a design-canvas placeholder preview. The preview pipeline must:

1. compile GUI designer state into AssemblyScript template logic,
2. compile that AssemblyScript to Wasm using the same compiler/tooling path used by invoice templates, and
3. render via the same Wasm execution + HTML/CSS rendering pipeline used in real invoice rendering.

The feature also includes layout verification: rendered output must be checked against expected layout constraints derived from the GUI design.

## Problem

The current designer experience allows quick visual editing, but it does not guarantee fidelity with real invoice rendering behavior. A preview built from designer-only placeholder logic can look correct in-editor while diverging from real rendered invoices.

That causes template regressions:

- spacing/alignment mismatches,
- binding behavior differences,
- table/totals discrepancies,
- late discovery after save or after invoice generation.

Users need a tight edit-preview loop with production-parity rendering and objective layout checks.

## Goals

- Provide an in-editor Preview workspace reachable from the Invoice Template Designer.
- Make preview authoritative by using the same runtime rendering logic as real invoices.
- Introduce a GUI-to-AssemblyScript compiler so GUI designs become real template logic.
- Support both curated sample invoices and existing tenant invoices for preview data.
- Verify rendered layout against expected constraints derived from design and report mismatches.
- Keep preview read-only and free of invoice/template persistence side effects.

## Non-goals

- Replacing or redesigning the existing invoice rendering runtime.
- Editing invoice business data from preview.
- Full visual diff screenshot tooling for every browser/print engine combination in MVP.
- Redesigning template assignment, invoice generation, or finalization workflows.

## Users and Primary Flows

Primary personas:

- Billing admins authoring invoice templates.
- Implementers validating that GUI-authored templates render correctly before deployment.

Primary flows:

1. **Design -> authoritative preview loop**
   - User edits template in GUI design mode.
   - User opens Preview.
   - System compiles GUI design to AssemblyScript, compiles to Wasm, renders with real pipeline.
   - User sees rendered invoice and layout verification status.
   - User returns to design and repeats.

2. **Preview with sample invoices**
   - User selects sample data source.
   - User chooses scenario and validates structure/formatting early (including tenants with no real invoices).

3. **Preview with existing invoices**
   - User selects existing invoice source.
   - User searches/selects tenant invoice.
   - User validates real-world rendering and mismatch report.

4. **Save template**
   - User saves after preview passes.
   - Persisted template logic is the compiler-generated AssemblyScript/Wasm representation.

## UX / UI Notes

- Keep existing top-level editor tabs:
  - `Visual`
  - `Code`
- Within `Visual`, provide secondary tabs:
  - `Design`
  - `Preview`
- Preview panel sections:
  - Data source controls (`Sample` / `Existing`)
  - Compile/Render status
  - Rendered invoice output
  - Layout verification summary (`Pass` / `Issues`)
  - Mismatch details list (node/constraint level)
- Preview is read-only; no drag/drop/resize/edit interactions.
- Designer and preview state should toggle quickly without losing unsaved design edits.

## Requirements

### Functional Requirements

- Add in-editor `Preview` tab within `Visual` mode.
- Support sample and existing-invoice data sources.
- Provide curated sample invoice scenarios for early design.
- Support existing invoice search/select within tenant.
- Fetch selected invoice details and map to renderer input model.
- Build a GUI compiler that transforms designer workspace state into AssemblyScript template source.
- Use deterministic code generation so identical design state yields identical AssemblyScript output.
- Compile generated AssemblyScript to Wasm using the same compiler path/options as real templates.
- Run preview rendering through the same Wasm execution + layout renderer path used for actual invoice rendering.
- Do not use design-canvas placeholder renderer output as authoritative preview content.
- Surface structured compiler errors in preview UI, including node mapping where available.
- Re-run compile + render when design changes (with debounced execution).
- Keep preview read-only and side-effect free (no invoice/template writes during preview).
- Save flow must persist compiler-generated template logic (AssemblyScript and compiled Wasm) so saved template matches preview path.
- Add layout verification that compares rendered HTML layout against expected design constraints.
- Display verification result and mismatch details in preview.
- Add stable automation IDs for preview, compile/render status, and verification UI.

### Non-functional Requirements

- Preview should complete compile + render + verification fast enough for iterative use in normal environments.
- Pipeline should avoid unnecessary recompilation when design output hash is unchanged.
- Error states must be explicit and recoverable (compile errors, data load errors, render errors, verification errors).
- Tenant isolation and auth requirements must match existing billing action standards.

## Data / API / Integrations

- Reuse existing data actions where applicable:
  - `fetchInvoicesPaginated` for existing invoice discovery.
  - `getInvoiceForRendering` for existing invoice detail payload.
  - `mapDbInvoiceToWasmViewModel` (or successor) for renderer input mapping.
- Introduce GUI compiler modules (IR/AST extraction, AssemblyScript generation, diagnostics mapping).
- Introduce preview compile/render orchestration actions that use existing template compilation and rendering primitives.
- Maintain compatibility with existing template save actions while routing GUI templates through compiler output.

## Security / Permissions

- Existing-invoice preview remains tenant-scoped and authenticated.
- Preview compile/render actions must not leak cross-tenant data.
- Preview operations must be read-only relative to invoice records.
- Template writes happen only through explicit save actions.

## Observability

- Surface user-facing states for compile/render/verify lifecycle.
- Keep actionable logs for compiler failures, render failures, and verification mismatches.
- No expanded telemetry scope required for MVP beyond current logging/error patterns.

## Rollout / Migration

- Ship behind existing GUI designer feature flag path.
- No required schema migration for MVP unless compiler metadata storage requires minor additive fields.
- Existing templates should continue to open; GUI compiler path applies when previewing/saving GUI-authored designs.

## Open Questions

1. Should `Code` tab be editable for GUI-authored templates, or read-only generated output to avoid dual-source-of-truth conflicts?
2. What tolerance thresholds should layout verification use (position/size deltas) before marking mismatch?
3. Should layout verification run automatically on every preview render, or allow manual re-check for heavy templates?
4. What minimum constraint set is required in MVP (alignment, spacing, sizing, containment, table structure)?
5. Should preview block save when verification fails, or allow save with warnings in MVP?

## Acceptance Criteria (Definition of Done)

- [ ] Visual mode contains `Design` and `Preview` tabs.
- [ ] Preview output is produced via real render pipeline (GUI -> AssemblyScript -> Wasm -> real HTML/CSS render).
- [ ] Preview supports both sample and existing invoice data sources.
- [ ] Compiler errors are surfaced clearly in preview and tied to design context where possible.
- [ ] Layout verification runs against rendered output and reports pass/fail with mismatch details.
- [ ] Preview is read-only and does not mutate invoice/template data.
- [ ] Saving persists compiler-generated template logic used by preview.
- [ ] Automated tests cover compile parity, render parity, and layout verification behavior.
