/** * Project iLinkWorld * File InsuranceSubscriptionScreen * Path screens/wallet/user * Created by BRICE ZELE * Date: 18/10/2021 */ import React, {useEffect, useState} from 'react'; import { Alert, Dimensions, FlatList, Image, Keyboard, KeyboardAvoidingView, Platform, ScrollView, StyleSheet, TouchableOpacity, View, } from 'react-native'; import {connect, useDispatch} from 'react-redux'; import Modal from 'react-native-modal'; import {Formik} from 'formik'; import * as Yup from 'yup'; import * as Utils from '../../../utils/UtilsFunction'; import {Color} from "../../../config/Color"; import I18n from 'react-native-i18n'; import {ScreenComponent} from "../../../components/ScreenComponent"; import TextInput from '../../../components/TextInput'; import Text from '../../../components/Text'; import PasswordInput from '../../../components/PasswordInput'; import Button from "../../../components/Button"; import FontAwesome from "react-native-vector-icons/FontAwesome"; import {responsiveWidth} from "react-native-responsive-dimensions"; import SwitchSelector from "react-native-switch-selector"; import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons"; import { fetchAddBeneficiaryToSubscription, fetchAddBeneficiaryToSubscriptionReset, fetchGetInsurancePrimeAmount, fetchGetListInsurance, fetchGetListInsuranceReset, fetchGetSubscriptionList, fetchGetSubscriptionListReset, fetchSubscribeInsurance, fetchSubscribeInsuranceReset, fetchUploadInsurance, fetchUploadInsuranceReset } from "../../../redux/insurance/insurance.actions"; import DropdownAlert from "react-native-dropdownalert"; import {readUser} from "../../../webservice/AuthApi"; import ImagePicker from "react-native-image-crop-picker"; import DateTimePicker from "@react-native-community/datetimepicker"; import * as Animatable from 'react-native-animatable'; import {createStructuredSelector} from "reselect"; import { selectAddBeneficiaryToSubscription, selectInsuranceList, selectInsurancePrimeAmount, selectSubscribeInsurance, selectSubscriptionList, selectUploadInsuranceImages } from "../../../redux/insurance/insurance.selector"; import {Dropdown} from "react-native-material-dropdown-v2"; import Icon from "react-native-vector-icons/FontAwesome5"; import {store} from "../../../redux/store"; let moment = require('moment-timezone'); const {width, height} = Dimensions.get('window'); const CIRCLE_SIZE = width * 0.5; const styles = StyleSheet.create({ textInput: { height: 46, backgroundColor: Color.fieldColor, borderRadius: 5, marginTop: 10, padding: 10, width: '100%', }, lineRow: { flexDirection: 'row', justifyContent: 'space-between', paddingBottom: 20, }, contain: { alignItems: 'center', marginTop: 40, paddingBottom: 20, paddingLeft: 20, paddingRight: 20, flex: 1, }, circle: { width: CIRCLE_SIZE, height: CIRCLE_SIZE, borderRadius: CIRCLE_SIZE / 2, position: 'absolute', top: '15%', }, circleContainer: { alignItems: 'flex-end', right: -(CIRCLE_SIZE / 3), top: -(CIRCLE_SIZE / 1.5), }, lineSeparator: { borderWidth: 1, width: '40%', height: 1, alignSelf: 'center', }, line: { width: 1, height: 14, backgroundColor: Color.grayColor, marginLeft: 10, }, contentModeView: { width: 30, height: '100%', alignItems: 'flex-end', justifyContent: 'center', }, contentFilter: { flexDirection: 'row', alignItems: 'center', marginLeft: 10, }, bottomModal: { justifyContent: 'flex-end', margin: 0, }, contentFilterBottom: { width: "100%", borderTopLeftRadius: 8, borderTopRightRadius: 8, paddingHorizontal: 20 }, contentSwipeDown: { paddingTop: 10, alignItems: 'center', }, lineSwipeDown: { width: 30, height: 2.5, backgroundColor: Color.dividerColor, }, contentActionModalBottom: { flexDirection: 'row', paddingVertical: 15, justifyContent: 'space-between', borderBottomWidth: 1, }, containModal: { paddingVertical: 10, paddingHorizontal: 20, flexDirection: 'row', justifyContent: 'space-between', }, floatingButtonAdd: { backgroundColor: Color.accentColor, position: "absolute", width: 25, bottom: 0, zIndex: 1000, right: 20, top: 35, height: 25, borderRadius: 12.5, alignItems: 'center', justifyContent: 'center', }, contentSwitch: { width: responsiveWidth(40), }, switch: {}, choosePhotoBtn: { marginTop: 10, marginBottom: 10, width: "auto", height: "auto", padding: 5, alignItems: 'center', borderColor: Color.borderColor, marginRight: 10, elevation: 2, }, checkbox: { alignSelf: "center", color: "white" }, itemAmountPerMonth: { paddingLeft: 10, marginTop: 10, flexDirection: 'row', }, dot: { width: 12, height: 12, borderRadius: 6 }, blockView: { paddingVertical: 10, borderBottomWidth: 0.5, }, }); const AddBeneficiaryScreen = ({ insuranceList, subscribeInsurance, insurancePrimeAmount, fetchSubscribeInsurance, fetchGetListInsurance, fetchGetInsurancePrimeAmount, fetchUploadInsurance, uploadInsuranceImages, fetchAddBeneficiaryToSubscription, addBeneficiaryToSubscription, fetchGetSubscriptionList, subscriptionList, navigation }) => { const [modalVisible, setModalVisible] = useState(false); const [isDropdownOpen, setIsDropdownOpen] = useState(false); const [user, setUser] = useState(null); const [insurance, setInsurance] = useState(null); const [amountPerMonth, setAmountPerMonth] = useState(null); useEffect(() => { console.log("amountPerMonth", amountPerMonth); }); const [firstNameBeneficiary, setFirstNameBeneficiary] = useState(null); const [lastNameBeneficiary, setLastNameBeneficiary] = useState(null); const [password, setPassword] = useState(null); let fileToSendTemp = new FormData(); let [fileToSend, setFileToSend] = useState(null); let [fileAdded, setFileAdded] = useState([]); const dispatch = useDispatch(); let dropDownAlertRef: any = null; const [insurances, setInsurances] = useState([]); const [validationOption, setValidationOption] = useState([ {label: I18n.t('YES'), value: 0}, {label: I18n.t('NO'), value: 1}, ]); const [sexeOption] = useState([ {label: I18n.t('MASCULIN'), value: "M"}, {label: I18n.t('FEMININ'), value: "F"}, ]); const [dateNaissance, setDateNaissance] = useState('' + moment(new Date(((new Date()).getFullYear() - 5), 0, 1)).format('YYYY-MM-DD')); const [showDateNaissancePicker, setShowDateNaissancePicker] = useState(false); const [showModalDetail, setShowModalDetail] = useState(false); const [modalViewBeneficiariesVisible, setModalViewBeneficiariesVisible] = useState(false); const [gender, setGender] = useState('M'); const [affiliations] = useState([ {label: I18n.t('ENFANT'), value: "CHILD"}, {label: I18n.t('CONJOINT'), value: 'SPOUSE'}, ]); const [affiliation, setAffliliation] = useState('CHILD'); const [subscription, setSubscription] = useState(null); const [subscriptions, setSubscriptions] = useState([]); const [wallet] = useState(store.getState().walletDetailReducer.result.response); let [currentYearMinusAgeLimit, setCurrentYearMinusAgeLimit] = useState(new Date(((new Date()).getFullYear() - 5), 0, 1)); let subscriptionRef = null; useEffect(() => { readUser().then((user) => { console.log("user", user); setUser(user) }); dispatch(fetchUploadInsuranceReset()); dispatch(fetchAddBeneficiaryToSubscriptionReset()); dispatch(fetchGetSubscriptionListReset()); }, []); useEffect(() => { if (user !== null) fetchGetSubscriptionList(user.id, 'EDITABLE', false); }, [user]); useEffect(() => { console.log('Beneficiaries', beneficiaries); }, [beneficiaries]); useEffect(() => { if (subscription !== null) console.log('Subscription', subscription); }, [subscription]); useEffect(() => { console.log("currentYearMinusAgeLimit", currentYearMinusAgeLimit); }, currentYearMinusAgeLimit); useEffect(() => { if (subscriptionList.result !== null) { let subscriptionListTemp = []; subscriptionList.result.response.map((insuranceItem, index) => { subscriptionListTemp.push(insuranceItem); }); setSubscriptions(subscriptionListTemp); } if (subscriptionList.error) { Alert.alert( I18n.t("ERROR_LABLE"), Utils.getErrorMsg(subscriptionList), [ { text: I18n.t("OK"), onPress: () => { dispatch(fetchGetListInsuranceReset()); } } ], { cancelable: false } ); /* dropDownAlertRef.alertWithType( 'error', I18n.t('ERROR_LABEL'), Utils.getErrorMsg(subscriptionList), ); dispatch(fetchGetListInsuranceReset());*/ } }, [subscriptionList]); useEffect(() => { if (addBeneficiaryToSubscription.result !== null) { Alert.alert( I18n.t("SUCCESS"), addBeneficiaryToSubscription.result.response, [ { text: I18n.t("OK"), onPress: () => { dispatch(fetchAddBeneficiaryToSubscriptionReset()); navigation.goBack(); } } ], {cancelable: false} ) } if (addBeneficiaryToSubscription.error) { Alert.alert( I18n.t("ERROR_LABLE"), Utils.getErrorMsg(addBeneficiaryToSubscription), [ { text: I18n.t("OK"), onPress: () => { dispatch(fetchSubscribeInsuranceReset()); } } ], { cancelable: false } ); /* dropDownAlertRef.alertWithType( 'error', I18n.t('ERROR_LABEL'), Utils.getErrorMsg(addBeneficiaryToSubscription), ); dispatch(fetchSubscribeInsuranceReset());*/ } }, [addBeneficiaryToSubscription]); useEffect(() => { if (uploadInsuranceImages.result !== null) { setModalVisible(false); if (subscription !== null) { if (beneficiaries.length === parseInt(subscription.max_number_of_beneficiaries)) { Alert.alert( I18n.t("ERROR_LABLE"), I18n.t('NUMBER_MAX_BENEFICIARY'), [ { text: I18n.t("OK"), onPress: () => { } } ], { cancelable: false } ); /* dropDownAlertRef.alertWithType( 'error', I18n.t('ERROR_LABEL'), I18n.t('NUMBER_MAX_BENEFICIARY'), );*/ } else { console.log("affiliation", affiliation); let beneficiariesTemp = beneficiaries; setBeneficiaries([{ lastname: lastNameBeneficiary, firstname: firstNameBeneficiary, gender: gender, birthdate: moment(dateNaissance).format('YYYY-MM-DD'), affiliation: affiliation, birthdate_proof: childAyantDroitDocument[1].checboxSelectedValue, profile_image: uploadInsuranceImages.result.response[0], birthdate_proof_doc: uploadInsuranceImages.result.response[1], justice_doc: uploadInsuranceImages.result.response.length > 1 ? uploadInsuranceImages.result.response[2] : null, marriage_certificate_doc: uploadInsuranceImages.result.response[1], id_document_type: "CNI", id_document_front: uploadInsuranceImages.result.response[2], id_document_back: uploadInsuranceImages.result.response[3], isEditable: true }, ...beneficiaries]); dropDownAlertRef.alertWithType( 'success', I18n.t('SUCCESS'), I18n.t('BENEFICIARY_SUCCESSFULLY_ADDED'), ); setModalVisible(false); } } } if (uploadInsuranceImages.error) { Alert.alert( I18n.t("ERROR_LABLE"), Utils.getErrorMsg(uploadInsuranceImages), [ { text: I18n.t("OK"), onPress: () => { dispatch(fetchUploadInsuranceReset()); } } ], { cancelable: false } ); /* dropDownAlertRef.alertWithType( 'error', I18n.t('ERROR_LABEL'), Utils.getErrorMsg(uploadInsuranceImages), ); dispatch(fetchUploadInsuranceReset());*/ } }, [uploadInsuranceImages]); const RegisterSchema = Yup.object().shape({ password: Yup.string().required(I18n.t('THIS_FIELD_IS_REQUIRED')) }); const AddBeneficiarySchema = Yup.object().shape({ lastname: Yup.string().required(I18n.t('THIS_FIELD_IS_REQUIRED')), firstname: Yup.string(), }); const createFormData = (key, photo) => { if (fileToSend !== null) fileToSendTemp = fileToSend; fileToSendTemp.append("files[]", { name: photo.path.split('/').pop(), type: photo.mime, uri: Platform.OS === "android" ? photo.path : photo.path.replace("file://", "") }); setFileAdded([key, ...fileAdded]); setFileToSend(fileToSendTemp); } const [childAyantDroitDocument, setChildAyantDroitDocument] = useState([ { label: I18n.t('PROFILE_PICTURE'), name: 'profile_image', isFrontCamera: false, file: null, hasCheckbox: false, }, { label: I18n.t('COPIE_LEGALISE_ACTE_NAISSANCE_CERTIFICAT_NAISSANCE'), name: 'birthdate_proof_doc', isFrontCamera: false, file: null, hasCheckbox: true, checkboxValue: ['CERTIFICATE', 'CERTIFIED_COPY'], checboxSelectedValue: 'CERTIFICATE', }, { label: I18n.t('DOCUMENT_JUSTICE_ENFANT_ADOPTE'), name: 'justice_doc', isFrontCamera: false, file: null, hasCheckbox: false, } ]); const [beneficiaries, setBeneficiaries] = useState([]); const [conjointAyantDroitDocument, setConjointAyantDroitDocument] = useState([ { label: I18n.t('PROFILE_PICTURE'), name: 'profile_image', isFrontCamera: false, file: null, hasCheckbox: false, }, { label: I18n.t('ACTE_MARIAGE'), name: 'marriage_certificate_doc', isFrontCamera: false, file: null, hasCheckbox: false, }, { label: I18n.t('CNI_FRONT_FACE'), name: 'id_document_front', isFrontCamera: false, file: null, hasCheckbox: false, }, { label: I18n.t('CNI_BACK_FACE'), name: 'id_document_back', isFrontCamera: false, file: null, hasCheckbox: false, } ]); const handleTakePhotoFromCamera = (name, isFrontCamera = false) => { ImagePicker.openCamera({ cropping: true, compressImageQuality: 0.7, useFrontCamera: false }).then(image => { if (affiliation === "CHILD") { let tempChildAyantDroitDocument = childAyantDroitDocument; setChildAyantDroitDocument(tempChildAyantDroitDocument.map(childAyantDroit => { if (name === childAyantDroit.name) { if (childAyantDroit.hasCheckbox) { return { label: childAyantDroit.label, name: childAyantDroit.name, isFrontCamera: childAyantDroit.isFrontCamera, file: image, hasCheckbox: childAyantDroit.hasCheckbox, checkboxValue: childAyantDroit.checkboxValue, checboxSelectedValue: childAyantDroit.checboxSelectedValue, }; } else { return { label: childAyantDroit.label, name: childAyantDroit.name, isFrontCamera: childAyantDroit.isFrontCamera, file: image } } } else return childAyantDroit; })); } else { setConjointAyantDroitDocument(conjointAyantDroitDocument.map(conjointAyantDroit => { if (name === conjointAyantDroit.name) { if (conjointAyantDroit.hasCheckbox) { return { label: conjointAyantDroit.label, name: conjointAyantDroit.name, isFrontCamera: conjointAyantDroit.isFrontCamera, file: image, hasCheckbox: conjointAyantDroit.hasCheckbox, checkboxValue: conjointAyantDroit.checkboxValue, checboxSelectedValue: conjointAyantDroit.checboxSelectedValue, }; } else { return { label: conjointAyantDroit.label, name: conjointAyantDroit.name, isFrontCamera: conjointAyantDroit.isFrontCamera, file: image } } } else return conjointAyantDroit; })); } createFormData(name, image); }); }; const onChangeDateNaissance = (event, selectedDate) => { const currentDate = selectedDate || dateNaissance; setShowDateNaissancePicker(Platform.OS === 'ios'); setDateNaissance(currentDate); }; const renderDateNaissancePicker = () => { return ( ); } const renderModalViewBeneficiaries = () => { return ( setModalViewBeneficiariesVisible(false)} swipeDirection={['down']} style={styles.bottomModal}> index} renderItem={({item, index}) => { console.log("Item", item); return ( {I18n.t('NOM_ASSURE')} {`${item.firstname} ${item.lastname}`} {I18n.t('AFFILIATION')} {item.affiliation === 'CHILD' ? I18n.t('ENFANT') : I18n.t('CONJOINT')} {item.hasOwnProperty('isEditable') && { let beneficiariesTemp = beneficiaries; console.log("beneficiariesTemp index", index); beneficiariesTemp.splice(index); console.log("beneficiariesTemp", beneficiariesTemp); setBeneficiaries([...beneficiariesTemp]); }}> } ); }}/> ); }; const renderAddNewIdentification = () => ( { fetchUploadInsurance(fileToSend); setFirstNameBeneficiary(values.firstname); setLastNameBeneficiary(values.lastname); }}> {({ values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting, }) => ( { setModalVisible(false); }} swipeDirection={['down']} style={styles.bottomModal}> {I18n.t('ADD_AYANT_DROIT')} { Keyboard.dismiss(); setShowDateNaissancePicker(true); }} success={touched.birthdate && !errors.birthdate} touched={touched.birthdate} error={errors.birthdate} /> {I18n.t('SEXE')} { setGender(value); }}/> {I18n.t('AFFILIATION')} { setFileAdded([]); if (value === 'CHILD') setCurrentYearMinusAgeLimit(new Date(((new Date()).getFullYear() - parseInt(subscription.network.age_limit_of_child_beneficiary)), 0, 1)); else setCurrentYearMinusAgeLimit(new Date(((new Date()).getFullYear() - parseInt(subscription.network.age_limit_of_insured_and_spouse)), 0, 1)); setAffliliation(value); }}/> index} renderItem={({item, index}) => { if (index === 0) { return ( handleTakePhotoFromCamera(item.name, item.isFrontCamera)}> {item.file === null ? : } {item.label} ); } else { return ( handleTakePhotoFromCamera(item.name, item.isFrontCamera)} disabled={!fileAdded.includes(affiliation === 'CHILD' ? childAyantDroitDocument[index - 1].name : conjointAyantDroitDocument[index - 1].name)}> {item.file === null ? : } {item.label} ); } }} /> )} ); return ( (dropDownAlertRef = ref)}/> { if (user !== null) { if (subscription === null) { subscriptionRef.shake(800); } else { console.log(user); console.log("insurance", insurance); setPassword(values.password); fetchAddBeneficiaryToSubscription(subscription.id, { password: values.password, beneficiaries }); } } }}> {({ values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting, }) => ( {/* { insurancesRef = comp }} style={{ width: responsiveWidth(90), height: 60, alignSelf: 'center', borderRadius: 10, paddingLeft: 20, paddingRight: 20, backgroundColor: 'white' }}> { console.log("Value", value); setInsurance( { age_limit_of_child_beneficiary: value.age_limit_of_child_beneficiary, age_limit_of_insured_and_spouse: value.age_limit_of_insured_and_spouse, id: value.id, max_number_of_beneficiaries: value.max_number_of_beneficiaries, name: value.name, months_prices: value.months_prices.map((item, index) => { return { id: item.id, number_of_months: item.number_of_months, min_amount: item.min_amount, checked: index === 0, }; }) } ); setAmountPerMonth(value.months_prices[0]); }} valueExtractor={(value) => { return value }} labelExtractor={(value) => { return value.name }} /> */} { subscriptionRef = comp }} style={{ width: responsiveWidth(90), height: 60, alignSelf: 'center', borderRadius: 10, paddingLeft: 20, paddingRight: 20, backgroundColor: 'white' }}> { console.log("Value", value); setSubscription( { id: value.id, network: value.network, insurance_subscription_id: value.insurance_subscription_id, network_id: value.network_id, user_id: value.user_id, number_of_months: value.number_of_months, bonus_amount: value.bonus_amount, number_of_beneficiaries: value.number_of_beneficiaries, total_bonus_amount: value.total_bonus_amount, state: value.state, created_at: value.created_at, updated_at: value.updated_at, start_at: value.start_at, end_at: value.end_at, insured_id: value.insured_id, subscription: value.subscription, beneficiaries: value.beneficiaries } ); }} valueExtractor={(value) => { return value }} labelExtractor={(value) => { return `${value.network.name} | ${I18n.t('ETAT')}: ${value.state} | ${I18n.t('AMOUNT_LABEL')}: ${value.total_bonus_amount}` }} /> } value={values.password} onBlur={handleBlur('password')} success={touched.password && !errors.password} touched={touched.password} error={errors.password} /> { if (subscription === null) { dropDownAlertRef.alertWithType( 'warn', I18n.t('ERROR_LABEL'), I18n.t('PLEASE_SELECT_INSURANCE_BEFORE'), ); } else { console.log("Souscription", subscription); setModalVisible(true); setShowDateNaissancePicker(false); dispatch(fetchUploadInsuranceReset()); setAffliliation('CHILD'); setCurrentYearMinusAgeLimit(new Date(((new Date()).getFullYear() - parseInt(subscription?.network?.age_limit_of_child_beneficiary)), 0, 1)); setDateNaissance('' + moment(new Date(((new Date()).getFullYear() - parseInt(subscription?.network?.age_limit_of_child_beneficiary)), 0, 1)).format('YYYY-MM-DD')); setFirstNameBeneficiary(null); setLastNameBeneficiary(null); setFileAdded([]); //setDateNaissance('' + moment().subtract(5, 'years').format()); } }}> {I18n.t('ADD_AYANT_DROIT')} )} {modalVisible && renderAddNewIdentification()} {modalViewBeneficiariesVisible && renderModalViewBeneficiaries()} {showDateNaissancePicker && renderDateNaissancePicker()} {(subscription !== null) && ( setModalViewBeneficiariesVisible(true)} > {beneficiaries.concat(subscription.beneficiaries).length} {I18n.t('AYANT_DROIT')} )} ); }; const mapStateToProps = createStructuredSelector({ insuranceList: selectInsuranceList, subscribeInsurance: selectSubscribeInsurance, uploadInsuranceImages: selectUploadInsuranceImages, insurancePrimeAmount: selectInsurancePrimeAmount, addBeneficiaryToSubscription: selectAddBeneficiaryToSubscription, subscriptionList: selectSubscriptionList }); export default connect(mapStateToProps, { fetchGetListInsurance, fetchSubscribeInsurance, fetchGetInsurancePrimeAmount, fetchUploadInsurance, fetchAddBeneficiaryToSubscription, fetchGetSubscriptionList, })( AddBeneficiaryScreen, );