@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
package/types.d.ts ADDED
@@ -0,0 +1,488 @@
1
+ /** The state of a payment. Only `succeeded` and `canceled` are final: a failed attempt may be tried again. */
2
+ export type PaymentStatus = 'pending' | 'requiresAction' | 'processing' | 'authorized' | 'succeeded' | 'failed' | 'canceled';
3
+ /** The state of a subscription. */
4
+ export type SubscriptionStatus = 'incomplete' | 'trialing' | 'active' | 'pastDue' | 'unpaid' | 'paused' | 'canceled';
5
+ /** The state of an invoice of a subscription. */
6
+ export type InvoiceStatus = 'draft' | 'open' | 'paid' | 'uncollectible' | 'void';
7
+ /** A movement of money of a payment, an entry of its ledger. */
8
+ export type TransactionType = 'authorization' | 'capture' | 'charge' | 'refund' | 'dispute';
9
+ /** The state of a ledger entry, `won` and `lost` for a closed dispute. */
10
+ export type TransactionStatus = 'pending' | 'succeeded' | 'failed' | 'canceled' | 'won' | 'lost';
11
+ /** When the money of a payment is taken: at once, or later with `capturePayment`. */
12
+ export type CaptureMethod = 'automatic' | 'manual';
13
+ /** The period of a recurring price. */
14
+ export type PlanInterval = 'day' | 'week' | 'month' | 'year';
15
+ /**
16
+ * What the client does next to complete a payment: nothing, confirm it with the client library of the gateway (the
17
+ * card form and 3D Secure), or follow a redirect to a page of the gateway.
18
+ */
19
+ export type PaymentNextAction = {
20
+ type: 'none';
21
+ } | {
22
+ type: 'confirm';
23
+ clientSecret: string;
24
+ publicKey?: string;
25
+ } | {
26
+ type: 'redirect';
27
+ url: string;
28
+ };
29
+ /** What a gateway can do, checked before a call it does not support (`PAYMENT_CAPABILITY_UNSUPPORTED`). */
30
+ export type PaymentCapability = 'checkout' | 'manualCapture' | 'savedMethods' | 'subscriptions' | 'portal' | 'prices';
31
+ /** The metadata of a record, sent to the gateway with it. */
32
+ export type PaymentMetadata = Record<string, string>;
33
+ /** A gateway of the `payments.gateways` config, completed with the defaults of the `payments` config. */
34
+ export type GatewayConfig = {
35
+ /** The name of the gateway, stored with its records */
36
+ name: string;
37
+ driver: string;
38
+ timeout: number;
39
+ maxRetries: number;
40
+ countries: string[];
41
+ currencies: string[];
42
+ secretKey?: string;
43
+ publicKey?: string;
44
+ webhookSecret?: string;
45
+ apiVersion?: string;
46
+ apiUrl?: string;
47
+ };
48
+ export type GatewayCustomerInput = {
49
+ email?: string;
50
+ name?: string;
51
+ locale?: string;
52
+ metadata?: PaymentMetadata;
53
+ };
54
+ export type GatewayCustomer = {
55
+ id: string;
56
+ email?: string;
57
+ name?: string;
58
+ };
59
+ /** A payment method as its gateway describes it, never the number of a card. */
60
+ export type GatewayPaymentMethod = {
61
+ id: string;
62
+ /** The kind of the method, i.e. `card` */
63
+ type: string;
64
+ customerId?: string;
65
+ brand?: string;
66
+ last4?: string;
67
+ expMonth?: number;
68
+ expYear?: number;
69
+ fingerprint?: string;
70
+ country?: string;
71
+ };
72
+ export type GatewayPaymentInput = {
73
+ /** The amount in the minor units of the currency */
74
+ amount: number;
75
+ /** The ISO 4217 code of the currency, in upper case */
76
+ currency: string;
77
+ captureMethod: CaptureMethod;
78
+ /** Sent with the request, so a retry of it never charges twice */
79
+ idempotencyKey: string;
80
+ customerId?: string;
81
+ /** A saved payment method to charge */
82
+ paymentMethodId?: string;
83
+ /** Charge the saved method while the customer is away, i.e. a renewal the application runs */
84
+ offSession?: boolean;
85
+ /** Save the payment method of the payment for later ones */
86
+ savePaymentMethod?: boolean;
87
+ description?: string;
88
+ /** The text on the statement of the customer */
89
+ statementDescriptor?: string;
90
+ /** Where the gateway sends the customer back after a redirect, i.e. of their bank */
91
+ returnUrl?: string;
92
+ receiptEmail?: string;
93
+ metadata?: PaymentMetadata;
94
+ };
95
+ /** A payment as its gateway holds it, with the amounts in minor units. */
96
+ export type GatewayPayment = {
97
+ id: string;
98
+ status: PaymentStatus;
99
+ amount: number;
100
+ currency: string;
101
+ amountCaptured: number;
102
+ amountRefunded: number;
103
+ livemode: boolean;
104
+ nextAction: PaymentNextAction;
105
+ metadata: PaymentMetadata;
106
+ customerId?: string;
107
+ paymentMethodId?: string;
108
+ paymentMethod?: GatewayPaymentMethod;
109
+ /** The ID of the charge of the payment, the reference of its ledger entry */
110
+ chargeId?: string;
111
+ /** The fee the gateway takes, once it is known */
112
+ fee?: number;
113
+ failureCode?: string;
114
+ failureMessage?: string;
115
+ receiptUrl?: string;
116
+ subscriptionId?: string;
117
+ invoiceId?: string;
118
+ };
119
+ export type GatewayRefundInput = {
120
+ /** The ID of the payment at the gateway */
121
+ paymentId: string;
122
+ idempotencyKey: string;
123
+ /** The amount in minor units, the whole remainder when left out */
124
+ amount?: number;
125
+ reason?: string;
126
+ metadata?: PaymentMetadata;
127
+ };
128
+ export type GatewayRefund = {
129
+ id: string;
130
+ paymentId: string;
131
+ amount: number;
132
+ currency: string;
133
+ status: TransactionStatus;
134
+ reason?: string;
135
+ failureReason?: string;
136
+ };
137
+ export type GatewayDispute = {
138
+ id: string;
139
+ paymentId: string;
140
+ amount: number;
141
+ currency: string;
142
+ /** `pending` while it is open */
143
+ status: TransactionStatus;
144
+ reason?: string;
145
+ };
146
+ export type GatewayCheckoutInput = {
147
+ mode: 'payment' | 'subscription';
148
+ successUrl: string;
149
+ cancelUrl: string;
150
+ idempotencyKey: string;
151
+ customerId?: string;
152
+ /** The payment of the checkout, for the `payment` mode */
153
+ amount?: number;
154
+ currency?: string;
155
+ captureMethod?: CaptureMethod;
156
+ /** The name of what is paid for, shown on the page of the gateway */
157
+ description?: string;
158
+ /** The price of the plan at the gateway, for the `subscription` mode */
159
+ priceId?: string;
160
+ quantity?: number;
161
+ trialDays?: number;
162
+ locale?: string;
163
+ metadata?: PaymentMetadata;
164
+ };
165
+ /** A hosted checkout page of a gateway. */
166
+ export type GatewayCheckout = {
167
+ id: string;
168
+ status: 'open' | 'complete' | 'expired';
169
+ /** The page the customer pays on, while it is open */
170
+ url?: string;
171
+ customerId?: string;
172
+ paymentId?: string;
173
+ subscriptionId?: string;
174
+ metadata?: PaymentMetadata;
175
+ };
176
+ /** The flow saving a payment method without a payment. */
177
+ export type GatewaySetup = {
178
+ id: string;
179
+ status: 'pending' | 'succeeded' | 'canceled';
180
+ nextAction: PaymentNextAction;
181
+ paymentMethodId?: string;
182
+ };
183
+ export type GatewaySubscriptionInput = {
184
+ customerId: string;
185
+ priceId: string;
186
+ idempotencyKey: string;
187
+ quantity?: number;
188
+ trialDays?: number;
189
+ /** A saved payment method to charge, the default one of the customer when left out */
190
+ paymentMethodId?: string;
191
+ metadata?: PaymentMetadata;
192
+ };
193
+ export type GatewaySubscriptionUpdate = {
194
+ priceId?: string;
195
+ quantity?: number;
196
+ /** Charge or credit the difference for the rest of the period */
197
+ prorate?: boolean;
198
+ cancelAtPeriodEnd?: boolean;
199
+ paymentMethodId?: string;
200
+ metadata?: PaymentMetadata;
201
+ };
202
+ export type GatewaySubscription = {
203
+ id: string;
204
+ status: SubscriptionStatus;
205
+ customerId: string;
206
+ priceId: string;
207
+ quantity: number;
208
+ cancelAtPeriodEnd: boolean;
209
+ livemode: boolean;
210
+ /** How the client confirms the first payment of a subscription that is `incomplete` */
211
+ nextAction: PaymentNextAction;
212
+ metadata: PaymentMetadata;
213
+ currentPeriodStart?: Date;
214
+ currentPeriodEnd?: Date;
215
+ trialEnd?: Date;
216
+ canceledAt?: Date;
217
+ endedAt?: Date;
218
+ latestInvoiceId?: string;
219
+ };
220
+ export type GatewayInvoice = {
221
+ id: string;
222
+ status: InvoiceStatus;
223
+ customerId: string;
224
+ amountDue: number;
225
+ amountPaid: number;
226
+ currency: string;
227
+ attemptCount: number;
228
+ livemode: boolean;
229
+ subscriptionId?: string;
230
+ /** The payment collecting the invoice */
231
+ paymentId?: string;
232
+ number?: string;
233
+ periodStart?: Date;
234
+ periodEnd?: Date;
235
+ nextAttemptAt?: Date;
236
+ hostedUrl?: string;
237
+ pdfUrl?: string;
238
+ };
239
+ /** A recurring price of a gateway, synchronized into the plans. */
240
+ export type GatewayPrice = {
241
+ id: string;
242
+ amount: number;
243
+ currency: string;
244
+ interval: PlanInterval;
245
+ intervalCount: number;
246
+ active: boolean;
247
+ /** The stable key of the price, the key of its plan */
248
+ key?: string;
249
+ name?: string;
250
+ trialDays?: number;
251
+ };
252
+ /** What a webhook event of a gateway is about, normalized by its driver. */
253
+ export type GatewayEventData = {
254
+ kind: 'payment';
255
+ payment: GatewayPayment;
256
+ } | {
257
+ kind: 'refund';
258
+ refund: GatewayRefund;
259
+ } | {
260
+ kind: 'dispute';
261
+ dispute: GatewayDispute;
262
+ } | {
263
+ kind: 'paymentMethod';
264
+ paymentMethod: GatewayPaymentMethod;
265
+ detached?: boolean;
266
+ } | {
267
+ kind: 'subscription';
268
+ subscription: GatewaySubscription;
269
+ trialWillEnd?: boolean;
270
+ } | {
271
+ kind: 'invoice';
272
+ invoice: GatewayInvoice;
273
+ } | {
274
+ kind: 'checkout';
275
+ checkout: GatewayCheckout;
276
+ } | {
277
+ kind: 'customer';
278
+ customerId: string;
279
+ deleted: true;
280
+ }
281
+ /** An event the module does nothing with */
282
+ | {
283
+ kind: 'ignored';
284
+ };
285
+ /** A verified webhook event of a gateway. */
286
+ export type GatewayEvent = {
287
+ /** The ID of the event at the gateway, received once */
288
+ id: string;
289
+ /** The type of the event as the gateway names it, i.e. `payment_intent.succeeded` */
290
+ type: string;
291
+ occurredAt: Date;
292
+ livemode: boolean;
293
+ data: GatewayEventData;
294
+ };
295
+ /** The headers of a webhook request. */
296
+ export type WebhookHeaders = Record<string, string | string[] | undefined>;
297
+ /** The customer of a gateway and the user it belongs to. */
298
+ export type PaymentCustomerRecord = {
299
+ id: string;
300
+ provider: string;
301
+ providerCustomerId: string;
302
+ userId: string | null;
303
+ email: string | null;
304
+ name: string | null;
305
+ locale: string | null;
306
+ defaultPaymentMethodId: string | null;
307
+ deletedAtProvider: Date | null;
308
+ createdAt: Date;
309
+ updatedAt: Date;
310
+ };
311
+ export type PaymentMethodRecord = {
312
+ id: string;
313
+ provider: string;
314
+ providerPaymentMethodId: string;
315
+ customerId: string;
316
+ userId: string | null;
317
+ type: string;
318
+ brand: string | null;
319
+ last4: string | null;
320
+ expMonth: number | null;
321
+ expYear: number | null;
322
+ fingerprint: string | null;
323
+ country: string | null;
324
+ isDefault: boolean;
325
+ createdAt: Date;
326
+ updatedAt: Date;
327
+ };
328
+ export type PaymentRecord = {
329
+ id: string;
330
+ provider: string;
331
+ providerPaymentId: string | null;
332
+ providerCheckoutId: string | null;
333
+ status: PaymentStatus;
334
+ amount: number;
335
+ currency: string;
336
+ amountCaptured: number;
337
+ amountRefunded: number;
338
+ captureMethod: CaptureMethod;
339
+ disputed: boolean;
340
+ livemode: boolean;
341
+ userId: string | null;
342
+ /** The address the payment was created with, receiving its emails when it has no customer */
343
+ email: string | null;
344
+ customerId: string | null;
345
+ paymentMethodId: string | null;
346
+ subscriptionId: string | null;
347
+ description: string | null;
348
+ /** What the payment is for in the application, i.e. the ID of an order */
349
+ reference: string | null;
350
+ referenceType: string | null;
351
+ idempotencyKey: string | null;
352
+ failureCode: string | null;
353
+ failureMessage: string | null;
354
+ receiptUrl: string | null;
355
+ metadata: PaymentMetadata | null;
356
+ paidAt: Date | null;
357
+ canceledAt: Date | null;
358
+ createdAt: Date;
359
+ updatedAt: Date;
360
+ };
361
+ export type PaymentTransactionRecord = {
362
+ id: string;
363
+ provider: string;
364
+ providerTransactionId: string;
365
+ paymentId: string;
366
+ type: TransactionType;
367
+ status: TransactionStatus;
368
+ amount: number;
369
+ currency: string;
370
+ fee: number | null;
371
+ reason: string | null;
372
+ failureReason: string | null;
373
+ occurredAt: Date;
374
+ createdAt: Date;
375
+ };
376
+ export type PaymentPlanRecord = {
377
+ id: string;
378
+ key: string;
379
+ provider: string;
380
+ providerPriceId: string;
381
+ name: string | null;
382
+ amount: number;
383
+ currency: string;
384
+ interval: PlanInterval;
385
+ intervalCount: number;
386
+ trialDays: number | null;
387
+ active: boolean;
388
+ createdAt: Date;
389
+ updatedAt: Date;
390
+ };
391
+ export type PaymentSubscriptionRecord = {
392
+ id: string;
393
+ provider: string;
394
+ providerSubscriptionId: string | null;
395
+ status: SubscriptionStatus;
396
+ userId: string | null;
397
+ customerId: string;
398
+ planId: string | null;
399
+ planKey: string | null;
400
+ providerPriceId: string;
401
+ quantity: number;
402
+ cancelAtPeriodEnd: boolean;
403
+ livemode: boolean;
404
+ currentPeriodStart: Date | null;
405
+ currentPeriodEnd: Date | null;
406
+ trialEnd: Date | null;
407
+ canceledAt: Date | null;
408
+ endedAt: Date | null;
409
+ pastDueAt: Date | null;
410
+ metadata: PaymentMetadata | null;
411
+ createdAt: Date;
412
+ updatedAt: Date;
413
+ };
414
+ export type PaymentInvoiceRecord = {
415
+ id: string;
416
+ provider: string;
417
+ providerInvoiceId: string;
418
+ status: InvoiceStatus;
419
+ subscriptionId: string | null;
420
+ customerId: string | null;
421
+ userId: string | null;
422
+ paymentId: string | null;
423
+ number: string | null;
424
+ amountDue: number;
425
+ amountPaid: number;
426
+ currency: string;
427
+ attemptCount: number;
428
+ periodStart: Date | null;
429
+ periodEnd: Date | null;
430
+ nextAttemptAt: Date | null;
431
+ hostedUrl: string | null;
432
+ pdfUrl: string | null;
433
+ paidAt: Date | null;
434
+ createdAt: Date;
435
+ updatedAt: Date;
436
+ };
437
+ /** A webhook event received from a gateway, the inbox processing each one once. */
438
+ export type PaymentWebhookEventRecord = {
439
+ id: string;
440
+ provider: string;
441
+ providerEventId: string;
442
+ type: string;
443
+ kind: string;
444
+ status: 'received' | 'processed' | 'failed' | 'ignored';
445
+ attempts: number;
446
+ livemode: boolean;
447
+ lastError: string | null;
448
+ payload: GatewayEventData | null;
449
+ occurredAt: Date;
450
+ processedAt: Date | null;
451
+ createdAt: Date;
452
+ };
453
+ /** The events of the payments the application listens to with `onPaymentEvent`. */
454
+ export type PaymentEventType = 'payment.succeeded' | 'payment.failed' | 'payment.requiresAction' | 'payment.authorized' | 'payment.canceled' | 'refund.succeeded' | 'refund.failed' | 'dispute.opened' | 'dispute.closed' | 'paymentMethod.attached' | 'paymentMethod.detached' | 'subscription.created' | 'subscription.updated' | 'subscription.pastDue' | 'subscription.canceled' | 'subscription.trialWillEnd' | 'invoice.paid' | 'invoice.paymentFailed';
455
+ /** An event of the payments as it is stored: written with the change it tells of, then delivered to the handlers. */
456
+ export type PaymentEventRecord = {
457
+ id: string;
458
+ type: PaymentEventType;
459
+ provider: string;
460
+ status: 'pending' | 'delivered' | 'failed';
461
+ attempts: number;
462
+ userId: string | null;
463
+ paymentId: string | null;
464
+ transactionId: string | null;
465
+ paymentMethodId: string | null;
466
+ subscriptionId: string | null;
467
+ invoiceId: string | null;
468
+ lastError: string | null;
469
+ deliveredAt: Date | null;
470
+ createdAt: Date;
471
+ };
472
+ /** An event of the payments with the records it is about, as a handler of `onPaymentEvent` receives it. */
473
+ export type PaymentEvent = {
474
+ /** The ID of the event, the same on every delivery of it */
475
+ id: string;
476
+ type: PaymentEventType;
477
+ /** The name of the gateway of the records */
478
+ gateway: string;
479
+ userId: string | null;
480
+ createdAt: Date;
481
+ customer?: PaymentCustomerRecord;
482
+ payment?: PaymentRecord;
483
+ /** The refund or the dispute of the payment */
484
+ transaction?: PaymentTransactionRecord;
485
+ paymentMethod?: PaymentMethodRecord;
486
+ subscription?: PaymentSubscriptionRecord;
487
+ invoice?: PaymentInvoiceRecord;
488
+ };
package/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Normalizes a currency code to upper case and checks it is an ISO 4217 code among the allowed currencies.
3
+ *
4
+ * @param {string} [currency] - The currency code, the `payments.currency` config when left out.
5
+ * @return {string} The code in upper case.
6
+ * @throws {PaymentError} `PAYMENT_CURRENCY_UNSUPPORTED` for an unknown code, or one not in `payments.currencies`.
7
+ */
8
+ export declare function normalizeCurrency(currency?: string): string;
9
+ /**
10
+ * Returns the number of decimals of a currency: `2` for most, `0` for the yen, `3` for the Kuwaiti dinar.
11
+ *
12
+ * @param {string} currency - The ISO 4217 code of the currency.
13
+ * @return {number} The number of decimals of its amounts.
14
+ */
15
+ export declare function currencyExponent(currency: string): number;
16
+ /**
17
+ * Converts an amount to the minor units of its currency, the integer the payments are stored and charged in.
18
+ *
19
+ * @example
20
+ * toMinorUnits(19.99, 'USD'); // 1999
21
+ * toMinorUnits('500', 'JPY'); // 500
22
+ *
23
+ * @param {number | string} amount - The amount in the currency, i.e. `19.99`.
24
+ * @param {string} currency - The ISO 4217 code of the currency.
25
+ * @return {number} The amount in minor units.
26
+ * @throws {PaymentError} `PAYMENT_AMOUNT_INVALID` for an amount that is not a number, or with more decimals than the
27
+ * currency has.
28
+ */
29
+ export declare function toMinorUnits(amount: number | string, currency: string): number;
30
+ /**
31
+ * Converts an amount in minor units to the amount in its currency.
32
+ *
33
+ * @example
34
+ * fromMinorUnits(1999, 'USD'); // 19.99
35
+ *
36
+ * @param {number} amount - The amount in minor units.
37
+ * @param {string} currency - The ISO 4217 code of the currency.
38
+ * @return {number} The amount in the currency.
39
+ */
40
+ export declare function fromMinorUnits(amount: number, currency: string): number;
41
+ /**
42
+ * Formats an amount in minor units for a reader, i.e. in an email.
43
+ *
44
+ * @example
45
+ * formatAmount(1999, 'USD'); // '$19.99'
46
+ * formatAmount(1999, 'EUR', 'de'); // '19,99 €'
47
+ *
48
+ * @param {number} amount - The amount in minor units.
49
+ * @param {string} currency - The ISO 4217 code of the currency.
50
+ * @param {string} [locale='en'] - The locale of the format.
51
+ * @return {string} The formatted amount with its currency.
52
+ */
53
+ export declare function formatAmount(amount: number, currency: string, locale?: string): string;
54
+ /**
55
+ * Checks the amount of a payment: a positive safe integer of minor units.
56
+ *
57
+ * @param {number} amount - The amount in minor units.
58
+ * @param {string} [currency] - The currency, named by the error.
59
+ * @throws {PaymentError} `PAYMENT_AMOUNT_INVALID` otherwise.
60
+ */
61
+ export declare function validateAmount(amount: number, currency?: string): void;
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeCurrency = normalizeCurrency;
4
+ exports.currencyExponent = currencyExponent;
5
+ exports.toMinorUnits = toMinorUnits;
6
+ exports.fromMinorUnits = fromMinorUnits;
7
+ exports.formatAmount = formatAmount;
8
+ exports.validateAmount = validateAmount;
9
+ const common_1 = require("@appweaver/common");
10
+ const config_1 = require("../config");
11
+ const exponents = new Map();
12
+ /**
13
+ * Normalizes a currency code to upper case and checks it is an ISO 4217 code among the allowed currencies.
14
+ *
15
+ * @param {string} [currency] - The currency code, the `payments.currency` config when left out.
16
+ * @return {string} The code in upper case.
17
+ * @throws {PaymentError} `PAYMENT_CURRENCY_UNSUPPORTED` for an unknown code, or one not in `payments.currencies`.
18
+ */
19
+ function normalizeCurrency(currency) {
20
+ const code = (currency ?? config_1.paymentsConfig.CURRENCY).toUpperCase();
21
+ const allowed = config_1.paymentsConfig.CURRENCIES.map((entry) => entry.toUpperCase());
22
+ if (!/^[A-Z]{3}$/.test(code) ||
23
+ (allowed.length > 0 && !allowed.includes(code))) {
24
+ throw new common_1.PaymentError(common_1.ErrorCode.PaymentCurrencyUnsupported, `The currency '${code}' is not supported`, { currency: code });
25
+ }
26
+ return code;
27
+ }
28
+ /**
29
+ * Returns the number of decimals of a currency: `2` for most, `0` for the yen, `3` for the Kuwaiti dinar.
30
+ *
31
+ * @param {string} currency - The ISO 4217 code of the currency.
32
+ * @return {number} The number of decimals of its amounts.
33
+ */
34
+ function currencyExponent(currency) {
35
+ const code = currency.toUpperCase();
36
+ let exponent = exponents.get(code);
37
+ if (exponent === undefined) {
38
+ try {
39
+ exponent =
40
+ new Intl.NumberFormat('en', {
41
+ style: 'currency',
42
+ currency: code
43
+ }).resolvedOptions().maximumFractionDigits ?? 2;
44
+ }
45
+ catch {
46
+ exponent = 2;
47
+ }
48
+ exponents.set(code, exponent);
49
+ }
50
+ return exponent;
51
+ }
52
+ /**
53
+ * Converts an amount to the minor units of its currency, the integer the payments are stored and charged in.
54
+ *
55
+ * @example
56
+ * toMinorUnits(19.99, 'USD'); // 1999
57
+ * toMinorUnits('500', 'JPY'); // 500
58
+ *
59
+ * @param {number | string} amount - The amount in the currency, i.e. `19.99`.
60
+ * @param {string} currency - The ISO 4217 code of the currency.
61
+ * @return {number} The amount in minor units.
62
+ * @throws {PaymentError} `PAYMENT_AMOUNT_INVALID` for an amount that is not a number, or with more decimals than the
63
+ * currency has.
64
+ */
65
+ function toMinorUnits(amount, currency) {
66
+ const exponent = currencyExponent(currency);
67
+ const text = String(amount).trim();
68
+ const match = /^(-?)(\d+)(?:\.(\d+))?$/.exec(text);
69
+ if (!match || (match[3] ?? '').replace(/0+$/, '').length > exponent) {
70
+ throw new common_1.PaymentError(common_1.ErrorCode.PaymentAmountInvalid, `The amount '${text}' is not an amount of ${currency.toUpperCase()}`, { amount: Number(amount), currency: currency.toUpperCase() });
71
+ }
72
+ const [, sign, whole, fraction = ''] = match;
73
+ const minor = Number(whole + fraction.padEnd(exponent, '0').slice(0, exponent));
74
+ return sign ? -minor : minor;
75
+ }
76
+ /**
77
+ * Converts an amount in minor units to the amount in its currency.
78
+ *
79
+ * @example
80
+ * fromMinorUnits(1999, 'USD'); // 19.99
81
+ *
82
+ * @param {number} amount - The amount in minor units.
83
+ * @param {string} currency - The ISO 4217 code of the currency.
84
+ * @return {number} The amount in the currency.
85
+ */
86
+ function fromMinorUnits(amount, currency) {
87
+ return amount / 10 ** currencyExponent(currency);
88
+ }
89
+ /**
90
+ * Formats an amount in minor units for a reader, i.e. in an email.
91
+ *
92
+ * @example
93
+ * formatAmount(1999, 'USD'); // '$19.99'
94
+ * formatAmount(1999, 'EUR', 'de'); // '19,99 €'
95
+ *
96
+ * @param {number} amount - The amount in minor units.
97
+ * @param {string} currency - The ISO 4217 code of the currency.
98
+ * @param {string} [locale='en'] - The locale of the format.
99
+ * @return {string} The formatted amount with its currency.
100
+ */
101
+ function formatAmount(amount, currency, locale = 'en') {
102
+ const value = fromMinorUnits(amount, currency);
103
+ try {
104
+ return new Intl.NumberFormat(locale, {
105
+ style: 'currency',
106
+ currency: currency.toUpperCase()
107
+ }).format(value);
108
+ }
109
+ catch {
110
+ return `${value.toFixed(currencyExponent(currency))} ${currency.toUpperCase()}`;
111
+ }
112
+ }
113
+ /**
114
+ * Checks the amount of a payment: a positive safe integer of minor units.
115
+ *
116
+ * @param {number} amount - The amount in minor units.
117
+ * @param {string} [currency] - The currency, named by the error.
118
+ * @throws {PaymentError} `PAYMENT_AMOUNT_INVALID` otherwise.
119
+ */
120
+ function validateAmount(amount, currency) {
121
+ if (!Number.isSafeInteger(amount) || amount <= 0) {
122
+ throw new common_1.PaymentError(common_1.ErrorCode.PaymentAmountInvalid, `The amount of a payment is a positive integer of minor units, not '${amount}'`, { amount, currency });
123
+ }
124
+ }