<?php
namespace App\Controller;
use App\Entity\GHCambioContrato;
use App\Entity\GHMatrizEntrenamiento;
use App\Entity\GHPerfilCargo;
use App\Entity\GHPerfilCargoRelaciones;
use App\Entity\GHVacante;
use App\Entity\ParTipoVinculacion;
use App\Entity\TerPersona;
use App\Form\GHPerfilCargoType;
use App\Form\GHPerfilCargoRelacionesType;
use App\Repository\GHPerfilCargoRepository;
use Doctrine\ORM\EntityManagerInterface;
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\Routing\Annotation\Route;
use Dompdf\Dompdf;
use App\Services\GHPerfilCargoMassUploadService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Color;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
class GHPerfilCargoController extends AbstractController
{
private $code = 0;
private $msj = "";
private $url = "";
private $html = "";
#[Route('/gh/perfil_cargo', name: 'gh_perfil_cargo')]
public function index(): Response
{
$entities = $this->entityManager->getRepository(GHPerfilCargo::class)->getAll([1]);
;
return $this->render('gh_perfil_cargo/index.html.twig', [
'entities' => $entities,
]);
}
#[Route('/gh/perfil_cargo/inactivos', name: 'gh_perfil_cargo_inactivos')]
public function inactivos(): Response
{
$entities = $this->entityManager->getRepository(GHPerfilCargo::class)->getAll([2, 3, 4, 5, 6]);
return $this->render('gh_perfil_cargo/index.html.twig', [
'entities' => $entities,
]);
}
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
#[Route('/gh/perfil_cargo/new/{step}', name: 'gh_perfil_cargo_new')]
public function crearGHPerfilCargo(Request $request, \App\Services\ResponseHandler $responseHandler, \App\Services\DocumentHandler $documentHandler, $step = 0): Response
{
$perfilCargo = new GHPerfilCargo();
$form = $this->createForm(GHPerfilCargoType::class, $perfilCargo, ['method' => 'POST', 'action' => $this->generateUrl($request->attributes->get('_route'))]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
foreach ($perfilCargo->getPersonalCargo() as $pc) {
if ($pc->getId() == $perfilCargo->getCargo()->getId()) {
$this->code = 'warning';
$this->msj = "Imposible continuar, el personal a cargo {$pc->getNombre()} no puede ser igual a el cargo {$perfilCargo->getCargo()->getNombre()}";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
}
$entityManager = $this->entityManager;
$existe = $entityManager->getRepository(GHPerfilCargo::class)->findOneBy(['cargo' => $perfilCargo->getCargo(), 'estado' => 1]);
if ($existe) {
$this->code = 'warning';
$this->msj = "Imposible continuar, ya existe un perfil de cargo para {$perfilCargo->getCargo()->getNombre()}";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
$file = $form->get('file')->getData();
if ($file) {
$rutaArchivo = $documentHandler->cargarArchivo($file, GHPerfilCargo::class);
if ($rutaArchivo['code'] != 'success') {
$this->code = 'warning';
$this->msj = "Imposible cargar el registro, {$rutaArchivo['msj']}";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
//$contrato->setEstado($this->entityManager->getRepository(\App\Entity\ParEstado::class)->find(1));
}
$perfilCargo->setArchivo($rutaArchivo['msj']);
}
$accesoInfoConf = (float) $form->get('accesoInfoConf')->getData();
$contratacionAsociados = (float) $form->get('constratacionAsociados')->getData();
$tomaDecisiones = (float) $form->get('tomaDecisiones')->getData(); // corregido
$programasInfoSensi = (float) $form->get('programasInfoSensible')->getData();
$contactoCarga = (float) $form->get('contactoCarga')->getData();
$ponderacion =
$accesoInfoConf * 0.20 +
$contratacionAsociados * 0.20 +
$tomaDecisiones * 0.25 +
$programasInfoSensi * 0.15 +
$contactoCarga * 0.20;
// Evaluación directa
if ($ponderacion >= 3) {
$perfilCargo->setParCriticidad(
$entityManager->getRepository(\App\Entity\ParCriticidad::class)->find(1)
);
} else {
$perfilCargo->setParCriticidad(
$entityManager->getRepository(\App\Entity\ParCriticidad::class)->find(2)
);
}
$perfilCargo->setEstado($this->entityManager->getRepository(\App\Entity\ParEstado::class)->find(1));
$perfilCargo->setCreateAt(new \DateTime('now'));
$entityManager->persist($perfilCargo);
$entityManager->flush();
return $this->redirectToRoute('gh_perfil_cargo_edit', ['id' => $perfilCargo->getId(), 'step' => 1]);
}
return $this->render('gh_perfil_cargo/editar.html.twig', [
'entity' => $perfilCargo,
'form' => $form->createView(),
'step' => $step,
'referencia' => $perfilCargo->getCargo()?->getNombre() ?? '',
]);
}
#[Route('/gh/perfil_cargo/ver/{id}', name: 'gh_perfil_cargo_view')]
public function verGHPerfilCargo(Request $request, GHPerfilCargo $perfilCargo, \App\Services\ResponseHandler $responseHandler): Response
{
$entityManager = $this->entityManager;
if (!$perfilCargo) {
throw $this->createNotFoundException('No se encontró el registro solicitado');
}
// Obtener las relaciones asociadas con el perfil cargo
$perfilCargoRelacion = $entityManager->getRepository(GHPerfilCargoRelaciones::class)
->findBy(['perfilCargo' => $perfilCargo]); // Obtener todas las relaciones asociadas
$formPerfilCargo = $this->createForm(GHPerfilCargoType::class, $perfilCargo, ['disabled' => true]);
return $this->render('gh_perfil_cargo/ver.html.twig', [
'perfilCargo' => $perfilCargo,
'perfilCargoRelacion' => $perfilCargoRelacion, // Asegúrate de que esta variable sea un array o Collection
'formPerfilCargo' => $formPerfilCargo->createView(),
'referencia' => $perfilCargo->getCargo()?->getNombre() ?? '',
]);
}
#[Route('/gh/perfil_cargo/edit/{id}/{step}', name: 'gh_perfil_cargo_edit')]
public function editarGHPerfilCargo(Request $request, GHPerfilCargo $perfilCargo, \App\Services\ResponseHandler $responseHandler, \App\Services\DocumentHandler $documentHandler, $step = 0): Response
{
$entityManager = $this->entityManager;
if (!$perfilCargo) {
throw $this->createNotFoundException('No se encontró el registro solicitado');
}
$empresaFilial = [];
foreach ($perfilCargo->getEmpresaFilial() as $ef) {
$empresaFilial[] = $ef->getId();
}
// Obtenemos los IDs actuales para que el form los incluya aunque no
// cumplan el filtro de nivel de autoridad (evita el select vacío en editar).
$idJefeActual = $perfilCargo->getJefeInmediatoCargo()?->getId() ?? 0;
$idCargoApruebaActual = $perfilCargo->getCargoAprueba()?->getId() ?? 0;
$form = $this->createForm(GHPerfilCargoType::class, $perfilCargo, [
'idEmpresaFilial' => $empresaFilial,
'idProceso' => $perfilCargo->getParProceso()->getId(),
'idJefeActual' => $idJefeActual,
'idCargoApruebaActual' => $idCargoApruebaActual,
'method' => 'POST',
'action' => $this->generateUrl($request->attributes->get('_route'), ['id' => $perfilCargo->getId()]),
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
foreach ($perfilCargo->getPersonalCargo() as $pc) {
if ($pc->getId() == $perfilCargo->getCargo()->getId()) {
$this->code = 'warning';
$this->msj = "Imposible continuar, el personal a cargo {$pc->getNombre()} no puede ser igual a el cargo {$perfilCargo->getCargo()->getNombre()}";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
}
$file = $form->get('file')->getData();
if ($file) {
$rutaArchivo = $documentHandler->cargarArchivo($file, GHPerfilCargo::class, "", $perfilCargo->getArchivo());
if ($rutaArchivo['code'] != 'success') {
$this->addFlash('warning', "Imposible cargar el registro, {$rutaArchivo['msj']}");
return $this->redirectToRoute($responseHandler->manejoRespuesta());
//$contrato->setEstado($this->entityManager->getRepository(\App\Entity\ParEstado::class)->find(1));
}
$perfilCargo->setArchivo($rutaArchivo['msj']);
}
$accesoInfoConf = (float) $form->get('accesoInfoConf')->getData();
$contratacionAsociados = (float) $form->get('constratacionAsociados')->getData();
$tomaDecisiones = (float) $form->get('tomaDecisiones')->getData(); // corregido
$programasInfoSensi = (float) $form->get('programasInfoSensible')->getData();
$contactoCarga = (float) $form->get('contactoCarga')->getData();
$ponderacion =
$accesoInfoConf * 0.20 +
$contratacionAsociados * 0.20 +
$tomaDecisiones * 0.25 +
$programasInfoSensi * 0.15 +
$contactoCarga * 0.20;
// Evaluación directa
if ($ponderacion >= 3) {
$perfilCargo->setParCriticidad(
$entityManager->getRepository(\App\Entity\ParCriticidad::class)->find(1)
);
} else {
$perfilCargo->setParCriticidad(
$entityManager->getRepository(\App\Entity\ParCriticidad::class)->find(2)
);
}
$perfilCargo->setFecha(new \DateTime('now'));
$entityManager->flush();
return $this->redirectToRoute('gh_perfil_cargo_edit', ['id' => $perfilCargo->getId(), 'step' => 1]);
}
return $this->render('gh_perfil_cargo/editar.html.twig', [
'entity' => $perfilCargo,
'form' => $form->createView(),
'step' => $step,
'referencia' => $perfilCargo->getCargo()?->getNombre() ?? '',
]);
}
#[Route('/gh/perfil_cargo/dashboard', name: 'gh_perfil_cargo_dashboard')]
public function dashboard(Request $request, \Doctrine\ORM\EntityManagerInterface $em, \App\Services\MailerCore $mailerCore): Response
{
$defaultData = ['message' => 'Dashboard'];
$form = $this->createFormBuilder($defaultData)
->add('empresa', \Symfony\Bridge\Doctrine\Form\Type\EntityType::class, [
'required' => false,
'placeholder' => 'Seleccione una opción',
'class' => \App\Entity\TerEmpresa::class,
'query_builder' => function (\Doctrine\ORM\EntityRepository $er) {
return $er->createQueryBuilder('e')
->orderBy('e.nombre', 'ASC');
},
'label' => 'Empresa',
'attr' => ['class' => 'form-control']
])
->add('sede', \Symfony\Bridge\Doctrine\Form\Type\EntityType::class, [
'required' => false,
'placeholder' => 'Seleccione una opción',
'class' => \App\Entity\TerSedeEmpresa::class,
'query_builder' => function (\Doctrine\ORM\EntityRepository $er) {
return $er->createQueryBuilder('p')
->orderBy('p.nombre', 'ASC');
},
'label' => 'Sucursal',
'attr' => ['class' => 'form-control']
])
->add('vinculacion', EntityType::class, [
'required' => false,
'placeholder' => 'Seleccione una opción',
'class' => ParTipoVinculacion::class,
'query_builder' => function (\Doctrine\ORM\EntityRepository $er) {
return $er->createQueryBuilder('t')
->orderBy('t.nombre', 'ASC');
},
'label' => 'Tipo Vinculación',
'attr' => ['class' => 'form-control',]
])
->add('consultar', \Symfony\Component\Form\Extension\Core\Type\SubmitType::class, [
'attr' => [
'class' => 'btn btn-primary-light btn-border-end mt-2'
],
'label_html' => true,
'label' => '<i class="fa fa-search"></i> Consultar'
])->getForm();
$form->handleRequest($request);
$estadistica = [];
if ($form->isSubmitted() && $form->isValid()) {
$empresa = $form->get('empresa')->getData() != null ? [$form->get('empresa')->getData()->getId()] : [];
$sede = $form->get('sede')->getData() != null ? [$form->get('sede')->getData()->getId()] : [];
$vinculacion = $form->get('vinculacion')->getData() != null ? [$form->get('vinculacion')->getData()->getId()] : [];
$estadistica = $em->getRepository(\App\Entity\GHPerfilCargo::class)->getConsolidadoPerfiles($empresa, $sede, $vinculacion);
} else {
$estadistica = $em->getRepository(\App\Entity\GHPerfilCargo::class)->getConsolidadoPerfiles();
}
return $this->render('gh_perfil_cargo/dashboard.html.twig', [
'estadisticas' => $estadistica,
'form' => $form->createView(),
]);
}
#[Route('/gh/perfil_cargo/dashboard/ver/{id}', name: 'gh_perfil_cargo_dashboard_ver')]
public function dashboardVer(
int $id,
Request $request,
EntityManagerInterface $em
): Response {
$empresa = $request->query->get('empresa') ? [$request->query->get('empresa')] : [];
$sede = $request->query->get('sede') ? [$request->query->get('sede')] : [];
$vinculacion = $request->query->get('vinculacion') ? [$request->query->get('vinculacion')] : [];
$cargoEstadistica = $em->getRepository(\App\Entity\GHPerfilCargo::class)
->getConsolidadoVer($id, $empresa, $sede, $vinculacion);
return $this->render('gh_perfil_cargo/dashboardVer.html.twig', [
'cargos' => $cargoEstadistica,
]);
}
#[Route('/{id}/agregar_relacion', name: 'gh_perfil_cargo_agregar_relacion')]
public function agregarRelacion(Request $request, EntityManagerInterface $entityManager, GHPerfilCargo $perfilCargo, \App\Services\ResponseHandler $responseHandler): Response
{
if (!$perfilCargo) {
throw $this->createNotFoundException('El registro selecciónado no existe, valide e intente nuevamente');
}
$perfilCargoRelacion = new \App\Entity\GHPerfilCargoRelaciones();
$form = $this->createForm(GHPerfilCargoRelacionesType::class, $perfilCargoRelacion, ['method' => 'POST', 'action' => $this->generateUrl($request->attributes->get('_route'), ['id' => $perfilCargo->getId()])]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->entityManager;
$perfilCargoRelacion->setPerfilCargo($perfilCargo);
$perfilCargoRelacion->setUpdateAt(new \DateTime('now'));
$perfilCargoRelacion->setUpdateUser($this->getUser()->getUsername());
$perfilCargoRelacion->setCreateAt(new \DateTime('now'));
$perfilCargoRelacion->setCreateUser($this->getUser()->getUsername());
$entityManager->persist($perfilCargoRelacion);
$entityManager->flush();
$this->code = 'success';
$this->msj = "Registro cargado exitosamente";
!
$this->url = $this->generateUrl('gh_perfil_cargo_edit', ['id' => $perfilCargo->getId(), 'step' => 1], 0);
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
return $this->render('gh_perfil_cargo/crearRelacion.html.twig', [
'entity' => $perfilCargo,
'form' => $form->createView(),
'referencia' => "Perfil {$perfilCargo->getCargo()->getNombre()}"
]);
}
#[Route('/{id}/editar_relacion', name: 'gh_perfil_cargo_editar_relacion')]
public function editarRelacion(Request $request, EntityManagerInterface $entityManager, \App\Entity\GHPerfilCargoRelaciones $perfilCargoRelacion, \App\Services\ResponseHandler $responseHandler): Response
{
if (!$perfilCargoRelacion) {
throw $this->createNotFoundException('El registro selecciónado no existe, valide e intente nuevamente');
}
$form = $this->createForm(GHPerfilCargoRelacionesType::class, $perfilCargoRelacion, ['method' => 'POST', 'action' => $this->generateUrl($request->attributes->get('_route'), ['id' => $perfilCargoRelacion->getId()])]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->entityManager;
$perfilCargoRelacion->setUpdateAt(new \DateTime('now'));
$perfilCargoRelacion->setUpdateUser($this->getUser()->getUsername());
$entityManager->persist($perfilCargoRelacion);
$entityManager->flush();
$this->code = 'success';
$this->msj = "Registro cargado exitosamente";
$this->url = $this->generateUrl('gh_perfil_cargo_edit', ['id' => $perfilCargoRelacion->getPerfilCargo()->getId(), 'step' => 1], 0);
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
return $this->render('gh_perfil_cargo/editarRelacion.html.twig', [
'entity' => $perfilCargoRelacion->getPerfilCargo(),
'form' => $form->createView(),
'referencia' => "Perfil {$perfilCargoRelacion->getPerfilCargo()->getCargo()->getNombre()}"
]);
}
#[Route('/{id}/eliminar_relacion', name: 'gh_perfil_cargo_eliminar_relacion', methods: ['GET'])]
public function eliminarRelacion(EntityManagerInterface $entityManager, \App\Entity\GHPerfilCargoRelaciones $perfilCargoRelacion, \App\Services\ResponseHandler $responseHandler): Response
{
if (!$perfilCargoRelacion) {
throw $this->createNotFoundException('El registro selecciónado no existe, valide e intente nuevamente');
}
$perfilCargo = $perfilCargoRelacion->getPerfilCargo();
$entityManager->remove($perfilCargoRelacion);
$entityManager->flush();
return $this->redirectToRoute('gh_perfil_cargo_edit', ['id' => $perfilCargo->getId(), 'step' => 1]);
}
#[Route('/{id}/eliminar', name: 'gh_perfil_cargo_eliminar', methods: ['POST'])]
public function eliminar(EntityManagerInterface $entityManager, GHPerfilCargo $perfilCargo, \App\Services\ResponseHandler $responseHandler): Response
{
$perfilCargo->setEstado($this->entityManager->getRepository(\App\Entity\ParEstado::class)->find(2));
$entityManager->persist($perfilCargo);
$entityManager->flush();
$this->addFlash('success', "Registro Eliminado exitosamente");
return $this->redirectToRoute('gh_perfil_cargo');
}
#[Route('/{id}/reactivar_eleiminar', name: 'gh_perfil_cargo_reActivar', methods: ['POST'])]
public function reActivar(EntityManagerInterface $entityManager, GHPerfilCargo $perfilCargo, \App\Services\ResponseHandler $responseHandler): Response
{
$perfilCargo->setEstado($this->entityManager->getRepository(\App\Entity\ParEstado::class)->find(1));
$entityManager->persist($perfilCargo);
$entityManager->flush();
$this->addFlash('success', "Registro Reactivado exitosamente");
return $this->redirectToRoute('gh_perfil_cargo_inactivos');
}
#[Route('/{id}/imprimir', name: 'gh_perfil_cargo_imprimir', methods: ['GET'])]
public function imprimir(EntityManagerInterface $entityManager, GHPerfilCargo $perfilCargo, \App\Services\ResponseHandler $responseHandler): Response
{
$path = $this->getParameter('kernel.project_dir') . '/public_html/assets/img/brand/logos-empresas.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
$rutaLogo = $base64;
$html = $this->renderView('formatos/formatoPerfilCargo.html.twig', ['logo' => $rutaLogo, 'perfilCargo' => $perfilCargo]);
$dompdf = new Dompdf();
//$customPaper = array(0, 0, 220, 130);
//$dompdf->setPaper($customPaper);
$dompdf->loadHtml($html);
$dompdf->render();
return new Response(
$dompdf->stream('resume', ["Attachment" => false]),
Response::HTTP_OK,
['Content-Type' => 'application/pdf']
);
}
#[Route('/{id}/imprimir_matriz', name: 'gh_perfil_cargo_imprimir_matriz', methods: ['GET'])]
public function imprimirMatriz(EntityManagerInterface $entityManager, GHPerfilCargo $perfilCargo, \App\Services\ResponseHandler $responseHandler): Response
{
$path = $this->getParameter('kernel.project_dir') . '/public_html/assets/img/brand/logos-empresas.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
$rutaLogo = $base64;
$html = $this->renderView('formatos/matrizCriticidad.html.twig', ['logo' => $rutaLogo, 'perfilCargo' => $perfilCargo]);
$dompdf = new Dompdf();
//$customPaper = array(0, 0, 220, 130);
//$dompdf->setPaper($customPaper);
$dompdf->set_paper('letter', 'landscape');
$dompdf->loadHtml($html);
$dompdf->render();
return new Response(
$dompdf->stream('resume', ["Attachment" => false]),
Response::HTTP_OK,
['Content-Type' => 'application/pdf']
);
}
#[Route('/imprimir_matriz_consolidado', name: 'gh_perfil_cargo_imprimir_matriz_consolidado', methods: ['GET'])]
public function imprimirMatrizConsolidado(EntityManagerInterface $entityManager, \App\Services\ResponseHandler $responseHandler): Response
{
$path = $this->getParameter('kernel.project_dir') . '/public_html/assets/img/brand/logos-empresas.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
$rutaLogo = $base64;
$perfilesCargo = $entityManager->getRepository(GHPerfilCargo::class)->findAll();
$html = $this->renderView('formatos/matrizCriticidadConsolidado.html.twig', ['logo' => $rutaLogo, 'perfilCargo' => $perfilesCargo]);
$dompdf = new Dompdf();
//$customPaper = array(0, 0, 220, 130);
//$dompdf->setPaper($customPaper);
$dompdf->set_paper('letter', 'landscape');
$dompdf->loadHtml($html);
$dompdf->render();
return new Response(
$dompdf->stream('resume', ["Attachment" => false]),
Response::HTTP_OK,
['Content-Type' => 'application/pdf']
);
}
// =========================================================================
// ── CARGUE MASIVO ────────────────────────────────────────────────────────
// =========================================================================
#[Route('/gh/perfil_cargo/cargue-masivo/modal', name: 'gh_perfil_cargo_mass_upload_modal', methods: ['GET'])]
public function cargueMasivoModal(): Response
{
return $this->render('gh_perfil_cargo/cargue_masivo.html.twig');
}
#[Route('/gh/perfil_cargo/cargue-masivo/descargar_plantilla', name: 'gh_perfil_cargo_plantilla', methods: ['GET'])]
public function descargarPlantilla(): Response
{
$spreadsheet = new Spreadsheet();
$hoja = $spreadsheet->getActiveSheet();
$hoja->setTitle('Cargue Perfiles');
// Columnas del cargue masivo (APROBADO POR debe ser el nombre exacto del cargo aprobador)
$columnas = [
'PROCESO',
'SUBPROCESO',
'CARGO',
'EMPRESAS',
'SUCURSALES',
'PRESTA SERVICIO A',
'JEFE INMEDIATO',
'PERSONAL A CARGO',
'NIVEL AUTORIDAD',
'NIVEL EDUCATIVO',
'TIPO PERFIL',
'TIPO CONTRATO',
'TIPO VINCULACION',
'SISTEMAS DE INFORMACION',
'RECURSOS DEL PERFIL',
'PRUEBA TECNICA',
'RANGO SALARIAL',
'EDUCACION',
'FORMACION',
'EXPERIENCIA',
'HABILIDADES',
'OBJETIVO DEL CARGO',
'RESPONSABILIDADES Y FUNCIONES',
'DOCUMENTOS APLICABLES',
'CONOCIMIENTOS ESPECIFICOS',
'COMPETENCIAS ORGANIZACIONALES',
'COMPETENCIAS FUNCIONALES',
'APROBADO POR',
'CRITICIDAD: ACCESO INFO CONFIDENCIAL',
'CRITICIDAD: CONTRATACION ASOCIADOS',
'CRITICIDAD: TOMA DECISIONES',
'CRITICIDAD: MANEJO INFO SENSIBLE',
'CRITICIDAD: CONTACTO CARGA'
];
// Fila de datos de ejemplo (APROBADO POR debe ser el nombre exacto del cargo, ej: DIRECTOR DE OPERACIONES)
$filaEjemplo = [
'TI',
'TI',
'Test - 14052026',
'AAI, LOG',
'Bogotá, Medellín',
'AAI',
'Desarrollador - TEST CARGO NUEVO',
'Director TI ,Pruebas IT',
'NIVEL 4',
'Técnico',
'Administrativo',
'Indefinido, Fijo',
'Directo',
'SIIGO, Otro',
'Carnetización, Gestión de Usuarios',
'SI',
'2000000 - 3000000',
'Técnico en Comercio Exterior',
'Normativa aduanera',
'2 años de experiencia',
'Trabajo bajo presión',
'Asegurar soporte',
'Revisar infraestructura',
'Decreto 1165',
'Manejo de VUCE',
'ORIENTACIÓN AL LOGRO',
'ATENCIÓN AL DETALLE',
'TEST CREAR APROBADO POR',
'1',
'3',
'5',
'5',
'3'
];
foreach ($columnas as $index => $nombreColumna) {
$letraColumna = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($index + 1);
$celda = $letraColumna . '1';
$hoja->setCellValue($celda, $nombreColumna);
$colorFondo = 'FF1A56A0'; // Azul oscuro por defecto
if (str_starts_with($nombreColumna, 'CRITICIDAD:'))
$colorFondo = 'FFC0392B'; // Rojo para criticidad
elseif (str_starts_with($nombreColumna, 'COMPETENCIAS'))
$colorFondo = 'FF8E44AD'; // Morado para competencias
elseif ($nombreColumna === 'APROBADO POR')
$colorFondo = 'FF1E8449'; // Verde para aprobado por
elseif (str_starts_with($nombreColumna, 'TIPO') || str_starts_with($nombreColumna, 'NIVEL'))
$colorFondo = 'FFD35400';
$hoja->getStyle($celda)->applyFromArray([
'font' => [
'bold' => true,
'color' => ['argb' => Color::COLOR_WHITE],
'size' => 11,
],
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => ['argb' => $colorFondo],
],
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
'wrapText' => true,
],
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
'color' => ['argb' => 'FFAAAAAA'],
],
],
]);
$hoja->getColumnDimension($letraColumna)->setAutoSize(true);
$hoja->setCellValue($letraColumna . '2', $filaEjemplo[$index]);
}
$writer = new Xlsx($spreadsheet);
$temp_file = tempnam(sys_get_temp_dir(), 'Plantilla');
$writer->save($temp_file);
return $this->file($temp_file, 'Plantilla_Cargue_PerfilCargo.xlsx', ResponseHeaderBag::DISPOSITION_ATTACHMENT);
}
#[Route('/gh/perfil_cargo/cargue-masivo/validar', name: 'gh_perfil_cargo_mass_upload_validar', methods: ['POST'])]
public function validar(Request $request, GHPerfilCargoMassUploadService $uploadService): JsonResponse
{
$archivo = $request->files->get('archivo');
if (!$archivo) {
return new JsonResponse(['exito' => false, 'mensaje' => 'No se subió ningún archivo.']);
}
try {
$filas = $uploadService->leerExcel($archivo);
$resultado = $uploadService->validarArchivo($filas);
return new JsonResponse(['exito' => true, 'resultado' => $resultado]);
} catch (\Exception $e) {
return new JsonResponse(['exito' => false, 'mensaje' => 'Error validando: ' . $e->getMessage()]);
}
}
#[Route('/gh/perfil_cargo/cargue_masivo/procesar', name: 'gh_perfil_cargo_mass_upload_procesar', methods: ['POST'])]
public function procesar(Request $request, GHPerfilCargoMassUploadService $uploadService): JsonResponse
{
$archivo = $request->files->get('archivo');
if (!$archivo) {
return new JsonResponse(['exito' => false, 'mensaje' => 'No se subió ningún archivo.']);
}
try {
$filas = $uploadService->leerExcel($archivo);
$resumen = $uploadService->procesarArchivo($filas);
return new JsonResponse(['exito' => true, 'resumen' => $resumen]);
} catch (\Exception $e) {
return new JsonResponse(['exito' => false, 'mensaje' => 'Error al procesar: ' . $e->getMessage()]);
}
}
}