@infosoftas/s4-orders-js-sdk 0.1.21 → 0.2.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 (72) hide show
  1. package/.editorconfig +0 -0
  2. package/.release-it.json +0 -0
  3. package/README.md +572 -471
  4. package/build/postcss-scope-tailwind.cjs +0 -0
  5. package/components.json +0 -0
  6. package/package.json +62 -58
  7. package/src/App.completion.test.tsx +677 -0
  8. package/src/App.css +0 -14
  9. package/src/App.paymentReturn.test.tsx +341 -0
  10. package/src/App.tsx +722 -639
  11. package/src/ErrorBoundary.tsx +0 -0
  12. package/src/api/InvoiceApi.ts +0 -0
  13. package/src/api/OrdersApi.ts +74 -59
  14. package/src/api/SubscribeApi.ts +0 -0
  15. package/src/bundle.ts +0 -0
  16. package/src/components/Alert/Alert.tsx +0 -0
  17. package/src/components/Button/Button.tsx +0 -0
  18. package/src/components/EHFForm/EHFForm.tsx +250 -253
  19. package/src/components/FormFields/AddressField.tsx +0 -0
  20. package/src/components/FormFields/EmailField.tsx +0 -0
  21. package/src/components/FormFields/FormFields.helper.ts +0 -0
  22. package/src/components/FormFields/FormFieldsMapper.ts +0 -0
  23. package/src/components/FormFields/InputField.tsx +0 -0
  24. package/src/components/FormFields/NameField.tsx +0 -0
  25. package/src/components/FormFields/PhoneField.tsx +0 -0
  26. package/src/components/FormFields/TermsCheckbox.tsx +0 -0
  27. package/src/components/FormFields/ToggleFiled.tsx +0 -0
  28. package/src/components/FormFields/fieldValidators.ts +0 -0
  29. package/src/components/OIOForm/OIOForm.tsx +304 -307
  30. package/src/components/OrderDenialModal/OrderDenialModal.tsx +0 -0
  31. package/src/components/OrderForm/ContactDetailsSection.tsx +0 -0
  32. package/src/components/OrderForm/OrderForm.tsx +417 -420
  33. package/src/components/OrderForm/PaymentMethodContent.tsx +0 -0
  34. package/src/components/OrderForm/PaymentMethodSection.tsx +0 -0
  35. package/src/components/OrderForm/SubmitConfirmationDialog.tsx +0 -0
  36. package/src/components/OrderForm/orderFormState.ts +0 -0
  37. package/src/components/OrderForm/useSlotElement.tsx +0 -0
  38. package/src/components/ui/alert-dialog.tsx +0 -0
  39. package/src/components/ui/alert.tsx +0 -0
  40. package/src/components/ui/button.tsx +0 -0
  41. package/src/components/ui/card.tsx +0 -0
  42. package/src/components/ui/checkbox.tsx +0 -0
  43. package/src/components/ui/field.tsx +0 -0
  44. package/src/components/ui/input.tsx +0 -0
  45. package/src/components/ui/label.tsx +0 -0
  46. package/src/components/ui/radio-group.tsx +0 -0
  47. package/src/components/ui/separator.tsx +0 -0
  48. package/src/components/ui/skeleton.tsx +0 -0
  49. package/src/components/ui/spinner.tsx +0 -0
  50. package/src/components/ui/switch.tsx +0 -0
  51. package/src/components/ui/textarea.tsx +0 -0
  52. package/src/constants/index.ts +0 -0
  53. package/src/custom.d.ts +0 -0
  54. package/src/enums/api.ts +0 -0
  55. package/src/enums/general.ts +42 -40
  56. package/src/hooks/useOrderForm.tsx +400 -403
  57. package/src/hooks/usePaymentReturn.tsx +139 -0
  58. package/src/hooks/useQueryParams.ts +0 -0
  59. package/src/index.tsx +0 -0
  60. package/src/lib/utils.ts +0 -0
  61. package/src/types/api.ts +0 -0
  62. package/src/types/general.ts +153 -136
  63. package/src/types/order.ts +91 -70
  64. package/src/utils/fetcher.ts +131 -113
  65. package/src/utils/helper.ts +0 -0
  66. package/src/utils/order.helper.test.ts +81 -0
  67. package/src/utils/order.helper.ts +285 -272
  68. package/src/utils/waitForOrderCompletion.ts +125 -0
  69. package/tsconfig.json +39 -38
  70. package/src/components/MainIframe/MainIframe.tsx +0 -42
  71. package/src/hooks/useIframe.tsx +0 -59
  72. package/src/hooks/useMessageEvent.tsx +0 -194
@@ -1,113 +1,131 @@
1
- import { HttpStatusCode } from '../enums/api';
2
- import type { ApiResponseType } from '../types/api';
3
- import { BASE_API } from '../constants/index';
4
-
5
- export type Method =
6
- | 'GET'
7
- | 'POST'
8
- | 'PUT'
9
- | 'DELETE'
10
- | 'HEAD'
11
- | 'OPTIONS'
12
- | 'PATCH';
13
-
14
- type Fetcher<T> = {
15
- url: string;
16
- params?: Record<string, string | string[]>;
17
- method?: Method;
18
- headers?: HeadersInit;
19
- body?: T;
20
- };
21
-
22
- export const getSdkApiKey = (): string => {
23
- return (
24
- sessionStorage.getItem('sdk_api_key') ||
25
- localStorage.getItem('sdk_api_key') ||
26
- ''
27
- );
28
- };
29
-
30
- export const getSdkApiUrl = (): string => {
31
- return (
32
- sessionStorage.getItem('sdk_api_url') ||
33
- localStorage.getItem('sdk_api_url') ||
34
- BASE_API
35
- );
36
- };
37
-
38
- function createHeader<T>(options: Fetcher<T>): Fetcher<T> {
39
- const accessToken = localStorage.getItem('authTokenKey') || '';
40
-
41
- const headers = new Headers({
42
- accept: 'application/json',
43
- ...(accessToken && {
44
- Authorization: `Bearer ${accessToken}`,
45
- }),
46
- ...options.headers,
47
- });
48
-
49
- if (!(options.body instanceof FormData)) {
50
- headers.append('Content-Type', 'application/json');
51
- }
52
-
53
- return { method: 'GET', ...options, headers };
54
- }
55
-
56
- async function fetcher<ResponseType, BodyType = void>(
57
- options: Fetcher<BodyType>
58
- ): Promise<ApiResponseType<ResponseType> | ResponseType> {
59
- const { url, method, headers, body, params } = createHeader(options);
60
-
61
- const apiUrl = getSdkApiUrl();
62
- const endpoint = new URL(`${apiUrl || BASE_API}${url}`);
63
-
64
- if (params) {
65
- Object.entries(params).forEach(([key, value]) => {
66
- if (Array.isArray(value)) {
67
- value.forEach((v) => endpoint.searchParams.append(key, v));
68
- return;
69
- }
70
- endpoint.searchParams.append(key, value);
71
- });
72
- }
73
-
74
- return new Promise<ApiResponseType<ResponseType> | ResponseType>(
75
- (resolve, reject) => {
76
- return fetch(endpoint.toString(), {
77
- method,
78
- headers,
79
- body: body instanceof FormData ? body : JSON.stringify(body),
80
- })
81
- .then(async (response) => {
82
- if (response.status === HttpStatusCode.UNAUTHORIZED) {
83
- localStorage.removeItem('authTokenKey');
84
- reject({ message: 'Not Authorized user!' });
85
- } else if (response.status === HttpStatusCode.FORBIDDEN) {
86
- reject({ message: 'Something Wrong with permission!' });
87
- } else if (response.status === HttpStatusCode.LIMIT) {
88
- reject({
89
- message: 'System busy please try again shortly!',
90
- });
91
- } else {
92
- if (response.ok) {
93
- response
94
- .json()
95
- .then((data) => resolve(data))
96
- .catch(() => resolve(null as ResponseType));
97
- } else {
98
- const data = await response?.json();
99
- const message =
100
- data.details || data.message || data.title;
101
- reject({ ...data, message });
102
- }
103
- }
104
- })
105
- .catch((error) => {
106
- console.log(error, 'error');
107
- reject(error?.response);
108
- });
109
- }
110
- );
111
- }
112
-
113
- export default fetcher;
1
+ import { HttpStatusCode } from '../enums/api';
2
+ import type { ApiResponseType } from '../types/api';
3
+ import { BASE_API } from '../constants/index';
4
+
5
+ export type Method =
6
+ | 'GET'
7
+ | 'POST'
8
+ | 'PUT'
9
+ | 'DELETE'
10
+ | 'HEAD'
11
+ | 'OPTIONS'
12
+ | 'PATCH';
13
+
14
+ type Fetcher<T> = {
15
+ url: string;
16
+ params?: Record<string, string | string[]>;
17
+ method?: Method;
18
+ headers?: HeadersInit;
19
+ body?: T;
20
+ signal?: AbortSignal;
21
+ cache?: RequestCache;
22
+ };
23
+
24
+ export const getSdkApiKey = (): string => {
25
+ return (
26
+ sessionStorage.getItem('sdk_api_key') ||
27
+ localStorage.getItem('sdk_api_key') ||
28
+ ''
29
+ );
30
+ };
31
+
32
+ export const getSdkApiUrl = (): string => {
33
+ return (
34
+ sessionStorage.getItem('sdk_api_url') ||
35
+ localStorage.getItem('sdk_api_url') ||
36
+ BASE_API
37
+ );
38
+ };
39
+
40
+ function createHeader<T>(options: Fetcher<T>): Fetcher<T> {
41
+ const accessToken = localStorage.getItem('authTokenKey') || '';
42
+
43
+ const headers = new Headers({
44
+ accept: 'application/json',
45
+ ...(accessToken && {
46
+ Authorization: `Bearer ${accessToken}`,
47
+ }),
48
+ ...options.headers,
49
+ });
50
+
51
+ if (!(options.body instanceof FormData)) {
52
+ headers.append('Content-Type', 'application/json');
53
+ }
54
+
55
+ return { method: 'GET', ...options, headers };
56
+ }
57
+
58
+ async function fetcher<ResponseType, BodyType = void>(
59
+ options: Fetcher<BodyType>
60
+ ): Promise<ApiResponseType<ResponseType> | ResponseType> {
61
+ const { url, method, headers, body, params, signal, cache } =
62
+ createHeader(options);
63
+
64
+ const apiUrl = getSdkApiUrl();
65
+ const endpoint = new URL(`${apiUrl || BASE_API}${url}`);
66
+
67
+ if (params) {
68
+ Object.entries(params).forEach(([key, value]) => {
69
+ if (Array.isArray(value)) {
70
+ value.forEach((v) => endpoint.searchParams.append(key, v));
71
+ return;
72
+ }
73
+ endpoint.searchParams.append(key, value);
74
+ });
75
+ }
76
+
77
+ return new Promise<ApiResponseType<ResponseType> | ResponseType>(
78
+ (resolve, reject) => {
79
+ return fetch(endpoint.toString(), {
80
+ method,
81
+ headers,
82
+ signal,
83
+ cache,
84
+ body: body instanceof FormData ? body : JSON.stringify(body),
85
+ })
86
+ .then(async (response) => {
87
+ if (response.status === HttpStatusCode.UNAUTHORIZED) {
88
+ localStorage.removeItem('authTokenKey');
89
+ reject({
90
+ status: response.status,
91
+ message: 'Not Authorized user!',
92
+ });
93
+ } else if (response.status === HttpStatusCode.FORBIDDEN) {
94
+ reject({
95
+ status: response.status,
96
+ message: 'Something Wrong with permission!',
97
+ });
98
+ } else if (response.status === HttpStatusCode.LIMIT) {
99
+ reject({
100
+ status: response.status,
101
+ retryAfter: response.headers.get('Retry-After'),
102
+ message: 'System busy please try again shortly!',
103
+ });
104
+ } else {
105
+ if (response.ok) {
106
+ response
107
+ .json()
108
+ .then((data) => resolve(data))
109
+ .catch(() => resolve(null as ResponseType));
110
+ } else {
111
+ const data =
112
+ (await response.json().catch(() => null)) || {};
113
+ const message =
114
+ data.details || data.message || data.title;
115
+ reject({
116
+ ...data,
117
+ status: response.status,
118
+ message,
119
+ });
120
+ }
121
+ }
122
+ })
123
+ .catch((error) => {
124
+ console.log(error, 'error');
125
+ reject(error?.response || error);
126
+ });
127
+ }
128
+ );
129
+ }
130
+
131
+ export default fetcher;
File without changes
@@ -0,0 +1,81 @@
1
+ // @vitest-environment jsdom
2
+
3
+ import { afterEach, describe, expect, it } from 'vitest';
4
+
5
+ import { PaymentMethodEnum } from '../enums/general';
6
+ import { prepareAgreementModel } from './order.helper';
7
+
8
+ const prepare = (paymentMethod: PaymentMethodEnum, redirectUrl?: string) =>
9
+ prepareAgreementModel({
10
+ paymentMethod,
11
+ redirectUrl,
12
+ generateSubscriberContact: false,
13
+ language: 'nb-NO',
14
+ merchantAgreementUrl: 'https://shop.example.test/terms',
15
+ });
16
+
17
+ const params = (url: string | undefined) => [
18
+ ...new URL(url as string).searchParams.entries(),
19
+ ];
20
+
21
+ // The page after a cancelled card payment, where the shopper tries again.
22
+ const cancelledReturn =
23
+ 'https://shop.example.test/checkout?journey=order&action=cancel&S4OrderId=old-order&TransactionId=old-tx';
24
+
25
+ describe('prepareAgreementModel return URLs', () => {
26
+ afterEach(() => {
27
+ window.history.replaceState({}, '', '/');
28
+ });
29
+
30
+ it('does not carry a previous return into the next SwedbankPay attempt', () => {
31
+ const { swedbankPay } = prepare(
32
+ PaymentMethodEnum.SwedbankPay,
33
+ cancelledReturn
34
+ );
35
+
36
+ expect(params(swedbankPay?.completeUrl)).toEqual([
37
+ ['journey', 'order'],
38
+ ['action', 'complete'],
39
+ ]);
40
+ expect(params(swedbankPay?.cancelUrl)).toEqual([
41
+ ['journey', 'order'],
42
+ ['action', 'cancel'],
43
+ ]);
44
+ });
45
+
46
+ it('does not carry a previous return into the next Mollie attempt', () => {
47
+ const { mollie } = prepare(PaymentMethodEnum.Mollie, cancelledReturn);
48
+
49
+ expect(params(mollie?.returnUrl)).toEqual([
50
+ ['journey', 'order'],
51
+ ['action', 'complete'],
52
+ ]);
53
+ });
54
+
55
+ it('does not carry previous return parameters into the Vipps redirect', () => {
56
+ const { vippsMobilePay } = prepare(
57
+ PaymentMethodEnum.Vipps,
58
+ `${cancelledReturn}&orderId=old-vipps&agreementId=old-agreement`
59
+ );
60
+
61
+ expect(params(vippsMobilePay?.merchantRedirectUrl)).toEqual([
62
+ ['journey', 'order'],
63
+ ]);
64
+ });
65
+
66
+ it('falls back to the current page and keeps journey and hashToken once', () => {
67
+ window.history.replaceState(
68
+ {},
69
+ '',
70
+ '/checkout?journey=order&hashToken=token-1&action=cancel&S4OrderId=old-order'
71
+ );
72
+
73
+ const { swedbankPay } = prepare(PaymentMethodEnum.SwedbankPay);
74
+
75
+ expect(params(swedbankPay?.completeUrl)).toEqual([
76
+ ['journey', 'order'],
77
+ ['hashToken', 'token-1'],
78
+ ['action', 'complete'],
79
+ ]);
80
+ });
81
+ });