Rev 6881 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useEffect, useRef } from 'react'import { axios, CKEDITOR_OPTIONS } from '../../utils'import { Button, Modal } from 'react-bootstrap'import { useForm } from 'react-hook-form'import { CKEditor } from 'ckeditor4-react'import { useDispatch, useSelector } from 'react-redux'import { addNotification } from '../../redux/notification/notification.actions'import { getMonths, getYears } from '../../utils/dates'import useFetchHelper from '../../hooks/useFetchHelper'import SwitchInput from '../UI/SwitchInput'import FormErrorFeedback from '../UI/FormErrorFeedback'import UbicationInput from '../../../shared/ubication-input/UbicationInput'const ExperienceModal = ({show = false,url = '',onClose = () => {},onComplete = () => {},isEdit = false,}) => {const addressKeys = useRef(['address1','address2','country','state','city1','city2','postal_code','latitude','longitude',])const labels = useSelector(({ intl }) => intl.labels)const { data: companySizes } = useFetchHelper('company-sizes')const { data: industries } = useFetchHelper('industries')const dispatch = useDispatch()const {register,errors,handleSubmit,setValue,clearErrors,watch,setError,reset,} = useForm()const isCurrent = watch('is_current', 'y')const handleModalOpen = () => {reset()onClose()}const getAddressHandler = (addresObject) => {addressKeys.current.map((addressKey) => setValue(addressKey, ''))const { address_components } = addresObjectif (address_components) {address_components.map((address_component) => {const address_component_name = address_component.long_nameconst address_component_type = address_component.types[0]switch (address_component_type) {case 'route':setValue('address1', address_component_name)breakcase 'sublocality':setValue('address2', address_component_name)breakcase 'locality':setValue('city1', address_component_name)breakcase 'administrative_area_level_2':setValue('city2', address_component_name)breakcase 'administrative_area_level_1':setValue('state', address_component_name)breakcase 'country':setValue('country', address_component_name)breakcase 'postal_code':setValue('postal_code', address_component_name)breakcase 'geometry':setValue('latitude', address_component.latitude)setValue('longitude', address_component.longitude)breakdefault:break}})}setValue('formatted_address', addresObject.formatted_address)clearErrors('formatted_address')}const onSubmit = handleSubmit((data) => {const formData = new FormData()Object.entries(data).map(([key, value]) => {if (!value) {return}formData.append(key, value)})axios.post(url, formData).then(({ data: response }) => {const { data, success } = responseif (!success) {typeof data === 'string'? dispatch(addNotification({ style: 'danger', msg: data })): Object.entries(data).map(([key, value]) =>setError(key, { message: value[0] }))return}onComplete(data)handleModalOpen()})})useEffect(() => {addressKeys.current.map((addressKey) => register(addressKey))register('formatted_address', { required: 'Este campo es requerido' })register('description', { required: true })register('is_current', { required: true })}, [])useEffect(() => {if (!isEdit) returnaxios.get(url).then(({ data: response }) => {const { data, success } = responseif (!success) {const errorMessage = typeof data === 'string' ? data : 'Error'dispatch(addNotification({ style: 'danger', msg: errorMessage }))return}Object.entries(data.experience).map(([key, value]) => value && setValue(key, value))Object.entries(data.location).map(([key, value]) => value && setValue(key, value))})}, [isEdit, show])useEffect(() => {console.log(errors)}, [errors])return (<Modal show={show} onHide={handleModalOpen}><Modal.Header><Modal.Title>{isEdit ? labels.edit : labels.add} - {labels.experience}</Modal.Title></Modal.Header><form onSubmit={onSubmit}><Modal.Body><div className="form-group"><inputtype="text"name="company"placeholder="Empresa"ref={register({required: 'este campo es requerido',})}/>{errors.company && (<FormErrorFeedback>{errors.company.message}</FormErrorFeedback>)}</div><div className="form-group"><selectname="industry_id"id="industry_id"ref={register({required: 'este campo es requerido',})}defaultValue=""><option value="" hidden>Industria</option>{Boolean(industries.length) &&industries.map(({ name, value }) => (<option value={value} key={value}>{name}</option>))}</select>{errors.industry_id && (<FormErrorFeedback>{errors.industry_id.message}</FormErrorFeedback>)}</div><div className="form-group"><selectname="company_size_id"id="company_size_id"ref={register({required: 'este campo es requerido',})}defaultValue=""><option value="" hidden>Tamaño de la Empresa</option>{Boolean(companySizes.length) &&companySizes.map(({ name, value }) => (<option value={value} key={value}>{name}</option>))}</select>{errors.company_size_id && (<FormErrorFeedback>{errors.company_size_id.message}</FormErrorFeedback>)}</div><div className="form-group"><inputtype="text"name="title"placeholder="Titulo"ref={register({required: 'este campo es requerido',})}/>{errors.title && (<FormErrorFeedback>{errors.title.message}</FormErrorFeedback>)}</div><div className="form-group datefm"><UbicationInputonGetAddress={getAddressHandler}settedQuery={watch('formatted_address')}/><i className="fa fa-map-marker" />{errors.formatted_address && (<FormErrorFeedback>{errors.formatted_address.message}</FormErrorFeedback>)}</div><div className="row profile-year" style={{ gap: '.5rem' }}><div className="input-c p-0"><div className="form-group"><selectname="from_month"id="from_month"ref={register({ required: 'este campo es requerido' })}defaultValue=""><option value="">Mes desde</option>{getMonths().map((month, id) => (<option key={id} value={id + 1}>{month}</option>))}</select>{errors.from_month && (<FormErrorFeedback>{errors.from_month.message}</FormErrorFeedback>)}</div></div><div className="input-c p-0"><div className="form-group"><selectname="from_year"ref={register({ required: 'este campo es requerido' })}defaultValue=""><option value="">Año desde</option>{getYears().map((year) => (<option key={year} value={year}>{year}</option>))}</select>{errors.from_year && (<FormErrorFeedback>{errors.from_year.message}</FormErrorFeedback>)}</div></div></div><label htmlFor="is_current"> Trabajo Actual</label><div className="form-group"><SwitchInputisChecked={watch('is_current' === 'y')}setValue={(val) => setValue('is_current', val ? 'y' : 'n')}/></div>{isCurrent !== 'y' && (<div className="row profile-year"><div className="input-c p-0"><div className="form-group"><selectname="to_month"id="to_month"ref={register}defaultValue=""><option value="">Mes hasta</option>{getMonths().map((month, id) => (<option key={id} value={id + 1}>{month}</option>))}</select>{errors.to_month && (<FormErrorFeedback>{errors.to_month.message}</FormErrorFeedback>)}</div></div><div className="input-c p-0"><div className="form-group"><selectname="to_year"id="to_year"ref={register}defaultValue=""><option value="">Año hasta</option>{getYears().map((year) => (<option key={year} value={year}>{year}</option>))}</select>{errors.to_year && (<FormErrorFeedback>{errors.to_year.message}</FormErrorFeedback>)}</div></div></div>)}<div className="form-group"><CKEditoronChange={(e) => setValue('description', e.editor.getData())}onInstanceReady={(e) => e.editor.setData(watch('description'))}config={CKEDITOR_OPTIONS}/>{errors.description && (<FormErrorFeedback>Este campo es requerido</FormErrorFeedback>)}</div></Modal.Body><Modal.Footer><Button size="sm" type="submit">{labels.accept}</Button><Button size="sm" variant="danger" onClick={handleModalOpen}>{labels.cancel}</Button></Modal.Footer></form></Modal>)}export default ExperienceModal