@tofound/billing 0.0.0-stage → 0.1.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 +46 -0
- package/LICENSE +3 -0
- package/README.md +34 -2
- 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 +165 -0
- package/dist/domain/types.js +18 -0
- package/dist/drizzle/index.d.ts +3 -0
- package/dist/drizzle/index.js +3 -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/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 +20 -0
- package/dist/index.js +18 -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/port.d.ts +201 -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/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 +11 -0
- package/dist/stores/testing.js +11 -0
- package/docs/API.md +198 -0
- package/docs/SCHEMA.md +108 -0
- package/package.json +75 -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,22 @@
|
|
|
1
|
+
import type { AccountId } from '../domain/types.js';
|
|
2
|
+
import type { LedgerStore } from '../ports/ledger-store.js';
|
|
3
|
+
/**
|
|
4
|
+
* The store conformance suite (`billing.ports` contract check). Every
|
|
5
|
+
* `LedgerStore` — memory, the Drizzle store, a host's adapter over legacy
|
|
6
|
+
* tables — must pass all of it. Framework-agnostic: each case throws on
|
|
7
|
+
* failure, so a host wires it into its own runner:
|
|
8
|
+
*
|
|
9
|
+
* for (const c of ledgerConformanceCases) test(c.name, () => c.run(target))
|
|
10
|
+
*/
|
|
11
|
+
export interface LedgerConformanceTarget<TTx = unknown> {
|
|
12
|
+
store: LedgerStore<TTx>;
|
|
13
|
+
/** A fresh, never-used account id of the host's type (uuid, text …). */
|
|
14
|
+
newAccountId(): string;
|
|
15
|
+
}
|
|
16
|
+
export interface ConformanceCase {
|
|
17
|
+
name: string;
|
|
18
|
+
run<TTx>(target: LedgerConformanceTarget<TTx>): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
/** Checks I1, I2, I6 and seq contiguity for one account; throws on violation. */
|
|
21
|
+
export declare function assertLedgerInvariants<TTx>(store: LedgerStore<TTx>, accountId: AccountId): Promise<void>;
|
|
22
|
+
export declare const ledgerConformanceCases: readonly ConformanceCase[];
|