<?php
namespace App\Controller;
use App\Entity\AssignedBadge;
use App\Entity\Badge;
use App\Entity\CompanyOrder;
use App\Entity\ErrorStamped;
use App\Entity\Operator;
use App\Entity\Stamped;
use App\Form\StampedInOutType;
use App\Form\StampedMensaSacchettoType;
use App\Form\StampedMensaType;
use App\Repository\StampedRepository;
use App\Service\TimbratoreLogger;
use App\Utils\DateTimeUtils;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController extends AbstractController
{
private $doctrine;
private $timbratoreLogger;
public function __construct(
ManagerRegistry $doctrine,
TimbratoreLogger $timbratoreLogger
)
{
$this->doctrine = $doctrine;
$this->timbratoreLogger = $timbratoreLogger;
}
/**
* @Route("/", name="home", methods={"GET","POST"})
* @param StampedRepository $stampedRepository
* @return Response
* @throws \Exception
*/
public function index(StampedRepository $stampedRepository): Response
{
if ($this->isGranted("ROLE_ADMIN_EMZA")) {
return $this->redirectToRoute('stamped_index', ['page' => '1', 'companyOrderType' => CompanyOrder::TYPE_EMZA]);
} elseif ($this->isGranted("ROLE_ADMIN")) {
return $this->redirectToRoute('stamped_index', ['page' => '1', 'companyOrderType' => CompanyOrder::TYPE_CANTIERE]);
}elseif ($this->isGranted("ROLE_ADMIN_MENSA")) {
return $this->redirectToRoute('stamped_index', ['page' => '1', 'companyOrderType' => CompanyOrder::TYPE_MENSA]);
}elseif ($this->isGranted("ROLE_ADMIN_CANTIERE")) {
return $this->redirectToRoute('stamped_index', ['page' => '1', 'companyOrderType' => CompanyOrder::TYPE_CANTIERE]);
} elseif ($this->isGranted("ROLE_MENSA_ASPORTO")) {
$form = $this->createForm(StampedMensaSacchettoType::class);
$userCompanyOrder = $this->get('security.token_storage')->getToken()->getUser()->getCompanyOrder();
return $this->render('default/home-mensa-sacchetto.html.twig', [
'form' => $form->createView(),
'userCompany' => $userCompanyOrder,
]);
} elseif ($this->isGranted("ROLE_MENSA")) {
$form = $this->createForm(StampedMensaType::class);
$userCompanyOrder = $this->get('security.token_storage')->getToken()->getUser()->getCompanyOrder();
return $this->render('default/home-mensa.html.twig', [
'form' => $form->createView(),
'userCompany' => $userCompanyOrder,
]);
} else {
$form = $this->createForm(StampedInOutType::class);
$userCompanyOrder = $this->get('security.token_storage')->getToken()->getUser()->getCompanyOrder();
return $this->render('default/home.html.twig', [
'form' => $form->createView(),
'userCompany' => $userCompanyOrder,
]);
}
}
/**
* @Route("/ajax/timbra", name="timbra_ajax", methods={"POST"})
* @param Request $request
* @return Response
* @throws \Exception
*/
public function timbraAjax(Request $request): Response
{
$datas = $request->request->get('data');
$result = new JsonResponse(['Inizializzo il result'], Response::HTTP_BAD_REQUEST);
$user = $this->getUser();
$userCompanyOrder = $user instanceof User ? $user->getCompanyOrder() : null;
$this->timbratoreLogger->log(
'stamp_request_received',
'INFO',
'Richiesta di timbrata ricevuta dal timbratore.',
[
'data_type' => is_array($datas) && isset($datas['type']) ? $datas['type'] : 'Cantiere',
'items' => is_array($datas) ? (isset($datas['type']) ? 1 : count($datas)) : 0,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
try {
if (array_key_exists('type', $datas) && $datas['type'] === 'MensaSacchetto') {
$typeForm = StampedMensaSacchettoType::class;
$data = [
'stamped_in_out[Badge' => $datas['stamped_mensa_sacchetto[Badge'],
'stamped_in_out[InOut' => 'in',
'stamped_in_out[date' => DateTimeUtils::getNow(),
];
$bagType = $datas['stamped_mensa_sacchetto[BagType'] ?? null;
$result = $this->saveTimbrate($data, $typeForm, 'MensaSacchetto', $bagType, $request);
} elseif (array_key_exists('type', $datas)) {
$typeForm = StampedMensaType::class;
$data = [
'stamped_in_out[Badge' => $datas['stamped_mensa[Badge'],
'stamped_in_out[InOut' => $datas['stamped_mensa[InOut'],
'stamped_in_out[date' => DateTimeUtils::getNow(),
];
$result = $this->saveTimbrate($data, $typeForm, 'Mensa', null, $request);
} else {
$typeForm = StampedInOutType::class;
foreach ($datas as $data) {
$result = $this->saveTimbrate($data, $typeForm, 'Cantiere', null, $request);
}
}
} catch (\Throwable $ex) {
$this->timbratoreLogger->log(
'stamp_ajax_exception',
'ERROR',
$ex->getMessage(),
[
'exception' => get_class($ex),
'file' => $ex->getFile(),
'line' => $ex->getLine(),
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
$result = new JsonResponse(['Non ci sono dati da processare'], Response::HTTP_BAD_REQUEST);
}
$this->timbratoreLogger->log(
$result->getStatusCode() >= 400 ? 'stamp_request_failed' : 'stamp_request_completed',
$result->getStatusCode() >= 400 ? 'ERROR' : 'INFO',
'Elaborazione richiesta timbrata completata.',
['status' => $result->getStatusCode()],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
return $result;
}
/**
* @Route("/ajax/timbratore-log", name="timbratore_log_ajax", methods={"POST"})
* @IsGranted("ROLE_USER")
*/
public function timbratoreLogAjax(Request $request): JsonResponse
{
$user = $this->getUser();
$companyOrder = $user instanceof User ? $user->getCompanyOrder() : null;
$payload = $request->request->all();
if (str_starts_with((string) $request->headers->get('Content-Type'), 'application/json')) {
$raw = $request->getContent();
$decoded = json_decode($raw, true);
if (is_array($decoded)) {
$payload = $decoded;
}
}
$event = isset($payload['event']) ? trim((string) $payload['event']) : '';
$level = isset($payload['level']) ? strtoupper(trim((string) $payload['level'])) : 'INFO';
$message = isset($payload['message']) ? (string) $payload['message'] : null;
$clientId = isset($payload['clientId']) ? (string) $payload['clientId'] : null;
$page = isset($payload['page']) ? (string) $payload['page'] : null;
$context = [];
if (isset($payload['context'])) {
if (is_string($payload['context'])) {
$decodedContext = json_decode($payload['context'], true);
if (is_array($decodedContext)) {
$context = $decodedContext;
}
} elseif (is_array($payload['context'])) {
$context = $payload['context'];
}
}
if ($page !== null) {
$context['page'] = substr($page, 0, 1000);
}
if ($event === '') {
return new JsonResponse(['error' => 'Evento mancante'], Response::HTTP_BAD_REQUEST);
}
$this->timbratoreLogger->log(
$event,
$level,
$message,
$context,
$request,
$user instanceof User ? $user : null,
$companyOrder,
$clientId
);
return new JsonResponse(['ok' => true], Response::HTTP_OK);
}
/**
* Salva una nuova timbrata (entrata o uscita) per un operatore.
*
* FUNZIONAMENTO MULTI-CANTIERE - CHIAVE DEL SISTEMA:
* La timbrata viene associata al cantiere del TIMBRATORE ($userCompanyOrder), NON al cantiere di appartenenza dell'operatore.
* Questo permette ad un operatore registrato su un cantiere di timbrare liberamente su qualsiasi altro timbratore.
*
* FLUSSO OPERATIVO:
* 1. Identifica l'operatore tramite il badge scansionato
* 2. Recupera il cantiere del timbratore corrente ($userCompanyOrder = cantiere dove si trova fisicamente il timbratore)
* 3. Verifica duplicati SOLO per la coppia (operatore + cantiere timbratore) nelle ultime N ore
* - N = 12h per le mense (tipi 'Mensa' e 'MensaSacchetto')
* - N = 4h per il timbratore cantiere (tipo 'Cantiere')
* 4. Salva la timbrata associandola al cantiere del timbratore
*
* ESEMPIO PRATICO MULTI-CANTIERE (finestra default = 4h):
* Operatore "Mario Rossi" registrato su Sovere:
* - Scenario A: Timbra su timbratore di Sovere
* → $userCompanyOrder = Sovere
* → Controllo duplicati su (Mario + Sovere)
* → Timbrata salvata con companyOrder = Sovere
*
* - Scenario B: Timbra su timbratore di Brescia
* → $userCompanyOrder = Brescia
* → Controllo duplicati su (Mario + Brescia) - cantiere diverso, nessun problema!
* → Timbrata salvata con companyOrder = Brescia
*
* - Scenario C: Ritorna su timbratore di Sovere dopo 30 minuti
* → $userCompanyOrder = Sovere
* → Controllo duplicati su (Mario + Sovere) - trova timbrata precedente nella finestra!
* → Timbrata BLOCCATA (duplicato)
*
* LOGICA ANTI-DUPLICATO:
* - Per ENTRATE: chiama getStampedWithinHoursEntry($userCompanyOrder, $operatorId, $duplicateCheckHours)
* - Per USCITE: chiama getStampedWithinHoursRelease($userCompanyOrder, $operatorId, $duplicateCheckHours)
* - Se trova duplicato E operatore non è isMulti → blocca la timbrata
* - Se NON trova duplicato OPPURE operatore è isMulti (mensa) → salva la timbrata
*
* GESTIONE ERRORI:
* - Badge non trovato → salva in ErrorStamped
* - Badge non assegnato → salva in ErrorStamped
* - Form non valido → ritorna errore 400
*
* @param array $data Dati form con badge, tipo timbrata (in/out), data
* @param string $typeForm Tipo form (StampedInOutType, StampedMensaType, StampedMensaSacchettoType)
* @param string $t Tipo timbrata ('Cantiere', 'Mensa', 'MensaSacchetto')
* @return JsonResponse Risposta JSON con esito operazione
* @throws \Exception
*/
public function saveTimbrate($data, $typeForm, $t, ?string $bagType = null, ?Request $request = null): JsonResponse
{
$form = $this->createForm($typeForm);
$form->submit($data);
if ($form->isSubmitted() && $form->isValid()) {
$actionForm = $data['stamped_in_out[InOut'];
$badgeForm = $data['stamped_in_out[Badge'];
$entityManager = $this->doctrine->getManager();
// PUNTO CHIAVE MULTI-CANTIERE: il companyOrder è del TIMBRATORE, non dell'operatore
// Questo permette di salvare la timbrata sul cantiere dove si trova fisicamente il timbratore
$user = $this->getUser();
$userCompanyOrder = $user instanceof User ? $user->getCompanyOrder() : null;
$this->timbratoreLogger->log(
'stamp_processing_started',
'INFO',
'Inizio elaborazione timbrata.',
[
'type' => $t,
'action' => $data['stamped_in_out[InOut'] ?? null,
'badge' => $data['stamped_in_out[Badge'] ?? null,
'bagType' => $bagType,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
// Determina se il timbratore corrente è una Mensa (Type = 2)
$isCurrentOrderMensa = ($userCompanyOrder && $userCompanyOrder->getType() == 2);
// Finestra anti-duplicato: 12h per le mense (Mensa e MensaSacchetto), 4h per il timbratore cantiere
$duplicateCheckHours = ($t === 'Mensa' || $t === 'MensaSacchetto') ? 12 : 4;
$assignedBadgeRepository = $entityManager->getRepository(AssignedBadge::class);
$badgeRepository = $entityManager->getRepository(Badge::class);
$stampedRepository = $entityManager->getRepository(Stamped::class);
$errorStamped = new ErrorStamped();
$errorStamped->setCompanyOrder($userCompanyOrder);
$errorStamped->setCodBadge($badgeForm);
$stamped = new Stamped();
/** @var Badge $badge */
$badge = $badgeRepository->findOneBy(['codBadge' => $badgeForm]);
if (!$badge) {
$this->timbratoreLogger->log(
'badge_not_found',
'WARNING',
'Badge non trovato in archivio.',
['badge' => $badgeForm, 'action' => $actionForm, 'type' => $t],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
} else {
$this->timbratoreLogger->log(
'badge_found',
'DEBUG',
'Badge trovato in archivio.',
['badgeId' => $badge->getId(), 'badge' => $badgeForm],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
}
$dataIn = DateTimeUtils::getNow();
$dataOut = DateTimeUtils::getNow();
try {
if (isset($data['stamped_in_out[date']) && $data['stamped_in_out[date']) {
if ($actionForm === 'in') {
$dataIn = $t === 'Cantiere' ? new \DateTime($data['stamped_in_out[date']) : DateTimeUtils::getNow();
} elseif ($actionForm === 'out') {
$dataOut = $t === 'Cantiere' ? new \DateTime($data['stamped_in_out[date']) : DateTimeUtils::getNow();
}
}
} catch (\Throwable $e) {
$this->timbratoreLogger->log(
'stamp_date_error',
'ERROR',
'Errore nella data della timbrata.',
[
'exception' => get_class($e),
'error' => $e->getMessage(),
'action' => $actionForm,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
return new JsonResponse(['Non ci sono settate le date di timbrata'], Response::HTTP_BAD_REQUEST);
}
if ($badge) {
$idBadge = $badge->getId();
/** @var AssignedBadge $assignedBadge */
$assignedBadge = $assignedBadgeRepository->findOneBy(['badge' => $idBadge]);
if ($assignedBadge) {
$operatorBadge = $assignedBadge->getOperator()->getId();
$this->timbratoreLogger->log(
'badge_assigned',
'INFO',
'Badge associato a un operatore.',
[
'badgeId' => $badge->getId(),
'operatorId' => $operatorBadge,
'action' => $actionForm,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
$operatorRepository = $entityManager->getRepository(Operator::class);
/** @var Operator $op */
$op = $operatorRepository->findOneBy(['id' => $operatorBadge]);
if ($actionForm === 'out') {
/** @var Stamped $stamped */
$stamped = $stampedRepository->getStamped($userCompanyOrder, $operatorBadge);
if ($stamped) {
// CONTROLLO DUPLICATI CON NUOVA LOGICA MENSA
$stampedRecent = $stampedRepository->getStampedWithinHoursRelease($userCompanyOrder, $operatorBadge, $duplicateCheckHours, $isCurrentOrderMensa);
if (!$stampedRecent) {
$stamped->setReleaseDate($dataOut);
$this->timbratoreLogger->log(
'stamp_release_updated',
'INFO',
'Uscita associata a una timbrata di entrata esistente.',
[
'stampedId' => $stamped->getId(),
'operatorId' => $operatorBadge,
'action' => $actionForm,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
} else {
$this->timbratoreLogger->log(
'stamp_release_duplicate_ignored',
'WARNING',
'Uscita duplicata ignorata perché esiste già una timbrata recente.',
[
'stampedId' => $stamped->getId(),
'operatorId' => $operatorBadge,
'duplicateCheckHours' => $duplicateCheckHours,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
}
} else {
/** @var Stamped $stampedWithinFourHours */
$stampedWithinFourHours = $stampedRepository->getStampedWithinHoursRelease($userCompanyOrder, $operatorBadge, $duplicateCheckHours, $isCurrentOrderMensa);
if ($stampedWithinFourHours and $op->getIsMulti() === false and $this->isMensaRole()) {
$this->timbratoreLogger->log(
'duplicate_blocked',
'WARNING',
'Timbrata bloccata perché già presente nella finestra anti-duplicato.',
[
'operatorId' => $operatorBadge,
'action' => $actionForm,
'duplicateCheckHours' => $duplicateCheckHours,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
return new JsonResponse(['Non puoi mangiare in mensa piu volte nel giro di poco'], Response::HTTP_BAD_REQUEST);
}
// Crea una nuova timbrata se non esiste duplicato nella finestra $duplicateCheckHours OPPURE se operatore è multi per mensa
if (!$stampedWithinFourHours || ($op->getIsMulti() === true && $this->isMensaRole())) {
$stamped = new Stamped();
$stamped->setCompanyOrder($userCompanyOrder);
$stamped->setOperator($op);
$stamped->setReleaseDate($dataOut);
$stamped->setStatus(Stamped::STATUS_ERROR);
} else {
// Se esiste un duplicato e non è multi, non creiamo un nuovo record
$this->timbratoreLogger->log(
'stamp_duplicate_ignored',
'WARNING',
'Nuova timbrata ignorata perché duplicata.',
[
'operatorId' => $operatorBadge,
'action' => $actionForm,
'duplicateCheckHours' => $duplicateCheckHours,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
$stamped = null;
}
}
} elseif ($actionForm === 'in') {
// CONTROLLO DUPLICATI CON NUOVA LOGICA MENSA
/** @var Stamped $stampedWithinFourHours */
$stampedWithinFourHours = $stampedRepository->getStampedWithinHoursEntry($userCompanyOrder, $operatorBadge, $duplicateCheckHours, $isCurrentOrderMensa);
if ($stampedWithinFourHours and $op->getIsMulti() === false and $this->isMensaRole()) {
$this->timbratoreLogger->log(
'duplicate_blocked',
'WARNING',
'Timbrata bloccata perché già presente nella finestra anti-duplicato.',
[
'operatorId' => $operatorBadge,
'action' => $actionForm,
'duplicateCheckHours' => $duplicateCheckHours,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
return new JsonResponse(['Non puoi mangiare in mensa piu volte nel giro di poco'], Response::HTTP_BAD_REQUEST);
}
// Crea una timbrata se non esiste duplicato nella finestra $duplicateCheckHours OPPURE se operatore è multi per mensa
if (!$stampedWithinFourHours || ($op->getIsMulti() === true && $this->isMensaRole())) {
$stamped->setEntryDate($dataIn);
$stamped->setCompanyOrder($userCompanyOrder);
$stamped->setOperator($op);
if ($this->isMensaRole()) {
$stamped->setReleaseDate($dataIn);
}
} else {
// Se esiste un duplicato e non è multi, non creiamo un nuovo record
$this->timbratoreLogger->log(
'stamp_duplicate_ignored',
'WARNING',
'Nuova timbrata ignorata perché duplicata.',
[
'operatorId' => $operatorBadge,
'action' => $actionForm,
'duplicateCheckHours' => $duplicateCheckHours,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
$stamped = null;
}
}
// Salvo solo se stamped non è null (non è un duplicato)
if ($stamped !== null) {
if ($bagType !== null) {
$stamped->setBagType($bagType);
}
$entityManager->persist($stamped);
$entityManager->flush();
$this->timbratoreLogger->log(
'stamp_saved',
'INFO',
'Timbrata salvata correttamente.',
[
'stampedId' => $stamped->getId(),
'operatorId' => $stamped->getOperator() ? $stamped->getOperator()->getId() : null,
'companyOrderId' => $stamped->getCompanyOrder() ? $stamped->getCompanyOrder()->getId() : null,
'action' => $actionForm,
'bagType' => $bagType,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
}
} else {
$this->timbratoreLogger->log(
'badge_not_assigned',
'WARNING',
'Badge trovato ma non assegnato a un operatore.',
['badgeId' => $badge->getId(), 'badge' => $badgeForm, 'action' => $actionForm],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
$errorStamped->setNBadge($badge->getNBadge());
if ($actionForm === 'out') {
$errorStamped->setReleaseDate($dataOut);
} elseif ($actionForm === 'in') {
$errorStamped->setEntryDate($dataIn);
if ($this->isMensaRole()) {
$this->timbratoreLogger->log(
'operator_not_registered',
'WARNING',
'Operatore non registrato/associato al badge.',
['badge' => $badgeForm, 'action' => $actionForm],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
return new JsonResponse(['Non sei registrato, richiedere al responsabile l inserimento a sistema'], Response::HTTP_BAD_REQUEST);
}
}
$errorStamped->setType(ErrorStamped::TYPE_ERROR_ASSIGNED);
$entityManager->persist($errorStamped);
$entityManager->flush();
$this->timbratoreLogger->log(
'error_stamped_saved',
'WARNING',
'Errore di timbratura registrato in ErrorStamped.',
[
'errorType' => $errorStamped->getType(),
'badge' => $badgeForm,
'action' => $actionForm,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
}
} else {
if ($actionForm === 'out') {
$errorStamped->setReleaseDate($dataOut);
} elseif ($actionForm === 'in') {
$errorStamped->setEntryDate($dataIn);
if ($this->isMensaRole()) {
$this->timbratoreLogger->log(
'operator_not_registered',
'WARNING',
'Operatore non registrato/associato al badge.',
['badge' => $badgeForm, 'action' => $actionForm],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
return new JsonResponse(['Non sei registrato, richiedere al responsabile l inserimento a sistema'], Response::HTTP_BAD_REQUEST);
}
}
$errorStamped->setType(ErrorStamped::TYPE_ERROR_ASSIGNED);
$entityManager->persist($errorStamped);
$entityManager->flush();
$this->timbratoreLogger->log(
'error_stamped_saved',
'WARNING',
'Badge non riconosciuto: errore di timbratura registrato.',
[
'errorType' => $errorStamped->getType(),
'badge' => $badgeForm,
'action' => $actionForm,
],
$request,
$user instanceof User ? $user : null,
$userCompanyOrder
);
}
} else {
$this->timbratoreLogger->log(
'stamp_form_invalid',
'ERROR',
'Il form della timbrata non è valido.',
[
'type' => $t,
'formErrors' => (string) $form->getErrors(true),
],
$request,
$this->getUser() instanceof User ? $this->getUser() : null,
$this->getUser() instanceof User ? $this->getUser()->getCompanyOrder() : null
);
return new JsonResponse(['Il form non è valido contattare l amministratore'], Response::HTTP_BAD_REQUEST);
}
if ($stamped && $badge && $this->isMensaRole() && $stamped->getId()) {
$responseData = [
'ok',
'stampedId' => $stamped->getId(),
'badgeStamped' => $badge->getNBadge(),
'codOperator' => $stamped->getOperator()->getId(),
'dataStamped' => $stamped->getCreatedAt() ? $stamped->getCreatedAt()->format('d-m-Y H:i:s') : DateTimeUtils::getNow()->format('d-m-Y H:i:s')
];
if ($stamped->getBagType() !== null) {
$responseData['bagType'] = $stamped->getBagType();
$responseData['bagTypeLabel'] = Stamped::BAG_TYPE_LABELS[$stamped->getBagType()] ?? $stamped->getBagType();
}
return new JsonResponse($responseData, Response::HTTP_OK);
} else {
return new JsonResponse(['ok'], Response::HTTP_OK);
}
}
/**
* @Route("/delete-multiple-ids", name="delete_multiple_ids", methods={"DELETE"})
* @IsGranted ("ROLE_ADMIN")
*
* @param Request $request
* @return Response
*/
public function deleteAjax(Request $request): Response
{
if (!$request->request->get('type')) {
return new JsonResponse(['Error, missing type parameter'], Response::HTTP_BAD_REQUEST);
}
$ids = $request->request->get('ids');
if (!$ids || !is_array($request->request->get('ids'))) {
return new JsonResponse(['Error ids not valid'], Response::HTTP_BAD_REQUEST);
}
switch ($request->request->get('type')) {
case 'stamped':
$result = $this->deleteMultipleIds($ids, Stamped::class);
break;
default:
return new JsonResponse(['Error, this type is not registered'], Response::HTTP_BAD_REQUEST);
}
return $result ? new JsonResponse(['ok'], Response::HTTP_OK) : new JsonResponse(['Error while deleting records'], Response::HTTP_BAD_REQUEST);
}
private function isMensaRole(): bool
{
return $this->isGranted("ROLE_MENSA") || $this->isGranted("ROLE_MENSA_ASPORTO");
}
private function deleteMultipleIds(array $ids, $className)
{
try {
$qb = $this->doctrine->getManager()->createQueryBuilder();
$qb->delete($className, 'e')
->andWhere('e.id IN (:id)')
->setParameter('id', $ids);
return $qb->getQuery()->execute();
} catch (Exception $e) {
return false;
}
}
}