Skip to content

0021 — Internal sample invoice preview

Status: proposed (2026-10-08) — implemented on a local branch; not merged, not deployed, and not yet reviewed by the owner against the PDFs of the four real orders. Builds on ADR 0019 (automatic internal sales invoices) and ADR 0020 (product GST/HSN classification). Adds a read-only, watermarked review surface to the accounting portal; touches no customer-facing surface, no checkout, no price, no order and no invoice, and leaves real invoice issuance exactly as it was — blocked and OFF.

Update (2026-10-09, ADR 0022). The locked layout engine described here now also draws issued invoices (samplepreview_locked.go, renderer locked-a4-v1); the sample output is byte-identical to before. The static guards below were extended, not relaxed: the new file joins the pinned file set, and the two files that may reference it (invoicepdf.go, invoicedoc.go) are named in an explicit allow-list. The sample feature itself is unchanged and remains separate, read-only and watermarked.

Context

The owner wants to see how the invoice of the four existing paid Hoodie orders (a fixed list of four historical order numbers, kept in the code) would look before deciding whether real invoicing may be switched on. ADR 0019 deliberately makes that impossible to learn by issuing one: issued invoices are immutable, their numbers are gap-free and permanent, and a backfill takes the oldest N awaiting orders (service.Backfill orders by created_at and cannot be aimed at four named orders). The earlier dry-run (service.DryRunInvoice, cmd/invoicedryrun) answers "what would the issuer do and what is still missing", but it produces no document the owner can read as an invoice.

There is also a deeper obstacle. The real issuer resolves HSN/rate by the order's IST date and from approved settings only, and it fails closed (pending_tax_review) when they are missing or do not cover the order's date. The owner's brief describes HSN 6109 at GST 5%, effective 2026-10-01 as temporary sample data for the Hoodie — a presentation input for judging how an invoice looks, not a tax determination. This work read no production data, so it has not verified which tax settings production holds or in which approval state, and the four orders may pre-date the effective date, in which case a faithful preview of the issuer would show nothing but a hold. The database's approved on a setting is only a Super Admin's save-time self-attestation, not an accountant's approval (ADR 0020). Using sample values without a hard wall around them would put an unapproved rate one function call away from a statutory document. So the decision is as much about the wall as about the feature.

Dependency — merge order. This change is built on the unmerged dry-run work (branch feat/invoice-dryrun-preview, commits 3205e4a and 129b8ee): the builder consumes the dry-run's facts document (service.DryRunInput), asks service.DryRunInvoice for the issuer's own verdict and reads through service.SampleFactsSQL (the minimal query of the sample, which shares the dry-run's facts model and macros), and the offline route needs cmd/invoicedryrun to print the facts block. Without those commits the backend does not compile (undefined: DryRunCheck, DryRunInput, ...). It must be merged after, or together with, the dry-run branch.

Decision

Two workflows that never meet.

Workflow A — SAMPLE PREVIEW (this ADR) Workflow B — ACTUAL INVOICE ISSUANCE (ADR 0019, unchanged)
Purpose Let an authorised internal reviewer see how an invoice would look Create the statutory internal sales invoice
Writes Nothing, ever (read-only transaction, always rolled back) public.invoices, series counter, snapshot, audit
Number None. Its reference is SAMPLE_PREVIEW_<order serial> Allocated from accounting.invoice_series
Tax inputs Unapproved, labelled SAMPLE / UNVERIFIED Approved configuration only, by the order's IST date
State Available once deployed; permission-gated OFF, blocked until every item under "Before issuance" is settled
Customer-visible Never Never

Workflow B (service.IssueInvoice, the invoice hook, the sweep, the backfill, both gates ACCOUNTING_INVOICE_ISSUANCE_ENABLED and accounting.settings.invoice_issuance_enabled) is not modified. Changing a product's tax setting later does not re-issue anything and does not change any historical invoice (ADR 0020, unchanged); the preview does not alter that either, because it never writes a tax setting.

The wall: sample tax inputs can never flow into issuance

The sample's HSN/GST is a render-only override applied inside a pure function. It is kept away from workflow B by construction and by tests, not by convention:

  • Pure builder. service.BuildSamplePreviews (aim-backend/internal/accounting/service/samplepreview.go) takes the sanitized facts document the dry-run already reads (DryRunInput) plus the seller settings payload and returns values. It has no pool, no context, no clock (the "today" it uses is the facts' own database-read IST date), no sequence access, no file, network or goroutine (enforced by the guards below, also for the methods of the allowed packages). It hands the sample inputs only to the issuer's own pure calculation kernel (computeInvoice), never to a writer. The names it declares (mostly Sample/sample-prefixed, a few helpers not) are exactly what the reverse guard below looks for in every other file.
  • AST/source guards (aim-backend/internal/compat/invoice_preview_guards_test.go, plus ..._rules_test.go, ..._rows_test.go and ..._package_test.go for the rules added after the independent regression review). The sample files are parsed with the Go parser without comments (prose can neither trip nor satisfy a rule) and calls are resolved through import paths (an alias is no way round). They enforce:
  • Imports and symbols. An import allow-list per role (the service files may import only bytes, errors, fmt, math, regexp, strings, time, unicode, the PDF library and dto; anything to do with the invoice hook, product tax setup, the audit writer, the journal, payments, partner integration, e-mail/SMS, net/http, os, database/sql is refused with the reason). From the in-repo packages a sample file may use only a listed set of symbols (the handler may use acctmw.IdentityFrom and the six role names, service.BuildSamplePreviews and the other sample entry points - not acctmw.AllRoles, the permission-cache functions or service.IssueInvoice); a listed symbol nothing uses fails as dead surface. No issuance identifier (IssueInvoice, AutoIssuer, Backfill, Dispatch, FormatInvoiceNumber, the series/number allocators, the test clock seams, and so on), and a sample file may use from the rest of its own package only a listed set of names.
  • SQL. Every string literal - raw and interpreted - is scanned, so an INSERT INTO ..., a series/snapshot/audit/nextval/ advisory-lock/FOR UPDATE token or any SQL in the pure files fails. In the handler the only SQL text allowed is the one seller projection of the settings SELECT, and the SQL argument of every Query/QueryRow must be one of two named values: the constant sampleSettingsSQL or the factsSQL returned by service.SampleFactsSQL (the broad service.DryRunFactsSQL is not an allowed symbol of the handler). No parameter, field, variable, range variable or other declaration may carry either name, neither may be assigned or addressed elsewhere, and a receiver called c is no exemption (the one call that is not a database query, fiber's c.Query("download"), is matched by its exact shape).
  • Database calls. No Exec, Begin, Commit, CopyFrom, SendBatch, Prepare, Acquire, Conn, PgConn, LargeObjects, Hijack (called or taken as a method value); BeginTx only with AccessMode: pgx.ReadOnly; only beginSampleReadOnly calls the pgxpool API (sampleOpener merely hands it the request's pool) and a pool-typed value may only be used to BeginTx. Of the shared *accounting.Deps the handler may only compare it with nil, pass it to a function of its own file, and read .Pool (compare it with nil or hand it to beginSampleReadOnly): a method or field added to Deps elsewhere, deps.Cfg and the JWT secret are out of reach.
  • Process state. No clock call in the pure files; no goroutine; no write to, increment of, address of, slice of or alias of a package-level variable - whether declared in the file, in a sibling sample file or in an imported package (acctmw.AllRoles, dto.ISTLocation, time.Local, pgx.ErrNoRows ...) - and no mutating method on a package-level value (including (*regexp.Regexp).Longest). The audience is a function that returns a fresh slice and the order allow-list is used only by value, so there is nothing to alias.
  • No I/O through allowed imports. The allow-listed packages are held to the same rule as the imports: no fpdf method that opens a path or loads an image or font (OutputFileAndClose, Image*, AddFont*, AddUTF8Font*, RegisterImage*, SetFontLocation, ...), no fmt.Print*/Fprint*/Scan*/Fscan*, no fiber package-level HTTP client, no log.Set*/Fatal*/Panic*/Default, no time.LoadLocation.
  • Routes: GET only. The pinned handler registers with .Get only. routes.go may name the /invoice-previews group exactly twice - its declaration with exactly the two gates, and the call to the registrar - so no route or middleware can be added to the group from there, and no other string in routes.go may mention the prefix. The handler package's route-table test reads fiber's table and fails on any non-GET/HEAD entry under the prefix that is more than the group's own two-gate chain, and on any GET/HEAD route other than the three.
  • Money. No float type or literal in the files that do money arithmetic and no money value converted to a float in the renderer. The guard is itself tested: every rule has offending synthetic sources and the legitimate look-alikes that must not trip it (TestPreviewGuard_GuardOfTheGuard); the real files must be exactly the pinned set, so a guard that finds nothing fails instead of passing. The guards are syntactic (no type information), so they have known limits (listed in SAMPLE_INVOICE_PREVIEW_RELEASE_PACK.md at the repository root); they are the second line: the first is the READ ONLY transaction, which the database enforces whatever the code says.
  • Reverse guard. TestPreviewGuard_NothingElseInTheTwoPackagesReferencesThePreview fails if any other file in internal/accounting/service or internal/accounting/handler — issuance included — mentions a symbol the preview declares (the only allowed exception is routes.go, which mounts the group and its gate and is itself checked as above). Issuance cannot learn the preview exists. Nothing in either package may run code the preview did not ask for: no non-test file declares func init() or calls anything but regexp.MustCompile, errors.New, conversions and builtins while package variables are initialised, and the methods the standard library calls implicitly (MarshalJSON, UnmarshalJSON, MarshalText, String, Error, Format, GoString, Scan, Value, ...) on the types the preview builds, formats or serialises may be declared only in the file that declares the type, and those types embed nothing.
  • Call-site allow-list. aim-backend/internal/compat/invoice_issuance_wiring_test.go pins the only non-test files that may call invoicehook.Set, Dispatch and Get, service.NewAutoIssuer, service.IssueInvoice and service.Backfill. A new file that calls any of them — directly or through an aliased import — fails the build. TestPreviewGuard_OnlyTheHandlerAndTheCLIUseTheSampleEntryPoints does the same in the other direction for the preview's own exported API.
  • 6109-literal containment. TestPreviewGuard_TheOwnersSampleTaxInputIsConfinedToTheBuilder fails if any production Go file other than samplepreview.go contains a string literal with 6109 or the product keyword the sample matches on. The owner's sample input exists in exactly one place.
  • Issuance default pinned. TestPreviewGuard_IssuanceEnvironmentGateDefaultsToOff pins that config/config.go still reads ACCOUNTING_INVOICE_ISSUANCE_ENABLED with the default "false", and that the preview has no flag of its own that could be mistaken for, or wired into, that gate. TestPreviewGuard_PaymentAndCheckoutCodeNeverMentionThePreview keeps the payment and checkout code from mentioning the preview at all.
  • No new write surface anywhere. The existing TestNoProductionWritesToCommerceTables and the product-tax isolation test still apply to the new files unchanged. The preview reads each product's stored tax settings through the sample's minimal facts query (rules 1 to 3 below) and never through the product-tax package, which the guard's import list refuses; the owner's 6109/5% input is a constant of its own.

What a preview contains

One SamplePreview value per order drives the JSON and the PDF, so the two cannot disagree. Each preview shows:

  • The owner's locked invoice layout (see "The locked invoice design" below), headed INTERNAL SAMPLE INVOICE PREVIEW and (SAMPLE — NOT A TAX INVOICE), for the company AIM ORIGINATORS PRIVATE LIMITED.
  • The watermark SAMPLE — NOT A TAX INVOICE on every page: a pale diagonal mark behind the content (opaque tint, no transparency) and the same words as ordinary horizontal text in a red band, plus a footer repeating the disclaimer — including pages created by automatic page breaks.
  • Preview reference SAMPLE_PREVIEW_<order serial> - the digits after the last hyphen of the order number. The underscore is outside the GST serial alphabet, so ValidInvoiceNumber is false for every possible reference and it can never be read as, or collide with, an invoice number. No invoice number is accepted, formed or printed anywhere.
  • The original order number and order date (IST).
  • Seller details marked unverified: legal name, registered address, PAN, GSTIN and state, each RESOLVED or UNRESOLVED, with the source (accounting settings or the built-in entity record) and a note that no accountant has verified them.
  • Per line: the product, HSN 6109 — SAMPLE / UNVERIFIED (or the product's own setting, labelled as sample), quantity, unit price, the discount or fee allocated to the line, taxable amount, GST 5% — SAMPLE / UNVERIFIED, and CGST + SGST (intra-state) or IGST (inter-state) only when the jurisdiction is established from recorded data (place of supply or delivery state against the seller state).
  • Order summary: items total, coupon and reward discounts, delivery and platform fee, total paid, taxable amount, total GST, and the preview total.
  • Payment: status, method, mode, gateway and a masked payment reference (first 4 + last 4 characters; a reference shorter than 12 is shown fully starred).
  • Amount in words of the total paid (Indian numbering).
  • A reconciliation of the amount paid against the preview calculation (items vs subtotal, line arithmetic, the checkout formula with the issuer's ±1 paisa tolerance, funding vs paid, preview total vs paid, taxable + GST vs total). A one-paisa residue is shown, not hidden.
  • UNRESOLVED instead of invention: any value the recorded data does not establish prints UNRESOLVED with its reason; none is defaulted. A line whose recorded unit price is zero while its amount is not shows the unit price as UNRESOLVED (UNIT_PRICE_NOT_RECORDED), never 0.00; a preview whose facts cannot be trusted (UNAVAILABLE) carries the order number, the status and the reason and nothing recorded on the order. A preview is also UNAVAILABLE when the order records an amount beyond 10,000,000,000.00 (1e12 paise), a quantity beyond 1,000,000 or more than 1,000 line items: the issuer's int64 arithmetic cannot be trusted at such magnitudes and no real order approaches them; the reason names the offending field, never its value.
  • A calculation warning instead of estimated tax: when the tax basis for a line or the jurisdiction is unknown, taxable value, GST and the CGST/SGST/IGST split are withheld behind a calculation warning (the UNRESOLVED item TAX_AMOUNTS_WITHHELD), never estimated.
  • The internal review disclaimer (not a tax invoice, no invoice number, not issued, posted, filed or sent, not to be given to a customer or relied on for GST) and a statement of what the issuer's own rules would say about the order today.
  • Where the data came from. A document made by the service says it was read from the database in a read-only transaction. A document made by the offline program says on its first page that it was rendered offline from a facts file supplied by the operator, with the first 16 hex digits of the SHA-256 of the facts text (the JSON carries all 64): the program cannot check where a file came from, and the repository's synthetic fixture uses the real order numbers, so a file-made document must not look like a database read. A caller that does not say where the facts came from gets the offline description.

Preview status per order is one of COMPLETE, COMPLETE_WITH_WARNINGS, INCOMPLETE, NOT_ELIGIBLE, NOT_RECONCILED, NOT_FOUND, UNAVAILABLE. An order with no consideration, a non-INR currency, a negative recorded amount, or amounts that do not reconcile is not given figures.

The locked invoice design

On 2026-10-09 the owner approved a reference mock-up as the final visual design of the invoice and ruled that it is not to be redesigned or re-argued. The sample PDF is that design, drawn from the SamplePreview by samplepreview_invoice.go; the portal shows that very PDF. Composition, top to bottom (A4 portrait, the reference's proportions and typographic hierarchy): the internal-use badge (top right); the project's own logo, the AIM STORE brand in red and black, the seller block (legal name, address, GSTIN, PAN, state); the title block and the information table (reference, date, order, payment); Bill To and Ship To boxes; the items table with a picture slot, HSN/SAC, quantity, unit price, taxable value, GST rate, CGST and SGST (or one IGST column, or one GST column when the jurisdiction is not established) and total; the right-aligned totals box ending in the blue Grand Total; Amount in Words (from the left edge of the totals box, as in the reference); GST Details and System Information boxes; and the footer with the QR code, the internal reference and the authorised-signatory area.

Nothing is copied from the mock-up's content: its customer, transaction id, seller phone and e-mail, product, SKU and signature are not data of this project and never appear. What differs from the mock-up, and why:

Mock-up Sample PDF Reason
title TAX INVOICE, "(Original for Supplier / Company Records)" INTERNAL SAMPLE INVOICE PREVIEW, "(SAMPLE — NOT A TAX INVOICE)" issuance is OFF: nothing may look issued
Invoice No. / Invoice Date Preview Ref. SAMPLE_PREVIEW_0000NN / "Not issued (sample)" no invoice number is ever formed or printed
the customer's name, mobile, e-mail, address "Withheld (internal sample)"; State and Place of Supply kept the facts carry no buyer data; privacy
seller phone and e-mail; PAN not shown; PAN is UNRESOLVED not verified data: nothing is invented
product photograph, SKU a neutral picture placeholder; no SKU no verified image is part of the facts
the line's HSN and rate the same cells, each with SAMPLE / UNVERIFIED under it the owner's sample tax inputs are unapproved
UPI transaction id the masked gateway reference (first 4 + last 4) the raw reference is never printed
Invoice Type "B2C (Regular)", Reverse Charge "No" "SAMPLE (not a tax invoice) - B2C", "Not assessed (sample)" reverse charge is not in the facts
Generated By / Updated At / Updated By / Source / Status Generated At (when the facts were read), Source (offline file with the start of its SHA-256, or the read-only database read), Payment Evidence, Reconciliation, Preview Status, Tax Approval "NOT APPROVED (sample)" the box carries the sample's own evidence
a handwritten signature a dashed "NOT SIGNED - sample preview" box no signature is ever fabricated
QR code (of the invoice) QR code of the preview reference only non-sensitive; not a statutory registration, and it says so
the rupee sign drawn as a vector shape the core PDF fonts have no glyph for it (no font is embedded)

Every page also carries the red band, the diagonal watermark and the footer. A short grey statement under the totals says how the figures were made (prices GST-inclusive, taxable value extracted, discounts and fees allocated pro rata: an unapproved treatment) and that the HSN and rate are unapproved sample inputs; an offline document prints, under the two boxes (or at the foot of page 1 when the boxes go to a page of their own), the full sentence that it was rendered offline from a file the program cannot check. A figure too wide for its cell is set smaller before it is ever cut (and for an absurd amount the column is widened at the expense of the product description); a label is set smaller before it is cut; a reason that does not fit beside a party-box label is left to the review notes and the box says UNRESOLVED; an unresolved seller identity is marked where the name is and under the signatory line; an order total that is not a paid sale is labelled "Order Total (recorded)", never "Grand Total".

One page wherever the order fits. The invoice is drawn into scratch documents at five densities (items row height, totals row height, closed-up boxes) and the roomiest that keeps it on ONE page is used, so one to three lines are one A4 page; a longer order flows over further pages with the items header repeated. The reviewer's material that has no place in the layout (the per-line allocation, the order summary, the reconciliation table, the payment record, every warning and unresolved item, what the real issuer would do, how the sample was made, the disclaimer) is a review-notes annex on its own page(s), drawn only when something needs reviewing: a status other than COMPLETE, a warning or unresolved item, a failed reconciliation check, a rounding residue, a payment-evidence verdict other than VERIFIED, a discount, fee or recorded tax to allocate, or a notice (for example that the order already has an invoice, or that another tax setting exists and is not used; the invoice page points to it). A COMPLETE, fully reconciled order with none of these is exactly one page and says on that page that its checks pass; the full notes are always available in the portal and in the JSON.

Assets and codes. The logo is the project's own (aim-store-website/public/logo.png, composited onto white so that it has no alpha channel and the PDF stays plain PDF 1.3), embedded in the binary; a test re-derives it from the website file. The QR code is encoded by samplepreview_qr.go (ISO/IEC 18004, byte mode, level M), verified against an independent generator (byte-identical matrices for byte-mode payloads of every supported version) and an independent decoder (every rendered PDF decodes to its exact reference). The static guards pin both: the image calls are allowed only in the invoice file and only in the shape that registers the embedded bytes under one constant name and draws that name (anything that could name a path stays refused), and the two new files are pinned sample files.

The sample tax-input rule

For each order line, in this order (the choice is recorded on the preview as taxInput.selection):

  1. An approved setting of the product that is in force today (IST, the facts' clock), ignoring the order date. This is the one rule the sample deliberately bypasses: the issuer asks "what applied on the order's date, approved only". A setting that only starts in the future is never picked, a rejected one never, and a draft or pending proposal never displaces an approved setting that is in force (so the figures under review do not change silently the day somebody's proposal takes effect). The other settings are listed as notices.
  2. Else the approved setting that covered the order's date (what the issuer itself would use), even though it has ended since; a notice says so.
  3. Else a draft or pending setting in force today (newest first), labelled as not approved with a warning.
  4. Else, for Hoodie lines only (matched on the case-insensitive substring hoodie of the line's product name), the owner's sample HSN 6109 / GST 5%, labelled SAMPLE / UNVERIFIED, with a warning that the real issuer would not issue the order for the stated reason.
  5. Else the line is UNRESOLVED and no tax is shown for it.

A setting that starts after the order's date is a warning (the real issuer would not use it for that order), not a footnote, and the order's status then reads COMPLETE_WITH_WARNINGS; page 1 of the PDF points at the warning by its code and the review notes repeat that caveat inside the sample-inputs box.

The owner's 6109 / 5% is the fourth tier, a fallback — not an override (decision for the owner to confirm). A product's own setting that is in force beats it, so the PDF can show another HSN and rate than the owner described. The owner's brief calls the Hoodie configuration temporary sample data, which is why the system's own setting comes first: when it is 6109 at 5% the two coincide, and when it is not the preview says so instead of hiding it (SAMPLE_TAX_DIFFERS_FROM_OWNER_INPUT, named on page 1 of the PDF and given in full in its review notes and in the portal's review notes). The alternative — apply 6109 / 5% to every Hoodie line whatever the product says — is a one-function change if the owner prefers it, at the price of a sample that no longer reflects what the system holds. Either way "approved" on a setting is only the system's flag (a Super Admin's attestation, see Context), and the PDF says so beside it.

The order-item snapshot columns (HSN/rate recorded on the item) are deliberately not used for the figures. The real issuer prefers them; the sample must show the owner's sample input, not whatever a past order happened to record. When a snapshot exists and differs, a warning (ITEM_SNAPSHOT_DIFFERS) says so.

The arithmetic is the issuer's own kernel (computeInvoice): GST-inclusive extraction (taxable = net ÷ (1 + rate), rounded half-up; CGST and SGST equal halves) and pro-rata allocation of order-level discounts and fees (largest remainder). These are the issuer's own unapproved treatment — ADR 0019 lists them as requiring an accountant's sign-off — and every preview says so in its "calculation method" statement (NOT APPROVED): in short on page 1 of the PDF ("unapproved treatment", "Tax Approval: NOT APPROVED (sample)"), and in full in the JSON, in the portal's review notes and in the PDF's review notes whenever it has them. That statement is the sample's own exact statement (sampleTreatmentNote) of how the figures were made: the inter-state and intra-state rounding rules and the allocation as the code applies them (an intra-state half is the rounded GST share of the net, and the taxable value is what remains, so the odd paisa sits in the taxable value), and the sample's HSN/rate rule, not the issuer's — which reads the order item's snapshot first. A test pins each sentence against an independent computation. Where the product's setting covers the order's date the sample's rule and the issuer's coincide, and tests compare the two over randomised orders so the arithmetic cannot drift.

Security and exposure

  • Server gate, two layers. The permission access_accounting_data and a hard-coded audience of six roles: accounts_admin, gst_accountant, accounts_staff, auditor, owner, super_admin (previewAudienceGate). The second layer is defence in depth — editing the permission table cannot open the surface to support, warehouse or a new role. /invoice-previews is a different prefix from /invoices, so the existing /invoices group and its gate do not apply to it; routes.go gives it its own group with both gates. The portal permission view_invoices matches exactly this set but is UI-only; the server is the boundary. No new permission, no migration, no new flag.
  • Uniform 404 from a four-order allow-list. The order number in the URL only selects one of four constants (sampleReviewOrders); it never reaches a query. Any other value, a malformed value, and an allow-listed order that is absent from the database all answer the same 404 with a byte-identical body.
  • Read-only. One REPEATABLE READ, READ ONLY transaction per request, always rolled back, never committed, running the sample's minimal facts query (exactly the requested orders and the records that belong to them: no other order, user, role or log, no table-wide count, no candidate scan of other products; the same query the owner pastes into the production terminal) plus a single SELECT that projects only the seller keys of the settings document (the paths the seller resolver reads, copied unchanged: numbering, switches, mail and bank settings and the rest of the company settings never leave the database). Tests prove the scope of what is read - the statements sent, the keys of the settings read, the content of the facts with a neighbouring order, an audit note and unrelated settings in the database - and that the previews are identical to those built from the broad read. Tests run the surface on a pool that refuses writes, and compare table fingerprints and the issuance-gate setting before and after the requests.
  • No buyer personal data. The facts carry a delivery state, a buyer-GSTIN presence flag and a payment reference already masked to first 4 + last 4 (and masked again by the builder, which is idempotent). Names, phones, e-mails, addresses and the buyer GSTIN never enter the response or the PDF.
  • Response headers. The PDF is application/pdf with Content-Disposition: inline|attachment; filename="Sample-Invoice-Preview-<ORDER>.pdf", Cache-Control: private, no-store and X-Content-Type-Options: nosniff; the JSON routes are Cache-Control: private, no-store.
  • Logs only, no audit rows. Each view logs the action, order number, role and user id. No accounting.audit_log row is written: the audit writer is a write and the surface is read-only by construction (the audit package is on the guard's import ban list); there is no state change to audit, and a request that must succeed with the database refusing writes cannot also insert a row.
  • Never exposed to customers. The routes live only in the accounting API behind portal authentication; the commerce API has none (internal/compat/invoice_exposure_test.go fails the build if a commerce route mentions invoices or a customer app calls an invoice endpoint). The real authentication chain is exercised in internal/compat/invoice_preview_e2e_test.go: no token is 401, a customer JWT is 403, a support JWT is 403, a customer token presented where a portal token belongs never succeeds, and a granted accounting role gets through. The PDF is rendered per request and returned; it is stored nowhere and sent nowhere.

API

All GET, base path /api/v1/accounting, behind the gate above:

Route Purpose
GET /invoice-previews the four orders: preview reference, order date, payment status, preview status and reason, UNRESOLVED and warning counts, whether a PDF is available
GET /invoice-previews/:orderNumber the full SamplePreview JSON (integer paise everywhere; each uncertain value {state, value, reason})
GET /invoice-previews/:orderNumber/pdf[?download=1] the PDF; 409 SAMPLE_PREVIEW_UNAVAILABLE when nothing can be rendered, 422 for a bad download value

The JSON shape is pinned by golden files. aim-backend/cmd/samplepreview/testdata/golden/ holds, byte for byte, what samplepreview -json writes for six variants of the repository's synthetic facts (the four orders as they are; facts that cannot be trusted; no delivery state; a failed payment; a Rs 10.00 mismatch; an order that does not exist). TestGolden_PortalContractFilesAreWhatTheProgramWrites regenerates them through the real program and fails on any difference (regenerate after an intentional change with UPDATE_GOLDEN=1 go test ./cmd/samplepreview -run TestGolden); the portal keeps byte copies and runs its mappers, its adapter and its page over them, with a test that names any copy that went stale. So neither side can change the shape of the detail JSON unnoticed, and the portal is tested against what the backend really sends rather than against hand-written fixtures. (The list rows and the PDF are covered by their own tests, not by the golden files.)

The portal page is src/app/(portal)/invoices/previews/page.tsx in aim-store-account-admin and its Simple-workspace twin src/app/simple/invoices/previews/page.tsx: nested under the existing Invoices navigation (access rule view_invoices), reached from a link on the Invoices pages, with no new navigation item. The PDF is fetched as a blob with the portal token, never as a public link.

Consequences

  • Deploying this changes nothing about issuance. No migration, no schema change, no flag, no permission row; the three routes are new and read-only. Issuance stays blocked and OFF; invoicehook, the sweep and the backfill are byte-for-byte what ADR 0019 left.
  • The preview is not evidence of anything. It is not a tax invoice, not an accounting record and not an accountant's determination. HSN 6109 and GST 5% are the owner's temporary sample values; the Hoodie's real classification is still a question for the accountant (see below). Passing the preview, or the owner liking the layout, approves nothing.
  • The audience is defined in code, not in the permission editor. The portal's view_invoices permission is a UI affordance (the server does not enforce it), so switching it off for a role in the permission editor hides the screen but does not close the endpoints for that role; the six-role list in invoice_previews.go does, and only a code change widens or narrows it.
  • Sample figures can differ from what the issuer would do. The sample uses today's setting where the issuer uses the order-date setting, and the owner's input where the issuer would hold. Each such difference is a labelled warning or notice on the preview itself.
  • The sample recomputes; an invoice never does. ADR 0019 requires an issued invoice to be persisted once and never recomputed from live product tax metadata. The sample recomputes from the product's current settings on every request. That is acceptable only because a sample is never stored, numbered or relied on.
  • A new guard entry must be edited deliberately to add a sample file, an import, an imported symbol, a name used from the rest of the package, a caller, a call that may run at package initialisation, or a method the standard library calls implicitly; that friction is the point.
  • Not built, deliberately: any stored or e-mailed preview, any preview for an order outside the four, any buyer detail, any change to the PDF of a real invoice (the real renderer invoicepdf.go is untouched; the sample has its own), a shareable link, and an audit trail beyond the request log.

How to operate it

In the portal. Sign in with one of the six roles → Invoices → Sample invoice previews (link on the Invoices page, in both the standard and the Simple workspace). The list shows each order's preview status; open one to read the details, or view/download its PDF.

The three endpoints are listed above. They work only after the backend carrying this change is deployed, and the screens additionally need the account-admin portal carrying it.

Offline, without deploying anything. The owner can have the four PDFs without anything of ours being deployed. It takes a computer with Go 1.25 or later and a checkout of a branch that contains both programs (today: this branch on top of the dry-run branch, see the dependency above); the first go run fetches the Go modules, so it needs the network once (the programs themselves use none).

  1. From aim-backend, run go run ./cmd/samplepreview -print-owner-block. It prints a script — plain text; printing it touches no database. The script starts a read-only session (PGOPTIONS) with statement, lock and idle limits, opens a BEGIN READ ONLY transaction, checks — without attempting any write — that PostgreSQL itself reports the transaction and the session as read-only and that no transaction id exists, only selects, ends with ROLLBACK, and prints a facts document between -----BEGIN AIM-ORDER-FACTS-V1----- and -----END AIM-ORDER-FACTS-V1----- (the END line only after the rollback has succeeded). It reads exactly the four orders and the records that belong to them (lines, refunds, invoice rows, the committing payment intent and the count of its audit-log rows, the wallet redeem total, the products they reference with those products' tax settings) plus company configuration (the seller GSTIN and state, whether a legal name, address and PAN are configured, the issuance on/off setting, the invoice series); no other order, user, role, log, migration or table-wide count, no audit-log notes, no price, stock or category, no record ids of orders and order lines, no invoice number (a marker says one exists), and customer-typed state text cut to 45 characters. The larger readiness block of invoicedryrun -print-owner-block shares the same read-only frame and is also accepted.
  2. Paste that script into the server terminal (its first line says where). This is the one step that reads the production database, read-only.
  3. Save what the script printed (not the script) as a UTF-8 text file outside the repository, for example facts.txt in your Documents folder. A terminal capture is fine: the markers are matched as whole lines. Windows PowerShell 5's > and Notepad's "Unicode" save UTF-16; the program reads that too.
  4. From aim-backend: go run ./cmd/samplepreview -in <path>\facts.txt -out <path>\previews with a directory outside the repository. It writes Sample-Invoice-Preview-<ORDER>.pdf per order (-json also writes the preview JSON of every order, also one that has no PDF; -check prints the summary and the digest of the facts and writes nothing; -h explains the program). It calls no database, no network and no clock and reads no environment variable, and it stops with a plain sentence when it is given the script instead of its output, or an empty or incomplete paste.

Real-order mode (-real). The plain mode renders any facts, so that the layout can be reviewed on any data. For the owner's review of the four REAL orders, samplepreview -real -now <UTC time> -in facts.txt -out <dir> is strict and refuses, before writing anything, unless the facts cover exactly the four allow-listed orders (none missing), carry the database's own proof of a read-only read (transaction_read_only on, write guard PASS, no transaction id), were read no more than -max-age (default 48 h) before -now (the caller supplies the time; the program reads no clock) and are not test data (a product called "synthetic", "rehearsal", "dummy" or "test order", also when the letters are spaced out or interrupted by invisible characters), and the output folder holds no sample file of an earlier run. It writes one AIM_STORE_SAMPLE_INVOICE_<order serial>.pdf per order - an order whose sample cannot be certified (its amounts do not reconcile: any failed reconciliation check, not only the checkout formula) keeps its PDF, which shows the discrepancy and says "APPROVAL BLOCKED", but is named ..._BLOCKED.pdf - the preview JSON of every order (-json) and SAMPLE_INVOICE_REAL_ORDERS_REPORT.txt with the SHA-256 of the facts and of every PDF, the freshness limit applied and the warning codes to read on each PDF. The exit status is 2 when any order is blocked and 1 when the facts are refused (nothing is written). Run the built program (go build -o), not go run: go run reports the program's exit status 2 as 1 and would make a blocked run look like a refusal.

An independent verifier (cmd/samplepreview/verify_test.go) re-reads the facts, recomputes every figure with its own exact-rational arithmetic and checks the preview JSON and the text of every PDF (order, product, quantity, historical unit price, paid total, GST split, A4, the watermark and band on every page, no invoice number, no personal data); pointed at the real output it is the final check of the owner's PDFs:

SAMPLE_VERIFY_FACTS=<facts.txt> SAMPLE_VERIFY_DIR=<output dir> \
  go test -count=1 ./cmd/samplepreview -run TestVerify_GeneratedRealOutput -v

It is itself tested against fit and damaged output and against 2,000 random orders. The owner-facing script generate-real-sample-pdfs.ps1 (kept with the owner's extraction block, outside the repository) builds the program, runs it into a fresh timestamped folder and runs the verifier for exit status 0 and 2 alike.

Every PDF made this way says on its first page that it was rendered offline from a facts file supplied by the operator, with the start of the SHA-256 of the facts text (the program prints all of it): the program cannot check where a file came from, so the document says what it is.

What the offline PDF shows for the seller depends on the settings the facts carry. The facts redact the legal name, address and PAN as the marker <configured>. When the accounting settings carry a seller, those three print as UNRESOLVED in a PDF made offline; when they carry none, the built-in entity record fills the legal name and address (marked unconfirmed) and only the PAN is UNRESOLVED. The in-portal preview reads the real settings and shows what is configured.

What has NOT been done. As of this record the change exists only as local commits: it is not pushed, not merged and not deployed, and the code itself reads no production data (the portal route reads in one read-only transaction once deployed). It also cannot be merged on its own (see "Dependency — merge order"). The owner has run the read-only extraction on his own server (2026-10-09) and generated the four PDFs of the real orders offline from it; the tests use synthetic orders on scratch databases only.

Before issuance (workflow B stays blocked until these are settled)

Taken from the blocker set of the dry-run preview (aim-backend/internal/accounting/service/dryrun.go); none is resolved by this ADR, and none is made easier by the sample:

  • HSN/SAC. The Hoodie's code is the accountant's decision. 6109 is only the owner's sample input and has not been verified. The database's approved status on a tax setting is a Super Admin's save-time self-attestation, not an accountant's approval (TAX_NOT_ACCOUNTANT_APPROVED).
  • GST rate, its effective-date treatment and the GST-inclusive extraction of the stored prices (also needed by every paid order, not just the Hoodie).
  • Seller details. The seller identity falls back to the built-in entity record when accounting settings carry none, and nobody has confirmed it (SELLER_IDENTITY_NOT_APPROVED); the seller state must agree with the registration.
  • Accounting approval of the document: the legal nature of an internal tax invoice dated the day it is created for a sale made earlier (DOCUMENT_CLASSIFICATION_NOT_APPROVED).
  • Approver. At least one active accounts_admin or gst_accountant must exist, because only those roles can run the targeted issue and backfill endpoints (NO_APPROVER_ROLE).
  • Numbering. An active invoice series for the financial year whose numbers are at most 16 characters (for example prefix AIM with four digits), exactly one active series, and the series itself approved (NO_ACTIVE_SERIES, SERIES_NOT_COMPLIANT, MULTIPLE_ACTIVE_SERIES, SERIES_NOT_APPROVED).
  • Historical tax treatment. The issuer resolves tax by the order's IST date; an order placed before any approved setting's effective date is held (NO_TAX_DATA), and invoices are dated the day they are created, never back-dated.
  • Scoped backfill safety. The backfill takes the oldest awaiting orders up to a limit and cannot be aimed at the four Hoodie orders (it orders by creation time), and once the gates are open the automatic trigger and the 72-hour sweep issue invoices for new paid orders as well. A scoped, previewed procedure is needed before the gates are opened.

When all of these are settled and the owner opens the gates through the existing production-issuance-flag workflow, the real invoices — not this sample — are what carry numbers and tax.