@tofound/billing 0.2.0 → 1.1.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.
- package/CHANGELOG.md +90 -1
- package/README.md +20 -5
- package/dist/hostkit/adjustments.d.ts +65 -0
- package/dist/hostkit/adjustments.js +84 -0
- package/dist/hostkit/index.d.ts +9 -0
- package/dist/hostkit/index.js +9 -0
- package/dist/hostkit/legacy-ledger.d.ts +87 -0
- package/dist/hostkit/legacy-ledger.js +111 -0
- package/dist/hostkit/quote-wire.d.ts +73 -0
- package/dist/hostkit/quote-wire.js +50 -0
- package/dist/inbox/apply.d.ts +47 -1
- package/dist/inbox/apply.js +32 -1
- package/dist/inbox/ingest.d.ts +33 -3
- package/dist/inbox/ingest.js +42 -5
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -0
- package/dist/providers/apple/events.d.ts +24 -0
- package/dist/providers/apple/events.js +232 -0
- package/dist/providers/apple/index.d.ts +54 -0
- package/dist/providers/apple/index.js +231 -0
- package/dist/providers/apple/jws.d.ts +50 -0
- package/dist/providers/apple/jws.js +206 -0
- package/dist/providers/google/api.d.ts +57 -0
- package/dist/providers/google/api.js +226 -0
- package/dist/providers/google/events.d.ts +46 -0
- package/dist/providers/google/events.js +135 -0
- package/dist/providers/google/index.d.ts +37 -0
- package/dist/providers/google/index.js +228 -0
- package/dist/providers/polar/index.d.ts +1 -1
- package/dist/providers/port.d.ts +2 -0
- package/dist/providers/sepay/index.js +29 -0
- package/docs/API.md +226 -9
- package/docs/GUIDE.md +254 -0
- package/docs/MIGRATION-LOHI.md +237 -0
- package/package.json +18 -1
package/docs/GUIDE.md
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
# @tofound/billing — task guide (1.1)
|
|
2
|
+
|
|
3
|
+
How to do the common jobs with the library. [API.md](API.md) is the
|
|
4
|
+
reference for every export; this page walks the order of the calls and what
|
|
5
|
+
to do when something fails. Examples use `LT`-style credits and a Postgres
|
|
6
|
+
host, but nothing here depends on a product.
|
|
7
|
+
|
|
8
|
+
Imports: the main entry `@tofound/billing` has the ledger, ingest, catalog,
|
|
9
|
+
plans, renewal and entitlement; the Drizzle stores and tables are in
|
|
10
|
+
`/drizzle`, `createPolarAdapter` and `resolvePolarEnvironment` in
|
|
11
|
+
`/providers/polar`, and `createAdminAdjustments` in `/hostkit`.
|
|
12
|
+
|
|
13
|
+
Every example assumes the pieces a host builds once:
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
const ledger = createLedger({ store: createDrizzleLedgerStore({ db, tables }) })
|
|
17
|
+
const terms = createDrizzleTermStore({ db, tables: termTables }) // plans only
|
|
18
|
+
const catalog = defineCatalog({ … }) // your config, no literals in the library
|
|
19
|
+
const plans = createPlans({ ledger, terms, catalog })
|
|
20
|
+
const renewal = createRenewal({ ledger, terms, catalog })
|
|
21
|
+
const ingest = createIngest({ adapters, store: createDrizzleIngestStore({ db, tables: ingestTables }), ledger, handlers, afterCredited, onHookError })
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Two rules hold throughout. **Prices come from your catalog and your
|
|
25
|
+
server, never from a client.** **Every money effect is keyed**, so a retry,
|
|
26
|
+
a redelivery and a replay each post once.
|
|
27
|
+
|
|
28
|
+
## 1. Sell credit packs
|
|
29
|
+
|
|
30
|
+
A pack is a server-priced checkout session; the provider's payment credits
|
|
31
|
+
the session once.
|
|
32
|
+
|
|
33
|
+
1. Declare packs in the catalog: `creditPacks: [{ key, market, provider, price, credits, bonusCredits?, productRef? }]`.
|
|
34
|
+
2. Start the checkout from the pack, never from a client amount:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
const pack = catalog.pack(key) // undefined for a key the client invented: answer 404 before going on
|
|
38
|
+
if (!pack) throw new NotFound()
|
|
39
|
+
const { session, redirect } = await ingest.createCheckout({
|
|
40
|
+
provider: pack.provider, accountId, amount: pack.price,
|
|
41
|
+
credits: pack.credits + pack.bonusCredits, productRef: pack.productRef,
|
|
42
|
+
description, successUrl, errorUrl, cancelUrl,
|
|
43
|
+
customerIpAddress, // 1.1: Polar uses it for the tax country; others ignore it
|
|
44
|
+
})
|
|
45
|
+
// send the buyer to `redirect` (SePay: `kind: 'form'`; Polar: `kind: 'redirect'`)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
3. Mount one raw-body route per provider that calls
|
|
49
|
+
`ingest.handle(provider, { headers, rawBody, url, receivedAt })` and
|
|
50
|
+
replies with `result.response`. The credit posts under `topup:<sessionId>`
|
|
51
|
+
once, however many times the provider repeats itself, and a payment that
|
|
52
|
+
lands after the session expired still credits.
|
|
53
|
+
4. For a client-return page, poll with `ingest.confirm(provider, proof)`; it
|
|
54
|
+
shares the webhook's event id, so the two cannot double-credit. Check the
|
|
55
|
+
caller owns the session before you call it.
|
|
56
|
+
5. Run `ingest.sweep()` on a timer: it retries `failed` rows with backoff and
|
|
57
|
+
re-enters rows a crash left `received`.
|
|
58
|
+
6. React to the credit with `afterCredited` (§ 2), not by polling the ledger.
|
|
59
|
+
|
|
60
|
+
**When it fails:** a wrong amount, a foreign currency or a second capture of
|
|
61
|
+
a paid session goes to `needs_review` with a `billing.alert` and credits
|
|
62
|
+
nothing; fix it by hand and `ingest.replay(provider, eventId)`.
|
|
63
|
+
|
|
64
|
+
## 2. React to a credit: `afterCredited`
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
createIngest({
|
|
68
|
+
…,
|
|
69
|
+
afterCredited: async (c) => { // c: CreditedPurchase
|
|
70
|
+
// c.provider, c.accountId, c.kind ('completed' | 'reinstated'),
|
|
71
|
+
// c.entry (the ledger entry, delta > 0), c.externalId, c.sessionId
|
|
72
|
+
await renewal.retryPastDue(c.accountId)
|
|
73
|
+
},
|
|
74
|
+
onHookError: (error, c) => report(error, c.accountId),
|
|
75
|
+
})
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
- It runs **after the delivery's transaction committed**, never inside it. The
|
|
79
|
+
crediting transaction already holds the account lock, which must come last,
|
|
80
|
+
so a hook that opens its own transaction (renewal does) cannot deadlock it.
|
|
81
|
+
- It runs **at most once per credit**. It does not run for a `duplicate`, a
|
|
82
|
+
replay of a settled row, an `ignored` or `needs_review` delivery, a
|
|
83
|
+
reversal, or an empty entry, and not for a delivery that credited nothing
|
|
84
|
+
(an `ignored` or `needs_review` outcome). A delivery with several events
|
|
85
|
+
announces each credit that committed, whatever its sibling's status. A
|
|
86
|
+
transaction that rolled back never ran it; the retry that finally commits
|
|
87
|
+
does.
|
|
88
|
+
- **A throwing hook changes nothing.** The error goes to `onHookError` (whose
|
|
89
|
+
own throw is swallowed) and the delivery stays `applied`, so the provider
|
|
90
|
+
is not asked to redeliver.
|
|
91
|
+
- It announces purchase credits (capture, reinstatement) and what a host
|
|
92
|
+
handler reports in `credited`; the refund a superseded term receives (§ 4)
|
|
93
|
+
is not announced. The hook is awaited before the provider is answered, so
|
|
94
|
+
keep it short.
|
|
95
|
+
- A crash between commit and hook loses the call. Keep a periodic backstop:
|
|
96
|
+
`renewal.renewDue()` retries past-due terms on its next run.
|
|
97
|
+
- It also fires for **host handlers**: a handler you supply for
|
|
98
|
+
`purchase.completed` that credits an account itself returns the credit, and
|
|
99
|
+
the library announces it:
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
handlers: {
|
|
103
|
+
'purchase.completed': async (event, ctx) => {
|
|
104
|
+
const posted = await ctx.ledger.credit({ … })
|
|
105
|
+
return { status: 'applied', events: posted.events, credited: { accountId, entry: posted.entry, kind: 'completed', sessionId, externalId: event.externalId } }
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### Hand one provider back to the library
|
|
111
|
+
|
|
112
|
+
A host that overrides `purchase.*` for its own top-up table still wants the
|
|
113
|
+
library's appliers for a provider whose sessions live in the library tables
|
|
114
|
+
(Polar). Delegate per provider with `defaultEventHandlers`:
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
const purchase: EventHandler<Tx> = (event, ctx) =>
|
|
118
|
+
ctx.delivery.provider === 'polar'
|
|
119
|
+
? defaultEventHandlers['purchase.completed'](event, ctx) // or 'purchase.reversed' / 'purchase.reinstated'
|
|
120
|
+
: hostTopup(event, ctx)
|
|
121
|
+
handlers: { 'purchase.completed': purchase, 'purchase.reversed': …, 'purchase.reinstated': … }
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`ctx.store` is the ingest store bound to the handler's transaction; the
|
|
125
|
+
default handlers apply through it and report the credit they post.
|
|
126
|
+
|
|
127
|
+
## 3. Sell a monthly plan end to end
|
|
128
|
+
|
|
129
|
+
1. **Catalog.** Plans with strict `rank` (one `free`), credit offers per
|
|
130
|
+
`market × months`, and `policies` (`graceDays`, `renewalLeadSec`,
|
|
131
|
+
`upgradeProration`).
|
|
132
|
+
2. **Quote.** `plans.quote({ accountId, plan, months, market })` returns the
|
|
133
|
+
kind (`new`, `extend`, `upgrade`, `renew`, `downgrade`, `blocked`), the
|
|
134
|
+
price and the funding lines. Render those lines; do not recompute them.
|
|
135
|
+
`market` is set by the host, never taken from the client.
|
|
136
|
+
3. **Purchase.** `plans.purchase({ …, idempotencyKey })`, inside the host
|
|
137
|
+
transaction when it also writes host rows (`plans.in(tx)`; a throw must
|
|
138
|
+
roll that transaction back). Mint the key once per confirm: a retry with it
|
|
139
|
+
buys once.
|
|
140
|
+
4. **Entitlement.** `resolveEntitlement(await terms.reader().listTerms(accountId), now, catalog, { balance })`
|
|
141
|
+
answers the plan, status (`active`, `grace`, `free`), warnings and quotas.
|
|
142
|
+
5. **Renewal.** `renewal.renewDue({ limit })` on a timer (every 15 minutes is
|
|
143
|
+
fine) under the host's own advisory lock, so two instances do not both
|
|
144
|
+
run. It charges the live catalog price, keyed by term and period end, so a
|
|
145
|
+
double run debits once.
|
|
146
|
+
6. **Retry on top-up.** `afterCredited` (§ 2) calls
|
|
147
|
+
`renewal.retryPastDue(accountId)`; the term continues from its old end.
|
|
148
|
+
The timer is the backstop.
|
|
149
|
+
|
|
150
|
+
## 4. Sell a provider subscription, and supersede a credit term
|
|
151
|
+
|
|
152
|
+
1. Add a provider offer to the plan: `{ source: 'polar', productRef, market, interval, price }`,
|
|
153
|
+
and map the provider's product ids to those refs in the adapter's
|
|
154
|
+
`products`.
|
|
155
|
+
2. Create the checkout **outside the ingest**: `polar.createCheckout({ sessionId: randomUUID(), accountId, amount: offer.price, productRef, … })`
|
|
156
|
+
with the catalog price (the adapter refuses a product priced differently).
|
|
157
|
+
No session row is written.
|
|
158
|
+
3. Wire the snapshot handler:
|
|
159
|
+
`handlers: { 'subscription.snapshot': createSnapshotHandler({ terms, catalog, resolveAccount }) }`.
|
|
160
|
+
`resolveAccount` maps the provider's external customer id to your account
|
|
161
|
+
and returns `null` for another host's customer.
|
|
162
|
+
4. **Supersede (S4).** When an entitled provider subscription of the same or
|
|
163
|
+
higher rank arrives, the snapshot handler closes the open credit term
|
|
164
|
+
(`superseded`) and refunds its unused share as a `plan_refund` credit
|
|
165
|
+
keyed `supersede:<termId>`. Before that, `plans.quote` answers `blocked`
|
|
166
|
+
(`covered_by_subscription`) for a plan the subscription already covers,
|
|
167
|
+
so the buyer is not charged twice.
|
|
168
|
+
5. Give the buyer the provider's portal for card and cancel:
|
|
169
|
+
`polar.createPortalSession({ kind: 'account_id', value: accountId }, returnUrl)`.
|
|
170
|
+
|
|
171
|
+
## 5. Handle a failed renewal, per source
|
|
172
|
+
|
|
173
|
+
| Source | What fails | What the library does | What the host does |
|
|
174
|
+
|---|---|---|---|
|
|
175
|
+
| **Credit renewal** | Balance below the live price at `periodEnd − renewalLeadSec` | An early failure emits `renewal_failed` and leaves the term `active`. At the period end the term becomes `past_due` with `graceUntil = periodEnd + graceDays`, still entitled. After the grace it is `expired`. | Show the shortfall from the `renewal_failed` event (`required`, `balance`, `shortfall`). A top-up fires `afterCredited`, which calls `retryPastDue`; the renewal timer retries too. |
|
|
176
|
+
| **Polar subscription** | The card is declined; Polar retries | The snapshot goes `past_due` and the term gets a grace window. `revoked`, or `canceled` once ended, ends access. Snapshots are ordered by Polar's `modified_at`, so an old one cannot undo a new one. | Show "update your card" with the portal link. A card fix arrives as an `active` snapshot; nothing else to do. |
|
|
177
|
+
| **Apple** | Billing retry or grace period (App Store) | Auto-renewable notifications become snapshots with `past_due` / `grace`. One-time (consumable) purchases are keyed by transaction; a refund reverses once. | Treat Apple's own retry and grace as the source of truth; do not charge credits for an Apple term. Selling Apple subscriptions is the host's decision; the adapter handles the notifications. |
|
|
178
|
+
| **Any webhook** | The handler throws | The row is `failed`, answered 5xx so the provider redelivers, retried by `sweep` with backoff, then `dead` with a `billing.alert`. | Alert on `billing.alert`; fix the cause and `ingest.replay(provider, eventId)`. |
|
|
179
|
+
|
|
180
|
+
A failed **pack** payment creates no order and no credit; the session simply
|
|
181
|
+
expires, and a late payment still credits once.
|
|
182
|
+
|
|
183
|
+
## 6. Refunds and reversals, and the shortfall
|
|
184
|
+
|
|
185
|
+
- A provider refund, chargeback or void becomes a reversal. The library
|
|
186
|
+
claws back through `ledger.reverse` (`reversal:<provider>:<externalId>:<n>`)
|
|
187
|
+
what the balance still holds; the part the buyer already spent is recorded
|
|
188
|
+
as the purchase's **`shortfall`** and reported in a `refund_applied` event
|
|
189
|
+
(`clawedBack`, `shortfall`).
|
|
190
|
+
- The reversal is ordered by the provider's own timestamp, so a refund that
|
|
191
|
+
arrives before its payment parks the payment and never credits it; a
|
|
192
|
+
reinstatement restores exactly what was taken back.
|
|
193
|
+
- **A shortfall is policy, and the host applies it.** The catalog carries the
|
|
194
|
+
choice (`policies.reversalShortfall`: `record` or `lapse_credit_terms`), but
|
|
195
|
+
the library only reports the numbers: it records the shortfall on the
|
|
196
|
+
purchase and emits `refund_applied`. Read the policy there and either record
|
|
197
|
+
it for support or close the credit terms the credits had bought yourself.
|
|
198
|
+
The library never takes a balance below zero to cover it.
|
|
199
|
+
- A **partial** refund is never guessed: it goes to `needs_review`.
|
|
200
|
+
Settle it by hand with an `adjustment` (`createAdminAdjustments`, which
|
|
201
|
+
can `clamp` to the balance and reports the shortfall).
|
|
202
|
+
|
|
203
|
+
## 7. Arm a provider in production (two switches)
|
|
204
|
+
|
|
205
|
+
A provider in production needs two independent switches, so a half-finished
|
|
206
|
+
deploy cannot take real money.
|
|
207
|
+
|
|
208
|
+
1. **The environment is explicit.** The adapter has no default.
|
|
209
|
+
`resolvePolarEnvironment({ environment: env.POLAR_ENV, productionEnabled: env.POLAR_PRODUCTION_ENABLED === 'true' })`
|
|
210
|
+
returns `production` only when **both** `POLAR_ENV=production` **and**
|
|
211
|
+
`productionEnabled` hold; `production` without the flag throws
|
|
212
|
+
`polar_production_disabled`, and an unset or misspelled value throws
|
|
213
|
+
`polar_environment_required`.
|
|
214
|
+
2. **The credentials match the environment.** Production secrets, the
|
|
215
|
+
production product ids in `products`, and a webhook secret for the
|
|
216
|
+
production endpoint. SePay refuses test credentials in production (and
|
|
217
|
+
live ones in sandbox).
|
|
218
|
+
|
|
219
|
+
Rehearse the switch in sandbox first, keep the routes returning 503 until
|
|
220
|
+
both switches are on, and disarm by clearing the second switch. Hosts
|
|
221
|
+
rotate secrets by listing the new one beside the old (`webhookSecrets`,
|
|
222
|
+
`webhookKeys`) and removing the old one after a day.
|
|
223
|
+
|
|
224
|
+
## 8. Migrate a legacy term table
|
|
225
|
+
|
|
226
|
+
The recipe Lohi follows for its subscription table, generic for any host
|
|
227
|
+
that already has one row per subscription.
|
|
228
|
+
|
|
229
|
+
1. **Add the library tables** (`createTermTables`) as new tables only; run
|
|
230
|
+
your own `db:generate` and `checkAdditiveDdl` on the SQL. Never alter the
|
|
231
|
+
legacy table.
|
|
232
|
+
2. **Copy with deterministic ids** (`legacy_<id>`), in batches of a few hundred
|
|
233
|
+
rows, one transaction each, `ON CONFLICT DO NOTHING`, key order, with a
|
|
234
|
+
`--dry-run`. Map: live row → an open `active` credit term; every other
|
|
235
|
+
row → `expired` (keep the original status in `meta`); a second live row →
|
|
236
|
+
a `scheduled` term, or list it for a human.
|
|
237
|
+
3. **Run modes, flipped by config only:** `legacy` (read and write the old
|
|
238
|
+
table) → `dual` (still the old table, mirror each write into terms in the
|
|
239
|
+
same transaction, run the library resolver in shadow and log mismatches)
|
|
240
|
+
→ `library_read` (read terms) → `library` (write through `createPlans` /
|
|
241
|
+
`createRenewal`, and project back to the legacy row in the same
|
|
242
|
+
transaction so a rollback is a config flip).
|
|
243
|
+
4. **Check parity both ways** before each step: every legacy row has its
|
|
244
|
+
term and the reverse; per account the resolved plan, end date, auto-renew
|
|
245
|
+
and status class match; the ledger history is untouched.
|
|
246
|
+
5. **Never drop the legacy table** in the same project.
|
|
247
|
+
|
|
248
|
+
## 9. Google Play subscriptions are not supported
|
|
249
|
+
|
|
250
|
+
The Google adapter handles **one-time products** only: a purchase is trusted
|
|
251
|
+
only as Play's own `products.get` answer, and a voided purchase is clawed
|
|
252
|
+
back once. Google Play **subscriptions are not supported yet**: subscription
|
|
253
|
+
notifications are acknowledged and `ignored`, no term is created and no
|
|
254
|
+
credit is granted. Do not sell a Google subscription through this library.
|
|
@@ -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": "
|
|
3
|
+
"version": "1.1.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,33 @@
|
|
|
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/GUIDE.md",
|
|
56
|
+
"docs/MIGRATION-LOHI.md",
|
|
40
57
|
"docs/SCHEMA.md",
|
|
41
58
|
"README.md",
|
|
42
59
|
"CHANGELOG.md",
|