@infosoftas/s4-orders-js-sdk 0.1.21-3 → 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,403 +1,403 @@
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
+ 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;