@tofound/billing 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/LICENSE +3 -0
  3. package/README.md +79 -2
  4. package/dist/catalog/catalog.d.ts +115 -0
  5. package/dist/catalog/catalog.js +201 -0
  6. package/dist/domain/errors.d.ts +14 -0
  7. package/dist/domain/errors.js +21 -0
  8. package/dist/domain/money.d.ts +21 -0
  9. package/dist/domain/money.js +77 -0
  10. package/dist/domain/types.d.ts +167 -0
  11. package/dist/domain/types.js +18 -0
  12. package/dist/drizzle/index.d.ts +5 -0
  13. package/dist/drizzle/index.js +5 -0
  14. package/dist/drizzle/schema-factory.d.ts +586 -0
  15. package/dist/drizzle/schema-factory.js +206 -0
  16. package/dist/drizzle/store.d.ts +20 -0
  17. package/dist/drizzle/store.js +124 -0
  18. package/dist/entitlement/resolve.d.ts +76 -0
  19. package/dist/entitlement/resolve.js +122 -0
  20. package/dist/inbox/apply.d.ts +48 -0
  21. package/dist/inbox/apply.js +299 -0
  22. package/dist/inbox/conformance.d.ts +20 -0
  23. package/dist/inbox/conformance.js +254 -0
  24. package/dist/inbox/drizzle.d.ts +14 -0
  25. package/dist/inbox/drizzle.js +203 -0
  26. package/dist/inbox/ingest.d.ts +108 -0
  27. package/dist/inbox/ingest.js +404 -0
  28. package/dist/inbox/memory.d.ts +13 -0
  29. package/dist/inbox/memory.js +172 -0
  30. package/dist/inbox/ports.d.ts +150 -0
  31. package/dist/inbox/ports.js +1 -0
  32. package/dist/inbox/redact.d.ts +2 -0
  33. package/dist/inbox/redact.js +47 -0
  34. package/dist/inbox/schema.d.ts +1158 -0
  35. package/dist/inbox/schema.js +90 -0
  36. package/dist/inbox/watermark.d.ts +13 -0
  37. package/dist/inbox/watermark.js +6 -0
  38. package/dist/index.d.ts +30 -0
  39. package/dist/index.js +27 -0
  40. package/dist/ledger/ledger.d.ts +47 -0
  41. package/dist/ledger/ledger.js +224 -0
  42. package/dist/ports/index.d.ts +2 -0
  43. package/dist/ports/index.js +1 -0
  44. package/dist/ports/ledger-store.d.ts +53 -0
  45. package/dist/ports/ledger-store.js +1 -0
  46. package/dist/ports/runtime.d.ts +9 -0
  47. package/dist/ports/runtime.js +1 -0
  48. package/dist/providers/polar/events.d.ts +17 -0
  49. package/dist/providers/polar/events.js +213 -0
  50. package/dist/providers/polar/index.d.ts +50 -0
  51. package/dist/providers/polar/index.js +271 -0
  52. package/dist/providers/polar/signature.d.ts +23 -0
  53. package/dist/providers/polar/signature.js +52 -0
  54. package/dist/providers/port.d.ts +207 -0
  55. package/dist/providers/port.js +30 -0
  56. package/dist/providers/sepay/index.d.ts +34 -0
  57. package/dist/providers/sepay/index.js +241 -0
  58. package/dist/providers/sepay/order.d.ts +32 -0
  59. package/dist/providers/sepay/order.js +69 -0
  60. package/dist/providers/sepay/signature.d.ts +8 -0
  61. package/dist/providers/sepay/signature.js +51 -0
  62. package/dist/quote/conformance.d.ts +16 -0
  63. package/dist/quote/conformance.js +39 -0
  64. package/dist/quote/index.d.ts +3 -0
  65. package/dist/quote/index.js +3 -0
  66. package/dist/quote/steps.d.ts +54 -0
  67. package/dist/quote/steps.js +103 -0
  68. package/dist/quote/waterfall.d.ts +98 -0
  69. package/dist/quote/waterfall.js +82 -0
  70. package/dist/renewal/renewal.d.ts +69 -0
  71. package/dist/renewal/renewal.js +198 -0
  72. package/dist/stores/conformance.d.ts +22 -0
  73. package/dist/stores/conformance.js +269 -0
  74. package/dist/stores/memory.d.ts +19 -0
  75. package/dist/stores/memory.js +137 -0
  76. package/dist/stores/testing.d.ts +13 -0
  77. package/dist/stores/testing.js +13 -0
  78. package/dist/terms/conformance.d.ts +17 -0
  79. package/dist/terms/conformance.js +198 -0
  80. package/dist/terms/decide.d.ts +97 -0
  81. package/dist/terms/decide.js +176 -0
  82. package/dist/terms/drizzle.d.ts +12 -0
  83. package/dist/terms/drizzle.js +131 -0
  84. package/dist/terms/memory.d.ts +23 -0
  85. package/dist/terms/memory.js +126 -0
  86. package/dist/terms/plans.d.ts +85 -0
  87. package/dist/terms/plans.js +331 -0
  88. package/dist/terms/ports.d.ts +55 -0
  89. package/dist/terms/ports.js +1 -0
  90. package/dist/terms/rules.d.ts +11 -0
  91. package/dist/terms/rules.js +36 -0
  92. package/dist/terms/schema.d.ts +711 -0
  93. package/dist/terms/schema.js +70 -0
  94. package/dist/terms/snapshot.d.ts +20 -0
  95. package/dist/terms/snapshot.js +134 -0
  96. package/dist/terms/types.d.ts +85 -0
  97. package/dist/terms/types.js +4 -0
  98. package/docs/API.md +417 -0
  99. package/docs/SCHEMA.md +163 -0
  100. package/package.json +80 -4
package/docs/API.md ADDED
@@ -0,0 +1,417 @@
1
+ # @tofound/billing — API (0.2)
2
+
3
+ Part of the `billing.public-api` contract with `src/index.ts` and
4
+ `src/domain/types.ts`. 0.x minors are additive; the declaration snapshot in
5
+ `test/contract/public-api.test.ts` fails on any change to these exports.
6
+
7
+ | Entry | Contents |
8
+ |---|---|
9
+ | `@tofound/billing` | domain types, money helpers, `BillingError`, `createLedger`, ports, `createMemoryLedgerStore`, waterfall + steps, provider port, `createIngest`, `createMemoryIngestStore`, `defineCatalog`, terms, `resolveEntitlement`, `createPlans`, `createRenewal`, `createSnapshotHandler`, `createMemoryTermStore` |
10
+ | `@tofound/billing/drizzle` | `createBillingTables`, `billingTableBuilder`, `checkAdditiveDdl`, `createDrizzleLedgerStore`, `createIngestTables`, `createDrizzleIngestStore`, `createTermTables`, `createDrizzleTermStore`, `termTableNames` (peer `drizzle-orm ^0.45`) |
11
+ | `@tofound/billing/providers/sepay` | `createSepayAdapter`, `respondSepay`, `signCheckoutFields`, `parseSepayOrder` |
12
+ | `@tofound/billing/providers/polar` | `createPolarAdapter`, `resolvePolarEnvironment`, `respondPolar`, `redactPolarPayload`, `signPolarWebhook`, `PolarApiError`, `POLAR_WEBHOOK_*` header names and tolerance; types `PolarAdapter`, `PolarAdapterOptions`, `PolarCheckoutRequest`, `PolarKeyDerivation` |
13
+ | `@tofound/billing/testing` | `ledgerConformanceCases`, `assertLedgerInvariants`, `assertQuoteMatchesSettlement`, `ingestConformanceCases`, `termConformanceCases`, memory stores |
14
+
15
+ The library reads no env, logs nothing and has no runtime dependencies. Every
16
+ amount is an integer in minor units — a safe-integer `number` in TS, `bigint`
17
+ in Postgres.
18
+
19
+ ## Money and units
20
+
21
+ - `CreditUnit {code, exponent}`: Lohi `{code:'LT', exponent:0}`, 2Novel
22
+ `{code:'credit', exponent:2}` (100 đ = 1 credit, so 1 minor unit = 1 đ).
23
+ `creditUnit(code, exponent)` validates and freezes one.
24
+ - `Money {currency:'VND'|'USD', amountMinor}`; `CURRENCY_EXPONENT` = VND 0, USD 2.
25
+ - `divRound(n, d, mode)` / `mulDivRound(a, n, d, mode)` round explicitly
26
+ (`floor` | `ceil` | `half_up`) in bigint, so `a × n` never overflows. Grants
27
+ and refunds round toward the customer.
28
+ - `formatMinor(amount, exponent)` → plain decimal string; display copy is the host's.
29
+
30
+ ## Ledger
31
+
32
+ ```ts
33
+ const ledger = createLedger({ store, clock?, ids?, events? })
34
+
35
+ await ledger.credit({ accountId, kind: 'topup', amount, idempotencyKey: `topup:${checkoutId}` })
36
+ await ledger.debit({ accountId, kind: 'spend', amount, idempotencyKey: `job:${jobId}:charge`, reason, source })
37
+ await ledger.debitUpTo({ accountId, kind: 'refund', amount, idempotencyKey }) // → {shortfall}
38
+ await ledger.reverse({ entryId, amount?, idempotencyKey })
39
+ await ledger.balance(accountId)
40
+ await ledger.findByKey(idempotencyKey) // the entry posted under a key, or null
41
+ await ledger.entries(accountId, { limit, beforeSeq }) // newest first
42
+ await db.transaction((tx) => ledger.in(tx).debit({ … })) // inside the host transaction
43
+ ```
44
+
45
+ Invariants every store upholds (design §4.3):
46
+
47
+ | | |
48
+ |---|---|
49
+ | I1 | `balanceAfter = previous balanceAfter + delta`; `seq` contiguous per account |
50
+ | I2 | No negative balance: `debit` throws `insufficient_credits {balance, required, shortfall}` and writes nothing |
51
+ | I3 | Same key + same intent (account, kind, requested amount, reversed entry) → the original entry, `replayed: true`, no events. Anything else → `idempotency_mismatch` |
52
+ | I4 | Entries are append-only |
53
+ | I5 | An entry is reversed at most once, by at most `|delta|` (`reversal_exceeds_original`, `already_reversed`) |
54
+ | I6 | Account balance = last `balanceAfter` = Σ delta |
55
+
56
+ - Posting order: lock the account (insert-or-lock `FOR UPDATE`, taken **last**,
57
+ after host, inbox, purchase and term rows) → look the key up → append →
58
+ update balance and seq. Concurrent spends serialize on the account row; a
59
+ key raced across accounts is settled by the unique index, never written twice.
60
+ - `debitUpTo` posts `min(balance, amount)` (possibly 0) and records
61
+ `meta.debitUpTo = {requested, shortfall}`.
62
+ - `reverse` posts kind `reversal` with `reversesId`, the opposite sign of the
63
+ original; clawing back a credit past zero throws `insufficient_credits`
64
+ (use `debitUpTo` for clawbacks that must record a shortfall).
65
+ - Kinds: `topup`, `grant`, `spend`, `refund`, `plan_purchase`, `plan_renewal`,
66
+ `plan_refund`, `reversal` (only via `reverse`), `conversion`, `resync`, `adjustment`.
67
+ - Events (`credited` / `debited`; none for a zero or replayed posting) go to
68
+ `events` after commit when the ledger opened the transaction. That delivery
69
+ is at most once: the posting is already durable, so a throwing sink never
70
+ fails it — the error goes to `onEventError(error, event)` and the remaining
71
+ events are still delivered. Under `ledger.in(tx)` the events come back in
72
+ the result for the host to emit after its own commit (or to write to its
73
+ outbox in the same transaction, for guaranteed delivery).
74
+ - `createLedger<TTx>` returns `Ledger<TTx>`: `in(tx)` accepts only the
75
+ store's transaction type.
76
+ - Errors are `BillingError {code, details}`; map `code` to HTTP and copy in the host:
77
+
78
+ | `code` | Thrown when | `details` |
79
+ |---|---|---|
80
+ | `insufficient_credits` | a debit or a credit's reversal would go below zero | `{balance, required, shortfall}` |
81
+ | `idempotency_mismatch` | the key was posted with another account, kind, amount or reversed entry | `{idempotencyKey, entryId}` |
82
+ | `invalid_amount` | an amount is not a positive safe integer | `{amount}` (or the named field) |
83
+ | `invalid_input` | missing account/key, unknown or `reversal` kind, non-integer paging, reversing a zero entry | the offending field |
84
+ | `entry_not_found` | `reverse` names an unknown entry | `{entryId}` |
85
+ | `reversal_exceeds_original` | `reverse` amount > \|original delta\| | `{entryId, amount, original}` |
86
+ | `already_reversed` | the entry already has its reversal | `{entryId, reversalId?}` |
87
+ | `balance_overflow` | a result leaves the safe-integer range | — |
88
+ | `invalid_catalog` | `defineCatalog` refuses the host's catalog | the offending key |
89
+ | `plan_not_found` | a plan key the catalog does not have | `{plan}` |
90
+ | `offer_not_found` | the plan is not sold for these months in this market | `{plan, months, market}` |
91
+ | `term_not_found` | auto-renew / cancel with no open credit term | `{accountId}` |
92
+ | `plan_blocked` | a plan purchase the quote refuses | `{reason}` (`covered_by_subscription`) |
93
+
94
+ A plain `Error` (not `BillingError`) signals a broken store or host setup,
95
+ e.g. a repeating `IdGenerator`; it is never an expected outcome.
96
+ - Stores assume READ COMMITTED. Do not call the top-level methods of a memory
97
+ store's ledger from inside that store's open transaction (it serializes).
98
+
99
+ ## Ports (`billing.ports`)
100
+
101
+ `LedgerStore<TTx>` = `transaction(fn)`, `bind(tx) → LedgerTx`, `reader()`.
102
+ `LedgerTx` adds `lockAccount`, `findReversalOf`, `appendEntry` (unique
103
+ conflict → `{inserted:false}`, never a thrown/aborted transaction) and
104
+ `setAccountState`. `Clock`, `IdGenerator`, `BillingEventSink`. A host adapter
105
+ (Lohi P4, over `user_wallets` / `wallet_transactions`) implements the same
106
+ port and must pass `ledgerConformanceCases`.
107
+
108
+ ## Quote and charge: one waterfall
109
+
110
+ ```ts
111
+ const w = createWaterfall<State, Tx>({
112
+ currency: 'credit',
113
+ price: (s) => s.price,
114
+ balance: (s) => s.balance,
115
+ steps: [
116
+ freeStep({ id: 'byok', when: (s) => s.byok, reason: { code: 'byok' } }),
117
+ quotaStep({ id: 'included', unit: 'credit_pool', pool: (s) => s.pool, reason: { code: 'included_pool' }, consume }),
118
+ creditsStep({ ledger }),
119
+ ],
120
+ })
121
+ w.quote(state) // read-only → Quote
122
+ await w.settle(tx, lockedState, { accountId, idempotencyKey }) // same steps, commits each line → {settled, replayed, quote, entries, events}
123
+ ```
124
+
125
+ - `Quote` mirrors Lohi's wire: `originalPrice`, `price` (what the wallet is
126
+ debited), `currency`, `reason {code, label?, detail?}`, `funding[]
127
+ {source, unit, amount, remainingBefore, remainingAfter, label?}`,
128
+ `settlement 'free'|'quota'|'wallet'|'blocked'`, `canSettle`, `shortfall?`,
129
+ `balance`, `upsell?`, `expiresInSec` (default 60). The host labels codes.
130
+ - Steps run in order while price remains. `freeStep` covers everything;
131
+ `quotaStep` spends `ceil(remaining / unitValue)` pool units (capped) and may
132
+ fund part; `creditsStep` debits the rest or blocks with the exact
133
+ `shortfall` — it never funds partially. Price left after every step blocks
134
+ with `not_covered`. A line's `unit` is the credit unit code exactly when it
135
+ settles from the wallet, so a pool counting credits uses its own unit name
136
+ (`included_credit`); the waterfall throws otherwise.
137
+ - `settle` re-walks on the locked state; a blocked walk writes nothing. If
138
+ the balance moved between the read and the account lock, the debit throws
139
+ `insufficient_credits` and the host transaction rolls back.
140
+ - `settle` first asks each step whether the key was already charged
141
+ (`creditsStep` looks the debit up): a repeat returns `{settled: true,
142
+ replayed: true}` with the original entry and runs nothing, even if the
143
+ drained balance no longer covers the price. A charge funded by quota alone
144
+ posts no ledger entry, so a host still makes the whole charge once-only the
145
+ way it already does — a stamp on the job/unlock row checked under its lock
146
+ before `settle` (2Novel's `cost_dong`, Lohi's unlock row).
147
+ - `Settled.events` carries the ledger events of the charge for the host to
148
+ emit after its commit (the sink is not called inside a host transaction).
149
+ - `assertQuoteMatchesSettlement(quote, {settled, walletDelta, meterDeltas})`
150
+ is the conformance check every host runs against real charges.
151
+ `walletDelta` is **balance after − balance before**, so a charge is
152
+ negative: a settled quote must show `walletDelta === -quote.price`, a
153
+ blocked one `0`. `meterDeltas` are the units each pool consumed (positive).
154
+
155
+ ## Provider ingest (`billing.provider-port`)
156
+
157
+ ```ts
158
+ const sepay = createSepayAdapter({ environment: 'production', webhookKeys: [current, next?], merchantId, secretKey })
159
+ const ingest = createIngest({ adapters: [sepay], store, ledger, events?, policy?, onUnmatched? })
160
+
161
+ const { session, redirect } = await ingest.createCheckout({ provider: 'sepay', accountId, amount, credits, productRef, description, successUrl, errorUrl, cancelUrl })
162
+ const r = await ingest.handle('sepay', { headers, rawBody, url, receivedAt }) // → reply with r.response
163
+ await ingest.confirm('sepay', { invoice: session.id }) // poll; same event id as the IPN
164
+ await ingest.closeCheckout(session.id, 'expired') // a later capture still credits
165
+ await ingest.replay('sepay', eventId) // re-opens needs_review / dead
166
+ await ingest.sweep() // cron: due failed + abandoned received rows
167
+ ```
168
+
169
+ - An adapter (`ProviderAdapter` in `src/providers/port.ts`) owns
170
+ `verify → normalize → respond`; the ingest owns the inbox, the checkout
171
+ sessions, the purchases and the ledger postings, in one store transaction.
172
+ Lock order: inbox row → session → purchase → account (last).
173
+ - `verify` throws `VerifyError('unauthorized' | 'malformed')` → 401 / 400 and
174
+ nothing is stored. Every verified delivery is one inbox row (unique
175
+ provider + event id), its payload redacted (`redactPayload`) before storage.
176
+ - Outcomes: `applied`, `ignored`, `duplicate` (row already final), `needs_review`
177
+ (`BillingError` or a refusal such as `amount_mismatch` — permanent, alerted),
178
+ `failed` (any other error: 5xx so the provider redelivers, retried by `sweep`
179
+ with `policy.backoff`), `dead` after `policy.maxAttempts` (alerted, acked).
180
+ - A purchase credits once: `topup:<sessionId>`, exact amount match against the
181
+ server-priced session. A reversal claws back through `ledger.reverse`
182
+ (`reversal:<provider>:<externalId>:<n>`), recording any spent part as
183
+ `shortfall`; a reinstatement re-credits (`reinstate:…`). Provider watermarks
184
+ (`isNewer`) drop stale events, and any delivery order of capture / reversal /
185
+ reinstatement converges to the same purchase state and balance.
186
+ - `confirm` credits the session's own account, whoever asks; a host route
187
+ that forwards a client's invoice still checks the caller owns that session
188
+ before it spends a provider API call on it.
189
+ - `sweep` lists only rows of the providers this ingest has adapters for, and
190
+ a row it cannot even record stays due without stopping the rows behind it.
191
+ - `onUnmatched` receives deliveries no session matches (e.g. another product's
192
+ SePay invoice) and may answer for them; a throw answers 5xx.
193
+ - SePay: `environment` is required (no default), and test credentials in
194
+ production or live ones in sandbox are refused. `x-secret-key` is compared in
195
+ constant time against every key in `webhookKeys`. Checkout form fields are
196
+ signed byte-for-byte as `sepay-pg-node@1.0.0`. An order lookup failure is
197
+ `unknown`, never `cancelled`.
198
+ - Events: `billing.webhook {provider, eventType, eventId, outcome, reason}`,
199
+ `billing.alert {alert: inbox_dead | inbox_needs_review}`, `refund_applied`,
200
+ plus the ledger's `credited` / `debited` — all after commit; a throwing sink
201
+ never fails the delivery.
202
+
203
+ ## Polar (`@tofound/billing/providers/polar`)
204
+
205
+ ```ts
206
+ const environment = resolvePolarEnvironment({ environment: env.POLAR_ENV, productionEnabled: env.POLAR_PRODUCTION_ENABLED === 'true' })
207
+ const polar = createPolarAdapter({
208
+ environment, // required: 'production' | 'sandbox'
209
+ webhookSecrets: [current, next?], // `whsec_…`; two only while rotating
210
+ products: { [polarProductId]: productRef }, // this environment's Polar products → catalog productRefs
211
+ accessToken?, // organization token: checkout + portal only
212
+ checkoutPattern?, toleranceSec?, clock?, fetch?, timeoutMs?,
213
+ })
214
+ const ingest = createIngest({
215
+ adapters: [polar], store, ledger,
216
+ handlers: { 'subscription.snapshot': createSnapshotHandler({ terms, catalog, resolveAccount }) },
217
+ })
218
+
219
+ const { redirect } = await ingest.createCheckout({ provider: 'polar', accountId, amount, credits, productRef, … }) // a credit pack
220
+ const r = await ingest.handle('polar', { headers, rawBody, url, receivedAt }) // → reply with r.response
221
+ const { url } = await polar.createPortalSession({ kind: 'account_id', value: accountId }, returnUrl) // or kind 'polar_customer_external_id'
222
+ ```
223
+
224
+ | Export | Signature |
225
+ |---|---|
226
+ | `resolvePolarEnvironment` | `({ environment: string \| null \| undefined, productionEnabled: boolean }) → 'production' \| 'sandbox'` |
227
+ | `createPolarAdapter` | `(PolarAdapterOptions) → PolarAdapter` (`ProviderAdapter` + `createCheckout` + `createPortalSession`) |
228
+ | `respondPolar` | `(IngestOutcome) → ProviderResponse`: the adapter's `respond` |
229
+ | `redactPolarPayload` | `(payload) → payload`: the adapter's `redact` (`redactPayload` plus `tax_id`, `custom_field_data`, `avatar_url`, `customer_ip_address`, and any Polar secret inside a value, e.g. the `polar_c_…` client secret in a checkout `url` → `polar_c_[redacted]`) |
230
+ | `signPolarWebhook` | `(secret, id, timestamp, rawBody, derivation = 'standard') → 'v1,<base64>'`: for host tests and fixtures |
231
+
232
+ - **Environment, never inferred.** `resolvePolarEnvironment` turns the host's
233
+ two switches into one value: `sandbox` → sandbox; `production` only with
234
+ `productionEnabled: true`, else `ProviderConfigError('polar_production_disabled')`;
235
+ anything else (unset, typo) → `polar_environment_required`. The adapter has
236
+ no default either, and it picks the API host:
237
+ `api.polar.sh` or `sandbox-api.polar.sh`. Sandbox and production products
238
+ have different ids, so pass the `products` map for the environment you run.
239
+ Other config errors: `polar_webhook_secrets_required`, `polar_invalid_tolerance`.
240
+ - **Standard Webhooks verification** runs on the raw body before any parse.
241
+ The signed content is `${webhook-id}.${webhook-timestamp}.${rawBody}`, HMAC-SHA256, and any
242
+ `v1,` entry of `webhook-signature` may match any secret in
243
+ `webhookSecrets`. Both key derivations are accepted: base64 after `whsec_` (standard) and the whole
244
+ string's UTF-8 (legacy). Comparison is constant-time. A missing header, a
245
+ `webhook-id` over 128 characters, a non-numeric timestamp, a timestamp
246
+ outside ±`toleranceSec` (300 s) or no matching signature → `unauthorized`
247
+ (401). Non-JSON, no `type` / `data`, or a `type` over 64 characters →
248
+ `malformed` (400). Nothing is stored in either case. The event id is
249
+ `polar:<webhook-id>`, so a retry of a message whose row is final is
250
+ `duplicate`; a `failed` row is processed again.
251
+ - **Credit packs.** `createCheckout` refuses an unmapped `productRef`
252
+ (exactly one Polar product per ref), a non-positive amount, or a session id
253
+ that is not `checkoutPattern` before any call (`ProviderConfigError` codes
254
+ `polar_unknown_product`, `polar_invalid_amount`, `polar_invalid_checkout_id`,
255
+ and `polar_not_configured` without a token). A failed call is `PolarApiError`
256
+ (`polar_unreachable`, `polar_error` with `status`, `polar_bad_response`). It then creates a Polar checkout
257
+ with `external_customer_id = accountId`, `metadata.checkout_id = sessionId`
258
+ and `allow_discount_codes: false`. A response whose currency or `amount`
259
+ (the product price before discount and tax) differs from the catalog amount,
260
+ or that carries a `discount_amount`, is refused as `polar_price_mismatch`.
261
+ The checkout's `net_amount` is not compared: it drops by the tax once a
262
+ tax-inclusive country is known.
263
+ The Polar checkout already exists by then; it is never handed to the buyer.
264
+ The session id comes from the ingest's `ids` (default `randomUUID`), so a custom
265
+ generator must match `checkoutPattern`, or every checkout throws
266
+ `polar_invalid_checkout_id`. `PolarCheckoutRequest.customerIpAddress` (sent for tax
267
+ country) is only accepted by a direct `polar.createCheckout` call;
268
+ `ingest.createCheckout` does not forward it.
269
+ `order.paid` for a one-time order becomes `purchase.completed`, bound to the
270
+ session by `metadata.checkout_id` and credited once (`topup:<sessionId>`).
271
+ Its amount is the catalog price, `subtotal_amount − discount_amount`, which
272
+ reads the same whatever the organization's tax behaviour: a tax-inclusive
273
+ $5.00 order (a DE buyer under `location`) has `net_amount` 420 and
274
+ `tax_amount` 80, a tax-exclusive one `total_amount` 540, and both are 500
275
+ here. `net_amount` and `total_amount` are never used; an order without a
276
+ readable subtotal is `needs_review` (`invalid_amount`). If the amount differs
277
+ from the session (a discount), the order goes to `needs_review`
278
+ (`amount_mismatch`) and nothing is credited. `order.created` / `order.updated` move no money, and a
279
+ subscription's own orders are receipts (`ignored`).
280
+ - **Refunds.** `order.refunded` with status `refunded` becomes
281
+ `purchase.reversed`, its amount on the same basis as the order's
282
+ (`refunded_amount` is not compared: it excludes a tax-inclusive order's tax). The reversal claws back once, in any order relative to
283
+ `order.paid`: a refund delivered first, carrying our `metadata.checkout_id`,
284
+ voids the session, and the late paid order never credits (a refund matching
285
+ neither a session nor a purchase is `ignored`, `no_match`). A partial refund is `needs_review` (`partial_refund`)
286
+ and is never guessed into a clawback.
287
+ - **Subscriptions.** `subscription.*` events become `subscription.snapshot` with
288
+ `account = { kind: 'polar_customer_external_id', value: external_customer_id }`.
289
+ The status maps as follows:
290
+ - `active` / `trialing` → `active`
291
+ - `past_due` / `unpaid` → `past_due`
292
+ - `canceled` → `active` (ends at period end), or `expired` when `ended_at` is at
293
+ or before the event's own `modified_at`
294
+ - revoked or paused → `revoked`
295
+
296
+ Statuses Polar sets before any payment (`incomplete`…) are `ignored`. Each
297
+ snapshot is watermarked by Polar's `modified_at`. Polar sends one change as
298
+ several events with the same `modified_at` (a revoke is `updated`,
299
+ `canceled` and `revoked`), so the event type breaks the tie (`tieBreak`):
300
+ `revoked` > `paused` > `canceled` > `uncanceled` > `past_due` > `active` >
301
+ `updated` > `created`. A revoke therefore ends `revoked` in any arrival
302
+ order; the outranked copies are `ignored` (`stale`). The period ends at
303
+ `ended_at` when that is before `current_period_end`. A product not in `products`
304
+ is `ignored` (`unknown_product`). Without a `subscription.snapshot` handler,
305
+ a snapshot is `needs_review` (`no_handler:…`).
306
+ - **Subscription checkouts** do not go through the ingest:
307
+ `ingest.createCheckout` sells credit packs (a session, credits on
308
+ `order.paid`). For a plan, call `polar.createCheckout` directly with a fresh
309
+ UUID `sessionId` (it is only carried in `metadata`), the plan offer's
310
+ `productRef` and its catalog price (the price guard applies). No session row
311
+ is written: the subscription reaches the terms through `subscription.*`
312
+ events bound by `external_customer_id = accountId`, and its orders are
313
+ receipts.
314
+ - **Webhook events to subscribe:** `order.paid`, `order.refunded`,
315
+ `subscription.created` / `.updated` / `.active` / `.canceled` /
316
+ `.uncanceled` / `.revoked` (and `.past_due` where offered). `checkout.*`
317
+ is not needed: the ingest has no `checkout.status` handler, so those
318
+ deliveries are verified, stored and `ignored` (`no_handler:checkout.status`),
319
+ which is harmless but fills the inbox (about half of the rows in a sandbox
320
+ run). The order carries everything a credit needs.
321
+ - **What the host wires:**
322
+ - **Environment and secrets:** resolve the environment once at boot, keep
323
+ the secrets server-side and pass the access token only where checkout or
324
+ the portal runs.
325
+ - **Webhook route:** a raw-body route that answers with `r.response`.
326
+ `respondPolar` acknowledges every outcome a retry cannot change with 200
327
+ and answers 5xx only on `failed`. A relayed delivery returns the
328
+ `onUnmatched` response as is.
329
+ - **`resolveAccount`:** maps the external customer id back to your account.
330
+ It returns `null` for another host's customers on a shared organization.
331
+ Only a subscription whose product is in `products` reaches it; that
332
+ `null` is relayed through `onUnmatched`. A subscription on an unmapped
333
+ product is `ignored` (`unknown_product`) and is not relayed. Another
334
+ host's one-time order goes to `needs_review` (`unsupported_account_ref`
335
+ or `unbound_order`, alerted), unless its `metadata.checkout_id` is a
336
+ session id this host's pattern accepts that matches none of its sessions;
337
+ that order is relayed as unmatched.
338
+ - **Catalog:** one Polar `productRef` per offer.
339
+ - **Monitoring:** watch the `billing.alert` events. `PolarApiError` never
340
+ carries the token or Polar's response body. A portal for any other
341
+ account kind is refused (`ProviderConfigError('polar_unsupported_account')`).
342
+
343
+ ## Catalog, terms and entitlement (0.2)
344
+
345
+ ```ts
346
+ const catalog = defineCatalog({ version, creditUnit, markets: [{ key: 'vn', currency: 'VND' }], plans, creditPacks?, policies? })
347
+ const terms = createDrizzleTermStore({ db, tables: { billingTerms, billingTermAccounts } }) // memory: createMemoryTermStore(ledgerStore)
348
+ const plans = createPlans({ ledger, terms, catalog, events? })
349
+ const renewal = createRenewal({ ledger, terms, catalog, marketOf?, events? })
350
+
351
+ const quote = await plans.quote({ accountId, plan: 'pro', months: 3, market }) // market set by the host, never the client
352
+ const bought = await plans.purchase({ accountId, plan: 'pro', months: 3, market, idempotencyKey })
353
+ const ent = resolveEntitlement(await terms.reader().listTerms(accountId), new Date(), catalog, { balance })
354
+ await renewal.renewDue() // host cron, under its own advisory lock
355
+ await renewal.retryPastDue(accountId) // after a top-up commits, in its own transaction
356
+ createIngest({ …, handlers: { 'subscription.snapshot': createSnapshotHandler({ terms, catalog, resolveAccount }) } })
357
+ ```
358
+
359
+ - **The catalog is the host's config**: plans (strict `rank`, exactly one
360
+ `free`), credit offers per `market` × `months`, provider offers by
361
+ `productRef`, packs and `policies` (`termDays` 30, `upgradeProration`
362
+ `remaining_time` | `none`, `graceDays` 3, `renewalLeadSec`). The library has
363
+ no plan or price literal.
364
+ - **Terms** (`billing_terms`) are one shape for credit, Polar, Apple and Google.
365
+ Credit terms are written only by plans and renewal; provider terms only by
366
+ the snapshot handler, under a watermark (an older snapshot is `ignored`).
367
+ At most one open (`active` | `grace` | `past_due`) credit term and one
368
+ `scheduled` term per account. Every writer locks the account's terms
369
+ first (`lockAccountTerms`, through the `term_accounts` guard row), then
370
+ the ledger account last.
371
+ - **Entitlement** (S1): the highest-rank entitled term wins, then the later
372
+ end, then the older term; quotas and permissions never sum; nothing entitled
373
+ → the free plan. A `past_due` term is entitled (`status: 'grace'`) until
374
+ `graceUntil`. `includedCredits` comes only from provider-funded terms.
375
+ Warnings: `two_subscriptions` (S5), `past_due`, `renewal_shortfall` (pass
376
+ `balance`), `scheduled_downgrade`.
377
+ - **Plan quotes** walk one waterfall (covered → credits) for both the quote
378
+ and the purchase, so `assertQuoteMatchesSettlement` holds. `kind`:
379
+ `new`; `extend` (S2, same plan, months appended, charged in full);
380
+ `upgrade` (end date kept; `remaining_time` charges
381
+ ceil(remaining/total × (offerNew − paid)), `originalPrice` is the unprorated
382
+ difference); `renew` (paying a past_due term, from its old end);
383
+ `downgrade` (S3b, no money now: the renewal switches plan under auto-renew,
384
+ otherwise a `scheduled` term charged when it starts; also after a
385
+ non-renewing subscription of ≥ rank, reason `scheduled_after_subscription`);
386
+ `blocked` (S3, a renewing subscription of ≥ rank, reason
387
+ `covered_by_subscription`). A new term supersedes a `scheduled` one that
388
+ would start inside it. The purchase writes term rows before the debit, so
389
+ a throw relies on the rollback: under `plans.in(tx)` the host must roll its
390
+ transaction back. A repeated `idempotencyKey` replays — from its ledger
391
+ entry, or for a purchase that charged nothing from the term that recorded
392
+ the key (the last 20 per term), whatever the term's status since.
393
+ - **Renewal** (D9) charges the **live** catalog price of
394
+ `nextPlanKey ?? planKey` (`plan_renewal`, key
395
+ `renew:<termId>:<periodEnd ISO>`, so a double run debits once). A short
396
+ balance makes the term `past_due` with `graceUntil = periodEnd + graceDays`
397
+ and emits `renewal_failed {required, balance, shortfall}`; grace passed →
398
+ `expired`. An early attempt inside `renewalLeadSec` that fails emits
399
+ `renewal_failed` but leaves the paid period `active` (outcome `skipped`);
400
+ the next run tries again.
401
+ - **S4 supersede**: an entitled provider subscription of ≥ rank closes the
402
+ credit term (`superseded`) and refunds its unused share,
403
+ ceil(remaining/total × paid), as `plan_refund` keyed `supersede:<termId>`.
404
+ A snapshot whose account `resolveAccount` does not know is `ignored`
405
+ (`no_match`) and relayed through `onUnmatched`, before its product is
406
+ checked (another host's subscription on a shared provider account); a
407
+ subscription already bound to another account is `needs_review`
408
+ (`account_mismatch`).
409
+ - Events after commit: `term_changed {change, term}`, `renewal_failed`, plus
410
+ the ledger's `credited` / `debited`; under `.in(tx)` they come back in the
411
+ result.
412
+
413
+ ## Drizzle
414
+
415
+ See [SCHEMA.md](SCHEMA.md). `createDrizzleLedgerStore({ db, tables })` works
416
+ with any Drizzle Postgres driver; `ledger.in(tx)` takes the host's Drizzle
417
+ transaction.
package/docs/SCHEMA.md ADDED
@@ -0,0 +1,163 @@
1
+ # @tofound/billing — schema factory and migration rules
2
+
3
+ Part of the `billing.schema-factory` contract with
4
+ `src/drizzle/schema-factory.ts`. Checked by `test/contract/schema.test.ts`.
5
+
6
+ ## The library ships no SQL
7
+
8
+ Each host owns its migrations. It re-exports the factory tables from a file
9
+ its drizzle-kit `schema` glob already covers, then runs its own `db:generate`:
10
+
11
+ ```ts
12
+ // 2novel/api/src/modules/credits/schema.ts
13
+ import { createBillingTables } from '@tofound/billing/drizzle'
14
+ import { uuid } from 'drizzle-orm/pg-core'
15
+ import { translate } from '../../db/schema-namespace'
16
+ import { workspaces } from '../workspace/schema'
17
+
18
+ export const { billingAccounts, billingEntries } = createBillingTables({
19
+ schema: translate,
20
+ prefix: 'billing_',
21
+ accountId: (n) => uuid(n).notNull().references(() => workspaces.id),
22
+ })
23
+ ```
24
+
25
+ drizzle-kit loads schema files with CJS `require`. The package is ESM-only;
26
+ every entry also carries a `default` export condition, so that `require`
27
+ resolves through Node's `require(esm)` (unflagged from Node 22.12, the
28
+ package's `engines` floor).
29
+
30
+ `BillingSchemaConfig`:
31
+
32
+ | Option | Default | |
33
+ |---|---|---|
34
+ | `schema` | `public` | a `pgSchema(...)`, e.g. 2Novel `translate` |
35
+ | `prefix` | `billing_` | lower snake case; prefixes tables, indexes and constraints |
36
+ | `accountId` | — | the host-typed subject column (`uuid`, `text` …), NOT NULL, optionally an FK to the host's subject table |
37
+
38
+ ## Tables (0.1, 0.2)
39
+
40
+ `<prefix>accounts` — one row per account, created on first posting.
41
+
42
+ | Column | Type | |
43
+ |---|---|---|
44
+ | `account_id` | host type | PK `<prefix>accounts_pk` |
45
+ | `balance` | bigint not null default 0 | CHECK ≥ 0 |
46
+ | `seq` | bigint not null default 0 | seq of the last entry |
47
+ | `created_at`, `updated_at` | timestamptz | |
48
+
49
+ `<prefix>entries` — append-only ledger.
50
+
51
+ | Column | Type | |
52
+ |---|---|---|
53
+ | `id` | varchar(64) PK | generated by the library |
54
+ | `account_id` | host type | |
55
+ | `seq` | bigint not null | UNIQUE (`account_id`, `seq`) |
56
+ | `delta`, `balance_after` | bigint not null | `balance_after` CHECK ≥ 0 |
57
+ | `kind` | varchar(32) not null | |
58
+ | `reason` | text | host label |
59
+ | `idempotency_key` | text not null | UNIQUE |
60
+ | `source_type`, `source_id` | varchar(64), text | |
61
+ | `reverses_id` | varchar(64) | UNIQUE (NULLs distinct = unique when not null) |
62
+ | `meta` | jsonb | |
63
+ | `created_at` | timestamptz not null | |
64
+
65
+ Inbox, checkout-session, purchase, term and account-token tables are declared
66
+ by their own modules through `billingTableBuilder(config)` — same schema, same
67
+ prefix, same rules — and a host re-exports them beside these.
68
+
69
+ Every factory returns an object of Drizzle tables. drizzle-kit only sees a
70
+ table that is a **named export** of a file its `schema` glob covers. So a host
71
+ destructures and exports every key a factory returns; a key it leaves out is
72
+ a table that never gets a migration:
73
+
74
+ | Factory (`@tofound/billing/drizzle`) | Returned keys → tables |
75
+ |---|---|
76
+ | `createBillingTables(config)` | `billingAccounts` → `<prefix>accounts`, `billingEntries` → `<prefix>entries` |
77
+ | `createIngestTables(config)` | `billingInbox` → `<prefix>inbox`, `billingCheckoutSessions` → `<prefix>checkout_sessions`, `billingPurchases` → `<prefix>purchases` |
78
+ | `createTermTables(config)` (0.2) | `billingTerms` → `<prefix>terms`, `billingTermAccounts` → `<prefix>term_accounts` |
79
+
80
+ ```ts
81
+ export const { billingInbox, billingCheckoutSessions, billingPurchases } = createIngestTables(config)
82
+ export const { billingTerms, billingTermAccounts } = createTermTables(config)
83
+ ```
84
+
85
+ Pass the same objects to the stores (`createDrizzleIngestStore({ db, tables:
86
+ { billingInbox, billingCheckoutSessions, billingPurchases } })`,
87
+ `createDrizzleTermStore({ db, tables: { billingTerms, billingTermAccounts }
88
+ })`).
89
+
90
+ `createIngestTables(config)` (0.1) returns `{ billingInbox,
91
+ billingCheckoutSessions, billingPurchases }`: `<prefix>inbox` (UNIQUE provider +
92
+ event_id; due index on status + next_attempt_at), `<prefix>checkout_sessions`
93
+ (CHECK amount > 0, credits > 0) and `<prefix>purchases` (UNIQUE provider +
94
+ environment + external_id). `ingestTableNames(prefix)` lists them for
95
+ `checkAdditiveDdl`.
96
+
97
+ `createTermTables(config)` (0.2) returns `{ billingTerms, billingTermAccounts }`:
98
+ `<prefix>terms`, one row per term of any source, and `<prefix>term_accounts`:
99
+
100
+ | Column | Type | |
101
+ |---|---|---|
102
+ | `id` | varchar(64) PK | |
103
+ | `account_id` | host type | |
104
+ | `source`, `environment`, `external_id` | varchar(16), varchar(16), text | UNIQUE (`source`, `environment`, `external_id`); NULL for credit terms |
105
+ | `plan_key`, `next_plan_key` | varchar(64) | catalog keys |
106
+ | `status` | varchar(16) not null | scheduled, active, grace, past_due, expired, superseded, revoked |
107
+ | `market` | varchar(64) | |
108
+ | `starts_at`, `current_period_start`, `current_period_end` | timestamptz not null | |
109
+ | `interval_months` | integer not null | CHECK > 0 |
110
+ | `auto_renew`, `cancel_at_period_end` | boolean not null default false | |
111
+ | `grace_until` | timestamptz | |
112
+ | `price_minor`, `price_unit` | bigint, varchar(16) | |
113
+ | `period_items`, `meta` | jsonb | |
114
+ | `superseded_by` | varchar(64) | |
115
+ | `last_event_at`, `last_event_ref` | timestamptz, text | provider watermark |
116
+ | `created_at`, `updated_at` | timestamptz not null | |
117
+
118
+ Partial unique indexes keep one open credit term (`source = 'credit'` and
119
+ status active / grace / past_due) and one `scheduled` term per account;
120
+ `(account_id, status)` serves the account lock and lists; three partial
121
+ indexes (`current_period_end` of active credit terms, `starts_at` of
122
+ scheduled, `grace_until` of past_due) bound `listDue` by the due rows.
123
+
124
+ `<prefix>term_accounts` (`account_id` host type, PK; `created_at`) holds one
125
+ guard row per account. `lockAccountTerms` upserts and locks it before the
126
+ account's term rows, so two first writers of an account with no terms yet (a
127
+ credit purchase and a provider snapshot) still serialize.
128
+ `termTableNames(prefix)` lists both for `checkAdditiveDdl`.
129
+
130
+ ## Rules: additive only, never a table rewrite
131
+
132
+ Hosts deploy by migrating the live database before rolling the container, so
133
+ a statement that rewrites or long-locks a table takes production down. Every
134
+ library schema change therefore:
135
+
136
+ 1. creates new tables and indexes only;
137
+ 2. evolves an existing library table only with a **nullable column without a
138
+ volatile default** (`now()`, `random()`, `gen_random_uuid()` …);
139
+ 3. never uses `GENERATED ALWAYS AS (…) STORED`;
140
+ 4. never touches a host table (an FK *from* a library table is fine);
141
+ 5. adds an index or constraint to an existing library table only
142
+ `CONCURRENTLY` / `NOT VALID` through a host custom migration;
143
+ 6. ships as a minor version with a CHANGELOG line telling hosts to `db:generate`.
144
+
145
+ `checkAdditiveDdl(statements, { libraryTables })` returns every violation in
146
+ a generated migration (`generated_stored`, `not_null_add_column`,
147
+ `volatile_default`, `non_library_table`, `destructive`, `blocking_index`,
148
+ `validating_constraint`, `unrecognized`). Hosts can run it on their own
149
+ generated or custom SQL: an element with several `;`-separated statements is
150
+ checked statement by statement, every action of a multi-action `ALTER TABLE`
151
+ is checked, a leading `SET lock_timeout` is allowed, and any shape it does not
152
+ recognise (a dollar-quoted function body, `VACUUM`, …) fails closed as
153
+ `unrecognized`. `ADD PRIMARY KEY` / `UNIQUE` on an existing table is a
154
+ `blocking_index` unless it adopts a concurrently built index (`USING INDEX`).
155
+
156
+ ## lock_timeout
157
+
158
+ A host migration that creates or alters library tables must run with
159
+ `SET lock_timeout = '5s'` (the deploy runner sets it, or open the migration
160
+ with it), so a migration that cannot get its lock fails fast instead of
161
+ queueing production behind it. The factory DDL takes locks only on its own new
162
+ tables and, for an FK, a brief `SHARE ROW EXCLUSIVE` on the referenced host
163
+ table; the schema test applies the generated SQL under that timeout.