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

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 (51) hide show
  1. package/.editorconfig +8 -8
  2. package/.release-it.json +10 -10
  3. package/README.md +565 -471
  4. package/package.json +62 -58
  5. package/src/App.completion.test.tsx +738 -0
  6. package/src/App.tsx +753 -639
  7. package/src/ErrorBoundary.tsx +41 -41
  8. package/src/api/InvoiceApi.ts +23 -23
  9. package/src/api/OrdersApi.ts +74 -59
  10. package/src/api/SubscribeApi.ts +18 -18
  11. package/src/bundle.ts +4 -4
  12. package/src/components/Alert/Alert.tsx +23 -23
  13. package/src/components/Button/Button.tsx +39 -39
  14. package/src/components/EHFForm/EHFForm.tsx +253 -253
  15. package/src/components/FormFields/AddressField.tsx +55 -55
  16. package/src/components/FormFields/EmailField.tsx +53 -53
  17. package/src/components/FormFields/FormFields.helper.ts +34 -34
  18. package/src/components/FormFields/FormFieldsMapper.ts +34 -34
  19. package/src/components/FormFields/InputField.tsx +52 -52
  20. package/src/components/FormFields/NameField.tsx +52 -52
  21. package/src/components/FormFields/PhoneField.tsx +53 -53
  22. package/src/components/FormFields/TermsCheckbox.tsx +70 -70
  23. package/src/components/FormFields/ToggleFiled.tsx +52 -52
  24. package/src/components/FormFields/fieldValidators.ts +71 -71
  25. package/src/components/MainIframe/MainIframe.tsx +42 -42
  26. package/src/components/OIOForm/OIOForm.tsx +307 -307
  27. package/src/components/OrderDenialModal/OrderDenialModal.tsx +102 -102
  28. package/src/components/OrderForm/ContactDetailsSection.tsx +71 -71
  29. package/src/components/OrderForm/OrderForm.tsx +420 -420
  30. package/src/components/OrderForm/PaymentMethodContent.tsx +62 -62
  31. package/src/components/OrderForm/PaymentMethodSection.tsx +79 -79
  32. package/src/components/OrderForm/SubmitConfirmationDialog.tsx +55 -55
  33. package/src/components/OrderForm/orderFormState.ts +171 -171
  34. package/src/components/OrderForm/useSlotElement.tsx +89 -89
  35. package/src/constants/index.ts +13 -13
  36. package/src/enums/api.ts +5 -5
  37. package/src/enums/general.ts +40 -40
  38. package/src/hooks/useIframe.tsx +59 -59
  39. package/src/hooks/useMessageEvent.tsx +194 -194
  40. package/src/hooks/useOrderForm.tsx +403 -403
  41. package/src/hooks/useQueryParams.ts +5 -5
  42. package/src/index.tsx +30 -30
  43. package/src/lib/utils.ts +1 -1
  44. package/src/types/api.ts +28 -28
  45. package/src/types/general.ts +154 -136
  46. package/src/types/order.ts +91 -70
  47. package/src/utils/fetcher.ts +131 -113
  48. package/src/utils/helper.ts +78 -78
  49. package/src/utils/order.helper.ts +272 -272
  50. package/src/utils/waitForOrderCompletion.ts +125 -0
  51. package/tsconfig.json +38 -38
@@ -1,420 +1,420 @@
1
- import {
2
- type FC,
3
- type KeyboardEvent,
4
- type ReactNode,
5
- useEffect,
6
- useRef,
7
- useState,
8
- } from 'react';
9
- import {
10
- FormProvider,
11
- useForm,
12
- type Resolver,
13
- type SubmitHandler,
14
- } from 'react-hook-form';
15
- import { zodResolver } from '@hookform/resolvers/zod';
16
-
17
- import { PaymentMethodEnum, UserActionEnum } from '../../enums/general';
18
- import { PAYMENT_METHOD_DEFAULT } from '../../constants/index';
19
- import Alert from '../Alert/Alert';
20
- import Button from '../Button/Button';
21
- import OrderDenialModal from '../OrderDenialModal/OrderDenialModal';
22
- import TermsCheckbox from '../FormFields/TermsCheckbox';
23
- import type { OrderFormInputsType, OrderInfoType } from '../../types/order';
24
- import type {
25
- PaymentMethodSettingsType,
26
- PaymentMethodOptionType,
27
- OrderFormFieldType,
28
- ContactRequestType,
29
- OrderDenialFallbackOfferType,
30
- SubmitConfirmationType,
31
- } from '../../types/general';
32
- import useOrderForm from '../../hooks/useOrderForm';
33
- import { useSlotElement, renderInSlot } from './useSlotElement';
34
- import {
35
- deriveOrderFormState,
36
- buildOrderFormSchema,
37
- type OrderFormConfig,
38
- } from './orderFormState';
39
- import PaymentMethodSection from './PaymentMethodSection';
40
- import ContactDetailsSection from './ContactDetailsSection';
41
- import SubmitConfirmationDialog from './SubmitConfirmationDialog';
42
-
43
- type Props = {
44
- callback: (url: string | null, orderInfo?: OrderInfoType | null) => void;
45
- updateFormData: (data: OrderFormInputsType) => void;
46
- submitStartCallback?: (id: string) => void;
47
- userActionCallback?: (
48
- action: UserActionEnum,
49
- args: object | null | undefined
50
- ) => void;
51
- setContactCallback?: (contactInfo: ContactRequestType) => void;
52
- templatePackageId: string;
53
- subscriberId?: string;
54
- userId?: string;
55
- identityProviderId?: string;
56
- organizationId: string;
57
- redirectUrl?: string;
58
- showIframe?: boolean;
59
- language: string;
60
- merchantAgreementUrl: string;
61
- paymentMethodsOptions?: PaymentMethodSettingsType;
62
- defaultValues?: OrderFormInputsType;
63
- paymentMethods?: PaymentMethodOptionType[];
64
- allowedPaymentMethods?: PaymentMethodEnum[];
65
- submitButtonText?: string;
66
- orderDenialCloseButtonText?: string;
67
- orderDenialContinueButtonText?: string;
68
- paymentMethodLabel?: string;
69
- contactDetailsLabel?: string;
70
- paymentMethodElementId?: string;
71
- contactDetailsElementId?: string;
72
- paymentMethodNotAllowedMsg?: string;
73
- errorReqMsg?: string;
74
- errorInvalidEmailMsg?: string;
75
- errorInvalidPhoneMsg?: string;
76
- errorTermsMsg?: string;
77
- invoiceAddressSelection?: {
78
- enabled?: boolean;
79
- label?: string;
80
- fields?: OrderFormFieldType[];
81
- paymentMethods?: PaymentMethodEnum[];
82
- };
83
- requireTermsAcceptance?: boolean;
84
- errorValidationTitleMsg?: string;
85
- errorValidationDenialOrderBlockingMsg?: string;
86
- errorValidationBlockingOffersMsg?: string;
87
- orderDenialOfferBaseText?: string;
88
- orderDenialOfferWithFallbackText?: string;
89
- orderDenialAmountText?: string;
90
- fetchDenialFallbackOffer?: (
91
- organizationId: string
92
- ) => Promise<OrderDenialFallbackOfferType | undefined>;
93
- termsAndConditionsText?: string | ReactNode;
94
- submitConfirmation?: SubmitConfirmationType;
95
- };
96
-
97
- const initialData = {
98
- invoiceAddressSelection: false,
99
- name: '',
100
- email: '',
101
- phoneNumber: '',
102
- country: '',
103
- city: '',
104
- address: '',
105
- zip: '',
106
- paymentMethod: PAYMENT_METHOD_DEFAULT,
107
- orderReference: '',
108
- };
109
-
110
- const OrderForm: FC<Props> = ({
111
- callback,
112
- updateFormData,
113
- submitStartCallback,
114
- userActionCallback,
115
- setContactCallback,
116
- templatePackageId,
117
- subscriberId,
118
- userId,
119
- identityProviderId,
120
- organizationId,
121
- redirectUrl,
122
- showIframe,
123
- paymentMethodsOptions,
124
- defaultValues,
125
- language,
126
- merchantAgreementUrl,
127
- paymentMethods = [],
128
- allowedPaymentMethods,
129
- invoiceAddressSelection,
130
- submitButtonText = 'Start',
131
- orderDenialCloseButtonText = 'Close',
132
- orderDenialContinueButtonText = 'Continue',
133
- paymentMethodLabel = 'Select payment method',
134
- contactDetailsLabel,
135
- paymentMethodElementId,
136
- contactDetailsElementId,
137
- paymentMethodNotAllowedMsg = 'This payment method not allowed!',
138
- errorReqMsg = '',
139
- errorInvalidEmailMsg = '',
140
- errorInvalidPhoneMsg = '',
141
- errorTermsMsg = '',
142
- errorValidationTitleMsg,
143
- errorValidationDenialOrderBlockingMsg,
144
- errorValidationBlockingOffersMsg,
145
- orderDenialOfferBaseText,
146
- orderDenialOfferWithFallbackText,
147
- orderDenialAmountText,
148
- fetchDenialFallbackOffer,
149
- requireTermsAcceptance,
150
- termsAndConditionsText,
151
- submitConfirmation,
152
- }) => {
153
- const subscriberIdValue =
154
- subscriberId || sessionStorage.getItem('subscriberId') || undefined;
155
-
156
- useEffect(() => {
157
- if (!templatePackageId)
158
- console.error('"templatePackageId" should be set');
159
- if (!organizationId) console.error('"organizationId" should be set');
160
- if (!userId) console.error('"userId" should be set');
161
- if (!identityProviderId)
162
- console.error('"identityProviderId" should be set');
163
- }, [templatePackageId, organizationId, userId, identityProviderId]);
164
-
165
- const config: OrderFormConfig = {
166
- paymentMethods,
167
- paymentMethodsOptions,
168
- allowedPaymentMethods,
169
- invoiceAddressSelection,
170
- };
171
-
172
- const messages = {
173
- errorReqMsg,
174
- errorInvalidEmailMsg,
175
- errorInvalidPhoneMsg,
176
- errorTermsMsg,
177
- };
178
-
179
- const configuredPaymentMethods = paymentMethods.map((m) => m.value);
180
- const initialPaymentMethod = configuredPaymentMethods.length
181
- ? ([defaultValues?.paymentMethod, PAYMENT_METHOD_DEFAULT].find(
182
- (m) => m && configuredPaymentMethods.includes(m)
183
- ) ?? configuredPaymentMethods[0])
184
- : defaultValues?.paymentMethod || PAYMENT_METHOD_DEFAULT;
185
-
186
- const resolver: Resolver<OrderFormInputsType> = (values, ctx, options) => {
187
- const schema = buildOrderFormSchema(
188
- deriveOrderFormState(values, config),
189
- requireTermsAcceptance,
190
- messages
191
- );
192
- return zodResolver(schema)(values, ctx, options);
193
- };
194
-
195
- const methods = useForm<OrderFormInputsType>({
196
- resolver,
197
- defaultValues: {
198
- ...initialData,
199
- ...(defaultValues ?? {}),
200
- paymentMethod: initialPaymentMethod,
201
- },
202
- });
203
-
204
- const { control, handleSubmit, setValue, watch } = methods;
205
-
206
- const derived = deriveOrderFormState(
207
- {
208
- paymentMethod: watch('paymentMethod'),
209
- invoiceAddressSelection: watch('invoiceAddressSelection'),
210
- },
211
- config
212
- );
213
-
214
- useEffect(() => {
215
- userActionCallback?.(UserActionEnum.SELECT_PAYMENT_METHOD, {
216
- paymentMethod: methods.getValues('paymentMethod'),
217
- initial: true,
218
- });
219
- }, []);
220
-
221
- const {
222
- orderSubmit,
223
- continueWithFallbackOffer,
224
- loading,
225
- apiErrorMsg,
226
- errorsMsg,
227
- orderDenialType,
228
- orderDenialMessage,
229
- orderDenialFallbackOffer,
230
- dismissOrderDenial,
231
- } = useOrderForm({
232
- callback,
233
- submitStartCallback,
234
- userActionCallback,
235
- setContactCallback,
236
- organizationId,
237
- subscriberId: subscriberIdValue,
238
- userId,
239
- identityProviderId,
240
- orderFields: derived.orderFields,
241
- redirectUrl,
242
- showIframe,
243
- language,
244
- merchantAgreementUrl,
245
- paymentMethodsOptions,
246
- templatePackageId,
247
- invoiceAddressToggle: watch('invoiceAddressSelection'),
248
- invoiceOrderFields: derived.invoiceOrderFields,
249
- errorValidationTitleMsg,
250
- errorValidationDenialOrderBlockingMsg,
251
- errorValidationBlockingOffersMsg,
252
- orderDenialOfferBaseText,
253
- orderDenialOfferWithFallbackText,
254
- orderDenialAmountText,
255
- fetchDenialFallbackOffer,
256
- });
257
-
258
- const [pendingSubmit, setPendingSubmit] =
259
- useState<OrderFormInputsType | null>(null);
260
-
261
- const submitOrder = async (data: OrderFormInputsType): Promise<void> => {
262
- if (
263
- derived.paymentMethod === PaymentMethodEnum.EHF ||
264
- derived.paymentMethod === PaymentMethodEnum.OIO
265
- ) {
266
- updateFormData?.(data);
267
- return;
268
- }
269
- await orderSubmit(data);
270
- };
271
-
272
- const onSubmit: SubmitHandler<OrderFormInputsType> = async (data) => {
273
- if (submitConfirmation) {
274
- setPendingSubmit(data);
275
- return;
276
- }
277
- await submitOrder(data);
278
- };
279
-
280
- const confirmSubmit = () => {
281
- const data = pendingSubmit;
282
- setPendingSubmit(null);
283
- if (data) submitOrder(data);
284
- };
285
-
286
- const handlePaymentChange = (paymentMethod: PaymentMethodEnum) => {
287
- setValue('paymentMethod', paymentMethod, { shouldValidate: true });
288
- if (!derived.invoicePaymentMethods.includes(paymentMethod)) {
289
- setValue('invoiceAddressSelection', false);
290
- }
291
-
292
- userActionCallback?.(UserActionEnum.SELECT_PAYMENT_METHOD, {
293
- paymentMethod,
294
- });
295
- };
296
-
297
- const paymentMethodSlot = useSlotElement(paymentMethodElementId);
298
- const contactDetailsSlot = useSlotElement(contactDetailsElementId);
299
- const formRef = useRef<HTMLFormElement>(null);
300
-
301
- const handleSlotKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
302
- if (event.key !== 'Enter' || event.defaultPrevented) return;
303
- if (!derived.allowPaymentMethod || loading) return;
304
-
305
- const target = event.target as HTMLElement;
306
- if (target.tagName !== 'INPUT') return;
307
-
308
- const { type } = target as HTMLInputElement;
309
- if (type === 'button' || type === 'submit' || type === 'reset') return;
310
-
311
- event.preventDefault();
312
- formRef.current?.requestSubmit();
313
- };
314
-
315
- const paymentMethodSection = derived.showPaymentMethodSelection ? (
316
- <PaymentMethodSection
317
- control={control}
318
- paymentMethods={paymentMethods}
319
- label={paymentMethodLabel}
320
- onChange={handlePaymentChange}
321
- />
322
- ) : null;
323
-
324
- const contactDetailsSection = derived.showContactDetails ? (
325
- <ContactDetailsSection
326
- label={contactDetailsLabel}
327
- orderFields={derived.orderFields}
328
- invoiceOrderFields={derived.invoiceOrderFields}
329
- showOrderFields={derived.showOrderFields}
330
- showInvoiceToggle={derived.showInvoiceToggle}
331
- showInvoiceFields={derived.showInvoiceFields}
332
- invoiceToggleLabel={invoiceAddressSelection?.label}
333
- onInvoiceToggle={(value) =>
334
- userActionCallback?.(UserActionEnum.TOGGLE_INVOICE_ADDRESS, {
335
- value,
336
- })
337
- }
338
- />
339
- ) : null;
340
-
341
- return (
342
- <FormProvider {...methods}>
343
- <form
344
- ref={formRef}
345
- className="sdk-order-form flex w-full flex-col gap-6"
346
- noValidate
347
- onSubmit={handleSubmit(onSubmit)}
348
- data-testid="sdk-order-form-id"
349
- >
350
- {renderInSlot(
351
- paymentMethodSection,
352
- paymentMethodSlot,
353
- handleSlotKeyDown
354
- )}
355
- {renderInSlot(
356
- contactDetailsSection,
357
- contactDetailsSlot,
358
- handleSlotKeyDown
359
- )}
360
- <div className="sdk-order-actions-section flex flex-col gap-4">
361
- {requireTermsAcceptance && (
362
- <TermsCheckbox
363
- name="termsAccept"
364
- label={termsAndConditionsText}
365
- required
366
- />
367
- )}
368
- {derived.allowPaymentMethod && (
369
- <Button
370
- type="submit"
371
- loading={loading}
372
- buttonText={submitButtonText}
373
- className="w-full"
374
- />
375
- )}
376
- <Alert
377
- msg={
378
- derived.allowPaymentMethod
379
- ? apiErrorMsg
380
- : paymentMethodNotAllowedMsg
381
- }
382
- />
383
- {errorsMsg?.length > 0 &&
384
- derived.allowPaymentMethod &&
385
- errorsMsg.map((i, index) => (
386
- <Alert key={`${i}-${index}`} msg={i} />
387
- ))}
388
- </div>
389
- {submitConfirmation && (
390
- <SubmitConfirmationDialog
391
- isOpen={!!pendingSubmit}
392
- confirmation={submitConfirmation}
393
- onConfirm={confirmSubmit}
394
- onCancel={() => setPendingSubmit(null)}
395
- />
396
- )}
397
- <OrderDenialModal
398
- isOpen={!!orderDenialType}
399
- message={orderDenialMessage}
400
- closeButtonText={orderDenialCloseButtonText}
401
- continueButtonText={orderDenialContinueButtonText}
402
- canContinue={
403
- orderDenialType === 'offer' &&
404
- !!orderDenialFallbackOffer?.templatePackageId
405
- }
406
- offer={
407
- orderDenialType === 'offer' &&
408
- !!orderDenialFallbackOffer?.templatePackageId
409
- ? orderDenialFallbackOffer
410
- : undefined
411
- }
412
- onClose={dismissOrderDenial}
413
- onContinue={continueWithFallbackOffer}
414
- />
415
- </form>
416
- </FormProvider>
417
- );
418
- };
419
-
420
- export default OrderForm;
1
+ import {
2
+ type FC,
3
+ type KeyboardEvent,
4
+ type ReactNode,
5
+ useEffect,
6
+ useRef,
7
+ useState,
8
+ } from 'react';
9
+ import {
10
+ FormProvider,
11
+ useForm,
12
+ type Resolver,
13
+ type SubmitHandler,
14
+ } from 'react-hook-form';
15
+ import { zodResolver } from '@hookform/resolvers/zod';
16
+
17
+ import { PaymentMethodEnum, UserActionEnum } from '../../enums/general';
18
+ import { PAYMENT_METHOD_DEFAULT } from '../../constants/index';
19
+ import Alert from '../Alert/Alert';
20
+ import Button from '../Button/Button';
21
+ import OrderDenialModal from '../OrderDenialModal/OrderDenialModal';
22
+ import TermsCheckbox from '../FormFields/TermsCheckbox';
23
+ import type { OrderFormInputsType, OrderInfoType } from '../../types/order';
24
+ import type {
25
+ PaymentMethodSettingsType,
26
+ PaymentMethodOptionType,
27
+ OrderFormFieldType,
28
+ ContactRequestType,
29
+ OrderDenialFallbackOfferType,
30
+ SubmitConfirmationType,
31
+ } from '../../types/general';
32
+ import useOrderForm from '../../hooks/useOrderForm';
33
+ import { useSlotElement, renderInSlot } from './useSlotElement';
34
+ import {
35
+ deriveOrderFormState,
36
+ buildOrderFormSchema,
37
+ type OrderFormConfig,
38
+ } from './orderFormState';
39
+ import PaymentMethodSection from './PaymentMethodSection';
40
+ import ContactDetailsSection from './ContactDetailsSection';
41
+ import SubmitConfirmationDialog from './SubmitConfirmationDialog';
42
+
43
+ type Props = {
44
+ callback: (url: string | null, orderInfo?: OrderInfoType | null) => void;
45
+ updateFormData: (data: OrderFormInputsType) => void;
46
+ submitStartCallback?: (id: string) => void;
47
+ userActionCallback?: (
48
+ action: UserActionEnum,
49
+ args: object | null | undefined
50
+ ) => void;
51
+ setContactCallback?: (contactInfo: ContactRequestType) => void;
52
+ templatePackageId: string;
53
+ subscriberId?: string;
54
+ userId?: string;
55
+ identityProviderId?: string;
56
+ organizationId: string;
57
+ redirectUrl?: string;
58
+ showIframe?: boolean;
59
+ language: string;
60
+ merchantAgreementUrl: string;
61
+ paymentMethodsOptions?: PaymentMethodSettingsType;
62
+ defaultValues?: OrderFormInputsType;
63
+ paymentMethods?: PaymentMethodOptionType[];
64
+ allowedPaymentMethods?: PaymentMethodEnum[];
65
+ submitButtonText?: string;
66
+ orderDenialCloseButtonText?: string;
67
+ orderDenialContinueButtonText?: string;
68
+ paymentMethodLabel?: string;
69
+ contactDetailsLabel?: string;
70
+ paymentMethodElementId?: string;
71
+ contactDetailsElementId?: string;
72
+ paymentMethodNotAllowedMsg?: string;
73
+ errorReqMsg?: string;
74
+ errorInvalidEmailMsg?: string;
75
+ errorInvalidPhoneMsg?: string;
76
+ errorTermsMsg?: string;
77
+ invoiceAddressSelection?: {
78
+ enabled?: boolean;
79
+ label?: string;
80
+ fields?: OrderFormFieldType[];
81
+ paymentMethods?: PaymentMethodEnum[];
82
+ };
83
+ requireTermsAcceptance?: boolean;
84
+ errorValidationTitleMsg?: string;
85
+ errorValidationDenialOrderBlockingMsg?: string;
86
+ errorValidationBlockingOffersMsg?: string;
87
+ orderDenialOfferBaseText?: string;
88
+ orderDenialOfferWithFallbackText?: string;
89
+ orderDenialAmountText?: string;
90
+ fetchDenialFallbackOffer?: (
91
+ organizationId: string
92
+ ) => Promise<OrderDenialFallbackOfferType | undefined>;
93
+ termsAndConditionsText?: string | ReactNode;
94
+ submitConfirmation?: SubmitConfirmationType;
95
+ };
96
+
97
+ const initialData = {
98
+ invoiceAddressSelection: false,
99
+ name: '',
100
+ email: '',
101
+ phoneNumber: '',
102
+ country: '',
103
+ city: '',
104
+ address: '',
105
+ zip: '',
106
+ paymentMethod: PAYMENT_METHOD_DEFAULT,
107
+ orderReference: '',
108
+ };
109
+
110
+ const OrderForm: FC<Props> = ({
111
+ callback,
112
+ updateFormData,
113
+ submitStartCallback,
114
+ userActionCallback,
115
+ setContactCallback,
116
+ templatePackageId,
117
+ subscriberId,
118
+ userId,
119
+ identityProviderId,
120
+ organizationId,
121
+ redirectUrl,
122
+ showIframe,
123
+ paymentMethodsOptions,
124
+ defaultValues,
125
+ language,
126
+ merchantAgreementUrl,
127
+ paymentMethods = [],
128
+ allowedPaymentMethods,
129
+ invoiceAddressSelection,
130
+ submitButtonText = 'Start',
131
+ orderDenialCloseButtonText = 'Close',
132
+ orderDenialContinueButtonText = 'Continue',
133
+ paymentMethodLabel = 'Select payment method',
134
+ contactDetailsLabel,
135
+ paymentMethodElementId,
136
+ contactDetailsElementId,
137
+ paymentMethodNotAllowedMsg = 'This payment method not allowed!',
138
+ errorReqMsg = '',
139
+ errorInvalidEmailMsg = '',
140
+ errorInvalidPhoneMsg = '',
141
+ errorTermsMsg = '',
142
+ errorValidationTitleMsg,
143
+ errorValidationDenialOrderBlockingMsg,
144
+ errorValidationBlockingOffersMsg,
145
+ orderDenialOfferBaseText,
146
+ orderDenialOfferWithFallbackText,
147
+ orderDenialAmountText,
148
+ fetchDenialFallbackOffer,
149
+ requireTermsAcceptance,
150
+ termsAndConditionsText,
151
+ submitConfirmation,
152
+ }) => {
153
+ const subscriberIdValue =
154
+ subscriberId || sessionStorage.getItem('subscriberId') || undefined;
155
+
156
+ useEffect(() => {
157
+ if (!templatePackageId)
158
+ console.error('"templatePackageId" should be set');
159
+ if (!organizationId) console.error('"organizationId" should be set');
160
+ if (!userId) console.error('"userId" should be set');
161
+ if (!identityProviderId)
162
+ console.error('"identityProviderId" should be set');
163
+ }, [templatePackageId, organizationId, userId, identityProviderId]);
164
+
165
+ const config: OrderFormConfig = {
166
+ paymentMethods,
167
+ paymentMethodsOptions,
168
+ allowedPaymentMethods,
169
+ invoiceAddressSelection,
170
+ };
171
+
172
+ const messages = {
173
+ errorReqMsg,
174
+ errorInvalidEmailMsg,
175
+ errorInvalidPhoneMsg,
176
+ errorTermsMsg,
177
+ };
178
+
179
+ const configuredPaymentMethods = paymentMethods.map((m) => m.value);
180
+ const initialPaymentMethod = configuredPaymentMethods.length
181
+ ? ([defaultValues?.paymentMethod, PAYMENT_METHOD_DEFAULT].find(
182
+ (m) => m && configuredPaymentMethods.includes(m)
183
+ ) ?? configuredPaymentMethods[0])
184
+ : defaultValues?.paymentMethod || PAYMENT_METHOD_DEFAULT;
185
+
186
+ const resolver: Resolver<OrderFormInputsType> = (values, ctx, options) => {
187
+ const schema = buildOrderFormSchema(
188
+ deriveOrderFormState(values, config),
189
+ requireTermsAcceptance,
190
+ messages
191
+ );
192
+ return zodResolver(schema)(values, ctx, options);
193
+ };
194
+
195
+ const methods = useForm<OrderFormInputsType>({
196
+ resolver,
197
+ defaultValues: {
198
+ ...initialData,
199
+ ...(defaultValues ?? {}),
200
+ paymentMethod: initialPaymentMethod,
201
+ },
202
+ });
203
+
204
+ const { control, handleSubmit, setValue, watch } = methods;
205
+
206
+ const derived = deriveOrderFormState(
207
+ {
208
+ paymentMethod: watch('paymentMethod'),
209
+ invoiceAddressSelection: watch('invoiceAddressSelection'),
210
+ },
211
+ config
212
+ );
213
+
214
+ useEffect(() => {
215
+ userActionCallback?.(UserActionEnum.SELECT_PAYMENT_METHOD, {
216
+ paymentMethod: methods.getValues('paymentMethod'),
217
+ initial: true,
218
+ });
219
+ }, []);
220
+
221
+ const {
222
+ orderSubmit,
223
+ continueWithFallbackOffer,
224
+ loading,
225
+ apiErrorMsg,
226
+ errorsMsg,
227
+ orderDenialType,
228
+ orderDenialMessage,
229
+ orderDenialFallbackOffer,
230
+ dismissOrderDenial,
231
+ } = useOrderForm({
232
+ callback,
233
+ submitStartCallback,
234
+ userActionCallback,
235
+ setContactCallback,
236
+ organizationId,
237
+ subscriberId: subscriberIdValue,
238
+ userId,
239
+ identityProviderId,
240
+ orderFields: derived.orderFields,
241
+ redirectUrl,
242
+ showIframe,
243
+ language,
244
+ merchantAgreementUrl,
245
+ paymentMethodsOptions,
246
+ templatePackageId,
247
+ invoiceAddressToggle: watch('invoiceAddressSelection'),
248
+ invoiceOrderFields: derived.invoiceOrderFields,
249
+ errorValidationTitleMsg,
250
+ errorValidationDenialOrderBlockingMsg,
251
+ errorValidationBlockingOffersMsg,
252
+ orderDenialOfferBaseText,
253
+ orderDenialOfferWithFallbackText,
254
+ orderDenialAmountText,
255
+ fetchDenialFallbackOffer,
256
+ });
257
+
258
+ const [pendingSubmit, setPendingSubmit] =
259
+ useState<OrderFormInputsType | null>(null);
260
+
261
+ const submitOrder = async (data: OrderFormInputsType): Promise<void> => {
262
+ if (
263
+ derived.paymentMethod === PaymentMethodEnum.EHF ||
264
+ derived.paymentMethod === PaymentMethodEnum.OIO
265
+ ) {
266
+ updateFormData?.(data);
267
+ return;
268
+ }
269
+ await orderSubmit(data);
270
+ };
271
+
272
+ const onSubmit: SubmitHandler<OrderFormInputsType> = async (data) => {
273
+ if (submitConfirmation) {
274
+ setPendingSubmit(data);
275
+ return;
276
+ }
277
+ await submitOrder(data);
278
+ };
279
+
280
+ const confirmSubmit = () => {
281
+ const data = pendingSubmit;
282
+ setPendingSubmit(null);
283
+ if (data) submitOrder(data);
284
+ };
285
+
286
+ const handlePaymentChange = (paymentMethod: PaymentMethodEnum) => {
287
+ setValue('paymentMethod', paymentMethod, { shouldValidate: true });
288
+ if (!derived.invoicePaymentMethods.includes(paymentMethod)) {
289
+ setValue('invoiceAddressSelection', false);
290
+ }
291
+
292
+ userActionCallback?.(UserActionEnum.SELECT_PAYMENT_METHOD, {
293
+ paymentMethod,
294
+ });
295
+ };
296
+
297
+ const paymentMethodSlot = useSlotElement(paymentMethodElementId);
298
+ const contactDetailsSlot = useSlotElement(contactDetailsElementId);
299
+ const formRef = useRef<HTMLFormElement>(null);
300
+
301
+ const handleSlotKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
302
+ if (event.key !== 'Enter' || event.defaultPrevented) return;
303
+ if (!derived.allowPaymentMethod || loading) return;
304
+
305
+ const target = event.target as HTMLElement;
306
+ if (target.tagName !== 'INPUT') return;
307
+
308
+ const { type } = target as HTMLInputElement;
309
+ if (type === 'button' || type === 'submit' || type === 'reset') return;
310
+
311
+ event.preventDefault();
312
+ formRef.current?.requestSubmit();
313
+ };
314
+
315
+ const paymentMethodSection = derived.showPaymentMethodSelection ? (
316
+ <PaymentMethodSection
317
+ control={control}
318
+ paymentMethods={paymentMethods}
319
+ label={paymentMethodLabel}
320
+ onChange={handlePaymentChange}
321
+ />
322
+ ) : null;
323
+
324
+ const contactDetailsSection = derived.showContactDetails ? (
325
+ <ContactDetailsSection
326
+ label={contactDetailsLabel}
327
+ orderFields={derived.orderFields}
328
+ invoiceOrderFields={derived.invoiceOrderFields}
329
+ showOrderFields={derived.showOrderFields}
330
+ showInvoiceToggle={derived.showInvoiceToggle}
331
+ showInvoiceFields={derived.showInvoiceFields}
332
+ invoiceToggleLabel={invoiceAddressSelection?.label}
333
+ onInvoiceToggle={(value) =>
334
+ userActionCallback?.(UserActionEnum.TOGGLE_INVOICE_ADDRESS, {
335
+ value,
336
+ })
337
+ }
338
+ />
339
+ ) : null;
340
+
341
+ return (
342
+ <FormProvider {...methods}>
343
+ <form
344
+ ref={formRef}
345
+ className="sdk-order-form flex w-full flex-col gap-6"
346
+ noValidate
347
+ onSubmit={handleSubmit(onSubmit)}
348
+ data-testid="sdk-order-form-id"
349
+ >
350
+ {renderInSlot(
351
+ paymentMethodSection,
352
+ paymentMethodSlot,
353
+ handleSlotKeyDown
354
+ )}
355
+ {renderInSlot(
356
+ contactDetailsSection,
357
+ contactDetailsSlot,
358
+ handleSlotKeyDown
359
+ )}
360
+ <div className="sdk-order-actions-section flex flex-col gap-4">
361
+ {requireTermsAcceptance && (
362
+ <TermsCheckbox
363
+ name="termsAccept"
364
+ label={termsAndConditionsText}
365
+ required
366
+ />
367
+ )}
368
+ {derived.allowPaymentMethod && (
369
+ <Button
370
+ type="submit"
371
+ loading={loading}
372
+ buttonText={submitButtonText}
373
+ className="w-full"
374
+ />
375
+ )}
376
+ <Alert
377
+ msg={
378
+ derived.allowPaymentMethod
379
+ ? apiErrorMsg
380
+ : paymentMethodNotAllowedMsg
381
+ }
382
+ />
383
+ {errorsMsg?.length > 0 &&
384
+ derived.allowPaymentMethod &&
385
+ errorsMsg.map((i, index) => (
386
+ <Alert key={`${i}-${index}`} msg={i} />
387
+ ))}
388
+ </div>
389
+ {submitConfirmation && (
390
+ <SubmitConfirmationDialog
391
+ isOpen={!!pendingSubmit}
392
+ confirmation={submitConfirmation}
393
+ onConfirm={confirmSubmit}
394
+ onCancel={() => setPendingSubmit(null)}
395
+ />
396
+ )}
397
+ <OrderDenialModal
398
+ isOpen={!!orderDenialType}
399
+ message={orderDenialMessage}
400
+ closeButtonText={orderDenialCloseButtonText}
401
+ continueButtonText={orderDenialContinueButtonText}
402
+ canContinue={
403
+ orderDenialType === 'offer' &&
404
+ !!orderDenialFallbackOffer?.templatePackageId
405
+ }
406
+ offer={
407
+ orderDenialType === 'offer' &&
408
+ !!orderDenialFallbackOffer?.templatePackageId
409
+ ? orderDenialFallbackOffer
410
+ : undefined
411
+ }
412
+ onClose={dismissOrderDenial}
413
+ onContinue={continueWithFallbackOffer}
414
+ />
415
+ </form>
416
+ </FormProvider>
417
+ );
418
+ };
419
+
420
+ export default OrderForm;