<?php
namespace App\Controller\Notificacion;
use App\Entity\Notificacion\Notificacion;
use App\Form\Notificacion\NotificacionType;
use App\Form\Notificacion\NotificacionEditType;
use App\Repository\Notificacion\NotificacionRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Form\Notificacion\NotificacionFiltroType;
use App\Form\Notificacion\NotificacionReceptoresType;
use App\Repository\SsoPersonaRepository;
use App\Entity\Notificacion\NotificacionUsuario;
use App\Repository\Notificacion\NotificacionAreasRepository;
use App\Repository\Notificacion\NotificacionUsuarioRepository;
use App\Repository\SsoUserRepository;
use App\Security\Voter\NotificacionVoter;
use Symfony\Component\Workflow\Registry;
#[Route('/notificacion/notificacion')]
class NotificacionController extends AbstractController
{
public const FORM_CONSULTA_NOTIFICACION = 'consulta_notificacion_form';
#[Route('/listado/{reset}', name: 'notificaciones_listado', methods: ['GET', 'POST'])]
public function notificacionesListado(
Request $request,
NotificacionAreasRepository $notificacionAreasRepository,
int $reset = null,
): Response
{
// Reinicio el formulario si reset = 1
if ($reset == 1)
$request->getSession()->remove(self::FORM_CONSULTA_NOTIFICACION);
// Inicializo el formulario con lo seteado previamente en la sesión
$data = ($request->getSession()->has(self::FORM_CONSULTA_NOTIFICACION))
? $request->getSession()->get(self::FORM_CONSULTA_NOTIFICACION)
: null;
$data['usuario_admin'] = $notificacionAreasRepository->esUsuarioAdmin($this->getUser()->getUserIdentifier());
$form = $this->createForm(NotificacionFiltroType::class, $data);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Guardo configuración del formulario en la sesión
$request->getSession()->set(self::FORM_CONSULTA_NOTIFICACION, $form->getData());
}
return $this->renderForm('notificacion/notificacion/index.html.twig', [
'form' => $form,
]);
}
#[Route('/notificacion_datos', name: 'notificaciones_datos', methods: ['POST'])]
public function notificacionesDatos(
Request $request,
NotificacionRepository $notificacionRepository,
NotificacionAreasRepository $notificacionAreasRepository,
Registry $workflows
): Response
{
// Proceso si hay filtro de datos
if ($request->getSession()->has(self::FORM_CONSULTA_NOTIFICACION)) {
$params['formulario'] = array_filter($request->getSession()->get(self::FORM_CONSULTA_NOTIFICACION));
}
$params['user'] = $this->getUser()->getUserIdentifier();
$params['draw'] = intval($request->request->get('draw'));
$params['start'] = $request->request->get('start');
$params['length'] = $request->request->get('length');
$params['search'] = $request->request->get('search');
$params['orders'] = $request->request->get('order');
$params['columns'] = $request->request->get('columns');
$params['usuarioAdmin'] = $notificacionAreasRepository->esUsuarioAdmin($params['user']);
$notificaciones = $notificacionRepository->loadNotificacionesData($params);
$params['start'] = 0;
$params['length'] = $notificacionRepository->count([]);
$notificacionesSinPaginar = $notificacionRepository->loadNotificacionesData($params);
// Agrego campos de acciones y url de la imagen
$notificaciones = array_reduce($notificaciones, function ($carry, $item) use($workflows) {
$urlSeleccion = $this->generateUrl('notificacion_validacion_edit', [
'idView' => $item['idView']
]);
$urlShowModal = $this->generateUrl('notificacion_show_modal', [
'idView' => $item['idView']
]);
$urlDetalle = $this->generateUrl('notificaciones_usuario_listado', [
'idView' => $item['idView']
]);
$notificacion = new Notificacion();
$notificacion->setSsoUsuario($item['sso_usuario']);
$notificacion->setEstado($item['estado']);
$workflow = $workflows->get($notificacion, 'notificacion');
if($workflow->can($notificacion, 'eliminar') && $this->isGranted(NotificacionVoter::ACCESS, $notificacion))
{
$urlEliminar = $this->generateUrl('notificacion_eliminar', [
'idView' => $item['idView']
]);
}
// Piso el estado con el span
$estado_class = Notificacion::VIEW_ESTADO[$item['estado']]['show_class'];
$estado_name = Notificacion::VIEW_ESTADO[$item['estado']]['show_name'];
$item['estado'] = "<span class='badge {$estado_class}'>{$estado_name}</span>";
$carry[] = $item + [
"acciones" => [
"seleccionar" => $urlSeleccion,
"showModal" => $urlShowModal,
"detalle" => $urlDetalle,
"eliminar" => isset($urlEliminar) ? $urlEliminar : null,
],
'estado' => $item['estado'],
];
return $carry;
}, []);
$respuesta['draw'] = $params['draw'];
$respuesta['recordsTotal'] = $params['length'];
$respuesta['recordsFiltered'] = count($notificacionesSinPaginar);
$respuesta['data'] = $notificaciones;
return $this->json($respuesta);
}
#[Route('/new', name: 'notificacion_notificacion_new', methods: ['GET', 'POST'])]
public function new(
Request $request,
EntityManagerInterface $entityManager,
Registry $workflows
): Response
{
$notificacion = new Notificacion();
$form = $this->createForm(NotificacionType::class, $notificacion);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$workflows->get($notificacion, 'notificacion')->getMarking($notificacion);
$entityManager->persist($notificacion);
$entityManager->flush();
if($form->getClickedButton() ? $form->getClickedButton()->getName() == "adjuntos" : false)
{
return $this->redirectToRoute('notificacion_notificacion_edit', [
'idView' => $notificacion->getIdView(),
'modalAdjuntoOpen' => true
], Response::HTTP_SEE_OTHER);
}
return $this->redirectToRoute('notificacion_cargar_receptores', [
'idView' => $notificacion->getIdView()
], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('notificacion/notificacion/new.html.twig', [
'notificacion' => $notificacion,
'form' => $form,
]);
}
#[Route('/{idView}/modal', name: 'notificacion_show_modal', methods: ['GET'])]
public function showModal(
Notificacion $notificacion,
NotificacionUsuarioRepository $notificacionUsuarioRepository
): Response
{
$this->denyAccessUnlessGranted(NotificacionVoter::ACCESS, $notificacion);
$leidos = $notificacionUsuarioRepository->findLeidosByNotificacion($notificacion);
$noLeidos = $notificacionUsuarioRepository->findNoLeidosByNotificacion($notificacion);
$mensaje = $notificacion->getMensaje();
//Si contiene el boton (de momento las notificaciones de confirmacion de asistencia)
if(strpos($mensaje, '"btn-'))
{
//Se reemplaza el href, por vacio, para que no realice confirmacion
$mensajeFinal = preg_replace('/href="([^\s]+)"/', '', $mensaje);
$notificacion->setMensaje($mensajeFinal);
}
return $this->render('notificacion/notificacion/showModal.html.twig', [
'notificacion' => $notificacion,
'leidos' => $leidos,
'noLeidos' => $noLeidos,
]);
}
#[Route('/{idView}/cargarReceptores', name: 'notificacion_cargar_receptores', methods: ['GET', 'POST'])]
public function cargarReceptores(
Request $request,
Notificacion $notificacion,
SsoPersonaRepository $ssoPersonaRepository
): Response
{
$this->denyAccessUnlessGranted(NotificacionVoter::ACCESS, $notificacion);
$form = $this->createForm(NotificacionReceptoresType::class);
$form->handleRequest($request);
$incorrectos = array();
$correctos = array();
if ($form->isSubmitted() && $form->isValid()) {
if($form->get('guardar')->isClicked())
{
$file = $form->get('receptores')->getData();
$handle = fopen($file, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$dni = preg_replace('~[\r\n]+~', '', $line);
$dniExiste = $ssoPersonaRepository->findByDni($dni);
if ($dniExiste) {
array_push($correctos, $dniExiste);
}
else{
array_push($incorrectos, $dni);
}
}
fclose($handle);
}
}
else
{
$dni = $form->get('receptor')->getData();
$dniExiste = $ssoPersonaRepository->findByDni($dni);
if ($dniExiste) {
array_push($correctos, $dniExiste);
}
else{
array_push($incorrectos, $dni);
}
}
$request->getSession()->set('correctos', $correctos);
$request->getSession()->set('incorrectos', $incorrectos);
return $this->redirectToRoute('ver_receptores', [
'idView' => $notificacion->getIdView()
], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('notificacion/notificacion/cargarReceptores.html.twig', [
'notificacion' => $notificacion,
'form' => $form,
]);
}
#[Route('/{idView}/verReceptores', name: 'ver_receptores', methods: ['GET', 'POST'])]
public function verReceptores(
Notificacion $notificacion,
Request $request,
): Response
{
$this->denyAccessUnlessGranted(NotificacionVoter::ACCESS, $notificacion);
$correctos = $request->getSession()->get('correctos');
$incorrectos = $request->getSession()->get('incorrectos');
return $this->render('notificacion/notificacion/verReceptores.html.twig', [
'notificacion' => $notificacion,
'correctos' => $correctos,
'incorrectos' => $incorrectos
]);
}
#[Route('/{idView}/crearNotificacionesUsuario', name: 'crear_notificaciones_usuario', methods: ['GET', 'POST'])]
public function crearNotificacionesUsuario(
Notificacion $notificacion,
Request $request,
EntityManagerInterface $entityManager,
SsoUserRepository $ssoUserRepository,
Registry $workflows
): Response
{
$this->denyAccessUnlessGranted(NotificacionVoter::ACCESS, $notificacion);
$correctos = $request->getSession()->get('correctos');
$workflow = $workflows->get($notificacion, 'notificacion');
foreach ($correctos as $dniCorrecto) {
$usuario = $ssoUserRepository->findUsuarioPorDni($dniCorrecto[0]->getDni());
$notificacionUsuario = new NotificacionUsuario();
$notificacionUsuario->setUsuario($usuario);
$workflowUsuario = $workflows->get($notificacionUsuario, 'notificacion_usuario');
$workflowUsuario->getMarking($notificacionUsuario);
$notificacion->addNotificacionesUsuario($notificacionUsuario);
}
$entityManager = $this->getDoctrine()->getManager();
$workflow->apply($notificacion, 'publicar');
$entityManager->flush();
$request->getSession()->getFlashBag()->add(
'notice', // notice / warning / error
"Estimado/a la notificación, fue publicada correctamente."
);
return $this->redirectToRoute('notificaciones_listado', [
'reset' => 1
], Response::HTTP_SEE_OTHER);
}
#[Route('/{idView}/edit/{modalAdjuntoOpen}', name: 'notificacion_notificacion_edit', methods: ['GET', 'POST'])]
public function edit(
Request $request,
Notificacion $notificacion,
EntityManagerInterface $entityManager,
bool $modalAdjuntoOpen = false ,
): Response
{
$this->denyAccessUnlessGranted(NotificacionVoter::ACCESS, $notificacion);
$tieneReceptores = count($notificacion->getNotificacionesUsuario()) > 0;
$form = $this->createForm(NotificacionEditType::class, $notificacion);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->flush();
if ($form->get('guardar')->isClicked()) {
if ($tieneReceptores) {
$request->getSession()->getFlashBag()->add(
'warning', // notice / warning / error
"Estimado/a la notificación fue persistida como BORRADOR y no fue publicada."
);
return $this->redirectToRoute('notificaciones_listado', [], Response::HTTP_SEE_OTHER);
} else {
return $this->redirectToRoute('notificacion_cargar_receptores', [
'idView' => $notificacion->getIdView()
], Response::HTTP_SEE_OTHER);
}
} elseif(($form->get('guardaryPublicar')->isClicked()) ) {
return $this->redirectToRoute('notificacion_editar_publicar', [
'idView' => $notificacion->getIdView()
], Response::HTTP_SEE_OTHER);
}
else
{
return $this->redirectToRoute('notificacion_cargar_receptores', [
'idView' => $notificacion->getIdView()
], Response::HTTP_SEE_OTHER);
}
}
return $this->renderForm('notificacion/notificacion/edit.html.twig', [
'notificacion' => $notificacion,
'form' => $form,
'tieneReceptores' => $tieneReceptores,
'modalAdjuntoOpen' => $modalAdjuntoOpen,
]);
}
#[Route('/{idView}/editarypublicar', name: 'notificacion_editar_publicar', methods: ['GET', 'POST'])]
public function editarPublicar(
Request $request,
Notificacion $notificacion,
EntityManagerInterface $entityManager,
Registry $workflows
): Response
{
$this->denyAccessUnlessGranted(NotificacionVoter::ACCESS, $notificacion);
$workflow = $workflows->get($notificacion, 'notificacion');
$workflow->apply($notificacion, 'publicar');
$entityManager->flush();
$request->getSession()->getFlashBag()->add(
'notice', // notice / warning / error
"Estimado/a la notificación, fue publicada correctamente."
);
return $this->redirectToRoute('notificaciones_listado',
[], Response::HTTP_SEE_OTHER);
}
#[Route('/{idView}/validacionEdit', name: 'notificacion_validacion_edit', methods: ['GET', 'POST'])]
public function validacionEdit(
Request $request,
Notificacion $notificacion,
EntityManagerInterface $entityManager,
NotificacionUsuarioRepository $notificacionUsuarioRepository,
Registry $workflows): Response
{
$this->denyAccessUnlessGranted(NotificacionVoter::ACCESS, $notificacion);
$leidos = $notificacionUsuarioRepository->findLeidosByNotificacion($notificacion);
$workflow = $workflows->get($notificacion, 'notificacion');
if (count($leidos) > 0) {
//si no cumple condiciones para editar lo dejo en el listado con mensaje flash de error.
$request->getSession()->getFlashBag()->add(
'error', // notice / warning / error
"Estimado/a no puede editar esta notificación porque ya fue leída al menos una vez. Ud. podría crear una nueva rectificando ésta."
);
return $this->redirectToRoute('notificaciones_listado', [], Response::HTTP_SEE_OTHER);
}
if ($notificacion->getEstado() == Notificacion::ESTADO_PUBLICADO) {
$workflow->apply($notificacion, 'despublicar');
$request->getSession()->getFlashBag()->add(
'warning', // notice / warning / error
"Estimado/a la notificación fue despublicada y marcada como BORRADOR. Vuelva a publicarla con el botón Guardar y Publicar."
);
$entityManager->flush();
}
return $this->redirectToRoute('notificacion_notificacion_edit', [
'idView' => $notificacion->getIdView()
], Response::HTTP_SEE_OTHER);
}
#[Route('/{idView}/eliminar', name: 'notificacion_eliminar', methods: ['GET', 'POST'])]
public function eliminar(
Request $request,
Notificacion $notificacion,
EntityManagerInterface $entityManager,
Registry $workflows
): Response
{
$this->denyAccessUnlessGranted(NotificacionVoter::ACCESS, $notificacion);
$workflow = $workflows->get($notificacion, 'notificacion');
if($workflow->can($notificacion, 'eliminar'))
{
$workflow->apply($notificacion, 'eliminar');
$entityManager->flush();
$request->getSession()->getFlashBag()->add(
'notice', // notice / warning / error
"Estimado/a la notificación, fue eliminada correctamente."
);
}
else
{
$request->getSession()->getFlashBag()->add(
'error', // notice / warning / error
"Estimado/a la notificación no puede ser eliminada, ya esta publicada."
);
}
return $this->redirectToRoute('notificaciones_listado',
[], Response::HTTP_SEE_OTHER);
}
}