@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
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@tofound/billing`. Versions follow semver; 0.x minors
|
|
4
|
+
are additive.
|
|
5
|
+
|
|
6
|
+
## 0.1.0 — 2026-10-17
|
|
7
|
+
|
|
8
|
+
First release (baseline: repository start).
|
|
9
|
+
|
|
10
|
+
- Domain: `CreditUnit`, `Money`, safe-integer amounts, explicit rounding
|
|
11
|
+
(`divRound`, `mulDivRound`), `BillingError` codes.
|
|
12
|
+
- Ledger: single-entry, append-only, per-account `seq` + `balanceAfter`,
|
|
13
|
+
global idempotency keys (replay / `idempotency_mismatch`), no overdraft,
|
|
14
|
+
`debitUpTo` with recorded shortfall, one partial-or-full reversal per entry,
|
|
15
|
+
`ledger.in(tx)` for host transactions, `findByKey`, post-commit domain
|
|
16
|
+
events delivered at most once (sink errors go to `onEventError`).
|
|
17
|
+
- Ports: `LedgerStore` / `LedgerTx` / `LedgerReader`, `Clock`, `IdGenerator`,
|
|
18
|
+
`BillingEventSink`.
|
|
19
|
+
- Stores: memory store; Drizzle Postgres store (`@tofound/billing/drizzle`).
|
|
20
|
+
- Schema factory: `createBillingTables` (accounts, entries) with `schema` /
|
|
21
|
+
`prefix` / host-typed `accountId`, `billingTableBuilder`, and
|
|
22
|
+
`checkAdditiveDdl` for the additive-migration rules (statement-split,
|
|
23
|
+
multi-action aware, fails closed). Hosts run their own
|
|
24
|
+
`db:generate`. Entries resolve under `require` too (drizzle-kit loads schema
|
|
25
|
+
files that way; Node ≥ 22.12).
|
|
26
|
+
- Quote/charge: `createWaterfall` with `freeStep`, `quotaStep`, `creditsStep`;
|
|
27
|
+
one walk for the quote and the settlement; a retried charge replays its
|
|
28
|
+
credits posting (`Settled.replayed`) and settlement returns its ledger
|
|
29
|
+
events for the host's outbox.
|
|
30
|
+
- Provider port: `ProviderAdapter`, `CheckoutCapable`, `PurchaseVerifier`,
|
|
31
|
+
normalized events and an explicit `ProviderEnvironment` (never inferred).
|
|
32
|
+
- Payment inbox (`createIngest`): verify a webhook, persist it, apply each
|
|
33
|
+
event exactly once into the ledger — replays and concurrent redeliveries
|
|
34
|
+
are duplicates, late payments after checkout expiry still credit, unmatched
|
|
35
|
+
deliveries are kept for manual replay, plus retry sweep, dead-letter and
|
|
36
|
+
per-purchase watermarks. Memory store and Drizzle store/tables
|
|
37
|
+
(`createIngestTables`, `createDrizzleIngestStore` in `/drizzle`); payloads
|
|
38
|
+
are redacted before storage.
|
|
39
|
+
- SePay adapter (`@tofound/billing/providers/sepay`): `createSepayAdapter`
|
|
40
|
+
with secret-header webhook verification, signed checkout fields
|
|
41
|
+
(byte-compatible with `sepay-pg-node@1.0.0`, no SDK), order lookup that never
|
|
42
|
+
turns a lookup failure into a cancellation, `TRANSACTION_VOID` precedence,
|
|
43
|
+
VND-only settlement, and `respondSepay` for the host route. The environment
|
|
44
|
+
is required and production with test credentials is refused.
|
|
45
|
+
- Testing kit (`@tofound/billing/testing`): store conformance cases, ledger
|
|
46
|
+
invariant check, `assertQuoteMatchesSettlement`, ingest conformance cases.
|
package/LICENSE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,35 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 2billing
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@tofound/billing` — the shared subscription & credit library for 2found
|
|
4
|
+
products (2Novel first, the Lohi reader api last). Each host API embeds it on
|
|
5
|
+
its own database; there is no billing service.
|
|
6
|
+
|
|
7
|
+
0.1 ships the money core: an idempotent, no-overdraft credit ledger behind
|
|
8
|
+
store ports, memory and Drizzle/Postgres stores, a Drizzle schema factory the
|
|
9
|
+
host re-exports and migrates itself, one quote/charge waterfall, a payment
|
|
10
|
+
webhook inbox (verify → persist → apply exactly once) and the SePay adapter
|
|
11
|
+
(`@tofound/billing/providers/sepay`). Terms, entitlement and the Polar, Apple
|
|
12
|
+
and Google adapters land in later versions.
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
bun add @tofound/billing@0.1.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { createLedger } from '@tofound/billing'
|
|
20
|
+
import { uuid } from 'drizzle-orm/pg-core'
|
|
21
|
+
import { createBillingTables, createDrizzleLedgerStore } from '@tofound/billing/drizzle'
|
|
22
|
+
|
|
23
|
+
// in a file your drizzle-kit `schema` glob covers, so `db:generate` sees the tables
|
|
24
|
+
export const { billingAccounts, billingEntries } = createBillingTables({ accountId: (n) => uuid(n).notNull() })
|
|
25
|
+
const ledger = createLedger({ store: createDrizzleLedgerStore({ db, tables: { billingAccounts, billingEntries } }) })
|
|
26
|
+
await db.transaction((tx) => ledger.in(tx).debit({ accountId, kind: 'spend', amount, idempotencyKey: `job:${id}:charge` }))
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- [docs/API.md](docs/API.md) — ledger, ports, waterfall, error codes
|
|
30
|
+
- [docs/SCHEMA.md](docs/SCHEMA.md) — schema factory and the additive migration rules
|
|
31
|
+
- [RELEASE.md](RELEASE.md) — how a version is checked, packed and published
|
|
32
|
+
- Contracts other work builds against: [.babysit/contracts.yaml](.babysit/contracts.yaml)
|
|
33
|
+
|
|
34
|
+
Develop with bun ≥ 1.3.14: `bun install`, then `bun run check` (needs a local
|
|
35
|
+
Postgres `initdb`, see RELEASE.md).
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { BillingErrorCode, InsufficientCredits } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* The one error type the library throws for domain outcomes. Hosts map
|
|
4
|
+
* `code` to their own HTTP status and copy (e.g. `insufficient_credits` →
|
|
5
|
+
* 402 with `details.shortfall`); the message is for logs only.
|
|
6
|
+
*/
|
|
7
|
+
export declare class BillingError extends Error {
|
|
8
|
+
readonly name = "BillingError";
|
|
9
|
+
readonly code: BillingErrorCode;
|
|
10
|
+
readonly details: Record<string, unknown>;
|
|
11
|
+
constructor(code: BillingErrorCode, message: string, details?: Record<string, unknown>);
|
|
12
|
+
}
|
|
13
|
+
export declare function isBillingError(value: unknown, code?: BillingErrorCode): value is BillingError;
|
|
14
|
+
export declare function insufficientCredits(details: InsufficientCredits): BillingError;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one error type the library throws for domain outcomes. Hosts map
|
|
3
|
+
* `code` to their own HTTP status and copy (e.g. `insufficient_credits` →
|
|
4
|
+
* 402 with `details.shortfall`); the message is for logs only.
|
|
5
|
+
*/
|
|
6
|
+
export class BillingError extends Error {
|
|
7
|
+
name = 'BillingError';
|
|
8
|
+
code;
|
|
9
|
+
details;
|
|
10
|
+
constructor(code, message, details = {}) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.details = details;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export function isBillingError(value, code) {
|
|
17
|
+
return value instanceof BillingError && (code === undefined || value.code === code);
|
|
18
|
+
}
|
|
19
|
+
export function insufficientCredits(details) {
|
|
20
|
+
return new BillingError('insufficient_credits', `insufficient credits: balance ${details.balance}, required ${details.required}`, { ...details });
|
|
21
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { CreditUnit, Currency, Money, RoundingMode } from './types.js';
|
|
2
|
+
/** Minor-unit exponent of each fiat currency. */
|
|
3
|
+
export declare const CURRENCY_EXPONENT: Readonly<Record<Currency, number>>;
|
|
4
|
+
/** Throws `invalid_amount` unless `value` is a safe integer (≥ 0 unless `signed`). */
|
|
5
|
+
export declare function assertMinor(value: number, label?: string, options?: {
|
|
6
|
+
signed?: boolean;
|
|
7
|
+
positive?: boolean;
|
|
8
|
+
}): number;
|
|
9
|
+
export declare function money(currency: Currency, amountMinor: number): Money;
|
|
10
|
+
export declare function creditUnit(code: string, exponent: number): CreditUnit;
|
|
11
|
+
/**
|
|
12
|
+
* `numerator / denominator` rounded explicitly, for integers only. Grants and
|
|
13
|
+
* refunds pass `'ceil'` (the customer never loses a fraction); charges that
|
|
14
|
+
* favour the customer pass `'floor'`. Fees in the design (upgrade proration)
|
|
15
|
+
* name their own mode.
|
|
16
|
+
*/
|
|
17
|
+
export declare function divRound(numerator: number, denominator: number, mode: RoundingMode): number;
|
|
18
|
+
/** `amount × numerator / denominator`, rounded, without intermediate overflow. */
|
|
19
|
+
export declare function mulDivRound(amount: number, numerator: number, denominator: number, mode: RoundingMode): number;
|
|
20
|
+
/** Render minor units as a plain decimal string (`150000, exp 2 → "1500.00"`). Display formatting is the host's. */
|
|
21
|
+
export declare function formatMinor(amountMinor: number, exponent: number): string;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { BillingError } from './errors.js';
|
|
2
|
+
/** Minor-unit exponent of each fiat currency. */
|
|
3
|
+
export const CURRENCY_EXPONENT = Object.freeze({ VND: 0, USD: 2 });
|
|
4
|
+
/** Throws `invalid_amount` unless `value` is a safe integer (≥ 0 unless `signed`). */
|
|
5
|
+
export function assertMinor(value, label = 'amount', options = {}) {
|
|
6
|
+
if (!Number.isSafeInteger(value)) {
|
|
7
|
+
throw new BillingError('invalid_amount', `${label} must be a safe integer in minor units, got ${value}`, { [label]: value });
|
|
8
|
+
}
|
|
9
|
+
if (options.positive && value <= 0) {
|
|
10
|
+
throw new BillingError('invalid_amount', `${label} must be positive, got ${value}`, { [label]: value });
|
|
11
|
+
}
|
|
12
|
+
if (!options.signed && value < 0) {
|
|
13
|
+
throw new BillingError('invalid_amount', `${label} must not be negative, got ${value}`, { [label]: value });
|
|
14
|
+
}
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
export function money(currency, amountMinor) {
|
|
18
|
+
if (!Object.hasOwn(CURRENCY_EXPONENT, currency))
|
|
19
|
+
throw new BillingError('invalid_input', `unknown currency ${currency}`);
|
|
20
|
+
return { currency, amountMinor: assertMinor(amountMinor, 'amountMinor') };
|
|
21
|
+
}
|
|
22
|
+
export function creditUnit(code, exponent) {
|
|
23
|
+
if (!code)
|
|
24
|
+
throw new BillingError('invalid_input', 'credit unit code is required');
|
|
25
|
+
if (!Number.isInteger(exponent) || exponent < 0 || exponent > 6) {
|
|
26
|
+
throw new BillingError('invalid_input', `credit unit exponent must be an integer 0..6, got ${exponent}`);
|
|
27
|
+
}
|
|
28
|
+
return Object.freeze({ code, exponent });
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* `numerator / denominator` rounded explicitly, for integers only. Grants and
|
|
32
|
+
* refunds pass `'ceil'` (the customer never loses a fraction); charges that
|
|
33
|
+
* favour the customer pass `'floor'`. Fees in the design (upgrade proration)
|
|
34
|
+
* name their own mode.
|
|
35
|
+
*/
|
|
36
|
+
export function divRound(numerator, denominator, mode) {
|
|
37
|
+
assertMinor(numerator, 'numerator', { signed: true });
|
|
38
|
+
assertMinor(denominator, 'denominator', { positive: true });
|
|
39
|
+
return roundQuotient(BigInt(numerator), BigInt(denominator), mode);
|
|
40
|
+
}
|
|
41
|
+
/** `amount × numerator / denominator`, rounded, without intermediate overflow. */
|
|
42
|
+
export function mulDivRound(amount, numerator, denominator, mode) {
|
|
43
|
+
assertMinor(amount, 'amount', { signed: true });
|
|
44
|
+
assertMinor(numerator, 'numerator', { signed: true });
|
|
45
|
+
assertMinor(denominator, 'denominator', { positive: true });
|
|
46
|
+
return roundQuotient(BigInt(amount) * BigInt(numerator), BigInt(denominator), mode);
|
|
47
|
+
}
|
|
48
|
+
function roundQuotient(n, d, mode) {
|
|
49
|
+
let q = n / d;
|
|
50
|
+
const r = n % d;
|
|
51
|
+
if (r !== 0n) {
|
|
52
|
+
const negative = n < 0n;
|
|
53
|
+
if (mode === 'ceil' && !negative)
|
|
54
|
+
q += 1n;
|
|
55
|
+
else if (mode === 'floor' && negative)
|
|
56
|
+
q -= 1n;
|
|
57
|
+
else if (mode === 'half_up' && (r < 0n ? -r : r) * 2n >= d)
|
|
58
|
+
q += negative ? -1n : 1n;
|
|
59
|
+
}
|
|
60
|
+
return toSafe(q);
|
|
61
|
+
}
|
|
62
|
+
/** Render minor units as a plain decimal string (`150000, exp 2 → "1500.00"`). Display formatting is the host's. */
|
|
63
|
+
export function formatMinor(amountMinor, exponent) {
|
|
64
|
+
assertMinor(amountMinor, 'amountMinor', { signed: true });
|
|
65
|
+
if (exponent === 0)
|
|
66
|
+
return String(amountMinor);
|
|
67
|
+
const negative = amountMinor < 0;
|
|
68
|
+
const digits = String(Math.abs(amountMinor)).padStart(exponent + 1, '0');
|
|
69
|
+
const out = `${digits.slice(0, -exponent)}.${digits.slice(-exponent)}`;
|
|
70
|
+
return negative ? `-${out}` : out;
|
|
71
|
+
}
|
|
72
|
+
function toSafe(value) {
|
|
73
|
+
if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
|
|
74
|
+
throw new BillingError('balance_overflow', `result ${value} exceeds the safe integer range`);
|
|
75
|
+
}
|
|
76
|
+
return Number(value);
|
|
77
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public domain types of `@tofound/billing` — part of the `billing.public-api`
|
|
3
|
+
* contract. Additive changes only within 0.x minors; every amount is an
|
|
4
|
+
* integer in minor units (no float math anywhere in the library).
|
|
5
|
+
*/
|
|
6
|
+
/** Fiat currencies a market prices in. */
|
|
7
|
+
export type Currency = 'VND' | 'USD';
|
|
8
|
+
/** A fiat amount in the currency's minor unit (VND exponent 0, USD 2). */
|
|
9
|
+
export interface Money {
|
|
10
|
+
currency: Currency;
|
|
11
|
+
amountMinor: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A host's store of value. Balances and ledger deltas are integers in
|
|
15
|
+
* `10^-exponent` of one unit: Lohi `{code:'LT', exponent:0}`, 2Novel
|
|
16
|
+
* `{code:'credit', exponent:2}` (1 minor unit = 1 đ at 100 đ = 1 credit).
|
|
17
|
+
*/
|
|
18
|
+
export interface CreditUnit {
|
|
19
|
+
code: string;
|
|
20
|
+
exponent: number;
|
|
21
|
+
}
|
|
22
|
+
/** Rounding of a non-integral result; grants and refunds favour the customer. */
|
|
23
|
+
export type RoundingMode = 'floor' | 'ceil' | 'half_up';
|
|
24
|
+
/** The host's subject id: a 2Novel workspace id or a Lohi user id. */
|
|
25
|
+
export type AccountId = string;
|
|
26
|
+
export declare const ENTRY_KINDS: readonly ["topup", "grant", "spend", "refund", "plan_purchase", "plan_renewal", "plan_refund", "reversal", "conversion", "resync", "adjustment"];
|
|
27
|
+
export type EntryKind = (typeof ENTRY_KINDS)[number];
|
|
28
|
+
/** JSON-serialisable metadata carried on an entry. */
|
|
29
|
+
export type EntryMeta = Record<string, unknown>;
|
|
30
|
+
/**
|
|
31
|
+
* One append-only ledger row. Invariants (I1–I6): `balanceAfter` =
|
|
32
|
+
* previous `balanceAfter` + `delta`, `seq` contiguous per account,
|
|
33
|
+
* `balanceAfter` ≥ 0, `idempotencyKey` globally unique, entries never change.
|
|
34
|
+
*/
|
|
35
|
+
export interface LedgerEntry {
|
|
36
|
+
id: string;
|
|
37
|
+
accountId: AccountId;
|
|
38
|
+
seq: number;
|
|
39
|
+
/** Signed, in credit minor units. */
|
|
40
|
+
delta: number;
|
|
41
|
+
balanceAfter: number;
|
|
42
|
+
kind: EntryKind;
|
|
43
|
+
/** Host label kept for analytics, e.g. Lohi `tts_pro`. */
|
|
44
|
+
reason: string | null;
|
|
45
|
+
idempotencyKey: string;
|
|
46
|
+
sourceType: string | null;
|
|
47
|
+
sourceId: string | null;
|
|
48
|
+
/** The entry this one reverses (kind `reversal`). */
|
|
49
|
+
reversesId: string | null;
|
|
50
|
+
meta: EntryMeta | null;
|
|
51
|
+
createdAt: Date;
|
|
52
|
+
}
|
|
53
|
+
/** The materialized balance of one account. */
|
|
54
|
+
export interface AccountState {
|
|
55
|
+
accountId: AccountId;
|
|
56
|
+
balance: number;
|
|
57
|
+
/** Seq of the last entry; 0 for an account with no entries. */
|
|
58
|
+
seq: number;
|
|
59
|
+
}
|
|
60
|
+
/** Where a posting came from (a job, a checkout, an admin request …). */
|
|
61
|
+
export interface EntrySource {
|
|
62
|
+
type: string;
|
|
63
|
+
id: string;
|
|
64
|
+
}
|
|
65
|
+
/** A credit or debit request. `amount` is a positive safe integer. */
|
|
66
|
+
export interface PostInput {
|
|
67
|
+
accountId: AccountId;
|
|
68
|
+
kind: EntryKind;
|
|
69
|
+
amount: number;
|
|
70
|
+
idempotencyKey: string;
|
|
71
|
+
reason?: string | null;
|
|
72
|
+
source?: EntrySource | null;
|
|
73
|
+
meta?: EntryMeta | null;
|
|
74
|
+
}
|
|
75
|
+
/** A partial or full counter-entry for an existing entry. */
|
|
76
|
+
export interface ReverseInput {
|
|
77
|
+
entryId: string;
|
|
78
|
+
idempotencyKey: string;
|
|
79
|
+
/** Defaults to |original delta|; at most that. */
|
|
80
|
+
amount?: number;
|
|
81
|
+
reason?: string | null;
|
|
82
|
+
meta?: EntryMeta | null;
|
|
83
|
+
}
|
|
84
|
+
/** Domain events a host maps onto its own bus (design §13). */
|
|
85
|
+
export type BillingEvent = {
|
|
86
|
+
type: 'credited';
|
|
87
|
+
accountId: AccountId;
|
|
88
|
+
entry: LedgerEntry;
|
|
89
|
+
} | {
|
|
90
|
+
type: 'debited';
|
|
91
|
+
accountId: AccountId;
|
|
92
|
+
entry: LedgerEntry;
|
|
93
|
+
};
|
|
94
|
+
export interface PostResult {
|
|
95
|
+
entry: LedgerEntry;
|
|
96
|
+
/** True when the idempotency key had already been posted with the same intent. */
|
|
97
|
+
replayed: boolean;
|
|
98
|
+
/**
|
|
99
|
+
* Events of this posting (empty on replay). When the ledger owns the
|
|
100
|
+
* transaction they are also sent to the configured sink after commit;
|
|
101
|
+
* under `ledger.in(tx)` the host emits them after its own commit.
|
|
102
|
+
*/
|
|
103
|
+
events: BillingEvent[];
|
|
104
|
+
}
|
|
105
|
+
export interface DebitUpToResult extends PostResult {
|
|
106
|
+
requested: number;
|
|
107
|
+
/** `requested − posted`; recorded on the entry as `meta.debitUpTo`. */
|
|
108
|
+
shortfall: number;
|
|
109
|
+
}
|
|
110
|
+
export interface EntryPage {
|
|
111
|
+
entries: LedgerEntry[];
|
|
112
|
+
/** Pass as `beforeSeq` for the next (older) page; null when exhausted. */
|
|
113
|
+
nextBeforeSeq: number | null;
|
|
114
|
+
}
|
|
115
|
+
export type BillingErrorCode = 'insufficient_credits' | 'idempotency_mismatch' | 'invalid_amount' | 'invalid_input' | 'entry_not_found' | 'reversal_exceeds_original' | 'already_reversed' | 'balance_overflow';
|
|
116
|
+
/** Details carried by `insufficient_credits`. */
|
|
117
|
+
export interface InsufficientCredits {
|
|
118
|
+
balance: number;
|
|
119
|
+
required: number;
|
|
120
|
+
shortfall: number;
|
|
121
|
+
}
|
|
122
|
+
/** How a settlement ends. `blocked` means it cannot, and why is in `reason`. */
|
|
123
|
+
export type Settlement = 'free' | 'quota' | 'wallet' | 'blocked';
|
|
124
|
+
/** A code the host labels; the library never composes user-facing copy. */
|
|
125
|
+
export interface QuoteReason {
|
|
126
|
+
code: string;
|
|
127
|
+
label?: string;
|
|
128
|
+
detail?: string;
|
|
129
|
+
}
|
|
130
|
+
/** One line of the settlement plan, in waterfall order. */
|
|
131
|
+
export interface FundingLine {
|
|
132
|
+
/** Step source, e.g. `byok`, `subscription_quota`, `wallet`. */
|
|
133
|
+
source: string;
|
|
134
|
+
/** What `amount` is denominated in: the credit unit code for money lines. */
|
|
135
|
+
unit: string;
|
|
136
|
+
amount: number;
|
|
137
|
+
/** Pool size before/after this line; `null` = unmetered. */
|
|
138
|
+
remainingBefore: number | null;
|
|
139
|
+
remainingAfter: number | null;
|
|
140
|
+
label?: string;
|
|
141
|
+
}
|
|
142
|
+
export interface Quote {
|
|
143
|
+
/** List price in credit minor units, before anything is applied. */
|
|
144
|
+
originalPrice: number;
|
|
145
|
+
/** What the wallet will actually be debited. */
|
|
146
|
+
price: number;
|
|
147
|
+
/** The credit unit code. */
|
|
148
|
+
currency: string;
|
|
149
|
+
reason: QuoteReason;
|
|
150
|
+
/** The plan in walk order; `funding[0]` is the primary source. */
|
|
151
|
+
funding: FundingLine[];
|
|
152
|
+
settlement: Settlement;
|
|
153
|
+
canSettle: boolean;
|
|
154
|
+
/** Credit minor units short; present only when `settlement === 'blocked'` for money. */
|
|
155
|
+
shortfall?: number;
|
|
156
|
+
/** `null` when the state has no account (guest). */
|
|
157
|
+
balance: number | null;
|
|
158
|
+
/** The plan that would remove this charge, when one would. */
|
|
159
|
+
upsell?: {
|
|
160
|
+
plan: string;
|
|
161
|
+
label?: string;
|
|
162
|
+
};
|
|
163
|
+
/** A quote is a forecast; settle re-derives everything. */
|
|
164
|
+
expiresInSec: number;
|
|
165
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public domain types of `@tofound/billing` — part of the `billing.public-api`
|
|
3
|
+
* contract. Additive changes only within 0.x minors; every amount is an
|
|
4
|
+
* integer in minor units (no float math anywhere in the library).
|
|
5
|
+
*/
|
|
6
|
+
export const ENTRY_KINDS = [
|
|
7
|
+
'topup',
|
|
8
|
+
'grant',
|
|
9
|
+
'spend',
|
|
10
|
+
'refund',
|
|
11
|
+
'plan_purchase',
|
|
12
|
+
'plan_renewal',
|
|
13
|
+
'plan_refund',
|
|
14
|
+
'reversal',
|
|
15
|
+
'conversion',
|
|
16
|
+
'resync',
|
|
17
|
+
'adjustment',
|
|
18
|
+
];
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { billingTableBuilder, checkAdditiveDdl, createBillingTables, DEFAULT_PREFIX, type BillingSchemaConfig, type BillingTables, type CheckAdditiveDdlOptions, type DdlRule, type DdlViolation, } from './schema-factory.js';
|
|
2
|
+
export { createDrizzleLedgerStore, type AnyPgDatabase, type AnyPgTransaction, type DrizzleLedgerStoreOptions, } from './store.js';
|
|
3
|
+
export { createDrizzleIngestStore, createIngestTables, ingestTableNames, type DrizzleIngestStoreOptions, type IngestTables, } from '../inbox/drizzle.js';
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { billingTableBuilder, checkAdditiveDdl, createBillingTables, DEFAULT_PREFIX, } from './schema-factory.js';
|
|
2
|
+
export { createDrizzleLedgerStore, } from './store.js';
|
|
3
|
+
export { createDrizzleIngestStore, createIngestTables, ingestTableNames, } from '../inbox/drizzle.js';
|