@infosoftas/s4-orders-js-sdk 0.2.0 → 0.2.2

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 (69) hide show
  1. package/.editorconfig +8 -8
  2. package/.release-it.json +10 -10
  3. package/README.md +27 -19
  4. package/build/postcss-scope-tailwind.cjs +0 -0
  5. package/components.json +0 -0
  6. package/package.json +1 -1
  7. package/src/App.completion.test.tsx +46 -107
  8. package/src/App.css +0 -14
  9. package/src/App.paymentReturn.test.tsx +341 -0
  10. package/src/App.tsx +22 -53
  11. package/src/ErrorBoundary.tsx +41 -41
  12. package/src/api/InvoiceApi.ts +23 -23
  13. package/src/api/SubscribeApi.ts +18 -18
  14. package/src/bundle.ts +4 -4
  15. package/src/components/Alert/Alert.tsx +23 -23
  16. package/src/components/Button/Button.tsx +39 -39
  17. package/src/components/EHFForm/EHFForm.tsx +1 -4
  18. package/src/components/FormFields/AddressField.tsx +55 -55
  19. package/src/components/FormFields/EmailField.tsx +53 -53
  20. package/src/components/FormFields/FormFields.helper.ts +34 -34
  21. package/src/components/FormFields/FormFieldsMapper.ts +34 -34
  22. package/src/components/FormFields/InputField.tsx +52 -52
  23. package/src/components/FormFields/NameField.tsx +52 -52
  24. package/src/components/FormFields/PhoneField.tsx +53 -53
  25. package/src/components/FormFields/TermsCheckbox.tsx +70 -70
  26. package/src/components/FormFields/ToggleFiled.tsx +52 -52
  27. package/src/components/FormFields/fieldValidators.ts +71 -71
  28. package/src/components/OIOForm/OIOForm.tsx +1 -4
  29. package/src/components/OrderDenialModal/OrderDenialModal.tsx +102 -102
  30. package/src/components/OrderForm/ContactDetailsSection.tsx +71 -71
  31. package/src/components/OrderForm/OrderForm.tsx +1 -4
  32. package/src/components/OrderForm/PaymentMethodContent.tsx +62 -62
  33. package/src/components/OrderForm/PaymentMethodSection.tsx +79 -79
  34. package/src/components/OrderForm/SubmitConfirmationDialog.tsx +55 -55
  35. package/src/components/OrderForm/orderFormState.ts +171 -171
  36. package/src/components/OrderForm/useSlotElement.tsx +89 -89
  37. package/src/components/ui/alert-dialog.tsx +0 -0
  38. package/src/components/ui/alert.tsx +0 -0
  39. package/src/components/ui/button.tsx +0 -0
  40. package/src/components/ui/card.tsx +0 -0
  41. package/src/components/ui/checkbox.tsx +0 -0
  42. package/src/components/ui/field.tsx +0 -0
  43. package/src/components/ui/input.tsx +0 -0
  44. package/src/components/ui/label.tsx +0 -0
  45. package/src/components/ui/radio-group.tsx +0 -0
  46. package/src/components/ui/separator.tsx +0 -0
  47. package/src/components/ui/skeleton.tsx +0 -0
  48. package/src/components/ui/spinner.tsx +0 -0
  49. package/src/components/ui/switch.tsx +0 -0
  50. package/src/components/ui/textarea.tsx +0 -0
  51. package/src/constants/index.ts +13 -13
  52. package/src/custom.d.ts +0 -0
  53. package/src/enums/api.ts +5 -5
  54. package/src/enums/general.ts +4 -2
  55. package/src/hooks/useOrderForm.test.tsx +86 -0
  56. package/src/hooks/useOrderForm.tsx +2 -5
  57. package/src/hooks/usePaymentReturn.tsx +139 -0
  58. package/src/hooks/useQueryParams.ts +5 -5
  59. package/src/index.tsx +30 -30
  60. package/src/lib/utils.ts +1 -1
  61. package/src/types/api.ts +28 -28
  62. package/src/types/general.ts +1 -2
  63. package/src/utils/helper.ts +78 -78
  64. package/src/utils/order.helper.test.ts +94 -0
  65. package/src/utils/order.helper.ts +41 -23
  66. package/tsconfig.json +1 -0
  67. package/src/components/MainIframe/MainIframe.tsx +0 -42
  68. package/src/hooks/useIframe.tsx +0 -59
  69. package/src/hooks/useMessageEvent.tsx +0 -194
@@ -1,13 +1,13 @@
1
- import { PaymentMethodEnum } from '../enums/general';
2
-
3
- export const BASE_API = '/';
4
-
5
- export const WRONG_MSG = 'Something went wrong!';
6
-
7
- export const PAYMENT_METHOD_DEFAULT: PaymentMethodEnum =
8
- PaymentMethodEnum.Vipps;
9
-
10
- export const INVOICE_ALLOWED_PAYMENT_METHODS = [
11
- PaymentMethodEnum.Email,
12
- PaymentMethodEnum.Invoice,
13
- ];
1
+ import { PaymentMethodEnum } from '../enums/general';
2
+
3
+ export const BASE_API = '/';
4
+
5
+ export const WRONG_MSG = 'Something went wrong!';
6
+
7
+ export const PAYMENT_METHOD_DEFAULT: PaymentMethodEnum =
8
+ PaymentMethodEnum.Vipps;
9
+
10
+ export const INVOICE_ALLOWED_PAYMENT_METHODS = [
11
+ PaymentMethodEnum.Email,
12
+ PaymentMethodEnum.Invoice,
13
+ ];
package/src/custom.d.ts CHANGED
File without changes
package/src/enums/api.ts CHANGED
@@ -1,5 +1,5 @@
1
- export enum HttpStatusCode {
2
- UNAUTHORIZED = 401,
3
- FORBIDDEN = 403,
4
- LIMIT = 429,
5
- }
1
+ export enum HttpStatusCode {
2
+ UNAUTHORIZED = 401,
3
+ FORBIDDEN = 403,
4
+ LIMIT = 429,
5
+ }
@@ -13,9 +13,11 @@ export enum MessageEventTypeEnum {
13
13
  ORDER_FLOW_COMPLETE = 'orderFlowComplete',
14
14
  ORDER_FLOW_CANCEL = 'orderFlowCancel',
15
15
  ORDER_UPDATE_INFO = 'orderUpdateInfo',
16
- VIPPS_COMPLETE = 'completeOrder',
17
- CANCEL = 'cancel',
16
+ }
17
+
18
+ export enum PaymentReturnActionEnum {
18
19
  COMPLETE = 'complete',
20
+ CANCEL = 'cancel',
19
21
  }
20
22
 
21
23
  export enum InvoiceLookupNetworkEnum {
@@ -0,0 +1,86 @@
1
+ // @vitest-environment jsdom
2
+
3
+ import { act, cleanup, renderHook } from '@testing-library/react';
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ import { orderStart } from '../api/OrdersApi';
7
+ import { PaymentMethodEnum } from '../enums/general';
8
+ import useOrderForm from './useOrderForm';
9
+
10
+ vi.mock('../api/OrdersApi', () => ({ orderStart: vi.fn() }));
11
+ vi.mock('../api/SubscribeApi', () => ({ createSubscriber: vi.fn() }));
12
+ vi.mock('../api/InvoiceApi', () => ({ invoiceLookup: vi.fn() }));
13
+
14
+ const renderOrderForm = (
15
+ submitStartCallback: (id: string) => void | Promise<void>,
16
+ callback = vi.fn()
17
+ ) =>
18
+ renderHook(() =>
19
+ useOrderForm({
20
+ callback,
21
+ submitStartCallback,
22
+ templatePackageId: 'template-1',
23
+ subscriberId: 'subscriber-1',
24
+ organizationId: 'organization-1',
25
+ language: 'en-US',
26
+ merchantAgreementUrl: 'https://shop.example.test/terms',
27
+ orderFields: [],
28
+ invoiceOrderFields: [],
29
+ })
30
+ );
31
+
32
+ const submit = (result: ReturnType<typeof renderOrderForm>['result']) =>
33
+ act(() =>
34
+ result.current.orderSubmit({
35
+ paymentMethod: PaymentMethodEnum.SwedbankPay,
36
+ })
37
+ );
38
+
39
+ describe('useOrderForm submitStartCallback', () => {
40
+ beforeEach(() => {
41
+ vi.mocked(orderStart).mockResolvedValue({
42
+ id: 'order-1',
43
+ terminalRedirectUrl: 'https://pay.example.test/terminal',
44
+ } as Awaited<ReturnType<typeof orderStart>>);
45
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
46
+ });
47
+
48
+ afterEach(() => {
49
+ cleanup();
50
+ vi.clearAllMocks();
51
+ vi.restoreAllMocks();
52
+ window.history.replaceState({}, '', '/');
53
+ });
54
+
55
+ it('waits for an async callback so its hashToken reaches the return URLs', async () => {
56
+ const { result } = renderOrderForm(async () => {
57
+ await new Promise((resolve) => setTimeout(resolve, 20));
58
+ window.history.replaceState({}, '', '/?hashToken=protected');
59
+ });
60
+
61
+ await submit(result);
62
+
63
+ const { paymentAgreement } = vi.mocked(orderStart).mock.calls[0][0];
64
+ const { completeUrl, cancelUrl } = paymentAgreement.swedbankPay ?? {};
65
+ expect(new URL(completeUrl as string).searchParams.get('hashToken')).toBe(
66
+ 'protected'
67
+ );
68
+ expect(new URL(cancelUrl as string).searchParams.get('hashToken')).toBe(
69
+ 'protected'
70
+ );
71
+ });
72
+
73
+ it('does not start the payment when the callback rejects', async () => {
74
+ const callback = vi.fn();
75
+ const { result } = renderOrderForm(
76
+ () => Promise.reject(new Error('token failed')),
77
+ callback
78
+ );
79
+
80
+ await submit(result);
81
+
82
+ expect(orderStart).not.toHaveBeenCalled();
83
+ expect(callback).toHaveBeenCalledWith(null);
84
+ expect(result.current.loading).toBe(false);
85
+ });
86
+ });
@@ -31,7 +31,7 @@ import {
31
31
 
32
32
  type Props = {
33
33
  callback: (url: string | null, orderInfo?: OrderInfoType | null) => void;
34
- submitStartCallback?: (id: string) => void;
34
+ submitStartCallback?: (id: string) => void | Promise<void>;
35
35
  userActionCallback?: (
36
36
  action: UserActionEnum,
37
37
  args: object | null | undefined
@@ -43,7 +43,6 @@ type Props = {
43
43
  identityProviderId?: string;
44
44
  organizationId: string;
45
45
  redirectUrl?: string;
46
- showIframe?: boolean;
47
46
  language: string;
48
47
  merchantAgreementUrl: string;
49
48
  paymentMethodsOptions?: PaymentMethodSettingsType;
@@ -115,7 +114,6 @@ const useOrderForm = ({
115
114
  identityProviderId,
116
115
  orderFields,
117
116
  redirectUrl,
118
- showIframe,
119
117
  language,
120
118
  merchantAgreementUrl,
121
119
  paymentMethodsOptions,
@@ -246,7 +244,7 @@ const useOrderForm = ({
246
244
  setContactCallback(contactModel);
247
245
  }
248
246
 
249
- submitStartCallback?.(id as string);
247
+ await submitStartCallback?.(id as string);
250
248
 
251
249
  if (id) {
252
250
  const paymentMethod =
@@ -259,7 +257,6 @@ const useOrderForm = ({
259
257
  const agreements = prepareAgreementModel({
260
258
  paymentMethod,
261
259
  redirectUrl,
262
- showIframe,
263
260
  phoneNumber: orderFields.find(
264
261
  (i) => i.name === 'phoneNumber'
265
262
  )
@@ -0,0 +1,139 @@
1
+ import { useEffect, useRef } from 'react';
2
+
3
+ import { PaymentMethodEnum, PaymentReturnActionEnum } from '../enums/general';
4
+ import type { CompleteOrderParamsType, OrderInfoType } from '../types/order';
5
+ import useQueryParams from './useQueryParams';
6
+
7
+ const MOLLIE_ORDER_TTL_MS = 20 * 60 * 1000;
8
+
9
+ // Reads and consumes the persisted Mollie order id. The key is always removed:
10
+ // the return leg gets one chance to use it, whether or not it is still valid.
11
+ const takeStoredMollieOrderId = (): string | null => {
12
+ const raw = sessionStorage.getItem('mollieOrderId');
13
+ if (!raw) {
14
+ return null;
15
+ }
16
+
17
+ sessionStorage.removeItem('mollieOrderId');
18
+
19
+ try {
20
+ const { id, ts } = JSON.parse(raw) as { id: string; ts: number };
21
+
22
+ return Date.now() - ts <= MOLLIE_ORDER_TTL_MS ? id : null;
23
+ } catch {
24
+ return null;
25
+ }
26
+ };
27
+
28
+ // Temporary, remove in the next release: checkouts started on the previous
29
+ // version open SwedbankPay in an iframe, so the provider returns inside that
30
+ // frame. A framed SDK renders nothing and no longer notifies the parent, so
31
+ // hand the return to the top-level page, which then handles it once.
32
+ const breakOutOfLegacyPaymentFrame = (): boolean => {
33
+ if (!window.top || window.top === window) {
34
+ return false;
35
+ }
36
+ try {
37
+ if (window.top.location.origin !== window.location.origin) {
38
+ return false;
39
+ }
40
+ window.top.location.replace(window.location.href);
41
+ return true;
42
+ } catch {
43
+ return false;
44
+ }
45
+ };
46
+
47
+ const usePaymentReturn = (
48
+ onPaymentComplete: (data: CompleteOrderParamsType) => Promise<void>,
49
+ onPaymentCancel: (orderId?: string) => void,
50
+ orderInfo: OrderInfoType | null
51
+ ) => {
52
+ const queryParams = useQueryParams();
53
+ const isBreakingOut = useRef(false);
54
+ const hasPaymentReturn =
55
+ queryParams.get('action') === PaymentReturnActionEnum.COMPLETE ||
56
+ queryParams.get('action') === PaymentReturnActionEnum.CANCEL ||
57
+ (!!queryParams.get('orderId') && !!queryParams.get('agreementId'));
58
+
59
+ useEffect(() => {
60
+ if (hasPaymentReturn) {
61
+ isBreakingOut.current = breakOutOfLegacyPaymentFrame();
62
+ }
63
+ }, [hasPaymentReturn]);
64
+
65
+ // Vipps / MobilePay
66
+ useEffect(() => {
67
+ if (isBreakingOut.current) {
68
+ return;
69
+ }
70
+ if (queryParams.get('orderId') && queryParams.get('agreementId')) {
71
+ onPaymentComplete({
72
+ orderId: queryParams.get('orderId') || '',
73
+ agreementId: queryParams.get('agreementId') || '',
74
+ orderInfo: orderInfo || null,
75
+ paymentMethod: PaymentMethodEnum.Vipps,
76
+ });
77
+ }
78
+ }, [queryParams.get('orderId'), queryParams.get('agreementId')]);
79
+
80
+ // SwedbankPay completion, and cancellation for every redirect provider
81
+ useEffect(() => {
82
+ if (isBreakingOut.current) {
83
+ return;
84
+ }
85
+ if (
86
+ queryParams.get('S4OrderId') &&
87
+ queryParams.get('TransactionId') &&
88
+ queryParams.get('action') === PaymentReturnActionEnum.COMPLETE
89
+ ) {
90
+ onPaymentComplete({
91
+ orderId: queryParams.get('S4OrderId') || '',
92
+ agreementId: queryParams.get('TransactionId') || '',
93
+ orderInfo: orderInfo || null,
94
+ });
95
+ }
96
+
97
+ if (queryParams.get('action') === PaymentReturnActionEnum.CANCEL) {
98
+ const cancelOrderId =
99
+ queryParams.get('S4OrderId') || takeStoredMollieOrderId();
100
+ onPaymentCancel(cancelOrderId || undefined);
101
+ }
102
+ }, [
103
+ queryParams.get('action'),
104
+ queryParams.get('S4OrderId'),
105
+ queryParams.get('TransactionId'),
106
+ ]);
107
+
108
+ // Mollie: a completion return with no TransactionId (that one is SwedbankPay's).
109
+ useEffect(() => {
110
+ if (isBreakingOut.current) {
111
+ return;
112
+ }
113
+ if (
114
+ queryParams.get('action') !== PaymentReturnActionEnum.COMPLETE ||
115
+ queryParams.get('TransactionId')
116
+ ) {
117
+ return;
118
+ }
119
+
120
+ const s4OrderId = queryParams.get('S4OrderId');
121
+ const storedOrderId = takeStoredMollieOrderId();
122
+ const mollieOrderId = s4OrderId || storedOrderId;
123
+ if (!mollieOrderId) {
124
+ return;
125
+ }
126
+
127
+ onPaymentComplete({
128
+ orderId: mollieOrderId,
129
+ agreementId: '',
130
+ orderInfo: orderInfo || null,
131
+ });
132
+ }, [
133
+ queryParams.get('action'),
134
+ queryParams.get('S4OrderId'),
135
+ queryParams.get('TransactionId'),
136
+ ]);
137
+ };
138
+
139
+ export default usePaymentReturn;
@@ -1,5 +1,5 @@
1
- function useQueryParams(): URLSearchParams {
2
- return new URLSearchParams(location.search);
3
- }
4
-
5
- export default useQueryParams;
1
+ function useQueryParams(): URLSearchParams {
2
+ return new URLSearchParams(location.search);
3
+ }
4
+
5
+ export default useQueryParams;
package/src/index.tsx CHANGED
@@ -1,30 +1,30 @@
1
- import { createRoot, type Root } from 'react-dom/client';
2
- import { createElement } from 'react';
3
-
4
- import type { ConfigType } from './types/general';
5
- import { createSubscriber } from './api/SubscribeApi';
6
- import App from './App';
7
-
8
- export const orderComponent = {
9
- root: null as Root | null,
10
- init: function (config: ConfigType) {
11
- if (!config.apiKey) {
12
- console.error('"apiKey" should be set');
13
- }
14
-
15
- if (!config.apiUrl) {
16
- console.error('"apiUrl" should be set');
17
- }
18
-
19
- const domNode = document.getElementById(config.domElementId);
20
- orderComponent.root = createRoot(
21
- domNode || document.createElement('div')
22
- );
23
- const reactElement = createElement(App, config);
24
- orderComponent.root.render(reactElement);
25
- },
26
- remove: function () {
27
- (orderComponent.root as Root)?.unmount();
28
- },
29
- createSubscriber,
30
- };
1
+ import { createRoot, type Root } from 'react-dom/client';
2
+ import { createElement } from 'react';
3
+
4
+ import type { ConfigType } from './types/general';
5
+ import { createSubscriber } from './api/SubscribeApi';
6
+ import App from './App';
7
+
8
+ export const orderComponent = {
9
+ root: null as Root | null,
10
+ init: function (config: ConfigType) {
11
+ if (!config.apiKey) {
12
+ console.error('"apiKey" should be set');
13
+ }
14
+
15
+ if (!config.apiUrl) {
16
+ console.error('"apiUrl" should be set');
17
+ }
18
+
19
+ const domNode = document.getElementById(config.domElementId);
20
+ orderComponent.root = createRoot(
21
+ domNode || document.createElement('div')
22
+ );
23
+ const reactElement = createElement(App, config);
24
+ orderComponent.root.render(reactElement);
25
+ },
26
+ remove: function () {
27
+ (orderComponent.root as Root)?.unmount();
28
+ },
29
+ createSubscriber,
30
+ };
package/src/lib/utils.ts CHANGED
@@ -1 +1 @@
1
- export { cn } from 'cn';
1
+ export { cn } from 'cn';
package/src/types/api.ts CHANGED
@@ -1,28 +1,28 @@
1
- import { HttpStatusCode } from '../enums/api';
2
-
3
- export interface ApiResponseType<T> {
4
- status: HttpStatusCode;
5
- text: string;
6
- error: string;
7
- code: HttpStatusCode;
8
- timestamp: string;
9
- data: T;
10
- query: string;
11
- url: string;
12
- }
13
-
14
- export type CreateSubscriberRequestType = {
15
- name?: string;
16
- email?: string;
17
- phone?: string;
18
- country?: string;
19
- city?: string;
20
- addressLines?: string[];
21
- zip?: string;
22
- careOf?: string;
23
- buyerReference?: string;
24
- gln?: string;
25
- organizationNumber?: string;
26
- identityProviderId?: string;
27
- userId?: string;
28
- };
1
+ import { HttpStatusCode } from '../enums/api';
2
+
3
+ export interface ApiResponseType<T> {
4
+ status: HttpStatusCode;
5
+ text: string;
6
+ error: string;
7
+ code: HttpStatusCode;
8
+ timestamp: string;
9
+ data: T;
10
+ query: string;
11
+ url: string;
12
+ }
13
+
14
+ export type CreateSubscriberRequestType = {
15
+ name?: string;
16
+ email?: string;
17
+ phone?: string;
18
+ country?: string;
19
+ city?: string;
20
+ addressLines?: string[];
21
+ zip?: string;
22
+ careOf?: string;
23
+ buyerReference?: string;
24
+ gln?: string;
25
+ organizationNumber?: string;
26
+ identityProviderId?: string;
27
+ userId?: string;
28
+ };
@@ -81,7 +81,7 @@ export type ConfigType = {
81
81
  orderCompletionFailedCallback?: (
82
82
  event: OrderCompletionFailedEventType
83
83
  ) => void;
84
- submitStartCallback?: (subscriberId: string) => void;
84
+ submitStartCallback?: (subscriberId: string) => void | Promise<void>;
85
85
  userActionCallback?: (
86
86
  action: UserActionEnum,
87
87
  args: object | null | undefined
@@ -98,7 +98,6 @@ export type ConfigType = {
98
98
  apiKey?: string;
99
99
  apiUrl?: string;
100
100
  redirectUrl?: string;
101
- showIframe?: boolean;
102
101
  availablePaymentMethods?: PaymentMethodOptionType[];
103
102
  allowedPaymentMethods?: PaymentMethodEnum[];
104
103
  paymentMethodsOptions?: PaymentMethodSettingsType;
@@ -1,78 +1,78 @@
1
- import { WRONG_MSG } from '../constants/index';
2
- import type { ErrorsMsg } from '../types/general';
3
-
4
- export const prepareErrorMessage = (
5
- error: Error,
6
- defaultMsg?: string,
7
- translations?: ErrorMessages
8
- ) => {
9
- if (typeof error === 'string') {
10
- try {
11
- const parsedError = JSON.parse(error);
12
- return (parsedError as { message: string }).message;
13
- } catch (e) {
14
- return translateError(error, translations);
15
- }
16
- } else {
17
- const serverErrorMsg = (error as { message: string })
18
- ?.message as string;
19
- return (
20
- translateError(serverErrorMsg, translations) ||
21
- defaultMsg ||
22
- WRONG_MSG
23
- );
24
- }
25
- };
26
-
27
- export const prepareErrorsArrayMessage = (
28
- errors: ErrorsMsg | null,
29
- translations?: ErrorMessages
30
- ) => {
31
- const msg: string[] = [];
32
-
33
- if (errors) {
34
- Object.entries(errors).forEach(([_, values]) => {
35
- if (values?.length > 0) {
36
- values.forEach((i) => {
37
- msg.push(translateError(i, translations));
38
- });
39
- }
40
- });
41
- }
42
-
43
- return msg;
44
- };
45
-
46
- export function uuidv4() {
47
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
48
- /[xy]/g,
49
- function (c) {
50
- const r = (Math.random() * 16) | 0;
51
- const v = c == 'x' ? r : (r & 0x3) | 0x8;
52
- return v.toString(16);
53
- }
54
- );
55
- }
56
-
57
- export type ErrorMessages = {
58
- errorValidationTitleMsg: string;
59
- errorValidationBlockingOffersMsg: string;
60
- errorValidationDenialOrderBlockingMsg: string;
61
- };
62
-
63
- const translateError = (errorMsg: string, translations?: ErrorMessages) => {
64
- if (!translations) {
65
- return errorMsg;
66
- }
67
-
68
- switch (errorMsg) {
69
- case 'One or more validation errors occurred.':
70
- return translations?.errorValidationTitleMsg;
71
- case 'The order/subscription will not be created because the subscriber has a denial order blocking offers.':
72
- return translations?.errorValidationBlockingOffersMsg;
73
- case 'The order/subscription will not be created because the subscriber has a denial order blocking all.':
74
- return translations?.errorValidationDenialOrderBlockingMsg;
75
- default:
76
- return errorMsg;
77
- }
78
- };
1
+ import { WRONG_MSG } from '../constants/index';
2
+ import type { ErrorsMsg } from '../types/general';
3
+
4
+ export const prepareErrorMessage = (
5
+ error: Error,
6
+ defaultMsg?: string,
7
+ translations?: ErrorMessages
8
+ ) => {
9
+ if (typeof error === 'string') {
10
+ try {
11
+ const parsedError = JSON.parse(error);
12
+ return (parsedError as { message: string }).message;
13
+ } catch (e) {
14
+ return translateError(error, translations);
15
+ }
16
+ } else {
17
+ const serverErrorMsg = (error as { message: string })
18
+ ?.message as string;
19
+ return (
20
+ translateError(serverErrorMsg, translations) ||
21
+ defaultMsg ||
22
+ WRONG_MSG
23
+ );
24
+ }
25
+ };
26
+
27
+ export const prepareErrorsArrayMessage = (
28
+ errors: ErrorsMsg | null,
29
+ translations?: ErrorMessages
30
+ ) => {
31
+ const msg: string[] = [];
32
+
33
+ if (errors) {
34
+ Object.entries(errors).forEach(([_, values]) => {
35
+ if (values?.length > 0) {
36
+ values.forEach((i) => {
37
+ msg.push(translateError(i, translations));
38
+ });
39
+ }
40
+ });
41
+ }
42
+
43
+ return msg;
44
+ };
45
+
46
+ export function uuidv4() {
47
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
48
+ /[xy]/g,
49
+ function (c) {
50
+ const r = (Math.random() * 16) | 0;
51
+ const v = c == 'x' ? r : (r & 0x3) | 0x8;
52
+ return v.toString(16);
53
+ }
54
+ );
55
+ }
56
+
57
+ export type ErrorMessages = {
58
+ errorValidationTitleMsg: string;
59
+ errorValidationBlockingOffersMsg: string;
60
+ errorValidationDenialOrderBlockingMsg: string;
61
+ };
62
+
63
+ const translateError = (errorMsg: string, translations?: ErrorMessages) => {
64
+ if (!translations) {
65
+ return errorMsg;
66
+ }
67
+
68
+ switch (errorMsg) {
69
+ case 'One or more validation errors occurred.':
70
+ return translations?.errorValidationTitleMsg;
71
+ case 'The order/subscription will not be created because the subscriber has a denial order blocking offers.':
72
+ return translations?.errorValidationBlockingOffersMsg;
73
+ case 'The order/subscription will not be created because the subscriber has a denial order blocking all.':
74
+ return translations?.errorValidationDenialOrderBlockingMsg;
75
+ default:
76
+ return errorMsg;
77
+ }
78
+ };