main.js 16.2 KB
Newer Older
1 2 3
var cont_experiencia = 0;
let cont_estudios = 0;
let cont_tecnologia = 0;
4

willgonzz committed
5
let cont_cargo = 0;
6 7 8
const experiencias = [];
const estudios = [];
const tecnologias = [];
9
let noValidateFlag = false;
10

willgonzz committed
11
const postulaciones = [];
12

13
var cont_referencias=0 ;
14 15
const referencias= [];

16

17

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
const formValidator = function () {
    'use strict'

    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.querySelectorAll('.needs-validation')
    var expForm = document.querySelector('#agregar-exp')


    // Loop over them and prevent submission
    Array.prototype.slice.call(forms)
        .forEach(function (form) {
            form.addEventListener('submit', function (event) {
                if (!form.checkValidity()) {
                    event.preventDefault()
                    event.stopPropagation()
33
                    noValidateFlag = true;
34 35 36 37 38 39
                }

                form.classList.add('was-validated')
            }, false)
        })
}
40 41 42 43 44 45 46 47
function carg(elemento) {
    var element = document.getElementById('descripcion');
    if(elemento == "otro"){
    element.style.display='block';
    }else{
    element.style.display='none';
    }
}
48
function agregarFieldExpierncia(event){
49 50 51 52
    //recoger del form
    const pairs = {};
    const formexp = document.querySelector("[name=experiencia-form]");
    const formData = new FormData(formexp);
53 54
    const reconocimientos = [{},{},{}];
    let pos_rec;
55 56
    let returnFlag = false;

57 58
    let requiredValues = ["institucion", "cargo", "fechaDesde"]

59
    formData.forEach((value, key)=>{
60
        if(requiredValues.includes(key)
61 62 63 64 65 66 67
        && value==="" && returnFlag == false){
            console.log(key, value)
            returnFlag = true;
        }
    });

    if(returnFlag===true){
68 69 70 71 72 73
        let message = "Rellene "
        for(let i=0;i<requiredValues.length;i++){
            message+=", "+requiredValues[i];
        }
        message += " como minimo."
        alert(message);
74 75 76
        return;
    }

77
    for (const [name, value] of formData){
78 79 80 81 82 83 84
        pos_rec = name.split("-");//rec-nombre-index
        if (pos_rec.length > 1) {
            reconocimientos[pos_rec[2]][pos_rec[1]] = value
        }
        else{
            pairs[name] = value
        }
85

86
    }
87
    pairs["reconocimientos"] = reconocimientos.filter(rec => rec.nombre);
88 89 90 91 92 93 94 95 96 97 98 99
    experiencias[cont_experiencia] = pairs;
    formexp.reset();
    //imprimir lista actualizada
    const div = document.querySelector("#experiencias")
    const div1 = document.createElement('div');
    let content='<ul>'
    for (let index = 0; index < experiencias.length; index++) {
        const exp = experiencias[index];
        if(exp==null) continue;
        content += `
        <li id="exp-${index}">        
            ${exp.institucion}
100
            <button type="button" onclick="eliminarExperiencia(event)"> <span class="glyphicon glyphicon-trash"></span> Eliminar</button>
101 102 103 104 105 106 107 108
        </li>
        
        `
    }
    content += "</ul>" 
    div1.innerHTML = content
    div.innerHTML = '';
    div.appendChild(div1);
109 110
    cont_experiencia++;
}
willgonzz committed
111 112 113 114 115 116
/*--------------------------------------------------------------------*/
function agregarFieldTecnologia(){
    //recoger del form
    const pairs = {};
    const formtecn = document.querySelector("[name=tecnologia-form]");
    const formData = new FormData(formtecn);
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

    //Validacion
    let returnFlag = false;

    let requiredValues = ["nombre", "nivel"]

    formData.forEach((value, key)=>{
        if(requiredValues.includes(key)
            && value==="" && returnFlag == false){
            console.log(key, value)
            returnFlag = true;
        }
    });

    if(returnFlag===true){
        let message = "Rellene "
        for(let i=0;i<requiredValues.length;i++){
            message+=", "+requiredValues[i];
        }
        message += " como minimo."
        alert(message);
        return;
    }

willgonzz committed
141 142 143 144
    for (const [name, value] of formData){
        pairs[name] = value
    }
    tecnologias[cont_tecnologia]={}
145
    tecnologias[cont_tecnologia]["tecnologia"]=pairs["tecnologia-id"]=="-1"?{nombre: pairs["tecnologia-nombre"]}:{id: pairs["tecnologia-id"],nombre:document.querySelector('[name=tecnologia-id] > option[value="'+pairs["tecnologia-id"]+'"]').innerHTML}
willgonzz committed
146 147 148
    tecnologias[cont_tecnologia]["nivel"]=pairs.nivel
    //tecnologias[cont_tecnologia] = pairs;
    formtecn.reset();
149
    document.querySelector("#tecnologia-nombre").classList.add('d-none')
willgonzz committed
150 151 152 153
    //imprimir lista actualizada
    const div = document.querySelector("#tecnologias")
    const div1 = document.createElement('div');
    console.log(tecnologias[0])
154

willgonzz committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    let content1='<ul>'
    for (let index = 0; index < tecnologias.length; index++) {
        const tecn = tecnologias[index];
        if(tecn==null) continue;
        content1 += `
        <li id="tecn-${index}">        
            ${tecn.tecnologia.nombre} 
            <button type="button" onclick="eliminarTecnologia(event)">Eliminar</button>
        </li>
        
        `
    }
    content1 += "</ul>" 
    div1.innerHTML = content1
    div.innerHTML = '';
    div.appendChild(div1);
    cont_tecnologia++;
172
}
173

willgonzz committed
174 175

/*--------------------------------------------------------------------*/
176
function eliminarExperiencia(event) {
177 178 179
    //eliminar del array
    experiencias[event.target.parentElement.id.split("-")[1]]=null
    //eliminar en html
180 181
    event.target.parentElement.remove()
}
willgonzz committed
182 183 184 185 186 187 188 189
/*----------------------------------------------------------------- */
function eliminarTecnologia(event) {
    //eliminar del array
    tecnologias[event.target.parentElement.id.split("-")[1]]=null
    //eliminar en html
    event.target.parentElement.remove()
}
/*----------------------------------------------------------------- */
190 191 192 193
function serializeJSON (form) {
    // Create a new FormData object
    const formData = new FormData(form);

194

195 196 197 198 199
    // Create an object to hold the name/value pairs
    const pairs = {};

    // Add each name/value pair to the object
    for (const [name, value] of formData) {
200
        pairs[name] = value
201
    }
202 203 204
    pairs["experiencias"] = experiencias.filter(exp => exp)//eliminacion de nulos
    pairs["estudios"] = estudios.filter(est => est)//eliminacion de nulos
    pairs["tecnologias"] = tecnologias.filter(tec => tec)//eliminacion de nulos
willgonzz committed
205
    pairs["postulaciones"] = postulaciones.filter(car => car)//eliminacion de nulos
206
    pairs["referencias"] = referencias.filter(tec => tec)
207

208 209 210 211 212 213
    
    // Return the JSON string
    return JSON.stringify(pairs, null, 2);
}

async function postData(url = '', data = {}) {
214 215
    var token = document.querySelector("meta[name='_csrf']").content;
    var headerxs = document.querySelector("meta[name='_csrf_header']").content;
216
    // Default options are marked with *
217
    let senddata = {
218 219 220 221 222
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
223 224
            'Content-Type': 'application/json',
            // 'Content-Type': 'application/x-www-form-urlencoded',
225 226 227 228
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: data // body data type must match "Content-Type" header
229 230 231
    }
    senddata["headers"][headerxs] = token;
    const response = await fetch(url, senddata);
232 233
    return response; // parses JSON response into native JavaScript objects
}
234
formValidator()
235 236
form = document.querySelector("form");
form.addEventListener("submit",(evt)=>{
237 238 239 240 241
    // if (!form.checkValidity()) {
    //     evt.preventDefault()
    //     evt.stopPropagation()
    // }
    // form.classList.add('was-validated')
242 243 244 245 246 247 248 249 250 251 252 253
    if(!noValidateFlag){
        postData('postulante', serializeJSON(form))
            .then(response => {
                if(response.status==200 || response.status==302){
                    location.replace(response.url);
                }else{
                    console.log(response.text().then(value => console.log(value)))
                }
            });
        evt.preventDefault();
    }
    noValidateFlag = false
254 255
} );

Joel Florentin committed
256
document.querySelector("#btn-new-tech").addEventListener('click',()=>{document.querySelector("#tecnologia-nombre").classList.remove('d-none')})
257 258 259 260 261 262 263 264


//Metodos para Estudios



function agregarFieldEstudio(){
    //recoger del form
265 266
    let pairs = {};
    const formest = document.querySelector("[name=estudio-form]");
267
    const formData = new FormData(formest);
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

    //Validacion
    let returnFlag = false;

    let requiredValues = ["tipoDeEstudio", "institucion", "estado", "fechaDesde", "temaDeEstudio"]

    formData.forEach((value, key)=>{
        if(requiredValues.includes(key)
            && value==="" && returnFlag == false){
            console.log(key, value)
            returnFlag = true;
        }
    });

    if(returnFlag===true){
        let message = "Rellene "
        for(let i=0;i<requiredValues.length;i++){
            message+=", "+requiredValues[i];
        }
        message += " como minimo."
        alert(message);
        return;
    }


293 294
    const estudioReconocimiento = [{},{},{}];
    let pos_rec;
295
    for (const [name, value] of formData){
296 297 298 299 300 301 302 303
        pos_rec = name.split("-");//rec-nombre-index
        if (pos_rec.length > 1) {
            estudioReconocimiento[pos_rec[2]][pos_rec[1]] = value
        }
        else{
            pairs[name] = value
        }
        
304
    }
305 306 307 308 309 310
    let nombre = pairs["institucion"]
    delete pairs["institucion"]
    console.log(pairs)
    pairs["institucion"] = {  }
    pairs["institucion"].nombre = nombre
    pairs["institucion"].subNombre = ""
311
    pairs["estudioReconocimiento"] = estudioReconocimiento.filter(rec => rec.nombre);
312 313 314 315 316 317 318 319 320 321 322 323
    estudios[cont_estudios] = pairs;
    formest.reset();
    //imprimir lista actualizada
    const div = document.querySelector("#estudios")
    const div1 = document.createElement('div');
    let content='<ul>'
    
    for (let index = 0; index < estudios.length; index++) {
        const est = estudios[index];
        if(est==null) continue;
        content += `
        <li id="est-${index}">        
324
            ${est.institucion.nombre}
325 326 327 328 329 330 331 332 333 334 335 336 337
            <button type="button" onclick="eliminarEstudio(event)">Eliminar</button>
        </li>
        
        `
    }
    content += "</ul>" 
    div1.innerHTML = content
    div.innerHTML = '';
    div.appendChild(div1);
    cont_estudios++;

}

338 339 340 341




342 343 344 345 346 347
function eliminarEstudio(event) {
    //eliminar del array
    estudios[event.target.parentElement.id.split("-")[1]]=null
    //eliminar en html
    event.target.parentElement.remove()
}
willgonzz committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
/*--------------------------------------------------------------------*/
function agregarFieldCargo(){
    //recoger del form
    const pairs = {};
    const formcar = document.querySelector("[name=cargo-form]");
    const formData = new FormData(formcar);

    //Validacion
    let returnFlag = false;

    let requiredValues = ["nombre"]

    formData.forEach((value, key)=>{
        if(requiredValues.includes(key)
            && value==="" && returnFlag == false){
            console.log(key, value)
            returnFlag = true;
        }
    });

    if(returnFlag===true){
        let message = "Rellene "
        for(let i=0;i<requiredValues.length;i++){
            message+=", "+requiredValues[i];
        }
        message += " como minimo."
        alert(message);
        return;
    }
377

willgonzz committed
378 379 380 381
    for (const [name, value] of formData){
        pairs[name] = value
    }
    console.log(pairs)
382 383 384 385 386 387 388 389 390
    for(let i=0;i<cont_cargo;i++){
        if(postulaciones[i]!==null){
            if(postulaciones[i]["id"]===pairs["cargo-id"]){
                alert("Ya has agregado ese cargo!")
                cont_cargo--;
                return;
            }
        }
    }
willgonzz committed
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    postulaciones[cont_cargo]={}
    postulaciones[cont_cargo]["id"]=pairs["cargo-id"]
    //postulaciones[cont_cargo]["cargo"]=pairs["cargo-id"]=="-1"?{nombre: pairs["cargo-nombre"]}:{id: pairs["cargo-id"],nombre:document.querySelector('[name=cargo-id] > option[value="'+pairs["cargo-id"]+'"]').innerHTML}
    console.log(postulaciones)
    formcar.reset();
    //imprimir lista actualizada
    const div = document.querySelector("#cargos")
    const div1 = document.createElement('div');

    let content1='<ul>'
    for (let index = 0; index < postulaciones.length; index++) {
        const car = postulaciones[index];
        if(car==null) continue;
        content1 += `
        <li id="car-${index}">
406
            ${document.querySelector('[name=cargo-id] > option[value="'+car.id+'"]').innerHTML}        
willgonzz committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
            <button type="button" onclick="eliminarCargoPostulante(event)">Eliminar</button>
        </li>
        
        `
    }
    content1 += "</ul>" 
    div1.innerHTML = content1
    div.innerHTML = '';
    div.appendChild(div1);
    cont_cargo++;
}

/*---------------------------------------------------------------------------------------------------*/
function eliminarCargoPostulante(event) {
    //eliminar del array
    postulaciones[event.target.parentElement.id.split("-")[1]]=null
    //eliminar en html
    event.target.parentElement.remove()
}
/*--------------------------------------------------------------------*/
427 428


429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
//evento para cambio de ciudad segun departamento
const depSelect = document.querySelector("#departamentos");
depSelect.addEventListener("change",evt => listarCiudades(evt.target.value))
listarCiudades(depSelect.value);
//variable ciudades esta declarada en el jsp
/**
 * Listar todas las ciudades en el select de ciudades
 * @param {*} depId 
 */
function listarCiudades(depId){
    const ciuAmostrar = ciudades.filter(c=>c.departamentoId==depId);
    const ciudad = document.querySelector("select[name=ciudadId]");
    const frag = document.createDocumentFragment();
    for (const ciu of ciuAmostrar) {
        const opt = document.createElement("option");    
        opt.value = ciu.id;
        opt.innerHTML = ciu.nombre;
        opt.setAttribute("data-departamentoId",ciu.departamentoId);
        frag.appendChild(opt)
    }
    ciudad.replaceChildren(frag);
    
    
}
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531



function agregarFieldReferencia(event){
    //recoger del form
    const pairs = {};
    const formexp = document.querySelector("[name=referencia-form]");
    const formData = new FormData(formexp);
    const referenciaPersonal = [{},{},{}];
    let pos_rec;
    let returnFlag = false;

    let requiredValues = ["nombre", "relacion", "telefono"]

    formData.forEach((value, key)=>{
        if(requiredValues.includes(key)
        && value==="" && returnFlag == false){
            console.log(key, value)
            returnFlag = true;
        }
    });

    if(returnFlag===true){
        let message = "Rellene "
        for(let i=0;i<requiredValues.length;i++){
            message+=", "+requiredValues[i];
        }
        message += " como minimo."
        alert(message);
        return;
    }

    for (const [name, value] of formData){
        pos_rec = name.split("-");//rec-nombre-index
        if (pos_rec.length > 1) {
            referenciaPersonal[pos_rec[2]][pos_rec[1]] = value
        }
        else{
            pairs[name] = value
        }

    }
    pairs["referenciaPersonal"] = referenciaPersonal.filter(rec => rec.nombre);
    referencias[cont_referencias] = pairs;
    formexp.reset();
    //imprimir lista actualizada
    const div = document.querySelector("#referencia")
    const div1 = document.createElement('div');
    let content='<ul>'
    for (let index = 0; index < referencias.length; index++) {
        const exp = referencias[index];
        if(exp==null) continue;
        content += `
        <li id="exp-${index}">        
            ${exp.nombre}
            <button type="button" onclick="eliminarReferencia(event)"> <span class="glyphicon glyphicon-trash"></span> Tras</button>
        </li>
        
        `
    }
    content += "</ul>" 
    div1.innerHTML = content
    div.innerHTML = '';
    div.appendChild(div1);
    cont_referencias++;
}

/*----------------------------------------------------------------- */
function eliminarReferencia(event) {
    //eliminar del array
    referencias[event.target.parentElement.id.split("-")[1]]=null
    //eliminar en html
    event.target.parentElement.remove()
}
/*----------------------------------------------------------------- */