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