0019 — Automatic internal GST sales invoices¶
Status: accepted (2026-10-07). Builds on aim-backend/docs/gst-invoice-architecture.md (the schema and invariants) and the accounting domain's issuance seam; touches no customer-facing surface.
Context¶
Paid product orders appeared in the Account Admin portal (/simple/orders) with
the Invoice column reading Not created. The cause was structural, not a
failed job:
service.IssueInvoicewas the only writer ofpublic.invoices, and its only caller wasPOST /settings/issue-invoice— a staff click, one order at a time. Nothing ran when an order was paid.- That endpoint is double-gated off (
ACCOUNTING_INVOICE_ISSUANCE_ENABLEDandaccounting.settings.invoice_issuance_enabled), and the deploy workflows pin the env flag tofalse. So the manual route was also unusable. /orderscarried only aninvoicePresentboolean and the portal hardcoded the invoice id/number tonull, so an invoiced order would still have read "Not created".
The first issuance code had never run against real data and had four latent defects that would have produced wrong statutory documents the moment it was switched on:
- It added GST on top of line totals, but AIM Store prices are
GST-inclusive (
order_checkout_repo.go: "GST is inclusive in the displayed price"). The invoice total would have exceeded what the customer paid. - It read the seller GSTIN/state from
payload.seller_gstin/gst.*, but the portal's Settings page saves company data underpayload.portal_settings.*. - It read
orders.place_of_supply, which checkout never writes, so every invoice would have been inter-state (IGST), including a Tamil Nadu customer of a Tamil Nadu seller. - A
pending_tax_reviewplaceholder was never completed: the "idempotent" check returned it forever, even after the tax data became available.
Decision¶
One canonical generator, called automatically after payment, retried by a sweep, recoverable by an explicit backfill.
- Trigger. Every order is created already
paidinsidecommitOrderCore(both the credits-only path and the provider-confirmed gateway path). Right after that transaction commits,invoicehook.Dispatch(orderID)hands the order to the issuer on a detached goroutine with its own context. A failing, slow or panicking issuer cannot affect the customer's payment or response (tested). Apaymentopsmaintenance pass (invoice_issue, everyPAYMENT_MAINTENANCE_INTERVAL_SECONDS) re-derives "paid, eligible, no invoice, created in the last 72 h" from the database, so an attempt that failed or never ran is healed without any state of its own. With no issuer installed — today's production default — all of it is a no-op. - Gates unchanged. The issuer is installed only when accounting and
ACCOUNTING_INVOICE_ISSUANCE_ENABLEDare on, and it re-reads the settings gate on every call, so the existingproduction-issuance-flagkill switch stops it within one request. No gate was added or removed. Deploying this change turns nothing on. - Eligibility (one definition,
repository.OrderInvoiceEligibleSQL, mirrored byservice.OrderEligibility): payment captured —payment_statuspaid, orpartially_refunded(the sale happened; only part was returned, which a credit note — not built here — records) — status notcancelled/rejected/failed, amount > 0. Pending, failed, cancelled, fully refunded, refund-pending and zero-value orders are never invoiced — including by the manual action (now 422ORDER_NOT_ELIGIBLE). The preview lists the captured-but-excluded orders so the exclusion is visible. - Idempotency, three layers. (1) A per-order advisory lock inside the issuance
transaction. (2) A partial unique index,
uq_invoices_one_sales_invoice_per_orderonpublic.invoices(order_id) WHERE credit_note_for IS NULL— credit notes legitimately share the order id. (3) A unique snapshot row per order. Replays, concurrent webhooks and the sweep all converge on one invoice; a lost race is answered with the winner. - GST-inclusive extraction. Taxable value = net line value ÷ (1 + rate),
rounded half-up; GST = net − taxable. Intra-state CGST and SGST are always
equal halves (any odd paisa sits in the taxable value, ±1 paisa from exact);
otherwise IGST. Order-level discounts (coupon, reward points) and
fees (delivery, platform) are allocated across goods lines pro rata
(largest-remainder, exact to the paisa). The adjustment is cross-checked against
the order's own recorded coupon/reward/delivery/platform/tax — an order that
does not reconcile to its items is held, never silently absorbed. The
grand total is, by an asserted invariant, exactly
orders.final_amount. HSN/SAC and rate come from the order-item snapshot columns when present, else the approved tax configuration effective on the order's IST date. - Fail closed, never guess. A missing HSN/rate, an unrecognised delivery
state, no line items → a
pending_tax_reviewinvoice (no number, NULL amounts) with the reasons in its audit note; re-checked by the sweep and completed in place once the data exists. No active series for the invoice date's FY → nothing is written and the order stays in the recovery queue. - Place of supply =
orders.place_of_supplyif it is a recognisable GST state, else the delivery state (the state where goods are delivered), mapped to its code by an exact-name table (the checkout clients' own state list). - Seller identity comes from
accounting.settings(every shape in the repo, includingportal_settings.company), falling back to the repository's entity record (aim-store-website/src/data/company.js: legal name, GSTIN, registered address) — a test fails the build if the backend constants drift from that file. The seller state is derived from the GSTIN (its first two digits are the registration's state code) and any separately configured state must agree with it — a disagreement, or a malformed configured GSTIN, holds invoices with the reason rather than flipping every sale to IGST or printing a bad identity. PAN, CIN, phone, e-mail and signature are never invented: absent configuration is listed on the invoice as "not configured". - Numbering is the existing
accounting.invoice_seriesallocator (atomicUPDATE … RETURNING), now selecting the series by the invoice date's financial year rather than the order date. A GST invoice number may have at most 16 characters from A-Z a-z 0-9 / - (CGST Rule 46), and issued numbers are permanent, so a series that would produce a longer one is refused at creation and, if it already exists, issuance writes nothing (the serial is given back) and the preview shows it as a blocker.AIM/2026-27/000001is 18 characters; use e.g. prefixAIMwith 4 digits (AIM/2026-27/0001). The financial-year label is now alwaysYYYY-YY(2008-09, not2008-9). - Immutable snapshot. The complete document — seller, buyer, order/payment
reference, per-line HSN/rate/taxable/CGST/SGST/IGST, totals, who/what generated
it — is stored in
accounting.invoice_snapshots(append-only trigger). The Account Admin screen and the PDF are both rendered from it, so they cannot disagree and no later product/customer/settings change rewrites history. Issued invoices cannot be updated or deleted at the database level (trg_invoices_issued_immutable); a correction is a credit note, which is not built here. - PDF.
GET /api/v1/accounting/invoices/:id/pdf, rendered server-side (pure Go,go-pdf/fpdf) from the snapshot, A4, byte-deterministic, behind the same portal authentication and permission as the invoice list. Printed as "Rs." (the core font has no rupee glyph). No logo bitmap, QR code or signature. - Recovery queue and backfill. "Create Missing Invoices" is now an exception
queue:
GET /invoices/missing, one backend predicate (OrderAwaitingInvoiceSQL), no date range, shared by the dashboard card, the drill-down and the order-list filter (the reconciliation detector uses the same predicate, scoped to its report period). The card asks for one row and reads the queue's total and value; the page shows the oldest 100 with the true total. Orders paid before automatic invoicing are not invoiced silently: the sweep only looks 72 h back. They are handled byGET /invoices/backfill/preview(read-only: counts, age, what would be held for tax review, what is excluded, readiness) followed byPOST /invoices/backfill(accounts_admin / gst_accountant, both gates, audited, same generator, resumable). A backfilled invoice is dated the day it is created — an invoice cannot be back-dated — and carries the order date. - Internal only. No customer route, screen, PDF, e-mail, SMS or WhatsApp
exists or was added;
internal/compat/invoice_exposure_test.gofails the build if a commerce route mentions invoices or a customer app calls an invoice endpoint. The portal's old "Email copy" stub was removed.
Consequences¶
- Deploying changes nothing in production until the owner enables issuance.
Migration
096(one unique index, one append-only table, two triggers) is applied by the next manual backend deploy; it refuses to run if duplicate sales invoices already exist. - Before enabling (all existing screens/workflows): an active invoice series for the current FY whose numbers are ≤ 16 characters (the preview checks); approved HSN/SAC + GST rate for every product being sold (otherwise invoices are held for tax review, not issued); an accountant's sign-off of the inclusive-price treatment above, which the docs have always listed as requiring professional validation. Seller identity needs nothing if the entity record is right.
- Deleting a customer who has an invoiced order is refused by the existing
HasInvoiceHistoryguard (statutory records must be kept) — previously only a theoretical case. - Not built, deliberately: correction/void/credit-note-from-invoice, refund accounting, internal notes, SKU (the commerce schema has none), reverse charge, e-invoicing/QR. Each is a separate decision.
How to operate it¶
- Owner/accountant checklist above; then enable via the existing
production-issuance-flagworkflow (it moves both gates together). - New paid orders are invoiced automatically from that moment.
- For orders paid earlier: portal → Today's Work → Create Missing Invoices → Review before creating (read-only preview) → confirm. Orders held for tax review complete automatically once their product tax codes are approved.
- Watch
aim_invoice_awaiting(paid orders inside the sweep window still without an invoice — the alertInvoiceSweepBacklogfires after 30 minutes) andaim_invoice_issue_total{trigger,outcome}in Prometheus. Create next year's invoice series before 1 April: with none, every new invoice waits in the queue. - Known limits: the PDF uses a core font, so non-Latin text (e.g. Tamil) prints as dots — the document says so, and the stored record and on-screen copy are exact; a held invoice completed later is labelled automatic whatever created it; the append-only snapshot retains buyer contact details permanently. Before enabling, check the preview's "held for tax review" count for old placeholder rows — the sweep completes them (dated that day) as soon as their data exists.