unioil-loyalty-rn-app/app/screens/route.js

620 lines
23 KiB
JavaScript

import * as React from 'react';
import DeviceInfo from 'react-native-device-info';
import { Platform, Alert, AppState, Linking, Appearance } from 'react-native';
import { NavigationContainer, DarkTheme, DefaultTheme } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { connect } from "react-redux";
import firebase from '@react-native-firebase/app';
import '@react-native-firebase/messaging';
import { saveAppTheme } from "../redux/actions/AppThemeActions";
import { saveFcmToken } from '../redux/actions/AppUserInfoActions';
import DB from '../components/storage/';
import Theme from '../components/theme.style.js';
import Notch from '../components/notch.js';
import REQUEST from '../components/api';
import MainMenu from './main/drawer.js';
import Login from './login/';
import Splash from './splash/';
import Mpin from './mpin';
import Setmpin from './mpin/setmpin';
import Setnewmpin from './mpin/setnewmpin';
import Otp from './mpin/otp';
import SecurityQuestion from './mpin/securityquestion';
import SuccessUpdateMpin from './mpin/succesupdatempin';
import PromoDetails from './main/promo/details.js';
import ProductDetails from './products/details.js';
import LoyaltyCardDetails from './loyalty/details.js';
import MyProfile from './myprofile/';
import TransactionDetails from './myprofile/transaction/details.js';
import EditProfile from './myprofile/profile/edit.js';
import AddAccountCard from './account/add.js';
import ActivateCard from './account/activate.js';
import AccountBirthdate from './account/birthdate.js';
import AccountSendOtp from './account/sendotp.js';
import AccountOtp from './account/otp.js';
import AccountEnrollActivateCard from './account/activate/index.js';
import AccountEnrollPin from './account/activate/pin.js';
import AccountEnrollForm from './account/activate/form.js';
import AccountEnrollOtp from './account/activate/otp.js';
import EnrollActivateCard from './apply/index.js';
import EnrollPin from './apply/pin.js';
import EnrollForm from './apply/form.js';
import EnrollOtp from './apply/otp.js';
import AddTracker from './tracker/add.js';
import AddFuelType from './tracker/addfueltype.js';
import EditTracker from './tracker/edit.js';
import TermsConditions from './login/t&c.js';
import LoginBirthday from './login/birthday.js';
import LoginSendOTP from './login/sendotp.js';
import LoginOTP from './login/otp.js';
import ApplySelectCard from './login/apply/card.js';
import ApplyCardDetails from './login/apply/details.js';
import ApplyForm from './login/apply/form.js';
import ApplyOTP from './login/apply/otp.js';
import LoginEnroll from './login/enroll.js';
import Account from './account/';
import Products from './products/';
import TopUp from './topup/';
import CheckOut from './topup/checkout';
import Tracker from './tracker/';
import About from './about/';
import Loyalty from './loyalty/';
import Contact from './contact/';
import OnBoarding from './onboard/';
// Disable temporarily
import Payatpump from './payatpump';
import PayatpumpStationSearch from './payatpump/search';
import PayatpumpDetails from './payatpump/stationdetails'
import PayatpumpStationDetails from './payatpump/fragments/stationdetailspanel';
import PayatpumpStationTransactionDetails from './payatpump/pumpstationtransactiondetails';
import PayatpumpPointsDetailsInput from './payatpump/pumppoinstdetails';
import PayatpumpPaymentList from './payatpump/pumppaymentlist';
import PayatpumpPaymentMethod from './payatpump/pumppaymentmethod';
import PayatpumpPaymentSuccess from './payatpump/pumppaymentsuccess';
import VerificationWebview from './payatpump/verificationWebview';
import StationDetails from './main/station/details.js';
import StationSearch from './main/station/search.js';
import TokenezationForm from './topup/form';
import messaging from '@react-native-firebase/messaging';
var PushNotification = require('react-native-push-notification');
const RootStack = createStackNavigator();
const AppStack = createStackNavigator();
const navOptions = () => ({
headerShown: true,
gestureEnabled: false
});
const shadowColor = 'transparent';
const screenOptions = {
headerLeft: () => { return null },
headerStyle: {
backgroundColor: Theme.colors.primary,
elevation: 0,
height: Notch.isIphoneWithNotch() ? 44 : 20,
shadowColor: shadowColor
},
headerTintColor: Theme.colors.primary,
headerTitleStyle: {
fontWeight: 'bold'
}
}
export function AppNavigation(props) {
return (
<AppStack.Navigator
initialRouteName={props.initialRoute || 'Main'}
screenOptions={screenOptions}>
<AppStack.Screen name="Main" component={MainMenu} options={navOptions} />
<AppStack.Screen name="Login" component={Login} options={{ headerShown: false }} />
<AppStack.Screen name="Mpin" component={Mpin} options={{ headerShown: false, gestureEnabled: false }} />
<AppStack.Screen name="Setmpin" component={Setmpin} options={navOptions} />
<AppStack.Screen name="Otp" component={Otp} options={navOptions} />
<AppStack.Screen name="SecurityQuestion" component={SecurityQuestion} options={navOptions} />
<AppStack.Screen name="Setnewmpin" component={Setnewmpin} options={navOptions} />
<AppStack.Screen name="SuccessUpdateMpin" component={SuccessUpdateMpin} options={navOptions} />
<AppStack.Screen name="Account" component={Account} options={navOptions} />
<AppStack.Screen name="Products" component={Products} options={navOptions} />
<AppStack.Screen name="TopUp" component={TopUp} options={navOptions} />
<AppStack.Screen name="CheckOut" component={CheckOut} options={navOptions} />
<AppStack.Screen name="Tracker" component={Tracker} options={navOptions} />
<AppStack.Screen name="About" component={About} options={navOptions} />
<AppStack.Screen name="Loyalty" component={Loyalty} options={navOptions} />
<AppStack.Screen name="Contact" component={Contact} options={navOptions} />
<AppStack.Screen name="OnBoarding" component={OnBoarding} options={{ headerShown: false }} />
<AppStack.Screen name="PromoDetails" component={PromoDetails} options={navOptions} />
<AppStack.Screen name="ProductDetails" component={ProductDetails} options={navOptions} />
<AppStack.Screen name="LoyaltyCardDetails" component={LoyaltyCardDetails} options={navOptions} />
<AppStack.Screen name="MyProfile" component={MyProfile} options={navOptions} />
<AppStack.Screen name="EditProfile" component={EditProfile} options={navOptions} />
<AppStack.Screen name="TransactionDetails" component={TransactionDetails} options={navOptions} />
<AppStack.Screen name="AddAccountCard" component={AddAccountCard} options={navOptions} />
<AppStack.Screen name="ActivateCard" component={ActivateCard} options={navOptions} />
<AppStack.Screen name="AddTracker" component={AddTracker} options={navOptions} />
<AppStack.Screen name="AddFuelType" component={AddFuelType} options={navOptions} />
<AppStack.Screen name="EditTracker" component={EditTracker} options={navOptions} />
<AppStack.Screen name="TermsConditions" component={TermsConditions} options={navOptions} />
<AppStack.Screen name="LoginBirthday" component={LoginBirthday} options={navOptions} />
<AppStack.Screen name="LoginSendOTP" component={LoginSendOTP} options={navOptions} />
<AppStack.Screen name="LoginOTP" component={LoginOTP} options={navOptions} />
<AppStack.Screen name="LoginEnroll" component={LoginEnroll} options={navOptions} />
<AppStack.Screen name="ApplySelectCard" component={ApplySelectCard} options={navOptions} />
<AppStack.Screen name="ApplyCardDetails" component={ApplyCardDetails} options={navOptions} />
<AppStack.Screen name="ApplyForm" component={ApplyForm} options={navOptions} />
<AppStack.Screen name="ApplyOTP" component={ApplyOTP} options={navOptions} />
<AppStack.Screen name="StationDetails" component={StationDetails} options={navOptions}/>
<AppStack.Screen name="StationSearch" component={StationSearch} options={navOptions} />
<AppStack.Screen name="EnrollActivate" component={EnrollActivateCard} options={navOptions} />
<AppStack.Screen name="EnrollPin" component={EnrollPin} options={navOptions} />
<AppStack.Screen name="EnrollForm" component={EnrollForm} options={navOptions} />
<AppStack.Screen name="EnrollOtp" component={EnrollOtp} options={navOptions} />
<AppStack.Screen name="AccountEnrollActivate" component={AccountEnrollActivateCard} options={navOptions} />
<AppStack.Screen name="AccountEnrollPin" component={AccountEnrollPin} options={navOptions} />
<AppStack.Screen name="AccountEnrollForm" component={AccountEnrollForm} options={navOptions} />
<AppStack.Screen name="AccountEnrollOtp" component={AccountEnrollOtp} options={navOptions} />
<AppStack.Screen name="AccountBirthdate" component={AccountBirthdate} options={navOptions} />
<AppStack.Screen name="AccountSendOtp" component={AccountSendOtp} options={navOptions} />
<AppStack.Screen name="AccountOtp" component={AccountOtp} options={navOptions} />
<AppStack.Screen name="TokenizationForm" component={TokenezationForm} options={navOptions} />
<AppStack.Screen name="Payatpump" component={Payatpump} options={navOptions} />
<AppStack.Screen name="PayatpumpStationSearch" component={PayatpumpStationSearch} options={navOptions} />
<AppStack.Screen name="PayatpumpDetails" component={PayatpumpDetails} options={navOptions} />
<AppStack.Screen name="PayatpumpStationDetails" component={PayatpumpStationDetails} options={navOptions} />
<AppStack.Screen name="PayatpumpStationTransactionDetails" component={PayatpumpStationTransactionDetails} options={navOptions} />
<AppStack.Screen name="PayatpumpPointsDetailsInput" component={PayatpumpPointsDetailsInput} options={navOptions} />
<AppStack.Screen name="PayatpumpPaymentList" component={PayatpumpPaymentList} options={navOptions} />
<AppStack.Screen name="PayatpumpPaymentMethod" component={PayatpumpPaymentMethod} options={navOptions} />
<AppStack.Screen name="PayatpumpPaymentSuccess" component={PayatpumpPaymentSuccess} options={navOptions} />
<AppStack.Screen name="VerificationWebview" component={VerificationWebview} options={navOptions} />
</AppStack.Navigator>
);
};
export function compareVersions(v1, comparator, v2) {
var comparator = comparator == '=' ? '==' : comparator;
if(['==','===','<','<=','>','>=','!=','!=='].indexOf(comparator) == -1) {
throw new Error('Invalid comparator. ' + comparator);
}
var v1parts = v1.split('.'), v2parts = v2.split('.');
var maxLen = Math.max(v1parts.length, v2parts.length);
var part1, part2;
var cmp = 0;
for(var i = 0; i < maxLen && !cmp; i++) {
part1 = parseInt(v1parts[i], 10) || 0;
part2 = parseInt(v2parts[i], 10) || 0;
if(part1 < part2)
cmp = 1;
if(part1 > part2)
cmp = -1;
}
return eval('0' + comparator + cmp);
}
class App extends React.Component {
state = {
loading: true,
route: '',
appState: AppState.currentState,
theme: DefaultTheme
}
componentDidMount() {
setTimeout(() => {
this.validate()
}, 3000)
this.applyTheme()
AppState.addEventListener('change', this._handleAppStateChange)
Appearance.addChangeListener(this._onChangeTheme)
}
componentWillUnmount() {
try {
AppState.removeEventListener('change', this._handleAppStateChange)
Appearance.removeChangeListener(this._onChangeTheme)
this.unsubscribe()
} catch (error) {
}
}
_onChangeTheme = () => {
this.applyTheme()
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
this.validateAppVersion()
}
this.setState({ appState: nextAppState })
this.applyTheme()
}
fcmTokenAuthorization = async () => {
const authStatus = await firebase.messaging().requestPermission();
const enabled = authStatus === firebase.messaging.AuthorizationStatus.AUTHORIZED || authStatus === firebase.messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
try {
const token = await firebase.messaging().getToken()
if(token) {
let existingToken = await DB.get("fcmToken") || ""
if(token != existingToken){
this.applySaveFcmToken(token)
}
}
this.props.saveFcmToken(token)
} catch (error) {
console.log(error);
}
}
}
applySaveFcmToken = (token) => {
DB.set("fcmRegistration", "new", (r) => {}, (e) => {})
DB.set("fcmToken", token, () => console.log("FCM TOKEN SAVED", token), () => console.log("FCM TOKEN SAVING FAILED"))
}
applyTheme = () => {
let theme = Appearance.getColorScheme() === 'dark' ? DarkTheme : DefaultTheme
this.setState({ theme: theme })
this.props.saveAppTheme({ theme: theme })
}
validate = async () => {
const SESSION = await DB.session();
const USER_PROFILE = await DB.profile();
const enter_mpin = await DB.get('enter_mpin')
const set_mpin = await DB.get('set_mpin')
this.fcmTokenAuthorization() //check fcm token
this.validateAppVersion() //check latest
if (
!SESSION ||
SESSION.token?.length == 0 ||
!SESSION.token ||
!SESSION.user
) {
this.setState({ route: "Login" })
} else {
if(USER_PROFILE) {
if(
USER_PROFILE.data.mpin == undefined
|| USER_PROFILE.data.mpin == null
|| USER_PROFILE.data.mpin == ""
) {
this.setState({ route: "Setmpin" })
} else {
if(set_mpin == null && enter_mpin == null) {
this.setState({ route: "OnBoarding" })
} else {
if(set_mpin) {
this.setState({ route: "Setmpin" })
}
if(enter_mpin || enter_mpin == 'false') {
this.setState({ route: "Mpin" })
}
}
}
} else {
this.setState({ route: "Login" })
}
}
this.setState({ loading: false })
};
validateAppVersion = async () => {
await REQUEST("getAppVersion", "get", {}, {}, {}, (res) => {
if(res.status == 1) {
let currentVersion = DeviceInfo.getReadableVersion()
let latestVersion = res.data.version
let is_force_update = parseInt(res.data.update_action)
let isNewVersion = compareVersions(currentVersion, "<", latestVersion)
if(isNewVersion) {
var buttons = [
{
text: "Update Now",
onPress: async () => {
let isDebug = false
if(isDebug) {
let testflightBeta = "https://beta.itunes.apple.com";
if(Linking.canOpenURL(testflightBeta)) {
Linking.openURL(testflightBeta);
} else {
let testflightJoin = "https://beta.itunes.apple.com";
Linking.openURL(testflightJoin);
}
} else {
let appstore = "https://apps.apple.com/ph/app/unioil/id1517293002";
if(Linking.canOpenURL(appstore)) {
Linking.openURL(appstore);
}
}
}
}
]
if(is_force_update == 0) {
buttons.push({
text: 'No',
style: 'cancel',
})
}
if(is_force_update == 2) return
Alert.alert("Update Information", res.data.update_message, buttons)
}
}
}, (error) => {
console.log(error)
})
}
registerNotifications = () => {
this.unsubscribe = messaging().onMessage(async (remoteMessage) => {
let allnotifs = await DB.get('notifications');
console.log('All Notifications', allnotifs);
let notifs = allnotifs ? JSON.parse(allnotifs) : null;
let existence = notifs
? notifs.find((notif) => {
return notif.messageId == remoteMessage.messageId;
})
: null;
console.log('Notif Data', allnotifs, existence);
if (!existence) {
let notifObj = {
title: '',
message: '',
playSound: false,
soundName: 'default',
};
if (Platform.OS == 'ios') {
notifObj.title = remoteMessage.data.notification.title;
notifObj.message = remoteMessage.data.notification.body;
} else {
notifObj.title = remoteMessage.notification.title;
notifObj.message = remoteMessage.notification.body;
}
PushNotification.localNotification(notifObj);
let result = await DB.AddNotification({
messageId:
Platform.OS == 'ios' ? remoteMessage.from : remoteMessage.messageId,
title: notifObj.title,
body: notifObj.message,
visible: true,
delivery: true,
recieved:
Platform.OS == 'ios' ? remoteMessage.from : remoteMessage.sentTime,
});
console.log(result);
}
});
}
appStack = () => {
return <AppNavigation initialRoute={this.state.route} />;
};
render() {
if (this.state.loading) {
return <Splash />;
}
return (
<SafeAreaProvider>
<NavigationContainer theme={this.state.theme}>
<RootStack.Navigator initialRouteName="App" headerMode="none">
<RootStack.Screen
name="App"
component={this.appStack}
options={navOptions}
/>
</RootStack.Navigator>
</NavigationContainer>
</SafeAreaProvider>
);
}
}
const mapStateToProps = (state) => {
return {
app_theme: state.appThemeReducer.theme,
token: state.appUserInfoReducer.token
}
}
const mapDispatchToProps = {
saveAppTheme,
saveFcmToken
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
// export default function App(props) {
// const [loading, setloading] = useState(true);
// const [route, setroute] = useState('');
// const validate = async () => {
// const SESSION = await DB.session();
// const USER_PROFILE = await DB.profile();
// const enter_mpin = await DB.get('enter_mpin')
// const set_mpin = await DB.get('set_mpin')
// console.log(USER_PROFILE, enter_mpin, set_mpin)
// if (
// !SESSION ||
// SESSION.token?.length == 0 ||
// !SESSION.token ||
// !SESSION.user
// ) {
// await setroute('Login');
// } else {
// if(USER_PROFILE) {
// if(
// USER_PROFILE.data.mpin == undefined
// || USER_PROFILE.data.mpin == null
// || USER_PROFILE.data.mpin == ""
// ) {
// await setroute('Setmpin');
// } else {
// if(set_mpin == null && enter_mpin == null) {
// await setroute('OnBoarding')
// } else {
// if(set_mpin) {
// await setroute('Setmpin')
// }
// if(enter_mpin || enter_mpin == 'false') {
// await setroute('Mpin')
// }
// }
// }
// } else {
// await setroute('Login')
// }
// }
// await setloading(false);
// };
// const showAlert = (status) => {
// switch(status) {
// case 0:
// setTimeout(() => {
// Alert.alert("Deleted Successfully", "\nYour credit card has successfully deleted.",
// [
// {
// text: 'No',
// style: 'cancel',
// },
// {
// text: "OK",
// onPress: async () => {
// console.log("HELLO")
// }
// }
// ])
// }, 300)
// break
// case 1:
// break
// case 2:
// break
// }
// }
// const validateAppVersion = async () => {
// await REQUEST("getAppVersion", "get", {}, {}, {}, (res) => {
// if(res.status == 1) {
// let currentVersion = DeviceInfo.getReadableVersion()
// let latestVersion = res.data.version
// let is_force_update = parseInt(res.data.update_action)
// let isNewVersion = compareVersions(currentVersion, "<", latestVersion)
// if(isNewVersion) {
// showAlert(is_force_update)
// }
// }
// }, (error) => {
// console.log(error)
// })
// }
// useEffect(() => {
// let timer = setTimeout(() => {
// validate()
// }, 3000)
// return () => {
// clearTimeout(timer)
// }
// }, [])
// useEffect(() => {
// validateAppVersion()
// }, [])
// useEffect(() => {
// const unsubscribe = messaging().onMessage(async (remoteMessage) => {
// let allnotifs = await DB.get('notifications');
// console.log('All Notifications', allnotifs);
// let notifs = allnotifs ? JSON.parse(allnotifs) : null;
// let existence = notifs
// ? notifs.find((notif) => {
// return notif.messageId == remoteMessage.messageId;
// })
// : null;
// console.log('Notif Data', allnotifs, existence);
// if (!existence) {
// let notifObj = {
// title: '',
// message: '',
// playSound: false,
// soundName: 'default',
// };
// if (Platform.OS == 'ios') {
// notifObj.title = remoteMessage.data.notification.title;
// notifObj.message = remoteMessage.data.notification.body;
// } else {
// notifObj.title = remoteMessage.notification.title;
// notifObj.message = remoteMessage.notification.body;
// }
// PushNotification.localNotification(notifObj);
// let result = await DB.AddNotification({
// messageId:
// Platform.OS == 'ios' ? remoteMessage.from : remoteMessage.messageId,
// title: notifObj.title,
// body: notifObj.message,
// visible: true,
// delivery: true,
// recieved:
// Platform.OS == 'ios' ? remoteMessage.from : remoteMessage.sentTime,
// });
// console.log(result);
// }
// });
// return unsubscribe;
// }, []);
// const appStack = () => {
// return <AppNavigation initialRoute={route} />;
// };
// if (loading) {
// return <Splash />;
// }
// return (
// <SafeAreaProvider>
// <NavigationContainer>
// <RootStack.Navigator initialRouteName="App" headerMode="none">
// <RootStack.Screen
// name="App"
// component={appStack}
// options={navOptions}
// />
// </RootStack.Navigator>
// </NavigationContainer>
// </SafeAreaProvider>
// );
// }