@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,403 +1,400 @@
1
- import { useRef, useState } from 'react';
2
- import type { SubmitHandler } from 'react-hook-form';
3
-
4
- import { createSubscriber } from '../api/SubscribeApi';
5
- import { orderStart } from '../api/OrdersApi';
6
- import { invoiceLookup } from '../api/InvoiceApi';
7
- import {
8
- InvoiceLookupNetworkEnum,
9
- PaymentMethodEnum,
10
- UserActionEnum,
11
- } from '../enums/general';
12
- import { WRONG_MSG, PAYMENT_METHOD_DEFAULT } from '../constants/index';
13
- import type { OrderFormInputsType, OrderInfoType } from '../types/order';
14
- import type {
15
- ErrorsMsg,
16
- OrderFormFieldType,
17
- OrderDenialFallbackOfferType,
18
- PaymentMethodSettingsType,
19
- ContactRequestType,
20
- } from '../types/general';
21
- import {
22
- prepareAgreementModel,
23
- prepareContactModel,
24
- prepareInvoiceModel,
25
- } from '../utils/order.helper';
26
- import {
27
- prepareErrorMessage,
28
- prepareErrorsArrayMessage,
29
- type ErrorMessages,
30
- } from '../utils/helper';
31
-
32
- type Props = {
33
- callback: (url: string | null, orderInfo?: OrderInfoType | null) => void;
34
- submitStartCallback?: (id: string) => void;
35
- userActionCallback?: (
36
- action: UserActionEnum,
37
- args: object | null | undefined
38
- ) => void;
39
- setContactCallback?: (contactInfo: ContactRequestType) => void;
40
- templatePackageId: string;
41
- subscriberId?: string;
42
- userId?: string;
43
- identityProviderId?: string;
44
- organizationId: string;
45
- redirectUrl?: string;
46
- showIframe?: boolean;
47
- language: string;
48
- merchantAgreementUrl: string;
49
- paymentMethodsOptions?: PaymentMethodSettingsType;
50
- orderFields: OrderFormFieldType[];
51
- invoiceAddressToggle?: boolean;
52
- invoiceOrderFields: OrderFormFieldType[];
53
- invoiceLookupNotFoundText?: string;
54
- errorValidationTitleMsg?: string;
55
- errorValidationDenialOrderBlockingMsg?: string;
56
- errorValidationBlockingOffersMsg?: string;
57
- orderDenialOfferBaseText?: string;
58
- orderDenialOfferWithFallbackText?: string;
59
- orderDenialAmountText?: string;
60
- fetchDenialFallbackOffer?: (
61
- organizationId: string
62
- ) => Promise<OrderDenialFallbackOfferType | undefined>;
63
- };
64
-
65
- type DenialErrorType = {
66
- status?: number;
67
- errors?: Record<string, string[] | undefined>;
68
- };
69
-
70
- const OFFER_DENIAL_BASE_TEXT =
71
- 'Hello again!\n\nLooks like you already tried this offer.';
72
- const OFFER_DENIAL_WITH_FALLBACK_TEXT =
73
- 'Hello again!\n\nLooks like you already tried this offer, but we would like to keep you with us.\n\nTherefore we got a new great offer for you:';
74
-
75
- const getDenialErrorType = (
76
- error: DenialErrorType
77
- ): 'offer' | 'amount' | null => {
78
- if (error?.status !== 400 || !error?.errors) {
79
- return null;
80
- }
81
-
82
- const normalizedEntries = Object.entries(error.errors).map(
83
- ([key, value]) => [key.toLowerCase(), value] as const
84
- );
85
-
86
- const hasOffer = normalizedEntries.some(
87
- ([key, value]) =>
88
- key === 'offer' && Array.isArray(value) && value.length > 0
89
- );
90
-
91
- if (hasOffer) {
92
- return 'offer';
93
- }
94
-
95
- const hasAmount = normalizedEntries.some(
96
- ([key, value]) =>
97
- key === 'amount' && Array.isArray(value) && value.length > 0
98
- );
99
-
100
- if (hasAmount) {
101
- return 'amount';
102
- }
103
-
104
- return null;
105
- };
106
-
107
- const useOrderForm = ({
108
- callback,
109
- submitStartCallback,
110
- userActionCallback,
111
- setContactCallback,
112
- organizationId,
113
- subscriberId,
114
- userId,
115
- identityProviderId,
116
- orderFields,
117
- redirectUrl,
118
- showIframe,
119
- language,
120
- merchantAgreementUrl,
121
- paymentMethodsOptions,
122
- templatePackageId,
123
- invoiceAddressToggle,
124
- invoiceOrderFields,
125
- invoiceLookupNotFoundText,
126
- errorValidationTitleMsg,
127
- errorValidationDenialOrderBlockingMsg,
128
- errorValidationBlockingOffersMsg,
129
- orderDenialOfferBaseText,
130
- orderDenialOfferWithFallbackText,
131
- orderDenialAmountText,
132
- fetchDenialFallbackOffer,
133
- }: Props) => {
134
- const [loading, setLoading] = useState<boolean>(false);
135
- const [apiErrorMsg, setApiErrorMsg] = useState<string>('');
136
- const [errorsMsg, setErrorsMsg] = useState<string[]>([]);
137
- const [orderDenialType, setOrderDenialType] = useState<
138
- 'offer' | 'amount' | null
139
- >(null);
140
- const [orderDenialFallbackOffer, setOrderDenialFallbackOffer] = useState<
141
- OrderDenialFallbackOfferType | undefined
142
- >();
143
- const [submittedOrderData, setSubmittedOrderData] =
144
- useState<OrderFormInputsType | null>(null);
145
- const fallbackOfferTemplatePackageIdRef = useRef<string | null>(null);
146
-
147
- const dismissOrderDenial = () => {
148
- setOrderDenialType(null);
149
- setOrderDenialFallbackOffer(undefined);
150
- };
151
-
152
- const getOrderDenialMessage = () => {
153
- if (orderDenialType === 'offer') {
154
- if (orderDenialFallbackOffer?.templatePackageId) {
155
- return (
156
- orderDenialOfferWithFallbackText ||
157
- OFFER_DENIAL_WITH_FALLBACK_TEXT
158
- );
159
- }
160
-
161
- return orderDenialOfferBaseText || OFFER_DENIAL_BASE_TEXT;
162
- }
163
-
164
- if (orderDenialType === 'amount') {
165
- return (
166
- orderDenialAmountText ||
167
- errorValidationDenialOrderBlockingMsg ||
168
- WRONG_MSG
169
- );
170
- }
171
-
172
- return '';
173
- };
174
-
175
- const orderSubmit: SubmitHandler<OrderFormInputsType> = async (
176
- data
177
- ): Promise<void> => {
178
- setApiErrorMsg('');
179
- setErrorsMsg([]);
180
- setOrderDenialType(null);
181
- setLoading(true);
182
- setSubmittedOrderData(data);
183
- try {
184
- let id: string | undefined = subscriberId;
185
- let invoiceResponse = null;
186
- if (data.paymentMethod === PaymentMethodEnum.OIO) {
187
- invoiceResponse = await invoiceLookup({
188
- network: data.gln
189
- ? InvoiceLookupNetworkEnum.OIO_GLN
190
- : InvoiceLookupNetworkEnum.OIO_Danish_CVR,
191
- value: data.gln || data.cvr || '',
192
- });
193
- }
194
- if (data.paymentMethod === PaymentMethodEnum.EHF) {
195
- invoiceResponse = await invoiceLookup({
196
- network: InvoiceLookupNetworkEnum.EHF,
197
- value: data.organizationNumber || '',
198
- });
199
- }
200
-
201
- // TODO: "recievesInvoice" should be deleted in the future
202
- const receivesInvoice =
203
- invoiceResponse?.receivesInvoice ||
204
- invoiceResponse?.recievesInvoice;
205
-
206
- if (invoiceResponse) {
207
- userActionCallback?.(
208
- UserActionEnum.SEARCH_ORGANIZATION_NUMBER,
209
- {
210
- organizationNumber: data.organizationNumber,
211
- cvr: data.cvr,
212
- gln: data.gln,
213
- found: !!receivesInvoice,
214
- }
215
- );
216
- }
217
-
218
- if (invoiceResponse && !receivesInvoice) {
219
- setLoading(false);
220
- const value =
221
- data.paymentMethod === PaymentMethodEnum.OIO
222
- ? data.gln || data.cvr || ''
223
- : data.organizationNumber || '';
224
- setApiErrorMsg(`${invoiceLookupNotFoundText || ''} (${value})`);
225
- return;
226
- }
227
-
228
- const contactModel = prepareContactModel({ data, orderFields });
229
- if (!subscriberId) {
230
- const response = await createSubscriber({
231
- ...contactModel,
232
- gln: data?.gln,
233
- organizationNumber:
234
- data.paymentMethod === PaymentMethodEnum.OIO
235
- ? data?.cvr
236
- : data.organizationNumber || undefined,
237
- ...(userId &&
238
- identityProviderId && { userId, identityProviderId }),
239
- });
240
- id = response.id;
241
-
242
- sessionStorage.setItem('subscriberId', id); // For avoiding attempt of creating subscriber again
243
- }
244
-
245
- if (setContactCallback) {
246
- setContactCallback(contactModel);
247
- }
248
-
249
- submitStartCallback?.(id as string);
250
-
251
- if (id) {
252
- const paymentMethod =
253
- data.paymentMethod || PAYMENT_METHOD_DEFAULT;
254
- const selectedTemplateSubscriptionPlanId =
255
- fallbackOfferTemplatePackageIdRef.current ||
256
- templatePackageId;
257
- fallbackOfferTemplatePackageIdRef.current = null;
258
-
259
- const agreements = prepareAgreementModel({
260
- paymentMethod,
261
- redirectUrl,
262
- showIframe,
263
- phoneNumber: orderFields.find(
264
- (i) => i.name === 'phoneNumber'
265
- )
266
- ? data.phoneNumber?.trim() || undefined
267
- : undefined,
268
- language,
269
- merchantAgreementUrl,
270
- generateSubscriberContact:
271
- paymentMethodsOptions?.[
272
- data.paymentMethod as PaymentMethodEnum
273
- ]?.generateSubscriberContact || false,
274
- accountId:
275
- paymentMethodsOptions?.[
276
- data.paymentMethod as PaymentMethodEnum
277
- ]?.accountId,
278
- });
279
- const responseOrder = await orderStart({
280
- subscriberId: id,
281
- subscriptionPlan: {
282
- organizationId,
283
- templateSubscriptionPlanId:
284
- selectedTemplateSubscriptionPlanId,
285
- },
286
- paymentAgreement: { ...agreements },
287
- invoiceContact: invoiceAddressToggle
288
- ? prepareInvoiceModel({
289
- data,
290
- orderFields: invoiceOrderFields,
291
- })
292
- : undefined,
293
- orderReference: data.orderReference || undefined,
294
- });
295
-
296
- if (!responseOrder.id) {
297
- callback(null);
298
- setApiErrorMsg(WRONG_MSG);
299
- setErrorsMsg([]);
300
- return;
301
- }
302
-
303
- callback(responseOrder.terminalRedirectUrl, {
304
- ...(data || {}),
305
- orderId: responseOrder.id,
306
- subscriberId: id,
307
- paymentMethod: paymentMethod,
308
- });
309
- return;
310
- }
311
- callback(null);
312
- setApiErrorMsg(WRONG_MSG);
313
- setErrorsMsg([]);
314
- } catch (error) {
315
- const translations = {
316
- errorValidationTitleMsg,
317
- errorValidationBlockingOffersMsg,
318
- errorValidationDenialOrderBlockingMsg,
319
- } as ErrorMessages;
320
-
321
- const detectedDenialType = getDenialErrorType(
322
- error as DenialErrorType
323
- );
324
- if (detectedDenialType) {
325
- setApiErrorMsg('');
326
- setErrorsMsg([]);
327
- setOrderDenialFallbackOffer(undefined);
328
- setOrderDenialType(detectedDenialType);
329
- callback(null);
330
- if (
331
- detectedDenialType === 'offer' &&
332
- fetchDenialFallbackOffer
333
- ) {
334
- void fetchDenialFallbackOffer(organizationId)
335
- .then((offer) => {
336
- setOrderDenialFallbackOffer(offer);
337
- if (offer?.templatePackageId) {
338
- fallbackOfferTemplatePackageIdRef.current =
339
- offer.templatePackageId;
340
- }
341
- })
342
- .catch(() => {
343
- setOrderDenialFallbackOffer(undefined);
344
- });
345
- }
346
- return;
347
- }
348
-
349
- console.error(error);
350
- setApiErrorMsg(
351
- prepareErrorMessage(error as Error, undefined, translations)
352
- );
353
- setErrorsMsg(
354
- prepareErrorsArrayMessage(
355
- (
356
- error as {
357
- errors: ErrorsMsg;
358
- }
359
- )?.errors,
360
- translations
361
- )
362
- );
363
- callback(null);
364
- } finally {
365
- setLoading(false);
366
- }
367
- };
368
-
369
- const continueWithFallbackOffer = async () => {
370
- if (orderDenialType !== 'offer' || !submittedOrderData) {
371
- return;
372
- }
373
-
374
- const fallbackTemplatePackageId =
375
- orderDenialFallbackOffer?.templatePackageId;
376
-
377
- if (!fallbackTemplatePackageId) {
378
- dismissOrderDenial();
379
- return;
380
- }
381
-
382
- fallbackOfferTemplatePackageIdRef.current = fallbackTemplatePackageId;
383
- userActionCallback?.(UserActionEnum.SELECT_FALLBACK_OFFER, {
384
- templatePackageId: fallbackTemplatePackageId,
385
- });
386
- dismissOrderDenial();
387
- await orderSubmit(submittedOrderData);
388
- };
389
-
390
- return {
391
- orderSubmit,
392
- continueWithFallbackOffer,
393
- loading,
394
- apiErrorMsg,
395
- errorsMsg,
396
- orderDenialType,
397
- orderDenialMessage: getOrderDenialMessage(),
398
- orderDenialFallbackOffer,
399
- dismissOrderDenial,
400
- };
401
- };
402
-
403
- export default useOrderForm;
1
+ import { useRef, useState } from 'react';
2
+ import type { SubmitHandler } from 'react-hook-form';
3
+
4
+ import { createSubscriber } from '../api/SubscribeApi';
5
+ import { orderStart } from '../api/OrdersApi';
6
+ import { invoiceLookup } from '../api/InvoiceApi';
7
+ import {
8
+ InvoiceLookupNetworkEnum,
9
+ PaymentMethodEnum,
10
+ UserActionEnum,
11
+ } from '../enums/general';
12
+ import { WRONG_MSG, PAYMENT_METHOD_DEFAULT } from '../constants/index';
13
+ import type { OrderFormInputsType, OrderInfoType } from '../types/order';
14
+ import type {
15
+ ErrorsMsg,
16
+ OrderFormFieldType,
17
+ OrderDenialFallbackOfferType,
18
+ PaymentMethodSettingsType,
19
+ ContactRequestType,
20
+ } from '../types/general';
21
+ import {
22
+ prepareAgreementModel,
23
+ prepareContactModel,
24
+ prepareInvoiceModel,
25
+ } from '../utils/order.helper';
26
+ import {
27
+ prepareErrorMessage,
28
+ prepareErrorsArrayMessage,
29
+ type ErrorMessages,
30
+ } from '../utils/helper';
31
+
32
+ type Props = {
33
+ callback: (url: string | null, orderInfo?: OrderInfoType | null) => void;
34
+ submitStartCallback?: (id: string) => void;
35
+ userActionCallback?: (
36
+ action: UserActionEnum,
37
+ args: object | null | undefined
38
+ ) => void;
39
+ setContactCallback?: (contactInfo: ContactRequestType) => void;
40
+ templatePackageId: string;
41
+ subscriberId?: string;
42
+ userId?: string;
43
+ identityProviderId?: string;
44
+ organizationId: string;
45
+ redirectUrl?: string;
46
+ language: string;
47
+ merchantAgreementUrl: string;
48
+ paymentMethodsOptions?: PaymentMethodSettingsType;
49
+ orderFields: OrderFormFieldType[];
50
+ invoiceAddressToggle?: boolean;
51
+ invoiceOrderFields: OrderFormFieldType[];
52
+ invoiceLookupNotFoundText?: string;
53
+ errorValidationTitleMsg?: string;
54
+ errorValidationDenialOrderBlockingMsg?: string;
55
+ errorValidationBlockingOffersMsg?: string;
56
+ orderDenialOfferBaseText?: string;
57
+ orderDenialOfferWithFallbackText?: string;
58
+ orderDenialAmountText?: string;
59
+ fetchDenialFallbackOffer?: (
60
+ organizationId: string
61
+ ) => Promise<OrderDenialFallbackOfferType | undefined>;
62
+ };
63
+
64
+ type DenialErrorType = {
65
+ status?: number;
66
+ errors?: Record<string, string[] | undefined>;
67
+ };
68
+
69
+ const OFFER_DENIAL_BASE_TEXT =
70
+ 'Hello again!\n\nLooks like you already tried this offer.';
71
+ const OFFER_DENIAL_WITH_FALLBACK_TEXT =
72
+ 'Hello again!\n\nLooks like you already tried this offer, but we would like to keep you with us.\n\nTherefore we got a new great offer for you:';
73
+
74
+ const getDenialErrorType = (
75
+ error: DenialErrorType
76
+ ): 'offer' | 'amount' | null => {
77
+ if (error?.status !== 400 || !error?.errors) {
78
+ return null;
79
+ }
80
+
81
+ const normalizedEntries = Object.entries(error.errors).map(
82
+ ([key, value]) => [key.toLowerCase(), value] as const
83
+ );
84
+
85
+ const hasOffer = normalizedEntries.some(
86
+ ([key, value]) =>
87
+ key === 'offer' && Array.isArray(value) && value.length > 0
88
+ );
89
+
90
+ if (hasOffer) {
91
+ return 'offer';
92
+ }
93
+
94
+ const hasAmount = normalizedEntries.some(
95
+ ([key, value]) =>
96
+ key === 'amount' && Array.isArray(value) && value.length > 0
97
+ );
98
+
99
+ if (hasAmount) {
100
+ return 'amount';
101
+ }
102
+
103
+ return null;
104
+ };
105
+
106
+ const useOrderForm = ({
107
+ callback,
108
+ submitStartCallback,
109
+ userActionCallback,
110
+ setContactCallback,
111
+ organizationId,
112
+ subscriberId,
113
+ userId,
114
+ identityProviderId,
115
+ orderFields,
116
+ redirectUrl,
117
+ language,
118
+ merchantAgreementUrl,
119
+ paymentMethodsOptions,
120
+ templatePackageId,
121
+ invoiceAddressToggle,
122
+ invoiceOrderFields,
123
+ invoiceLookupNotFoundText,
124
+ errorValidationTitleMsg,
125
+ errorValidationDenialOrderBlockingMsg,
126
+ errorValidationBlockingOffersMsg,
127
+ orderDenialOfferBaseText,
128
+ orderDenialOfferWithFallbackText,
129
+ orderDenialAmountText,
130
+ fetchDenialFallbackOffer,
131
+ }: Props) => {
132
+ const [loading, setLoading] = useState<boolean>(false);
133
+ const [apiErrorMsg, setApiErrorMsg] = useState<string>('');
134
+ const [errorsMsg, setErrorsMsg] = useState<string[]>([]);
135
+ const [orderDenialType, setOrderDenialType] = useState<
136
+ 'offer' | 'amount' | null
137
+ >(null);
138
+ const [orderDenialFallbackOffer, setOrderDenialFallbackOffer] = useState<
139
+ OrderDenialFallbackOfferType | undefined
140
+ >();
141
+ const [submittedOrderData, setSubmittedOrderData] =
142
+ useState<OrderFormInputsType | null>(null);
143
+ const fallbackOfferTemplatePackageIdRef = useRef<string | null>(null);
144
+
145
+ const dismissOrderDenial = () => {
146
+ setOrderDenialType(null);
147
+ setOrderDenialFallbackOffer(undefined);
148
+ };
149
+
150
+ const getOrderDenialMessage = () => {
151
+ if (orderDenialType === 'offer') {
152
+ if (orderDenialFallbackOffer?.templatePackageId) {
153
+ return (
154
+ orderDenialOfferWithFallbackText ||
155
+ OFFER_DENIAL_WITH_FALLBACK_TEXT
156
+ );
157
+ }
158
+
159
+ return orderDenialOfferBaseText || OFFER_DENIAL_BASE_TEXT;
160
+ }
161
+
162
+ if (orderDenialType === 'amount') {
163
+ return (
164
+ orderDenialAmountText ||
165
+ errorValidationDenialOrderBlockingMsg ||
166
+ WRONG_MSG
167
+ );
168
+ }
169
+
170
+ return '';
171
+ };
172
+
173
+ const orderSubmit: SubmitHandler<OrderFormInputsType> = async (
174
+ data
175
+ ): Promise<void> => {
176
+ setApiErrorMsg('');
177
+ setErrorsMsg([]);
178
+ setOrderDenialType(null);
179
+ setLoading(true);
180
+ setSubmittedOrderData(data);
181
+ try {
182
+ let id: string | undefined = subscriberId;
183
+ let invoiceResponse = null;
184
+ if (data.paymentMethod === PaymentMethodEnum.OIO) {
185
+ invoiceResponse = await invoiceLookup({
186
+ network: data.gln
187
+ ? InvoiceLookupNetworkEnum.OIO_GLN
188
+ : InvoiceLookupNetworkEnum.OIO_Danish_CVR,
189
+ value: data.gln || data.cvr || '',
190
+ });
191
+ }
192
+ if (data.paymentMethod === PaymentMethodEnum.EHF) {
193
+ invoiceResponse = await invoiceLookup({
194
+ network: InvoiceLookupNetworkEnum.EHF,
195
+ value: data.organizationNumber || '',
196
+ });
197
+ }
198
+
199
+ // TODO: "recievesInvoice" should be deleted in the future
200
+ const receivesInvoice =
201
+ invoiceResponse?.receivesInvoice ||
202
+ invoiceResponse?.recievesInvoice;
203
+
204
+ if (invoiceResponse) {
205
+ userActionCallback?.(
206
+ UserActionEnum.SEARCH_ORGANIZATION_NUMBER,
207
+ {
208
+ organizationNumber: data.organizationNumber,
209
+ cvr: data.cvr,
210
+ gln: data.gln,
211
+ found: !!receivesInvoice,
212
+ }
213
+ );
214
+ }
215
+
216
+ if (invoiceResponse && !receivesInvoice) {
217
+ setLoading(false);
218
+ const value =
219
+ data.paymentMethod === PaymentMethodEnum.OIO
220
+ ? data.gln || data.cvr || ''
221
+ : data.organizationNumber || '';
222
+ setApiErrorMsg(`${invoiceLookupNotFoundText || ''} (${value})`);
223
+ return;
224
+ }
225
+
226
+ const contactModel = prepareContactModel({ data, orderFields });
227
+ if (!subscriberId) {
228
+ const response = await createSubscriber({
229
+ ...contactModel,
230
+ gln: data?.gln,
231
+ organizationNumber:
232
+ data.paymentMethod === PaymentMethodEnum.OIO
233
+ ? data?.cvr
234
+ : data.organizationNumber || undefined,
235
+ ...(userId &&
236
+ identityProviderId && { userId, identityProviderId }),
237
+ });
238
+ id = response.id;
239
+
240
+ sessionStorage.setItem('subscriberId', id); // For avoiding attempt of creating subscriber again
241
+ }
242
+
243
+ if (setContactCallback) {
244
+ setContactCallback(contactModel);
245
+ }
246
+
247
+ submitStartCallback?.(id as string);
248
+
249
+ if (id) {
250
+ const paymentMethod =
251
+ data.paymentMethod || PAYMENT_METHOD_DEFAULT;
252
+ const selectedTemplateSubscriptionPlanId =
253
+ fallbackOfferTemplatePackageIdRef.current ||
254
+ templatePackageId;
255
+ fallbackOfferTemplatePackageIdRef.current = null;
256
+
257
+ const agreements = prepareAgreementModel({
258
+ paymentMethod,
259
+ redirectUrl,
260
+ phoneNumber: orderFields.find(
261
+ (i) => i.name === 'phoneNumber'
262
+ )
263
+ ? data.phoneNumber?.trim() || undefined
264
+ : undefined,
265
+ language,
266
+ merchantAgreementUrl,
267
+ generateSubscriberContact:
268
+ paymentMethodsOptions?.[
269
+ data.paymentMethod as PaymentMethodEnum
270
+ ]?.generateSubscriberContact || false,
271
+ accountId:
272
+ paymentMethodsOptions?.[
273
+ data.paymentMethod as PaymentMethodEnum
274
+ ]?.accountId,
275
+ });
276
+ const responseOrder = await orderStart({
277
+ subscriberId: id,
278
+ subscriptionPlan: {
279
+ organizationId,
280
+ templateSubscriptionPlanId:
281
+ selectedTemplateSubscriptionPlanId,
282
+ },
283
+ paymentAgreement: { ...agreements },
284
+ invoiceContact: invoiceAddressToggle
285
+ ? prepareInvoiceModel({
286
+ data,
287
+ orderFields: invoiceOrderFields,
288
+ })
289
+ : undefined,
290
+ orderReference: data.orderReference || undefined,
291
+ });
292
+
293
+ if (!responseOrder.id) {
294
+ callback(null);
295
+ setApiErrorMsg(WRONG_MSG);
296
+ setErrorsMsg([]);
297
+ return;
298
+ }
299
+
300
+ callback(responseOrder.terminalRedirectUrl, {
301
+ ...(data || {}),
302
+ orderId: responseOrder.id,
303
+ subscriberId: id,
304
+ paymentMethod: paymentMethod,
305
+ });
306
+ return;
307
+ }
308
+ callback(null);
309
+ setApiErrorMsg(WRONG_MSG);
310
+ setErrorsMsg([]);
311
+ } catch (error) {
312
+ const translations = {
313
+ errorValidationTitleMsg,
314
+ errorValidationBlockingOffersMsg,
315
+ errorValidationDenialOrderBlockingMsg,
316
+ } as ErrorMessages;
317
+
318
+ const detectedDenialType = getDenialErrorType(
319
+ error as DenialErrorType
320
+ );
321
+ if (detectedDenialType) {
322
+ setApiErrorMsg('');
323
+ setErrorsMsg([]);
324
+ setOrderDenialFallbackOffer(undefined);
325
+ setOrderDenialType(detectedDenialType);
326
+ callback(null);
327
+ if (
328
+ detectedDenialType === 'offer' &&
329
+ fetchDenialFallbackOffer
330
+ ) {
331
+ void fetchDenialFallbackOffer(organizationId)
332
+ .then((offer) => {
333
+ setOrderDenialFallbackOffer(offer);
334
+ if (offer?.templatePackageId) {
335
+ fallbackOfferTemplatePackageIdRef.current =
336
+ offer.templatePackageId;
337
+ }
338
+ })
339
+ .catch(() => {
340
+ setOrderDenialFallbackOffer(undefined);
341
+ });
342
+ }
343
+ return;
344
+ }
345
+
346
+ console.error(error);
347
+ setApiErrorMsg(
348
+ prepareErrorMessage(error as Error, undefined, translations)
349
+ );
350
+ setErrorsMsg(
351
+ prepareErrorsArrayMessage(
352
+ (
353
+ error as {
354
+ errors: ErrorsMsg;
355
+ }
356
+ )?.errors,
357
+ translations
358
+ )
359
+ );
360
+ callback(null);
361
+ } finally {
362
+ setLoading(false);
363
+ }
364
+ };
365
+
366
+ const continueWithFallbackOffer = async () => {
367
+ if (orderDenialType !== 'offer' || !submittedOrderData) {
368
+ return;
369
+ }
370
+
371
+ const fallbackTemplatePackageId =
372
+ orderDenialFallbackOffer?.templatePackageId;
373
+
374
+ if (!fallbackTemplatePackageId) {
375
+ dismissOrderDenial();
376
+ return;
377
+ }
378
+
379
+ fallbackOfferTemplatePackageIdRef.current = fallbackTemplatePackageId;
380
+ userActionCallback?.(UserActionEnum.SELECT_FALLBACK_OFFER, {
381
+ templatePackageId: fallbackTemplatePackageId,
382
+ });
383
+ dismissOrderDenial();
384
+ await orderSubmit(submittedOrderData);
385
+ };
386
+
387
+ return {
388
+ orderSubmit,
389
+ continueWithFallbackOffer,
390
+ loading,
391
+ apiErrorMsg,
392
+ errorsMsg,
393
+ orderDenialType,
394
+ orderDenialMessage: getOrderDenialMessage(),
395
+ orderDenialFallbackOffer,
396
+ dismissOrderDenial,
397
+ };
398
+ };
399
+
400
+ export default useOrderForm;