simba-mobile-cad3/app/screens/account/AddNetwork.js

801 lines
34 KiB
JavaScript

import React, {Component} from 'react';
import {Alert, Image, Platform, ScrollView, StatusBar, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {Fumi} from 'react-native-textinput-effects';
import * as Animatable from 'react-native-animatable'
import I18n from 'react-native-i18n'
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome'
import {AssignAgentGeo, getCodeInformationForAddTaxe, readUser} from './../../webservice/AuthApi';
import {responsiveHeight, responsiveWidth} from 'react-native-responsive-dimensions';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import Button from 'apsl-react-native-button'
import {IlinkEmitter} from "../../utils/events";
import {Dropdown} from "react-native-material-dropdown-v2";
import isNil from 'lodash/isNil';
import isEqual from 'lodash/isEqual';
import {Color} from "../../config/Color";
import ImagePicker from "react-native-image-crop-picker";
import {FontWeight, Typography} from "../../config/typography";
import {ProgressDialog} from "react-native-simple-dialogs";
import axios from "axios";
import {uploadImage} from "../../webservice/IlinkConstants";
import Dialog from "react-native-dialog";
import FilteredList from "../login/FilteredList ";
let theme = require('./../../utils/theme.json');
require('./../../utils/Translations')
const route = require('./../../route.json');
export default class AddNetwork extends Component {
static navigatorStyle = {
navBarBackgroundColor: theme.primaryDark,
navBarTextColor: 'white',
navBarButtonColor: 'white',
drawUnderStatusBar: false,
statusBarColor: theme.primaryDarkAdvanced,
statusBarTextColorScheme: 'light',
};
static navigationOptions = ({navigation}) => {
return {
drawerLabel: () => null,
title: I18n.t('AVIS_IMPOSITION') + ' N°' + navigation.getParam("item", "-").id_tax_notice,
headerTintColor: 'white',
headerStyle: {
backgroundColor: Color.primaryColor,
marginTop: 20,
color: 'white'
},
headerTitleStyle: {
color: "white"
},
}
};
updateLangue() {
this.props.navigation.setParams({name: I18n.t('CHANGE_INFORMATION')})
this.forceUpdate()
}
static options(passProps) {
return {
topBar: {
title: {
text: "",
},
backButton: {
visible: true,
color: "white"
},
buttonsRight: [],
buttonColor: "white",
background: {
color: theme.primaryDark
}
}
}
}
constructor(props) {
super(props);
this.state = this.generateState();
this.dataToSendTemp = new FormData();
this.user = null;
IlinkEmitter.on("langueChange", this.updateLangue.bind(this));
readUser().then((user) => {
if (user) {
if (user !== undefined) {
if (user.category !== undefined) {
this.user = user;
}
}
}
});
}
generateState() {
return {
isLoading: false,
notifi: false,
isFirstStep: true,
id_network_tax: null,
tax_units_count: [],
units_per_tax_unit_count: [],
id_company_type: null,
identification_number: null,
trade_registry: null,
tabTaxe: [0],
number_of_days: [],
taxes_selected: [],
result: null,
image: null,
index: 0,
displayImage: false,
loadingUpload: false,
item: this.props.navigation.getParam("item", null),
password: null,
neighborhood: null,
building_value: [],
built: [false]
}
}
createFormData = (photo) => {
this.dataToSendTemp.append("image", {
name: photo.path.split('/').pop(),
type: photo.mime,
uri:
Platform.OS === "android" ? photo.path : photo.path.replace("file://", "")
});
};
retreiveCodeInformation() {
const membre = this.state.validateCode;
return new Promise(async (resolve, reject) => {
let datas = await getCodeInformationForAddTaxe(membre, this.state.item.id_agent);
console.log("DATA", datas);
resolve(datas);
});
}
renderLoader = () => {
return (
<ProgressDialog
visible={this.state.loadingUpload}
title={I18n.t('LOADING')}
message={I18n.t('UPLOAD_PHOTO')}
/>
)
};
ckeckIfFieldIsOK(champ) {
return (isNil(champ) || isEqual(champ.length, 0));
}
uploadImage = () => {
axios({
url: `${uploadImage}`,
method: 'POST',
data: this.dataToSendTemp,
headers: {
'X-Localization': I18n.currentLocale(),
'Content-Type': 'multipart/form-data'
},
})
.then(response => {
console.log(response);
let taxes_selected = this.state.taxes_selected;
taxes_selected[this.state.index].image = response.data.response.filename;
this.setState({taxes_selected, loadingUpload: false});
})
.catch(error => {
console.log(error);
if (error.response)
console.log(error.response);
else if (error.request)
console.log(error.request);
else
console.log(error.message);
Alert.alert("", I18n.t('TITLE_ERROR_SURVENU'), [{
text: "Ok",
onPress: () => {
}
}]);
this.setState({loadingUpload: false});
});
};
renderDialogImage = () => {
return (
<Dialog.Container contentStyle={{width: responsiveWidth(80)}} useNativeDriver={true}
visible={this.state.displayImage}>
<Dialog.Title>{I18n.t('PREVISUALISATION')}</Dialog.Title>
<View>
<View style={{width: 50}}/>
<View style={{justifyContent: 'center', alignContent: 'center', alignItems: 'center'}}>
<Image source={{uri: this.state.image.path}} style={{
width: this.state.image.width, height: this.state.image.height, aspectRatio: 1,
resizeMode: 'contain'
}}/>
</View>
<View style={{width: 50}}/>
</View>
<Dialog.Button bold={true} label={I18n.t('OK')} onPress={() => {
this.setState({
displayImage: false,
loadingUpload: true
});
this.uploadImage();
}}/>
</Dialog.Container>
)
}
renderTaxesDropdown = (index) => {
const selectedNeighbourhood = this.state.result && this.state.result.neighborhoods
? this.state.result.neighborhoods.find(n => n.name === this.state.neighborhood)
: null;
const mercurialValue = selectedNeighbourhood
? (this.state.built[index]
? selectedNeighbourhood.mercur_built_value
: selectedNeighbourhood.mercur_unbuilt_value)
: null;
return (
<>
<Animatable.View key={index}>
<View
style={{
marginTop: 20,
flexDirection: "row",
paddingRight: 20,
paddingLeft: 20,
}}>
<View style={{
width: responsiveWidth(90),
borderRadius: 10,
alignSelf: "center",
backgroundColor: 'white'
}}>
<Dropdown
label={I18n.t('TAXES')}
data={this.state.result.taxes}
useNativeDriver={true}
valueExtractor={(value) => {
return value
}}
onChangeText={(value, i, data) => {
let taxes_seleted = this.state.taxes_selected;
if (index === 0) {
taxes_seleted = new Array();
taxes_seleted[index] = value;
} else
taxes_seleted[index] = value;
this.setState({taxes_selected: taxes_seleted}, () => {
console.log("Taxes", this.state.taxes_selected);
});
}}
labelExtractor={(value) => {
return value.name
}}
/>
</View>
{
this.state.result.network.has_many_taxes === "1" &&
<View>
<TouchableOpacity
style={[styles.contain], {
backgroundColor: Color.accentColor,
alignItems: "center",
justifyContent: "center",
position: "absolute",
width: 25,
bottom: 0,
zIndex: 10,
left: -10,
height: 25,
borderRadius: 11}}
onPress={() => {
let tabTaxe = this.state.tabTaxe;
if (index === 0) {
let lastElement = this.state.tabTaxe[this.state.tabTaxe.length - 1];
tabTaxe.push(lastElement++);
this.setState({tabTaxe});
} else {
tabTaxe = tabTaxe.filter((element, i) => index !== i);
this.setState({tabTaxe});
}
}}
activeOpacity={0.9}>
<View>
<View>
<Icon name={index > 0 ? 'minus' : 'plus'} color={Color.whiteColor}
size={20}/>
</View>
</View>
</TouchableOpacity>
</View>
}
</View>
</Animatable.View>
{
!isNil(this.state.taxes_selected[index]) ?
this.state.taxes_selected[index].measurement_unit !== "forfait" &&
<>
<Animatable.View>
<Fumi iconClass={FontAwesomeIcon}
iconName={'check-circle'}
label={this.state.taxes_selected[index].labels[0]}
iconColor={'#f95a25'}
keyboardType="decimal-pad"
iconSize={20}
style={styles.input}
onChangeText={(value) => {
let tax_units_count = this.state.tax_units_count;
if (index === 0) {
tax_units_count = [];
tax_units_count[0] = value;
} else
tax_units_count[index] = value;
this.setState({tax_units_count: tax_units_count});
}}
>
</Fumi>
</Animatable.View>
{
this.state.taxes_selected[index].labels.length === 2 &&
<Animatable.View>
<Fumi iconClass={FontAwesomeIcon}
iconName={'check'}
label={isNil(this.state.taxes_selected[index].labels[1]) ? I18n.t('UNIT_PER_TAXE_UNIT_COUNT') : this.state.taxes_selected[index].labels[1]}
iconColor={'#f95a25'}
keyboardType="decimal-pad"
iconSize={20}
style={styles.input}
onChangeText={(value) => {
let units_per_tax_unit_count = this.state.units_per_tax_unit_count;
if (index === 0) {
units_per_tax_unit_count = [];
units_per_tax_unit_count[0] = value;
} else
units_per_tax_unit_count[index] = value;
this.setState({units_per_tax_unit_count: units_per_tax_unit_count});
}}
>
</Fumi>
</Animatable.View>
}
</> :
null
}
{
!isNil(this.state.taxes_selected[index]) &&
this.state.taxes_selected[index].name?.toLowerCase() === 'taxe sur la propriété' && (
<>
<Animatable.View>
<View
style={{
width: responsiveWidth(90),
alignSelf: 'center',
backgroundColor: 'white',
borderRadius: 10,
marginTop: 20,
paddingLeft: 20,
paddingRight: 20,
}}>
<Dropdown
label={I18n.t('BUILDING_CONSTRUCTED')}
data={[{value: 'Non'}, {value: 'Oui'}]}
value={this.state.built[index] ? 'Oui' : 'Non'}
onChangeText={value => {
const built = [...this.state.built];
built[index] = value === 'Oui';
this.setState({built});
}}
/>
</View>
</Animatable.View>
{mercurialValue != null && (
<Text
style={{
marginTop: 5,
marginLeft: responsiveWidth(6),
fontSize: 16,
color: '#fff',
}}>
{`${I18n.t('MERCURIAL_VALUE')}: ${mercurialValue}`}
</Text>
)}
{this.state.built[index] && (
<Animatable.View>
<Fumi
iconClass={FontAwesomeIcon}
iconName="building"
label={I18n.t('CONSTRUCTION_VALUE')}
iconColor="#f95a25"
iconSize={20}
keyboardType="decimal-pad"
style={styles.input}
onChangeText={value => {
const building_value = [...this.state.building_value];
building_value[index] = value;
this.setState({building_value});
}}
/>
</Animatable.View>
)}
</>
)
}
{
!isNil(this.state.taxes_selected[index]) ?
this.state.taxes_selected[index].billing_period === 'jour' &&
(<Animatable.View>
<Fumi iconClass={FontAwesomeIcon} iconName={'calendar'}
label={I18n.t('NUMBER_OF_DAYS')}
iconColor={'#f95a25'}
iconSize={20}
keyboardType='numeric'
onChangeText={(value) => {
let {number_of_days} = this.state.number_of_days;
if (index === 0) {
number_of_days = [];
number_of_days[0] = value;
} else
number_of_days[index] = value;
this.setState({number_of_days});
}}
style={styles.input}
>
</Fumi>
</Animatable.View>) : null
}
{!isNil(this.state.taxes_selected[index]) ?
this.state.taxes_selected[index].has_image_capture === "1" &&
<View style={[styles.contentPicker]}>
<TouchableOpacity
style={[styles.contain]}
onPress={() => {
ImagePicker.openCamera({
width: 400,
height: 281,
cropping: true,
useFrontCamera: false
}).then(image => {
this.createFormData(image);
this.setState({image, displayImage: true, index});
})
}}
activeOpacity={0.9}>
<View style={[styles.contcontainerCenterentLeft]}>
<View>
<Icon name='image' color={Color.whiteColor}
style={[styles.thumb]} size={80}/>
<View style={[styles.point, {backgroundColor: Color.accentColor}]}>
<Icon name='camera-image' color={Color.whiteColor} size={20}/>
</View>
</View>
</View>
</TouchableOpacity>
<Text
style={[Typography.footnote, FontWeight.semibold], {color: Color.whiteColor}}>{I18n.t('IMAGE_TAKE')}</Text>
</View> : null
}
</>
)
}
render() {
const hasPropertyTax = this.state.taxes_selected.some(
t => t && t.name?.toLowerCase() === 'taxe sur la propriété'
);
return (
<View style={style.container}>
<StatusBar
backgroundColor="#00000030"
barStyle="light-content"
translucent={true}
/>
{this.state.displayImage && this.renderDialogImage()}
{this.state.loadingUpload && this.renderLoader()}
<ScrollView style={{flex: 1, paddingTop: 30}}>
<View style={style.appContainer}>
<Image source={require('../../assets/img/icon3.png')}
style={{width: responsiveWidth(90), resizeMode: "contain",
height: responsiveHeight(16), // Delete this line if the image size sucks and change the width and the height of icon3.png to 257 x 112
}}/>
</View>
<Text style={style.title}>{I18n.t('ADD_NETWORK')}</Text>
{
this.state.isFirstStep ?
<>
<Animatable.View>
<Fumi iconClass={FontAwesomeIcon}
iconName={"code"}
style={style.input}
inputStyle={{color: 'black'}}
value={this.state.validateCode}
label={I18n.t('SPONSOR_CODE')}
onChangeText={(text) => this.setState({validateCode: text})}
style={style.input}/>
</Animatable.View>
</> :
<>
{this.renderTaxesDropdown(0)}
{hasPropertyTax && (
<Animatable.View>
<FilteredList
items={this.state.result.neighborhoods}
placeholder={I18n.t('FIND_A_NEIGHBORHOOD')}
onItemSelect={selectedItem => {
this.setState({neighborhood: selectedItem.name});
}}
/>
</Animatable.View>
)}
{
this.state.tabTaxe.map((element, index) => (
index > 0 &&
this.renderTaxesDropdown(index)
))
}
<Animatable.View ref={(comp) => {
this.passwordAnim = comp
}}>
<Fumi iconClass={FontAwesomeIcon} iconName={'lock'}
label={I18n.t('PASSWORD')}
iconColor={'#f95a25'}
iconSize={20}
secureTextEntry={true}
value={this.state.password}
onChangeText={(password) => {
this.setState({password})
}}
style={styles.input}
>
</Fumi>
</Animatable.View>
</>
}
<Button style={style.btnStyle} textStyle={style.btnTextStyle}
isLoading={this.state.isLoading} onPress={() => {
if (this.state.isFirstStep) {
this.setState({isLoading: true})
this.retreiveCodeInformation().then((result) => {
console.log(result);
if (result.error !== undefined) {
switch (result.error) {
default:
Alert.alert(I18n.t("ERROR_LABEL"), result.error_msg
, [{
text: 'OK', onPress: () => {
//this.props.navigation.goBack();
}
}], {cancelable: false});
}
this.setState({isLoading: false});
} else
this.setState({isLoading: false, taxes: result.taxes, isFirstStep: false, result});
}).catch((error) => {
console.warn(error);
this.setState({isLoading: false});
});
} else {
console.log("ICI===>")
if (this.ckeckIfFieldIsOK(this.state.password))
this.passwordAnim.shake(800);
else
this.validateNetwork();
}
}}
>{this.state.isFirstStep ? I18n.t('NEXT') : I18n.t('VALIDATE')}</Button>
</ScrollView>
</View>)
}
async validateNetwork() {
const {validateCode, isLoading, enterPhone, password, item} = this.state;
if (validateCode !== undefined && validateCode !== null) {
this.setState({isLoading: true});
let taxes_to_send = [];
for (let i = 0; i < this.state.tabTaxe.length; i++) {
if (this.state.taxes_selected[i].hasOwnProperty("id")) {
if (this.state.taxes_selected[i].has_image_capture === "1") {
let taxe = {
has_image_capture: this.state.taxes_selected[i].has_image_capture,
image: this.state.taxes_selected[i].image,
id_network_tax: this.state.taxes_selected[i].id,
name: this.state.taxes_selected[i].name,
tax_units_count: isNil(this.state.tax_units_count[i]) ? null : this.state.tax_units_count[i],
units_per_tax_unit_count: isNil(this.state.units_per_tax_unit_count[i]) ? null : this.state.units_per_tax_unit_count[i],
number_of_days: isNil(this.state.number_of_days[i]) ? null : this.state.number_of_days[i],
};
if (this.state.taxes_selected[i].name?.toLowerCase() === 'taxe sur la propriété') {
taxe.building_value = isNil(this.state.building_value[i]) ? null : this.state.building_value[i];
taxe.built = this.state.built[i];
}
taxes_to_send.push(taxe);
} else {
let taxe = {
has_image_capture: this.state.taxes_selected[i].has_image_capture,
id_network_tax: this.state.taxes_selected[i].id,
name: this.state.taxes_selected[i].name,
tax_units_count: isNil(this.state.tax_units_count[i]) ? null : this.state.tax_units_count[i],
units_per_tax_unit_count: isNil(this.state.units_per_tax_unit_count[i]) ? null : this.state.units_per_tax_unit_count[i],
number_of_days: isNil(this.state.number_of_days[i]) ? null : this.state.number_of_days[i],
};
if (this.state.taxes_selected[i].name?.toLowerCase() === 'taxe sur la propriété') {
taxe.building_value = isNil(this.state.building_value[i]) ? null : this.state.building_value[i];
taxe.built = this.state.built[i];
}
taxes_to_send.push(taxe);
}
}
}
let res = await AssignAgentGeo(validateCode, enterPhone, taxes_to_send, item.id_agent, password, item.id, this.state.neighborhood);
this.setState({isLoading: false});
if (res) {
if (res['success'] !== undefined) {
Alert.alert(
I18n.t('ADD_SUCCES'),
I18n.t('ADD_SUCCESS_TEXT')
, [
{
text: 'OK', onPress: () => {
this.setState({validateCode: "", enterPhone: ""});
this.props.navigation.popToTop();
}
}
])
} else {
if (res['error']) {
let error = res["error"];
Alert.alert("Une erreur est survenu",
res["error_msg"]
, [{
text: "Ok", onPress: () => {
}
}]);
} else {
if (res['error']) {
let error = res["error"];
Alert.alert("Une erreur est survenu",
"Verifier que les champs sont bien rempli"
, [{
text: "Ok", onPress: () => {
}
}]);
}
}
}
}
}
}
}
const style = StyleSheet.create({
btnHelpText: {
color: 'white',
fontWeight: 'bold'
},
btnHelp: {
width: responsiveWidth(10),
marginTop: responsiveHeight(10),
alignSelf: 'flex-end',
marginRight: 20,
borderColor: 'transparent',
backgroundColor: theme.primaryDark
},
btnTextStyle: {
color: "white",
fontWeight: 'bold',
},
btnStyle: {
alignSelf: 'center',
width: responsiveWidth(95),
marginTop: 20,
borderColor: 'transparent',
backgroundColor: theme.primaryDarkAdvanced,
height: responsiveHeight(8),
marginBottom: responsiveHeight(8) // espace ajouté en bas
},
appContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center'
},
container: {
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'center',
flex: 1,
width: responsiveWidth(100),
height: responsiveHeight(100),
backgroundColor: theme.primary
},
input: {
height: 60,
width: responsiveWidth(90),
marginTop: responsiveHeight(2),
marginLeft: responsiveWidth(5),
marginRight: responsiveWidth(5),
borderRadius: 5,
},
logo: {
width: 128,
height: 128
},
nameApp: {
fontSize: 27,
fontWeight: 'bold',
color: 'white'
},
title: {
fontSize: 22,
fontWeight: 'bold',
margin: 10,
color: 'white'
},
subtitle: {
fontSize: 20,
margin: 10,
color: 'white'
}
});
const styles = StyleSheet.create({
rowContainer: {
height: 52,
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
},
iconContainer: {
marginRight: 16,
},
map: {
height: 200,
marginRight: responsiveWidth(5),
marginLeft: responsiveWidth(5),
marginVertical: 10,
},
btnvalide: {
marginTop: 20,
marginLeft: 20,
marginRight: 20,
borderColor: 'transparent',
backgroundColor: theme.accentLight,
height: 52
},
input: {
height: 60,
marginTop: responsiveHeight(2),
marginLeft: responsiveWidth(5),
marginRight: responsiveWidth(5),
borderRadius: 5,
},
contentPicker: {
padding: 10,
borderRadius: 8,
flex: 1,
alignItems: "center"
},
contain: {flexDirection: "row"},
thumb: {
borderRadius: 30,
marginRight: 10
},
point: {
width: 25,
height: 25,
borderRadius: 11,
alignItems: "center",
justifyContent: "center",
position: "absolute",
right: 9,
bottom: 0
},
})