@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,16 @@
|
|
|
1
|
+
import type { Quote } from '../domain/types.js';
|
|
2
|
+
/** What a real settlement did, measured by the host's test around it. */
|
|
3
|
+
export interface ObservedSettlement {
|
|
4
|
+
/** Whether the charge went through. */
|
|
5
|
+
settled: boolean;
|
|
6
|
+
/** Balance after − balance before (credit minor units). */
|
|
7
|
+
walletDelta: number;
|
|
8
|
+
/** Units each metered pool consumed, keyed by funding `source`. */
|
|
9
|
+
meterDeltas?: Record<string, number>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The quote/charge conformance check (design §8): the quote must have
|
|
13
|
+
* predicted the money, the meters and the outcome of a real settlement.
|
|
14
|
+
* Throws an `Error` listing every mismatch; framework-agnostic.
|
|
15
|
+
*/
|
|
16
|
+
export declare function assertQuoteMatchesSettlement(quote: Quote, observed: ObservedSettlement): void;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The quote/charge conformance check (design §8): the quote must have
|
|
3
|
+
* predicted the money, the meters and the outcome of a real settlement.
|
|
4
|
+
* Throws an `Error` listing every mismatch; framework-agnostic.
|
|
5
|
+
*/
|
|
6
|
+
export function assertQuoteMatchesSettlement(quote, observed) {
|
|
7
|
+
const problems = [];
|
|
8
|
+
const expect = (ok, message) => {
|
|
9
|
+
if (!ok)
|
|
10
|
+
problems.push(message);
|
|
11
|
+
};
|
|
12
|
+
const walletLines = quote.funding.filter((l) => l.unit === quote.currency);
|
|
13
|
+
const walletSum = walletLines.reduce((sum, l) => sum + l.amount, 0);
|
|
14
|
+
expect(walletSum === quote.price, `price ${quote.price} ≠ Σ wallet lines ${walletSum}`);
|
|
15
|
+
expect(quote.price <= quote.originalPrice, `price ${quote.price} > originalPrice ${quote.originalPrice}`);
|
|
16
|
+
expect(quote.canSettle === (quote.settlement !== 'blocked'), `canSettle ${quote.canSettle} vs settlement ${quote.settlement}`);
|
|
17
|
+
expect(quote.shortfall === undefined || quote.settlement === 'blocked', 'shortfall on a quote that is not blocked');
|
|
18
|
+
expect(observed.settled === quote.canSettle, `quote canSettle ${quote.canSettle} but settled ${observed.settled}`);
|
|
19
|
+
const meters = observed.meterDeltas ?? {};
|
|
20
|
+
if (observed.settled) {
|
|
21
|
+
expect(observed.walletDelta === -quote.price, `wallet moved ${observed.walletDelta}, quote predicted ${-quote.price}`);
|
|
22
|
+
const predicted = {};
|
|
23
|
+
for (const line of quote.funding) {
|
|
24
|
+
if (line.unit === quote.currency || line.remainingBefore === null)
|
|
25
|
+
continue;
|
|
26
|
+
predicted[line.source] = (predicted[line.source] ?? 0) + line.amount;
|
|
27
|
+
}
|
|
28
|
+
for (const source of new Set([...Object.keys(predicted), ...Object.keys(meters)])) {
|
|
29
|
+
expect((meters[source] ?? 0) === (predicted[source] ?? 0), `meter ${source} moved ${meters[source] ?? 0}, quote predicted ${predicted[source] ?? 0}`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
expect(observed.walletDelta === 0, `blocked settlement moved the wallet by ${observed.walletDelta}`);
|
|
34
|
+
for (const [source, delta] of Object.entries(meters))
|
|
35
|
+
expect(delta === 0, `blocked settlement moved meter ${source} by ${delta}`);
|
|
36
|
+
}
|
|
37
|
+
if (problems.length)
|
|
38
|
+
throw new Error(`quote does not match settlement:\n- ${problems.join('\n- ')}`);
|
|
39
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { assertQuoteMatchesSettlement, type ObservedSettlement } from './conformance.js';
|
|
2
|
+
export { creditsStep, freeStep, quotaStep, type QuotaPool } from './steps.js';
|
|
3
|
+
export { createWaterfall, type SettleContext, type SettleOptions, type Settled, type StepContext, type StepPlan, type Waterfall, type WaterfallConfig, type WaterfallStep, } from './waterfall.js';
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { Quote, QuoteReason } from '../domain/types.js';
|
|
2
|
+
import type { LedgerOps } from '../ledger/ledger.js';
|
|
3
|
+
import type { SettleContext, WaterfallStep } from './waterfall.js';
|
|
4
|
+
/**
|
|
5
|
+
* Covers the whole remaining price for nothing when `when(state)` holds —
|
|
6
|
+
* BYOK, an already-owned resource, flat plan coverage.
|
|
7
|
+
*/
|
|
8
|
+
export declare function freeStep<S, TTx = unknown>(options: {
|
|
9
|
+
id: string;
|
|
10
|
+
source?: string;
|
|
11
|
+
when: (state: S) => boolean;
|
|
12
|
+
reason: QuoteReason;
|
|
13
|
+
label?: string;
|
|
14
|
+
}): WaterfallStep<S, TTx>;
|
|
15
|
+
export interface QuotaPool {
|
|
16
|
+
/** Units left in the pool. */
|
|
17
|
+
remaining: number;
|
|
18
|
+
/** Price (credit minor units) one unit covers: 1 for a credit pool, the list price for "one chapter". */
|
|
19
|
+
unitValue: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Spends a metered pool (an included monthly pool, a pass quota) before money.
|
|
23
|
+
* `unit` names what the pool counts and must differ from the credit unit code
|
|
24
|
+
* (`included_credit`, not `credit`), so money and meter lines stay apart.
|
|
25
|
+
* May fund part of the price; the host's `consume` commits the units inside
|
|
26
|
+
* the settle transaction, under the host's own meter row lock.
|
|
27
|
+
*/
|
|
28
|
+
export declare function quotaStep<S, TTx>(options: {
|
|
29
|
+
id: string;
|
|
30
|
+
source?: string;
|
|
31
|
+
unit: string;
|
|
32
|
+
pool: (state: S) => QuotaPool | null;
|
|
33
|
+
reason: QuoteReason;
|
|
34
|
+
label?: string;
|
|
35
|
+
consume: (tx: TTx, units: number, ctx: SettleContext<S>) => Promise<void>;
|
|
36
|
+
}): WaterfallStep<S, TTx>;
|
|
37
|
+
/**
|
|
38
|
+
* Debits the credit wallet for whatever is still unfunded, or blocks with the
|
|
39
|
+
* exact shortfall. Never funds partially: a wallet that cannot pay the rest
|
|
40
|
+
* blocks the whole charge, as both hosts do today.
|
|
41
|
+
*/
|
|
42
|
+
export declare function creditsStep<S, TTx>(options: {
|
|
43
|
+
/** `ledger.in` — the settle transaction is handed to it. */
|
|
44
|
+
ledger: {
|
|
45
|
+
in(tx: TTx): LedgerOps;
|
|
46
|
+
};
|
|
47
|
+
id?: string;
|
|
48
|
+
source?: string;
|
|
49
|
+
reason?: QuoteReason;
|
|
50
|
+
insufficientReason?: QuoteReason;
|
|
51
|
+
noAccountReason?: QuoteReason;
|
|
52
|
+
upsell?: (state: S) => Quote['upsell'] | undefined;
|
|
53
|
+
label?: string;
|
|
54
|
+
}): WaterfallStep<S, TTx>;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { BillingError } from '../domain/errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* Covers the whole remaining price for nothing when `when(state)` holds —
|
|
4
|
+
* BYOK, an already-owned resource, flat plan coverage.
|
|
5
|
+
*/
|
|
6
|
+
export function freeStep(options) {
|
|
7
|
+
return {
|
|
8
|
+
id: options.id,
|
|
9
|
+
plan: ({ state, remaining }) => options.when(state)
|
|
10
|
+
? {
|
|
11
|
+
type: 'fund',
|
|
12
|
+
covers: remaining,
|
|
13
|
+
settlement: 'free',
|
|
14
|
+
reason: options.reason,
|
|
15
|
+
line: withLabel({ source: options.source ?? options.id, unit: 'none', amount: 0, remainingBefore: null, remainingAfter: null }, options.label),
|
|
16
|
+
}
|
|
17
|
+
: null,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Spends a metered pool (an included monthly pool, a pass quota) before money.
|
|
22
|
+
* `unit` names what the pool counts and must differ from the credit unit code
|
|
23
|
+
* (`included_credit`, not `credit`), so money and meter lines stay apart.
|
|
24
|
+
* May fund part of the price; the host's `consume` commits the units inside
|
|
25
|
+
* the settle transaction, under the host's own meter row lock.
|
|
26
|
+
*/
|
|
27
|
+
export function quotaStep(options) {
|
|
28
|
+
return {
|
|
29
|
+
id: options.id,
|
|
30
|
+
plan({ state, remaining }) {
|
|
31
|
+
const pool = options.pool(state);
|
|
32
|
+
if (!pool || pool.remaining <= 0)
|
|
33
|
+
return null;
|
|
34
|
+
if (!Number.isSafeInteger(pool.unitValue) || pool.unitValue <= 0) {
|
|
35
|
+
throw new RangeError(`quota step ${options.id}: unitValue must be a positive integer`);
|
|
36
|
+
}
|
|
37
|
+
const units = Math.min(pool.remaining, Math.ceil(remaining / pool.unitValue));
|
|
38
|
+
return {
|
|
39
|
+
type: 'fund',
|
|
40
|
+
covers: Math.min(remaining, units * pool.unitValue),
|
|
41
|
+
settlement: 'quota',
|
|
42
|
+
reason: options.reason,
|
|
43
|
+
line: withLabel({ source: options.source ?? options.id, unit: options.unit, amount: units, remainingBefore: pool.remaining, remainingAfter: pool.remaining - units }, options.label),
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
settle: (tx, line, ctx) => options.consume(tx, line.amount, ctx),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Debits the credit wallet for whatever is still unfunded, or blocks with the
|
|
51
|
+
* exact shortfall. Never funds partially: a wallet that cannot pay the rest
|
|
52
|
+
* blocks the whole charge, as both hosts do today.
|
|
53
|
+
*/
|
|
54
|
+
export function creditsStep(options) {
|
|
55
|
+
return {
|
|
56
|
+
id: options.id ?? 'credits',
|
|
57
|
+
plan({ state, remaining, balance, currency }) {
|
|
58
|
+
if (balance === null)
|
|
59
|
+
return { type: 'block', reason: options.noAccountReason ?? { code: 'no_account' } };
|
|
60
|
+
if (balance < remaining) {
|
|
61
|
+
const upsell = options.upsell?.(state);
|
|
62
|
+
return {
|
|
63
|
+
type: 'block',
|
|
64
|
+
reason: options.insufficientReason ?? { code: 'insufficient_credits' },
|
|
65
|
+
shortfall: remaining - balance,
|
|
66
|
+
...(upsell ? { upsell } : {}),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
type: 'fund',
|
|
71
|
+
covers: remaining,
|
|
72
|
+
settlement: 'wallet',
|
|
73
|
+
reason: options.reason ?? { code: 'list_price' },
|
|
74
|
+
line: withLabel({ source: options.source ?? 'wallet', unit: currency, amount: remaining, remainingBefore: balance, remainingAfter: balance - remaining }, options.label),
|
|
75
|
+
};
|
|
76
|
+
},
|
|
77
|
+
settle: (tx, line, ctx) => options.ledger.in(tx).debit({
|
|
78
|
+
accountId: ctx.accountId,
|
|
79
|
+
kind: ctx.kind ?? 'spend',
|
|
80
|
+
amount: line.amount,
|
|
81
|
+
idempotencyKey: ctx.idempotencyKey,
|
|
82
|
+
reason: ctx.reason ?? null,
|
|
83
|
+
source: ctx.source ?? null,
|
|
84
|
+
meta: ctx.meta ?? null,
|
|
85
|
+
}),
|
|
86
|
+
async replay(tx, ctx) {
|
|
87
|
+
const entry = await options.ledger.in(tx).findByKey(ctx.idempotencyKey);
|
|
88
|
+
if (!entry)
|
|
89
|
+
return null;
|
|
90
|
+
const kind = ctx.kind ?? 'spend';
|
|
91
|
+
if (entry.accountId !== ctx.accountId || entry.kind !== kind || entry.delta >= 0) {
|
|
92
|
+
throw new BillingError('idempotency_mismatch', `idempotency key ${ctx.idempotencyKey} was posted with a different intent`, {
|
|
93
|
+
idempotencyKey: ctx.idempotencyKey,
|
|
94
|
+
entryId: entry.id,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return { entry, replayed: true, events: [] };
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function withLabel(line, label) {
|
|
102
|
+
return label === undefined ? line : { ...line, label };
|
|
103
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { AccountId, BillingEvent, EntryKind, EntryMeta, EntrySource, FundingLine, LedgerEntry, PostResult, Quote, QuoteReason, Settlement } from '../domain/types.js';
|
|
2
|
+
/**
|
|
3
|
+
* One waterfall, walked twice (design §8): `quote` is the read-only walk,
|
|
4
|
+
* `settle` walks the same steps on locked state inside a transaction and
|
|
5
|
+
* commits each funding line. A host never writes a second pricing function
|
|
6
|
+
* beside its charge path — it composes steps here and both paths follow.
|
|
7
|
+
*/
|
|
8
|
+
/** What a step sees when the walk reaches it. */
|
|
9
|
+
export interface StepContext<S> {
|
|
10
|
+
state: S;
|
|
11
|
+
originalPrice: number;
|
|
12
|
+
/** Price still unfunded when the walk reaches this step (> 0). */
|
|
13
|
+
remaining: number;
|
|
14
|
+
/** Credit balance from `config.balance(state)`; `null` without an account. */
|
|
15
|
+
balance: number | null;
|
|
16
|
+
/** Credit unit code — the `unit` of money lines. */
|
|
17
|
+
currency: string;
|
|
18
|
+
}
|
|
19
|
+
export type StepPlan = {
|
|
20
|
+
type: 'fund';
|
|
21
|
+
/** `unit` is the credit unit code exactly when `settlement` is `wallet`. */
|
|
22
|
+
line: FundingLine;
|
|
23
|
+
/** Price (credit minor units) this line takes off `remaining`. */
|
|
24
|
+
covers: number;
|
|
25
|
+
settlement: Exclude<Settlement, 'blocked'>;
|
|
26
|
+
reason: QuoteReason;
|
|
27
|
+
} | {
|
|
28
|
+
type: 'block';
|
|
29
|
+
reason: QuoteReason;
|
|
30
|
+
shortfall?: number;
|
|
31
|
+
upsell?: Quote['upsell'];
|
|
32
|
+
};
|
|
33
|
+
export interface SettleOptions {
|
|
34
|
+
accountId: AccountId;
|
|
35
|
+
/** Key of this charge; the credits step debits under it. */
|
|
36
|
+
idempotencyKey: string;
|
|
37
|
+
/** Ledger kind of the debit. Default `spend`. */
|
|
38
|
+
kind?: EntryKind;
|
|
39
|
+
reason?: string | null;
|
|
40
|
+
source?: EntrySource | null;
|
|
41
|
+
meta?: EntryMeta | null;
|
|
42
|
+
}
|
|
43
|
+
export interface SettleContext<S> extends SettleOptions {
|
|
44
|
+
state: S;
|
|
45
|
+
quote: Quote;
|
|
46
|
+
}
|
|
47
|
+
export interface WaterfallStep<S, TTx> {
|
|
48
|
+
id: string;
|
|
49
|
+
/** Fund some or all of `remaining`, block the walk, or `null` to pass. Pure. */
|
|
50
|
+
plan(ctx: StepContext<S>): StepPlan | null;
|
|
51
|
+
/** Commit this step's line inside the settle transaction. */
|
|
52
|
+
settle?(tx: TTx, line: FundingLine, ctx: SettleContext<S>): Promise<PostResult | void>;
|
|
53
|
+
/**
|
|
54
|
+
* The posting this step already committed under `options.idempotencyKey`,
|
|
55
|
+
* if any. `settle` asks before walking, so a retried charge replays even
|
|
56
|
+
* when the balance it drained no longer covers the price.
|
|
57
|
+
*/
|
|
58
|
+
replay?(tx: TTx, options: SettleOptions): Promise<PostResult | null>;
|
|
59
|
+
}
|
|
60
|
+
export interface WaterfallConfig<S, TTx> {
|
|
61
|
+
steps: readonly WaterfallStep<S, TTx>[];
|
|
62
|
+
/** Credit unit code, e.g. `credit` or `LT`. */
|
|
63
|
+
currency: string;
|
|
64
|
+
/** List price of the thing being quoted, in credit minor units. */
|
|
65
|
+
price(state: S): number;
|
|
66
|
+
balance(state: S): number | null;
|
|
67
|
+
/** Default 60, like Lohi `QUOTE_TTL_SEC`. */
|
|
68
|
+
expiresInSec?: number;
|
|
69
|
+
/** Reason when the price is 0 and nothing needed funding. Default `{code:'list_price'}`. */
|
|
70
|
+
freeReason?: QuoteReason;
|
|
71
|
+
/** Reason when every step passed and price is still unfunded. Default `{code:'not_covered'}`. */
|
|
72
|
+
uncoveredReason?: QuoteReason;
|
|
73
|
+
}
|
|
74
|
+
export interface Settled {
|
|
75
|
+
settled: boolean;
|
|
76
|
+
/**
|
|
77
|
+
* The key was already charged: nothing ran, `entries` holds the original
|
|
78
|
+
* posting and `quote` describes the current (post-charge) state.
|
|
79
|
+
*/
|
|
80
|
+
replayed: boolean;
|
|
81
|
+
/** The quote of the locked state — what was actually charged. */
|
|
82
|
+
quote: Quote;
|
|
83
|
+
/** Ledger entries the steps posted (or replayed). */
|
|
84
|
+
entries: LedgerEntry[];
|
|
85
|
+
/** Ledger events of this settlement, for the host to emit after its commit. */
|
|
86
|
+
events: BillingEvent[];
|
|
87
|
+
}
|
|
88
|
+
export interface Waterfall<S, TTx> {
|
|
89
|
+
quote(state: S): Quote;
|
|
90
|
+
/**
|
|
91
|
+
* Re-walk on state read under the host's locks and commit each line. A key
|
|
92
|
+
* whose credits line was already posted replays without running any step.
|
|
93
|
+
* A charge funded by quota alone posts no ledger entry, so the host guards
|
|
94
|
+
* repeats with its own stamp (job/unlock row) before settling.
|
|
95
|
+
*/
|
|
96
|
+
settle(tx: TTx, lockedState: S, options: SettleOptions): Promise<Settled>;
|
|
97
|
+
}
|
|
98
|
+
export declare function createWaterfall<S, TTx>(config: WaterfallConfig<S, TTx>): Waterfall<S, TTx>;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
export function createWaterfall(config) {
|
|
2
|
+
const expiresInSec = config.expiresInSec ?? 60;
|
|
3
|
+
function walk(state) {
|
|
4
|
+
const originalPrice = config.price(state);
|
|
5
|
+
if (!Number.isSafeInteger(originalPrice) || originalPrice < 0) {
|
|
6
|
+
throw new RangeError(`waterfall price must be a non-negative safe integer, got ${originalPrice}`);
|
|
7
|
+
}
|
|
8
|
+
const balance = config.balance(state);
|
|
9
|
+
const planned = [];
|
|
10
|
+
let remaining = originalPrice;
|
|
11
|
+
let block = null;
|
|
12
|
+
for (const step of config.steps) {
|
|
13
|
+
if (remaining <= 0)
|
|
14
|
+
break;
|
|
15
|
+
const plan = step.plan({ state, originalPrice, remaining, balance, currency: config.currency });
|
|
16
|
+
if (!plan)
|
|
17
|
+
continue;
|
|
18
|
+
if (plan.type === 'block') {
|
|
19
|
+
block = plan;
|
|
20
|
+
break;
|
|
21
|
+
}
|
|
22
|
+
if (!Number.isSafeInteger(plan.covers) || plan.covers <= 0 || plan.covers > remaining) {
|
|
23
|
+
throw new RangeError(`step ${step.id} covers ${plan.covers} of ${remaining}`);
|
|
24
|
+
}
|
|
25
|
+
// The unit is what tells money lines from meter lines on the wire and in
|
|
26
|
+
// assertQuoteMatchesSettlement, so it must agree with the settlement.
|
|
27
|
+
if ((plan.settlement === 'wallet') !== (plan.line.unit === config.currency)) {
|
|
28
|
+
throw new RangeError(`step ${step.id}: unit ${plan.line.unit} must be ${config.currency} exactly when it settles from the wallet`);
|
|
29
|
+
}
|
|
30
|
+
planned.push({ step, line: plan.line, settlement: plan.settlement, reason: plan.reason });
|
|
31
|
+
remaining -= plan.covers;
|
|
32
|
+
}
|
|
33
|
+
if (!block && remaining > 0)
|
|
34
|
+
block = { type: 'block', reason: config.uncoveredReason ?? { code: 'not_covered' } };
|
|
35
|
+
const funding = planned.map((p) => p.line);
|
|
36
|
+
const price = planned.filter((p) => p.settlement === 'wallet').reduce((sum, p) => sum + p.line.amount, 0);
|
|
37
|
+
const settlement = block
|
|
38
|
+
? 'blocked'
|
|
39
|
+
: planned.some((p) => p.settlement === 'wallet')
|
|
40
|
+
? 'wallet'
|
|
41
|
+
: planned.some((p) => p.settlement === 'quota')
|
|
42
|
+
? 'quota'
|
|
43
|
+
: 'free';
|
|
44
|
+
const quote = {
|
|
45
|
+
originalPrice,
|
|
46
|
+
price,
|
|
47
|
+
currency: config.currency,
|
|
48
|
+
reason: block ? block.reason : (planned[0]?.reason ?? config.freeReason ?? { code: 'list_price' }),
|
|
49
|
+
funding,
|
|
50
|
+
settlement,
|
|
51
|
+
canSettle: !block,
|
|
52
|
+
balance,
|
|
53
|
+
expiresInSec,
|
|
54
|
+
...(block?.shortfall === undefined ? {} : { shortfall: block.shortfall }),
|
|
55
|
+
...(block?.upsell ? { upsell: block.upsell } : {}),
|
|
56
|
+
};
|
|
57
|
+
return { quote, planned };
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
quote: (state) => walk(state).quote,
|
|
61
|
+
async settle(tx, lockedState, options) {
|
|
62
|
+
for (const step of config.steps) {
|
|
63
|
+
const prior = await step.replay?.(tx, options);
|
|
64
|
+
if (prior)
|
|
65
|
+
return { settled: true, replayed: true, quote: walk(lockedState).quote, entries: [prior.entry], events: [] };
|
|
66
|
+
}
|
|
67
|
+
const { quote, planned } = walk(lockedState);
|
|
68
|
+
if (!quote.canSettle)
|
|
69
|
+
return { settled: false, replayed: false, quote, entries: [], events: [] };
|
|
70
|
+
const entries = [];
|
|
71
|
+
const events = [];
|
|
72
|
+
for (const { step, line } of planned) {
|
|
73
|
+
const posted = await step.settle?.(tx, line, { ...options, state: lockedState, quote });
|
|
74
|
+
if (posted) {
|
|
75
|
+
entries.push(posted.entry);
|
|
76
|
+
events.push(...posted.events);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return { settled: true, replayed: false, quote, entries, events };
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renewal of credit-bought months (design §4.9, §4.10, D9). The trigger is
|
|
3
|
+
* the host's (2Novel: an interval under `pg_try_advisory_lock`; Lohi: the
|
|
4
|
+
* admin `renew-due`); this module is what each run does:
|
|
5
|
+
*
|
|
6
|
+
* - an auto-renewing term at its period end is charged the **live** catalog
|
|
7
|
+
* price of `nextPlanKey ?? planKey` for `intervalMonths`, keyed
|
|
8
|
+
* `renew:<termId>:<previous periodEnd ISO>` — a double run debits once;
|
|
9
|
+
* - a short balance (or a plan no longer sold for credits) makes it
|
|
10
|
+
* `past_due` with `graceUntil = periodEnd + graceDays`; it stays entitled
|
|
11
|
+
* until then, and a paid retry continues the period from the old end. An
|
|
12
|
+
* early attempt (`renewalLeadSec`) that fails leaves the paid period
|
|
13
|
+
* `active` and is tried again by the next run;
|
|
14
|
+
* - grace passed, or a non-renewing term ended → `expired`, and the
|
|
15
|
+
* entitlement falls to the next term or the free plan;
|
|
16
|
+
* - a scheduled term (S3b) is charged and activated when it starts.
|
|
17
|
+
*
|
|
18
|
+
* Each term runs in its own transaction: term rows (oldest first), then the
|
|
19
|
+
* ledger account. `retryPastDue` is what a host calls once a top-up has
|
|
20
|
+
* committed — in its own transaction, never inside the crediting one, which
|
|
21
|
+
* already holds the account lock that must come last.
|
|
22
|
+
*/
|
|
23
|
+
import type { Catalog } from '../catalog/catalog.js';
|
|
24
|
+
import type { AccountId, BillingEvent, LedgerEntry } from '../domain/types.js';
|
|
25
|
+
import type { Ledger } from '../ledger/ledger.js';
|
|
26
|
+
import type { Clock } from '../ports/runtime.js';
|
|
27
|
+
import type { TermStore } from '../terms/ports.js';
|
|
28
|
+
import type { Term, TermEvent } from '../terms/types.js';
|
|
29
|
+
export type RenewalEvent = TermEvent | BillingEvent;
|
|
30
|
+
export interface RenewalOptions<TTx> {
|
|
31
|
+
ledger: Ledger<TTx>;
|
|
32
|
+
terms: TermStore<TTx>;
|
|
33
|
+
catalog: Catalog;
|
|
34
|
+
clock?: Clock;
|
|
35
|
+
/** The account's market now, for the live price; `null`/absent → the term's own market. */
|
|
36
|
+
marketOf?: (accountId: AccountId) => string | null | Promise<string | null>;
|
|
37
|
+
/** At-most-once, after commit, for transactions the service opened. */
|
|
38
|
+
events?: (event: RenewalEvent) => void | Promise<void>;
|
|
39
|
+
onEventError?: (error: unknown, event: RenewalEvent) => void;
|
|
40
|
+
}
|
|
41
|
+
export type RenewalOutcome = 'renewed' | 'activated' | 'past_due' | 'expired' | 'skipped' | 'error';
|
|
42
|
+
export interface RenewalResult {
|
|
43
|
+
termId: string;
|
|
44
|
+
accountId: AccountId;
|
|
45
|
+
outcome: RenewalOutcome;
|
|
46
|
+
/** Why a renewal failed (`insufficient_credits`, `offer_not_found`) or was skipped, or the error message. */
|
|
47
|
+
reason?: string;
|
|
48
|
+
entry?: LedgerEntry | null;
|
|
49
|
+
term?: Term;
|
|
50
|
+
}
|
|
51
|
+
export interface RenewalRun {
|
|
52
|
+
results: RenewalResult[];
|
|
53
|
+
events: RenewalEvent[];
|
|
54
|
+
}
|
|
55
|
+
export interface RenewalOps {
|
|
56
|
+
/** Process one term if it is due at `now`. */
|
|
57
|
+
renewTerm(termId: string, now?: Date): Promise<RenewalRun>;
|
|
58
|
+
/** Charge the account's past_due credit terms again (or expire them once grace has passed). */
|
|
59
|
+
retryPastDue(accountId: AccountId, now?: Date): Promise<RenewalRun>;
|
|
60
|
+
}
|
|
61
|
+
export interface RenewalService<TTx = unknown> extends RenewalOps {
|
|
62
|
+
/** Every due term, each in its own transaction; one term's error does not stop the batch. */
|
|
63
|
+
renewDue(input?: {
|
|
64
|
+
now?: Date;
|
|
65
|
+
limit?: number;
|
|
66
|
+
}): Promise<RenewalRun>;
|
|
67
|
+
in(tx: TTx): RenewalOps;
|
|
68
|
+
}
|
|
69
|
+
export declare function createRenewal<TTx>(options: RenewalOptions<TTx>): RenewalService<TTx>;
|
|
@@ -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 });
|