Linux SRV-16 6.18.44-paas #1 SMP PREEMPT_DYNAMIC Thu Aug 13 10:08:12 UTC 2026 x86_64
/
srv
/
data
/
web
/
vhosts
/
716cf56cb2.url-de-test.ws
/
htdocs
/
src
/
Controller
/
Front
/
/srv/data/web/vhosts/716cf56cb2.url-de-test.ws/htdocs/src/Controller/Front/BookingController.php
<?php namespace App\Controller\Front; use App\Entity\User; use App\Entity\Saison; use App\Entity\Booking; use App\Service\Mailer; use Psr\Log\LoggerInterface; use App\Service\PaypalPayment; use App\Service\ValidateDates; use App\Form\SearchLogementType; use App\Service\CalculPriceVisit; use App\Repository\IcalRepository; use App\Repository\UserRepository; use App\Service\AvailableLogements; use App\Repository\SaisonRepository; use App\Repository\BookingRepository; use App\Repository\LogementRepository; use App\Repository\TaxeRepository; use App\Service\IcalService; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface; /** * @Route("/reservation") */ class BookingController extends AbstractController { protected $saisonRepository; protected $logementRepository; protected $bookingRepository; protected $session; protected $calculPriceVisit; protected $em; protected $mailer; protected $validateDates; protected $userRepository; protected $logger; protected $icalRepository; protected $icalService; protected $availableLogements; protected $taxesRepository; public function __construct(LoggerInterface $logger, IcalRepository $icalRepository, Mailer $mailer, EntityManagerInterface $em, SaisonRepository $saisonRepository, LogementRepository $logementRepository, BookingRepository $bookingRepository, SessionInterface $session, CalculPriceVisit $calculPriceVisit, ValidateDates $validateDates, UserRepository $userRepository, IcalService $icalService, AvailableLogements $availableLogements, TaxeRepository $taxeRepository) { $this->saisonRepository = $saisonRepository; $this->logementRepository = $logementRepository; $this->bookingRepository = $bookingRepository; $this->session = $session; $this->calculPriceVisit = $calculPriceVisit; $this->em = $em; $this->mailer = $mailer; $this->validateDates = $validateDates; $this->userRepository = $userRepository; $this->logger = $logger; $this->icalRepository = $icalRepository; $this->icalService = $icalService; $this->availableLogements = $availableLogements; $this->taxesRepository = $taxeRepository; } /** * @Route("/", name="app_search_booking", methods={"GET", "POST"}) */ public function search(Request $request): Response { $saison = $this->saisonRepository->findOneBy(['name' => Saison::HAUTE_SAISON]); $form = $this->createForm(SearchLogementType::class); if ($this->session->get('searchFormData')) { $dataHome = $this->session->get('searchFormData'); $form->submit([ 'start' => $dataHome['start']->format('Y-m-d'), 'end' => $dataHome['end']->format('Y-m-d'), 'nbPersonnes' => $dataHome['nbPersonnes'], 'nbEnfants' => $dataHome['nbEnfants'] ]); } else { $form->handleRequest($request); } if (($form->isSubmitted() && $form->isValid()) || $this->session->get('searchFormData')) { $data = $form->getData(); $isValidateDates = $this->validateDates->validate($data); if ($isValidateDates) { $logements = $this->logementRepository->findAll(); $taxes = $this->taxesRepository->findAll(); //synchronize with booking foreach ($logements as $logement) { foreach ($logement->getIcals() as $ical) { if (!$ical->isIsGenerated()) { $this->icalService->import($logement, $ical->getAccessLink()); } } } $logementsDisponibles = $this->logementRepository->availableLogements($data); if (count($logementsDisponibles) === 0) { $newDates = $this->availableLogements->consecutiveAvailableDays($data); } $nights = $data['start']->diff($data['end'])->days; $this->session->set("infos_reservation", ['start' => $data['start'], 'end' => $data['end']]); $this->session->set("personnes", ['nbAdultes' => $data['nbPersonnes'], 'nbEnfants' => $data['nbEnfants']]); $logementsWithTotalPrice = []; foreach ($logementsDisponibles as $logement) { $totalPriceWithoutTaxes = $this->calculPriceVisit->totalPrice($data, $logement); $totalPrice = $totalPriceWithoutTaxes; $taxesArray = []; foreach ($taxes as $taxe) { $taxesArray[] = [ $taxe->getName() . ' (' . $taxe->getTaux() . '%)' => $totalPrice * ($taxe->getTaux() / 100) ]; $totalPrice += $totalPrice * ($taxe->getTaux() / 100); } $logementsWithTotalPrice[] = [ 'logement' => $logement, 'totalPrice' => $totalPrice, ]; } } $viewData = [ "hauteSaison" => $saison, "form" => $form->createView(), ]; if (isset($nights)) { $viewData['nights'] = $nights; } if (isset($logementsDisponibles) && count($logementsWithTotalPrice) > 0) { $viewData['logements'] = $logementsWithTotalPrice; } if (isset($newDates)) { $viewData['newDates'] = $newDates; } $this->session->remove('searchFormData'); return $this->render("Front/Booking/search.html.twig", $viewData); } return $this->render("Front/Booking/search.html.twig", [ "form" => $form->createView(), "hauteSaison" => $saison, ]); } /** * @Route("/resume/{id}", name="app_resume_booking", methods={"GET", "POST"}) */ public function resumeBooking(int $id, Request $request): Response { $logement = $this->logementRepository->find($id); $taxes = $this->taxesRepository->findAll(); $dates = $this->session->get("infos_reservation"); $this->session->set('referer', [$request->attributes->get('_route'), $request->attributes->get('id')]); foreach ($logement->getBookings() as $booking) { if (!( ($dates['start'] < $booking->getCheckin() && $dates['end'] < $booking->getCheckin()) || ($dates['start'] > $booking->getCheckout() && $dates['end'] > $booking->getCheckout()) )) { return $this->redirectToRoute("app_search_booking"); } } if (!isset($dates)) { return $this->redirectToRoute("app_search_booking"); } $totalPriceWithoutTaxes = $this->calculPriceVisit->totalPrice($dates, $logement); $totalPrice = $totalPriceWithoutTaxes; $taxesArray = []; foreach ($taxes as $taxe) { $taxesArray[] = [ $taxe->getName() . ' (' . $taxe->getTaux() . '%)' => $totalPrice * ($taxe->getTaux() / 100) ]; $totalPrice += $totalPrice * ($taxe->getTaux() / 100); } $splitPrices = $this->calculPriceVisit->accompte($totalPrice); $beforeOneMonth = $this->validateDates->beforeOneMonth($dates); $this->session->set("prices", ["total" => $totalPrice, "splitted" => $splitPrices]); $nights = $dates['start']->diff($dates['end'])->days; return $this->render("Front/Booking/create.html.twig", [ "logement" => $logement, "dates" => $dates, "total" => $totalPrice, "splitPrices" => $splitPrices, "beforeOneMonth" => $beforeOneMonth, "taxes" => $taxesArray, "nights" => $nights ]); } /** * @Route("/create/orders", name="app_create_order", methods={"GET", "POST"}) */ public function createOrder(Request $request, PaypalPayment $paypalPayment): Response { try { $response = $request->getContent(); // Décoder les données JSON en tableau associatif $data = json_decode($response, true); $fundingSource = $this->session->set("fundingSource", $data['source']); $prices = $this->session->get("prices"); $accompte = strval($prices['splitted']['accompte'] / 100); $total = strval($prices['total'] / 100); $dates = $this->session->get("infos_reservation"); $beforeOneMonth = $this->validateDates->beforeOneMonth($dates); if ($beforeOneMonth) { $order = $paypalPayment->createOrder($accompte); } else { $order = $paypalPayment->createOrder($total); } $data = json_decode($order->getContent(), true); } catch (\Exception $e) { $this->addFlash("danger", "Une erreur est survenue"); $this->logger->error('Create order paypal error: ' . $e->getMessage()); } return new JsonResponse($data); } /** * @Route("/orders/{orderID}/capture", name="app_capture_order", methods={"GET", "POST"}) */ public function captureOrder(string $orderID, PaypalPayment $paypalPayment): JsonResponse { try { $capture = $paypalPayment->captureOrder($orderID); $data = json_decode($capture->getContent(), true); } catch (\Exception $e) { $this->addFlash("danger", "Une erreur est survenue"); $this->logger->error('Capture order paypal error: ' . $e->getMessage()); } return new JsonResponse($data); } /** * @Route("/create/{id}/{orderid}", name="app_create_booking", methods={"GET", "POST"}) */ public function createBooking(int $id, string $orderid, TokenGeneratorInterface $tokenGenerator) { try { $logement = $this->logementRepository->find($id); $prices = $this->session->get("prices"); $dates = $this->session->get("infos_reservation"); $fundingSource = $this->session->get("fundingSource"); $personnes = $this->session->get("personnes"); $saison = $this->saisonRepository->findCurrentSaison($dates['start']); /** * @var User */ $user = $this->getUser(); $booking = new Booking(); $booking->setLogement($logement) ->setUser($user) ->setSaison($saison[0]) ->setTotalPrice($prices["total"]) ->setAdvance($prices['splitted']['accompte']) ->setRest($prices['splitted']['rest']) ->setCheckin($dates['start']) ->setCheckout($dates['end']) ->setLogementName($logement->getName()) ->setLogementPrice($logement->getPrice()) ->setUserName($user->getFirstname() . " " . $user->getLastname()) ->setUserPhone($user->getPhone()) ->setUserEmail($user->getEmail()) ->setOrderId($orderid) ->setFundingSource($fundingSource) ->setStatusAdvance(Booking::STATUS_PENDING) ->setStatusRest(Booking::STATUS_PENDING) ->setSaisonName($saison[0]->getName()) ->setNbAdultes($personnes['nbAdultes']) ->setNbEnfants($personnes['nbEnfants']); $beforeOneMonth = $this->validateDates->beforeOneMonth($dates); if ($beforeOneMonth) { $tokenRest = $tokenGenerator->generateToken(); $booking->setTokenRest($tokenRest); } $this->em->persist($booking); $this->em->flush(); $this->addFlash("success", "Votre réservation à bien été enregistré, <br/> L'équipe A CASA vous remercie ! <br/> <a href='/'>Retour à l'accueil</a>"); } catch (\Exception $e) { $this->logger->error("error creating booking" . $e->getMessage()); throw new \Exception($e); } return $this->redirectToRoute("app_success_booking"); } /** * @Route("/vwKhykRBfUSHqdCniEdBV", name="app_webhook_paypal", methods={"GET", "POST"}) */ public function webhook(Request $request): JsonResponse { $payload = json_decode($request->getContent(), true); try { if (isset($payload['event_type'])) { switch ($payload['event_type']) { case 'PAYMENT.CAPTURE.COMPLETED': $orderID = $payload['resource']['supplementary_data']['related_ids']['order_id']; $booking = $this->bookingRepository->findOneBy(['orderId' => $orderID]); $amount = (int)$payload['resource']['amount']['value'] * 100; if ($amount === $booking->getAdvance()) { $booking->setStatusAdvance(Booking::STATUS_PAID); $this->mailer->bookingAdmin($booking); $this->mailer->bookingClient($booking); } else if ($amount === $booking->getRest()) { $booking->setStatusRest(Booking::STATUS_PAID); $booking->setTokenRest(null); } else if ($amount === $booking->getTotalPrice()) { $booking->setStatusAdvance(Booking::STATUS_PAID); $booking->setStatusRest(Booking::STATUS_PAID); $this->mailer->bookingClient($booking); $this->mailer->bookingAdmin($booking); } $this->em->persist($booking); break; } } $this->em->flush(); return new JsonResponse("success"); } catch (\Exception $e) { $this->logger->error('Webhook processing error: ' . $e->getMessage()); return new JsonResponse("error"); } } /** * @Route("/orders/rest", name="app_create_order_rest", methods={"GET", "POST"}) */ public function createOrderRest(Request $request, PaypalPayment $paypalPayment): Response { try { $response = $request->getContent(); // Décoder les données JSON en tableau associatif $data = json_decode($response, true); $bookingID = $data['id']; $booking = $this->bookingRepository->find($bookingID); $rest = strval($booking->getRest() / 100); $order = $paypalPayment->createOrder($rest); $data = json_decode($order->getContent(), true); } catch (\Exception $e) { $this->addFlash("danger", "Une erreur est survenue"); $this->logger->error('Create order rest paypal error: ' . $e->getMessage()); } return new JsonResponse($data); } /** * @Route("/order/{id}/{orderid}", name="app_update_orderId_booking", methods={"GET", "POST"}) */ public function updateOrderIdBooking(int $id, string $orderid) { try { $booking = $this->bookingRepository->find($id); $booking->setOrderId($orderid); $this->em->persist($booking); $this->em->flush(); $this->addFlash("success", "Votre paiement à bien été validé, <br/> L'équipe A CASA vous remercie ! <br/> <a href='/'>Retour à l'accueil</a>"); } catch (\Exception $e) { $this->logger->error("error update orderId booking" . $e->getMessage()); $this->addFlash("danger", "Une erreur est survenue"); } return $this->redirectToRoute("app_success_booking"); } /** * @Route("/confirmation", name="app_success_booking", methods={"GET"}) */ public function bookingSuccess(): Response { return $this->render("Front/Pages/booking-success.html.twig"); } /** * @Route("/return-ical/{id}", name="app_return_ical") */ public function retrunIcal(int $id, Request $request): Response { $response = $this->icalService->generate($id, $request); return new Response(file_get_contents($response->getContent())); } /** * @Route("cancel/{id}", name="app_front_cancel_booking", methods={"GET", "POST"}) */ public function cancelBooking(int $id) { $booking = $this->bookingRepository->find($id); $booking->setIsCancel(true); $this->em->persist($booking); $this->em->flush(); try { $this->mailer->bookingCancel($booking); } catch (\Exception $e) { $this->logger->error('error send email cancel reservation : ' . $e->getMessage()); } $this->addFlash('success', 'Votre réservation à bien été annulée'); return $this->redirectToRoute("app_profile"); } /** * @Route("/{token}", name="app_pay_rest_booking", methods={"GET", "POST"}) */ public function payRest(string $token): Response { $booking = $this->bookingRepository->findOneBy(['tokenRest' => $token]); if (!$booking) { throw new NotFoundHttpException("Cette page n'éxiste pas !"); } return $this->render("Front/Booking/pay-rest-booking.html.twig", [ "booking" => $booking ]); } }