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


4 5
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
6
import com.roshka.DTO.ConvocatoriaDTO;
7
import com.roshka.DTO.PostulanteListaDTO;
8
import com.roshka.modelo.DBFile;
9 10 11
import com.roshka.modelo.EstadoPostulante;
import com.roshka.modelo.Postulante;
import com.roshka.repositorio.*;
12
import com.roshka.service.PdfGenerator;
13
import com.roshka.utils.PostulantesExcelExporter;
14 15 16
import org.hibernate.jpa.TypedParameterValue;
import org.hibernate.type.StringType;
import org.springframework.beans.factory.annotation.Autowired;
17 18
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
19 20 21 22
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
23 24 25
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
26 27 28 29 30
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

Cesar Giulano Gonzalez Maqueda committed
31 32
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
33 34 35 36 37 38 39
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
40
import java.util.stream.Collectors;
41 42 43


@Controller
44
@RequestMapping("/postulantes")
45 46 47 48 49 50 51 52 53
public class PostulanteRRHHController {
    PostulanteRepository post;
    TecnologiaRepository tecRepo;
    ExperienciaRepository expRepo;
    InstitucionRepository institucionRepository;
    DepartamentoRepository depRepo;
    CiudadRepository ciuRepo;
    EstudioRepository estudioRepository;
    PostulanteTecnologiaRepository postulanteTecnologiaRepository;
54
    ConvocatoriaRepository convRepo;
55 56 57 58 59 60 61 62 63
    CargoRepository carRepo;
    DBFileRepository fileRepo;

    @Autowired
    public PostulanteRRHHController(
            PostulanteRepository post, TecnologiaRepository tecRepo, ExperienciaRepository expRepo,
            InstitucionRepository institucionRepository, DepartamentoRepository depRepo,
            CiudadRepository ciuRepo, EstudioRepository estudioRepository,
            PostulanteTecnologiaRepository postulanteTecnologiaRepository,
64
            ConvocatoriaRepository convRepo, CargoRepository carRepo, DBFileRepository fileRepo) {
65 66 67 68 69 70 71 72
        this.post = post;
        this.tecRepo = tecRepo;
        this.expRepo = expRepo;
        this.institucionRepository = institucionRepository;
        this.depRepo = depRepo;
        this.ciuRepo = ciuRepo;
        this.estudioRepository = estudioRepository;
        this.postulanteTecnologiaRepository = postulanteTecnologiaRepository;
73
        this.convRepo =convRepo;
74 75 76 77
        this.carRepo=carRepo;
        this.fileRepo = fileRepo;
    }

78
    @RequestMapping()
79
    public String postulantes(HttpServletRequest request, Model model,
80 81 82 83 84 85
                            @RequestParam(required = false)Long tecId,
                            @RequestParam(required = false)String nombre,
                            @RequestParam(required = false)EstadoPostulante estado,
                            @RequestParam(required = false)Long lvlEng,
                            @RequestParam(required = false)Long lvlTec,
                            @RequestParam(required = false)Long instId,
86
                            @RequestParam(required = false)String expInMonths,
87 88 89
                            @RequestParam(required = false)Long cargoId,
                            @RequestParam(required = false)Long convId, 
                            @RequestParam(defaultValue = "0")Integer nroPagina
90
                            ) throws IOException {
91

92
        final Integer CANTIDAD_POR_PAGINA = 10;
93 94 95 96
        Pageable page = PageRequest.of(nroPagina,CANTIDAD_POR_PAGINA,Sort.by("id"));
        model.addAttribute("tecnologias", tecRepo.findAll());
        model.addAttribute("institucionesEducativas", institucionRepository.findAll());
        model.addAttribute("estadoP", EstadoPostulante.values());
97

98 99
        model.addAttribute("cargos", carRepo.findAll());
        try {
100 101 102 103 104 105
            //se convierte a DTO las convocatorias
            model.addAttribute("convocatoriaC", new ObjectMapper().writeValueAsString(
                convRepo.findAll().stream().map(conv ->
                        new ConvocatoriaDTO(conv.getId(), conv.getCargoId(), conv.getEstado(), conv.getFechaInicio(), conv.getFechaFin()) )
                .collect(Collectors.toList()))
            );
106 107 108 109
        } catch (JsonProcessingException er) {
            // TODO Auto-generated catch block
            er.printStackTrace();
        }
110 111 112 113 114 115 116
        long infRange = 0L;
        long supRange = 1200L;
        if(expInMonths != null && !expInMonths.trim().isEmpty()){
            String[] rango = expInMonths.split("-");
            infRange = Long.parseLong(rango[0]);
            supRange = Long.parseLong(rango[1]);
        }
117 118
        Page<Postulante> postulantesPag = post.postulantesMultiFiltro(
                nombre == null || nombre.trim().isEmpty() ?
119
                new TypedParameterValue(StringType.INSTANCE,null) :
120
                new TypedParameterValue(StringType.INSTANCE,"%"+nombre.trim()+"%"),
121
                     lvlEng, lvlTec, tecId, instId,cargoId,page,estado,convId, infRange, supRange);
122
        model.addAttribute("numeroOcurrencias", postulantesPag.getTotalElements());
123 124 125 126
        List<Postulante> postulantes = postulantesPag.getContent();
        List<PostulanteListaDTO> postulantesDTO = new ArrayList<>();
        
        for (Postulante postulante : postulantes) {
127
            postulantesDTO.add(new PostulanteListaDTO(postulante.getId(), postulante.getNombre(),
128
                    postulante.getApellido(), postulante.getNivelIngles(),
129 130
                    postulante.getMesesDeExperiencia(), postulante.getTecnologias(),postulante.getEstadoPostulante(),
                    postulante.getPostulaciones()));
131
        }
132

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

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

139 140
        return "postulantes";
    }
141 142


143
    @RequestMapping("/excel")
144 145 146 147 148 149 150
    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)Long lvlEng,
                                       @RequestParam(required = false)Long lvlTec,
                                       @RequestParam(required = false)Long instId,
151
                                       @RequestParam(required = false)String expInMonths,
152 153 154 155 156
                                       @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"));
157 158 159 160 161 162 163
        long infRange = 0L;
        long supRange = 1200L;
        if(expInMonths != null && !expInMonths.trim().isEmpty()){
            String[] rango = expInMonths.split("-");
            infRange = Long.parseLong(rango[0]);
            supRange = Long.parseLong(rango[1]);
        }
164 165 166 167
        Page<Postulante> postulantesPag = post.postulantesMultiFiltro(
                nombre == null || nombre.trim().isEmpty() ?
                        new TypedParameterValue(StringType.INSTANCE,null) :
                        new TypedParameterValue(StringType.INSTANCE,"%"+nombre+"%"),
168
                        lvlEng, lvlTec, tecId, instId,cargoId,page,estado,convId, infRange, supRange);
169 170 171 172
        List<Postulante> postulantes = postulantesPag.getContent();
        List<PostulanteListaDTO> postulantesDTO = new ArrayList<>();

        for (Postulante postulante : postulantes) {
173
            postulantesDTO.add(new PostulanteListaDTO(postulante.getId(), postulante.getNombre(),
174
                    postulante.getApellido(), postulante.getNivelIngles(),
175 176
                    postulante.getMesesDeExperiencia(), postulante.getTecnologias(),postulante.getEstadoPostulante(),
                    postulante.getPostulaciones()));
177 178 179 180 181 182 183 184 185 186 187
        }

        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>();
188
        filtros.put("nombre", nombre == null ? "-":nombre);
189 190 191 192 193 194
        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());
195 196
        filtros.put("convocatoria", convId == null ? "-" : convRepo.findById(convId).get().getCargo().getNombre());
        filtros.put("convocatoriaFecha", convId == null ? "-" : convRepo.findById(convId).get().getFechaInicio().toString());
197 198 199 200 201

        PostulantesExcelExporter excelExporter = new PostulantesExcelExporter(postulantesDTO, filtros);

        excelExporter.export(response);
    }
202 203
 

204
    @GetMapping({"/{postulanteId}"})
205 206 207 208 209 210 211 212
    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";
        
    }
213 214


215
    @PostMapping({"/{postulanteId}"})
216 217 218 219
    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());
220 221 222 223
        //si se le contrata, actualizar la fecha actual
        if(postulanteVd.getEstadoPostulante() == EstadoPostulante.CONTRATADO){
            postulanteVd.setFechaContratado(new Date());
        }
224 225 226
        postulanteVd.setComentarioRRHH(postulante.getComentarioRRHH());
        post.setPostulanteEstadoAndComentario(postulante.getEstadoPostulante(), postulante.getComentarioRRHH(), postulanteId);
        //post.save(postulanteVd);
227
        return "redirect:/postulantes/"+postulanteId;
228 229
    }

230
    @GetMapping("/cvFile/{fileId}")
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    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();
        }

    }
248

249
    @GetMapping("/{id}/pdf")
250 251 252 253 254 255 256 257 258 259
    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"))
260
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + postulante.getNroDocument() + ".pdf" + "\"")
261 262 263 264 265 266 267 268
                    .body(new ByteArrayResource(pdf.generatePdfReport(postulante)));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }

    }
269 270
}