@appweaver/payments 0.0.0-stage → 3.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 (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +212 -2
  3. package/config.d.ts +77 -0
  4. package/config.js +118 -0
  5. package/gateway/fake-gateway.d.ts +144 -0
  6. package/gateway/fake-gateway.js +805 -0
  7. package/gateway/gateway-registry.d.ts +99 -0
  8. package/gateway/gateway-registry.js +275 -0
  9. package/gateway/payment-gateway.d.ts +68 -0
  10. package/gateway/payment-gateway.js +82 -0
  11. package/index.d.ts +16 -0
  12. package/index.js +51 -0
  13. package/locales/en.json +47 -0
  14. package/maintenance/payment-maintenance-jobs.d.ts +5 -0
  15. package/maintenance/payment-maintenance-jobs.js +38 -0
  16. package/module.d.ts +8 -0
  17. package/module.js +85 -0
  18. package/package.json +67 -3
  19. package/resources/model-util.d.ts +40 -0
  20. package/resources/model-util.js +30 -0
  21. package/resources/payment/model.d.ts +2 -0
  22. package/resources/payment/model.js +106 -0
  23. package/resources/payment-customer/model.d.ts +2 -0
  24. package/resources/payment-customer/model.js +53 -0
  25. package/resources/payment-event/model.d.ts +2 -0
  26. package/resources/payment-event/model.js +31 -0
  27. package/resources/payment-invoice/model.d.ts +2 -0
  28. package/resources/payment-invoice/model.js +55 -0
  29. package/resources/payment-method/model.d.ts +2 -0
  30. package/resources/payment-method/model.js +37 -0
  31. package/resources/payment-plan/model.d.ts +2 -0
  32. package/resources/payment-plan/model.js +37 -0
  33. package/resources/payment-subscription/model.d.ts +2 -0
  34. package/resources/payment-subscription/model.js +82 -0
  35. package/resources/payment-transaction/model.d.ts +2 -0
  36. package/resources/payment-transaction/model.js +43 -0
  37. package/resources/payment-webhook-event/model.d.ts +2 -0
  38. package/resources/payment-webhook-event/model.js +32 -0
  39. package/resources/policies.d.ts +15 -0
  40. package/resources/policies.js +36 -0
  41. package/resources/services.d.ts +6 -0
  42. package/resources/services.js +19 -0
  43. package/resources/subscriptions.d.ts +9 -0
  44. package/resources/subscriptions.js +30 -0
  45. package/resources.d.ts +8 -0
  46. package/resources.js +34 -0
  47. package/service/payment-emails.d.ts +12 -0
  48. package/service/payment-emails.js +145 -0
  49. package/service/payment-events.d.ts +90 -0
  50. package/service/payment-events.js +472 -0
  51. package/service/payment-handlers.d.ts +26 -0
  52. package/service/payment-handlers.js +42 -0
  53. package/service/payment-store.d.ts +50 -0
  54. package/service/payment-store.js +95 -0
  55. package/service/payment-sync.d.ts +113 -0
  56. package/service/payment-sync.js +745 -0
  57. package/service/payments-service.d.ts +307 -0
  58. package/service/payments-service.js +747 -0
  59. package/service/subscriptions-service.d.ts +178 -0
  60. package/service/subscriptions-service.js +433 -0
  61. package/tasks/payments-replay.d.ts +10 -0
  62. package/tasks/payments-replay.js +36 -0
  63. package/tasks/payments-sync-plans.d.ts +10 -0
  64. package/tasks/payments-sync-plans.js +24 -0
  65. package/templates/emails/payment-action-required.html.hbs +28 -0
  66. package/templates/emails/payment-action-required.subject.hbs +1 -0
  67. package/templates/emails/payment-failed.html.hbs +37 -0
  68. package/templates/emails/payment-failed.subject.hbs +1 -0
  69. package/templates/emails/payment-receipt.html.hbs +45 -0
  70. package/templates/emails/payment-receipt.subject.hbs +1 -0
  71. package/templates/emails/payment-refunded.html.hbs +37 -0
  72. package/templates/emails/payment-refunded.subject.hbs +1 -0
  73. package/templates/emails/subscription-canceled.html.hbs +24 -0
  74. package/templates/emails/subscription-canceled.subject.hbs +1 -0
  75. package/templates/emails/subscription-trial-ending.html.hbs +25 -0
  76. package/templates/emails/subscription-trial-ending.subject.hbs +1 -0
  77. package/templates/layouts/email.html.hbs +36 -0
  78. package/templates/partials/email-button.html.hbs +15 -0
  79. package/tsconfig.build.tsbuildinfo +1 -0
  80. package/types.d.ts +488 -0
  81. package/types.js +2 -0
  82. package/utils/money-util.d.ts +61 -0
  83. package/utils/money-util.js +124 -0
  84. package/utils/status-util.d.ts +29 -0
  85. package/utils/status-util.js +93 -0
  86. package/utils/telemetry.d.ts +16 -0
  87. package/utils/telemetry.js +69 -0
  88. package/web/payment-routes.d.ts +7 -0
  89. package/web/payment-routes.js +410 -0
  90. package/web/payment-schemas.d.ts +70 -0
  91. package/web/payment-schemas.js +101 -0
@@ -0,0 +1,472 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PaymentEvents = void 0;
4
+ const common_1 = require("@appweaver/common");
5
+ const core_1 = require("@appweaver/core");
6
+ const data_1 = require("@appweaver/data");
7
+ const config_1 = require("../config");
8
+ const fake_gateway_1 = require("../gateway/fake-gateway");
9
+ const gateway_registry_1 = require("../gateway/gateway-registry");
10
+ const telemetry_1 = require("../utils/telemetry");
11
+ const payment_emails_1 = require("./payment-emails");
12
+ const payment_handlers_1 = require("./payment-handlers");
13
+ const payment_store_1 = require("./payment-store");
14
+ const payment_sync_1 = require("./payment-sync");
15
+ const logger = (0, common_1.createLogger)('payments');
16
+ /** The name of the queue processing the webhook events and delivering the events of the payments. */
17
+ const PAYMENTS_QUEUE = 'payments';
18
+ /** The dates of the objects of a gateway, read back from the JSON of a stored event. */
19
+ const DATE_KEYS = new Set([
20
+ 'currentPeriodStart',
21
+ 'currentPeriodEnd',
22
+ 'trialEnd',
23
+ 'canceledAt',
24
+ 'endedAt',
25
+ 'periodStart',
26
+ 'periodEnd',
27
+ 'nextAttemptAt'
28
+ ]);
29
+ /**
30
+ * The inbox of the webhook events and the outbox of the events of the payments. A webhook request is verified,
31
+ * stored once by the ID of its event and answered at once; a job of the `payments` queue then applies it to the
32
+ * records, in one transaction with the events telling of the change, which other jobs deliver to the handlers of
33
+ * `onPaymentEvent` and to the emails.
34
+ */
35
+ class PaymentEvents {
36
+ static [common_1.LIFECYCLE] = true;
37
+ /** @internal */
38
+ _store = new payment_store_1.PaymentStore();
39
+ /** @internal */
40
+ _sync = new payment_sync_1.PaymentSync(this._store);
41
+ /** @internal */
42
+ _registry = (0, gateway_registry_1.gatewayRegistry)();
43
+ /** @internal */
44
+ _queue = (0, core_1.inject)(common_1.Queue).get(PAYMENTS_QUEUE);
45
+ constructor() {
46
+ this._queue.addWorker((job) => this.processJob(job), {
47
+ concurrency: config_1.paymentsConfig.QUEUE_CONCURRENCY
48
+ });
49
+ this._queue.onFailed((job, error) => {
50
+ logger.error({ err: error, job: job?.data }, 'Processing of a payment job failed');
51
+ });
52
+ }
53
+ /** Receives the events of the built-in `fake` gateway, which calls no webhook. */
54
+ onInit() {
55
+ (0, fake_gateway_1.onFakePaymentEvent)(async (gateway, event) => {
56
+ const record = await this.receive(gateway, event, false);
57
+ if (record) {
58
+ await this.processWebhook(record.id);
59
+ }
60
+ });
61
+ }
62
+ /**
63
+ * Receives a webhook request of a gateway: verifies its signature, stores its event and queues its processing.
64
+ *
65
+ * @param {string} gateway - The name of the gateway, the end of the URL of the request.
66
+ * @param {Buffer} body - The body of the request as it was received.
67
+ * @param {WebhookHeaders} headers - The headers of the request.
68
+ * @return {Promise<PaymentWebhookEventRecord | null>} The stored event, `null` for one received before.
69
+ * @throws {PaymentError} `PAYMENT_GATEWAY_UNKNOWN` for a gateway that is not configured, `PAYMENT_WEBHOOK_INVALID`
70
+ * for a missing or wrong signature.
71
+ */
72
+ async receiveWebhook(gateway, body, headers) {
73
+ const driver = await this._registry.gateway(gateway);
74
+ let event;
75
+ try {
76
+ event = await driver.verifyWebhook(body, headers, config_1.paymentsWebhooksConfig.TOLERANCE);
77
+ }
78
+ catch (e) {
79
+ (0, telemetry_1.countWebhookEvent)(gateway, 'invalid');
80
+ throw e;
81
+ }
82
+ return this.receive(gateway, event);
83
+ }
84
+ /**
85
+ * Stores a verified event of a gateway once, by its ID, and queues its processing.
86
+ *
87
+ * @param {string} gateway - The name of the gateway.
88
+ * @param {GatewayEvent} event - The event.
89
+ * @param {boolean} [queue=true] - Queue the processing, `false` when the caller processes the event itself.
90
+ * @return {Promise<PaymentWebhookEventRecord | null>} The stored event, `null` for one received before.
91
+ */
92
+ async receive(gateway, event, queue = true) {
93
+ const ignored = event.data.kind === 'ignored' || !this.applies(event.data.kind);
94
+ let record;
95
+ try {
96
+ record = await this._store.webhookEvents.create({
97
+ provider: gateway,
98
+ providerEventId: event.id,
99
+ type: event.type,
100
+ kind: event.data.kind,
101
+ status: ignored ? 'ignored' : 'received',
102
+ livemode: event.livemode,
103
+ payload: ignored ? null : event.data,
104
+ occurredAt: event.occurredAt
105
+ });
106
+ }
107
+ catch (e) {
108
+ if (!(0, payment_store_1.isUniqueViolation)(e)) {
109
+ throw e;
110
+ }
111
+ // The gateway sends an event again until it is answered: the first delivery is the one processed
112
+ (0, telemetry_1.countWebhookEvent)(gateway, 'duplicate');
113
+ const existing = await this._store.webhookEvents.find({
114
+ provider: gateway,
115
+ providerEventId: event.id
116
+ });
117
+ if (existing?.status === 'received' && queue) {
118
+ await this.enqueue('webhook', existing.id);
119
+ }
120
+ return null;
121
+ }
122
+ (0, telemetry_1.countWebhookEvent)(gateway, ignored ? 'ignored' : 'received');
123
+ if (!ignored && queue) {
124
+ await this.enqueue('webhook', record.id);
125
+ }
126
+ return record;
127
+ }
128
+ /**
129
+ * Applies a stored webhook event to the records, once: the object of the event is read from its gateway again
130
+ * (`payments.webhooks.refetch`), so an event delivered late cannot move a record back, then applied in one
131
+ * transaction with the events of the change.
132
+ *
133
+ * @param {string} id - The ID of the stored event.
134
+ * @return {Promise<PaymentWebhookEventRecord | null>} The event, `null` for an unknown one.
135
+ * @throws The error of the processing, which is tried again up to `payments.webhooks.maxAttempts` times.
136
+ */
137
+ async processWebhook(id) {
138
+ const record = await this._store.webhookEvents.findById(id);
139
+ if (!record || record.status !== 'received' || !record.payload) {
140
+ return record;
141
+ }
142
+ const attempts = record.attempts + 1;
143
+ try {
144
+ const steps = await this.steps(record.provider, reviveDates(record.payload));
145
+ const events = await (0, data_1.runTransaction)(async () => {
146
+ const applied = [];
147
+ for (const step of steps) {
148
+ applied.push(...(await this.apply(record.provider, step)));
149
+ }
150
+ await this._store.webhookEvents.update(id, {
151
+ status: 'processed',
152
+ attempts,
153
+ lastError: null,
154
+ processedAt: new Date()
155
+ });
156
+ return applied;
157
+ });
158
+ (0, telemetry_1.countWebhookEvent)(record.provider, 'processed');
159
+ await this.dispatch(events);
160
+ return { ...record, status: 'processed', attempts };
161
+ }
162
+ catch (e) {
163
+ const failed = attempts >= config_1.paymentsWebhooksConfig.MAX_ATTEMPTS;
164
+ await this._store.webhookEvents.update(id, {
165
+ status: failed ? 'failed' : 'received',
166
+ attempts,
167
+ lastError: errorMessage(e)
168
+ });
169
+ if (failed) {
170
+ (0, telemetry_1.countWebhookEvent)(record.provider, 'failed');
171
+ logger.error({ err: e, gateway: record.provider, event: record.providerEventId }, 'Webhook event failed, replay it with the payments-replay task');
172
+ }
173
+ throw e;
174
+ }
175
+ }
176
+ /**
177
+ * Processes a stored webhook event again, i.e. a failed one once its cause is fixed.
178
+ *
179
+ * @param {string} id - The ID of the stored event.
180
+ * @return {Promise<PaymentWebhookEventRecord>} The processed event.
181
+ * @throws {PaymentError} `PAYMENT_NOT_FOUND` for an unknown event.
182
+ */
183
+ async replayWebhook(id) {
184
+ const moved = await this._store.webhookEvents.updateWhere({ id, payload: { not: null } }, { status: 'received', attempts: 0 });
185
+ const record = moved ? await this.processWebhook(id) : null;
186
+ if (!record) {
187
+ throw new common_1.PaymentError(common_1.ErrorCode.PaymentNotFound, `No webhook event '${id}' to replay`, { id });
188
+ }
189
+ return record;
190
+ }
191
+ /**
192
+ * Queues the delivery of events of the payments, once the transaction that wrote them is committed.
193
+ *
194
+ * @param {PaymentEventRecord[]} events - The stored events.
195
+ */
196
+ async dispatch(events) {
197
+ for (const event of events) {
198
+ try {
199
+ await this.enqueue('event', event.id);
200
+ }
201
+ catch (e) {
202
+ // The event is stored: the maintenance job queues it again
203
+ logger.warn({ err: e, event: event.id, type: event.type }, 'Payment event not queued, it is delivered by the next maintenance run');
204
+ }
205
+ }
206
+ }
207
+ /**
208
+ * Delivers a stored event to the handlers of `onPaymentEvent`, then sends its email.
209
+ *
210
+ * @param {string} id - The ID of the event.
211
+ * @return {Promise<boolean>} `true` when the event was delivered by this call.
212
+ * @throws The error of a handler, which has the event delivered again up to `payments.eventMaxAttempts` times.
213
+ */
214
+ async deliver(id) {
215
+ const record = await this._store.events.findById(id);
216
+ if (!record || record.status !== 'pending') {
217
+ return false;
218
+ }
219
+ const event = await this.load(record);
220
+ const attempts = record.attempts + 1;
221
+ try {
222
+ for (const handler of (0, payment_handlers_1.paymentEventHandlers)(record.type)) {
223
+ await handler(event);
224
+ }
225
+ }
226
+ catch (e) {
227
+ const failed = attempts >= config_1.paymentsConfig.EVENT_MAX_ATTEMPTS;
228
+ await this._store.events.update(id, {
229
+ status: failed ? 'failed' : 'pending',
230
+ attempts,
231
+ lastError: errorMessage(e)
232
+ });
233
+ (0, telemetry_1.countPaymentEvent)(record.type, failed ? 'failed' : 'retried');
234
+ throw e;
235
+ }
236
+ const moved = await this._store.events.updateWhere({ id, status: 'pending' }, {
237
+ status: 'delivered',
238
+ attempts,
239
+ lastError: null,
240
+ deliveredAt: new Date()
241
+ });
242
+ if (moved === 0) {
243
+ return false;
244
+ }
245
+ (0, telemetry_1.countPaymentEvent)(record.type, 'delivered');
246
+ // The handlers ran: a failing email is logged, never a reason to run them again
247
+ await (0, payment_emails_1.sendPaymentEmail)(event).catch((e) => logger.error({ err: e, event: id, type: record.type }, 'Sending the email of a payment event failed'));
248
+ return true;
249
+ }
250
+ /**
251
+ * Queues the stored work no job finished, i.e. after a crash or a queue that lost its jobs: the received webhook
252
+ * events and the pending events of the payments older than a minute.
253
+ *
254
+ * @param {Date} now - The current time.
255
+ * @param {number} limit - The most records of each kind to queue.
256
+ * @return {Promise<number>} The number of queued jobs.
257
+ */
258
+ async requeue(now, limit) {
259
+ const before = new Date(now.valueOf() - 60_000);
260
+ const options = { orderBy: { createdAt: 'asc' }, take: limit };
261
+ const webhooks = await this._store.webhookEvents.list({ status: 'received', createdAt: { lt: before } }, options);
262
+ const events = await this._store.events.list({ status: 'pending', createdAt: { lt: before } }, options);
263
+ for (const record of webhooks) {
264
+ await this.enqueue('webhook', record.id);
265
+ }
266
+ for (const record of events) {
267
+ await this.enqueue('event', record.id);
268
+ }
269
+ return webhooks.length + events.length;
270
+ }
271
+ /**
272
+ * Deletes the processed webhook events and the delivered events of the payments older than their retention. The
273
+ * failed ones are kept.
274
+ *
275
+ * @param {Date} now - The current time.
276
+ * @return {Promise<number>} The number of deleted records.
277
+ */
278
+ async prune(now) {
279
+ let deleted = 0;
280
+ if (config_1.paymentsWebhooksConfig.RETENTION > 0) {
281
+ deleted += await this._store.webhookEvents.deleteWhere({
282
+ status: { in: ['processed', 'ignored'] },
283
+ createdAt: {
284
+ lt: new Date(now.valueOf() - config_1.paymentsWebhooksConfig.RETENTION)
285
+ }
286
+ });
287
+ }
288
+ if (config_1.paymentsConfig.EVENT_RETENTION > 0) {
289
+ deleted += await this._store.events.deleteWhere({
290
+ status: 'delivered',
291
+ createdAt: {
292
+ lt: new Date(now.valueOf() - config_1.paymentsConfig.EVENT_RETENTION)
293
+ }
294
+ });
295
+ }
296
+ return deleted;
297
+ }
298
+ /**
299
+ * Loads the records an event is about.
300
+ *
301
+ * @param {PaymentEventRecord} record - The stored event.
302
+ * @return {Promise<PaymentEvent>} The event as the handlers receive it.
303
+ */
304
+ async load(record) {
305
+ const store = this._store;
306
+ const found = async (id, find) => id ? ((await find(id)) ?? undefined) : undefined;
307
+ const payment = await found(record.paymentId, (id) => store.payments.findById(id));
308
+ // The models of the subscriptions have no tables when they are off
309
+ const subscriptions = config_1.paymentsSubscriptionsConfig.ENABLED;
310
+ const subscription = await found(subscriptions
311
+ ? (record.subscriptionId ?? payment?.subscriptionId ?? null)
312
+ : null, (id) => store.subscriptions.findById(id));
313
+ const paymentMethod = await found(record.paymentMethodId ?? payment?.paymentMethodId ?? null, (id) => store.methods.findById(id));
314
+ const invoice = await found(subscriptions ? record.invoiceId : null, (id) => store.invoices.findById(id));
315
+ const customer = await found(payment?.customerId ??
316
+ subscription?.customerId ??
317
+ paymentMethod?.customerId ??
318
+ invoice?.customerId ??
319
+ null, (id) => store.customers.findById(id));
320
+ return {
321
+ id: record.id,
322
+ type: record.type,
323
+ gateway: record.provider,
324
+ userId: record.userId,
325
+ createdAt: record.createdAt,
326
+ customer,
327
+ payment,
328
+ transaction: await found(record.transactionId, (id) => store.transactions.findById(id)),
329
+ paymentMethod,
330
+ subscription,
331
+ invoice
332
+ };
333
+ }
334
+ /** @internal */
335
+ async processJob(job) {
336
+ if (job.data.kind === 'webhook') {
337
+ await this.processWebhook(job.data.id);
338
+ }
339
+ else {
340
+ await this.deliver(job.data.id);
341
+ }
342
+ }
343
+ /** @internal */
344
+ async enqueue(kind, id) {
345
+ const attempts = kind === 'webhook'
346
+ ? config_1.paymentsWebhooksConfig.MAX_ATTEMPTS
347
+ : config_1.paymentsConfig.EVENT_MAX_ATTEMPTS;
348
+ await this._queue.sendJob({ kind, id }, kind, {
349
+ attempts,
350
+ backoff: { type: 'exponential', delay: 2000 }
351
+ });
352
+ }
353
+ /**
354
+ * Reads the object of an event from its gateway, the state it has now, before any transaction: a completed
355
+ * checkout becomes the subscription and the payment it created.
356
+ *
357
+ * @internal
358
+ */
359
+ async steps(provider, data) {
360
+ if (!this.applies(data.kind)) {
361
+ return [];
362
+ }
363
+ const gateway = await this._registry.gateway(provider);
364
+ const refetch = config_1.paymentsWebhooksConfig.REFETCH;
365
+ switch (data.kind) {
366
+ case 'payment':
367
+ return [
368
+ {
369
+ data: refetch
370
+ ? { ...data, payment: await gateway.getPayment(data.payment.id) }
371
+ : data
372
+ }
373
+ ];
374
+ case 'subscription':
375
+ return [
376
+ {
377
+ data: refetch
378
+ ? {
379
+ ...data,
380
+ subscription: await gateway.getSubscription(data.subscription.id)
381
+ }
382
+ : data
383
+ }
384
+ ];
385
+ case 'invoice':
386
+ return [
387
+ {
388
+ data: refetch
389
+ ? { ...data, invoice: await gateway.getInvoice(data.invoice.id) }
390
+ : data
391
+ }
392
+ ];
393
+ case 'checkout': {
394
+ const checkout = refetch
395
+ ? await gateway.getCheckout(data.checkout.id)
396
+ : data.checkout;
397
+ if (checkout.status !== 'complete') {
398
+ return [{ data: { kind: 'checkout', checkout } }];
399
+ }
400
+ const steps = [];
401
+ if (checkout.subscriptionId && this.applies('subscription')) {
402
+ steps.push({
403
+ data: {
404
+ kind: 'subscription',
405
+ subscription: await gateway.getSubscription(checkout.subscriptionId)
406
+ },
407
+ recordId: checkout.metadata?.[payment_sync_1.SUBSCRIPTION_METADATA_KEY]
408
+ });
409
+ }
410
+ if (checkout.paymentId) {
411
+ const local = await this._store.payments.find({
412
+ provider,
413
+ providerCheckoutId: checkout.id
414
+ });
415
+ steps.push({
416
+ data: {
417
+ kind: 'payment',
418
+ payment: await gateway.getPayment(checkout.paymentId)
419
+ },
420
+ recordId: local?.id ?? checkout.metadata?.[payment_sync_1.PAYMENT_METADATA_KEY]
421
+ });
422
+ }
423
+ return steps;
424
+ }
425
+ default:
426
+ return [{ data }];
427
+ }
428
+ }
429
+ /** Tells whether the objects of a kind are applied: the ones of the subscriptions only when they are on. @internal */
430
+ applies(kind) {
431
+ return (config_1.paymentsSubscriptionsConfig.ENABLED ||
432
+ (kind !== 'subscription' && kind !== 'invoice'));
433
+ }
434
+ /** @internal */
435
+ async apply(provider, { data, recordId }) {
436
+ switch (data.kind) {
437
+ case 'checkout':
438
+ return data.checkout.status === 'expired'
439
+ ? this._sync.expireCheckout(provider, data.checkout)
440
+ : [];
441
+ case 'payment':
442
+ return (await this._sync.applyPayment(provider, data.payment, recordId))
443
+ .events;
444
+ case 'subscription':
445
+ return (await this._sync.applySubscription(provider, data.subscription, {
446
+ recordId,
447
+ trialWillEnd: data.trialWillEnd
448
+ })).events;
449
+ default:
450
+ return this._sync.apply(provider, data);
451
+ }
452
+ }
453
+ }
454
+ exports.PaymentEvents = PaymentEvents;
455
+ /** Reads the dates of a stored object of a gateway back from their JSON strings. */
456
+ function reviveDates(value) {
457
+ if (Array.isArray(value)) {
458
+ return value.map(reviveDates);
459
+ }
460
+ if (value && typeof value === 'object' && !(value instanceof Date)) {
461
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
462
+ key,
463
+ DATE_KEYS.has(key) && typeof entry === 'string'
464
+ ? new Date(entry)
465
+ : reviveDates(entry)
466
+ ]));
467
+ }
468
+ return value;
469
+ }
470
+ function errorMessage(error) {
471
+ return (error instanceof Error ? error.message : String(error)).slice(0, 1000);
472
+ }
@@ -0,0 +1,26 @@
1
+ import { PaymentEvent, PaymentEventType } from '../types';
2
+ /** A handler of the events of the payments. A thrown error has the event delivered again. */
3
+ export type PaymentEventHandler = (event: PaymentEvent) => unknown;
4
+ /**
5
+ * Listens to the events of the payments: a paid, failed or refunded payment, a started, changed or canceled
6
+ * subscription, a paid invoice. An event is stored with the change it tells of and delivered at least once, with the
7
+ * same `id` on every delivery, so a handler doing something once checks it. A handler that throws has the event
8
+ * delivered again, to every handler, up to `payments.eventMaxAttempts` times.
9
+ *
10
+ * @example
11
+ * onPaymentEvent('payment.succeeded', async ({ payment }) => {
12
+ * await orders.markPaid(payment!.reference!);
13
+ * });
14
+ *
15
+ * @param {PaymentEventType | PaymentEventType[] | '*'} type - The types of the events, `'*'` for all of them.
16
+ * @param {PaymentEventHandler} handler - The handler.
17
+ * @return {Function} Removes the handler.
18
+ */
19
+ export declare function onPaymentEvent(type: PaymentEventType | PaymentEventType[] | '*', handler: PaymentEventHandler): () => void;
20
+ /**
21
+ * Returns the handlers of a type of event, the ones of every type last.
22
+ *
23
+ * @param {PaymentEventType} type - The type of the event.
24
+ * @return {PaymentEventHandler[]} The handlers.
25
+ */
26
+ export declare function paymentEventHandlers(type: PaymentEventType): PaymentEventHandler[];
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.onPaymentEvent = onPaymentEvent;
4
+ exports.paymentEventHandlers = paymentEventHandlers;
5
+ const PAYMENT_HANDLERS = Symbol.for('appweaver.PaymentEventHandlers');
6
+ const globals = globalThis;
7
+ const handlers = (globals[PAYMENT_HANDLERS] ??= new Map());
8
+ /**
9
+ * Listens to the events of the payments: a paid, failed or refunded payment, a started, changed or canceled
10
+ * subscription, a paid invoice. An event is stored with the change it tells of and delivered at least once, with the
11
+ * same `id` on every delivery, so a handler doing something once checks it. A handler that throws has the event
12
+ * delivered again, to every handler, up to `payments.eventMaxAttempts` times.
13
+ *
14
+ * @example
15
+ * onPaymentEvent('payment.succeeded', async ({ payment }) => {
16
+ * await orders.markPaid(payment!.reference!);
17
+ * });
18
+ *
19
+ * @param {PaymentEventType | PaymentEventType[] | '*'} type - The types of the events, `'*'` for all of them.
20
+ * @param {PaymentEventHandler} handler - The handler.
21
+ * @return {Function} Removes the handler.
22
+ */
23
+ function onPaymentEvent(type, handler) {
24
+ const types = [type].flat();
25
+ for (const name of types) {
26
+ let set = handlers.get(name);
27
+ if (!set) {
28
+ handlers.set(name, (set = new Set()));
29
+ }
30
+ set.add(handler);
31
+ }
32
+ return () => types.forEach((name) => handlers.get(name)?.delete(handler));
33
+ }
34
+ /**
35
+ * Returns the handlers of a type of event, the ones of every type last.
36
+ *
37
+ * @param {PaymentEventType} type - The type of the event.
38
+ * @return {PaymentEventHandler[]} The handlers.
39
+ */
40
+ function paymentEventHandlers(type) {
41
+ return [...(handlers.get(type) ?? []), ...(handlers.get('*') ?? [])];
42
+ }
@@ -0,0 +1,50 @@
1
+ import { PaymentCustomerRecord, PaymentEventRecord, PaymentInvoiceRecord, PaymentMethodRecord, PaymentPlanRecord, PaymentRecord, PaymentSubscriptionRecord, PaymentTransactionRecord, PaymentWebhookEventRecord } from '../types';
2
+ /** The condition of a query of the database client. */
3
+ export type Where = Record<string, unknown>;
4
+ type ListOptions = {
5
+ orderBy?: Record<string, 'asc' | 'desc'>;
6
+ take?: number;
7
+ };
8
+ /**
9
+ * The records of a payment model, read and written with the database client of its service, so inside the current
10
+ * transaction. The amounts, `BigInt` columns, are read as numbers.
11
+ */
12
+ export declare class PaymentTable<T extends {
13
+ id: string;
14
+ }> {
15
+ private readonly _model;
16
+ constructor(_model: string);
17
+ create(data: Partial<T>): Promise<T>;
18
+ findById(id: string): Promise<T | null>;
19
+ find(where: Where, orderBy?: Record<string, 'asc' | 'desc'>): Promise<T | null>;
20
+ list(where: Where, options?: ListOptions): Promise<T[]>;
21
+ update(id: string, data: Partial<T>): Promise<T>;
22
+ /**
23
+ * Updates the records matching a condition, the compare-and-set of a state.
24
+ *
25
+ * @return {Promise<number>} The number of updated records, `0` when another call changed them first.
26
+ */
27
+ updateWhere(where: Where, data: Partial<T>): Promise<number>;
28
+ deleteWhere(where: Where): Promise<number>;
29
+ count(where: Where): Promise<number>;
30
+ }
31
+ /** The tables of the payment models. */
32
+ export declare class PaymentStore {
33
+ readonly customers: PaymentTable<PaymentCustomerRecord>;
34
+ readonly methods: PaymentTable<PaymentMethodRecord>;
35
+ readonly payments: PaymentTable<PaymentRecord>;
36
+ readonly transactions: PaymentTable<PaymentTransactionRecord>;
37
+ readonly plans: PaymentTable<PaymentPlanRecord>;
38
+ readonly subscriptions: PaymentTable<PaymentSubscriptionRecord>;
39
+ readonly invoices: PaymentTable<PaymentInvoiceRecord>;
40
+ readonly events: PaymentTable<PaymentEventRecord>;
41
+ readonly webhookEvents: PaymentTable<PaymentWebhookEventRecord>;
42
+ }
43
+ /**
44
+ * Tells whether an error is a violated unique constraint, i.e. of a record another call created first.
45
+ *
46
+ * @param {unknown} error - The error of a write.
47
+ * @return {boolean} `true` for a unique violation.
48
+ */
49
+ export declare function isUniqueViolation(error: unknown): boolean;
50
+ export {};
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PaymentStore = exports.PaymentTable = void 0;
4
+ exports.isUniqueViolation = isUniqueViolation;
5
+ const common_1 = require("@appweaver/common");
6
+ const core_1 = require("@appweaver/core");
7
+ const data_1 = require("@appweaver/data");
8
+ /**
9
+ * The records of a payment model, read and written with the database client of its service, so inside the current
10
+ * transaction. The amounts, `BigInt` columns, are read as numbers.
11
+ */
12
+ class PaymentTable {
13
+ _model;
14
+ constructor(_model) {
15
+ this._model = _model;
16
+ }
17
+ create(data) {
18
+ return this.run((client) => client.create({ data }));
19
+ }
20
+ findById(id) {
21
+ return this.find({ id });
22
+ }
23
+ find(where, orderBy) {
24
+ return this.run((client) => client.findFirst({ where, orderBy }));
25
+ }
26
+ list(where, options = {}) {
27
+ return this.run((client) => client.findMany({ where, ...options }));
28
+ }
29
+ update(id, data) {
30
+ return this.run((client) => client.update({ where: { id }, data }));
31
+ }
32
+ /**
33
+ * Updates the records matching a condition, the compare-and-set of a state.
34
+ *
35
+ * @return {Promise<number>} The number of updated records, `0` when another call changed them first.
36
+ */
37
+ async updateWhere(where, data) {
38
+ const { count } = await this.run((client) => client.updateMany({ where, data }));
39
+ return count;
40
+ }
41
+ async deleteWhere(where) {
42
+ const { count } = await this.run((client) => client.deleteMany({ where }));
43
+ return count;
44
+ }
45
+ count(where) {
46
+ return this.run((client) => client.count({ where }));
47
+ }
48
+ /** @internal */
49
+ async run(query) {
50
+ try {
51
+ return toNumbers(await query((0, core_1.injectService)(this._model).client));
52
+ }
53
+ catch (e) {
54
+ throw (0, data_1.toDatabaseError)(e, this._model);
55
+ }
56
+ }
57
+ }
58
+ exports.PaymentTable = PaymentTable;
59
+ /** The tables of the payment models. */
60
+ class PaymentStore {
61
+ customers = new PaymentTable('PaymentCustomer');
62
+ methods = new PaymentTable('PaymentMethod');
63
+ payments = new PaymentTable('Payment');
64
+ transactions = new PaymentTable('PaymentTransaction');
65
+ plans = new PaymentTable('PaymentPlan');
66
+ subscriptions = new PaymentTable('PaymentSubscription');
67
+ invoices = new PaymentTable('PaymentInvoice');
68
+ events = new PaymentTable('PaymentEvent');
69
+ webhookEvents = new PaymentTable('PaymentWebhookEvent');
70
+ }
71
+ exports.PaymentStore = PaymentStore;
72
+ /**
73
+ * Tells whether an error is a violated unique constraint, i.e. of a record another call created first.
74
+ *
75
+ * @param {unknown} error - The error of a write.
76
+ * @return {boolean} `true` for a unique violation.
77
+ */
78
+ function isUniqueViolation(error) {
79
+ return (0, common_1.isAppweaverError)(error) && error.is(common_1.ErrorCode.DatabaseUniqueViolation);
80
+ }
81
+ /** Reads the `BigInt` columns of a record, or of a list of them, as numbers. */
82
+ function toNumbers(value) {
83
+ if (Array.isArray(value)) {
84
+ return value.map(toNumbers);
85
+ }
86
+ if (value && typeof value === 'object' && !(value instanceof Date)) {
87
+ const record = value;
88
+ for (const [key, entry] of Object.entries(record)) {
89
+ if (typeof entry === 'bigint') {
90
+ record[key] = Number(entry);
91
+ }
92
+ }
93
+ }
94
+ return value;
95
+ }