← Back
Editing: DashboardController.php
<?php namespace App\Controller; use App\Entity\Item; use App\Entity\Note; use App\Entity\User; use App\Enum\UserRole; use App\Notation\Calculator\NoteCalculator; use App\Notation\Render\NoteColorator; use App\Notation\Render\NoteRenderer; use App\Repository\AdresseRepository; use App\Repository\AgencyPrestataireRepository; use App\Repository\AgencyRepository; use App\Repository\ControleRepository; use App\Repository\HistoriqueAlerteRepository; use App\Repository\ItemRepository; use App\Repository\NoteRepository; use App\Repository\ThematicRepository; use App\Repository\UserRepository; use App\Service\AddressService; use App\Service\AgentService; use App\Service\ControleService; use App\Service\ElevatorBreakdownService; use App\Service\NoteService; use App\Service\PdfService; use App\Service\SolutionService; use App\Service\UserService; use App\Service\Utils; use App\Session\Filter\Role\ManagerSessionFilters; use App\Session\Filter\ValueObject\DateRange; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\NonUniqueResultException; use Doctrine\ORM\NoResultException; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Serializer\SerializerInterface; use Twig\Environment; /** * Controller for manager dashboard. */ class DashboardController extends AbstractController { /** * DashboardController constructor. */ public function __construct( private readonly ControleService $controleService, private readonly ElevatorBreakdownService $elevatorBreakdownService, private readonly Utils $utils, private readonly SolutionService $solutionService, private readonly Environment $templating, private readonly NoteColorator $noteColorator, private readonly string $publicDir, private readonly string $baseUrlCm, ) { } /** * @Route("/", name="homepage") * * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface * @throws \Exception */ #[Route(path: '/', name: 'homepage')] public function index( SolutionService $solutionService, AgentService $agentService, UserService $userService, EntityManagerInterface $em, ManagerSessionFilters $sessionFilters, ThematicRepository $thematicRepository, NoteCalculator $noteCalculator, array $widgets, array $bottomSlot ): Response { $user = $this->getUser(); if (!$user instanceof User) { throw new \Exception('Bad user type'); } if ($this->container->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) { return $this->redirectToRoute('admin'); } if ($this->container->get('security.authorization_checker')->isGranted('ROLE_ORGANIZATION')) { return $this->redirectToRoute('organization_index'); } if ($this->container->get('security.authorization_checker')->isGranted('ROLE_SUPERVISOR')) { return $this->redirectToRoute('supervisor_index'); } $agents = $userService->getAgentsForCurrentSolution(); $agents = $this->utils->sortAgentsByPercentDone($agents, $agentService); $thematics = $thematicRepository->findForAgency($user->getAgency()); $solutionName = $solutionService->getCurrent()->getName(); $widgets = $widgets[$solutionService->getCurrent()->getSlug()]; $bottomSlot = $bottomSlot[$solutionService->getCurrent()->getSlug()]; $calculatedNoteContainer = ($noteCalculator)( dateRange: $sessionFilters->getDateRange(), user: $this->getUser() ); return $this->render( 'dashboard/index.html.twig', [ 'agents' => $agents, 'agentService' => $agentService, 'thematics' => $thematics, 'solutionName' => $solutionName, 'widgets' => $widgets, 'calculatedNoteContainer' => $calculatedNoteContainer, 'bottomSlot' => $bottomSlot, ] ); } public function controlesDoneHistory(ManagerSessionFilters $sessionFilters): Response { $historic = $this->controleService->groupControlByMonth( $sessionFilters->getDateRange()->getDateStart(), $sessionFilters->getDateRange()->getDateEnd() ); return $this->render('dashboard/_controles-done-history.html.twig', ['historic' => $historic]); } /** * @throws NonUniqueResultException * @throws NoResultException */ #[IsGranted('ROLE_ADMIN')] #[Route(path: '/admin', name: 'admin')] public function admin(AgencyRepository $agencyRepository, UserRepository $userRepository): Response { $agencies = $agencyRepository->getAgencysWithSearch(); $nbUsers = $userRepository->countAll(); $nbAgencies = count($agencies); return $this->render( 'dashboard/admin.html.twig', [ 'agencies' => $agencies, 'nbUsers' => $nbUsers, 'nbAgencies' => $nbAgencies, ] ); } #[Route(path: '/historique', name: 'historique')] public function historique(ManagerSessionFilters $sessionFilters): Response { $historic = $this->controleService->groupControlByMonth( $sessionFilters->getDateRange()->getDateStart(), $sessionFilters->getDateRange()->getDateEnd() ); $agents = $this->getUser()->getAgents(); return $this->render( 'dashboard/historique.html.twig', [ 'historic' => $historic, 'agents' => $agents, ] ); } #[Route(path: '/history/ajax', name: 'history_ajax', methods: ['POST'])] public function ajaxHistory(Request $request, ManagerSessionFilters $sessionFilters): JsonResponse { $historic = $this->controleService->groupControlByMonth( $sessionFilters->getDateRange()->getDateStart(), $sessionFilters->getDateRange()->getDateEnd(), $request->request->all()['agents'] ); return $this->json(array_values($historic)); } #[Route(path: '/objectifs', name: 'objectifs')] public function objectifs(AgentService $agentService, UserService $userService): Response { $agents = $userService->getAgentsForCurrentSolution(); return $this->render( 'dashboard/objectifs.html.twig', [ 'agents' => $agents, 'agentService' => $agentService, ] ); } #[Route(path: '/evaluationItemParResidence', name: 'evaluationItemParResidence', methods: ['GET', 'POST'])] public function evaluationItemParResidence( Request $request, AdresseRepository $adresseRepository, ItemRepository $itemRepository, NoteRenderer $noteRenderer ): Response { $item = $itemRepository->find(intval($request->query->get('idItem'))); $listeNoteByAdresses = $adresseRepository->noteItemsByAgentByAdresse( intval($request->query->get('idAgent')), $item->getId() ); return $this->render( 'dashboard/evaluationItemParResidence.html.twig', [ 'item' => $item, 'idAgent' => $request->query->get('idAgent'), 'listeNoteByAdresse' => $listeNoteByAdresses, 'noteChartFormatter' => $noteRenderer->renderChartFormatter($item->getNotationType()), ] ); } /** * @throws \Exception */ #[Route(path: '/evaluationQualite', name: 'evaluationQualite', methods: ['GET', 'POST'])] public function evaluationQualite( Request $request, UserService $userService, ItemRepository $itemRepository, NoteRepository $noteRepository, NoteRenderer $noteRenderer ): Response { $selectedItemId = $request->get('id'); $selectedItem = $itemRepository->getItemByIdWithZone($selectedItemId); $listeAgents = $userService->getAgentsForCurrentSolution(); $listeAgents = array_filter( $listeAgents, function ($agent) { return in_array('ROLE_AGENT', $agent->getArrayRoles()); } ); $listeNoteByAgent = []; foreach ($listeAgents as $agent) { $result = $noteRepository->noteItemsByAgent( $agent, $selectedItem['item'] ); if ($result) { $listeNoteByAgent[] = $result; } else { $result[0]['item'] = null; $result[0]['averageNote'] = null; $result[0]['nomAgent'] = $agent->getNom(); $result[0]['prenomAgent'] = $agent->getPrenom(); $result[0]['idAgent'] = $agent->getId(); $listeNoteByAgent[] = $result; } } return $this->render( 'dashboard/evaluationQualite.html.twig', [ 'noteChartFormatter' => $noteRenderer->renderChartFormatter($selectedItem['item']->getNotationType()), 'selectedItem' => $selectedItem['item'], 'selectedZone' => $selectedItem['zone'], 'listeAgents' => $listeNoteByAgent, ] ); } #[Route(path: '/evaluationQualiteComplete', name: 'evaluationQualiteComplete')] public function evaluationQualiteComplete( AdresseRepository $adresseRepository, ManagerSessionFilters $sessionFilters, EntityManagerInterface $em ): Response { $listeAdresses = $adresseRepository->getByManager($this->getUser()); $listeVilles = $adresseRepository->getVillesByManager($this->getUser()); $listeStatsItems = $this->getStatsItem( $em, $sessionFilters->getDateRange()->getDateStart(), $sessionFilters->getDateRange()->getDateEnd() ); return $this->render( 'dashboard/evaluationQualiteComplete.html.twig', [ 'listeAdresses' => $listeAdresses, 'listeVilles' => $listeVilles, 'listeStatsItems' => $listeStatsItems, ] ); } #[Route(path: '/loadAddresses', name: 'load_addresses')] public function loadAddresses( Request $request, SerializerInterface $serializer, AdresseRepository $adresseRepository ): Response { $city = $request->get('selectedVille'); $addresses = $adresseRepository->getRuesByVillesByManager($this->getUser(), $city); $response = new Response(); $response->headers->set('Content-Type', 'application/json'); $response->setContent($serializer->serialize($addresses, 'json', ['groups' => 'manager'])); return $response; } /** * @throws \Exception */ #[Route(path: '/loadGraphNoteMoyenne', name: 'loadGraphNoteMoyenne')] public function loadGraphNoteMoyenne( Request $request, NoteRepository $noteRepository, ManagerSessionFilters $sessionFilters ): Response { $selectedVille = $request->get('selectedVille'); $selectedRue = $request->get('selectedRue'); $selectedResidence = $request->get('selectedResidence'); $selectedBatiment = $request->get('selectedBatiment'); $selectedNumero = $request->get('selectedNumero'); $result = $noteRepository->averageNoteByManagerByFullAdresse( $this->getUser(), $selectedVille, $selectedRue, $selectedResidence, $selectedBatiment, $selectedNumero, $sessionFilters->getDateRange()->getDateStart(), $sessionFilters->getDateRange()->getDateEnd() ); $noteMoyenne = round(floatval($result[0]['noteMoyenne']), 1); return $this->render( 'dashboard/graphNoteMoyenne.html.twig', [ 'noteMoyenne' => $noteMoyenne, ] ); } /** * @throws \Exception */ #[Route(path: '/loadGraphDetailsNote', name: 'loadGraphDetailsNote')] public function loadGraphDetailsNote( Request $request, ThematicRepository $thematicRepository, ManagerSessionFilters $sessionFilters ): Response { $selectedVille = $request->get('selectedVille'); $selectedRue = $request->get('selectedRue'); $selectedResidence = $request->get('selectedResidence'); $selectedBatiment = $request->get('selectedBatiment'); $selectedNumero = $request->get('selectedNumero'); $listStatsByThematic = $thematicRepository->findAverageNote( manager: $this->getUser(), ville: $selectedVille, voie: $selectedRue, residence: $selectedResidence, batiment: $selectedBatiment, numero: $selectedNumero, dateStart: $sessionFilters->getDateRange()->getDateStart(), dateEnd: $sessionFilters->getDateRange()->getDateEnd() ); return $this->render( 'dashboard/graphDetailsNote.html.twig', [ 'listStatsByThematic' => $listStatsByThematic, ] ); } /** * @throws \Exception */ #[Route(path: '/loadGraphHistoNote', name: 'loadGraphHistoNote')] public function loadGraphHistoNote( Request $request, NoteRepository $noteRepository, ManagerSessionFilters $sessionFilters ): Response { $selectedVille = $request->get('selectedVille'); $selectedRue = $request->get('selectedRue'); $selectedResidence = $request->get('selectedResidence'); $selectedBatiment = $request->get('selectedBatiment'); $selectedNumero = $request->get('selectedNumero'); $historyDate = new \DateTime($sessionFilters->getDateRange()->getDateStart()->format('Y-m-d')); $interval = new \DateInterval('P1M'); $formatter = new \IntlDateFormatter( 'fr_FR', \IntlDateFormatter::TRADITIONAL, \IntlDateFormatter::TRADITIONAL ); $formatter->setPattern('MMM yy'); while ($historyDate <= $sessionFilters->getDateRange()->getDateEnd()) { $dateEnd = clone $historyDate; $dateEnd = $dateEnd->modify('first day of this month'); $dateEnd->add($interval); $results = $noteRepository->averageNoteByManagerByFullAdresse( $this->getUser(), $selectedVille, $selectedRue, $selectedResidence, $selectedBatiment, $selectedNumero, $historyDate, $dateEnd ); $frenchMonth = $formatter->format($historyDate); $listeFinale[$frenchMonth] = 0; foreach ($results as $item) { $listeFinale[$frenchMonth] = round(floatval($item['noteMoyenne']), 1); } $historyDate = clone $dateEnd; } return $this->render( 'dashboard/graphHistoNote.html.twig', [ 'listeNoteMois' => $listeFinale, ] ); } /** * @throws \Exception */ #[Route(path: '/evaluationQualiteParAgent', name: 'evaluationQualiteParAgent')] public function evaluationQualiteParAgent( Request $request, ThematicRepository $thematicRepository, UserRepository $userRepository, ): Response { if (!$request->query->has('agentId')) { throw new \Exception('Agent id is required'); } $idAgent = $request->query->get('agentId'); $agent = $userRepository->find($idAgent); $thematics = $thematicRepository->findForAgent($agent); return $this->render( 'dashboard/evaluationQualiteParAgent.html.twig', ['thematics' => $thematics, 'agent' => $agent, 'roleAgent' => UserRole::ROLE_AGENT] ); } #[Route(path: '/alertes-prestataires.{_format}', name: 'alertes_prestataires')] public function alertesPrestataires( Utils $utils, ManagerSessionFilters $sessionFilters, AgencyPrestataireRepository $agencyPrestataireRepository ): Response { $prestataires = $agencyPrestataireRepository->getPrestatairesByManager($this->getUser()); return $this->render( 'dashboard/alertes-prestataires.html.twig', [ 'months' => array_keys( $utils->getMonthsTimeline( $sessionFilters->getDateRange()->getDateStart(), $sessionFilters->getDateRange()->getDateEnd() ) ), 'prestataires' => $prestataires, ] ); } #[Route(path: '/loadGraphHistoAlerte', name: 'loadGraphHistoAlerte')] public function loadGraphHistoAlerte( Request $request, HistoriqueAlerteRepository $historiqueAlerteRepository, AgencyPrestataireRepository $agencyPrestataireRepository, AdresseRepository $adresseRepository, ManagerSessionFilters $sessionFilters ): JsonResponse { $prestataire = $agencyPrestataireRepository->find($request->get('prestataire')); $alertes = $historiqueAlerteRepository->getByManagerByPrestataire( $this->getUser(), $prestataire ); $result = []; $finalNotes = $finalAddresses = 0; $interval = new \DateInterval('P1M'); $currentDate = clone $sessionFilters->getDateRange()->getDateStart(); while ($currentDate <= $sessionFilters->getDateRange()->getDateEnd()) { $dateEnd = clone $currentDate; $dateEnd = $dateEnd->modify('first day of this month'); $dateEnd->add($interval); $nbalerte = 0; foreach ($alertes as $alerte) { if ($alerte->getDate() >= $currentDate && $alerte->getDate() < $dateEnd) { ++$nbalerte; } } $result['alertes'][] = $nbalerte; $adresses = $adresseRepository->getAllByManagerByPrestataireInDateRange( $this->getUser(), $prestataire->getPrestataire(), $currentDate, $dateEnd ); $totalAverage = 0; foreach ($adresses as $adresse) { $totalAverage += $adresse['noteMoyenne']; if ($adresse['noteMoyenne'] > 0) { $finalNotes += $adresse['noteMoyenne']; ++$finalAddresses; } } $result['satisfaction'][] = round($totalAverage / count($adresses), 1); $currentDate = clone $dateEnd; } $result['actualSatisfaction'] = 5; if ($finalAddresses > 0) { $result['actualSatisfaction'] = round($finalNotes / $finalAddresses, 1); } $result['prestaName'] = $prestataire->getPrestataire()->getNom(); $result['prestaContactName'] = $prestataire->getPrenomContact().' '.$prestataire->getNomContact(); $result['prestaMail'] = $prestataire->getMailContact(); $result['prestaPhone'] = $prestataire->getTelephone(); return new JsonResponse($result); } /** * @return BinaryFileResponse * * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception * @throws \Exception */ #[Route(path: '/export-dashboard', name: 'export_dashboard')] public function exportDashboard( Request $request, UserService $userService, ItemRepository $itemRepository, NoteRepository $noteRepository ) { $selectedItemId = $request->get('id'); $selectedItem = $itemRepository->getItemByIdWithZone($selectedItemId); $listeAgents = $userService->getAgentsForCurrentSolution(); $listeNoteByAgent = []; foreach ($listeAgents as $agent) { $result = $noteRepository->noteItemsByAgent($agent, $selectedItem['item']); if ($result) { $listeNoteByAgent[] = $result; } else { $result[0]['item'] = null; $result[0]['averageNote'] = null; $result[0]['nomAgent'] = $agent->getNom(); $result[0]['prenomAgent'] = $agent->getPrenom(); $result[0]['idAgent'] = $agent->getId(); $listeNoteByAgent[] = $result; } } $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setTitle('Adresse'); $sheet->setCellValue('A1', 'Item'); $sheet->setCellValue('B1', 'Agent'); $sheet->setCellValue('C1', 'Note Moyenne'); $sheet->getColumnDimension('A')->setAutoSize(true); $sheet->getColumnDimension('B')->setAutoSize(true); $sheet->getColumnDimension('C')->setAutoSize(true); for ($i = 0; $i < count($listeNoteByAgent); ++$i) { $sheet->setCellValue('A'.($i + 2), $selectedItem['item']->getNom()); $sheet->setCellValue( 'B'.($i + 2), $listeNoteByAgent[$i][0]['prenomAgent'].' '.$listeNoteByAgent[$i][0]['nomAgent'] ); $sheet->setCellValue('C'.($i + 2), $listeNoteByAgent[$i][0]['averageNote']); } $nom = $selectedItem['item']->getNom(); $writer = new Xlsx($spreadsheet); $fileName = 'Notes_'.$nom.'_par_agent.xlsx'; /** @var string $temp_file */ $temp_file = tempnam(sys_get_temp_dir(), $fileName); // Create the excel file in the tmp directory of the system $writer->save($temp_file); // Return the excel file as an attachment return $this->file($temp_file, $fileName, ResponseHeaderBag::DISPOSITION_INLINE); } /** * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception */ #[Route(path: '/export-dashboard-par-agent', name: 'export_dashboard_par_agent')] public function exportDashboardByAgent( Request $request, UserRepository $userRepository, NoteRepository $noteRepository ): BinaryFileResponse { $agentId = $request->get('id'); $agent = $userRepository->find($agentId); $listeAllNotedItem = $noteRepository->noteAllItemsByAgent($agentId); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setTitle('Note Par Item'); $sheet->setCellValue('A1', 'Zone'); $sheet->setCellValue('B1', 'Item'); $sheet->setCellValue('C1', 'Note Moyenne'); $sheet->getColumnDimension('A')->setAutoSize(true); $sheet->getColumnDimension('B')->setAutoSize(true); $sheet->getColumnDimension('c')->setAutoSize(true); $i = 0; foreach ($listeAllNotedItem as $item) { $sheet->setCellValue('A'.($i + 2), $item['zone']); $sheet->setCellValue('B'.($i + 2), $item['item']); $sheet->setCellValue('C'.($i + 2), $item['note']); ++$i; } $nom = $agent->getPrenom().'_'.$agent->getNom(); $writer = new Xlsx($spreadsheet); $fileName = 'Notes_agent_'.$nom.'.xlsx'; $temp_file = tempnam(sys_get_temp_dir(), $fileName); // Create the excel file in the tmp directory of the system $writer->save($temp_file); // Return the excel file as an attachment return $this->file($temp_file, $fileName, ResponseHeaderBag::DISPOSITION_INLINE); } /** * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception */ #[Route(path: '/export-dashboard-par-adresse', name: 'export_dashboard_par_adresse')] public function exportDashboardByAdresse( Request $request, AdresseRepository $adresseRepository, ItemRepository $itemRepository ): BinaryFileResponse { $idItem = $request->get('idItem'); $item = $itemRepository->find($idItem); $idAgent = $request->get('idAgent'); // get Note Item By Agent by Adresse $listeNoteByAdresses = $adresseRepository->noteItemsByAgentByAdresse($idAgent, $idItem); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setTitle('Note Item par Adresse'); $sheet->setCellValue('A1', 'Ville'); $sheet->setCellValue('B1', 'Voie'); $sheet->setCellValue('C1', 'Note Moyenne'); $sheet->getColumnDimension('A')->setAutoSize(true); $sheet->getColumnDimension('B')->setAutoSize(true); $sheet->getColumnDimension('C')->setAutoSize(true); for ($i = 0; $i < count($listeNoteByAdresses); ++$i) { $sheet->setCellValue('A'.($i + 2), $listeNoteByAdresses[$i]['ville']); $sheet->setCellValue('B'.($i + 2), $listeNoteByAdresses[$i]['voie']); $sheet->setCellValue('C'.($i + 2), $listeNoteByAdresses[$i]['averageNote']); } $nom = $item->getNom().'_par_adresse'; $writer = new Xlsx($spreadsheet); $fileName = 'Notes_agent_'.$nom.'.xlsx'; $temp_file = tempnam(sys_get_temp_dir(), $fileName); // Create the excel file in the tmp directory of the system $writer->save($temp_file); // Return the excel file as an attachment return $this->file($temp_file, $fileName, ResponseHeaderBag::DISPOSITION_INLINE); } /** * @throws \Exception */ #[Route(path: '/sort-agents', name: 'sortAgents')] public function sortAgents(Request $request, AgentService $agentService, UserService $userService): JsonResponse { $orderBy = $request->request->get('order', 'ASC'); $results = []; $agents = $userService->getAgentsForCurrentSolution(); $agents = $this->utils->sortAgentsByPercentDone($agents, $agentService, $orderBy); foreach ($agents as $agent) { $service = $agentService->setAgent($agent); $results[] = [ 'pourcentage' => $service->getPercentDone(), 'id' => $service->getAgent()->getId(), 'nom' => $service->getAgent()->getNom(), 'prenom' => $service->getAgent()->getPrenom(), ]; } $response = new JsonResponse(['agents' => $results]); return $response; } /** * @throws \Exception */ public function controlesDone(UserService $userService): Response { $controlsDone = 0; $stats = $userService->statsByManager($this->getUser()); if ($stats['totalControles'] > 0) { $controlsDone = round(($stats['controlsDone'] / $stats['totalControles']) * 100, 1); $controlsDone = str_replace(',', '.', $controlsDone); } return $this->render('dashboard/widgets/_controles-done.html.twig', ['controlsDone' => $controlsDone]); } /** * @throws NoResultException * @throws NonUniqueResultException */ public function notesAverage(ControleRepository $controleRepository): Response { $averageNote = round( $controleRepository->averageNoteByManager( $this->getUser() ), 1 ); return $this->render('dashboard/widgets/_notes-average.html.twig', ['averageNote' => $averageNote]); } public function prestatairesAlerts( HistoriqueAlerteRepository $historiqueAlerteRepository, ManagerSessionFilters $sessionFilters ): Response { $historiqueAlertes = $historiqueAlerteRepository->findByUser( $this->getUser() ); $diff = $sessionFilters->getDateRange()->getDateEnd()->diff($sessionFilters->getDateRange()->getDateStart()); $months = 0; $label = 'Alertes'; if ($diff->y >= 1) { $months += ($diff->y * 12) + $diff->m; } if ($diff->m >= 1) { $months += $diff->m; } if ($months >= 1) { $label = 'Alertes par mois'; } if ($months > 0) { $historiqueAlertes = number_format(count($historiqueAlertes) / $months, 1); } else { $historiqueAlertes = count($historiqueAlertes); } return $this->render( 'dashboard/widgets/_prestataires-alerts.html.twig', ['historiqueAlertes' => $historiqueAlertes, 'label' => $label] ); } /** * @throws \Exception */ public function agentDone(AgentService $agentService, UserService $userService): Response { $agents = $userService->getAgentsForCurrentSolution(); $agents = array_filter( $agents, function ($agent) { return in_array('ROLE_AGENT', $agent->getArrayRoles()); } ); $goals = []; $goals['agentsCompleted'] = 0; foreach ($agents as $agent) { $agentService->setAgent($agent); if (0 === $agentService->getRemainingControls()) { ++$goals['agentsCompleted']; } } $goals['totalAgents'] = count($agents); return $this->render('dashboard/widgets/_agent-done.html.twig', ['goals' => $goals]); } public function elevatorBreakdown(AdresseRepository $adresseRepository): Response { $addresses = $adresseRepository->getByManager($this->getUser()); $elevatorBreakdown = 0; foreach ($addresses as $address) { if (false === $address[0]->getAscenseurIsActive()) { ++$elevatorBreakdown; } } return $this->render( 'dashboard/widgets/_elevator-breakdown.html.twig', [ 'totalElevators' => count($addresses), 'elevatorBreakdown' => $elevatorBreakdown, ] ); } public function elevatorBreakdownHistory(): Response { $historic = $this->elevatorBreakdownService->groupBreakdownsByMonth( $this->getUser(), new \DateTime('4 months ago'), new \DateTime() ); return $this->render('dashboard/_elevator-breakdown-history.html.twig', ['historic' => $historic]); } /** * @throws \Exception */ #[Route(path: '/reset.html', name: 'reset')] public function reset(KernelInterface $kernel): RedirectResponse { $application = new Application($kernel); $application->setAutoExit(false); $input = new ArrayInput( [ 'command' => 'doctrine:fixtures:load', // (optional) define the value of command arguments '-n', ] ); // You can use NullOutput() if you don't need the output $output = new BufferedOutput(); $application->run($input, $output); // return the output, don't use if you used NullOutput() $content = $output->fetch(); return $this->redirectToRoute('homepage'); } /** * @throws \Exception */ private function getStatsItem( EntityManagerInterface $em, ?\DateTimeInterface $startDate = null, ?\DateTimeInterface $endDate = null ): array { $allItems = $em->getRepository(Item::class)->getAllWithZone($this->getUser()); $statsItem = $em->getRepository(Note::class)->averageNoteItemsByManager( manager: $this->getUser(), options: ['dateRange' => new DateRange($startDate, $endDate)] ); $diff = []; foreach ($allItems as $item) { $item['averageNote'] = 0; $add = true; foreach ($statsItem as $stat) { if ($item['itemId'] === $stat['itemId']) { $add = false; break; } } if ($add) { $diff[] = $item; } } $statsItem = array_merge($statsItem, $diff); $result = []; foreach ($statsItem as $stat) { if (0 === $stat['averageNote']) { continue; } $arr['item'] = $stat['item']; $arr['notationType'] = $stat['notationType']; $arr['averageNote'] = round($stat['averageNote'], 1); $arr['itemSubZone'] = null; $zone = $stat['zone']; if (str_contains($stat['zone'], 'PROPRETE')) { $zone = 'PROPRETE'; if (!str_contains($stat['zone'], 'AUTRES LOCAUX')) { $arr['itemSubZone'] = substr($stat['zone'], 10); } } /* @todo Refactoriser ce truc immonde */ $arr['colorCode'] = ($this->noteColorator)($arr['averageNote']); $arr['color'] = ($arr['averageNote'] >= 3.5) ? 'blue' : 'pink'; $arr['color'] = ('pink' == $arr['color'] && $arr['averageNote'] > 2) ? 'green' : $arr['color']; $arr['percentage'] = ($arr['averageNote'] / 5) * 100; $arr['itemId'] = $stat['itemId']; $result[$zone][] = $arr; } return $result; } /** * @throws \Exception */ #[Route(path: '/generateEvaluationQualite', name: 'generateEvaluationQualite')] public function generateEvaluationQualite( Request $request, NoteRepository $noteRepository, ThematicRepository $thematicRepository, NoteService $noteService, AddressService $addressService, ManagerSessionFilters $sessionFilters, PdfService $pdfService ): Response { $compagnyLogoPath = $this->getUser()->getAgency()?->getLogo() ?? $this->getUser()->getOrganization()?->getLogo( ); $arrowTrendDown = $this->utils->imageToBase64($this->publicDir.'/img/arrow-trend-down-solid.png'); $arrowTrendUp = $this->utils->imageToBase64($this->publicDir.'/img/arrow-trend-up-solid.png'); $selectedVille = $request->get('selectedVille'); $selectedRue = $request->get('selectedRue'); $selectedResidence = $request->get('selectedResidence'); $selectedBatiment = $request->get('selectedBatiment'); $selectedNumero = $request->get('selectedNumero'); $selectedId = $request->get('selectedId'); $agency = $addressService->getAgencyByAddressId($selectedId); $startDate = $sessionFilters->getDateRange()->getDateStart(); $endDate = $sessionFilters->getDateRange()->getDateEnd(); $prevEndDate = clone $startDate; $prevStartDate = clone $startDate; $prevStartDate->sub(date_diff($startDate, $endDate)); /***** NOTE AVERAGE */ $resultAverageNote = $noteRepository->averageNoteByManagerByFullAdresse( $this->getUser(), $selectedVille, $selectedRue, $selectedResidence, $selectedBatiment, $selectedNumero, $startDate, $endDate ); $averageNote = round(floatval($resultAverageNote[0]['noteMoyenne']), 1); $resultPrevAverageNote = $noteRepository->averageNoteByManagerByFullAdresse( $this->getUser(), $selectedVille, $selectedRue, $selectedResidence, $selectedBatiment, $selectedNumero, $prevStartDate, $prevEndDate ); $prevAverageNote = round(floatval($resultPrevAverageNote[0]['noteMoyenne']), 1); /***** NOTE AVERAGE */ /***** NOTE DETAIL */ $listeStatsByThematic = $thematicRepository->averageNoteByManagerByFullAdresse( $this->getUser(), $selectedVille, $selectedRue, $selectedResidence, $selectedBatiment, $selectedNumero, $startDate, $endDate, ); $prevListeStatsByThematicRaw = $thematicRepository->averageNoteByManagerByFullAdresse( $this->getUser(), $selectedVille, $selectedRue, $selectedResidence, $selectedBatiment, $selectedNumero, $prevStartDate, $prevEndDate, ); $prevListeStatsByThematic = []; foreach ($prevListeStatsByThematicRaw as $item) { $prevListeStatsByThematic[$item[0]->getId()] = $item; } /***** NOTE DETAIL */ /***** HISTORIQUE NOTE */ $historyDate = (new \DateTime())->modify('first day of this month')->setTime(0, 0, 0); $endDateTmp = clone $historyDate; $historyDate->sub(new \DateInterval('P3M')); $endDateTmp->sub(new \DateInterval('P1M')); $finalList = $noteService->averageNoteByManagerByFullAdresse( $this->getUser(), $selectedVille, $selectedRue, $selectedResidence, $selectedBatiment, $selectedNumero, $historyDate, $endDateTmp ); /***** HISTORIQUE NOTE */ $html = $this->templating->render('export/pdf_quality.html.twig', [ 'user' => $this->getUser(), 'date' => (new \DateTime())->format('d/m/Y').' à '.(new \DateTime())->format('H:i'), 'compagnyLogo' => $compagnyLogoPath ? $this->utils->imageToBase64( "{$this->publicDir}/uploads/logos/$compagnyLogoPath" ) : null, 'arrowTrendDown' => $arrowTrendDown, 'arrowTrendUp' => $arrowTrendUp, 'dateStart' => $startDate->format('d/m/Y'), 'dateEnd' => $endDate->format('d/m/Y'), 'agency' => $agency, 'selectedVille' => $selectedVille, 'selectedNumero' => $selectedNumero, 'selectedRue' => $selectedRue, 'averageNote' => $averageNote, 'prevAverageNote' => $prevAverageNote, 'listeStatsByThematic' => array_chunk($listeStatsByThematic, 2, true), 'prevListeStatsByThematic' => $prevListeStatsByThematic, 'listeFinale' => $finalList, ]); $pdfFilepath = $this->publicDir.'/uploads/quality-'.$this->getUser()->getUserName().'.pdf'; $filesystem = new Filesystem(); if (!empty($pdfFilepath) && $filesystem->exists($pdfFilepath)) { $filesystem->remove($pdfFilepath); } $pdfService->generatePdf( $html, $pdfFilepath ); return new JsonResponse([ 'full_path' => $this->baseUrlCm.'/uploads/quality-'.$this->getUser()->getUserName().'.pdf', 'file' => 'evaluation-qualite-'.$startDate->format('Ymd').'-'.$endDate->format('Ymd').'.pdf', ]); } }
Save File
Cancel