tf-checkout-react 1.0.101 → 1.0.102

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