<?php
namespace App\Controller\Backend;
use App\Controller\BaseController;
use App\Form\Backend\AdvancedSearchType;
use App\Service\AdvancedSearchService;
use App\Service\ExportService;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Knp\Component\Pager\PaginatorInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
#[IsGranted('ROLE_USER', message: "Vous n'avez pas l'autorisation pour cette action !")]
#[Route('/admin')]
class AdvancedSearchController extends BaseController
{
public function __construct(
ManagerRegistry $doctrine,
private AdvancedSearchService $advancedSearchService
)
{
parent::__construct($doctrine);
}
#[Route(path: '/advanced-search/{entity}', name: 'advanced_search', methods: ['GET', 'POST'])]
public function advancedSearch(
Request $request,
PaginatorInterface $paginator,
string $entity
): Response
{
$searchParams = $this->advancedSearchService->getSearchParameters($entity);
$forEmailSending = (bool) $request->request->get('for_email', false);
$forSmsSending = (bool) $request->request->get('for_sms', false);
$forDisplayArchived = $request->request->get('for_not_display_achived', false);
$advancedSearch = $this->advancedSearchService->initAndUpdateAdvancedSearchByRequest(
$request,
$entity,
$searchParams,
$forSmsSending,
$forEmailSending,
$forDisplayArchived
);
$advancedSearchForm = $this->createForm(AdvancedSearchType::class, $advancedSearch, [
'parameters' => $searchParams,
'entityName' => $entity,
]);
$advancedSearchForm->handleRequest($request);
$sendingRouteName = $forEmailSending ? 'send_email' : 'send_sms';
$class = $this->advancedSearchService->getEntityNamespace($searchParams, $entity).ucfirst($this->advancedSearchService->getEntityClass($searchParams, $entity));
$advancedSearch = $this->advancedSearchService->addDefaultFilter($advancedSearch, $entity, $searchParams);
$repository = $this->advancedSearchService->getRepository($searchParams, $entity, $class);
$userFilters = $this->getUser()->getFiltersByRole($entity);
$query = $repository->retrieveAllData(
$advancedSearch,
$forEmailSending,
$forSmsSending,
$forDisplayArchived,
$searchParams,
[],
$this->getUser()
);
$results = $paginator->paginate(
$query,
$request->query->getInt('page', 1),
self::ITEM_PER_PAGE
);
$renderParams = [
'menu' => strtolower($entity)
];
if (isset($searchParams['menu'])) {
$renderParams['menu'] = $searchParams['menu'];
}
if (isset($searchParams['submenu'])) {
$renderParams['submenu'] = $searchParams['submenu'];
}
return $this->renderForm('backend/advanced_search/advanced_search.html.twig', array_merge([
'advancedSearchForm' => $advancedSearchForm,
'entity' => $entity,
'advancedSearchResults' => $results,
'forEmailSending' => $forEmailSending,
'forSmsSending' => $forSmsSending,
'formRouteName' => $sendingRouteName,
'forNotDisplayArchived' => $forDisplayArchived,
'searchParams' => $searchParams,
'title' => $searchParams['title'] ?? 'Inconnu'
], $renderParams));
}
#[Route("/advanced-export/{entity}/{type}", name: 'advanced_export', methods: ['POST'])]
public function exportAdvancedSearch(
Request $request,
ParameterBagInterface $parameters,
string $entity,
string $type
): JsonResponse
{
if (!in_array($type, ['excel', 'csv'])) {
throw new \Exception('Seul les export "excel" et "csv" sont disponibles.');
}
$forDisplayArchived = $request->request->get('for_not_display_achived', false);
$searchParams = $this->advancedSearchService->getSearchParameters($entity);
$exportParams = $this->advancedSearchService->getExportParameters($entity);
$advancedSearch = $this->advancedSearchService->initAndUpdateAdvancedSearchByRequest(
$request,
$entity,
$searchParams,
false,
false,
$forDisplayArchived
);
$advancedSearchForm = $this->createForm(AdvancedSearchType::class, $advancedSearch, [
'parameters' => $searchParams,
'entityName' => $entity,
]);
$advancedSearchForm->handleRequest($request);
$class = $this->advancedSearchService->getEntityNamespace($searchParams, $entity).ucfirst($this->advancedSearchService->getEntityClass($searchParams, $entity));
$advancedSearch = $this->advancedSearchService->addDefaultFilter($advancedSearch, $entity, $searchParams);
$repository = $this->advancedSearchService->getRepository($searchParams, $entity, $class);
$userFilters = $this->getUser()->getFiltersByRole($entity);
$datas = $repository->retrieveAllData(
$advancedSearch,
false,
false,
$forDisplayArchived,
$searchParams,
[],
$this->getUser()
)->getResult();
$exportService = new ExportService(
$entity,
$type,
$exportParams,
$datas,
$parameters
);
try {
$filename = $exportService->export();
return new JsonResponse([
'status' => 'ok',
'message' => 'Export effectué avec succès',
'filename' => $filename
]);
} catch (\Exception $exception) {
return new JsonResponse([
'status' => 'nok',
'message' => $exception->getFile().' '.$exception->getLine().' - '.$exception->getMessage(),
]);
}
}
#[Route('/advanced-export-download/{filename}', name: 'advanced_export_download', methods: ['GET'])]
public function downloadExportAdvancedSearch(ParameterBagInterface $parameters, string $filename): BinaryFileResponse
{
$filepath = $parameters->get('export_path').$filename;
return $this->file($filepath, $filename);
}
#[Route('/advanced-selection-persist', name: 'update_session_selection_contact', methods: ['POST'])]
public function updateSessionSelection(Request $request): JsonResponse
{
$datas = json_decode($request->getContent(), true);
$request->getSession()->set('contact_selection', $datas);
return new JsonResponse([
'status' => 'ok',
'message' => 'Mise à jour de la sélection effectuée avec succès'
]);
}
#[Route('/advanced-search-entity-list', name: 'advanced_search_entity_list', methods: ['POST'])]
public function getEntityList(Request $request, EntityManagerInterface $em): JsonResponse
{
$datas = json_decode($request->getContent(), true);
$entityResults = $em->getRepository($datas['entity'])->findAll();
$results = [];
foreach ($entityResults as $entityResult) {
$results[] = [
'id' => $entityResult->getId(),
'value' => $entityResult->{'get'.ucfirst($datas['choice_label'])}()
];
}
return new JsonResponse($results);
}
}