@tofound/billing 1.0.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 CHANGED
@@ -4,6 +4,36 @@ All notable changes to `@tofound/billing`. Versions follow semver; 0.x minors
4
4
  were additive. From 1.0.0 the public API is frozen: removing or narrowing
5
5
  anything in the declaration snapshot is a major version.
6
6
 
7
+ ## 1.1.0 — 2026-10-24
8
+
9
+ Additive to 1.0: every 1.0 export is unchanged (the public-api declaration
10
+ snapshot only grows). No schema change.
11
+
12
+ To adopt: pin `@tofound/billing@1.1.0`.
13
+
14
+ - **`afterCredited` / `onHookError`** on `createIngest`: a hook called after
15
+ the delivery's transaction commits, at most once per credit, with a
16
+ `CreditedPurchase` (`provider`, `accountId`, `kind`, `entry`, `externalId`,
17
+ `sessionId`). It fires for the library's own appliers and for a host handler
18
+ that returns the new optional `credited` field on its result
19
+ (`HandlerResult`, an alias of `ApplyResult`). It never fires for a duplicate,
20
+ a replay of a settled row, an ignored delivery, a reversal, a rolled-back
21
+ attempt or an empty entry. A hook that throws goes to `onHookError` and never
22
+ changes the delivery outcome.
23
+ - **`defaultEventHandlers`** exported: the library's `purchase.completed`,
24
+ `purchase.reversed` and `purchase.reinstated` appliers, so a host that
25
+ overrides a kind for one provider can delegate the others back. `ApplyContext`
26
+ gains `store` (the ingest store bound to the handler's transaction) and
27
+ `newId`; handlers only read them, so existing handlers compile unchanged
28
+ (a test that builds an `ApplyContext` by hand adds the two fields).
29
+ - **`ingest.createCheckout` forwards `customerIpAddress`** to the adapter
30
+ (`CheckoutRequest.customerIpAddress`, optional). Polar uses it to pick the tax
31
+ country; before, only a direct `polar.createCheckout` sent it.
32
+ - **`docs/GUIDE.md`**, a task guide shipped in the package: credit packs, a
33
+ monthly plan end to end, a provider subscription and supersede, failed
34
+ renewals per source, refunds with shortfall, arming a provider, migrating a
35
+ legacy term table, and that Google Play subscriptions are not supported.
36
+
7
37
  ## 1.0.0 — 2026-10-24
8
38
 
9
39
  The 1.0 API freeze. Every 0.2 export is unchanged (changes since 0.2.0 are
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  products (2Novel first, the Lohi reader api last). Each host API embeds it on
5
5
  its own database; there is no billing service.
6
6
 
7
- 1.0 ships (the public API is frozen from 1.0.0 on):
7
+ 1.1 ships (the public API is frozen from 1.0.0 on; 1.1 only adds):
8
8
 
9
9
  - **The money core** (since 0.1): an idempotent, no-overdraft credit ledger
10
10
  behind store ports, memory and Drizzle/Postgres stores, a Drizzle schema
@@ -23,7 +23,7 @@ its own database; there is no billing service.
23
23
  (`@tofound/billing/providers/google`) adapters.
24
24
 
25
25
  ```sh
26
- bun add @tofound/billing@1.0.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
26
+ bun add @tofound/billing@1.1.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
27
27
  ```
28
28
 
29
29
  ```ts
@@ -1,11 +1,33 @@
1
- import type { AccountId, BillingEvent } from '../domain/types.js';
1
+ import type { AccountId, BillingEvent, LedgerEntry } from '../domain/types.js';
2
2
  import type { LedgerOps } from '../ledger/ledger.js';
3
3
  import type { NormalizedEvent, PurchaseChangedEvent, PurchaseCompletedEvent, VerifiedDelivery } from '../providers/port.js';
4
4
  import type { IngestTx } from './ports.js';
5
5
  export type ApplyStatus = 'applied' | 'ignored' | 'needs_review';
6
+ /**
7
+ * A credit this apply posted, reported so `afterCredited` can fire once the
8
+ * transaction has committed. A host handler sets it on its result when it
9
+ * credits an account itself (Lohi's SePay / Apple / Google top-ups).
10
+ */
11
+ export interface HandlerCredited {
12
+ accountId: AccountId;
13
+ /** The crediting ledger entry (`delta > 0`); a zero or negative entry never fires the hook. */
14
+ entry: LedgerEntry;
15
+ /** `completed`: the credit of a capture. `reinstated`: credit a provider reinstatement gave back or released (a capture parked under a reversal). */
16
+ kind: 'completed' | 'reinstated';
17
+ /** The provider's purchase id, when the handler knows it. */
18
+ externalId?: string | null;
19
+ /** The checkout session the credit settles, when there is one. */
20
+ sessionId?: string | null;
21
+ }
6
22
  export interface ApplyResult {
7
23
  status: ApplyStatus;
8
24
  reason?: string;
25
+ /**
26
+ * An account this apply credited. Fires `afterCredited` after commit,
27
+ * whatever the `status` (a credit that committed is announced), but not when
28
+ * the entry is empty. Absent on a duplicate, replay, ignore or reversal.
29
+ */
30
+ credited?: HandlerCredited;
9
31
  /** No session or purchase on this host owns the event (the `onUnmatched` hook may forward it). */
10
32
  unmatched?: boolean;
11
33
  /** Ledger events to emit after commit. */
@@ -28,8 +50,14 @@ export interface ApplyContext<TTx = unknown> {
28
50
  ledger: LedgerOps;
29
51
  delivery: VerifiedDelivery;
30
52
  now: Date;
53
+ /** The ingest store bound to `tx`: what `defaultEventHandlers` apply through. Valid only inside the handler's transaction. */
54
+ store: IngestTx;
55
+ /** The ingest's id generator, for rows a delegated library applier inserts. */
56
+ newId: () => string;
31
57
  }
32
58
  export type EventHandler<TTx = unknown> = (event: NormalizedEvent, ctx: ApplyContext<TTx>) => Promise<ApplyResult>;
59
+ /** What an {@link EventHandler} returns. */
60
+ export type HandlerResult = ApplyResult;
33
61
  interface Deps {
34
62
  tx: IngestTx;
35
63
  ledger: LedgerOps;
@@ -45,4 +73,22 @@ export declare function applyPurchaseCompleted(event: PurchaseCompletedEvent, d:
45
73
  * arrive in, the purchase ends where the newest event puts it.
46
74
  */
47
75
  export declare function applyPurchaseChanged(event: PurchaseChangedEvent, d: Deps): Promise<ApplyResult>;
76
+ /**
77
+ * The library's own appliers, keyed by the event kind they handle. A host
78
+ * that overrides one kind (Lohi's `purchase.completed` over its own top-up
79
+ * table) hands the deliveries it does not own back to these, per provider:
80
+ *
81
+ * ```ts
82
+ * handlers: { 'purchase.completed': (e, ctx) =>
83
+ * ctx.delivery.provider === 'polar' ? defaultEventHandlers['purchase.completed'](e, ctx) : lohiTopup(e, ctx) }
84
+ * ```
85
+ *
86
+ * They apply through `ctx.store` inside the handler's transaction and report
87
+ * the credit they post in `credited`.
88
+ */
89
+ export declare const defaultEventHandlers: {
90
+ readonly 'purchase.completed': EventHandler<unknown>;
91
+ readonly 'purchase.reversed': EventHandler<unknown>;
92
+ readonly 'purchase.reinstated': EventHandler<unknown>;
93
+ };
48
94
  export {};
@@ -11,6 +11,10 @@
11
11
  */
12
12
  import { isBillingError } from '../domain/errors.js';
13
13
  import { isNewer } from './watermark.js';
14
+ /** The `credited` field for a fresh entry: a keyed replay posted nothing new. */
15
+ const creditedOf = (posted, kind, ref) => !posted.replayed
16
+ ? { credited: { accountId: posted.entry.accountId, entry: posted.entry, kind, externalId: ref.externalId, sessionId: ref.sessionId } }
17
+ : {};
14
18
  const sameMoney = (a, b) => a.currency === b.currency && a.amountMinor === b.amountMinor;
15
19
  /** The one ledger key of a checkout's credit: whichever path pays it, it is paid once. */
16
20
  const topupKey = (sessionId) => `topup:${sessionId}`;
@@ -117,6 +121,7 @@ export async function applyPurchaseCompleted(event, d) {
117
121
  status: 'applied',
118
122
  ...(session.status === 'pending' ? {} : { reason: `late_${session.status}` }),
119
123
  events: posted.events,
124
+ ...creditedOf(posted, 'completed', { externalId: event.externalId, sessionId: session.id }),
120
125
  };
121
126
  }
122
127
  /**
@@ -225,6 +230,7 @@ async function reinstate(purchase, mark, d) {
225
230
  return { status: 'ignored', reason: 'not_reversed' };
226
231
  }
227
232
  let events = [];
233
+ let credited = {};
228
234
  const patch = {
229
235
  status: 'reinstated',
230
236
  clawedBack: 0,
@@ -245,6 +251,7 @@ async function reinstate(purchase, mark, d) {
245
251
  meta: { provider: purchase.provider, externalId: purchase.externalId, amount: purchase.amount },
246
252
  });
247
253
  events = posted.events;
254
+ credited = creditedOf(posted, 'reinstated', { externalId: purchase.externalId, sessionId: pending.sessionId });
248
255
  Object.assign(patch, { credits: pending.credits, creditEntryId: posted.entry.id, meta: withoutPending(purchase.meta) });
249
256
  // The session is paid now: a second capture of it is money for a human.
250
257
  await d.tx.updateSession(pending.sessionId, { status: 'completed', externalId: purchase.externalId, completedAt: d.now });
@@ -260,11 +267,35 @@ async function reinstate(purchase, mark, d) {
260
267
  source: { type: 'purchase', id: purchase.id },
261
268
  });
262
269
  events = posted.events;
270
+ credited = creditedOf(posted, 'reinstated', { externalId: purchase.externalId, sessionId: purchase.checkoutSessionId });
263
271
  patch.creditEntryId = posted.entry.id;
264
272
  }
265
273
  await d.tx.updatePurchase(purchase.id, patch);
266
- return { status: 'applied', events };
274
+ return { status: 'applied', events, ...credited };
267
275
  }
276
+ /**
277
+ * The library's own appliers, keyed by the event kind they handle. A host
278
+ * that overrides one kind (Lohi's `purchase.completed` over its own top-up
279
+ * table) hands the deliveries it does not own back to these, per provider:
280
+ *
281
+ * ```ts
282
+ * handlers: { 'purchase.completed': (e, ctx) =>
283
+ * ctx.delivery.provider === 'polar' ? defaultEventHandlers['purchase.completed'](e, ctx) : lohiTopup(e, ctx) }
284
+ * ```
285
+ *
286
+ * They apply through `ctx.store` inside the handler's transaction and report
287
+ * the credit they post in `credited`.
288
+ */
289
+ export const defaultEventHandlers = Object.freeze({
290
+ 'purchase.completed': handlerFor('purchase.completed', (event, d) => applyPurchaseCompleted(event, d)),
291
+ 'purchase.reversed': handlerFor('purchase.reversed', (event, d) => applyPurchaseChanged(event, d)),
292
+ 'purchase.reinstated': handlerFor('purchase.reinstated', (event, d) => applyPurchaseChanged(event, d)),
293
+ });
294
+ /** An event of another kind than the one a default handler is for is refused, not misapplied. */
295
+ function handlerFor(kind, apply) {
296
+ return async (event, ctx) => event.kind === kind ? apply(event, depsOf(ctx)) : { status: 'ignored', reason: `no_handler:${event.kind}` };
297
+ }
298
+ const depsOf = (ctx) => ({ tx: ctx.store, ledger: ctx.ledger, delivery: ctx.delivery, now: ctx.now, newId: ctx.newId });
268
299
  /**
269
300
  * Counter the purchase's crediting entry by what the balance still holds;
270
301
  * the rest of the purchase's credits is the shortfall (design §4.11 — the
@@ -1,8 +1,8 @@
1
- import type { AccountId, BillingEvent, Money } from '../domain/types.js';
1
+ import type { AccountId, BillingEvent, LedgerEntry, Money } from '../domain/types.js';
2
2
  import type { Ledger } from '../ledger/ledger.js';
3
3
  import type { Clock, IdGenerator } from '../ports/runtime.js';
4
4
  import { type CheckoutRedirect, type InboundRequest, type IngestOutcome, type NormalizedEvent, type ProviderAdapter, type ProviderId, type ProviderResponse, type VerifiedDelivery } from '../providers/port.js';
5
- import { type EventHandler, type PurchaseReversed } from './apply.js';
5
+ import { type EventHandler, type HandlerCredited, type PurchaseReversed } from './apply.js';
6
6
  import { type CheckoutSession, type IngestReader, type IngestStore } from './ports.js';
7
7
  /** Structured events for the host's metrics, alerts and bus (design §13). */
8
8
  export type IngestEvent = {
@@ -46,6 +46,30 @@ export type UnmatchedHook = (input: {
46
46
  request: InboundRequest;
47
47
  delivery: VerifiedDelivery;
48
48
  }) => Promise<ProviderResponse | void>;
49
+ /** An account the ingest credited, handed to `afterCredited` once the credit has committed. */
50
+ export interface CreditedPurchase {
51
+ provider: ProviderId;
52
+ accountId: AccountId;
53
+ /** `completed`: the credit of a capture. `reinstated`: credit a provider reinstatement gave back or released (a capture parked under a reversal). */
54
+ kind: HandlerCredited['kind'];
55
+ /** The crediting ledger entry (`delta > 0`). */
56
+ entry: LedgerEntry;
57
+ /** The provider's purchase id, when the applier knows it. */
58
+ externalId: string | null;
59
+ /** The checkout session the credit settles, when there is one. */
60
+ sessionId: string | null;
61
+ }
62
+ /**
63
+ * Runs after the inbox transaction commits, at most once per credit, for the
64
+ * library's own appliers and for host handlers that return `credited`. Never
65
+ * for a duplicate, a replay of a settled row, an ignored delivery or an empty
66
+ * entry. A throw (or a rejection) goes to `onHookError` and changes nothing:
67
+ * the delivery stays `applied`. A process crash between the commit and the
68
+ * hook loses the call, so the host keeps a periodic backstop (Lohi: the
69
+ * renewal tick). The hook is awaited before the provider is answered, so keep
70
+ * it short: hand slow work to a queue.
71
+ */
72
+ export type AfterCreditedHook = (credited: CreditedPurchase) => void | Promise<void>;
49
73
  export interface IngestOptions<TTx> {
50
74
  adapters: readonly ProviderAdapter[];
51
75
  /** Must share its transactions with the ledger's store. */
@@ -56,8 +80,12 @@ export interface IngestOptions<TTx> {
56
80
  policy?: IngestPolicy;
57
81
  events?: IngestEventSink;
58
82
  onUnmatched?: UnmatchedHook;
59
- /** Appliers for event kinds the library does not apply itself (P1: `subscription.snapshot`). */
83
+ /** Appliers for event kinds the library does not apply itself (P1: `subscription.snapshot`). A host may also override `purchase.*` and delegate back through `defaultEventHandlers`. */
60
84
  handlers?: Partial<Record<NormalizedEvent['kind'], EventHandler<TTx>>>;
85
+ /** Called after commit when a delivery credited an account; see {@link AfterCreditedHook}. */
86
+ afterCredited?: AfterCreditedHook;
87
+ /** Receives what `afterCredited` threw. A throw or rejection here is swallowed too. */
88
+ onHookError?: (error: unknown, credited: CreditedPurchase) => void | Promise<void>;
61
89
  }
62
90
  export interface IngestResult extends IngestOutcome {
63
91
  response: ProviderResponse;
@@ -74,6 +102,8 @@ export interface CreateCheckoutInput {
74
102
  successUrl: string;
75
103
  errorUrl: string;
76
104
  cancelUrl: string;
105
+ /** The buyer's IP, forwarded to adapters that use it (Polar picks the tax country from it). Empty or blank means unknown. */
106
+ customerIpAddress?: string | null;
77
107
  /** Session lifetime. Default 30 min. A payment after it still credits. */
78
108
  ttlMs?: number;
79
109
  meta?: Record<string, unknown> | null;
@@ -102,10 +102,11 @@ export function createIngest(options) {
102
102
  });
103
103
  async function applyEvent(event, tx, delivery, now) {
104
104
  const ops = ledger.in(tx);
105
+ const bound = store.bind(tx);
105
106
  const handler = options.handlers?.[event.kind];
106
107
  if (handler)
107
- return handler(event, { tx, ledger: ops, delivery, now });
108
- const deps = { tx: store.bind(tx), ledger: ops, delivery, now, newId: ids };
108
+ return handler(event, { tx, ledger: ops, delivery, now, store: bound, newId: ids });
109
+ const deps = { tx: bound, ledger: ops, delivery, now, newId: ids };
109
110
  switch (event.kind) {
110
111
  case 'purchase.completed':
111
112
  return applyPurchaseCompleted(event, deps);
@@ -123,10 +124,12 @@ export function createIngest(options) {
123
124
  return { status: 'ignored', reason: `no_handler:${event.kind}` };
124
125
  }
125
126
  }
126
- /** Worst status wins: needs_review > applied > ignored. */
127
+ /** Worst status wins: needs_review > applied > ignored. Every credit is kept: it committed with its siblings. */
127
128
  function combine(results) {
129
+ // One credit is announced once, even if two events of a delivery report the same entry.
130
+ const credits = results.flatMap((r) => (r.credited ? [r.credited] : [])).filter((c, i, all) => all.findIndex((o) => o.entry?.id === c.entry?.id) === i);
128
131
  if (results.length === 0)
129
- return { status: 'ignored', reason: 'no_events' };
132
+ return { status: 'ignored', reason: 'no_events', credits };
130
133
  const pick = results.find((r) => r.status === 'needs_review') ?? results.find((r) => r.status === 'applied') ?? results[0];
131
134
  const reason = pick.reason ?? results.find((r) => r.reason)?.reason;
132
135
  const reversal = results.find((r) => r.reversal)?.reversal;
@@ -136,8 +139,40 @@ export function createIngest(options) {
136
139
  unmatched: results.every((r) => r.unmatched === true),
137
140
  events: results.flatMap((r) => r.events ?? []),
138
141
  ...(reversal ? { reversal } : {}),
142
+ credits,
139
143
  };
140
144
  }
145
+ const creditedPurchase = (provider, credited) => ({
146
+ provider,
147
+ accountId: credited.accountId,
148
+ kind: credited.kind,
149
+ entry: credited.entry,
150
+ externalId: credited.externalId ?? null,
151
+ sessionId: credited.sessionId ?? null,
152
+ });
153
+ /** After commit. A hook failure is the host's to hear about, never the delivery's. */
154
+ async function announce(provider, credits) {
155
+ const hook = options.afterCredited;
156
+ if (!hook)
157
+ return;
158
+ for (const reported of credits) {
159
+ // A malformed `credited` from a host handler (no entry …) is the hook's problem, not the delivery's.
160
+ if (!(reported?.entry?.delta > 0))
161
+ continue;
162
+ const credited = creditedPurchase(provider, reported);
163
+ try {
164
+ await hook(credited);
165
+ }
166
+ catch (error) {
167
+ try {
168
+ await options.onHookError?.(error, credited);
169
+ }
170
+ catch {
171
+ // A broken error sink must not turn a committed credit into a retry.
172
+ }
173
+ }
174
+ }
175
+ }
141
176
  /**
142
177
  * Normalize and apply one stored row. `manual` (replay) re-opens a final
143
178
  * `needs_review`/`dead` row with a fresh retry budget.
@@ -155,7 +190,7 @@ export function createIngest(options) {
155
190
  return null;
156
191
  const reopen = manual && (locked.status === 'needs_review' || locked.status === 'dead');
157
192
  if (FINAL_INBOX_STATUSES.has(locked.status) && !reopen)
158
- return { status: 'ignored', skipped: locked };
193
+ return { status: 'ignored', skipped: locked, credits: [] };
159
194
  const applied = combine(await sequential(events, (event) => applyEvent(event, tx, delivery, now)));
160
195
  await itx.updateInbox(locked.id, {
161
196
  status: applied.status,
@@ -180,6 +215,7 @@ export function createIngest(options) {
180
215
  after.push({ type: 'billing.alert', alert: 'inbox_needs_review', provider: row.provider, eventId: row.eventId, reason: result.reason ?? null });
181
216
  }
182
217
  await emit(after);
218
+ await announce(row.provider, result.credits);
183
219
  return {
184
220
  status: result.status,
185
221
  eventId: row.eventId,
@@ -377,6 +413,7 @@ export function createIngest(options) {
377
413
  errorUrl: input.errorUrl,
378
414
  cancelUrl: input.cancelUrl,
379
415
  productRef: session.productRef,
416
+ ...(input.customerIpAddress?.trim() ? { customerIpAddress: input.customerIpAddress.trim() } : {}),
380
417
  });
381
418
  await store.transaction((tx) => store.bind(tx).insertSession(session));
382
419
  return { session, redirect };
package/dist/index.d.ts CHANGED
@@ -12,8 +12,8 @@ export type { BillingEventSink, Clock, EntryListOptions, IdGenerator, LedgerRead
12
12
  export { createMemoryLedgerStore, type MemoryLedgerStore, type MemoryTx } from './stores/memory.js';
13
13
  export { createWaterfall, creditsStep, freeStep, quotaStep, type QuotaPool, type SettleContext, type SettleOptions, type Settled, type StepContext, type StepPlan, type Waterfall, type WaterfallConfig, type WaterfallStep, } from './quote/index.js';
14
14
  export * from './providers/port.js';
15
- export { createIngest, type CreateCheckoutInput, type Ingest, type IngestEvent, type IngestEventSink, type IngestOptions, type IngestPolicy, type IngestResult, type SweepResult, type UnmatchedHook, } from './inbox/ingest.js';
16
- export type { ApplyContext, ApplyResult, ApplyStatus, EventHandler, PurchaseReversed } from './inbox/apply.js';
15
+ export { createIngest, type AfterCreditedHook, type CreateCheckoutInput, type CreditedPurchase, type Ingest, type IngestEvent, type IngestEventSink, type IngestOptions, type IngestPolicy, type IngestResult, type SweepResult, type UnmatchedHook, } from './inbox/ingest.js';
16
+ export { defaultEventHandlers, type ApplyContext, type ApplyResult, type ApplyStatus, type EventHandler, type HandlerCredited, type HandlerResult, type PurchaseReversed, } from './inbox/apply.js';
17
17
  export { FINAL_INBOX_STATUSES, type CheckoutSession, type CheckoutSessionPatch, type CheckoutSessionStatus, type InboxListOptions, type InboxPatch, type InboxRow, type InboxStatus, type IngestReader, type IngestStore, type IngestTx, type Purchase, type PurchasePatch, type PurchaseStatus, } from './inbox/ports.js';
18
18
  export { createMemoryIngestStore, type MemoryIngestStore } from './inbox/memory.js';
19
19
  export { isSensitiveKey, redactPayload } from './inbox/redact.js';
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ export { createMemoryLedgerStore } from './stores/memory.js';
12
12
  export { createWaterfall, creditsStep, freeStep, quotaStep, } from './quote/index.js';
13
13
  export * from './providers/port.js';
14
14
  export { createIngest, } from './inbox/ingest.js';
15
+ export { defaultEventHandlers, } from './inbox/apply.js';
15
16
  export { FINAL_INBOX_STATUSES, } from './inbox/ports.js';
16
17
  export { createMemoryIngestStore } from './inbox/memory.js';
17
18
  export { isSensitiveKey, redactPayload } from './inbox/redact.js';
@@ -29,7 +29,7 @@ export interface PolarAdapterOptions {
29
29
  /** API timeout. Default 10 s. */
30
30
  timeoutMs?: number;
31
31
  }
32
- /** A checkout request; Polar uses the buyer's IP for tax country when the host has it. */
32
+ /** A checkout request; Polar uses the buyer's IP (`customerIpAddress`) for the tax country when the host has it. */
33
33
  export interface PolarCheckoutRequest extends CheckoutRequest {
34
34
  customerIpAddress?: string | null;
35
35
  }
@@ -151,6 +151,8 @@ export interface CheckoutRequest {
151
151
  errorUrl: string;
152
152
  cancelUrl: string;
153
153
  productRef?: string | null;
154
+ /** The buyer's IP when the host has it; adapters that cannot use it ignore it (Polar: tax country). */
155
+ customerIpAddress?: string | null;
154
156
  }
155
157
  export type CheckoutRedirect = {
156
158
  kind: 'redirect';
package/docs/API.md CHANGED
@@ -1,14 +1,15 @@
1
- # @tofound/billing — API (1.0)
1
+ # @tofound/billing — API (1.1)
2
2
 
3
3
  Part of the `billing.public-api` contract with `src/index.ts` and
4
- `src/domain/types.ts`. 0.x minors were additive. From 1.0.0 the API is
4
+ `src/domain/types.ts`. 0.x minors were additive; 1.1.0 is additive to 1.0.0. From 1.0.0 the API is
5
5
  frozen: the declaration snapshot in `test/contract/public-api.test.ts` fails
6
6
  on any change to these exports, and removing or narrowing one is a major
7
- version.
7
+ version. For task-oriented walkthroughs (packs, plans, failed renewals,
8
+ refunds, arming a provider) see [GUIDE.md](GUIDE.md).
8
9
 
9
10
  | Entry | Contents |
10
11
  |---|---|
11
- | `@tofound/billing` | domain types, money helpers, `BillingError`, `createLedger`, ports, `createMemoryLedgerStore`, waterfall + steps, provider port, `createIngest`, `createMemoryIngestStore`, `defineCatalog`, terms, `resolveEntitlement`, `createPlans`, `createRenewal`, `createSnapshotHandler`, `createMemoryTermStore` |
12
+ | `@tofound/billing` | domain types, money helpers, `BillingError`, `createLedger`, ports, `createMemoryLedgerStore`, waterfall + steps, provider port, `createIngest`, `defaultEventHandlers`, `createMemoryIngestStore`, `defineCatalog`, terms, `resolveEntitlement`, `createPlans`, `createRenewal`, `createSnapshotHandler`, `createMemoryTermStore` |
12
13
  | `@tofound/billing/drizzle` | `createBillingTables`, `billingTableBuilder`, `checkAdditiveDdl`, `createDrizzleLedgerStore`, `createIngestTables`, `createDrizzleIngestStore`, `createTermTables`, `createDrizzleTermStore`, `termTableNames` (peer `drizzle-orm ^0.45`) |
13
14
  | `@tofound/billing/providers/sepay` | `createSepayAdapter`, `respondSepay`, `signCheckoutFields`, `parseSepayOrder` |
14
15
  | `@tofound/billing/providers/polar` | `createPolarAdapter`, `resolvePolarEnvironment`, `respondPolar`, `redactPolarPayload`, `signPolarWebhook`, `PolarApiError`, `POLAR_WEBHOOK_*` header names and tolerance; types `PolarAdapter`, `PolarAdapterOptions`, `PolarCheckoutRequest`, `PolarKeyDerivation` |
@@ -161,9 +162,9 @@ await w.settle(tx, lockedState, { accountId, idempotencyKey }) // same steps, co
161
162
 
162
163
  ```ts
163
164
  const sepay = createSepayAdapter({ environment: 'production', webhookKeys: [current, next?], merchantId, secretKey })
164
- const ingest = createIngest({ adapters: [sepay], store, ledger, events?, policy?, onUnmatched? })
165
+ const ingest = createIngest({ adapters: [sepay], store, ledger, events?, policy?, onUnmatched?, handlers?, afterCredited?, onHookError? })
165
166
 
166
- const { session, redirect } = await ingest.createCheckout({ provider: 'sepay', accountId, amount, credits, productRef, description, successUrl, errorUrl, cancelUrl })
167
+ const { session, redirect } = await ingest.createCheckout({ provider: 'sepay', accountId, amount, credits, productRef, description, successUrl, errorUrl, cancelUrl, customerIpAddress? })
167
168
  const r = await ingest.handle('sepay', { headers, rawBody, url, receivedAt }) // → reply with r.response
168
169
  await ingest.confirm('sepay', { invoice: session.id }) // poll; same event id as the IPN
169
170
  await ingest.closeCheckout(session.id, 'expired') // a later capture still credits
@@ -191,6 +192,32 @@ await ingest.sweep()
191
192
  - `confirm` credits the session's own account, whoever asks; a host route
192
193
  that forwards a client's invoice still checks the caller owns that session
193
194
  before it spends a provider API call on it.
195
+ - **`afterCredited(c: CreditedPurchase)`** (1.1) runs after the delivery's
196
+ transaction commits, at most once per credit: `{ provider, accountId, kind:
197
+ 'completed' | 'reinstated', entry, externalId, sessionId }`. It fires for the
198
+ library's own appliers and for a host handler whose `ApplyResult`
199
+ (`HandlerResult`) carries `credited: { accountId, entry, kind, externalId?,
200
+ sessionId? }`. It never fires for `duplicate`, `ignored`, a replay of a
201
+ settled row, a reversal, a rolled-back attempt or an entry with `delta ≤ 0`,
202
+ and it fires whatever the delivery's status when a credit committed (a
203
+ sibling event that needs review does not unsend it). A throw or rejection
204
+ goes to `onHookError(error, c)` (itself guarded) and never changes the
205
+ outcome; a crash between commit and hook loses the call, so keep a periodic
206
+ backstop.
207
+ - `afterCredited` announces **purchase credits** (capture, reinstatement) and
208
+ what a host handler reports in `credited`. Other credits the ingest posts,
209
+ such as the `plan_refund` of a superseded term from `createSnapshotHandler`,
210
+ are not announced. The hook is awaited before the provider is answered: keep
211
+ it short and hand slow work to a queue.
212
+ - **`defaultEventHandlers`** (1.1) are the library's `purchase.completed` /
213
+ `purchase.reversed` / `purchase.reinstated` appliers as `EventHandler`s, so a
214
+ host that overrides one kind for a provider can hand the others back per
215
+ delivery. They apply through `ctx.store` (the ingest store bound to the
216
+ handler's transaction; with `ctx.newId`, new on `ApplyContext` in 1.1) and
217
+ return `credited`. A handler given an event of another kind answers
218
+ `ignored` (`no_handler:<kind>`).
219
+ - **`createCheckout({ customerIpAddress })`** (1.1) is forwarded to the adapter's
220
+ `CheckoutRequest` when non-empty; an adapter that cannot use it ignores it.
194
221
  - `sweep` lists only rows of the providers this ingest has adapters for, and
195
222
  a row it cannot even record stays due without stopping the rows behind it.
196
223
  - `onUnmatched` receives deliveries no session matches (e.g. another product's
@@ -268,9 +295,9 @@ const { url } = await polar.createPortalSession({ kind: 'account_id', value: acc
268
295
  The Polar checkout already exists by then; it is never handed to the buyer.
269
296
  The session id comes from the ingest's `ids` (default `randomUUID`), so a custom
270
297
  generator must match `checkoutPattern`, or every checkout throws
271
- `polar_invalid_checkout_id`. `PolarCheckoutRequest.customerIpAddress` (sent for tax
272
- country) is only accepted by a direct `polar.createCheckout` call;
273
- `ingest.createCheckout` does not forward it.
298
+ `polar_invalid_checkout_id`. `customerIpAddress` (sent for the tax country) is forwarded by
299
+ `ingest.createCheckout` since 1.1 and accepted by a direct
300
+ `polar.createCheckout` call.
274
301
  `order.paid` for a one-time order becomes `purchase.completed`, bound to the
275
302
  session by `metadata.checkout_id` and credited once (`topup:<sessionId>`).
276
303
  Its amount is the catalog price, `subtotal_amount − discount_amount`, which
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tofound/billing",
3
- "version": "1.0.0",
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",
@@ -52,6 +52,7 @@
52
52
  "files": [
53
53
  "dist",
54
54
  "docs/API.md",
55
+ "docs/GUIDE.md",
55
56
  "docs/MIGRATION-LOHI.md",
56
57
  "docs/SCHEMA.md",
57
58
  "README.md",