@tofound/billing 0.0.0-stage → 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 +122 -0
- package/LICENSE +3 -0
- package/README.md +79 -2
- package/dist/catalog/catalog.d.ts +115 -0
- package/dist/catalog/catalog.js +201 -0
- package/dist/domain/errors.d.ts +14 -0
- package/dist/domain/errors.js +21 -0
- package/dist/domain/money.d.ts +21 -0
- package/dist/domain/money.js +77 -0
- package/dist/domain/types.d.ts +167 -0
- package/dist/domain/types.js +18 -0
- package/dist/drizzle/index.d.ts +5 -0
- package/dist/drizzle/index.js +5 -0
- package/dist/drizzle/schema-factory.d.ts +586 -0
- package/dist/drizzle/schema-factory.js +206 -0
- package/dist/drizzle/store.d.ts +20 -0
- package/dist/drizzle/store.js +124 -0
- package/dist/entitlement/resolve.d.ts +76 -0
- package/dist/entitlement/resolve.js +122 -0
- package/dist/inbox/apply.d.ts +48 -0
- package/dist/inbox/apply.js +299 -0
- package/dist/inbox/conformance.d.ts +20 -0
- package/dist/inbox/conformance.js +254 -0
- package/dist/inbox/drizzle.d.ts +14 -0
- package/dist/inbox/drizzle.js +203 -0
- package/dist/inbox/ingest.d.ts +108 -0
- package/dist/inbox/ingest.js +404 -0
- package/dist/inbox/memory.d.ts +13 -0
- package/dist/inbox/memory.js +172 -0
- package/dist/inbox/ports.d.ts +150 -0
- package/dist/inbox/ports.js +1 -0
- package/dist/inbox/redact.d.ts +2 -0
- package/dist/inbox/redact.js +47 -0
- package/dist/inbox/schema.d.ts +1158 -0
- package/dist/inbox/schema.js +90 -0
- package/dist/inbox/watermark.d.ts +13 -0
- package/dist/inbox/watermark.js +6 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +27 -0
- package/dist/ledger/ledger.d.ts +47 -0
- package/dist/ledger/ledger.js +224 -0
- package/dist/ports/index.d.ts +2 -0
- package/dist/ports/index.js +1 -0
- package/dist/ports/ledger-store.d.ts +53 -0
- package/dist/ports/ledger-store.js +1 -0
- package/dist/ports/runtime.d.ts +9 -0
- package/dist/ports/runtime.js +1 -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 +207 -0
- package/dist/providers/port.js +30 -0
- package/dist/providers/sepay/index.d.ts +34 -0
- package/dist/providers/sepay/index.js +241 -0
- package/dist/providers/sepay/order.d.ts +32 -0
- package/dist/providers/sepay/order.js +69 -0
- package/dist/providers/sepay/signature.d.ts +8 -0
- package/dist/providers/sepay/signature.js +51 -0
- package/dist/quote/conformance.d.ts +16 -0
- package/dist/quote/conformance.js +39 -0
- package/dist/quote/index.d.ts +3 -0
- package/dist/quote/index.js +3 -0
- package/dist/quote/steps.d.ts +54 -0
- package/dist/quote/steps.js +103 -0
- package/dist/quote/waterfall.d.ts +98 -0
- package/dist/quote/waterfall.js +82 -0
- package/dist/renewal/renewal.d.ts +69 -0
- package/dist/renewal/renewal.js +198 -0
- package/dist/stores/conformance.d.ts +22 -0
- package/dist/stores/conformance.js +269 -0
- package/dist/stores/memory.d.ts +19 -0
- package/dist/stores/memory.js +137 -0
- package/dist/stores/testing.d.ts +13 -0
- package/dist/stores/testing.js +13 -0
- 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 +417 -0
- package/docs/SCHEMA.md +163 -0
- package/package.json +80 -4
|
@@ -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;
|
|
@@ -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;
|