-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
691 lines (613 loc) · 26.6 KB
/
App.js
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
import * as React from 'react';
import {
Platform,
StatusBar,
StyleSheet,
View,
Button,
Alert,
TouchableOpacity,
Image,
} from 'react-native';
import { firebase } from '@react-native-firebase/perf';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as SplashScreen from 'expo-splash-screen';
import * as Font from 'expo-font';
import {Ionicons} from '@expo/vector-icons';
import {NavigationContainer, DrawerActions} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import DrawerNavigator from './navigation/DrawerNavigator';
import BottomTabNavigator from './navigation/BottomTabNavigator';
import useLinking from './navigation/useLinking';
import DefaultRemoteConfig from './utils/defaultRemoteConfig'
import {Icon} from 'react-native-elements';
import {useNavigation} from '@react-navigation/native'
import {SignIn, CreateAccount, Splash} from './screens/LoginScreen';
import ForgotPasswordScreen from './screens/ForgotPasswordScreen';
import OtpVerificationScreen from './screens/OtpVerificationScreen';
import ResetPasswordScreen from './screens/ResetPasswordScreen';
import {
AuthRequestLogin,
AuthRequestGoogleLogin,
AuthRequestFBLogin,
AuthRequestAppleLogin
} from './components/AuthLoginComponent';
import {CreateAccountComponent} from './components/CreateAccountComponent';
import {RequestPasswordOTP} from './components/RequestPasswordOTP';
import {VerifyOTP} from './components/VerifyOTPPassoword';
import {AuthContext} from './constants/Context';
import {storeData, retrieveData, storeUser} from './components/AuthKeyStorageComponent';
import Store from './config/store';
import ProductScreen from './screens/Products';
import PaymentType from './screens/PaymentType';
import Cart from './screens/Cart';
import Loading from './components/loading';
import AddressDetail from './screens/AddressDetail';
import AddressCreation from './screens/AddressCreation';
import Payment from './screens/Payment';
import PaymentSuccess from './screens/PaymentSuccess';
import ProfileNavigatorScreens from './navigation/profileNavigator';
import Orders from './screens/Orders';
import OrderDetail from './screens/OrderDetail';
import Support from './screens/Support';
import RestaurantList from './screens/RestaurantList';
import MyDetails from './screens/MyDetails';
import messaging from '@react-native-firebase/messaging';
import remoteConfig from '@react-native-firebase/remote-config';
import {RequestEmailOTP} from "./components/RequestEmailOTP";
import {VerifyEmailOTP} from "./components/VerifyEmailOTP";
import {setRemoteConfig} from "./utils/vars";
const Stack = createStackNavigator();
state = {
email: "",
password: ""
}
export default function App(props) {
const [isLoadingComplete, setLoadingComplete] = React.useState(false);
const [initialNavigationState, setInitialNavigationState] = React.useState();
const containerRef = React.useRef();
const {getInitialState} = useLinking(containerRef);
const [isLoading, setIsLoading] = React.useState(true);
const [userToken, setUserToken] = React.useState(null);
const authContext = React.useMemo(() => {
return {
signIn: (email, password) => {
loginRequest(email, password);
},
signUp: (email, password, confirmpassword) => {
setIsLoading(true);
CreateAccountComponent(email, password, confirmpassword)
.then((data) => {
const result = JSON.stringify(data);
if (result.toUpperCase() == '"Account created"'.toUpperCase()) {
loginRequest(email, password);
} else {
setIsLoading(false);
if(JSON.parse(result)?.DuplicateUserName && JSON.parse(result)?.DuplicateUserName[0] !== ""){
Alert.alert(JSON.parse(result)?.DuplicateUserName[0]);
} else {
Alert.alert("Please try to create account again.");
}
}
}).catch((error) => {
setIsLoading(false);
console.log('error', error)
});
},
ForgotPasswordOTP: (email) => {
return new Promise((resolve, reject) => {
RequestPasswordOTP(email)
.then((data) => {
resolve(data);
}).catch((error) => {
reject(error)
console.log('error', error)
});
})
},
RequestEmailOTP: (email) => {
return new Promise((resolve, reject) => {
RequestEmailOTP(email)
.then((data) => {
resolve(data);
}).catch((error) => {
reject(error)
console.log('error', error)
});
})
},
VerifyOTPResetPassword: (data = {}) => {
return new Promise((resolve, reject) => {
VerifyOTP(data)
.then((data) => {
resolve(data);
}).catch((error) => {
reject(error)
console.log('error', error)
});
})
},
VerifyEmailOTP: (data = {}) => {
return new Promise((resolve, reject) => {
VerifyEmailOTP(data)
.then((data) => {
resolve(data);
}).catch((error) => {
reject(error)
console.log('error', error)
});
})
},
signOut: () => {
setUserToken(null);
},
googleSignIn: (token) => {
googleSignInRequest(token);
},
facebookSignIn: (token) => {
facebookSignInRequest(token);
},
appleSignIn: (data) => {
appleSignInRequest(data);
},
}
}, []);
const remote = async () => {
new Promise(async (resolve,reject)=>{
try {
await remoteConfig().setConfigSettings({
minimumFetchIntervalMillis: 300,
});
remoteConfig()
.setDefaults({
'us_remote_config': JSON.stringify(DefaultRemoteConfig),
}).then(() => remoteConfig().fetch(300).then(() => remoteConfig().fetchAndActivate()
.then(async (fetchedRemotely) => {
if (fetchedRemotely) {
let config = await remoteConfig().getAll();
console.log('[config]',config)
let config1 = config['us_remote_config']
console.log('[config]',config1)
setRemoteConfig(JSON.parse(config1._value));
await AsyncStorage.setItem('us_remote_config',config1._value);
Store.setRemoteConfig(config1._value ? JSON.parse(config1._value) : {})
resolve()
} else {
AsyncStorage.getItem('us_remote_config').then((conf)=>{
console.log('[config]',JSON.parse(conf))
if(conf !== null){
setRemoteConfig(JSON.parse(conf));
Store.setRemoteConfig(JSON.parse(conf))
}
});
resolve()
}
})));
} catch (err){
alert('cache')
}
})
}
// Load any resources or data that we need prior to rendering the app
React.useEffect(async () => {
await firebase.perf().setPerformanceCollectionEnabled(true);
await remote();
messaging().onMessage(async (remoteMessage) => {
console.log("[Notification]", remoteMessage);
//setTimeout(()=>containerRef?.current?.navigate('PaymentSuccess', { orderId: "rauk-189660406", orderType: 2 }),1000)
//store.dispatch(callSetOrderShow(0));
});
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log("[Notification]", remoteMessage);
setTimeout(() => containerRef?.current?.navigate('PaymentSuccess', {
orderId: "rauk-189660406",
orderType: 2
}), 1000)
//store.dispatch(callSetOrderShow(0));
});
messaging().onNotificationOpenedApp(remoteMessage => {
setTimeout(() => containerRef?.current?.navigate('PaymentSuccess', {
orderId: "rauk-189660406",
orderType: 2
}), 3000)
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
});
// Check whether an initial notification is available
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
setTimeout(() => containerRef?.current?.navigate('PaymentSuccess', {
orderId: "rauk-189660406",
orderType: 2
}), 3000)
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
}
});
async function loadResourcesAndDataAsync() {
try {
SplashScreen.preventAutoHide();
// Load our initial navigation state
setInitialNavigationState(await getInitialState());
// Load fonts
await Font.loadAsync({
...Ionicons.font,
'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf'),
'SFProText': require('./assets/fonts/FontsFree-Net-SFProText-Semibold.ttf'),
'Roboto-Regular': require('./assets/fonts/Roboto-Regular.ttf'),
'Roboto-Medium': require('./assets/fonts/Roboto-Medium.ttf'),
'Roboto-Bold': require('./assets/fonts/Roboto-Bold.ttf'),
});
let loginCredential = await AsyncStorage.getItem('login credential');
let facebookCredential = await AsyncStorage.getItem('facebook credential');
let googleCredential = await AsyncStorage.getItem('google credential');
let appleCredential = await AsyncStorage.getItem('apple credential');
console.log('google credential', googleCredential)
if (loginCredential != null) {
let parsed = JSON.parse(loginCredential);
loginRequest(parsed.email, parsed.password);
} else if (facebookCredential != null) {
facebookSignInRequest(facebookCredential);
} else if (googleCredential != null) {
googleSignInRequest(googleCredential);
} else if (appleCredential != null) {
let parsed = JSON.parse(appleCredential);
appleSignInRequest(parsed);
} else {
setIsLoading(false)
}
} catch (e) {
// We might want to provide this error information to an error reporting service
console.warn(e);
} finally {
setLoadingComplete(true);
SplashScreen.hide();
}
}
loadResourcesAndDataAsync();
// setTimeout(() => {
// setIsLoading(false);
// }, 1000)
}, []);
function loginRequest(email, password) {
var STORAGE_KEY = 'id_token';
setIsLoading(true);
AuthRequestLogin(email, password)
.then((data) => {
//Alert.alert("received call");
if (data.login_failure) {
Alert.alert(data.login_failure[0]);
setUserToken(null);
} else {
const result = JSON.parse(data);
setUserToken(result.auth_token);
//store token
storeData(STORAGE_KEY, result.auth_token)
.then((data) => {
const result = JSON.stringify(data);
});
//store user
storeUser(result.auth_token).then((data) => {
console.log("user stored " + data);
});
let obj = {
email: email,
password: password
}
AsyncStorage.setItem('login credential', JSON.stringify(obj));
}
setIsLoading(false);
}).catch((error) => {
console.log('error.', error)
if (error == 'TypeError: Network request failed') {
alert('Please check your internet connection and try again.');
}
setIsLoading(false);
setUserToken(null);
});
};
function googleSignInRequest(token) {
var STORAGE_KEY = 'id_token';
setIsLoading(true);
AuthRequestGoogleLogin(token)
.then((data) => {
console.log('google response', data)
const result = JSON.parse(data);
setUserToken(result.auth_token);
//store token
storeData(STORAGE_KEY, result.auth_token)
.then((data) => {
const result = JSON.stringify(data);
});
//store user
storeUser(result.auth_token).then((data) => {
console.log("user stored " + data);
});
AsyncStorage.setItem('google credential', token);
setIsLoading(false);
}).catch((error) => {
if (error == 'TypeError: Network request failed') {
alert('Please check your internet connection and try again.');
}
setIsLoading(false);
setUserToken(null);
});
};
function facebookSignInRequest(token) {
var STORAGE_KEY = 'id_token';
setIsLoading(true);
AuthRequestFBLogin(token)
.then((data) => {
const result = JSON.parse(data);
setUserToken(result.auth_token);
//store token
storeData(STORAGE_KEY, result.auth_token)
.then((data) => {
const result = JSON.stringify(data);
});
storeUser(result.auth_token).then((data) => {
console.log("user stored " + data);
});
AsyncStorage.setItem('facebook credential', token);
setIsLoading(false);
}).catch((error) => {
if (error == 'TypeError: Network request failed') {
alert('Please check your internet connection and try again.');
}
setIsLoading(false);
setUserToken(null);
});
};
function appleSignInRequest(dataObject) {
var STORAGE_KEY = 'id_token';
setIsLoading(true);
AuthRequestAppleLogin(dataObject)
.then((data) => {
const result = JSON.parse(data);
setUserToken(result.auth_token);
//store token
storeData(STORAGE_KEY, result.auth_token)
.then((data) => {
const result = JSON.stringify(data);
});
storeUser(result.auth_token).then((data) => {
console.log("user stored " + data);
});
AsyncStorage.setItem('apple credential', JSON.stringify(dataObject));
setIsLoading(false);
}).catch((error) => {
console.log('error', error)
if (error == 'TypeError: Network request failed') {
alert('Please check your internet connection and try again.');
}
setIsLoading(false);
setUserToken(null);
});
};
if (isLoading) {
return <Splash/>;
}
if (!isLoadingComplete && !props.skipLoadingScreen) {
return null;
} else {
return (
<AuthContext.Provider value={authContext}>
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default"/>}
<NavigationContainer ref={containerRef} initialState={initialNavigationState}>
<RootStackScreen userToken={userToken} state={state}/>
</NavigationContainer>
</View>
</AuthContext.Provider>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
menuIcon: {
paddingRight: 5
},
});
const AuthStack = createStackNavigator();
const AuthStackScreen = () => (
<AuthStack.Navigator headerMode="none">
<AuthStack.Screen name="SignIn" component={SignIn} options={{title: "Sign In"}}/>
<AuthStack.Screen name="ForgotPassword" component={ForgotPasswordScreen} options={{title: "Forgot Password"}}/>
<AuthStack.Screen name="ResetPassword" component={ResetPasswordScreen} options={{title: "Forgot Password"}}/>
<AuthStack.Screen name="OtpVerification" component={OtpVerificationScreen}
options={{title: "OTP Verification"}}/>
<AuthStack.Screen name="CreateAccount" component={CreateAccount}
options={{title: "Create Account"}}/>
</AuthStack.Navigator>
);
const PageStack = createStackNavigator();
const PageScreen = () => (
<PageStack.Navigator headerMode="screen"
>
<PageStack.Screen name="Page" component={BottomTabNavigator}
options={{headerShown: false}}
/>
<PageStack.Screen name="Products" component={ProductScreen} options={({navigation, userToken}) => (
{
headerMode: 'screen',
title: 'Product Details',
headerStyle: {
backgroundColor: '#f4511e'
},
headerTintColor: '#fff'
}
)}/>
<PageStack.Screen name="Cart"
component={Cart}
options={({navigation}) => (
{
headerShown: false
}
)}
/>
<PageStack.Screen name="PaymentType"
component={PaymentType}
options={({navigation}) => (
{
headerShown: false
}
)}
/>
<PageStack.Screen name="Payment"
component={Payment}
options={({navigation}) => (
{
headerShown: false
}
)}
/>
<PageStack.Screen name="PaymentSuccess"
component={PaymentSuccess}
options={({navigation}) => (
{
headerShown: false
}
)}
/>
<PageStack.Screen name="MyProfile" component={ProfileNavigatorScreens}/>
<PageStack.Screen name="AddressDetail"
component={AddressDetail}
options={({navigation}) => (
{
headerMode: 'screen',
title: 'Address Detail',
headerStyle: {
backgroundColor: '#f4511e'
},
headerTintColor: '#fff',
headerBackTitle: ''
}
)}
/>
<PageStack.Screen name="CreateAddress"
component={AddressCreation}
options={({navigation}) => (
{
headerShown: false
// headerMode: 'screen',
// title: 'Address Creation',
// headerStyle: {
// backgroundColor: '#f4511e'
// },
// headerTintColor: '#fff',
// headerBackTitle: ''
}
)}
/>
<PageStack.Screen name="Orders" component={Orders}
options={({navigation}) => (
{
headerShown: false
}
)}
/>
<PageStack.Screen name="OrderDetail" component={OrderDetail}
options={({navigation}) => (
{
headerShown: false
}
)}
/>
<PageStack.Screen name="Support" component={Support}
options={({navigation}) => (
{
headerShown: false
}
)}
/>
<PageStack.Screen name="MyDetails" component={MyDetails}
options={({navigation}) => (
{
headerShown: false
}
)}
/>
<PageStack.Screen name="SignIn" component={SignIn}
options={{headerShown: false}}
/>
<PageStack.Screen name="ForgotPassword" component={ForgotPasswordScreen}
options={{title: "Forgot Password", headerShown: false}}/>
<PageStack.Screen name="ResetPassword" component={ResetPasswordScreen}
options={{title: "Forgot Password", headerShown: false}}/>
<PageStack.Screen name="OtpVerification" component={OtpVerificationScreen}
options={{title: "OTP Verification", headerShown: false}}/>
<PageStack.Screen name="CreateAccount" component={CreateAccount}
options={{headerShown: false}}/>
<PageStack.Screen name="RestaurantList"
component={RestaurantList}
options={({navigation}) => (
{
headerShown: false
}
)}
/>
</PageStack.Navigator>
);
const RootStack = createStackNavigator();
const RootStackScreen = ({userToken}) => (
<RootStack.Navigator>
{
userToken ? (
<RootStack.Screen name="App" component={PageScreen}
options={({navigation}) => (
{headerShown: false}
)}
// options={({navigation, userToken}) => (
// {
// title: 'Restaurant Name',
// headerStyle: {
// backgroundColor: '#f4511e',
// },
// headerTintColor: '#fff',
// headerTitleStyle: {
// fontWeight: 'bold',
// },
// headerLeft: () => (
// <Icon style={styles.menuIcon} name='menu' size={42} color='white'
// onPress={()=> {navigation.dispatch(DrawerActions.openDrawer())}}
// />
// ),
// headerRight: () => (
// <TouchableOpacity style={{paddingRight: 15, position: 'relative'}} onPress={() => this.props.navigation.navigate('Cart')} >
// <Image source={require('./assets/images/cart-icon-white.png')} style={{width: 29, height: 32, resizeMode: 'contain'}} />
// <View style={{width: 20, height: 20, borderRadius: 10, position: 'absolute', backgroundColor: '#fff', bottom: -7, right: 7, justifyContent: 'center'}}>
// <Text style={{color: '#000', textAlign: 'center', fontSize: 10}}>{Store.cartCount}</Text>
// </View>
// </TouchableOpacity>
// )
// }
// )}
/>
) : (
<RootStack.Screen name="Auth" component={AuthStackScreen}
options={({navigation}) => ({headerShown: false}
// {
// title: 'Restaurant Name',
// headerStyle: {
// backgroundColor: '#f4511e',
// },
// headerTintColor: '#fff',
// headerTitleStyle: {
// fontWeight: 'bold',
// },
// }
)}
/>
)
}
</RootStack.Navigator>
);