Rev 15125 | 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 'react-datetime/css/react-datetime.css'
import axios from 'axios'
import SearchLocationInput from '../../../shared/SearchLocationInput'
import { addNotification } from '../../../redux/notification/notification.actions'
import { useDispatch } from 'react-redux'
import { CKEditor } from 'ckeditor4-react'
import { config } from '../../../shared/helpers/ckeditor_config'
const FormView = ({
actionLink,
googleApiKey,
jobCategories: jsonCategories,
industries: jsonIndustries,
jobDescritions: jsonDescriptions,
action,
setAction
}) => {
const dispatch = useDispatch()
const locationRef = useRef()
const { handleSubmit, register, setValue, errors } = useForm()
const [inputErrors, setInputErrors] = useState({})
const [location, setLocation] = useState({})
const [isActive, setIsActive] = useState(false)
const [year, setYear] = useState(new Date())
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: new Date(year).toLocaleDateString('en', { year: 'numeric', month: '2-digit', day: '2-digit' }),
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
}
setAction('')
dispatch(addNotification({
style: 'success',
msg: `Registro ${action === 'edit' ? 'actualizado' : 'guardado'}`
}))
})
.catch(() => dispatch(addNotification({
style: 'danger',
msg: 'Ha ocurrido un error'
})))
}
useEffect(() => register('description'), [])
const getData = ({ editor }) => {
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
})
editor.setData(respData.description)
setYear(new Date(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('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)
}
})
}
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) => setYear(e.toDate())}
inputProps={{ className: 'form-control' }}
value={year}
closeOnSelect
/>
{inputErrors.year && <p>{inputErrors.year}</p>}
</div>
<div className="form-group">
<label>Descripción</label>
<CKEditor
onChange={(e) => setValue('description', e.editor.getData())}
onInstanceReady={action === 'edit' && getData}
config={config} />
</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={() => setAction('')}
>
Cancelar
</button>
</div>
</form>
</div>
</div>
</section>
)
}
export default FormView