<?php
namespace App\Controller;
use App\Entity\GHCandidato;
use App\Entity\GHPerfilCargo;
use App\Entity\GHPeriodoPrueba;
use App\Entity\GHVacante;
use App\Entity\ParEstado;
use App\Entity\TerPersona;
use App\Form\GHVacanteEliminadaType;
use App\Form\GHVacanteType;
use App\Repository\GHVacanteRepository;
use App\Services\ExcelExporterService;
use App\Services\MailerCore;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Dompdf\Dompdf;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Routing\Annotation\Route;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class GHVacanteController extends AbstractController {
private $entityManager;
private $repository;
private $code = 0;
private $msj = "";
private $url = "";
private $html = "";
#[Route('/gh/vacante', name: 'gh_vacante')]
public function index(Request $request): Response {
//// //todos los registros para Gestión Humana
if ($this->getUser()->getPersona()->getPerfilCargo()->getParProceso()->getId() == 1) {
$entities = $this->repository->getAll([4,5]);
} else {
$entities = $this->repository->getAll([4,5], $this->getUser()->getPersona()->getId());
}
//$entities = $this->repository->getAll([4, 5, 29]);
return $this->render('gh_vacante/index.html.twig', [
'controller_name' => 'GHVacanteController',
'entities' => $entities,
'tipoFiltro' => "vacantesExcel",
'titulo' => 'Vacantes'
]);
}
#[Route('/gh/vacante_eliminadas', name: 'gh_vacante_eliminadas')]
public function eliminadas(Request $request): Response {
//todos los registros para Gestión Humana Eliminados
if ($this->getUser()->getPersona()->getPerfilCargo()->getParProceso()->getId() == 1) {
$entities = $this->repository->getAll([6]);
} else {
$entities = $this->repository->getAll([6], $this->getUser()->getPersona()->getId());
}
//$entities = $this->repository->getAll([6]);
return $this->render('gh_vacante/index.html.twig', [
'controller_name' => 'GHVacanteController',
'entities' => $entities,
'tipoFiltro' => "vacantesExcel",
'titulo' => 'Vacantes Descartadas'
]);
}
#[Route('/gh/vacante_revision', name: 'gh_vacante_revision')]
public function vacanteRevision(Request $request): Response {
$entities = $this->repository->getAll([4]);
return $this->render('gh_vacante/index.html.twig', [
'controller_name' => 'GHVacanteController',
'entities' => $entities,
'tipoFiltro' => "vacantesExcel",
'titulo' => 'Aprobación Solicitud'
]);
}
#[Route('/gh/vacante_seleccion', name: 'gh_vacante_seleccion')]
public function vacanteSeleccion(Request $request): Response {
$entities = $this->repository->getAll([5, 7]);
return $this->render('gh_vacante/index.html.twig', [
'controller_name' => 'GHVacanteController',
'entities' => $entities,
'tipoFiltro' => "vacantesExcel",
'titulo' => 'Proceso Seleccion'
]);
}
public function __construct(EntityManagerInterface $entityManager, GHVacanteRepository $GHVacanteRepository) {
$this->entityManager = $entityManager;
$this->repository = $GHVacanteRepository;
}
#[Route('/gh/vacante/crear', name: 'gh_vacante_new')]
public function crearVacante(Request $request, \App\Services\MailerCore $mailerCore, \App\Services\ResponseHandler $responseHandler): Response {
$vacante = new GHVacante();
$form = $this->createForm(GHVacanteType::class, $vacante, [
'method' => 'POST',
'with_extra_fields' => true, // Correcto
'action' => $this->generateUrl($request->attributes->get('_route')),
]);
$form->remove('observacionCierre')
->remove('empresaTpm')
->remove('fecha')
->remove('cargoTpm')
->remove('TipoSeleccionTmp')
->remove('TipoContratoTpm')
->remove('ResumenPerfilTpm')
->remove('rangoSalarialTpm')
->remove('sedeTpm')
->remove('estado')
;
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->entityManager;
// if ($vacante->getPerfilCargo()) {
// $vacanteRepetida = $entityManager->getRepository(GHVacante::class)->findOneBy(['perfilCargo' => $vacante->getPerfilCargo()->getId(), 'empresaFilial' => $vacante->getEmpresaFilial()->getId(), 'sede' => $vacante->getSede()->getId(), 'estado' => 4]);
// if ($vacanteRepetida) {
//
// $this->code = 'warning';
// $this->msj = "El sistema ya cuenta con una vacante igual, valide e intente nuevamente.";
// return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
// }
// }
$vacante->setFecha(new \DateTime('now'));
$vacante->setNumeroPostulados(0);
$vacante->setNumeroAdmitidos(0);
$vacante->setPersonaSolicita($this->getUser()->getPersona());
$cargoPersona = $this->getUser()->getPersona()?->getPerfilCargo()?->getCargo()?->getId() ?? null;
if ($this->getUser()->getPersona()->getPerfilCargo()->getParNivelAutoridad()->getId() == 4) {
// si es admin notificar y autorizar.
$vacante->setEstado($this->entityManager->getRepository(\App\Entity\ParEstado::class)->find(5));
$entityManager->persist($vacante);
$entityManager->flush();
$mailerCore->notificarVacante('notificar', [$vacante]);
} else {
$vacante->setEstado($this->entityManager->getRepository(\App\Entity\ParEstado::class)->find(4));
$entityManager->persist($vacante);
$entityManager->flush();
$mailerCore->notificarVacante('notificar', [$vacante], ['gestion.humana@logisticazf.com.co']); //notificacion de creacion
// Validar si son directores en gerente para no enviar la aprobación
$directoresGerentes = in_array($cargoPersona,[11,2,5,8,19,29,38,1]);
if($cargoPersona && !$directoresGerentes){
$mailerCore->notificarVacante('gestionar', [$vacante]); //notificacion de aprobacion
}
if($directoresGerentes)
// Queda en estado aprobado inmediatamente
$vacante->setEstado($this->entityManager->getRepository(\App\Entity\ParEstado::class)->find(5));
}
$vacante->setCreateUser($this->getUser()->getUsername());
$entityManager->persist($vacante);
$entityManager->flush();
$this->code = 'success';
$this->msj = "Registro cargado exitosamente.";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
return $this->render('gh_vacante/crear.html.twig', [
'vacante' => $vacante,
'form' => $form->createView(),
]);
}
#[Route('/gh/vacante/{id}/eliminar', name: 'gh_vacante_eliminar', methods: ['GET'])]
public function eliminar(EntityManagerInterface $entityManager, \App\Services\MailerCore $mailerCore, GHVacante $entity, \App\Services\ResponseHandler $responseHandler): Response {
$entity->setEstado($entityManager->getRepository(\App\Entity\ParEstado::class)->find(3));
$vacante = $entity;
$entityManager->persist($vacante);
$entityManager->flush();
$this->addFlash('success', "Registro Eliminado exitosamente");
return $this->redirectToRoute('gh_vacante');
}
#[Route('/gh/vacante/{id}/aprobar', name: 'gh_vacante_aprobar', methods: ['GET'])]
public function aprobarVacante(Request $request, \App\Services\MailerCore $mailerCore, GHVacante $entity, \App\Services\ResponseHandler $responseHandler): Response {
$vacante = $entity;
if (!$vacante) {
throw $this->createNotFoundException('No se encontró la vacante');
}
$empresaFilial = $vacante->getEmpresaFilial()->getId();
$idPerfilCargo = $vacante->getPerfilCargo()->getId();
$estadoAnt = $vacante->getEstado();
$form = $this->createForm(GHVacanteType::class, $vacante, ['with_extra_fields' => true,'idEmpresaFilial' => $empresaFilial, 'idPerfilCargo' => $idPerfilCargo, 'method' => 'POST', 'action' => $this->generateUrl($request->attributes->get('_route'), ['id' => $vacante->getId()])]);
$form
->remove('empresaFilial')
->remove('perfilCargo')
->remove('ParTipoSeleccion')
->remove('ParTipoContrato')
// ->remove('resumenPerfilCandidato')
->remove('empresaFilial')
->remove('empresaFilial')
->remove('empresaFilial')
->remove('empresaFilial')
->remove('empresaFilial')
->remove('empresaTpm')
->remove('cargoTpm')
->remove('TipoSeleccionTmp')
->remove('TipoContratoTpm')
->remove('ResumenPerfilTpm')
->remove('rangoSalarialTpm')
->remove('sedeTpm')
->remove('fecha')
->remove('sede')
;
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->entityManager->persist($this->getUser());
$this->entityManager->flush();
$vacante->setPersonaAprueba($this->getUser()->getPersona());
$this->entityManager->persist($vacante);
$this->entityManager->flush();
$estado = $vacante->getEstado()->getId();
if ($estado == 6) {
// Validar el correo del solicitante
$emailSolicitante = [$vacante->getPersonaSolicita()?->getEmail() ?? 'gestion.humana@logisticazf.com.co'];
$mailerCore->notificarVacante('rechazar', [$vacante], $emailSolicitante);
}
$this->code = 'success';
$this->msj = "Registro almacenado con exito.";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
return $this->render('gh_vacante/aprobar.html.twig', [
'vacante' => $vacante,
'form' => $form->createView(),
]);
}
#[Route('/gh/vacante/editar/{id}', name: 'gh_vacante_edit')]
public function actualizarVacante(Request $request, GHVacante $vacante, \App\Services\ResponseHandler $responseHandler, \App\Services\MailerCore $mailerCore) {
$entityManager = $this->entityManager;
if (!$vacante) {
throw $this->createNotFoundException('No se encontró la vacante');
}
dump($vacante);
$empresaFilial = $vacante->getEmpresaFilial()->getId();
$idPerfilCargo = $vacante->getPerfilCargo()->getId();
$estadoAnt = $vacante->getEstado();
$form = $this->createForm(GHVacanteType::class, $vacante, ['with_extra_fields' => true,'idEmpresaFilial' => $empresaFilial, 'idPerfilCargo' => $idPerfilCargo, 'method' => 'POST', 'action' => $this->generateUrl($request->attributes->get('_route'), ['id' => $vacante->getId()])]);
$form
->remove('empresaTpm')
->remove('cargoTpm')
->remove('TipoSeleccionTmp')
->remove('TipoContratoTpm')
->remove('ResumenPerfilTpm')
->remove('rangoSalarialTpm')
->remove('sedeTpm')
->remove('estado')
->remove('observacionCierre')
->remove('fecha');
if ($this->getUser()->getPersona()->getPerfilCargo()->getParProceso()->getId() != 1 && !$this->getUser()->getPersona()->hasNivelDirector()) {
$form->remove('estado')->remove('observacionCierre');
}
$form->handleRequest($request);
if ($form->isSubmitted()) {
$vacante->setFecha(new \DateTime('now'));
$entityManager->persist($vacante);
$entityManager->flush();
$this->code = 'success';
$this->msj = 'Registro cargado exitosamente.';
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
return $this->render('gh_vacante/actualizar.html.twig', [
'vacante' => $vacante,
'form' => $form->createView(),
'accion' => "Editar"
]);
}
#[Route('/gh/vacante/editar_eliminada/{id}', name: 'gh_vacante_edit_eliminada')]
public function actualizarVacanteEliminada(Request $request, GHVacante $vacante, \App\Services\ResponseHandler $responseHandler, \App\Services\MailerCore $mailerCore) {
$entityManager = $this->entityManager;
if (!$vacante) {
throw $this->createNotFoundException('No se encontró la vacante');
}
$empresaFilial = $vacante->getEmpresaFilial()->getId();
$idPerfilCargo = $vacante->getPerfilCargo()->getId();
$estadoAnt = $vacante->getEstado();
$form = $this->createForm(GHVacanteEliminadaType::class, $vacante, [
'with_extra_fields' => true,
'idEmpresaFilial' => $empresaFilial,
'idPerfilCargo' => $idPerfilCargo,
'method' => 'POST',
'action' => $this->generateUrl($request->attributes->get('_route'), ['id' => $vacante->getId()])]);
$form
->remove('empresaTpm')
->remove('cargoTpm')
->remove('TipoSeleccionTmp')
->remove('TipoContratoTpm')
->remove('ResumenPerfilTpm')
->remove('rangoSalarialTpm')
->remove('sedeTpm')
->remove('estado')
->remove('observacionCierre')
->remove('fecha')
;
$estado = $vacante->getEstado();
// if ($estado->getId() == 6) {
// $form ->add('estado', EntityType::class, [
// 'class' => ParEstado::class,
// 'query_builder' => function (EntityRepository $er) {
// return $er->createQueryBuilder('e')
// ->where('e.id in (5,6)')
// ->orderBy('e.nombre', 'ASC');
// }
// ]);
// }
if ($this->getUser()->getPersona()->getPerfilCargo()->getParProceso()->getId() != 1 && !$this->getUser()->getPersona()->hasNivelDirector()) {
$form->remove('estado')->remove('observacionCierre');
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->persist($vacante);
$entityManager->flush();
if ($this->getUser()->getPersona()->getPerfilCargo()->getParNivelAutoridad()->getId() == 4) {
// si es admin notificar y autorizar.
$vacante->setEstado($this->entityManager->getRepository(\App\Entity\ParEstado::class)->find(5));
$entityManager->persist($vacante);
$entityManager->flush();
// $mailerCore->notificarVacante('notificar', [$vacante]);
} else {
$vacante->setEstado($this->entityManager->getRepository(\App\Entity\ParEstado::class)->find(4));
$entityManager->persist($vacante);
$entityManager->flush();
//$mailerCore->notificarVacante('notificar', [$vacante], ['gestion.humana@logisticazf.com.co']); //notificacion de creacion
$mailerCore->notificarVacante('gestionar', [$vacante]); //notificacion de aprobacion
}
$this->code = 'success';
$this->msj = 'Registro cargado exitosamente.';
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
return $this->render('gh_vacante/actualizar.html.twig', [
'vacante' => $vacante,
'form' => $form->createView(),
'accion' => "Editar"
]);
}
/**
* Calcula los días hábiles entre dos fechas (de lunes a viernes)
*
* @param \DateTime $startDate Fecha de inicio
* @param \DateTime $endDate Fecha final
* @return int Número de días hábiles
*/
private function calcularDiasHabiles(\DateTime $startDate, \DateTime $endDate): int {
$diasHabiles = 0;
$startDate = clone $startDate; // para no modificar el original
$startDate->modify('+1 day'); // iniciar desde el día siguiente
while ($startDate <= $endDate) {
if (in_array($startDate->format('N'), [1, 2, 3, 4, 5])) { // lunes a viernes (1 a 5)
$diasHabiles++;
}
$startDate->modify('+1 day');
}
return $diasHabiles;
}
#[Route('/gh/vacante/ver/{id}', name: 'gh_vacante_view')]
public function verVacante(Request $request, GHVacante $vacante, \App\Services\ResponseHandler $responseHandler) {
if (!$vacante) {
throw $this->createNotFoundException('No se encontró la vacante');
}
// Fecha actual
$diaActual = new \DateTime('now');
// Fecha de la vacante
$fechaVacante = $vacante->getFecha();
// Calcular días hábiles
$diasHabiles = $fechaVacante ? $this->calcularDiasHabiles($fechaVacante, $diaActual) : null;
$candidatos = $vacante->getCandidato(); // Esto ya es una colección
$candidatosContratado = 0;
foreach ($candidatos as $candidato) {
$afiliaciones = $candidato->getAfiliacionContratacion();
if (!$afiliaciones->isEmpty()) {
$tieneTipoContratado = false;
foreach ($afiliaciones as $afiliacion) {
$tipoId = $afiliacion->getTipoAfiliacion()->getId();
if (in_array($tipoId, [2, 3])) {
$tieneTipoContratado = true;
break; // ya no necesitamos seguir revisando este candidato
}
}
if ($tieneTipoContratado) {
$candidatosContratado++;
}
}
}
return $this->render('gh_vacante/ver.html.twig', [
'vacante' => $vacante,
'accion' => 'Ver',
'diasHabiles' => $diasHabiles,
'candidatosContratado' => $candidatosContratado,
]);
}
#[Route('/gh/vacante/ver_candidato/{id}', name: 'gh_vacante_ver_candidato')]
public function verCandidatoVacante(Request $request, \App\Entity\GHCandidato $candidato, \App\Services\ResponseHandler $responseHandler) {
if (!$candidato) {
throw $this->createNotFoundException('No se encontró la vacante');
}
$solicitante = $candidato->getVacante()->getCreateUser();
$solicitanteEdit = $candidato->getVacante()->getUpdateUser();
$cargoPersona = $this->getUser()->getPersona()->getPerfilCargo()->getCargo()->getId(); // ID Del cargo
// Validar si el candidato alguna vez fue rechazado o desistio
$candidatoFinalizado = false;
if($candidato->getMotivoFinalizacion())
$candidatoFinalizado = true;
// Validar quien puede ver los enlaces
$verLink = false;
if ($solicitante && $solicitante === $this->getUser()->getUsername() || $solicitante === $this->getUser()) {
$verLink = true;
} elseif ($solicitanteEdit && $solicitanteEdit === $this->getUser()->getUsername() || $solicitanteEdit === $this->getUser()) {
$verLink = true;
}
if(in_array($cargoPersona, [11,33,20]))
$verLink = false;
$personaNombre = $this->getUser()->getPersona()->getNombres();
$personaCargo = $this->getUser()->getPersona()->getPerfilCargo()->getCargo()->getNombre();
$completo = "$personaNombre ($personaCargo)";
$usuario = $this->getUser();
$procesoGH = 1;
return $this->render('gh_vacante/dashCandidato.html.twig', [
'candidato' => $candidato,
'accion' => "Ver",
'verLink' => $verLink,
'procesoGH' => $procesoGH,
'candidatoFinalizado' => $candidatoFinalizado,
]);
}
#[Route('/gh/vacante/descargar_excel/{id}', name: 'gh_vacante_excel', methods: ['GET'])]
public function descargarExcel(GHVacante $vacante, ExcelExporterService $excelExporterService): Response
{
if (!$vacante) {
throw $this->createNotFoundException('No se encontró la vacante');
}
$titulo = 'Resumen Vacante ' . $vacante->getPerfilCargo()->getCargo()->getNombre();
$perfil = $vacante->getPerfilCargo();
$empresa = $perfil->getEmpresaFilial()->first();
$sucursal = $perfil->getSede()->first();
// Inicializar cabecera y datos
$cabecera = [
'Cargo',
'Descripción del cargo',
'Responsabilidades',
'Funciones',
'Críticidad',
'Educación',
'Formación',
'Experiencia',
];
$datos = [[
strip_tags($perfil->getCargo()->getNombre() ?? ''),
strip_tags($perfil->getResumenCargo() ?? ''),
strip_tags($perfil->getResponsabilidades() ?? ''),
strip_tags($perfil->getFunciones() ?? ''),
$perfil->getParCriticidad()?->getNombreCriticidad() ?? '',
strip_tags($perfil->getEducacion() ?? ''),
strip_tags($perfil->getFormacionExperiencia() ?? ''),
strip_tags($perfil->getExperiencia() ?? ''),
]];
// Validar si hay conocimientos específicos
$conocimientos = strip_tags($perfil->getConocimientosEspecificos() ?? '');
if ($conocimientos !== '') {
$cabecera[] = 'Conocimientos Específicos';
$datos[0][] = $conocimientos;
}
// Agregar campos finales comunes
$cabecera = array_merge($cabecera, [
'Empresa',
'Fecha Solicitud',
'Rango Salarial',
'Sucursal',
'Número Vacantes',
'Requerimiento Específico',
]);
$datos[0] = array_merge($datos[0], [
$empresa->getNombre(),
$vacante->getFecha()?->format('d/m/Y') ?? '',
$perfil->getRangoSalarial() ?? '',
$sucursal->getNombre() ?? '',
$vacante->getNumeroVacante() ?? '',
strip_tags($vacante->getRequerimientoEspecifico() ?? ''),
]);
return $excelExporterService->export(
$titulo,
$cabecera,
$datos,
'Consolidado_Vacante_' . $perfil->getCargo()->getNombre() . '.xlsx'
);
}
#[Route('/gh/vacante/descargar', name: 'gh_vacante_descargar')]
public function descargarVacantes(Request $request) {
$data = $this->repository->getDescargable([5, 7]);
foreach ($data as $key => $value) {
foreach ($value as $key2 => $value2) {
if ($key2 == 'descripcion') {
$data[$key][$key2] = strip_tags($value2);
}
}
}
$res = $this->generateExcelAction(['nombreArchivo' => 'Listado de Vacantes'], ['Doc_legal' => $data]);
return $res;
}
private function generateExcelAction($archivo, $datos) {
// ask the service for a excel object
$phpExcelObject = new Spreadsheet();
$fecha = new \DateTime('now');
$modificado = isset($archivo['modificado']) ? $archivo['modificado'] : "LOOGIC";
$titulo = isset($archivo['titulo']) ? $archivo['titulo'] : "INFORME_POR_LOOGIC";
$asunto = isset($archivo['asunto']) ? $archivo['asunto'] : "INFORME_LOOGIC";
$descripcion = isset($archivo['descripcion']) ? $archivo['descripcion'] : "INFORME GENERADO POR LOOGIC";
$keyWords = isset($archivo['keyWords']) ? $archivo['keyWords'] : "INFORME LOOGIC";
$categoria = isset($archivo['categoria']) ? $archivo['categoria'] : "LOOGIC";
$nombreArchivo = isset($archivo['nombreArchivo']) ? $archivo['nombreArchivo'] . " {$fecha->format('Y-m-d His')}" : "INFORME_LOOGIC {$fecha->format('Y-m-d His')}";
$phpExcelObject->getProperties()->setCreator("LOOGIC COLOMBIA")
->setLastModifiedBy($modificado)
->setTitle($titulo)
->setSubject($asunto)
->setDescription($descripcion)
->setKeywords($keyWords)
->setCategory($categoria);
$hoja = 0;
$styleEncabezado = array(
'font' => array(
'bold' => true,
//'color' => array('rgb' => 'FF0000'),
'size' => 10,
'name' => 'Verdana'
));
$buffer = 0;
foreach ($datos as $sheetName => $array) {
$col = 'A';
$iteracion = 2;
$cambio = false;
$phpExcelObject->createSheet($hoja);
if (isset($archivo['nombreArchivo']) && $archivo['nombreArchivo'] == 'Matriz de Requisitos Legales') {
$phpExcelObject->setActiveSheetIndex($hoja)->setCellValue("A1", mb_strtoupper("Matriz General de Requisitos Legales y Otros Requisitos (GER-FR-077)", 'utf-8'));
}
foreach ($array as $arr => $val) {
foreach ($val as $key => $result) {
if ($iteracion == 2) {
$phpExcelObject->setActiveSheetIndex($hoja)->setCellValue($col . $iteracion, mb_strtoupper($key, 'utf-8'));
$phpExcelObject->getActiveSheet()->getStyle($col . $iteracion)->applyFromArray($styleEncabezado);
$phpExcelObject->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
$phpExcelObject->setActiveSheetIndex($hoja)->setCellValue($col . ($iteracion + 1), $result);
} else if ($buffer !== count($val)) {
//$iteracion = $iteracion + 2;
$phpExcelObject->setActiveSheetIndex($hoja)->setCellValue($col . ($iteracion + 2), mb_strtoupper($key, 'utf-8'));
$phpExcelObject->getActiveSheet()->getStyle($col . ($iteracion + 2))->applyFromArray($styleEncabezado);
$phpExcelObject->setActiveSheetIndex($hoja)->setCellValue($col . ($iteracion + 3), $result);
$cambio = true;
} else {
$phpExcelObject->setActiveSheetIndex($hoja)->setCellValue($col . ($iteracion + 1), $result);
}
$col++;
}
$buffer = count($val);
if ($cambio === true) {
$iteracion = $iteracion + 3; //aumento proporcional de acuerdo a el ultimo valor del encabezado.
$cambio = false;
} else {
$iteracion++;
}
$col = 'A';
}
$phpExcelObject->getActiveSheet()->setTitle($sheetName);
$hoja++;
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$phpExcelObject->setActiveSheetIndex(0);
// create the writer
$writer = new Xlsx($phpExcelObject);
ob_start();
// create the response
$writer->save('php://output');
$excelOutput = ob_get_clean();
return new Response(
$excelOutput,
200,
[
'content-type' => 'text/x-csv; charset=windows-1251',
'Content-Disposition' => 'attachment; filename="' . $nombreArchivo . '.xlsx"'
]
);
//return $response;
}
#[Route('/gh/vacante/reaperturar/{id}', name: 'gh_vacante_reaperturar')]
public function reaperturarVacante(Request $request, GHVacante $vacante, EntityManagerInterface $entityManager, MailerCore $mailerCore) {
if (!$vacante) {
throw $this->createNotFoundException('No se encontró la vacante');
}
$candidatosNoAprobados = false;
// Inicializamos el formulario antes del ciclo foreach
$empresaFilial = $vacante->getEmpresaFilial()->getId();
$idPerfilCargo = $vacante->getPerfilCargo()->getId();
$form = $this->createForm(GHVacanteType::class, $vacante, [
'with_extra_fields' => true,
'idEmpresaFilial' => $empresaFilial,
'idPerfilCargo' => $idPerfilCargo,
'method' => 'POST',
'action' => $this->generateUrl($request->attributes->get('_route'), ['id' => $vacante->getId()])
]);
$form
->remove('empresaTpm')
->remove('cargoTpm')
->remove('TipoSeleccionTmp')
->remove('TipoContratoTpm')
->remove('ResumenPerfilTpm')
->remove('rangoSalarialTpm')
->remove('sedeTpm')
->remove('estado')
->remove('observacionCierre')
->remove('fecha');
foreach ($vacante->getCandidato() as $candidato) {
$persona = $this->entityManager->getRepository(TerPersona::class)->findOneBy(['numeroDocumento' => trim($candidato->getNumeroDocumento())]);
if ($persona) {
foreach ($persona->getPeriodoPrueba() as $periodoPrueba) {
if ($periodoPrueba && $periodoPrueba->getEstado() && $periodoPrueba->getEstado()->getId() == 6) {
$candidatosNoAprobados = true;
break;
}
}
}
// Si no se encuentran candidatos no aprobados, no se puede reaperturar la vacante
if (!$candidatosNoAprobados) {
$this->code = 'warning';
$this->msj = 'No se puede reaperturar la vacante, ya que no hay candidatos desaprobados.';
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
}
$form->handleRequest($request);
if ($form->isSubmitted()) {
$vacante->setEstado($this->entityManager->getRepository(\App\Entity\ParEstado::class)->find(29));
$entityManager->persist($vacante);
$entityManager->flush();
$mailerCore->notificarVacante('reaperturar', [$vacante],[$vacante->getPersonaSolicita()->getEmail()]);
$this->code = 'success';
$this->msj = 'Registro cargado exitosamente.';
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
// Siempre debe estar aquí
return $this->render('gh_vacante/actualizar.html.twig', [
'vacante' => $vacante,
'form' => $form->createView(),
'accion' => "Editar"
]);
}
}