@tofound/billing 0.1.0 → 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 +76 -0
- package/README.md +58 -13
- package/dist/catalog/catalog.d.ts +115 -0
- package/dist/catalog/catalog.js +201 -0
- package/dist/domain/types.d.ts +3 -1
- package/dist/drizzle/index.d.ts +2 -0
- package/dist/drizzle/index.js +2 -0
- package/dist/entitlement/resolve.d.ts +76 -0
- package/dist/entitlement/resolve.js +122 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +9 -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 +6 -0
- package/dist/renewal/renewal.d.ts +69 -0
- package/dist/renewal/renewal.js +198 -0
- package/dist/stores/testing.d.ts +4 -2
- package/dist/stores/testing.js +4 -2
- 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 +223 -4
- package/docs/SCHEMA.md +57 -2
- package/package.json +6 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,82 @@
|
|
|
3
3
|
All notable changes to `@tofound/billing`. Versions follow semver; 0.x minors
|
|
4
4
|
are additive.
|
|
5
5
|
|
|
6
|
+
## 0.2.0 — 2026-10-18
|
|
7
|
+
|
|
8
|
+
Additive to 0.1: every 0.1 export is unchanged (public-api declaration
|
|
9
|
+
snapshot only grows). One type widens: `BillingErrorCode` gains five members
|
|
10
|
+
(below), so an exhaustive `switch` over it in a consumer needs the new cases
|
|
11
|
+
(or a `default`) to typecheck.
|
|
12
|
+
|
|
13
|
+
To adopt: pin `@tofound/billing@0.2.0`. If you use terms, export the tables
|
|
14
|
+
`createTermTables` returns from your drizzle schema and run `db:generate`.
|
|
15
|
+
|
|
16
|
+
- Catalog as config (`defineCatalog`): plans with strict ranks and one free
|
|
17
|
+
plan, N-month credit offers per market, provider offers by `productRef`,
|
|
18
|
+
credit packs and policies (`termDays`, `upgradeProration`, `graceDays`,
|
|
19
|
+
`renewalLeadSec`). Validated and frozen at boot (`invalid_catalog`).
|
|
20
|
+
- Terms (`Term`, `TermStore`): one shape for credit, Polar, Apple and Google
|
|
21
|
+
subscriptions; memory store and Drizzle tables/store (`createTermTables`,
|
|
22
|
+
`createDrizzleTermStore`, `termTableNames` in `/drizzle`); term store
|
|
23
|
+
conformance cases in `/testing`. **Schema:** two new tables,
|
|
24
|
+
`<prefix>terms` and the per-account lock row `<prefix>term_accounts` —
|
|
25
|
+
add `createTermTables(...)` to your drizzle schema and run `db:generate`
|
|
26
|
+
(additive: new tables and indexes only).
|
|
27
|
+
- Entitlement (`resolveEntitlement`): stacking S1–S5 across sources —
|
|
28
|
+
highest rank wins, then the later end; credit terms carry no included pool;
|
|
29
|
+
warnings `two_subscriptions`, `past_due`, `renewal_shortfall`,
|
|
30
|
+
`scheduled_downgrade`; nothing entitled → the free plan.
|
|
31
|
+
- Plans (`createPlans`): quote and buy N months with credits through one
|
|
32
|
+
waterfall — new, extend (S2), upgrade with host-policy proration
|
|
33
|
+
(`remaining_time`: ceil(remaining/total × (offerNew − paid)), end date kept;
|
|
34
|
+
or `none`), renew a past_due term, downgrade scheduled with no money moved
|
|
35
|
+
(S3b), blocked when a renewing subscription of ≥ rank covers it (S3,
|
|
36
|
+
`plan_blocked`); idempotent purchase keys; auto-renew on/off, cancel,
|
|
37
|
+
cancel now.
|
|
38
|
+
- Renewal (`createRenewal`): charges the live catalog price at period end
|
|
39
|
+
(`renew:<termId>:<periodEnd>`, a double run debits once); a short balance →
|
|
40
|
+
`past_due` with `graceDays` of entitlement; `retryPastDue` after a top-up
|
|
41
|
+
renews from the old end; grace passed → expired → free; scheduled terms
|
|
42
|
+
activate when they start; a failed early attempt (`renewalLeadSec`) keeps
|
|
43
|
+
the paid period active and is retried by the next run.
|
|
44
|
+
- Provider subscriptions (`createSnapshotHandler` for the ingest
|
|
45
|
+
`subscription.snapshot` slot): upserts the provider term under a watermark;
|
|
46
|
+
an entitled subscription of ≥ rank supersedes the credit term and refunds
|
|
47
|
+
its unused share pro rata (`plan_refund`, `supersede:<termId>`, rounded up);
|
|
48
|
+
an account `resolveAccount` does not know is ignored as unmatched and
|
|
49
|
+
relayed through `onUnmatched`.
|
|
50
|
+
- Polar adapter (`@tofound/billing/providers/polar`, new entry point):
|
|
51
|
+
`createPolarAdapter` for the ingest inbox, with Standard Webhooks
|
|
52
|
+
verification before any parse (both secret derivations, a rotation list,
|
|
53
|
+
a 300 s replay window). It normalizes three kinds of event:
|
|
54
|
+
- subscriptions → `subscription.snapshot`, for `createSnapshotHandler`;
|
|
55
|
+
- one-time **credit-pack orders** bound to a checkout session →
|
|
56
|
+
`purchase.completed`, credited once;
|
|
57
|
+
- **full refunds** → `purchase.reversed` (a ledger reversal). A partial
|
|
58
|
+
refund goes to `needs_review`.
|
|
59
|
+
|
|
60
|
+
An order's amount is the catalog price, `subtotal_amount −
|
|
61
|
+
discount_amount`, so tax-inclusive (EU buyers under tax behaviour
|
|
62
|
+
`location`), tax-exclusive and untaxed orders all credit the full pack;
|
|
63
|
+
refunds use the same basis. Polar's same-instant subscription events (one
|
|
64
|
+
revoke as `updated`, `canceled`, `revoked`) are ordered by type through the
|
|
65
|
+
new optional `SubscriptionSnapshotEvent.tieBreak`, which the snapshot handler
|
|
66
|
+
compares before the event id, and the period ends at `ended_at`.
|
|
67
|
+
`redactPolarPayload` also scrubs Polar secrets inside values, such as the
|
|
68
|
+
checkout client secret in a checkout `url`.
|
|
69
|
+
|
|
70
|
+
`createCheckout` opens one-time checkouts and `createPortalSession` opens
|
|
71
|
+
customer portal sessions. `resolvePolarEnvironment` makes the environment
|
|
72
|
+
explicit and refuses an unarmed production. Also exported:
|
|
73
|
+
`respondPolar`, `redactPolarPayload`, `signPolarWebhook` (test
|
|
74
|
+
deliveries), `PolarApiError` and the webhook header constants.
|
|
75
|
+
- Error codes: `invalid_catalog`, `plan_not_found`, `offer_not_found`,
|
|
76
|
+
`term_not_found`, `plan_blocked`. They widen the `BillingErrorCode` union,
|
|
77
|
+
so check exhaustive switches.
|
|
78
|
+
- Docs: the README describes 0.2 and links only to files shipped in the
|
|
79
|
+
package (no private-repo links). `docs/SCHEMA.md` names the tables each
|
|
80
|
+
factory returns. `docs/API.md` documents the `walletDelta` sign.
|
|
81
|
+
|
|
6
82
|
## 0.1.0 — 2026-10-17
|
|
7
83
|
|
|
8
84
|
First release (baseline: repository start).
|
package/README.md
CHANGED
|
@@ -4,15 +4,25 @@
|
|
|
4
4
|
products (2Novel first, the Lohi reader api last). Each host API embeds it on
|
|
5
5
|
its own database; there is no billing service.
|
|
6
6
|
|
|
7
|
-
0.
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
and
|
|
7
|
+
0.2 ships:
|
|
8
|
+
|
|
9
|
+
- **The money core** (since 0.1): an idempotent, no-overdraft credit ledger
|
|
10
|
+
behind store ports, memory and Drizzle/Postgres stores, a Drizzle schema
|
|
11
|
+
factory the host re-exports and migrates itself, one quote/charge waterfall
|
|
12
|
+
and a payment webhook inbox (verify → persist → apply exactly once).
|
|
13
|
+
- **Catalog, terms and entitlement** (0.2): the catalog as host config
|
|
14
|
+
(`defineCatalog`), subscription terms from credits, Polar, Apple and Google in
|
|
15
|
+
one shape, `resolveEntitlement` (stacking rules S1–S5), buying N months with
|
|
16
|
+
credits (`createPlans`: extend, prorated upgrade, scheduled downgrade),
|
|
17
|
+
renewal at the live price with `past_due` + grace (`createRenewal`), and
|
|
18
|
+
provider snapshots that supersede a credit term with a pro-rata refund
|
|
19
|
+
(`createSnapshotHandler`).
|
|
20
|
+
- **Providers**: SePay (`@tofound/billing/providers/sepay`) and, new in 0.2,
|
|
21
|
+
Polar (`@tofound/billing/providers/polar`). Apple and Google adapters are
|
|
22
|
+
not in 0.2 yet; their terms already fit the 0.2 shape.
|
|
13
23
|
|
|
14
24
|
```sh
|
|
15
|
-
bun add @tofound/billing@0.
|
|
25
|
+
bun add @tofound/billing@0.2.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
|
|
16
26
|
```
|
|
17
27
|
|
|
18
28
|
```ts
|
|
@@ -26,10 +36,45 @@ const ledger = createLedger({ store: createDrizzleLedgerStore({ db, tables: { bi
|
|
|
26
36
|
await db.transaction((tx) => ledger.in(tx).debit({ accountId, kind: 'spend', amount, idempotencyKey: `job:${id}:charge` }))
|
|
27
37
|
```
|
|
28
38
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
39
|
+
Plans, terms and entitlement run on the same `db`:
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { createPlans, createRenewal, defineCatalog, resolveEntitlement } from '@tofound/billing'
|
|
43
|
+
import { createDrizzleTermStore, createTermTables } from '@tofound/billing/drizzle'
|
|
44
|
+
|
|
45
|
+
export const { billingTerms, billingTermAccounts } = createTermTables({ accountId: (n) => uuid(n).notNull() })
|
|
46
|
+
const catalog = defineCatalog(hostCatalogConfig) // plans, prices, policies: the host's data, never the library's
|
|
47
|
+
const terms = createDrizzleTermStore({ db, tables: { billingTerms, billingTermAccounts } })
|
|
48
|
+
const plans = createPlans({ ledger, terms, catalog })
|
|
49
|
+
const renewal = createRenewal({ ledger, terms, catalog })
|
|
50
|
+
const ent = resolveEntitlement(await terms.reader().listTerms(accountId), new Date(), catalog)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Polar
|
|
54
|
+
|
|
55
|
+
`@tofound/billing/providers/polar` is a webhook and checkout adapter for the
|
|
56
|
+
ingest inbox. `createPolarAdapter({ environment, webhookSecrets, products,
|
|
57
|
+
accessToken })` verifies Standard Webhooks signatures (secret rotation, 300 s
|
|
58
|
+
replay window) before parsing. It normalizes Polar subscriptions to
|
|
59
|
+
`subscription.snapshot` (applied by `createSnapshotHandler`), one-time credit
|
|
60
|
+
pack orders to `purchase.completed` and full refunds to `purchase.reversed`.
|
|
61
|
+
It also opens checkouts (`createCheckout`) and customer portal sessions.
|
|
62
|
+
`resolvePolarEnvironment` turns the host's environment and production-arming
|
|
63
|
+
switches into one required value. `signPolarWebhook` signs test deliveries.
|
|
64
|
+
The full entry is in `docs/API.md`.
|
|
65
|
+
|
|
66
|
+
## Documentation
|
|
67
|
+
|
|
68
|
+
These files ship inside the package (`node_modules/@tofound/billing/…`):
|
|
69
|
+
|
|
70
|
+
- `docs/API.md`: ledger, ports, waterfall, inbox, providers, catalog, terms,
|
|
71
|
+
entitlement, renewal and error codes.
|
|
72
|
+
- `docs/SCHEMA.md`: the schema factory, the tables each factory returns and the
|
|
73
|
+
additive migration rules.
|
|
74
|
+
- `CHANGELOG.md`: what each version adds, and what a host must do to adopt it.
|
|
33
75
|
|
|
34
|
-
Develop with bun ≥ 1.3.14: `bun install`, then `bun run check` (
|
|
35
|
-
Postgres
|
|
76
|
+
Develop with bun ≥ 1.3.14: `bun install`, then `bun run check` (typecheck,
|
|
77
|
+
build, tests on memory and Postgres, pack smoke). It needs a local Postgres
|
|
78
|
+
`initdb` (`PG_BIN` or a Homebrew `postgresql@17`), or
|
|
79
|
+
`BILLING_TEST_DATABASE_URL`, in which it creates a throwaway schema. Never
|
|
80
|
+
point it at a shared or production database.
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { CreditUnit, Currency, Money } from '../domain/types.js';
|
|
2
|
+
/** A market the host prices in; the API sets it per account, the user never picks it (D11). */
|
|
3
|
+
export interface MarketSpec {
|
|
4
|
+
key: string;
|
|
5
|
+
currency: Currency;
|
|
6
|
+
}
|
|
7
|
+
/** N months of a plan bought with credits (the VN path). */
|
|
8
|
+
export interface CreditOffer {
|
|
9
|
+
source: 'credit';
|
|
10
|
+
market: string;
|
|
11
|
+
months: number;
|
|
12
|
+
/** Credit minor units for the whole `months`. */
|
|
13
|
+
credits: number;
|
|
14
|
+
}
|
|
15
|
+
/** A provider-billed offer; `productRef` maps to the provider's product id in host config. */
|
|
16
|
+
export interface ProviderOffer {
|
|
17
|
+
source: 'polar' | 'apple' | 'google';
|
|
18
|
+
productRef: string;
|
|
19
|
+
market?: string;
|
|
20
|
+
interval?: 'month' | 'year';
|
|
21
|
+
price?: Money;
|
|
22
|
+
/** Google base plan id. */
|
|
23
|
+
basePlan?: string;
|
|
24
|
+
}
|
|
25
|
+
export type PlanOffer = CreditOffer | ProviderOffer;
|
|
26
|
+
export interface PlanSpec {
|
|
27
|
+
key: string;
|
|
28
|
+
/** Strictly ordered across plans; higher wins (S1). */
|
|
29
|
+
rank: number;
|
|
30
|
+
/** The plan an account without an entitled term resolves to. Exactly one, the lowest rank, with no offers. */
|
|
31
|
+
free?: boolean;
|
|
32
|
+
permissions?: readonly string[];
|
|
33
|
+
quotas?: Readonly<Record<string, number>>;
|
|
34
|
+
/** Per-period credit pool of provider-funded terms only (A1). */
|
|
35
|
+
includedCredits?: number;
|
|
36
|
+
offers?: readonly PlanOffer[];
|
|
37
|
+
}
|
|
38
|
+
export type PackProvider = 'sepay' | 'polar' | 'apple' | 'google';
|
|
39
|
+
export interface CreditPackSpec {
|
|
40
|
+
key: string;
|
|
41
|
+
market: string;
|
|
42
|
+
provider: PackProvider;
|
|
43
|
+
price: Money;
|
|
44
|
+
credits: number;
|
|
45
|
+
bonusCredits?: number;
|
|
46
|
+
productRef?: string;
|
|
47
|
+
}
|
|
48
|
+
export type UpgradeProration = 'remaining_time' | 'none';
|
|
49
|
+
export type ReversalShortfallPolicy = 'lapse_credit_terms' | 'record';
|
|
50
|
+
export interface CatalogPolicies {
|
|
51
|
+
/** Days in one catalog month; a term of N months lasts N × termDays. */
|
|
52
|
+
termDays: number;
|
|
53
|
+
/** 2Novel `remaining_time`, Lohi `none` (D8). */
|
|
54
|
+
upgradeProration: UpgradeProration;
|
|
55
|
+
/** Days a failed renewal stays entitled as `past_due` (D9). */
|
|
56
|
+
graceDays: number;
|
|
57
|
+
reversalShortfall: ReversalShortfallPolicy;
|
|
58
|
+
/** How early `renewDue` may renew before the period end. */
|
|
59
|
+
renewalLeadSec: number;
|
|
60
|
+
}
|
|
61
|
+
export declare const DEFAULT_POLICIES: Readonly<CatalogPolicies>;
|
|
62
|
+
export interface CatalogSpec {
|
|
63
|
+
version: string | number;
|
|
64
|
+
creditUnit: CreditUnit;
|
|
65
|
+
markets: readonly MarketSpec[];
|
|
66
|
+
plans: readonly PlanSpec[];
|
|
67
|
+
creditPacks?: readonly CreditPackSpec[];
|
|
68
|
+
policies?: Partial<CatalogPolicies>;
|
|
69
|
+
/** Longest plan/pack key the host can store (Lohi `user_subscriptions.tier` is 16). Default 64. */
|
|
70
|
+
maxKeyLength?: number;
|
|
71
|
+
}
|
|
72
|
+
export interface Plan {
|
|
73
|
+
key: string;
|
|
74
|
+
rank: number;
|
|
75
|
+
free: boolean;
|
|
76
|
+
permissions: readonly string[];
|
|
77
|
+
quotas: Readonly<Record<string, number>>;
|
|
78
|
+
includedCredits: number | null;
|
|
79
|
+
offers: readonly PlanOffer[];
|
|
80
|
+
}
|
|
81
|
+
export type CreditPack = Readonly<Required<Omit<CreditPackSpec, 'productRef'>>> & {
|
|
82
|
+
readonly productRef: string | null;
|
|
83
|
+
};
|
|
84
|
+
export type ProductMatch = {
|
|
85
|
+
kind: 'plan';
|
|
86
|
+
plan: Plan;
|
|
87
|
+
offer: ProviderOffer;
|
|
88
|
+
} | {
|
|
89
|
+
kind: 'pack';
|
|
90
|
+
pack: CreditPack;
|
|
91
|
+
};
|
|
92
|
+
export interface Catalog {
|
|
93
|
+
readonly version: string | number;
|
|
94
|
+
readonly creditUnit: CreditUnit;
|
|
95
|
+
readonly markets: readonly MarketSpec[];
|
|
96
|
+
readonly policies: Readonly<CatalogPolicies>;
|
|
97
|
+
/** Every plan, lowest rank first. */
|
|
98
|
+
readonly plans: readonly Plan[];
|
|
99
|
+
readonly creditPacks: readonly CreditPack[];
|
|
100
|
+
readonly freePlan: Plan;
|
|
101
|
+
/** Throws `plan_not_found`. */
|
|
102
|
+
plan(key: string): Plan;
|
|
103
|
+
findPlan(key: string): Plan | undefined;
|
|
104
|
+
plansWithPermission(permission: string): Plan[];
|
|
105
|
+
market(key: string): MarketSpec | undefined;
|
|
106
|
+
creditOffer(plan: string, market: string, months: number): CreditOffer | undefined;
|
|
107
|
+
/** Credit offers of a plan in a market, fewest months first. */
|
|
108
|
+
creditOffers(plan: string, market: string): CreditOffer[];
|
|
109
|
+
pack(key: string): CreditPack | undefined;
|
|
110
|
+
packsFor(market: string, provider?: PackProvider): CreditPack[];
|
|
111
|
+
/** The plan offer or credit pack a provider product ref names. */
|
|
112
|
+
offerByProductRef(productRef: string): ProductMatch | undefined;
|
|
113
|
+
}
|
|
114
|
+
/** Validate and freeze a host catalog. */
|
|
115
|
+
export declare function defineCatalog(spec: CatalogSpec): Catalog;
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Catalog as config (design §4.4). The library ships no plan, price or tier
|
|
3
|
+
* literal: a host passes its own catalog values to `defineCatalog`, which
|
|
4
|
+
* validates and freezes them and answers the lookups the terms, renewal and
|
|
5
|
+
* entitlement code need. Errors are `BillingError('invalid_catalog')` at
|
|
6
|
+
* definition time, so a broken catalog fails at boot, not at checkout.
|
|
7
|
+
*/
|
|
8
|
+
import { BillingError } from '../domain/errors.js';
|
|
9
|
+
import { CURRENCY_EXPONENT } from '../domain/money.js';
|
|
10
|
+
export const DEFAULT_POLICIES = Object.freeze({
|
|
11
|
+
termDays: 30,
|
|
12
|
+
upgradeProration: 'remaining_time',
|
|
13
|
+
graceDays: 3,
|
|
14
|
+
reversalShortfall: 'record',
|
|
15
|
+
renewalLeadSec: 0,
|
|
16
|
+
});
|
|
17
|
+
const KEY = /^[a-z0-9][a-z0-9_.-]*$/;
|
|
18
|
+
function fail(message, details = {}) {
|
|
19
|
+
throw new BillingError('invalid_catalog', message, details);
|
|
20
|
+
}
|
|
21
|
+
function safeInt(value, what, min) {
|
|
22
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min)
|
|
23
|
+
fail(`${what} must be a safe integer ≥ ${min}, got ${String(value)}`);
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
/** Validate and freeze a host catalog. */
|
|
27
|
+
export function defineCatalog(spec) {
|
|
28
|
+
const maxKeyLength = spec.maxKeyLength ?? 64;
|
|
29
|
+
safeInt(maxKeyLength, 'maxKeyLength', 1);
|
|
30
|
+
const checkKey = (key, what) => {
|
|
31
|
+
if (typeof key !== 'string' || !KEY.test(key))
|
|
32
|
+
fail(`${what} key must be lower-case [a-z0-9_.-], got ${JSON.stringify(key)}`);
|
|
33
|
+
if (key.length > maxKeyLength)
|
|
34
|
+
fail(`${what} key ${key} is longer than ${maxKeyLength}`, { key });
|
|
35
|
+
return key;
|
|
36
|
+
};
|
|
37
|
+
const unit = spec.creditUnit;
|
|
38
|
+
if (!unit?.code || !Number.isInteger(unit.exponent) || unit.exponent < 0 || unit.exponent > 6)
|
|
39
|
+
fail('creditUnit needs a code and an exponent 0..6');
|
|
40
|
+
const policies = { ...DEFAULT_POLICIES, ...(spec.policies ?? {}) };
|
|
41
|
+
safeInt(policies.termDays, 'policies.termDays', 1);
|
|
42
|
+
safeInt(policies.graceDays, 'policies.graceDays', 0);
|
|
43
|
+
safeInt(policies.renewalLeadSec, 'policies.renewalLeadSec', 0);
|
|
44
|
+
if (!['remaining_time', 'none'].includes(policies.upgradeProration))
|
|
45
|
+
fail(`unknown upgradeProration ${policies.upgradeProration}`);
|
|
46
|
+
if (!['lapse_credit_terms', 'record'].includes(policies.reversalShortfall))
|
|
47
|
+
fail(`unknown reversalShortfall ${policies.reversalShortfall}`);
|
|
48
|
+
if (!spec.markets?.length)
|
|
49
|
+
fail('a catalog needs at least one market');
|
|
50
|
+
const markets = new Map();
|
|
51
|
+
for (const m of spec.markets) {
|
|
52
|
+
checkKey(m.key, 'market');
|
|
53
|
+
if (markets.has(m.key))
|
|
54
|
+
fail(`duplicate market ${m.key}`);
|
|
55
|
+
if (!Object.hasOwn(CURRENCY_EXPONENT, m.currency))
|
|
56
|
+
fail(`market ${m.key}: unknown currency ${m.currency}`);
|
|
57
|
+
markets.set(m.key, Object.freeze({ key: m.key, currency: m.currency }));
|
|
58
|
+
}
|
|
59
|
+
const checkMoney = (price, market, what) => {
|
|
60
|
+
if (!price)
|
|
61
|
+
return;
|
|
62
|
+
if (!Object.hasOwn(CURRENCY_EXPONENT, price.currency))
|
|
63
|
+
fail(`${what}: unknown currency ${price.currency}`);
|
|
64
|
+
safeInt(price.amountMinor, `${what} price`, 1);
|
|
65
|
+
const m = market === undefined ? undefined : markets.get(market);
|
|
66
|
+
if (m && m.currency !== price.currency)
|
|
67
|
+
fail(`${what}: price in ${price.currency} but market ${m.key} prices in ${m.currency}`);
|
|
68
|
+
};
|
|
69
|
+
const checkMarket = (market, what) => {
|
|
70
|
+
if (market !== undefined && !markets.has(market))
|
|
71
|
+
fail(`${what}: unknown market ${market}`);
|
|
72
|
+
};
|
|
73
|
+
const productRefs = new Map();
|
|
74
|
+
const claimRef = (ref, match, what) => {
|
|
75
|
+
if (typeof ref !== 'string' || !ref)
|
|
76
|
+
fail(`${what}: productRef is required`);
|
|
77
|
+
if (productRefs.has(ref))
|
|
78
|
+
fail(`duplicate productRef ${ref}`, { productRef: ref });
|
|
79
|
+
productRefs.set(ref, match);
|
|
80
|
+
};
|
|
81
|
+
if (!spec.plans?.length)
|
|
82
|
+
fail('a catalog needs at least one plan');
|
|
83
|
+
const byKey = new Map();
|
|
84
|
+
const ranks = new Set();
|
|
85
|
+
for (const p of spec.plans) {
|
|
86
|
+
checkKey(p.key, 'plan');
|
|
87
|
+
if (byKey.has(p.key))
|
|
88
|
+
fail(`duplicate plan ${p.key}`);
|
|
89
|
+
safeInt(p.rank, `plan ${p.key} rank`, 0);
|
|
90
|
+
if (ranks.has(p.rank))
|
|
91
|
+
fail(`plan ranks must be strictly ordered; rank ${p.rank} repeats at ${p.key}`);
|
|
92
|
+
ranks.add(p.rank);
|
|
93
|
+
for (const [name, value] of Object.entries(p.quotas ?? {}))
|
|
94
|
+
safeInt(value, `plan ${p.key} quota ${name}`, 0);
|
|
95
|
+
if (p.includedCredits !== undefined)
|
|
96
|
+
safeInt(p.includedCredits, `plan ${p.key} includedCredits`, 0);
|
|
97
|
+
const offers = [];
|
|
98
|
+
const plan = {
|
|
99
|
+
key: p.key,
|
|
100
|
+
rank: p.rank,
|
|
101
|
+
free: p.free === true,
|
|
102
|
+
permissions: Object.freeze([...(p.permissions ?? [])]),
|
|
103
|
+
quotas: Object.freeze({ ...(p.quotas ?? {}) }),
|
|
104
|
+
includedCredits: p.includedCredits ?? null,
|
|
105
|
+
offers,
|
|
106
|
+
};
|
|
107
|
+
const creditMonths = new Set();
|
|
108
|
+
for (const o of p.offers ?? []) {
|
|
109
|
+
const what = `plan ${p.key} ${o.source} offer`;
|
|
110
|
+
if (o.source === 'credit') {
|
|
111
|
+
checkMarket(o.market, what);
|
|
112
|
+
if (o.market === undefined)
|
|
113
|
+
fail(`${what}: market is required`);
|
|
114
|
+
safeInt(o.months, `${what} months`, 1);
|
|
115
|
+
safeInt(o.credits, `${what} credits`, 1);
|
|
116
|
+
const slot = `${o.market}:${o.months}`;
|
|
117
|
+
if (creditMonths.has(slot))
|
|
118
|
+
fail(`${what}: ${o.months} months in ${o.market} is offered twice`);
|
|
119
|
+
creditMonths.add(slot);
|
|
120
|
+
offers.push(Object.freeze({ source: 'credit', market: o.market, months: o.months, credits: o.credits }));
|
|
121
|
+
}
|
|
122
|
+
else if (o.source === 'polar' || o.source === 'apple' || o.source === 'google') {
|
|
123
|
+
checkMarket(o.market, what);
|
|
124
|
+
checkMoney(o.price, o.market, what);
|
|
125
|
+
const offer = Object.freeze({ ...o });
|
|
126
|
+
claimRef(o.productRef, { kind: 'plan', plan, offer }, what);
|
|
127
|
+
offers.push(offer);
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
fail(`${what}: unknown source`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
Object.freeze(offers);
|
|
134
|
+
byKey.set(p.key, Object.freeze(plan));
|
|
135
|
+
}
|
|
136
|
+
const plans = [...byKey.values()].sort((a, b) => a.rank - b.rank);
|
|
137
|
+
const frees = plans.filter((p) => p.free);
|
|
138
|
+
if (frees.length !== 1)
|
|
139
|
+
fail(`exactly one plan must be free, found ${frees.length}`);
|
|
140
|
+
const freePlan = frees[0];
|
|
141
|
+
if (freePlan !== plans[0])
|
|
142
|
+
fail(`free plan ${freePlan.key} must have the lowest rank`);
|
|
143
|
+
if (freePlan.offers.length)
|
|
144
|
+
fail(`free plan ${freePlan.key} cannot have offers`);
|
|
145
|
+
const packs = [];
|
|
146
|
+
const packKeys = new Set();
|
|
147
|
+
for (const k of spec.creditPacks ?? []) {
|
|
148
|
+
checkKey(k.key, 'pack');
|
|
149
|
+
if (packKeys.has(k.key))
|
|
150
|
+
fail(`duplicate pack ${k.key}`);
|
|
151
|
+
packKeys.add(k.key);
|
|
152
|
+
const what = `pack ${k.key}`;
|
|
153
|
+
checkMarket(k.market, what);
|
|
154
|
+
if (!['sepay', 'polar', 'apple', 'google'].includes(k.provider))
|
|
155
|
+
fail(`${what}: unknown provider ${k.provider}`);
|
|
156
|
+
checkMoney(k.price, k.market, what);
|
|
157
|
+
if (!k.price)
|
|
158
|
+
fail(`${what}: price is required`);
|
|
159
|
+
safeInt(k.credits, `${what} credits`, 1);
|
|
160
|
+
if (k.bonusCredits !== undefined)
|
|
161
|
+
safeInt(k.bonusCredits, `${what} bonusCredits`, 0);
|
|
162
|
+
const pack = Object.freeze({
|
|
163
|
+
key: k.key,
|
|
164
|
+
market: k.market,
|
|
165
|
+
provider: k.provider,
|
|
166
|
+
price: Object.freeze({ ...k.price }),
|
|
167
|
+
credits: k.credits,
|
|
168
|
+
bonusCredits: k.bonusCredits ?? 0,
|
|
169
|
+
productRef: k.productRef ?? null,
|
|
170
|
+
});
|
|
171
|
+
if (k.productRef !== undefined)
|
|
172
|
+
claimRef(k.productRef, { kind: 'pack', pack }, what);
|
|
173
|
+
packs.push(pack);
|
|
174
|
+
}
|
|
175
|
+
const creditOffers = (plan, market) => (byKey.get(plan)?.offers ?? [])
|
|
176
|
+
.filter((o) => o.source === 'credit' && o.market === market)
|
|
177
|
+
.sort((a, b) => a.months - b.months);
|
|
178
|
+
return Object.freeze({
|
|
179
|
+
version: spec.version,
|
|
180
|
+
creditUnit: Object.freeze({ code: unit.code, exponent: unit.exponent }),
|
|
181
|
+
markets: Object.freeze([...markets.values()]),
|
|
182
|
+
policies: Object.freeze(policies),
|
|
183
|
+
plans: Object.freeze(plans),
|
|
184
|
+
creditPacks: Object.freeze(packs),
|
|
185
|
+
freePlan,
|
|
186
|
+
plan(key) {
|
|
187
|
+
const p = byKey.get(key);
|
|
188
|
+
if (!p)
|
|
189
|
+
throw new BillingError('plan_not_found', `unknown plan ${key}`, { plan: key });
|
|
190
|
+
return p;
|
|
191
|
+
},
|
|
192
|
+
findPlan: (key) => byKey.get(key),
|
|
193
|
+
plansWithPermission: (permission) => plans.filter((p) => p.permissions.includes(permission)),
|
|
194
|
+
market: (key) => markets.get(key),
|
|
195
|
+
creditOffer: (plan, market, months) => creditOffers(plan, market).find((o) => o.months === months),
|
|
196
|
+
creditOffers,
|
|
197
|
+
pack: (key) => packs.find((p) => p.key === key),
|
|
198
|
+
packsFor: (market, provider) => packs.filter((p) => p.market === market && (!provider || p.provider === provider)),
|
|
199
|
+
offerByProductRef: (productRef) => productRefs.get(productRef),
|
|
200
|
+
});
|
|
201
|
+
}
|
package/dist/domain/types.d.ts
CHANGED
|
@@ -112,7 +112,9 @@ export interface EntryPage {
|
|
|
112
112
|
/** Pass as `beforeSeq` for the next (older) page; null when exhausted. */
|
|
113
113
|
nextBeforeSeq: number | null;
|
|
114
114
|
}
|
|
115
|
-
export type BillingErrorCode = 'insufficient_credits' | 'idempotency_mismatch' | 'invalid_amount' | 'invalid_input' | 'entry_not_found' | 'reversal_exceeds_original' | 'already_reversed' | 'balance_overflow'
|
|
115
|
+
export type BillingErrorCode = 'insufficient_credits' | 'idempotency_mismatch' | 'invalid_amount' | 'invalid_input' | 'entry_not_found' | 'reversal_exceeds_original' | 'already_reversed' | 'balance_overflow' | 'invalid_catalog' | 'plan_not_found' | 'offer_not_found' | 'term_not_found'
|
|
116
|
+
/** A plan purchase the quote refuses (`details.reason`, e.g. `covered_by_subscription`). */
|
|
117
|
+
| 'plan_blocked';
|
|
116
118
|
/** Details carried by `insufficient_credits`. */
|
|
117
119
|
export interface InsufficientCredits {
|
|
118
120
|
balance: number;
|
package/dist/drizzle/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
export { billingTableBuilder, checkAdditiveDdl, createBillingTables, DEFAULT_PREFIX, type BillingSchemaConfig, type BillingTables, type CheckAdditiveDdlOptions, type DdlRule, type DdlViolation, } from './schema-factory.js';
|
|
2
2
|
export { createDrizzleLedgerStore, type AnyPgDatabase, type AnyPgTransaction, type DrizzleLedgerStoreOptions, } from './store.js';
|
|
3
3
|
export { createDrizzleIngestStore, createIngestTables, ingestTableNames, type DrizzleIngestStoreOptions, type IngestTables, } from '../inbox/drizzle.js';
|
|
4
|
+
export { createTermTables, termTableNames, type TermTables } from '../terms/schema.js';
|
|
5
|
+
export { createDrizzleTermStore, type DrizzleTermStoreOptions } from '../terms/drizzle.js';
|
package/dist/drizzle/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
export { billingTableBuilder, checkAdditiveDdl, createBillingTables, DEFAULT_PREFIX, } from './schema-factory.js';
|
|
2
2
|
export { createDrizzleLedgerStore, } from './store.js';
|
|
3
3
|
export { createDrizzleIngestStore, createIngestTables, ingestTableNames, } from '../inbox/drizzle.js';
|
|
4
|
+
export { createTermTables, termTableNames } from '../terms/schema.js';
|
|
5
|
+
export { createDrizzleTermStore } from '../terms/drizzle.js';
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one entitlement resolver (design §4.7): "what plan and permissions does
|
|
3
|
+
* this account have now", from every term of every source. Pure — the host
|
|
4
|
+
* reads the account's terms (`termStore.reader().listTerms`) and the result
|
|
5
|
+
* is a function of those terms, the clock and the catalog.
|
|
6
|
+
*/
|
|
7
|
+
import type { Catalog } from '../catalog/catalog.js';
|
|
8
|
+
import type { Term, TermSource } from '../terms/types.js';
|
|
9
|
+
export type EntitlementStatus = 'active' | 'grace' | 'free';
|
|
10
|
+
export type EntitlementWarningCode =
|
|
11
|
+
/** S5: two auto-renewing provider subscriptions bill the account. */
|
|
12
|
+
'two_subscriptions'
|
|
13
|
+
/** The winning term's renewal failed; it is entitled until `graceUntil`. */
|
|
14
|
+
| 'past_due'
|
|
15
|
+
/** The winning credit term renews soon and the balance does not cover the live price (needs `balance`). */
|
|
16
|
+
| 'renewal_shortfall'
|
|
17
|
+
/** A lower plan takes over at renewal or at the end of the term (S3b). */
|
|
18
|
+
| 'scheduled_downgrade';
|
|
19
|
+
export interface EntitlementWarning {
|
|
20
|
+
code: EntitlementWarningCode;
|
|
21
|
+
termIds: string[];
|
|
22
|
+
}
|
|
23
|
+
export interface EntitlementRenewal {
|
|
24
|
+
auto: boolean;
|
|
25
|
+
at: Date;
|
|
26
|
+
/** The plan the renewal buys (`nextPlanKey ?? planKey`). */
|
|
27
|
+
plan: string;
|
|
28
|
+
/** Credit terms: the live credit price; provider terms: the provider's price snapshot. `null` when unknown. */
|
|
29
|
+
price: {
|
|
30
|
+
amountMinor: number;
|
|
31
|
+
unit: string;
|
|
32
|
+
} | null;
|
|
33
|
+
}
|
|
34
|
+
export interface Entitlement {
|
|
35
|
+
plan: string;
|
|
36
|
+
rank: number;
|
|
37
|
+
permissions: readonly string[];
|
|
38
|
+
quotas: Readonly<Record<string, number>>;
|
|
39
|
+
/** Per-period pool; only provider-funded terms carry one (A1). */
|
|
40
|
+
includedCredits: number | null;
|
|
41
|
+
/** The winning term; `null` on the free plan. */
|
|
42
|
+
term: Term | null;
|
|
43
|
+
source: TermSource | null;
|
|
44
|
+
status: EntitlementStatus;
|
|
45
|
+
/** When the winning term's entitlement ends unless renewed. */
|
|
46
|
+
endsAt: Date | null;
|
|
47
|
+
graceUntil: Date | null;
|
|
48
|
+
renewal: EntitlementRenewal | null;
|
|
49
|
+
warnings: EntitlementWarning[];
|
|
50
|
+
}
|
|
51
|
+
export interface ResolveOptions {
|
|
52
|
+
/** Market for the live renewal price of credit terms; default the term's own market. */
|
|
53
|
+
market?: string;
|
|
54
|
+
/** Credit balance, to flag `renewal_shortfall` on an auto-renewing credit term. */
|
|
55
|
+
balance?: number;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Until when a term entitles its account, or `null` when it does not at `now`.
|
|
59
|
+
*
|
|
60
|
+
* - `active` before its period end. An auto-renewing term past its end is
|
|
61
|
+
* still entitled for `graceDays` while the renewal (job or provider
|
|
62
|
+
* webhook) catches up — the renewal itself decides past_due.
|
|
63
|
+
* - `grace` until `graceUntil` (the period end when the provider sent none).
|
|
64
|
+
* - `past_due` only while `graceUntil` is ahead (a credit term's 3-day grace,
|
|
65
|
+
* AC15); a provider `past_due` without one is not entitled (§4.6).
|
|
66
|
+
* - `scheduled` once `startsAt` passed and before its period end, in case
|
|
67
|
+
* activation has not run yet.
|
|
68
|
+
*/
|
|
69
|
+
export declare function entitledUntil(term: Term, now: Date, graceDays: number): Date | null;
|
|
70
|
+
export declare function isEntitled(term: Term, now: Date, graceDays: number): boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Resolve the account's entitlement (S1: highest rank wins, then the later
|
|
73
|
+
* end, then the older term; quotas and permissions never sum). Terms naming a
|
|
74
|
+
* plan the catalog no longer has are ignored. No entitled term → the free plan.
|
|
75
|
+
*/
|
|
76
|
+
export declare function resolveEntitlement(terms: readonly Term[], now: Date, catalog: Catalog, options?: ResolveOptions): Entitlement;
|