src/Controller/PlanningController.php line 1544

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