@tofound/billing 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +136 -1
  2. package/README.md +73 -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/hostkit/adjustments.d.ts +65 -0
  11. package/dist/hostkit/adjustments.js +84 -0
  12. package/dist/hostkit/index.d.ts +9 -0
  13. package/dist/hostkit/index.js +9 -0
  14. package/dist/hostkit/legacy-ledger.d.ts +87 -0
  15. package/dist/hostkit/legacy-ledger.js +111 -0
  16. package/dist/hostkit/quote-wire.d.ts +73 -0
  17. package/dist/hostkit/quote-wire.js +50 -0
  18. package/dist/index.d.ts +10 -0
  19. package/dist/index.js +9 -0
  20. package/dist/providers/apple/events.d.ts +24 -0
  21. package/dist/providers/apple/events.js +232 -0
  22. package/dist/providers/apple/index.d.ts +54 -0
  23. package/dist/providers/apple/index.js +231 -0
  24. package/dist/providers/apple/jws.d.ts +50 -0
  25. package/dist/providers/apple/jws.js +206 -0
  26. package/dist/providers/google/api.d.ts +57 -0
  27. package/dist/providers/google/api.js +226 -0
  28. package/dist/providers/google/events.d.ts +46 -0
  29. package/dist/providers/google/events.js +135 -0
  30. package/dist/providers/google/index.d.ts +37 -0
  31. package/dist/providers/google/index.js +228 -0
  32. package/dist/providers/polar/events.d.ts +17 -0
  33. package/dist/providers/polar/events.js +213 -0
  34. package/dist/providers/polar/index.d.ts +50 -0
  35. package/dist/providers/polar/index.js +271 -0
  36. package/dist/providers/polar/signature.d.ts +23 -0
  37. package/dist/providers/polar/signature.js +52 -0
  38. package/dist/providers/port.d.ts +6 -0
  39. package/dist/providers/sepay/index.js +29 -0
  40. package/dist/renewal/renewal.d.ts +69 -0
  41. package/dist/renewal/renewal.js +198 -0
  42. package/dist/stores/testing.d.ts +4 -2
  43. package/dist/stores/testing.js +4 -2
  44. package/dist/terms/conformance.d.ts +17 -0
  45. package/dist/terms/conformance.js +198 -0
  46. package/dist/terms/decide.d.ts +97 -0
  47. package/dist/terms/decide.js +176 -0
  48. package/dist/terms/drizzle.d.ts +12 -0
  49. package/dist/terms/drizzle.js +131 -0
  50. package/dist/terms/memory.d.ts +23 -0
  51. package/dist/terms/memory.js +126 -0
  52. package/dist/terms/plans.d.ts +85 -0
  53. package/dist/terms/plans.js +331 -0
  54. package/dist/terms/ports.d.ts +55 -0
  55. package/dist/terms/ports.js +1 -0
  56. package/dist/terms/rules.d.ts +11 -0
  57. package/dist/terms/rules.js +36 -0
  58. package/dist/terms/schema.d.ts +711 -0
  59. package/dist/terms/schema.js +70 -0
  60. package/dist/terms/snapshot.d.ts +20 -0
  61. package/dist/terms/snapshot.js +134 -0
  62. package/dist/terms/types.d.ts +85 -0
  63. package/dist/terms/types.js +4 -0
  64. package/docs/API.md +415 -6
  65. package/docs/MIGRATION-LOHI.md +237 -0
  66. package/docs/SCHEMA.md +57 -2
  67. package/package.json +22 -1
@@ -0,0 +1,176 @@
1
+ import { BillingError } from '../domain/errors.js';
2
+ import { mulDivRound } from '../domain/money.js';
3
+ import { entitledUntil } from '../entitlement/resolve.js';
4
+ import { addTermMonths, renews } from './rules.js';
5
+ import { OPEN_TERM_STATUSES } from './types.js';
6
+ const OPEN = new Set(OPEN_TERM_STATUSES);
7
+ /**
8
+ * Decide a credit purchase of `months` of `plan` against the account's open
9
+ * and scheduled terms. Throws `plan_not_found`, `offer_not_found` (the plan is
10
+ * not sold for these months in this market) or `invalid_input` (the free plan).
11
+ */
12
+ export function decidePlanPurchase(terms, req, catalog, now) {
13
+ const plan = catalog.plan(req.plan);
14
+ if (plan.free)
15
+ throw new BillingError('invalid_input', `the free plan ${plan.key} cannot be bought`, { plan: plan.key });
16
+ if (!Number.isSafeInteger(req.months) || req.months <= 0) {
17
+ throw new BillingError('invalid_input', `months must be a positive integer, got ${req.months}`, { months: req.months });
18
+ }
19
+ const offer = catalog.creditOffer(plan.key, req.market, req.months);
20
+ if (!offer) {
21
+ throw new BillingError('offer_not_found', `plan ${plan.key} is not sold for ${req.months} months in ${req.market}`, {
22
+ plan: plan.key,
23
+ months: req.months,
24
+ market: req.market,
25
+ });
26
+ }
27
+ const { graceDays, termDays } = catalog.policies;
28
+ const rankOf = (t) => catalog.findPlan(t.planKey)?.rank ?? -1;
29
+ const end = (from, months) => addTermMonths(from, months, termDays);
30
+ const base = { plan: plan.key, months: req.months, market: req.market, listPrice: offer.credits };
31
+ const decision = (d) => ({ ...base, ...d });
32
+ const mine = terms.filter((t) => t.accountId === req.accountId);
33
+ const entitledProviders = mine.filter((t) => t.source !== 'credit' && entitledUntil(t, now, graceDays));
34
+ const open = mine.find((t) => t.source === 'credit' && OPEN.has(t.status)) ?? null;
35
+ const scheduled = mine.find((t) => t.source === 'credit' && t.status === 'scheduled') ?? null;
36
+ // S3: an auto-renewing provider subscription of ≥ rank already covers it.
37
+ const covering = entitledProviders.find((t) => renews(t) && rankOf(t) >= plan.rank);
38
+ if (covering) {
39
+ return decision({
40
+ kind: 'blocked',
41
+ charge: offer.credits,
42
+ reason: { code: 'covered_by_subscription' },
43
+ effect: { type: 'none' },
44
+ periodStart: null,
45
+ periodEnd: null,
46
+ scheduled: false,
47
+ });
48
+ }
49
+ const live = open && entitledUntil(open, now, graceDays) ? open : null;
50
+ if (!live) {
51
+ // A non-renewing subscription of ≥ rank runs out first: start after it (S3b).
52
+ const ending = entitledProviders
53
+ .filter((t) => rankOf(t) >= plan.rank)
54
+ .sort((a, b) => b.currentPeriodEnd.getTime() - a.currentPeriodEnd.getTime())[0];
55
+ if (ending)
56
+ return schedule(ending.currentPeriodEnd, { code: 'scheduled_after_subscription' });
57
+ const items = [{ months: req.months, credits: offer.credits }];
58
+ return decision({
59
+ kind: 'new',
60
+ charge: offer.credits,
61
+ reason: { code: 'list_price' },
62
+ effect: { type: 'create', close: open, scheduled, startsAt: now, periodEnd: end(now, req.months), items },
63
+ periodStart: now,
64
+ periodEnd: end(now, req.months),
65
+ scheduled: false,
66
+ });
67
+ }
68
+ if (live.status === 'past_due' || live.status === 'grace') {
69
+ // Paying the unpaid renewal: the period continues from the old end.
70
+ const periodEnd = end(live.currentPeriodEnd, req.months);
71
+ return decision({
72
+ kind: 'renew',
73
+ charge: offer.credits,
74
+ reason: { code: 'list_price' },
75
+ effect: { type: 'renew', term: live, periodStart: live.currentPeriodEnd, periodEnd, items: [{ months: req.months, credits: offer.credits }] },
76
+ periodStart: live.currentPeriodEnd,
77
+ periodEnd,
78
+ scheduled: false,
79
+ });
80
+ }
81
+ const currentRank = rankOf(live);
82
+ if (live.planKey === plan.key) {
83
+ // S2: same plan extends the term, charged in full.
84
+ const periodEnd = end(live.currentPeriodEnd, req.months);
85
+ return decision({
86
+ kind: 'extend',
87
+ charge: offer.credits,
88
+ reason: { code: 'list_price' },
89
+ effect: { type: 'extend', term: live, periodEnd, items: [...itemsOf(live), { months: req.months, credits: offer.credits }], scheduled },
90
+ periodStart: live.currentPeriodStart,
91
+ periodEnd,
92
+ scheduled: false,
93
+ });
94
+ }
95
+ if (plan.rank > currentRank)
96
+ return upgrade(live, plan);
97
+ // S3b: a lower plan never moves money now.
98
+ if (renews(live)) {
99
+ return decision({
100
+ kind: 'downgrade',
101
+ charge: 0,
102
+ reason: { code: 'downgrade' },
103
+ effect: { type: 'next_plan', term: live },
104
+ periodStart: live.currentPeriodEnd,
105
+ periodEnd: end(live.currentPeriodEnd, req.months),
106
+ scheduled: true,
107
+ });
108
+ }
109
+ return schedule(live.currentPeriodEnd, { code: 'downgrade' });
110
+ function schedule(startsAt, reason) {
111
+ const periodEnd = end(startsAt, req.months);
112
+ return decision({
113
+ kind: 'downgrade',
114
+ charge: 0,
115
+ reason,
116
+ effect: { type: 'schedule', existing: scheduled, startsAt, periodEnd },
117
+ periodStart: startsAt,
118
+ periodEnd,
119
+ scheduled: true,
120
+ });
121
+ }
122
+ function upgrade(term, next) {
123
+ // The new plan's value for the same purchases that make up this period.
124
+ const items = itemsOf(term).map((item) => {
125
+ const o = catalog.creditOffer(next.key, req.market, item.months);
126
+ if (!o) {
127
+ throw new BillingError('offer_not_found', `plan ${next.key} is not sold for ${item.months} months in ${req.market}`, {
128
+ plan: next.key,
129
+ months: item.months,
130
+ market: req.market,
131
+ });
132
+ }
133
+ return { months: item.months, credits: o.credits };
134
+ });
135
+ const newValue = items.reduce((sum, i) => sum + i.credits, 0);
136
+ const paid = term.priceMinor ?? 0;
137
+ const diff = Math.max(0, newValue - paid);
138
+ // remaining_time: ceil(remaining/total × (offerNew − paid)); the end date is kept.
139
+ const charge = catalog.policies.upgradeProration === 'remaining_time' ? remainingShare(diff, term, now) : diff;
140
+ return {
141
+ ...base,
142
+ listPrice: diff,
143
+ kind: 'upgrade',
144
+ charge,
145
+ reason: { code: catalog.policies.upgradeProration === 'remaining_time' ? 'prorated_upgrade' : 'upgrade' },
146
+ effect: { type: 'upgrade', term, items },
147
+ periodStart: term.currentPeriodStart,
148
+ periodEnd: term.currentPeriodEnd,
149
+ scheduled: false,
150
+ };
151
+ }
152
+ }
153
+ /** The purchases of a credit term's current period (one item for a term from before items were kept). */
154
+ export function itemsOf(term) {
155
+ if (term.periodItems?.length)
156
+ return term.periodItems.map((i) => ({ ...i }));
157
+ return [{ months: term.intervalMonths, credits: term.priceMinor ?? 0 }];
158
+ }
159
+ /**
160
+ * Credits a superseded credit term returns (S4): the unused share of what
161
+ * its period is worth, rounded in the customer's favour. Nothing for a term
162
+ * whose period was never paid (past_due).
163
+ */
164
+ export function supersedeRefund(term, now) {
165
+ if (term.status !== 'active' || !term.priceMinor)
166
+ return 0;
167
+ return remainingShare(term.priceMinor, term, now);
168
+ }
169
+ /** `amount` × the unused share of the term's current period at `now`, rounded up. */
170
+ function remainingShare(amount, term, now) {
171
+ const total = term.currentPeriodEnd.getTime() - term.currentPeriodStart.getTime();
172
+ if (total <= 0)
173
+ return 0;
174
+ const remaining = Math.min(total, Math.max(0, term.currentPeriodEnd.getTime() - now.getTime()));
175
+ return mulDivRound(amount, remaining, total, 'ceil');
176
+ }
@@ -0,0 +1,12 @@
1
+ import type { PgTable } from 'drizzle-orm/pg-core';
2
+ import type { AnyPgDatabase, AnyPgTransaction } from '../drizzle/store.js';
3
+ import type { TermStore } from './ports.js';
4
+ export interface DrizzleTermStoreOptions {
5
+ db: AnyPgDatabase;
6
+ /** The host's term tables (`createTermTables(...)`), whatever their account column type. */
7
+ tables: {
8
+ billingTerms: PgTable;
9
+ billingTermAccounts: PgTable;
10
+ };
11
+ }
12
+ export declare function createDrizzleTermStore(options: DrizzleTermStoreOptions): TermStore<AnyPgTransaction>;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Postgres `TermStore` over `billing_terms`. Runs in the same Drizzle
3
+ * transaction as `createDrizzleLedgerStore` on the same `db`, so a term and
4
+ * its ledger entry commit together. Expects READ COMMITTED (the Postgres
5
+ * default).
6
+ */
7
+ import { and, asc, desc, eq, inArray, isNotNull, lte, or } from 'drizzle-orm';
8
+ import { renewalDueAt } from './rules.js';
9
+ import { OPEN_TERM_STATUSES } from './types.js';
10
+ const LOCKED_STATUSES = ['scheduled', ...OPEN_TERM_STATUSES];
11
+ export function createDrizzleTermStore(options) {
12
+ const { db } = options;
13
+ // The account column's TS type is the host's; the library reads and writes it as a string.
14
+ const terms = options.tables.billingTerms;
15
+ const guards = options.tables.billingTermAccounts;
16
+ const toTerm = (r) => ({
17
+ id: r.id,
18
+ accountId: String(r.accountId),
19
+ source: r.source,
20
+ environment: r.environment,
21
+ externalId: r.externalId,
22
+ planKey: r.planKey,
23
+ status: r.status,
24
+ market: r.market,
25
+ startsAt: r.startsAt,
26
+ currentPeriodStart: r.currentPeriodStart,
27
+ currentPeriodEnd: r.currentPeriodEnd,
28
+ intervalMonths: r.intervalMonths,
29
+ autoRenew: r.autoRenew,
30
+ cancelAtPeriodEnd: r.cancelAtPeriodEnd,
31
+ graceUntil: r.graceUntil,
32
+ nextPlanKey: r.nextPlanKey,
33
+ priceMinor: r.priceMinor,
34
+ priceUnit: r.priceUnit,
35
+ periodItems: r.periodItems ?? null,
36
+ supersededBy: r.supersededBy,
37
+ lastEventAt: r.lastEventAt,
38
+ lastEventRef: r.lastEventRef,
39
+ meta: r.meta ?? null,
40
+ createdAt: r.createdAt,
41
+ updatedAt: r.updatedAt,
42
+ });
43
+ const externalKey = (source, environment, externalId) => and(eq(terms.source, source), eq(terms.environment, environment), eq(terms.externalId, externalId));
44
+ const reader = (ex) => ({
45
+ async getTerm(id) {
46
+ const [row] = await ex.select().from(terms).where(eq(terms.id, id));
47
+ return row ? toTerm(row) : null;
48
+ },
49
+ async listTerms(accountId, opts = {}) {
50
+ const rows = await ex
51
+ .select()
52
+ .from(terms)
53
+ .where(and(eq(terms.accountId, accountId), opts.statuses ? inArray(terms.status, [...opts.statuses]) : undefined))
54
+ .orderBy(desc(terms.createdAt), desc(terms.id))
55
+ .limit(opts.limit ?? 50);
56
+ return rows.map(toTerm);
57
+ },
58
+ async findExternal(source, environment, externalId) {
59
+ const [row] = await ex.select().from(terms).where(externalKey(source, environment, externalId));
60
+ return row ? toTerm(row) : null;
61
+ },
62
+ async listDue(now, leadSec, limit) {
63
+ // One query per branch of `isRenewalDue`, each served by its partial index.
64
+ const lead = new Date(now.getTime() + leadSec * 1000);
65
+ const credit = eq(terms.source, 'credit');
66
+ const [active, scheduled, pastDue] = await Promise.all([
67
+ ex
68
+ .select()
69
+ .from(terms)
70
+ .where(and(credit, eq(terms.status, 'active'), lte(terms.currentPeriodEnd, lead), or(eq(terms.autoRenew, true), lte(terms.currentPeriodEnd, now))))
71
+ .orderBy(asc(terms.currentPeriodEnd))
72
+ .limit(limit),
73
+ ex
74
+ .select()
75
+ .from(terms)
76
+ .where(and(credit, eq(terms.status, 'scheduled'), lte(terms.startsAt, now)))
77
+ .orderBy(asc(terms.startsAt))
78
+ .limit(limit),
79
+ ex
80
+ .select()
81
+ .from(terms)
82
+ .where(and(credit, eq(terms.status, 'past_due'), isNotNull(terms.graceUntil), lte(terms.graceUntil, now)))
83
+ .orderBy(asc(terms.graceUntil))
84
+ .limit(limit),
85
+ ]);
86
+ return [...active, ...scheduled, ...pastDue]
87
+ .map(toTerm)
88
+ .sort((a, b) => renewalDueAt(a, leadSec) - renewalDueAt(b, leadSec))
89
+ .slice(0, limit);
90
+ },
91
+ });
92
+ const bind = (tx) => ({
93
+ ...reader(tx),
94
+ async lockAccountTerms(accountId) {
95
+ // The guard row first: it exists (and blocks) even before the account's first term.
96
+ await tx.insert(guards).values({ accountId: accountId }).onConflictDoNothing();
97
+ await tx.select({ accountId: guards.accountId }).from(guards).where(eq(guards.accountId, accountId)).for('update');
98
+ const rows = await tx
99
+ .select()
100
+ .from(terms)
101
+ .where(and(eq(terms.accountId, accountId), inArray(terms.status, LOCKED_STATUSES)))
102
+ .orderBy(asc(terms.createdAt), asc(terms.id))
103
+ .for('update');
104
+ return rows.map(toTerm);
105
+ },
106
+ async lockTerm(id) {
107
+ const [row] = await tx.select().from(terms).where(eq(terms.id, id)).for('update');
108
+ return row ? toTerm(row) : null;
109
+ },
110
+ async lockExternal(source, environment, externalId) {
111
+ const [row] = await tx.select().from(terms).where(externalKey(source, environment, externalId)).for('update');
112
+ return row ? toTerm(row) : null;
113
+ },
114
+ async insertTerm(t) {
115
+ const inserted = await tx
116
+ .insert(terms)
117
+ .values({ ...t, accountId: t.accountId })
118
+ .onConflictDoNothing()
119
+ .returning({ id: terms.id });
120
+ return { inserted: inserted.length === 1 };
121
+ },
122
+ async updateTerm(id, patch) {
123
+ await tx.update(terms).set({ ...patch, updatedAt: new Date() }).where(eq(terms.id, id));
124
+ },
125
+ });
126
+ return {
127
+ transaction: (fn) => db.transaction((tx) => fn(tx)),
128
+ bind,
129
+ reader: () => reader(db),
130
+ };
131
+ }
@@ -0,0 +1,23 @@
1
+ import type { AccountId } from '../domain/types.js';
2
+ import type { MemoryTx } from '../stores/memory.js';
3
+ import type { TermStore } from './ports.js';
4
+ import { type Term } from './types.js';
5
+ /** Anything that opens memory transactions: a memory ledger store, or another wrapper around one. */
6
+ export interface MemoryTransactor {
7
+ transaction<T>(fn: (tx: MemoryTx) => Promise<T>): Promise<T>;
8
+ }
9
+ export interface MemoryTermStore extends TermStore<MemoryTx> {
10
+ /** Committed terms of one account, oldest first (test inspection). */
11
+ dump(accountId: AccountId): Term[];
12
+ }
13
+ /**
14
+ * In-process `TermStore`. It runs inside `base`'s transactions (one store-wide
15
+ * mutex) and commits its staged rows when `fn` resolves, so a term and its
16
+ * ledger entry land together or not at all. To use terms and the inbox in
17
+ * one transaction, chain the wrappers:
18
+ *
19
+ * const ledgerStore = createMemoryLedgerStore()
20
+ * const termStore = createMemoryTermStore(ledgerStore)
21
+ * const ingestStore = createMemoryIngestStore({ ...ledgerStore, transaction: termStore.transaction })
22
+ */
23
+ export declare function createMemoryTermStore(base: MemoryTransactor): MemoryTermStore;
@@ -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>;