PostulanteController.java 11 KB
Newer Older
1 2 3
package com.roshka.controller;


4
import java.util.ArrayList;
willgonzz committed
5
import java.util.Date;
6
import java.util.List;
7
import java.util.Locale;
8 9


10
import javax.validation.ConstraintViolationException;
11

12
import com.roshka.DTO.PostulanteListaDTO;
13
import com.roshka.modelo.*;
14 15
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
16
import com.roshka.modelo.Disponibilidad;
17
import com.roshka.modelo.EstadoPostulante;
18 19
import com.roshka.modelo.EstadoCivil;
import com.roshka.modelo.Nacionalidad;
20
import com.roshka.modelo.Postulante;
21
import com.roshka.modelo.TipoExperiencia;
22
import com.roshka.repositorio.*;
23
import com.roshka.repositorio.CiudadRepository;
willgonzz committed
24
import com.roshka.repositorio.ConvocatoriaRepository;
25
import com.roshka.repositorio.DepartamentoRepository;
26
import com.roshka.repositorio.ExperienciaRepository;
27
import com.roshka.repositorio.InstitucionRepository;
28
import com.roshka.repositorio.PostulanteRepository;
29
import com.roshka.repositorio.TecnologiaRepository;
30
import com.roshka.utils.Helper;
31

32

33 34
import org.hibernate.jpa.TypedParameterValue;
import org.hibernate.type.StringType;
willgonzz committed
35 36
import org.hibernate.type.IntegerType;
import org.hibernate.type.LongType;
37
import org.springframework.beans.factory.annotation.Autowired;
38 39 40
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
41
import org.springframework.data.domain.Sort;
42 43
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
44
import org.springframework.stereotype.Controller;
45
import org.springframework.ui.Model;
46
import org.springframework.validation.BindingResult;
47 48
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
49

50 51


52 53
@Controller
public class PostulanteController {
54
    PostulanteRepository post;
55
    TecnologiaRepository tecRepo;
56
    ExperienciaRepository expRepo;
57
    InstitucionRepository institucionRepository;
58
    DepartamentoRepository depRepo;
59
    CiudadRepository ciuRepo;
60 61
    EstudioRepository estudioRepository;
    PostulanteTecnologiaRepository postulanteTecnologiaRepository;
willgonzz committed
62 63
    ConvocatoriaRepository cargoRepo;
    CargoRepository carRepo;
64

65
    @Autowired
66 67 68
    public PostulanteController(
            PostulanteRepository post, TecnologiaRepository tecRepo, ExperienciaRepository expRepo,
            InstitucionRepository institucionRepository, DepartamentoRepository depRepo,
69
            CiudadRepository ciuRepo, EstudioRepository estudioRepository,
70 71
            PostulanteTecnologiaRepository postulanteTecnologiaRepository,
            ConvocatoriaRepository cargoRepo, CargoRepository carRepo) {
72 73 74 75
        this.post = post;
        this.tecRepo = tecRepo;
        this.expRepo = expRepo;
        this.institucionRepository = institucionRepository;
76 77
        this.depRepo = depRepo;
        this.ciuRepo = ciuRepo;
78 79
        this.estudioRepository = estudioRepository;
        this.postulanteTecnologiaRepository = postulanteTecnologiaRepository;
willgonzz committed
80 81
        this.cargoRepo =cargoRepo;
        this.carRepo=carRepo;
82
    }
83

84
    @RequestMapping("home")
85
    public String index() {
86
      
87

88
      return "index";
89 90
    }

Joel Florentin committed
91
    @RequestMapping("/postulantes")
Joel Florentin committed
92
    public String postulantes(Model model,
93 94
                            @RequestParam(required = false)Long tecId,
                            @RequestParam(required = false)String nombre,
95
                            @RequestParam(required = false)EstadoPostulante estado,
96
                            @RequestParam(required = false)Disponibilidad dispo,
97 98
                            @RequestParam(required = false)Long lvlEng,
                            @RequestParam(required = false)Long lvlTec,
99
                            @RequestParam(required = false)Long instId,
100
                            @RequestParam(required = false)Long expInMonths,
101
                            @RequestParam(required = false)Long cargoId,
102
                            @RequestParam(required = false)Long convId, 
103
                            @RequestParam(defaultValue = "0")Integer nroPagina
104
                            ) {
105
        final Integer CANTIDAD_POR_PAGINA = 5;
106
        Pageable page = PageRequest.of(nroPagina,CANTIDAD_POR_PAGINA,Sort.by("id"));
Joel Florentin committed
107
        model.addAttribute("tecnologias", tecRepo.findAll());
108 109
        model.addAttribute("disponibilidades", Disponibilidad.values());
        model.addAttribute("institucionesEducativas", institucionRepository.findAll());
110
        model.addAttribute("estadoP", EstadoPostulante.values());
111 112
        model.addAttribute("convocatoriaC", cargoRepo.findAll());
        Page<Postulante> postulantesPag = post.postulantesMultiFiltro(nombre == null || nombre.trim().isEmpty() ? new TypedParameterValue(StringType.INSTANCE,null) : new TypedParameterValue(StringType.INSTANCE,"%"+nombre+"%"),dispo, lvlEng, lvlTec, tecId, instId,cargoId,page,estado,convId);
113
        List<Postulante> postulantes = postulantesPag.getContent();
114 115 116 117 118 119 120 121 122 123
        List<PostulanteListaDTO> postulantesDTO = new ArrayList<>();
        
        for (Postulante postulante : postulantes) {
            long expTotal = 0;
            //Sumamos el tiempo de experiencia total en meses de cada postulante
            //expTotal = postulante.getExperiencias().stream().mapToLong(e -> Helper.getMonthsDifference(e.getFechaDesde(), e.getFechaHasta())).sum();
            for (Experiencia experiencia : postulante.getExperiencias()) {
                expTotal +=  Helper.getMonthsDifference(experiencia.getFechaDesde(), experiencia.getFechaHasta());
            }
            if(expInMonths != null && expInMonths > expTotal) continue;
124
            postulantesDTO.add(new PostulanteListaDTO(postulante.getId(), postulante.getNombre(), postulante.getApellido(), postulante.getDisponibilidad(), postulante.getNivelIngles(), expTotal, postulante.getTecnologias(),postulante.getEstadoPostulante(),postulante.getPostulaciones()));
125 126
        }
        
127
        model.addAttribute("pages", postulantesPag.getTotalPages());
128
        model.addAttribute("postulantes", postulantesDTO);
Joel Florentin committed
129 130
        return "postulantes";
    }
131
    
132
    @RequestMapping("/postulante")
133 134
    public String getFormPostulante(Model model){
        model.addAttribute("tecnologias", tecRepo.findAll());
135
        model.addAttribute("disponibilidades", Disponibilidad.values());
136 137
        model.addAttribute("tiposDeEstudio", TipoDeEstudio.values());
        model.addAttribute("estadosEstudio", EstadoEstudio.values());
138 139 140
        model.addAttribute("estadosCiviles", EstadoCivil.values());
        model.addAttribute("nacionalidades", Nacionalidad.values());
        model.addAttribute("tiposExperencia", TipoExperiencia.values());
willgonzz committed
141
        model.addAttribute("CargosDisponibles", cargoRepo.f1ndByCargoAndEstado(new TypedParameterValue(LongType.INSTANCE, null), new Date(), new TypedParameterValue(IntegerType.INSTANCE, 1)));
142 143
        try {
            model.addAttribute("ciudades", new ObjectMapper().writeValueAsString(ciuRepo.findAll()));
willgonzz committed
144
        } catch (JsonProcessingException er) {
145
            // TODO Auto-generated catch block
willgonzz committed
146
            er.printStackTrace();
147 148
        }
        model.addAttribute("departamentos", depRepo.findAll());
149
        
150 151
        return "postulante-form";
    }
152
    
153 154
    @PostMapping(value = "/postulante",consumes = "application/json")
    public String guardarPostulante(@RequestBody Postulante postulante){
155 156 157 158 159 160 161 162
        //Codigo encargado de modificar postulacion si se envia mismo CI
        Postulante postulantex = post.findByNroDocument(postulante.getnroDocument());
        if(postulantex != null){
            estudioRepository.findByPostulante(postulantex).forEach(x -> estudioRepository.delete(x));
            expRepo.findByPostulante(postulantex).forEach(x -> expRepo.delete(x));
            postulanteTecnologiaRepository.findByPostulante(postulantex).forEach(x -> postulanteTecnologiaRepository.delete(x));
            postulante.setId(postulantex.getId());
        }
163
        postulante.getTecnologias().stream().filter(
164
            tec -> tec.getTecnologia().getId() != 0 
165
            ).forEach(
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
                tec -> tec.setTecnologia(tecRepo.getById(tec.getTecnologia().getId()))
                );
                /* for (int i = 0; i < postulante.getPostulaciones().size(); i++) {
                    postulante.getPostulaciones().set(i, cargoRepo.getById(postulante.getPostulaciones().get(i).getId()));
                }
                */
                
                for(Estudio estudio: postulante.getEstudios()){
                    String nombreIns = "";
                    nombreIns = estudio.getInstitucion().getNombre().toLowerCase();
                    Institucion institucion = institucionRepository.findByNombre(nombreIns);
                    if(institucion==null){
                        institucionRepository.save(estudio.getInstitucion());
                    }else{
                        estudio.setInstitucion(institucion);
                    }
                }
                post.save(postulante);
                return "redirect:/postulacion-correcta";
185
            }
186

187 188
            @GetMapping("/postulacion-correcta")
            public String successPostulation(Model model){
189 190 191
        model.addAttribute("mensaje1", "Tu informacion se ha recibido correctamente!");
        model.addAttribute("mensaje2", " espera por que nos pongamos en contacto!");
        return "exitoRegistro";
192 193
    }

194 195 196
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseEntity<String> handleValidationExceptions(
197
        MethodArgumentNotValidException ex) {
198 199
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(ex.getMessage());
200
    }
201
            
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({ConstraintViolationException.class})
    public ResponseEntity<String> handleValidationExceptions2(
        ConstraintViolationException ex) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
            .body(ex.getMessage());
        }



    @GetMapping({"/postulante/{postulanteId}"})
    public String getPostulanteDetalle(Model model, @PathVariable("postulanteId") Long postulanteId) {
        Postulante p = post.findById(postulanteId).orElse(null);
        model.addAttribute("postulante",p);
        model.addAttribute("estadoP", EstadoPostulante.values());
217
        return "detallepostulante2";
218 219 220 221 222 223 224 225 226 227 228 229 230

    }
    @PostMapping({"/postulante/{postulanteId}"})
    public String setPostulanteEstado(@ModelAttribute Postulante postulante, BindingResult result, @PathVariable("postulanteId") Long postulanteId) {
        //post.setPostulanteEstadoAndComentario(postulante.getEstadoPostulante(),postulante.getComentarioRRHH(), postulante.getId());
        Postulante postulanteVd = post.getById(postulanteId);
        postulanteVd.setEstadoPostulante(postulante.getEstadoPostulante());
        postulanteVd.setComentarioRRHH(postulante.getComentarioRRHH());
        post.setPostulanteEstadoAndComentario(postulante.getEstadoPostulante(), postulante.getComentarioRRHH(), postulanteId);
        //post.save(postulanteVd);
        return "redirect:/postulante/"+postulanteId;
    }
}
231