@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,745 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PaymentSync = exports.SUBSCRIPTION_METADATA_KEY = exports.PAYMENT_METADATA_KEY = void 0;
4
+ const common_1 = require("@appweaver/common");
5
+ const data_1 = require("@appweaver/data");
6
+ const config_1 = require("../config");
7
+ const status_util_1 = require("../utils/status-util");
8
+ const payment_store_1 = require("./payment-store");
9
+ const logger = (0, common_1.createLogger)('payments');
10
+ /** The key of the metadata of a gateway payment naming its payment record. */
11
+ exports.PAYMENT_METADATA_KEY = 'appweaverPaymentId';
12
+ /** The key of the metadata of a gateway subscription naming its subscription record. */
13
+ exports.SUBSCRIPTION_METADATA_KEY = 'appweaverSubscriptionId';
14
+ const PAYMENT_EVENTS = {
15
+ succeeded: 'payment.succeeded',
16
+ failed: 'payment.failed',
17
+ requiresAction: 'payment.requiresAction',
18
+ authorized: 'payment.authorized',
19
+ canceled: 'payment.canceled'
20
+ };
21
+ /** The states of a subscription that is running, the ones it is announced as created in. */
22
+ const STARTED = ['trialing', 'active'];
23
+ /**
24
+ * Applies the objects of the gateways to the records, the only place moving their state: the answer of a call to a
25
+ * gateway, a webhook event and the reconciliation all go through it. An object is applied in a transaction with the
26
+ * events telling of the change, and applying it again changes nothing, so the events delivered twice or out of order
27
+ * are harmless. A state moves with a compare-and-set, so of two calls applying the same change only one records it.
28
+ */
29
+ class PaymentSync {
30
+ _store;
31
+ constructor(_store) {
32
+ this._store = _store;
33
+ }
34
+ /**
35
+ * Applies the object of a webhook event.
36
+ *
37
+ * @param {string} provider - The name of the gateway.
38
+ * @param {GatewayEventData} data - The object of the event.
39
+ * @return {Promise<PaymentEventRecord[]>} The events to deliver.
40
+ */
41
+ async apply(provider, data) {
42
+ switch (data.kind) {
43
+ case 'payment':
44
+ return (await this.applyPayment(provider, data.payment)).events;
45
+ case 'refund':
46
+ return (await this.applyRefund(provider, data.refund)).events;
47
+ case 'dispute':
48
+ return (await this.applyDispute(provider, data.dispute)).events;
49
+ case 'paymentMethod':
50
+ return (await this.applyPaymentMethod(provider, data.paymentMethod, data.detached)).events;
51
+ case 'subscription':
52
+ return (await this.applySubscription(provider, data.subscription, {
53
+ trialWillEnd: data.trialWillEnd
54
+ })).events;
55
+ case 'invoice':
56
+ return (await this.applyInvoice(provider, data.invoice)).events;
57
+ case 'customer':
58
+ await this._store.customers.updateWhere({ provider, providerCustomerId: data.customerId }, { deletedAtProvider: new Date() });
59
+ return [];
60
+ default:
61
+ return [];
62
+ }
63
+ }
64
+ /**
65
+ * Applies a payment of a gateway to its record: the one with its ID, the one its metadata or the given ID names,
66
+ * or a new one when the payment belongs to a known customer, i.e. the renewal of a subscription.
67
+ *
68
+ * @param {string} provider - The name of the gateway.
69
+ * @param {GatewayPayment} payment - The payment of the gateway.
70
+ * @param {string} [recordId] - The ID of the record of the payment, when the caller knows it.
71
+ * @return {Promise<Applied<PaymentRecord>>} The record, `null` for a payment of no known customer, and the events.
72
+ */
73
+ applyPayment(provider, payment, recordId) {
74
+ return (0, data_1.runTransaction)(async () => {
75
+ const events = [];
76
+ const local = await this.findPayment(provider, payment, recordId);
77
+ if (!local) {
78
+ return { record: null, events };
79
+ }
80
+ const paymentMethodId = (await this.localMethodId(provider, payment, local)) ??
81
+ local.paymentMethodId;
82
+ const patch = {
83
+ providerPaymentId: payment.id,
84
+ amountCaptured: payment.amountCaptured,
85
+ amountRefunded: Math.max(payment.amountRefunded, local.amountRefunded),
86
+ livemode: payment.livemode,
87
+ paymentMethodId,
88
+ ...(await this.subscriptionRef(provider, payment, local)),
89
+ failureCode: payment.failureCode ?? null,
90
+ failureMessage: payment.failureMessage ?? null,
91
+ receiptUrl: payment.receiptUrl ?? local.receiptUrl
92
+ };
93
+ if (payment.invoiceId && config_1.paymentsSubscriptionsConfig.ENABLED) {
94
+ await this._store.invoices.updateWhere({ provider, providerInvoiceId: payment.invoiceId, paymentId: null }, { paymentId: local.id });
95
+ }
96
+ const previous = local.status;
97
+ const moves = payment.status !== previous && (0, status_util_1.canTransition)(previous, payment.status);
98
+ if (moves) {
99
+ const now = new Date();
100
+ const moved = await this._store.payments.updateWhere({ id: local.id, status: previous }, {
101
+ ...patch,
102
+ status: payment.status,
103
+ ...(payment.status === 'succeeded' ? { paidAt: now } : {}),
104
+ ...(payment.status === 'canceled' ? { canceledAt: now } : {})
105
+ });
106
+ if (moved === 0) {
107
+ // Another call applied the change first, and recorded its events
108
+ return {
109
+ record: await this._store.payments.findById(local.id),
110
+ events
111
+ };
112
+ }
113
+ }
114
+ else if (differs(local, patch)) {
115
+ await this._store.payments.update(local.id, patch);
116
+ }
117
+ const record = (await this._store.payments.findById(local.id));
118
+ if (moves) {
119
+ await this.recordCharge(record, payment, previous);
120
+ const type = PAYMENT_EVENTS[record.status];
121
+ if (type) {
122
+ events.push(await this.event(type, record.provider, {
123
+ userId: record.userId,
124
+ paymentId: record.id,
125
+ subscriptionId: record.subscriptionId
126
+ }));
127
+ }
128
+ }
129
+ else if (payment.fee !== undefined && payment.chargeId) {
130
+ await this._store.transactions.updateWhere({ provider, providerTransactionId: payment.chargeId, fee: null }, { fee: payment.fee });
131
+ }
132
+ return { record, events };
133
+ });
134
+ }
135
+ /**
136
+ * Applies a refund of a gateway to the ledger of its payment and to the refunded amount of the payment.
137
+ *
138
+ * @param {string} provider - The name of the gateway.
139
+ * @param {GatewayRefund} refund - The refund of the gateway.
140
+ * @return {Promise<Applied<PaymentTransactionRecord>>} The ledger entry, `null` for an unknown payment, and the
141
+ * events.
142
+ */
143
+ applyRefund(provider, refund) {
144
+ return (0, data_1.runTransaction)(async () => {
145
+ const events = [];
146
+ const payment = await this._store.payments.find({
147
+ provider,
148
+ providerPaymentId: refund.paymentId
149
+ });
150
+ if (!payment) {
151
+ return { record: null, events };
152
+ }
153
+ const { record, changed } = await this.recordTransaction(payment, {
154
+ type: 'refund',
155
+ providerTransactionId: refund.id,
156
+ status: refund.status,
157
+ amount: refund.amount,
158
+ currency: refund.currency,
159
+ reason: refund.reason ?? null,
160
+ failureReason: refund.failureReason ?? null
161
+ });
162
+ if (changed) {
163
+ const refunds = await this._store.transactions.list({
164
+ paymentId: payment.id,
165
+ type: 'refund',
166
+ status: 'succeeded'
167
+ });
168
+ await this._store.payments.update(payment.id, {
169
+ amountRefunded: refunds.reduce((sum, entry) => sum + entry.amount, 0)
170
+ });
171
+ const type = record.status === 'succeeded'
172
+ ? 'refund.succeeded'
173
+ : record.status === 'failed'
174
+ ? 'refund.failed'
175
+ : undefined;
176
+ if (type) {
177
+ events.push(await this.event(type, provider, {
178
+ userId: payment.userId,
179
+ paymentId: payment.id,
180
+ transactionId: record.id
181
+ }));
182
+ }
183
+ }
184
+ return { record, events };
185
+ });
186
+ }
187
+ /**
188
+ * Applies a dispute of a gateway to the ledger of its payment, and marks the payment as disputed while it is open
189
+ * or lost.
190
+ *
191
+ * @param {string} provider - The name of the gateway.
192
+ * @param {GatewayDispute} dispute - The dispute of the gateway.
193
+ * @return {Promise<Applied<PaymentTransactionRecord>>} The ledger entry, `null` for an unknown payment, and the
194
+ * events.
195
+ */
196
+ applyDispute(provider, dispute) {
197
+ return (0, data_1.runTransaction)(async () => {
198
+ const events = [];
199
+ const payment = await this._store.payments.find({
200
+ provider,
201
+ providerPaymentId: dispute.paymentId
202
+ });
203
+ if (!payment) {
204
+ return { record: null, events };
205
+ }
206
+ const { record, changed, created } = await this.recordTransaction(payment, {
207
+ type: 'dispute',
208
+ providerTransactionId: dispute.id,
209
+ status: dispute.status,
210
+ amount: dispute.amount,
211
+ currency: dispute.currency,
212
+ reason: dispute.reason ?? null
213
+ });
214
+ if (changed) {
215
+ await this._store.payments.update(payment.id, {
216
+ disputed: record.status !== 'won'
217
+ });
218
+ const closed = record.status === 'won' || record.status === 'lost';
219
+ const refs = {
220
+ userId: payment.userId,
221
+ paymentId: payment.id,
222
+ transactionId: record.id
223
+ };
224
+ if (created) {
225
+ events.push(await this.event('dispute.opened', provider, refs));
226
+ }
227
+ if (closed) {
228
+ events.push(await this.event('dispute.closed', provider, refs));
229
+ }
230
+ }
231
+ return { record, events };
232
+ });
233
+ }
234
+ /**
235
+ * Applies a payment method of a gateway: saves it to the customer it is attached to, the first one as their
236
+ * default, or removes a detached one.
237
+ *
238
+ * @param {string} provider - The name of the gateway.
239
+ * @param {GatewayPaymentMethod} method - The payment method of the gateway.
240
+ * @param {boolean} [detached=false] - Whether the method was removed from its customer.
241
+ * @return {Promise<Applied<PaymentMethodRecord>>} The record, `null` for a method of no known customer, and the
242
+ * events.
243
+ */
244
+ applyPaymentMethod(provider, method, detached = false) {
245
+ return (0, data_1.runTransaction)(async () => {
246
+ const events = [];
247
+ const where = { provider, providerPaymentMethodId: method.id };
248
+ const local = await this._store.methods.find(where);
249
+ if (detached) {
250
+ if (!local) {
251
+ return { record: null, events };
252
+ }
253
+ await this._store.methods.deleteWhere({ id: local.id });
254
+ await this._store.customers.updateWhere({ id: local.customerId, defaultPaymentMethodId: local.id }, { defaultPaymentMethodId: null });
255
+ events.push(await this.event('paymentMethod.detached', provider, {
256
+ userId: local.userId,
257
+ paymentMethodId: local.id
258
+ }));
259
+ return { record: local, events };
260
+ }
261
+ const customer = method.customerId
262
+ ? await this._store.customers.find({
263
+ provider,
264
+ providerCustomerId: method.customerId
265
+ })
266
+ : null;
267
+ if (!customer) {
268
+ return { record: local, events };
269
+ }
270
+ const details = {
271
+ type: method.type,
272
+ brand: method.brand ?? null,
273
+ last4: method.last4 ?? null,
274
+ expMonth: method.expMonth ?? null,
275
+ expYear: method.expYear ?? null,
276
+ fingerprint: method.fingerprint ?? null,
277
+ country: method.country ?? null
278
+ };
279
+ if (local) {
280
+ if (differs(local, details)) {
281
+ await this._store.methods.update(local.id, details);
282
+ }
283
+ return { record: { ...local, ...details }, events };
284
+ }
285
+ let record;
286
+ try {
287
+ record = await this._store.methods.create({
288
+ ...where,
289
+ ...details,
290
+ customerId: customer.id,
291
+ userId: customer.userId,
292
+ isDefault: !customer.defaultPaymentMethodId
293
+ });
294
+ }
295
+ catch (e) {
296
+ if (!(0, payment_store_1.isUniqueViolation)(e)) {
297
+ throw e;
298
+ }
299
+ return { record: await this._store.methods.find(where), events };
300
+ }
301
+ if (record.isDefault) {
302
+ await this._store.customers.update(customer.id, {
303
+ defaultPaymentMethodId: record.id
304
+ });
305
+ }
306
+ events.push(await this.event('paymentMethod.attached', provider, {
307
+ userId: record.userId,
308
+ paymentMethodId: record.id
309
+ }));
310
+ return { record, events };
311
+ });
312
+ }
313
+ /**
314
+ * Applies a subscription of a gateway to its record: the one with its ID, the one its metadata or the given ID
315
+ * names, or a new one for a known customer. A canceled subscription never changes again.
316
+ *
317
+ * @param {string} provider - The name of the gateway.
318
+ * @param {GatewaySubscription} subscription - The subscription of the gateway.
319
+ * @param {Object} [options] - The ID of the record when the caller knows it, and whether the gateway announces
320
+ * the end of the trial.
321
+ * @return {Promise<Applied<PaymentSubscriptionRecord>>} The record, `null` for a subscription of no known
322
+ * customer, and the events.
323
+ */
324
+ applySubscription(provider, subscription, options = {}) {
325
+ return (0, data_1.runTransaction)(async () => {
326
+ const events = [];
327
+ const found = await this.findSubscription(provider, subscription, options.recordId);
328
+ if (!found) {
329
+ return { record: null, events };
330
+ }
331
+ const { local, created } = found;
332
+ if (local.status === 'canceled' && !created) {
333
+ return { record: local, events };
334
+ }
335
+ const plan = await this._store.plans.find({
336
+ provider,
337
+ providerPriceId: subscription.priceId
338
+ });
339
+ const pastDue = subscription.status === 'pastDue';
340
+ const patch = {
341
+ providerSubscriptionId: subscription.id,
342
+ status: subscription.status,
343
+ providerPriceId: subscription.priceId,
344
+ planId: plan?.id ?? null,
345
+ planKey: plan?.key ?? local.planKey,
346
+ quantity: subscription.quantity,
347
+ cancelAtPeriodEnd: subscription.cancelAtPeriodEnd,
348
+ livemode: subscription.livemode,
349
+ currentPeriodStart: subscription.currentPeriodStart ?? null,
350
+ currentPeriodEnd: subscription.currentPeriodEnd ?? null,
351
+ trialEnd: subscription.trialEnd ?? null,
352
+ canceledAt: subscription.canceledAt ?? null,
353
+ endedAt: subscription.endedAt ?? null,
354
+ pastDueAt: pastDue ? (local.pastDueAt ?? new Date()) : null
355
+ };
356
+ const previous = local.status;
357
+ const changed = differs(local, patch);
358
+ if (changed) {
359
+ const moved = await this._store.subscriptions.updateWhere({ id: local.id, status: previous }, patch);
360
+ if (moved === 0) {
361
+ return {
362
+ record: await this._store.subscriptions.findById(local.id),
363
+ events
364
+ };
365
+ }
366
+ }
367
+ const record = { ...local, ...patch };
368
+ const refs = { userId: record.userId, subscriptionId: record.id };
369
+ const started = STARTED.includes(record.status) &&
370
+ (created || previous === 'incomplete');
371
+ if (started) {
372
+ events.push(await this.event('subscription.created', provider, refs));
373
+ }
374
+ else if (record.status !== previous && record.status === 'canceled') {
375
+ events.push(await this.event('subscription.canceled', provider, refs));
376
+ }
377
+ else if (record.status !== previous && pastDue) {
378
+ events.push(await this.event('subscription.pastDue', provider, refs));
379
+ }
380
+ else if (changed && !created) {
381
+ events.push(await this.event('subscription.updated', provider, refs));
382
+ }
383
+ if (options.trialWillEnd) {
384
+ events.push(await this.event('subscription.trialWillEnd', provider, refs));
385
+ }
386
+ return { record, events };
387
+ });
388
+ }
389
+ /**
390
+ * Applies an invoice of a gateway to its record, linked to its subscription and to the payment collecting it.
391
+ *
392
+ * @param {string} provider - The name of the gateway.
393
+ * @param {GatewayInvoice} invoice - The invoice of the gateway.
394
+ * @return {Promise<Applied<PaymentInvoiceRecord>>} The record, `null` for an invoice of no known customer, and
395
+ * the events.
396
+ */
397
+ applyInvoice(provider, invoice) {
398
+ return (0, data_1.runTransaction)(async () => {
399
+ const events = [];
400
+ const where = { provider, providerInvoiceId: invoice.id };
401
+ const customer = await this._store.customers.find({
402
+ provider,
403
+ providerCustomerId: invoice.customerId
404
+ });
405
+ if (!customer) {
406
+ return { record: null, events };
407
+ }
408
+ const subscription = invoice.subscriptionId
409
+ ? await this._store.subscriptions.find({
410
+ provider,
411
+ providerSubscriptionId: invoice.subscriptionId
412
+ })
413
+ : null;
414
+ const payment = invoice.paymentId
415
+ ? await this._store.payments.find({
416
+ provider,
417
+ providerPaymentId: invoice.paymentId
418
+ })
419
+ : null;
420
+ if (payment && subscription && !payment.subscriptionId) {
421
+ await this._store.payments.update(payment.id, {
422
+ subscriptionId: subscription.id
423
+ });
424
+ }
425
+ let local = await this._store.invoices.find(where);
426
+ const paid = invoice.status === 'paid';
427
+ const patch = {
428
+ status: invoice.status,
429
+ subscriptionId: subscription?.id ?? local?.subscriptionId ?? null,
430
+ paymentId: payment?.id ?? local?.paymentId ?? null,
431
+ number: invoice.number ?? null,
432
+ amountDue: invoice.amountDue,
433
+ amountPaid: invoice.amountPaid,
434
+ currency: invoice.currency,
435
+ attemptCount: invoice.attemptCount,
436
+ periodStart: invoice.periodStart ?? null,
437
+ periodEnd: invoice.periodEnd ?? null,
438
+ nextAttemptAt: invoice.nextAttemptAt ?? null,
439
+ hostedUrl: invoice.hostedUrl ?? null,
440
+ pdfUrl: invoice.pdfUrl ?? null
441
+ };
442
+ const before = local;
443
+ if (!local) {
444
+ try {
445
+ local = await this._store.invoices.create({
446
+ ...where,
447
+ ...patch,
448
+ customerId: customer.id,
449
+ userId: customer.userId,
450
+ paidAt: paid ? new Date() : null
451
+ });
452
+ }
453
+ catch (e) {
454
+ if (!(0, payment_store_1.isUniqueViolation)(e)) {
455
+ throw e;
456
+ }
457
+ return { record: await this._store.invoices.find(where), events };
458
+ }
459
+ }
460
+ else if (differs(local, patch)) {
461
+ const moved = await this._store.invoices.updateWhere({ id: local.id, status: local.status }, { ...patch, ...(paid && !local.paidAt ? { paidAt: new Date() } : {}) });
462
+ if (moved === 0) {
463
+ return { record: await this._store.invoices.find(where), events };
464
+ }
465
+ local = { ...local, ...patch };
466
+ }
467
+ const refs = {
468
+ userId: local.userId,
469
+ invoiceId: local.id,
470
+ subscriptionId: local.subscriptionId,
471
+ paymentId: local.paymentId
472
+ };
473
+ if (paid && before?.status !== 'paid') {
474
+ events.push(await this.event('invoice.paid', provider, refs));
475
+ }
476
+ else if (invoice.status === 'open' &&
477
+ invoice.attemptCount > (before?.attemptCount ?? 0)) {
478
+ events.push(await this.event('invoice.paymentFailed', provider, refs));
479
+ }
480
+ return { record: local, events };
481
+ });
482
+ }
483
+ /**
484
+ * Applies a hosted checkout that expired unpaid: cancels the payment or the subscription waiting for it.
485
+ *
486
+ * @param {string} provider - The name of the gateway.
487
+ * @param {GatewayCheckout} checkout - The expired checkout of the gateway.
488
+ * @return {Promise<PaymentEventRecord[]>} The events to deliver.
489
+ */
490
+ expireCheckout(provider, checkout) {
491
+ return (0, data_1.runTransaction)(async () => {
492
+ const events = [];
493
+ const payment = await this._store.payments.find({
494
+ provider,
495
+ providerCheckoutId: checkout.id
496
+ });
497
+ if (payment && !payment.providerPaymentId) {
498
+ const moved = await this._store.payments.updateWhere({ id: payment.id, status: 'pending' }, { status: 'canceled', canceledAt: new Date() });
499
+ if (moved) {
500
+ events.push(await this.event('payment.canceled', provider, {
501
+ userId: payment.userId,
502
+ paymentId: payment.id
503
+ }));
504
+ }
505
+ }
506
+ const subscriptionId = checkout.metadata?.[exports.SUBSCRIPTION_METADATA_KEY];
507
+ if (subscriptionId && config_1.paymentsSubscriptionsConfig.ENABLED) {
508
+ await this._store.subscriptions.updateWhere({
509
+ id: subscriptionId,
510
+ provider,
511
+ status: 'incomplete',
512
+ providerSubscriptionId: null
513
+ }, { status: 'canceled', canceledAt: new Date(), endedAt: new Date() });
514
+ }
515
+ return events;
516
+ });
517
+ }
518
+ /**
519
+ * Records an event of the payments, delivered to the handlers once the transaction writing it commits.
520
+ *
521
+ * @param {PaymentEventType} type - The type of the event.
522
+ * @param {string} provider - The name of the gateway of its records.
523
+ * @param {EventRefs} refs - The records the event is about.
524
+ * @return {Promise<PaymentEventRecord>} The stored event.
525
+ */
526
+ event(type, provider, refs) {
527
+ return this._store.events.create({ type, provider, ...refs });
528
+ }
529
+ /** @internal */
530
+ async findPayment(provider, payment, recordId) {
531
+ const local = await this._store.payments.find({
532
+ provider,
533
+ providerPaymentId: payment.id
534
+ });
535
+ if (local) {
536
+ return local;
537
+ }
538
+ // The answer of the gateway may come after its webhook: the record is then found by the ID in the metadata
539
+ const id = recordId ?? payment.metadata[exports.PAYMENT_METADATA_KEY];
540
+ const named = id ? await this._store.payments.findById(id) : null;
541
+ if (named?.provider === provider && !named.providerPaymentId) {
542
+ return named;
543
+ }
544
+ const customer = payment.customerId
545
+ ? await this._store.customers.find({
546
+ provider,
547
+ providerCustomerId: payment.customerId
548
+ })
549
+ : null;
550
+ if (!customer) {
551
+ logger.debug({ gateway: provider, payment: payment.id }, 'Payment of no known customer ignored');
552
+ return null;
553
+ }
554
+ try {
555
+ return await this._store.payments.create({
556
+ provider,
557
+ providerPaymentId: payment.id,
558
+ status: 'pending',
559
+ amount: payment.amount,
560
+ currency: payment.currency,
561
+ livemode: payment.livemode,
562
+ userId: customer.userId,
563
+ customerId: customer.id,
564
+ ...(await this.subscriptionRef(provider, payment)),
565
+ metadata: payment.metadata
566
+ });
567
+ }
568
+ catch (e) {
569
+ if (!(0, payment_store_1.isUniqueViolation)(e)) {
570
+ throw e;
571
+ }
572
+ return this._store.payments.find({
573
+ provider,
574
+ providerPaymentId: payment.id
575
+ });
576
+ }
577
+ }
578
+ /**
579
+ * The subscription a payment of a gateway belongs to, as the column of its record: the one the record has, or the
580
+ * record of the subscription of the gateway. Nothing with the subscriptions off, when the column does not exist.
581
+ *
582
+ * @internal
583
+ */
584
+ async subscriptionRef(provider, payment, local) {
585
+ if (!config_1.paymentsSubscriptionsConfig.ENABLED) {
586
+ return {};
587
+ }
588
+ if (local?.subscriptionId) {
589
+ return { subscriptionId: local.subscriptionId };
590
+ }
591
+ const subscription = payment.subscriptionId
592
+ ? await this._store.subscriptions.find({
593
+ provider,
594
+ providerSubscriptionId: payment.subscriptionId
595
+ })
596
+ : null;
597
+ return { subscriptionId: subscription?.id ?? null };
598
+ }
599
+ /** The ID of the record of the payment method paying, saved from its details when it is not known yet. @internal */
600
+ async localMethodId(provider, payment, local) {
601
+ const providerPaymentMethodId = payment.paymentMethod?.id ?? payment.paymentMethodId;
602
+ if (!providerPaymentMethodId) {
603
+ return null;
604
+ }
605
+ const method = await this._store.methods.find({
606
+ provider,
607
+ providerPaymentMethodId
608
+ });
609
+ if (method || !payment.paymentMethod?.customerId || !local.customerId) {
610
+ return method?.id ?? null;
611
+ }
612
+ const saved = await this.applyPaymentMethod(provider, payment.paymentMethod);
613
+ return saved.record?.id ?? null;
614
+ }
615
+ /** @internal */
616
+ async findSubscription(provider, subscription, recordId) {
617
+ const where = { provider, providerSubscriptionId: subscription.id };
618
+ const local = await this._store.subscriptions.find(where);
619
+ if (local) {
620
+ return { local, created: false };
621
+ }
622
+ const id = recordId ?? subscription.metadata[exports.SUBSCRIPTION_METADATA_KEY];
623
+ const named = id ? await this._store.subscriptions.findById(id) : null;
624
+ if (named?.provider === provider && !named.providerSubscriptionId) {
625
+ return { local: named, created: false };
626
+ }
627
+ const customer = await this._store.customers.find({
628
+ provider,
629
+ providerCustomerId: subscription.customerId
630
+ });
631
+ if (!customer) {
632
+ logger.debug({ gateway: provider, subscription: subscription.id }, 'Subscription of no known customer ignored');
633
+ return null;
634
+ }
635
+ try {
636
+ const created = await this._store.subscriptions.create({
637
+ ...where,
638
+ status: 'incomplete',
639
+ userId: customer.userId,
640
+ customerId: customer.id,
641
+ providerPriceId: subscription.priceId,
642
+ quantity: subscription.quantity,
643
+ metadata: subscription.metadata
644
+ });
645
+ return { local: created, created: true };
646
+ }
647
+ catch (e) {
648
+ if (!(0, payment_store_1.isUniqueViolation)(e)) {
649
+ throw e;
650
+ }
651
+ const existing = await this._store.subscriptions.find(where);
652
+ return existing ? { local: existing, created: false } : null;
653
+ }
654
+ }
655
+ /** Writes the ledger entry of a payment that moved: its authorization, its charge or its capture. @internal */
656
+ async recordCharge(record, payment, previous) {
657
+ const reference = payment.chargeId ?? payment.id;
658
+ const entry = {
659
+ providerTransactionId: reference,
660
+ currency: record.currency,
661
+ fee: payment.fee ?? null
662
+ };
663
+ if (record.status === 'authorized') {
664
+ await this.recordTransaction(record, {
665
+ ...entry,
666
+ type: 'authorization',
667
+ status: 'succeeded',
668
+ amount: record.amount
669
+ });
670
+ }
671
+ else if (record.status === 'succeeded') {
672
+ await this.recordTransaction(record, {
673
+ ...entry,
674
+ type: previous === 'authorized' ? 'capture' : 'charge',
675
+ status: 'succeeded',
676
+ amount: record.amountCaptured
677
+ });
678
+ }
679
+ else if (record.status === 'failed' && payment.chargeId) {
680
+ await this.recordTransaction(record, {
681
+ ...entry,
682
+ type: 'charge',
683
+ status: 'failed',
684
+ amount: record.amount,
685
+ failureReason: payment.failureMessage ?? payment.failureCode ?? null
686
+ });
687
+ }
688
+ else if (record.status === 'canceled' && previous === 'authorized') {
689
+ await this._store.transactions.updateWhere({ paymentId: record.id, type: 'authorization', status: 'succeeded' }, { status: 'canceled' });
690
+ }
691
+ }
692
+ /**
693
+ * Writes an entry of the ledger of a payment once, by its type and its ID at the gateway, then only moves its
694
+ * state.
695
+ *
696
+ * @internal
697
+ */
698
+ async recordTransaction(payment, entry) {
699
+ const where = {
700
+ provider: payment.provider,
701
+ type: entry.type,
702
+ providerTransactionId: entry.providerTransactionId
703
+ };
704
+ let existing = await this._store.transactions.find(where);
705
+ if (!existing) {
706
+ try {
707
+ const record = await this._store.transactions.create({
708
+ ...entry,
709
+ provider: payment.provider,
710
+ paymentId: payment.id,
711
+ userId: payment.userId,
712
+ occurredAt: new Date()
713
+ });
714
+ return { record, changed: true, created: true };
715
+ }
716
+ catch (e) {
717
+ if (!(0, payment_store_1.isUniqueViolation)(e)) {
718
+ throw e;
719
+ }
720
+ existing = (await this._store.transactions.find(where));
721
+ }
722
+ }
723
+ if (existing.status === entry.status || !entry.status) {
724
+ return { record: existing, changed: false, created: false };
725
+ }
726
+ const moved = await this._store.transactions.updateWhere({ id: existing.id, status: existing.status }, { status: entry.status, failureReason: entry.failureReason ?? null });
727
+ return {
728
+ record: { ...existing, status: entry.status },
729
+ changed: moved > 0,
730
+ created: false
731
+ };
732
+ }
733
+ }
734
+ exports.PaymentSync = PaymentSync;
735
+ /** Tells whether a patch changes a field of a record. */
736
+ function differs(record, patch) {
737
+ return Object.entries(patch).some(([key, value]) => {
738
+ const current = record[key];
739
+ if (current instanceof Date || value instanceof Date) {
740
+ return (current?.valueOf() !==
741
+ value?.valueOf());
742
+ }
743
+ return (current ?? null) !== (value ?? null);
744
+ });
745
+ }