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

429 lines
14 KiB
JavaScript

import * as React from 'react'
import {useState, useEffect} from 'react'
import { connect } from "react-redux";
import {SafeAreaView, View, Modal, Dimensions, Image, Platform, Alert, Keyboard} from 'react-native'
import {Button, Icon} from 'native-base';
import Theme from '../../components/theme.style'
import CustomHeader from '../../components/header.js'
import Elements from '../../components/elements'
import Assets from '../../components/assets.manager'
import Form from '../../components/paymaya/form'
import DB from '../../components/storage'
import Tokenization from '../../components/paymaya/tokenization'
import REQUEST from '../../components/api/';
import * as UTILS from './utils'
class TokenizationForm extends React.Component {
constructor(props) {
super(props)
}
state = {
loading: false,
isVisibleModal: true,
keyboardHeight: 0
}
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow)
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide)
}
componentWillUnmount() {
this.keyboardDidShowListener.remove()
this.keyboardDidHideListener.remove()
}
_keyboardDidShow = (e) => {
this.setState({ keyboardHeight: e.endCoordinates.screenY - e.endCoordinates.height - 44 });
}
_keyboardDidHide = () => {
this.setState({ keyboardHeight: 0 });
}
transactionEntry = async (transactionId, amount, onSuccess, onError) => {
const SESSION = await DB.session()
REQUEST('topup_transaction_entry', 'post', {
Authorization: SESSION.token
}, {}, {
amount: amount,
paymaya_tranx_id: transactionId
}, (res) => onSuccess(res), (error) => onError(error))
}
onCreateVault = async (card) => {
this.setState({ loading: true })
let merchant = await UTILS.createMerchantDetails()
merchant.card = {card: {name: card.name, number: card.cardnumber, expMonth: card.expmonth, expYear: card.expyear, cvc: card.cvv}}
let checkout = await Tokenization.initNewCheckout(merchant, this.props.amount)
if(checkout.status == "success") {
this.transactionEntry(checkout.id, this.props.amount,
onSuccess => {
this.setState({ loading: false, isVisibleModal: false })
this.props.onGoBack();
this.props.onSuccess({
amount: this.props.amount,
transactionId: checkout.id,
data: {redirectUrl: checkout.verificationUrl, card_number: checkout.card_number, type: 'create', },
onBack: (res, msg) => alert(msg)
});
},
onError => {
setTimeout(() => {
Alert.alert("Top Up", `\n${onError.error}`)
}, 700)
})
} else if(checkout.status == "failed"){
this.setState({ loading: false, isVisibleModal: false })
if(checkout.result.parameters.length > 0) {
setTimeout(() => {
Alert.alert("Top Up", `\n${checkout.result.parameters[0]?.description}`)
}, 700)
} else {
Platform.OS == 'ios' ? setTimeout(() => {
Alert.alert("Top Up", "\nFailed to add new card.")
}, 300) : Alert.alert("Top Up", "\nFailed to add new card.")
}
} else {
this.setState({ loading: false })
this.props.onGoBack()
}
/*
* Old code for purchasing value points
*/
// let checkout = await Tokenization.initCheckOut("", "", merchant, this.props.amount)
// if(checkout.status == 'failed'){
// this.setState({ loading: false, isVisibleModal: false })
// if(checkout.result.merchant.parameters) {
// Platform.OS == 'ios' ? setTimeout(() => {
// Alert.alert("Top Up", "\nUpdate your profile first before using this feature.")
// }, 300) : Alert.alert("Top Up", "\nUpdate your profile first before using this feature.")
// } else {
// Platform.OS == 'ios' ? setTimeout(() => {
// Alert.alert("Top Up", "\nFailed to add new card.")
// }, 300) : Alert.alert("Top Up", "\nFailed to add new card.")
// }
// } else if(checkout.status == 'success') {
// this.setState({ loading: false, isVisibleModal: false })
// this.props.onGoBack();
// this.props.onSuccess({
// amount: this.props.amount,
// data: {redirectUrl: checkout.verificationUrl, card_number: checkout.card_number, type: 'create'},
// onBack: (res, msg) => alert(msg)
// });
// }
// this.setState({ loading: false })
// this.props.onGoBack()
}
onAddVault = async (card) => {
this.setState({ loading: true })
let merchant = await UTILS.createMerchantDetails()
merchant.card = {card: {name: card.name, number: card.cardnumber, expMonth: card.expmonth, expYear: card.expyear, cvc: card.cvv}}
let addedCard = await Tokenization.initNewAddCard(this.props.customerId, merchant)
if(addedCard.status == 'failed') {
this.setState({ loading: false, isVisibleModal: false })
let message = addedCard?.result?.merchant?.parameters != undefined ? addedCard?.result?.merchant?.parameters[0].description : checkout?.card != undefined ? checkout?.card.parameters[0].description : "Invalid card"
Platform.OS == 'ios' ? setTimeout(() => {
Alert.alert("Top Up", message)
}, 800) : Alert.alert("Top Up", message)
this.props.onGoBack()
} else if(addedCard.status == 'success') {
this.setState({ loading: false, isVisibleModal: false })
if(addedCard.link.code) {
console.log("CUSTOMER ID", addedCard)
this.props.onGoBack()
} else {
this.props.onSuccess({
amount: this.props.amount,
data: {redirectUrl: addedCard.link.verificationUrl, card_number: addedCard.link.maskedPan, type: 'add'},
onBack: (res, msg) => {
Platform.OS == 'ios' ? setTimeout(() => {
Alert.alert(
'Add Card',
`\nYour new credit card has successfully added to your account.`,
[
{
text: "OK",
onPress: async () => {
await this.props.onDone()
}
},
]
)
}, 700) : null
}
});
}
}
/*
* Old code for adding new card
*/
// this.setState({ loading: true })
// let ccard = {card: {name: card.name, number: card.cardnumber, expMonth: card.expmonth, expYear: card.expyear, cvc: card.cvv}}
// let checkout = await Tokenization.initAdd(ccard, this.props.customerId)
// if(checkout.status == 'failed') {
// this.setState({ loading: false, isVisibleModal: false })
// let message = checkout?.result?.merchant?.parameters != undefined ? checkout?.result?.merchant?.parameters[0].description : checkout?.card != undefined ? checkout?.card.parameters[0].description : "Invalid card"
// Platform.OS == 'ios' ? setTimeout(() => {
// Alert.alert("Top Up", message)
// }, 800) : Alert.alert("Top Up", message)
// this.props.onGoBack()
// console.log("RESULT CARD", checkout)
// } else if(checkout.status == 'success') {
// this.setState({ loading: false, isVisibleModal: false })
// if(checkout.link.code) {
// console.log("CUSTOMER ID", this.props.customerId, checkout.link.code)
// this.props.onGoBack()
// } else {
// this.props.onSuccess({
// amount: this.props.amount,
// data: {redirectUrl: checkout.link.verificationUrl, card_number: checkout.link.maskedPan, type: 'add'},
// onBack: (res, msg) => {
// Platform.OS == 'ios' ? setTimeout(() => {
// Alert.alert(
// 'Add Card',
// `\nYour new credit card has successfully added to your account.`,
// [
// {
// text: "OK",
// onPress: async () => {
// await this.props.onDone()
// }
// },
// ]
// )
// }, 700) : null
// }
// });
// }
// console.log("RESULT CARD", checkout.link.maskedPan)
// }
}
handleFormSend = async (card) => {
let cards = this.props.cardlist
let filteredCard = cards.find(function(item) {
return card.cardnumber.includes(item.first6) && card.cardnumber.includes(item.last4)
})
if(filteredCard && this.props.type === 'add') {
this.setState({ loading: false, isVisibleModal: false })
Platform.OS == 'ios' ? setTimeout(() => {
Alert.alert("Error", "This card is already on your list.")
}, 800) : Alert.alert("Error", "This card is already on your list.")
return
}
if(this.props.type == "create"){
Alert.alert(
'Confirm Top Up',
`\nYour credit card will be used to pay ${parseFloat(this.props.amount).toFixed(2)} points.`,
[
{
text: "NO",
style: "cancel"
},
{
text: "YES",
onPress: () => {
this.onCreateVault(card)
}
},
]
)
} else if(this.props.type == 'add') {
this.onAddVault(card)
}
}
render() {
return (
<Modal
animationType="fade"
visible={this.state.isVisibleModal}
onRequestClose={() => this.props.onGoBack()}
transparent={true}
presentationStyle="overFullScreen"
style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.9)'}}>
<View style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.5)', justifyContent: 'center', alignItems: 'center'}}>
<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} />
<View style={{width: '90%', marginBottom: this.state.keyboardHeight }}>
<Button activeOpacity={1} iconRight style={{backgroundColor: this.props.app_theme?.theme.dark ? this.props.app_theme?.theme.colors.border : Theme.colors.white, flexDirection: 'row-reverse', padding: 10}} onPress={() => this.props.onGoBack()}>
<Image source={Assets.icons.stpcloseform} style={{width: 25, height: 25}} />
</Button>
<Form onSend={(card) => this.handleFormSend(card)} />
</View>
</View>
</Modal>
)
}
}
const mapStateToProps = (state) => {
return {
app_theme: state.appThemeReducer.theme
}
}
export default connect(mapStateToProps, null)(TokenizationForm)
// export default function TokenizerForm(props){
// let {
// isVisible,
// onGoBack,
// amount,
// onSuccess,
// } = props;
// const [loading, setloading] = useState(false)
// const onCreateVault = async (card) => {
// setloading(true)
// let merchant = await UTILS.createMerchantDetails()
// merchant.card = {card: {name: card.name, number: card.credit_card, expMonth: card.expmonth, expYear: card.expyear, cvc: card.cvv}}
// console.log(merchant)
// let checkout = await Tokenization.initCheckOut("", "", merchant, amount)
// if(checkout.status == 'failed'){
// if(checkout.result.merchant.parameters){
// Platform.OS == 'ios' ? setTimeout(() => {
// Alert.alert("Top Up", "\nUpdate your profile first before using this feature.")
// }, 300) : Alert.alert("Top Up", "\nUpdate your profile first before using this feature.")
// }
// // alert(JSON.stringify(checkout.result, null, '\t'))
// console.log("RESULT CARD", checkout.result.card)
// console.log("RESULT MERCHANT", checkout.result.merchant)
// setloading(false)
// }else if(checkout.status == 'success'){
// console.log("RESULT", checkout)
// setloading(false)
// onGoBack();
// onSuccess({
// amount: amount,
// data: {redirectUrl: checkout.verificationUrl, card_number: checkout.card_number, type: 'create'},
// // onBack: (res, msg) => props.route.params.onReload(res, msg)
// onBack: (res, msg) => alert(msg)
// });
// }
// setloading(false)
// props.onGoBack()
// // let client = {}
// // client.card = {
// // card: {
// // number: card.card_number,
// // expMonth: card.expmonth,
// // expYear: card.expyear,
// // cvc: card.cvv
// // }
// // }
// }
// const onAddVault = async (card) => {
// setloading(true)
// let ccard = {card: {name: card.name, number: card.credit_card, expMonth: card.expmonth, expYear: card.expyear, cvc: card.cvv}}
// let checkout = await Tokenization.initAdd(ccard, props.customerId)
// if(checkout.status == 'failed'){
// setTimeout(() => {
// alert(JSON.stringify(checkout, null, '\t'))
// }, 700)
// console.log("RESULT CARD", checkout)
// setloading(false)
// }else if(checkout.status == 'success'){
// console.log("RESULT", checkout.link.maskedPan)
// console.log("CUST ID", props.customerId)
// if(checkout.link.code){
// console.log(props.customerId)
// }else{
// onSuccess({
// amount: amount,
// data: {redirectUrl: checkout.link.verificationUrl, card_number: checkout.link.maskedPan, type: 'add'},
// // onBack: (res, msg) => props.route.params.onReload(res, msg)
// onBack: (res, msg) => {
// Platform.OS == 'ios' ? setTimeout(() => {
// Alert.alert(
// 'Add Card',
// `\nYour new credit card has successfully added to your account.`,
// [
// {
// text: "OK",
// onPress: async () => {
// await props.onDone()
// }
// },
// ]
// )
// }, 700) :
// null
// }
// });
// }
// }
// setloading(false)
// props.onGoBack()
// }
// const handleJustu = async (card) => {
// if(props.type == "create"){
// Platform.OS == 'ios' ? setTimeout(() => {
// Alert.alert(
// 'Confirm Top Up',
// `\nYour credit card will be used to pay ${parseFloat(props.amount).toFixed(2)} points.`,
// [
// {
// text: "NO",
// style: "cancel"
// },
// {
// text: "YES",
// onPress: () => {
// onCreateVault(card)
// }
// },
// ]
// )
// }, 700) :
// null
// }else if(props.type == 'add'){
// onAddVault(card)
// }
// }
// return (
// <Modal
// animationType="fade"
// visible={isVisible}
// onRequestClose={onGoBack}
// transparent={true}
// presentationStyle="overFullScreen"
// style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.9)'}}>
// <View style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.5)', justifyContent: 'center', alignItems: 'center'}}>
// <Elements.loader visible={loading} />
// <View style={{width: '90%'}}>
// <Button activeOpacity={1} iconRight style={{backgroundColor: 'white', flexDirection: 'row-reverse', padding: 10}} onPress={onGoBack}>
// {/* <Icon name='close' style={{color: 'black'}} /> */}
// <Image source={Assets.icons.stpcloseform} style={{width: 25, height: 25}} />
// </Button>
// <Form onSend={handleJustu} />
// </View>
// </View>
// </Modal>
// )
// }