0024 — Scalable automatic GST invoice numbering, verified tax rates and recorded GST decisions¶
Status: proposed (2026-10-14) — implemented on branch feat/scalable-gst-invoice-system (PR #105) and revised after an independent three-part review; not merged, not deployed. Builds on ADR 0019 (automatic internal sales invoices), 0020 (product GST/HSN), 0022 (automatic issuance) and 0023 (Super Admin access). Nothing here changes an issuance switch or creates a series: ACCOUNTING_INVOICE_ISSUANCE_ENABLED, the settings gate invoice_issuance_enabled, ACCOUNTING_JOURNAL_ENGINE_ENABLED and customer access to invoices are exactly as they were, and deploying this change issues no invoice, takes no invoice number and writes no production data beyond three additive migrations.
Context¶
Four things stood between the deployed engine (ADR 0022) and a system the company could switch on:
- A hard ceiling of 9,999 invoices a year. A number was
PREFIX/FY/serial;AIM/2026-27/uses 12 of the 16 characters a GST invoice number may have (CGST Rule 46 — the existing basis of this system's limit; the CA confirms it), leaving four digits. After 9,999 invoices every order was held until a person created another series by hand — and a financial year could only ever have one. - "Approved" was being read as "right". A tax configuration is approved when a role presses Approve, and the Product screen approves in the same step it saves when the saver may approve. Production's two approved configurations are self-approved sample data (the Hoodie's "6109 at 5 %" among them), and the engine would have used them.
- Mandatory GST decisions existed only in people's heads — reverse charge, the invoice date, credit notes, part-refunds, e-invoicing, signature, B2B/B2C, CGST-SGST/IGST, delivery fees, rounding — so nothing could stop an invoice from being issued while one of them was open.
- Readiness said "populated", not "ready". A seller identity that was only the built-in company record, a series with one number left and no successor, a trigger that had been dropped: each read as a pass.
Decision¶
1. Numbering¶
A standard number, PREFIX/YYS/SERIAL — for example AIM/26A/00000001:
| Part | Rule |
|---|---|
| PREFIX | 1–4 characters, A–Z 0–9, starting with a letter (as engineering reads the e-invoice schema, a leading 0, - or / is not accepted there, so a letter is always safe; to be confirmed with the CA) |
| YY | the last two digits of the year the financial year starts in (2026-27 → 26); the series row also keeps the full label. Two digits are unambiguous only within a century, so the standard format accepts financial years starting 2017–2099 (a typed 2127-28 would otherwise take the numbers of 2027-28 for good) |
| S | the series letter A…Z, assigned in order within (prefix, financial year) |
| SERIAL | zero-padded to 11 − len(PREFIX) digits — every digit that fits — so a number is always exactly 16 characters |
Capacity is finite and stated, never "unlimited":
| Prefix | Serial digits | Per series | Per financial year (26 series) |
|---|---|---|---|
| 1 character | 10 | 9,999,999,999 | 259,999,999,974 |
| 2 characters | 9 | 999,999,999 | 25,999,999,974 |
3 characters (AIM) |
8 | 99,999,999 | 2,599,999,974 |
| 4 characters | 7 | 9,999,999 | 259,999,974 |
If every letter is used and the last series is full, the allocator refuses (ErrSeriesNamespaceExhausted): invoices are held with the reason, the readiness page blocks, and nothing is reused, skipped or squeezed in. That is the documented ceiling, not infinity; the screens say so.
Formats considered. The format had to stay within 16 characters from A-Z 0-9 / -, be unique for the financial year, be consecutive within a series, and be easy for a person to read in a register.
| Format | Length | Serial digits | Verdict |
|---|---|---|---|
AIM/2026-27/0001 (legacy) |
16 | 4 → 9,999 a year, one series | the problem this change solves |
A26A0000000001 (compact, no separators) |
14 | 10 → 9,999,999,999 per series | rejected as the default: the company is reduced to one letter, the series letter and the year run into the serial so a register is hard to scan, and there is no separator to tell the prefix from the rest |
AIM/26A/00000001 (standard) |
16 | 8 → 99,999,999 per series, 26 series | chosen: readable, the company prefix stays, separators keep the parts apart, every character is used, and 2.6 billion invoices a year is a ceiling nobody will meet |
A/26A/0000000001 (standard with a one-letter prefix) |
16 | 10 → 9,999,999,999 per series | available today without any change: it is the standard format with prefix A, if the owner ever wants the compact format's capacity |
One allocator, one transaction. allocateInvoiceNumber runs inside the transaction that writes the invoice:
- it takes the active series of the invoice's financial year
FOR UPDATE(a bounded retry covers the row-lock/LIMITquirk) and advances the counter with a guard in theUPDATEitself (next_number ≤ capacity), so two issuers can never take the same serial; - when the number it hands out is the last of the series, the same transaction closes that series (
closed_reason = 'exhausted') and opens its successor (next letter, same prefix and width,origin = 'rollover',predecessor_idset, activated). No request ever sees a full active series, and the successor appears or does not appear together with the invoice that triggered it. A series that is somehow already full rolls over before issuing; - a new financial year opens itself: when the year has no series at all (not even a switched-off one) and an earlier year has a standard series with rollover on, the first invoice dated in the new year opens letter
Aunder a per-year advisory lock (origin = 'fy_rollover'), with the prefix and width of the most recently created such series of the latest earlier year (not the highest letter: after a prefix change the letter says nothing about which prefix is in use). A year that holds any series was decided by a person and is never opened for them. The dry run and the readiness page predict the same series with the same rule; - the legacy format stays, unchanged and without rollover: a legacy series that fills answers
SERIES_EXHAUSTEDand holds orders, exactly as a missing series does; - everything — counter, rollover, successor, invoice, snapshot, audit row — commits or rolls back together. A failed PDF write, a database connection lost mid-transaction or a validation failure after the number was taken gives the number back and undoes the rollover (tested end to end, including a server-terminated connection). There are no gaps by construction, and no number is ever recycled. A rollover or a year-opening is written to the server log only after the commit, so an undone one never appears there.
Financial-year safety. An invoice is dated the day it is issued (IST) and numbered from that day's financial year, read from the database's clock (the issuing transaction's own NOW()), and the sale's year is the order's own stamp (orders.created_at, written by the same clock) compared exactly: a misconfigured application clock can neither mint a financial year nor move a sale placed milliseconds before midnight into the new year. A sale placed in an earlier financial year is not moved silently into the new one (it would also move its tax into the new year's returns): the issue is refused with the reason and no number is used. The automatic sweep does not select such sales (left in, they sat at the front of every batch for 72 hours after year end and starved the ordinary orders behind them), the queue shows them as a financial-year hold with guidance that names the CA (not "create a series", which cannot help), and readiness counts them. There is no in-system way to invoice them today: how a sale that crosses a financial year is invoiced is the CA's decision (§3), and an order that is not a real sale can be marked never-invoice.
Idempotency is unchanged and still the foundation: one sales invoice per order (a unique constraint), the per-order advisory lock, the stored document unique per invoice, payment and webhook replays resolving to the existing invoice. The allocator adds nothing a retry could duplicate, because the number is part of the same transaction as the row that holds it.
The database holds the same rules (migration 101), as a backstop to the code: a generated number_prefix that is UNIQUE (so two series can never share a number whatever is configured) and prefix-free (no series' prefix may contain another's, checked when a series is created or renamed, one transaction at a time); a counter that never goes backwards, never past its width, and — on a series that has issued numbers — moves one number at a time (a jump would skip numbers; positioning a series that has issued nothing is allowed); a closed series stays closed and an exhausted one cannot be activated; one active series per financial year (098, unchanged); a series that has issued numbers cannot be renamed, re-padded or deleted. "Does this series have numbers" is a range look-up on a C-collation index of the invoice number, so it does not read the whole invoices table; the series list reads its issued count and last number from the gap-free counter. The portal and the API can switch a series on or off and switch its rollover on or off, each with an audited reason; nothing edits a counter. A series that is full but was switched off by hand (never closed) is a dead end for its prefix in that year — rollover happens only at the moment an active series takes its last number — and the refusal says to use a different prefix.
Audit. A series created by a person, closed by exhaustion, opened by rollover or by a new year, activated, deactivated or given a different rollover setting each write an audit row naming the actor (or system and what triggered it), the series and before/after.
2. Tax rates must be verified, not merely approved (migration 102)¶
(ADR 0025 / migration 104 supersedes the "independence is recorded only as far as the system can see it" wording below: a verification is now recorded only by a verified person who is not the approver, by proven mobile number and by account, on the values the verifier saw (the request names them; a configuration that no longer holds them answers TAX_CONFIG_CHANGED). It counts only for the approval it confirmed — recorded at or after that approval — and every live verification of a configuration is withdrawn when the configuration leaves approved, so a configuration withdrawn and approved again is verified again. A configuration approved before a second verified person had to approve it cannot be verified at all: it is withdrawn and entered again.)
accounting.product_tax_verifications is an append-only record (it cannot be edited, deleted or truncated) that the business owner, a chartered accountant or a tax adviser confirmed a configuration's exact HSN/SAC, rate and effective date, on a written basis (a 5–300 character reference to the advice), by a named login. It is bound to those exact values: change the configuration and the verification no longer matches (state stale; it is withdrawn before a new one is recorded). Independence is recorded only as far as the system can see it: a store-admin account (where the Product screen records who created and approved a rate) and a portal login (where the verification is recorded) are different UUID spaces with nothing linking them, so a verification is marked independent only when both people are in the same login system and differ — otherwise it is not shown to be independent, which in the usual flow it never is. Readiness warns about every verification not shown independent, whatever capacity the verifier declared; the recorded basis is the evidence. The person states the capacity themselves (nothing is pre-selected).
The engine uses a configuration only while a live verification of exactly its values exists. Otherwise the line is held for tax review with the reason ("approved but have not been verified by the owner or an accountant"), exactly like a line with no configuration. The same holds for a tax snapshot on an order line (the columns checkout may one day fill): it is used only when a verified configuration for the order's date says exactly the same, and otherwise the line is held with a reason naming the snapshot — a rate is never printed because a column happens to carry it. Nothing verifies anything by itself, nothing promotes sample or self-approved data, and a withdrawn verification takes effect at once without touching an invoice already issued. Roles: owner, GST accountant, and the Super Admin that inherits them; everyone else reads. (POST /tax-configs/:id/verify, …/verification/revoke, audited with the basis.)
3. The GST decisions are recorded, or invoicing stops (migration 103)¶
accounting.gst_policy_decisions is an append-only register (newest per decision wins; the history stays) of ten mandatory decisions. For each, the system states what it does today — checked against the code, not hoped — and the answers on offer, and which of them it can carry out:
| Decision | What the system does today |
|---|---|
| Reverse charge | every invoice states "Reverse charge: No" |
| Invoice date and timing | issued when the order is confirmed paid, dated that IST day; the rate is the one in force on the day the order was placed, so after a hold or a retry the two days can differ; a cross-year sale is held |
| Credit and debit notes | raised by accounting staff from the portal, from their own gap-free series; a note for the whole order reverses the invoice figure for figure, a note for a refund carries the refunded amount only, with no tax split (none exists per refund, and none is invented) |
| Partial refunds | the invoice for the whole sale stands; a credit note records the refunded amount only, without a tax split — how the tax is adjusted is for the CA to say |
| E-invoicing (IRN and QR) | ordinary tax invoices only; no IRN or QR is obtained |
| Signature | a system-generated PDF with an "Authorised Signatory" caption and no signature |
| Business and consumer sales | B2B when the order records a buyer GSTIN of the right shape (not checked against the register), else B2C; a recorded value of the wrong shape is still printed as recorded, on a B2C invoice; the same calculation |
| CGST/SGST and IGST | equal CGST+SGST within the seller's state, else IGST; cess and UTGST are not handled |
| Delivery and platform fees | spread across the goods lines in proportion to value, each at its own line's rate |
| Rounding | exact to the paisa; the total equals what the customer was charged |
The engine holds an order while any decision is unrecorded, or recorded as an answer the system cannot carry out ("e-invoicing applies" is recordable — it is the honest answer — and it stops invoicing until the IRN/QR step exists or the decision is corrected). The system never records one for anyone and never states a statutory threshold; the question asks the CA, and the owner or GST accountant records the answer with its written basis (POST /settings/gst-policies/:key). A decision's time is the clock at the moment it is recorded (not the start of its transaction), so the decision recorded last is always the current one. Re-confirming each financial year is part of the e-invoicing question, and readiness warns when the recorded e-invoicing decision predates the current financial year.
4. Readiness classifies, and does not pass what is merely populated¶
GET /invoices/readiness reports every check as PASS, WARNING (look at it; issuing is not stopped) or BLOCKING (issuing cannot or must not run), each non-pass with what to do and who does it, pointing at screens that exist:
deployment flag · database gate · journal engine (reported, never required) · customer invoice access (a constant: no customer route exists) · seller GSTIN, state, legal name, address, and that they are SAVED in Settings (the built-in company record is a warning, not a pass) · PAN and contact (optional) · the series for the year, number format, numbers left, automatic rollover, next financial year opens by itself · approved and verified tax configurations · each of the ten GST decisions and a dedicated e-invoicing line · invoice PDF layout version · stored documents (the integrity line describes what the database enforces; the on-demand re-hash is its own panel) · owner exclusions, historical orders, held and failed orders, the 72-hour window · the paid orders switching issuance on will invoice at once (a test order placed yesterday is not "historical") · sales from an earlier financial year (never invoiced automatically) · an e-invoicing decision to re-confirm for the new year · record protection checked by trigger name and enabled state (a dropped or disabled trigger blocks) · who can approve and who can run.
A series at 90 % or more that will hand over by itself is a pass (it needs nothing from anyone); one that will not is a warning; a full one with no successor blocks. The portal shows the counts, groups the actions by who must act (owner first), and treats a value the server did not send as not reported, never as fine.
5. Seller contact: the key the portal saves is the key the engine reads¶
The portal's Settings form saves the invoice contact as supportEmail / supportPhone; the resolver read email / phone, which the portal never writes, so a correctly configured portal printed no contact. Both spellings are now read (an explicitly stored email/phone wins), and a malformed contact is refused at save. The seller's legal name, GSTIN (33ABGCA0227M1ZV), state code (33) and registered address are the entity record already in the system; they reach an invoice from Settings once a person has saved them: the engine holds every order, with a reason naming what is not saved, while the GSTIN, legal name or registered address is only pre-filled (the activation workflow does not read the readiness page, so the engine is the control). The Company profile can be saved as pre-filled. PAN and CIN stay optional and are never invented.
6. Exclusions and the historical orders¶
GET /invoices/exclusions/check?orderRefs=… is a read-only look: it resolves each order number or id to the exact order and reports its statuses, amount, any payment-gateway payment, an existing invoice or exclusion, and whether the automatic sweep would invoice it. It returns no buyer detail, writes nothing and excludes nothing. The exclusion remains POST /invoices/exclusions for the owner (and the Super Admin that holds the owner's rights) with an audited reason; the portal offers the owner's wording as a suggestion the person must choose — the reason box opens empty, so nothing is attested by default. An order with a numbered invoice cannot be excluded; an excluded order leaves every queue and no path invoices it.
The automatic recovery sweep invoices paid orders created within the last 72 hours (by created_at) once issuance is on; anything older is invoiced only by a backfill the owner has approved for an IST date range, a maximum number of orders and an expiry of at most 30 days, run by a person other than the approver. Production's four older test orders are therefore never invoiced automatically; marking them never-invoice is the owner's separate, audited decision and keeps them out of any later backfill.
7. Verification that does not go stale¶
production-accounting-verify asserted "19 accounting tables", "6 tracked migrations" and "only the seeded settings row exists" — all false since the accounting release grew. It now checks named requirements (migrations, tables, protection triggers that exist and are enabled, numbering columns, unique indexes, functions) computed in the read-only SQL into one verdict row per tier, so there is no number to go stale, and an absent verdict fails.
What this does not do (owner and CA, not engineering)¶
- It does not turn invoicing on. Activation is
production-issuance-flagwith its server marker and exact phrase, after the owner's written go-ahead and a readiness page whose only blockers are the two switches. - It does not decide a GST rate, a tax treatment, an e-invoicing obligation, a signature or any other statutory matter. Every such item is a blocker that a named person clears, in writing.
- It does not create a series, verify a rate, record a decision or mark an order. Those are the owner's and accountants' acts, in the portal, audited.
- It does not backfill, re-date or re-number anything, and it does not touch checkout, payments or the wallet.
- It does not change the owner-approved A4 invoice layout (
locked-a4-v1) or the sample-preview pages.
Consequences¶
- The ceiling moves from 9,999 a year to 2.6 billion a year for a three-letter prefix, with automatic rollover and a documented end (when the last letter fills, orders are held and the missed-invoice alarm fires).
- Until the owner and the CA do their part, every order is held — by design, with a reason that says exactly what is missing. Today's production would hold all of them: no series, nothing verified, no decision recorded.
- The sample-invoice preview's issuer outlook (the line saying what the real issuer would do) now reflects the new rules; its warnings, status and PDF pages are unchanged.
- The readiness page is stricter: states that used to read as passes (an unsaved seller, an unverified rate) now block.
- The admin app's Product screen still marks an approved setting "Tax Ready" (the setup step is done); verification is a separate step in the accounting portal, and the admin copy that used to say an approved setting is "active for invoices" now says it also needs that verification. No admin status, filter or API shape changed.
Migrations and rollback¶
Three additive migrations, applied in order inside one transaction per file, after the deploy workflow's database dump: 101 (series columns, generated number_prefix, indexes including the C-collation index on the invoice number, the replaced guard), 102 (product_tax_verifications, append-only, TRUNCATE refused), 103 (gst_policy_decisions, append-only, TRUNCATE refused). They touch no order, payment, invoice, journal or wallet row; the only existing data they change is activated_at, back-filled for series that are active (there are none in production). Compensating scripts rollback_101.sql…rollback_103.sql exist, are never applied automatically, and each says what it destroys; rollback_101 refuses while any standard-format series has issued numbers.
Application rollback needs care. Migration 101 replaces the old (prefix, fy_label) uniqueness, which the previous backend's series creation relies on, so rolling the image back also needs rollback_101.sql (then 102 and 103 are optional, they only stop being read) — tested: the three compensating scripts and the three migrations applied again restore the schema exactly. Before the first standard series is created (the state right after this deploy, when production has no series at all) that is the whole procedure. After a standard series exists, rollback_101 refuses, and the previous backend would format its numbers as 20 characters and refuse to issue them, holding every order: safe but pointless. So do not roll the application back below this change then — switch issuance off and roll forward, or restore from backup. The release runbook says the same.
To confirm with the company's chartered accountant¶
Engineering has read the rules as stated here; none of these is decided by the system, and none is asserted as settled law:
- that several series per financial year, with the series letter inside the number (
AIM/26A/00000001), satisfy the invoice-numbering rule (CGST Rule 46, as engineering reads it: at most 16 characters, one or multiple series, unique for the financial year), and how such series are reported in the documents-issued summary of the GST return; - the character rules for an invoice number if e-invoicing ever applies;
- how a sale placed before midnight on 31 March but invoiced after it is dated and numbered (the system holds it), and whether
orders.created_at— when the order row was written, which for a gateway payment committed later by reconciliation is after the payment — is the right "sale date"; - whether a supply at a verified 0 % rate is invoiced on a tax invoice at all;
- whether the buyer must receive the tax invoice (the issued PDF is marked for internal use, and there is no customer route), and the treatment of an odd buyer GSTIN;
- the tax adjustment of a part-refund (the credit note carries no tax split), and the rate taken from the order's day.
Testing¶
- Pure unit tests for the format, capacities, prefix rules and every readiness classification; database-backed tests of the allocator against a real PostgreSQL: consecutive numbers, rollover taking the last number, an already-full series, rollover off, legacy exhaustion, namespace exhaustion, year opening (once, under concurrency; from the most recently created series), rollback giving the number back and undoing the rollover, an issue interrupted by a failing document write and by a server-terminated connection (nothing left behind; the retry takes the same number and rolls over once), concurrent issuers (distinct, gap-free numbers; exactly one rollover), 10,500 numbers in one year with no 9,999 ceiling, the IST financial-year boundary, the database clock, and the cross-year refusal, sweep and queue.
- The HTTP surface of the standard series (create, idempotence, refusals with the field named, the supported years, rollover switch, closed series, the legacy contract unchanged), and the migrations' compensating scripts (a full round trip restores the schema) and database protections (prefix-free on rename, one-number-at-a-time counter, TRUNCATE refused, newest decision by the clock).
- Differential tests prove the dry-run predictor (and the sample preview's issuer outlook) equal the real issuer on each of those cases.
- The tax-verification and GST-decision workflows: who may, what is required, supersession, append-only at the database, audited; and that the engine really holds on each missing item.
- Readiness: every check's classification, "populated is not ready", the exact shape of today's production, and the read-only guarantee (a footprint of every table that could be written is identical before and after).
- The whole migration chain provisioned from scratch exactly as CI does, the fail-closed startup migrations, and the three CI shards, against a fresh database.
- Portal: the series manager (standard and legacy), readiness by class, tax verification, GST decisions, the exclusion pre-check, the authorization contract against the server's own probes, typecheck, lint and the api-mode production build.