/** * @format * @flow */ import React from 'react'; import { Alert, Animated, AsyncStorage, BackHandler, Dimensions, FlatList, Linking, PermissionsAndroid, Platform, ProgressBarAndroid, ScrollView, StatusBar, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import axios from "axios"; import IMap from './IMap' import ActionButton from 'react-native-action-button'; import {CardView} from "react-native-cardview" import {responsiveHeight, responsiveWidth,} from 'react-native-responsive-dimensions'; import {material} from 'react-native-typography'; import {getMakersFrom, loadGroupeAgent} from './../../webservice/MapService'; import { getCountryNetwork, getDefaultTown, getTownInformationName, readUser, saveActifsSociety } from './../../webservice/AuthApi' import BaseScreen from './../BaseScreen' import isEqual from 'lodash/isEqual'; import Button from 'apsl-react-native-button' import I18n from 'react-native-i18n' import {IlinkEmitter} from "./../../utils/events" import _ from 'lodash'; import Configuration from "../../webservice/persistences/Configuration"; import {MaterialDialog} from "react-native-material-dialog"; import {ProgressDialog} from 'react-native-simple-dialogs'; import SnapSlider from 'react-native-snap-slider' import call from "react-native-phone-call"; import Icon from 'react-native-vector-icons/MaterialIcons'; import Geolocation from 'react-native-geolocation-service'; import InterticielAds from './../ads/InterticielAds' import SnackBar from 'react-native-snackbar-component' import {FAB, Surface} from 'react-native-paper' import BottomSheet from 'reanimated-bottom-sheet' import MarkerManager from './../../webservice/persistences/MarkerManager'; import TextInput from "../../components/TextInput"; import {bindActionCreators} from 'redux'; import getAuthApiKey from '../../webservice/AuthKeyApi'; import {connect} from 'react-redux'; import getWalletActivated from '../../webservice/WalletApi'; import {saveOnesignalIdsAction, saveOnesignalIdsReset} from '../../webservice/OnesignalApi'; import OneSignal from 'react-native-onesignal'; import {actifToSave, saveOnesignalIds, uploadImage, usagerToSave} from '../../webservice/IlinkConstants'; import {updateDefaultNetworkAction, updateDefaultNetworkReset} from "../../webservice/UpdateDefaultNetworkApi"; import {getData} from "../../webservice/persistences/StorageService"; import {createGeolocatedAccounts} from "../../webservice/AuthApi"; import {callingCodes} from "@ideditor/country-coder"; import * as Animatable from "react-native-animatable"; import FontAwesome from "react-native-vector-icons/FontAwesome"; import { getQRCodeDetailAction, getQRCodeDetailReset, searchUserAction, searchUserReset } from "../../webservice/regisseur/WalletRegisseurApi"; import Dialog from "react-native-dialog"; import {Color} from "../../config/Color"; import {Typography} from "../../config/typography"; import FontAwesomeIcon from "react-native-vector-icons/FontAwesome5"; import QRCodeScanner from "react-native-qrcode-scanner"; import {RNCamera} from "react-native-camera"; const countries = require("./../../utils/country_code.json") let geolib = require("geolib") require('./../../utils/Translations') const GEOLOCATION_OPTIONS = { enableHighAccuracy: true, timeout: 20000, maximumAge: 500, useSignificantChanges: false, distanceFilter: 0 }; const radioOptions = [{label: "mon Reseau", value: 0}, {label: "Tout", value: 1}] const theme = require('./../../utils/theme.json'); const route = require('./../../route.json'); const {width: viewportWidth, height: viewportHeight} = Dimensions.get('window'); const slideHeight = responsiveHeight(30) > 270 ? 270 : responsiveHeight(30) //var Fabric = require('react-native-fabric'); //var { Crashlytics } = Fabric const defaultProps = { enableHack: false, geolocationOptions: GEOLOCATION_OPTIONS, }; class Home extends BaseScreen { static navigationOptions = ({navigation}) => { return { headerMode: "none", headerStyle: { display: 'none' }, header: null, drawerLabel: navigation.getParam("name", I18n.t('MAP')), drawerIcon: ({tintColor}) => ( ), } }; static defaultProps = { draggableRange: { top: responsiveHeight(30), bottom: 0 }, panel: null }; _draggedValue = new Animated.Value(0) renderIcon = icon => ({isActive}) => ( ) onLoadMore() { const {user, prevRegion, boundarie} = this.state; if (user.category === undefined || user.category === null || user.category === "super") { if (this.promiseRegion) this.promiseRegion.done(); this.promiseRegion = new Promise(async (resolve, reject) => { this.setState({isNeedLoadMore: false, isLoadingMap: true}) const camera = await this.mapRef.getCamera();//comment this const zoom = camera.zoom - 10 let res = []; if (this.state.filternetworkTemp !== undefined) { let net = this.state.filternetworkTemp.id res = this.state.networks.filter(function (item) { return item.id === net }); } if (res.length > 0) { this.setState({isLoadingMap: false}) let reseau = res[0]; const pos = {longitude: user.longitude, latitude: user.latitude} try { //let data = await loadMarkers(pos, reseau, 5000, this.state.page) let data = await this.loadingMarkers(this.state.myPosition, this.state.filternetwork, this.filterOptions[this.state.increasePas].value); this.treatNewData(pos, data, false) } catch (e) { this.setState({isNeedLoadMore: false, isLoadingMap: false}) } } else { this.setState({isNeedLoadMore: true, isLoadingMap: false}) } if (this.map) this.map.focusToUser() resolve() }) } } openDrawer = () => { this.props.navigation.openDrawer() } onslidingEvent(event) { this.setState({ maxHeightSliding: event.nativeEvent.layout.height }); } onIds = async (device) => { console.log('Device info: ', device); AsyncStorage.getAllKeys((err, keys) => { AsyncStorage.multiGet(keys, (err, stores) => { stores.map(async (result, i, store) => { let key = store[i][0]; if (i === 0) { if (!_.isEqual(key, '@config:onesignalIds')) { this._saveOneSignalIds(device.userId); console.log("FIRST LAUNCH", true); //IlinkEmitter.emit("firstlaunch"); this.onFirstLaunch(); } } }); }); }); } onFirstLaunch = () => { console.warn("FIRST LAUNCH ON HOME"); readUser().then(async (user) => { console.log("USER", user); if (user) { if (user !== undefined) { global.onesignalIds = await this._getOneSignalIds(); if (global.onesignalIds) { console.log("ONESIGNAL", global.onesignalIds); if (user !== undefined) { if (user.category !== undefined) { this.saveOneSignal(false, { code_membre: user.code_membre, player_id: global.onesignalIds, set_default: false }); /* this.props.saveOnesignalIdsAction(false, { code_membre: user.user_code, player_id: onesignalIds, set_default: false }); */ } else { this.saveOneSignal(true, { user_code: user.user_code, player_id: global.onesignalIds, set_default: false }); /* this.props.saveOnesignalIdsAction(true, { user_code: user.user_code, player_id: onesignalIds, set_default: false }); */ } } //this.props.saveOnesignalIdsAction() } //this.props.getWalletActivated(user.agentId); } } }); } saveOneSignal = (isUser, data) => { axios({ url: isUser ? `${saveOnesignalIds}/saveUser` : `${saveOnesignalIds}/saveAgent`, method: 'POST', data, headers: { 'X-Localization': I18n.currentLocale() } }) .then(response => { console.warn(response); if (response.data.status === 201) this.renderOneSignalResponse(response.data.error); }) .catch(error => { console.warn(error); if (error.response) this.renderOneSignalResponse(error.response); else if (error.request) this.renderOneSignalResponse(error.request); else this.renderOneSignalResponse(error.message); }); } _retrieveData = async () => { try { const value = await AsyncStorage.getItem('position'); if (value !== null) { let re = JSON.parse(value) re.longitudeDelta = 0.04 re.latitudeDelta = 0.01 const pos = JSON.parse(value) this.setState({region: re, oldPosition: pos}) } } catch (error) { console.warn(error) } }; _getOneSignalIds = () => { return new Promise(async (resolve, reject) => { try { const getElement = await AsyncStorage.getItem('@config:onesignalIds'); resolve(getElement); } catch (error) { reject(error); } }); } componentDidMount() { //this.onMapReady();//comment this readUser().then(async (user) => { if (user) { if (user !== undefined) { if (user.phone !== undefined) this.props.getAuthApiKey(user.phone); } } }); /* AsyncStorage.getAllKeys((err, keys) => { AsyncStorage.multiGet(keys, (err, stores) => { stores.map((result, i, store) => { let key = store[i][0]; let value = store[i][1]; console.log('STORAGE VALUE ', `key: ${key} | value: ${value}`); }); }); }); */ this.mounted = true; this.configuration = new Configuration() const {navigation} = this.props; this.markerManager = new MarkerManager() this.configuration.getCurrentPubValue().then((value) => { try { const val = parseInt(value) this.setState({isPubShow: val}); } catch (e) { } }) this.focusListener = navigation.addListener("didFocus", () => { this.configuration.getCurrentPasValue().then((value) => { try { this.setState({pas: parseInt(value)}); } catch (e) { } }) this.componentDidAppear(); }); this.blurListener = navigation.addListener("didBlur", (payload) => { this.componentDidDisappear() }) this._retrieveData(); getData(usagerToSave).then(resultGet => { if (!_.isNil(resultGet)) this.synchronizedUsager(resultGet); else this.synchronizedActif(); }); //this.toggleSlidingUp(false) if (this.props.coordinate) return; } componentWillReceiveProps(nextProps) { if (nextProps.resultSearchUserByName !== null) { this.setState({displayDialogResultSearch: true}); } if (nextProps.resultGetQRCodeDetail !== null) { if (nextProps.resultGetQRCodeDetail.response !== null) { this.setState({userName: '' + nextProps.resultGetQRCodeDetail.response.phone}) } } if (nextProps.errorGetQRCodeDetail !== null) { if (typeof nextProps.errorGetQRCodeDetail.data !== 'undefined') { Alert.alert( I18n.t("ERROR_LABEL"), nextProps.errorGetQRCodeDetail.data.error, [ { text: I18n.t("OK"), onPress: () => { this.setState({ displayPhoneField: false, userName: '' }); this.props.searchUserReset(); this.props.getQRCodeDetailReset(); } } ], {cancelable: false} ); } } } async requestCameraPermission() { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { 'title': 'Cool Photo App Camera Permission', 'message': 'Cool Photo App needs access to your camera ' + 'so you can take awesome pictures.' } ) if (granted === PermissionsAndroid.RESULTS.GRANTED) { readUser().then((user) => { if (user) { if (user.category !== undefined && user.category !== null) { const myPosition = { latitude: parseFloat(user.latitude), longitude: parseFloat(user.longitude) } const reg = { latitude: myPosition.latitude, longitude: myPosition.longitude, latitudeDelta: 0.03, longitudeDelta: 0.01, } this.setState({myPosition: myPosition}); this.mapRef.animateToCoordinate({ latitude: myPosition.latitude, longitude: myPosition.longitude }, 1000) this.mapRef.animateToRegion(reg, 1000) this.setState({isLoading: false, isLoadingMap: false, loadingDialog: false}) if (user.category !== "geolocated") { this.showMyMembers(); } else { if (myPosition.latitude <= 0 && myPosition.longitude <= 0) { this.props.navigation.push(route.updateinfo); } } } else { this.getPosition(); this.watchLocation(); } } }) } else { } } catch (err) { console.log(err) } } _storeData = async (position) => { try { await AsyncStorage.setItem('position', JSON.stringify(position)); } catch (error) { console.warn(error) } }; renderLoader = () => { return ( ) } uploadImage = () => { return new Promise(async (resolve, reject) => { axios({ url: `${uploadImage}`, method: 'POST', data: this.dataToSendTemp, headers: { 'X-Localization': I18n.currentLocale(), 'Content-Type': 'multipart/form-data' }, }) .then(response => { resolve(response); console.log(response); //taxes_selected[this.state.index].image = response.data.response.filename; }) .catch(error => { Alert.alert("", I18n.t('TITLE_ERROR_SURVENU'), [{ text: "Ok", onPress: () => { } }]); reject(error); }); }); }; createFormData = (photo) => { this.dataToSendTemp.append("image", { name: photo.path.split('/').pop(), type: photo.mime, uri: Platform.OS === "android" ? photo.path : photo.path.replace("file://", "") }); } createUsagerAccounts = (usagers) => { console.log("createGeolocatedAccounts===>>",JSON.stringify(usagers)); createGeolocatedAccounts(usagers).then((result) => { console.log("resultcreateGeolocatedAccounts===>>", result); this.setState({displaySynchronizeLoader: false}); if (!_.isNil(result)) { let message = ""; if (_.isArray(result)) { result.map((statusMessage) => { message += statusMessage.agent; if (statusMessage.hasOwnProperty('success_msg')) { message += ": " + statusMessage.success_msg + "\n"; } else { message += ": " + statusMessage.error_msg + "\n"; } }); } else message = result.error_msg; Alert.alert("", message, [{ text: "Ok", onPress: () => { AsyncStorage.removeItem(usagerToSave); this.synchronizedActif(); } }]); } }).catch((error) => { console.log("Erreur d'execution", error); this.setState({displaySynchronizeLoader: false}); }); this.setState({index: this.state.index + 1}); } createActifsAccounts = (actifs) => { console.log("createActifsAccounts===>>",actifs) saveActifsSociety(actifs).then((result) => { console.log("result", result); this.setState({displaySynchronizeLoader: false}); if (!_.isNil(result)) { let message = ""; result.data.response.map((statusMessage) => { if (statusMessage.hasOwnProperty('success_msg')) { message += statusMessage.company_name + ": " + statusMessage.success_msg + "\n"; } else { message += statusMessage.company_name + ": " + statusMessage.error_msg + "\n"; } }); Alert.alert("", message, [{ text: "Ok", onPress: () => { AsyncStorage.removeItem(actifToSave); } }]); } }).catch((error) => { console.log("Erreur d'execution", error); this.setState({displaySynchronizeLoader: false}); }); this.setState({index: this.state.index + 1}); } synchronizedUsager = (resultGet) => { let usagersToSave = JSON.parse(resultGet); console.log('Usager Saved', usagersToSave); if ((usagersToSave.filter((usager) => !usager.isSaved)).length > 0) { this.setState({displaySynchronizeLoader: true}) let usagersToSend = new Array(); getDefaultTown().then(result => { console.log("get default town result", result); getTownInformationName(result.default_locality).then((resultTowwn) => { getTownInformationName(result.default_locality).then((resultTowwn) => { usagersToSave.map((usager, index) => { this.setState({index}); //SEND IMAGE TO SERVER console.warn("L'USAGER ", usager); if (!usager.isSaved) { console.log("get town information", resultTowwn); console.log("usager to save infos", usagersToSave[index]); console.log("usager infos", usager); let town = null; if (resultTowwn instanceof Array) { town = resultTowwn[0]; } else town = resultTowwn; usagersToSave[index].data.town = town; if (usager.data.taxes.length === 0) { console.log("Tableau de taxe vide"); usagersToSend.push(usagersToSave[index].data); console.log("Usagers to send length", usagersToSend); console.log("Usagers To save", usagersToSave); } else { usager.data.taxes.map((taxe, indexTaxe) => { if (taxe.has_image_capture === "1") { this.createFormData(taxe.image); this.uploadImage().then((response) => { if (usager.data.hasOwnProperty("secondary_taxes")) { console.warn("UPLOADE DE LIMAGE TAXE SECONDAIRE 1"); let hasLoadAllSecondaryImage = false; usager.data.secondary_taxes.map((taxe_secondaire, indexTaxeSecondaire) => { this.createFormData(taxe_secondaire.image); this.uploadImage().then((response) => { console.warn("UPLOADE DE LIMAGE TAXE SECONDAIRE SUCCESS", indexTaxeSecondaire + 1, usager.data.secondary_taxes.length); usagersToSave[index].data.secondary_taxes[indexTaxeSecondaire].image = response.data.response.filename; usagersToSave[index].data.taxes[indexTaxe].image = response.data.response.filename; if ((indexTaxeSecondaire + 1) === usager.data.secondary_taxes.length) usagersToSend.push(usagersToSave[index].data); if (usagersToSend.length === (usagersToSave.filter((usager) => !usager.isSaved)).length) { console.log("Isco2===>>", usagersToSend); this.createUsagerAccounts(usagersToSend); } console.warn("USAGERS FORMATE", usagersToSave); }).catch(error => { console.log("Erreur d'execution upload photo", error); }); }); } else { usagersToSave[index].data.taxes[indexTaxe].image = response.data.response.filename; usagersToSend.push(usagersToSave[index].data); } }).catch(error => { console.log("Erreur d'execution upload photo", error); }); } else { console.log("USAGER HAS SECONDARY TAXES 2", usager.data.hasOwnProperty("secondary_taxes")); if (usager.data.hasOwnProperty("secondary_taxes")) { usager.data.secondary_taxes.map((taxe_secondaire, indexTaxeSecondaire) => { this.createFormData(taxe_secondaire.image); this.uploadImage().then((response) => { console.warn("UPLOADE DE LIMAGE TAXE SECONDAIRE SUCCESS 2"); usagersToSave[index].data.secondary_taxes[indexTaxeSecondaire].image = response.data.response.filename; usagersToSave[index].data.taxes[indexTaxe].image = response.data.response.filename; if ((indexTaxeSecondaire + 1) === usager.data.secondary_taxes.length) usagersToSend.push(usagersToSave[index].data); if (usagersToSend.length === (usagersToSave.filter((usager) => !usager.isSaved)).length) { console.log("Isco3===>>", usagersToSend); this.createUsagerAccounts(usagersToSend); } console.warn("USAGERS FORMATE", usagersToSave); }).catch(error => { console.log("Erreur d'execution upload photo", error); }); }) } else usagersToSend.push(usagersToSave[index].data); // if (usagersToSend.length === (usagersToSave.filter((usager) => !usager.isSaved)).length) { // console.log("Isco4===>>", usagersToSend); // this.createUsagerAccounts(usagersToSend); // } } }); } console.log("Usagers to send length", usagersToSend.length); console.log("Usagers to save length", (usagersToSave.filter((usager) => !usager.isSaved)).length); if (usagersToSend.length === (usagersToSave.filter((usager) => !usager.isSaved)).length) { console.log("Isco5===>>", usagersToSend); this.createUsagerAccounts(usagersToSend); } } }); }).catch(error => { console.log("Erreur d'execution recup town infos", error); }); }).catch(error => { console.log("Erreur d'execution recup default town", error); }); }); } } synchronizedActif = () => { getData(actifToSave).then(resultGet => { console.log("DATA FROM ASYNC STORAGE ACTIF ARRAY", resultGet); if (!_.isNil(resultGet)) { let actifsToSave = JSON.parse(resultGet); if ((actifsToSave.filter((actif) => !actif.isSaved)).length > 0) { this.setState({ displaySynchronizeLoader: true, messageSynchronize: I18n.t('SAUVEGARDER_OF_ACTIF_LOADING_SAVE') }) let actifsToSend = new Array(); actifsToSave.map((actif, index) => { this.setState({index}); //SEND IMAGE TO SERVER console.warn("L'USAGER", actif); if (!actif.isSaved) { actif.data.taxes.map((taxe, indexTaxe) => { console.log("Usagers to send length", actifsToSend.length); console.log("Usagers To save", actifsToSave.filter((usager) => !usager.isSaved).length); console.log("taxe.has_image_capture", taxe.has_image_capture); console.log("taxe.has_image_capture", taxe.has_image_capture === "1"); if (taxe.has_image_capture === "1") { this.createFormData(taxe.image); this.uploadImage().then((response) => { actifsToSave[index].data.taxes[indexTaxe].image = response.data.response.filename; actifsToSend.push(actif.data); if (actifsToSend.length === (actifsToSave.filter((usager) => !usager.isSaved)).length) this.createActifsAccounts(actifsToSend); }).catch(error => { this.setState({ displaySynchronizeLoader: false }) console.log("Erreur d'execution upload photo", error); }); } else { actifsToSend.push(actif.data); console.log("actifsToSend.push===>>",actif.data) console.log("actifsToSend.length === (actifsToSave.filter((usager) => !usager.isSaved)).length",actifsToSend.length === (actifsToSave.filter((usager) => !usager.isSaved)).length) if (actifsToSend.length === (actifsToSave.filter((usager) => !usager.isSaved)).length) this.createActifsAccounts(actifsToSend); } }); } }); } console.log("DATA FROM ASYNC STORAGE USAGER ARRAY", JSON.parse(resultGet)); } }); } watchLocation() { this.watchID = Geolocation.watchPosition((position) => { const myLastPosition = this.state.myPosition; let myPosition = position.coords; const oldPosition = this.state.oldPosition if (!myLastPosition || (myPosition.longitude !== myLastPosition.longitude || myPosition.latitude !== myLastPosition.latitude)) { if (myPosition.longitude !== 0 && myPosition.latitude !== 0) this._storeData(myPosition) if (isEqual(this.state.region, {}) || isEqual(this.state.region, undefined) || isEqual(this.state.region, null)) if (!this.state.myPosition.longitude && !this.state.myPosition.latitude) { if (this.mapRef !== null && this.mapRef !== undefined) { this.mapRef.animateToRegion({ latitude: myPosition.latitude, longitude: myPosition.longitude, latitudeDelta: 0.03, longitudeDelta: 0.01, }, 1000) this.mapRef.animateCamera({ center: this.myPosition, pitch: 0, heading: 0, altitude: 0, zoom: 12 }, 1000) } } this.setState({ region: { latitude: myPosition.latitude, longitude: myPosition.longitude, latitudeDelta: 0.003, longitudeDelta: 0.004 } }); this.setState({myPosition: myPosition}); if (this.map) this.map.focusToUser() } }, (error => console.log("wat s", error)), GEOLOCATION_OPTIONS); } getNetworks(pays) { if (pays) { getCountryNetwork(pays).then((result) => { this.reseaux = []; let networks = result; for (let prop in networks) { this.reseaux.push(networks[prop]); } this.setState({networks: this.reseaux}); let c = this.reseaux.filter((item) => { return item.name.includes(this.state.network); }); if (this.state.user.category === undefined || this.state.user.category === null || this.state.user.category === "super") { if (c.length > 0 && pays) { this.setState({filternetwork: c[0], myNetwork: c[0], filternetworkTemp: c[0]}); console.warn("CECI S'EXECUTE"); this.retrieveAllPoint(pays) //ici } else { if (this.state.user) { if (!this.state.user.category) Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE_CHOOSE_ANOTHER') , [ { text: I18n.t("NO"), onPress: () => { BackHandler.exitApp() } }, { text: I18n.t("YES"), onPress: () => { this.setState({updateDefaultNetwork: true}); this.showNewDialogNetwork(); /*if (pays !== null && pays !== undefined) this.getNetworks(pays) else this.requestCameraPermission();*/ } } ], {cancelable: false} ) } } } }, (err) => { // Crashlytics.log("get networks"+e.message) //Change message here Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE_CHOOSE_ANOTHER') , [ { text: I18n.t("NO"), onPress: () => { //BackHandler.exitApp() } }, { text: I18n.t("YES"), onPress: () => { if (pays !== null && pays !== undefined) this.getNetworks(pays) else this.requestCameraPermission() } } ], {cancelable: false} ) }) } else { console.log("get network missing pays") var msg = "impossible de récupérer le nom du pays"; Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ { text: I18n.t("NO"), onPress: () => { BackHandler.exitApp() } }, { text: I18n.t("YES"), onPress: () => { this.requestCameraPermission() } } ], {cancelable: false} ) } } getPosition(options = null) { console.log("on get position") Geolocation.getCurrentPosition( (position) => { const myLastPosition = this.state.myPosition; const myPosition = position.coords; const oldPosition = this.state.oldPosition if (!isEqual(myPosition, myLastPosition) && myPosition.longitude !== 0 && myPosition.latitude !== 0 || myLastPosition) { if (this.map) this.map.focusToUser(); let indicatif = callingCodes([myPosition.longitude, myPosition.latitude]); if (Array.isArray(indicatif)) indicatif = "+" + indicatif[0]; this.setState({ indicatif: indicatif, enterPhone: indicatif }); this.getNetworks(indicatif); /* getOpenCagePositionInformation(myPosition).then((response) => { if (response) { if (response.results !== undefined) { if (response.results.length > 0) { let most = response.results[0] let {address_components, county, country} = most.components; let indicatif = callingCodes([myPosition.longitude, myPosition.latitude]); if (Array.isArray(indicatif)) indicatif = "+" + indicatif[0]; console.log("OPENCAGE RESPONSE", indicatif); this.setState({ address: address_components, textadress: most.formatted, indicatif: indicatif, enterPhone: indicatif, shortCountry: county, longCountry: country }); } } else { console.log("on else result null ") Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ { text: I18n.t("NO"), onPress: () => { BackHandler.exitApp() } }, { text: I18n.t("YES"), onPress: () => { this.getPosition(options) } } ], {cancelable: false} ) } } else { Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ { text: I18n.t("NO"), onPress: () => { BackHandler.exitApp() } }, { text: I18n.t("YES"), onPress: () => { this.getPosition(options) } } ], {cancelable: false} ) } }); */ const reg = { latitude: myPosition.latitude, longitude: myPosition.longitude, latitudeDelta: 0.03, longitudeDelta: 0.01, } this.setState({myPosition: myPosition, region: reg}); if (this.mapRef && !this.state.myPositionIsAnimated) { //comment this.mapRef.animateCamera({ center: myPosition, pitch: 0, heading: 0, altitude: 5, zoom: 12 }, 1000); this.setState({myPositionIsAnimated: true}) } } else console.warn("errror") }, (error) => { console.warn(error.message) switch (error.code) { case 3: if (this.state.oldPosition) { this.treatPosition(this.state.oldPosition) } break; default: //Crashlytics.log(error.message) console.log("onjjj", error.message) /* Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{ this.getPosition(options) }} ], {cancelable:false} )*/ } }, GEOLOCATION_OPTIONS ); } componentDidDisappear() { BackHandler.removeEventListener('hardwareBackPress', this.backPressed); } componentDidAppear() { BackHandler.addEventListener('hardwareBackPress', this.backPressed); // this.props.start(); readUser().then((user) => { if (user) { if (user.category) { this.setState({user: user}) this.setState({network: user.network}); const myPosition = { latitude: parseFloat(user.latitude), longitude: parseFloat(user.longitude) } const reg = { latitude: myPosition.latitude, longitude: myPosition.longitude, latitudeDelta: 0.03, longitudeDelta: 0.01, } this.setState({myPosition: myPosition}); this.refocusMap(true); } /*if (Platform.OS === 'android') { // this.requestCameraPermission(); } else { this.getPosition(); this.watchLocation(); }*/ } }) } componentWillUnmount() { OneSignal.removeEventListener('ids', this.onIds); this.mounted = false; this.blurListener.remove(); this.focusListener.remove() if (this.watchID) Geolocation.clearWatch(this.watchID); } backPressed = () => { Alert.alert( I18n.t('EXIT_TITLE'), I18n.t('EXIT_DESC'), [ {text: I18n.t('NO'), onPress: () => console.log('Cancel Pressed'), style: 'cancel'}, {text: I18n.t("YES"), onPress: () => BackHandler.exitApp()}, ], {cancelable: false}); return true; } constructor(props) { super(props); this.state = this.geInitialState(); this.mounted = false; this.props.searchUserReset(); this.props.getQRCodeDetailReset(); IlinkEmitter.on("firstlaunch", this.onFirstLaunch); this.dataToSendTemp = new FormData(); this.filterOptions = [ {value: 5, label: "5 km"}, {value: 15, label: "15 km"}, {value: 20, label: "20 km"}, {value: 25, label: "25 km"} ]; Icon.getImageSource('md-car', 24, 'white').then((resutl) => { this.setState({caricon: resutl}) }); //this._renderFavoriteIcon = this._renderFavoriteIcon.bind(this); this.makeMarkerInformation = this.makeMarkerInformation.bind(this); //IlinkEmitter.on("langueChange", this.updateLangue.bind(this)) OneSignal.addEventListener('ids', this.onIds); global.appHasLoaded = true; }; /* updateLangue() { this.props.navigation.setParams({ name: I18n.t('MAP') }) this.forceUpdate(); } */ _getOneSignalIds = () => { return new Promise(async (resolve, reject) => { try { const getElement = await AsyncStorage.getItem('@config:onesignalIds'); resolve(getElement); } catch (error) { reject(error); } }); } _saveOneSignalIds = async (ids) => { try { await AsyncStorage.setItem('@config:onesignalIds', ids); } catch (error) { console.warn(error); } } makeCardSearch() { /* if (!this.state.isPubShow) { */ return ( this.openDrawer()} > Menu {this.state.filternetwork.name ? this.state.filternetwork.name : this.state.network} {this.renderSupplementInformation()} {this.showLoadingMapView()} ) /* } */ } renderSupplementInformation() { if (this.state.user && this.state.user.category === "geolocated") { return () } else return ( {this.state.markers.length + " " + (this.state.currentNetworkSize === 0 ? "" : "/" + this.state.currentNetworkSize)} { this.setState({page: this.state.page + 1}) this.onLoadMore() }} style={{ borderRadius: 12, height: 32, width: 32, backgroundColor: "white", borderColor: "transparent", }}> = this.state.currentNetworkSize ? "close" : "refresh"} size={32} color={this.state.markers.length >= this.state.currentNetworkSize ? "red" : "grey"} /> ) } _renderMarker2() { let {currentMarker, myPosition} = this.state; let marker = currentMarker const ma = {latitude: parseFloat(currentMarker.latitude), longitude: parseFloat(currentMarker.longitude)} const meter_distance = geolib.getDistance(myPosition, ma); const distanceTxt = (meter_distance > 900 ? (meter_distance / 1000) + " Km" : meter_distance + "m") + I18n.t('TO_YOU') var name = marker.lastname === null ? marker.adresse : marker.lastname return ( {name} { this.toggleSlidingUp(false) } }> {marker.adresse} {marker.network} {/*{I18n.t('SOLDE_UNVAIBLE')}*/} {distanceTxt} {!this.state.needRoad ? this.showBtnItineraire() : this.showBtnClose()} ) } _renderItemMarkerdetails(markers) { let marker = markers if (marker !== undefined && marker !== null) { let {currentMarker, myPosition} = this.state; const ma = {latitude: parseFloat(currentMarker.latitude), longitude: parseFloat(currentMarker.longitude)} const meter_distance = geolib.getDistance(myPosition, ma); const distanceTxt = (meter_distance > 900 ? (meter_distance / 1000) + " Km" : meter_distance + "m") + I18n.t('TO_YOU') var name = marker.lastname === null ? marker.adresse : marker.lastname return ( {name} { this.toggleSlidingUp(false) } }> {marker.adresse} {marker.network} {I18n.t('SOLDE_UNVAIBLE')} {distanceTxt} {!this.state.needRoad ? this.showBtnItineraire() : this.showBtnClose()} ); } } renderCurrentMarker(marker) { if (marker) { return ( {name} { this.toggleSlidingUp(false) } }> {marker.adresse} {marker.network} {I18n.t('SOLDE_UNVAIBLE')} {distanceTxt} {!this.state.needRoad ? this.showBtnItineraire() : this.showBtnClose()} ) } } callItem(marker) { const args = { number: marker.phone, // String value with the number to call prompt: false // Optional boolean property. Determines if the user should be prompt prior to the call } return Linking.canOpenURL(`tel:${marker.phone}`).then(canOpen => { if (!canOpen) { //return createError(`invalid URL provided: ${url}`) console.log("error") } else { return Linking.openURL(`tel:${marker.phone}`).catch((err) => Promise.reject(err)) } }) call(args).catch((e) => console.log(e)) } makeMarkerInformation() { let {currentMarker, myPosition} = this.state; // console.log(geolib.getDistance(myPosition,currentMarker)) if (currentMarker !== undefined && currentMarker !== null) { // this.setState({stateSheet:BottomSheetBehavior.STATE_EXPANDED}) return this._renderItemMarkerdetails(currentMarker); } else { return (Impossible de'afficher l'element) } } makeActionButon() { let cu = this.state.user; if (cu) { switch (cu.category) { case "super": return this.getSuperActionButton(); break; case "geolocated": return this.geoLocatedAction(); break; case "hyper": return this.getHypervisorActionButton(); break; default: return this.getSimpleActionButton(); break; } } } getSuperActionButton() { return ( this.showFilterDialog()} size={48} > { this.setState({dialogSearchUser: true}); }} size={48} > this.showMyMembers()} size={48} > this.refocusMap(false)} size={48} > { this.showMynetworkMap(); }}> { this.onMapTypeChange(); }} size={48} > { this.showNewDialogNetwork(); }}> ) } getSimpleActionButton() { return ( this.showFilterDialog()} size={48} > { this.setState({dialogSearchUser: true}); }} size={48} > this.refocusMap(false)} size={48} > { this.onMapTypeChange(); } } size={48} > { this.showMynetworkMap(); }}> { this.showNewDialogNetwork(); }}> ) } toggleSlidingUp(state) { if (state && this.bottomSheetRef) { this.bottomSheetRef.snapTo(1) this.setState({showcurentMarker: state}) } else if (!state) this.bottomSheetRef.snapTo(0) const height = slideHeight let initialValue = !state ? 0 : height, finalValue = !state ? height : 0; this.setState({ panelVisible: state }); if (!state && this.state.needRoad) { this.setState({needRoad: false}); } this.state.animation.setValue(initialValue); //Step 3 Animated.timing( //Step 4 this.state.animation, { toValue: finalValue, duration: 200, } ).start((animation) => { if (!state && this.map) { this.map.focusToUser() } }); } makeSlidingUp() { /*return ( this.onslidingEvent(event)} ref={(c) => this.panel = c} onRequestClose={() => this.setState({panelVisible: false, needRoad: false})}> {this.makeMarkerInformation()} )*/ return ( { this.bottomSheetRef = r }} snapPoints={[0, "30%"]} renderHeader={() => this.markerView()} />) } /* _renderFavoriteIcon() { const { top, bottom } = this.props.draggableRange const draggedValue = this._draggedValue.interpolate({ inputRange: [bottom, top], outputRange: [1, 0], extrapolate: 'clamp' }) const transform = [{ scale: draggedValue }] return ( { this.setState({ needRoad: true }) }}> ) } */ geInitialState() { return { isSaveOneSignalDisplay: false, region: { latitude: 0, longitude: 0, latitudeDelta: 0.015, longitudeDelta: 0.0121, }, pas: 100, prevRegion: { latitude: 0, longitude: 0, }, displayDialogResultSearch: false, updateDefaultNetwork: false, increasePas: 0, isPubShow: true, loadingDialog: true, textreach: "", currentNetworkSize: 0, markersearchfilter: [], animation: new Animated.Value(0), myPosition: null, currentMarker: null, filterNetworkOption: radioOptions[1], needRoad: false, initialAnim: false, filternetwork: {}, destinationPosition: {}, panelVisible: false, markers: [], isNeedLoadMore: false, isLoadingMap: false, value: 5, page: 0, valuePosition: 0, markerfilter: null, allpoint: [], typeMap: 'standard', indexTypeMap: 0, user: null, snack_visible: false, snack_text_message: "", networks: [], dialogSliderVisible: false, showProgress: false, myNetwork: {}, dialogNetworkVisible: false, dialogSearchUser: false, myPositionMarkerText: I18n.t("YOUR_THERE"), isSaveOneSignalOK: false, messageSynchronize: I18n.t("SAUVEGARDER_OF_USAGER_LOADING_SAVE"), displaySynchronizeLoader: false, nbreUsagerSaved: 0, index: 0, userName: '', isNumeroAssureSearch: false, isPhoneAssureSearch: false, showQRCodeScanner: false }; }; onMarkerPress(marker) { console.warn(marker) this.setState({currentMarker: marker}); this.toggleSlidingUp(true) } onMapTypeChange() { var newState = {index: this.state.indexTypeMap, text: this.state.typeMap}; newState.index = newState.index + 1; newState.index = newState.index % 3; switch (newState.index) { default: newState.text = 'standard'; break; case 1: newState.text = 'hybrid'; break; case 2: newState.text = "terrain"; break; } this.setState({indexTypeMap: newState.index, typeMap: newState.text}); } /* { this.map=re if(re!=null) { this.mapRef = re.getMapRef(); } }} typeMap={this.state.typeMap} onMarkerClick={(e)=>this.onMarkerPress(e)} network={this.state.filternetwork} initialRegion={this.state.region} markers={this.state.markers} selectedMarker={this.state.currentMarker} myNetwork={this.state.myNetwork} lang={this.state.lang} myPosition={this.state.myPosition} onMapReady={()=>{ readUser().then((user) => { if (user) { this.setState({user: user}) this.setState({network: user.network}); if (Platform.OS === 'android') { this.requestCameraPermission(); } else { this.getPosition(); this.watchLocation(); } } }) }} needRoad={this.state.needRoad} onNeedRoadReady={(data)=>{ this.setState({showProgress: false}) }} onNeedRoadError={(message)=>{ this.setState({showProgress: false}) Alert.alert(I18n.t("PROBLEM_OCCUR"),I18n.t("PROBLEM_OCCUR_DIRECTION"),[{text:"Ok",onPress:()=>{}}]) }} />*/ showInterticiel() { if (this.state.isPubShow) { return ( this.setState({isPubShow: false})} navigation={this.props.navigation} />) } } renderBottomHome() { return ( { this.map = re if (re != null) { this.mapRef = re.getMapRef(); } }} typeMap={this.state.typeMap} onMarkerClick={(e) => this.onMarkerPress(e)} network={this.state.filternetwork} initialRegion={this.state.region} markers={this.state.markers} selectedMarker={this.state.currentMarker} myNetwork={this.state.myNetwork} lang={this.state.lang} myPosition={this.state.myPosition} onMapReady={() => { readUser().then((user) => { if (user) { this.setState({user: user}) this.setState({network: user.network}); if (user.category) { this.setState({loadingDialog: false}) if (user.category !== "geolocated") { this.showMyMembers(); } else { if (myPosition.latitude <= 0 && myPosition.longitude <= 0) { this.props.navigation.push(route.updateinfo); } } } else { if (Platform.OS === 'android') { this.requestCameraPermission(); } else { //this.getPosition(); this.watchLocation(); } } } }); }} needRoad={this.state.needRoad} onNeedRoadReady={(data) => { this.setState({showProgress: false}) }} onNeedRoadError={(message) => { this.setState({showProgress: false}) Alert.alert(I18n.t("PROBLEM_OCCUR"), I18n.t("PROBLEM_OCCUR_DIRECTION"), [{ text: "Ok", onPress: () => { } }]) }} /> {this.makeCardSearch()} { this.bottomSheetRef = r }} snapPoints={[60, "30%", "100%"]} renderHeader={() => this.renderHeader()} /> ) } renderInner() { return ( Freud junior ) } markerView() { if (this.state.currentMarker) return this._renderMarker2() } renderHeader() { return ( { return ( ) }} style={{marginTop: 40, marginRight: 20}} buttonColor={theme.primary}/> {this.markerView()} {this.renderFilterMarker()} { if (!this.state.showFilterDistance) { this.bottomSheetRef.snapTo(2) this.setState({showFilterDistance: true}) } else { this.bottomSheetRef.snapTo(0) this.setState({showFilterDistance: false}) } } }/> { this.bottomSheetRef.snapTo(2) this.setState({showdialogNetworkVisible: true}) }} /> {this.makeMarkerButton()} ) } renderFilterMarker() { if (this.state.showFilterDistance) return ( {I18n.t('TEXT_FILTER_DISTANCE')} this.slidingComplete(item)} /> {(this.state.value === undefined ? 0 : this.state.value)} km {I18n.t("DISTANCE_ARROUND")} ) } else return ( ) } renderOneSignalResponse = (message) => { Alert.alert( I18n.t('PHISIC_SECURITY'), message, [ { text: I18n.t('REFUSED'), onPress: () => { BackHandler.exitApp(); } }, { text: I18n.t("SUBMIT_LABEL"), onPress: () => { readUser().then((user) => { if (user) { if (user.category !== undefined) { this.saveOneSignal(false, { code_membre: user.code_membre, player_id: global.onesignalIds, set_default: true }); } else { this.saveOneSignal(true, { user_code: user.user_code, player_id: global.onesignalIds, set_default: true }); } } }); } } ], {cancelable: false} ) } renderOldHome() { return ( {this.state.displaySynchronizeLoader && this.renderLoader()} {(this.state.displayDialogResultSearch && this.props.resultSearchUserByName !== null) && this.renderDialogResultSearchUser()} {/* Start here to comment */} { (this.state.loadingDialog || this.props.loading) ? {I18n.t("LOADING_DOTS")} : null } { this.map = re if (re != null) { this.mapRef = re.getMapRef(); } }} typeMap={this.state.typeMap} onMarkerClick={(e) => this.onMarkerPress(e)} network={this.state.filternetwork} initialRegion={this.state.region} markers={this.state.markers} selectedMarker={this.state.currentMarker} myNetwork={this.state.myNetwork} lang={this.state.lang} myPosition={this.state.myPosition} onMapReady={Platform.OS === 'android' ? this.onMapReady : null} onLayout={Platform.OS === 'ios' ? this.onMapReady : null} needRoad={this.state.needRoad} onNeedRoadReady={(data) => { this.setState({showProgress: false}) }} onNeedRoadError={(message) => { this.setState({showProgress: false}) Alert.alert(I18n.t("PROBLEM_OCCUR"), I18n.t("PROBLEM_OCCUR_DIRECTION"), [{ text: "Ok", onPress: () => { } }]) }} /> {this.makeCardSearch()} {this.makeSlidingUp()} {this.makeDialogLoader()} {this.makeDistanceDialog()} {this.makeNetworkChangeDialog()} {this.renderSearchUser()} {this.state.showQRCodeScanner && this.renderDialogQRCodeScanner()} {this.makeActionButon()} ) } onMapReady = () => { readUser().then((user) => { if (user) { this.setState({user: user}); this.setState({network: user.network, isSaveOneSignalOK: true}); console.log("LATITUDE", user.latitude); console.log("LONGITUDE", user.longitude); const myPosition = { latitude: _.isNil(user.latitude) ? 0 : parseFloat(user.latitude), longitude: _.isNil(user.longitude) ? 0 : parseFloat(user.longitude) } this.setState({myPosition}); this.refocusMap(false); if (user.category) { this.setState({loadingDialog: false}); if (user.category == "hyper") { this.showMyMembers(); } else if (user.category === "super") { this.getPosition(); this.watchLocation(); } else { if (myPosition.latitude <= 0 && myPosition.longitude <= 0) { this.props.navigation.push(route.updateinfo); } } } else { if (Platform.OS === 'android') { this.requestCameraPermission(); } else { this.getPosition(); this.watchLocation(); } } } }) .catch((error) => { console.log("ERROR LOADING USER", error.message); }); } renderTutoOldHome() { return ( {this.makeCardSearch()} ) } render() { if (false) { return this.renderBottomHome() } else return this.renderOldHome() } renderCurrentMarker() { if (this.state.currentMarker) { return ( {this.makeMarkerInformation()} ) } } makeDialogLoader() { return () } showMynetworkMap(usr = null) { const user = usr === null ? this.state.user : usr let {myNetwork} = this.state; this.setState({ filternetwork: myNetwork, page: 0, increasePas: 0, filternetworkTemp: myNetwork, loadingDialog: true }) return new Promise(() => { if (myNetwork !== undefined) { this.loadingMarkers(this.state.myPosition, myNetwork, this.state.value).then((data) => { let items = data ? data : [] this.setState({loadingDialog: false}) if (user.category !== undefined && user.category !== null) { const filter = items.filter(item => item.code_parrain === user.code_membre) this.treatNewData(this.state.myPosition, filter, true) } else this.treatNewData(this.state.myPosition, items, true) }).catch((e) => { this.setState({loadingDialog: false}) console.log("error j") console.log(e) }) } else { this.setState({loadingDialog: false}) console.log("error no net") } }) } showMyMembers() { let {code_membre} = this.state.user; if (code_membre !== undefined) { loadGroupeAgent(code_membre).then((data) => { if (data.success === 1) return this.setState({markers: data.datas}) }) } else console.log("error") } slidingComplete(itemSelected) { this.setState({value: this.filterOptions[itemSelected].value, valuePosition: itemSelected}); } makeDistanceDialog() { return ( { this.setState({dialogSliderVisible: false, showProgress: true}) setTimeout(() => this.filterPoint(), 300) } } cancelLabel={I18n.t("QUIT_")} okLabel={I18n.t('FILTER')} onCancel={() => { this.setState({dialogSliderVisible: false}) }} onTouchOutside={() => this.setState({dialogSliderVisible: false})}> {I18n.t('TEXT_FILTER_DISTANCE')} this.slidingComplete(item)} /> {(this.state.value === undefined ? 0 : this.state.value)} km {I18n.t("DISTANCE_ARROUND")} ) } showFilterDialog() { this.setState({dialogSliderVisible: true}) } async filterPoint() { const {value, myPosition, user, filternetwork} = this.state if (value !== undefined) { this.setState({page: 0}) const metervalue = value * 1000 let res = this.state.networks.filter(function (item) { return item.id === filternetwork.id }) let reseau = res[0]; this.loadingMarkers(myPosition, filternetwork, value).then((datas) => { this.treatNewData(this.state.prevRegion, datas, true) }).catch((e) => { this.setState({showProgress: false}) Alert.alert(I18n.t("ERROR_FILTER"), I18n.t("ERROR_FILTER_TEXT"), [{text: I18n.t("CANCEL")}, { text: I18n.t("RESTART"), onPress: () => { this.filterPoint() } }]) }) } else { this.setState({showProgress: false}) this.setState({ snack_visible: true, snack_text_message: "impossible de filtrer les élements" }) setTimeout(() => { this.setState({snack_visible: false}) }, 5000) } } userChangeMarker(item) { if (this.mapRef !== null && this.mapRef !== undefined) { const reg = { latitude: parseFloat(item.latitude), longitude: parseFloat(item.longitude), latitudeDelta: 0.03, longitudeDelta: 0.01, } this.mapRef.animateToCoordinate({ latitude: parseFloat(item.latitude), longitude: parseFloat(item.longitude) }, 1000) this.mapRef.animateToRegion(reg, 1000); } } geoLocatedAction() { return ( this.refocusMap()} size={48} > { this.onMapTypeChange(); } } size={48} > ) } makeNetworkChangeDialog() { return ( this.setState({dialogNetworkVisible: false})} onOk={result => { this.setState({dialogNetworkVisible: false, page: 0}); this.setState({showProgress: true, filternetwork: this.state.filternetworkTemp}); this.props.updateDefaultNetworkAction({ id_user: this.state.user.agentId, id_network: this.state.filternetworkTemp.id }); setTimeout(() => this.showFilterNetwork() , 500) }} > this.renderRow(item)}/> ) } renderDialogQRCodeScanner() { return ( {I18n.t('SCAN')} {I18n.t('BRING_YOUR_CAMERA_CLOSER_TO_SCAN_QR_CODE')} { this.setState({ showQRCodeScanner: false }); this.props.getQRCodeDetailAction(result.data); //fetchGetUserByIdQRCode(result.data); }} flashMode={RNCamera.Constants.FlashMode.off} /> { this.setState({ showQRCodeScanner: false }); }}/> ) } renderSearchUser() { return ( this.setState({ dialogSearchUser: false })} onOk={() => { console.log( "On ok search user===>>", this.state.userName, this.state.indicatif, this.state.isPhoneAssureSearch, this.state.isNumeroAssureSearch ); // Prépare le payload const payload = { dial_code: this.state.indicatif }; if (this.state.isPhoneAssureSearch) { payload.phone = this.state.userName; } else if (this.state.isNumeroAssureSearch) { payload.identification_number = this.state.userName; } else { payload.name = this.state.userName; } // Lance l'action this.props.searchUserAction(payload, true); this.setState({ dialogSearchUser: false }); }} > this.setState({ userName })} icon={ } /> {/* Mode téléphone */} this.setState({ isPhoneAssureSearch: true, isNumeroAssureSearch: false }) } style={{ marginHorizontal: 5 }} /> {/* Mode nom */} this.setState({ isPhoneAssureSearch: false, isNumeroAssureSearch: false }) } style={{ marginHorizontal: 5 }} /> {/* Mode NIU */} this.setState({ isPhoneAssureSearch: false, isNumeroAssureSearch: true }) } style={{ marginHorizontal: 5 }} /> {/* Scanner QR */} this.setState({ showQRCodeScanner: true })} style={{ marginHorizontal: 5 }} /> ); } renderDialogResultSearchUser() { const {resultSearchUserByName, errorGetAvisImposition} = this.props; console.log("resultGetAvisImposition", resultSearchUserByName); return ( {I18n.t('USAGER_SEARCH')} { Array.isArray(resultSearchUserByName.response) && (resultSearchUserByName.response.length) > 0 ? resultSearchUserByName.response.map((item) => ( { this.props.searchUserReset(); this.setState({ userName: '', displayDialogResultSearch: false }); console.log("Markers", this.state.markers); if (this.state.markers.filter((marker) => marker.phone === item.phone).length > 0) this.userChangeMarker(item); else { this.setState({ markers: [...this.state.markers, item], }, () => { this.userChangeMarker(item); }); this.setState({currentNetworkSize: this.state.currentNetworkSize + 1}) } }} style={[styles.paymentItem]}> {item.lastname} {`${item.phone} | ${item.email} | ${item.adresse}`} )) : {I18n.t('NO_USAGER_CORRESPONDING_TO_SEARCH')} } { this.props.searchUserReset(); this.setState({ displayDialogResultSearch: false }); }}/> ); } renderRow = (row) => ( this.onRowPress(row)}> {row.name} ); onRowPress(rowID) { this.setState({filternetworkTemp: rowID}) } showNewDialogNetwork() { this.setState({dialogNetworkVisible: true, loadingDialog: false}); } async showFilterNetwork() { const {myPosition, user, filternetwork} = this.state if (filternetwork !== undefined) { this.setState({showProgress: true}) this.loadingMarkers(this.state.myPosition, filternetwork, this.state.value, 0).then((data) => { this.setState({showProgress: false}) this.treatNewData(myPosition, data, true) }).catch((e) => { this.setState({ snack_visible: true, snack_text_message: "Probleme de connexion" }) console.log(e) }) } else console.log("error no net") } showBtnItineraire() { return ( ) } showBtnClose() { return ( ) } //markerManager: MarkerManager getHypervisorActionButton() { return ( this.refocusMap(false)} size={48} > { this.onMapTypeChange(); } } size={48} > ) } moveToMarker(item) { this.mapRef.animateToCoordinate({ latitude: parseFloat(item.latitude), longitude: parseFloat(item.longitude) }, 1000) this.setState({textreach: item.lastname, texta: true}) this.setState({markersearchfilter: []}); this.onMarkerPress(item) } refocusMap(zoom = true) { if (zoom) { if (this.mapRef && this.state.myPosition !== undefined) { this.mapRef.animateCamera({ center: { latitude: this.state.myPosition.latitude, longitude: this.state.myPosition.longitude }, pitch: 0, heading: 0, }, 1000) } } else { if (this.mapRef && this.state.myPosition !== undefined) { this.mapRef.animateCamera({ center: { latitude: this.state.myPosition.latitude, longitude: this.state.myPosition.longitude }, pitch: 0, heading: 0, altitude: 5, zoom: 12 }, 1000) } } if (this.map) this.map.focusToUser() } renderCardSeashItem(item) { return ( { this.moveToMarker(item) }}> {item.firstname === null ? item.adresse : item.firstname} {item.lastname} {item.network} ) } retrieveAllPoint(dial_code) { /* let markers= this.markerManager.getLocalMarkers() console.log( markers.length) if(markers.length>0){ console.debug("load from local") for (let p of markers) { console.log(` ${p.lastname}`); } this.markerManager.close(); this.setState({allpoint: [], loadingDialog: false}) }else*/ getMakersFrom(dial_code).then((data) => { new Promise((resolve, reject) => { try { const ds = data.datas this.setState({allpoint: ds, loadingDialog: false}) resolve(ds) } catch (e) { //Crashlytics.log(e.message) console.warn(e.message) reject(new Error(e.message)) } }).then((ds) => { // this.markerManager.insertMarkers(ds).then((res)=>{console.warn(res)}) this.onLoadMore() }).catch((e) => { this.setState({loadingDialog: false}) //Crashlytics.log(e.message) console.log("on get marker") Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ { text: I18n.t("NO"), onPress: () => { BackHandler.exitApp() } }, { text: I18n.t("YES"), onPress: () => { this.setState({loadingDialog: true}) if (dial_code !== null && dial_code !== undefined) this.retrieveAllPoint(dial_code) else this.requestCameraPermission() } } ], {cancelable: false} ) }) }).catch((e) => { console.log("on retreive>getmarkers", e.message) this.setState({loadingDialog: false}) if (this.state.allpoint.length <= 0) { console.log("no point") Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ { text: I18n.t("NO"), onPress: () => { BackHandler.exitApp() } }, { text: I18n.t("YES"), onPress: () => { if (this.state.allpoint.length <= 0) { this.setState({loadingDialog: true}) if (dial_code !== null && dial_code !== undefined) this.retrieveAllPoint(dial_code) else this.requestCameraPermission() } } } ], {cancelable: false} ) } }) } showLoadMoreView() { if (this.state.isNeedLoadMore) return ( {(this.state.markers.length === 0 ? this.state.markers.length : (this.state.markers.length))} / {this.state.currentNetworkSize} ) } showLoadingMapView() { if (this.state.isLoadingMap) return ( {I18n.t("LOADING_TEXT_MARKERS") + " " + this.filterOptions[this.state.increasePas].value + " km " + I18n.t("DISTANCE_ARROUND")} ) } loadingMarkers(myPosition, filternetwork, value, p = undefined) { return new Promise((resolve, reject) => { const {allpoint} = this.state let page = p !== undefined ? p : this.state.page let data = allpoint .filter((mark, index) => { const location = {longitude: parseFloat(mark.longitude), latitude: parseFloat(mark.latitude)} return geolib.getDistance(myPosition, location) <= (value * 1000) && mark.network === filternetwork.name }) .slice(0, (page + 1) * this.state.pas) try { const currentNetwork = allpoint .filter((mark, index) => { const location = {longitude: parseFloat(mark.longitude), latitude: parseFloat(mark.latitude)} return geolib.getDistance(myPosition, location) <= (value * 1000) && mark.network === filternetwork.name }) this.setState({ currentNetworkSize: currentNetwork.length, showProgress: false, currentNetworkMarkers: currentNetwork }) } catch (e) { console.debug("after " + e.message) } if (this.state.user.category !== 'geolocated' && this.state.user.category !== 'super' && this.state.user.category !== 'hyper') { if (data.length === 0) { this.loadMoreIfHasNoPoint(); } } console.debug("data:", data, "value" + value * 1000) resolve(data) }) } loadMoreIfHasNoPoint = () => { /* Alert.alert( 'INFORMATIONS', '' + this.state.increasePas , [ { text: I18n.t("NO"), onPress: () => { } }, { text: I18n.t("YES"), onPress: () => { } } ], { cancelable: false } ); */ if (this.state.increasePas === this.filterOptions.length - 1) { this.setState({ increasePas: 0, snack_visible: true, snack_text_message: I18n.t('NO_NETWORK_MARKER'), isLoadingMap: false }) setTimeout(() => { this.setState({snack_visible: false}) }, 5000); } else { if (this.state.increasePas + 1 !== this.filterOptions.length) { this.setState({increasePas: this.state.increasePas + 1, isLoadingMap: true}, () => { this.onLoadMore(); }); } } } treatNewData(pos, data, isFilter = false) { /* this.setState({ isLoadingMap: false }); */ let items = data; if (data.length > 0) { let corrent = items; if (isFilter) this.setState({showProgress: false}) if (corrent.length > 0) { this.setState({markers: corrent, prevRegion: pos}); } if (items.length < this.state.currentNetworkSize) { this.setState({isNeedLoadMore: true}) } else { if (isFilter && items.length <= 0) { this.setState({increasePas: 0, showProgress: false}, () => { this.loadMoreIfHasNoPoint(); }); } this.setState({isNeedLoadMore: false}) } } else { this.setState({showProgress: false, markers: data}); } } async treatPosition(myPosition) { const myLastPosition = this.state.myPosition; console.log("on treatposition") if (myPosition.longitude !== myLastPosition.longitude || myPosition.latitude !== myLastPosition.latitude) { this.setState({myPosition: myPosition}) if (this.map) this.map.focusToUser(); let indicatif = callingCodes([myPosition.longitude, myPosition.latitude]); if (Array.isArray(indicatif)) indicatif = "+" + indicatif[0]; this.setState({ indicatif: indicatif, enterPhone: indicatif }); this.getNetworks(indicatif); /* getOpenCagePositionInformation(myPosition).then((response) => { if (response) { if (response.results !== undefined) { if (response.results.length > 0) { let most = response.results[0] let {address_components, county, country} = most.components; let indicatif = callingCodes([myPosition.longitude, myPosition.latitude]); console.log("OPENCAGE RESPONSE", indicatif); this.setState({ address: address_components, textadress: most.formatted, indicatif: `+${indicatif}`, enterPhone: `+${indicatif}`, shortCountry: county, longCountry: country }); this.getNetworks(indicatif); } } else { console.log("on treat 1") Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ { text: I18n.t("NO"), onPress: () => { BackHandler.exitApp() } }, { text: I18n.t("YES"), onPress: () => { this.treatPosition(myPosition) } } ], {cancelable: false} ) } } else { console.log("on treat 2") Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ { text: I18n.t("NO"), onPress: () => { BackHandler.exitApp() } }, { text: I18n.t("YES"), onPress: () => { this.treatPosition(myPosition) } } ], {cancelable: false} ) } }).catch((error) => { //Crashlytics.log(error.message) console.log("on treat 3") Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ { text: I18n.t("NO"), onPress: () => { BackHandler.exitApp() } }, { text: I18n.t("YES"), onPress: () => { this.treatPosition(myPosition) } } ], {cancelable: false} ) });*/ const reg = { latitude: myPosition.latitude, longitude: myPosition.longitude, latitudeDelta: 0.03, longitudeDelta: 0.01, } this.setState({myPosition: myPosition, region: reg}); if (this.mapRef && !this.state.myPositionIsAnimated) { this.mapRef.animateCamera({ center: myPosition, pitch: 0, heading: 0, altitude: 5, zoom: 13 }, 1000) this.setState({myPositionIsAnimated: true}) } } } } const mapStateToProps = state => ({ loading: state.authKeyReducer.loading, authKey: state.authKeyReducer.authKey, error: state.authKeyReducer.error, loadingSaveOneSignal: state.saveOnesignalReducer.loading, resultSaveOneSignal: state.saveOnesignalReducer.result, errorSaveOneSignal: state.saveOnesignalReducer.error, loadingUpdateDefaultNetwork: state.updateDefaultNetworkReducer.loading, resultUpdateDefaultNetwork: state.updateDefaultNetworkReducer.result, errorUpdateDefaultNetwork: state.updateDefaultNetworkReducer.error, loadingSearchUserByName: state.searchUserReducer.loading, resultSearchUserByName: state.searchUserReducer.result, errorSearchUserByName: state.searchUserReducer.error, loadingGetQRCodeDetail: state.getQRCodeDetailReducer.loading, resultGetQRCodeDetail: state.getQRCodeDetailReducer.result, errorGetQRCodeDetail: state.getQRCodeDetailReducer.error, }); const mapDispatchToProps = dispatch => bindActionCreators({ getAuthApiKey, getWalletActivated, saveOnesignalIdsAction, saveOnesignalIdsReset, updateDefaultNetworkAction, updateDefaultNetworkReset, searchUserAction, searchUserReset, getQRCodeDetailReset, getQRCodeDetailAction }, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(Home); const markerDetails = StyleSheet.create({ solde: { backgroundColor: theme.accent, color: "white", marginLeft: 10, padding: 5, fontSize: 9, borderRadius: 100, }, title: { color: 'black', marginLeft: 10, flex: 1, fontSize: 11, fontWeight: 'bold', }, subtitle2: { color: 'black', marginLeft: 10, flex: 1, fontSize: 10, fontWeight: 'bold', }, subtitle: { color: 'black', marginLeft: 9, fontSize: 9 }, otherInformation: { marginLeft: 13, fontSize: 9 }, reseau: { marginLeft: 10, fontWeight: 'bold', color: theme.accent, fontSize: 10 }, container: { flex: 1, width: responsiveWidth(95), alignSelf: "center", paddingTop: responsiveHeight(1), marginBottom: responsiveHeight(1), backgroundColor: "white", justifyContent: 'flex-start' } }) const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#FFF', }, paymentItem: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", width: "100%", borderBottomColor: '#EEE', borderBottomWidth: 1 }, panelContainer: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, }, panel: { height: 600, padding: 20, backgroundColor: '#f7f5eee8', }, header: { backgroundColor: '#f7f5eee8', shadowColor: '#000000', paddingTop: 20, borderTopLeftRadius: 20, borderTopRightRadius: 20, }, panelHandle: { width: 40, height: 8, borderRadius: 4, backgroundColor: '#00000040', marginBottom: 10, }, panelTitle: { fontSize: 27, height: 35, }, panelSubtitle: { fontSize: 14, color: 'gray', height: 30, marginBottom: 10, }, panelButton: { padding: 20, borderRadius: 10, backgroundColor: '#318bfb', alignItems: 'center', marginVertical: 10, }, panelButtonTitle: { fontSize: 17, fontWeight: 'bold', color: 'white', }, fab: { position: 'absolute', margin: 16, right: 0, bottom: 0, }, networkname: { backgroundColor: theme.primary, padding: 5, color: "white", marginRight: 10, fontSize: 10, borderRadius: 12, }, input: { height: 60, width: '80%', marginTop: responsiveHeight(2), marginLeft: responsiveWidth(5), marginRight: responsiveWidth(5), borderRadius: 5, borderWidth: 1 }, myClusterTextStyle: { color: "white" }, myClusterStyle: { backgroundColor: theme.accent, height: 32, justifyContent: 'center', alignItems: 'center', width: 32, borderRadius: 16 }, rowContainer: { height: 52, flex: 1, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center', }, iconContainer: { marginRight: 16, }, mapmarker: { width: 52, height: 52, }, slidingup: { backgroundColor: "transparent", position: "absolute", height: slideHeight, bottom: 0, left: responsiveWidth(2.5), width: responsiveWidth(95), zIndex: 1 }, panelHeader: { height: 120, backgroundColor: '#b197fc', alignItems: 'center', justifyContent: 'center' }, favoriteIcon: { left: responsiveWidth(75), backgroundColor: theme.primary, width: 64, justifyContent: 'center', alignContent: 'center', bottom: -64, position: 'absolute', height: 64, padding: 8, zIndex: 1, borderRadius: 32, }, hambuger: { color: theme.primary, borderColor: theme.primary, borderWidth: 1, alignSelf: 'center', padding: 5, }, topBar: { position: 'absolute', alignSelf: 'center', justifyContent: 'center', borderRadius: 10, alignItems: 'center', marginTop: responsiveHeight(4), width: responsiveWidth(90), }, searchInput: { flex: 1, fontSize: 14 }, search: { width: responsiveWidth(70), height: responsiveHeight(10), backgroundColor: '#00000000', }, map: { width: responsiveWidth(100), height: responsiveHeight(100), }, backgroundd_drawer: { backgroundColor: '#000', }, cardsearch: { width: responsiveWidth(90), height: responsiveHeight(10), position: 'absolute', alignSelf: 'center', marginTop: 5, }, actionButtonIcon: { fontSize: 20, height: 22, color: 'white', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });