unioil-loyalty-rn-app/app/screens/login/otp.js

478 lines
17 KiB
JavaScript

import * as React from 'react';
import { connect } from "react-redux";
import { saveUserInfo } from "../../redux/actions/AppUserInfoActions";
import { useState, useEffect } from 'react';
import { StyleSheet, SafeAreaView, ScrollView, TouchableOpacity, Button, View, Text, TextInput, KeyboardAvoidingView, Alert } from 'react-native';
import {useNetInfo} from "@react-native-community/netinfo";
// import NetInfo from "@react-native-community/netinfo";
import NetInfo from "../../components/netstatus";
import CustomHeader from '../../components/header.js';
import Assets from '../../components/assets.manager.js';
import Elements from '../../components/elements.js';
import Theme from '../../components/theme.style.js';
import DB from '../../components/storage/';
import REQUEST from '../../components/api/';
import CustomOTPInput from '../../components/otpinput';
import CustomSafeArea from '../../components/safeArea.component';
class TermsConditions extends React.PureComponent {
constructor(props) {
super(props)
}
state = {
loading: false,
infodialog: false,
errordialog: false,
otp: "",
resend: false,
retries: 0,
valid: false,
session: null,
data: {}
}
componentDidMount() {
this.init()
this.activateResend()
}
componentWillUnmount() {
}
init = async () => {
this.setState({ data: this.props.route.params, session: await DB.get("session") })
}
activateResend = () => {
setTimeout(() => {
this.setState({ resend: true })
}, 15000)
}
onErrorWarning = (success) => {
if(Platform.OS == 'ios'){
if(success.data.code == 1) {
setTimeout(() => {
Alert.alert(
'Error',
'\n'+success.message,
[
{
text: 'Ok',
onPress: async () => {
this.props.navigation.navigate('Login');
},
},
],
{cancelable: true},
);
this.setState({ resend: true })
}, 700)
} else {
setTimeout(() => {
Alert.alert("Error", success.message)
}, 700)
this.setState({ resend: true })
}
} else {
Alert.alert("Error", success.message)
this.setState({ resend: true })
}
}
onSaveSession = async (success) => {
let session = {
card_number: this.state.data.card_number,
lcard_uuid: this.state.data.lcard_uuid,
mobile_number: this.state.data.mobile_number
}
console.log(session)
await DB.settoken({token: success.data.token, card_number: session.card_number}, () => {
DB.setsession(session, (res) => {
if(this.state.data.transactionType != undefined &&
this.state.data.transactionType == "ActivateCard") {
this.setState({ loading: false })
let sessiondata = {
card_number: this.state.data.card_number,
lcard_uuid: this.state.data.lcard_uuid,
mobile_number: Theme.formatter.PMBL(this.state.data.mobile_number)
}
let data = {
sessiondata: sessiondata,
token: success.data.token,
}
this.props.navigation.navigate("Setmpin", data)
} else {
let token = `Bearer ${success.data.token}`
this.props.saveUserInfo({ token: token, card_number: success.data.userDetails.card_number }).then(data => {
if(data.status == 1) {
DB.updateProfile(data, res => {
this.setState({ loading: false })
if(
data.data.mpin == undefined ||
data.data.mpin == null ||
data.data.mpin == ""
) {
let sessiondata = {
card_number: data.data.card_number,
lcard_uuid: data.data.lcard_uuid,
mobile_number: Theme.formatter.PMBL(data.data.mobile)
}
let accountdata = {
sessiondata: sessiondata,
token: token
}
this.props.navigation.navigate("Setmpin", accountdata)
} else {
this.props.navigation.navigate("OnBoarding", { token: success.data.token })
}
}, error => {
this.setState({ loading: false })
console.log("Error saving profile", error)
})
} else {
this.setState({ loading: false })
}
})
.catch(error => {
this.setState({ loading: false })
console.log(error)
})
}
}, (error) => {
this.setState({ loading: false })
console.log(error)
})
}, (error) => {
this.setState({ loading: false })
console.log(error)
})
}
onSubmit = () => {
NetInfo.netstatus(isConnected => {
if(isConnected){
this.setState({ loading: true })
this.validateOTP(success => {
if(success.status == 1 && success.data.token){
this.onSaveSession(success)
}else{
this.setState({ loading: false })
this.onErrorWarning(success)
}
}, error => {
this.setState({ loading: false, resend: true })
})
}else{
Elements.nointernet2()
}
})
}
onRetry = async () => {
if(this.state.resend){
this.setState({ loading: true })
this.retryValidateOTP(success => {
if(success.status == 1){
this.setState({ loading: false })
Platform.OS == 'ios' ? setTimeout(() => {
Alert.alert("Requested.", "New OTP code will be submitted on your mobile number.")
}, 300) : Alert.alert("Requested.", "New OTP code will be submitted on your mobile number.")
}else{
this.setState({ loading: false })
}
}, error => {
this.setState({ loading: false })
})
}
}
validateOTP = async (successCallback, errorCallback) => {
this.setState({ loading: true, retries: this.state.retries + 1 })
await REQUEST("sendOTP", "post", {}, {}, {
otp: this.state.otp,
lcard_uuid: this.state.data.lcard_uuid
}, async (data) => {
successCallback(data)
}, function(error){
errorCallback(error)
})
}
retryValidateOTP = async (successCallback, errorCallback) => {
let params = `lcard_uuid=${this.state.data.lcard_uuid}&mobile=${Theme.formatter.PMBL(this.state.data.mobile_number)}&is_resend=false`;
await REQUEST("requestOTP", "get", {}, params, {},
function(res){
successCallback(res)
}, function(error){
errorCallback(error)
}
)
}
render() {
return (
<CustomSafeArea>
<Elements.loaderView
title="Validating"
message="Please wait..."
isDarkMode={this.props.app_theme?.theme.dark}
backgroundColor={this.props.app_theme?.theme.colors.border}
color={this.props.app_theme?.theme.colors.text}
visible={this.state.loading} />
<Elements.infodialog
title="Requested."
message="New OTP code will be submitted on your mobile number."
buttonConfirmText="OK"
shown={this.state.infodialog}
onCancel={() => this.setState({ infodialog: false })}
onSubmit={(value) => this.setState({ infodialog: false })}
/>
<Elements.infodialog
title="Error"
message="Incorrect OTP. The OTP you have entered does not exist."
buttonConfirmText="OK"
shown={this.state.errordialog}
onCancel={() => this.setState({ errordialog: false })}
onSubmit={(value) => this.setState({ errordialog: false })}
/>
<CustomHeader title="" menu={false} back={true} onBackPress={() => this.props.navigation.goBack()} navigation={this.props.navigation} />
<KeyboardAvoidingView style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text style={{padding: 15, fontSize: 22, color: this.props.app_theme?.theme.dark ? this.props.app_theme?.theme.colors.text : Theme.colors.textPrimary, fontWeight: 'bold'}}>Enter Code</Text>
<Text style={{padding: 5, fontSize: 16, color: this.props.app_theme?.theme.dark ? this.props.app_theme?.theme.colors.text : Theme.colors.textPrimary, width: '85%', textAlign: 'center'}}>Enter the 4-digit verification code sent to</Text>
<Text style={{padding: 15, paddingTop: 5, fontSize: 15, color: Theme.colors.accent, width: '85%', textAlign: 'center'}}>{Theme.formatter.ENCMBL(this.state.data.mobile_number || "+639000000000")}</Text>
<CustomOTPInput
containerStyle={{ marginBottom: 30 }}
textColor={this.props.app_theme?.theme.colors.text}
isDarkMode={this.props.app_theme?.theme.dark}
onChangeText={(v) => {
this.setState({ otp: v, valid: v.length == 4 ? true : false })
}}
/>
<TouchableOpacity disabled={!this.state.valid} onPress={() => this.onSubmit()} style={{backgroundColor: this.state.valid ? Theme.colors.primary : this.props.app_theme?.theme.dark ? this.props.app_theme?.theme.colors.border : Theme.colors.primary + "15", padding: 15, width: '80%', borderRadius: 10, elevation: this.state.valid ? 3 : 0}}>
<Text style={{textAlign: 'center', color: "#fff", fontSize: 16}}>Submit</Text>
</TouchableOpacity>
<View style={{flexDirection: 'row', width: '80%', padding: 30}}>
<TouchableOpacity onPress={() => this.onRetry()} style={{flex: 2}}>
<Text style={{textAlign: 'center', color: this.state.resend ? Theme.colors.primary : Theme.colors.darkGray, fontSize: 16}}>Resend Code</Text>
</TouchableOpacity>
</View>
<View style={{padding: 70}}></View>
</KeyboardAvoidingView>
</CustomSafeArea>
)
}
}
const mapStateToProps = (state) => {
return {
userinfo: state.appUserInfoReducer.userinfo,
app_theme: state.appThemeReducer.theme
}
}
const mapDispatchToProps = {
saveUserInfo
}
export default connect(mapStateToProps, mapDispatchToProps)(TermsConditions)
// export default function TermsConditions(navigation) {
// const [loading, setloading] = useState(false);
// const [infodialog, setinfodialog] = useState(false);
// const [errordialog, seterrordialog] = useState(false);
// const [otp, setotp] = useState("");
// const [resend, setresend] = useState(false);
// const [retries, setretries] = useState(0);
// const [valid, setvalid] = useState(false);
// const [session,setsession] = useState(null);
// const [data, setdata] = useState({});
// const init = async () => {
// await setdata(navigation.route.params)
// await setsession(await DB.get("session"))
// }
// const activateResend = () => {
// setTimeout(() => {
// setresend(true)
// console.log("tick")
// }, 15000)
// }
// useEffect(() => {
// init()
// activateResend()
// }, [])
// const encyptNumber = (contact) => {
// let replacement = "****"
// let index = 6
// return contact.substr(0, index) + replacement+ contact.substr(index + replacement.length)
// }
// const getRetries = () => { return retries }
// const onRetry = async () => {
// if(resend){
// setloading(true)
// let params = `lcard_uuid=${data.lcard_uuid}&mobile=${Theme.formatter.PMBL(data.mobile_number)}&is_resend=true`;
// await REQUEST("requestOTP", "get", {}, params, {},
// function(res){
// console.log(res)
// if(res.status == 1){
// setloading(false)
// // setinfodialog(true)
// Platform.OS == 'ios' ? setTimeout(() => {
// Alert.alert("Requested.", "New OTP code will be submitted on your mobile number.")
// }, 300) : Alert.alert("Requested.", "New OTP code will be submitted on your mobile number.")
// }else{
// setloading(false)
// console.log(res.data)
// }
// console.log("RESPONSE: " , res)
// }, function(error){
// setloading(false)
// console.log(error)
// })
// }
// }
// const onSubmit = async () => {
// setloading(true)
// setretries(retries + 1)
// await REQUEST("sendOTP", "post", {}, {}, {
// otp: otp,
// lcard_uuid: data.lcard_uuid
// }, async (data) => {
// console.log(data)
// if(data.status == 1 && data.data.token){
// setloading(false)
// DB.settoken(data.data.token, function(){
// console.log("TOKEN SAVED!")
// navigation.navigation.navigate("OnBoarding")
// }, function(e){
// console.log("DEVICE INFO SAVING FAILED!", e)
// })
// }else{
// setloading(false)
// if(Platform.OS == 'ios'){
// setTimeout(() => {
// Alert.alert("Error", '\n' + data.message)
// setresend(true)
// }, 700)
// }else{
// Alert.alert("Error", data.message)
// setresend(true)
// }
// }
// console.log("RESPONSE: " , data)
// }, function(error){
// setloading(false)
// setresend(true)
// console.log(error)
// })
// // if(OTP == otp){
// // navigation.navigation.navigate("OnBoarding")
// // }else{
// // seterrordialog(true)
// // }
// console.log(retries, resend)
// }
// return (
// <SafeAreaView style={{flex: 1}}>
// <Elements.loader visible={loading} />
// <Elements.infodialog
// title="Requested."
// message="New OTP code will be submitted on your mobile number."
// buttonConfirmText="OK"
// shown={infodialog}
// onCancel={() => setinfodialog(false)}
// onSubmit={(value) => setinfodialog(false)}
// />
// <Elements.infodialog
// title="Error"
// message="Incorrect OTP. The OTP you have entered does not exist."
// buttonConfirmText="OK"
// shown={errordialog}
// onCancel={() => seterrordialog(false)}
// onSubmit={(value) => seterrordialog(false)}
// />
// <CustomHeader title="" menu={false} back={true} backscreen="Login" navigation={navigation} />
// <KeyboardAvoidingView style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
// <Text style={{padding: 15, fontSize: 22, color: Theme.colors.textPrimary, fontWeight: 'bold'}}>Enter Code</Text>
// <Text style={{padding: 5, fontSize: 16, color: Theme.colors.textPrimary, width: '85%', textAlign: 'center'}}>Enter the 4-digit verification code sent to</Text>
// <Text style={{padding: 15, paddingTop: 5, fontSize: 15, color: Theme.colors.accent, width: '85%', textAlign: 'center'}}>{Theme.formatter.ENCMBL(data.mobile_number || "+639000000000")}</Text>
// {/* <CustomOTPInput
// onChangeText={(v) => setvalid(false)}
// onDone={async (val) => {
// await setotp(val)
// await setvalid(val.length == 4 ? true : false)
// }}
// /> */}
// <CustomOTPInput
// onChangeText={(v) => {
// setotp(v)
// setvalid(v.length == 4 ? true : false)
// }}
// />
// <TouchableOpacity onPress={() => {
// NetInfo.fetch().then(state => {
// console.log("Connection type", state.type);
// console.log("Is connected?", state.isConnected);
// if(state.isConnected){
// onSubmit()
// }else{
// Elements.nointernet2()
// }
// })
// }} style={{backgroundColor: valid ? Theme.colors.primary : Theme.colors.primary + "15", padding: 15, width: '80%', borderRadius: 10, elevation: valid ? 3 : 0}}>
// <Text style={{textAlign: 'center', color: "#fff", fontSize: 16}}>Submit</Text>
// </TouchableOpacity>
// <View style={{flexDirection: 'row', width: '80%', padding: 30}}>
// <TouchableOpacity activeOpacity={1} onPress={onRetry} style={{flex: 2}}>
// <Text style={{textAlign: 'center', color: resend ? Theme.colors.primary : Theme.colors.darkGray, fontSize: 16}}>Resend Code</Text>
// </TouchableOpacity>
// </View>
// <View style={{flexDirection: 'row', width: '80%', padding: 15, paddingTop: 5}}>
// <Text style={{textAlign: 'center', color: Theme.colors.darkGray, fontSize: 16}}>Your account will be locked for 24 hours after 3 attempts of entering the wrong OTP</Text>
// </View>
// <View style={{padding: 70}}></View>
// </KeyboardAvoidingView>
// </SafeAreaView>
// );
// }
const styles = StyleSheet.create({
input: {
flex: 1, padding: 0, margin: 5, fontSize: 18, textAlign: 'center', borderBottomColor: Theme.colors.accent, borderBottomWidth: 1.5, color: Theme.colors.black
}
});