@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,198 @@
1
+ import { isBillingError } from '../domain/errors.js';
2
+ import { addDays, addTermMonths, renews } from '../terms/rules.js';
3
+ const isOpenCredit = (t) => t.source === 'credit' && (t.status === 'active' || t.status === 'past_due' || t.status === 'grace');
4
+ export function createRenewal(options) {
5
+ const { ledger, terms, catalog } = options;
6
+ const clock = options.clock ?? { now: () => new Date() };
7
+ const { graceDays, termDays, renewalLeadSec } = catalog.policies;
8
+ function ops(tx) {
9
+ const t = terms.bind(tx);
10
+ const l = ledger.in(tx);
11
+ return {
12
+ async renewTerm(termId, now = clock.now()) {
13
+ const peek = await t.getTerm(termId);
14
+ if (!peek)
15
+ return { results: [], events: [] };
16
+ // Lock the account's term rows in the one order every path uses.
17
+ const locked = await t.lockAccountTerms(peek.accountId);
18
+ const term = locked.find((x) => x.id === termId);
19
+ if (!term)
20
+ return run(skip(peek, 'not_open'));
21
+ return processTerm(t, l, term, locked, now);
22
+ },
23
+ async retryPastDue(accountId, now = clock.now()) {
24
+ const locked = await t.lockAccountTerms(accountId);
25
+ const out = { results: [], events: [] };
26
+ for (const term of locked.filter((x) => x.source === 'credit' && x.status === 'past_due')) {
27
+ const r = await processTerm(t, l, term, locked, now);
28
+ out.results.push(...r.results);
29
+ out.events.push(...r.events);
30
+ }
31
+ return out;
32
+ },
33
+ };
34
+ }
35
+ async function processTerm(t, l, term, locked, now) {
36
+ if (term.source !== 'credit')
37
+ return run(skip(term, 'not_credit'));
38
+ const at = now.getTime();
39
+ switch (term.status) {
40
+ case 'active': {
41
+ if (!renews(term))
42
+ return at >= term.currentPeriodEnd.getTime() ? expire(t, term) : run(skip(term, 'not_due'));
43
+ if (term.currentPeriodEnd.getTime() - renewalLeadSec * 1000 > at)
44
+ return run(skip(term, 'not_due'));
45
+ return charge(t, l, term, term.currentPeriodEnd, 'renewed', now);
46
+ }
47
+ case 'past_due':
48
+ if (term.graceUntil && at >= term.graceUntil.getTime())
49
+ return expire(t, term);
50
+ return charge(t, l, term, term.currentPeriodEnd, 'renewed', now);
51
+ case 'scheduled': {
52
+ if (term.startsAt.getTime() > at)
53
+ return run(skip(term, 'not_due'));
54
+ const out = { results: [], events: [] };
55
+ const before = locked.find((x) => x.id !== term.id && isOpenCredit(x));
56
+ if (before) {
57
+ // The term it follows must be over first (one open credit term per account).
58
+ const ended = before.status === 'active' && !renews(before) && at >= before.currentPeriodEnd.getTime();
59
+ const lapsed = before.status === 'past_due' && before.graceUntil !== null && at >= before.graceUntil.getTime();
60
+ if (!ended && !lapsed)
61
+ return run(skip(term, 'predecessor_open'));
62
+ const r = await expire(t, before);
63
+ out.results.push(...r.results);
64
+ out.events.push(...r.events);
65
+ }
66
+ const r = await charge(t, l, term, term.startsAt, 'activated', now);
67
+ return { results: [...out.results, ...r.results], events: [...out.events, ...r.events] };
68
+ }
69
+ default:
70
+ return run(skip(term, 'not_open'));
71
+ }
72
+ }
73
+ /** Charge the next period, starting at `from`; on failure the term goes past_due. */
74
+ async function charge(t, l, term, from, outcome, now) {
75
+ const planKey = term.nextPlanKey ?? term.planKey;
76
+ const market = (await options.marketOf?.(term.accountId)) ?? term.market;
77
+ const offer = market ? catalog.creditOffer(planKey, market, term.intervalMonths) : undefined;
78
+ if (!offer)
79
+ return pastDue(t, term, from, now, 'offer_not_found', null, await l.balance(term.accountId));
80
+ let entry;
81
+ let ledgerEvents;
82
+ try {
83
+ const posted = await l.debit({
84
+ accountId: term.accountId,
85
+ kind: 'plan_renewal',
86
+ amount: offer.credits,
87
+ idempotencyKey: `renew:${term.id}:${from.toISOString()}`,
88
+ source: { type: 'term', id: term.id },
89
+ meta: { plan: planKey, months: term.intervalMonths, market },
90
+ });
91
+ entry = posted.entry;
92
+ ledgerEvents = posted.events;
93
+ }
94
+ catch (error) {
95
+ if (!isBillingError(error, 'insufficient_credits'))
96
+ throw error;
97
+ return pastDue(t, term, from, now, 'insufficient_credits', offer.credits, Number(error.details['balance'] ?? 0));
98
+ }
99
+ const patch = {
100
+ status: 'active',
101
+ planKey,
102
+ nextPlanKey: null,
103
+ graceUntil: null,
104
+ market,
105
+ currentPeriodStart: from,
106
+ currentPeriodEnd: addTermMonths(from, term.intervalMonths, termDays),
107
+ periodItems: [{ months: term.intervalMonths, credits: offer.credits }],
108
+ priceMinor: offer.credits,
109
+ priceUnit: catalog.creditUnit.code,
110
+ };
111
+ const next = await write(t, term, patch);
112
+ const change = outcome;
113
+ return {
114
+ results: [{ termId: term.id, accountId: term.accountId, outcome, entry, term: next }],
115
+ events: [{ type: 'term_changed', accountId: term.accountId, change, term: next }, ...ledgerEvents],
116
+ };
117
+ }
118
+ async function pastDue(t, term, from, now, reason, required, balance) {
119
+ const failed = (next) => ({
120
+ type: 'renewal_failed',
121
+ accountId: term.accountId,
122
+ term: next,
123
+ reason,
124
+ required,
125
+ balance,
126
+ shortfall: required === null ? null : Math.max(0, required - balance),
127
+ });
128
+ // An early attempt inside the lead: the period is still paid, so it stays active and the next run retries.
129
+ if (term.status === 'active' && now < term.currentPeriodEnd) {
130
+ return { results: [{ termId: term.id, accountId: term.accountId, outcome: 'skipped', reason, entry: null, term }], events: [failed(term)] };
131
+ }
132
+ const patch = { status: 'past_due' };
133
+ if (term.status === 'scheduled') {
134
+ // Never paid: an empty period at its start, so a retry charges from there.
135
+ Object.assign(patch, { currentPeriodStart: from, currentPeriodEnd: from, graceUntil: addDays(from, graceDays), planKey: term.nextPlanKey ?? term.planKey, nextPlanKey: null });
136
+ }
137
+ else if (term.status !== 'past_due') {
138
+ patch.graceUntil = addDays(term.currentPeriodEnd, graceDays);
139
+ }
140
+ const next = await write(t, term, patch);
141
+ const events = [failed(next)];
142
+ if (term.status !== 'past_due')
143
+ events.unshift({ type: 'term_changed', accountId: term.accountId, change: 'past_due', term: next });
144
+ return { results: [{ termId: term.id, accountId: term.accountId, outcome: 'past_due', reason, entry: null, term: next }], events };
145
+ }
146
+ async function expire(t, term) {
147
+ const next = await write(t, term, { status: 'expired' });
148
+ return {
149
+ results: [{ termId: term.id, accountId: term.accountId, outcome: 'expired', term: next }],
150
+ events: [{ type: 'term_changed', accountId: term.accountId, change: 'expired', term: next }],
151
+ };
152
+ }
153
+ async function write(t, term, patch) {
154
+ await t.updateTerm(term.id, patch);
155
+ return { ...term, ...patch, updatedAt: clock.now() };
156
+ }
157
+ async function emit(events) {
158
+ if (!options.events)
159
+ return;
160
+ for (const event of events) {
161
+ try {
162
+ await options.events(event);
163
+ }
164
+ catch (error) {
165
+ options.onEventError?.(error, event);
166
+ }
167
+ }
168
+ }
169
+ async function own(fn) {
170
+ const result = await terms.transaction((tx) => fn(ops(tx)));
171
+ await emit(result.events);
172
+ return result;
173
+ }
174
+ return {
175
+ renewTerm: (termId, now) => own((o) => o.renewTerm(termId, now)),
176
+ retryPastDue: (accountId, now) => own((o) => o.retryPastDue(accountId, now)),
177
+ async renewDue(input = {}) {
178
+ const now = input.now ?? clock.now();
179
+ const limit = Math.min(Math.max(input.limit ?? 100, 1), 1000);
180
+ const due = await terms.reader().listDue(now, renewalLeadSec, limit);
181
+ const out = { results: [], events: [] };
182
+ for (const term of due) {
183
+ try {
184
+ const r = await own((o) => o.renewTerm(term.id, now));
185
+ out.results.push(...r.results);
186
+ out.events.push(...r.events);
187
+ }
188
+ catch (error) {
189
+ out.results.push({ termId: term.id, accountId: term.accountId, outcome: 'error', reason: error instanceof Error ? error.message : String(error) });
190
+ }
191
+ }
192
+ return out;
193
+ },
194
+ in: (tx) => ops(tx),
195
+ };
196
+ }
197
+ const run = (result) => ({ results: [result], events: [] });
198
+ const skip = (term, reason) => ({ termId: term.id, accountId: term.accountId, outcome: 'skipped', reason });
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * `@tofound/billing/testing` — the kit hosts use to prove their own stores
3
3
  * and charge paths: the store conformance suite, the ledger invariant check,
4
- * the quote/settle conformance assertion, the ingest store conformance suite
5
- * and the memory stores.
4
+ * the quote/settle conformance assertion, the ingest and term store
5
+ * conformance suites and the memory stores.
6
6
  */
7
7
  export { assertLedgerInvariants, ledgerConformanceCases, type ConformanceCase, type LedgerConformanceTarget, } from './conformance.js';
8
8
  export { createMemoryLedgerStore, type MemoryLedgerStore, type MemoryTx } from './memory.js';
9
9
  export { assertQuoteMatchesSettlement, type ObservedSettlement } from '../quote/conformance.js';
10
10
  export { ingestConformanceCases, type IngestConformanceCase, type IngestConformanceTarget } from '../inbox/conformance.js';
11
11
  export { createMemoryIngestStore, type MemoryIngestStore } from '../inbox/memory.js';
12
+ export { termConformanceCases, type TermConformanceCase, type TermConformanceTarget } from '../terms/conformance.js';
13
+ export { createMemoryTermStore, type MemoryTermStore } from '../terms/memory.js';
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * `@tofound/billing/testing` — the kit hosts use to prove their own stores
3
3
  * and charge paths: the store conformance suite, the ledger invariant check,
4
- * the quote/settle conformance assertion, the ingest store conformance suite
5
- * and the memory stores.
4
+ * the quote/settle conformance assertion, the ingest and term store
5
+ * conformance suites and the memory stores.
6
6
  */
7
7
  export { assertLedgerInvariants, ledgerConformanceCases, } from './conformance.js';
8
8
  export { createMemoryLedgerStore } from './memory.js';
9
9
  export { assertQuoteMatchesSettlement } from '../quote/conformance.js';
10
10
  export { ingestConformanceCases } from '../inbox/conformance.js';
11
11
  export { createMemoryIngestStore } from '../inbox/memory.js';
12
+ export { termConformanceCases } from '../terms/conformance.js';
13
+ export { createMemoryTermStore } from '../terms/memory.js';
@@ -0,0 +1,17 @@
1
+ import type { TermStore } from './ports.js';
2
+ /**
3
+ * The term store conformance suite. Every `TermStore` — memory, the Drizzle
4
+ * store, a host adapter — must pass all of it. Each case throws on failure:
5
+ *
6
+ * for (const c of termConformanceCases) test(c.name, () => c.run(target))
7
+ */
8
+ export interface TermConformanceTarget<TTx = unknown> {
9
+ store: TermStore<TTx>;
10
+ /** A fresh, never-used account id of the host's type. */
11
+ newAccountId(): string;
12
+ }
13
+ export interface TermConformanceCase {
14
+ name: string;
15
+ run<TTx>(target: TermConformanceTarget<TTx>): Promise<void>;
16
+ }
17
+ export declare const termConformanceCases: TermConformanceCase[];
@@ -0,0 +1,198 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ function check(ok, message) {
3
+ if (!ok)
4
+ throw new Error(`term conformance: ${message}`);
5
+ }
6
+ function equal(actual, expected, what) {
7
+ check(actual === expected, `${what}: expected ${String(expected)}, got ${String(actual)}`);
8
+ }
9
+ const uid = () => randomUUID();
10
+ const at = (iso) => new Date(iso);
11
+ const ROLLBACK = new Error('term conformance rollback');
12
+ function creditTerm(accountId, over = {}) {
13
+ const start = at('2026-01-01T00:00:00Z');
14
+ return {
15
+ id: uid(),
16
+ accountId,
17
+ source: 'credit',
18
+ environment: null,
19
+ externalId: null,
20
+ planKey: 'pro',
21
+ status: 'active',
22
+ market: 'vn',
23
+ startsAt: start,
24
+ currentPeriodStart: start,
25
+ currentPeriodEnd: at('2026-01-31T00:00:00Z'),
26
+ intervalMonths: 1,
27
+ autoRenew: true,
28
+ cancelAtPeriodEnd: false,
29
+ graceUntil: null,
30
+ nextPlanKey: null,
31
+ priceMinor: 9_900_000,
32
+ priceUnit: 'LT',
33
+ periodItems: [{ months: 1, credits: 9_900_000 }],
34
+ supersededBy: null,
35
+ lastEventAt: null,
36
+ lastEventRef: null,
37
+ meta: { purchaseKey: 'k1' },
38
+ createdAt: start,
39
+ updatedAt: start,
40
+ ...over,
41
+ };
42
+ }
43
+ function providerTerm(accountId, over = {}) {
44
+ return creditTerm(accountId, {
45
+ source: 'polar',
46
+ environment: 'sandbox',
47
+ externalId: `sub_${uid()}`,
48
+ market: null,
49
+ priceMinor: 199_000,
50
+ priceUnit: 'VND',
51
+ periodItems: null,
52
+ meta: null,
53
+ lastEventAt: at('2026-01-01T00:00:00Z'),
54
+ lastEventRef: 'evt_1',
55
+ ...over,
56
+ });
57
+ }
58
+ async function insert(t, term) {
59
+ return t.store.transaction((tx) => t.store.bind(tx).insertTerm(term));
60
+ }
61
+ export const termConformanceCases = [
62
+ {
63
+ name: 'a term round-trips every field',
64
+ async run(t) {
65
+ const term = creditTerm(t.newAccountId(), { graceUntil: at('2026-02-03T00:00:00Z'), nextPlanKey: 'basic', status: 'past_due' });
66
+ equal((await insert(t, term)).inserted, true, 'insert');
67
+ const read = await t.store.reader().getTerm(term.id);
68
+ check(read !== null, 'term stored');
69
+ for (const key of Object.keys(term)) {
70
+ if (key === 'updatedAt')
71
+ continue;
72
+ const a = read[key];
73
+ const b = term[key];
74
+ const norm = (v) => (v instanceof Date ? v.toISOString() : JSON.stringify(v));
75
+ equal(norm(a), norm(b), key);
76
+ }
77
+ },
78
+ },
79
+ {
80
+ name: 'one open credit term per account; a closed one does not count',
81
+ async run(t) {
82
+ const accountId = t.newAccountId();
83
+ equal((await insert(t, creditTerm(accountId))).inserted, true, 'first open term');
84
+ equal((await insert(t, creditTerm(accountId, { status: 'past_due' }))).inserted, false, 'second open term');
85
+ equal((await insert(t, creditTerm(accountId, { status: 'expired' }))).inserted, true, 'an expired term');
86
+ // A provider term is not a credit term.
87
+ equal((await insert(t, providerTerm(accountId))).inserted, true, 'a provider term beside it');
88
+ },
89
+ },
90
+ {
91
+ name: 'one scheduled term per account',
92
+ async run(t) {
93
+ const accountId = t.newAccountId();
94
+ const later = { status: 'scheduled', startsAt: at('2026-01-31T00:00:00Z') };
95
+ equal((await insert(t, creditTerm(accountId, later))).inserted, true, 'first scheduled');
96
+ equal((await insert(t, creditTerm(accountId, later))).inserted, false, 'second scheduled');
97
+ },
98
+ },
99
+ {
100
+ name: 'provider terms are unique per (source, environment, externalId)',
101
+ async run(t) {
102
+ const accountId = t.newAccountId();
103
+ const p = providerTerm(accountId);
104
+ equal((await insert(t, p)).inserted, true, 'first');
105
+ equal((await insert(t, { ...p, id: uid() })).inserted, false, 'duplicate');
106
+ equal((await insert(t, { ...p, id: uid(), environment: 'production' })).inserted, true, 'other environment');
107
+ const found = await t.store.reader().findExternal('polar', 'sandbox', p.externalId);
108
+ equal(found?.id, p.id, 'findExternal');
109
+ const locked = await t.store.transaction((tx) => t.store.bind(tx).lockExternal('polar', 'sandbox', p.externalId));
110
+ equal(locked?.id, p.id, 'lockExternal');
111
+ },
112
+ },
113
+ {
114
+ name: 'a conflicting insert does not abort the transaction',
115
+ async run(t) {
116
+ const accountId = t.newAccountId();
117
+ await insert(t, creditTerm(accountId));
118
+ const next = creditTerm(accountId, { status: 'expired' });
119
+ await t.store.transaction(async (tx) => {
120
+ const s = t.store.bind(tx);
121
+ equal((await s.insertTerm(creditTerm(accountId))).inserted, false, 'conflict');
122
+ equal((await s.insertTerm(next)).inserted, true, 'next insert in the same transaction');
123
+ });
124
+ check((await t.store.reader().getTerm(next.id)) !== null, 'committed after the conflict');
125
+ },
126
+ },
127
+ {
128
+ name: 'updateTerm patches, and a rollback discards it',
129
+ async run(t) {
130
+ const term = creditTerm(t.newAccountId());
131
+ await insert(t, term);
132
+ const end = at('2026-03-02T00:00:00Z');
133
+ await t.store.transaction(async (tx) => {
134
+ const s = t.store.bind(tx);
135
+ equal((await s.lockTerm(term.id))?.id, term.id, 'lockTerm');
136
+ await s.updateTerm(term.id, { currentPeriodEnd: end, periodItems: [{ months: 1, credits: 1 }, { months: 1, credits: 2 }], autoRenew: false });
137
+ equal((await s.getTerm(term.id))?.currentPeriodEnd.getTime(), end.getTime(), 'read own write');
138
+ });
139
+ const read = await t.store.reader().getTerm(term.id);
140
+ equal(read?.currentPeriodEnd.getTime(), end.getTime(), 'committed end');
141
+ equal(read?.periodItems?.length, 2, 'items');
142
+ equal(read?.autoRenew, false, 'autoRenew');
143
+ await t.store
144
+ .transaction(async (tx) => {
145
+ await t.store.bind(tx).updateTerm(term.id, { status: 'expired' });
146
+ throw ROLLBACK;
147
+ })
148
+ .catch((e) => check(e === ROLLBACK, 'rollback error'));
149
+ equal((await t.store.reader().getTerm(term.id))?.status, 'active', 'rolled back');
150
+ },
151
+ },
152
+ {
153
+ name: 'lockAccountTerms returns scheduled and open terms of every source, oldest first',
154
+ async run(t) {
155
+ const accountId = t.newAccountId();
156
+ const a = creditTerm(accountId, { createdAt: at('2026-01-01T00:00:00Z') });
157
+ const b = providerTerm(accountId, { createdAt: at('2026-01-02T00:00:00Z') });
158
+ const c = creditTerm(accountId, { status: 'scheduled', createdAt: at('2026-01-03T00:00:00Z') });
159
+ const d = creditTerm(accountId, { status: 'expired', createdAt: at('2026-01-04T00:00:00Z') });
160
+ const other = creditTerm(t.newAccountId());
161
+ for (const x of [c, a, d, b, other])
162
+ await insert(t, x);
163
+ const locked = await t.store.transaction((tx) => t.store.bind(tx).lockAccountTerms(accountId));
164
+ equal(locked.map((x) => x.id).join(','), [a.id, b.id, c.id].join(','), 'locked rows');
165
+ const listed = await t.store.reader().listTerms(accountId);
166
+ equal(listed.map((x) => x.id).join(','), [d.id, c.id, b.id, a.id].join(','), 'listTerms newest first');
167
+ const open = await t.store.reader().listTerms(accountId, { statuses: ['active'], limit: 1 });
168
+ equal(open.map((x) => x.id).join(','), b.id, 'status filter + limit');
169
+ },
170
+ },
171
+ {
172
+ name: 'listDue returns credit terms with renewal work, oldest due first',
173
+ async run(t) {
174
+ const base = Date.parse('2031-06-01T00:00:00Z') + Math.floor(Math.random() * 1e9);
175
+ const d = (ms) => new Date(base + ms);
176
+ const now = d(10_000);
177
+ const rows = [
178
+ creditTerm(t.newAccountId(), { currentPeriodEnd: d(3_000) }), // 0 auto-renew, ended
179
+ creditTerm(t.newAccountId(), { currentPeriodEnd: d(15_000) }), // 1 auto-renew within the 10 s lead
180
+ creditTerm(t.newAccountId(), { currentPeriodEnd: d(25_000) }), // 2 outside the lead
181
+ creditTerm(t.newAccountId(), { currentPeriodEnd: d(1_000), autoRenew: false }), // 3 ended, not renewing → expire
182
+ creditTerm(t.newAccountId(), { currentPeriodEnd: d(15_000), autoRenew: false }), // 4 not renewing, not ended
183
+ creditTerm(t.newAccountId(), { status: 'scheduled', startsAt: d(2_000) }), // 5 scheduled, starts
184
+ creditTerm(t.newAccountId(), { status: 'scheduled', startsAt: d(20_000) }), // 6 not yet
185
+ creditTerm(t.newAccountId(), { status: 'past_due', graceUntil: d(4_000) }), // 7 grace over
186
+ creditTerm(t.newAccountId(), { status: 'past_due', graceUntil: d(40_000) }), // 8 in grace
187
+ providerTerm(t.newAccountId(), { currentPeriodEnd: d(0) }), // 9 provider: never
188
+ creditTerm(t.newAccountId(), { currentPeriodEnd: d(0), status: 'expired' }), // 10 final
189
+ ];
190
+ for (const r of rows)
191
+ await insert(t, r);
192
+ const ids = new Set(rows.map((r) => r.id));
193
+ const due = (await t.store.reader().listDue(now, 10, 10_000)).filter((r) => ids.has(r.id));
194
+ const order = [0, 3, 5, 7, 1].map((i) => rows[i].id);
195
+ equal(due.map((r) => r.id).join(','), order.join(','), 'due terms in order');
196
+ },
197
+ },
198
+ ];
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Buying months with credits (design §4.7 S2–S4, §4.8): the pure decision of
3
+ * what a purchase is, what it costs now and what it does to the account's
4
+ * terms. The quote and the purchase both run it — the quote on a read, the
5
+ * purchase on the rows it locked — so they cannot disagree.
6
+ */
7
+ import type { Catalog } from '../catalog/catalog.js';
8
+ import type { QuoteReason } from '../domain/types.js';
9
+ import { type PeriodItem, type Term } from './types.js';
10
+ export type PlanQuoteKind = 'new' | 'extend' | 'upgrade' | 'renew' | 'downgrade' | 'blocked';
11
+ export interface PlanRequest {
12
+ accountId: string;
13
+ plan: string;
14
+ months: number;
15
+ /** The account's market, set by the host (D11). */
16
+ market: string;
17
+ }
18
+ /** What a purchase does to the terms; applied by the plans service. */
19
+ export type TermEffect =
20
+ /**
21
+ * Insert a new active credit term, after closing `close` (an open term that
22
+ * no longer entitles); a `scheduled` term it replaces is superseded by it.
23
+ */
24
+ {
25
+ type: 'create';
26
+ close: Term | null;
27
+ scheduled: Term | null;
28
+ startsAt: Date;
29
+ periodEnd: Date;
30
+ items: PeriodItem[];
31
+ }
32
+ /** S2: add months to the open term (and push a scheduled successor back). */
33
+ | {
34
+ type: 'extend';
35
+ term: Term;
36
+ periodEnd: Date;
37
+ items: PeriodItem[];
38
+ scheduled: Term | null;
39
+ }
40
+ /** Switch the open term's plan now; the end date is kept. */
41
+ | {
42
+ type: 'upgrade';
43
+ term: Term;
44
+ items: PeriodItem[];
45
+ }
46
+ /** Pay a past_due term: the next period runs from its old end. */
47
+ | {
48
+ type: 'renew';
49
+ term: Term;
50
+ periodStart: Date;
51
+ periodEnd: Date;
52
+ items: PeriodItem[];
53
+ }
54
+ /** S3b under auto-renew: the renewal switches plan and interval. */
55
+ | {
56
+ type: 'next_plan';
57
+ term: Term;
58
+ }
59
+ /** S3b without auto-renew (or after a non-renewing subscription): a scheduled term, charged when it starts. */
60
+ | {
61
+ type: 'schedule';
62
+ existing: Term | null;
63
+ startsAt: Date;
64
+ periodEnd: Date;
65
+ } | {
66
+ type: 'none';
67
+ };
68
+ export interface PlanDecision {
69
+ kind: PlanQuoteKind;
70
+ plan: string;
71
+ months: number;
72
+ market: string;
73
+ /** Credit minor units charged now. */
74
+ charge: number;
75
+ /** The list value the charge is derived from (`charge` except on a prorated upgrade). */
76
+ listPrice: number;
77
+ reason: QuoteReason;
78
+ effect: TermEffect;
79
+ /** The period the account ends up with for this plan; `null` when blocked. */
80
+ periodStart: Date | null;
81
+ periodEnd: Date | null;
82
+ scheduled: boolean;
83
+ }
84
+ /**
85
+ * Decide a credit purchase of `months` of `plan` against the account's open
86
+ * and scheduled terms. Throws `plan_not_found`, `offer_not_found` (the plan is
87
+ * not sold for these months in this market) or `invalid_input` (the free plan).
88
+ */
89
+ export declare function decidePlanPurchase(terms: readonly Term[], req: PlanRequest, catalog: Catalog, now: Date): PlanDecision;
90
+ /** The purchases of a credit term's current period (one item for a term from before items were kept). */
91
+ export declare function itemsOf(term: Term): PeriodItem[];
92
+ /**
93
+ * Credits a superseded credit term returns (S4): the unused share of what
94
+ * its period is worth, rounded in the customer's favour. Nothing for a term
95
+ * whose period was never paid (past_due).
96
+ */
97
+ export declare function supersedeRefund(term: Term, now: Date): number;