Skip to content

Instantly share code, notes, and snippets.

@romreed
Created June 11, 2020 17:29
Show Gist options
  • Save romreed/4bcb325ba0c87a9216e445d565b5d97e to your computer and use it in GitHub Desktop.
Save romreed/4bcb325ba0c87a9216e445d565b5d97e to your computer and use it in GitHub Desktop.
import {bindActionCreators, Dispatch} from "redux";
import {
addCar,
clearParkingCondition,
getParkingCondition,
ParkingItemType,
setCurrentCar,
UserProfileType
} from "../../actions/parking";
import {connect} from "react-redux";
import {RootState} from "../../reducer";
import React, {useEffect, useRef, useState} from "react";
import {Keyboard, Platform, SafeAreaView, ScrollView, View} from "react-native";
import styles from "./style"
import Header from "../../components/Header";
import CustomModal from "../../components/CustomModal";
import ChooseCreditCard from "../../components/ChooseCreditCart";
import {createCryptogram, getIp, logEvent, transliterate, validatePrice} from "../../core/actions";
import {Provider} from "react-native-paper";
import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view";
import CustomInput from "../../components/CustomInput";
import ChooseCar from "../../components/ChooseCar";
import ChoosePeriod from "../../components/ChoosePeriod";
import CustomButton from "../../components/CustomButton";
import Indicator from "../../components/Indicator";
import LinkButton from "../../components/LinkButton";
import {
getSubscriptionPrice,
payForSubscription,
SetCurrentSumMonths,
setCurrentSumMonths,
SubscriptionPriceType
} from "../../actions/subscriptions";
import {PaySubscription} from "../../api";
import EnterCreditCart from "../../components/EnterCreditCart";
import {BankCart} from "../../actions/payment";
import {customAlert} from "../../components/Alert";
import _ from "lodash";
interface SubscriptionsChooseCarTypes {
navigation: any
currentParking: null | ParkingItemType
isFetchAddCar: boolean
addCar: (clearNumber: string) => void
setCurrentCar: ({
plate,
id
}: {
plate: string,
id: number
}) => void
getParkingCondition: (id: string) => void
addCarError: null | string
userProfile: null | UserProfileType
payForSubscription: (data: PaySubscription) => void
isFetchPayForSubscription: boolean
payForSubscriptionError: null | string
bankCarts: null | BankCart[]
getSubscriptionPrice: (id: number) => void
isFetchSubscriptionPrice: boolean
subscriptionPrice: SubscriptionPriceType | null
setCurrentSumMonths: ({sum, months}: SetCurrentSumMonths) => void
parkingCondition: null | string
isFetchParkingCondition: boolean
clearParkingCondition: () => void
currentCarNumber: null | {
id: number,
plate: string
}
}
export const SubscriptionsChooseCar = ({
navigation,
currentParking,
isFetchAddCar,
addCar,
addCarError,
userProfile,
setCurrentCar,
getParkingCondition,
payForSubscription,
isFetchPayForSubscription,
payForSubscriptionError,
bankCarts,
getSubscriptionPrice,
isFetchSubscriptionPrice,
subscriptionPrice,
setCurrentSumMonths,
isFetchParkingCondition,
parkingCondition,
clearParkingCondition,
currentCarNumber
}: SubscriptionsChooseCarTypes) => {
const modalRef = useRef<CustomModal>(null);
const modalRefPay = useRef<CustomModal>(null);
const [carNumber, setCarNumber] = useState('')
const [carId, setCarId] = useState<null | number>(null)
const [carChecked, setCarChecked] = useState(false)
const [countMonth, setCountMonth] = useState(1)
const [price, setPrice] = useState(0)
const [validCart, setValidCart] = useState(false)
const [cart, setCart] = useState<any>({})
useEffect(() => {
if (!isFetchParkingCondition && parkingCondition) {
customAlert({
title: 'Успловия тарифа',
subTitle: parkingCondition,
okText: "ОК",
okPress: () => clearParkingCondition()
})
}
}, [
parkingCondition,
isFetchParkingCondition
])
useEffect(() => {
if (countMonth && price) {
setCurrentSumMonths({
sum: countMonth * price,
months: countMonth
})
}
}, [countMonth, price])
useEffect(() => {
if (currentParking) {
getSubscriptionPrice(currentParking.id)
}
}, [currentParking])
useEffect(() => {
if (subscriptionPrice) {
setPrice(subscriptionPrice.price)
}
}, [subscriptionPrice])
useEffect(() => {
if (!isFetchPayForSubscription && !payForSubscriptionError) {
modalRefPay.current?._hideModal()
}
}, [isFetchPayForSubscription, payForSubscriptionError])
useEffect(() => {
if (!isFetchAddCar && addCarError === null) {
modalRef.current?._hideModal()
Keyboard.dismiss()
}
return () => {
};
}, [isFetchAddCar, addCarError])
useEffect(() => {
if (currentCarNumber) {
setCarNumber(currentCarNumber.plate)
setCarId(currentCarNumber.id)
} else if (userProfile?.cars && userProfile?.cars.length > 0 && carNumber.length === 0) {
const number = userProfile?.cars[userProfile.cars.length - 1].plate
const id = userProfile?.cars[userProfile.cars.length - 1].id
setCarNumber(number)
setCarId(id)
}
return () => {
};
}, [userProfile, currentCarNumber])
const setCarNumberChange = (number: string) => {
if (number.match("^[A-Za-z0-9]+$") !== null) {
setCarNumber(Platform.OS === "ios" ? number.toUpperCase() : number)
if (number && number.length > 5 && number.length <= 10) {
setCarChecked(true)
} else {
setCarChecked(false)
}
} else if (number === "") {
setCarNumber(number)
setCarChecked(false)
}
logEvent({type: "SubscriptionsChooseCar_setCarNumberChange", data: {number}})
}
const onClose = () => {
setCarNumber("")
setCarId(null)
setCarChecked(false)
Keyboard.dismiss()
logEvent({type: "SubscriptionsChooseCar_onClose", data: {}})
}
const createCarNumber = () => {
setCarNumber("")
setCarId(null)
setCarChecked(false)
modalRef.current?._showModal({title: 'Добавить автомобить'})
Keyboard.dismiss()
logEvent({type: "SubscriptionsChooseCar_createCarNumber", data: {}})
}
const chooseCar = async (car: {
plate: string,
id: number
}) => {
setCarNumber(car.plate)
setCarId(car.id)
await setCurrentCar(car)
logEvent({type: "SubscriptionsChooseCar_chooseCar", data: {car}})
}
const paySubscription = () => {
bankCarts && bankCarts?.length > 0
?
modalRefPay.current?._showModal({title: 'Выбрать карту банка'})
:
modalRefPay.current?._showModal({title: 'Добавить карту банка'})
logEvent({type: "SubscriptionsChooseCar_paySubscription", data: {}})
}
// @ts-ignore
const period = Array.apply(null, {length: 12}).map(function (value, index) {
return index + 1;
})
const saveCar = () => {
carNumber && addCar(carNumber)
logEvent({type: "SubscriptionsChooseCar_saveCar", data: {}})
}
// const makePayNewCart = async () => {
// if (carId && carNumber) {
// await setCurrentCar({plate: carNumber, id: carId})
// if (validCart && Object.keys(cart).length !== 0 && subscriptionPrice) {
// if (cart?.number !== null && carNumber && currentParking) {
// const cryptogram = await createCryptogram({
// number: cart?.values?.number,
// extDate: cart?.values?.expiry,
// cvvCode: cart?.values?.cvc,
// })
// const clientIp = await getIp()
//
// payForSubscription({
// parkingId: currentParking?.id,
// carId: carId,
// plate: carNumber,
// sum: price * countMonth,
// cryptogram,
// tariffMonthId: subscriptionPrice.id,
// clientIp: clientIp ? clientIp : "",
// cardHolderName: cart?.values?.name,
// months: countMonth
// })
// }
// }
// }
// logEvent({type: "SubscriptionsChooseCar_makePayNewCart", data: {}})
// }
const makePayNewCart = _.throttle(async() => {
if (carId && carNumber) {
await setCurrentCar({plate: carNumber, id: carId})
if (validCart && Object.keys(cart).length !== 0 && subscriptionPrice) {
if (cart?.number !== null && carNumber && currentParking) {
const cryptogram = await createCryptogram({
number: cart?.values?.number,
extDate: cart?.values?.expiry,
cvvCode: cart?.values?.cvc,
})
const clientIp = await getIp()
await payForSubscription({
parkingId: currentParking?.id,
carId: carId,
plate: carNumber,
sum: price * countMonth,
cryptogram,
tariffMonthId: subscriptionPrice.id,
clientIp: clientIp ? clientIp : "",
cardHolderName: cart?.values?.name,
months: countMonth
})
}
}
}
logEvent({type: "SubscriptionsChooseCar_makePayNewCart", data: {}})
},5000,{
leading:true,
trailing:false
})
const makePay = async (cart: BankCart) => {
if (carId && carNumber && currentParking && subscriptionPrice) {
await setCurrentCar({plate: carNumber, id: carId})
const clientIp = await getIp()
payForSubscription({
parkingId: currentParking?.id,
carId: carId,
plate: carNumber,
sum: price * countMonth, //todo: переписать для прода
tariffMonthId: subscriptionPrice.id,
clientIp: clientIp ? clientIp : "",
bankCardId: cart.id,
months: countMonth
})
}
logEvent({type: "SubscriptionsChooseCar_makePay", data: {}})
}
const choosePeriod = (count: number) => {
setCountMonth(count)
logEvent({type: "SubscriptionsChooseCar_choosePeriod", data: {}})
}
const condition = () => {
currentParking?.id && getParkingCondition(currentParking?.id.toString())
logEvent({type: "SubscriptionsChooseCar_condition", data: {}})
}
return (
<SafeAreaView style={styles.main}>
<Provider>
<Header
title={'Абонементы'}
subTitle={'Покупка нового абонемента на парковку'}
onPressLeft={() => {
navigation.goBack();
logEvent({type: "SubscriptionsChooseCar_navigation_goBack", data: {}})
}}
/>
<KeyboardAwareScrollView
contentContainerStyle={styles.main}
>
<ScrollView style={styles.main}
contentContainerStyle={styles.container}
>
<View style={styles.item}>
<CustomInput
mode={'outlined'}
label={'Парковка'}
onChangeText={() => {
}}
editable={false}
value={`${currentParking?.title}`}
/>
</View>
<ChoosePeriod
period={period}
value={countMonth}
onChoose={(count) => choosePeriod(count)}
/>
<View style={styles.item}>
{!isFetchSubscriptionPrice ?
<CustomInput
mode={'outlined'}
label={'Сумма'}
onChangeText={() => {
}}
value={(price * countMonth).toString()}
keyboardType="numeric"
icon={"rub"}
error={validatePrice(price) === null}
editable={false}
/>
:
<View style={styles.indicatorPrice}>
<Indicator isFetch={true} fullScreen={false} style={styles.indicator}/>
</View>
}
</View>
<View style={styles.itemShort}>
<LinkButton
text={'Условия тарифа'}
onPress={condition}
labelStyle={styles.condition}
/>
</View>
<View style={styles.item}>
{
userProfile?.cars && userProfile?.cars.length > 0
?
<View style={styles.chooseCarWrapper}>
<ChooseCar cars={userProfile?.cars} onChoose={chooseCar} value={carNumber}/>
</View>
:
<CustomInput
mode={'outlined'}
label={'Добавить автомобиль'}
onChangeText={() => {
}}
value={''}
placeholder={'Добавить автомобиль'}
onFocus={() => createCarNumber()}
onPressPen={() => createCarNumber()}
/>
}
</View>
<View style={styles.item}>
<CustomButton text={'Оплатить'}
uppercase={false}
onPress={paySubscription}
/>
</View>
</ScrollView>
</KeyboardAwareScrollView>
<CustomModal ref={modalRef} onClose={onClose}>
<CustomInput
mode={'outlined'}
label='Гос. номер авто'
value={carNumber}
placeholder={"Номер вводите латиницей"}
onChangeText={setCarNumberChange}
/>
<View style={styles.saveWrapperModal}>
{
!isFetchAddCar ?
<CustomButton text={'Сохранить'}
uppercase={false}
onPress={saveCar}
isActive={isFetchAddCar ? !isFetchAddCar : carChecked}
/>
:
<Indicator isFetch={isFetchAddCar} fullScreen={false} style={styles.indicator}/>
}
</View>
</CustomModal>
<CustomModal ref={modalRefPay} onClose={onClose}>
{
bankCarts && bankCarts?.length > 0
?
<ChooseCreditCard
onSavePress={makePay}
isFetch={isFetchPayForSubscription}
/>
: <EnterCreditCart
onChangeCart={(cart) => setCart(cart)}
onSavePress={makePayNewCart}
isFetch={isFetchPayForSubscription}
onValidCart={(valid: boolean) => setValidCart(valid)}
/>
}
</CustomModal>
</Provider>
</SafeAreaView>
)
}
const mapDispatchToProps = (dispatch: Dispatch) => {
return bindActionCreators({
addCar,
setCurrentCar,
getParkingCondition,
getSubscriptionPrice,
payForSubscription,
setCurrentSumMonths,
clearParkingCondition
}, dispatch)
}
export default connect((state: RootState) => {
const {parking, subscriptions, payment} = state;
return {
isFetchAddCar: parking.isFetchAddCar,
currentParking: parking.currentParking,
addCarError: parking.addCarError,
userProfile: parking.userProfile,
isFetchPayForSubscription: subscriptions.isFetchPayForSubscription,
payForSubscriptionError: subscriptions.payForSubscriptionError,
bankCarts: payment.bankCarts,
isFetchSubscriptionPrice: subscriptions.isFetchSubscriptionPrice,
subscriptionPrice: subscriptions.subscriptionPrice,
parkingCondition: parking.parkingCondition,
isFetchParkingCondition: parking.isFetchParkingCondition,
currentCarNumber: parking.currentCarNumber
};
}, mapDispatchToProps)(SubscriptionsChooseCar)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment