@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.
Files changed (45) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +58 -13
  3. package/dist/catalog/catalog.d.ts +115 -0
  4. package/dist/catalog/catalog.js +201 -0
  5. package/dist/domain/types.d.ts +3 -1
  6. package/dist/drizzle/index.d.ts +2 -0
  7. package/dist/drizzle/index.js +2 -0
  8. package/dist/entitlement/resolve.d.ts +76 -0
  9. package/dist/entitlement/resolve.js +122 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +9 -0
  12. package/dist/providers/polar/events.d.ts +17 -0
  13. package/dist/providers/polar/events.js +213 -0
  14. package/dist/providers/polar/index.d.ts +50 -0
  15. package/dist/providers/polar/index.js +271 -0
  16. package/dist/providers/polar/signature.d.ts +23 -0
  17. package/dist/providers/polar/signature.js +52 -0
  18. package/dist/providers/port.d.ts +6 -0
  19. package/dist/renewal/renewal.d.ts +69 -0
  20. package/dist/renewal/renewal.js +198 -0
  21. package/dist/stores/testing.d.ts +4 -2
  22. package/dist/stores/testing.js +4 -2
  23. package/dist/terms/conformance.d.ts +17 -0
  24. package/dist/terms/conformance.js +198 -0
  25. package/dist/terms/decide.d.ts +97 -0
  26. package/dist/terms/decide.js +176 -0
  27. package/dist/terms/drizzle.d.ts +12 -0
  28. package/dist/terms/drizzle.js +131 -0
  29. package/dist/terms/memory.d.ts +23 -0
  30. package/dist/terms/memory.js +126 -0
  31. package/dist/terms/plans.d.ts +85 -0
  32. package/dist/terms/plans.js +331 -0
  33. package/dist/terms/ports.d.ts +55 -0
  34. package/dist/terms/ports.js +1 -0
  35. package/dist/terms/rules.d.ts +11 -0
  36. package/dist/terms/rules.js +36 -0
  37. package/dist/terms/schema.d.ts +711 -0
  38. package/dist/terms/schema.js +70 -0
  39. package/dist/terms/snapshot.d.ts +20 -0
  40. package/dist/terms/snapshot.js +134 -0
  41. package/dist/terms/types.d.ts +85 -0
  42. package/dist/terms/types.js +4 -0
  43. package/docs/API.md +223 -4
  44. package/docs/SCHEMA.md +57 -2
  45. package/package.json +6 -1
@@ -0,0 +1,126 @@
1
+ import { isRenewalDue, renewalDueAt } from './rules.js';
2
+ import { OPEN_TERM_STATUSES } from './types.js';
3
+ const OPEN = new Set(OPEN_TERM_STATUSES);
4
+ /**
5
+ * In-process `TermStore`. It runs inside `base`'s transactions (one store-wide
6
+ * mutex) and commits its staged rows when `fn` resolves, so a term and its
7
+ * ledger entry land together or not at all. To use terms and the inbox in
8
+ * one transaction, chain the wrappers:
9
+ *
10
+ * const ledgerStore = createMemoryLedgerStore()
11
+ * const termStore = createMemoryTermStore(ledgerStore)
12
+ * const ingestStore = createMemoryIngestStore({ ...ledgerStore, transaction: termStore.transaction })
13
+ */
14
+ export function createMemoryTermStore(base) {
15
+ const terms = new Map();
16
+ const staging = new WeakMap();
17
+ const clone = (value) => structuredClone(value);
18
+ const list = (rows, accountId, options = {}) => [...rows]
19
+ .filter((t) => t.accountId === accountId && (!options.statuses || options.statuses.includes(t.status)))
20
+ .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : -1))
21
+ .slice(0, options.limit ?? 50)
22
+ .map(clone);
23
+ const committed = {
24
+ async getTerm(id) {
25
+ const t = terms.get(id);
26
+ return t ? clone(t) : null;
27
+ },
28
+ async listTerms(accountId, options) {
29
+ return list(terms.values(), accountId, options);
30
+ },
31
+ async findExternal(source, environment, externalId) {
32
+ for (const t of terms.values()) {
33
+ if (t.source === source && t.environment === environment && t.externalId === externalId)
34
+ return clone(t);
35
+ }
36
+ return null;
37
+ },
38
+ async listDue(now, leadSec, limit) {
39
+ return [...terms.values()]
40
+ .filter((t) => isRenewalDue(t, now, leadSec))
41
+ .sort((a, b) => renewalDueAt(a, leadSec) - renewalDueAt(b, leadSec))
42
+ .slice(0, limit)
43
+ .map(clone);
44
+ },
45
+ };
46
+ function staged(tx) {
47
+ let s = staging.get(tx);
48
+ if (!s) {
49
+ s = new Map();
50
+ staging.set(tx, s);
51
+ }
52
+ return s;
53
+ }
54
+ function bind(tx) {
55
+ const view = () => new Map([...terms, ...staged(tx)]);
56
+ const read = (id) => staged(tx).get(id) ?? terms.get(id);
57
+ const findExternal = async (source, environment, externalId) => {
58
+ for (const t of view().values()) {
59
+ if (t.source === source && t.environment === environment && t.externalId === externalId)
60
+ return clone(t);
61
+ }
62
+ return null;
63
+ };
64
+ /** The rows a term's unique keys would collide with. */
65
+ const clashes = (t, rows) => [...rows.values()].some((o) => o.id !== t.id &&
66
+ ((t.externalId !== null && o.source === t.source && o.environment === t.environment && o.externalId === t.externalId) ||
67
+ (t.source === 'credit' && o.source === 'credit' && o.accountId === t.accountId && OPEN.has(t.status) && OPEN.has(o.status)) ||
68
+ (t.status === 'scheduled' && o.status === 'scheduled' && o.accountId === t.accountId)));
69
+ return {
70
+ getTerm: async (id) => {
71
+ const t = read(id);
72
+ return t ? clone(t) : null;
73
+ },
74
+ listTerms: async (accountId, options) => list(view().values(), accountId, options),
75
+ findExternal,
76
+ listDue: committed.listDue,
77
+ async lockAccountTerms(accountId) {
78
+ return [...view().values()]
79
+ .filter((t) => t.accountId === accountId && (t.status === 'scheduled' || OPEN.has(t.status)))
80
+ .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || (a.id < b.id ? -1 : 1))
81
+ .map(clone);
82
+ },
83
+ async lockTerm(id) {
84
+ const t = read(id);
85
+ return t ? clone(t) : null;
86
+ },
87
+ lockExternal: findExternal,
88
+ async insertTerm(term) {
89
+ const rows = view();
90
+ if (rows.has(term.id) || clashes(term, rows))
91
+ return { inserted: false };
92
+ staged(tx).set(term.id, clone(term));
93
+ return { inserted: true };
94
+ },
95
+ async updateTerm(id, patch) {
96
+ const t = read(id);
97
+ if (!t)
98
+ return;
99
+ const next = { ...clone(t), ...clone(patch), updatedAt: new Date() };
100
+ // The partial unique indexes of the Postgres table, enforced the same way.
101
+ if (clashes(next, view()))
102
+ throw new Error(`unique violation: term ${id} would duplicate an open or scheduled term`);
103
+ staged(tx).set(id, next);
104
+ },
105
+ };
106
+ }
107
+ return {
108
+ transaction: (fn) => base.transaction(async (tx) => {
109
+ try {
110
+ const result = await fn(tx);
111
+ for (const [id, term] of staging.get(tx) ?? [])
112
+ terms.set(id, term);
113
+ return result;
114
+ }
115
+ finally {
116
+ staging.delete(tx);
117
+ }
118
+ }),
119
+ bind,
120
+ reader: () => committed,
121
+ dump: (accountId) => [...terms.values()]
122
+ .filter((t) => t.accountId === accountId)
123
+ .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())
124
+ .map(clone),
125
+ };
126
+ }
@@ -0,0 +1,85 @@
1
+ import type { Catalog } from '../catalog/catalog.js';
2
+ import type { AccountId, BillingEvent, EntryMeta, LedgerEntry, Quote } from '../domain/types.js';
3
+ import type { Ledger } from '../ledger/ledger.js';
4
+ import type { Clock, IdGenerator } from '../ports/runtime.js';
5
+ import { type PlanQuoteKind, type PlanRequest } from './decide.js';
6
+ import type { TermStore } from './ports.js';
7
+ import { type Term, type TermEvent } from './types.js';
8
+ export type PlansEvent = TermEvent | BillingEvent;
9
+ /** Receives term and ledger events after the service's own transaction commits. */
10
+ export type PlansEventSink = (event: PlansEvent) => void | Promise<void>;
11
+ export interface PlansOptions<TTx> {
12
+ ledger: Ledger<TTx>;
13
+ terms: TermStore<TTx>;
14
+ catalog: Catalog;
15
+ clock?: Clock;
16
+ ids?: IdGenerator;
17
+ /** At-most-once, after commit, for transactions the service opened (see `LedgerOptions.events`). */
18
+ events?: PlansEventSink;
19
+ onEventError?: (error: unknown, event: PlansEvent) => void;
20
+ }
21
+ export interface PlanQuote extends Quote {
22
+ kind: PlanQuoteKind;
23
+ plan: string;
24
+ months: number;
25
+ market: string;
26
+ /** The period this purchase produces (kept on upgrade, extended on extend/renew); `null` when blocked. */
27
+ periodStart: Date | null;
28
+ periodEnd: Date | null;
29
+ /** True when the plan takes effect later (downgrade, after a non-renewing subscription); nothing is charged now. */
30
+ scheduled: boolean;
31
+ }
32
+ export interface PlanPurchaseInput extends PlanRequest {
33
+ /** Minted once per confirm; a retry with it buys once. */
34
+ idempotencyKey: string;
35
+ /** Auto-renew of a newly created term. Default true. */
36
+ autoRenew?: boolean;
37
+ /** Host label on the ledger entry. */
38
+ reason?: string | null;
39
+ meta?: EntryMeta | null;
40
+ }
41
+ export interface PlanPurchaseResult {
42
+ kind: Exclude<PlanQuoteKind, 'blocked'>;
43
+ /** The quote of the locked state — what was charged. */
44
+ quote: PlanQuote;
45
+ term: Term;
46
+ charged: number;
47
+ balance: number;
48
+ entry: LedgerEntry | null;
49
+ /** The key was already used: nothing ran, `term` is its current state. */
50
+ replayed: boolean;
51
+ events: PlansEvent[];
52
+ }
53
+ export interface TermUpdateResult {
54
+ term: Term;
55
+ events: PlansEvent[];
56
+ }
57
+ export interface PlanOps {
58
+ quote(req: PlanRequest): Promise<PlanQuote>;
59
+ /**
60
+ * Throws `plan_blocked` (`details.reason`), `insufficient_credits`
61
+ * (`details.shortfall`), `offer_not_found`, `plan_not_found` or
62
+ * `idempotency_mismatch`. Term rows are written before the debit, so a
63
+ * throw relies on the rollback: the service's own transaction rolls back;
64
+ * under `in(tx)` the host must roll its transaction back too.
65
+ */
66
+ purchase(input: PlanPurchaseInput): Promise<PlanPurchaseResult>;
67
+ /** Turn auto-renew of the open credit term on or off. On, a scheduled lower plan becomes its next plan. */
68
+ setAutoRenew(input: {
69
+ accountId: AccountId;
70
+ autoRenew: boolean;
71
+ }): Promise<TermUpdateResult>;
72
+ /** Auto-renew off and any scheduled term dropped; the term runs to its end, no refund. */
73
+ cancel(input: {
74
+ accountId: AccountId;
75
+ }): Promise<TermUpdateResult>;
76
+ /** Lapse the open credit term now, no refund (Lohi DELETE). */
77
+ cancelNow(input: {
78
+ accountId: AccountId;
79
+ }): Promise<TermUpdateResult>;
80
+ }
81
+ export interface Plans<TTx = unknown> extends PlanOps {
82
+ /** The same operations in a transaction the host holds; the host emits the returned events after commit. */
83
+ in(tx: TTx): PlanOps;
84
+ }
85
+ export declare function createPlans<TTx>(options: PlansOptions<TTx>): Plans<TTx>;
@@ -0,0 +1,331 @@
1
+ /**
2
+ * The plans service (design §4.8): quote and buy N months of a plan with
3
+ * credits, and the auto-renew controls. The quote and the purchase walk one
4
+ * waterfall — covered (S3) → credits → blocked — over the same decision
5
+ * (`decidePlanPurchase`), the purchase on rows it locked: term rows first,
6
+ * the ledger account last.
7
+ */
8
+ import { randomUUID } from 'node:crypto';
9
+ import { BillingError, insufficientCredits } from '../domain/errors.js';
10
+ import { creditsStep } from '../quote/steps.js';
11
+ import { createWaterfall } from '../quote/waterfall.js';
12
+ import { decidePlanPurchase } from './decide.js';
13
+ import { OPEN_TERM_STATUSES } from './types.js';
14
+ const OPEN = new Set(OPEN_TERM_STATUSES);
15
+ const MAX_PLAN_ATTEMPTS = 3;
16
+ /** Purchase keys a term remembers, newest last: how a purchase that charged nothing replays. */
17
+ const PURCHASES_KEPT = 20;
18
+ const purchasesOf = (term) => (Array.isArray(term.meta?.['purchases']) ? term.meta['purchases'] : []);
19
+ export function createPlans(options) {
20
+ const { ledger, terms, catalog } = options;
21
+ const clock = options.clock ?? { now: () => new Date() };
22
+ const ids = options.ids ?? randomUUID;
23
+ const unit = catalog.creditUnit.code;
24
+ const covered = {
25
+ id: 'covered',
26
+ plan: ({ state }) => (state.decision.kind === 'blocked' ? { type: 'block', reason: state.decision.reason } : null),
27
+ };
28
+ const waterfall = createWaterfall({
29
+ steps: [covered, creditsStep({ ledger, source: 'credits' })],
30
+ currency: unit,
31
+ price: (s) => s.decision.charge,
32
+ balance: (s) => s.balance,
33
+ });
34
+ function toQuote(state) {
35
+ const q = waterfall.quote(state);
36
+ const d = state.decision;
37
+ return {
38
+ ...q,
39
+ originalPrice: d.listPrice,
40
+ // A settleable purchase is explained by the decision (list price, proration, downgrade).
41
+ reason: q.canSettle ? d.reason : q.reason,
42
+ kind: d.kind,
43
+ plan: d.plan,
44
+ months: d.months,
45
+ market: d.market,
46
+ periodStart: d.periodStart,
47
+ periodEnd: d.periodEnd,
48
+ scheduled: d.scheduled,
49
+ };
50
+ }
51
+ async function quoteOn(reader, ledgerOps, req) {
52
+ const list = await reader.listTerms(req.accountId, { statuses: ['scheduled', ...OPEN_TERM_STATUSES] });
53
+ const now = clock.now();
54
+ return toQuote({ decision: decidePlanPurchase(list, req, catalog, now), balance: await ledgerOps.balance(req.accountId) });
55
+ }
56
+ function ops(tx) {
57
+ const t = terms.bind(tx);
58
+ const l = ledger.in(tx);
59
+ return {
60
+ quote: (req) => quoteOn(t, l, req),
61
+ purchase: (input) => purchase(tx, t, l, input),
62
+ setAutoRenew: (input) => setAutoRenew(t, input.accountId, input.autoRenew),
63
+ cancel: (input) => cancel(t, input.accountId),
64
+ cancelNow: (input) => cancelNow(t, input.accountId),
65
+ };
66
+ }
67
+ async function purchase(tx, t, l, input) {
68
+ if (!input.idempotencyKey)
69
+ throw new BillingError('invalid_input', 'idempotencyKey is required');
70
+ for (let attempt = 0; attempt < MAX_PLAN_ATTEMPTS; attempt++) {
71
+ const locked = await t.lockAccountTerms(input.accountId);
72
+ const replayed = await replay(t, l, input);
73
+ if (replayed)
74
+ return replayed;
75
+ const now = clock.now();
76
+ const decision = decidePlanPurchase(locked, input, catalog, now);
77
+ const state = { decision, balance: await l.balance(input.accountId) };
78
+ const quote = toQuote(state);
79
+ if (decision.kind === 'blocked') {
80
+ throw new BillingError('plan_blocked', `plan ${decision.plan} cannot be bought: ${decision.reason.code}`, { reason: decision.reason.code });
81
+ }
82
+ if (!quote.canSettle) {
83
+ throw insufficientCredits({ balance: state.balance, required: decision.charge, shortfall: quote.shortfall ?? decision.charge });
84
+ }
85
+ const applied = await apply(t, decision, input, now);
86
+ if (!applied)
87
+ continue; // a concurrent purchase created the term first: plan again on its result
88
+ let entry = null;
89
+ const events = [{ type: 'term_changed', accountId: input.accountId, change: applied.change, term: applied.term }];
90
+ if (decision.charge > 0) {
91
+ const settled = await waterfall.settle(tx, state, {
92
+ accountId: input.accountId,
93
+ idempotencyKey: input.idempotencyKey,
94
+ kind: 'plan_purchase',
95
+ reason: input.reason ?? null,
96
+ source: { type: 'term', id: applied.term.id },
97
+ meta: { ...(input.meta ?? {}), plan: decision.plan, months: decision.months, quoteKind: decision.kind },
98
+ });
99
+ if (!settled.settled) {
100
+ throw insufficientCredits({ balance: settled.quote.balance ?? 0, required: decision.charge, shortfall: settled.quote.shortfall ?? decision.charge });
101
+ }
102
+ entry = settled.entries[0] ?? null;
103
+ events.push(...settled.events);
104
+ }
105
+ return {
106
+ kind: decision.kind,
107
+ quote,
108
+ term: applied.term,
109
+ charged: decision.charge,
110
+ balance: await l.balance(input.accountId),
111
+ entry,
112
+ replayed: false,
113
+ events,
114
+ };
115
+ }
116
+ throw new Error(`plan purchase ${input.idempotencyKey}: the account's terms kept changing under it`);
117
+ }
118
+ /** The key's earlier outcome: its ledger entry, or (for a purchase that charged nothing) the term that recorded it. */
119
+ async function replay(t, l, input) {
120
+ const entry = await l.findByKey(input.idempotencyKey);
121
+ let term = null;
122
+ let recorded;
123
+ if (entry) {
124
+ if (entry.accountId !== input.accountId || entry.kind !== 'plan_purchase' || entry.sourceType !== 'term' || !entry.sourceId) {
125
+ throw new BillingError('idempotency_mismatch', `idempotency key ${input.idempotencyKey} was posted with a different intent`, {
126
+ idempotencyKey: input.idempotencyKey,
127
+ entryId: entry.id,
128
+ });
129
+ }
130
+ term = await t.getTerm(entry.sourceId);
131
+ recorded = entry.meta ?? undefined;
132
+ }
133
+ else {
134
+ // Any status: the term may have expired or been superseded since.
135
+ for (const x of await t.listTerms(input.accountId)) {
136
+ recorded = purchasesOf(x).find((p) => p.key === input.idempotencyKey);
137
+ if (recorded) {
138
+ term = x;
139
+ break;
140
+ }
141
+ }
142
+ }
143
+ if (!term)
144
+ return null;
145
+ if (recorded && (recorded.plan !== input.plan || recorded.months !== input.months)) {
146
+ throw new BillingError('idempotency_mismatch', `idempotency key ${input.idempotencyKey} bought a different plan`, {
147
+ idempotencyKey: input.idempotencyKey,
148
+ });
149
+ }
150
+ const balance = await l.balance(input.accountId);
151
+ const kind = (recorded?.quoteKind ?? 'new');
152
+ const charged = entry ? -entry.delta : 0;
153
+ const quote = {
154
+ originalPrice: charged,
155
+ price: charged,
156
+ currency: unit,
157
+ reason: { code: 'replayed' },
158
+ funding: [],
159
+ settlement: charged > 0 ? 'wallet' : 'free',
160
+ canSettle: true,
161
+ balance,
162
+ expiresInSec: 0,
163
+ kind,
164
+ plan: input.plan,
165
+ months: input.months,
166
+ market: input.market,
167
+ periodStart: term.currentPeriodStart,
168
+ periodEnd: term.currentPeriodEnd,
169
+ scheduled: term.status === 'scheduled',
170
+ };
171
+ return { kind, quote, term, charged, balance, entry, replayed: true, events: [] };
172
+ }
173
+ /** Write the decision's term effect; `null` when a unique conflict says another purchase got there first. */
174
+ async function apply(t, d, input, now) {
175
+ const record = { key: input.idempotencyKey, plan: d.plan, months: d.months, quoteKind: d.kind };
176
+ const marker = { purchases: [record] };
177
+ const e = d.effect;
178
+ const update = async (term, patch, change) => {
179
+ const next = { ...patch, meta: { ...(term.meta ?? {}), purchases: [...purchasesOf(term), record].slice(-PURCHASES_KEPT) } };
180
+ await t.updateTerm(term.id, next);
181
+ return { term: { ...term, ...next, updatedAt: now }, change };
182
+ };
183
+ switch (e.type) {
184
+ case 'create': {
185
+ if (e.close)
186
+ await t.updateTerm(e.close.id, { status: 'expired' });
187
+ const term = creditTerm(input.accountId, d, now, {
188
+ status: 'active',
189
+ startsAt: e.startsAt,
190
+ currentPeriodStart: e.startsAt,
191
+ currentPeriodEnd: e.periodEnd,
192
+ autoRenew: input.autoRenew ?? true,
193
+ priceMinor: d.charge,
194
+ periodItems: e.items,
195
+ meta: marker,
196
+ });
197
+ if (!(await t.insertTerm(term)).inserted)
198
+ return null;
199
+ // A scheduled term it replaces would start inside this one: the purchase supersedes it.
200
+ if (e.scheduled)
201
+ await t.updateTerm(e.scheduled.id, { status: 'superseded', supersededBy: term.id, autoRenew: false });
202
+ return { term, change: 'created' };
203
+ }
204
+ case 'extend': {
205
+ if (e.scheduled) {
206
+ const length = e.scheduled.currentPeriodEnd.getTime() - e.scheduled.startsAt.getTime();
207
+ await t.updateTerm(e.scheduled.id, {
208
+ startsAt: e.periodEnd,
209
+ currentPeriodStart: e.periodEnd,
210
+ currentPeriodEnd: new Date(e.periodEnd.getTime() + length),
211
+ });
212
+ }
213
+ return update(e.term, { currentPeriodEnd: e.periodEnd, periodItems: e.items, priceMinor: sum(e.items), market: d.market }, 'extended');
214
+ }
215
+ case 'upgrade':
216
+ return update(e.term, { planKey: d.plan, nextPlanKey: null, periodItems: e.items, priceMinor: sum(e.items), market: d.market }, 'upgraded');
217
+ case 'renew':
218
+ return update(e.term, {
219
+ status: 'active',
220
+ planKey: d.plan,
221
+ nextPlanKey: null,
222
+ graceUntil: null,
223
+ currentPeriodStart: e.periodStart,
224
+ currentPeriodEnd: e.periodEnd,
225
+ intervalMonths: d.months,
226
+ periodItems: e.items,
227
+ priceMinor: sum(e.items),
228
+ market: d.market,
229
+ }, 'renewed');
230
+ case 'next_plan':
231
+ return update(e.term, { nextPlanKey: d.plan, intervalMonths: d.months }, 'scheduled');
232
+ case 'schedule': {
233
+ const patch = { planKey: d.plan, intervalMonths: d.months, startsAt: e.startsAt, currentPeriodStart: e.startsAt, currentPeriodEnd: e.periodEnd, market: d.market };
234
+ if (e.existing)
235
+ return update(e.existing, patch, 'scheduled');
236
+ const term = creditTerm(input.accountId, d, now, { ...patch, status: 'scheduled', autoRenew: input.autoRenew ?? true, priceMinor: null, periodItems: null, meta: marker });
237
+ return (await t.insertTerm(term)).inserted ? { term, change: 'scheduled' } : null;
238
+ }
239
+ case 'none':
240
+ throw new Error(`decision ${d.kind} has no term effect`);
241
+ }
242
+ }
243
+ function creditTerm(accountId, d, now, fields) {
244
+ return {
245
+ id: ids(),
246
+ accountId,
247
+ source: 'credit',
248
+ environment: null,
249
+ externalId: null,
250
+ planKey: d.plan,
251
+ market: d.market,
252
+ intervalMonths: d.months,
253
+ autoRenew: true,
254
+ cancelAtPeriodEnd: false,
255
+ graceUntil: null,
256
+ nextPlanKey: null,
257
+ priceMinor: null,
258
+ priceUnit: unit,
259
+ periodItems: null,
260
+ supersededBy: null,
261
+ lastEventAt: null,
262
+ lastEventRef: null,
263
+ meta: null,
264
+ createdAt: now,
265
+ updatedAt: now,
266
+ ...fields,
267
+ };
268
+ }
269
+ async function openCreditTerm(t, accountId) {
270
+ const locked = await t.lockAccountTerms(accountId);
271
+ const open = locked.find((x) => x.source === 'credit' && OPEN.has(x.status));
272
+ if (!open)
273
+ throw new BillingError('term_not_found', `account ${accountId} has no open credit term`, { accountId });
274
+ return { open, scheduled: locked.find((x) => x.source === 'credit' && x.status === 'scheduled') ?? null };
275
+ }
276
+ async function setAutoRenew(t, accountId, autoRenew) {
277
+ const { open, scheduled } = await openCreditTerm(t, accountId);
278
+ const patch = { autoRenew, cancelAtPeriodEnd: !autoRenew };
279
+ if (autoRenew && scheduled) {
280
+ // The scheduled lower plan becomes what the renewal buys.
281
+ patch.nextPlanKey = scheduled.planKey;
282
+ patch.intervalMonths = scheduled.intervalMonths;
283
+ await t.updateTerm(scheduled.id, { status: 'superseded', supersededBy: open.id });
284
+ }
285
+ // Without auto-renew nothing renews, so a renewal preference has no meaning.
286
+ if (!autoRenew)
287
+ patch.nextPlanKey = null;
288
+ await t.updateTerm(open.id, patch);
289
+ const term = { ...open, ...patch, updatedAt: clock.now() };
290
+ return { term, events: [{ type: 'term_changed', accountId, change: 'auto_renew', term }] };
291
+ }
292
+ async function cancel(t, accountId) {
293
+ const { scheduled } = await openCreditTerm(t, accountId);
294
+ if (scheduled)
295
+ await t.updateTerm(scheduled.id, { status: 'expired' });
296
+ const result = await setAutoRenew(t, accountId, false);
297
+ return { term: result.term, events: [{ type: 'term_changed', accountId, change: 'cancelled', term: result.term }] };
298
+ }
299
+ async function cancelNow(t, accountId) {
300
+ const { open, scheduled } = await openCreditTerm(t, accountId);
301
+ if (scheduled)
302
+ await t.updateTerm(scheduled.id, { status: 'expired' });
303
+ const patch = { status: 'expired', autoRenew: false, cancelAtPeriodEnd: false, nextPlanKey: null, graceUntil: null };
304
+ await t.updateTerm(open.id, patch);
305
+ const term = { ...open, ...patch, updatedAt: clock.now() };
306
+ return { term, events: [{ type: 'term_changed', accountId, change: 'cancelled', term }] };
307
+ }
308
+ async function own(run) {
309
+ const result = await terms.transaction((tx) => run(ops(tx)));
310
+ if (options.events) {
311
+ for (const event of result.events) {
312
+ try {
313
+ await options.events(event);
314
+ }
315
+ catch (error) {
316
+ options.onEventError?.(error, event);
317
+ }
318
+ }
319
+ }
320
+ return result;
321
+ }
322
+ return {
323
+ quote: (req) => quoteOn(terms.reader(), ledger, req),
324
+ purchase: (input) => own((o) => o.purchase(input)),
325
+ setAutoRenew: (input) => own((o) => o.setAutoRenew(input)),
326
+ cancel: (input) => own((o) => o.cancel(input)),
327
+ cancelNow: (input) => own((o) => o.cancelNow(input)),
328
+ in: (tx) => ops(tx),
329
+ };
330
+ }
331
+ const sum = (items) => items.reduce((s, i) => s + i.credits, 0);
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Persistence port of terms. Like `IngestStore`, a store exposes its native
3
+ * transaction type and runs in the same transaction as the paired
4
+ * `LedgerStore`, so a term change and its ledger entry commit together. Both
5
+ * implementations (memory, Drizzle) pass `termConformanceCases`.
6
+ *
7
+ * Lock order (design §4.3): host rows → inbox → term rows → account (taken
8
+ * by the ledger, last).
9
+ */
10
+ import type { AccountId } from '../domain/types.js';
11
+ import type { ProviderEnvironment } from '../providers/port.js';
12
+ import type { Term, TermPatch, TermSource, TermStatus } from './types.js';
13
+ export interface TermListOptions {
14
+ statuses?: readonly TermStatus[];
15
+ /** Default 50, newest first. */
16
+ limit?: number;
17
+ }
18
+ export interface TermReader {
19
+ getTerm(id: string): Promise<Term | null>;
20
+ /** The account's terms, newest first. */
21
+ listTerms(accountId: AccountId, options?: TermListOptions): Promise<Term[]>;
22
+ findExternal(source: TermSource, environment: ProviderEnvironment, externalId: string): Promise<Term | null>;
23
+ /**
24
+ * Credit terms with renewal work at `now`, oldest due first: active with
25
+ * auto-renew and `currentPeriodEnd − leadSec ≤ now`, active and ended,
26
+ * scheduled with `startsAt ≤ now`, past_due with `graceUntil ≤ now`.
27
+ */
28
+ listDue(now: Date, leadSec: number, limit: number): Promise<Term[]>;
29
+ }
30
+ export interface TermTx extends TermReader {
31
+ /**
32
+ * Lock the account for term changes, then `SELECT … FOR UPDATE` its
33
+ * scheduled and open terms (every source), oldest first. The account lock
34
+ * holds even when it has no terms yet, so two first writers (a purchase and
35
+ * a provider snapshot) serialize.
36
+ */
37
+ lockAccountTerms(accountId: AccountId): Promise<Term[]>;
38
+ lockTerm(id: string): Promise<Term | null>;
39
+ lockExternal(source: TermSource, environment: ProviderEnvironment, externalId: string): Promise<Term | null>;
40
+ /**
41
+ * Insert a term. A unique conflict — `(source, environment, externalId)`,
42
+ * one open credit term or one scheduled term per account — answers
43
+ * `{inserted:false}`, writes nothing and does not abort the transaction.
44
+ */
45
+ insertTerm(term: Term): Promise<{
46
+ inserted: boolean;
47
+ }>;
48
+ updateTerm(id: string, patch: TermPatch): Promise<void>;
49
+ }
50
+ export interface TermStore<TTx = unknown> {
51
+ /** Must be the same transaction the paired `LedgerStore` runs in. */
52
+ transaction<T>(fn: (tx: TTx) => Promise<T>): Promise<T>;
53
+ bind(tx: TTx): TermTx;
54
+ reader(): TermReader;
55
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ /** Pure term rules shared by the stores, the plans service and renewal. */
2
+ import type { Term } from './types.js';
3
+ /** `from` + `months` catalog months of `termDays` days each (design §4.8: now + months × termDays). */
4
+ export declare function addTermMonths(from: Date, months: number, termDays: number): Date;
5
+ /** Whether the term renews at its period end: auto-renew on and not cancelled. */
6
+ export declare function renews(t: Term): boolean;
7
+ export declare function addDays(from: Date, days: number): Date;
8
+ /** Whether a credit term has renewal work at `now` (the `listDue` predicate). */
9
+ export declare function isRenewalDue(t: Term, now: Date, leadSec: number): boolean;
10
+ /** When `isRenewalDue` turns true, for ordering. */
11
+ export declare function renewalDueAt(t: Term, leadSec: number): number;
@@ -0,0 +1,36 @@
1
+ const DAY_MS = 86_400_000;
2
+ /** `from` + `months` catalog months of `termDays` days each (design §4.8: now + months × termDays). */
3
+ export function addTermMonths(from, months, termDays) {
4
+ return new Date(from.getTime() + months * termDays * DAY_MS);
5
+ }
6
+ /** Whether the term renews at its period end: auto-renew on and not cancelled. */
7
+ export function renews(t) {
8
+ return t.autoRenew && !t.cancelAtPeriodEnd;
9
+ }
10
+ export function addDays(from, days) {
11
+ return new Date(from.getTime() + days * DAY_MS);
12
+ }
13
+ /** Whether a credit term has renewal work at `now` (the `listDue` predicate). */
14
+ export function isRenewalDue(t, now, leadSec) {
15
+ if (t.source !== 'credit')
16
+ return false;
17
+ const at = now.getTime();
18
+ switch (t.status) {
19
+ case 'active':
20
+ return t.currentPeriodEnd.getTime() <= at || (t.autoRenew && t.currentPeriodEnd.getTime() - leadSec * 1000 <= at);
21
+ case 'scheduled':
22
+ return t.startsAt.getTime() <= at;
23
+ case 'past_due':
24
+ return t.graceUntil !== null && t.graceUntil.getTime() <= at;
25
+ default:
26
+ return false;
27
+ }
28
+ }
29
+ /** When `isRenewalDue` turns true, for ordering. */
30
+ export function renewalDueAt(t, leadSec) {
31
+ if (t.status === 'scheduled')
32
+ return t.startsAt.getTime();
33
+ if (t.status === 'past_due')
34
+ return t.graceUntil?.getTime() ?? 0;
35
+ return t.currentPeriodEnd.getTime() - (t.autoRenew ? leadSec * 1000 : 0);
36
+ }