Rev 14838 | Rev 15104 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useState, useEffect, useRef } from 'react'
import { useForm } from 'react-hook-form'
import Datetime from 'react-datetime'
import axios from 'axios'
import SearchLocationInput from '../../../shared/SearchLocationInput'
import DescriptionInput from '../../../shared/DescriptionInput'
import { useHistory, useParams } from 'react-router-dom'
import 'react-datetime/css/react-datetime.css'
import { addNotification } from '../../../redux/notification/notification.actions'
import { useDispatch } from 'react-redux'
import parse from 'html-react-parser'
const FormView = ({
actionLink,
googleApiKey,
jobCategories: jsonCategories,
industries: jsonIndustries,
jobDescritions: jsonDescriptions
}) => {
const history = useHistory()
const { action } = useParams()
const dispatch = useDispatch()
const locationRef = useRef()
const { handleSubmit, register, setValue, errors, watch } = useForm()
const [inputErrors, setInputErrors] = useState({})
const [location, setLocation] = useState({})
const [isActive, setIsActive] = useState(false)
const [year, setYear] = useState(Date.now())
const [locationLabel, setLocationLabel] = useState('')
const [jobsDescriptions, setJobsDescriptions] = useState([])
const [jobsCategory, setJobsCategory] = useState([])
const [industry, setIndustry] = useState([])
const onSubmit = (data) => {
const formData = new FormData()
const submitData = {
...data,
...location,
last_date: year,
status: isActive ? 'a' : 'i'
}
if (!location.formatted_address) {
// locationRef.current.focus();
dispatch(addNotification({
style: 'danger',
msg: 'Es requerida una ubicación'
}))
return setInputErrors(prev => ({ ...prev, location: 'Es requerida una ubicación' }))
}
if (!submitData.description) {
// locationRef.current.focus();
dispatch(addNotification({
style: 'danger',
msg: 'Es requerida una descripcion'
}))
return
}
if (!year) {
return setInputErrors(prev => ({ ...prev, year: 'Este campo es requerido' }))
}
Object.entries(submitData).forEach((entries) => {
formData.append(entries[0], entries[1])
})
axios.post(actionLink, formData)
.then(({ data }) => {
if (!data.success) {
typeof data.data === 'string'
?
dispatch(addNotification({
style: 'danger',
msg: data.data
}))
: Object.entries(data.data).map(([key, value]) =>
value.map(err =>
dispatch(addNotification({
style: 'danger',
msg: `${key}: ${err}`
}))
)
)
return
}
history.goBack()
dispatch(addNotification({
style: 'success',
msg: `Registro ${action === 'edit' ? 'actualizado' : 'guardado'}`
}))
})
.catch(() => dispatch(addNotification({
style: 'danger',
msg: 'Ha ocurrido un error'
})))
}
useEffect(() => register('description'), [])
useEffect(() => {
if (action === 'edit') {
axios.get(actionLink)
.then(({ data }) => {
const respData = data.data
if (data.success) {
setLocationLabel(respData.formatted_address)
setLocation({
formatted_address: respData.formatted_address,
latitude: respData.latitude,
location_search: respData.location_search,
longitude: respData.longitude,
city1: respData.city1,
city2: respData.city2,
country: respData.country,
postal_code: respData.postal_code,
state: respData.state
})
setYear(respData.last_date)
respData.status === 'a' ? setIsActive(true) : setIsActive(false)
Object.entries(respData.job_category.category_options).map(([value, label]) => {
setJobsCategory(prev => [...prev, { value: value, label: label }])
})
Object.entries(respData.industry.industry_options).map(([value, label]) => {
setIndustry(prev => [...prev, { value: value, label: label }])
})
Object.entries(respData.job_description.description_options).map(([value, label]) => {
setJobsDescriptions(prev => [...prev, { value: value, label: label }])
})
setValue('name', respData.name)
setValue('description', respData.description)
setValue('job_description_id', respData.job_description.current_description.description_id);
setValue('job_category_id', respData.job_category.current_category.job_category_id);
setValue('industry_id', respData.industry.current_industry.industry_id);
}
})
}
}, [action])
useEffect(() => {
if (action === 'add') {
Object.entries(jsonCategories).map(([value, label]) => setJobsCategory(prev => [...prev, { value: value, label: label }]))
Object.entries(jsonIndustries).map(([value, label]) => setIndustry(prev => [...prev, { value: value, label: label }]))
Object.entries(jsonDescriptions).map(([value, label]) => setJobsDescriptions(prev => [...prev, { value: value, label: label }]))
}
}, [action])
return (
<section className="container">
<div className="row">
<div className="col-xs-12 col-md-12">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="form-group">
<label>Nombre</label>
<input
type="text"
name="name"
className="form-control"
ref={register({ required: true, maxLength: 120 })}
/>
{errors.name && <p>Este campo es requerido</p>}
</div>
<div className="form-group">
<label>Cargo a evaluar</label>
<select name="job_description_id" className="form-control" ref={register({ required: true })}>
{
jobsDescriptions.map(({ label, value }) => (
<option key={value} value={value}>{label}</option>
))
}
</select>
</div>
<div className="form-group">
<label>Categoría de Empleo</label>
<select name="job_category_id" className="form-control" ref={register({ required: true })}>
{
jobsCategory.map(({ label, value }) => (
<option key={value} value={value}>{label}</option>
))
}
</select>
</div>
<div className="form-group">
<label>Ubicación</label>
<SearchLocationInput
ref={locationRef}
value={locationLabel}
setValue={setLocationLabel}
googleApiKey={googleApiKey}
updateData={setLocation}
/>
{inputErrors.location && <p>{inputErrors.location}</p>}
</div>
<div className="form-group">
<label>Industria</label>
<select name="industry_id" className="form-control" ref={register({ required: true })}>
{
industry.map(({ label, value }) => (
<option key={value} value={value}>{label}</option>
))
}
</select>
</div>
<div className="form-group">
<label>Último día de aplicación</label>
<Datetime
dateFormat="DD-MM-YYYY"
timeFormat={false}
onChange={(e) => {
if (Date.now() > new Date(e.toDate()).getTime()) {
setYear(new Date(new Intl.DateTimeFormat('en-EN', year).format()))
return dispatch(addNotification({
style: 'danger',
msg: 'La fecha no puede ser igual o anterior a la actual'
}))
}
setYear(new Intl.DateTimeFormat({ year: 'numeric', month: 'numeric', day: 'numeric' }).format(e.toDate()))
}}
inputProps={{ className: 'form-control' }}
initialValue={
new Date(new Intl.DateTimeFormat('en-EN', action === 'edit' ? Date.parse(year) : year).format())
}
closeOnSelect
/>
{inputErrors.year && <p>{inputErrors.year}</p>}
</div>
<div className="form-group">
<label>Descripción</label>
<DescriptionInput
onChange={setValue}
name="description"
defaultValue={watch('description') ? parse(watch('description')) : ''}
/>
</div>
<div className="form-group">
<label>Estatus</label>
<div
className={`toggle btn btn-block btn-primary ${!isActive && 'off'}`}
data-toggle="toggle"
role="button"
style={{ width: '130px' }}
onClick={() => setIsActive(!isActive)}
>
<input
type="checkbox"
checked={isActive}
/>
<div className="toggle-group">
<label htmlFor="status" className="btn btn-primary toggle-on">Activo</label>
<label htmlFor="status" className="btn btn-light toggle-off">Inactivo</label>
<span className="toggle-handle btn btn-light"></span>
</div>
</div>
</div>
<div className="form-group">
<button
type="submit"
className="btn btn-primary btn-form-save-close mr-2"
>
Guardar
</button>
<button
type="button"
className="btn btn-secondary btn-edit-cancel"
onClick={() => history.goBack()}
>
Cancelar
</button>
</div>
</form>
</div>
</div>
</section>
)
}
export default FormView