@tofound/billing 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +76 -0
- package/README.md +58 -13
- package/dist/catalog/catalog.d.ts +115 -0
- package/dist/catalog/catalog.js +201 -0
- package/dist/domain/types.d.ts +3 -1
- package/dist/drizzle/index.d.ts +2 -0
- package/dist/drizzle/index.js +2 -0
- package/dist/entitlement/resolve.d.ts +76 -0
- package/dist/entitlement/resolve.js +122 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +9 -0
- package/dist/providers/polar/events.d.ts +17 -0
- package/dist/providers/polar/events.js +213 -0
- package/dist/providers/polar/index.d.ts +50 -0
- package/dist/providers/polar/index.js +271 -0
- package/dist/providers/polar/signature.d.ts +23 -0
- package/dist/providers/polar/signature.js +52 -0
- package/dist/providers/port.d.ts +6 -0
- package/dist/renewal/renewal.d.ts +69 -0
- package/dist/renewal/renewal.js +198 -0
- package/dist/stores/testing.d.ts +4 -2
- package/dist/stores/testing.js +4 -2
- package/dist/terms/conformance.d.ts +17 -0
- package/dist/terms/conformance.js +198 -0
- package/dist/terms/decide.d.ts +97 -0
- package/dist/terms/decide.js +176 -0
- package/dist/terms/drizzle.d.ts +12 -0
- package/dist/terms/drizzle.js +131 -0
- package/dist/terms/memory.d.ts +23 -0
- package/dist/terms/memory.js +126 -0
- package/dist/terms/plans.d.ts +85 -0
- package/dist/terms/plans.js +331 -0
- package/dist/terms/ports.d.ts +55 -0
- package/dist/terms/ports.js +1 -0
- package/dist/terms/rules.d.ts +11 -0
- package/dist/terms/rules.js +36 -0
- package/dist/terms/schema.d.ts +711 -0
- package/dist/terms/schema.js +70 -0
- package/dist/terms/snapshot.d.ts +20 -0
- package/dist/terms/snapshot.js +134 -0
- package/dist/terms/types.d.ts +85 -0
- package/dist/terms/types.js +4 -0
- package/docs/API.md +223 -4
- package/docs/SCHEMA.md +57 -2
- package/package.json +6 -1
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `billing_terms` table: every subscription term of every source, and
|
|
3
|
+
* `billing_term_accounts`, one guard row per account that `lockAccountTerms`
|
|
4
|
+
* locks first, so writers of an account with no terms yet still serialize. Declared
|
|
5
|
+
* through `billingTableBuilder`, so it takes the host's schema and prefix like
|
|
6
|
+
* the ledger tables and follows the same additive rules (docs/SCHEMA.md,
|
|
7
|
+
* `checkAdditiveDdl`): a new table and its indexes only.
|
|
8
|
+
*/
|
|
9
|
+
import { sql } from 'drizzle-orm';
|
|
10
|
+
import { bigint, boolean, check, index, integer, jsonb, primaryKey, text, timestamp, uniqueIndex, varchar } from 'drizzle-orm/pg-core';
|
|
11
|
+
import { billingTableBuilder, DEFAULT_PREFIX } from '../drizzle/schema-factory.js';
|
|
12
|
+
export function createTermTables(config) {
|
|
13
|
+
const b = billingTableBuilder(config);
|
|
14
|
+
const tz = (name) => timestamp(name, { withTimezone: true });
|
|
15
|
+
const billingTerms = b.table(b.name('terms'), {
|
|
16
|
+
id: varchar('id', { length: 64 }).primaryKey(),
|
|
17
|
+
accountId: config.accountId('account_id'),
|
|
18
|
+
source: varchar('source', { length: 16 }).notNull(),
|
|
19
|
+
environment: varchar('environment', { length: 16 }),
|
|
20
|
+
externalId: text('external_id'),
|
|
21
|
+
planKey: varchar('plan_key', { length: 64 }).notNull(),
|
|
22
|
+
status: varchar('status', { length: 16 }).notNull(),
|
|
23
|
+
market: varchar('market', { length: 64 }),
|
|
24
|
+
startsAt: tz('starts_at').notNull(),
|
|
25
|
+
currentPeriodStart: tz('current_period_start').notNull(),
|
|
26
|
+
currentPeriodEnd: tz('current_period_end').notNull(),
|
|
27
|
+
intervalMonths: integer('interval_months').notNull(),
|
|
28
|
+
autoRenew: boolean('auto_renew').notNull().default(false),
|
|
29
|
+
cancelAtPeriodEnd: boolean('cancel_at_period_end').notNull().default(false),
|
|
30
|
+
graceUntil: tz('grace_until'),
|
|
31
|
+
nextPlanKey: varchar('next_plan_key', { length: 64 }),
|
|
32
|
+
priceMinor: bigint('price_minor', { mode: 'number' }),
|
|
33
|
+
priceUnit: varchar('price_unit', { length: 16 }),
|
|
34
|
+
periodItems: jsonb('period_items').$type(),
|
|
35
|
+
supersededBy: varchar('superseded_by', { length: 64 }),
|
|
36
|
+
lastEventAt: tz('last_event_at'),
|
|
37
|
+
lastEventRef: text('last_event_ref'),
|
|
38
|
+
meta: jsonb('meta').$type(),
|
|
39
|
+
createdAt: tz('created_at').notNull().defaultNow(),
|
|
40
|
+
updatedAt: tz('updated_at').notNull().defaultNow(),
|
|
41
|
+
}, (t) => [
|
|
42
|
+
// NULLs are distinct: credit terms (no external id) never collide here.
|
|
43
|
+
uniqueIndex(b.name('terms_external_uq')).on(t.source, t.environment, t.externalId),
|
|
44
|
+
// One open credit term per account, and one scheduled term.
|
|
45
|
+
uniqueIndex(b.name('terms_open_credit_uq'))
|
|
46
|
+
.on(t.accountId)
|
|
47
|
+
.where(sql `${t.source} = 'credit' and ${t.status} in ('active', 'grace', 'past_due')`),
|
|
48
|
+
uniqueIndex(b.name('terms_scheduled_uq')).on(t.accountId).where(sql `${t.status} = 'scheduled'`),
|
|
49
|
+
// `lockAccountTerms` and `listTerms`.
|
|
50
|
+
index(b.name('terms_account_status_idx')).on(t.accountId, t.status),
|
|
51
|
+
// `listDue`: each branch of the predicate has its own partial index, so a run costs the due rows.
|
|
52
|
+
index(b.name('terms_due_active_idx'))
|
|
53
|
+
.on(t.currentPeriodEnd)
|
|
54
|
+
.where(sql `${t.source} = 'credit' and ${t.status} = 'active'`),
|
|
55
|
+
index(b.name('terms_due_scheduled_idx')).on(t.startsAt).where(sql `${t.status} = 'scheduled'`),
|
|
56
|
+
index(b.name('terms_due_past_due_idx'))
|
|
57
|
+
.on(t.graceUntil)
|
|
58
|
+
.where(sql `${t.source} = 'credit' and ${t.status} = 'past_due'`),
|
|
59
|
+
check(b.name('terms_interval_pos'), sql `${t.intervalMonths} > 0`),
|
|
60
|
+
]);
|
|
61
|
+
const billingTermAccounts = b.table(b.name('term_accounts'), {
|
|
62
|
+
accountId: config.accountId('account_id'),
|
|
63
|
+
createdAt: tz('created_at').notNull().defaultNow(),
|
|
64
|
+
}, (t) => [primaryKey({ name: b.name('term_accounts_pk'), columns: [t.accountId] })]);
|
|
65
|
+
return { billingTerms, billingTermAccounts };
|
|
66
|
+
}
|
|
67
|
+
/** Unqualified table names for `checkAdditiveDdl({libraryTables})`. */
|
|
68
|
+
export function termTableNames(prefix = DEFAULT_PREFIX) {
|
|
69
|
+
return [`${prefix}terms`, `${prefix}term_accounts`];
|
|
70
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Catalog } from '../catalog/catalog.js';
|
|
2
|
+
import type { AccountId } from '../domain/types.js';
|
|
3
|
+
import type { ApplyContext, EventHandler } from '../inbox/apply.js';
|
|
4
|
+
import type { IdGenerator } from '../ports/runtime.js';
|
|
5
|
+
import type { AccountRef } from '../providers/port.js';
|
|
6
|
+
import type { TermStore } from './ports.js';
|
|
7
|
+
export interface SnapshotHandlerOptions<TTx> {
|
|
8
|
+
terms: TermStore<TTx>;
|
|
9
|
+
catalog: Catalog;
|
|
10
|
+
/**
|
|
11
|
+
* Map the event's server-issued reference to the host's account (Polar
|
|
12
|
+
* `external_customer_id`, Apple `appAccountToken` …). Default: only
|
|
13
|
+
* `account_id` references resolve. `null` → `ignored` as `no_match`,
|
|
14
|
+
* unmatched: relayed through the ingest `onUnmatched` hook (another host's
|
|
15
|
+
* subscription on a shared provider account).
|
|
16
|
+
*/
|
|
17
|
+
resolveAccount?: (ref: AccountRef, ctx: ApplyContext<TTx>) => AccountId | null | Promise<AccountId | null>;
|
|
18
|
+
ids?: IdGenerator;
|
|
19
|
+
}
|
|
20
|
+
export declare function createSnapshotHandler<TTx>(options: SnapshotHandlerOptions<TTx>): EventHandler<TTx>;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider terms from `subscription.snapshot` events (design §4.6, S4). The
|
|
3
|
+
* handler plugs into the ingest service's handler slot, so a snapshot is
|
|
4
|
+
* applied in the inbox transaction:
|
|
5
|
+
*
|
|
6
|
+
* createIngest({ …, handlers: { 'subscription.snapshot': createSnapshotHandler({ terms, catalog, resolveAccount }) } })
|
|
7
|
+
*
|
|
8
|
+
* A snapshot only changes its term when it is newer than the term's
|
|
9
|
+
* watermark, so redelivered or out-of-order events cannot regress it. When the
|
|
10
|
+
* provider term entitles at ≥ the rank of the account's open credit term,
|
|
11
|
+
* that credit term is `superseded` and its unused share is refunded in
|
|
12
|
+
* credits (`plan_refund`, key `supersede:<termId>`).
|
|
13
|
+
*/
|
|
14
|
+
import { randomUUID } from 'node:crypto';
|
|
15
|
+
import { entitledUntil } from '../entitlement/resolve.js';
|
|
16
|
+
import { isNewer } from '../inbox/watermark.js';
|
|
17
|
+
import { supersedeRefund } from './decide.js';
|
|
18
|
+
import { renews } from './rules.js';
|
|
19
|
+
const SOURCES = new Set(['polar', 'apple', 'google']);
|
|
20
|
+
export function createSnapshotHandler(options) {
|
|
21
|
+
const { catalog } = options;
|
|
22
|
+
const ids = options.ids ?? randomUUID;
|
|
23
|
+
const resolveAccount = options.resolveAccount ?? ((ref) => (ref.kind === 'account_id' ? ref.value : null));
|
|
24
|
+
return async (event, ctx) => {
|
|
25
|
+
if (event.kind !== 'subscription.snapshot')
|
|
26
|
+
return { status: 'ignored', reason: `not_a_snapshot:${event.kind}` };
|
|
27
|
+
const { delivery } = ctx;
|
|
28
|
+
if (!SOURCES.has(delivery.provider))
|
|
29
|
+
return { status: 'needs_review', reason: 'unsupported_provider' };
|
|
30
|
+
const source = delivery.provider;
|
|
31
|
+
// Another host's subscription (its products may be unknown here) is relayed before the plan is checked.
|
|
32
|
+
const accountId = await resolveAccount(event.account, ctx);
|
|
33
|
+
if (!accountId)
|
|
34
|
+
return { status: 'ignored', reason: 'no_match', unmatched: true };
|
|
35
|
+
const match = catalog.offerByProductRef(event.planRef);
|
|
36
|
+
if (match?.kind !== 'plan')
|
|
37
|
+
return { status: 'needs_review', reason: 'unknown_plan_ref' };
|
|
38
|
+
if (match.offer.source !== source)
|
|
39
|
+
return { status: 'needs_review', reason: 'plan_ref_provider_mismatch' };
|
|
40
|
+
const t = options.terms.bind(ctx.tx);
|
|
41
|
+
// Never lock another account's row: a subscription's account does not change, so an unlocked read settles it.
|
|
42
|
+
const known = await t.findExternal(source, delivery.environment, event.externalId);
|
|
43
|
+
if (known && known.accountId !== accountId)
|
|
44
|
+
return { status: 'needs_review', reason: 'account_mismatch' };
|
|
45
|
+
// Lock order: the account's open terms (oldest first, as purchases do), then this one.
|
|
46
|
+
const open = await t.lockAccountTerms(accountId);
|
|
47
|
+
const existing = open.find((x) => x.source === source && x.environment === delivery.environment && x.externalId === event.externalId) ??
|
|
48
|
+
(await t.lockExternal(source, delivery.environment, event.externalId));
|
|
49
|
+
if (existing && existing.accountId !== accountId)
|
|
50
|
+
return { status: 'needs_review', reason: 'account_mismatch' };
|
|
51
|
+
// The tie-break leads the ref, so it orders same-instant snapshots before the event id does.
|
|
52
|
+
const mark = { at: event.occurredAt, ref: event.tieBreak ? `${event.tieBreak}:${delivery.eventId}` : delivery.eventId };
|
|
53
|
+
const watermark = existing?.lastEventAt ? { at: existing.lastEventAt, ref: existing.lastEventRef ?? '' } : null;
|
|
54
|
+
if (!isNewer(watermark, mark))
|
|
55
|
+
return { status: 'ignored', reason: 'stale' };
|
|
56
|
+
const nextPlan = event.nextPlanRef ? catalog.offerByProductRef(event.nextPlanRef) : undefined;
|
|
57
|
+
const patch = {
|
|
58
|
+
planKey: match.plan.key,
|
|
59
|
+
status: event.status,
|
|
60
|
+
currentPeriodStart: event.periodStart,
|
|
61
|
+
currentPeriodEnd: event.periodEnd,
|
|
62
|
+
intervalMonths: intervalOf(event, match.offer.interval, catalog.policies.termDays),
|
|
63
|
+
autoRenew: event.autoRenew,
|
|
64
|
+
cancelAtPeriodEnd: event.cancelAtPeriodEnd,
|
|
65
|
+
graceUntil: event.graceUntil ?? null,
|
|
66
|
+
nextPlanKey: nextPlan?.kind === 'plan' ? nextPlan.plan.key : null,
|
|
67
|
+
priceMinor: event.price?.amountMinor ?? existing?.priceMinor ?? null,
|
|
68
|
+
priceUnit: event.price?.currency ?? existing?.priceUnit ?? null,
|
|
69
|
+
lastEventAt: mark.at,
|
|
70
|
+
lastEventRef: mark.ref,
|
|
71
|
+
};
|
|
72
|
+
let term;
|
|
73
|
+
if (existing) {
|
|
74
|
+
await t.updateTerm(existing.id, patch);
|
|
75
|
+
term = { ...existing, ...patch };
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
term = {
|
|
79
|
+
id: ids(),
|
|
80
|
+
accountId,
|
|
81
|
+
source,
|
|
82
|
+
environment: delivery.environment,
|
|
83
|
+
externalId: event.externalId,
|
|
84
|
+
market: match.offer.market ?? null,
|
|
85
|
+
startsAt: event.periodStart,
|
|
86
|
+
periodItems: null,
|
|
87
|
+
supersededBy: null,
|
|
88
|
+
meta: null,
|
|
89
|
+
createdAt: ctx.now,
|
|
90
|
+
updatedAt: ctx.now,
|
|
91
|
+
...patch,
|
|
92
|
+
};
|
|
93
|
+
// A concurrent first snapshot of the same subscription: transient, the inbox retries.
|
|
94
|
+
if (!(await t.insertTerm(term)).inserted)
|
|
95
|
+
throw new Error(`term ${source}:${event.externalId} was created concurrently`);
|
|
96
|
+
}
|
|
97
|
+
if (!entitledUntil(term, ctx.now, catalog.policies.graceDays))
|
|
98
|
+
return { status: 'applied' };
|
|
99
|
+
// S4: an entitling subscription of ≥ rank replaces the account's credit terms.
|
|
100
|
+
const rank = match.plan.rank;
|
|
101
|
+
const result = { status: 'applied', events: [] };
|
|
102
|
+
for (const credit of open.filter((x) => x.source === 'credit')) {
|
|
103
|
+
const creditRank = catalog.findPlan(credit.planKey)?.rank ?? -1;
|
|
104
|
+
if (creditRank > rank)
|
|
105
|
+
continue;
|
|
106
|
+
if (credit.status === 'scheduled' && !renews(term))
|
|
107
|
+
continue;
|
|
108
|
+
const refund = supersedeRefund(credit, ctx.now);
|
|
109
|
+
await t.updateTerm(credit.id, { status: 'superseded', supersededBy: term.id, autoRenew: false });
|
|
110
|
+
if (refund > 0) {
|
|
111
|
+
const posted = await ctx.ledger.credit({
|
|
112
|
+
accountId,
|
|
113
|
+
kind: 'plan_refund',
|
|
114
|
+
amount: refund,
|
|
115
|
+
idempotencyKey: `supersede:${credit.id}`,
|
|
116
|
+
source: { type: 'term', id: credit.id },
|
|
117
|
+
meta: { supersededBy: term.id, provider: source },
|
|
118
|
+
});
|
|
119
|
+
result.events.push(...posted.events);
|
|
120
|
+
}
|
|
121
|
+
result.reason = 'superseded_credit_term';
|
|
122
|
+
}
|
|
123
|
+
return result;
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
/** Renewal interval in catalog months: the offer's interval, else the period's length. */
|
|
127
|
+
function intervalOf(event, interval, termDays) {
|
|
128
|
+
if (interval === 'year')
|
|
129
|
+
return 12;
|
|
130
|
+
if (interval === 'month')
|
|
131
|
+
return 1;
|
|
132
|
+
const days = (event.periodEnd.getTime() - event.periodStart.getTime()) / 86_400_000;
|
|
133
|
+
return Math.max(1, Math.round(days / termDays));
|
|
134
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subscription terms (design §4.6): one shape for the four sources. Credit
|
|
3
|
+
* terms are written only by the plans and renewal services; provider terms
|
|
4
|
+
* only from `subscription.snapshot` events, under a watermark.
|
|
5
|
+
*/
|
|
6
|
+
import type { AccountId } from '../domain/types.js';
|
|
7
|
+
import type { ProviderEnvironment } from '../providers/port.js';
|
|
8
|
+
export type TermSource = 'credit' | 'polar' | 'apple' | 'google';
|
|
9
|
+
/**
|
|
10
|
+
* - `scheduled`: a credit term that starts at `startsAt` (S3b), charged then.
|
|
11
|
+
* - `active`: entitled until the period end.
|
|
12
|
+
* - `grace` (provider): entitled until `graceUntil`.
|
|
13
|
+
* - `past_due`: renewal unpaid; entitled only while `graceUntil` is ahead.
|
|
14
|
+
* - `expired` / `superseded` / `revoked`: final.
|
|
15
|
+
*/
|
|
16
|
+
export type TermStatus = 'scheduled' | 'active' | 'grace' | 'past_due' | 'expired' | 'superseded' | 'revoked';
|
|
17
|
+
export declare const TERM_STATUSES: readonly TermStatus[];
|
|
18
|
+
/** Statuses of a term still in play (at most one per account for credit terms, plus one scheduled). */
|
|
19
|
+
export declare const OPEN_TERM_STATUSES: readonly TermStatus[];
|
|
20
|
+
export declare const FINAL_TERM_STATUSES: readonly TermStatus[];
|
|
21
|
+
/** One purchase making up the current period of a credit term (an S2 extension adds one). */
|
|
22
|
+
export interface PeriodItem {
|
|
23
|
+
months: number;
|
|
24
|
+
/** Credit minor units this item is worth at the term's plan. */
|
|
25
|
+
credits: number;
|
|
26
|
+
}
|
|
27
|
+
export interface Term {
|
|
28
|
+
id: string;
|
|
29
|
+
accountId: AccountId;
|
|
30
|
+
source: TermSource;
|
|
31
|
+
/** Provider rail; `null` for credit terms. */
|
|
32
|
+
environment: ProviderEnvironment | null;
|
|
33
|
+
/** Provider subscription id / originalTransactionId / purchaseToken; `null` for credit terms. */
|
|
34
|
+
externalId: string | null;
|
|
35
|
+
planKey: string;
|
|
36
|
+
status: TermStatus;
|
|
37
|
+
/** Market the term was bought in (credit terms); the host may re-price renewals by its own. */
|
|
38
|
+
market: string | null;
|
|
39
|
+
startsAt: Date;
|
|
40
|
+
currentPeriodStart: Date;
|
|
41
|
+
currentPeriodEnd: Date;
|
|
42
|
+
/** Renewal interval in catalog months. */
|
|
43
|
+
intervalMonths: number;
|
|
44
|
+
autoRenew: boolean;
|
|
45
|
+
cancelAtPeriodEnd: boolean;
|
|
46
|
+
graceUntil: Date | null;
|
|
47
|
+
/** Plan a renewal switches to (a downgrade under auto-renew, S3b). */
|
|
48
|
+
nextPlanKey: string | null;
|
|
49
|
+
/**
|
|
50
|
+
* What the current period is worth: credit minor units for a credit term
|
|
51
|
+
* (sum of `periodItems`), the provider's price otherwise.
|
|
52
|
+
*/
|
|
53
|
+
priceMinor: number | null;
|
|
54
|
+
/** The credit unit code, or the provider's currency. */
|
|
55
|
+
priceUnit: string | null;
|
|
56
|
+
/** Credit terms: the purchases making up the current period. */
|
|
57
|
+
periodItems: PeriodItem[] | null;
|
|
58
|
+
supersededBy: string | null;
|
|
59
|
+
/** Provider watermark: only a newer snapshot changes the term. */
|
|
60
|
+
lastEventAt: Date | null;
|
|
61
|
+
lastEventRef: string | null;
|
|
62
|
+
meta: Record<string, unknown> | null;
|
|
63
|
+
createdAt: Date;
|
|
64
|
+
updatedAt: Date;
|
|
65
|
+
}
|
|
66
|
+
export type TermPatch = Partial<Pick<Term, 'planKey' | 'status' | 'market' | 'startsAt' | 'currentPeriodStart' | 'currentPeriodEnd' | 'intervalMonths' | 'autoRenew' | 'cancelAtPeriodEnd' | 'graceUntil' | 'nextPlanKey' | 'priceMinor' | 'priceUnit' | 'periodItems' | 'supersededBy' | 'lastEventAt' | 'lastEventRef' | 'meta'>>;
|
|
67
|
+
export type TermChange = 'created' | 'extended' | 'upgraded' | 'scheduled' | 'activated' | 'renewed' | 'past_due' | 'expired' | 'superseded' | 'auto_renew' | 'cancelled';
|
|
68
|
+
/** Domain events of terms (design §13); the host maps them onto its bus. */
|
|
69
|
+
export type TermEvent = {
|
|
70
|
+
type: 'term_changed';
|
|
71
|
+
accountId: AccountId;
|
|
72
|
+
change: TermChange;
|
|
73
|
+
term: Term;
|
|
74
|
+
} | {
|
|
75
|
+
type: 'renewal_failed';
|
|
76
|
+
accountId: AccountId;
|
|
77
|
+
term: Term;
|
|
78
|
+
/** `insufficient_credits` or `offer_not_found` (the plan is no longer sold for credits). */
|
|
79
|
+
reason: string;
|
|
80
|
+
required: number | null;
|
|
81
|
+
balance: number;
|
|
82
|
+
shortfall: number | null;
|
|
83
|
+
};
|
|
84
|
+
/** Receives term events after the service's own transaction commits; errors go to `onEventError`. */
|
|
85
|
+
export type TermEventSink = (event: TermEvent) => void | Promise<void>;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export const TERM_STATUSES = ['scheduled', 'active', 'grace', 'past_due', 'expired', 'superseded', 'revoked'];
|
|
2
|
+
/** Statuses of a term still in play (at most one per account for credit terms, plus one scheduled). */
|
|
3
|
+
export const OPEN_TERM_STATUSES = ['active', 'grace', 'past_due'];
|
|
4
|
+
export const FINAL_TERM_STATUSES = ['expired', 'superseded', 'revoked'];
|
package/docs/API.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# @tofound/billing — API (0.
|
|
1
|
+
# @tofound/billing — API (0.2)
|
|
2
2
|
|
|
3
3
|
Part of the `billing.public-api` contract with `src/index.ts` and
|
|
4
4
|
`src/domain/types.ts`. 0.x minors are additive; the declaration snapshot in
|
|
@@ -6,10 +6,11 @@ Part of the `billing.public-api` contract with `src/index.ts` and
|
|
|
6
6
|
|
|
7
7
|
| Entry | Contents |
|
|
8
8
|
|---|---|
|
|
9
|
-
| `@tofound/billing` | domain types, money helpers, `BillingError`, `createLedger`, ports, `createMemoryLedgerStore`, waterfall + steps, provider port, `createIngest`, `createMemoryIngestStore` |
|
|
10
|
-
| `@tofound/billing/drizzle` | `createBillingTables`, `billingTableBuilder`, `checkAdditiveDdl`, `createDrizzleLedgerStore`, `createIngestTables`, `createDrizzleIngestStore` (peer `drizzle-orm ^0.45`) |
|
|
9
|
+
| `@tofound/billing` | domain types, money helpers, `BillingError`, `createLedger`, ports, `createMemoryLedgerStore`, waterfall + steps, provider port, `createIngest`, `createMemoryIngestStore`, `defineCatalog`, terms, `resolveEntitlement`, `createPlans`, `createRenewal`, `createSnapshotHandler`, `createMemoryTermStore` |
|
|
10
|
+
| `@tofound/billing/drizzle` | `createBillingTables`, `billingTableBuilder`, `checkAdditiveDdl`, `createDrizzleLedgerStore`, `createIngestTables`, `createDrizzleIngestStore`, `createTermTables`, `createDrizzleTermStore`, `termTableNames` (peer `drizzle-orm ^0.45`) |
|
|
11
11
|
| `@tofound/billing/providers/sepay` | `createSepayAdapter`, `respondSepay`, `signCheckoutFields`, `parseSepayOrder` |
|
|
12
|
-
| `@tofound/billing/
|
|
12
|
+
| `@tofound/billing/providers/polar` | `createPolarAdapter`, `resolvePolarEnvironment`, `respondPolar`, `redactPolarPayload`, `signPolarWebhook`, `PolarApiError`, `POLAR_WEBHOOK_*` header names and tolerance; types `PolarAdapter`, `PolarAdapterOptions`, `PolarCheckoutRequest`, `PolarKeyDerivation` |
|
|
13
|
+
| `@tofound/billing/testing` | `ledgerConformanceCases`, `assertLedgerInvariants`, `assertQuoteMatchesSettlement`, `ingestConformanceCases`, `termConformanceCases`, memory stores |
|
|
13
14
|
|
|
14
15
|
The library reads no env, logs nothing and has no runtime dependencies. Every
|
|
15
16
|
amount is an integer in minor units — a safe-integer `number` in TS, `bigint`
|
|
@@ -84,6 +85,11 @@ Invariants every store upholds (design §4.3):
|
|
|
84
85
|
| `reversal_exceeds_original` | `reverse` amount > \|original delta\| | `{entryId, amount, original}` |
|
|
85
86
|
| `already_reversed` | the entry already has its reversal | `{entryId, reversalId?}` |
|
|
86
87
|
| `balance_overflow` | a result leaves the safe-integer range | — |
|
|
88
|
+
| `invalid_catalog` | `defineCatalog` refuses the host's catalog | the offending key |
|
|
89
|
+
| `plan_not_found` | a plan key the catalog does not have | `{plan}` |
|
|
90
|
+
| `offer_not_found` | the plan is not sold for these months in this market | `{plan, months, market}` |
|
|
91
|
+
| `term_not_found` | auto-renew / cancel with no open credit term | `{accountId}` |
|
|
92
|
+
| `plan_blocked` | a plan purchase the quote refuses | `{reason}` (`covered_by_subscription`) |
|
|
87
93
|
|
|
88
94
|
A plain `Error` (not `BillingError`) signals a broken store or host setup,
|
|
89
95
|
e.g. a repeating `IdGenerator`; it is never an expected outcome.
|
|
@@ -142,6 +148,9 @@ await w.settle(tx, lockedState, { accountId, idempotencyKey }) // same steps, co
|
|
|
142
148
|
emit after its commit (the sink is not called inside a host transaction).
|
|
143
149
|
- `assertQuoteMatchesSettlement(quote, {settled, walletDelta, meterDeltas})`
|
|
144
150
|
is the conformance check every host runs against real charges.
|
|
151
|
+
`walletDelta` is **balance after − balance before**, so a charge is
|
|
152
|
+
negative: a settled quote must show `walletDelta === -quote.price`, a
|
|
153
|
+
blocked one `0`. `meterDeltas` are the units each pool consumed (positive).
|
|
145
154
|
|
|
146
155
|
## Provider ingest (`billing.provider-port`)
|
|
147
156
|
|
|
@@ -191,6 +200,216 @@ await ingest.sweep()
|
|
|
191
200
|
plus the ledger's `credited` / `debited` — all after commit; a throwing sink
|
|
192
201
|
never fails the delivery.
|
|
193
202
|
|
|
203
|
+
## Polar (`@tofound/billing/providers/polar`)
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
const environment = resolvePolarEnvironment({ environment: env.POLAR_ENV, productionEnabled: env.POLAR_PRODUCTION_ENABLED === 'true' })
|
|
207
|
+
const polar = createPolarAdapter({
|
|
208
|
+
environment, // required: 'production' | 'sandbox'
|
|
209
|
+
webhookSecrets: [current, next?], // `whsec_…`; two only while rotating
|
|
210
|
+
products: { [polarProductId]: productRef }, // this environment's Polar products → catalog productRefs
|
|
211
|
+
accessToken?, // organization token: checkout + portal only
|
|
212
|
+
checkoutPattern?, toleranceSec?, clock?, fetch?, timeoutMs?,
|
|
213
|
+
})
|
|
214
|
+
const ingest = createIngest({
|
|
215
|
+
adapters: [polar], store, ledger,
|
|
216
|
+
handlers: { 'subscription.snapshot': createSnapshotHandler({ terms, catalog, resolveAccount }) },
|
|
217
|
+
})
|
|
218
|
+
|
|
219
|
+
const { redirect } = await ingest.createCheckout({ provider: 'polar', accountId, amount, credits, productRef, … }) // a credit pack
|
|
220
|
+
const r = await ingest.handle('polar', { headers, rawBody, url, receivedAt }) // → reply with r.response
|
|
221
|
+
const { url } = await polar.createPortalSession({ kind: 'account_id', value: accountId }, returnUrl) // or kind 'polar_customer_external_id'
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
| Export | Signature |
|
|
225
|
+
|---|---|
|
|
226
|
+
| `resolvePolarEnvironment` | `({ environment: string \| null \| undefined, productionEnabled: boolean }) → 'production' \| 'sandbox'` |
|
|
227
|
+
| `createPolarAdapter` | `(PolarAdapterOptions) → PolarAdapter` (`ProviderAdapter` + `createCheckout` + `createPortalSession`) |
|
|
228
|
+
| `respondPolar` | `(IngestOutcome) → ProviderResponse`: the adapter's `respond` |
|
|
229
|
+
| `redactPolarPayload` | `(payload) → payload`: the adapter's `redact` (`redactPayload` plus `tax_id`, `custom_field_data`, `avatar_url`, `customer_ip_address`, and any Polar secret inside a value, e.g. the `polar_c_…` client secret in a checkout `url` → `polar_c_[redacted]`) |
|
|
230
|
+
| `signPolarWebhook` | `(secret, id, timestamp, rawBody, derivation = 'standard') → 'v1,<base64>'`: for host tests and fixtures |
|
|
231
|
+
|
|
232
|
+
- **Environment, never inferred.** `resolvePolarEnvironment` turns the host's
|
|
233
|
+
two switches into one value: `sandbox` → sandbox; `production` only with
|
|
234
|
+
`productionEnabled: true`, else `ProviderConfigError('polar_production_disabled')`;
|
|
235
|
+
anything else (unset, typo) → `polar_environment_required`. The adapter has
|
|
236
|
+
no default either, and it picks the API host:
|
|
237
|
+
`api.polar.sh` or `sandbox-api.polar.sh`. Sandbox and production products
|
|
238
|
+
have different ids, so pass the `products` map for the environment you run.
|
|
239
|
+
Other config errors: `polar_webhook_secrets_required`, `polar_invalid_tolerance`.
|
|
240
|
+
- **Standard Webhooks verification** runs on the raw body before any parse.
|
|
241
|
+
The signed content is `${webhook-id}.${webhook-timestamp}.${rawBody}`, HMAC-SHA256, and any
|
|
242
|
+
`v1,` entry of `webhook-signature` may match any secret in
|
|
243
|
+
`webhookSecrets`. Both key derivations are accepted: base64 after `whsec_` (standard) and the whole
|
|
244
|
+
string's UTF-8 (legacy). Comparison is constant-time. A missing header, a
|
|
245
|
+
`webhook-id` over 128 characters, a non-numeric timestamp, a timestamp
|
|
246
|
+
outside ±`toleranceSec` (300 s) or no matching signature → `unauthorized`
|
|
247
|
+
(401). Non-JSON, no `type` / `data`, or a `type` over 64 characters →
|
|
248
|
+
`malformed` (400). Nothing is stored in either case. The event id is
|
|
249
|
+
`polar:<webhook-id>`, so a retry of a message whose row is final is
|
|
250
|
+
`duplicate`; a `failed` row is processed again.
|
|
251
|
+
- **Credit packs.** `createCheckout` refuses an unmapped `productRef`
|
|
252
|
+
(exactly one Polar product per ref), a non-positive amount, or a session id
|
|
253
|
+
that is not `checkoutPattern` before any call (`ProviderConfigError` codes
|
|
254
|
+
`polar_unknown_product`, `polar_invalid_amount`, `polar_invalid_checkout_id`,
|
|
255
|
+
and `polar_not_configured` without a token). A failed call is `PolarApiError`
|
|
256
|
+
(`polar_unreachable`, `polar_error` with `status`, `polar_bad_response`). It then creates a Polar checkout
|
|
257
|
+
with `external_customer_id = accountId`, `metadata.checkout_id = sessionId`
|
|
258
|
+
and `allow_discount_codes: false`. A response whose currency or `amount`
|
|
259
|
+
(the product price before discount and tax) differs from the catalog amount,
|
|
260
|
+
or that carries a `discount_amount`, is refused as `polar_price_mismatch`.
|
|
261
|
+
The checkout's `net_amount` is not compared: it drops by the tax once a
|
|
262
|
+
tax-inclusive country is known.
|
|
263
|
+
The Polar checkout already exists by then; it is never handed to the buyer.
|
|
264
|
+
The session id comes from the ingest's `ids` (default `randomUUID`), so a custom
|
|
265
|
+
generator must match `checkoutPattern`, or every checkout throws
|
|
266
|
+
`polar_invalid_checkout_id`. `PolarCheckoutRequest.customerIpAddress` (sent for tax
|
|
267
|
+
country) is only accepted by a direct `polar.createCheckout` call;
|
|
268
|
+
`ingest.createCheckout` does not forward it.
|
|
269
|
+
`order.paid` for a one-time order becomes `purchase.completed`, bound to the
|
|
270
|
+
session by `metadata.checkout_id` and credited once (`topup:<sessionId>`).
|
|
271
|
+
Its amount is the catalog price, `subtotal_amount − discount_amount`, which
|
|
272
|
+
reads the same whatever the organization's tax behaviour: a tax-inclusive
|
|
273
|
+
$5.00 order (a DE buyer under `location`) has `net_amount` 420 and
|
|
274
|
+
`tax_amount` 80, a tax-exclusive one `total_amount` 540, and both are 500
|
|
275
|
+
here. `net_amount` and `total_amount` are never used; an order without a
|
|
276
|
+
readable subtotal is `needs_review` (`invalid_amount`). If the amount differs
|
|
277
|
+
from the session (a discount), the order goes to `needs_review`
|
|
278
|
+
(`amount_mismatch`) and nothing is credited. `order.created` / `order.updated` move no money, and a
|
|
279
|
+
subscription's own orders are receipts (`ignored`).
|
|
280
|
+
- **Refunds.** `order.refunded` with status `refunded` becomes
|
|
281
|
+
`purchase.reversed`, its amount on the same basis as the order's
|
|
282
|
+
(`refunded_amount` is not compared: it excludes a tax-inclusive order's tax). The reversal claws back once, in any order relative to
|
|
283
|
+
`order.paid`: a refund delivered first, carrying our `metadata.checkout_id`,
|
|
284
|
+
voids the session, and the late paid order never credits (a refund matching
|
|
285
|
+
neither a session nor a purchase is `ignored`, `no_match`). A partial refund is `needs_review` (`partial_refund`)
|
|
286
|
+
and is never guessed into a clawback.
|
|
287
|
+
- **Subscriptions.** `subscription.*` events become `subscription.snapshot` with
|
|
288
|
+
`account = { kind: 'polar_customer_external_id', value: external_customer_id }`.
|
|
289
|
+
The status maps as follows:
|
|
290
|
+
- `active` / `trialing` → `active`
|
|
291
|
+
- `past_due` / `unpaid` → `past_due`
|
|
292
|
+
- `canceled` → `active` (ends at period end), or `expired` when `ended_at` is at
|
|
293
|
+
or before the event's own `modified_at`
|
|
294
|
+
- revoked or paused → `revoked`
|
|
295
|
+
|
|
296
|
+
Statuses Polar sets before any payment (`incomplete`…) are `ignored`. Each
|
|
297
|
+
snapshot is watermarked by Polar's `modified_at`. Polar sends one change as
|
|
298
|
+
several events with the same `modified_at` (a revoke is `updated`,
|
|
299
|
+
`canceled` and `revoked`), so the event type breaks the tie (`tieBreak`):
|
|
300
|
+
`revoked` > `paused` > `canceled` > `uncanceled` > `past_due` > `active` >
|
|
301
|
+
`updated` > `created`. A revoke therefore ends `revoked` in any arrival
|
|
302
|
+
order; the outranked copies are `ignored` (`stale`). The period ends at
|
|
303
|
+
`ended_at` when that is before `current_period_end`. A product not in `products`
|
|
304
|
+
is `ignored` (`unknown_product`). Without a `subscription.snapshot` handler,
|
|
305
|
+
a snapshot is `needs_review` (`no_handler:…`).
|
|
306
|
+
- **Subscription checkouts** do not go through the ingest:
|
|
307
|
+
`ingest.createCheckout` sells credit packs (a session, credits on
|
|
308
|
+
`order.paid`). For a plan, call `polar.createCheckout` directly with a fresh
|
|
309
|
+
UUID `sessionId` (it is only carried in `metadata`), the plan offer's
|
|
310
|
+
`productRef` and its catalog price (the price guard applies). No session row
|
|
311
|
+
is written: the subscription reaches the terms through `subscription.*`
|
|
312
|
+
events bound by `external_customer_id = accountId`, and its orders are
|
|
313
|
+
receipts.
|
|
314
|
+
- **Webhook events to subscribe:** `order.paid`, `order.refunded`,
|
|
315
|
+
`subscription.created` / `.updated` / `.active` / `.canceled` /
|
|
316
|
+
`.uncanceled` / `.revoked` (and `.past_due` where offered). `checkout.*`
|
|
317
|
+
is not needed: the ingest has no `checkout.status` handler, so those
|
|
318
|
+
deliveries are verified, stored and `ignored` (`no_handler:checkout.status`),
|
|
319
|
+
which is harmless but fills the inbox (about half of the rows in a sandbox
|
|
320
|
+
run). The order carries everything a credit needs.
|
|
321
|
+
- **What the host wires:**
|
|
322
|
+
- **Environment and secrets:** resolve the environment once at boot, keep
|
|
323
|
+
the secrets server-side and pass the access token only where checkout or
|
|
324
|
+
the portal runs.
|
|
325
|
+
- **Webhook route:** a raw-body route that answers with `r.response`.
|
|
326
|
+
`respondPolar` acknowledges every outcome a retry cannot change with 200
|
|
327
|
+
and answers 5xx only on `failed`. A relayed delivery returns the
|
|
328
|
+
`onUnmatched` response as is.
|
|
329
|
+
- **`resolveAccount`:** maps the external customer id back to your account.
|
|
330
|
+
It returns `null` for another host's customers on a shared organization.
|
|
331
|
+
Only a subscription whose product is in `products` reaches it; that
|
|
332
|
+
`null` is relayed through `onUnmatched`. A subscription on an unmapped
|
|
333
|
+
product is `ignored` (`unknown_product`) and is not relayed. Another
|
|
334
|
+
host's one-time order goes to `needs_review` (`unsupported_account_ref`
|
|
335
|
+
or `unbound_order`, alerted), unless its `metadata.checkout_id` is a
|
|
336
|
+
session id this host's pattern accepts that matches none of its sessions;
|
|
337
|
+
that order is relayed as unmatched.
|
|
338
|
+
- **Catalog:** one Polar `productRef` per offer.
|
|
339
|
+
- **Monitoring:** watch the `billing.alert` events. `PolarApiError` never
|
|
340
|
+
carries the token or Polar's response body. A portal for any other
|
|
341
|
+
account kind is refused (`ProviderConfigError('polar_unsupported_account')`).
|
|
342
|
+
|
|
343
|
+
## Catalog, terms and entitlement (0.2)
|
|
344
|
+
|
|
345
|
+
```ts
|
|
346
|
+
const catalog = defineCatalog({ version, creditUnit, markets: [{ key: 'vn', currency: 'VND' }], plans, creditPacks?, policies? })
|
|
347
|
+
const terms = createDrizzleTermStore({ db, tables: { billingTerms, billingTermAccounts } }) // memory: createMemoryTermStore(ledgerStore)
|
|
348
|
+
const plans = createPlans({ ledger, terms, catalog, events? })
|
|
349
|
+
const renewal = createRenewal({ ledger, terms, catalog, marketOf?, events? })
|
|
350
|
+
|
|
351
|
+
const quote = await plans.quote({ accountId, plan: 'pro', months: 3, market }) // market set by the host, never the client
|
|
352
|
+
const bought = await plans.purchase({ accountId, plan: 'pro', months: 3, market, idempotencyKey })
|
|
353
|
+
const ent = resolveEntitlement(await terms.reader().listTerms(accountId), new Date(), catalog, { balance })
|
|
354
|
+
await renewal.renewDue() // host cron, under its own advisory lock
|
|
355
|
+
await renewal.retryPastDue(accountId) // after a top-up commits, in its own transaction
|
|
356
|
+
createIngest({ …, handlers: { 'subscription.snapshot': createSnapshotHandler({ terms, catalog, resolveAccount }) } })
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
- **The catalog is the host's config**: plans (strict `rank`, exactly one
|
|
360
|
+
`free`), credit offers per `market` × `months`, provider offers by
|
|
361
|
+
`productRef`, packs and `policies` (`termDays` 30, `upgradeProration`
|
|
362
|
+
`remaining_time` | `none`, `graceDays` 3, `renewalLeadSec`). The library has
|
|
363
|
+
no plan or price literal.
|
|
364
|
+
- **Terms** (`billing_terms`) are one shape for credit, Polar, Apple and Google.
|
|
365
|
+
Credit terms are written only by plans and renewal; provider terms only by
|
|
366
|
+
the snapshot handler, under a watermark (an older snapshot is `ignored`).
|
|
367
|
+
At most one open (`active` | `grace` | `past_due`) credit term and one
|
|
368
|
+
`scheduled` term per account. Every writer locks the account's terms
|
|
369
|
+
first (`lockAccountTerms`, through the `term_accounts` guard row), then
|
|
370
|
+
the ledger account last.
|
|
371
|
+
- **Entitlement** (S1): the highest-rank entitled term wins, then the later
|
|
372
|
+
end, then the older term; quotas and permissions never sum; nothing entitled
|
|
373
|
+
→ the free plan. A `past_due` term is entitled (`status: 'grace'`) until
|
|
374
|
+
`graceUntil`. `includedCredits` comes only from provider-funded terms.
|
|
375
|
+
Warnings: `two_subscriptions` (S5), `past_due`, `renewal_shortfall` (pass
|
|
376
|
+
`balance`), `scheduled_downgrade`.
|
|
377
|
+
- **Plan quotes** walk one waterfall (covered → credits) for both the quote
|
|
378
|
+
and the purchase, so `assertQuoteMatchesSettlement` holds. `kind`:
|
|
379
|
+
`new`; `extend` (S2, same plan, months appended, charged in full);
|
|
380
|
+
`upgrade` (end date kept; `remaining_time` charges
|
|
381
|
+
ceil(remaining/total × (offerNew − paid)), `originalPrice` is the unprorated
|
|
382
|
+
difference); `renew` (paying a past_due term, from its old end);
|
|
383
|
+
`downgrade` (S3b, no money now: the renewal switches plan under auto-renew,
|
|
384
|
+
otherwise a `scheduled` term charged when it starts; also after a
|
|
385
|
+
non-renewing subscription of ≥ rank, reason `scheduled_after_subscription`);
|
|
386
|
+
`blocked` (S3, a renewing subscription of ≥ rank, reason
|
|
387
|
+
`covered_by_subscription`). A new term supersedes a `scheduled` one that
|
|
388
|
+
would start inside it. The purchase writes term rows before the debit, so
|
|
389
|
+
a throw relies on the rollback: under `plans.in(tx)` the host must roll its
|
|
390
|
+
transaction back. A repeated `idempotencyKey` replays — from its ledger
|
|
391
|
+
entry, or for a purchase that charged nothing from the term that recorded
|
|
392
|
+
the key (the last 20 per term), whatever the term's status since.
|
|
393
|
+
- **Renewal** (D9) charges the **live** catalog price of
|
|
394
|
+
`nextPlanKey ?? planKey` (`plan_renewal`, key
|
|
395
|
+
`renew:<termId>:<periodEnd ISO>`, so a double run debits once). A short
|
|
396
|
+
balance makes the term `past_due` with `graceUntil = periodEnd + graceDays`
|
|
397
|
+
and emits `renewal_failed {required, balance, shortfall}`; grace passed →
|
|
398
|
+
`expired`. An early attempt inside `renewalLeadSec` that fails emits
|
|
399
|
+
`renewal_failed` but leaves the paid period `active` (outcome `skipped`);
|
|
400
|
+
the next run tries again.
|
|
401
|
+
- **S4 supersede**: an entitled provider subscription of ≥ rank closes the
|
|
402
|
+
credit term (`superseded`) and refunds its unused share,
|
|
403
|
+
ceil(remaining/total × paid), as `plan_refund` keyed `supersede:<termId>`.
|
|
404
|
+
A snapshot whose account `resolveAccount` does not know is `ignored`
|
|
405
|
+
(`no_match`) and relayed through `onUnmatched`, before its product is
|
|
406
|
+
checked (another host's subscription on a shared provider account); a
|
|
407
|
+
subscription already bound to another account is `needs_review`
|
|
408
|
+
(`account_mismatch`).
|
|
409
|
+
- Events after commit: `term_changed {change, term}`, `renewal_failed`, plus
|
|
410
|
+
the ledger's `credited` / `debited`; under `.in(tx)` they come back in the
|
|
411
|
+
result.
|
|
412
|
+
|
|
194
413
|
## Drizzle
|
|
195
414
|
|
|
196
415
|
See [SCHEMA.md](SCHEMA.md). `createDrizzleLedgerStore({ db, tables })` works
|