unioil-loyalty-rn-app/app/screens/apply/form.js

394 lines
17 KiB
JavaScript

import * as React from 'react';
import {
ScrollView,
TouchableOpacity,
View,
Text,
TextInput,
Alert,
Platform,
KeyboardAvoidingView
} from 'react-native';
import { connect } from "react-redux";
import { checkPhoneNumberInput } from '../../utils/number.js';
import CustomHeader from '../../components/header.js';
import Elements from '../../components/elements.js';
import Theme from '../../components/theme.style.js';
import Icon from '../../components/icons.js';
import moment from 'moment';
import DB from '../../components/storage/';
import REQUEST from '../../components/api/';
import MobileValidation from '../../components/api/mobile.js';
import CustomSafeArea from '../../components/safeArea.component.js';
import { dateFormaterForAndroid } from '../../utils/date.js';
const CustomInput = (props) => {
const titlecolor = props.current == props.index && props.focus ? Theme.colors.accent : Theme.colors.darkGray
const bordercolor = props.error ? Theme.colors.primary : (props.focus && props.current == 1 ? Theme.colors.accent : 'gray')
const borderwidth = props.error ? 1.6 : (props.focus && props.current == props.index ? 1.5 : 1)
const style = {
container: {flexDirection: 'row', width: '80%', marginTop: props.top || 30, alignItems: 'center'},
title: {fontSize: 12, color: titlecolor, marginTop: -25, marginBottom: 15},
input: {width: '100%', fontSize: 16, padding: 0, borderBottomColor: bordercolor, borderBottomWidth: borderwidth, color: props.isDarkMode ? props.textColor : Theme.colors.black},
error: {fontSize: 12, color: Theme.colors.primary, marginTop: 5, marginBottom: 15}
}
return (
<View style={style.container}>
<View style={{flex: 1}}>
{props.current >= props.index ?
<Text style={style.title}>
{props.title}
</Text> : null}
<TextInput
keyboardType={props.keyboardType || null}
maxLength={props.maxlength || null}
placeholder={props.placeholder || props.title || null}
placeholderTextColor={props.isDarkMode ? Theme.colors.darkGray : Theme.colors.gray}
value={props.value || null}
onFocus={props.onFocus || null}
onChange={props.onChange || null}
onChangeText={props.onChangeText || null}
style={style.input}
/>
{props.error ? <Text style={style.error}>{props.errorMessage}</Text> : null }
</View>
</View>)
}
class ApplyForm extends React.PureComponent {
constructor(props) {
super(props)
this.cardnumber = ""
}
state = {
loading: false,
card: null,
datepicker: false,
focus: false,
activeInput: null,
agree: false,
errors: null,
processed: false,
fname: null,
lname: null,
email: null,
birthdate: "",
number: null,
valid: false,
validEmail: true,
validPhone: true,
}
componentDidMount() {
this.setState({ card: this.props.route?.params || {} })
}
componentWillUnmount() {
}
setCardNumber = () => {
this.setState({ valid: this.cardnumber.length == 15 ? true : false })
}
onAgree = () => {
this.setState({ agree: this.state.agree == false ? true : false, valid: !this.state.agree })
}
validateEmail = () => {
let regEx = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
return regEx.test(this.state.email)
}
validateNumber = () => {
return this.state.number != null ? this.state.number.length > 11 : false
}
validatemobile = async () => {
let num = this.state.number.substr(1, this.state.number.length-1)
let validation = await MobileValidation(num)
if(validation.status == 0){
Alert.alert("Information", '\n' + validation.message);
this.setState({ errors:{mobile: [validation.message]}, loading: false })
} else {
this.activateCard(success => {
this.processActivatedCard(success)
}, err => {
Alert.alert("Information", `\n${err.message}`);
})
}
}
activateCard = async (successCallback, errorCallback) => {
this.setState({ loading: true })
let uuid = await DB.get("deviceUUID")
let body = {
birthdate: Theme.formatter.DT4API(this.state.birthdate || ""),
cardtype_uuid: this.state.card.card_uuid,
deviceUUID: uuid,
email: this.state.email,
firstname: this.state.fname,
pin: this.state.card.pin,
card_number: this.state.card.card_number,
lastname: this.state.lname,
mobile: Theme.formatter.PMBL(this.state.number.substr(1, this.state.number.length-1) || "")
}
await REQUEST("activateCard", "post", {}, {}, body, async (res) => {
successCallback(res)
}, function(error){
errorCallback(error)
}, "Card", "Activate")
}
stripString = (regex, regexReplace ,string, replaceString) => {
let validMobileNumber = regex.test(string);
if(!validMobileNumber) {
return null
}
return string.replace(regexReplace, replaceString)
}
processActivatedCard = (success) => {
if(success.status == 1){
this.setState({ errors: null, processed: true, loading: false })
this.props.navigation.navigate("LoginSendOTP", {
lcard_uuid: success.data.lcard_uuid,
mobile_number: this.state.number.substr(1, this.state.number.length-1),
card_number: this.state.card.card_number,
transactionType: this.props.route.params?.transactionType
})
} else if(success.status == 0 && Object.keys(success.data).length == 0) {
this.setState({ errors: null, loading: false })
}else{
this.setState({ errors: success.data, loading: false })
}
}
onSubmit = () => {
this.setState({ loading: true });
const bday = Theme.platform === "android" ? dateFormaterForAndroid(this.state.birthdate) : this.state.birthdate;
if(this.state.valid){
let errs = {}
let bdayElapsed = moment(bday).fromNow(true).split(" ");
if(!this.state.fname) errs = Object.assign({"firstname": ["The firstname field is required."]}, errs)
if(!this.state.lname) errs = Object.assign({"lastname": ["The lastname field is required."]}, errs)
if(!this.state.birthdate) errs = Object.assign({"birthdate": ["The birthdate field is required."]}, errs)
if(bdayElapsed[1] != 'years' || bdayElapsed[1] == 'years' && bdayElapsed[0] < 18) errs = Object.assign({"birthdate": ["You must be at least 18 years old to join the Loyalty Program"]}, errs)
if(!this.state.number) errs = Object.assign({"mobile": ["The mobile field is required."]}, errs)
if(!this.state.email) errs = Object.assign({"email": ["The email field is required."]}, errs)
if(this.state.number.length < 13) errs = Object.assign({"mobile": ["Please enter your 10-digit Mobile Phone Number"]}, errs)
if(!this.validateEmail()) errs = Object.assign({"email": ["The email address is invalid"]}, errs)
this.setState({ errors: errs })
if(Object.keys(errs).length > 0) {
this.setState({ loading: false });
return false
} else {
this.validatemobile()
}
}
}
onChangeTextValueFirstname = (text) => {
if (/^[a-zA-Z ]+$/.test(text) || text === "") {
this.setState({ fname: text })
}
}
onChangeTextValueLastname = (text) => {
if (/^[a-zA-Z ]+$/.test(text) || text === "") {
this.setState({ lname: text })
}
}
notEmpty = () => {
const { fname, lname, email, birthdate, number } = this.state;
if(fname && lname && email && birthdate && number) return true;
return false;
}
showContent = () => {
return (
<ScrollView>
<View style={{flex: 1}}>
<View style={{flex: 1, alignItems: 'center'}}>
<Text style={{alignSelf: 'center', fontFamily: 'Arial', fontWeight: 'bold', fontSize: 25, padding: 15, marginTop: 25, color: this.props.app_theme?.theme. dark ? this.props.app_theme?.theme.colors.text : Theme.colors.textPrimary}}>Enter Your Details</Text>
<Text style={{alignSelf: 'center', textAlign: 'center', width: '90%', marginTop: 0, padding: 15, color: this.props.app_theme?.theme.dark ? this.props.app_theme?.theme.colors.text : Theme.colors.textPrimary, fontFamily: 'Arial', fontSize: 16}}>
Fill out the remaining forms and you're good to go!
</Text>
<CustomInput
title="First Name"
value={this.state.fname}
index={1}
current={this.state.activeInput}
keyboardType={'ascii-capable'}
textColor={this.props.app_theme?.theme.colors.text}
isDarkMode={this.props.app_theme?.theme.dark}
focus={this.state.focus}
error={this.state.errors && this.state.errors.firstname ? this.state.errors.firstname : false}
errorMessage={this.state.errors && this.state.errors.firstname ? this.state.errors.firstname[0] : ""}
onFocus={() => {
this.setState({ activeInput: 1, focus: true })
}}
onChangeText={this.onChangeTextValueFirstname}
/>
<CustomInput
top={50}
title="Last Name"
keyboardType={'ascii-capable'}
value={this.state.lname}
index={2}
current={this.state.activeInput}
textColor={this.props.app_theme?.theme.colors.text}
isDarkMode={this.props.app_theme?.theme.dark}
focus={this.state.focus}
error={this.state.errors && this.state.errors.lastname ? this.state.errors.lastname : false}
errorMessage={this.state.errors && this.state.errors.lastname ? this.state.errors.lastname[0] : ""}
onFocus={() => {
this.setState({ activeInput: 2, focus: true })
}}
onChangeText={this.onChangeTextValueLastname}
/>
<CustomInput
top={50}
title="Email Address"
value={this.state.email}
index={3}
current={this.state.activeInput}
keyboardType={'ascii-capable'}
textColor={this.props.app_theme?.theme.colors.text}
isDarkMode={this.props.app_theme?.theme.dark}
focus={this.state.focus}
error={this.state.errors && this.state.errors.email ? this.state.errors.email : false}
errorMessage={this.state.errors && this.state.errors.email ? this.state.errors.email[0] : ""}
onFocus={() => {
this.setState({ activeInput: 3, focus: true })
}}
onChangeText={(val) => {
this.setState({ email: val })
}}
/>
<View style={{flexDirection: 'row', width: '80%', marginTop: 35, alignItems: 'center'}}>
<View style={{flex: 1}}>
{this.state.activeInput >= 4 ? <Text style={{fontSize: 12, color: this.state.activeInput == 4 && this.state.focus ? Theme.colors.accent : Theme.colors.darkGray, marginTop: -25, marginBottom: 15}}>Birthday</Text> : null}
<TouchableOpacity
onPress={() => {
this.setState({ datepicker: true, activeInput: 4 })
}}
style={{}}>
<View style={{paddingTop: 15, paddingBottom: 5,borderColor: this.state.errors && this.state.errors.birthdate ? Theme.colors.primary : 'gray', borderBottomWidth: this.state.errors && this.state.errors.birthdate ? 1.5 : 1}}>
<Text style={{fontSize: 17, fontFamily: 'Arial', color: (this.state.birthdate && this.props.app_theme?.theme.dark) ? this.props.app_theme?.theme.colors.text : this.state.birthdate ? Theme.colors.textPrimary : Theme.colors.darkGray}}>{this.state.birthdate || "Birthday"}</Text>
</View>
</TouchableOpacity>
{this.state.errors && this.state.errors.birthdate ?
<Text style={{fontSize: 12, color: Theme.colors.primary, marginTop: 5, marginBottom: 15, width: '90%'}}>
{this.state.errors?.birthdate[0]}
</Text> : null}
</View>
</View>
<CustomInput
top={50}
index={5}
current={this.state.activeInput}
focus={this.state.focus}
title="Mobile Number"
value={this.state.number && this.state.number.length <= 2 ? '+63' : this.state.number}
keyboardType="numeric"
textColor={this.props.app_theme?.theme.colors.text}
isDarkMode={this.props.app_theme?.theme.dark}
maxlength={13}
error={this.state.errors && this.state.errors.mobile ? this.state.errors.mobile : false}
errorMessage={this.state.errors && this.state.errors.mobile ? this.state.errors.mobile[0] : ""}
onFocus={() => {
this.setState({ activeInput: 5, focus: true, errors: null })
if(this.state.number == null) this.setState({ number: "+63" })
}}
onChangeText={(val) => {
if(!val.startsWith("+63")) {
return this.setState({ number: "+63" })
}
this.setState({ number: val, errors: null });
if(this.state.agree){
if(val.length < 13) this.setState({ agree: false })
else if(val.length == 13 && this.notEmpty()) this.setState({ agree: true })
}
}}
/>
<View style={{flexDirection: 'row', width: '80%', marginTop: 15, alignItems: 'center'}}>
<TouchableOpacity disabled={!this.notEmpty()} onPress={() => this.state.fname && this.state.lname && this.state.birthdate && this.state.email && this.state.number ? this.onAgree() : null} style={{flex: 0, paddingTop: 15}}>
{!this.state.agree ? <Icon.Feather color={this.props.app_theme?.theme.colors.text} name="square" size={20} /> : <Icon.AntDesign name="checksquare" color={Theme.colors.accent} size={20} />}
</TouchableOpacity>
<View style={{flex: 1, paddingTop: 10, paddingHorizontal: 10}}>
<View style={{flexDirection: 'row', paddingTop: 5, alignItems: 'center'}}>
<Text style={{ color: this.props.app_theme?.theme.dark ? this.props.app_theme?.theme.colors.text : Theme.colors.textPrimary}}>I agree to </Text>
<TouchableOpacity style={{ paddingVertical: 10 }} onPress={() => this.props.navigation.navigate("TermsConditions", {screen: 'back'})}>
<Text style={{color: Theme.colors.primary}}>Unioil's Data Privacy Policy.</Text>
</TouchableOpacity>
</View>
</View>
</View>
<View style={{alignItems: 'center', justifyContent: 'flex-end', padding: 20, marginTop: 20}}>
<TouchableOpacity onPress={() => this.onSubmit()} disabled={!this.notEmpty() || !this.state.agree} style={{padding: 20, paddingTop: 15, width: Theme.screen.w - 60, paddingBottom: 15, borderRadius: 10, backgroundColor: this.notEmpty() && this.state.agree ? Theme.colors.primary : this.props.app_theme?.theme.dark ? this.props.app_theme?.theme.colors.border : Theme.colors.primary + "15"}}>
<Text style={{fontSize: 16, fontFamily: 'Arial', textAlign: 'center', color: '#fff'}}>Submit</Text>
</TouchableOpacity>
</View>
</View>
</View>
</ScrollView>
)
}
render() {
return (
<CustomSafeArea>
<Elements.loader visible={this.state.loading} />
<Elements.CustomDatePicker
visible={this.state.datepicker}
date={this.state.birthdate && new Date(this.state.birthdate)}
textColor={this.props.app_theme?.theme.colors.text}
isDarkMode={this.props.app_theme?.theme.dark}
modalBackgroundColor={this.props.app_theme?.theme.colors.border}
onConfirm={(selectedDate) => {
this.setState({ birthdate: selectedDate ? moment(selectedDate).format("MMMM DD, YYYY") : birthdate != null ? birthdate : null, datepicker: false, agree: false, valid: false })
}}
onCancel={() => this.setState({ datepicker: false })}
/>
<CustomHeader title="" menu={false} back={true} onBackPress={() => this.props.navigation.goBack()} navigation={this.props.navigation} />
{ Theme.platform === "android" ?
this.showContent()
:
<KeyboardAvoidingView
style={{flex: 1}}
behavior="padding"
keyboardVerticalOffset={Theme.platform === 'ios' ? 50 : 70}
>
{this.showContent()}
</KeyboardAvoidingView>}
</CustomSafeArea>
);
}
}
const mapStateToProps = (state) => {
return {
app_theme: state.appThemeReducer.theme
}
}
export default connect(mapStateToProps, null)(ApplyForm);