Rev 5475 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
/* eslint-disable camelcase *//* eslint-disable react/prop-types */import { CKEditor } from 'ckeditor4-react'import React, { useEffect, useRef } from 'react'import { Button, Modal } from 'react-bootstrap'import { useForm } from 'react-hook-form'import { useDispatch } from 'react-redux'import styled from 'styled-components'import { addNotification } from '../../../redux/notification/notification.actions'import FormErrorFeedback from '../../../shared/form-error-feedback/FormErrorFeedback'import UbicationInput from '../../../shared/ubication-input/UbicationInput'import { axios, CKEDITOR_OPTIONS } from '../../../utils'const StyledSwitch = styled.label`position: relative;display: inline-block;width: 60px;height: 34px;input {opacity: 0;width: 0;height: 0;}.slider {position: absolute;cursor: pointer;top: 0;left: 0;right: 0;bottom: 0;background-color: #ccc;-webkit-transition: 0.4s;transition: 0.4s;}.slider:before {position: absolute;content: '';height: 26px;width: 26px;left: 4px;bottom: 4px;background-color: white;-webkit-transition: 0.4s;transition: 0.4s;}input:checked + .slider {background-color: #2196f3;}input:focus + .slider {box-shadow: 0 0 1px #2196f3;}input:checked + .slider:before {-webkit-transform: translateX(26px);-ms-transform: translateX(26px);transform: translateX(26px);}.slider.round {border-radius: 34px;}.slider.round:before {border-radius: 50%;}`const ExperienceModal = ({show = false,closeModal = () => {},setUserExperiences = () => {},postUrl = '',settedDescription = '',industriesOptions = [],companySizesOptions = [],months = [],}) => {const {register,errors,handleSubmit,setValue,clearErrors,getValues,watch,} = useForm()const dispatch = useDispatch()const isAddressEmpty = useRef(true)const addressKeys = useRef(['address1','address2','country','state','city1','city2','postal_code','latitude','longitude',])const handleModalOpen = () => {Object.keys(getValues()).map(([key]) => setValue(key, ''))closeModal()}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}})isAddressEmpty.current = false} else {isAddressEmpty.current = true}setValue('formatted_address', addresObject.formatted_address)clearErrors('formatted_address')}const getYears = () => {const date = new Date()const currentYear = date.getFullYear()let years = []for (let index = currentYear; index > currentYear - 100; index--) {years = [...years, index]}return years}const onSubmitHandler = async (data) => {const formData = new FormData()Object.entries(data).map(([key, value]) => {if (!value) return nullreturn formData.append(key, value)})await axios.post(postUrl, formData).then(({ data: response }) => {if (!response.success) {typeof response.data === 'string'? dispatch(addNotification({ style: 'danger', msg: response.data })): Object.entries(response.data).map(([key, value]) => {if (key in getValues())dispatch(addNotification({style: 'danger',msg: `${key}: ${Array.isArray(value) ? value[0] : value}`,}))return null})return}setUserExperiences(response.data)handleModalOpen()})}useEffect(() => {addressKeys.current.map((addressKey) => register(addressKey))register('formatted_address', {required: 'Este campo es requerido',})register('description', { required: true })}, [])useEffect(async () => {if (settedDescription) {const { data } = await axios.get(postUrl)if (!data.success) {addNotification({style: 'danger',msg:typeof data.data === 'string' ? data.data : 'Ha ocurrido un error',})return}Object.entries(data.data.experience).map(([key, value]) => value && setValue(key, value))Object.entries(data.data.location).map(([key, value]) => value && setValue(key, value))}}, [show])return (<Modal show={show} onHide={handleModalOpen}><Modal.Header><Modal.Title>Experiencia</Modal.Title></Modal.Header><form onSubmit={handleSubmit(onSubmitHandler)}><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>{industriesOptions &&Object.entries(industriesOptions).map(([key, value]) => (<option value={key} key={key}>{value}</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>{companySizesOptions &&Object.entries(companySizesOptions).map(([key, value]) => (<option value={key} key={key}>{value}</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>{months.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"><StyledSwitch className="switch"><inputtype="checkbox"name="is_current"id="is_current"value="y"ref={register}/><span className="slider round"></span></StyledSwitch></div>{!watch('is_current') && (<div className="row profile-year"><div className="input-c p-0"><div className="form-group"><selectname="to_month"id="to_month"ref={register({required: 'este campo es requerido',})}defaultValue=""><option value="">Mes hasta</option>{months.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({required: 'este campo es requerido',})}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(settedDescription)}config={CKEDITOR_OPTIONS}/>{errors.description && (<FormErrorFeedback>Este campo es requerido</FormErrorFeedback>)}</div></Modal.Body><Modal.Footer><Button size="sm" type="submit">Enviar</Button><Button size="sm" variant="danger" onClick={handleModalOpen}>Cancelar</Button></Modal.Footer></form></Modal>)}export default ExperienceModal