PostulanteRRHHController.java 12.9 KB
Newer Older
1 2 3
package com.roshka.controller;


4 5 6
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
7 8
import java.util.ArrayList;

9 10
import java.util.Date;
import java.util.HashMap;
11 12 13

import java.util.List;

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


33
import com.roshka.utils.PostulantesExcelExporter;
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
import org.hibernate.jpa.TypedParameterValue;
import org.hibernate.type.StringType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

Cesar Giulano Gonzalez Maqueda committed
51 52
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89


@Controller
public class PostulanteRRHHController {
    PostulanteRepository post;
    TecnologiaRepository tecRepo;
    ExperienciaRepository expRepo;
    InstitucionRepository institucionRepository;
    DepartamentoRepository depRepo;
    CiudadRepository ciuRepo;
    EstudioRepository estudioRepository;
    PostulanteTecnologiaRepository postulanteTecnologiaRepository;
    ConvocatoriaRepository cargoRepo;
    CargoRepository carRepo;
    DBFileRepository fileRepo;

    @Autowired
    public PostulanteRRHHController(
            PostulanteRepository post, TecnologiaRepository tecRepo, ExperienciaRepository expRepo,
            InstitucionRepository institucionRepository, DepartamentoRepository depRepo,
            CiudadRepository ciuRepo, EstudioRepository estudioRepository,
            PostulanteTecnologiaRepository postulanteTecnologiaRepository,
            ConvocatoriaRepository cargoRepo, CargoRepository carRepo, DBFileRepository fileRepo) {
        this.post = post;
        this.tecRepo = tecRepo;
        this.expRepo = expRepo;
        this.institucionRepository = institucionRepository;
        this.depRepo = depRepo;
        this.ciuRepo = ciuRepo;
        this.estudioRepository = estudioRepository;
        this.postulanteTecnologiaRepository = postulanteTecnologiaRepository;
        this.cargoRepo =cargoRepo;
        this.carRepo=carRepo;
        this.fileRepo = fileRepo;
    }

    @RequestMapping("/postulantes")
90
    public String postulantes(HttpServletRequest request, Model model,
91 92 93 94 95 96 97 98 99 100 101
                            @RequestParam(required = false)Long tecId,
                            @RequestParam(required = false)String nombre,
                            @RequestParam(required = false)EstadoPostulante estado,
                            @RequestParam(required = false)Disponibilidad dispo,
                            @RequestParam(required = false)Long lvlEng,
                            @RequestParam(required = false)Long lvlTec,
                            @RequestParam(required = false)Long instId,
                            @RequestParam(required = false)Long expInMonths,
                            @RequestParam(required = false)Long cargoId,
                            @RequestParam(required = false)Long convId, 
                            @RequestParam(defaultValue = "0")Integer nroPagina
102
                            ) throws IOException {
103
        final Integer CANTIDAD_POR_PAGINA = 1;
104 105 106 107 108
        Pageable page = PageRequest.of(nroPagina,CANTIDAD_POR_PAGINA,Sort.by("id"));
        model.addAttribute("tecnologias", tecRepo.findAll());
        model.addAttribute("disponibilidades", Disponibilidad.values());
        model.addAttribute("institucionesEducativas", institucionRepository.findAll());
        model.addAttribute("estadoP", EstadoPostulante.values());
109

110 111 112 113 114 115 116 117 118
        model.addAttribute("cargos", carRepo.findAll());
        model.addAttribute("cargoRepo", cargoRepo);
        //model.addAttribute("convocatoriaC", cargoRepo.findAll());
        try {
            model.addAttribute("convocatoriaC", new ObjectMapper().writeValueAsString(cargoRepo.findAll()));
        } catch (JsonProcessingException er) {
            // TODO Auto-generated catch block
            er.printStackTrace();
        }
119 120
        Page<Postulante> postulantesPag = post.postulantesMultiFiltro(
                nombre == null || nombre.trim().isEmpty() ?
121 122
                new TypedParameterValue(StringType.INSTANCE,null) :
                new TypedParameterValue(StringType.INSTANCE,"%"+nombre+"%"),
123
                    dispo, lvlEng, lvlTec, tecId, instId,cargoId,page,estado,convId, expInMonths);
124
        model.addAttribute("numeroOcurrencias", postulantesPag.getTotalElements());
125 126 127 128
        List<Postulante> postulantes = postulantesPag.getContent();
        List<PostulanteListaDTO> postulantesDTO = new ArrayList<>();
        
        for (Postulante postulante : postulantes) {
129 130 131 132
            postulantesDTO.add(new PostulanteListaDTO(postulante.getId(), postulante.getNombre(),
                    postulante.getApellido(), postulante.getDisponibilidad(), postulante.getNivelIngles(),
                    postulante.getMesesDeExperiencia(), postulante.getTecnologias(),postulante.getEstadoPostulante(),
                    postulante.getPostulaciones()));
133
        }
134

135 136
        model.addAttribute("pages", postulantesPag.getTotalPages());
        model.addAttribute("postulantes", postulantesDTO);
137 138 139 140

        String query = request.getQueryString();
        model.addAttribute("query", query);

141 142
        return "postulantes";
    }
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163


    @RequestMapping("/postulantesExcel")
    public void exportPostulantesExcel(HttpServletResponse response, Model model,
                                       @RequestParam(required = false)Long tecId,
                                       @RequestParam(required = false)String nombre,
                                       @RequestParam(required = false)EstadoPostulante estado,
                                       @RequestParam(required = false)Disponibilidad dispo,
                                       @RequestParam(required = false)Long lvlEng,
                                       @RequestParam(required = false)Long lvlTec,
                                       @RequestParam(required = false)Long instId,
                                       @RequestParam(required = false)Long expInMonths,
                                       @RequestParam(required = false)Long cargoId,
                                       @RequestParam(required = false)Long convId,
                                       @RequestParam(defaultValue = "0")Integer nroPagina
    ) throws IOException {
        Pageable page = PageRequest.of(0,Integer.MAX_VALUE,Sort.by("id"));
        Page<Postulante> postulantesPag = post.postulantesMultiFiltro(
                nombre == null || nombre.trim().isEmpty() ?
                        new TypedParameterValue(StringType.INSTANCE,null) :
                        new TypedParameterValue(StringType.INSTANCE,"%"+nombre+"%"),
164
                dispo, lvlEng, lvlTec, tecId, instId,cargoId,page,estado,convId, expInMonths);
165 166 167 168
        List<Postulante> postulantes = postulantesPag.getContent();
        List<PostulanteListaDTO> postulantesDTO = new ArrayList<>();

        for (Postulante postulante : postulantes) {
169 170 171 172
            postulantesDTO.add(new PostulanteListaDTO(postulante.getId(), postulante.getNombre(),
                    postulante.getApellido(), postulante.getDisponibilidad(), postulante.getNivelIngles(),
                    postulante.getMesesDeExperiencia(), postulante.getTecnologias(),postulante.getEstadoPostulante(),
                    postulante.getPostulaciones()));
173 174 175 176 177 178 179 180 181 182 183
        }

        response.setContentType("application/octet-stream");
        DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
        String currentDateTime = dateFormatter.format(new Date());

        String headerKey = "Content-Disposition";
        String headerValue = "attachment; filename=postulantes_" + currentDateTime + ".xlsx";
        response.setHeader(headerKey, headerValue);

        HashMap<String, String> filtros = new HashMap<String, String>();
184
        filtros.put("nombre", nombre == null ? "-":nombre);
185 186 187 188 189 190 191
        filtros.put("nivelIngles", lvlEng == null ? "-" : lvlEng.toString());
        filtros.put("tecnologia", tecId == null ? "-" : tecRepo.findById(tecId).get().getNombre());
        filtros.put("nivelTecnologia", lvlTec == null ? "-" : lvlTec.toString());
        filtros.put("institucion", instId == null ? "-" : institucionRepository.findById(instId).get().getNombre());
        filtros.put("estado", estado == null ? "-" : estado.getEstado());
        filtros.put("experienciaEnMeses", expInMonths == null ? "-" : expInMonths.toString());
        filtros.put("convocatoria", convId == null ? "-" : cargoRepo.findById(convId).get().getCargo().getNombre());
192
        filtros.put("convocatoriaFecha", convId == null ? "-" : cargoRepo.findById(convId).get().getFechaInicio().toString());
193 194 195 196 197

        PostulantesExcelExporter excelExporter = new PostulantesExcelExporter(postulantesDTO, filtros);

        excelExporter.export(response);
    }
198 199 200 201 202 203 204 205 206 207 208
 

    @GetMapping({"/postulantes/{postulanteId}"})
    public String getPostulanteDetalle(Model model, @PathVariable("postulanteId") Long postulanteId) {
        Postulante p = post.findById(postulanteId).orElse(null);
        model.addAttribute("postulante",p);
        model.addAttribute("cvId", fileRepo.getIdByPostulante(p));
        model.addAttribute("estadoP", EstadoPostulante.values());				
        return "detallepostulante";
        
    }
209 210


211 212 213 214 215
    @PostMapping({"/postulantes/{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());
216 217 218 219
        //si se le contrata, actualizar la fecha actual
        if(postulanteVd.getEstadoPostulante() == EstadoPostulante.CONTRATADO){
            postulanteVd.setFechaContratado(new Date());
        }
220 221 222
        postulanteVd.setComentarioRRHH(postulante.getComentarioRRHH());
        post.setPostulanteEstadoAndComentario(postulante.getEstadoPostulante(), postulante.getComentarioRRHH(), postulanteId);
        //post.save(postulanteVd);
223
        return "redirect:/postulantes/"+postulanteId;
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
    }

    @GetMapping("/postulantes/cvFile/{fileId}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileId) {
        // Load file from database
        DBFile dbFile;
        try {
            dbFile = fileRepo.findById(fileId)
            .orElseThrow(() -> new Exception("File not found with id " + fileId));
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(dbFile.getFileType()))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dbFile.getFileName() + "\"")
                    .body(new ByteArrayResource(dbFile.getData()));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }

    }
244 245 246 247 248 249 250 251 252 253 254 255

    @GetMapping("/postulantes/{id}/pdf")
    public ResponseEntity<Resource> downloadPDF(@PathVariable Long id) {
        // Load file from database
        PdfGenerator pdf =  new PdfGenerator();
        
        
        try {
            Postulante postulante = post.findById(id)
            .orElseThrow(() -> new Exception("Postulante no encontrado"));
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType("application/pdf"))
256
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + postulante.getNroDocument() + ".pdf" + "\"")
257 258 259 260 261 262 263 264
                    .body(new ByteArrayResource(pdf.generatePdfReport(postulante)));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }

    }
265 266
}