@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.
Files changed (68) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/LICENSE +3 -0
  3. package/README.md +34 -2
  4. package/dist/domain/errors.d.ts +14 -0
  5. package/dist/domain/errors.js +21 -0
  6. package/dist/domain/money.d.ts +21 -0
  7. package/dist/domain/money.js +77 -0
  8. package/dist/domain/types.d.ts +165 -0
  9. package/dist/domain/types.js +18 -0
  10. package/dist/drizzle/index.d.ts +3 -0
  11. package/dist/drizzle/index.js +3 -0
  12. package/dist/drizzle/schema-factory.d.ts +586 -0
  13. package/dist/drizzle/schema-factory.js +206 -0
  14. package/dist/drizzle/store.d.ts +20 -0
  15. package/dist/drizzle/store.js +124 -0
  16. package/dist/inbox/apply.d.ts +48 -0
  17. package/dist/inbox/apply.js +299 -0
  18. package/dist/inbox/conformance.d.ts +20 -0
  19. package/dist/inbox/conformance.js +254 -0
  20. package/dist/inbox/drizzle.d.ts +14 -0
  21. package/dist/inbox/drizzle.js +203 -0
  22. package/dist/inbox/ingest.d.ts +108 -0
  23. package/dist/inbox/ingest.js +404 -0
  24. package/dist/inbox/memory.d.ts +13 -0
  25. package/dist/inbox/memory.js +172 -0
  26. package/dist/inbox/ports.d.ts +150 -0
  27. package/dist/inbox/ports.js +1 -0
  28. package/dist/inbox/redact.d.ts +2 -0
  29. package/dist/inbox/redact.js +47 -0
  30. package/dist/inbox/schema.d.ts +1158 -0
  31. package/dist/inbox/schema.js +90 -0
  32. package/dist/inbox/watermark.d.ts +13 -0
  33. package/dist/inbox/watermark.js +6 -0
  34. package/dist/index.d.ts +20 -0
  35. package/dist/index.js +18 -0
  36. package/dist/ledger/ledger.d.ts +47 -0
  37. package/dist/ledger/ledger.js +224 -0
  38. package/dist/ports/index.d.ts +2 -0
  39. package/dist/ports/index.js +1 -0
  40. package/dist/ports/ledger-store.d.ts +53 -0
  41. package/dist/ports/ledger-store.js +1 -0
  42. package/dist/ports/runtime.d.ts +9 -0
  43. package/dist/ports/runtime.js +1 -0
  44. package/dist/providers/port.d.ts +201 -0
  45. package/dist/providers/port.js +30 -0
  46. package/dist/providers/sepay/index.d.ts +34 -0
  47. package/dist/providers/sepay/index.js +241 -0
  48. package/dist/providers/sepay/order.d.ts +32 -0
  49. package/dist/providers/sepay/order.js +69 -0
  50. package/dist/providers/sepay/signature.d.ts +8 -0
  51. package/dist/providers/sepay/signature.js +51 -0
  52. package/dist/quote/conformance.d.ts +16 -0
  53. package/dist/quote/conformance.js +39 -0
  54. package/dist/quote/index.d.ts +3 -0
  55. package/dist/quote/index.js +3 -0
  56. package/dist/quote/steps.d.ts +54 -0
  57. package/dist/quote/steps.js +103 -0
  58. package/dist/quote/waterfall.d.ts +98 -0
  59. package/dist/quote/waterfall.js +82 -0
  60. package/dist/stores/conformance.d.ts +22 -0
  61. package/dist/stores/conformance.js +269 -0
  62. package/dist/stores/memory.d.ts +19 -0
  63. package/dist/stores/memory.js +137 -0
  64. package/dist/stores/testing.d.ts +11 -0
  65. package/dist/stores/testing.js +11 -0
  66. package/docs/API.md +198 -0
  67. package/docs/SCHEMA.md +108 -0
  68. package/package.json +75 -4
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Applying normalized events inside the inbox transaction (design §4.11, §6).
3
+ *
4
+ * Purchases credit **exactly once**: the checkout session is the unit of
5
+ * money (`topup:<sessionId>` is the ledger key), the provider's amount must
6
+ * equal the session's, and a purchase only moves forward
7
+ * (`completed → reversed ⇄ reinstated`, newest event wins). A capture after
8
+ * the session expired or was cancelled still credits — money taken is money
9
+ * owed (2Novel used to refuse it). A void seen before its capture blocks that
10
+ * capture unless a newer reinstatement follows.
11
+ */
12
+ import { isBillingError } from '../domain/errors.js';
13
+ import { isNewer } from './watermark.js';
14
+ const sameMoney = (a, b) => a.currency === b.currency && a.amountMinor === b.amountMinor;
15
+ /** The one ledger key of a checkout's credit: whichever path pays it, it is paid once. */
16
+ const topupKey = (sessionId) => `topup:${sessionId}`;
17
+ /** An adapter's fallback purchase id when the provider sent none (SePay: `inv:<invoice>`). */
18
+ const isSynthetic = (externalId) => externalId === null || externalId.startsWith('inv:');
19
+ const pendingOf = (p) => {
20
+ const pending = p.meta?.['pendingCredit'];
21
+ return pending && typeof pending.credits === 'number' && pending.credits > 0 ? pending : null;
22
+ };
23
+ const withoutPending = (meta) => {
24
+ if (!meta)
25
+ return null;
26
+ const { pendingCredit: _, ...rest } = meta;
27
+ return Object.keys(rest).length ? rest : null;
28
+ };
29
+ export async function applyPurchaseCompleted(event, d) {
30
+ const { delivery } = d;
31
+ const sessionId = event.checkoutRef ?? (event.account.kind === 'checkout' ? event.account.value : null);
32
+ // Only checkout-bound purchases are applied by the library in 0.1; other
33
+ // bindings (Apple appAccountToken …) arrive with their adapters.
34
+ if (!sessionId)
35
+ return { status: 'needs_review', reason: 'unsupported_account_ref' };
36
+ const session = await d.tx.lockSession(sessionId);
37
+ if (!session)
38
+ return { status: 'ignored', reason: 'no_match', unmatched: true };
39
+ if (session.provider !== delivery.provider || session.environment !== delivery.environment) {
40
+ return { status: 'needs_review', reason: 'session_provider_mismatch' };
41
+ }
42
+ if (!sameMoney(event.amount, session.amount))
43
+ return { status: 'needs_review', reason: 'amount_mismatch' };
44
+ let purchase = await d.tx.lockPurchase(delivery.provider, delivery.environment, event.externalId);
45
+ if (!purchase && session.externalId && session.externalId !== event.externalId && isSynthetic(event.externalId)) {
46
+ // A capture without the provider's id (a poll) belongs to the purchase
47
+ // an earlier void or reinstatement recorded on this session.
48
+ purchase = await d.tx.lockPurchase(delivery.provider, delivery.environment, session.externalId);
49
+ }
50
+ if (purchase) {
51
+ if (purchase.credits > 0)
52
+ return { status: 'ignored', reason: 'already_completed' };
53
+ if (purchase.status === 'reversed') {
54
+ // Voided before the capture reached us: never credit now, but remember
55
+ // what a newer reinstatement owes (Lohi `refundWalletTopup` blocks it).
56
+ if (!pendingOf(purchase)) {
57
+ await d.tx.updatePurchase(purchase.id, {
58
+ meta: { ...(purchase.meta ?? {}), pendingCredit: { sessionId: session.id, credits: session.credits } },
59
+ });
60
+ }
61
+ return { status: 'ignored', reason: 'reversed_before_credit' };
62
+ }
63
+ // Reinstated before its capture arrived: the capture credits now.
64
+ }
65
+ else if (session.status === 'voided') {
66
+ return { status: 'ignored', reason: 'reversed_before_credit' };
67
+ }
68
+ else if (session.status === 'completed') {
69
+ // The same capture seen under another id (a poll without SePay's order id)
70
+ // is a duplicate; two different captures of one invoice is money for a human.
71
+ if (session.externalId === event.externalId || isSynthetic(session.externalId) || isSynthetic(event.externalId)) {
72
+ return { status: 'ignored', reason: 'already_completed' };
73
+ }
74
+ return { status: 'needs_review', reason: 'second_capture' };
75
+ }
76
+ // pending | expired | cancelled (or reinstated-first): a verified capture is credited.
77
+ const posted = await d.ledger.credit({
78
+ accountId: session.accountId,
79
+ kind: 'topup',
80
+ amount: session.credits,
81
+ idempotencyKey: topupKey(session.id),
82
+ source: { type: 'checkout_session', id: session.id },
83
+ meta: { provider: delivery.provider, externalId: event.externalId, amount: event.amount },
84
+ });
85
+ const now = d.now;
86
+ if (purchase) {
87
+ await d.tx.updatePurchase(purchase.id, { credits: session.credits, creditEntryId: posted.entry.id });
88
+ }
89
+ else {
90
+ const { inserted } = await d.tx.insertPurchase({
91
+ id: d.newId(),
92
+ accountId: session.accountId,
93
+ provider: delivery.provider,
94
+ environment: delivery.environment,
95
+ externalId: event.externalId,
96
+ checkoutSessionId: session.id,
97
+ status: 'completed',
98
+ amount: event.amount,
99
+ credits: session.credits,
100
+ creditEntryId: posted.entry.id,
101
+ clawedBack: 0,
102
+ shortfall: 0,
103
+ reversals: 0,
104
+ lastEventAt: null,
105
+ lastEventRef: null,
106
+ meta: event.productRef ? { productRef: event.productRef } : null,
107
+ createdAt: now,
108
+ updatedAt: now,
109
+ });
110
+ // The unique key serializes captures; losing that race means a concurrent
111
+ // winner credited under the same ledger key (a replay).
112
+ if (!inserted)
113
+ return { status: 'ignored', reason: 'already_completed' };
114
+ }
115
+ await d.tx.updateSession(session.id, { status: 'completed', externalId: purchase?.externalId ?? event.externalId, completedAt: now });
116
+ return {
117
+ status: 'applied',
118
+ ...(session.status === 'pending' ? {} : { reason: `late_${session.status}` }),
119
+ events: posted.events,
120
+ };
121
+ }
122
+ /**
123
+ * `purchase.reversed` / `purchase.reinstated`. Only an event newer than the
124
+ * purchase's watermark changes it, so redelivered or out-of-order events
125
+ * cannot regress state; whatever order capture, reversal and reinstatement
126
+ * arrive in, the purchase ends where the newest event puts it.
127
+ */
128
+ export async function applyPurchaseChanged(event, d) {
129
+ const { delivery } = d;
130
+ const reversing = event.kind === 'purchase.reversed';
131
+ // Lock order: session before purchase, as on the capture path. Without a
132
+ // checkout ref the purchase names its session; that peek is unlocked, the
133
+ // lock follows in order.
134
+ const sessionId = event.checkoutRef ?? (await d.tx.getPurchase(delivery.provider, delivery.environment, event.externalId))?.checkoutSessionId ?? null;
135
+ const session = sessionId ? await d.tx.lockSession(sessionId) : null;
136
+ let purchase = await d.tx.lockPurchase(delivery.provider, delivery.environment, event.externalId);
137
+ if (!purchase &&
138
+ session?.externalId &&
139
+ session.externalId !== event.externalId &&
140
+ (isSynthetic(session.externalId) || isSynthetic(event.externalId))) {
141
+ // One side is a stand-in for the provider's id, so both name the
142
+ // session's purchase. Two real, different ids are two orders.
143
+ purchase = await d.tx.lockPurchase(delivery.provider, delivery.environment, session.externalId);
144
+ }
145
+ const mark = { at: event.occurredAt, ref: delivery.eventId };
146
+ if (!purchase) {
147
+ if (!session)
148
+ return { status: 'ignored', reason: 'no_match', unmatched: true };
149
+ if (session.provider !== delivery.provider || session.environment !== delivery.environment) {
150
+ return { status: 'needs_review', reason: 'session_provider_mismatch' };
151
+ }
152
+ if (event.amount && !sameMoney(event.amount, session.amount))
153
+ return { status: 'needs_review', reason: 'purchase_mismatch' };
154
+ // The change outran its capture: record it, so the capture lands on the
155
+ // newest word instead of resurrecting a voided purchase.
156
+ const now = d.now;
157
+ await d.tx.insertPurchase({
158
+ id: d.newId(),
159
+ accountId: session.accountId,
160
+ provider: delivery.provider,
161
+ environment: delivery.environment,
162
+ externalId: event.externalId,
163
+ checkoutSessionId: session.id,
164
+ status: reversing ? 'reversed' : 'reinstated',
165
+ amount: session.amount,
166
+ credits: 0,
167
+ creditEntryId: null,
168
+ clawedBack: 0,
169
+ shortfall: 0,
170
+ reversals: reversing ? 1 : 0,
171
+ lastEventAt: mark.at,
172
+ lastEventRef: mark.ref,
173
+ meta: event.reason ? { reason: event.reason } : null,
174
+ createdAt: now,
175
+ updatedAt: now,
176
+ });
177
+ // The session remembers the purchase, so a capture that arrives without
178
+ // the provider's id (a poll) still finds this record.
179
+ if (session.status !== 'completed') {
180
+ await d.tx.updateSession(session.id, { ...(reversing ? { status: 'voided' } : {}), externalId: event.externalId });
181
+ }
182
+ return { status: 'applied', reason: reversing ? 'reversed_before_credit' : 'reinstated_before_credit' };
183
+ }
184
+ if (event.amount && !sameMoney(event.amount, purchase.amount))
185
+ return { status: 'needs_review', reason: 'purchase_mismatch' };
186
+ const current = purchase.lastEventAt ? { at: purchase.lastEventAt, ref: purchase.lastEventRef ?? '' } : null;
187
+ if (!isNewer(current, mark))
188
+ return { status: 'ignored', reason: 'stale' };
189
+ return reversing ? reverse(purchase, mark, d) : reinstate(purchase, mark, d);
190
+ }
191
+ async function reverse(purchase, mark, d) {
192
+ if (purchase.status === 'reversed') {
193
+ await d.tx.updatePurchase(purchase.id, { lastEventAt: mark.at, lastEventRef: mark.ref });
194
+ return { status: 'ignored', reason: 'already_reversed' };
195
+ }
196
+ const claw = await clawback(purchase, d);
197
+ await d.tx.updatePurchase(purchase.id, {
198
+ status: 'reversed',
199
+ reversals: purchase.reversals + 1,
200
+ clawedBack: claw.clawedBack,
201
+ shortfall: claw.shortfall,
202
+ // Once countered, the entry cannot be reversed again; a reinstatement
203
+ // posts the next crediting entry.
204
+ creditEntryId: claw.clawedBack > 0 ? null : purchase.creditEntryId,
205
+ lastEventAt: mark.at,
206
+ lastEventRef: mark.ref,
207
+ });
208
+ return {
209
+ status: 'applied',
210
+ ...(claw.shortfall > 0 ? { reason: 'reversed_with_shortfall' } : {}),
211
+ events: claw.events,
212
+ reversal: {
213
+ accountId: purchase.accountId,
214
+ provider: d.delivery.provider,
215
+ externalId: purchase.externalId,
216
+ clawedBack: claw.clawedBack,
217
+ shortfall: claw.shortfall,
218
+ },
219
+ };
220
+ }
221
+ async function reinstate(purchase, mark, d) {
222
+ if (purchase.status !== 'reversed') {
223
+ // Newest word is "reinstated" either way; nothing was taken back.
224
+ await d.tx.updatePurchase(purchase.id, { status: 'reinstated', lastEventAt: mark.at, lastEventRef: mark.ref });
225
+ return { status: 'ignored', reason: 'not_reversed' };
226
+ }
227
+ let events = [];
228
+ const patch = {
229
+ status: 'reinstated',
230
+ clawedBack: 0,
231
+ shortfall: 0,
232
+ lastEventAt: mark.at,
233
+ lastEventRef: mark.ref,
234
+ };
235
+ const pending = pendingOf(purchase);
236
+ if (pending) {
237
+ // The capture we parked under the reversal is owed now — under the
238
+ // capture's own ledger key, so it can never be credited twice.
239
+ const posted = await d.ledger.credit({
240
+ accountId: purchase.accountId,
241
+ kind: 'topup',
242
+ amount: pending.credits,
243
+ idempotencyKey: topupKey(pending.sessionId),
244
+ source: { type: 'checkout_session', id: pending.sessionId },
245
+ meta: { provider: purchase.provider, externalId: purchase.externalId, amount: purchase.amount },
246
+ });
247
+ events = posted.events;
248
+ Object.assign(patch, { credits: pending.credits, creditEntryId: posted.entry.id, meta: withoutPending(purchase.meta) });
249
+ // The session is paid now: a second capture of it is money for a human.
250
+ await d.tx.updateSession(pending.sessionId, { status: 'completed', externalId: purchase.externalId, completedAt: d.now });
251
+ }
252
+ else if (purchase.clawedBack > 0) {
253
+ // Restore only what the reversal actually took back.
254
+ const posted = await d.ledger.credit({
255
+ accountId: purchase.accountId,
256
+ kind: 'adjustment',
257
+ reason: 'provider_reinstated',
258
+ amount: purchase.clawedBack,
259
+ idempotencyKey: `reinstate:${purchase.provider}:${purchase.externalId}:${purchase.reversals}`,
260
+ source: { type: 'purchase', id: purchase.id },
261
+ });
262
+ events = posted.events;
263
+ patch.creditEntryId = posted.entry.id;
264
+ }
265
+ await d.tx.updatePurchase(purchase.id, patch);
266
+ return { status: 'applied', events };
267
+ }
268
+ /**
269
+ * Counter the purchase's crediting entry by what the balance still holds;
270
+ * the rest of the purchase's credits is the shortfall (design §4.11 — the
271
+ * host's policy decides whether a shortfall lapses terms). Every read and
272
+ * write goes through the open transaction.
273
+ */
274
+ async function clawback(purchase, d) {
275
+ if (!purchase.creditEntryId)
276
+ return { clawedBack: 0, shortfall: purchase.credits, events: [] };
277
+ const entryId = purchase.creditEntryId;
278
+ const key = `reversal:${purchase.provider}:${purchase.externalId}:${purchase.reversals + 1}`;
279
+ const reverseEntry = (amount) => d.ledger.reverse({ entryId, ...(amount === undefined ? {} : { amount }), idempotencyKey: key, reason: 'provider_reversal' });
280
+ // After a partial clawback and a reinstatement the crediting entry is the
281
+ // smaller adjustment, but the purchase still granted `credits`.
282
+ const owed = (taken) => Math.max(purchase.credits, taken);
283
+ try {
284
+ const posted = await reverseEntry();
285
+ const taken = Math.abs(posted.entry.delta);
286
+ return { clawedBack: taken, shortfall: owed(taken) - taken, events: posted.events };
287
+ }
288
+ catch (err) {
289
+ if (!isBillingError(err, 'insufficient_credits'))
290
+ throw err;
291
+ // The ledger holds the account lock now, so this balance is stable.
292
+ const available = Number(err.details['balance'] ?? 0);
293
+ const required = Number(err.details['required'] ?? 0);
294
+ if (available <= 0)
295
+ return { clawedBack: 0, shortfall: owed(required), events: [] };
296
+ const posted = await reverseEntry(available);
297
+ return { clawedBack: available, shortfall: owed(required) - available, events: posted.events };
298
+ }
299
+ }
@@ -0,0 +1,20 @@
1
+ import type { LedgerStore } from '../ports/ledger-store.js';
2
+ import type { IngestStore } from './ports.js';
3
+ /**
4
+ * The ingest store conformance suite. Every `IngestStore` — memory, the
5
+ * Drizzle store, a host adapter — must pass all of it, paired with the
6
+ * `LedgerStore` it shares transactions with. Each case throws on failure:
7
+ *
8
+ * for (const c of ingestConformanceCases) test(c.name, () => c.run(target))
9
+ */
10
+ export interface IngestConformanceTarget<TTx = unknown> {
11
+ store: IngestStore<TTx>;
12
+ ledgerStore: LedgerStore<TTx>;
13
+ /** A fresh, never-used account id of the host's type. */
14
+ newAccountId(): string;
15
+ }
16
+ export interface IngestConformanceCase {
17
+ name: string;
18
+ run<TTx>(target: IngestConformanceTarget<TTx>): Promise<void>;
19
+ }
20
+ export declare const ingestConformanceCases: IngestConformanceCase[];
@@ -0,0 +1,254 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createLedger } from '../ledger/ledger.js';
3
+ function check(ok, message) {
4
+ if (!ok)
5
+ throw new Error(`ingest conformance: ${message}`);
6
+ }
7
+ function equal(actual, expected, what) {
8
+ check(actual === expected, `${what}: expected ${String(expected)}, got ${String(actual)}`);
9
+ }
10
+ const uid = () => randomUUID();
11
+ const at = (iso) => new Date(iso);
12
+ function inboxRow(over = {}) {
13
+ const now = at('2026-01-01T00:00:00Z');
14
+ return {
15
+ id: uid(),
16
+ provider: 'sepay',
17
+ environment: 'sandbox',
18
+ eventId: `sepay:ORDER_PAID:${uid()}`,
19
+ eventType: 'ORDER_PAID',
20
+ subjectRef: null,
21
+ status: 'received',
22
+ attempts: 0,
23
+ deliveryCount: 1,
24
+ nextAttemptAt: now,
25
+ lastError: null,
26
+ reason: null,
27
+ payload: { order: { order_amount: '50000' } },
28
+ occurredAt: now,
29
+ receivedAt: now,
30
+ lastReceivedAt: now,
31
+ processedAt: null,
32
+ ...over,
33
+ };
34
+ }
35
+ function session(accountId, over = {}) {
36
+ const now = at('2026-01-01T00:00:00Z');
37
+ return {
38
+ id: uid(),
39
+ accountId,
40
+ provider: 'sepay',
41
+ environment: 'sandbox',
42
+ status: 'pending',
43
+ amount: { currency: 'VND', amountMinor: 50_000 },
44
+ credits: 5_000_000,
45
+ productRef: 'pack_50k',
46
+ externalId: null,
47
+ expiresAt: at('2026-01-01T00:30:00Z'),
48
+ completedAt: null,
49
+ meta: { market: 'vn' },
50
+ createdAt: now,
51
+ updatedAt: now,
52
+ ...over,
53
+ };
54
+ }
55
+ function purchase(accountId, over = {}) {
56
+ const now = at('2026-01-01T00:00:00Z');
57
+ return {
58
+ id: uid(),
59
+ accountId,
60
+ provider: 'sepay',
61
+ environment: 'sandbox',
62
+ externalId: `ord_${uid()}`,
63
+ checkoutSessionId: null,
64
+ status: 'completed',
65
+ amount: { currency: 'VND', amountMinor: 50_000 },
66
+ credits: 5_000_000,
67
+ creditEntryId: null,
68
+ clawedBack: 0,
69
+ shortfall: 0,
70
+ reversals: 0,
71
+ lastEventAt: null,
72
+ lastEventRef: null,
73
+ meta: null,
74
+ createdAt: now,
75
+ updatedAt: now,
76
+ ...over,
77
+ };
78
+ }
79
+ const ROLLBACK = new Error('ingest conformance rollback');
80
+ export const ingestConformanceCases = [
81
+ {
82
+ name: 'receive inserts once and counts redeliveries on the existing row',
83
+ async run(t) {
84
+ const row = inboxRow();
85
+ const first = await t.store.transaction((tx) => t.store.bind(tx).receive(row));
86
+ equal(first.inserted, true, 'first insert');
87
+ const later = at('2026-01-01T00:05:00Z');
88
+ const again = await t.store.transaction((tx) => t.store.bind(tx).receive({ ...row, id: uid(), lastReceivedAt: later, status: 'received' }));
89
+ equal(again.inserted, false, 'second insert');
90
+ equal(again.row.id, row.id, 'existing row id');
91
+ equal(again.row.deliveryCount, 2, 'delivery count');
92
+ const stored = await t.store.reader().getInbox('sepay', row.eventId);
93
+ check(stored !== null, 'row stored');
94
+ equal(stored.deliveryCount, 2, 'stored delivery count');
95
+ equal(stored.lastReceivedAt.getTime(), later.getTime(), 'lastReceivedAt');
96
+ equal(stored.receivedAt.getTime(), row.receivedAt.getTime(), 'receivedAt kept');
97
+ equal(JSON.stringify(stored.payload), JSON.stringify(row.payload), 'payload round-trips');
98
+ },
99
+ },
100
+ {
101
+ name: 'the same event id under another provider is a different row',
102
+ async run(t) {
103
+ const eventId = `shared:${uid()}`;
104
+ await t.store.transaction((tx) => t.store.bind(tx).receive(inboxRow({ eventId })));
105
+ const other = await t.store.transaction((tx) => t.store.bind(tx).receive(inboxRow({ eventId, provider: 'polar' })));
106
+ equal(other.inserted, true, 'other provider inserts');
107
+ },
108
+ },
109
+ {
110
+ name: 'updateInbox patches status, attempts and retry fields',
111
+ async run(t) {
112
+ const row = inboxRow();
113
+ await t.store.transaction((tx) => t.store.bind(tx).receive(row));
114
+ const next = at('2026-01-01T01:00:00Z');
115
+ await t.store.transaction(async (tx) => {
116
+ const itx = t.store.bind(tx);
117
+ const locked = await itx.lockInbox('sepay', row.eventId);
118
+ check(locked !== null, 'lockInbox finds the row');
119
+ await itx.updateInbox(locked.id, { status: 'failed', attempts: 1, nextAttemptAt: next, lastError: 'boom', reason: null });
120
+ });
121
+ const stored = await t.store.reader().getInbox('sepay', row.eventId);
122
+ equal(stored?.status, 'failed', 'status');
123
+ equal(stored?.attempts, 1, 'attempts');
124
+ equal(stored?.nextAttemptAt?.getTime(), next.getTime(), 'nextAttemptAt');
125
+ equal(stored?.lastError, 'boom', 'lastError');
126
+ },
127
+ },
128
+ {
129
+ name: 'listDue returns received/failed rows due by now, oldest due first, and nothing final',
130
+ async run(t) {
131
+ const base = Date.parse('2030-06-01T00:00:00Z') + Math.floor(Math.random() * 1e9);
132
+ const due = (ms) => new Date(base + ms);
133
+ const rows = [
134
+ inboxRow({ status: 'failed', nextAttemptAt: due(2_000) }),
135
+ inboxRow({ status: 'received', nextAttemptAt: due(1_000) }),
136
+ inboxRow({ status: 'failed', nextAttemptAt: due(60_000) }),
137
+ inboxRow({ status: 'applied', nextAttemptAt: due(0) }),
138
+ inboxRow({ status: 'dead', nextAttemptAt: null }),
139
+ inboxRow({ provider: 'polar', eventId: `polar:${uid()}`, status: 'failed', nextAttemptAt: due(500) }),
140
+ ];
141
+ for (const row of rows)
142
+ await t.store.transaction((tx) => t.store.bind(tx).receive(row));
143
+ const listed = await t.store.reader().listDue(due(5_000), 1_000);
144
+ const mine = listed.filter((r) => rows.some((x) => x.eventId === r.eventId)).map((r) => r.eventId);
145
+ equal(mine.join(','), [rows[5].eventId, rows[1].eventId, rows[0].eventId].join(','), 'due rows in order');
146
+ // Only the providers asked for: a row no registered adapter can process never blocks the sweep.
147
+ const sepayOnly = (await t.store.reader().listDue(due(5_000), 1_000, ['sepay'])).filter((r) => rows.some((x) => x.eventId === r.eventId));
148
+ equal(sepayOnly.map((r) => r.eventId).join(','), [rows[1].eventId, rows[0].eventId].join(','), 'due rows of the listed providers');
149
+ },
150
+ },
151
+ {
152
+ name: 'listInbox filters by status, newest first',
153
+ async run(t) {
154
+ const reason = `list-${uid()}`;
155
+ const a = inboxRow({ status: 'needs_review', reason, receivedAt: at('2031-01-01T00:00:00Z') });
156
+ const b = inboxRow({ status: 'needs_review', reason, receivedAt: at('2031-01-02T00:00:00Z') });
157
+ for (const row of [a, b])
158
+ await t.store.transaction((tx) => t.store.bind(tx).receive(row));
159
+ const listed = (await t.store.reader().listInbox({ statuses: ['needs_review'], limit: 10_000 })).filter((r) => r.reason === reason);
160
+ equal(listed.map((r) => r.eventId).join(','), [b.eventId, a.eventId].join(','), 'newest first');
161
+ const older = (await t.store.reader().listInbox({ statuses: ['needs_review'], limit: 10_000, receivedBefore: b.receivedAt })).filter((r) => r.reason === reason);
162
+ equal(older.map((r) => r.eventId).join(','), a.eventId, 'receivedBefore page');
163
+ },
164
+ },
165
+ {
166
+ name: 'checkout sessions round-trip, lock and update',
167
+ async run(t) {
168
+ const s = session(t.newAccountId());
169
+ await t.store.transaction((tx) => t.store.bind(tx).insertSession(s));
170
+ const read = await t.store.reader().getSession(s.id);
171
+ check(read !== null, 'session stored');
172
+ equal(read.accountId, s.accountId, 'accountId');
173
+ equal(read.amount.amountMinor, 50_000, 'amount');
174
+ equal(read.amount.currency, 'VND', 'currency');
175
+ equal(read.credits, 5_000_000, 'credits');
176
+ equal(read.status, 'pending', 'status');
177
+ const done = at('2026-01-01T00:10:00Z');
178
+ await t.store.transaction(async (tx) => {
179
+ const itx = t.store.bind(tx);
180
+ const locked = await itx.lockSession(s.id);
181
+ equal(locked?.id, s.id, 'lockSession');
182
+ await itx.updateSession(s.id, { status: 'completed', externalId: 'ord_1', completedAt: done });
183
+ equal((await itx.getSession(s.id))?.status, 'completed', 'read own write');
184
+ });
185
+ const after = await t.store.reader().getSession(s.id);
186
+ equal(after?.status, 'completed', 'committed status');
187
+ equal(after?.externalId, 'ord_1', 'externalId');
188
+ equal(after?.completedAt?.getTime(), done.getTime(), 'completedAt');
189
+ },
190
+ },
191
+ {
192
+ name: 'purchases are unique per (provider, environment, externalId)',
193
+ async run(t) {
194
+ const accountId = t.newAccountId();
195
+ const p = purchase(accountId);
196
+ const first = await t.store.transaction((tx) => t.store.bind(tx).insertPurchase(p));
197
+ equal(first.inserted, true, 'first insert');
198
+ const dup = await t.store.transaction((tx) => t.store.bind(tx).insertPurchase({ ...p, id: uid() }));
199
+ equal(dup.inserted, false, 'duplicate insert');
200
+ const otherEnv = await t.store.transaction((tx) => t.store.bind(tx).insertPurchase({ ...p, id: uid(), environment: 'production' }));
201
+ equal(otherEnv.inserted, true, 'other environment');
202
+ const when = at('2026-02-01T00:00:00Z');
203
+ await t.store.transaction(async (tx) => {
204
+ const itx = t.store.bind(tx);
205
+ const locked = await itx.lockPurchase('sepay', 'sandbox', p.externalId);
206
+ check(locked !== null, 'lockPurchase');
207
+ await itx.updatePurchase(locked.id, { status: 'reversed', reversals: 1, clawedBack: 10, shortfall: 5, lastEventAt: when, lastEventRef: 'e1' });
208
+ });
209
+ const read = await t.store.reader().getPurchase('sepay', 'sandbox', p.externalId);
210
+ equal(read?.status, 'reversed', 'status');
211
+ equal(read?.clawedBack, 10, 'clawedBack');
212
+ equal(read?.shortfall, 5, 'shortfall');
213
+ equal(read?.lastEventAt?.getTime(), when.getTime(), 'lastEventAt');
214
+ equal(read?.amount.amountMinor, 50_000, 'amount');
215
+ },
216
+ },
217
+ {
218
+ name: 'inbox, purchase and ledger entry commit together and roll back together',
219
+ async run(t) {
220
+ const ledger = createLedger({ store: t.ledgerStore });
221
+ const accountId = t.newAccountId();
222
+ const row = inboxRow();
223
+ const p = purchase(accountId);
224
+ const s = session(accountId);
225
+ try {
226
+ await t.store.transaction(async (tx) => {
227
+ const itx = t.store.bind(tx);
228
+ await itx.receive(row);
229
+ await itx.insertSession(s);
230
+ await itx.insertPurchase(p);
231
+ await ledger.in(tx).credit({ accountId, kind: 'topup', amount: 100, idempotencyKey: `conf:${row.id}` });
232
+ throw ROLLBACK;
233
+ });
234
+ }
235
+ catch (error) {
236
+ if (error !== ROLLBACK)
237
+ throw error;
238
+ }
239
+ equal(await t.store.reader().getInbox('sepay', row.eventId), null, 'inbox rolled back');
240
+ equal(await t.store.reader().getSession(s.id), null, 'session rolled back');
241
+ equal(await t.store.reader().getPurchase('sepay', 'sandbox', p.externalId), null, 'purchase rolled back');
242
+ equal(await ledger.balance(accountId), 0, 'ledger rolled back');
243
+ await t.store.transaction(async (tx) => {
244
+ const itx = t.store.bind(tx);
245
+ await itx.receive(row);
246
+ await itx.insertPurchase(p);
247
+ await ledger.in(tx).credit({ accountId, kind: 'topup', amount: 100, idempotencyKey: `conf:${row.id}` });
248
+ });
249
+ check((await t.store.reader().getInbox('sepay', row.eventId)) !== null, 'inbox committed');
250
+ check((await t.store.reader().getPurchase('sepay', 'sandbox', p.externalId)) !== null, 'purchase committed');
251
+ equal(await ledger.balance(accountId), 100, 'ledger committed');
252
+ },
253
+ },
254
+ ];
@@ -0,0 +1,14 @@
1
+ import type { PgTable } from 'drizzle-orm/pg-core';
2
+ import type { AnyPgDatabase, AnyPgTransaction } from '../drizzle/store.js';
3
+ import type { IngestStore } from './ports.js';
4
+ export { createIngestTables, ingestTableNames, type IngestTables } from './schema.js';
5
+ export interface DrizzleIngestStoreOptions {
6
+ db: AnyPgDatabase;
7
+ /** The host's ingest tables (`createIngestTables(...)`), whatever its account column type. */
8
+ tables: {
9
+ billingInbox: PgTable;
10
+ billingCheckoutSessions: PgTable;
11
+ billingPurchases: PgTable;
12
+ };
13
+ }
14
+ export declare function createDrizzleIngestStore(options: DrizzleIngestStoreOptions): IngestStore<AnyPgTransaction>;