@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
@@ -0,0 +1,94 @@
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
+
82
+ it('uses the live hashToken over a stale one in the Vipps redirectUrl', () => {
83
+ window.history.replaceState({}, '', '/checkout?hashToken=live');
84
+
85
+ const { vippsMobilePay } = prepare(
86
+ PaymentMethodEnum.Vipps,
87
+ 'https://shop.example.test/checkout?hashToken=stale'
88
+ );
89
+
90
+ expect(params(vippsMobilePay?.merchantRedirectUrl)).toEqual([
91
+ ['hashToken', 'live'],
92
+ ]);
93
+ });
94
+ });
@@ -1,4 +1,4 @@
1
- import { MessageEventTypeEnum, PaymentMethodEnum } from '../enums/general';
1
+ import { PaymentMethodEnum, PaymentReturnActionEnum } from '../enums/general';
2
2
  import type { AgreementsType, OrderFormInputsType } from '../types/order';
3
3
  import type { OrderFormFieldType } from '../types/general';
4
4
  import { FIELD_TYPES } from '../components/FormFields/FormFields.helper';
@@ -6,7 +6,6 @@ import { FIELD_TYPES } from '../components/FormFields/FormFields.helper';
6
6
  type AgreementModelType = {
7
7
  paymentMethod: PaymentMethodEnum;
8
8
  redirectUrl?: string;
9
- showIframe?: boolean;
10
9
  phoneNumber?: string;
11
10
  generateSubscriberContact: boolean;
12
11
  language: string;
@@ -35,10 +34,30 @@ const mapToPaymentProviderLanguage = (language: string) => {
35
34
  return 'en-US';
36
35
  };
37
36
 
37
+ // Parameters a payment provider adds on return. A return URL built from a page
38
+ // that is itself a return would otherwise carry the previous attempt's values,
39
+ // and the first `action`/`S4OrderId` wins when the next return is read.
40
+ const PAYMENT_RETURN_PARAMS = [
41
+ 'action',
42
+ 's4orderid',
43
+ 'transactionid',
44
+ 'orderid',
45
+ 'agreementid',
46
+ ];
47
+
48
+ const withoutPaymentReturnParams = (href: string) => {
49
+ const url = new URL(href);
50
+ for (const key of [...url.searchParams.keys()]) {
51
+ if (PAYMENT_RETURN_PARAMS.includes(key.toLowerCase())) {
52
+ url.searchParams.delete(key);
53
+ }
54
+ }
55
+ return url;
56
+ };
57
+
38
58
  export const prepareAgreementModel = ({
39
59
  paymentMethod,
40
60
  redirectUrl,
41
- showIframe,
42
61
  phoneNumber,
43
62
  generateSubscriberContact,
44
63
  language,
@@ -51,28 +70,27 @@ export const prepareAgreementModel = ({
51
70
  const existUrl = new URL(window.location.href);
52
71
  const journey = existUrl.searchParams.get('journey');
53
72
  const hashToken = existUrl.searchParams.get('hashToken');
54
- const url = showIframe
55
- ? window.location.href.split('?')[0]
56
- : redirectUrl || window.location.href;
57
- const cancelUrl = new URL(url);
58
- cancelUrl.searchParams.append('action', `${MessageEventTypeEnum.CANCEL}`);
59
- if (journey) {
60
- cancelUrl.searchParams.append('journey', journey);
61
- }
62
- if (hashToken) {
63
- cancelUrl.searchParams.append('hashToken', hashToken);
64
- }
65
- const confirmUrl = new URL(url);
66
- confirmUrl.searchParams.append(
67
- 'action',
68
- `${MessageEventTypeEnum.COMPLETE}`
73
+ const baseUrl = withoutPaymentReturnParams(
74
+ redirectUrl || window.location.href
69
75
  );
70
- if (journey) {
71
- confirmUrl.searchParams.append('journey', journey);
72
- }
76
+ // The host may set the token after the config was built (e.g. once a new
77
+ // subscriber exists), so the live value wins over one in `redirectUrl`.
73
78
  if (hashToken) {
74
- confirmUrl.searchParams.append('hashToken', hashToken);
79
+ baseUrl.searchParams.set('hashToken', hashToken);
75
80
  }
81
+ const buildReturnUrl = (action: PaymentReturnActionEnum) => {
82
+ const returnUrl = new URL(baseUrl);
83
+ returnUrl.searchParams.set('action', action);
84
+ if (journey) {
85
+ returnUrl.searchParams.set('journey', journey);
86
+ }
87
+ if (hashToken) {
88
+ returnUrl.searchParams.set('hashToken', hashToken);
89
+ }
90
+ return returnUrl;
91
+ };
92
+ const cancelUrl = buildReturnUrl(PaymentReturnActionEnum.CANCEL);
93
+ const confirmUrl = buildReturnUrl(PaymentReturnActionEnum.COMPLETE);
76
94
 
77
95
  if (paymentMethod === PaymentMethodEnum.SwedbankPay) {
78
96
  model.swedbankPay = {
@@ -105,7 +123,7 @@ export const prepareAgreementModel = ({
105
123
  merchantAgreementUrl,
106
124
  accountId,
107
125
  phoneNumber,
108
- merchantRedirectUrl: redirectUrl || window.location.href,
126
+ merchantRedirectUrl: `${baseUrl}`,
109
127
  };
110
128
 
111
129
  return model;
package/tsconfig.json CHANGED
@@ -12,6 +12,7 @@
12
12
  "noFallthroughCasesInSwitch": true,
13
13
  "module": "esnext",
14
14
  "resolveJsonModule": true,
15
+ "moduleResolution": "bundler",
15
16
  "isolatedModules": true,
16
17
  "verbatimModuleSyntax": true,
17
18
  "noEmit": false,
@@ -1,42 +0,0 @@
1
- import { type FC, useEffect, useState } from 'react';
2
-
3
- import useIframe from '../../hooks/useIframe';
4
-
5
- type Props = {
6
- iframeSrc: string | null;
7
- };
8
-
9
- const MainIframe: FC<Props> = ({ iframeSrc }) => {
10
- const [loading, setLoading] = useState(false);
11
-
12
- const { frameRef, messageReceiver } = useIframe();
13
-
14
- useEffect(() => {
15
- if (frameRef && iframeSrc) {
16
- setLoading(true);
17
- frameRef?.current &&
18
- (frameRef?.current as HTMLIFrameElement).addEventListener(
19
- 'load',
20
- () => {
21
- setLoading(false);
22
- }
23
- );
24
- messageReceiver();
25
- }
26
- }, [frameRef, iframeSrc]);
27
-
28
- return (
29
- <div className="sdk-iframe-wrapper" data-testid="sdk-iframe-id">
30
- {loading && <div>... Loading</div>}
31
- {iframeSrc && (
32
- <iframe
33
- ref={frameRef}
34
- src={iframeSrc}
35
- style={{ minHeight: '830px', width: '100%' }}
36
- ></iframe>
37
- )}
38
- </div>
39
- );
40
- };
41
-
42
- export default MainIframe;
@@ -1,59 +0,0 @@
1
- import { useRef } from 'react';
2
-
3
- let currentMessageReceiver: (event: Event) => void;
4
-
5
- const useIframe = () => {
6
- const frameRef = useRef(null);
7
-
8
- const messageReceiver = (
9
- callback?: (type: string, value: string) => void
10
- ) => {
11
- if (currentMessageReceiver) {
12
- window.removeEventListener('message', currentMessageReceiver);
13
- }
14
-
15
- currentMessageReceiver = (event: Event) => {
16
- if (!frameRef.current) {
17
- return;
18
- }
19
-
20
- const childWindow = (frameRef.current as HTMLIFrameElement)
21
- .contentWindow;
22
-
23
- if ((event as MessageEvent).source !== childWindow) {
24
- return; // Skip message in this event listener
25
- }
26
-
27
- let { value, type } = (event as MessageEvent).data as unknown as {
28
- value: string;
29
- type: string;
30
- };
31
-
32
- if (callback) {
33
- callback(type, value);
34
- }
35
- };
36
-
37
- window.addEventListener('message', currentMessageReceiver, false);
38
-
39
- return () => {
40
- removeMessageReceiver();
41
- };
42
- };
43
-
44
- const removeMessageReceiver = () => {
45
- if (currentMessageReceiver) {
46
- window.removeEventListener(
47
- 'addEventListener',
48
- currentMessageReceiver
49
- );
50
- }
51
- };
52
-
53
- return {
54
- frameRef,
55
- messageReceiver,
56
- };
57
- };
58
-
59
- export default useIframe;
@@ -1,194 +0,0 @@
1
- import { useEffect, useCallback } from 'react';
2
-
3
- import { MessageEventTypeEnum, PaymentMethodEnum } 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
- const useMessageEvent = (
29
- messageCallback: (data: CompleteOrderParamsType) => Promise<void>,
30
- handleMessageEvent: (type: MessageEventTypeEnum, orderId?: string) => void,
31
- showIframe: boolean,
32
- orderInfo: OrderInfoType | null
33
- ) => {
34
- const queryParams = useQueryParams();
35
-
36
- const handleMessage = useCallback(
37
- async (event: MessageEvent) => {
38
- // Vipps handler
39
- if (event.data.type === MessageEventTypeEnum.VIPPS_COMPLETE) {
40
- await messageCallback({
41
- orderId: event.data.orderId || '',
42
- agreementId: event.data.agreementId || '',
43
- orderInfo: orderInfo || null,
44
- });
45
- }
46
-
47
- // SwedbankPay handler
48
- if (event.data.type === MessageEventTypeEnum.COMPLETE) {
49
- await messageCallback({
50
- orderId: event.data.orderId || '',
51
- agreementId: event.data.agreementId || '',
52
- orderInfo: orderInfo || null,
53
- });
54
- }
55
- if (event.data.type === MessageEventTypeEnum.CANCEL) {
56
- handleMessageEvent(event.data.type);
57
- }
58
- },
59
- [orderInfo]
60
- );
61
-
62
- useEffect(() => {
63
- window.addEventListener('message', handleMessage, false);
64
-
65
- return () => {
66
- window.removeEventListener('message', handleMessage, false);
67
- };
68
- }, [handleMessage]);
69
-
70
- // Vipps
71
- useEffect(() => {
72
- if (
73
- queryParams.get('orderId') &&
74
- queryParams.get('agreementId') &&
75
- top &&
76
- window !== top
77
- ) {
78
- top?.postMessage(
79
- {
80
- type: MessageEventTypeEnum.VIPPS_COMPLETE,
81
- orderId: queryParams.get('orderId'),
82
- agreementId: queryParams.get('agreementId'),
83
- },
84
- top?.location?.origin || '*'
85
- );
86
- }
87
- }, [queryParams.get('orderId'), queryParams.get('agreementId')]);
88
-
89
- //Vipps
90
- useEffect(() => {
91
- if (
92
- queryParams.get('orderId') &&
93
- queryParams.get('agreementId')
94
- // !showIframe
95
- ) {
96
- messageCallback({
97
- orderId: queryParams.get('orderId') || '',
98
- agreementId: queryParams.get('agreementId') || '',
99
- orderInfo: orderInfo || null,
100
- paymentMethod: PaymentMethodEnum.Vipps,
101
- });
102
- }
103
- }, [
104
- queryParams.get('orderId'),
105
- queryParams.get('agreementId'),
106
- // showIframe,
107
- ]);
108
-
109
- // SwedbankPay
110
- useEffect(() => {
111
- if (
112
- queryParams.get('action') &&
113
- queryParams.get('S4OrderId') &&
114
- queryParams.get('TransactionId') &&
115
- top &&
116
- window !== top
117
- ) {
118
- top?.postMessage(
119
- {
120
- type: queryParams.get('action'),
121
- orderId: queryParams.get('S4OrderId'),
122
- agreementId: queryParams.get('TransactionId'),
123
- },
124
- top?.location?.origin || '*'
125
- );
126
- }
127
- }, [
128
- queryParams.get('S4OrderId'),
129
- queryParams.get('TransactionId'),
130
- queryParams.get('action'),
131
- ]);
132
-
133
- // SwedbankPay
134
- useEffect(() => {
135
- if (
136
- queryParams.get('S4OrderId') &&
137
- queryParams.get('TransactionId') &&
138
- queryParams.get('action') === MessageEventTypeEnum.COMPLETE &&
139
- !showIframe
140
- ) {
141
- messageCallback({
142
- orderId: queryParams.get('S4OrderId') || '',
143
- agreementId: queryParams.get('TransactionId') || '',
144
- orderInfo: orderInfo || null,
145
- });
146
- }
147
-
148
- if (
149
- queryParams.get('action') === MessageEventTypeEnum.CANCEL &&
150
- (!showIframe || !queryParams.get('TransactionId'))
151
- ) {
152
- const cancelOrderId =
153
- queryParams.get('S4OrderId') || takeStoredMollieOrderId();
154
- handleMessageEvent(
155
- queryParams.get('action') as MessageEventTypeEnum,
156
- cancelOrderId || undefined
157
- );
158
- }
159
- }, [
160
- queryParams.get('action'),
161
- queryParams.get('S4OrderId'),
162
- queryParams.get('TransactionId'),
163
- showIframe,
164
- ]);
165
-
166
- // Mollie: a completion return with no TransactionId (that one is SwedbankPay's).
167
- useEffect(() => {
168
- if (
169
- queryParams.get('action') !== MessageEventTypeEnum.COMPLETE ||
170
- queryParams.get('TransactionId')
171
- ) {
172
- return;
173
- }
174
-
175
- const s4OrderId = queryParams.get('S4OrderId');
176
- const storedOrderId = takeStoredMollieOrderId();
177
- const mollieOrderId = s4OrderId || storedOrderId;
178
- if (!mollieOrderId) {
179
- return;
180
- }
181
-
182
- messageCallback({
183
- orderId: mollieOrderId,
184
- agreementId: '',
185
- orderInfo: orderInfo || null,
186
- });
187
- }, [
188
- queryParams.get('action'),
189
- queryParams.get('S4OrderId'),
190
- queryParams.get('TransactionId'),
191
- ]);
192
- };
193
-
194
- export default useMessageEvent;