<?php
namespace App\Controller\Traitement;
use App\Entity\PMessengerStatut;
use App\Controller\ApiController;
use App\Service\DataTableService;
use App\Entity\PGenerationFichier;
use App\Service\CalculPaieService;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class DemandeController extends AbstractController
{
private $em;
private $client;
private $api;
private $calculPaieService;
private $dataTableService;
public function __construct(ManagerRegistry $doctrine, DataTableService $dataTableService, CalculPaieService $calculPaieService, ApiController $api, HttpClientInterface $client)
{
$this->em = $doctrine->getManager();
$this->api = $api;
$this->client = $client;
$this->calculPaieService = $calculPaieService;
$this->dataTableService = $dataTableService;
}
#[Route('/traitement/demande', name: 'app_traitement_demande')]
public function index(Request $request): Response
{
$operations = $this->api->check($this->getUser(), 'app_traitement_demande', $this->em, $request);
if (!is_array($operations)) {
return $this->redirectToRoute('app_site');
} elseif (count($operations) == 0) {
return $this->render('includes/404.html.twig');
}
$oneHourAgo = new \DateTime();
$oneHourAgo->modify('-1 hour');
$messages = $this->em->createQueryBuilder()
->select('m')
->from(PMessengerStatut::class, 'm')
->where('m.created <= :oneHourAgo')
->andWhere('m.statut IN (:statut)')
->setParameter('oneHourAgo', $oneHourAgo)
->setParameter('statut', ['en cours','demarer'])
->getQuery()
->getResult()
;
// dd($messages);
foreach ($messages as $message) {
$message->setStatut('error');
$message->setMessage('Something went wrong');
}
$this->em->flush();
return $this->render('traitement/demande/index.html.twig', [
'operations' => $operations,
'periode' => $this->calculPaieService->getPeriode()
]);
}
#[Route('/app_traitement_demande_list', name: 'app_traitement_demande_list', options: ['expose' => true])]
public function app_traitement_demande_list(Request $request): Response
{
$draw = $request->query->get('draw');
$columns = $request->get('columns');
$start = $request->query->get('start') ?? 0;
$length = $request->query->get('length') ?? 10;
$dossier = $request->getSession()->get('dossier');
$search = $request->query->all('search')["value"];
$orderColumnIndex = $request->query->all('order')[0]['column'];
$orderColumn = $request->query->all("columns")[$orderColumnIndex]['name'];
$orderDir = $request->query->all('order')[0]['dir'] ?? 'asc';
$initialQueryBuilder = $this->em->createQueryBuilder()
->from(PMessengerStatut::class, 'm')
->innerJoin('m.user', 'u')
->leftJoin('m.generationFichier', 'generationFichier')
;
if($this->getUser()->getUserIdentifier() != 'admin') {
$initialQueryBuilder->andWhere('u.username = :username')
->setParameter('username', $this->getUser()->getUserIdentifier());
}
$queryBuilder = clone $initialQueryBuilder;
$selectColumns = $this->dataTableService->selectColumns($columns);
$queryBuilder->select(implode(', ', $selectColumns));
$queryBuilder->addSelect('generationFichier.token');
if (!empty($search)) {
$conditions = $this->dataTableService->search($columns);
$queryBuilder->andWhere('(' . implode(' OR ', $conditions) . ')')
->setParameter('search', "%$search%");
}
$filteredRecords = count($queryBuilder->getQuery()->getResult());
// Paginate results
$queryBuilder->setFirstResult($start)
->setMaxResults($length)
->orderBy("m.id","DESC");
$results = $queryBuilder->getQuery()->getResult();
$totalRecords = clone $initialQueryBuilder;
$totalRecords->select('COUNT(m.id)');
$totalRecords = $totalRecords->getQuery()
->getSingleScalarResult();
return new JsonResponse([
'draw' => $draw,
'recordsTotal' => $totalRecords,
'recordsFiltered' => $filteredRecords,
'data' => $results,
]);
}
#[Route('/download/{token}', name: 'app_traitement_demande_download', options: ['expose' => true])]
public function app_traitement_demande_download($token): Response
{
/** @var PGenerationFichier */
$generationFichier = $this->em->getRepository(PGenerationFichier::class)->findOneBy(['token' => $token]);
$zipFilePath = tempnam(sys_get_temp_dir(), 'zip_') . '.zip';
// Create a new instance of ZipArchive
$zip = new \ZipArchive();
// Open the ZIP file for writing
if ($zip->open($zipFilePath, \ZipArchive::CREATE) !== TRUE) {
throw new \Exception('Cannot open the ZIP file for writing.');
}
$files = [];
$name = '';
if($generationFichier->getTxtFileName()) {
$name = pathinfo($this->getParameter('tempfiles').$generationFichier->getTxtFileName(), PATHINFO_FILENAME);
array_push($files, $this->getParameter('tempfiles').$generationFichier->getTxtFileName());
}
if($generationFichier->getExcelFileName()) {
$name = pathinfo($this->getParameter('tempfiles').$generationFichier->getExcelFileName(), PATHINFO_FILENAME);
array_push($files, $this->getParameter('tempfiles').$generationFichier->getExcelFileName());
}
// Add files to the ZIP
foreach ($files as $file) {
if (file_exists($file)) {
// Get the file's name
$fileName = basename($file);
// Add the file to the ZIP archive
$zip->addFile($file, $fileName);
} else {
throw new \Exception("File does not exist: $file");
}
}
// Close the ZIP file
$zip->close();
// Create a response to download the ZIP file
$response = new StreamedResponse(function () use ($zipFilePath) {
readfile($zipFilePath);
// Remove the temporary ZIP file after sending it to the user
unlink($zipFilePath);
});
// Set headers to download the file
$customFileName = $name.'.zip';
$response->headers->set('Content-Type', 'application/zip');
$response->headers->set('Content-Disposition', 'attachment; filename="'.$customFileName.'"');
$response->headers->set('Content-Length', filesize($zipFilePath));
return $response;
}
}