Rev 15322 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
/* eslint-disable no-mixed-spaces-and-tabs */
import axios from 'axios'
import { CKEditor } from 'ckeditor4-react'
import React, { useEffect, useState } from 'react'
import { useRef } from 'react'
import { useForm } from 'react-hook-form'
import { useDispatch } from 'react-redux'
import { addNotification } from '../../redux/notification/notification.actions'
import { config } from '../../shared/helpers/ckeditor_config'
import ToggleComponent from '../../shared/ToggleComponent'
import ConductModal from '../component/ConductModal'
const CONDUCTS_OPTIONS = {
0: 'No aplica',
1: 'Uno',
2: 'Dos',
3: 'Tres',
4: 'Cuatro'
}
const FormView = ({
actionLink = '',
setActionLink = function () { },
action = '',
setAction = function () { }
}) => {
// Hooks
const dispatch = useDispatch()
const selectInput = useRef(null)
const selectInput2 = useRef(null)
const {
setValue,
register,
handleSubmit
} = useForm()
//States
const [initObjectives, setInitObjectives] = useState('')
const [initFunctions, setInitFunctions] = useState('')
const [competencyOptions, setCompetencyOptions] = useState([])
const [competenciesSelected, setCompetenciesSelected] = useState([])
const [competencyTypeOptions, setCompetencyTypeOptions] = useState([])
const [jobsDescription, setJobsDescription] = useState([])
const [subordinatesSelected, setSubordinatesSelected] = useState([])
const [selectBehavior, setSelectBehavior] = useState({})
const [isShowModal, setIsShowModal] = useState(false)
const [isActive, setIsActive] = useState(false)
const onSubmit = (data) => {
const submitData = new FormData()
submitData.append('subordinates_selected', JSON.stringify(subordinatesSelected))
submitData.append('competencies_selected', JSON.stringify(competenciesSelected))
submitData.append('name', data.name)
submitData.append('job_description_id_boss', data.job_description_id_boss)
submitData.append('status', data.status ? 'a' : 'i')
submitData.append('objectives', data.objectives)
submitData.append('functions', data.functions)
axios.post(actionLink, submitData)
.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
}
setActionLink('')
setAction('')
dispatch(addNotification({
style: 'success',
msg: `Registro ${action === 'edit' ? 'actualizado' : 'añadido'}`
}))
})
}
const addCompetencies = () => {
const current_competency = competencyOptions.find(competency => competency.competency_id === selectInput.current.value)
if (competenciesSelected.some(competency => competency.competency_id === current_competency.competency_id)) {
return dispatch(addNotification({ style: 'danger', msg: 'Competencia ya agregada' }))
}
const competencies = new Set([current_competency, ...competenciesSelected])
setCompetenciesSelected([...competencies])
}
const addSubordinates = () => {
const current_subordinate = jobsDescription.find(subordinate => subordinate.job_description_id === selectInput2.current.value)
if (current_subordinate) {
const filterSubordinate = new Set([current_subordinate, ...subordinatesSelected])
setSubordinatesSelected([...filterSubordinate])
}
}
const deleteCompetency = (id) => setCompetenciesSelected(prev => prev.filter(competency => competency.competency_id !== id))
const deleteSubordinate = (id) => setSubordinatesSelected(prev => prev.filter(subordinate => subordinate.job_description_id !== id))
const editLevel = (val) => {
let i = 0
let j = 0
const competencies = [...competenciesSelected]
for (i = 0; i < competencies.length; i++) {
if (competencies[i].competency_id === selectBehavior.competency_id) {
for (j = 0; j < competencies[i].behaviors.length; j++) {
if (competencies[i].behaviors[j].behavior_id === selectBehavior.behavior_id) {
competencies[i].behaviors[j].level = val
break
}
}
break
}
}
setCompetenciesSelected(competencies)
setSelectBehavior({})
setIsShowModal(false)
}
const displayModal = (behavior) => {
setSelectBehavior(behavior)
setIsShowModal(true)
}
useEffect(() => {
register('status')
register('objectives')
register('functions')
}, [])
useEffect(() => {
axios.get(actionLink)
.then(({ data }) => {
if (!data.success) {
return dispatch(addNotification({
style: 'danger',
msg: 'Ha ocurrido un error'
}))
}
setCompetencyOptions(data.data['competencies'])
setCompetencyTypeOptions(data.data['competency_types'])
setJobsDescription(data.data['jobs_description'])
setIsActive(true)
if (action === 'edit') {
setInitObjectives(data.data['objectives'])
setInitFunctions(data.data['functions'])
setCompetenciesSelected(data.data['competencies_selected'])
setSubordinatesSelected(data.data['subordinates_selected'])
setValue('name', data.data['name'])
setValue('status', data.data['status'])
setValue('job_description_id_boss', data.data['job_description_id_boss'])
setIsActive((data.data['status'] == 'a') ? true : false)
}
})
}, [action])
useEffect(() => {
if (action === 'add') {
setInitFunctions(' ')
setInitObjectives(' ')
}
}, [action])
return (
<section className="content">
<div className="container-fluid">
<div className="row">
<form onSubmit={handleSubmit(onSubmit)}>
<div className='card'>
<div className="card-header">
<ul className="nav nav-tabs" id="myTab" role="tablist">
<li className="nav-item" role="presentation">
<button
className="nav-link active"
id="home-tab"
data-toggle="tab"
data-target="#home"
type="button"
role="tab"
aria-controls="home"
aria-selected="true"
>
General
</button>
</li>
<li className="nav-item" role="presentation">
<button
className="nav-link"
id="profile-tab"
data-toggle="tab"
data-target="#profile"
type="button"
role="tab"
aria-controls="profile"
aria-selected="false"
>
Competencias
</button>
</li>
<li className="nav-item" role="presentation">
<button
className="nav-link"
id="contact-tab"
data-toggle="tab"
data-target="#contact"
type="button"
role="tab"
aria-controls="contact"
aria-selected="false"
>
Dependientes
</button>
</li>
</ul>
</div>
<div className="card-body">
<div className="tab-content" id="myTabContent">
<div className="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
<div className="card p-2">
<div className="row">
<div className="col-md-4">
<div className="form-group">
<label>Nombre</label>
<input className='form-control' type="text" name='name' ref={register} />
</div>
</div>
<div className="col-md-4">
<div className="form-group">
<label>Superior</label>
<select className='form-control' name="job_description_id_boss" ref={register}>
<option value="">No aplica</option>
{
jobsDescription.map((description) =>
<option
key={description.job_description_id}
value={description.job_description_id}
>
{description.name}
</option>
)
}
</select>
</div>
</div>
<div className="col-md-4">
<div className="form-group">
<label>Estatus</label>
<ToggleComponent
setValue={(e) => setValue('status', e)}
currentValue={isActive}
/>
</div>
</div>
</div>
<div className="row">
<div className="form-group w-100">
<label>Objetivo</label>
{initObjectives &&
<CKEditor
onChange={(e) => setValue('objectives', e.editor.getData())}
onInstanceReady={(e) => e.editor.setData(initObjectives)}
config={config}
name="objectives"
/>
}
</div>
</div>
<div className="row">
<div className="form-group w-100">
<label>Funciones</label>
{initFunctions &&
<CKEditor
onChange={(e) => setValue('functions', e.editor.getData())}
onInstanceReady={(e) => e.editor.setData(initFunctions)}
config={config}
name="functions"
/>
}
</div>
</div>
</div>
</div>
<div className="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
<div className="card p-2">
<div className="row" style={{ gap: '.5rem' }}>
<div className="col-md-9">
<select className='form-control' ref={selectInput}>
<option value="">Seleccione</option>
{competencyOptions.map((competency) => {
const competency_type = competencyTypeOptions.find(type => type.competency_type_id === competency.competency_type_id)
return (
<option
key={competency.competency_id}
value={competency.competency_id}>
{`${competency_type?.name} - ${competency.name}`}
</option>
)
})
}
</select>
</div>
<div className='col-md-3'>
<button
type='button'
className='btn btn-primary'
onClick={addCompetencies}
>
Agregar Competencia
</button>
</div>
</div>
{
competenciesSelected.map(competency_selected => {
const competency_type = competencyTypeOptions.find(type => type.competency_type_id === competency_selected.competency_type_id)
return (
<div key={competency_selected.competency_type_id}>
<h3 className='my-2'>{`${competency_type.name} - ${competency_selected.name}`}</h3>
<table className='table table-bordered'>
<thead>
<tr>
<th>Elemento</th>
<th>Título</th>
<th>Nivel</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<tr>
<td>Competencia</td>
<td>{competency_selected.name}</td>
<td></td>
<td>
<button
type='button'
className='btn btn-primary'
onClick={() => deleteCompetency(competency_selected.competency_id)}
>
<i className='fa fa-ban mr-1' />
Borrar Competencia
</button>
</td>
</tr>
{
competency_selected.behaviors?.map(behavior => (
<tr key={behavior.behavior_id}>
<td>- Conducta Observable</td>
<td>{behavior.description}</td>
<td>{CONDUCTS_OPTIONS[behavior.level]}</td>
<td>
<button
type='button'
className='btn btn-primary'
onClick={() => displayModal(behavior)}
>
<i className='fa fa-edit mr-1' />
Editar Perfil
</button>
</td>
</tr>
))
}
</tbody>
</table>
</div>
)
})
}
</div>
<ConductModal
isShow={isShowModal}
onSubmit={(val) => editLevel(val)}
closeModal={() => setIsShowModal(false)}
/>
</div>
<div className="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">
<div className="card p-2">
<div className="row" style={{ gap: '.5rem' }}>
<div className="col-md-9">
<select className='form-control' ref={selectInput2}>
<option value="">Seleccione</option>
{
jobsDescription.map((subordinate) =>
<option
key={subordinate.job_description_id}
value={subordinate.job_description_id}
>
{subordinate.name}
</option>
)
}
</select>
</div>
<div className='col-md-3'>
<button
type='button'
className='btn btn-primary'
onClick={addSubordinates}
>
Agregar
</button>
</div>
</div>
<div className="d-block p-2">
<table className='table table-bordered'>
<thead>
<tr>
<th>Nombre</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
{
subordinatesSelected.map(subordinate =>
<tr key={subordinate.job_description_id}>
<td>{subordinate.name}</td>
<td>
<button
type='button'
className='btn btn-primary'
onClick={() => deleteSubordinate(subordinate.job_description_id)}
>
<i className='fa fa-ban mr-1' />
Borrar
</button>
</td>
</tr>
)
}
</tbody>
</table>
</div>
</div>
</div>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary btn-form-save-close mr-2">
Guardar & Cerrar
</button>
<button
type="button"
className="btn btn-secondary btn-edit-cancel"
onClick={() => setAction('')}
>
Cancelar
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</section >
)
}
export default FormView