@tofound/billing 0.2.0 → 1.0.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.
@@ -0,0 +1,237 @@
1
+ # Migrating the Lohi reader API onto `@tofound/billing` 1.0
2
+
3
+ This guide is for the team moving the Lohi reader API (`api/` in the Lohi
4
+ monorepo) onto the library. The library becomes the money engine, and Lohi's
5
+ tables, reason strings, bus events and every iOS response stay exactly as
6
+ they are. Nothing in this guide is a scheduler or a new charge: the Lohi
7
+ renewal trigger stays the admin endpoint it is today.
8
+
9
+ The work is three tickets, in this order:
10
+
11
+ | Step | What moves | Library pieces |
12
+ |---|---|---|
13
+ | 1. Ledger seam | Every balance write outside top-ups and subscriptions goes through one `wallet/ledger.ts` | `createLegacyLedgerStore`, `createLedger`, `createAdminAdjustments` |
14
+ | 2. Top-ups and stores | `completeTopup`, Apple, Google and SePay onto the ingest inbox | `createIngest`, provider adapters, `onUnmatched` |
15
+ | 3. Subscriptions | `user_subscriptions` onto terms through an adapter | `TermStore` conformance, `createPlans` with policy `none` |
16
+
17
+ Step 1 comes first because steps 2 and 3 call the seam it creates.
18
+
19
+ ## Ground rules
20
+
21
+ - **Record before you change.** Capture the iOS wire byte for byte first:
22
+ wallet balance, Apple packs, Apple top-up (including the replay answer),
23
+ `/v1/subscriptions/*`, `/v1/app-config`, `/pricing/quote` and
24
+ `/novel/tts/pricing`. Then compare against the recording after every change.
25
+ `tier: null` makes the app wipe its offline library, so a resolver error
26
+ must answer 5xx, never `tier: null`.
27
+ - **Same tables.** `user_wallets` stays the balance and keeps its
28
+ `CHECK (balance >= 0)`. `wallet_transactions` stays the history, and its
29
+ `reason` column keeps today's strings, so analytics prefixes do not move.
30
+ - **Additive migration only**, generated with `bun run db:generate`, opened
31
+ with `SET lock_timeout = '5s'`, with no rewrite of a big table. Re-measure
32
+ `wallet_transactions` before you write it. Above about 1 GB, build the
33
+ indexes with `CREATE INDEX CONCURRENTLY` through a custom migration.
34
+ - **Pin exactly:** `"@tofound/billing": "1.0.0"`, refreshed in both lockfiles.
35
+
36
+ ## Step 1 — the ledger seam over `user_wallets` / `wallet_transactions`
37
+
38
+ ### Schema (additive)
39
+
40
+ `wallet_transactions` gains two nullable columns. Neither has a default, so
41
+ adding them rewrites nothing:
42
+
43
+ | Column | Type | Why |
44
+ |---|---|---|
45
+ | `idempotency_key` | `text`, partial unique index `WHERE idempotency_key IS NOT NULL` | The ledger's replay guard (I3). |
46
+ | `ledger` | `jsonb`, partial unique index on `(ledger->>'reversesId') WHERE … IS NOT NULL` | Kind, reversal link, source and meta. Lohi has no columns for these, and the ledger's replay check compares kind and reversal. |
47
+
48
+ The design originally named only `idempotency_key`. The `ledger` column
49
+ exists because the store conformance suite round-trips `kind`, `reversesId`,
50
+ `sourceType`/`sourceId` and `meta`. Without it, a replay would be checked
51
+ against the inferred kind, and a reversal could be posted twice.
52
+
53
+ Pre-existing rows keep both columns `NULL`. The store reads them with key
54
+ `legacy:<id>`, and their kind comes from `kindOf`, which maps Lohi's reason
55
+ strings onto ledger kinds.
56
+
57
+ ### The driver
58
+
59
+ `createLegacyLedgerStore(driver, codec)` from `@tofound/billing/hostkit`
60
+ turns a small driver into a full `LedgerStore`. The driver is row I/O only:
61
+
62
+ ```ts
63
+ import { createLedger } from '@tofound/billing'
64
+ import { createLegacyLedgerStore, type LegacyWalletDriver } from '@tofound/billing/hostkit'
65
+
66
+ const driver: LegacyWalletDriver<Tx> = {
67
+ transaction: (fn) => db.transaction(fn),
68
+ lockWallet, // SELECT … FOR UPDATE user_wallets, insert at 0 when missing
69
+ setBalance, // UPDATE user_wallets SET balance
70
+ insertRow, // INSERT wallet_transactions … ON CONFLICT DO NOTHING → inserted?
71
+ getBalance, getRow, findRowByKey, findReversalOf,
72
+ countRows, // rows of the user, optionally only those before a row
73
+ listRows, // newest first by (created_at, id), limit/offset
74
+ }
75
+ export const walletStore = createLegacyLedgerStore(driver, {
76
+ reasonOf: (entry) => entry.reason ?? entry.kind, // the Lohi reason string you pass as `reason`
77
+ kindOf: (row) => lohiKindOf(row.reason, row.amount), // old rows only
78
+ })
79
+ export const ledger = createLedger({ store: walletStore, events: toLohiBus })
80
+ ```
81
+
82
+ What the kit does for you:
83
+
84
+ - **seq.** Lohi has no seq column, so an entry's seq is its position in the
85
+ user's `(created_at, id)` order. The kit keeps new rows strictly after the
86
+ newest one, moving `created_at` by 1 ms when the clock has not advanced, so
87
+ that order is the posting order.
88
+ - **Replay and no overdraft.** These come from the ledger, under the wallet
89
+ row lock.
90
+
91
+ What the driver must get right (each one failed a test here first):
92
+
93
+ - **Compare order in the database.** `created_at` is stored to the
94
+ microsecond, but a JS `Date` keeps only milliseconds. So `countRows(…,
95
+ before)` must compare `(created_at, id) < (SELECT created_at, id FROM
96
+ wallet_transactions WHERE id = $1)`, not a time read back into JS. Rows
97
+ written in one transaction share `now()` to the microsecond, and the `id`
98
+ breaks the tie.
99
+ - **A lookup by a non-uuid id is a miss.** `wallet_transactions.id` is
100
+ `uuid`, so `getRow` must return `null` for anything else instead of letting
101
+ Postgres raise `invalid input syntax for type uuid`.
102
+ - **Refuse without aborting.** Use `ON CONFLICT DO NOTHING` for both unique
103
+ indexes. A conflict must not throw, or the host's transaction aborts.
104
+ - **`reason` is `varchar(64)`.** Keep the reasons you pass within it.
105
+ - **Paging.** `listRows` pages with OFFSET on the `(user_id, created_at)`
106
+ index, which is fine at today's size. Re-measure if one user ever has tens
107
+ of thousands of rows.
108
+
109
+ **Acceptance:** run the library's own suite against the real database.
110
+
111
+ ```ts
112
+ import { ledgerConformanceCases } from '@tofound/billing/testing'
113
+ for (const c of ledgerConformanceCases) test(c.name, () => c.run({ store: walletStore, newAccountId: newUserId }))
114
+ ```
115
+
116
+ The library's own test suite runs this against a Lohi-shaped reference
117
+ driver, on memory and on Postgres, and it passes.
118
+
119
+ ### Routing the writes
120
+
121
+ There are 16 `update(userWallets)` and 17 `insert(walletTransactions)` sites.
122
+ Move every one of them outside `wallet/topup*` and `subscriptions/**` onto
123
+ `ledger.in(tx)` (`credit`, `debit`, `debitUpTo`, `reverse`), passing the same
124
+ `reason` string as today. Then add a scan test that fails on a direct write
125
+ anywhere else.
126
+
127
+ The ledger hands back `BillingEvent`s. Map `credited` / `debited` onto the
128
+ existing `wallet_credited` / `wallet_debited` bus events, after the commit.
129
+ Renewal retry and revenue analytics listen to those events, so their names
130
+ and payloads do not change.
131
+
132
+ ### Admin balance adjustment
133
+
134
+ `POST /admin/users/:id/topup` becomes:
135
+
136
+ ```ts
137
+ import { createAdminAdjustments } from '@tofound/billing/hostkit'
138
+
139
+ const adjustments = createAdminAdjustments({ store: walletStore, overdraft: 'clamp', keyPrefix: 'admin_topup:' })
140
+ const result = await adjustments.adjust({
141
+ accountId: userId, amount, requestId, // requestId: minted once per admin action, globally unique
142
+ reason: note ? `admin_topup:${note}` : 'admin_topup', // today's reason string
143
+ actorId: actor.sub, note,
144
+ })
145
+ if (result.status === 'balance_changed') { /* only when you pass expectedBalance */ }
146
+ return c.json({ balance: result.balanceAfter })
147
+ ```
148
+
149
+ - `overdraft: 'clamp'` keeps Lohi's `max(0, balance + amount)`, and the
150
+ untaken part comes back as `shortfall`. 2Novel uses the default `reject`,
151
+ which raises `insufficient_credits`.
152
+ - A retried request id answers `replayed` with the first entry. Idempotency
153
+ keys are global, so mint `requestId` as a UUID.
154
+ - The route needs one new input: the admin client sends a `requestId`.
155
+ Without one, a double-click posts twice, exactly as it does today.
156
+
157
+ ## Step 2 — top-ups and store notifications
158
+
159
+ `completeTopup` becomes `purchases.applyCompleted` plus an in-transaction
160
+ `afterCredited` hook, where promotion bonuses and referral rewards run as
161
+ today. Lohi's tables stay, through adapters: `wallet_topups` (purchases and
162
+ checkout sessions, with `provider_order_id` as `externalId`),
163
+ `wallet_topup_refunds` and `apple_topup_refund_state` (the reversal records
164
+ and watermark).
165
+
166
+ - **SePay.** Use `createSepayAdapter({ environment, … })` with Lohi's own
167
+ environment rule passed explicitly. `forwardLitransIpn` becomes the ingest
168
+ `onUnmatched` hook, so unknown invoices still reach 2Novel. Since 1.0 the
169
+ adapter drops `order.user_agent` from stored payloads. An IPN whose
170
+ `transaction.transaction_amount` disagrees with `order.order_amount` goes
171
+ to `needs_review` (`amount_mismatch`) and credits nothing.
172
+ - **Apple and Google.** Use the `/providers/apple` and `/providers/google`
173
+ adapters. A client proof (`signedTransaction`, purchase token) and its
174
+ store notification have different event ids (`apple:txn:<transactionId>` /
175
+ `apple:<notificationUUID>`, `google:order:<orderId>` / `google:<messageId>`).
176
+ They credit once because both resolve to the same purchase (`transactionId`
177
+ / `orderId`): whichever arrives second answers `ignored` /
178
+ `already_completed`, not `duplicate`. The Apple top-up
179
+ replay answer must still decode on shipped builds, because otherwise iOS
180
+ never finishes the transaction.
181
+ - **Strict environment.** A production adapter refuses Sandbox payloads
182
+ (401) and ignores Play license-tester purchases. Run one ingest per
183
+ environment: a production and a sandbox adapter share the provider id
184
+ (`apple` / `google`), so one `createIngest` refuses both
185
+ (`duplicate_adapter`), and the host routes each delivery to its ingest.
186
+ - **Only checkout-bound purchases credit.** Create a server-priced checkout
187
+ session before `ingest.confirm`, or set `appAccountToken` /
188
+ `obfuscatedExternalAccountId` to the session id (a UUID by default). A
189
+ notification naming no session is `ignored` (`unbound_purchase`), and the
190
+ app's proof settles it.
191
+ - **A refund or void that outruns an unbound purchase stays unmatched.** The
192
+ later proof of an already-revoked purchase parks as
193
+ `reversed_before_credit` and voids the session.
194
+ - **Lohi's per-user `appAccountToken`** is not a session id, so it works
195
+ only through proofs that carry `checkoutRef`.
196
+ - **`ingest.confirm` does not catch what `verifyPurchase` throws.** A bad
197
+ proof throws `VerifyError` (`unauthorized` / `malformed`), a bad
198
+ `checkoutRef` throws `ProviderConfigError`, and a Play lookup failure
199
+ throws `GooglePlayApiError`; the host maps these to its own response.
200
+ Apple's `AppleApiError` comes only from `reportConsumption`.
201
+ - **Not in the library yet:** `createIngest` has no entry for
202
+ `Reconcilable` deliveries, so feed `google.listChangesSince` results
203
+ through a host shim. The live App Store and Play endpoints have not been
204
+ exercised against real store accounts.
205
+
206
+ ## Step 3 — subscriptions
207
+
208
+ `user_subscriptions` becomes a `TermStore` adapter. It must pass
209
+ `termConformanceCases`.
210
+
211
+ - **Mapping:** liveness stays `ends_at > now()`, `tier` becomes the plan,
212
+ `lt_cost` becomes the price snapshot, and `auto_renewal` is kept. Meters
213
+ stay Lohi's.
214
+ - **Policies:** proration `none` (the end date is inherited), no refunds,
215
+ comps at `lt_cost 0`.
216
+ - **Unchanged:** the admin `renew-due` trigger, and 1809 rows that are
217
+ "active" past `ends_at`. Neither changes here, and no scheduler is added.
218
+
219
+ Ask the catalog for tiers (`SUBSCRIPTION_TIERS`,
220
+ `tiersWithPermission(…)`). Never retype a tier list: the library carries no
221
+ tier literals.
222
+
223
+ ## Quotes
224
+
225
+ Lohi keeps `planFunding()` and `GATES`, and `/pricing/quote` stays byte
226
+ identical. Only the wallet step's balance read and debit move onto the
227
+ ledger. A new surface that serves a library `Quote` uses `serializeQuote`
228
+ from the host kit. It emits Lohi's key order and labels from a host labeler,
229
+ and `coveredSources` adds the legacy `subscriptionCovered` key that shipped
230
+ iOS builds decode.
231
+
232
+ ## Rollback
233
+
234
+ The migration is additive and every writer keeps the same rows, so the
235
+ previous image still reads and writes the tables correctly: an image rollback
236
+ is safe at any point. Rolling forward again needs no resync, because the
237
+ balance never lived anywhere but `user_wallets`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tofound/billing",
3
- "version": "0.2.0",
3
+ "version": "1.0.0",
4
4
  "description": "Shared subscription and credit library by 2found: credit ledger, quote/charge waterfall, Drizzle schema factory.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -27,16 +27,32 @@
27
27
  "import": "./dist/providers/polar/index.js",
28
28
  "default": "./dist/providers/polar/index.js"
29
29
  },
30
+ "./providers/apple": {
31
+ "types": "./dist/providers/apple/index.d.ts",
32
+ "import": "./dist/providers/apple/index.js",
33
+ "default": "./dist/providers/apple/index.js"
34
+ },
35
+ "./providers/google": {
36
+ "types": "./dist/providers/google/index.d.ts",
37
+ "import": "./dist/providers/google/index.js",
38
+ "default": "./dist/providers/google/index.js"
39
+ },
30
40
  "./testing": {
31
41
  "types": "./dist/stores/testing.d.ts",
32
42
  "import": "./dist/stores/testing.js",
33
43
  "default": "./dist/stores/testing.js"
34
44
  },
45
+ "./hostkit": {
46
+ "types": "./dist/hostkit/index.d.ts",
47
+ "import": "./dist/hostkit/index.js",
48
+ "default": "./dist/hostkit/index.js"
49
+ },
35
50
  "./package.json": "./package.json"
36
51
  },
37
52
  "files": [
38
53
  "dist",
39
54
  "docs/API.md",
55
+ "docs/MIGRATION-LOHI.md",
40
56
  "docs/SCHEMA.md",
41
57
  "README.md",
42
58
  "CHANGELOG.md",