PostulanteController.java 11.2 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(defaultValue = "0")Integer nroPagina
103
                            ) {
104
        final Integer CANTIDAD_POR_PAGINA = 5;
105
        Pageable page = PageRequest.of(nroPagina,CANTIDAD_POR_PAGINA,Sort.by("id"));
Joel Florentin committed
106
        model.addAttribute("tecnologias", tecRepo.findAll());
107 108
        model.addAttribute("disponibilidades", Disponibilidad.values());
        model.addAttribute("institucionesEducativas", institucionRepository.findAll());
109 110
        model.addAttribute("estadoP", EstadoPostulante.values());
        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);
111
        List<Postulante> postulantes = postulantesPag.getContent();
112 113 114 115 116 117 118 119 120 121
        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;
122
            postulantesDTO.add(new PostulanteListaDTO(postulante.getId(), postulante.getNombre(), postulante.getApellido(), postulante.getDisponibilidad(), postulante.getNivelIngles(), expTotal, postulante.getTecnologias(),postulante.getEstadoPostulante()));
123 124
        }
        
125
        model.addAttribute("pages", postulantesPag.getTotalPages());
126
        model.addAttribute("postulantes", postulantesDTO);
Joel Florentin committed
127 128
        return "postulantes";
    }
129
    
130
    @RequestMapping("/postulante")
131 132
    public String getFormPostulante(Model model){
        model.addAttribute("tecnologias", tecRepo.findAll());
133
        model.addAttribute("disponibilidades", Disponibilidad.values());
134 135
        model.addAttribute("tiposDeEstudio", TipoDeEstudio.values());
        model.addAttribute("estadosEstudio", EstadoEstudio.values());
136 137 138
        model.addAttribute("estadosCiviles", EstadoCivil.values());
        model.addAttribute("nacionalidades", Nacionalidad.values());
        model.addAttribute("tiposExperencia", TipoExperiencia.values());
willgonzz committed
139
        model.addAttribute("CargosDisponibles", cargoRepo.f1ndByCargoAndEstado(new TypedParameterValue(LongType.INSTANCE, null), new Date(), new TypedParameterValue(IntegerType.INSTANCE, 1)));
140 141
        try {
            model.addAttribute("ciudades", new ObjectMapper().writeValueAsString(ciuRepo.findAll()));
willgonzz committed
142
        } catch (JsonProcessingException er) {
143
            // TODO Auto-generated catch block
willgonzz committed
144
            er.printStackTrace();
145 146
        }
        model.addAttribute("departamentos", depRepo.findAll());
147
        
148 149
        return "postulante-form";
    }
150
    
151 152
    @PostMapping(value = "/postulante",consumes = "application/json")
    public String guardarPostulante(@RequestBody Postulante postulante){
153 154 155 156 157 158 159 160
        //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());
        }
161
        postulante.getTecnologias().stream().filter(
162
            tec -> tec.getTecnologia().getId() != 0 
163
            ).forEach(
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
                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";
183
            }
184

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

192 193 194
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseEntity<String> handleValidationExceptions(
195
        MethodArgumentNotValidException ex) {
196 197
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(ex.getMessage());
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
            }
            
            @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());				
                    return "detallepostulante";
                    
                }
                @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;
                }
            }