@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,27 @@
1
+ import type { IdValue } from '../branded-type.js';
2
+ import { isValidID } from '../id-validator.js';
3
+ import { type AccessRight, type Handler, defaultSerialize, setAccess } from './handler.js';
4
+
5
+ export const IdHandler = <ID extends IdValue>(regex: RegExp, access?: Partial<AccessRight>): Handler<ID> => {
6
+ return {
7
+ deserialize: (id: unknown) => {
8
+ if (typeof id === 'string' && isValidID<ID>(id, regex)) {
9
+ return id;
10
+ }
11
+
12
+ if (typeof id === 'object' && id !== null && Object.hasOwn(id, 'id')) {
13
+ const data = id as { id: string };
14
+
15
+ if (isValidID<ID>(data.id, regex)) {
16
+ return data.id;
17
+ }
18
+ }
19
+
20
+ return undefined;
21
+ },
22
+ serialize: defaultSerialize,
23
+ ...setAccess(
24
+ access ?? { gettable: true, postable: false, patchable: false, postRequired: false, patchRequired: false },
25
+ ),
26
+ };
27
+ };
@@ -0,0 +1,23 @@
1
+ import { StancerValidationError } from '#core/error/validation-error.js';
2
+
3
+ import type { IdValue } from './branded-type.js';
4
+
5
+ export const ID_SUFFIX_LENGTH = 24;
6
+
7
+ export const isValidID = <ID extends IdValue>(id: string, regex: RegExp): id is ID => regex.test(id);
8
+ export const IdErrorMessage = (value: string, regex: RegExp) => `The id (${value}) doesn't match the pattern ${regex}`;
9
+
10
+ export const IdValidator = <Id extends IdValue>(regex: RegExp) => {
11
+ return {
12
+ validate: (arg0: string): arg0 is Id => isValidID<Id>(arg0, regex),
13
+ errorMessage: (value: string) => IdErrorMessage(value, regex),
14
+ };
15
+ };
16
+
17
+ export const validateID = <ID extends IdValue>(id: string, regex: RegExp) => {
18
+ if (isValidID<ID>(id, regex)) {
19
+ return id;
20
+ }
21
+
22
+ throw new StancerValidationError(IdErrorMessage(id, regex));
23
+ };
@@ -0,0 +1,49 @@
1
+ import type { ModelType } from '#core/abstract-model.js';
2
+ import type { ValidationFunction } from '#core/validator.js';
3
+
4
+ const inMutation = <T extends object>(mutations: T, key: string | number | symbol): key is keyof T => {
5
+ return Object.hasOwn(mutations, key);
6
+ };
7
+
8
+ export type MutationTrackedObject<T extends Partial<ModelType>> = T & {
9
+ getMutations(): Partial<T>;
10
+ toRaw(): T;
11
+ };
12
+ export const trackObjectMutations = <T extends ModelType>(
13
+ data: Partial<T>,
14
+ validator: ValidationFunction<T>,
15
+ ): MutationTrackedObject<T> => {
16
+ const mutations: Partial<T> = {};
17
+ const handler: ProxyHandler<T> = {
18
+ deleteProperty(target, key: string | symbol) {
19
+ if (inMutation(mutations, key)) {
20
+ mutations[key] = undefined;
21
+ }
22
+ return Reflect.deleteProperty(target, key);
23
+ },
24
+ get(target, key, receiver) {
25
+ if (key === 'getMutations') {
26
+ return () => ({ ...mutations });
27
+ }
28
+ if (key === 'toRaw') {
29
+ return () => target;
30
+ }
31
+ return Reflect.get(target, key, receiver);
32
+ },
33
+ set(target, key: string | symbol, value, receiver) {
34
+ if (typeof key === 'symbol') {
35
+ return Reflect.set(target, key, value, receiver);
36
+ }
37
+ const oldValue = Reflect.get(target, key, receiver);
38
+ if (oldValue === undefined || oldValue !== value) {
39
+ // validator throw error on fail
40
+ validator(key as keyof T, value);
41
+ mutations[key as keyof T] = value;
42
+ }
43
+ return Reflect.set(target, key, value, receiver);
44
+ },
45
+ };
46
+
47
+ // We redefine getMutations & toRaw in handler get. Proxy has getMutations & toRaw
48
+ return new Proxy(data, handler) as MutationTrackedObject<T>;
49
+ };
@@ -0,0 +1,43 @@
1
+ import type { Url } from 'url';
2
+
3
+ import type { IdValue } from './common/branded-type.js';
4
+
5
+ export interface ListParams {
6
+ filters: Record<string, unknown>;
7
+ limit: number;
8
+ start: number;
9
+ end: number;
10
+ }
11
+
12
+ export type EndpointGenerator<Data> = AsyncIterableIterator<Partial<Data>, void, Partial<Data>>;
13
+ export interface EndpointInterface<Data> {
14
+ /**
15
+ * Delete the object with specific id in the API
16
+ * @param id The Id of the object we want to delete
17
+ * @returns The response of the API
18
+ */
19
+ delete: (id: IdValue) => Promise<Partial<Data>>;
20
+
21
+ /**
22
+ * Get an object from the API
23
+ * @param id The Id of the object we want to get
24
+ * @returns The data of an object
25
+ */
26
+ get: (id: IdValue) => Promise<Partial<Data>>;
27
+
28
+ /**
29
+ * Get a list of object from the API
30
+ * @param params The params of the listing
31
+ * @param endpoint A custom url for specific subObject
32
+ * @returns A generator of object Data
33
+ */
34
+ list: (params: Partial<ListParams>, endpoint?: Url) => EndpointGenerator<Data>;
35
+
36
+ /**
37
+ * Sent an object to the API
38
+ * @param id The ID of the object
39
+ * @param mutations The data to be sent to our API
40
+ * @returns The new data of the object.
41
+ */
42
+ send: (id: IdValue | undefined, mutations: Partial<Data>) => Promise<Partial<Data>>;
43
+ }
@@ -0,0 +1 @@
1
+ export class StancerError extends Error {}
@@ -0,0 +1,7 @@
1
+ import { StancerApiError } from './api-error.js';
2
+
3
+ export class StancerApiConflictError extends StancerApiError {
4
+ constructor(message?: string) {
5
+ super(409, message ?? 'Conflict');
6
+ }
7
+ }
@@ -0,0 +1,10 @@
1
+ import { StancerError } from '../../base-error.js';
2
+
3
+ export class StancerApiError extends StancerError {
4
+ constructor(
5
+ public httpStatus: number,
6
+ message: string,
7
+ ) {
8
+ super(message);
9
+ }
10
+ }
@@ -0,0 +1,7 @@
1
+ import { StancerApiError } from './api-error.js';
2
+
3
+ export class StancerApiNotFoundError extends StancerApiError {
4
+ constructor(message?: string) {
5
+ super(404, message ?? 'Not Found');
6
+ }
7
+ }
@@ -0,0 +1,7 @@
1
+ import { StancerApiError } from './api-error.js';
2
+
3
+ export class StancerApiUnauthorizedError extends StancerApiError {
4
+ constructor(message?: string) {
5
+ super(401, message ?? 'Unauthorized');
6
+ }
7
+ }
@@ -0,0 +1,7 @@
1
+ import { StancerApiError } from './api-error.js';
2
+
3
+ export class StancerApiUnknownError extends StancerApiError {
4
+ constructor(code?: number, message?: string) {
5
+ super(code ?? 500, message ?? 'Unknown Error');
6
+ }
7
+ }
@@ -0,0 +1,13 @@
1
+ import { StancerApiError } from './api-error.js';
2
+
3
+ export interface StancerApiValidationErrorDetails {
4
+ loc: (string | number)[];
5
+ msg: string;
6
+ type: string;
7
+ }
8
+
9
+ export class StancerApiValidationError extends StancerApiError {
10
+ constructor(public details?: StancerApiValidationErrorDetails[]) {
11
+ super(422, details ? `Validation failed: ${JSON.stringify(details)}` : 'Payload cannot be validated');
12
+ }
13
+ }
@@ -0,0 +1,6 @@
1
+ export * from './api-conflict-error.js';
2
+ export * from './api-error.js';
3
+ export * from './api-not-found-error.js';
4
+ export * from './api-unauthorized-error.js';
5
+ export * from './api-unknown-error.js';
6
+ export * from './api-validation-error.js';
@@ -0,0 +1,8 @@
1
+ import { StancerError } from '../base-error.js';
2
+
3
+ export class StancerRouteInaccessibleError extends StancerError {
4
+ constructor(verb: 'POST' | 'PATCH' | 'LIST' | 'DELETE', resource: string, error?: ErrorOptions) {
5
+ const message = `${verb} is not allowed for ${resource} resource`;
6
+ super(message, error);
7
+ }
8
+ }
@@ -0,0 +1,3 @@
1
+ import { StancerError } from './base-error.js';
2
+
3
+ export class StancerUnpopulatedError extends StancerError {}
@@ -0,0 +1,3 @@
1
+ import { StancerError } from './base-error.js';
2
+
3
+ export class UnsendableError extends StancerError {}
@@ -0,0 +1,3 @@
1
+ import { StancerError } from './base-error.js';
2
+
3
+ export class StancerValidationError extends StancerError {}
@@ -0,0 +1,129 @@
1
+ import { Temporal } from 'temporal-polyfill';
2
+
3
+ import { StancerValidationError } from './error/validation-error.js';
4
+
5
+ //#region Types
6
+
7
+ interface ValidatorObject<Property> {
8
+ errorMessage: (value: string) => string;
9
+ validate: (value: Property) => boolean;
10
+ }
11
+
12
+ /**
13
+ * Validator configuration mapping each property to either a ValidatorObject or true (pass-through).
14
+ */
15
+ export type Validator<ValidationData> = {
16
+ [Property in keyof ValidationData]: ValidatorObject<ValidationData[Property]> | true;
17
+ };
18
+
19
+ /**
20
+ * Validation function that validates a single property value.
21
+ * @returns true if valid
22
+ * @throws {StancerValidationError} if invalid
23
+ */
24
+ export type ValidationFunction<Data> = <Key extends keyof Data>(key: Key, value: Data[Key]) => true | never;
25
+
26
+ interface ExactSize {
27
+ size: number;
28
+ min?: undefined;
29
+ max?: undefined;
30
+ }
31
+
32
+ interface BorderedSize {
33
+ min: number;
34
+ max: number;
35
+ size?: undefined;
36
+ }
37
+
38
+ type GoldilocksSize = ExactSize | BorderedSize;
39
+
40
+ //#endregion
41
+
42
+ //#region Core Validation Logic
43
+
44
+ /**
45
+ * Creates a validation function from a validator configuration.
46
+ */
47
+ export const processValidator = <Data>(validator: Validator<Data>): ValidationFunction<Data> => {
48
+ return (key, value) => {
49
+ const rule = validator[key];
50
+
51
+ if (!rule || rule === true) {
52
+ return true;
53
+ }
54
+
55
+ if (!rule.validate(value)) {
56
+ throw new StancerValidationError(rule.errorMessage(String(value)));
57
+ }
58
+
59
+ return true;
60
+ };
61
+ };
62
+
63
+ //#endregion
64
+
65
+ //#region Validator Factories
66
+
67
+ /**
68
+ * Pass-through validator that accepts any value without validation.
69
+ * Use for fields like createdAt that are set server-side.
70
+ */
71
+ export const createdAtValidator = true;
72
+
73
+ /**
74
+ * Creates a string length validator with exact size or min/max bounds.
75
+ * @throws {StancerValidationError} At creation time if configuration is invalid
76
+ */
77
+ export const goldilocksValidator = (propertyName: string, { max, min, size }: GoldilocksSize) => {
78
+ const hasExactSize = size !== undefined || (max !== undefined && max === min);
79
+ const hasBoundedSize = min !== undefined && max !== undefined && min <= max;
80
+
81
+ if (hasExactSize) {
82
+ const exactLength = size ?? max;
83
+ return {
84
+ errorMessage: (value: string) => `${value} of ${propertyName} must be exactly ${exactLength} characters`,
85
+ validate: (value: string) => value.length === exactLength,
86
+ };
87
+ }
88
+
89
+ if (hasBoundedSize) {
90
+ return {
91
+ errorMessage: (value: string) => `${value} of ${propertyName} must be between ${min} and ${max} characters`,
92
+ validate: (value: string) => value.length >= min && value.length <= max,
93
+ };
94
+ }
95
+
96
+ throw new StancerValidationError(
97
+ `goldilocksValidator for ${propertyName} requires either a size parameter or both min and max parameters`,
98
+ );
99
+ };
100
+
101
+ /**
102
+ * Creates an enum validator for string union types.
103
+ * @param strict - When false and not in DEBUG mode, bypasses validation to prevent SDK crashes
104
+ * when API adds new enum values unknown to the SDK.
105
+ */
106
+ export const enumValidator = <Enum extends readonly string[]>(values: Enum, strict: boolean = true) => {
107
+ if (!strict && process.env['DEBUG'] !== 'true') {
108
+ return true;
109
+ }
110
+
111
+ return {
112
+ validate: (value: unknown): value is (typeof values)[number] =>
113
+ typeof value === 'string' && values.includes(value as (typeof values)[number]),
114
+ errorMessage: (value: string) => `Expected one of ${values.join(', ')}. Got ${value}`,
115
+ };
116
+ };
117
+
118
+ /**
119
+ * Creates a PlainDate validator ensuring the date is between 1971 and today.
120
+ */
121
+ export const plainDateValidator = (field: string) => {
122
+ return {
123
+ validate: (value: Temporal.PlainDate) =>
124
+ value.year > 1970 && Temporal.PlainDate.compare(Temporal.Now.plainDateISO(), value) === 1,
125
+ errorMessage: () => `${field} must be a date between 1971 and now.`,
126
+ };
127
+ };
128
+
129
+ //#endregion
@@ -0,0 +1,29 @@
1
+ import { AddressModel, type IdAddress } from '#address/model.js';
2
+ import { ApiEndpoint, baseHandler } from '#api/abstract-api-endpoint.js';
3
+ import { RFC9557Handler } from '#core/common/handler/date-handler.js';
4
+ import { defaultHandler } from '#core/common/handler/handler.js';
5
+ import { IdHandler } from '#core/common/handler/id-handler.js';
6
+
7
+ import { type CustomerData, CustomerModel, type IdCustomer } from './model.js';
8
+
9
+ export class CustomerApiEndpoint extends ApiEndpoint<CustomerData> {
10
+ protected _handler = {
11
+ ...baseHandler('created'),
12
+ id: IdHandler<IdCustomer>(CustomerModel.regex),
13
+ billingAddress: IdHandler<IdAddress>(AddressModel.regex, { gettable: true, postable: true, patchable: true }),
14
+ country: defaultHandler<CustomerData['country']>('string'),
15
+ dateBirth: RFC9557Handler({}),
16
+ email: defaultHandler<CustomerData['email']>('string', { postRequired: 'partial' }),
17
+ externalId: defaultHandler<CustomerData['externalId']>('string'),
18
+ legalId: defaultHandler<CustomerData['legalId']>('string'),
19
+ mobile: defaultHandler<CustomerData['mobile']>('string', { postRequired: 'partial' }),
20
+ name: defaultHandler<CustomerData['name']>('string'),
21
+ shippingAddress: IdHandler<IdAddress>(AddressModel.regex, { gettable: true, postable: true, patchable: true }),
22
+ };
23
+
24
+ constructor() {
25
+ super({
26
+ name: 'customers',
27
+ });
28
+ }
29
+ }
@@ -0,0 +1,113 @@
1
+ import type { IdAddress } from '#address/model.js';
2
+ import { AbstractModel, type ModelType } from '#core/abstract-model.js';
3
+ import type { IdValue } from '#core/common/branded-type.js';
4
+ import { validateID } from '#core/common/id-validator.js';
5
+
6
+ export type IdCustomer = IdValue<`cust_${string}`>;
7
+ export const idCustomer = (id: string) => validateID<IdCustomer>(id, CustomerModel.regex);
8
+
9
+ export interface CustomerData extends ModelType {
10
+ id: IdCustomer;
11
+ country: string;
12
+ dateBirth: Temporal.PlainDate;
13
+ email: string;
14
+ externalId: string;
15
+ legalId: string;
16
+ mobile: string;
17
+ name: string;
18
+ billingAddress: IdAddress;
19
+ shippingAddress: IdAddress;
20
+ }
21
+
22
+ export class CustomerModel extends AbstractModel<CustomerData> {
23
+ static regex = /^cust_[a-zA-Z0-9]{24}$/;
24
+
25
+ //#region Getters
26
+
27
+ get billingAddress() {
28
+ return this._data.billingAddress;
29
+ }
30
+
31
+ get country() {
32
+ return this._data.country;
33
+ }
34
+
35
+ get dateBirth() {
36
+ return this._data.dateBirth;
37
+ }
38
+
39
+ get email() {
40
+ return this._data.email;
41
+ }
42
+
43
+ get externalId() {
44
+ return this._data.externalId;
45
+ }
46
+
47
+ get legalId() {
48
+ return this._data.legalId;
49
+ }
50
+
51
+ get mobile() {
52
+ return this._data.mobile;
53
+ }
54
+
55
+ get name() {
56
+ return this._data.name;
57
+ }
58
+
59
+ get shippingAddress() {
60
+ return this._data.shippingAddress;
61
+ }
62
+
63
+ //#endregion
64
+
65
+ //#region Setters
66
+
67
+ setBillingAddress(value: IdAddress) {
68
+ this._data.billingAddress = value;
69
+ return this;
70
+ }
71
+
72
+ setCountry(value: string) {
73
+ this._data.country = value;
74
+ return this;
75
+ }
76
+
77
+ setDateBirth(value: Temporal.PlainDate) {
78
+ this._data.dateBirth = value;
79
+ return this;
80
+ }
81
+
82
+ setEmail(value: string) {
83
+ this._data.email = value;
84
+ return this;
85
+ }
86
+
87
+ setExternalId(value: string) {
88
+ this._data.externalId = value;
89
+ return this;
90
+ }
91
+
92
+ setLegalId(value: string) {
93
+ this._data.legalId = value;
94
+ return this;
95
+ }
96
+
97
+ setMobile(value: string) {
98
+ this._data.mobile = value;
99
+ return this;
100
+ }
101
+
102
+ setName(value: string) {
103
+ this._data.name = value;
104
+ return this;
105
+ }
106
+
107
+ setShippingAddress(value: IdAddress) {
108
+ this._data.shippingAddress = value;
109
+ return this;
110
+ }
111
+
112
+ //#endregion
113
+ }
@@ -0,0 +1,14 @@
1
+ import { AbstractRepository, type Repository } from '#core/abstract-repository.js';
2
+ import type { EndpointInterface } from '#core/endpoint-interface.js';
3
+ import { CustomerApiEndpoint } from '#customer/api-endpoint.js';
4
+ import { type CustomerData, CustomerModel } from '#customer/model.js';
5
+ import { customerValidator } from '#customer/validator.js';
6
+
7
+ export class CustomerRepository
8
+ extends AbstractRepository<CustomerData, CustomerModel>
9
+ implements Repository<CustomerData, CustomerModel>
10
+ {
11
+ constructor(endpoint?: EndpointInterface<CustomerData>) {
12
+ super({ endpoint: endpoint ?? new CustomerApiEndpoint(), validator: customerValidator, model: CustomerModel });
13
+ }
14
+ }
@@ -0,0 +1,26 @@
1
+ import { Temporal } from 'temporal-polyfill';
2
+
3
+ import { AddressModel, type IdAddress } from '#address/model.js';
4
+ import { IdValidator } from '#core/common/id-validator.js';
5
+ import { type Validator, createdAtValidator, goldilocksValidator } from '#core/validator.js';
6
+
7
+ import { type CustomerData, CustomerModel, type IdCustomer } from './model.js';
8
+
9
+ export const customerValidator: Validator<CustomerData> = {
10
+ id: IdValidator<IdCustomer>(CustomerModel.regex),
11
+ billingAddress: IdValidator<IdAddress>(AddressModel.regex),
12
+ country: goldilocksValidator('country', { size: 2 }),
13
+ createdAt: createdAtValidator,
14
+ dateBirth: {
15
+ validate: (arg0: Temporal.PlainDate) =>
16
+ arg0 instanceof Temporal.PlainDate && Temporal.PlainDate.compare(Temporal.Now.plainDateISO(), arg0) === 1,
17
+ errorMessage: (arg0) => `DateBirth ${arg0.toString()} must be a Temporal.PlainDate set in the past.`,
18
+ },
19
+ deleted: true,
20
+ email: goldilocksValidator('email', { min: 1, max: 64 }),
21
+ externalId: goldilocksValidator('externalId', { min: 1, max: 36 }),
22
+ legalId: goldilocksValidator('legalId', { min: 1, max: 16 }),
23
+ mobile: goldilocksValidator('mobile', { min: 1, max: 16 }),
24
+ name: goldilocksValidator('name', { min: 1, max: 64 }),
25
+ shippingAddress: IdValidator<IdAddress>(AddressModel.regex),
26
+ };
@@ -0,0 +1,118 @@
1
+ import { ApiEndpoint, baseHandler } from '#api/abstract-api-endpoint.js';
2
+ import { Http } from '#api/http/index.js';
3
+ import { RFC9557Handler, timestampHandler } from '#core/common/handler/date-handler.js';
4
+ import { enumHandler } from '#core/common/handler/enum-handler.js';
5
+ import { type Handler, defaultHandler, setAccess } from '#core/common/handler/handler.js';
6
+ import { IdHandler } from '#core/common/handler/id-handler.js';
7
+ import { RefundApiEndpoint } from '#refund/api-endpoint.js';
8
+ import { RefundModel } from '#refund/model.js';
9
+ import { refundValidator } from '#refund/validator.js';
10
+
11
+ import { AddressModel, type IdAddress } from '../address/model.js';
12
+ import { CardModel, type IdCard } from '../card/model.js';
13
+ import { CustomerModel, type IdCustomer } from '../customer/model.js';
14
+ import { type IdPaymentIntent, PaymentIntentModel } from '../payment-intent/model.js';
15
+ import { type IdPayout, PayoutModel } from '../payout/model.js';
16
+ import { type IdSepa, SepaModel } from '../sepa/model.js';
17
+ import { CurrencyEnum } from './enum/currency.js';
18
+ import { type Method, MethodEnum } from './enum/method.js';
19
+ import { StatusEnum } from './enum/status.js';
20
+ import { type Device, type IdPayment, type PaymentAmount, type PaymentData, PaymentModel } from './model.js';
21
+
22
+ const authHandler: Handler<boolean> = {
23
+ deserialize: (arg0: unknown): boolean | undefined => {
24
+ if (arg0) {
25
+ return true;
26
+ }
27
+ return undefined;
28
+ },
29
+ serialize: (arg0: boolean) => {
30
+ if (arg0 === false) {
31
+ return undefined;
32
+ }
33
+ return true;
34
+ },
35
+ ...setAccess({}),
36
+ };
37
+ export const methodsAllowedHandler: Handler<Method[]> = {
38
+ deserialize: (arg0: unknown) => {
39
+ if (!Array.isArray(arg0)) {
40
+ return undefined;
41
+ }
42
+ return arg0
43
+ .map((value) => (MethodEnum.includes(value) ? value : undefined))
44
+ .filter((value) => value !== undefined) as Method[];
45
+ },
46
+ serialize: (arg0: Method[]) => {
47
+ return arg0;
48
+ },
49
+ ...setAccess({}),
50
+ };
51
+ const deviceHandler: Handler<Device> = {
52
+ deserialize: (arg0: unknown) => (arg0 as Device) ?? undefined,
53
+ serialize: (arg0: Device) => arg0,
54
+ ...setAccess({}),
55
+ };
56
+ export class PaymentApiEndpoint extends ApiEndpoint<PaymentData> {
57
+ public _handler = {
58
+ ...baseHandler('created'),
59
+ id: IdHandler<IdPayment>(PaymentModel.regex),
60
+ amount: defaultHandler<PaymentAmount>('number', { postRequired: true }),
61
+ auth: authHandler,
62
+ billingAddress: IdHandler<IdAddress>(AddressModel.regex, { postable: true }),
63
+ card: IdHandler<IdCard>(CardModel.regex, { postable: true }),
64
+ capture: defaultHandler<PaymentData['capture']>('boolean', {}),
65
+ currency: enumHandler(CurrencyEnum, { postable: true, postRequired: true }),
66
+ customer: IdHandler<IdCustomer>(CustomerModel.regex, { postable: true, patchable: true }),
67
+ dateBank: RFC9557Handler({ postable: false, patchable: false }),
68
+ datePayment: timestampHandler({ postable: false, patchable: false }, 'date_paym'),
69
+ dateSettlement: RFC9557Handler({}),
70
+ description: defaultHandler<PaymentData['description']>('string'),
71
+ device: deviceHandler,
72
+ fee: defaultHandler<PaymentData['fee']>('number', { postable: false, patchable: false }),
73
+ method: enumHandler(MethodEnum, { postable: false, patchable: false }),
74
+ methodsAllowed: methodsAllowedHandler,
75
+ orderId: defaultHandler<PaymentData['orderId']>('string'),
76
+ origin: defaultHandler<PaymentData['origin']>('string', { postable: false, patchable: false }),
77
+ paymentIntent: IdHandler<IdPaymentIntent>(PaymentIntentModel.regex, { postable: false, patchable: false }),
78
+ payout: IdHandler<IdPayout>(PayoutModel.regex, { postable: false, patchable: false }),
79
+ response: defaultHandler<PaymentData['response']>('string', { postable: false, patchable: false }),
80
+ responseAuthor: defaultHandler<PaymentData['responseAuthor']>('string', { postable: false, patchable: false }),
81
+ returnUrl: defaultHandler<PaymentData['returnUrl']>('string'),
82
+ sepa: IdHandler<IdSepa>(SepaModel.regex, { postable: true }),
83
+ shippingAddress: IdHandler<IdAddress>(AddressModel.regex, { postable: true }),
84
+ status: enumHandler(StatusEnum, { postable: false }),
85
+ uniqueId: defaultHandler<PaymentData['uniqueId']>('string', { patchable: false }),
86
+ wallet: defaultHandler<PaymentData['wallet']>('object', { gettable: false }),
87
+ };
88
+ private _refundApiEndpoint?: RefundApiEndpoint;
89
+ constructor(refundApiEndpoint?: RefundApiEndpoint) {
90
+ super({
91
+ name: 'payments',
92
+ });
93
+ if (refundApiEndpoint) {
94
+ this._refundApiEndpoint = refundApiEndpoint;
95
+ }
96
+ }
97
+
98
+ async refunds(id: IdPayment): Promise<RefundModel[]> {
99
+ if (this._refundApiEndpoint === undefined) {
100
+ this._refundApiEndpoint = new RefundApiEndpoint();
101
+ }
102
+ const refundEndpoint = this._refundApiEndpoint;
103
+ return this._httpClient
104
+ .makeRequest(
105
+ Http.createRequest({
106
+ url: `${this._getResourceUri(id)}/refunds`,
107
+ method: 'GET',
108
+ authenticated: true,
109
+ }),
110
+ )
111
+ .then(Http.transformResponseToData<Record<string, unknown>[]>)
112
+ .then((refunds) =>
113
+ Object.values(refunds).map(
114
+ (data) => new RefundModel(refundValidator, refundEndpoint.deserializeResource(data)),
115
+ ),
116
+ );
117
+ }
118
+ }