@tofound/billing 0.1.0 → 1.0.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 +136 -1
- package/README.md +73 -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/hostkit/adjustments.d.ts +65 -0
- package/dist/hostkit/adjustments.js +84 -0
- package/dist/hostkit/index.d.ts +9 -0
- package/dist/hostkit/index.js +9 -0
- package/dist/hostkit/legacy-ledger.d.ts +87 -0
- package/dist/hostkit/legacy-ledger.js +111 -0
- package/dist/hostkit/quote-wire.d.ts +73 -0
- package/dist/hostkit/quote-wire.js +50 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +9 -0
- package/dist/providers/apple/events.d.ts +24 -0
- package/dist/providers/apple/events.js +232 -0
- package/dist/providers/apple/index.d.ts +54 -0
- package/dist/providers/apple/index.js +231 -0
- package/dist/providers/apple/jws.d.ts +50 -0
- package/dist/providers/apple/jws.js +206 -0
- package/dist/providers/google/api.d.ts +57 -0
- package/dist/providers/google/api.js +226 -0
- package/dist/providers/google/events.d.ts +46 -0
- package/dist/providers/google/events.js +135 -0
- package/dist/providers/google/index.d.ts +37 -0
- package/dist/providers/google/index.js +228 -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/providers/sepay/index.js +29 -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 +415 -6
- package/docs/MIGRATION-LOHI.md +237 -0
- package/docs/SCHEMA.md +57 -2
- package/package.json +22 -1
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `billing_terms` table: every subscription term of every source, and
|
|
3
|
+
* `billing_term_accounts`, one guard row per account that `lockAccountTerms`
|
|
4
|
+
* locks first, so writers of an account with no terms yet still serialize. Declared
|
|
5
|
+
* through `billingTableBuilder`, so it takes the host's schema and prefix like
|
|
6
|
+
* the ledger tables and follows the same additive rules (docs/SCHEMA.md,
|
|
7
|
+
* `checkAdditiveDdl`): a new table and its indexes only.
|
|
8
|
+
*/
|
|
9
|
+
import { sql } from 'drizzle-orm';
|
|
10
|
+
import { bigint, boolean, check, index, integer, jsonb, primaryKey, text, timestamp, uniqueIndex, varchar } from 'drizzle-orm/pg-core';
|
|
11
|
+
import { billingTableBuilder, DEFAULT_PREFIX } from '../drizzle/schema-factory.js';
|
|
12
|
+
export function createTermTables(config) {
|
|
13
|
+
const b = billingTableBuilder(config);
|
|
14
|
+
const tz = (name) => timestamp(name, { withTimezone: true });
|
|
15
|
+
const billingTerms = b.table(b.name('terms'), {
|
|
16
|
+
id: varchar('id', { length: 64 }).primaryKey(),
|
|
17
|
+
accountId: config.accountId('account_id'),
|
|
18
|
+
source: varchar('source', { length: 16 }).notNull(),
|
|
19
|
+
environment: varchar('environment', { length: 16 }),
|
|
20
|
+
externalId: text('external_id'),
|
|
21
|
+
planKey: varchar('plan_key', { length: 64 }).notNull(),
|
|
22
|
+
status: varchar('status', { length: 16 }).notNull(),
|
|
23
|
+
market: varchar('market', { length: 64 }),
|
|
24
|
+
startsAt: tz('starts_at').notNull(),
|
|
25
|
+
currentPeriodStart: tz('current_period_start').notNull(),
|
|
26
|
+
currentPeriodEnd: tz('current_period_end').notNull(),
|
|
27
|
+
intervalMonths: integer('interval_months').notNull(),
|
|
28
|
+
autoRenew: boolean('auto_renew').notNull().default(false),
|
|
29
|
+
cancelAtPeriodEnd: boolean('cancel_at_period_end').notNull().default(false),
|
|
30
|
+
graceUntil: tz('grace_until'),
|
|
31
|
+
nextPlanKey: varchar('next_plan_key', { length: 64 }),
|
|
32
|
+
priceMinor: bigint('price_minor', { mode: 'number' }),
|
|
33
|
+
priceUnit: varchar('price_unit', { length: 16 }),
|
|
34
|
+
periodItems: jsonb('period_items').$type(),
|
|
35
|
+
supersededBy: varchar('superseded_by', { length: 64 }),
|
|
36
|
+
lastEventAt: tz('last_event_at'),
|
|
37
|
+
lastEventRef: text('last_event_ref'),
|
|
38
|
+
meta: jsonb('meta').$type(),
|
|
39
|
+
createdAt: tz('created_at').notNull().defaultNow(),
|
|
40
|
+
updatedAt: tz('updated_at').notNull().defaultNow(),
|
|
41
|
+
}, (t) => [
|
|
42
|
+
// NULLs are distinct: credit terms (no external id) never collide here.
|
|
43
|
+
uniqueIndex(b.name('terms_external_uq')).on(t.source, t.environment, t.externalId),
|
|
44
|
+
// One open credit term per account, and one scheduled term.
|
|
45
|
+
uniqueIndex(b.name('terms_open_credit_uq'))
|
|
46
|
+
.on(t.accountId)
|
|
47
|
+
.where(sql `${t.source} = 'credit' and ${t.status} in ('active', 'grace', 'past_due')`),
|
|
48
|
+
uniqueIndex(b.name('terms_scheduled_uq')).on(t.accountId).where(sql `${t.status} = 'scheduled'`),
|
|
49
|
+
// `lockAccountTerms` and `listTerms`.
|
|
50
|
+
index(b.name('terms_account_status_idx')).on(t.accountId, t.status),
|
|
51
|
+
// `listDue`: each branch of the predicate has its own partial index, so a run costs the due rows.
|
|
52
|
+
index(b.name('terms_due_active_idx'))
|
|
53
|
+
.on(t.currentPeriodEnd)
|
|
54
|
+
.where(sql `${t.source} = 'credit' and ${t.status} = 'active'`),
|
|
55
|
+
index(b.name('terms_due_scheduled_idx')).on(t.startsAt).where(sql `${t.status} = 'scheduled'`),
|
|
56
|
+
index(b.name('terms_due_past_due_idx'))
|
|
57
|
+
.on(t.graceUntil)
|
|
58
|
+
.where(sql `${t.source} = 'credit' and ${t.status} = 'past_due'`),
|
|
59
|
+
check(b.name('terms_interval_pos'), sql `${t.intervalMonths} > 0`),
|
|
60
|
+
]);
|
|
61
|
+
const billingTermAccounts = b.table(b.name('term_accounts'), {
|
|
62
|
+
accountId: config.accountId('account_id'),
|
|
63
|
+
createdAt: tz('created_at').notNull().defaultNow(),
|
|
64
|
+
}, (t) => [primaryKey({ name: b.name('term_accounts_pk'), columns: [t.accountId] })]);
|
|
65
|
+
return { billingTerms, billingTermAccounts };
|
|
66
|
+
}
|
|
67
|
+
/** Unqualified table names for `checkAdditiveDdl({libraryTables})`. */
|
|
68
|
+
export function termTableNames(prefix = DEFAULT_PREFIX) {
|
|
69
|
+
return [`${prefix}terms`, `${prefix}term_accounts`];
|
|
70
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Catalog } from '../catalog/catalog.js';
|
|
2
|
+
import type { AccountId } from '../domain/types.js';
|
|
3
|
+
import type { ApplyContext, EventHandler } from '../inbox/apply.js';
|
|
4
|
+
import type { IdGenerator } from '../ports/runtime.js';
|
|
5
|
+
import type { AccountRef } from '../providers/port.js';
|
|
6
|
+
import type { TermStore } from './ports.js';
|
|
7
|
+
export interface SnapshotHandlerOptions<TTx> {
|
|
8
|
+
terms: TermStore<TTx>;
|
|
9
|
+
catalog: Catalog;
|
|
10
|
+
/**
|
|
11
|
+
* Map the event's server-issued reference to the host's account (Polar
|
|
12
|
+
* `external_customer_id`, Apple `appAccountToken` …). Default: only
|
|
13
|
+
* `account_id` references resolve. `null` → `ignored` as `no_match`,
|
|
14
|
+
* unmatched: relayed through the ingest `onUnmatched` hook (another host's
|
|
15
|
+
* subscription on a shared provider account).
|
|
16
|
+
*/
|
|
17
|
+
resolveAccount?: (ref: AccountRef, ctx: ApplyContext<TTx>) => AccountId | null | Promise<AccountId | null>;
|
|
18
|
+
ids?: IdGenerator;
|
|
19
|
+
}
|
|
20
|
+
export declare function createSnapshotHandler<TTx>(options: SnapshotHandlerOptions<TTx>): EventHandler<TTx>;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider terms from `subscription.snapshot` events (design §4.6, S4). The
|
|
3
|
+
* handler plugs into the ingest service's handler slot, so a snapshot is
|
|
4
|
+
* applied in the inbox transaction:
|
|
5
|
+
*
|
|
6
|
+
* createIngest({ …, handlers: { 'subscription.snapshot': createSnapshotHandler({ terms, catalog, resolveAccount }) } })
|
|
7
|
+
*
|
|
8
|
+
* A snapshot only changes its term when it is newer than the term's
|
|
9
|
+
* watermark, so redelivered or out-of-order events cannot regress it. When the
|
|
10
|
+
* provider term entitles at ≥ the rank of the account's open credit term,
|
|
11
|
+
* that credit term is `superseded` and its unused share is refunded in
|
|
12
|
+
* credits (`plan_refund`, key `supersede:<termId>`).
|
|
13
|
+
*/
|
|
14
|
+
import { randomUUID } from 'node:crypto';
|
|
15
|
+
import { entitledUntil } from '../entitlement/resolve.js';
|
|
16
|
+
import { isNewer } from '../inbox/watermark.js';
|
|
17
|
+
import { supersedeRefund } from './decide.js';
|
|
18
|
+
import { renews } from './rules.js';
|
|
19
|
+
const SOURCES = new Set(['polar', 'apple', 'google']);
|
|
20
|
+
export function createSnapshotHandler(options) {
|
|
21
|
+
const { catalog } = options;
|
|
22
|
+
const ids = options.ids ?? randomUUID;
|
|
23
|
+
const resolveAccount = options.resolveAccount ?? ((ref) => (ref.kind === 'account_id' ? ref.value : null));
|
|
24
|
+
return async (event, ctx) => {
|
|
25
|
+
if (event.kind !== 'subscription.snapshot')
|
|
26
|
+
return { status: 'ignored', reason: `not_a_snapshot:${event.kind}` };
|
|
27
|
+
const { delivery } = ctx;
|
|
28
|
+
if (!SOURCES.has(delivery.provider))
|
|
29
|
+
return { status: 'needs_review', reason: 'unsupported_provider' };
|
|
30
|
+
const source = delivery.provider;
|
|
31
|
+
// Another host's subscription (its products may be unknown here) is relayed before the plan is checked.
|
|
32
|
+
const accountId = await resolveAccount(event.account, ctx);
|
|
33
|
+
if (!accountId)
|
|
34
|
+
return { status: 'ignored', reason: 'no_match', unmatched: true };
|
|
35
|
+
const match = catalog.offerByProductRef(event.planRef);
|
|
36
|
+
if (match?.kind !== 'plan')
|
|
37
|
+
return { status: 'needs_review', reason: 'unknown_plan_ref' };
|
|
38
|
+
if (match.offer.source !== source)
|
|
39
|
+
return { status: 'needs_review', reason: 'plan_ref_provider_mismatch' };
|
|
40
|
+
const t = options.terms.bind(ctx.tx);
|
|
41
|
+
// Never lock another account's row: a subscription's account does not change, so an unlocked read settles it.
|
|
42
|
+
const known = await t.findExternal(source, delivery.environment, event.externalId);
|
|
43
|
+
if (known && known.accountId !== accountId)
|
|
44
|
+
return { status: 'needs_review', reason: 'account_mismatch' };
|
|
45
|
+
// Lock order: the account's open terms (oldest first, as purchases do), then this one.
|
|
46
|
+
const open = await t.lockAccountTerms(accountId);
|
|
47
|
+
const existing = open.find((x) => x.source === source && x.environment === delivery.environment && x.externalId === event.externalId) ??
|
|
48
|
+
(await t.lockExternal(source, delivery.environment, event.externalId));
|
|
49
|
+
if (existing && existing.accountId !== accountId)
|
|
50
|
+
return { status: 'needs_review', reason: 'account_mismatch' };
|
|
51
|
+
// The tie-break leads the ref, so it orders same-instant snapshots before the event id does.
|
|
52
|
+
const mark = { at: event.occurredAt, ref: event.tieBreak ? `${event.tieBreak}:${delivery.eventId}` : delivery.eventId };
|
|
53
|
+
const watermark = existing?.lastEventAt ? { at: existing.lastEventAt, ref: existing.lastEventRef ?? '' } : null;
|
|
54
|
+
if (!isNewer(watermark, mark))
|
|
55
|
+
return { status: 'ignored', reason: 'stale' };
|
|
56
|
+
const nextPlan = event.nextPlanRef ? catalog.offerByProductRef(event.nextPlanRef) : undefined;
|
|
57
|
+
const patch = {
|
|
58
|
+
planKey: match.plan.key,
|
|
59
|
+
status: event.status,
|
|
60
|
+
currentPeriodStart: event.periodStart,
|
|
61
|
+
currentPeriodEnd: event.periodEnd,
|
|
62
|
+
intervalMonths: intervalOf(event, match.offer.interval, catalog.policies.termDays),
|
|
63
|
+
autoRenew: event.autoRenew,
|
|
64
|
+
cancelAtPeriodEnd: event.cancelAtPeriodEnd,
|
|
65
|
+
graceUntil: event.graceUntil ?? null,
|
|
66
|
+
nextPlanKey: nextPlan?.kind === 'plan' ? nextPlan.plan.key : null,
|
|
67
|
+
priceMinor: event.price?.amountMinor ?? existing?.priceMinor ?? null,
|
|
68
|
+
priceUnit: event.price?.currency ?? existing?.priceUnit ?? null,
|
|
69
|
+
lastEventAt: mark.at,
|
|
70
|
+
lastEventRef: mark.ref,
|
|
71
|
+
};
|
|
72
|
+
let term;
|
|
73
|
+
if (existing) {
|
|
74
|
+
await t.updateTerm(existing.id, patch);
|
|
75
|
+
term = { ...existing, ...patch };
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
term = {
|
|
79
|
+
id: ids(),
|
|
80
|
+
accountId,
|
|
81
|
+
source,
|
|
82
|
+
environment: delivery.environment,
|
|
83
|
+
externalId: event.externalId,
|
|
84
|
+
market: match.offer.market ?? null,
|
|
85
|
+
startsAt: event.periodStart,
|
|
86
|
+
periodItems: null,
|
|
87
|
+
supersededBy: null,
|
|
88
|
+
meta: null,
|
|
89
|
+
createdAt: ctx.now,
|
|
90
|
+
updatedAt: ctx.now,
|
|
91
|
+
...patch,
|
|
92
|
+
};
|
|
93
|
+
// A concurrent first snapshot of the same subscription: transient, the inbox retries.
|
|
94
|
+
if (!(await t.insertTerm(term)).inserted)
|
|
95
|
+
throw new Error(`term ${source}:${event.externalId} was created concurrently`);
|
|
96
|
+
}
|
|
97
|
+
if (!entitledUntil(term, ctx.now, catalog.policies.graceDays))
|
|
98
|
+
return { status: 'applied' };
|
|
99
|
+
// S4: an entitling subscription of ≥ rank replaces the account's credit terms.
|
|
100
|
+
const rank = match.plan.rank;
|
|
101
|
+
const result = { status: 'applied', events: [] };
|
|
102
|
+
for (const credit of open.filter((x) => x.source === 'credit')) {
|
|
103
|
+
const creditRank = catalog.findPlan(credit.planKey)?.rank ?? -1;
|
|
104
|
+
if (creditRank > rank)
|
|
105
|
+
continue;
|
|
106
|
+
if (credit.status === 'scheduled' && !renews(term))
|
|
107
|
+
continue;
|
|
108
|
+
const refund = supersedeRefund(credit, ctx.now);
|
|
109
|
+
await t.updateTerm(credit.id, { status: 'superseded', supersededBy: term.id, autoRenew: false });
|
|
110
|
+
if (refund > 0) {
|
|
111
|
+
const posted = await ctx.ledger.credit({
|
|
112
|
+
accountId,
|
|
113
|
+
kind: 'plan_refund',
|
|
114
|
+
amount: refund,
|
|
115
|
+
idempotencyKey: `supersede:${credit.id}`,
|
|
116
|
+
source: { type: 'term', id: credit.id },
|
|
117
|
+
meta: { supersededBy: term.id, provider: source },
|
|
118
|
+
});
|
|
119
|
+
result.events.push(...posted.events);
|
|
120
|
+
}
|
|
121
|
+
result.reason = 'superseded_credit_term';
|
|
122
|
+
}
|
|
123
|
+
return result;
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
/** Renewal interval in catalog months: the offer's interval, else the period's length. */
|
|
127
|
+
function intervalOf(event, interval, termDays) {
|
|
128
|
+
if (interval === 'year')
|
|
129
|
+
return 12;
|
|
130
|
+
if (interval === 'month')
|
|
131
|
+
return 1;
|
|
132
|
+
const days = (event.periodEnd.getTime() - event.periodStart.getTime()) / 86_400_000;
|
|
133
|
+
return Math.max(1, Math.round(days / termDays));
|
|
134
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subscription terms (design §4.6): one shape for the four sources. Credit
|
|
3
|
+
* terms are written only by the plans and renewal services; provider terms
|
|
4
|
+
* only from `subscription.snapshot` events, under a watermark.
|
|
5
|
+
*/
|
|
6
|
+
import type { AccountId } from '../domain/types.js';
|
|
7
|
+
import type { ProviderEnvironment } from '../providers/port.js';
|
|
8
|
+
export type TermSource = 'credit' | 'polar' | 'apple' | 'google';
|
|
9
|
+
/**
|
|
10
|
+
* - `scheduled`: a credit term that starts at `startsAt` (S3b), charged then.
|
|
11
|
+
* - `active`: entitled until the period end.
|
|
12
|
+
* - `grace` (provider): entitled until `graceUntil`.
|
|
13
|
+
* - `past_due`: renewal unpaid; entitled only while `graceUntil` is ahead.
|
|
14
|
+
* - `expired` / `superseded` / `revoked`: final.
|
|
15
|
+
*/
|
|
16
|
+
export type TermStatus = 'scheduled' | 'active' | 'grace' | 'past_due' | 'expired' | 'superseded' | 'revoked';
|
|
17
|
+
export declare const TERM_STATUSES: readonly TermStatus[];
|
|
18
|
+
/** Statuses of a term still in play (at most one per account for credit terms, plus one scheduled). */
|
|
19
|
+
export declare const OPEN_TERM_STATUSES: readonly TermStatus[];
|
|
20
|
+
export declare const FINAL_TERM_STATUSES: readonly TermStatus[];
|
|
21
|
+
/** One purchase making up the current period of a credit term (an S2 extension adds one). */
|
|
22
|
+
export interface PeriodItem {
|
|
23
|
+
months: number;
|
|
24
|
+
/** Credit minor units this item is worth at the term's plan. */
|
|
25
|
+
credits: number;
|
|
26
|
+
}
|
|
27
|
+
export interface Term {
|
|
28
|
+
id: string;
|
|
29
|
+
accountId: AccountId;
|
|
30
|
+
source: TermSource;
|
|
31
|
+
/** Provider rail; `null` for credit terms. */
|
|
32
|
+
environment: ProviderEnvironment | null;
|
|
33
|
+
/** Provider subscription id / originalTransactionId / purchaseToken; `null` for credit terms. */
|
|
34
|
+
externalId: string | null;
|
|
35
|
+
planKey: string;
|
|
36
|
+
status: TermStatus;
|
|
37
|
+
/** Market the term was bought in (credit terms); the host may re-price renewals by its own. */
|
|
38
|
+
market: string | null;
|
|
39
|
+
startsAt: Date;
|
|
40
|
+
currentPeriodStart: Date;
|
|
41
|
+
currentPeriodEnd: Date;
|
|
42
|
+
/** Renewal interval in catalog months. */
|
|
43
|
+
intervalMonths: number;
|
|
44
|
+
autoRenew: boolean;
|
|
45
|
+
cancelAtPeriodEnd: boolean;
|
|
46
|
+
graceUntil: Date | null;
|
|
47
|
+
/** Plan a renewal switches to (a downgrade under auto-renew, S3b). */
|
|
48
|
+
nextPlanKey: string | null;
|
|
49
|
+
/**
|
|
50
|
+
* What the current period is worth: credit minor units for a credit term
|
|
51
|
+
* (sum of `periodItems`), the provider's price otherwise.
|
|
52
|
+
*/
|
|
53
|
+
priceMinor: number | null;
|
|
54
|
+
/** The credit unit code, or the provider's currency. */
|
|
55
|
+
priceUnit: string | null;
|
|
56
|
+
/** Credit terms: the purchases making up the current period. */
|
|
57
|
+
periodItems: PeriodItem[] | null;
|
|
58
|
+
supersededBy: string | null;
|
|
59
|
+
/** Provider watermark: only a newer snapshot changes the term. */
|
|
60
|
+
lastEventAt: Date | null;
|
|
61
|
+
lastEventRef: string | null;
|
|
62
|
+
meta: Record<string, unknown> | null;
|
|
63
|
+
createdAt: Date;
|
|
64
|
+
updatedAt: Date;
|
|
65
|
+
}
|
|
66
|
+
export type TermPatch = Partial<Pick<Term, 'planKey' | 'status' | 'market' | 'startsAt' | 'currentPeriodStart' | 'currentPeriodEnd' | 'intervalMonths' | 'autoRenew' | 'cancelAtPeriodEnd' | 'graceUntil' | 'nextPlanKey' | 'priceMinor' | 'priceUnit' | 'periodItems' | 'supersededBy' | 'lastEventAt' | 'lastEventRef' | 'meta'>>;
|
|
67
|
+
export type TermChange = 'created' | 'extended' | 'upgraded' | 'scheduled' | 'activated' | 'renewed' | 'past_due' | 'expired' | 'superseded' | 'auto_renew' | 'cancelled';
|
|
68
|
+
/** Domain events of terms (design §13); the host maps them onto its bus. */
|
|
69
|
+
export type TermEvent = {
|
|
70
|
+
type: 'term_changed';
|
|
71
|
+
accountId: AccountId;
|
|
72
|
+
change: TermChange;
|
|
73
|
+
term: Term;
|
|
74
|
+
} | {
|
|
75
|
+
type: 'renewal_failed';
|
|
76
|
+
accountId: AccountId;
|
|
77
|
+
term: Term;
|
|
78
|
+
/** `insufficient_credits` or `offer_not_found` (the plan is no longer sold for credits). */
|
|
79
|
+
reason: string;
|
|
80
|
+
required: number | null;
|
|
81
|
+
balance: number;
|
|
82
|
+
shortfall: number | null;
|
|
83
|
+
};
|
|
84
|
+
/** Receives term events after the service's own transaction commits; errors go to `onEventError`. */
|
|
85
|
+
export type TermEventSink = (event: TermEvent) => void | Promise<void>;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export const TERM_STATUSES = ['scheduled', 'active', 'grace', 'past_due', 'expired', 'superseded', 'revoked'];
|
|
2
|
+
/** Statuses of a term still in play (at most one per account for credit terms, plus one scheduled). */
|
|
3
|
+
export const OPEN_TERM_STATUSES = ['active', 'grace', 'past_due'];
|
|
4
|
+
export const FINAL_TERM_STATUSES = ['expired', 'superseded', 'revoked'];
|