@tofound/billing 1.3.0 → 1.5.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 CHANGED
@@ -4,6 +4,54 @@ All notable changes to `@tofound/billing`. Versions follow semver; 0.x minors
4
4
  were additive. From 1.0.0 the public API is frozen: removing or narrowing
5
5
  anything in the declaration snapshot is a major version.
6
6
 
7
+ ## 1.5.0 — 2026-11-06
8
+
9
+ Additive to 1.4: every 1.4 export is unchanged (the public-api declaration
10
+ snapshot only grows). No schema change (`billing_terms.source` is already a
11
+ `varchar(16)`). Terms and offers of the existing sources behave exactly as in
12
+ 1.4.0.
13
+
14
+ To adopt: pin `@tofound/billing@1.5.0`.
15
+
16
+ - **SePay prepay terms.** `TermSource` gains `'sepay'`: a manual prepay the
17
+ host opens when a transfer settles. It never auto-renews; `entitledUntil`
18
+ keeps it entitled for `policies.graceDays` after `currentPeriodEnd` so a
19
+ late re-payment extends it without a gap. As a non-credit term it carries
20
+ the plan's `includedCredits`, and the credit renewal job skips it. A host
21
+ with an exhaustive `switch` over `TermSource` / `Term.source` /
22
+ `Entitlement.source` adds a `'sepay'` arm when it adopts 1.5.0.
23
+ - **SePay prepay offers.** `ProviderOffer.source` gains `'sepay'` and an
24
+ optional `months`. A `sepay` offer needs `market`, `months` and `price` (for
25
+ the whole `months`), takes no `interval`, and is unique per market and
26
+ months. New catalog lookups `prepayOffer(plan, market, months)` and
27
+ `prepayOffers(plan, market)`.
28
+ - **Docs:** GUIDE §4 (SePay prepay) and §5 (failed renewal per source).
29
+
30
+ ## 1.4.0 — 2026-10-29
31
+
32
+ Additive to 1.3: every 1.3 export is unchanged (the public-api declaration
33
+ snapshot only grows). No schema change. `readOrder`, `verifyPurchase`,
34
+ `cancelOrder` and `confirm` behave exactly as in 1.3.0.
35
+
36
+ To adopt: pin `@tofound/billing@1.4.0`.
37
+
38
+ - **Read-only purchase lookup.** A new provider port, `PurchaseLookup<TProof>`
39
+ (`lookupPurchase(proof): Promise<PurchaseLookupResult>`). It reports what the
40
+ provider says about one purchase: `paid` (with `externalId`, `amount` and
41
+ `occurredAt`), `pending`, `cancelled`, `not_found`, or `unavailable` with a
42
+ short reason. It never applies anything and never throws. The guard
43
+ `isPurchaseLookup` is exported from the root entry.
44
+ - **SePay `lookupPurchase({ invoice })`.** One order-detail GET. `CAPTURED`
45
+ maps to `paid` (`externalId` = order id, else the invoice; `occurredAt` = the
46
+ lookup time), `AUTHENTICATION_NOT_NEEDED` to `pending` and `CANCELLED` to
47
+ `cancelled`. HTTP 404 or no data for the invoice is `not_found`. A timeout,
48
+ network error, other non-2xx or unparseable order is `unavailable` with the
49
+ reason `timeout`, `network`, `http_<n>` or `malformed`; missing merchant
50
+ credentials give `not_configured`. The new option
51
+ `SepayAdapterOptions.lookupTimeoutMs` sets the timeout (default 8 s);
52
+ `timeoutMs` still governs `readOrder`.
53
+ - **Docs:** README (SePay section).
54
+
7
55
  ## 1.3.0 — 2026-10-28
8
56
 
9
57
  Additive to 1.2: every 1.2 export is unchanged (the public-api declaration
package/README.md CHANGED
@@ -4,7 +4,7 @@
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
- 1.3 ships (the public API is frozen from 1.0.0 on; 1.1, 1.2 and 1.3 only add):
7
+ 1.4 ships (the public API is frozen from 1.0.0 on; 1.1 to 1.4 only add):
8
8
 
9
9
  - **The money core** (since 0.1): an idempotent, no-overdraft credit ledger
10
10
  behind store ports, memory and Drizzle/Postgres stores, a Drizzle schema
@@ -23,7 +23,7 @@ its own database; there is no billing service.
23
23
  (`@tofound/billing/providers/google`) adapters.
24
24
 
25
25
  ```sh
26
- bun add @tofound/billing@1.3.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
26
+ bun add @tofound/billing@1.5.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
27
27
  ```
28
28
 
29
29
  ```ts
@@ -64,6 +64,32 @@ It also opens checkouts (`createCheckout`) and customer portal sessions.
64
64
  switches into one required value. `signPolarWebhook` signs test deliveries.
65
65
  The full entry is in `docs/API.md`.
66
66
 
67
+ ## SePay
68
+
69
+ `@tofound/billing/providers/sepay` verifies and normalizes SePay IPNs, signs
70
+ checkout forms and reads orders. `createSepayAdapter({ environment,
71
+ webhookKeys, merchantId, secretKey })` needs the environment passed explicitly
72
+ and refuses credentials of the other rail.
73
+
74
+ `lookupPurchase({ invoice })` (new in 1.4, the `PurchaseLookup` port) is a
75
+ read-only answer about one invoice. It makes one order-detail request, applies
76
+ nothing and never throws; `isPurchaseLookup(adapter)` tells whether an adapter
77
+ has it. It maps the order like this:
78
+
79
+ | SePay answers | Result |
80
+ |---|---|
81
+ | `CAPTURED` | `paid`: `externalId` = order id (else the invoice), `amount` in VND, `occurredAt` = the lookup time (the order body carries no paid time) |
82
+ | `AUTHENTICATION_NOT_NEEDED` | `pending` |
83
+ | `CANCELLED` | `cancelled` |
84
+ | HTTP 404, or no `data` for this invoice | `not_found` |
85
+ | timeout (`lookupTimeoutMs`, default 8 s), network error | `unavailable`, reason `timeout` / `network` |
86
+ | any other non-2xx (5xx, 401, 403 …) | `unavailable`, reason `http_<status>` |
87
+ | an unparseable body, or this invoice in another currency, amount or status | `unavailable`, reason `malformed` |
88
+ | no merchant credentials configured | `unavailable`, reason `not_configured` |
89
+
90
+ To credit a paid invoice, the host still goes through `verifyPurchase` or its
91
+ own apply path. `readOrder` and `verifyPurchase` are unchanged.
92
+
67
93
  ## Host kit
68
94
 
69
95
  `@tofound/billing/hostkit` (new in 1.0) is for hosts that keep their own
@@ -12,15 +12,21 @@ export interface CreditOffer {
12
12
  /** Credit minor units for the whole `months`. */
13
13
  credits: number;
14
14
  }
15
- /** A provider-billed offer; `productRef` maps to the provider's product id in host config. */
15
+ /**
16
+ * A provider-billed offer; `productRef` maps to the provider's product id in host config.
17
+ * A `sepay` offer is a manual prepay: `market`, `months` and `price` (the whole
18
+ * `months`) are required, one per market and months, and it never auto-renews.
19
+ */
16
20
  export interface ProviderOffer {
17
- source: 'polar' | 'apple' | 'google';
21
+ source: 'sepay' | 'polar' | 'apple' | 'google';
18
22
  productRef: string;
19
23
  market?: string;
20
24
  interval?: 'month' | 'year';
21
25
  price?: Money;
22
26
  /** Google base plan id. */
23
27
  basePlan?: string;
28
+ /** `sepay` only: catalog months the prepay buys. */
29
+ months?: number;
24
30
  }
25
31
  export type PlanOffer = CreditOffer | ProviderOffer;
26
32
  export interface PlanSpec {
@@ -106,6 +112,10 @@ export interface Catalog {
106
112
  creditOffer(plan: string, market: string, months: number): CreditOffer | undefined;
107
113
  /** Credit offers of a plan in a market, fewest months first. */
108
114
  creditOffers(plan: string, market: string): CreditOffer[];
115
+ /** The `sepay` prepay offer of a plan for `months` in a market. */
116
+ prepayOffer(plan: string, market: string, months: number): ProviderOffer | undefined;
117
+ /** `sepay` prepay offers of a plan in a market, fewest months first. */
118
+ prepayOffers(plan: string, market: string): ProviderOffer[];
109
119
  pack(key: string): CreditPack | undefined;
110
120
  packsFor(market: string, provider?: PackProvider): CreditPack[];
111
121
  /** The plan offer or credit pack a provider product ref names. */
@@ -105,6 +105,7 @@ export function defineCatalog(spec) {
105
105
  offers,
106
106
  };
107
107
  const creditMonths = new Set();
108
+ const prepayMonths = new Set();
108
109
  for (const o of p.offers ?? []) {
109
110
  const what = `plan ${p.key} ${o.source} offer`;
110
111
  if (o.source === 'credit') {
@@ -119,6 +120,24 @@ export function defineCatalog(spec) {
119
120
  creditMonths.add(slot);
120
121
  offers.push(Object.freeze({ source: 'credit', market: o.market, months: o.months, credits: o.credits }));
121
122
  }
123
+ else if (o.source === 'sepay') {
124
+ checkMarket(o.market, what);
125
+ if (o.market === undefined)
126
+ fail(`${what}: market is required`);
127
+ safeInt(o.months, `${what} months`, 1);
128
+ if (!o.price)
129
+ fail(`${what}: price is required`);
130
+ checkMoney(o.price, o.market, what);
131
+ if (o.interval !== undefined)
132
+ fail(`${what}: a prepay has months, not an interval`);
133
+ const slot = `${o.market}:${o.months}`;
134
+ if (prepayMonths.has(slot))
135
+ fail(`${what}: ${o.months} months in ${o.market} is offered twice`);
136
+ prepayMonths.add(slot);
137
+ const offer = Object.freeze({ ...o, price: Object.freeze({ ...o.price }) });
138
+ claimRef(o.productRef, { kind: 'plan', plan, offer }, what);
139
+ offers.push(offer);
140
+ }
122
141
  else if (o.source === 'polar' || o.source === 'apple' || o.source === 'google') {
123
142
  checkMarket(o.market, what);
124
143
  checkMoney(o.price, o.market, what);
@@ -175,6 +194,9 @@ export function defineCatalog(spec) {
175
194
  const creditOffers = (plan, market) => (byKey.get(plan)?.offers ?? [])
176
195
  .filter((o) => o.source === 'credit' && o.market === market)
177
196
  .sort((a, b) => a.months - b.months);
197
+ const prepayOffers = (plan, market) => (byKey.get(plan)?.offers ?? [])
198
+ .filter((o) => o.source === 'sepay' && o.market === market)
199
+ .sort((a, b) => (a.months ?? 0) - (b.months ?? 0));
178
200
  return Object.freeze({
179
201
  version: spec.version,
180
202
  creditUnit: Object.freeze({ code: unit.code, exponent: unit.exponent }),
@@ -194,6 +216,8 @@ export function defineCatalog(spec) {
194
216
  market: (key) => markets.get(key),
195
217
  creditOffer: (plan, market, months) => creditOffers(plan, market).find((o) => o.months === months),
196
218
  creditOffers,
219
+ prepayOffer: (plan, market, months) => prepayOffers(plan, market).find((o) => o.months === months),
220
+ prepayOffers,
197
221
  pack: (key) => packs.find((p) => p.key === key),
198
222
  packsFor: (market, provider) => packs.filter((p) => p.market === market && (!provider || p.provider === provider)),
199
223
  offerByProductRef: (productRef) => productRefs.get(productRef),
@@ -59,7 +59,9 @@ export interface ResolveOptions {
59
59
  *
60
60
  * - `active` before its period end. An auto-renewing term past its end is
61
61
  * still entitled for `graceDays` while the renewal (job or provider
62
- * webhook) catches up — the renewal itself decides past_due.
62
+ * webhook) catches up — the renewal itself decides past_due. A `sepay`
63
+ * prepay never auto-renews but keeps the same `graceDays`, so a user who
64
+ * re-pays a day late is not cut off.
63
65
  * - `grace` until `graceUntil` (the period end when the provider sent none).
64
66
  * - `past_due` only while `graceUntil` is ahead (a credit term's 3-day grace,
65
67
  * AC15); a provider `past_due` without one is not entitled (§4.6).
@@ -4,7 +4,9 @@ import { addDays } from '../terms/rules.js';
4
4
  *
5
5
  * - `active` before its period end. An auto-renewing term past its end is
6
6
  * still entitled for `graceDays` while the renewal (job or provider
7
- * webhook) catches up — the renewal itself decides past_due.
7
+ * webhook) catches up — the renewal itself decides past_due. A `sepay`
8
+ * prepay never auto-renews but keeps the same `graceDays`, so a user who
9
+ * re-pays a day late is not cut off.
8
10
  * - `grace` until `graceUntil` (the period end when the provider sent none).
9
11
  * - `past_due` only while `graceUntil` is ahead (a credit term's 3-day grace,
10
12
  * AC15); a provider `past_due` without one is not entitled (§4.6).
@@ -20,7 +22,8 @@ export function entitledUntil(term, now, graceDays) {
20
22
  return null;
21
23
  if (at < term.currentPeriodEnd.getTime())
22
24
  return term.currentPeriodEnd;
23
- return term.autoRenew && !term.cancelAtPeriodEnd ? before(addDays(term.currentPeriodEnd, graceDays)) : null;
25
+ // A renewing term, or a sepay prepay the user re-pays by hand, keeps `graceDays` past its end.
26
+ return (term.autoRenew && !term.cancelAtPeriodEnd) || term.source === 'sepay' ? before(addDays(term.currentPeriodEnd, graceDays)) : null;
24
27
  }
25
28
  case 'grace':
26
29
  return before(term.graceUntil ?? term.currentPeriodEnd);
@@ -186,6 +186,27 @@ export interface PortalCapable {
186
186
  export interface PurchaseVerifier<TProof = unknown> {
187
187
  verifyPurchase(proof: TProof): Promise<VerifiedDelivery | null>;
188
188
  }
189
+ /**
190
+ * What the provider says about one purchase right now. `paid.occurredAt` is
191
+ * the adapter's best time for the capture (SePay: the lookup time, since its
192
+ * order body carries none); `unavailable` is any answer the adapter could not
193
+ * vouch for, with a short code (`timeout`, `network`, `http_<n>`, `malformed` …).
194
+ */
195
+ export type PurchaseLookupResult = {
196
+ state: 'paid';
197
+ externalId: string;
198
+ amount: Money;
199
+ occurredAt: Date;
200
+ } | {
201
+ state: 'pending' | 'cancelled' | 'not_found';
202
+ } | {
203
+ state: 'unavailable';
204
+ reason: string;
205
+ };
206
+ /** Read-only: what the provider says about one purchase. Never applies anything and never throws. */
207
+ export interface PurchaseLookup<TProof = unknown> {
208
+ lookupPurchase(proof: TProof): Promise<PurchaseLookupResult>;
209
+ }
189
210
  export interface Reconcilable {
190
211
  listChangesSince(cursor: string | null, limit: number): Promise<{
191
212
  deliveries: VerifiedDelivery[];
@@ -200,6 +221,7 @@ export interface ConsumptionReporter {
200
221
  }
201
222
  export declare function isCheckoutCapable<T extends object>(adapter: T): adapter is T & CheckoutCapable;
202
223
  export declare function isPurchaseVerifier<T extends object>(adapter: T): adapter is T & PurchaseVerifier;
224
+ export declare function isPurchaseLookup(adapter: unknown): adapter is PurchaseLookup;
203
225
  /** `verify` refused a delivery: `unauthorized` → 401, `malformed` → 400. Nothing is stored. */
204
226
  export declare class VerifyError extends Error {
205
227
  readonly name = "VerifyError";
@@ -4,6 +4,9 @@ export function isCheckoutCapable(adapter) {
4
4
  export function isPurchaseVerifier(adapter) {
5
5
  return typeof adapter.verifyPurchase === 'function';
6
6
  }
7
+ export function isPurchaseLookup(adapter) {
8
+ return typeof adapter === 'object' && adapter !== null && typeof adapter.lookupPurchase === 'function';
9
+ }
7
10
  // ---------------------------------------------------------------------------
8
11
  // Errors
9
12
  // ---------------------------------------------------------------------------
@@ -1,4 +1,4 @@
1
- import { type CheckoutCapable, type IngestOutcome, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse, type PurchaseVerifier } from '../port.js';
1
+ import { type CheckoutCapable, type IngestOutcome, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse, type PurchaseLookup, type PurchaseVerifier } from '../port.js';
2
2
  import { type SepayOrderState } from './order.js';
3
3
  export { parseSepayOrder, parseVnd, type SepayOrderState } from './order.js';
4
4
  export { signCheckoutFields } from './signature.js';
@@ -17,12 +17,14 @@ export interface SepayAdapterOptions {
17
17
  fetch?: typeof fetch;
18
18
  /** Order API timeout. Default 10 s. */
19
19
  timeoutMs?: number;
20
+ /** `lookupPurchase` timeout per call; past it the answer is `unavailable/timeout`. Default 8 s. */
21
+ lookupTimeoutMs?: number;
20
22
  }
21
23
  /** Poll proof: the checkout session id used as the SePay invoice. */
22
24
  export interface SepayPurchaseProof {
23
25
  invoice: string;
24
26
  }
25
- export interface SepayAdapter extends ProviderAdapter, CheckoutCapable, PurchaseVerifier<SepayPurchaseProof> {
27
+ export interface SepayAdapter extends ProviderAdapter, CheckoutCapable, PurchaseVerifier<SepayPurchaseProof>, PurchaseLookup<SepayPurchaseProof> {
26
28
  readonly id: 'sepay';
27
29
  /** Current order state; `unknown` on any lookup failure. */
28
30
  readOrder(invoice: string): Promise<SepayOrderState>;
@@ -154,6 +154,15 @@ export function createSepayAdapter(options) {
154
154
  const now = new Date();
155
155
  return deliveryOf(body, now, JSON.stringify(body));
156
156
  },
157
+ async lookupPurchase(proof) {
158
+ // Read-only and never throws: missing merchant credentials are an answer too.
159
+ if (!merchantId || !secretKey)
160
+ return { state: 'unavailable', reason: 'not_configured' };
161
+ // No invoice names no order; a typed caller cannot pass one, an untyped one gets an answer, not a throw.
162
+ if (typeof proof?.invoice !== 'string' || proof.invoice === '')
163
+ return { state: 'not_found' };
164
+ return orderClient().lookup(proof.invoice, options.lookupTimeoutMs ?? 8_000);
165
+ },
157
166
  readOrder: async (invoice) => orderClient().read(invoice),
158
167
  cancelOrder: async (invoice) => orderClient().cancel(invoice),
159
168
  };
@@ -4,6 +4,7 @@
4
4
  * cancellation, and another invoice or currency is never accepted as this
5
5
  * purchase.
6
6
  */
7
+ import type { PurchaseLookupResult } from '../port.js';
7
8
  export type SepayOrderState = {
8
9
  state: 'unknown';
9
10
  } | {
@@ -24,6 +25,12 @@ export interface SepayOrderClientOptions {
24
25
  }
25
26
  export declare function createSepayOrderClient(options: SepayOrderClientOptions): {
26
27
  read: (invoice: string) => Promise<SepayOrderState>;
28
+ /**
29
+ * The read-only lookup over the same order-detail request: a missing
30
+ * order is `not_found`, anything the client cannot vouch for is
31
+ * `unavailable` with a short code, and it never throws.
32
+ */
33
+ lookup(invoice: string, timeoutMs: number): Promise<PurchaseLookupResult>;
27
34
  /**
28
35
  * A 200 cancellation answer is not a state snapshot: re-read the order,
29
36
  * so a capture racing the cancellation wins and is still settled.
@@ -1,9 +1,3 @@
1
- /**
2
- * SePay order API (read, cancel), ported from Lohi `api/src/lib/sepay.ts` —
3
- * the stricter of the two host copies: a lookup failure is never proof of
4
- * cancellation, and another invoice or currency is never accepted as this
5
- * purchase.
6
- */
7
1
  /** Parse SePay's order body (`{data: {...}}`) for `invoice`. Anything off is `unknown`. */
8
2
  export function parseSepayOrder(body, invoice) {
9
3
  const data = body?.data;
@@ -31,20 +25,31 @@ export function parseVnd(raw) {
31
25
  }
32
26
  export function createSepayOrderClient(options) {
33
27
  const authorization = `Basic ${Buffer.from(`${options.merchantId}:${options.secretKey}`).toString('base64')}`;
34
- async function request(path, body) {
35
- const response = await options.fetch(`${options.apiBase}/${path}`, {
28
+ function call(path, signal, body) {
29
+ return options.fetch(`${options.apiBase}/${path}`, {
36
30
  method: body ? 'POST' : 'GET',
37
31
  headers: { Authorization: authorization, 'Content-Type': 'application/json' },
38
32
  ...(body ? { body: JSON.stringify(body) } : {}),
39
- signal: AbortSignal.timeout(options.timeoutMs),
33
+ signal,
40
34
  });
35
+ }
36
+ /** Network errors and the timeout throw; everything the server answered is returned. */
37
+ async function detail(invoice, signal) {
38
+ const response = await call(`order/detail/${encodeURIComponent(invoice)}`, signal);
41
39
  if (!response.ok)
42
- return null;
43
- return response.json();
40
+ return { status: response.status, json: false };
41
+ const text = await response.text();
42
+ try {
43
+ return { status: response.status, json: true, body: JSON.parse(text) };
44
+ }
45
+ catch {
46
+ return { status: response.status, json: false };
47
+ }
44
48
  }
45
49
  async function read(invoice) {
46
50
  try {
47
- return parseSepayOrder(await request(`order/detail/${encodeURIComponent(invoice)}`), invoice);
51
+ const answer = await detail(invoice, AbortSignal.timeout(options.timeoutMs));
52
+ return answer.json ? parseSepayOrder(answer.body, invoice) : { state: 'unknown' };
48
53
  }
49
54
  catch {
50
55
  return { state: 'unknown' };
@@ -52,13 +57,35 @@ export function createSepayOrderClient(options) {
52
57
  }
53
58
  return {
54
59
  read,
60
+ /**
61
+ * The read-only lookup over the same order-detail request: a missing
62
+ * order is `not_found`, anything the client cannot vouch for is
63
+ * `unavailable` with a short code, and it never throws.
64
+ */
65
+ async lookup(invoice, timeoutMs) {
66
+ const signal = AbortSignal.timeout(timeoutMs);
67
+ let answer;
68
+ try {
69
+ answer = await detail(invoice, signal);
70
+ }
71
+ catch {
72
+ return { state: 'unavailable', reason: signal.aborted ? 'timeout' : 'network' };
73
+ }
74
+ if (answer.status === 404)
75
+ return { state: 'not_found' };
76
+ if (answer.status < 200 || answer.status > 299)
77
+ return { state: 'unavailable', reason: `http_${answer.status}` };
78
+ if (!answer.json)
79
+ return { state: 'unavailable', reason: 'malformed' };
80
+ return lookupResultOf(answer.body, invoice, new Date());
81
+ },
55
82
  /**
56
83
  * A 200 cancellation answer is not a state snapshot: re-read the order,
57
84
  * so a capture racing the cancellation wins and is still settled.
58
85
  */
59
86
  async cancel(invoice) {
60
87
  try {
61
- await request('order/cancel', { order_invoice_number: invoice });
88
+ await call('order/cancel', AbortSignal.timeout(options.timeoutMs), { order_invoice_number: invoice });
62
89
  }
63
90
  catch {
64
91
  // The re-read below is the answer either way.
@@ -67,3 +94,25 @@ export function createSepayOrderClient(options) {
67
94
  },
68
95
  };
69
96
  }
97
+ /**
98
+ * A 2xx order body as a lookup result. No `data` for this invoice is
99
+ * `not_found`; data for it that `parseSepayOrder` refuses (another currency,
100
+ * an unreadable amount or status) is `malformed`, never a guess. `paid` carries
101
+ * the lookup time: SePay's order body has no capture time.
102
+ */
103
+ function lookupResultOf(body, invoice, now) {
104
+ const data = body?.data;
105
+ if (!data || typeof data !== 'object' || data['order_invoice_number'] !== invoice) {
106
+ return { state: 'not_found' };
107
+ }
108
+ const order = parseSepayOrder(body, invoice);
109
+ switch (order.state) {
110
+ case 'paid':
111
+ return { state: 'paid', externalId: order.orderId ?? invoice, amount: { currency: 'VND', amountMinor: order.amountVnd }, occurredAt: now };
112
+ case 'pending':
113
+ case 'cancelled':
114
+ return { state: order.state };
115
+ default:
116
+ return { state: 'unavailable', reason: 'malformed' };
117
+ }
118
+ }
@@ -1,11 +1,14 @@
1
1
  /**
2
- * Subscription terms (design §4.6): one shape for the four sources. Credit
2
+ * Subscription terms (design §4.6): one shape for every source. Credit
3
3
  * terms are written only by the plans and renewal services; provider terms
4
- * only from `subscription.snapshot` events, under a watermark.
4
+ * only from `subscription.snapshot` events, under a watermark. A `sepay` term
5
+ * is a manual prepay (SePay has no charge-on-file): the host opens it when the
6
+ * transfer settles; it never auto-renews and is entitled for `graceDays` after
7
+ * its end so a late re-payment extends it without a gap.
5
8
  */
6
9
  import type { AccountId } from '../domain/types.js';
7
10
  import type { ProviderEnvironment } from '../providers/port.js';
8
- export type TermSource = 'credit' | 'polar' | 'apple' | 'google';
11
+ export type TermSource = 'credit' | 'sepay' | 'polar' | 'apple' | 'google';
9
12
  /**
10
13
  * - `scheduled`: a credit term that starts at `startsAt` (S3b), charged then.
11
14
  * - `active`: entitled until the period end.
package/docs/GUIDE.md CHANGED
@@ -169,6 +169,17 @@ default handlers apply through it and report the credit they post.
169
169
  5. Give the buyer the provider's portal for card and cancel:
170
170
  `polar.createPortalSession({ kind: 'account_id', value: accountId }, returnUrl)`.
171
171
 
172
+ **A SePay prepay** (no charge-on-file) is a `sepay` offer
173
+ `{ source: 'sepay', productRef, market, months, price }` — `price` is the whole
174
+ `months`, one offer per market and months; look it up with
175
+ `catalog.prepayOffer(plan, market, months)`. There is no snapshot: when the
176
+ transfer settles, the host inserts a `source: 'sepay'` term itself
177
+ (`externalId` = its order id, so a replayed settlement hits the
178
+ `(source, environment, externalId)` unique key and opens nothing), with
179
+ `autoRenew: false`. It is entitled until `currentPeriodEnd + graceDays`; a
180
+ re-payment extends it from `max(now, currentPeriodEnd)`, and the host
181
+ expires it after the grace. It carries the plan's `includedCredits`.
182
+
172
183
  ## 5. Handle a failed renewal, per source
173
184
 
174
185
  | Source | What fails | What the library does | What the host does |
@@ -176,6 +187,7 @@ default handlers apply through it and report the credit they post.
176
187
  | **Credit renewal** | Balance below the live price at `periodEnd − renewalLeadSec` | An early failure emits `renewal_failed` and leaves the term `active`. At the period end the term becomes `past_due` with `graceUntil = periodEnd + graceDays`, still entitled. After the grace it is `expired`. | Show the shortfall from the `renewal_failed` event (`required`, `balance`, `shortfall`). A top-up fires `afterCredited`, which calls `retryPastDue`; the renewal timer retries too. |
177
188
  | **Polar subscription** | The card is declined; Polar retries | The snapshot goes `past_due` and the term gets a grace window. `revoked`, or `canceled` once ended, ends access. Snapshots are ordered by Polar's `modified_at`, so an old one cannot undo a new one. | Show "update your card" with the portal link. A card fix arrives as an `active` snapshot; nothing else to do. |
178
189
  | **Apple** | Billing retry or grace period (App Store) | Auto-renewable notifications become snapshots with `past_due` / `grace`. One-time (consumable) purchases are keyed by transaction; a refund reverses once. | Treat Apple's own retry and grace as the source of truth; do not charge credits for an Apple term. Selling Apple subscriptions is the host's decision; the adapter handles the notifications. |
190
+ | **SePay prepay** | Nothing is charged: the period simply ends | Entitled for `graceDays` after `currentPeriodEnd`, never renewed (`renewal.auto` is `false`); the renewal job skips it. | Nudge before the end with a checkout link; a paid re-checkout extends the term; expire it after the grace. |
179
191
  | **Any webhook** | The handler throws | The row is `failed`, answered 5xx so the provider redelivers, retried by `sweep` with backoff, then `dead` with a `billing.alert`. | Alert on `billing.alert`; fix the cause and `ingest.replay(provider, eventId)`. |
180
192
 
181
193
  A failed **pack** payment creates no order and no credit; the session simply
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tofound/billing",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "description": "Shared subscription and credit library by 2found: credit ledger, quote/charge waterfall, Drizzle schema factory.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",