-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathApp.tsx
More file actions
615 lines (539 loc) · 19.2 KB
/
App.tsx
File metadata and controls
615 lines (539 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
// React Components
import { Linking, Platform, Pressable } from 'react-native'
import React, { useEffect, useMemo, useRef, useState } from 'react'
// OneSignal Push Notifications
import { OneSignal } from 'react-native-onesignal'
// Navigation Components
import { enableFreeze } from 'react-native-screens'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import { createNativeStackNavigator } from '@react-navigation/native-stack'
import { NavigationContainer, useNavigation, DefaultTheme, DarkTheme } from '@react-navigation/native'
enableFreeze(true)
const Stack = createNativeStackNavigator()
// Auth Context
import { AuthProvider, useAuth } from './auth/AuthContext'
// Settings Context
import { SettingsProvider, useSettings } from './settings/SettingsContext'
// App Lock
import { AppLockProvider } from './lock/AppLockContext'
import LockScreen from './lock/LockScreen'
// Online Status
import { OnlineStatusProvider } from './hooks/OnlineStatusContext'
// Loading
import GlobalLoadingBar from './ui/GlobalLoadingBar'
import { LoadingProvider, useLoading } from './loading/LoadingContext'
import { registerLoadingCallbacks, unregisterLoadingCallbacks } from './api/client'
// Theme Provider
import { useTheme } from './theme/ThemeContext'
import { ThemeProvider } from './theme/ThemeContext'
import { createContainerStyles } from './theme/themeUtils'
// Routes
import { ROUTES } from './routes'
// Deep Linking
import linking from './linking'
// Screens without auth
import HelpScreen from './screens/help/Help'
import LoginScreen from './auth/screens/Login'
import SplashScreen from './screens/splash/Splash'
import WelcomeScreen from './screens/welcome/Welcome'
import RegisterScreen from './auth/screens/Register'
import Recover2FAScreen from './auth/screens/Recover2FA'
import RecoverPasswordScreen from './auth/screens/RecoverPassword'
// Screens with auth
import Onboard from './screens/onboard/Onboard'
import MainStack from './screens/MainStack'
import Send from './screens/transaction/Send'
import SendConfirm from './screens/transaction/SendConfirm'
import SendSuccess from './screens/transaction/SendSuccess'
import Receive from './screens/transaction/Receive'
import Transaction from './screens/transaction/Transaction'
import Transactions from './screens/transaction/Transactions'
import Pay from './screens/transaction/Pay'
import P2PCreate from './screens/p2p/P2PCreate'
import P2POffer from './screens/p2p/P2POffer'
import P2PUser from './screens/p2p/P2PUser'
import GoldCheck from './screens/settings/subpanels/GoldCheck'
import Scan from './screens/scan/Scan'
// Invest Screens
import Savings from './screens/invest/Savings'
import StockDetail from './screens/invest/StockDetail'
// InOut Screens
import Add from './screens/add/Add'
import Withdraw from './screens/withdraw/Withdraw'
// Store Screens
import PhoneTopupIndex from './screens/store/PhoneTopupIndex'
import PhoneTopupPurchase from './screens/store/PhoneTopupPurchase'
import GiftCards from './screens/store/GiftCards'
import GiftCardDetail from './screens/store/GiftCardDetail'
import MyPurchases from './screens/store/MyPurchases'
import PurchaseDetail from './screens/store/PurchaseDetail'
// Settings Stack
import SettingsStack from './screens/settings/SettingsStack'
import Contacts from './screens/settings/subpanels/Contacts'
// Notifications
import { Toaster, toast } from 'sonner-native'
// Sound
import playSound from './helpers/playSound'
// UI Components
import QPAvatar from './ui/particles/QPAvatar'
import ErrorBoundary from './ui/ErrorBoundary'
import UpdatePromptModal from './ui/UpdatePromptModal'
// Version Check
import { maybePromptUpdate } from './helpers/versionCheck'
// Parse P2P UUID from a deep link URL
const parseP2PUuid = (url: string): string | null => {
const match = url.match(/\/p2p\/([^/?#]+)/)
if (match) return match[1]
const schemeMatch = url.match(/qvapay:\/\/p2p\/([^/?#]+)/)
if (schemeMatch) return schemeMatch[1]
return null
}
// Parse Pay UUID from a deep link URL (e.g. https://qvapay.com/pay/<uuid> or qvapay://pay/<uuid>)
const parsePayUuid = (url: string): string | null => {
const match = url.match(/\/pay\/([^/?#]+)/)
if (match) return match[1]
const schemeMatch = url.match(/qvapay:\/\/pay\/([^/?#]+)/)
if (schemeMatch) return schemeMatch[1]
return null
}
// Main App Navigator Component
const AppNavigator = ({ pendingDeepLinkRef }: { pendingDeepLinkRef: React.RefObject<string | null> }) => {
// Theme variables, dark and light modes
const { theme } = useTheme()
const containerStyles = useMemo(() => createContainerStyles(theme), [theme])
// Consistent header options using native back button (works with iOS liquid glass)
const getHeaderOptions = useMemo(() => (title: string, options?: {
animation?: 'slide_from_right' | 'slide_from_bottom' | 'slide_from_left' | 'none';
headerRight?: () => React.ReactNode;
}) => ({
headerTitle: title,
headerTitleAlign: 'center' as const,
headerShown: true,
headerShadowVisible: false,
animation: options?.animation || 'slide_from_right' as const,
...(options?.headerRight && { headerRight: options.headerRight }),
}), [])
// State to control minimum splash screen time
const [splashReady, setSplashReady] = useState(false)
// Update prompt state
const [updateInfo, setUpdateInfo] = useState<{ needsUpdate: boolean; currentVersion?: string; latestVersion?: string; storeUrl?: string } | null>(null)
// Check if this is the first time using the app
const { appearance, sounds, isLoading: settingsLoading } = useSettings()
const firstTime = appearance.firstTime
// Navigation
const navigation = useNavigation()
// Auth Context
const { user } = useAuth()
const { isAuthenticated, isLoading: authLoading } = useAuth()
useEffect(() => {
const timer = setTimeout(() => {
setSplashReady(true)
}, 2000)
return () => clearTimeout(timer)
}, [])
// Check for store update on app launch
useEffect(() => {
(async () => {
const info = await maybePromptUpdate()
if (info?.needsUpdate) setUpdateInfo(info)
})()
}, [])
// Navigation handler for auth state changes
// Only re-run when auth state actually changes, not on settings/theme changes
useEffect(() => {
if (splashReady && !authLoading && !settingsLoading) {
const currentRoute = navigation.getState()?.routes[navigation.getState()?.index || 0]?.name
if (isAuthenticated && !firstTime && currentRoute !== ROUTES.MAIN_STACK) {
// Check for a pending deep link after login
const pendingUrl = pendingDeepLinkRef.current
if (pendingUrl) {
pendingDeepLinkRef.current = null
const payUuid = parsePayUuid(pendingUrl)
if (payUuid) {
navigation.reset({
index: 1,
routes: [
{ name: ROUTES.MAIN_STACK as never },
{ name: ROUTES.PAY_SCREEN as never, params: { uuid: payUuid } as never },
],
})
return
}
const p2pUuid = parseP2PUuid(pendingUrl)
if (p2pUuid) {
navigation.reset({
index: 1,
routes: [
{ name: ROUTES.MAIN_STACK as never },
{ name: ROUTES.P2P_OFFER_SCREEN as never, params: { p2p_uuid: p2pUuid } as never },
],
})
return
}
}
navigation.reset({ index: 0, routes: [{ name: ROUTES.MAIN_STACK as never }] })
} else if (!isAuthenticated && !firstTime && currentRoute !== ROUTES.WELCOME_SCREEN) {
// Capture the current deep link URL before resetting to Welcome
Linking.getInitialURL().then((url) => {
if (!url) return
if (parsePayUuid(url)) {
pendingDeepLinkRef.current = url
toast.info('Inicia sesión para pagar la factura')
} else if (parseP2PUuid(url)) {
pendingDeepLinkRef.current = url
toast.info('Inicia sesión para ver la oferta P2P')
}
})
navigation.reset({ index: 0, routes: [{ name: ROUTES.WELCOME_SCREEN as never }] })
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [splashReady, authLoading, settingsLoading, isAuthenticated, firstTime])
// Listen for foreground deep links while unauthenticated
useEffect(() => {
const subscription = Linking.addEventListener('url', ({ url }) => {
if (!isAuthenticated && url) {
if (parsePayUuid(url)) {
pendingDeepLinkRef.current = url
toast.info('Inicia sesión para pagar la factura')
} else if (parseP2PUuid(url)) {
pendingDeepLinkRef.current = url
toast.info('Inicia sesión para ver la oferta P2P')
}
}
})
return () => subscription.remove()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isAuthenticated])
// OneSignal notification listeners
useEffect(() => {
// Foreground notification: show as toast
const onForeground = (event: any) => {
event.preventDefault()
const notification = event.getNotification()
const data = notification.additionalData
// Play sound based on notification type
if (sounds?.enabled) {
if (sounds?.transactionSound && (data?.type === 'transaction' || data?.type === 'transfer')) {
playSound('money_in')
} else {
playSound('notification')
}
}
toast.info(notification.title || 'QvaPay', { description: notification.body || undefined })
notification.display()
}
// Notification tapped: navigate to the right screen
const onClicked = (event: any) => {
const data = event.notification?.additionalData
if (!data?.type || !isAuthenticated) return
if (data.type === 'transaction' && data.uuid) {
(navigation as any).navigate(ROUTES.TRANSACTION, { uuid: data.uuid })
} else if (data.type === 'p2p' && data.uuid) {
(navigation as any).navigate(ROUTES.P2P_OFFER_SCREEN, { p2p_uuid: data.uuid })
} else if (data.type === 'transfer') {
(navigation as any).navigate(ROUTES.TRANSACTIONS)
}
}
OneSignal.Notifications.addEventListener('foregroundWillDisplay', onForeground)
OneSignal.Notifications.addEventListener('click', onClicked)
return () => {
OneSignal.Notifications.removeEventListener('foregroundWillDisplay', onForeground)
OneSignal.Notifications.removeEventListener('click', onClicked)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isAuthenticated])
// Memoized screen options to prevent re-renders that cause liquid glass flash on iOS
const stackScreenOptions = useMemo(() => ({
headerShown: false,
headerStyle: { backgroundColor: theme.colors.background },
headerShadowVisible: false,
headerBackButtonDisplayMode: 'minimal' as const,
headerTintColor: theme.colors.primaryText,
contentStyle: { backgroundColor: theme.colors.background },
}), [theme])
// Show splash screen if still loading or if minimum time hasn't passed
if (authLoading || settingsLoading || !splashReady) { return <SplashScreen /> }
// Show unauthenticated screens (welcome, login, register)
return (
<>
<Stack.Navigator initialRouteName={firstTime ? ROUTES.ONBOARD_SCREEN : isAuthenticated ? ROUTES.MAIN_STACK : ROUTES.WELCOME_SCREEN} screenOptions={stackScreenOptions}>
{/* Onboard Screen */}
<Stack.Screen name={ROUTES.ONBOARD_SCREEN} component={Onboard} />
{/* Welcome Screen */}
<Stack.Screen
name={ROUTES.WELCOME_SCREEN}
component={WelcomeScreen}
options={{
animation: 'none'
}}
/>
{/* Main Stack */}
<Stack.Screen name={ROUTES.MAIN_STACK} component={MainStack} />
{/* Add and Withdraw Screens */}
<Stack.Screen
name={ROUTES.ADD}
component={Add}
options={getHeaderOptions('Depositar')}
/>
<Stack.Screen
name={ROUTES.WITHDRAW}
component={Withdraw}
options={getHeaderOptions('Extraer')}
/>
{/* P2P Create Screen */}
<Stack.Screen
name={ROUTES.P2P_CREATE_SCREEN}
component={P2PCreate}
options={getHeaderOptions('', { animation: 'slide_from_bottom' })}
/>
{/* P2P Offer Screen */}
<Stack.Screen
name={ROUTES.P2P_OFFER_SCREEN}
component={P2POffer}
options={{
...getHeaderOptions(''),
// Android fallback
headerRight: () => (
<Pressable style={containerStyles.headerRight} onPress={() => { }}>
<QPAvatar user={user} size={32} />
</Pressable>
),
// iOS native header items (liquid glass compatible)
...(Platform.OS === 'ios' && {
unstable_headerRightItems: () => [{
type: 'custom' as const,
element: <QPAvatar user={user} size={28} />,
hidesSharedBackground: true,
}],
}),
}}
/>
{/* P2P User Profile Screen */}
<Stack.Screen
name={ROUTES.P2P_USER_SCREEN}
component={P2PUser}
options={getHeaderOptions('Perfil P2P')}
/>
{/* GoldCheck — also reachable from SettingsStack, but registered here so
peer profile and other screens can push it directly with a back button */}
<Stack.Screen
name={ROUTES.GOLD_CHECK}
component={GoldCheck}
options={getHeaderOptions('Hazte GOLD')}
/>
{/* Settings Stack */}
<Stack.Screen
name={ROUTES.SETTINGS_STACK}
component={SettingsStack}
options={{
animation: 'slide_from_bottom'
}}
/>
{/* Contacts (accessible from Send) */}
<Stack.Screen
name={ROUTES.CONTACTS}
component={Contacts}
options={getHeaderOptions('Contactos')}
/>
{/* Send, Receive and Send Success Screens */}
<Stack.Screen
name={ROUTES.SEND}
component={Send}
options={getHeaderOptions('Enviar QUSD')}
/>
<Stack.Screen
name={ROUTES.SEND_CONFIRM}
component={SendConfirm}
options={getHeaderOptions('Confirmar pago')}
/>
<Stack.Screen name={ROUTES.SEND_SUCCESS} component={SendSuccess} />
<Stack.Screen name={ROUTES.RECEIVE} component={Receive} options={getHeaderOptions('Recibir')} />
{/* Transaction Screen */}
<Stack.Screen
name={ROUTES.TRANSACTIONS}
component={Transactions}
options={getHeaderOptions('Transacciones')}
/>
<Stack.Screen
name={ROUTES.TRANSACTION}
component={Transaction}
options={getHeaderOptions('')}
/>
{/* Pay Screen — bottom-sheet style, slides from bottom, transparent backdrop */}
<Stack.Screen
name={ROUTES.PAY_SCREEN}
component={Pay}
options={{
headerShown: false,
animation: 'slide_from_bottom',
presentation: 'transparentModal',
contentStyle: { backgroundColor: 'transparent' },
}}
/>
{/* Savings Screen */}
<Stack.Screen
name={ROUTES.SAVINGS_SCREEN}
component={Savings}
options={getHeaderOptions('Ahorros')}
/>
{/* Stock Detail Screen */}
<Stack.Screen
name={ROUTES.STOCK_DETAIL_SCREEN}
component={StockDetail}
options={({ route }) => getHeaderOptions(route.params?.name || '')}
/>
{/* QR Scan Screen */}
<Stack.Screen
name={ROUTES.SCAN_SCREEN}
component={Scan}
options={{
animation: 'slide_from_bottom',
headerShown: false,
}}
/>
{/* Login and Register Screens */}
<Stack.Screen
name={ROUTES.LOGIN_SCREEN}
component={LoginScreen}
options={getHeaderOptions('')}
/>
<Stack.Screen
name={ROUTES.REGISTER_SCREEN}
component={RegisterScreen}
options={getHeaderOptions('')}
/>
{/* Recover Password Screen */}
<Stack.Screen
name={ROUTES.RECOVER_PASSWORD_SCREEN}
component={RecoverPasswordScreen}
options={getHeaderOptions('')}
/>
<Stack.Screen
name={ROUTES.RECOVER_2FA_SCREEN}
component={Recover2FAScreen}
options={getHeaderOptions('')}
/>
{/* Phone Topup Screens */}
<Stack.Screen
name={ROUTES.PHONE_TOPUP_INDEX}
component={PhoneTopupIndex}
options={({ route }) => getHeaderOptions(route.params?.external === true ? 'Recargas del exterior' : route.params?.external === false ? 'Microrecargas' : 'Recargas telefónicas')}
/>
<Stack.Screen
name={ROUTES.PHONE_TOPUP_PURCHASE}
component={PhoneTopupPurchase}
options={getHeaderOptions('Comprar recarga')}
/>
{/* Gift Card Screens */}
<Stack.Screen
name={ROUTES.GIFT_CARDS}
component={GiftCards}
options={getHeaderOptions('Tarjetas de regalo')}
/>
<Stack.Screen
name={ROUTES.GIFT_CARD_DETAIL}
component={GiftCardDetail}
options={getHeaderOptions('')}
/>
{/* My Purchases Screens */}
<Stack.Screen
name={ROUTES.MY_PURCHASES}
component={MyPurchases}
options={getHeaderOptions('Mis Compras')}
/>
<Stack.Screen
name={ROUTES.PURCHASE_DETAIL}
component={PurchaseDetail}
options={getHeaderOptions('')}
/>
{/* Accesible Screens */}
<Stack.Screen name={ROUTES.HELP_SCREEN} component={HelpScreen} />
</Stack.Navigator>
<UpdatePromptModal
visible={!!updateInfo?.needsUpdate}
currentVersion={updateInfo?.currentVersion}
latestVersion={updateInfo?.latestVersion}
storeUrl={updateInfo?.storeUrl}
onDismiss={() => setUpdateInfo(null)}
/>
</>
)
}
// Theme Provider with Settings Integration
const ThemeProviderWithSettings = ({ children }: { children: React.ReactNode }) => {
const { settings, updateSettings } = useSettings()
return (
<ThemeProvider settings={settings} updateSettings={updateSettings}>
{children}
</ThemeProvider>
)
}
// Navigation wrapper that provides theme to NavigationContainer
// This prevents the iOS native layer from using default white background during transitions
const NavigationWrapper = ({ children }: { children: React.ReactNode }) => {
const { theme, isDark } = useTheme()
const baseTheme = isDark ? DarkTheme : DefaultTheme
const navigationTheme = useMemo(() => ({
...baseTheme,
dark: isDark,
colors: {
...baseTheme.colors,
primary: theme.colors.primary,
background: theme.colors.background,
card: theme.colors.background,
text: theme.colors.primaryText,
border: theme.colors.surface,
notification: theme.colors.primary,
},
}), [theme, isDark, baseTheme])
return (
<NavigationContainer linking={linking as any} theme={navigationTheme}>
{children}
</NavigationContainer>
)
}
// Bridge component that connects LoadingContext to Axios interceptors
const LoadingBridge = ({ children }: { children: React.ReactNode }) => {
const { startLoading, stopLoading } = useLoading()
useEffect(() => {
registerLoadingCallbacks(startLoading, stopLoading)
return () => { unregisterLoadingCallbacks() }
}, [startLoading, stopLoading])
return <>{children}</>
}
// Initialize OneSignal (must be called outside component, before render)
OneSignal.initialize('8f69c017-b7e7-40b2-903b-11ce7ac5cc81')
function App() {
const pendingDeepLinkRef = useRef<string | null>(null)
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<ErrorBoundary>
<SafeAreaProvider>
<LoadingProvider>
<AuthProvider>
<OnlineStatusProvider>
<SettingsProvider>
<ThemeProviderWithSettings>
<LoadingBridge>
<AppLockProvider>
<NavigationWrapper>
<GlobalLoadingBar />
<AppNavigator pendingDeepLinkRef={pendingDeepLinkRef} />
<Toaster position="top-center" />
</NavigationWrapper>
<LockScreen />
</AppLockProvider>
</LoadingBridge>
</ThemeProviderWithSettings>
</SettingsProvider>
</OnlineStatusProvider>
</AuthProvider>
</LoadingProvider>
</SafeAreaProvider>
</ErrorBoundary>
</GestureHandlerRootView>
)
}
export default App