import React from 'react'; import { Alert, Button, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View, } from 'react-native'; // Reduxs import { connect } from 'react-redux'; import { setContact } from '../Store/Actions/contacts'; // Helpers import Helpers from '../Lib/Helpers'; // Translations import i18n from '../../I18n'; // Icons import FontAwesome5 from 'react-native-vector-icons/FontAwesome5'; // Style import styles from '../../Resources/Styles/ContactDetailsStyle'; // UI Elements import { ButtonGroup, CheckBox, Overlay } from '@rneui/themed'; // Flash Messages import { showMessage } from 'react-native-flash-message'; // Picker import { Picker } from '@react-native-picker/picker'; // * Select List import SectionedMultiSelect from 'react-native-sectioned-multi-select'; // vCard parser import vCard from 'vcard-parser'; // BarCode Scanner import { BarCodeScanner } from 'expo-barcode-scanner'; // FormModel import { InputStatus } from '../Enums/InputStatus'; import { InputType } from '../Enums/InputType'; import { Contact, Form } from './../../Database'; import { InputData } from './../Models/Contact'; function mapStateToProps(state) { return { locale: state.locale.locale, contacts: state.contacts, currentUser: state.app.currentUser, mainColor: state.app.mainColor, }; } /** * @typedef {(user: import('./../Models/User').User, data: import('./../Models/Contact').Contact) => any} setContact */ const mapDispatchToProps = dispatch => { return { setContact: (user, data) => dispatch(setContact(user, data)), }; }; class ContactDetailsScreen extends React.Component { constructor(props) { super(props); // * This is to hold array of number for multiple inputs selects const multipleSelectInputs = Object.fromEntries( new Map( Form.getAll() .filter(form => form.type === InputType.SELECT_MULTIPLE) .map(form => [`input${form.id}`, { show: false, selectedItems: [] }]), ), ); const { contactId } = props.route.params; const paramContact = Contact.get(this.props.currentUser.id, contactId); if (paramContact) { this.state.action = 'edit'; } // * Init Contact data list const contact = paramContact ? this.initContact(paramContact) : this.initNewContact(Contact.new()); this.state.contact = contact; // * Setup All inputs State this.state.allInputs = Form.getAll().map(form => { const isDefault = form.status === InputStatus.DEFAULT; const inputData = Object.assign({}, InputData); inputData.title = form.placeholder[this.props.locale]; inputData.required = form.required; inputData.formSlug = form.slug; inputData.type = form.type; inputData.value = (!isDefault ? contact[form.slug] : contact.data.find(input => input.formSlug === form.slug)?.value) ?? ''; if (form.type === InputType.CHECKBOX) { inputData.value = (!isDefault ? contact[form.slug] : contact.data.find(input => input.formSlug === form.slug) ?.value) ?? []; } // * Init Multiple selete State if (form.type === InputType.SELECT_MULTIPLE) { const details = form.details.map( detail => JSON.parse(detail)[i18n.locale] ?? null, ); multipleSelectInputs[`input${form.id}`].selectedItems = ( inputData.value ?? [] ) .map((selectedDetail, detailIndex) => details.indexOf(selectedDetail)) .filter(detailIndex => detailIndex !== -1); console.debug('SELECT_MULTIPLE', inputData.value); console.debug(multipleSelectInputs[`input${form.id}`]); } return inputData; }); this.state.multipleSelectInputs = multipleSelectInputs; } // * --- STATE --- state = { /** @type {'add'|'edit} */ action: 'add', /** Is Working Saving Contact */ savingContact: false, /** @type {0|1} 0 is VISITS 1, is NOTES */ selectedVisitsOrNoteTab: 0, // * -- VISITS selectedVisitIndex: 0, showNewVisit: false, tmpVisitNote: '', newVisitTitle: '', // * -- VCARD /** @type {boolean|null} TRUE ok, FALSE refused, NULL not asked */ hasPermission: null, vCardData: { name: '', firstname: '', email: '', company: '', address: '', phone: '', }, /** @type {string|null} */ parsedType: null, /** @type {string[]} */ parsedDatas: [], /** @type {boolean} */ showQRcodevCard: false, /** @type {boolean} */ showDynContact: false, /** @type {boolean} */ scanned: false, }; // * --- METHODS // * - CONTACT METHODS saveContact() { this.setState({ savingContact: true, }); /** @type {typeof import('./../Models/Contact').ContactData} */ const contact = Object.assign({}, this.state.contact); const defaultForms = Form.getAll(InputStatus.DEFAULT); const lockedForms = Form.getAll(InputStatus.LOCKED); console.debug('save Contact'); let error = ''; // * VALIDATE SYSTEM FIELDS if ( !contact.email || contact.email.length < 5 || contact.email.length >= 255 || !Helpers.isEmailValid(contact.email) ) { console.debug('invalid prop email'); error = error.concat(i18n.t('error.invalid_email_address') + '.\n'); } const lockedFields = ['firstname', 'lastname', 'phone']; lockedFields.forEach(fieldName => { const form = lockedForms.find(inputForm => inputForm.name === fieldName); if (!form) { this.setState({ savingContact: false, }); throw new Error(`failed to get form ${fieldName}`); } if (contact[fieldName]?.length) { contact[fieldName] = contact[fieldName].trim(); } if (form.required && !contact[fieldName]?.length) { error = error.concat( i18n.t('contact_details_s.input_required', { placeholder: form.placeholder[i18n.locale], }) + '.\n', ); } if (contact[fieldName] && contact[fieldName]?.length >= 255) { console.debug(`invalid prop invalid_${fieldName}`); error = error.concat(i18n.t(`contact.invalid_${fieldName}`) + '.\n'); } }); contact.data.forEach(input => { const formToValidate = defaultForms.find( form => form.slug === input.formSlug, ); if (formToValidate.required && !input?.value?.length) { console.debug('invalid data ', input.formSlug); error = error.concat( i18n.t('contact_details_s.input_required', { placeholder: formToValidate.placeholder[i18n.locale], }) + '.\n', ); } if ( formToValidate.type === InputType.EMAIL || formToValidate.type === InputType.PHONE || formToValidate.type === InputType.TEXT ) { if (input?.value?.length) { input.value = input.value.trim(); } if (input?.value?.length > 255) { console.debug('invalid data ', input.formSlug); error = error.concat( i18n.t('contact_details_s.input_too_long', { placeholder: formToValidate.placeholder[i18n.locale], }) + '.\n', ); } } if ( input?.value?.length && formToValidate.type === InputType.EMAIL && !Helpers.isEmailValid(input.value) ) { console.debug('invalid data email ', input.formSlug); error = error.concat( i18n.t('contact_details_s.input_email', { placeholder: formToValidate.placeholder[i18n.locale], }) + '.\n', ); } }); if (error.length > 0) { this.setState({ savingContact: false, }); Alert.alert(i18n.t('global.warning') + ' !', error, [{ text: 'OK' }], { cancelable: false, }); return; } console.debug(contact.data); // * Stringify fields to store them contact.visits = JSON.stringify(contact.visits); contact.data = JSON.stringify(contact.data); contact.timestamp = new Date(); contact.synced = false; /** @type {setContact} */ const setContactHook = this.props.setContact; setContactHook(this.props.currentUser, contact); if (this.state.action === 'edit') { showMessage({ message: i18n.t('contact_details_s.contact_saved') + '.', type: 'success', duration: 500, }); setTimeout( () => this.setState({ savingContact: false, }), 800, ); } else { setTimeout(() => { this.props.navigation.navigate('ContactScreen', { contactAdded: true, }); }, 1500); } } /** * * @param {import('./../Models/Contact').Contact} contact * @returns {import('./../Models/Contact').ContactData} */ initContact(contact) { contact = contact.toJSON(); // * Stringify fields to store them contact.visits = JSON.parse(contact.visits); /** @type {Map} */ const originalData = new Map( [...JSON.parse(contact.data)].map(input => [input.formSlug, input]), ); contact.data = Form.getAll(InputStatus.DEFAULT).map( this.initField.bind(this), ); console.debug(contact.data); contact.data.map(input => { const originalInput = originalData.get(input.formSlug); // * Had this input before ? if (originalInput !== undefined) { // * Copy only if it is the same type input.value = input.type === originalInput.type ? originalInput.value : input.value; } }); return contact; } /** * Get new instance of Contact * @param {import('./../Models/Contact').ContactData} contact * @returns {import('./../Models/Contact').ContactData} */ initNewContact(contact) { // * Init DEFAULT Fields contact.data = Form.getAll(InputStatus.DEFAULT).map( this.initField.bind(this), ); contact.visits = []; contact.notes = ''; contact.app_user_id = this.props.currentUser.id; return contact; } /** * Setup input field * @param {import('./../Models/Form').Form} form * @returns {import('./../Models/Contact').InputDataType} */ initField(form) { const inputData = Object.assign({}, InputData); inputData.title = form.placeholder[this.props.locale]; inputData.required = form.required; inputData.formSlug = form.slug; inputData.type = form.type; inputData.value = ''; if ( form.type === InputType.CHECKBOX || form.type === InputType.SELECT_MULTIPLE ) { inputData.value = []; } return inputData; } // * - VISITS METHODS newVisit() { /** @type {typeof import('./../Models/Contact').ContactData} */ const contact = this.state.contact; contact.visits.unshift({ title: this.state.newVisitTitle, note: '' }); this.setState({ contact: contact, showNewVisit: false, selectedVisitIndex: 0, }); } deleteVisit() { Alert.alert( i18n.t('global.confirmation'), i18n.t('contact_details_s.confirm_visit_delete'), [ { text: i18n.t('global.no'), onPress: () => console.debug('Cancel Pressed'), style: 'cancel', }, { text: i18n.t('global.yes'), onPress: () => { /** @type {typeof import('./../Models/Contact').ContactData} */ const contact = this.state.contact; contact.visits.splice(this.state.selectedVisitIndex, 1); if (contact.visits.length === 0) { this.setState({ contact: contact, selectedVisitIndex: 0, }); } else { this.setState({ contact: contact, selectedVisitIndex: 0, }); } }, }, ], { cancelable: false }, ); } // * END - VISITS METHODS /** @type {import('expo-barcode-scanner').BarCodeScannedCallback} */ handleBarCodeScanned({ type, data }) { this.setState({ scanned: true }); if (!data.includes('VCARD')) { Alert.alert(i18n.t('contact_details_s.qrcode_not_vcard_format')); return; } /** @type {{ }} */ let datas = vCard.parse(data); /** @type {string[]} */ const tmpDatas = []; if (datas.n !== undefined) { const nx = Object.assign( { n1: [{ value: datas.n[0].value[0] }] }, { n2: [{ value: datas.n[0].value[1] }] }, ); datas = Object.assign(datas, nx); } if (datas.adr !== undefined) { const tmp = datas.adr[0].value; let tmpadr = ''; for (let i = 0; i < tmp.length; i++) { if (tmp[i].length > 0) { if (tmpadr.length > 0) { tmpadr = tmpadr + ', ' + tmp[i]; } else { tmpadr = tmp[i]; } } } datas.adr = [{ value: tmpadr }]; } Object.keys(datas).map((objectKey, index) => { if ( objectKey === 'email' || objectKey === 'adr' || objectKey === 'tel' || objectKey === 'org' || objectKey === 'n1' || objectKey === 'n2' ) { let value = datas[objectKey][0].value; if (typeof value === 'string') { tmpDatas.push(value); } } }); this.setState({ parsedType: 'vcard', parsedDatas: tmpDatas, showQRcodevCard: false, showDynContact: true, }); } // * END --- METHODS componentDidMount() { const { action } = this.props.route.params; this.setState({ action: action === 'edit' ? 'edit' : 'add' }); // BarCodeScanner.requestPermissionsAsync().then(res => { // this.setState({ hasPermission: res.status === 'granted' }); // }); } render() { return ( {/* LEFT SIDE -- FORMULARY VIEW */} {/* ALL INPUTS : They are sorted on sync by server */} {this.renderFormulary(Form.getAll()).map((input, inputIndex) => { input.key = inputIndex; return input; })} {/* BOTTOM SPACE */} {/* RIGHT SIDE -- VISITS AND NOTES */} {/* VISITS AND NOTES */} this.setState({ selectedVisitsOrNoteTab: index }) } /> {/* VISITS */} {this.state.selectedVisitsOrNoteTab === 0 && ( {this.state.contact.visits.length > 0 && ( { this.setState({ selectedVisitIndex: itemIndex, }); }}> {this.state.contact.visits.map((item, index) => { return ( ); })} )} {this.state.contact.visits.length === 0 && ( {i18n.t('contact_details_s.no_visits')}. )} { const localDatetimeString = new Date().toLocaleString( this.props.locale, ); this.setState({ showNewVisit: true, newVisitTitle: localDatetimeString.substring( 0, localDatetimeString.length - 3, ), }); }}> {this.state.contact.visits.length > 0 && ( this.deleteVisit()}> )} {this.state.contact.visits.length > 0 && ( { /** @type {typeof import('./../Models/Contact').ContactData} */ const contact = this.state.contact; contact.visits[this.state.selectedVisitIndex].note = text; this.setState({ contact: contact }); }} /> )} )} {/* NOTES */} {this.state.selectedVisitsOrNoteTab === 1 && ( { /** @type {typeof import('./../Models/Contact').ContactData} */ const contact = this.state.contact; contact.notes = text; this.setState({ contact: contact }); }} /> )} {/* ACTIONS BUTTONS on BOTTOM */} {/* {this.state.action === 'add' && (