diff --git a/curriculumsearch/src/main/resources/static/main.js b/curriculumsearch/src/main/resources/static/main.js index 6652c4a..9070da3 100644 --- a/curriculumsearch/src/main/resources/static/main.js +++ b/curriculumsearch/src/main/resources/static/main.js @@ -13,7 +13,18 @@ const postulaciones = []; var cont_referencias=0 ; const referencias= []; +form = document.querySelector("form"); +const depSelect = document.querySelector("#departamentos"); + +console.log("saddsa", bootstrap) +const modalCargo = bootstrap.Modal.getOrCreateInstance(document.getElementById('cargoForm')) +const modalExperiencia = bootstrap.Modal.getOrCreateInstance(document.getElementById('experienciaForm')) +const modalTecnologia = bootstrap.Modal.getOrCreateInstance(document.getElementById('tecnologiaForm')) +const modalEstudio = bootstrap.Modal.getOrCreateInstance(document.getElementById('estudioForm')) +const modalReferencia = bootstrap.Modal.getOrCreateInstance(document.getElementById('referenciaForm')) +//variable ciudades esta declarada en el jsp +/*-----------------Definicion de funciones de poblacion de elementos y validaciones----------------------------------------*/ const formValidator = function () { 'use strict' @@ -37,114 +48,66 @@ const formValidator = function () { }, false) }) } -function carg(elemento) { - var element = document.getElementById('descripcion'); - if(elemento == "otro"){ - element.style.display='block'; - }else{ - element.style.display='none'; +function fechasMaxMin(){ + var today = new Date(); + var dd = today.getDate()-1; + var mm = today.getMonth() + 1; //January is 0! + var yyyy = today.getFullYear(); + + if (dd < 10) { + dd = '0' + dd; } -} -function agregarFieldExpierncia(event){ - //recoger del form - const pairs = {}; - const formexp = document.querySelector("[name=experiencia-form]"); - formexp.classList.add('was-validated') - const formData = new FormData(formexp); - let error=validarfecha(formData.get("fechaDesde"), formData.get("fechaHasta")) - let appendTo = "Hasta"; - if (error) { - if(error.includes("desde")) appendTo = "Desde"; - formexp.querySelector(".errorfecha"+appendTo) - - formexp['fecha'+appendTo].setCustomValidity(error) - document.querySelector(".errorfecha"+appendTo).innerHTML = error; - console.log(error); - - } - else{ - formexp.fechaDesde.setCustomValidity('') - formexp.fechaHasta.setCustomValidity('') - } - - const reconocimientos = [{},{},{}]; - let pos_rec; - let returnFlag = false; + if (mm < 10) { + mm = '0' + mm; + } - let requiredValues = ["institucion", "cargo", "fechaDesde"] + today = yyyy + '-' + mm + '-' + dd; - 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 fch.addEventListener('keydown',()=>false))//no dejar cargar manualmente fechas - for (const [name, value] of formData){ - pos_rec = name.split("-");//rec-nombre-index - if (pos_rec.length > 1) { - reconocimientos[pos_rec[2]][pos_rec[1]] = value - } - else{ - pairs[name] = value - } + fechaDesdeEstudio.setAttribute("max", today); + fechaDesdeExperiencia.setAttribute("max", today); + fechaNacimiento.setAttribute("max", today); + fechaDesdeExperiencia.addEventListener("change", ()=>{ + fechaHastaExperiencia.setAttribute("min", fechaDesdeExperiencia.value) + }) + fechaDesdeEstudio.addEventListener("change", ()=>{ + fechaHastaEstudio.setAttribute("min", fechaDesdeEstudio.value) + }) +} + + 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) } - pairs["reconocimientos"] = reconocimientos.filter(rec => rec.nombre); - experiencias[cont_experiencia] = pairs; - formexp.reset(); - formexp.classList.remove('was-validated') - //imprimir lista actualizada - const div = document.querySelector("#experiencias") - const div1 = document.createElement('div'); + ciudad.replaceChildren(frag); + - let content=''; - for (let index = 0; index < experiencias.length; index++) { - const exp = experiencias[index]; - if(exp==null) continue; - content += ` -
-

Experiencia

-
-
-
-
-
-
-
- - -
- - ` - } - //content += "" - div.innerHTML = content - //div.innerHTML = ''; - //div.appendChild(div1); - cont_experiencia++; } + function validarfecha(fechaDesde, fechaHasta){ let fechadehoy= new Date().toISOString().slice(0,10); if(fechaDesde>fechadehoy ){ return "la fecha desde no puede ser mayor a la fecha actual" ; } - if(fechaHasta =! null && fechaHasta>fechadehoy){ - return "la fecha hasta no puede ser mayor a la fecha actual" ; - } + if(fechaHasta =! null && fechaDesde>fechaHasta){ return "la fecha desde no puede ser mayor a la fecha hasta"; @@ -152,7 +115,7 @@ function validarfecha(fechaDesde, fechaHasta){ return false } -/*--------------------------------------------------------------------*/ +/*-----------------Tecnologia----------------------------------------*/ function agregarFieldTecnologia(){ //recoger del form const pairs = {}; @@ -217,146 +180,135 @@ function agregarFieldTecnologia(){ cont_tecnologia++; document.querySelector("#no-valid-tecno").style.display = "none"; } - - -/*--------------------------------------------------------------------*/ -function eliminarExperiencia(event) { - //eliminar del array - experiencias[event.target.parentElement.id.split("-")[1]]=null - //eliminar en html - event.target.parentElement.remove() -} -/*----------------------------------------------------------------- */ function eliminarTecnologia(event) { //eliminar del array tecnologias[event.target.parentElement.id.split("-")[1]]=null //eliminar en html event.target.parentElement.remove() } -/*----------------------------------------------------------------- */ -function serializeJSON (form) { - // Create a new FormData object - const formData = new FormData(form); - if(formData.get('fechaNacimiento')>=new Date().toISOString().slice(0,10)){ - form['fechaNacimiento'].setCustomValidity('Fecha de nacimiento debe ser menor que actual') - noValidateFlag = true; - return; +/*----------------Experiencia-----------------------------------------*/ +function agregarFieldExpierncia(event){ + //recoger del form + const pairs = {}; + const formexp = document.querySelector("[name=experiencia-form]"); + formexp.classList.add('was-validated') + const formData = new FormData(formexp); + let error=validarfecha(formData.get("fechaDesde"), formData.get("fechaHasta")) + let appendTo = "Hasta"; + if (error) { + + if(error.includes("desde")) appendTo = "Desde"; + + + formexp['fecha'+appendTo].setCustomValidity(error) + formexp.querySelector(".errorFecha"+appendTo).innerHTML = error; + console.log(error); + } else{ - form['fechaNacimiento'].setCustomValidity('') + formexp.fechaDesde.setCustomValidity('') + formexp.fechaHasta.setCustomValidity('') } + + const reconocimientos = [{},{},{}]; + let pos_rec; + let returnFlag = false; + let requiredValues = ["institucion", "cargo", "fechaDesde"] - // Create an object to hold the name/value pairs - const pairs = {}; + formData.forEach((value, key)=>{ + if(requiredValues.includes(key) + && value==="" && returnFlag == false){ + console.log(key, value) + returnFlag = true; + } + }); - // Add each name/value pair to the object - for (const [name, value] of formData) { - pairs[name] = value - } - 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 - pairs["postulaciones"] = postulaciones.filter(car => car)//eliminacion de nulos - pairs["referencias"] = referencias.filter(tec => tec) - if(pairs["postulaciones"].length<1){ - document.querySelector("#no-valid-cargo").style.display = "block"; - noValidateFlag = true; - }else{ - document.querySelector("#no-valid-cargo").style.display = "none"; - } - console.log(pairs["tecnologias"]) - if(pairs["tecnologias"].length<1){ - document.querySelector("#no-valid-tecno").style.display = "block"; - noValidateFlag = true; - }else{ - document.querySelector("#no-valid-tecno").style.display = "none"; - } - if(noValidateFlag){ + if(returnFlag===true){ + let message = "Rellene " + for(let i=0;i 1) { + reconocimientos[pos_rec[2]][pos_rec[1]] = value + } + else{ + pairs[name] = value + } -async function postData(url = '', data = {}) { - var token = document.querySelector("meta[name='_csrf']").content; - var headerxs = document.querySelector("meta[name='_csrf_header']").content; - // Default options are marked with * - let senddata = { - 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: { - //'Content-Type': undefined//'application/json', - // 'Content-Type': 'application/x-www-form-urlencoded', - }, - 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 } - senddata["headers"][headerxs] = token; - let response = null - if(!noValidateFlag){ - response = await fetch(url, senddata); + pairs["reconocimientos"] = reconocimientos.filter(rec => rec.nombre); + experiencias[cont_experiencia] = pairs; + formexp.reset(); + formexp.classList.remove('was-validated') + //imprimir lista actualizada + const div = document.querySelector("#experiencias") + const div1 = document.createElement('div'); + + let content=''; + for (let index = 0; index < experiencias.length; index++) { + const exp = experiencias[index]; + if(exp==null) continue; + content += ` +
+

Experiencia

+
+
+
+
+
+
+
+ + +
+ + ` } - return response; // parses JSON response into native JavaScript objects + //content += "" + div.innerHTML = content + //div.innerHTML = ''; + //div.appendChild(div1); + cont_experiencia++; + modalExperiencia.hide() } - -function formatearJsonWithFile(json, file){ - formData = new FormData(); - - formData.append("file", file); - formData.append('postulante', new Blob([json], { - type: "application/json" - })); - return formData +function eliminarExperiencia(event) { + //eliminar del array + experiencias[event.target.parentElement.id.split("-")[1]]=null + //eliminar en html + event.target.parentElement.remove() } -formValidator() -form = document.querySelector("form"); -form.addEventListener("submit",(evt)=>{ - // if (!form.checkValidity()) { - // evt.preventDefault() - // evt.stopPropagation() - // } - // form.classList.add('was-validated') - evt.preventDefault(); - let formSerialized = serializeJSON(form); - let fileCV = obtenerCV(); - if(!noValidateFlag){ - postData('work-with-us', formatearJsonWithFile(formSerialized,fileCV)) - .then(response => { - if(response.status==200 || response.status==302){ - location.replace(response.url); - }else{ - console.log(response.text().then(value => console.log(value))) - } - }); - } - noValidateFlag = false -} ); - - - -//Metodos para Estudios - - +/*---------------Estudios---------------------------*/ function agregarFieldEstudio(){ //recoger del form let pairs = {}; const formest = document.querySelector("[name=estudio-form]"); const formData = new FormData(formest); + formest.classList.add('was-validated') + let error=validarfecha(formData.get("fechaDesde"), formData.get("fechaHasta")) + let appendTo = "Hasta"; + if (error) { + + if(error.includes("desde")) appendTo = "Desde"; + + formest['fecha'+appendTo].setCustomValidity(error) + formest.querySelector(".errorFecha"+appendTo).innerHTML = error; + console.log(error); + + } + else{ + formest.fechaDesde.setCustomValidity('') + formest.fechaHasta.setCustomValidity('') + } //Validacion let returnFlag = false; @@ -377,7 +329,7 @@ function agregarFieldEstudio(){ message+=", "+requiredValues[i]; } message += " como minimo." - alert(message); + //alert(message); return; } @@ -430,20 +382,17 @@ function agregarFieldEstudio(){ //div.innerHTML = ''; //div.appendChild(div1); cont_estudios++; - + formest.classList.remove('was-validated') + modalEstudio.hide() } - - - - function eliminarEstudio(event) { //eliminar del array estudios[event.target.parentElement.id.split("-")[1]]=null //eliminar en html event.target.parentElement.remove() } -/*--------------------------------------------------------------------*/ +/*------------Cargos----------------------------------------*/ function agregarFieldCargo(){ //recoger del form const pairs = {}; @@ -513,49 +462,21 @@ function agregarFieldCargo(){ //div.appendChild(div1); cont_cargo++; document.querySelector("#no-valid-cargo").style.display = "none"; + modalCargo.hide() } - -/*---------------------------------------------------------------------------------------------------*/ function eliminarCargoPostulante(event) { //eliminar del array postulaciones[event.target.parentElement.id.split("-")[1]]=null //eliminar en html event.target.parentElement.remove() } -/*--------------------------------------------------------------------*/ - - -//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); - - -} - - +/*--------------Referencias----------------------------- */ function agregarFieldReferencia(event){ //recoger del form const pairs = {}; const formexp = document.querySelector("[name=referencia-form]"); + formexp.classList.add('was-validated') const formData = new FormData(formexp); const referenciaPersonal = [{},{},{}]; let pos_rec; @@ -577,7 +498,7 @@ function agregarFieldReferencia(event){ message+=", "+requiredValues[i]; } message += " como minimo." - alert(message); + //alert(message); return; } @@ -617,71 +538,147 @@ function agregarFieldReferencia(event){ //div.innerHTML = ''; //div.appendChild(div1); cont_referencias++; + formexp.classList.remove('was-validated') + modalExperiencia.hide() } - -/*----------------------------------------------------------------- */ function eliminarReferencia(event) { //eliminar del array referencias[event.target.parentElement.id.split("-")[1]]=null //eliminar en html event.target.parentElement.remove() } -/*----------------------------------------------------------------- */ - - - -/*--------------------------------------------------------------------------------------------------------- */ -// $(function(){ -// $("#wizard").steps({ -// headerTag: "h4", -// bodyTag: "section", -// transitionEffect: "fade", -// enableAllSteps: true, -// transitionEffectSpeed: 500, -// onStepChanging: function (event, currentIndex, newIndex) { -// if ( newIndex === 1 ) { -// $('.steps ul').addClass('step-2'); -// } else { -// $('.steps ul').removeClass('step-2'); -// } -// if ( newIndex === 2 ) { -// $('.steps ul').addClass('step-3'); -// } else { -// $('.steps ul').removeClass('step-3'); -// } -// -// if ( newIndex === 3 ) { -// $('.steps ul').addClass('step-4'); -// $('.actions ul').addClass('step-last'); -// } else { -// $('.steps ul').removeClass('step-4'); -// $('.actions ul').removeClass('step-last'); -// } -// return true; -// }, -// labels: { -// finish: "Order again", -// next: "Next", -// previous: "Previous" -// } -// }); -// // Custom Steps Jquery Steps -// $('.wizard > .steps li a').click(function(){ -// $(this).parent().addClass('checked'); -// $(this).parent().prevAll().addClass('checked'); -// $(this).parent().nextAll().removeClass('checked'); -// }); -// // Custom Button Jquery Steps -// $('.forward').click(function(){ -// $("#wizard").steps('next'); -// }) -// $('.backward').click(function(){ -// $("#wizard").steps('previous'); -// }) -// // Checkbox -// $('.checkbox-circle label').click(function(){ -// $('.checkbox-circle label').removeClass('active'); -// $(this).addClass('active'); -// }) -// }) -/*--------------------------------------------------------------------------------------------------------- */ \ No newline at end of file +/*--------------Form submit----------------------------- */ +function serializeJSON (form) { + // Create a new FormData object + const formData = new FormData(form); + + if(formData.get('fechaNacimiento')>=new Date().toISOString().slice(0,10)){ + form['fechaNacimiento'].setCustomValidity('Fecha de nacimiento debe ser menor que actual') + noValidateFlag = true; + return; + } + else{ + form['fechaNacimiento'].setCustomValidity('') + } + + + // 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) { + pairs[name] = value + } + 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 + pairs["postulaciones"] = postulaciones.filter(car => car)//eliminacion de nulos + pairs["referencias"] = referencias.filter(tec => tec) + if(pairs["postulaciones"].length<1){ + document.querySelector("#no-valid-cargo").style.display = "block"; + noValidateFlag = true; + }else{ + document.querySelector("#no-valid-cargo").style.display = "none"; + } + console.log(pairs["tecnologias"]) + if(pairs["tecnologias"].length<1){ + document.querySelector("#no-valid-tecno").style.display = "block"; + noValidateFlag = true; + }else{ + document.querySelector("#no-valid-tecno").style.display = "none"; + } + if(noValidateFlag){ + return; + } + noValidateFlag = false + + // Return the JSON string + return JSON.stringify(pairs, null, 2); +} + +function obtenerCV(){ + let input = document.querySelector('#cvFile') + return input.files[0]; + +} + +async function postData(url = '', data = {}) { + var token = document.querySelector("meta[name='_csrf']").content; + var headerxs = document.querySelector("meta[name='_csrf_header']").content; + // Default options are marked with * + let senddata = { + 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: { + //'Content-Type': undefined//'application/json', + // 'Content-Type': 'application/x-www-form-urlencoded', + }, + 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 + } + senddata["headers"][headerxs] = token; + let response = null + if(!noValidateFlag){ + response = await fetch(url, senddata); + } + return response; // parses JSON response into native JavaScript objects +} + +function formatearJsonWithFile(json, file){ + formData = new FormData(); + + formData.append("file", file); + formData.append('postulante', new Blob([json], { + type: "application/json" + })); + return formData +} + +/*--------------Llamar funciones y agregar listeners----------------------------- */ +formValidator(); +fechasMaxMin(); +listarCiudades(depSelect.value); + +form.addEventListener("submit",(evt)=>{ + // if (!form.checkValidity()) { + // evt.preventDefault() + // evt.stopPropagation() + // } + // form.classList.add('was-validated') + evt.preventDefault(); + let formSerialized = serializeJSON(form); + let fileCV = obtenerCV(); + if(!noValidateFlag){ + postData('work-with-us', formatearJsonWithFile(formSerialized,fileCV)) + .then(response => { + if(response.status==200 || response.status==302){ + location.replace(response.url); + }else{ + + errorDispatcher(response.text().then(value => console.log(value))); + + } + },(reason)=>{ + errorDispatcher(reason); + }); + } + noValidateFlag = false +} ); + +function errorDispatcher(reason){ + const errorSection = document.querySelector("#errorSection") + errorSection.innerHTML = ` + `; + console.log(reason) + errorSection.focus() +} + +//evento para cambio de ciudad segun departamento +depSelect.addEventListener("change",evt => listarCiudades(evt.target.value)) + diff --git a/curriculumsearch/src/main/webapp/jsp/postulante-form.jsp b/curriculumsearch/src/main/webapp/jsp/postulante-form.jsp index a411b61..dc0e7ba 100644 --- a/curriculumsearch/src/main/webapp/jsp/postulante-form.jsp +++ b/curriculumsearch/src/main/webapp/jsp/postulante-form.jsp @@ -15,6 +15,11 @@ +
+
+ +
+
@@ -23,38 +28,25 @@

Curriculum

-
- - -
- Luce Bien! -
- -
+
-
- Luce Bien! -
+
-
- Luce Bien! -
+
-
- Luce Bien! -
+
@@ -68,7 +60,7 @@
- @@ -78,9 +70,7 @@
-
- Luce Bien! -
+
@@ -103,21 +93,24 @@
-
- Luce Bien! -
+
-
- Luce Bien! -
+ +
+ +
+ + + +
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
- Cancelar + Cancelar
@@ -188,12 +181,12 @@
-
@@ -436,49 +435,11 @@ - - - - + + + \ No newline at end of file