src/Controller/PlanningController.php line 244

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Billing;
  4. use App\Entity\Client;
  5. use App\Entity\Company;
  6. use App\Entity\Contract;
  7. use App\Entity\Intervenant;
  8. use App\Entity\LogCancel;
  9. use App\Entity\LogPlanning;
  10. use App\Entity\LogRDV;
  11. use App\Entity\Product;
  12. use App\Entity\RDV;
  13. use App\Entity\RDVProduct;
  14. use App\Entity\Salon;
  15. use App\Entity\Session;
  16. use App\Entity\SessionSalon;
  17. use App\Entity\Site;
  18. use App\Entity\User;
  19. use App\Form\AddSessionSalonType;
  20. use App\Form\CompanyType;
  21. use App\Form\FilterType;
  22. use App\Form\RDVType;
  23. use App\Form\ReplanningIntervenantType;
  24. use App\Form\ReplanningType;
  25. use App\Form\SessionSalonType;
  26. use App\Manager\ReglementManager;
  27. use App\Message\SendingPlanning;
  28. use App\Repository\BillingRepository;
  29. use App\Repository\ClientRepository;
  30. use App\Repository\IntervenantRepository;
  31. use App\Repository\ProductRepository;
  32. use App\Repository\RDVProductRepository;
  33. use App\Repository\RDVRepository;
  34. use App\Repository\SalonRepository;
  35. use App\Repository\SessionSalonRepository;
  36. use App\Service\MailService;
  37. use App\Service\PaytweakService;
  38. use App\Traits\BillingManagerTrait;
  39. use App\Traits\MailServiceTrait;
  40. use App\Traits\ManagerTrait;
  41. use App\Traits\RDVManagerTrait;
  42. use DateTime;
  43. use Doctrine\Common\Collections\ArrayCollection;
  44. use Doctrine\ORM\EntityManagerInterface;
  45. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  46. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  47. use Psr\Log\LoggerInterface;
  48. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  49. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  50. use Symfony\Component\Form\FormFactoryInterface;
  51. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  52. use Symfony\Component\HttpFoundation\JsonResponse;
  53. use Symfony\Component\HttpFoundation\RedirectResponse;
  54. use Symfony\Component\HttpFoundation\Request;
  55. use Symfony\Component\HttpFoundation\Response;
  56. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  57. use Symfony\Component\HttpFoundation\StreamedResponse;
  58. use Symfony\Component\Messenger\MessageBusInterface;
  59. use Symfony\Component\Routing\Annotation\Route;
  60. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  61. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  62. use Symfony\Component\Security\Csrf\CsrfTokenManager;
  63. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  64. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  65. use Symfony\Component\Serializer\Serializer;
  66. use Symfony\Component\Serializer\SerializerInterface;
  67. /**
  68.  * @Route("/planning")
  69.  */
  70. class PlanningController extends AbstractController
  71. {
  72.     use RDVManagerTrait;
  73.     use ManagerTrait;
  74.     use BillingManagerTrait;
  75.     use MailServiceTrait;
  76.     /**
  77.      * @Route("/site", methods={"GET"})
  78.      * @Template()
  79.      */
  80.     public function site(SerializerInterface $serializer): array
  81.     {
  82.         $em $this->managerRegistry;
  83.         $sessions $em->getRepository(RDV::class)->findForPlanning();
  84.         $sites $em->getRepository(Site::class)->findAll();
  85.         $intervenants $em->getRepository(Intervenant::class)->findAll();
  86.         $companies $em->getRepository(Company::class)->findAll();
  87.         $rdv = new RDV();
  88.         $form $this->createForm(RDVType::class, $rdv);
  89.         $sessions $serializer->serialize($sessions'json', [
  90.             'groups' => 'rdv',
  91.             'circular_reference_handler' => function ($object) {
  92.                 return $object->getId();
  93.             }
  94.         ]);
  95.         //dump($sessions);die;
  96.         return [
  97.             'sites' => $sites,
  98.             'intervenants' => $intervenants,
  99.             'sessions' => $sessions,
  100.             'companies' => $companies,
  101.             'form' => $form->createView()
  102.         ];
  103.     }
  104.     /**
  105.      * TODO: not in use
  106.      * @Route("/intervenant", methods={"GET"})
  107.      * @Template()
  108.      */
  109.     public function intervenant(SerializerInterface $serializer): array
  110.     {
  111.         $em $this->managerRegistry;
  112.         $sessions $em->getRepository(RDV::class)->findAll();
  113.         $rdv = new RDV();
  114.         $form $this->createForm(RDVType::class, $rdv);
  115.         $sessions $serializer->serialize($sessions'json', [
  116.             'groups' => 'rdv',
  117.             'circular_reference_handler' => function ($object) {
  118.                 return $object->getId();
  119.             }
  120.         ]);        //dump($sessions);die;
  121.         return [
  122.             'sessions' => $sessions,
  123.             'form' => $form->createView()
  124.         ];
  125.     }
  126.     /**
  127.      * @Route("/envoiPlanning")
  128.      */
  129.     public function envoiPlanning(MessageBusInterface $messageBus): RedirectResponse
  130.     {
  131.         $this->addFlash('success''Envoi pris en compte. ');
  132.         $messageBus->dispatch(new SendingPlanning());
  133.         return $this->redirectToRoute('app_planning_pilotage');
  134.     }
  135.     /**
  136.      * @Route("/liste", methods={"GET","POST"})
  137.      * @Template()
  138.      */
  139.     public function liste(
  140.         Request $request,
  141.         RDVRepository $RDVRepository,
  142.         SessionSalonRepository $sessionSalonRepository,
  143.         ProductRepository  $productRepository,
  144.         ClientRepository $clientRepository
  145.     ): array {
  146.         $em $this->managerRegistry;
  147.         // date ajdh
  148.         //$sessions = $repository->findFromToday();
  149.         $sites $em->getRepository(Site::class)->findAll();
  150.         $rdv = new RDV();
  151.         $status $request->query->get('status');
  152.         $client $request->query->get('client');
  153.         $clientId $request->query->get('client_id');
  154.         $clientFind null;
  155.         if ($clientId) {
  156.             $clientFind $clientRepository->find($clientId);
  157.             $rdv->setClient($clientFind);
  158.             $salon $clientFind->getSite()->getSalons();
  159.             $first =  $salon->first();
  160.             if ($first) {
  161.                 $rdv->setSalon($first);
  162.             }
  163.         }
  164.         $formFilter $this->createForm(FilterType::class, null, ['status' => $status'client' => $clientFind]);
  165.         $form $this->createForm(RDVType::class, $rdv, ['withCustomPicker' => true]);
  166.         $formReplanning $this->createForm(ReplanningType::class, null);
  167.         $formReplanning2 $this->createForm(ReplanningIntervenantType::class, null);
  168.         $formReplanning->handleRequest($request);
  169.         $formReplanning2->handleRequest($request);
  170.         $formFilter->handleRequest($request);
  171.         $sessions $RDVRepository->findByFilter(nullnull$clientnullnull$status$clientId);
  172.         // replannification
  173.         if ($formReplanning->isSubmitted() && $formReplanning->isValid()) {
  174.             $this->RDVManager->replannification($formReplanning);
  175.             $em->getManager()->flush();
  176.         }
  177.         if ($formReplanning2->isSubmitted() && $formReplanning2->isValid()) {
  178.             $this->RDVManager->replannificationIntervenant($formReplanning2);
  179.             $em->getManager()->flush();
  180.         }
  181.         if ($formFilter->isSubmitted() && $formFilter->isValid()) {
  182.             $intervenant $formFilter->getData()['intervenant'];
  183.             $site $formFilter->getData()['site'];
  184.             $client $formFilter->getData()['client'];
  185.             $start $formFilter->getData()['start'];
  186.             $status $formFilter->getData()['status'];
  187.             $end $formFilter->getData()['end'];
  188.             $salon $formFilter->getData()['salon'];
  189.             $request->getSession()->set('intervenant'$intervenant);
  190.             $request->getSession()->set('site'$site);
  191.             $request->getSession()->set('client'$client);
  192.             $request->getSession()->set('start'$start);
  193.             $request->getSession()->set('end'$end);
  194.             $request->getSession()->set('salon'$salon);
  195.             $sessions $RDVRepository->findByFilter($intervenant$site$client$start$end$status$clientIdnull$salon);
  196.         }
  197.         return [
  198.             'sessions' => $sessions,
  199.             'form' => $form->createView(),
  200.             'formReplanning' => $formReplanning->createView(),
  201.             'formReplanning2' => $formReplanning2->createView(),
  202.             'formFilter' => $formFilter->createView(),
  203.             'sites' => $sites,
  204.             'intervenant' => $request->getSession()->get('intervenant'),
  205.         ];
  206.     }
  207.     /**
  208.      * @Route("/coiffeurListe", methods={"GET","POST"})
  209.      * @Template()
  210.      * @param Request $request
  211.      * @param RDVRepository $repository
  212.      * @return array
  213.      */
  214.     public function coiffeurListe(
  215.         Request $request,
  216.         RDVRepository $repository,
  217.         SessionSalonRepository $sessionSalonRepository,
  218.         RDVRepository $RDVRepository,
  219.         ClientRepository  $clientRepository,
  220.         ProductRepository  $productRepository,
  221.         BillingRepository $billingRepository
  222.     ): array {
  223.         $em $this->managerRegistry;
  224.         // date ajdh
  225.         //$sessions = $repository->findFromToday();
  226.         $sites $em->getRepository(Site::class)->findAll();
  227.         $rdv = new RDV();
  228.         $status $request->query->get('status');
  229.         $client $request->query->get('client');
  230.         $clientId $request->query->get('client_id');
  231.         $formFilter $this->createForm(FilterType::class, null, ['status' => $status'client' => $client]);
  232.         $form $this->createForm(
  233.             RDVType::class,
  234.             $rdv,
  235.             ['withCustomPicker' => true]
  236.         );
  237.         $formReplanning $this->createForm(ReplanningType::class, null);
  238.         $formReplanning->handleRequest($request);
  239.         $formReplanning2 $this->createForm(ReplanningType::class, null);
  240.         $formReplanning2->handleRequest($request);
  241.         $formFilter->handleRequest($request);
  242.         $sessions $repository->findByFilterCoiffeuse(nullnull$clientnullnull$status$clientId$this->getUser());
  243.         $sessionsResult =  [];
  244.         /** @var Session $session */
  245.         foreach ($sessions as $session) {
  246.             $session['client'] = null;
  247.             if (isset($session['client_id'])) {
  248.                 $client $clientRepository->find($session['client_id']);
  249.                 $session['client'] = $client;
  250.             }
  251.             if ($client == null)
  252.                 continue;
  253.             $billings $client->getBillings();
  254.             /** @var Billing $billing */
  255.             $lastBilling = [];
  256.             $billings $billingRepository->searchUnpaid($client);
  257.             $session['paid'] = null;
  258.             $currentDate = new \DateTime();
  259.             if (count($billings) > 0) {
  260.                 $myLastElement end($billings);
  261.                 $diff $currentDate->diff($myLastElement['dateBilling'])->format("%r%a");
  262.                 $session['paid'] =  abs($diff);
  263.             }
  264.             $products $productRepository->getProductsArrayByRDV($session['id']);
  265.             $session['products'] = $products;
  266.             $session['label'] = RDV::getRDVLabel($session['status']);
  267.             $sessionRdv $RDVRepository->find($session['id']);
  268.             $session['ttc'] = $sessionRdv->ttc();
  269.             $sessionsResult[] = $session;
  270.         }
  271.         // replannification
  272.         if ($formReplanning->isSubmitted() && $formReplanning->isValid()) {
  273.             $this->RDVManager->replannification($formReplanning);
  274.             $em->getManager()->flush();
  275.         }
  276.         // replannificcation  interrvenant
  277.         if ($formReplanning2->isSubmitted() && $formReplanning2->isValid()) {
  278.             $this->RDVManager->replannification($formReplanning2);
  279.             $em->getManager()->flush();
  280.         }
  281.         if ($formFilter->isSubmitted() && $formFilter->isValid()) {
  282.             $intervenant $formFilter->getData()['intervenant'];
  283.             $site $formFilter->getData()['site'];
  284.             $client $formFilter->getData()['client'];
  285.             $start $formFilter->getData()['start'];
  286.             $status $formFilter->getData()['status'];
  287.             $salon $formFilter->getData()['salon'];
  288.             $end $formFilter->getData()['end'];
  289.             $request->getSession()->set('intervenant'$intervenant);
  290.             $request->getSession()->set('site'$site);
  291.             $request->getSession()->set('client'$client);
  292.             $request->getSession()->set('start'$start);
  293.             $request->getSession()->set('end'$end);
  294.             $sessions $repository->findByFilterCoiffeuse($intervenant$site$client$start$end$statusnullnull$salon);
  295.             $sessionsResult =  [];
  296.             foreach ($sessions as $session) {
  297.                 $client null;
  298.                 if ($session['client_id']) {
  299.                     $client $clientRepository->find($session['client_id']);
  300.                 }
  301.                 $products $productRepository->getProductsArrayByRDV($session['id']);
  302.                 $session['products'] = $products;
  303.                 $session['client'] = $client;
  304.                 $session['label'] = RDV::getRDVLabel($session['status']);
  305.                 $billings = [];
  306.                 if ($client) {
  307.                     $billings $billingRepository->searchUnpaid($client);
  308.                 }
  309.                 $session['paid'] = null;
  310.                 $currentDate = new \DateTime();
  311.                 if (count($billings) > 0) {
  312.                     $myLastElement end($billings);
  313.                     $diff $currentDate->diff($myLastElement['dateBilling'])->format("%r%a");
  314.                     $session['paid'] =  abs($diff);
  315.                 }
  316.                 $sessionRdv $RDVRepository->find($session['id']);
  317.                 $session['ttc'] = $sessionRdv->ttc();
  318.                 $sessionsResult[] = $session;
  319.             }
  320.         }
  321.         return [
  322.             'sessions' => $sessionsResult,
  323.             'form' => $form->createView(),
  324.             'formReplanning' => $formReplanning->createView(),
  325.             'formReplanning2' => $formReplanning2->createView(),
  326.             'formFilter' => $formFilter->createView(),
  327.             'sites' => $sites,
  328.             'intervenant' => $request->getSession()->get('intervenant'),
  329.         ];
  330.     }
  331.     /**
  332.      * @Route("/new", methods={"GET","POST"})
  333.      */
  334.     public function new(Request $request): Response
  335.     {
  336.         $company = new Company();
  337.         $form $this->createForm(CompanyType::class, $company);
  338.         $form->handleRequest($request);
  339.         if ($form->isSubmitted() && $form->isValid()) {
  340.             $entityManager $this->getDoctrine()->getManager();
  341.             $entityManager->persist($company);
  342.             $entityManager->flush();
  343.             return $this->redirectToRoute('company_index');
  344.         }
  345.         return $this->render('company/new.html.twig', [
  346.             'company' => $company,
  347.             'form' => $form->createView(),
  348.         ]);
  349.     }
  350.     /**
  351.      * @Route("/newJOS", methods={"GET","POST"})
  352.      */
  353.     public function newJOS(Request $request): Response
  354.     {
  355.         $em $this->getDoctrine()->getManager();
  356.         $sessionSalon = new SessionSalon();
  357.         $form $this->createForm(AddSessionSalonType::class, $sessionSalon, []);
  358.         $form->handleRequest($request);
  359.         if ($form->isSubmitted() && $form->isValid()) {
  360.             $em->persist($sessionSalon);
  361.             $em->flush();
  362.             return $this->redirectToRoute('app_planning_pilotage');
  363.         }
  364.         return $this->render('planning/newJOS.html.twig', [
  365.             'session' => $sessionSalon,
  366.             'form' => $form->createView()
  367.         ]);
  368.     }
  369.     /**
  370.      * @Route("/pilotage-expoitation", methods={"GET","POST"})
  371.      */
  372.     public function pilotage(
  373.         Request                $request,
  374.         SerializerInterface    $serializer,
  375.         SessionSalonRepository $sessionSalonRepository,
  376.         SalonRepository        $salonRepository,
  377.         IntervenantRepository  $intervenantRepository
  378.     ): Response {
  379.         $salonQuery $request->query->get('salon');
  380.         $intervenantQuery $request->query->get('intervenant');
  381.         $dateDebut $request->query->get('date_debut');
  382.         $dateFin $request->query->get('date_fin');
  383.         $user $this->getUser();
  384.         $sessions $sessionSalonRepository->findAllMax($salonQuery$intervenantQuery$dateDebut$dateFin$user);
  385.         $salons $salonRepository->findAll();
  386.         $intervenants $intervenantRepository->findAll();
  387.         //        $sessions = $serializer->serialize($sessions, 'json', [
  388.         //            'groups' => 'rdv',
  389.         //            'circular_reference_handler' => function ($object) {
  390.         //                return $object->getId();
  391.         //            }
  392.         //        ]);
  393.         return $this->render('planning/pilotage.html.twig', [
  394.             'dateDebut' => $dateDebut,
  395.             'dateFin' =>  $dateFin,
  396.             'sessions' => $sessions,
  397.             'salons' => $salons,
  398.             'intervenants' => $intervenants
  399.         ]);
  400.     }
  401.     /**
  402.      * @Route("/calendrier-expoitation", methods={"GET","POST"})
  403.      */
  404.     public function calendrier(
  405.         Request                $request,
  406.         RDVRepository           $rdvRepository,
  407.         SessionSalonRepository $sessionSalonRepository,
  408.         SalonRepository        $salonRepository,
  409.         IntervenantRepository  $intervenantRepository
  410.     ): Response {
  411.         $salonQuery $request->query->get('salon');
  412.         $intervenantQuery $request->query->get('intervenant');
  413.         $dateDebut $request->query->get('date_debut');
  414.         $dateFin $request->query->get('date_fin');
  415.         $metier $request->query->get('metier');
  416.         $status $request->query->get('status');
  417.         $zoneGeographique $request->query->get('zoneGeographique');
  418.         $user $this->getUser();
  419.         $sessions $sessionSalonRepository->findCalendar($salonQuery$intervenantQuery$dateDebut$dateFin$user$zoneGeographique$metier$status);
  420.         $intervenantsFilter $intervenantRepository->findAll();
  421.         $intervenants = [];
  422.         $ressources = [];
  423.         $events = [];
  424.         $ca = [];
  425.         $rdvsNumber = [];
  426.         $sessionsIds = [];
  427.         $joursReposColor '#794cf6';
  428.         $jourReposDays = [];
  429.         $key 1;
  430.         usort($sessions, function($a$b) {
  431.             // Prioritize "IDF" by moving it to the front.
  432.             if ($a['zoneGeographique'] === 'IDF' && $b['zoneGeographique'] !== 'IDF') {
  433.                 return -1;
  434.             } elseif ($a['zoneGeographique'] !== 'IDF' && $b['zoneGeographique'] === 'IDF') {
  435.                 return 1;
  436.             }
  437.             // Prioritize "Coiffeur" by moving it to the front.
  438.             if ($a['metier'] === Intervenant::METIER_COIFFEUR && $b['metier'] !== Intervenant::METIER_COIFFEUR) {
  439.                 return -1;
  440.             } elseif ($a['metier'] !== Intervenant::METIER_COIFFEUR && $b['metier'] === Intervenant::METIER_COIFFEUR) {
  441.                 return 1;
  442.             }
  443.             // For other values, use standard string comparison for 'zoneGeographique'.
  444.             $zoneComparison strcmp($a['zoneGeographique'], $b['zoneGeographique']);
  445.             if ($zoneComparison !== 0) {
  446.                 return $zoneComparison;
  447.             }
  448.             // For other values, use standard string comparison for 'metier'.
  449.             $metierComparison strcmp($a['metier'], $b['metier']);
  450.             if ($metierComparison !== 0) {
  451.                 return $metierComparison;
  452.             }
  453.             // For other values, use standard string comparison for 'intervenant_last_name'.
  454.             return strcmp($a['intervenant_last_name'], $b['intervenant_last_name']);
  455.         });
  456.         foreach ($sessions as &$session) {
  457.             // dd($session);
  458.             // // get chiffre d'affaire et totale des rdvs  par salon
  459.             // if (!in_array($session['salon_id'], $sessionsIds)) {
  460.             //     $rdvs = $rdvRepository->findBy(['salon' => $session['salon_id'], 'intervenant' => $session['intervenant_id']]);
  461.             //     $rdvsNumber[$session['salon_id']] = count($rdvs);
  462.             //     $totalHt = $this->calculateTotalHtForRDVs($rdvs);
  463.             //     $sessionsIds[] = $session['salon_id'];
  464.             //     $ca[$session['salon_id']] = number_format($totalHt, 2);
  465.             // }
  466.             $name htmlspecialchars($session['salon_name'], ENT_QUOTES'UTF-8');
  467.             $intervenants[]=[
  468.                 'id' => $session['intervenant_id'],
  469.                 'firstname' => $session['intervenant_first_name'],
  470.                 'lastname' => $session['intervenant_last_name'],
  471.             ];
  472.             $hourEnd $session['end'] ? $session['end']->format('H:i') : '';
  473.             $title = ($session['observation'] ? "❶ " "") . ($session['actionArealiser'] ? "🚩 " "") . $name " - Horaire: {$session['start']->format('H:i')} " $hourEnd;
  474.             $eventColor $this->getColorForSessionStatus($session['status']);
  475.             $events[] = [
  476.                 'start' => $session['start']->format('Y-m-d\TH:i'),
  477.                 'end' => $session['end'] ? $session['end']->format('Y-m-d\TH:i') : $session['start']->format('Y-m-d\T23:59'),
  478.                 'title' => $title,
  479.                 //'allDay' => true,
  480.                 'color' => $eventColor,
  481.                 'resource' => $session['intervenant_id'],
  482.                 'event_id' => $session['session_id']
  483.             ];
  484.             if (isset($session['absence_start']) && isset($session['absence_end'])) {
  485.                 $heureDebut $session['absence_start_time'] ?? '00:00';
  486.                 $heureFin $session['absence_end_time'] ?? '23:59';
  487.                 $absenceStart $this->createDateTimeObject($session['absence_start'], $heureDebut);
  488.                 $absenceEnd $this->createDateTimeObject($session['absence_end'], $heureFin);
  489.                 $dateRange $absenceStart->format('d-m-Y H:i') . ' - ' $absenceEnd->format('d-m-Y H:i');
  490.                 $absenceEvent = [
  491.                     'start' => $absenceStart->format('Y-m-d\TH:i'),
  492.                     'end' => $absenceEnd->format('Y-m-d\TH:i'),
  493.                     'title' => 'Absence: ' $session['motif'] . '  ' $session['absence_comment'] .' -- Date : ' $dateRange,
  494.                     'resource' => $session['intervenant_id'],
  495.                     'event_id' => 'absence_' $session['session_id'],
  496.                     'color' => '#ff9c04',
  497.                 ];
  498.                 $events[] = $absenceEvent;
  499.             }
  500.             //intervenant_id
  501.             $ressources[$session['intervenant_id']] = [
  502.                 'id' => $session['intervenant_id'],
  503.                 'name' => $session["intervenant_last_name"] . " " $session["intervenant_first_name"],
  504.                 'color' => '#34c8e0'
  505.             ];
  506.             $key++;
  507.         }
  508.         $holidays $this->getHolidays();
  509.         $holidayColor '#ff0000';
  510.         $exist = [];
  511.         foreach ($sessions as $sessionRepo) {
  512.             $endDate = (new DateTime("now"))->modify("+1 years");
  513.             $startDate = (new DateTime("now"))->modify("-5 months");
  514.             if ((!in_array($sessionRepo['intervenant_id'], $exist)) ){
  515.                 foreach ($holidays as $holiday) {
  516.                     $events[] = [
  517.                         'start' => $holiday->format('Y-m-d\T00:00'),
  518.                         'end' => $holiday->format('Y-m-d\T23:59'),
  519.                         'title' => 'Holiday',
  520.                         'color' => $holidayColor,
  521.                         'resource' => $sessionRepo['intervenant_id'],
  522.                         'event_id' => 'holiday_' $holiday->format('Ymd'),
  523.                     ];
  524.                 }
  525.                 if ( $sessionRepo['joursRepos'] !== null ) {
  526.                     while ($startDate <= $endDate) {
  527.                         $joursrepos $sessionRepo['joursRepos'];
  528.                         asort($joursrepos);
  529.                         foreach ($joursrepos as $key => $reposDay) {
  530.                             if ($startDate->format('w') == $reposDay) {
  531.                                 $events[] = [
  532.                                     'start' => $startDate->format('Y-m-d\T00:00'),
  533.                                     'end' => $startDate->format('Y-m-d\T23:59'),
  534.                                     'title' => 'Repos',
  535.                                     'color' => $joursReposColor,
  536.                                     'resource' => $sessionRepo['intervenant_id'],
  537.                                     'event_id' => 'repos_' rand(100010000) . '_' $sessionRepo['session_id']
  538.                                 ];
  539.                             }
  540.                         }
  541.                         $startDate->modify('+1 days');
  542.                     }
  543.                 }
  544.                 $exist[] = $sessionRepo['intervenant_id'];
  545.             }
  546.         }
  547.         $salons $salonRepository->findAll();
  548.         return $this->render('planning/calendar.html.twig', [
  549.             'intervenantsFilter' => $intervenantsFilter,
  550.             'dateDebut' => $dateDebut,
  551.             'dateFin' =>  $dateFin,
  552.             'sessions' => $events,
  553.             'ressources' => array_values($ressources),
  554.             'salons' => $salons,
  555.             'intervenants' => json_encode($intervenants)
  556.         ]);
  557.     }
  558.     public function createDateTimeObject($absenceDate$heure)
  559.     {
  560.         $heure strlen($heure) !== $heure $heure ':00';
  561.         return \DateTime::createFromFormat('d-m-Y H:i'$absenceDate ' ' $heure);
  562.     }
  563.     public function getColorForSessionStatus($status) {
  564.         switch ($status) {
  565.             case 'modifier':
  566.                 return 'rgb(255, 245, 97)';
  567.             case 'event':
  568.                 return '#FF5733';
  569.             case 'indisponible':
  570.                 return '#707070';
  571.             default:
  572.                 return 'rgb(52, 200, 224)';
  573.         }
  574.     }
  575.     public function calculateTotalHtForRDVs($rdvs) {
  576.         $totalHt 0;
  577.         foreach ($rdvs as $rdv) {
  578.             $rdvProductsArray iterator_to_array($rdv->getRdvProducts());
  579.             foreach ($rdv->getRDVBillings() as $RDVBilling) {
  580.                 $billing $RDVBilling->getBilling();
  581.                 $rdv $RDVBilling->getRDV();
  582.                 if ($billing->getStatus() === Billing::STATUS_SENT || $billing->getStatus() === Billing::STATUS_REGLEE) {
  583.                     $products array_map(function ($rdvProduct) {
  584.                         return $rdvProduct->getProduct()->getId();
  585.                     }, $rdvProductsArray);
  586.                     foreach ($billing->getBillingItems() as $item) {
  587.                         if (in_array($item->getProduct()->getId(), $products)) {
  588.                             $ht $item->getPrice() * $item->getQuantity();
  589.                             if ($item->getDiscount()) {
  590.                                 $totalHt += $ht - ($ht $item->getDiscount() / 100);
  591.                             } else {
  592.                                 $totalHt += $ht;
  593.                             }
  594.                         }
  595.                     }
  596.                 }
  597.             }
  598.         }
  599.         return $totalHt;
  600.     }
  601.     /**
  602.      * Get holidays for the current year and the next year.
  603.      *
  604.      * @param null $year
  605.      * @return array
  606.      * @throws \Exception
  607.      */
  608.     public function getHolidays($year null)
  609.     {
  610.         // If $year is not specified, use the current year
  611.         if ($year === null) {
  612.             $currentYear intval(date('Y'));
  613.         } else {
  614.             $currentYear intval($year);
  615.         }
  616.         // Calculate the next year
  617.         $nextYear $currentYear 1;
  618.         $dateTimeHoliday = array();
  619.         $easterDate easter_date($currentYear);
  620.         $easterDay date('j'$easterDate);
  621.         $easterMonth date('n'$easterDate);
  622.         $easterYear date('Y'$easterDate);
  623.         $holidays = array(
  624.             // Fixed holidays
  625.             gmmktime(00011$currentYear), // New Year's Day
  626.             gmmktime(00051$currentYear), // Labor Day
  627.             gmmktime(00058$currentYear), // Victory in Europe Day
  628.             gmmktime(000714$currentYear), // Bastille Day
  629.             gmmktime(000815$currentYear), // Assumption Day
  630.             gmmktime(000111$currentYear), // All Saints' Day
  631.             gmmktime(0001111$currentYear), // Armistice Day
  632.             gmmktime(0001225$currentYear), // Christmas Day
  633.             // Holidays dependent on Easter
  634.             gmmktime(000$easterMonth$easterDay 1$currentYear), // Easter Monday
  635.             gmmktime(000$easterMonth$easterDay 39$currentYear), // Ascension
  636.             gmmktime(000$easterMonth$easterDay 50$currentYear), // Pentecost
  637.         );
  638.         // Add holidays for the next year
  639.         foreach ($holidays as $holiday) {
  640.             $holidayNextYear $holiday 31536000// Add one year in seconds
  641.             $holidays[] = $holidayNextYear;
  642.         }
  643.         // Sort the holidays
  644.         sort($holidays);
  645.         foreach ($holidays as $value) {
  646.             $dateTimeHoliday[] = new \DateTime('@' $value, new \DateTimeZone('Europe/Paris'));
  647.         }
  648.         return $dateTimeHoliday;
  649.     }
  650.     /**
  651.      * @Route("/send_email", name="send_email", methods={"POST"})
  652.      */
  653.     public function sendEmail(MailService $mailServiceRequest $requestIntervenantRepository $intervenantRepository)
  654.     {
  655.         $id $request->request->all()['id'];
  656.         $intervenant $intervenantRepository->find($id);
  657.         $email $intervenant->getEmail();
  658.         if (!$email) {
  659.             $email $intervenant->getEmailPro();
  660.             if (!$email) {
  661.                 $user $intervenant->getUser();
  662.                 if (!$user) {
  663.                     return new JsonResponse('Utilisateur non trouvé'400);
  664.                 }
  665.                 $email $user->getEmail();
  666.             }
  667.         }
  668.         $mailService->sendToIntervenant(
  669.             $email,
  670.             [
  671.                 'intervenant' => $intervenant
  672.             ]
  673.         );
  674.         return new JsonResponse('ok'200);
  675.     }
  676.     /**
  677.      * @Route("/generateForm", methods={"GET","POST"})
  678.      */
  679.     public function generateForm(
  680.         Request                $request,
  681.         SessionSalonRepository  $sessionSalonRepository,
  682.         FormFactoryInterface $formFactory,
  683.         UrlGeneratorInterface  $urlGenerator
  684.     ): Response {
  685.         $sessionSalonQuery $request->request->get('sessionSalon');
  686.         $sessionSalon $sessionSalonRepository->find($sessionSalonQuery);
  687.         $actionUrl $urlGenerator->generate('planning_handle_form'); // Replace with your actual route name
  688.         $form $formFactory->create(AddSessionSalonType::class, $sessionSalon, [
  689.             'action' => $actionUrl,
  690.         ]);
  691.         $form->add('sessionSalon'HiddenType::class, [
  692.             'data' => $sessionSalon->getId(),
  693.             'mapped' => false
  694.         ]);
  695.         // Render the form view separately
  696.         $formView $this->renderView('planning/SessionSalon/_form.html.twig', [
  697.             'form' => $form->createView(),
  698.         ]);
  699.         return new JsonResponse(['view' => $formView]);
  700.     }
  701.     /**
  702.      * @Route("/handleForm", methods={"GET","POST"}, name="planning_handle_form")
  703.      */
  704.     public function handleForm(
  705.         Request                $request,
  706.         EntityManagerInterface  $entityManager,
  707.         RDVRepository $RDVRepository,
  708.         SessionSalonRepository  $sessionSalonRepository,
  709.         IntervenantRepository $intervenantRepository
  710.     ): Response {
  711.         $sessionSalonId $request->request->get('add_session_salon')['sessionSalon'];
  712.         // Retrieve the sessionSalon entity from the repository
  713.         /** @var SessionSalon $sessionSalon */
  714.         $sessionSalon $sessionSalonRepository->find($sessionSalonId);
  715.         $dateSession $sessionSalon->getStart();
  716.         $oldIntervenant $sessionSalon->getIntervenant(); // JOS INTERVENANT
  717.         $form $this->createForm(AddSessionSalonType::class,$sessionSalon);
  718.         $form->handleRequest($request);
  719.         if ($form->isSubmitted()) {
  720.             if ($sessionSalon) {
  721.                 $day $request->request->get('add_session_salon')['start']['date']['day'];
  722.                 $month $request->request->get('add_session_salon')['start']['date']['month'];
  723.                 $year $request->request->get('add_session_salon')['start']['date']['year'];
  724.                 $hour $request->request->get('add_session_salon')['start']['time']['hour'];
  725.                 $minute $request->request->get('add_session_salon')['start']['time']['minute'];
  726.                 $dayEnd $request->request->get('add_session_salon')['end']['date']['day'];
  727.                 $monthEnd $request->request->get('add_session_salon')['end']['date']['month'];
  728.                 $yearEnd $request->request->get('add_session_salon')['end']['date']['year'];
  729.                 $hourEnd $request->request->get('add_session_salon')['end']['time']['hour'];
  730.                 $minuteEnd $request->request->get('add_session_salon')['end']['time']['minute'];
  731.                 $timestamp strtotime("$year-$month-$day $hour:$minute");
  732.                 $timestampEnd strtotime("$yearEnd-$monthEnd-$dayEnd $hourEnd:$minuteEnd");
  733.                 $dateTime \DateTime::createFromFormat('U'$timestamp);
  734.                 $intervenantId $request->request->get('add_session_salon')['intervenant']; // INTERVENANT CHOOSE
  735.                 $intervenant $intervenantRepository->find($intervenantId);
  736.                 $rdvs $RDVRepository->replanifierDate($oldIntervenant$sessionSalon->getSalon(), $dateSession);
  737.                 $logplanning = new LogPlanning();
  738.                 $logplanning->setIntervenantOld($oldIntervenant);
  739.                 $logplanning->setNewIntervenant($intervenant);
  740.                 $logplanning->setSessionSalon($sessionSalon);
  741.                 $entityManager->persist($logplanning);
  742.                 $entityManager->flush();
  743.                 /** @var RDV $rdv */
  744.                 foreach ($rdvs as $rdv) {
  745.                     $dateTimeStart \DateTime::createFromFormat('U'$timestamp);
  746.                     $dateTimeEnd \DateTime::createFromFormat('U'$timestampEnd);
  747.                     $dateTimeStart->setTime(
  748.                         $rdv->getStart()->format('H'),    // Hours
  749.                         $rdv->getStart()->format('i'),    // Minutes
  750.                         $rdv->getStart()->format('s')     // Seconds
  751.                     );
  752.                     $dateTimeEnd->setTime(
  753.                         $rdv->getEnd()->format('H'),    // Hours
  754.                         $rdv->getEnd()->format('i'),    // Minutes
  755.                         $rdv->getEnd()->format('s')     // Seconds
  756.                     );
  757.                     $rdv->setStart($dateTimeStart);
  758.                     $rdv->setEnd($dateTimeEnd);
  759.                     $rdv->setIntervenant($intervenant);
  760.                     $entityManager->persist($rdv);
  761.                 }
  762. //                // replanification
  763.                 // take all rdv from the JOS intervenant of today and set up to the new intervenant/
  764. //                $rdvs = $RDVRepository->replanifierIntervenant($oldIntervenant, $dateTime);
  765. //                /** @var RDV $rdv */
  766. //                foreach ($rdvs as $rdv) {
  767. //                    $rdv->setIntervenant($intervenant);
  768. //                    $entityManager->persist($rdv);
  769. //                }
  770.                 if ($intervenant) {
  771.                     $sessionSalon->setIntervenant($intervenant);
  772.                 }
  773.             }
  774.             $entityManager->persist($sessionSalon);
  775.             $entityManager->flush();
  776.         }
  777.         return $this->redirectToRoute('app_planning_calendrier');
  778.     }
  779.     /**
  780.      * @Route("/dragdrop", methods={"GET","POST"})
  781.      */
  782.     public function dragdrop(Request  $request,
  783.                              SessionSalonRepository $sessionSalonRepository,
  784.                              EntityManagerInterface  $entityManager,
  785.     RDVRepository $RDVRepository,
  786.     IntervenantRepository  $intervenantRepository
  787.     ) {
  788.         $event $request->request->get('event');
  789.         $resource $request->request->get('resource');
  790.         $start $request->request->get('start');
  791.         if (strlen($start) === 13) {
  792.             $start $start 1000// Convert milliseconds to seconds
  793.         }
  794.         /** @var SessionSalon $sessionSalon */
  795.         $sessionSalon $sessionSalonRepository->find($event);
  796.         $updated false;
  797.         if($sessionSalon){
  798.             $updated true;
  799.             $intervenant $intervenantRepository->find($resource);
  800.             // prends les rdv de l'ancienne intervenannte sur l'ancienne date et on les passe à la nouvelle date
  801.             $rdvs $RDVRepository->replanifierDate($sessionSalon->getIntervenant(), $sessionSalon->getSalon(), $sessionSalon->getStart());
  802.             /** @var RDV $rdv */
  803.             foreach ($rdvs as $rdv){
  804.                 $dateTimeStart \DateTime::createFromFormat('U'$start);
  805.                 $dateTimeEnd \DateTime::createFromFormat('U'$start);
  806.                 $dateTimeStart->setTime(
  807.                     $rdv->getStart()->format('H'),    // Hours
  808.                     $rdv->getStart()->format('i'),    // Minutes
  809.                     $rdv->getStart()->format('s')     // Seconds
  810.                 );
  811.                 $dateTimeEnd->setTime(
  812.                     $rdv->getEnd()->format('H'),    // Hours
  813.                     $rdv->getEnd()->format('i'),    // Minutes
  814.                     $rdv->getEnd()->format('s')     // Seconds
  815.                 );
  816.                 $rdv->setStart($dateTimeStart);
  817.                 $rdv->setEnd($dateTimeEnd);
  818.                 $rdv->setIntervenant($intervenant);
  819.                 $entityManager->persist($rdv);
  820.             }
  821.             // replanification
  822.             // $rdvs = $RDVRepository->replanifierIntervenant($sessionSalon->getIntervenant(), $dateTime);
  823.             // /** @var RDV $rdv */
  824.             // foreach ($rdvs as $rdv){
  825.             //     $entityManager->persist($rdv);
  826.             // }
  827.             if($intervenant){
  828.                 $sessionSalon->setIntervenant($intervenant);
  829.             }
  830.             $dateTime \DateTime::createFromFormat('U'$start);
  831.             $dateTime->setTime(100000);
  832.             $endTime \DateTime::createFromFormat('U'$start);
  833.             $endTime->setTime(180000);
  834.             $sessionSalon->setStart($dateTime);
  835.             $sessionSalon->setEnd($endTime);
  836.             $entityManager->persist($sessionSalon);
  837.             $entityManager->flush();
  838.         }
  839.         return new JsonResponse(['status' => $updated]);
  840.     }
  841.     /**
  842.      * @Route("/export-calendrier", methods={"GET","POST"})
  843.      */
  844.     public function exportCalendrier(Request  $requestSessionSalonRepository  $sessionSalonRepository){
  845.         $salonQuery $request->query->get('salon');
  846.         $intervenantQuery $request->query->get('intervenant');
  847.         $dateDebut $request->query->get('date_debut');
  848.         $dateFin $request->query->get('date_fin');
  849.         $user $this->getUser();
  850.         $sessions $sessionSalonRepository->findAllMax($salonQuery$intervenantQuery$dateDebut$dateFin$user);
  851.         // Create a new PhpSpreadsheet spreadsheet
  852.         $spreadsheet = new Spreadsheet();
  853.         // Create a new worksheet
  854.         $worksheet $spreadsheet->getActiveSheet();
  855.         // Add headers to the worksheet (customize this part as needed)
  856.         $worksheet->setCellValue('A1''Session Start');
  857.         $worksheet->setCellValue('B1''Session End');
  858.         $worksheet->setCellValue('C1''Session Title');
  859.         $worksheet->setCellValue('D1''Intervenant Name');
  860.         $row 2// Start from row 2
  861.         // Add data to the worksheet
  862.         /** @var SessionSalon $session */
  863.         foreach ($sessions as $session) {
  864.             $worksheet->setCellValue('A' $row$session->getStart()->format('Y-m-d\TH:i'));
  865.             $worksheet->setCellValue('B' $row$session->getEnd() ? $session->getEnd()->format('Y-m-d\TH:i') : $session->getStart()->format('Y-m-d\T23:59'));
  866.             $worksheet->setCellValue('C' $rowhtmlspecialchars($session->getSalon()->getName(), ENT_QUOTES'UTF-8'));
  867.             $worksheet->setCellValue('D' $row$session->getIntervenant()->getLastname() . " " $session->getIntervenant()->getFirstname());
  868.             $row++;
  869.         }
  870.         // Create a response for the Excel file
  871.         // Create a temporary file to store the Excel data
  872.         $filePath $this->getParameter('kernel.project_dir') . '/public/exported_excel.xlsx';
  873.         $writer = new Xlsx($spreadsheet);
  874.         $writer->save($filePath);
  875.         // Create a BinaryFileResponse for the temporary file
  876.         $response = new Response();
  877.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  878.         $response->headers->set('Content-Disposition''attachment;filename="exported_excel.xlsx"');
  879.         // Read the file and set its content
  880.         $response->setContent(file_get_contents($filePath));
  881.         return $response;
  882.     }
  883.     /**
  884.      * @Route("/{id}/delete", name="planning_delete", methods={"DELETE"})
  885.      */
  886.     public function deletePlanning(Request $requestSessionSalon $sessionSalon): Response
  887.     {
  888.         if ($this->isCsrfTokenValid('delete' $sessionSalon->getId(), $request->request->get('_token'))) {
  889.             $entityManager $this->getDoctrine()->getManager();
  890.             $entityManager->remove($sessionSalon);
  891.             $entityManager->flush();
  892.         }
  893.         return $this->redirectToRoute('app_planning_pilotage');
  894.     }
  895.     /**
  896.      * @Route("/{id}/sessionSalon", methods={"GET","POST"})
  897.      */
  898.     public function sessionSalon(Request $request,int $idSessionSalon $sessionSalonEntityManagerInterface $em,
  899.                                 RDVRepository $RDVRepositoryIntervenantRepository  $intervenantRepository,
  900.                                 SessionSalonRepository  $sessionSalonRepository): Response
  901.     {
  902.         $form $this->createForm(SessionSalonType::class, $sessionSalon, [
  903.             'salon' => $sessionSalon->getSalon()
  904.         ]);
  905.         $form->handleRequest($request);
  906.         if ($form->isSubmitted() && $form->isValid()) {
  907.             $oldInfo $sessionSalonRepository->getOldInInfos($id);
  908.             // Make a copy of the old intervenant
  909.             $oldIntervenant $intervenantRepository->find($oldInfo["id"]);
  910.             $rdvs $RDVRepository->replanifierDate($oldIntervenant$sessionSalon->getSalon(), $oldInfo["start"]);
  911.             // Retrieve the new intervenant entity
  912.             $intervenantRequest $request->request->get('session_salon')["intervenant"];
  913.             $intervenant $intervenantRepository->find($intervenantRequest);
  914.             // Retrieve the start date information
  915.             $dateStart $request->request->get('session_salon')["start"];
  916.             $year $dateStart["date"]["year"];
  917.             $month $dateStart["date"]["month"];
  918.             $day $dateStart["date"]["day"];
  919.             foreach ($rdvs as $rdv){
  920.                 $start $rdv->getStart();
  921.                 $end $rdv->getEnd();
  922.                 // Create new start and end DateTime objects
  923.                 $newStart = new DateTime("$year-$month-$day " $start->format('H:i:s'));
  924.                 $newEnd = new DateTime("$year-$month-$day " $end->format('H:i:s'));
  925.                 // Update RDV properties
  926.                 $rdv->setStart($newStart);
  927.                 $rdv->setEnd($newEnd);
  928.                 $rdv->setIntervenant($intervenant);
  929.                 $em->persist($rdv);
  930.             }
  931.             $em->persist($sessionSalon);
  932.             $em->flush();
  933.         }
  934.         return $this->render('planning/session_salon.html.twig', [
  935.             'session' => $sessionSalon,
  936.             'form' => $form->createView()
  937.         ]);
  938.     }
  939.     /**
  940.      * @Route("/fusion", methods={"GET","POST"})
  941.      */
  942.     public function fusion(Request $requestRDVRepository $RDVRepositoryEntityManagerInterface $entityManager)
  943.     {
  944.         // do handle consumer
  945.         //        //TODO : filter by auto author
  946.         //        $rdvs = $RDVRepository->findForFusion();
  947.         //
  948.         //        foreach ($rdvs as $rdv) {
  949.         //
  950.         //            if(!$rdv->getClient()){
  951.         //                continue;
  952.         //            }
  953.         //
  954.         //            foreach ($rdvs as $key => $rdv2) {
  955.         //
  956.         //                if(!$rdv2->getClient()){
  957.         //                    continue;
  958.         //                }
  959.         //
  960.         //                if ($rdv->getId() != $rdv2->getId() &&
  961.         //                    $rdv->getClient()->getId() == $rdv2->getClient()->getId() &&
  962.         //                    $rdv->getStart() == $rdv2->getStart() &&
  963.         //                    $rdv->getSalon()->getId() == $rdv2->getSalon()->getId()
  964.         //
  965.         //                ) {
  966.         //
  967.         //                    $gridA = $rdv->getSalon()->getGridPrice()->getId();
  968.         //                    $gridB = $rdv2->getSalon()->getGridPrice()->getId();
  969.         //                    $total1 = 0;
  970.         //                    $total2 = 0;
  971.         //                    foreach ($rdv->getRdvProducts() as $rdvProduct) {
  972.         //                        $total1 += $rdvProduct->getProduct()->getPriceSellTTCByGrid($gridA);
  973.         //                    }
  974.         //
  975.         //                    foreach ($rdv2->getRdvProducts() as $rdvProduct) {
  976.         //                        $total2 += $rdvProduct->getProduct()->getPriceSellTTCByGrid($gridB);
  977.         //                    }
  978.         //
  979.         //                    if ($total1 >= $total2) {
  980.         //                        // delete 2
  981.         //                        $entityManager->remove($rdv2);
  982.         //                    } else {
  983.         //                        $entityManager->remove($rdv);
  984.         //                    }
  985.         //                    $entityManager->flush();
  986.         //
  987.         //                }
  988.         //
  989.         //
  990.         //            }
  991.         //        }
  992.         return $this->redirectToRoute('app_planning_site');
  993.     }
  994.     /**
  995.      * @Route("/downloadExcel")
  996.      */
  997.     public function downloadExcel(RDVRepository $repository)
  998.     {
  999.         $entities = new ArrayCollection($repository->findForExport());
  1000.         $response = new StreamedResponse();
  1001.         $columns $this->getColumnsForEntity(RDV::class);
  1002.         $response->setCallback(function () use ($entities$columns) {
  1003.             $handle fopen('php://output''w+');
  1004.             // Add header
  1005.             fputcsv($handlearray_keys($columns));
  1006.             while ($entity $entities->current()) {
  1007.                 $values = [];
  1008.                 foreach ($columns as $column => $callback) {
  1009.                     $value $callback;
  1010.                     if (is_callable($callback)) {
  1011.                         $value $callback($entity);
  1012.                     }
  1013.                     $values[] = $value;
  1014.                 }
  1015.                 fputcsv($handle$values);
  1016.                 $entities->next();
  1017.             }
  1018.             fclose($handle);
  1019.         });
  1020.         $filename 'rdv_export.csv';
  1021.         $response->headers->set('Content-Type''text/csv; charset=utf-8');
  1022.         $response->headers->set('Content-Disposition''attachment; filename="' $filename '"');
  1023.         return $response;
  1024.     }
  1025.     /**
  1026.      * @Route("/addRdv", methods={"POST"}, condition="request.isXmlHttpRequest()")
  1027.      */
  1028.     public function addRdvAjax(
  1029.         Request $request,
  1030.         SerializerInterface $serializer,
  1031.         ProductRepository $productRepository,
  1032.         SalonRepository $salonRepository,
  1033.         SessionSalonRepository $sessionSalonRepository
  1034.     ) {
  1035.         $rdv = new RDV();
  1036.         $em $this->getDoctrine()->getManager();
  1037.         $form $this->createForm(RDVType::class, $rdv, [
  1038.             'action' => $this->generateUrl($request->get('_route'))
  1039.         ])->handleRequest($request);
  1040.         if ($form->isSubmitted()) {
  1041.             $products $form->get('products')->getViewData();
  1042.             foreach ($products as $product) {
  1043.                 $obj $productRepository->find($product);
  1044.                 $rdvProduct = new RDVProduct();
  1045.                 $rdvProduct->setRdv($rdv);
  1046.                 $rdvProduct->setProduct($obj);
  1047.                 $em->persist($rdvProduct);
  1048.             }
  1049.             $params $request->request->get('rdv');
  1050.             $salon $salonRepository->find((int)$params['salon']);
  1051.             $start = new \DateTime($params['start']);
  1052.             $end = clone $start;
  1053.             $sessionLength $salon->getSite()->getType() === Site::TYPE_EHPAD '+15 minutes' '+30 minutes';
  1054.             $end->modify($sessionLength);
  1055.             $rdv->setStart($start);
  1056.             $rdv->setEnd($end);
  1057.             $sessionSalon $sessionSalonRepository->findSessionBySalonAndDate($salon$start);
  1058.             $rdv->setIntervenant($sessionSalon[0]->getIntervenant());
  1059.             $rdv->setAuthor($this->getUser());
  1060.             $this->getDoctrine()->getManager()->persist($rdv);
  1061.             $this->getDoctrine()->getManager()->flush();
  1062.             $rdv_json $serializer->serialize($rdv'json', [
  1063.                 'groups' => 'rdv',
  1064.                 'circular_reference_handler' => function ($object) {
  1065.                     return $object->getId();
  1066.                 }
  1067.             ]);
  1068.             return new JsonResponse($rdv_jsonResponse::HTTP_OK, [], true);
  1069.         }
  1070.         return new JsonResponse(nullResponse::HTTP_BAD_REQUEST);
  1071.     }
  1072.     /**
  1073.      * @Route("/getPlannings", methods={"GET"}, condition="request.isXmlHttpRequest()")
  1074.      */
  1075.     public function ajaxFilter(Request $requestRDVRepository $repositorySerializerInterface $serializer)
  1076.     {
  1077.         $company $request->get('company');
  1078.         $intervenant $request->get('intervenant');
  1079.         $site $request->get('site');
  1080.         $result null;
  1081.         if ($site) {
  1082.             $result $repository->findBySite($site);
  1083.         }
  1084.         if ($company) {
  1085.             $result $repository->findByCompany($company);
  1086.         }
  1087.         if ($intervenant) {
  1088.             $result $repository->findBy(['intervenant' => $intervenant]);
  1089.         }
  1090.         if (!$site && !$company && !$intervenant) {
  1091.             $result $repository->findAll();
  1092.         }
  1093.         $result $serializer->serialize($result'json', [
  1094.             'groups' => 'rdv',
  1095.             'circular_reference_handler' => function ($object) {
  1096.                 return $object->getId();
  1097.             }
  1098.         ]);
  1099.         return new JsonResponse($resultResponse::HTTP_OK, [], true);
  1100.     }
  1101.     /**
  1102.      * @Route("/getSalons/{id}", methods={"GET"}, condition="request.isXmlHttpRequest()")
  1103.      */
  1104.     public function ajaxGetSalons(Client $clientSerializerInterface $serializer)
  1105.     {
  1106.         // dump('d'. $client->getSite()->getId());die;
  1107.         $salons $client->getSite()->getSalons();
  1108.         $result $serializer->serialize($salons'json', [
  1109.             'groups' => 'rdv',
  1110.             'circular_reference_handler' => function ($object) {
  1111.                 return $object->getId();
  1112.             }
  1113.         ]);
  1114.         return new JsonResponse($resultResponse::HTTP_OK, [], true);
  1115.     }
  1116.     /**
  1117.      * @Route("/getIntervenants/{id}/{date}", methods={"GET"}, condition="request.isXmlHttpRequest()")
  1118.      */
  1119.     public function ajaxGetIntervenants(
  1120.         Salon                  $salon,
  1121.         SerializerInterface    $serializer,
  1122.         SessionSalonRepository $sessionSalonRepository,
  1123.         $date
  1124.     ) {
  1125.         // dump('d'. $client->getSite()->getId());die;
  1126.         //        $intervenants = $salon->getIntervenantSalons()->filter(function ($e){
  1127.         //            return $e->getIntervenant()->getStatus() == 1;
  1128.         //        });
  1129.         $date date_create_from_format('Y-m-d H:i'$date);
  1130.         $intervenants = [];
  1131.         $sessionsSalons $sessionSalonRepository->findBy(['salon' => $salon]);
  1132.         /** @var SessionSalon $sessionSalon */
  1133.         foreach ($sessionsSalons as $sessionSalon) {
  1134.             $dateSalon $sessionSalon->getStart();
  1135.             if ($sessionSalon->getIntervenant() && $sessionSalon->getIntervenant()->getStatus() == && $dateSalon->format('Y-m-d') == $date->format('Y-m-d')) {
  1136.                 $intervenants[$sessionSalon->getIntervenant()->getId()] = $sessionSalon->getIntervenant();
  1137.             }
  1138.         }
  1139.         $result $serializer->serialize(array_values($intervenants), 'json', [
  1140.             'groups' => 'rdv',
  1141.             'circular_reference_handler' => function ($object) {
  1142.                 return $object->getId();
  1143.             }
  1144.         ]);
  1145.         return new JsonResponse($resultResponse::HTTP_OK, [], true);
  1146.     }
  1147.     /**
  1148.      * @Route("/getProducts/{id}", methods={"GET"}, condition="request.isXmlHttpRequest()")
  1149.      */
  1150.     public function ajaxGetProducts(Salon $salonSerializerInterface $serializerProductRepository $productRepository)
  1151.     {
  1152.         $tag $salon->getService();
  1153.         $products $productRepository->findBy([
  1154.             'type' => strtolower($tag),
  1155.             'indisponibleVente' => 0
  1156.         ]);
  1157.         $result $serializer->serialize($products'json', [
  1158.             'groups' => 'planning',
  1159.             'circular_reference_handler' => function ($object) {
  1160.                 return $object->getId();
  1161.             }
  1162.         ]);
  1163.         return new JsonResponse($resultResponse::HTTP_OK, [], true);
  1164.     }
  1165.     /**
  1166.      * @Route("/{id}", methods={"GET"})
  1167.      */
  1168.     public function show(RDV $company): Response
  1169.     {
  1170.         return $this->render('company/show.html.twig', [
  1171.             'company' => $company,
  1172.         ]);
  1173.     }
  1174.     /**
  1175.      * @Route("/{id}/edit", methods={"GET","POST"})
  1176.      */
  1177.     public function edit(
  1178.         Request                $request,
  1179.         RDV $rdv,
  1180.         ProductRepository      $productRepository,
  1181.         RDVProductRepository   $RDVProductRepository,
  1182.         SessionSalonRepository $sessionSalonRepository,
  1183.         RDVRepository          $RDVRepository,
  1184.         PaytweakService $paytweakService,
  1185.         LoggerInterface $logger,
  1186.         ReglementManager  $reglementManager,
  1187.         ClientRepository  $clientRepository,
  1188.         CsrfTokenManagerInterface  $csrfTokenManager
  1189.     ): Response {
  1190.         //        if (!$rdv->getClient()) {
  1191.         //            return $this->redirectToRoute('app_planning_liste');
  1192.         //        }
  1193.         $em $this->getDoctrine()->getManager();
  1194.         /** @var User $user */
  1195.         $user $this->getUser();
  1196.         $canBill true;
  1197.         $canvalidate true;
  1198.         $total 0;
  1199.         if ($user->hasRole('ROLE_COIFFEUR')) {
  1200.             if (!$rdv->getIntervenant() || !$rdv->getIntervenant()->getUser() || ($rdv->getIntervenant()->getUser() && $rdv->getIntervenant()->getUser() != $user)) {
  1201.                 $canBill false;
  1202.             }
  1203.         }
  1204.         // on désactiver l'option facturer
  1205.         if ($user->hasRole('ROLE_COIFFEUR')) {
  1206.             $canvalidate false;
  1207.         }
  1208.         // on désativer le fait de changer de stratus
  1209.         $canChangeStatus true;
  1210.         if ($user->hasRole('ROLE_COIFFEUR') && $rdv->getStatus() === RDV::STATUS_FACTURER) {
  1211.             $canChangeStatus false;
  1212.         }
  1213.         $disabled false;
  1214.         if ($rdv->getValidated()) {
  1215.             $dif time() - $rdv->getValidated()->getTimestamp();
  1216.             // $user->hasRole(User::ROLE_COIFFEUR) &&
  1217.             if ($rdv->getStatus() == RDV::STATUS_VALIDATED && $dif 86400) {
  1218.                 $disabled true;
  1219.             }
  1220.         }
  1221.         if ($user->hasRole(User::ROLE_COIFFEUR && $rdv->getStatus() === RDV::STATUS_ANNULER)) {
  1222.             $disabled true;
  1223.         }
  1224.         if ($user->hasRole(User::ROLE_ADMIN) ||  $user->hasRole(User::ROLE_BO) ||  $user->hasRole(User::ROLE_ADMINISTRATIVE)) {
  1225.             $disabled false;
  1226.         }
  1227.         if ($rdv->isPlatform()) {
  1228.             $createdFrom 'Plateforme';
  1229.         } else {
  1230.             $createdFrom $rdv->getAuthor() ?: 'auto';
  1231.         }
  1232.         $oldStatus $rdv->getStatus();
  1233.         $now = new \DateTime();
  1234.         $form $this->createForm(
  1235.             RDVType::class,
  1236.             $rdv,
  1237.             [
  1238.                 'edition' => true,
  1239.                 'disabled' => $disabled,
  1240.                 'salon' => $rdv->getSalon(),
  1241.                 'hideFacture' => $user->hasRole(User::ROLE_COIFFEUR),
  1242.                 'canValidate' => $user->hasRole(User::ROLE_ADMIN)
  1243.                     ||  $user->hasRole(User::ROLE_BO)
  1244.                     ||  $user->hasRole(User::ROLE_ADMINISTRATIVE),
  1245.                 'createdFrom' => $createdFrom,
  1246.                 'csrf_protection' => true,
  1247.                 'csrf_field_name' => '_token',
  1248.                 // important part; unique key
  1249.                 'csrf_token_id'   => 'form_intention',
  1250.                 'canChangeStatus' => $canChangeStatus
  1251.             ]
  1252.         );
  1253.         if($rdv->getClient()){
  1254.             if ($rdv->getClient()->getConsignesClient()){
  1255.                 $form->get('consignesClient')->setData($rdv->getClient()->getConsignesClient());
  1256.             }
  1257.             if ($rdv->getClient()->getRoomNumber()){
  1258.                 $form->get('roomNumber')->setData($rdv->getClient()->getRoomNumber());
  1259.             }
  1260.         }
  1261.         $form->handleRequest($request);
  1262.         if (!$form->isSubmitted()) {
  1263.             $total 0;
  1264.             $products $productRepository->getProductsByRDV($rdv);
  1265.             foreach ($products as $product) {
  1266.                 $grid $rdv->getSalon() && $rdv->getSalon()->getGridPrice() ? $rdv->getSalon()->getGridPrice()->getId() : 1;
  1267.                 $productObj $productRepository->find($product);
  1268.                 $total += $productObj->getPriceSellTTCByGrid($grid);
  1269.             }
  1270.             $form->get(
  1271.                 'products'
  1272.             )->setData($products);
  1273.         } else if ($form->isSubmitted() && $form->isValid()) {
  1274.             $roomNumber $form->get('roomNumber')->getData();
  1275.             $comment $form->get('consignesClient')->getData();
  1276.             $client$rdv->getClient();
  1277.             if($client) {
  1278.                 $client->setConsignesClient($comment);
  1279.                 $client->setRoomNumber($roomNumber);
  1280.                 $em->persist($client);
  1281.             }
  1282.             $products $form->get('products')->getViewData();
  1283.             $csrfTokenManager->refreshToken('form_intention');
  1284.             // START: Si on change la date d’un RDV créé par une récurrence de contrat, les RDV de la même récurrence => décalage des autres RDV
  1285.             $uow $em->getUnitOfWork();
  1286.             /** @var RDV $oldRDV */
  1287.             $oldRDV $uow->getOriginalEntityData($rdv);
  1288.             if ($oldRDV['start'] != $rdv->getStart() && $rdv->getContract()) {
  1289.                 $diff $oldRDV['start']->diff($rdv->getStart());
  1290.                 $diff2 $oldRDV['start']->diff($rdv->getStart());
  1291.                 $rdvs = [];
  1292.                 if ($rdv->getContract()) {
  1293.                     $rdvs $RDVRepository->findForReplanificationByContract([$rdv->getContract()], $rdv->getStart(), $rdv->getSalon());
  1294.                 }
  1295.                 /** @var RDV $item */
  1296.                 foreach ($rdvs as $item) {
  1297.                     if ($item->getId() === $rdv->getId()) {
  1298.                         continue;
  1299.                     }
  1300.                     $date = clone $item->getStart();
  1301.                     $endDate = clone $item->getEnd();
  1302.                     $date->add($diff);
  1303.                     $endDate->add($diff2);
  1304.                     $item->setStart($date);
  1305.                     $item->setEnd($endDate);
  1306.                     $em->persist($item);
  1307.                     $em->flush();
  1308.                 }
  1309.                 $em->flush();
  1310.             }
  1311.             // END
  1312.             $productRdv $RDVProductRepository->findBy([
  1313.                 'rdv' => $rdv
  1314.             ]);
  1315.             /*
  1316.              * On duplique le RDV à la prochaine date d’ouverture du salon,
  1317.              * Seule la date et le statut sont différents du RDV d’origine. Le statut = « Replanifié »
  1318.              * Le RDV d’origine est lui conservé en statut annulé
  1319.              */
  1320.             if (
  1321.                 $oldStatus != RDV::STATUS_ANNULER
  1322.                 && $rdv->getStatus() === RDV::STATUS_ANNULER
  1323.                 && $rdv->getCancelReason()->getLabel() != 'Décès'
  1324.                 && $rdv->getCancelReason()->getLabel() != 'Client parti du site'
  1325.                 && $rdv->getCancelReason()->getLabel() != 'RDV supprimé'
  1326.             ) {
  1327.                 $sessionSalons null;
  1328.                 $salon $rdv->getSalon();
  1329.                 $dateStart = clone $rdv->getStart();
  1330.                 $dateStart->setTime(0000);
  1331.                 $dateStart->modify('+1 day');
  1332.                 if ($salon) {
  1333.                     $sessionSalons $sessionSalonRepository->findFirstBySalon($salon$dateStart);
  1334.                 }
  1335.                 //1 . create new RDV  to next "JOS"
  1336.                 if ($sessionSalons) {
  1337.                     /** @var \DateTime $josStart */
  1338.                     // keep the rdv hour
  1339.                     $josStart $sessionSalons->getStart();
  1340.                     /** @var \DateTime $josEnd */
  1341.                     $josEnd $sessionSalons->getEnd();
  1342.                     $josStart->setTime(
  1343.                         $rdv->getStart()->format('H'),    // Hours
  1344.                         $rdv->getStart()->format('i'),    // Minutes
  1345.                         $rdv->getStart()->format('s')     // Seconds
  1346.                     );
  1347.                     $josEnd->setTime(
  1348.                         $rdv->getEnd()->format('H'),    // Hours
  1349.                         $rdv->getEnd()->format('i'),    // Minutes
  1350.                         $rdv->getEnd()->format('s')     // Seconds
  1351.                     );
  1352.                     //  CREATE NEW RDV because we cancel the previous one
  1353.                     $rdv2 = new RDV();
  1354.                     $rdv2->setStatus(RDV::STATUS_REPLANIFIER);
  1355.                     $rdv2->setStart($josStart);
  1356.                     $rdv2->setEnd($josStart);
  1357.                     $rdv2->setAuthor($rdv->getAuthor());
  1358.                     $rdv2->setPriorite($rdv->getPriorite());
  1359.                     $rdv2->setRdvProducts($rdv->getRdvProducts());
  1360.                     if($rdv->getRecurrenceRdvs()) {
  1361.                         $rdv2->setRecurrenceRdvs($rdv->getRecurrenceRdvs());
  1362.                     }
  1363.                     foreach ($rdv->getRdvProducts() as $rdvProductOld) {
  1364.                         $rdvProduct = new RDVProduct();
  1365.                         $rdvProduct->setRdv($rdv2);
  1366.                         $rdvProduct->setProduct($rdvProductOld->getProduct());
  1367.                         $em->persist($rdvProduct);
  1368.                     }
  1369.                     $rdv2->setBillings($rdv->getBillings());
  1370.                     $logRDV = new LogCancel();
  1371.                     $rdv2->setSalon($rdv->getSalon());
  1372.                     $rdv2->setRDVBillings($rdv->getRDVBillings()); // to fix ??
  1373.                     $logRDV->setIntervenantOld($rdv->getIntervenant());
  1374.                     if ($sessionSalons->getIntervenant()) {
  1375.                         $rdv2->setIntervenant($sessionSalons->getIntervenant());
  1376.                         $logRDV->setNewIntervenant($sessionSalons->getIntervenant());
  1377.                     } else {
  1378.                         $rdv2->setIntervenant($rdv->getIntervenant());
  1379.                         $logRDV->setNewIntervenant($rdv->getIntervenant());
  1380.                     }
  1381.                     $logRDV->setSessionSalon($sessionSalons);
  1382.                     $em->persist($logRDV);
  1383.                     if ($rdv->getContract()) {
  1384.                         $rdv2->setContract($rdv->getContract());
  1385.                     }
  1386.                     $rdv2->setComment($rdv->getComment());
  1387.                     $rdv2->setClient($rdv->getClient());
  1388.                     $rdv2->setValidated($rdv->getValidated());
  1389.                     $rdv2->setCommentForfait($rdv->getCommentForfait());
  1390.                     $em->persist($rdv2);
  1391.                     ///// END CREATE NEW RDV
  1392.                 }
  1393.                 // 2. get all contracts of the clients
  1394. //                $clientContrats = [];
  1395. //                foreach ($rdv->getClient()->getContract() as $contract) {
  1396. //                    $clientContrats[] = $contract->getId();
  1397. //                }
  1398. //
  1399. //                // 3. get theirs RDV, we exclude the new RDV with the status
  1400. //                $rdvs = $RDVRepository->findForReplanificationByContract($clientContrats, $rdv->getStart(), $rdv->getSalon());
  1401. //
  1402. //                /** @var RDV $item */
  1403. //                foreach ($rdvs as $item) {
  1404. //                    // do not report current RDV
  1405. //                    if ($item->getId() === $rdv->getId()) {
  1406. //                        continue;
  1407. //                    }
  1408. //                    $dateStart = clone $item->getStart();
  1409. //                    $dateStart->setTime(0, 0, 0, 0);
  1410. //                    $dateStart->modify('+1 day');
  1411. //                    // find next jos
  1412. //                    $sessionSalons = $sessionSalonRepository->findFirstBySalon($item->getSalon(), $dateStart);
  1413. //                    if ($sessionSalons) {
  1414. //                        $item->setStart($sessionSalons->getStart());
  1415. //                        $item->setEnd($sessionSalons->getStart());
  1416. //                        $em->persist($item);
  1417. //                    }
  1418. //                }
  1419.                 $rdvs $RDVRepository->findForReplanificationNewRecurence($rdv->getClient(), $rdv->getStart(), $rdv->getSalon());
  1420.                 /** @var RDV $item */
  1421.                 foreach ($rdvs as $item) {
  1422.                     // do not report current RDV
  1423.                     if ($item->getId() === $rdv->getId()) {
  1424.                         continue;
  1425.                     }
  1426.                     $dateStart = clone $item->getStart();
  1427.                     $dateStart->setTime(0000);
  1428.                     $dateStart->modify('+1 day');
  1429.                     // find next jos
  1430.                     $sessionSalons $sessionSalonRepository->findFirstBySalon($item->getSalon(), $dateStart);
  1431.                     if ($sessionSalons) {
  1432.                         $item->setStart($sessionSalons->getStart());
  1433.                         $item->setEnd($sessionSalons->getStart());
  1434.                         $em->persist($item);
  1435.                     }
  1436.                 }
  1437.                 $em->flush();
  1438.             }
  1439.             if (
  1440.                 $rdv->getStatus() === RDV::STATUS_ANNULER
  1441.                 && ($rdv->getCancelReason()->getLabel() == 'Décès'
  1442.                 || $rdv->getCancelReason()->getLabel() == 'Client parti du site')
  1443.             ) {
  1444.                 $rdvsTodelete $this->RDVManager->findFromTodayByStatusPlan($client);
  1445.                 foreach ($rdvsTodelete as $rdvDelete) {
  1446.                     if($rdvDelete->getId() === $rdv->getId()){
  1447.                         continue;
  1448.                     }
  1449.                     $em->remove($rdvDelete);
  1450.                 }
  1451.                 $em->flush();
  1452.             }
  1453.             foreach ($productRdv as $product) {
  1454.                 $em->remove($product);
  1455.             }
  1456.             $em->flush();
  1457.             $total 0;
  1458.             foreach ($products as $product) {
  1459.                 $grid $rdv->getSalon() && $rdv->getSalon()->getGridPrice() ? $rdv->getSalon()->getGridPrice()->getId() : 1;
  1460.                 $productObj $productRepository->find($product);
  1461.                 $total += $productObj->getPriceSellTTCByGrid($grid);
  1462.                 // if rdvproduct already exists
  1463.                 $rdvProduct $RDVProductRepository->findOneBy([
  1464.                     'product' => $product,
  1465.                     'rdv' => $rdv
  1466.                 ]);
  1467.                 if (!$rdvProduct) {
  1468.                     $rdvProduct = new RDVProduct();
  1469.                     $rdvProduct->setRdv($rdv);
  1470.                     $rdvProduct->setProduct($productObj);
  1471.                     $rdv->addRdvProduct($rdvProduct);
  1472.                     $em->persist($rdvProduct);
  1473.                     $em->persist($rdv);
  1474.                 }
  1475.             }
  1476.             if ($oldStatus != RDV::STATUS_VALIDATED && $rdv->getStatus() === RDV::STATUS_VALIDATED) {
  1477.                 $rdv->setValidated(new \DateTime());
  1478.                 if($rdv->isPlatform()){
  1479.                     $clientExist $clientRepository->findOneBy([
  1480.                         'lastname' => $rdv->getClient()->getLastname(),
  1481.                         'firstname' => $rdv->getClient()->getFirstname(),
  1482.                         'civilite' => $rdv->getClient()->getCivilite(),
  1483.                         'site' => $rdv->getSalon()->getSite(),
  1484.                     ]);
  1485.                     $paymentLink $rdv->getPaymentLink();
  1486.                     if($clientExist){
  1487.                         /** @var RDV $lastRDV */
  1488.                         $lastRDV $this->RDVManager->getRepository()->findOneByClientAndToken($clientExist);
  1489.                         if($lastRDV){
  1490.                             $paymentLink $lastRDV->getPaymentLink();
  1491.                             //$path = parse_url($paymentLink, PHP_URL_PATH);
  1492.                             //$orderIdPaytweak = basename($path);
  1493.                         }
  1494.                     }
  1495.                     $billing $this->billingManager->createFromRDV($rdv$this->getUser());
  1496.                     $response $paytweakService->triggerPayment($paymentLink$billing->getTtc(), $billing->getCode());
  1497.                     if ($response['code'] !== 'OK') {
  1498.                         $this->mailService->sentErrorPaytweakResa($rdv$response['code'], $response['message']);
  1499.                         $logger->error('An error occurred for RDV ID ' $rdv->getId() . ': ' $response['message']);
  1500.                     }
  1501.                 }
  1502.             }
  1503.             // set the form product agains
  1504.             $em->flush();
  1505.         }
  1506.         return $this->render('planning/edit.html.twig', [
  1507.             'rdv' => $rdv,
  1508.             'canvalidate' => $canvalidate,
  1509.             'canBill' => $canBill,
  1510.             'total' => $total,
  1511.             'rdvProducts' => $rdv->getRdvProducts(),
  1512.             'form' => $form->createView(),
  1513.             'minuteIncrement' => $rdv->getSalon()->getSite()->getType() === Site::TYPE_EHPAD 15 30,
  1514.         ]);
  1515.     }
  1516.     /**
  1517.      * @Route("/{id}", methods={"DELETE"})
  1518.      */
  1519.     public function delete(Request $requestRDV $RDV): Response
  1520.     {
  1521.         if ($this->isCsrfTokenValid('delete' $RDV->getId(), $request->request->get('_token'))) {
  1522.             $entityManager $this->getDoctrine()->getManager();
  1523.             $entityManager->remove($RDV);
  1524.             $entityManager->flush();
  1525.         }
  1526.         return $this->redirectToRoute('app_planning_liste');
  1527.     }
  1528.     /**
  1529.      * @param $class
  1530.      * @return \Closure[]|mixed
  1531.      */
  1532.     private function getColumnsForEntity($class)
  1533.     {
  1534.         $columns[RDV::class] = [
  1535.             'Id' => function (RDV $RDV) {
  1536.                 return $RDV->getId();
  1537.             },
  1538.             'Client' => function (RDV $RDV) {
  1539.                 return (string)$RDV->getClient();
  1540.             },
  1541.             'Début' => function (RDV $RDV) {
  1542.                 return $RDV->getStart() ?  $RDV->getStart()->format('d-m-Y H:i:s') ? $RDV->getStart()->format('d-m-Y H:i:s') : '' '';
  1543.             },
  1544.             'Fin' => function (RDV $RDV) {
  1545.                 return $RDV->getEnd() ? $RDV->getEnd()->format('d-m-Y H:i:s') ? $RDV->getEnd()->format('d-m-Y H:i:s') : '' '';
  1546.             },
  1547.             'Intervenant' => function (RDV $RDV) {
  1548.                 return (string)$RDV->getIntervenant();
  1549.             },
  1550.             'Salon' => function (RDV $RDV) {
  1551.                 return $RDV->getSalon() ? $RDV->getSalon()->getName() : '';
  1552.             },
  1553.             'Status' => function (RDV $RDV) {
  1554.                 return $RDV->getStatus();
  1555.             },
  1556.             'Raison annulation' => function (RDV $RDV) {
  1557.                 return $RDV->getCancelReason();
  1558.             },
  1559.             'Commentaires' => function (RDV $RDV) {
  1560.                 return $RDV->getComment();
  1561.             },
  1562.             'Prise de RDV' => function (RDV $RDV) {
  1563.                 if ($RDV->isPlatform()) {
  1564.                     $createdFrom 'Plateforme';
  1565.                 } else {
  1566.                     $createdFrom $RDV->getAuthor() ? $RDV->getAuthor() : 'auto';
  1567.                 }
  1568.                 return $createdFrom;
  1569.             },
  1570.             'Priorite' => function (RDV $RDV) {
  1571.                 return $RDV->getPriorite();
  1572.             },
  1573.             'Récurrence' => function (RDV $RDV) {
  1574.                 return $RDV->getRecurrence();
  1575.             },
  1576.             'Email de facturation' => function (RDV $RDV) {
  1577.                 $billingEmail "";
  1578.                 $client $RDV->getClient();
  1579.                 if ($client && $client->getBillingInfos()) {
  1580.                     $billingEmail $client->getBillingInfos()->getEmail();
  1581.                 }
  1582.                 return $billingEmail;
  1583.             },
  1584.             'Montant TTC' => function (RDV $RDV) {
  1585.                 return $RDV->ttc();
  1586.             },
  1587.             'Products' => function (RDV $RDV) {
  1588.                 $products =[];
  1589.                 $productsRDV $RDV->getRdvProducts();
  1590.                 foreach($productsRDV as $productRdv)
  1591.                 {$products []= $productRdv->getProduct()->getName(); }
  1592.                 return implode(","$products);
  1593.             },
  1594.             'Factures' => function (RDV $RDV) {
  1595.                 $billingCodes = [];
  1596.                 if($RDV->getBillings() && $RDV->getRDVBillings()->count() > 0){
  1597.                     foreach ($RDV->getRDVBillings() as $billing) {
  1598.                         $billingCodes[] = $billing->getBilling()->getCode();
  1599.                     }
  1600.                 }
  1601.                 return implode(","$billingCodes);
  1602.             },
  1603.         ];
  1604.         if (array_key_exists($class$columns)) {
  1605.             return $columns[$class];
  1606.         }
  1607.         throw new \InvalidArgumentException(sprintf(
  1608.             'No columns set for "%s" entity',
  1609.             $class
  1610.         ));
  1611.     }
  1612. }