Skip to content

0022 — Automatic GST invoice issuance: stored documents, controlled operation, historical-order controls

Status: proposed (2026-10-09) — implemented on branch feat/automatic-gst-invoice-issuance; not merged, not deployed, and not activated. Builds on ADR 0019 (the canonical generator, the trigger, the sweep), ADR 0020 (product GST/HSN classification) and ADR 0021 (the locked invoice design and its layout engine). Production keeps ACCOUNTING_INVOICE_ISSUANCE_ENABLED=false, the settings gate invoice_issuance_enabled=false and ACCOUNTING_JOURNAL_ENGINE_ENABLED=false; deploying this change issues no invoice, takes no number and touches no existing order. Activation is a separate, controlled operation (docs/runbooks/invoice-issuance-activation.md).

Context

ADR 0019 made one generator, service.IssueInvoice, produce an immutable invoice (header, persisted snapshot, gap-free number) when an order is paid, with a recovery sweep and an explicit backfill. It left the system correct but not yet operable as a statutory book:

  1. The document was not the document. The invoice PDF was re-rendered from the snapshot on every request with a plain layout, and nothing proved that the bytes shown today are the bytes that were issued. The owner then approved a locked design (ADR 0021) that existed only for the internal sample preview.
  2. A failure left no trace. A failed attempt correctly consumes no number, but staff could not see which orders were waiting, why, or how often they had been tried; "no active series" and "HSN missing" looked identical to "nothing happened".
  3. Nothing said whether issuance could run. Seller identity, numbering, tax configuration and the stored documents were all checked, but only at the moment of the first failing order.
  4. Reports read the wrong columns. The HSN summary, the GSTR-1 HSN flag, the GST source ledger and the sales register read the order's own line columns, which are empty whenever the HSN came from an approved tax configuration — precisely the automatic-invoice case — so a CA's export would have been incomplete.
  5. Historical orders were one careless call away from being invoiced. The explicit backfill invoices the oldest awaiting orders; the only protection was that nobody ran it. Some historical paid orders are test orders that must never be invoiced.
  6. Credit-note numbers broke the numbering rule. They were taken from a Postgres sequence at draft time and formatted CN-2026-27-000001 (17 characters; the limit is 16, CGST Rules 46 and 53), and a sequence is not gap-free. A full-order credit note also took its tax split from the order's own columns, which are empty for an automatically issued invoice.

Decision

The issued document is stored, checksummed and drawn by the locked design

  • RenderInvoicePDF now maps the persisted dto.InvoiceSnapshot onto the layout engine's data contract (LockedInvoice) and draws it with the same engine as the sample preview (samplepreview_locked.go, locked-a4-v1): TAX INVOICE wording, the locked boxes, QR, no sample markers. It refuses anything that does not foot (lines sum to the totals, taxable + GST = grand total, no round-off or cess it cannot show) and invents nothing: a seller PAN, phone, e-mail, signature or buyer value appears only when it was recorded. The sample path is byte-identical to before (verified against the sample PDFs); static guards extend, not relax, ADR 0021's isolation (samplepreview_locked.go joins the pinned set; the two files that may touch it do so through an explicit allow-list).
  • accounting.invoice_documents (migration 098) stores the rendered PDF, written in the same transaction as the invoice, its number, its snapshot and its audit row. An invoice therefore never exists without its document, and a render failure rolls the whole issuance back with the number. The row is append-only and carries the SHA-256, which the database recomputes (CHECK sha256 = encode(sha256(pdf),'hex')). The PDF is private by construction: a database row behind the authenticated accounting API; there is no file and no public path.
  • GET /invoices/:id/pdf serves the stored bytes after verifying them twice (in Go and by the database's own recomputation); a document that fails is never served (500, audited as Critical). A role without customer-contact access gets the same layout rendered on demand with the buyer's mobile and e-mail masked. Every view (VIEW) and download (EXPORT, ?download=1) writes an audit row before any byte is sent; if the row cannot be written nothing is served. EnsureInvoiceDocument writes a missing document (an invoice issued before documents existed) from its snapshot, audited, never replacing one; CheckInvoiceDocuments is the integrity report.

Numbering, idempotency and failure

  • Numbers are PREFIX/FY/serial, at most 16 characters of A-Z a-z 0-9 / -, allocated in the issuance transaction under the active series' row lock, from the financial year of the IST instant of issuance. The invoice date is that IST day (not the order's day): a delayed confirmation across 31 March / 1 April lands in the new year's series. A failure at any step — including storing the document — rolls the allocation back (tested by injecting a failure at the last step).
  • Migration 098 moves the numbering rules into the database as well: one active series per financial year, a counter that can never go backwards, a series whose numbers are on issued invoices cannot be renamed, re-padded, re-yeared or deleted (that check never runs on the hot issuance path), a YYYY-YY financial-year label, a closed invoice status set.
  • Idempotency is unchanged and now covered end to end: an advisory lock per order, a unique index of one sales invoice per order, the provider-confirmed payment as the only trigger. A webhook delivered twice, the inline trigger, the recovery sweep and a staff retry racing on one order produce one invoice, one document and one number.

Seller identity is configuration, never a default

  • A tax invoice must carry the supplier's name, address and GSTIN. An order whose seller legal name or registered address is not configured is held (pending_tax_review, with the reason) instead of being printed with a gap. The legal-entity record remains a fallback for the company's own GSTIN and is reported as such, not as saved configuration. A configured PAN must be well-formed and equal characters 3–12 of the GSTIN, or it is refused; phone and e-mail print only if configured. Saving Settings refuses a seller identity (GSTIN / PAN / state) that issuance would refuse, when the save introduces the problem.

Operating it: attempts, readiness, queue, retry

  • accounting.invoice_issue_attempts (098) is the operational record of attempts that did not produce an invoice: one row per order, written best-effort outside the issuance transaction by every sanctioned caller, closed when the invoice exists. It holds no customer data and no number; an unexpected error is recorded as a generic sentence, the real text stays in the server log.
  • GET /invoices/readiness returns structured, per-check blockers with who must act (gates, seller identity, numbering, approved tax configurations, stored documents, history). customerAccessEnabled is a constant false.
  • GET /invoices/issuance-queue lists paid orders without an invoice, held invoices and failed attempts with reason, attempt count and next action; POST /invoices/issuance-queue/retry (accounts_admin / gst_accountant, reason required, both issuance gates) goes through service.IssueManually → the one generator. The compat guard allow-list names the only files that may call IssueInvoice and IssueManually.
  • Series administration: issued-number facts per series, activate / deactivate with a reason, a friendly 409 when a year already has an active series.

Historical orders: excluded or approved, never swept in

  • accounting.invoice_exclusions (migration 100): the owner marks an order "never invoice" (a test order, a non-sale) with a reason. The generator refuses it and it leaves every awaiting-invoice queue and count (one shared SQL definition). An order that already has an invoice cannot be excluded; an exclusion can be lifted, leaving history.
  • accounting.invoice_backfill_approvals (migration 100): every backfill run now needs an approval — a scope (IST date range of the order), a cap, an expiry (≤ 30 days), a reason — given by an owner or super admin, never by the roles that run the backfill, and the run is refused if the same person gave it. The cap is taken one order at a time under the approval's row lock, so concurrent runs cannot exceed it. Scope, cap, reason, approver and expiry can never be edited; an approval can only be revoked. Automatic issuance never backfills: the sweep still looks back 72 hours only. Issuing an order older than that window that has no invoice is a historical backfill however it is triggered: the single-order retry and the manual issue endpoint take the same approval (approvalId), check the same scope and cap, name the approval in the invoice's own audit row, and give the slot back if no new invoice results. An order that is merely held (no number yet) may still be excluded.

Reports and reconciliation

  • New: invoice register (issued invoices by date with whole-range totals), invoice-number reconciliation (per series: gaps, duplicates, unparsable numbers, a counter drifted ahead of or behind the invoices) and payment-to-invoice reconciliation (missing invoices, held invoices, amount mismatches, payments no longer captured, missing documents), each as JSON and CSV; CSV downloads are audited (EXPORT) and carry every row (one full pass of up to 50,000; a larger export is refused with 422 EXPORT_TOO_LARGE rather than truncated). The reconciliation engine also raises payment_amount_mismatch.
  • Corrected: HSN summary (now per HSN and rate), GSTR-1 HSN flag, GST source ledger and the sales register read the issued invoice's persisted lines (the order columns only for an invoice with no snapshot). All GST reports stay drafts for a CA: isFilingReady is false and no return is filed.

Credit notes

  • Migration 099 adds accounting.note_series. A credit note's number is allocated when it is issued, inside the issuing transaction, from the year's series (CN/2026-27/00001, 16 characters), gap-free; a draft carries a DRAFT-… placeholder and consumes nothing. A deactivated series stops numbering (409); it is not silently replaced. A credit note for a whole order reverses its invoice figure for figure (taxable value, each tax head, total, lines from the persisted invoice); a partial (refund) note keeps its honest zero tax split. Invoices are never edited or cancelled in place: a correction is a credit note, and a re-issue is a new invoice with a new number.

Access control and audit

Every sensitive action is authorised on the server; the portal only mirrors it.

Action Roles
read invoices, queue, readiness, reports any role with access_accounting_data
view / download a PDF same, audited; the buyer's contact is masked for the roles that lack customer-contact access (a fixed role list mirroring the portal's view_customer_contact permission; today that is warehouse, which has no invoice access at all)
retry an issuance, write a missing document, run an approved backfill accounts_admin, gst_accountant (an order older than the sweep window additionally needs an owner approval)
change an invoice series; edit Settings accounts_admin
approve / revoke a backfill owner, super_admin
exclude / lift an order owner, super_admin
one invoice's audit trail view_audit_logs
document-integrity scan accounts_admin, gst_accountant, auditor, owner, super_admin

Audit rows carry actor login and role, action, timestamp, request id, entity, before/after and the stated reason, and are written in the same transaction as the change (the trail is append-only by trigger). There is no customer-facing invoice route; deploying this feature creates none.

Consequences

  • Deploying changes no behaviour for customers or for existing data. Issuance stays off; pending_tax_review semantics, eligibility and the 72-hour sweep are as in ADR 0019, plus the seller-identity hold. Migrations 098–100 are additive and idempotent; each has a compensating rollback script that warns when statutory data would be lost.
  • An issued document can be proven unchanged (SHA-256) and regenerated byte-for-byte from the snapshot (the renderer is deterministic); a renderer upgrade will not touch issued documents.
  • The cost: the stored PDFs live in Postgres (tens of kilobytes each), and the backfill is deliberately harder to use than before — the owner's approval is part of the procedure.
  • Re-invoicing the same order is not supported. An order has at most one sales invoice (a unique index). A wrong invoice is corrected by a credit note; issuing a replacement invoice for the same order needs a CA-approved procedure outside this change.
  • Not done, on purpose: no GST return is filed; the journal engine is not enabled; no customer can see an invoice; no historical order is invoiced; no e-invoice (IRN) is generated; an invoice carries "Authorised Signatory" with blank space, not a digital signature; no payment, wallet or order row is written.

Before activation (the owner and the company's CA must settle these)

These are not defects in the code; they are decisions and facts the code must not guess:

  1. HSN/SAC and rate per product. The sample HSN 6109 at 5 % is not an approved configuration. Each sold product needs an HSN/SAC and rate, confirmed by the CA and approved in Settings — ideally by someone other than the person who entered it (readiness flags every self-approved configuration).
  2. Reverse charge is recorded as "No" for every invoice (AIM sells its own goods); the CA confirms.
  3. Signature / e-invoice. Whether the document needs a signature or an IRN before it may leave the company (B2B above the e-invoicing threshold), and therefore whether it may ever be sent to a customer, is the CA's call; the system keeps customer access off meanwhile.
  4. Invoice date semantics (IST day of issuance rather than of the order), the credit-note series convention, and the treatment of partial-refund credit notes.
  5. Seller details in Settings: legal name, registered address, GSTIN; optional PAN, phone, e-mail.
  6. An active invoice series for the current financial year that yields numbers of at most 16 characters.
  7. Exclusions for the historical test orders, recorded by the owner before activation.

See docs/runbooks/invoice-issuance-activation.md for the order of operations, the checks, and the rollback / recovery plan.