tf-checkout-react 1.0.104 → 1.0.105

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 (78) hide show
  1. package/dist/components/ticketsContainer/TicketsSection.d.ts +2 -1
  2. package/dist/components/ticketsContainer/index.d.ts +2 -1
  3. package/dist/images/done.svg +3 -3
  4. package/dist/tf-checkout-react.cjs.development.js +8 -6
  5. package/dist/tf-checkout-react.cjs.development.js.map +1 -1
  6. package/dist/tf-checkout-react.cjs.production.min.js +1 -1
  7. package/dist/tf-checkout-react.cjs.production.min.js.map +1 -1
  8. package/dist/tf-checkout-react.esm.js +8 -6
  9. package/dist/tf-checkout-react.esm.js.map +1 -1
  10. package/package.json +89 -89
  11. package/src/.d.ts +2 -2
  12. package/src/api/index.ts +293 -293
  13. package/src/assets/images/done.svg +3 -3
  14. package/src/components/billing-info-container/index.tsx +796 -796
  15. package/src/components/billing-info-container/style.css +105 -105
  16. package/src/components/billing-info-container/utils.ts +224 -224
  17. package/src/components/common/CheckboxField.tsx +41 -41
  18. package/src/components/common/CustomField.tsx +84 -84
  19. package/src/components/common/FormikPhoneNumberField.tsx +51 -51
  20. package/src/components/common/Loader.tsx +9 -9
  21. package/src/components/common/RadioField.tsx +35 -35
  22. package/src/components/common/RedirectModal.tsx +43 -43
  23. package/src/components/common/SelectField.tsx +80 -80
  24. package/src/components/common/SnackbarAlert.tsx +53 -53
  25. package/src/components/common/index.tsx +4 -4
  26. package/src/components/confirmModal/index.tsx +51 -51
  27. package/src/components/confirmModal/style.css +21 -21
  28. package/src/components/confirmationContainer/config.ts +72 -72
  29. package/src/components/confirmationContainer/index.tsx +197 -197
  30. package/src/components/confirmationContainer/social-buttons.tsx +94 -94
  31. package/src/components/confirmationContainer/style.css +202 -202
  32. package/src/components/countdown/index.tsx +89 -89
  33. package/src/components/countdown/style.css +9 -9
  34. package/src/components/index.ts +7 -7
  35. package/src/components/loginModal/index.tsx +209 -209
  36. package/src/components/loginModal/style.css +71 -71
  37. package/src/components/myTicketsContainer/index.tsx +196 -196
  38. package/src/components/myTicketsContainer/row.tsx +41 -41
  39. package/src/components/myTicketsContainer/style.css +39 -39
  40. package/src/components/myTicketsContainer/tableConfig.tsx +34 -34
  41. package/src/components/orderDetailsContainer/index.tsx +249 -249
  42. package/src/components/orderDetailsContainer/style.css +72 -72
  43. package/src/components/orderDetailsContainer/ticketsTable.tsx +124 -124
  44. package/src/components/paymentContainer/index.tsx +284 -284
  45. package/src/components/registerModal/index.tsx +190 -190
  46. package/src/components/stripePayment/index.tsx +253 -253
  47. package/src/components/stripePayment/style.css +59 -59
  48. package/src/components/ticketResale/index.tsx +56 -56
  49. package/src/components/ticketResaleModal/index.tsx +210 -210
  50. package/src/components/ticketResaleModal/style.css +28 -28
  51. package/src/components/ticketsContainer/PromoCodeSection.tsx +99 -99
  52. package/src/components/ticketsContainer/ReferralLogic.tsx +33 -33
  53. package/src/components/ticketsContainer/TicketRow.tsx +83 -83
  54. package/src/components/ticketsContainer/TicketsSection.tsx +85 -81
  55. package/src/components/ticketsContainer/index.tsx +430 -427
  56. package/src/components/ticketsContainer/style.css +181 -181
  57. package/src/components/ticketsContainer/utils.ts +11 -11
  58. package/src/components/timerWidget/index.tsx +70 -70
  59. package/src/components/timerWidget/style.css +26 -26
  60. package/src/components/waitingList/index.tsx +178 -178
  61. package/src/components/waitingList/style.css +26 -26
  62. package/src/env.ts +20 -20
  63. package/src/index.ts +14 -14
  64. package/src/normalizers/index.ts +45 -45
  65. package/src/types/billing-info-data.ts +37 -37
  66. package/src/types/payment-field.ts +7 -7
  67. package/src/types/referral-promotion.ts +7 -7
  68. package/src/utils/createCheckoutDataBodyWithDefaultHolder.ts +59 -59
  69. package/src/utils/downloadPDF.tsx +30 -30
  70. package/src/utils/formikErrorFocus.ts +24 -24
  71. package/src/utils/getImage.ts +14 -14
  72. package/src/utils/getQueryVariable.ts +13 -13
  73. package/src/utils/index.ts +5 -5
  74. package/src/utils/setConfigs.ts +26 -26
  75. package/src/utils/showZero.tsx +10 -10
  76. package/src/validators/index.ts +20 -20
  77. package/src/.DS_Store +0 -0
  78. package/src/components/.DS_Store +0 -0
@@ -1,796 +1,796 @@
1
- import React, { FC, useEffect, useState, useRef } from 'react'
2
- import { AxiosError } from 'axios'
3
- import {
4
- Field,
5
- Form,
6
- Formik,
7
- FormikHelpers,
8
- FormikProps,
9
- FormikValues,
10
- } from 'formik'
11
- import Button from '@mui/material/Button'
12
- import _identity from 'lodash/identity'
13
- import _map from 'lodash/map'
14
- import _get from 'lodash/get'
15
- import _includes from 'lodash/includes'
16
- import _isEqual from 'lodash/isEqual'
17
- import _isEmpty from 'lodash/isEmpty'
18
-
19
- import './style.css'
20
- import { combineValidators, requiredValidator } from '../../validators'
21
- import { IBillingInfoData } from '../../types'
22
- import {
23
- getCart,
24
- getCountries,
25
- getProfileData,
26
- handleSetAccessToken,
27
- postOnCheckout,
28
- register,
29
- setCustomHeader,
30
- getStates,
31
- } from '../../api'
32
- import { LoginModal } from '../loginModal'
33
- import { RegisterModal } from '../registerModal'
34
- import {
35
- assingUniqueIds,
36
- createCheckoutDataBody,
37
- createRegisterFormData,
38
- getInitialValues,
39
- getValidateFunctions,
40
- setLoggedUserData,
41
- } from './utils'
42
- import { createCheckoutDataBodyWithDefaultHolder } from '../../utils'
43
- import axios from 'axios'
44
- import { CustomField, CheckboxField, SelectField, FormikPhoneNumberField } from '../common/index'
45
- import { CircularProgress, ThemeOptions } from '@mui/material'
46
- import { nanoid } from 'nanoid'
47
- import { getQueryVariable } from '../../utils/getQueryVariable'
48
- import { ErrorFocus } from '../../utils/formikErrorFocus'
49
- import { ThemeProvider, createTheme } from '@mui/material/styles'
50
- import { CSSProperties } from '@mui/styles'
51
- import Backdrop from '@mui/material/Backdrop'
52
- import TimerWidget from '../timerWidget'
53
- import SnackbarAlert from '../common/SnackbarAlert'
54
-
55
- export interface IBillingInfoPage {
56
- data?: IBillingInfoData[];
57
- ticketHoldersFields?: IBillingInfoData;
58
- handleSubmit?: (
59
- values: FormikValues,
60
- formikHelpers: FormikHelpers<FormikValues>,
61
- eventId: any,
62
- res: any
63
- ) => void;
64
- onRegisterSuccess?: (value: {
65
- accessToken: string;
66
- refreshToken: string;
67
- }) => void;
68
- onRegisterError?: (e: AxiosError, email: string) => void;
69
- onSubmitError?: (e: AxiosError) => void;
70
- onGetCartSuccess?: (res: any) => void;
71
- onGetCartError?: (e: AxiosError) => void;
72
- onGetCountriesSuccess?: (res: any) => void;
73
- onGetCountriesError?: (e: AxiosError) => void;
74
- onGetStatesSuccess?: (res: any) => void;
75
- onGetStatesError?: (e: AxiosError) => void;
76
- onGetProfileDataSuccess?: (res: any) => void;
77
- onGetProfileDataError?: (e: AxiosError) => void;
78
- onAuthorizeSuccess?: () => void;
79
- onAuthorizeError?: (e: AxiosError) => void;
80
- onLogin?: () => void;
81
- onLoginSuccess?: () => void;
82
- onErrorClose?: () => void;
83
- initialValues?: FormikValues;
84
- buttonName?: string;
85
- theme?: 'light' | 'dark';
86
- isLoggedIn?: boolean;
87
- accountInfoTitle?: string | JSX.Element;
88
- hideLogo?: boolean;
89
- themeOptions?: ThemeOptions & {
90
- input?: CSSProperties;
91
- checkbox?: CSSProperties;
92
- };
93
- hideErrorsAlertSection?: boolean;
94
- onSkipBillingPage: (data: any) => void;
95
- skipPage?: boolean;
96
- canSkipHolderNames?: boolean;
97
- onCountdownFinish?: () => void;
98
- enableTimer?: boolean;
99
- }
100
-
101
- const LogicRunner: FC<{
102
- values: any;
103
- setStates: React.Dispatch<any>;
104
- setFieldValue: any;
105
- setValues: any;
106
- setUserValues: any;
107
- onGetStatesSuccess: any;
108
- onGetStatesError: any;
109
- }> = ({
110
- values,
111
- setStates,
112
- setFieldValue,
113
- setValues,
114
- setUserValues,
115
- onGetStatesSuccess,
116
- onGetStatesError,
117
- }) => {
118
- const prevCountry = useRef(values.country)
119
- useEffect(() => {
120
- const fetchStates = async () => {
121
- try {
122
- const res = await getStates(values.country)
123
- const mappedStates = _map(_get(res, 'data.data'), (item, key) => ({
124
- label: item,
125
- value: key,
126
- }))
127
- setStates(mappedStates)
128
- if (prevCountry.current !== values.country) {
129
- setFieldValue('state', mappedStates[0]?.value ?? '')
130
- prevCountry.current = values.country
131
- }
132
- onGetStatesSuccess(res.data)
133
- } catch (e) {
134
- if (axios.isAxiosError(e)) {
135
- onGetStatesError(e)
136
- }
137
- }
138
- }
139
- fetchStates()
140
- }, [values.country, setStates, setFieldValue])
141
- const userDataEncoded =
142
- typeof window !== 'undefined'
143
- ? window.localStorage.getItem('user_data')
144
- : ''
145
- useEffect(() => {
146
- // set user data from local storage
147
- const getStoredUserData = () => {
148
- if (typeof window !== 'undefined') {
149
- if (userDataEncoded) {
150
- try {
151
- const parsedData = JSON.parse(userDataEncoded)
152
- const mappedValues = {
153
- firstName: parsedData?.first_name || '',
154
- lastName: parsedData?.last_name || '',
155
- email: parsedData?.email || '',
156
- phone: parsedData?.phone || '',
157
- confirmEmail: parsedData?.email || '',
158
- state: parsedData?.state || '',
159
- street_address: parsedData?.street_address || '',
160
- country: parsedData?.country || '1',
161
- zip: parsedData?.zip || '',
162
- brand_opt_in: parsedData?.brand_opt_in || '',
163
- city: parsedData?.city || '',
164
- confirmPassword: '',
165
- password: '',
166
- 'holderFirstName-0': parsedData?.first_name || '',
167
- 'holderLastName-0': parsedData?.last_name || '',
168
- 'holderEmail-0': parsedData?.email || '',
169
- }
170
- setValues(mappedValues)
171
- setUserValues(mappedValues)
172
- } catch (e) {}
173
- }
174
- }
175
- }
176
- getStoredUserData()
177
- }, [userDataEncoded, setValues, setUserValues])
178
- return null
179
- }
180
- export const BillingInfoContainer = ({
181
- data = [],
182
- ticketHoldersFields = {
183
- id: 1,
184
- fields: [],
185
- },
186
- initialValues = {},
187
- buttonName = 'Submit',
188
- handleSubmit = _identity,
189
- theme = 'light',
190
- onRegisterSuccess = () => {},
191
- onRegisterError = () => {},
192
- onSubmitError = () => {},
193
- onGetCartSuccess = () => {},
194
- onGetCartError = () => {},
195
- onGetCountriesSuccess = () => {},
196
- onGetCountriesError = () => {},
197
- onGetStatesSuccess = () => {},
198
- onGetStatesError = () => {},
199
- onGetProfileDataSuccess = () => {},
200
- onGetProfileDataError = () => {},
201
- onAuthorizeSuccess = () => {},
202
- onAuthorizeError = () => {},
203
- onLogin,
204
- onLoginSuccess = () => {},
205
- isLoggedIn: pIsLoggedIn = false,
206
- accountInfoTitle = '',
207
- hideLogo,
208
- themeOptions,
209
- onErrorClose = () => {},
210
- hideErrorsAlertSection = false,
211
- onSkipBillingPage = () => {},
212
- skipPage = false,
213
- canSkipHolderNames = false,
214
- onCountdownFinish = () => {},
215
- enableTimer = false
216
- }: IBillingInfoPage) => {
217
- const themeMui = createTheme(themeOptions)
218
- const isWindowDefined = typeof window !== 'undefined'
219
- const userData =
220
- isWindowDefined && window.localStorage.getItem('user_data')
221
- ? JSON.parse(window.localStorage.getItem('user_data') || '')
222
- : {}
223
- const access_token =
224
- isWindowDefined && window.localStorage.getItem('access_token')
225
- ? window.localStorage.getItem('access_token') || ''
226
- : ''
227
- const [dataWithUniqueIds, setDataWithUniqueIds] = useState<
228
- IBillingInfoData[]
229
- >(data)
230
- const [isLoggedIn, setIsLoggedIn] = useState(!!access_token)
231
- const [cartInfoData, setCartInfo] = useState<any>({})
232
- const [countries, setCountries] = useState<any>([])
233
- const [states, setStates] = useState<any>([])
234
- const [showModalLogin, setShowModalLogin] = useState(false)
235
- const [alreadyHasUser, setAlreadyHasUser] = useState(false)
236
- const [userExpired, setUserExpired] = useState(false)
237
- const [showModalRegister, setShowModalRegister] = useState(false)
238
- const [ticketsQuantity, setTicketsQuantity] = useState<string[]>([])
239
- const [userValues, setUserValues] = useState<any>({
240
- firstName: '',
241
- lastName: '',
242
- email: '',
243
- phone: '',
244
- confirmEmail: '',
245
- holderFirstName: '',
246
- holderLastName: '',
247
- holderAge: '',
248
- city: '',
249
- country: '',
250
- street_address: '',
251
- state: '',
252
- zip: '',
253
- })
254
- const [loading, setLoading] = useState(true)
255
- const [error, setError] = useState(null)
256
- const emailLogged =
257
- _get(userData, 'email', '') || _get(userValues, 'email', '')
258
- const firstNameLogged =
259
- _get(userData, 'first_name', '') || _get(userValues, 'first_name', '')
260
- const lastNameLogged =
261
- _get(userData, 'last_name', '') || _get(userValues, 'last_name', '')
262
- const showDOB = getQueryVariable('age_required') === 'true'
263
- const showTicketHolders = getQueryVariable('names_required') === 'true'
264
- const eventId = getQueryVariable('event_id')
265
- const optedInFieldValue: boolean = _get(cartInfoData, 'optedIn', false)
266
- const ttfOptIn: boolean = Boolean(_get(cartInfoData, 'ttfOptIn', false))
267
- const hideTtfOptIn: boolean = _get(cartInfoData, 'hide_ttf_opt_in', true)
268
- const expirationTime = _get(cartInfoData, 'expires_at')
269
- const flagRequirePhone = getQueryVariable('phone_required') === 'true'
270
-
271
- // Get prevProps
272
- const prevData = useRef(data)
273
-
274
- useEffect(() => {
275
- const hasUniqueId = _get(dataWithUniqueIds, '[0].uniqueId')
276
- const isEqualData = _isEqual(prevData.current, data)
277
- if (!hasUniqueId || !isEqualData) {
278
- setDataWithUniqueIds(assingUniqueIds(data))
279
- if (!isEqualData) {
280
- prevData.current = data
281
- }
282
- }
283
- }, [dataWithUniqueIds, data])
284
-
285
- const getQuantity = (cart: any = []) => {
286
- let qty: any = 0
287
- cart.forEach((item: any) => {
288
- qty += +item.quantity
289
- })
290
- return qty
291
- }
292
-
293
- useEffect(() => {
294
- if ((pIsLoggedIn || access_token) && !isLoggedIn) {
295
- setIsLoggedIn(true)
296
- }
297
- }, [pIsLoggedIn, isLoggedIn, access_token])
298
- //just once
299
- useEffect(() => {
300
- // fetch countries data
301
- const fetchCountries = async () => {
302
- try {
303
- const res = await getCountries()
304
- setCustomHeader(res)
305
- setCountries(
306
- _map(_get(res, 'data.data'), (item, key) => ({
307
- label: item,
308
- value: key,
309
- }))
310
- )
311
- onGetCountriesSuccess(res.data)
312
- } catch (e) {
313
- if (axios.isAxiosError(e)) {
314
- onGetCountriesError(e)
315
- }
316
- }
317
- }
318
- fetchCountries()
319
- fetchCart()
320
- }, [])
321
- // fetch cart data
322
- const fetchCart = async () => {
323
- try {
324
- const res = await getCart()
325
- setCustomHeader(res)
326
- const cartInfo = _get(res, 'data.data.attributes')
327
- setCartInfo(cartInfo)
328
- const { cart = [] } = cartInfo
329
- setTicketsQuantity(
330
- new Array(getQuantity(cart)).fill(null).map(() => nanoid())
331
- )
332
- onGetCartSuccess(res.data)
333
- } catch (e) {
334
- if (axios.isAxiosError(e)) {
335
- onGetCartError(e)
336
- }
337
- }
338
- }
339
- // fetch user data
340
- const fetchUserData = async (token: string) => {
341
- try {
342
- if (isWindowDefined && token) {
343
- const userDataResponse = await getProfileData(token)
344
- const profileSpecifiedData = _get(userDataResponse, 'data.data')
345
- const profileDataObj = setLoggedUserData(profileSpecifiedData)
346
- setUserValues({
347
- ...profileDataObj,
348
- firstName: profileDataObj.first_name,
349
- lastName: profileDataObj.last_name,
350
- })
351
- window.localStorage.setItem(
352
- 'user_data',
353
- JSON.stringify(profileDataObj)
354
- )
355
- onGetProfileDataSuccess(userDataResponse.data)
356
- }
357
- } catch (e) {
358
- if (axios.isAxiosError(e)) {
359
- onGetProfileDataError(e)
360
- }
361
- }
362
- }
363
- useEffect(() => {
364
- fetchUserData(access_token)
365
- }, [access_token])
366
-
367
- useEffect(() => {
368
- const collectPaymentData = async () => {
369
- if (skipPage && !_isEmpty(ticketsQuantity) && !showDOB) {
370
- setLoading(true)
371
- const checkoutBody = createCheckoutDataBodyWithDefaultHolder(
372
- ticketsQuantity.length,
373
- userData
374
- )
375
-
376
- try {
377
- const res = await postOnCheckout(checkoutBody, access_token)
378
- onSkipBillingPage(_get(res, 'data.data.attributes'))
379
- setLoading(false)
380
- } catch (e) {
381
- onSubmitError(e)
382
- }
383
- } else {
384
- setLoading(false)
385
- }
386
- }
387
- collectPaymentData()
388
- }, [skipPage, ticketsQuantity])
389
-
390
-
391
- const collectCheckoutBody = (values: object): object => {
392
- let checkoutBody = {}
393
-
394
- // Auto collect ticket holders name when it was skipped optionally
395
- if (showDOB && !showTicketHolders && canSkipHolderNames) {
396
- checkoutBody = createCheckoutDataBodyWithDefaultHolder(
397
- ticketsQuantity.length,
398
- values,
399
- true
400
- )
401
- } else {
402
- checkoutBody = createCheckoutDataBody(
403
- ticketsQuantity.length,
404
- values,
405
- { emailLogged, firstNameLogged, lastNameLogged },
406
- showDOB
407
- )
408
- }
409
-
410
- return checkoutBody
411
- }
412
-
413
- // Displaying loader
414
- if (loading) {
415
- return (
416
- <Backdrop sx={{ color: '#fff' }} open={true}>
417
- <CircularProgress color="inherit" />
418
- </Backdrop>
419
- )
420
- }
421
-
422
- return (
423
- <ThemeProvider theme={themeMui}>
424
- {expirationTime && enableTimer && (
425
- <TimerWidget
426
- expires_at={expirationTime}
427
- onCountdownFinish={onCountdownFinish}
428
- />
429
- )}
430
- <Formik
431
- initialValues={getInitialValues(
432
- dataWithUniqueIds,
433
- {
434
- ...initialValues,
435
- country: _get(userData, 'country', '') || '1',
436
- state: _get(userData, 'state', '') || '1',
437
- brand_opt_in: optedInFieldValue,
438
- ttf_opt_in: ttfOptIn,
439
- },
440
- userValues
441
- )}
442
- enableReinitialize={true}
443
- onSubmit={async (values, formikHelpers) => {
444
- try {
445
- if (isLoggedIn) {
446
- if (access_token) {
447
- const updatedUserData = await getProfileData(access_token)
448
- const profileSpecifiedData = _get(updatedUserData, 'data.data')
449
- const profileDataObj = setLoggedUserData(profileSpecifiedData)
450
- if (isWindowDefined) {
451
- window.localStorage.setItem(
452
- 'user_data',
453
- JSON.stringify(profileDataObj)
454
- )
455
- }
456
- }
457
-
458
- const checkoutBody = collectCheckoutBody(values)
459
- const res = await postOnCheckout(checkoutBody, access_token)
460
- handleSubmit(
461
- values,
462
- formikHelpers as FormikHelpers<any>,
463
- eventId,
464
- res
465
- )
466
- return
467
- }
468
- const checkoutBodyForRegistration = createCheckoutDataBody(
469
- ticketsQuantity.length,
470
- values,
471
- { emailLogged, firstNameLogged, lastNameLogged },
472
- showDOB
473
- )
474
- const bodyFormData = createRegisterFormData(
475
- values,
476
- checkoutBodyForRegistration
477
- )
478
- let access_token_register = null
479
- try {
480
- const resRegister = await register(bodyFormData)
481
- access_token_register = _get(
482
- resRegister,
483
- 'data.data.attributes.access_token'
484
- )
485
- const refreshToken = _get(
486
- resRegister,
487
- 'data.data.attributes.refresh_token'
488
- )
489
- handleSetAccessToken(access_token_register)
490
- const tokens = {
491
- accessToken: access_token_register,
492
- refreshToken,
493
- }
494
- onRegisterSuccess(tokens)
495
- } catch (e) {
496
- if (axios.isAxiosError(e)) {
497
- const error = e?.response?.data?.message
498
- if (_includes(error, 'You must be aged')) {
499
- formikHelpers.setFieldError('holderAge', error)
500
- }
501
- if (error?.password) {
502
- formikHelpers.setFieldError('password', error.password)
503
- formikHelpers.setFieldError(
504
- 'confirmPassword',
505
- error.password
506
- )
507
- }
508
- if (error?.email && !onLogin) {
509
- // False will stand for outside controll
510
- setAlreadyHasUser(true)
511
- setShowModalLogin(true)
512
- }
513
-
514
- if (_includes(error, 'The cart is expired') && !hideErrorsAlertSection) {
515
- setError(error)
516
- }
517
-
518
- onRegisterError(e, values.email)
519
- }
520
- return
521
- }
522
- const profileData = await getProfileData(access_token_register)
523
- const profileSpecifiedData = _get(profileData, 'data.data')
524
- const profileDataObj = setLoggedUserData(profileSpecifiedData)
525
- if (isWindowDefined) {
526
- window.localStorage.setItem(
527
- 'user_data',
528
- JSON.stringify(profileDataObj)
529
- )
530
- }
531
-
532
- const checkoutBody = collectCheckoutBody(values)
533
- const res = await postOnCheckout(
534
- checkoutBody,
535
- access_token_register
536
- )
537
- handleSubmit(
538
- values,
539
- formikHelpers as FormikHelpers<any>,
540
- eventId,
541
- res
542
- )
543
- } catch (e) {
544
- if (axios.isAxiosError(e)) {
545
- if (e.response?.data.error === 'invalid_token') {
546
- if (isWindowDefined) {
547
- window.localStorage.removeItem('user_data')
548
- window.localStorage.removeItem('access_token')
549
- setUserExpired(true)
550
- setShowModalLogin(true)
551
- }
552
- }
553
- if (e.response?.data.message && !hideErrorsAlertSection) {
554
- setError(_get(e, 'response.data.message'))
555
- }
556
- onSubmitError(e)
557
- }
558
- }
559
- }}
560
- >
561
- {(props: FormikProps<any>) => (
562
- <Form onSubmit={props.handleSubmit}>
563
- <ErrorFocus />
564
- <LogicRunner
565
- values={props.values}
566
- setStates={setStates}
567
- setFieldValue={props.setFieldValue}
568
- setValues={props.setValues}
569
- setUserValues={setUserValues}
570
- onGetStatesSuccess={onGetStatesSuccess}
571
- onGetStatesError={onGetStatesError}
572
- />
573
- <div className={`billing-info-container ${theme}`}>
574
- <SnackbarAlert
575
- type="error"
576
- isOpen={!!error}
577
- message={error || ''}
578
- onClose={() => {
579
- setError(null)
580
- onErrorClose()
581
- }}
582
- />
583
- {!isLoggedIn && (
584
- <div className="account-actions-block">
585
- <div>{accountInfoTitle}</div>
586
- <div>Login & skip ahead:</div>
587
- <div className="login-block">
588
- <button
589
- className="login-register-button"
590
- type="button"
591
- onClick={() => {
592
- // If outside login needed to skip package login functionallity
593
- if (onLogin) {
594
- onLogin()
595
- } else {
596
- setShowModalLogin(true)
597
- }
598
- }}
599
- >
600
- Login
601
- </button>
602
- {!hideLogo && (
603
- <div className="logo-image-container">
604
- <img
605
- src={
606
- theme === 'dark'
607
- ? 'https://www.ticketfairy.com/resources/images/logo-ttf.svg'
608
- : 'https://www.ticketfairy.com/resources/images/logo-ttf-black.svg'
609
- }
610
- alt="nodata"
611
- />
612
- </div>
613
- )}
614
- </div>
615
- </div>
616
- )}
617
- {_map(dataWithUniqueIds, item => {
618
- const { label, labelClassName, fields } = item
619
- return (
620
- <React.Fragment key={item.uniqueId}>
621
- <p className={labelClassName}>{label}</p>
622
- {_map(fields, group => {
623
- const { groupClassname, groupItems } = group
624
- return (
625
- <React.Fragment key={group.uniqueId}>
626
- <div className={groupClassname}>
627
- {_map(
628
- groupItems.filter(el => {
629
- if (el.name === 'holderAge' && !showDOB) {
630
- return false
631
- }
632
- if (el.name === 'ttf_opt_in' && hideTtfOptIn) {
633
- return false
634
- }
635
- if (el.name === 'phone') {
636
- el.required = flagRequirePhone
637
- }
638
- return true
639
- }),
640
- element =>
641
- [
642
- 'password',
643
- 'confirmPassword',
644
- 'password-info',
645
- ].includes(element.name) &&
646
- isLoggedIn ? null : (
647
- <React.Fragment key={element.uniqueId}>
648
- <div className={element.className}>
649
- {element.component ? (
650
- element.component
651
- ) : (
652
- <Field
653
- name={element.name}
654
- label={element.name === 'phone'
655
- ? `${element.label}${flagRequirePhone ? '' : ' (optional)'} `
656
- : element.label}
657
- type={element.type}
658
- validate={getValidateFunctions(
659
- element,
660
- states,
661
- props.values
662
- )}
663
- setFieldValue={props.setFieldValue}
664
- onBlur={props.handleBlur}
665
- component={
666
- element.type === 'checkbox'
667
- ? CheckboxField
668
- : element.type === 'select'
669
- ? SelectField
670
- : element.type === 'phone'
671
- ? FormikPhoneNumberField
672
- : CustomField
673
- }
674
- selectOptions={
675
- element.name === 'country'
676
- ? countries
677
- : element.name === 'state'
678
- ? states
679
- : []
680
- }
681
- theme={theme}
682
- />
683
- )}
684
- </div>
685
- </React.Fragment>
686
- )
687
- )}
688
- </div>
689
- </React.Fragment>
690
- )
691
- })}
692
- </React.Fragment>
693
- )
694
- })}
695
- {!_isEmpty(ticketHoldersFields.fields) && (
696
- <div className="ticket-holders-fields">
697
- <p>{ticketHoldersFields.label}</p>
698
- {_map(ticketsQuantity, (_item, index) => (
699
- <div key={_item}>
700
- <h5>Ticket {index + 1}</h5>
701
- {_map(ticketHoldersFields.fields, group => {
702
- const { groupClassname, groupItems } = group
703
- return (
704
- <div key={group.id}>
705
- <div className={groupClassname}>
706
- {_map(groupItems, element => (
707
- <div
708
- className={element.className}
709
- key={element.name}
710
- >
711
- <Field
712
- name={`${element.name}-${index}`}
713
- label={element.label}
714
- type={element.type}
715
- required={true}
716
- component={
717
- element.type === 'checkbox'
718
- ? CheckboxField
719
- : CustomField
720
- }
721
- validate={combineValidators(
722
- element.required
723
- ? requiredValidator
724
- : () => {},
725
- element.onValidate
726
- ? element.onValidate
727
- : () => {}
728
- )}
729
- />
730
- </div>
731
- ))}
732
- </div>
733
- </div>
734
- )
735
- })}
736
- </div>
737
- ))}
738
- </div>
739
- )}
740
- <div className="button-container">
741
- <Button
742
- type="submit"
743
- variant="contained"
744
- className="login-register-button"
745
- disabled={props.isSubmitting}
746
- >
747
- {props.isSubmitting ? (
748
- <CircularProgress size={26} />
749
- ) : (
750
- buttonName
751
- )}
752
- </Button>
753
- </div>
754
- </div>
755
- </Form>
756
- )}
757
- </Formik>
758
- {showModalLogin && (
759
- <LoginModal
760
- onClose={() => {
761
- setShowModalLogin(false)
762
- }}
763
- onLogin={() => {
764
- setShowModalLogin(false)
765
- setUserExpired(false)
766
- onLoginSuccess()
767
- }}
768
- alreadyHasUser={alreadyHasUser}
769
- userExpired={userExpired}
770
- onAuthorizeSuccess={onAuthorizeSuccess}
771
- onAuthorizeError={onAuthorizeError}
772
- onGetProfileDataSuccess={(data: any) => {
773
- fetchCart()
774
- onGetProfileDataSuccess(data)
775
- }}
776
- onGetProfileDataError={onGetProfileDataError}
777
- />
778
- )}
779
- {showModalRegister && (
780
- <RegisterModal
781
- onClose={() => {
782
- setShowModalRegister(false)
783
- }}
784
- onRegister={() => {
785
- setShowModalRegister(false)
786
- }}
787
- onGetProfileDataSuccess={(data: any) => {
788
- fetchCart()
789
- onGetProfileDataSuccess(data)
790
- }}
791
- onGetProfileDataError={onGetProfileDataError}
792
- />
793
- )}
794
- </ThemeProvider>
795
- )
796
- }
1
+ import React, { FC, useEffect, useState, useRef } from 'react'
2
+ import { AxiosError } from 'axios'
3
+ import {
4
+ Field,
5
+ Form,
6
+ Formik,
7
+ FormikHelpers,
8
+ FormikProps,
9
+ FormikValues,
10
+ } from 'formik'
11
+ import Button from '@mui/material/Button'
12
+ import _identity from 'lodash/identity'
13
+ import _map from 'lodash/map'
14
+ import _get from 'lodash/get'
15
+ import _includes from 'lodash/includes'
16
+ import _isEqual from 'lodash/isEqual'
17
+ import _isEmpty from 'lodash/isEmpty'
18
+
19
+ import './style.css'
20
+ import { combineValidators, requiredValidator } from '../../validators'
21
+ import { IBillingInfoData } from '../../types'
22
+ import {
23
+ getCart,
24
+ getCountries,
25
+ getProfileData,
26
+ handleSetAccessToken,
27
+ postOnCheckout,
28
+ register,
29
+ setCustomHeader,
30
+ getStates,
31
+ } from '../../api'
32
+ import { LoginModal } from '../loginModal'
33
+ import { RegisterModal } from '../registerModal'
34
+ import {
35
+ assingUniqueIds,
36
+ createCheckoutDataBody,
37
+ createRegisterFormData,
38
+ getInitialValues,
39
+ getValidateFunctions,
40
+ setLoggedUserData,
41
+ } from './utils'
42
+ import { createCheckoutDataBodyWithDefaultHolder } from '../../utils'
43
+ import axios from 'axios'
44
+ import { CustomField, CheckboxField, SelectField, FormikPhoneNumberField } from '../common/index'
45
+ import { CircularProgress, ThemeOptions } from '@mui/material'
46
+ import { nanoid } from 'nanoid'
47
+ import { getQueryVariable } from '../../utils/getQueryVariable'
48
+ import { ErrorFocus } from '../../utils/formikErrorFocus'
49
+ import { ThemeProvider, createTheme } from '@mui/material/styles'
50
+ import { CSSProperties } from '@mui/styles'
51
+ import Backdrop from '@mui/material/Backdrop'
52
+ import TimerWidget from '../timerWidget'
53
+ import SnackbarAlert from '../common/SnackbarAlert'
54
+
55
+ export interface IBillingInfoPage {
56
+ data?: IBillingInfoData[];
57
+ ticketHoldersFields?: IBillingInfoData;
58
+ handleSubmit?: (
59
+ values: FormikValues,
60
+ formikHelpers: FormikHelpers<FormikValues>,
61
+ eventId: any,
62
+ res: any
63
+ ) => void;
64
+ onRegisterSuccess?: (value: {
65
+ accessToken: string;
66
+ refreshToken: string;
67
+ }) => void;
68
+ onRegisterError?: (e: AxiosError, email: string) => void;
69
+ onSubmitError?: (e: AxiosError) => void;
70
+ onGetCartSuccess?: (res: any) => void;
71
+ onGetCartError?: (e: AxiosError) => void;
72
+ onGetCountriesSuccess?: (res: any) => void;
73
+ onGetCountriesError?: (e: AxiosError) => void;
74
+ onGetStatesSuccess?: (res: any) => void;
75
+ onGetStatesError?: (e: AxiosError) => void;
76
+ onGetProfileDataSuccess?: (res: any) => void;
77
+ onGetProfileDataError?: (e: AxiosError) => void;
78
+ onAuthorizeSuccess?: () => void;
79
+ onAuthorizeError?: (e: AxiosError) => void;
80
+ onLogin?: () => void;
81
+ onLoginSuccess?: () => void;
82
+ onErrorClose?: () => void;
83
+ initialValues?: FormikValues;
84
+ buttonName?: string;
85
+ theme?: 'light' | 'dark';
86
+ isLoggedIn?: boolean;
87
+ accountInfoTitle?: string | JSX.Element;
88
+ hideLogo?: boolean;
89
+ themeOptions?: ThemeOptions & {
90
+ input?: CSSProperties;
91
+ checkbox?: CSSProperties;
92
+ };
93
+ hideErrorsAlertSection?: boolean;
94
+ onSkipBillingPage: (data: any) => void;
95
+ skipPage?: boolean;
96
+ canSkipHolderNames?: boolean;
97
+ onCountdownFinish?: () => void;
98
+ enableTimer?: boolean;
99
+ }
100
+
101
+ const LogicRunner: FC<{
102
+ values: any;
103
+ setStates: React.Dispatch<any>;
104
+ setFieldValue: any;
105
+ setValues: any;
106
+ setUserValues: any;
107
+ onGetStatesSuccess: any;
108
+ onGetStatesError: any;
109
+ }> = ({
110
+ values,
111
+ setStates,
112
+ setFieldValue,
113
+ setValues,
114
+ setUserValues,
115
+ onGetStatesSuccess,
116
+ onGetStatesError,
117
+ }) => {
118
+ const prevCountry = useRef(values.country)
119
+ useEffect(() => {
120
+ const fetchStates = async () => {
121
+ try {
122
+ const res = await getStates(values.country)
123
+ const mappedStates = _map(_get(res, 'data.data'), (item, key) => ({
124
+ label: item,
125
+ value: key,
126
+ }))
127
+ setStates(mappedStates)
128
+ if (prevCountry.current !== values.country) {
129
+ setFieldValue('state', mappedStates[0]?.value ?? '')
130
+ prevCountry.current = values.country
131
+ }
132
+ onGetStatesSuccess(res.data)
133
+ } catch (e) {
134
+ if (axios.isAxiosError(e)) {
135
+ onGetStatesError(e)
136
+ }
137
+ }
138
+ }
139
+ fetchStates()
140
+ }, [values.country, setStates, setFieldValue])
141
+ const userDataEncoded =
142
+ typeof window !== 'undefined'
143
+ ? window.localStorage.getItem('user_data')
144
+ : ''
145
+ useEffect(() => {
146
+ // set user data from local storage
147
+ const getStoredUserData = () => {
148
+ if (typeof window !== 'undefined') {
149
+ if (userDataEncoded) {
150
+ try {
151
+ const parsedData = JSON.parse(userDataEncoded)
152
+ const mappedValues = {
153
+ firstName: parsedData?.first_name || '',
154
+ lastName: parsedData?.last_name || '',
155
+ email: parsedData?.email || '',
156
+ phone: parsedData?.phone || '',
157
+ confirmEmail: parsedData?.email || '',
158
+ state: parsedData?.state || '',
159
+ street_address: parsedData?.street_address || '',
160
+ country: parsedData?.country || '1',
161
+ zip: parsedData?.zip || '',
162
+ brand_opt_in: parsedData?.brand_opt_in || '',
163
+ city: parsedData?.city || '',
164
+ confirmPassword: '',
165
+ password: '',
166
+ 'holderFirstName-0': parsedData?.first_name || '',
167
+ 'holderLastName-0': parsedData?.last_name || '',
168
+ 'holderEmail-0': parsedData?.email || '',
169
+ }
170
+ setValues(mappedValues)
171
+ setUserValues(mappedValues)
172
+ } catch (e) {}
173
+ }
174
+ }
175
+ }
176
+ getStoredUserData()
177
+ }, [userDataEncoded, setValues, setUserValues])
178
+ return null
179
+ }
180
+ export const BillingInfoContainer = ({
181
+ data = [],
182
+ ticketHoldersFields = {
183
+ id: 1,
184
+ fields: [],
185
+ },
186
+ initialValues = {},
187
+ buttonName = 'Submit',
188
+ handleSubmit = _identity,
189
+ theme = 'light',
190
+ onRegisterSuccess = () => {},
191
+ onRegisterError = () => {},
192
+ onSubmitError = () => {},
193
+ onGetCartSuccess = () => {},
194
+ onGetCartError = () => {},
195
+ onGetCountriesSuccess = () => {},
196
+ onGetCountriesError = () => {},
197
+ onGetStatesSuccess = () => {},
198
+ onGetStatesError = () => {},
199
+ onGetProfileDataSuccess = () => {},
200
+ onGetProfileDataError = () => {},
201
+ onAuthorizeSuccess = () => {},
202
+ onAuthorizeError = () => {},
203
+ onLogin,
204
+ onLoginSuccess = () => {},
205
+ isLoggedIn: pIsLoggedIn = false,
206
+ accountInfoTitle = '',
207
+ hideLogo,
208
+ themeOptions,
209
+ onErrorClose = () => {},
210
+ hideErrorsAlertSection = false,
211
+ onSkipBillingPage = () => {},
212
+ skipPage = false,
213
+ canSkipHolderNames = false,
214
+ onCountdownFinish = () => {},
215
+ enableTimer = false
216
+ }: IBillingInfoPage) => {
217
+ const themeMui = createTheme(themeOptions)
218
+ const isWindowDefined = typeof window !== 'undefined'
219
+ const userData =
220
+ isWindowDefined && window.localStorage.getItem('user_data')
221
+ ? JSON.parse(window.localStorage.getItem('user_data') || '')
222
+ : {}
223
+ const access_token =
224
+ isWindowDefined && window.localStorage.getItem('access_token')
225
+ ? window.localStorage.getItem('access_token') || ''
226
+ : ''
227
+ const [dataWithUniqueIds, setDataWithUniqueIds] = useState<
228
+ IBillingInfoData[]
229
+ >(data)
230
+ const [isLoggedIn, setIsLoggedIn] = useState(!!access_token)
231
+ const [cartInfoData, setCartInfo] = useState<any>({})
232
+ const [countries, setCountries] = useState<any>([])
233
+ const [states, setStates] = useState<any>([])
234
+ const [showModalLogin, setShowModalLogin] = useState(false)
235
+ const [alreadyHasUser, setAlreadyHasUser] = useState(false)
236
+ const [userExpired, setUserExpired] = useState(false)
237
+ const [showModalRegister, setShowModalRegister] = useState(false)
238
+ const [ticketsQuantity, setTicketsQuantity] = useState<string[]>([])
239
+ const [userValues, setUserValues] = useState<any>({
240
+ firstName: '',
241
+ lastName: '',
242
+ email: '',
243
+ phone: '',
244
+ confirmEmail: '',
245
+ holderFirstName: '',
246
+ holderLastName: '',
247
+ holderAge: '',
248
+ city: '',
249
+ country: '',
250
+ street_address: '',
251
+ state: '',
252
+ zip: '',
253
+ })
254
+ const [loading, setLoading] = useState(true)
255
+ const [error, setError] = useState(null)
256
+ const emailLogged =
257
+ _get(userData, 'email', '') || _get(userValues, 'email', '')
258
+ const firstNameLogged =
259
+ _get(userData, 'first_name', '') || _get(userValues, 'first_name', '')
260
+ const lastNameLogged =
261
+ _get(userData, 'last_name', '') || _get(userValues, 'last_name', '')
262
+ const showDOB = getQueryVariable('age_required') === 'true'
263
+ const showTicketHolders = getQueryVariable('names_required') === 'true'
264
+ const eventId = getQueryVariable('event_id')
265
+ const optedInFieldValue: boolean = _get(cartInfoData, 'optedIn', false)
266
+ const ttfOptIn: boolean = Boolean(_get(cartInfoData, 'ttfOptIn', false))
267
+ const hideTtfOptIn: boolean = _get(cartInfoData, 'hide_ttf_opt_in', true)
268
+ const expirationTime = _get(cartInfoData, 'expires_at')
269
+ const flagRequirePhone = getQueryVariable('phone_required') === 'true'
270
+
271
+ // Get prevProps
272
+ const prevData = useRef(data)
273
+
274
+ useEffect(() => {
275
+ const hasUniqueId = _get(dataWithUniqueIds, '[0].uniqueId')
276
+ const isEqualData = _isEqual(prevData.current, data)
277
+ if (!hasUniqueId || !isEqualData) {
278
+ setDataWithUniqueIds(assingUniqueIds(data))
279
+ if (!isEqualData) {
280
+ prevData.current = data
281
+ }
282
+ }
283
+ }, [dataWithUniqueIds, data])
284
+
285
+ const getQuantity = (cart: any = []) => {
286
+ let qty: any = 0
287
+ cart.forEach((item: any) => {
288
+ qty += +item.quantity
289
+ })
290
+ return qty
291
+ }
292
+
293
+ useEffect(() => {
294
+ if ((pIsLoggedIn || access_token) && !isLoggedIn) {
295
+ setIsLoggedIn(true)
296
+ }
297
+ }, [pIsLoggedIn, isLoggedIn, access_token])
298
+ //just once
299
+ useEffect(() => {
300
+ // fetch countries data
301
+ const fetchCountries = async () => {
302
+ try {
303
+ const res = await getCountries()
304
+ setCustomHeader(res)
305
+ setCountries(
306
+ _map(_get(res, 'data.data'), (item, key) => ({
307
+ label: item,
308
+ value: key,
309
+ }))
310
+ )
311
+ onGetCountriesSuccess(res.data)
312
+ } catch (e) {
313
+ if (axios.isAxiosError(e)) {
314
+ onGetCountriesError(e)
315
+ }
316
+ }
317
+ }
318
+ fetchCountries()
319
+ fetchCart()
320
+ }, [])
321
+ // fetch cart data
322
+ const fetchCart = async () => {
323
+ try {
324
+ const res = await getCart()
325
+ setCustomHeader(res)
326
+ const cartInfo = _get(res, 'data.data.attributes')
327
+ setCartInfo(cartInfo)
328
+ const { cart = [] } = cartInfo
329
+ setTicketsQuantity(
330
+ new Array(getQuantity(cart)).fill(null).map(() => nanoid())
331
+ )
332
+ onGetCartSuccess(res.data)
333
+ } catch (e) {
334
+ if (axios.isAxiosError(e)) {
335
+ onGetCartError(e)
336
+ }
337
+ }
338
+ }
339
+ // fetch user data
340
+ const fetchUserData = async (token: string) => {
341
+ try {
342
+ if (isWindowDefined && token) {
343
+ const userDataResponse = await getProfileData(token)
344
+ const profileSpecifiedData = _get(userDataResponse, 'data.data')
345
+ const profileDataObj = setLoggedUserData(profileSpecifiedData)
346
+ setUserValues({
347
+ ...profileDataObj,
348
+ firstName: profileDataObj.first_name,
349
+ lastName: profileDataObj.last_name,
350
+ })
351
+ window.localStorage.setItem(
352
+ 'user_data',
353
+ JSON.stringify(profileDataObj)
354
+ )
355
+ onGetProfileDataSuccess(userDataResponse.data)
356
+ }
357
+ } catch (e) {
358
+ if (axios.isAxiosError(e)) {
359
+ onGetProfileDataError(e)
360
+ }
361
+ }
362
+ }
363
+ useEffect(() => {
364
+ fetchUserData(access_token)
365
+ }, [access_token])
366
+
367
+ useEffect(() => {
368
+ const collectPaymentData = async () => {
369
+ if (skipPage && !_isEmpty(ticketsQuantity) && !showDOB) {
370
+ setLoading(true)
371
+ const checkoutBody = createCheckoutDataBodyWithDefaultHolder(
372
+ ticketsQuantity.length,
373
+ userData
374
+ )
375
+
376
+ try {
377
+ const res = await postOnCheckout(checkoutBody, access_token)
378
+ onSkipBillingPage(_get(res, 'data.data.attributes'))
379
+ setLoading(false)
380
+ } catch (e) {
381
+ onSubmitError(e)
382
+ }
383
+ } else {
384
+ setLoading(false)
385
+ }
386
+ }
387
+ collectPaymentData()
388
+ }, [skipPage, ticketsQuantity])
389
+
390
+
391
+ const collectCheckoutBody = (values: object): object => {
392
+ let checkoutBody = {}
393
+
394
+ // Auto collect ticket holders name when it was skipped optionally
395
+ if (showDOB && !showTicketHolders && canSkipHolderNames) {
396
+ checkoutBody = createCheckoutDataBodyWithDefaultHolder(
397
+ ticketsQuantity.length,
398
+ values,
399
+ true
400
+ )
401
+ } else {
402
+ checkoutBody = createCheckoutDataBody(
403
+ ticketsQuantity.length,
404
+ values,
405
+ { emailLogged, firstNameLogged, lastNameLogged },
406
+ showDOB
407
+ )
408
+ }
409
+
410
+ return checkoutBody
411
+ }
412
+
413
+ // Displaying loader
414
+ if (loading) {
415
+ return (
416
+ <Backdrop sx={{ color: '#fff' }} open={true}>
417
+ <CircularProgress color="inherit" />
418
+ </Backdrop>
419
+ )
420
+ }
421
+
422
+ return (
423
+ <ThemeProvider theme={themeMui}>
424
+ {expirationTime && enableTimer && (
425
+ <TimerWidget
426
+ expires_at={expirationTime}
427
+ onCountdownFinish={onCountdownFinish}
428
+ />
429
+ )}
430
+ <Formik
431
+ initialValues={getInitialValues(
432
+ dataWithUniqueIds,
433
+ {
434
+ ...initialValues,
435
+ country: _get(userData, 'country', '') || '1',
436
+ state: _get(userData, 'state', '') || '1',
437
+ brand_opt_in: optedInFieldValue,
438
+ ttf_opt_in: ttfOptIn,
439
+ },
440
+ userValues
441
+ )}
442
+ enableReinitialize={true}
443
+ onSubmit={async (values, formikHelpers) => {
444
+ try {
445
+ if (isLoggedIn) {
446
+ if (access_token) {
447
+ const updatedUserData = await getProfileData(access_token)
448
+ const profileSpecifiedData = _get(updatedUserData, 'data.data')
449
+ const profileDataObj = setLoggedUserData(profileSpecifiedData)
450
+ if (isWindowDefined) {
451
+ window.localStorage.setItem(
452
+ 'user_data',
453
+ JSON.stringify(profileDataObj)
454
+ )
455
+ }
456
+ }
457
+
458
+ const checkoutBody = collectCheckoutBody(values)
459
+ const res = await postOnCheckout(checkoutBody, access_token)
460
+ handleSubmit(
461
+ values,
462
+ formikHelpers as FormikHelpers<any>,
463
+ eventId,
464
+ res
465
+ )
466
+ return
467
+ }
468
+ const checkoutBodyForRegistration = createCheckoutDataBody(
469
+ ticketsQuantity.length,
470
+ values,
471
+ { emailLogged, firstNameLogged, lastNameLogged },
472
+ showDOB
473
+ )
474
+ const bodyFormData = createRegisterFormData(
475
+ values,
476
+ checkoutBodyForRegistration
477
+ )
478
+ let access_token_register = null
479
+ try {
480
+ const resRegister = await register(bodyFormData)
481
+ access_token_register = _get(
482
+ resRegister,
483
+ 'data.data.attributes.access_token'
484
+ )
485
+ const refreshToken = _get(
486
+ resRegister,
487
+ 'data.data.attributes.refresh_token'
488
+ )
489
+ handleSetAccessToken(access_token_register)
490
+ const tokens = {
491
+ accessToken: access_token_register,
492
+ refreshToken,
493
+ }
494
+ onRegisterSuccess(tokens)
495
+ } catch (e) {
496
+ if (axios.isAxiosError(e)) {
497
+ const error = e?.response?.data?.message
498
+ if (_includes(error, 'You must be aged')) {
499
+ formikHelpers.setFieldError('holderAge', error)
500
+ }
501
+ if (error?.password) {
502
+ formikHelpers.setFieldError('password', error.password)
503
+ formikHelpers.setFieldError(
504
+ 'confirmPassword',
505
+ error.password
506
+ )
507
+ }
508
+ if (error?.email && !onLogin) {
509
+ // False will stand for outside controll
510
+ setAlreadyHasUser(true)
511
+ setShowModalLogin(true)
512
+ }
513
+
514
+ if (_includes(error, 'The cart is expired') && !hideErrorsAlertSection) {
515
+ setError(error)
516
+ }
517
+
518
+ onRegisterError(e, values.email)
519
+ }
520
+ return
521
+ }
522
+ const profileData = await getProfileData(access_token_register)
523
+ const profileSpecifiedData = _get(profileData, 'data.data')
524
+ const profileDataObj = setLoggedUserData(profileSpecifiedData)
525
+ if (isWindowDefined) {
526
+ window.localStorage.setItem(
527
+ 'user_data',
528
+ JSON.stringify(profileDataObj)
529
+ )
530
+ }
531
+
532
+ const checkoutBody = collectCheckoutBody(values)
533
+ const res = await postOnCheckout(
534
+ checkoutBody,
535
+ access_token_register
536
+ )
537
+ handleSubmit(
538
+ values,
539
+ formikHelpers as FormikHelpers<any>,
540
+ eventId,
541
+ res
542
+ )
543
+ } catch (e) {
544
+ if (axios.isAxiosError(e)) {
545
+ if (e.response?.data.error === 'invalid_token') {
546
+ if (isWindowDefined) {
547
+ window.localStorage.removeItem('user_data')
548
+ window.localStorage.removeItem('access_token')
549
+ setUserExpired(true)
550
+ setShowModalLogin(true)
551
+ }
552
+ }
553
+ if (e.response?.data.message && !hideErrorsAlertSection) {
554
+ setError(_get(e, 'response.data.message'))
555
+ }
556
+ onSubmitError(e)
557
+ }
558
+ }
559
+ }}
560
+ >
561
+ {(props: FormikProps<any>) => (
562
+ <Form onSubmit={props.handleSubmit}>
563
+ <ErrorFocus />
564
+ <LogicRunner
565
+ values={props.values}
566
+ setStates={setStates}
567
+ setFieldValue={props.setFieldValue}
568
+ setValues={props.setValues}
569
+ setUserValues={setUserValues}
570
+ onGetStatesSuccess={onGetStatesSuccess}
571
+ onGetStatesError={onGetStatesError}
572
+ />
573
+ <div className={`billing-info-container ${theme}`}>
574
+ <SnackbarAlert
575
+ type="error"
576
+ isOpen={!!error}
577
+ message={error || ''}
578
+ onClose={() => {
579
+ setError(null)
580
+ onErrorClose()
581
+ }}
582
+ />
583
+ {!isLoggedIn && (
584
+ <div className="account-actions-block">
585
+ <div>{accountInfoTitle}</div>
586
+ <div>Login & skip ahead:</div>
587
+ <div className="login-block">
588
+ <button
589
+ className="login-register-button"
590
+ type="button"
591
+ onClick={() => {
592
+ // If outside login needed to skip package login functionallity
593
+ if (onLogin) {
594
+ onLogin()
595
+ } else {
596
+ setShowModalLogin(true)
597
+ }
598
+ }}
599
+ >
600
+ Login
601
+ </button>
602
+ {!hideLogo && (
603
+ <div className="logo-image-container">
604
+ <img
605
+ src={
606
+ theme === 'dark'
607
+ ? 'https://www.ticketfairy.com/resources/images/logo-ttf.svg'
608
+ : 'https://www.ticketfairy.com/resources/images/logo-ttf-black.svg'
609
+ }
610
+ alt="nodata"
611
+ />
612
+ </div>
613
+ )}
614
+ </div>
615
+ </div>
616
+ )}
617
+ {_map(dataWithUniqueIds, item => {
618
+ const { label, labelClassName, fields } = item
619
+ return (
620
+ <React.Fragment key={item.uniqueId}>
621
+ <p className={labelClassName}>{label}</p>
622
+ {_map(fields, group => {
623
+ const { groupClassname, groupItems } = group
624
+ return (
625
+ <React.Fragment key={group.uniqueId}>
626
+ <div className={groupClassname}>
627
+ {_map(
628
+ groupItems.filter(el => {
629
+ if (el.name === 'holderAge' && !showDOB) {
630
+ return false
631
+ }
632
+ if (el.name === 'ttf_opt_in' && hideTtfOptIn) {
633
+ return false
634
+ }
635
+ if (el.name === 'phone') {
636
+ el.required = flagRequirePhone
637
+ }
638
+ return true
639
+ }),
640
+ element =>
641
+ [
642
+ 'password',
643
+ 'confirmPassword',
644
+ 'password-info',
645
+ ].includes(element.name) &&
646
+ isLoggedIn ? null : (
647
+ <React.Fragment key={element.uniqueId}>
648
+ <div className={element.className}>
649
+ {element.component ? (
650
+ element.component
651
+ ) : (
652
+ <Field
653
+ name={element.name}
654
+ label={element.name === 'phone'
655
+ ? `${element.label}${flagRequirePhone ? '' : ' (optional)'} `
656
+ : element.label}
657
+ type={element.type}
658
+ validate={getValidateFunctions(
659
+ element,
660
+ states,
661
+ props.values
662
+ )}
663
+ setFieldValue={props.setFieldValue}
664
+ onBlur={props.handleBlur}
665
+ component={
666
+ element.type === 'checkbox'
667
+ ? CheckboxField
668
+ : element.type === 'select'
669
+ ? SelectField
670
+ : element.type === 'phone'
671
+ ? FormikPhoneNumberField
672
+ : CustomField
673
+ }
674
+ selectOptions={
675
+ element.name === 'country'
676
+ ? countries
677
+ : element.name === 'state'
678
+ ? states
679
+ : []
680
+ }
681
+ theme={theme}
682
+ />
683
+ )}
684
+ </div>
685
+ </React.Fragment>
686
+ )
687
+ )}
688
+ </div>
689
+ </React.Fragment>
690
+ )
691
+ })}
692
+ </React.Fragment>
693
+ )
694
+ })}
695
+ {!_isEmpty(ticketHoldersFields.fields) && (
696
+ <div className="ticket-holders-fields">
697
+ <p>{ticketHoldersFields.label}</p>
698
+ {_map(ticketsQuantity, (_item, index) => (
699
+ <div key={_item}>
700
+ <h5>Ticket {index + 1}</h5>
701
+ {_map(ticketHoldersFields.fields, group => {
702
+ const { groupClassname, groupItems } = group
703
+ return (
704
+ <div key={group.id}>
705
+ <div className={groupClassname}>
706
+ {_map(groupItems, element => (
707
+ <div
708
+ className={element.className}
709
+ key={element.name}
710
+ >
711
+ <Field
712
+ name={`${element.name}-${index}`}
713
+ label={element.label}
714
+ type={element.type}
715
+ required={true}
716
+ component={
717
+ element.type === 'checkbox'
718
+ ? CheckboxField
719
+ : CustomField
720
+ }
721
+ validate={combineValidators(
722
+ element.required
723
+ ? requiredValidator
724
+ : () => {},
725
+ element.onValidate
726
+ ? element.onValidate
727
+ : () => {}
728
+ )}
729
+ />
730
+ </div>
731
+ ))}
732
+ </div>
733
+ </div>
734
+ )
735
+ })}
736
+ </div>
737
+ ))}
738
+ </div>
739
+ )}
740
+ <div className="button-container">
741
+ <Button
742
+ type="submit"
743
+ variant="contained"
744
+ className="login-register-button"
745
+ disabled={props.isSubmitting}
746
+ >
747
+ {props.isSubmitting ? (
748
+ <CircularProgress size={26} />
749
+ ) : (
750
+ buttonName
751
+ )}
752
+ </Button>
753
+ </div>
754
+ </div>
755
+ </Form>
756
+ )}
757
+ </Formik>
758
+ {showModalLogin && (
759
+ <LoginModal
760
+ onClose={() => {
761
+ setShowModalLogin(false)
762
+ }}
763
+ onLogin={() => {
764
+ setShowModalLogin(false)
765
+ setUserExpired(false)
766
+ onLoginSuccess()
767
+ }}
768
+ alreadyHasUser={alreadyHasUser}
769
+ userExpired={userExpired}
770
+ onAuthorizeSuccess={onAuthorizeSuccess}
771
+ onAuthorizeError={onAuthorizeError}
772
+ onGetProfileDataSuccess={(data: any) => {
773
+ fetchCart()
774
+ onGetProfileDataSuccess(data)
775
+ }}
776
+ onGetProfileDataError={onGetProfileDataError}
777
+ />
778
+ )}
779
+ {showModalRegister && (
780
+ <RegisterModal
781
+ onClose={() => {
782
+ setShowModalRegister(false)
783
+ }}
784
+ onRegister={() => {
785
+ setShowModalRegister(false)
786
+ }}
787
+ onGetProfileDataSuccess={(data: any) => {
788
+ fetchCart()
789
+ onGetProfileDataSuccess(data)
790
+ }}
791
+ onGetProfileDataError={onGetProfileDataError}
792
+ />
793
+ )}
794
+ </ThemeProvider>
795
+ )
796
+ }