@stancer/stancer 0.0.0-stage → 1.0.1

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 (139) hide show
  1. package/.editorconfig +14 -0
  2. package/.gitlab-ci.yml +159 -0
  3. package/.prettierignore +3 -0
  4. package/CHANGELOG.md +14 -0
  5. package/LICENSE +19 -0
  6. package/README.md +166 -2
  7. package/eslint.config.js +14 -0
  8. package/package.json +58 -3
  9. package/pnpm-workspace.yaml +19 -0
  10. package/prettier.config.js +3 -0
  11. package/src/address/api-endpoint.ts +30 -0
  12. package/src/address/model.ts +79 -0
  13. package/src/address/repository.ts +18 -0
  14. package/src/address/validator.ts +34 -0
  15. package/src/api-endpoint/abstract-api-endpoint.ts +310 -0
  16. package/src/api-endpoint/configuration.ts +125 -0
  17. package/src/api-endpoint/http/fetch-http-client.ts +29 -0
  18. package/src/api-endpoint/http/http.ts +75 -0
  19. package/src/api-endpoint/http/index.ts +2 -0
  20. package/src/api-endpoint/version.ts +4 -0
  21. package/src/card/api-endpoint.ts +39 -0
  22. package/src/card/enum/funding.ts +11 -0
  23. package/src/card/enum/nature.ts +7 -0
  24. package/src/card/enum/network.ts +16 -0
  25. package/src/card/model.ts +139 -0
  26. package/src/card/repository.ts +11 -0
  27. package/src/card/validator.ts +79 -0
  28. package/src/core/abstract-model.ts +126 -0
  29. package/src/core/abstract-repository.ts +201 -0
  30. package/src/core/common/branded-type.ts +15 -0
  31. package/src/core/common/handler/date-handler.ts +31 -0
  32. package/src/core/common/handler/enum-handler.ts +18 -0
  33. package/src/core/common/handler/handler.ts +64 -0
  34. package/src/core/common/handler/id-handler.ts +27 -0
  35. package/src/core/common/id-validator.ts +23 -0
  36. package/src/core/common/mutation-tracked-object.ts +49 -0
  37. package/src/core/endpoint-interface.ts +43 -0
  38. package/src/core/error/base-error.ts +1 -0
  39. package/src/core/error/endpoint/api/api-conflict-error.ts +7 -0
  40. package/src/core/error/endpoint/api/api-error.ts +10 -0
  41. package/src/core/error/endpoint/api/api-not-found-error.ts +7 -0
  42. package/src/core/error/endpoint/api/api-unauthorized-error.ts +7 -0
  43. package/src/core/error/endpoint/api/api-unknown-error.ts +7 -0
  44. package/src/core/error/endpoint/api/api-validation-error.ts +13 -0
  45. package/src/core/error/endpoint/api/index.ts +6 -0
  46. package/src/core/error/endpoint/route-inaccessible-error.ts +8 -0
  47. package/src/core/error/unpopulated-error.ts +3 -0
  48. package/src/core/error/unsendable-error.ts +3 -0
  49. package/src/core/error/validation-error.ts +3 -0
  50. package/src/core/validator.ts +129 -0
  51. package/src/customer/api-endpoint.ts +29 -0
  52. package/src/customer/model.ts +113 -0
  53. package/src/customer/repository.ts +14 -0
  54. package/src/customer/validator.ts +26 -0
  55. package/src/payment/api-endpoint.ts +118 -0
  56. package/src/payment/enum/currency.ts +14 -0
  57. package/src/payment/enum/method.ts +2 -0
  58. package/src/payment/enum/status.ts +21 -0
  59. package/src/payment/model.ts +378 -0
  60. package/src/payment/repository.ts +73 -0
  61. package/src/payment/validator.ts +96 -0
  62. package/src/payment-intent/api-endpoint.ts +123 -0
  63. package/src/payment-intent/enum/status.ts +21 -0
  64. package/src/payment-intent/enum/threeds.ts +2 -0
  65. package/src/payment-intent/model.ts +266 -0
  66. package/src/payment-intent/repository.ts +85 -0
  67. package/src/payment-intent/validator.ts +45 -0
  68. package/src/payout/model.ts +8 -0
  69. package/src/refund/api-endpoint.ts +33 -0
  70. package/src/refund/enum/refund-status.ts +11 -0
  71. package/src/refund/model.ts +90 -0
  72. package/src/refund/repository.ts +14 -0
  73. package/src/refund/validator.ts +44 -0
  74. package/src/sepa/api-endpoint.ts +26 -0
  75. package/src/sepa/model.ts +80 -0
  76. package/src/sepa/repository.ts +11 -0
  77. package/src/sepa/validator.ts +56 -0
  78. package/test/fixtures/endpoint.stub.ts +22 -0
  79. package/test/fixtures/list-endpoint.stub.ts +33 -0
  80. package/test/fixtures/list-model.stub.ts +24 -0
  81. package/test/fixtures/model.stub.ts +12 -0
  82. package/test/functional/address.test.ts +126 -0
  83. package/test/functional/card.test.ts +175 -0
  84. package/test/functional/customer.test.ts +174 -0
  85. package/test/functional/payment-intent.test.ts +215 -0
  86. package/test/functional/payment.test.ts +206 -0
  87. package/test/functional/refund.test.ts +112 -0
  88. package/test/functional/sepa.test.ts +136 -0
  89. package/test/integration/stub-integration.test.ts +88 -0
  90. package/test/stub/stub-endpoint.ts +42 -0
  91. package/test/stub/stub-model.ts +82 -0
  92. package/test/stub/stub-repository.ts +11 -0
  93. package/test/test-helper.ts +133 -0
  94. package/test/unit/address/api-endpoint.test.ts +134 -0
  95. package/test/unit/address/fixtures.ts +60 -0
  96. package/test/unit/address/model.test.ts +75 -0
  97. package/test/unit/address/repository.test.ts +148 -0
  98. package/test/unit/address/validator.test.ts +49 -0
  99. package/test/unit/api-endpoint/http/fetch-http-client.test.ts +44 -0
  100. package/test/unit/api-endpoint/http/http.test.ts +152 -0
  101. package/test/unit/card/api-endpoint.test.ts +170 -0
  102. package/test/unit/card/card-helper.ts +116 -0
  103. package/test/unit/card/fixtures.ts +87 -0
  104. package/test/unit/card/model.test.ts +167 -0
  105. package/test/unit/card/repository.test.ts +146 -0
  106. package/test/unit/card/validator.test.ts +96 -0
  107. package/test/unit/core/common/mutation-tracked-object.test.ts +24 -0
  108. package/test/unit/customer/api-endpoint.test.ts +143 -0
  109. package/test/unit/customer/fixtures.ts +73 -0
  110. package/test/unit/customer/model.test.ts +90 -0
  111. package/test/unit/customer/repository.test.ts +148 -0
  112. package/test/unit/customer/validator.test.ts +62 -0
  113. package/test/unit/payment/api-endpoint.test.ts +188 -0
  114. package/test/unit/payment/fixtures.ts +116 -0
  115. package/test/unit/payment/model.test.ts +240 -0
  116. package/test/unit/payment/repository.test.ts +270 -0
  117. package/test/unit/payment/validator.test.ts +137 -0
  118. package/test/unit/payment-intent/api-endpoint.test.ts +142 -0
  119. package/test/unit/payment-intent/fixtures.ts +94 -0
  120. package/test/unit/payment-intent/model.test.ts +157 -0
  121. package/test/unit/payment-intent/repository.test.ts +263 -0
  122. package/test/unit/payment-intent/validator.test.ts +136 -0
  123. package/test/unit/refund/api-endpoint.test.ts +129 -0
  124. package/test/unit/refund/fixtures.ts +58 -0
  125. package/test/unit/refund/model.test.ts +89 -0
  126. package/test/unit/refund/repository.test.ts +157 -0
  127. package/test/unit/refund/validator.test.ts +89 -0
  128. package/test/unit/sepa/api-endpoint.test.ts +170 -0
  129. package/test/unit/sepa/fixture.ts +62 -0
  130. package/test/unit/sepa/model.test.ts +86 -0
  131. package/test/unit/sepa/repository.test.ts +149 -0
  132. package/test/unit/sepa/sepa-helper.ts +71 -0
  133. package/test/unit/sepa/validator.test.ts +58 -0
  134. package/test/unit/stub/stub-endpoint.test.ts +236 -0
  135. package/test/unit/stub/stub-list-endpoint.test.ts +86 -0
  136. package/test/unit/stub/stub-model.test.ts +111 -0
  137. package/test/unit/stub/stub-repository.test.ts +144 -0
  138. package/tsconfig.json +50 -0
  139. package/vitest.config.ts +20 -0
@@ -0,0 +1,14 @@
1
+ export const CurrencyEnum = [
2
+ 'aud',
3
+ 'cad',
4
+ 'chf',
5
+ 'dkk',
6
+ 'eur',
7
+ 'gbp',
8
+ 'nok',
9
+ 'pln',
10
+ 'sek',
11
+ 'usd',
12
+ ] as const;
13
+
14
+ export type Currency = (typeof CurrencyEnum)[number];
@@ -0,0 +1,2 @@
1
+ export const MethodEnum = ['card', 'sepa'] as const;
2
+ export type Method = (typeof MethodEnum)[number];
@@ -0,0 +1,21 @@
1
+ export const StatusEnum = [
2
+ 'refused',
3
+ 'authorized',
4
+ 'expired',
5
+ 'to_capture',
6
+ 'capture_sent',
7
+ 'captured',
8
+ 'disputed',
9
+ 'canceled',
10
+ 'failed',
11
+ 'authorize',
12
+ 'capture',
13
+ ] as const;
14
+
15
+ export type PaymentStatus = (typeof StatusEnum)[number];
16
+
17
+ export const succeedPaymentStatus = [
18
+ 'to_capture',
19
+ 'capture_sent',
20
+ 'captured',
21
+ ];
@@ -0,0 +1,378 @@
1
+ import { Temporal } from 'temporal-polyfill';
2
+
3
+ import { AbstractModel, type ModelData } from '#core/abstract-model.js';
4
+ import type { Branded, IdValue } from '#core/common/branded-type.js';
5
+ import { validateID } from '#core/common/id-validator.js';
6
+ import { StancerUnpopulatedError } from '#core/error/unpopulated-error.js';
7
+ import { StancerValidationError } from '#core/error/validation-error.js';
8
+ import type { RefundModel } from '#refund/model.js';
9
+
10
+ import type { IdAddress } from '../address/model.js';
11
+ import type { IdCard } from '../card/model.js';
12
+ import type { IdCustomer } from '../customer/model.js';
13
+ import type { IdPaymentIntent } from '../payment-intent/model.js';
14
+ import type { IdPayout } from '../payout/model.js';
15
+ import type { IdSepa } from '../sepa/model.js';
16
+ import type { Currency } from './enum/currency.js';
17
+ import type { Method } from './enum/method.js';
18
+ import { type PaymentStatus, succeedPaymentStatus } from './enum/status.js';
19
+
20
+ export type IdPayment = IdValue<`paym_${string}`>;
21
+ export const idPayment = (id: string) => validateID<IdPayment>(id, PaymentModel.regex);
22
+
23
+ export type PaymentAmount = Branded<number, 'amount'>;
24
+
25
+ export const paymentAmount = (amount: number): PaymentAmount => {
26
+ if (!Number.isInteger(amount) && amount >= 0) {
27
+ throw new StancerValidationError(`Payment amount must be a positive integer (in cents)`);
28
+ }
29
+ return amount as PaymentAmount;
30
+ };
31
+
32
+ export interface Auth {
33
+ device: Device | null;
34
+ message: string | null;
35
+ redirectUrl: string | null;
36
+ returnUrl: string | null;
37
+ status: string | null;
38
+ uuid: string | null;
39
+ }
40
+
41
+ export interface Wallet {
42
+ apple_pay: {
43
+ paymentData: {
44
+ data: string;
45
+ signature: string;
46
+ header: Headers;
47
+ version: string;
48
+ };
49
+ };
50
+ }
51
+ export interface Device {
52
+ city: string;
53
+ country: string;
54
+ http_accept: string;
55
+ ip: string;
56
+ languages: string;
57
+ port: number;
58
+ user_agent: string;
59
+ zip_code: string;
60
+ }
61
+
62
+ export interface PaymentData extends ModelData {
63
+ id: IdPayment;
64
+ amount: PaymentAmount;
65
+ auth: boolean;
66
+ wallet: Wallet;
67
+ capture: boolean;
68
+ currency: Currency;
69
+ customer: IdCustomer;
70
+ datePayment: Temporal.Instant;
71
+ dateSettlement: Temporal.PlainDate;
72
+ dateBank: Temporal.PlainDate;
73
+ description: string;
74
+ device: Device;
75
+ fee: number;
76
+ method: Method;
77
+ methodsAllowed: Method[];
78
+ orderId: string;
79
+ uniqueId: string;
80
+ response: string;
81
+ responseAuthor: string;
82
+ returnUrl: string;
83
+ card: IdCard;
84
+ sepa: IdSepa;
85
+ status: PaymentStatus;
86
+ origin: string;
87
+ payout: IdPayout;
88
+ billingAddress: IdAddress;
89
+ shippingAddress: IdAddress;
90
+ paymentIntent: IdPaymentIntent;
91
+ }
92
+ export class PaymentModel extends AbstractModel<PaymentData> {
93
+ static regex = /^paym_[a-zA-Z0-9]{24}$/;
94
+
95
+ private _refundedAmount = 0;
96
+ private _refundPopulated = false;
97
+ private _refunds: RefundModel[] = [];
98
+
99
+ //#region Getters
100
+
101
+ get amount() {
102
+ return this._data.amount;
103
+ }
104
+
105
+ get auth() {
106
+ return this._data.auth;
107
+ }
108
+
109
+ get billingAddress() {
110
+ return this._data.billingAddress;
111
+ }
112
+
113
+ get capture() {
114
+ return this._data.capture;
115
+ }
116
+
117
+ get card() {
118
+ return this._data.card;
119
+ }
120
+
121
+ get currency() {
122
+ return this._data.currency;
123
+ }
124
+
125
+ get customer() {
126
+ return this._data.customer;
127
+ }
128
+
129
+ get dateBank() {
130
+ return this._data.dateBank;
131
+ }
132
+
133
+ get datePayment() {
134
+ return this._data.datePayment;
135
+ }
136
+
137
+ get datePaym() {
138
+ return this.datePayment;
139
+ }
140
+
141
+ get dateSettlement() {
142
+ return this._data.dateSettlement;
143
+ }
144
+
145
+ get description() {
146
+ return this._data.description;
147
+ }
148
+
149
+ get device() {
150
+ return this._data.device;
151
+ }
152
+
153
+ get fee() {
154
+ return this._data.fee;
155
+ }
156
+
157
+ get method() {
158
+ return this._data.method;
159
+ }
160
+
161
+ get methodsAllowed() {
162
+ return this._data.methodsAllowed;
163
+ }
164
+
165
+ get orderId() {
166
+ return this._data.orderId;
167
+ }
168
+
169
+ get origin() {
170
+ return this._data.origin;
171
+ }
172
+
173
+ get payout() {
174
+ return this._data.payout;
175
+ }
176
+
177
+ get paymentIntent() {
178
+ return this._data.paymentIntent;
179
+ }
180
+
181
+ get refundableAmount() {
182
+ if (!this.isRefundPopulated()) {
183
+ throw new StancerUnpopulatedError('refund is not populated');
184
+ }
185
+
186
+ if (this.amount) {
187
+ return this.amount - this.refundedAmount;
188
+ }
189
+
190
+ return 0;
191
+ }
192
+
193
+ get refundedAmount() {
194
+ if (!this.isRefundPopulated()) {
195
+ throw new StancerUnpopulatedError('refund is not populated');
196
+ }
197
+
198
+ return this._refundedAmount;
199
+ }
200
+
201
+ get refunds() {
202
+ if (!this.isRefundPopulated()) {
203
+ throw new StancerUnpopulatedError('refund is not populated');
204
+ }
205
+
206
+ return this._refunds;
207
+ }
208
+
209
+ get response() {
210
+ return this._data.response;
211
+ }
212
+
213
+ get responseAuthor() {
214
+ return this._data.responseAuthor;
215
+ }
216
+
217
+ get returnUrl() {
218
+ return this._data.returnUrl;
219
+ }
220
+
221
+ get sepa() {
222
+ return this._data.sepa;
223
+ }
224
+
225
+ get shippingAddress() {
226
+ return this._data.shippingAddress;
227
+ }
228
+
229
+ get status() {
230
+ return this._data.status;
231
+ }
232
+
233
+ get uniqueId() {
234
+ return this._data.uniqueId;
235
+ }
236
+
237
+ //#endregion
238
+
239
+ //#region Methods
240
+
241
+ isError(): boolean {
242
+ if (!this.status) {
243
+ return false;
244
+ }
245
+
246
+ if (this.capture === false && this.status === 'authorized') {
247
+ return false;
248
+ }
249
+
250
+ return !succeedPaymentStatus.includes(this.status);
251
+ }
252
+
253
+ isNotError() {
254
+ return !this.isError();
255
+ }
256
+
257
+ isNotSuccess() {
258
+ return !this.isSuccess();
259
+ }
260
+
261
+ isRefundPopulated() {
262
+ return this._refundPopulated;
263
+ }
264
+
265
+ isSuccess() {
266
+ if (this.capture === false && this.status === 'authorized') {
267
+ return true;
268
+ }
269
+
270
+ return this.status && succeedPaymentStatus.includes(this.status);
271
+ }
272
+
273
+ populateRefund(refunds: RefundModel[]) {
274
+ this._refundPopulated = true;
275
+ this._refundedAmount = refunds.reduce((prev, curr) => prev + (curr.amount ?? 0), 0);
276
+ this._refunds = refunds;
277
+ }
278
+
279
+ setAmount(value: number) {
280
+ this._data.amount = value as PaymentAmount;
281
+ return this;
282
+ }
283
+
284
+ setAuth(value: boolean) {
285
+ if (value === true) {
286
+ this._data.auth = true;
287
+ }
288
+
289
+ return this;
290
+ }
291
+
292
+ setBillingAddress(value: IdAddress) {
293
+ this._data.billingAddress = value;
294
+ return this;
295
+ }
296
+
297
+ setCapture(value: boolean) {
298
+ this._data.capture = value;
299
+ return this;
300
+ }
301
+
302
+ setCard(value: IdCard) {
303
+ this._data.card = value;
304
+ this._data.method = 'card';
305
+ return this;
306
+ }
307
+
308
+ setCurrency(value: Currency) {
309
+ if ((this.methodsAllowed?.includes('sepa') || this._data.method === 'sepa') && value !== 'eur') {
310
+ throw new StancerValidationError(`You can not use ${value} currency with sepa method`);
311
+ }
312
+
313
+ this._data.currency = value;
314
+ return this;
315
+ }
316
+
317
+ setCustomer(value: IdCustomer) {
318
+ this._data.customer = value;
319
+ return this;
320
+ }
321
+
322
+ setDateSettlement(value: Temporal.PlainDate) {
323
+ this._data.dateSettlement = value;
324
+ return this;
325
+ }
326
+
327
+ setDescription(value: string) {
328
+ this._data.description = value;
329
+ return this;
330
+ }
331
+
332
+ setDevice(value: Device) {
333
+ this._data.device = value;
334
+ return this;
335
+ }
336
+
337
+ setMethodsAllowed(values: Method[]) {
338
+ this._data.methodsAllowed = values;
339
+ return this;
340
+ }
341
+
342
+ setOrderId(value: string) {
343
+ this._data.orderId = value;
344
+ return this;
345
+ }
346
+
347
+ setReturnUrl(value: string) {
348
+ this._data.returnUrl = value;
349
+ return this;
350
+ }
351
+
352
+ setSepa(value: IdSepa) {
353
+ if (this._data.currency && this._data.currency !== 'eur') {
354
+ throw new StancerValidationError(`You can not use ${this._data.currency} currency with sepa method`);
355
+ }
356
+
357
+ this._data.sepa = value;
358
+ this._data.method = 'sepa';
359
+ return this;
360
+ }
361
+
362
+ setShippingAddress(value: IdAddress) {
363
+ this._data.shippingAddress = value;
364
+ return this;
365
+ }
366
+
367
+ setStatus(value: PaymentStatus) {
368
+ this._data.status = value;
369
+ return this;
370
+ }
371
+
372
+ setUniqueId(value: string) {
373
+ this._data.uniqueId = value;
374
+ return this;
375
+ }
376
+
377
+ //#endregion
378
+ }
@@ -0,0 +1,73 @@
1
+ import { AbstractRepository, type Repository } from '#core/abstract-repository.js';
2
+ import { StancerValidationError } from '#core/error/validation-error.js';
3
+ import { PaymentApiEndpoint } from '#payment/api-endpoint.js';
4
+ import { type PaymentData, PaymentModel } from '#payment/model.js';
5
+ import { paymentValidator } from '#payment/validator.js';
6
+ import { type RefundAmount, refundAmount } from '#refund/model.js';
7
+ import { RefundRepository } from '#refund/repository.js';
8
+
9
+ export class PaymentRepository
10
+ extends AbstractRepository<PaymentData, PaymentModel, PaymentApiEndpoint>
11
+ implements Repository<PaymentData, PaymentModel>
12
+ {
13
+ private _refundRepository?: RefundRepository;
14
+
15
+ constructor(endpoint?: PaymentApiEndpoint, refundRepository?: RefundRepository) {
16
+ super({ endpoint: endpoint ?? new PaymentApiEndpoint(), validator: paymentValidator, model: PaymentModel });
17
+ if (refundRepository) {
18
+ this._refundRepository = refundRepository;
19
+ }
20
+ }
21
+
22
+ public async refund(payment: PaymentModel, amount?: RefundAmount) {
23
+ if (!payment.amount || !payment.id) {
24
+ throw new StancerValidationError('Payment must be populated before calling refund method');
25
+ }
26
+
27
+ if (payment.isNotSuccess()) {
28
+ throw new StancerValidationError('Payment must be successful to be refunded');
29
+ }
30
+
31
+ if (!payment.isRefundPopulated()) {
32
+ await this.populateRefunds(payment);
33
+ }
34
+
35
+ const refundingAmount = refundAmount(amount ?? payment.amount);
36
+ if (refundingAmount > payment.amount || refundingAmount > payment.refundableAmount) {
37
+ throw new StancerValidationError(
38
+ `You are trying to refund ${refundingAmount}, which is ${refundingAmount - payment.refundableAmount} more than the refundable amount of ${payment.refundableAmount}.`,
39
+ );
40
+ }
41
+
42
+ if (
43
+ (payment.status === 'to_capture' || payment.status === 'capture_sent') &&
44
+ payment.amount !== payment.refundableAmount
45
+ ) {
46
+ throw new StancerValidationError(`Partial refund is not allowed when payment is not captured.`);
47
+ }
48
+
49
+ if (!this._refundRepository) {
50
+ this._refundRepository = new RefundRepository();
51
+ }
52
+
53
+ const refundRepository = this._refundRepository;
54
+ const refund = await refundRepository.create();
55
+ refundRepository.send(refund.setPayment(payment.id).setAmount(refundingAmount));
56
+ return await this.populateRefunds(payment);
57
+ }
58
+
59
+ /**
60
+ * Populate the refunds property of a payment and return it
61
+ * @param payment a payment
62
+ * @returns the payment with populate refunds
63
+ */
64
+ public async populateRefunds(payment: PaymentModel) {
65
+ if (payment.id === undefined) {
66
+ throw new StancerValidationError('Payment must be populated before calling populateRefund method');
67
+ }
68
+
69
+ const refunds = await this.endpoint.refunds(payment.id);
70
+ payment.populateRefund(refunds);
71
+ return payment;
72
+ }
73
+ }
@@ -0,0 +1,96 @@
1
+ import { Temporal } from 'temporal-polyfill';
2
+
3
+ import { IdValidator } from '#core/common/id-validator.js';
4
+ import {
5
+ type Validator,
6
+ createdAtValidator,
7
+ enumValidator,
8
+ goldilocksValidator,
9
+ plainDateValidator,
10
+ } from '#core/validator.js';
11
+
12
+ import { AddressModel, type IdAddress } from '../address/model.js';
13
+ import { CardModel, type IdCard } from '../card/model.js';
14
+ import { CustomerModel, type IdCustomer } from '../customer/model.js';
15
+ import { type IdPaymentIntent, PaymentIntentModel } from '../payment-intent/model.js';
16
+ import { type IdPayout, PayoutModel } from '../payout/model.js';
17
+ import { type IdSepa, SepaModel } from '../sepa/model.js';
18
+ import { CurrencyEnum } from './enum/currency.js';
19
+ import { MethodEnum } from './enum/method.js';
20
+ import { StatusEnum } from './enum/status.js';
21
+ import { type Device, type IdPayment, type PaymentData, PaymentModel } from './model.js';
22
+
23
+ export const amountValidator = {
24
+ validate: (value: number) => Number.isInteger(value) && value >= 0,
25
+ errorMessage: (value: string) => `value (${value}) must be a positive integer (in cents)`,
26
+ };
27
+
28
+ const authValidator = {
29
+ validate: (arg0: boolean) => typeof arg0 === 'boolean',
30
+ errorMessage: (value: string) => `auth must be true (received: ${value})`,
31
+ };
32
+
33
+ export const captureValidator = {
34
+ validate: (arg0: boolean) => typeof arg0 === 'boolean',
35
+ errorMessage: (value: string) => `capture must be boolean (received: ${value})`,
36
+ };
37
+
38
+ const deviceValidator = {
39
+ validate: (arg0: Device | boolean) => typeof arg0 === 'boolean' || Object.hasOwn(arg0, 'city'),
40
+ errorMessage: () => `device must be a boolean or a Device `,
41
+ };
42
+
43
+ const instantValidator = (field: string) => {
44
+ return {
45
+ validate: (arg0: Temporal.Instant) =>
46
+ Temporal.Instant.compare(Temporal.Now.instant().toZonedDateTimeISO('UTC'), arg0) >= 0,
47
+ errorMessage: () => `${field} must be a date in the past.`,
48
+ };
49
+ };
50
+
51
+ export const methodsAllowedValidator = {
52
+ validate: (arg0: ('card' | 'sepa')[]) => {
53
+ if (!Array.isArray(arg0)) {
54
+ return false;
55
+ }
56
+ const validator = enumValidator(MethodEnum);
57
+ if (validator === true) {
58
+ return true;
59
+ }
60
+ return arg0.every((method) => validator.validate(method));
61
+ },
62
+ errorMessage: (value: string) => `${value.toString()} is not a valid array of allowed method`,
63
+ };
64
+
65
+ export const paymentValidator: Validator<PaymentData> = {
66
+ id: IdValidator<IdPayment>(PaymentModel.regex),
67
+ amount: amountValidator,
68
+ auth: authValidator,
69
+ billingAddress: IdValidator<IdAddress>(AddressModel.regex),
70
+ card: IdValidator<IdCard>(CardModel.regex),
71
+ capture: captureValidator,
72
+ createdAt: createdAtValidator,
73
+ currency: enumValidator(CurrencyEnum),
74
+ customer: IdValidator<IdCustomer>(CustomerModel.regex),
75
+ dateBank: plainDateValidator('dateBank'),
76
+ datePayment: instantValidator('datePayment'),
77
+ dateSettlement: plainDateValidator('dateSettlement'),
78
+ deleted: true,
79
+ description: goldilocksValidator('description', { min: 1, max: 64 }),
80
+ device: deviceValidator,
81
+ fee: true,
82
+ method: enumValidator(MethodEnum, false),
83
+ methodsAllowed: methodsAllowedValidator,
84
+ orderId: goldilocksValidator('orderId', { min: 1, max: 36 }),
85
+ origin: true,
86
+ paymentIntent: IdValidator<IdPaymentIntent>(PaymentIntentModel.regex),
87
+ payout: IdValidator<IdPayout>(PayoutModel.regex),
88
+ response: true,
89
+ responseAuthor: true,
90
+ returnUrl: goldilocksValidator('returnUrl', { min: 1, max: 2048 }),
91
+ sepa: IdValidator<IdSepa>(SepaModel.regex),
92
+ shippingAddress: IdValidator<IdAddress>(AddressModel.regex),
93
+ status: enumValidator(StatusEnum, false),
94
+ uniqueId: goldilocksValidator('uniqueId', { min: 1, max: 36 }),
95
+ wallet: true,
96
+ };
@@ -0,0 +1,123 @@
1
+ import { ApiEndpoint, baseHandler } from '#api/abstract-api-endpoint.js';
2
+ import { Http } from '#api/http/index.js';
3
+ import { RFC9557Handler } from '#core/common/handler/date-handler.js';
4
+ import { enumHandler } from '#core/common/handler/enum-handler.js';
5
+ import { defaultHandler } from '#core/common/handler/handler.js';
6
+ import { IdHandler } from '#core/common/handler/id-handler.js';
7
+ import { PaymentApiEndpoint, methodsAllowedHandler } from '#payment/api-endpoint.js';
8
+ import { CurrencyEnum } from '#payment/enum/currency.js';
9
+ import { type IdPayment, type PaymentAmount, PaymentModel } from '#payment/model.js';
10
+ import { paymentValidator } from '#payment/validator.js';
11
+ import { RefundApiEndpoint } from '#refund/api-endpoint.js';
12
+ import { type RefundAmount, RefundModel } from '#refund/model.js';
13
+ import { refundValidator } from '#refund/validator.js';
14
+
15
+ import { AddressModel, type IdAddress } from '../address/model.js';
16
+ import { CardModel, type IdCard } from '../card/model.js';
17
+ import { CustomerModel, type IdCustomer } from '../customer/model.js';
18
+ import { type IdSepa, SepaModel } from '../sepa/model.js';
19
+ import { PaymentIntentStatusEnum } from './enum/status.js';
20
+ import { ThreeDSEnum } from './enum/threeds.js';
21
+ import { type IdPaymentIntent, type PaymentIntentData, PaymentIntentModel } from './model.js';
22
+
23
+ export interface PaymentIntentEndpoint extends ApiEndpoint<PaymentIntentData> {
24
+ refunds: (id: IdPaymentIntent) => Promise<RefundModel[]>;
25
+ payments: (id: IdPaymentIntent) => Promise<PaymentModel[]>;
26
+ capture: (id: IdPaymentIntent) => Promise<Partial<PaymentIntentData>>;
27
+ refund: (id: IdPaymentIntent, amount: RefundAmount) => Promise<Partial<PaymentIntentData>>;
28
+ }
29
+
30
+ export class PaymentIntentApiEndpoint extends ApiEndpoint<PaymentIntentData> {
31
+ public _handler = {
32
+ ...baseHandler('created_at'),
33
+ id: IdHandler<IdPaymentIntent>(PaymentIntentModel.regex),
34
+ amount: defaultHandler<PaymentAmount>('number', { postRequired: true }),
35
+ billingAddress: IdHandler<IdAddress>(AddressModel.regex, { postable: true }),
36
+ card: IdHandler<IdCard>(CardModel.regex, { postable: true }),
37
+ capture: defaultHandler<PaymentIntentData['capture']>('boolean', {}),
38
+ currency: enumHandler(CurrencyEnum, { postable: true, postRequired: true }),
39
+ customer: IdHandler<IdCustomer>(CustomerModel.regex, { postable: true, patchable: true }),
40
+ dateBank: RFC9557Handler({ postable: false, patchable: false }),
41
+ dateSettlement: RFC9557Handler({}),
42
+ description: defaultHandler<PaymentIntentData['description']>('string'),
43
+ metadata: defaultHandler<PaymentIntentData['metadata']>('string'),
44
+ methodsAllowed: methodsAllowedHandler,
45
+ orderId: defaultHandler<PaymentIntentData['orderId']>('string'),
46
+ origin: defaultHandler<PaymentIntentData['origin']>('string', { postable: false, patchable: false }),
47
+ payment: IdHandler<IdPayment>(PaymentModel.regex, { postable: false, patchable: false }),
48
+ returnUrl: defaultHandler<PaymentIntentData['returnUrl']>('string'),
49
+ sepa: IdHandler<IdSepa>(SepaModel.regex, { postable: true }),
50
+ shippingAddress: IdHandler<IdAddress>(AddressModel.regex, { postable: true }),
51
+ status: enumHandler(PaymentIntentStatusEnum, { postable: false, patchable: false }),
52
+ threeds: enumHandler(ThreeDSEnum),
53
+ uniqueId: defaultHandler<PaymentIntentData['uniqueId']>('string'),
54
+ url: defaultHandler<PaymentIntentData['url']>('string'),
55
+ };
56
+
57
+ constructor() {
58
+ super({
59
+ name: 'payment_intents',
60
+ });
61
+ }
62
+
63
+ public async capture(id: IdPaymentIntent): Promise<Partial<PaymentIntentData>> {
64
+ return this._httpClient
65
+ .makeRequest(
66
+ Http.createRequest({
67
+ url: `${this._getResourceUri(id)}/capture`,
68
+ method: 'POST',
69
+ authenticated: true,
70
+ }),
71
+ )
72
+ .then(Http.transformResponseToData<Record<string, unknown>>)
73
+ .then(this.deserializeResource);
74
+ }
75
+
76
+ public async payments(id: IdPaymentIntent): Promise<PaymentModel[]> {
77
+ return this._httpClient
78
+ .makeRequest(
79
+ Http.createRequest({
80
+ url: `${this._getResourceUri(id)}/payments`,
81
+ method: 'GET',
82
+ authenticated: true,
83
+ }),
84
+ )
85
+ .then(Http.transformResponseToData<Record<string, unknown>[]>)
86
+ .then((payments) =>
87
+ Object.values(payments).map(
88
+ (data) => new PaymentModel(paymentValidator, new PaymentApiEndpoint().deserializeResource(data)),
89
+ ),
90
+ );
91
+ }
92
+
93
+ public async refund(id: IdPaymentIntent, amount: RefundAmount): Promise<Partial<PaymentIntentData>> {
94
+ return this._httpClient
95
+ .makeRequest(
96
+ Http.createRequest({
97
+ url: `${this._getResourceUri(id)}/refunds`,
98
+ method: 'POST',
99
+ authenticated: true,
100
+ body: JSON.stringify({ amount }),
101
+ }),
102
+ )
103
+ .then(Http.transformResponseToData<Record<string, unknown>>)
104
+ .then(this.deserializeResource);
105
+ }
106
+
107
+ public async refunds(id: IdPaymentIntent): Promise<RefundModel[]> {
108
+ return this._httpClient
109
+ .makeRequest(
110
+ Http.createRequest({
111
+ url: `${this._getResourceUri(id)}/refunds`,
112
+ method: 'GET',
113
+ authenticated: true,
114
+ }),
115
+ )
116
+ .then(Http.transformResponseToData<Record<string, unknown>[]>)
117
+ .then((refunds) =>
118
+ Object.values(refunds).map(
119
+ (data) => new RefundModel(refundValidator, new RefundApiEndpoint().deserializeResource(data)),
120
+ ),
121
+ );
122
+ }
123
+ }