<?php
namespace App\Controller;
use App\Entity\GHCambioContrato;
use App\Entity\GHCandidato;
use App\Entity\GHPeriodoPrueba;
use App\Entity\ParCargo;
use App\Entity\ParEstado;
use App\Entity\TerPersona;
use App\Form\GHCambioContratoType;
use App\Form\GHPeriodoPruebaType;
use App\Repository\GHCambioContratoRepository;
use App\Repository\GHPeriodoPruebaRepository;
use Doctrine\ORM\EntityManagerInterface;
use Dompdf\Dompdf;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints\File;
#[Route('/cambio_contrato')]
class GHCambioContratoController extends AbstractController {
private $code = 0;
private $msj = "";
private $url = "";
private $html = "";
private $em = null;
private $documentHandler = null;
private $mailerCore = null;
private $repo;
public function __construct(\App\Services\DocumentHandler $documentHandler, \App\Services\MailerCore $mailerCore, \Doctrine\ORM\EntityManagerInterface $entityManager, GHCambioContratoRepository $repo) {
$this->em = $entityManager;
$this->mailerCore = $mailerCore;
$this->documentHandler = $documentHandler;
$this->repo = $repo;
}
#[Route('/', name: 'gh_cambio_contrato', methods: ['GET'])]
public function index(): Response
{
$procesoPersona = $this->getUser()->getPersona()->getPerfilCargo()->getParProceso()->getId();
//dump($procesoPersona);
$autoridadPersona = $this->getUser()->getPersona()->getPerfilCargo()->getParNivelAutoridad()->getId();
//dump($autoridadPersona);
$idPersona = $this->getUser()->getPersona()->getId();
//dump($idPersona);
if ($procesoPersona === 1 || $autoridadPersona === 4 ) {
$entities = $this->repo->getAll([4, 6, 5, 35]);
} else {
$entities = $this->repo->getAll([4, 6, 5, 35], $this->getUser()->getPersona()->getId());
}
return $this->render('gh_cambio_contrato/index.html.twig', [
'entities' => $entities,
]);
}
#[Route('/gestionar', name: 'gh_cambio_contrato_gestionar', methods: ['GET'])]
public function gestionar(GHCambioContratoRepository $gHCambioContratoRepository): Response {
$entities = $gHCambioContratoRepository->getAll([5]); //35
return $this->render('gh_cambio_contrato/index.html.twig', [
'entities' => $entities,
]);
}
#[Route('/gh/periodo/prueba', name: 'gh_periodo_prueba_cambio')]
public function periodoPruebaIndex(GHPeriodoPruebaRepository $GHPeriodoPruebaRepository): Response {
$entities = $GHPeriodoPruebaRepository->getAllMantenimiento([49,5,6], null, true);
return $this->render('gh_periodo_prueba/index.html.twig', [
'controller_name' => 'GHPeriodoPruebaController',
'entities' => $entities,
]);
}
private function limpiarValorMonetario($valor): ?float
{
if (is_null($valor)) {
return null;
}
// Convertir a string si es número
$valorString = (string) $valor;
// Remover símbolo de pesos, puntos y espacios
$valorLimpio = str_replace(['$', '.', ' ', ','], '', $valorString);
// Convertir a float
return is_numeric($valorLimpio) ? (int) $valorLimpio : null;
}
public function validarCamposMoneda(GHCambioContrato $cambioContrato, EntityManagerInterface $entityManager, FormInterface $form){
$camposMoneda = [
'salario' => 'setSalario',
'bonoSalarial' => 'setBonoSalarial',
];
foreach ($camposMoneda as $campo => $valor) {
if($form->get($campo)->getData()){
$cambioContrato->{$valor}(strval($this->limpiarValorMonetario($form->get($campo)->getData())));
}
}
$entityManager->persist($cambioContrato);
}
#[Route('/new', name: 'gh_cambio_contrato_new', methods: ['GET', 'POST'])]
public function new(Request $request, EntityManagerInterface $entityManager, \App\Services\ResponseHandler $responseHandler, \App\Services\MailerCore $mailerCore): Response {
// Validar al colaborador para saber el tipo de contrato
$idColaborador = $request->request->get('gh_cambio_contrato')['colaborador'] ?? null;
// Buscar al colaborador
if($idColaborador){
$colaborador = $entityManager->getRepository(TerPersona::class)->find($idColaborador);
// Si el tipo contrato es null, entonces no filtrar, mostrar TODOS
$idTipoContrato = $colaborador && $colaborador->getPerfilCargo()?->getTipoContrato()?->first() ? $colaborador->getPerfilCargo()?->getTipoContrato()?->first()?->getId() : null;
}else{
$idTipoContrato = null;
}
$gHCambioContrato = new GHCambioContrato();
$form = $this->createForm(GHCambioContratoType::class, $gHCambioContrato, ['method' => 'POST', 'action' => $this->generateUrl($request->attributes->get('_route')),
'id_tipo_contrato' => $idTipoContrato]);
$form->remove('observacionAprobacion')
->remove('fechaPeriodoPrueba')
->remove('aproboPeriodoPrueba')
->remove('estado')
->remove('aprobacionGerenteDirector')
;
$form
->add('fechaFinPeriodoPrueba', \Symfony\Component\Form\Extension\Core\Type\DateTimeType::class, [
'required' => false,
'widget' => 'single_text',
'html5' => false,
'format' => 'yyyy-MM-dd',
'attr' => [
'class' => 'fc-datepicker'
],
'label' => 'Fecha Fin Periodo Prueba'
])
;
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//verificar si el colaborador tiene cambios en proceso (ID #4)
$tieneProceso = $entityManager->createQuery("
SELECT COUNT(e.id)
FROM App\Entity\GHCambioContrato cc
JOIN cc.estado e
WHERE cc.colaborador = :idColaborador
AND e.id = 4
")
->setParameter('idColaborador', $gHCambioContrato->getColaborador()->getId())
->getSingleScalarResult() > 0;
//En caso de tener proceso arrancar advertencia y recargar módulo
if($tieneProceso){
// $this->addFlash('warning', "El colaborador cuenta con un cambio de contrato que se encuentra actualmente proceso");
$this->code = 'warning';
$this->msj = "El colaborador cuenta con una solicitud actualmente En Proceso";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
// return $this->redirectToRoute('gh_cambio_contrato_new');
}
$gHCambioContrato->setUsuarioSolicita($this->getUser()->getPersona());
//$gHCambioContrato->setCargo($gHCambioContrato->getColaborador()->getPerfilCargo()->getCargo()->getNombre());
// Validar campos moneda
$this->validarCamposMoneda($gHCambioContrato, $entityManager, $form);
// if ($this->getUser()->getPersona()->hasNivelDirector()) {
// // si es admin notificar y autorizar. (SE PIDIO CAMBIAR ESTO PARA QUE SIEMPRE SEA 'EN PROCESO)
// $gHCambioContrato->setEstado($entityManager->getRepository(\App\Entity\ParEstado::class)->find(5));
// $entityManager->persist($gHCambioContrato);
// $entityManager->flush();
// } else {
$gHCambioContrato->setEstado($entityManager->getRepository(\App\Entity\ParEstado::class)->find(4));
$entityManager->persist($gHCambioContrato);
$entityManager->flush();
// Validar que si la persona no es gerente o directo , envia este correo
$colaborador->getPerfilCargo()->getCargo()->getId();
$esGerenteDirector = $this->getUser()->getPersona()->getPerfilCargo()?->getCargo()?->getId() ?? null;
if(!in_array($esGerenteDirector,[1,2,5,8,11,19,29])) // Validar los IDS gerentes, directores
$mailerCore->cambioContrato('notificacion', [$gHCambioContrato]);
$mailerCore->cambioContrato('notificacionGH', [$gHCambioContrato]);
$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_cambio_contrato/new.html.twig', [
'gh_cambio_contrato' => $gHCambioContrato,
'form' => $form->createView(),
]);
}
#[Route('/{id}/editar', name: 'gh_cambio_contrato_editar', methods: ['GET', 'POST'])]
public function editar(Request $request, GHCambioContrato $gHCambioContrato, EntityManagerInterface $entityManager, \App\Services\ResponseHandler $responseHandler, \App\Services\MailerCore $mailerCore): Response {
if ($gHCambioContrato->getEstado()->getId() === 3) {
$this->code = 'warning';
$this->msj = "Registro ya procesado, imposible continuar.";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
$form = $this->createForm(GHCambioContratoType::class, $gHCambioContrato, [
'method' => 'POST',
'colaborador' => $gHCambioContrato->getColaborador(),
'action' => $this->generateUrl($request->attributes->get('_route'),
[
'id' => $gHCambioContrato->getId()
]),
'disabled_fields' => false,
// Perfil cargo de cambio contrato
'perfilCargo' => $gHCambioContrato->getCargo() ?? null
]);
$form->remove('persona')
->remove('fechaPeriodoPrueba')
->remove('aproboPeriodoPrueba')
->remove('estado')
->remove('observacionAprobacion')
->remove('aprobacionGerenteDirector')
;
$form
->add('fechaFinPeriodoPrueba', \Symfony\Component\Form\Extension\Core\Type\DateTimeType::class, [
'required' => false,
'widget' => 'single_text',
'html5' => false,
'format' => 'yyyy-MM-dd',
'attr' => [
'class' => 'fc-datepicker'
],
'label' => 'Fecha Fin Periodo Prueba'
])
;
$colaborador = $gHCambioContrato->getColaborador();
$cargoTmp = $colaborador?->getPerfilCargo()?->getCargo()?->getNombre() ?? 'N/A';
$empresaObj = $colaborador->getEmpresa();
$empresaTmp = $empresaObj?->getNombre() ?? 'N/A';
$candidato = $entityManager->getRepository(GHCandidato::class)->findOneBy([
'numeroDocumento' => $colaborador->getNumeroDocumento()
]);
$tipoContrato = null;
$sucursal = null;
$salario = null;
if($candidato){
$salario = $candidato->getContratacion() && $candidato->getContratacion()->last() ? $candidato->getContratacion()->last()->getSalario() : 'N/A';
$sucursal = $candidato->getVacante()->getSede() ? $candidato->getVacante()->getSede()->getNombre() : 'N/A';
$tipoContrato = $candidato->getVacante()->getParTipoContrato() ? $candidato->getVacante()->getParTipoContrato()->getNombre() : 'N/A';
}
$form->get('cargoTmp')->setData($cargoTmp);
$form->get('salarioTmp')->setData($salario);
$form->get('empresaTmp')->setData($empresaTmp);
$form->get('sedeTmp')->setData($sucursal);
$form->get('tipoContratoTmp')->setData($colaborador->getTipoContrato() ? $colaborador->getTipoContrato()->getNombre() : ($tipoContrato ?? 'N/A'));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$gHCambioContrato->setUpdateAt(new \DateTime('now'));
$gHCambioContrato->setUpdateUser($this->getUser()->getUsername());
// Actualizar el cambio de sucursal
if($form->get('sede')->getData() !== null){
$gHCambioContrato->getColaborador()->setSede($entityManager->getRepository(\App\Entity\TerSedeEmpresa::class)->find($form->get('sede')->getData()));
}
// Validar campos moneda
$this->validarCamposMoneda($gHCambioContrato, $entityManager, $form);
$entityManager->flush();
if ($gHCambioContrato->getEstado()->getId() == 6) {
$mailerCore->cambioContrato('rechazo', [$gHCambioContrato]);
}
$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_cambio_contrato/editar.html.twig', [
'entity' => $gHCambioContrato,
'form' => $form->createView(),
]);
}
#[Route('/{id}/confirmar_condiciones', name: 'gh_cambio_contrato_confirmar_condiciones', methods: ['GET', 'POST'])]
public function confirmarCondiciones(Request $request, GHCambioContrato $gHCambioContrato, EntityManagerInterface $entityManager, \App\Services\ResponseHandler $responseHandler, \App\Services\MailerCore $mailerCore, \App\Services\DocumentHandler $documentHandler): Response {
if ($gHCambioContrato->getEstado()->getId() == 6) {
$this->code = 'warning';
$this->msj = "Registro ya procesado, imposible continuar.";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
$form = $this->createForm(GHCambioContratoType::class, $gHCambioContrato, ['method' => 'POST', 'action' => $this->generateUrl($request->attributes->get('_route'), ['id' => $gHCambioContrato->getId()]), 'disabled_fields' => true]);
$form->add('file', \Symfony\Component\Form\Extension\Core\Type\FileType::class, [
'label' => 'Prueba Técnica',
'mapped' => false,
'required' => false,
'constraints' => [
new File([
'maxSize' => '5120k',
])
]
])
->remove('colaborador')
->remove('motivo')
->remove('empresa')
->remove('sede')
->remove('aproboPeriodoPrueba')
->remove('cambio')
->remove('cargoTmp')
->remove('salarioTmp')
->remove('empresaTmp')
->remove('sedeTmp')
->remove('tipoContratoTmp')
->remove('periodoPrueba')
->remove('observacion')
->remove('cargo')
->remove('tipoContrato')
;
/* if ($gHCambioContrato->getCargo()->getPerfilCargo()->getParCriticidad()->getId() == 1) { */
$form->add('file2', \Symfony\Component\Form\Extension\Core\Type\FileType::class, [
'label' => 'Examen medico ocupacional',
'mapped' => false,
'required' => false,
'constraints' => [
new File([
'maxSize' => '5120k',
])
]
])
->add('file3', \Symfony\Component\Form\Extension\Core\Type\FileType::class, [
'label' => 'Visita Domiciliaria',
'mapped' => false,
'required' => false,
'constraints' => [
new File([
'maxSize' => '5120k',
])
]
])
->add('file4', \Symfony\Component\Form\Extension\Core\Type\FileType::class, [
'label' => 'Otro Si',
'mapped' => false,
'required' => false,
'constraints' => [
new File([
'maxSize' => '5120k',
])
]
])
->add('file5', \Symfony\Component\Form\Extension\Core\Type\FileType::class, [
'label' => 'Cesión de Contrato',
'mapped' => false,
'required' => false,
'constraints' => [
new File([
'maxSize' => '5120k',
])
]
])
->add('file6', \Symfony\Component\Form\Extension\Core\Type\FileType::class, [
'label' => 'Carta de Notificación',
'mapped' => false,
'required' => false,
'constraints' => [
new File([
'maxSize' => '5120k',
])
]
])
->add('fechaNovedad', \Symfony\Component\Form\Extension\Core\Type\DateTimeType::class, ['required' => false, 'widget' => 'single_text', 'html5' => false, 'format' => 'yyyy-MM-dd', 'attr' => ['class' => 'fc-datepicker'], 'label' => 'Fecha Novedad'])
->add('entrevistaJefe', null, ['required' => false, 'label' => 'Entrevista Jefe Inmediato'])
->add('resultadoPruebaTecnica', \Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, ['label' => 'Concepto Prueba Técnica','required' => false, 'choices' => ['Aprobado' => 'Aprobado', 'Rechazado' => 'Rechazado'], 'placeholder' => 'Seleccione una opción'])
->add('resultadoExamenMedico', \Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, ['label' => 'Concepto Examen Médico','required' => false, 'choices' => ['Aprobado' => 'Aprobado', 'Rechazado' => 'Rechazado'], 'placeholder' => 'Seleccione una opción'])
->add('resultadoVisitaDomiciliaria', \Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, ['label' => 'Concepto Visita Domiciliaria','required' => false, 'choices' => ['Aprobado' => 'Aprobado', 'Rechazado' => 'Rechazado'], 'placeholder' => 'Seleccione una opción'])
->add('resultadoCarta', \Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, ['label' => 'Concepto Entrevista Jefe Inmediato','required' => false, 'choices' => ['Aprobado' => 'Aprobado', 'Rechazado' => 'Rechazado'], 'placeholder' => 'Seleccione una opción'])
;
if (null == $gHCambioContrato->getCargo()){
$form->remove('entrevistaJefe');
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$colaborador = $gHCambioContrato->getColaborador();
$pruebaTecnica = $form->get('file')->getData();
$examen = $form->get('file2')->getData();
$visita = $form->get('file3')->getData();
$contrato = null;
$otrosi = $form->get('file4')->getData();
$carta = null;
$cesion = $form->get('file5')->getData();
$carta = $form->get('file6')->getData();
if ($pruebaTecnica) {
$rutaArchivo = $documentHandler->cargarArchivo($pruebaTecnica, GHCambioContrato::class);
if ($rutaArchivo['code'] != 'success') {
$this->code = 'warning';
$this->msj = "Imposible continuar, valide la Prueba Técnica, {$rutaArchivo['msj']}";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
$gHCambioContrato->setPruebaTecnica($rutaArchivo['msj']);
}
if ($examen) {
$rutaArchivo = $documentHandler->cargarArchivo($examen, GHCambioContrato::class);
if ($rutaArchivo['code'] != 'success') {
$this->code = 'warning';
$this->msj = "Imposible cargar el registro examen medico, {$rutaArchivo['msj']}";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
$gHCambioContrato->setExamenMedico($rutaArchivo['msj']);
}
if ($visita) {
$rutaArchivo = $documentHandler->cargarArchivo($visita, GHCambioContrato::class);
if ($rutaArchivo['code'] != 'success') {
$this->code = 'warning';
$this->msj = "Imposible cargar el registro visita domiciliaria, {$rutaArchivo['msj']}";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
$gHCambioContrato->setVisitaDomiciliaria($rutaArchivo['msj']);
}
if ($otrosi) {
$rutaArchivo = $documentHandler->cargarArchivo($otrosi, GHCambioContrato::class);
if ($rutaArchivo['code'] != 'success') {
$this->code = 'warning';
$this->msj = "Imposible cargar el otro si, {$rutaArchivo['msj']}";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
$gHCambioContrato->setOtroSi($rutaArchivo['msj']);
}
if ($cesion) {
$rutaArchivo = $documentHandler->cargarArchivo($cesion, GHCambioContrato::class);
if ($rutaArchivo['code'] != 'success') {
$this->code = 'warning';
$this->msj = "Imposible cargar la cesion de contrato, {$rutaArchivo['msj']}";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
$gHCambioContrato->setCesionContrato($rutaArchivo['msj']);
}
if ($carta) {
$rutaArchivo = $documentHandler->cargarArchivo($carta, GHCambioContrato::class);
if ($rutaArchivo['code'] != 'success') {
$this->code = 'warning';
$this->msj = "Imposible cargar la carta de notificación, {$rutaArchivo['msj']}";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
$gHCambioContrato->setCartaNotificacion($rutaArchivo['msj']);
}
// Guardar la ruta de lois archivos en base de datos.
$entityManager->persist($gHCambioContrato);
$entityManager->flush();
// if ($gHCambioContrato->getEstado() && $gHCambioContrato->getEstado()->getId() === 35) {
// $colaborador = $entityManager->getRepository(TerPersona::class)->find($gHCambioContrato->getColaborador()->getId());
//
// if ($colaborador && $colaborador->getPerfilCargo()) {
// $cargoActual = $colaborador->getPerfilCargo()->getCargo();
// $cargoActualizado = $gHCambioContrato->getCargo()?->getCargo();
//
// if ($cargoActual && $cargoActualizado && $cargoActual->getId() !== $cargoActualizado->getId()) {
// $colaborador->getPerfilCargo()->setCargo($cargoActualizado);
// }
//
// $salarioActual = $colaborador->getPerfilCargo()->getRangoSalarial();
// $salarioActualizado = $gHCambioContrato->getSalario();
//
// if ($salarioActual && $salarioActualizado && $salarioActual != $salarioActualizado) {
// $colaborador->getPerfilCargo()->setRangoSalarial($salarioActualizado);
// }
//
// $empresaActual = $colaborador->getPerfilCargo()->getEmpresaFilial();
// $empresaActualizado = $gHCambioContrato->getEmpresa();
//
// if ($empresaActual && $empresaActualizado && $empresaActual->first()->getId() !== $empresaActualizado->getId()) {
// $colaborador->getPerfilCargo()->addEmpresaFilial($empresaActualizado);
// }
//
// $sucursalActual = $colaborador->getPerfilCargo()->getSede();
// $sucursalActualizado = $gHCambioContrato->getSede();
//
// if ($sucursalActual && $sucursalActualizado && $sucursalActual->first()->getId() !== $sucursalActualizado->getId()) {
// $colaborador->getPerfilCargo()->addSede($sucursalActualizado);
// }
//
// $tipoContratoActual = $colaborador->getPerfilCargo()->getTipoContrato();
// $tipoContratoActualizado = $gHCambioContrato->getTipoContrato();
//
// if ($tipoContratoActual && $tipoContratoActualizado && $tipoContratoActual->first()->getId() !== $tipoContratoActualizado->getId()) {
// $colaborador->getPerfilCargo()->addTipoContrato($tipoContratoActualizado);
// }
// $colaborador->setUpdateAt(new \DateTime());
// $colaborador->setUpdateUser($this->getUser()->getUsername());
// $entityManager->persist($colaborador);
// $entityManager->flush();
// }
// }
// Validar que solo valido el estado EJECUTADO
if($gHCambioContrato->getEstado()->getId() == 35) {
dump($gHCambioContrato);
// Actualizar sede
if($gHCambioContrato->getSede()) {
$colaborador->setSede($gHCambioContrato->getSede());
}
// Actualizar Salario
if($gHCambioContrato->getSalario()){
$colaborador->setSalario("$".number_format(intval($gHCambioContrato->getSalario()),0,',','.')); // Guardar $25.500.500
}
// Cambio tipo contrato
if($gHCambioContrato->getTipoContrato()) {
$colaborador->setTipoContrato($gHCambioContrato->getTipoContrato());
}
// Cambio empresa
if($gHCambioContrato->getEmpresa()){
$colaborador->setEmpresa($gHCambioContrato->getEmpresa());
}
$entityManager->persist($colaborador);
$entityManager->flush();
}
if ($gHCambioContrato->getPeriodoPrueba() && $gHCambioContrato->getEstado()->getId() == 35) {
$periodoPrueba = new \App\Entity\GHPeriodoPrueba();
$periodoPrueba->setPersona($gHCambioContrato->getColaborador());
$periodoPrueba->setFechaIngreso($gHCambioContrato->getFechaNovedad());
// $periodoPrueba->setFechaFinPeriodo($gHCambioContrato->getFechaFinPeriodoPrueba());
// $periodoPrueba->setCreateAt(new \DateTime('now'));
// $periodoPrueba->setCreateUser($this->getUser()->getUsername());
// $periodoPrueba->setUpdateAt(new \DateTime('now'));
// $periodoPrueba->setUpdateUser($this->getUser()->getUsername());
$periodoPrueba->setEstado($entityManager->getRepository(ParEstado::class)->find(49));
$periodoPrueba->setModuloMantenimiento(true);
$cambioContrato = $entityManager->getRepository(GHPeriodoPrueba::class)->findOneBy([
'cambioContrato' => $gHCambioContrato,
]);
if(!$cambioContrato)
$periodoPrueba->setCambioContrato($gHCambioContrato);
// Validar a la persona el cambio de proceso
if($gHCambioContrato->getCargo()) {
$colaborador->setPerfilCargo($gHCambioContrato->getCargo());
}
$entityManager->persist($periodoPrueba);
$entityManager->persist($colaborador);
$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]));
}
// dump($gHCambioContrato->getCargo());
// dump($gHCambioContrato->getColaborador());
$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_cambio_contrato/confirmarCondiciones.html.twig', [
'entity' => $gHCambioContrato,
'form' => $form->createView(),
]);
}
#[Route('/{id}/ver', name: 'gh_cambio_contrato_ver')]
public function ver(Request $request, GHCambioContrato $gHCambioContrato, EntityManagerInterface $entityManager, \App\Services\ResponseHandler $responseHandler, \App\Services\MailerCore $mailerCore, \App\Services\DocumentHandler $documentHandler): Response {
if ($gHCambioContrato->getEstado()->getId() == 6) {
$this->code = 'warning';
$this->msj = "Registro ya procesado, imposible continuar.";
return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
}
$colaborador = $gHCambioContrato->getColaborador();
$cambios = $entityManager->getRepository(\App\Entity\GHCambioContrato::class)->findBy(['colaborador' => $colaborador->getId()]);
$form = $this->createForm(GHCambioContratoType::class, $gHCambioContrato, ['method' => 'POST', 'action' => $this->generateUrl($request->attributes->get('_route'), ['id' => $gHCambioContrato->getId()]), 'disabled_fields' => true]);
// Validar si el colaborador fue en algun momento vacante
$candidato = $entityManager->getRepository(GHCandidato::class)->findOneBy([
'numeroDocumento' => $colaborador->getNumeroDocumento()
]);
$salario = null;
$tipoContrato = null;
$sucursal = null;
if($candidato){
$salario = $candidato->getContratacion() && $candidato->getContratacion()->last() ? $candidato->getContratacion()->last()->getSalario() : 'N/A';
$tipoContrato = $candidato->getVacante()->getParTipoContrato() ? $candidato->getVacante()->getParTipoContrato()->getNombre() : 'N/A';
$sucursal = $candidato->getVacante()->getSede() ? $candidato->getVacante()->getSede()->getNombre() : 'N/A';
}
// Sigue actualizando los campos visibles si deseas:
$cargo = $colaborador?->getPerfilCargo()?->getCargo()?->getNombre() ?? 'N/A';
$salario = $colaborador->getSalario() ? $colaborador->getSalario() : ($salario ?? 'N/A'); // Validar si encontro registro de salario desde la contratacion
$empresaObj = $colaborador?->getEmpresa();
$empresa = $empresaObj ? $empresaObj->getNombre() : 'N/A';
$tipoContrato = $colaborador->getTipoContrato() ? $colaborador->getTipoContrato()->getNombre() : ($tipoContrato ?? 'N/A');
// Comprimir la info de el colaborador
$colaboradorInfoVer = [
'empresa' => $empresa,
'cargo' => $cargo,
'salario' => $salario,
'tipoContrato' => $tipoContrato,
'sucursal' => ($colaborador->getSede() ? $colaborador->getSede()->getNombre() : ($sucursal ?? 'N/A')),
];
$form->add('file', \Symfony\Component\Form\Extension\Core\Type\FileType::class, [
'label' => 'Prueba Técnica',
'mapped' => false,
'required' => true,
'constraints' => [
new File([
'maxSize' => '5120k',
])
]
])
->remove('colaborador')
->remove('sede')
->remove('tipoContrato')
->remove('aproboPeriodoPrueba')
->remove('cambio')
->remove('cargoTmp')
->remove('salarioTmp')
->remove('empresaTmp')
->remove('sedeTmp')
->remove('tipoContratoTmp')
->remove('periodoPrueba')
->remove('observacionAprobacion')
->remove('fechaPeriodoPrueba')
->remove('salario')
->remove('bonoSalarial')
->remove('cargo')
->remove('estado');
$form
->add('fechaNovedad', \Symfony\Component\Form\Extension\Core\Type\DateTimeType::class, ['required' => true, 'widget' => 'single_text', 'html5' => false, 'format' => 'yyyy-MM-dd', 'attr' => ['class' => 'fc-datepicker'], 'label' => 'Fecha Novedad', 'disabled' => true])
->add('entrevistaJefe', null, ['required' => true, 'label' => 'Entrevista Jefe Inmediato', 'disabled' => true])
->add('resultadoPruebaTecnica', \Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, ['required' => true, 'choices' => ['Aprobado' => 'Aprobado', 'Rechazado' => 'Rechazado'], 'placeholder' => 'Seleccione un Concepto', 'disabled' => true])
->add('resultadoExamenMedico', \Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, ['required' => true, 'choices' => ['Aprobado' => 'Aprobado', 'Rechazado' => 'Rechazado'], 'placeholder' => 'Seleccione un Concepto', 'disabled' => true])
->add('resultadoVisitaDomiciliaria', \Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, ['required' => true, 'choices' => ['Aprobado' => 'Aprobado', 'Rechazado' => 'Rechazado'], 'placeholder' => 'Seleccione un Concepto', 'disabled' => true])
->add('resultadoCarta', \Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, ['required' => true, 'choices' => ['Aprobado' => 'Aprobado', 'Rechazado' => 'Rechazado'], 'placeholder' => 'Seleccione un Concepto', 'disabled' => true])
->add('estado', \Symfony\Bridge\Doctrine\Form\Type\EntityType::class, ['class' => \App\Entity\ParEstado::class, 'query_builder' => function (\Doctrine\ORM\EntityRepository $er) {
return $er->createQueryBuilder('e')
->where('e.id in (4,35,6)')
->orderBy('e.nombre', 'ASC');
}, 'label' => 'Estado',
'placeholder' => 'Seleccione una Opción.',
'disabled' => true,
'attr' => ['class' => 'form-control']])
;
return $this->render('gh_cambio_contrato/ver.html.twig', [
'entity' => $gHCambioContrato,
'cambios' => $cambios,
'form' => $form->createView(),
'colaboradorInfoVer' => $colaboradorInfoVer,
]);
}
#[Route('/gh/periodo_prueba/editar/{id}', name: 'gh_periodo_prueba_edit_cambio')]
public function editarPeriodoPrueba(Request $request, GHPeriodoPrueba $periodoPrueba,EntityManagerInterface $entityManager, \App\Services\ResponseHandler $responseHandler, \App\Services\MailerCore $mailerCore): Response {
if (!$periodoPrueba) {
throw $this->createNotFoundException('No se encontró el período de prueba.');
}
$referencia = $periodoPrueba->getPersona()?->getNombres() ?? 'Sin nombre';
$form = $this->createForm(GHPeriodoPruebaType::class, $periodoPrueba, [
'method' => 'POST',
'action' => $this->generateUrl('gh_periodo_prueba_edit', [
'id' => $periodoPrueba->getId(),
])
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$periodoPrueba->setUpdateAt(new \DateTime('now'));
$periodoPrueba->setUpdateUser($this->getUser()->getUsername());
// Limpiar el valor de porcentaje
$valor = $form->get('porcentajeTotal')->getData();
$valorLimpio = intval(str_replace('%', '', $valor));
$periodoPrueba->setPorcentajeTotal($valorLimpio);
$estado = $entityManager->getRepository(\App\Entity\ParEstado::class)
->find($periodoPrueba->getPorcentajeTotal() < 80 ? 6 : 5);
$periodoPrueba->setEstado($estado);
$nombreArchivo = uniqid() . ".pdf";
$periodoPrueba->setCarta($nombreArchivo);
$entityManager->persist($periodoPrueba);
$entityManager->flush();
// // Logo como imagen base64
// $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);
// $html = $this->renderView('formatos/calificacionPeriodoPrueba.html.twig', [
// 'logo' => $base64,
// 'entity' => $periodoPrueba
// ]);
// $dompdf = new Dompdf();
// $dompdf->setPaper([0, 0, 220, 130]);
// $dompdf->loadHtml($html);
// $dompdf->render();
//
// $output = $dompdf->output();
// $ruta = $this->getParameter('kernel.project_dir') . "/public_html/Repository/GHPeriodoPrueba/$nombreArchivo";
// file_put_contents($ruta, $output);
if ($estado->getId() === 6) {
$mailerCore->periodoPrueba('rechazo', [$periodoPrueba]);
}
$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_cambio_contrato/peridoPruebaCambio.html.twig', [
'entity' => $periodoPrueba,
'form' => $form->createView(),
'referencia' => $referencia,
]);
}
#[Route('/gh/periodo_prueba/imprimir/{id}', name: 'gh_periodo_prueba_cambio_imprimir', methods: ['GET'])]
public function imprimir(EntityManagerInterface $entityManager, GHPeriodoPrueba $periodoPrueba, \App\Services\ResponseHandler $responseHandler): Response {
if ($periodoPrueba->getEstado() == null) {
$this->addFlash('warning', "No es posible imprimir, no se ha registrado la calificación");
return $this->redirectToRoute($responseHandler->manejoRespuesta());
}
$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;
// Validar la persona que ejecuto la calificacion del periodo de prueba
$usuario = null;
if(str_contains($periodoPrueba->getUpdateUser(),"(")) // Validar que no tenga caracteres
$usuario = strstr($periodoPrueba->getUpdateUser(),"(",true);
$personaCalifica = $entityManager->getRepository(TerPersona::class)->findOneBy([
'nombres' => $usuario
]);
// validar que encontro una persona
if(!$personaCalifica) {
Throw $this->createNotFoundException("¡Error al generar PDF!");
}
$html = $this->renderView('formatos/periodoPrueba.html.twig', [
'logo' => $rutaLogo,
'entity' => $periodoPrueba,
'personaCalifica' => $personaCalifica,
]);
$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('/gh/periodo_prueba_cambio/otro_si/{id}', name: 'gh_periodo_prueba_cambio_otro_si')]
// public function otrosiPeriodoPrueba(EntityManagerInterface $entityManager, $id, \App\Services\ResponseHandler $responseHandler, \App\Services\DocumentHandler $documentHandler): Response {
//
// $periodoPrueba = $entityManager->getRepository(GHPeriodoPrueba::class)->find($id);
//
// if (!$periodoPrueba) {
// throw $this->createNotFoundException('');
// }
// if ($periodoPrueba->getEstado() == null || $periodoPrueba->getEstado()->getId() != 5) {
//
// $this->code = 'warning';
// $this->msj = "Imposible continuar, el periodo de prueba no fue aprobado.";
// return new Response(json_encode(['code' => $this->code, 'msj' => $this->msj, 'url' => $this->url, 'html' => $this->html]));
// // $this->addFlash('danger', "Imposible continuar, el periodo de prueba no fue aprobado.");
// // return $this->redirectToRoute($responseHandler->manejoRespuesta());
// }
//
// $referencia = $periodoPrueba->getPersona()->getNombres();
//
// $form = $this->createForm(GHPeriodoPruebaType::class, $periodoPrueba, ['disabled_fields' => true, 'method' => 'POST', 'action' => $this->generateUrl($request->attributes->get('_route'),['id'=>$periodoPrueba->getId()] )]);
// $form->add('file', \Symfony\Component\Form\Extension\Core\Type\FileType::class, [
// 'label' => 'Otro Si',
// 'mapped' => false,
// 'required' => true,
// 'constraints' => [
// new File([
// 'maxSize' => '5120k',
// ])
// ]
// ]);
// $form->handleRequest($request);
//
// if ($form->isSubmitted() && $form->isValid()) {
// $otroSi = $form->get('file')->getData();
// if ($otroSi) {
// $rutaArchivo = $documentHandler->cargarArchivo($otroSi, GHPeriodoPrueba::class);
// if ($rutaArchivo['code'] == 'success') {
// $periodoPrueba->setOtrosi($rutaArchivo['msj']);
// }
//
// $periodoPrueba->setUpdateAt(new \DateTime('now'));
// $periodoPrueba->setUpdateUser($this->getUser()->getUsername());
//
// $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]));
//
// // $this->addFlash('success', "Registro cargado exitosamente.");
// // return $this->redirectToRoute($responseHandler->manejoRespuesta());
// } else {
// $this->addFlash('danger', "Imposible continuar, valide el otro si.");
// }
//
// return $this->redirectToRoute($responseHandler->manejoRespuesta());
// }
//
// return $this->render('gh_cambio_contrato/peridoPruebaCambio.html.twig', [
// 'entity' => $periodoPrueba,
// 'form' => $form->createView(),
// 'referencia' => $referencia,
// ]);
// }
}