Rev 6770 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useEffect, useRef, useState } from 'react'
import { useForm } from 'react-hook-form'
import { CKEditor } from 'ckeditor4-react'
import { useDispatch, useSelector } from 'react-redux'
import { Button, Modal } from 'react-bootstrap'
import { addNotification } from '../../redux/notification/notification.actions'
import { axios, CKEDITOR_OPTIONS } from '../../utils'
import { getYears } from '../../utils/dates'
import Spinner from '../UI/Spinner'
import FormErrorFeedback from '../UI/FormErrorFeedback'
import SwitchInput from '../UI/SwitchInput'
import UbicationInput from '../../../shared/ubication-input/UbicationInput'
import useFetchHelper from '../../hooks/useFetchHelper'
const EducationModal = ({
show = false,
closeModal = () => {},
postUrl = '',
setEducations = () => {},
settedDescription = '',
}) => {
const [modalLoading, setModalLoading] = useState(false)
const { data: degrees } = useFetchHelper('degrees')
const isAddressEmpty = useRef(true)
const addressKeys = useRef([
'address1',
'address2',
'country',
'state',
'city1',
'city2',
'postal_code',
'latitude',
'longitude',
])
const labels = useSelector(({ intl }) => intl.labels)
const dispatch = useDispatch()
const {
register,
errors,
handleSubmit,
setValue,
clearErrors,
getValues,
watch,
} = useForm()
const handleModalOpen = () => {
Object.keys(getValues()).map(([key]) => setValue(key, ''))
closeModal()
}
const getAddressHandler = (addresObject) => {
addressKeys.current.map((addressKey) => {
setValue(addressKey, '')
})
const { address_components } = addresObject
if (address_components) {
address_components.map((address_component) => {
const address_component_name = address_component.long_name
const address_component_type = address_component.types[0]
switch (address_component_type) {
case 'route':
setValue('address1', address_component_name)
break
case 'sublocality':
setValue('address2', address_component_name)
break
case 'locality':
setValue('city1', address_component_name)
break
case 'administrative_area_level_2':
setValue('city2', address_component_name)
break
case 'administrative_area_level_1':
setValue('state', address_component_name)
break
case 'country':
setValue('country', address_component_name)
break
case 'postal_code':
setValue('postal_code', address_component_name)
break
case 'geometry':
setValue('latitude', address_component.latitude)
setValue('longitude', address_component.longitude)
break
default:
break
}
})
isAddressEmpty.current = false
} else {
isAddressEmpty.current = true
}
setValue('formatted_address', addresObject.formatted_address)
clearErrors('formatted_address')
}
const onSubmitHandler = async (data) => {
setModalLoading(true)
const formData = new FormData()
Object.entries(data).map(([key, value]) => {
if (key === 'is_current') {
value === 'y'
? formData.append('to_year', new Date().getFullYear())
: formData.append(key, value)
}
formData.append(key, value)
})
await axios.post(postUrl, formData).then((response) => {
const resData = response.data
if (resData.success) {
setEducations(resData.data)
handleModalOpen()
} else {
const resError = resData.data
if (resError.constructor.name === 'Object') {
Object.entries(resError).map(([key, value]) => {
if (key in getValues()) {
dispatch(
addNotification({
style: 'danger',
msg: `${key}: ${Array.isArray(value) ? value[0] : value}`,
})
)
}
})
} else {
dispatch(addNotification({ style: 'danger', msg: resError }))
}
}
})
setModalLoading(false)
}
useEffect(() => {
addressKeys.current.map((addressKey) => register(addressKey))
register('formatted_address', { required: 'Este campo es requerido' })
register('description', { required: true })
register('is_current')
}, [])
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',
})
setModalLoading(false)
return
}
Object.entries(data.data.education).map(([key, value]) =>
setValue(key, value)
)
Object.entries(data.data.location).map(([key, value]) =>
setValue(key, value)
)
isAddressEmpty.current = false
}
}, [show])
return (
<Modal show={show} onHide={handleModalOpen}>
<Modal.Header closeButton>
<Modal.Title>{labels.education}</Modal.Title>
</Modal.Header>
<form onSubmit={handleSubmit(onSubmitHandler)}>
<Modal.Body>
<div className="form-group">
<select
name="degree_id"
id="degree_id"
defaultValue=""
ref={register({
required: labels.error_field_empty,
})}
>
<option value="" hidden>
{labels.degree}
</option>
{degrees &&
Object.entries(degrees).map(([key, value]) => (
<option value={key} key={key}>
{value}
</option>
))}
</select>
{errors.degree_id && (
<FormErrorFeedback>{errors.degree_id.message}</FormErrorFeedback>
)}
</div>
<div className="form-group">
<input
type="text"
name="university"
id="university"
placeholder="Universidad"
ref={register({
required: labels.error_field_empty,
})}
/>
{errors.university && (
<FormErrorFeedback>{errors.university.message}</FormErrorFeedback>
)}
</div>
<div className="form-group">
<input
type="text"
name="field_of_study"
id="field_of_study"
placeholder="Campo de estudio"
ref={register({
required: labels.error_field_empty,
})}
/>
{errors.field_of_study && (
<FormErrorFeedback>
{errors.field_of_study.message}
</FormErrorFeedback>
)}
</div>
<div className="form-group datefm">
<UbicationInput
onGetAddress={getAddressHandler}
settedQuery={watch('formatted_address')}
/>
<i className="fa fa-map-marker"></i>
{errors.formatted_address && (
<FormErrorFeedback>
{errors.formatted_address.message}
</FormErrorFeedback>
)}
</div>
<div className="form-grop">
<input
type="text"
name="grade_or_percentage"
id="grade_or_percentage"
placeholder="Grado o porcentaje"
ref={register({
required: labels.error_field_empty,
})}
/>
{errors.grade_or_percentage && (
<FormErrorFeedback>
{errors.grade_or_percentage.message}
</FormErrorFeedback>
)}
</div>
<div className="row profile-year d-flex align-items-center pt-1">
<div className="input-c p-0 pr-2">
<div className="form-group">
<select
name="from_year"
id="from_year"
defaultValue=""
ref={register({
required: labels.error_field_empty,
})}
>
<option value="">{labels.from_year}</option>
{getYears().map((year) => (
<option key={year} value={year}>
{year}
</option>
))}
</select>
{errors.from_year && (
<FormErrorFeedback>
{errors.from_year.message}
</FormErrorFeedback>
)}
</div>
</div>
{!watch('is_current') && (
<div className="input-c p-0 pr-2">
<div className="form-group">
<select
name="to_year"
id="to_year"
defaultValue=""
ref={register({
required: labels.error_field_empty,
})}
>
<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 className="input-c p-0">
<label htmlFor="is_current">{labels.current_education}</label>
<SwitchInput
setValue={(val) => setValue('is_current', val ? 'y' : 'n')}
/>
</div>
</div>
<div className="form-group">
<CKEditor
onChange={(e) => setValue('description', e.editor.getData())}
onInstanceReady={(e) => e.editor.setData(settedDescription)}
config={CKEDITOR_OPTIONS}
/>
{errors.description && (
<FormErrorFeedback>{labels.error_field_empty}</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>
{modalLoading && <Spinner />}
</Modal>
)
}
export default EducationModal