src/Controller/Api/CartContoller.php line 305

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Api;
  3. use App\Entity\Booking;
  4. use App\Entity\Cart;
  5. use App\Entity\Custom;
  6. use App\Entity\CustomCart;
  7. use App\Entity\User;
  8. use App\Form\BookingType;
  9. use App\Form\CartType;
  10. use App\Helpers\FormHelper;
  11. use App\Helpers\ResponseCode;
  12. use App\Helpers\TngGuestClient;
  13. use App\Helpers\TngStaffClient;
  14. use App\Repository\BookingRepository;
  15. use App\Repository\CartRepository;
  16. use App\Repository\CustomRepository;
  17. use App\Repository\ServiceRepository;
  18. use App\Repository\SubServiceRepository;
  19. use App\Utils\Fondy;
  20. use App\Utils\Mercure;
  21. use App\Utils\Paginator;
  22. use App\Utils\ResponseTrait;
  23. use Doctrine\ORM\EntityManagerInterface;
  24. use Knp\Component\Pager\PaginatorInterface;
  25. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  26. use Symfony\Component\DependencyInjection\ContainerInterface;
  27. use Symfony\Component\HttpFoundation\Request;
  28. use Symfony\Component\Routing\Annotation\Route;
  29. use Symfony\Contracts\Translation\TranslatorInterface;
  30. class CartContoller extends AbstractController
  31. {
  32.     use ResponseTrait;
  33.     /**
  34.      * @Route(path="/api/cart", methods={"GET"})
  35.      */
  36.     public function getCart(CartRepository $repository)
  37.     {
  38.         /** @var User $user */
  39.         $user $this->getUser();
  40.         $cart $repository->getByUser($user);
  41.         return $this->statusOk(
  42.             null,
  43.             null,
  44.             [
  45.                 'items' => $cart,
  46.             ]
  47.         );
  48.     }
  49.     /**
  50.      * @Route(path="/api/customs/archived", methods={"GET"})
  51.      */
  52.     public function getCustomsArchived(Request $requestPaginator $paginatorServicePaginatorInterface $paginatorCustomRepository $customRepository)
  53.     {
  54.         $query $customRepository->getByUser($this->getUser());
  55.         $items $paginator->paginate(
  56.             $query,
  57.             $request->query->getInt('page'1),
  58.             $request->query->getInt('limit'10)
  59.         );
  60.         $items $paginatorService->getResponsePaginate($items);
  61.         return $this->statusOk(
  62.             null,
  63.             null,
  64.             $items
  65.         );
  66.     }
  67.     /**
  68.      * @Route(path="/api/customs/archived/{id}", methods={"GET"})
  69.      */
  70.     public function getCustomArchived(CartRepository $repositoryCustomRepository $customRepository$id)
  71.     {
  72.         /** @var User $user */
  73.         $user $this->getUser();
  74.         $custom $customRepository->getByUserAndId($this->getUser(), $id);
  75.         return $this->statusOk(
  76.             null,
  77.             null,
  78.             $custom
  79.         );
  80.     }
  81.     /**
  82.      * @Route(path="/api/add-to-cart", methods={"POST"})
  83.      */
  84.     public function addToCart(Request $requestCartRepository $repository)
  85.     {
  86.         $data $request->request->all();
  87.         $form $this->createForm(CartType::class);
  88.         $form->submit($data);
  89.         if ($form->isSubmitted() && $form->isValid()) {
  90.             /** @var User $user */
  91.             $user $this->getUser();
  92.             $subServices $form->getData()['sub_services'];
  93.             $em $this->getDoctrine()->getManager();
  94.             foreach ($subServices as $subService) {
  95.                 $cart $repository->getByUserAndSubService($user$subService) ?: new Cart();
  96.                 if ($cart->getId()) {
  97.                     $cart->setCount($cart->getCount() + 1);
  98.                 }
  99.                 $cart->setUser($user)
  100.                     ->setSubService($subService);
  101.                 $em->persist($cart);
  102.             }
  103.             $em->flush();
  104.             return $this->statusOk(nullnull$user);
  105.         }
  106.         $errors FormHelper::getErrors2($form);
  107.         return $this->statusConflict($errorsResponseCode::VALIDATION_FAIL);
  108.     }
  109.     /**
  110.      * @Route(path="/api/cart/{id}", methods={"PATCH"})
  111.      */
  112.     public function changeCount(CartRepository $repositoryRequest $request$id)
  113.     {
  114.         /** @var User $user */
  115.         $user $this->getUser();
  116.         $cart $repository->getByUserAndId($user$id ?: 0);
  117.         if ($cart && $request->request->has('count')) {
  118.             $em $this->getDoctrine()->getManager();
  119.             $count $request->request->getInt('count');
  120.             if ($count 1) {
  121.                 $em->remove($cart);
  122.             } else {
  123.                 $cart->setCount($count);
  124.                 $em->persist($cart);
  125.             }
  126.             $em->flush();
  127.         }
  128.         $cart $repository->getByUser($user);
  129.         return $this->statusOk(
  130.             null,
  131.             null,
  132.             [
  133.                 'items' => $cart,
  134.             ]
  135.         );
  136.     }
  137.     /**
  138.      * @Route(path="/api/booking", methods={"POST"})
  139.      */
  140.     public function addBooking(
  141.         Request $request,
  142.         ContainerInterface $container,
  143.         SubServiceRepository $subServiceRepository,
  144.         EntityManagerInterface $em,
  145.         Fondy $fondy,
  146.         Mercure $mercure
  147.     )
  148.     {
  149.         /** @var User $user */
  150.         $user $this->getUser();
  151.         $errors = [];
  152.         $data $request->request->all();
  153.         $form $this->createForm(BookingType::class);
  154.         $form->submit($data);
  155.         if ($form->isSubmitted() && $form->isValid())
  156.         {
  157.             $subService $subServiceRepository->findOneBy(['id' => $form->getData()['sub_service']]);
  158.             $bookDate = \DateTime::createFromFormat('Y-m-d*H:i:s'$form->getData()['book_date']);
  159.             $this->guestClient = new TngGuestClient($container->getParameter('tng_api_key'));
  160.             $this->staffClient = new TngStaffClient($container->getParameter('tng_api_key'));
  161.             $this->staffClient->login($container->getParameter('tng_staff_login'), $container->getParameter('tng_staff_password'));
  162.             if($subService->getTngId() > && $userSession $this->staffClient->getUserSessionByEmail($user->getEmail()))
  163.             {
  164.                 $this->guestClient->setUserSession($userSession);
  165.                 // try to book
  166.                 $bookData = [
  167.                     'outlet_id' => $subService->getOutletId(),
  168.                     'offer_id' => $subService->getTngId(),
  169.                     'profile_id' => $user->getTngId(),
  170.                     'comment' => "created by domosfera api",
  171.                     'from' => $bookDate->format('d.m.Y H:i'),
  172.                 ];
  173.                 if($bookId $this->guestClient->createBooking($bookData))
  174.                 {
  175.                     // make cart
  176.                     $total $subService->getPrice();
  177.                     $custom = new Custom();
  178.                     $custom->setUser($user);
  179.                     $customCart = new CustomCart();
  180.                     $customCart
  181.                         ->setCount(1)
  182.                         ->setSubService($subService)
  183.                         ->setCustom($custom);
  184.                     $em->persist($customCart);
  185.                     $custom->setCost($total);
  186.                     $em->persist($custom);
  187.                     $em->flush();
  188.                     // pay
  189.                     $result $fondy->initiatePayment(ceil($total 100), $user->getRecToken(), 'Services_Payment_'.$custom->getId());
  190.                     $custom->setOrderId($result['order_id'] ?? '')
  191.                         ->setStatus($result['order_status'] ?? '')
  192.                         ->setPaymentId($result['payment_id'] ?? '');
  193.                     $em->persist($custom);
  194.                     $em->flush();
  195.                     //$mercure->sendMessageAboutCustom($custom);
  196.                     // make booking
  197.                     if($result['order_id'])
  198.                     {
  199.                         $tenderId $this->getTngTenderId($user->getCardType());
  200.                         $offers $payments = [];
  201.                         $customCart->setTngId($bookId);
  202.                         $em->persist($customCart);
  203.                         $em->flush();
  204.                         $offers[] = [
  205.                             'bookingId' => $bookId,
  206.                         ];
  207.                         $payments[] = [
  208.                             'tenderId' => $tenderId,
  209.                             'amount' => $customCart->getSubService()->getPrice() * $customCart->getCount(),
  210.                         ];
  211.                         if($billId $this->guestClient->makeBill($custom->getUser()->getTngId(), $customCart->getSubService()->getOutletId(), $offers$payments))
  212.                         {
  213.                             $customCart->setBillId($billId->id);
  214.                             $em->persist($customCart);
  215.                             $em->flush();
  216.                             $custom->setStatus('payed');
  217.                             $em->persist($custom);
  218.                             $em->flush();
  219.                         }
  220.                     }
  221.                     $booking = new Booking();
  222.                     $booking->setTngId($bookId);
  223.                     $booking->setCustomCart($customCart);
  224.                     $booking->setBookDate($bookDate);
  225.                     $em->persist($booking);
  226.                     $em->flush();
  227.                     return $this->statusOk(nullnull$booking);
  228.                 }
  229.             }
  230.         }
  231.         else
  232.         {
  233.             $errors FormHelper::getErrors2($form);
  234.         }
  235.         return $this->statusConflict($errorsResponseCode::VALIDATION_FAIL);
  236.     }
  237.     /**
  238.      * @Route(path="/api/booking", methods={"GET"})
  239.      */
  240.     public function getBookings(
  241.         Request $request,
  242.         BookingRepository $bookingRepository
  243.     )
  244.     {
  245.         /** @var User $user */
  246.         $user $this->getUser();
  247.         $bookings $bookingRepository->getByUser($user);
  248.         return $this->statusOk(
  249.             null,
  250.             null,
  251.             [
  252.                 'items' => $bookings,
  253.             ]
  254.         );
  255.     }
  256.     /**
  257.      * @Route(path="/api/booking/cancel/{booking_id}", methods={"GET"})
  258.      */
  259.     public function cancelBooking(
  260.         Request $request,
  261.         BookingRepository $bookingRepository,
  262.         ContainerInterface $container,
  263.         EntityManagerInterface $em,
  264.         $booking_id
  265.     )
  266.     {
  267.         /** @var User $user */
  268.         $user $this->getUser();
  269.         $booking $bookingRepository->findOneBy(['id' => $booking_id]);
  270.         if($booking && $booking->getCustomCart()->getCustom()->getUser()->getId() == $user->getId())
  271.         {
  272.             $this->guestClient = new TngGuestClient($container->getParameter('tng_api_key'));
  273.             $this->staffClient = new TngStaffClient($container->getParameter('tng_api_key'));
  274.             $this->staffClient->login($container->getParameter('tng_staff_login'), $container->getParameter('tng_staff_password'));
  275.             if($userSession $this->staffClient->getUserSessionByEmail($user->getEmail()))
  276.             {
  277.                 $this->guestClient->setUserSession($userSession);
  278.                 if($this->guestClient->cancelBooking($booking->getTngId()))
  279.                 {
  280.                     $booking->setIsCanceled(1);
  281.                     $em->persist($booking);
  282.                     $em->flush();
  283.                     return $this->statusOk(nullnull$booking);
  284.                 }
  285.             }
  286.         }
  287.         return $this->statusConflict([], ResponseCode::VALIDATION_FAIL);
  288.     }
  289.     /**
  290.      * @Route(path="/api/cart", methods={"POST"})
  291.      */
  292.     public function initiatePayment(
  293.         Request $request,
  294.         EntityManagerInterface $em,
  295.         TranslatorInterface $translator,
  296.         CartRepository $repository,
  297.         Fondy $fondy,
  298.         Mercure $mercure
  299.     )
  300.     {
  301.         $ids $request->get('cart_id', []);
  302.         if(!$ids || !count($ids))
  303.             return $this->statusConflict($translator->trans('cart_empty'), ResponseCode::CART_EMPTY);
  304.         if(!is_array($ids))
  305.             $ids = [$ids];
  306.         /** @var User $user */
  307.         $user $this->getUser();
  308.         $cart = [];
  309.         foreach($ids as $id)
  310.             if($carttmp $repository->getByUserAndId($user$id))
  311.             $cart[] = $carttmp;
  312.         if (!count($cart)) {
  313.             return $this->statusConflict($translator->trans('cart_empty'), ResponseCode::CART_EMPTY);
  314.         }
  315.         $total 0;
  316.         $custom = new Custom();
  317.         $custom->setUser($user);
  318.         foreach ($cart as $item) {
  319.             $subService $item->getSubService();
  320.             $total += $subService->getPrice() * $item->getCount();
  321.             $customCart = new CustomCart();
  322.             $customCart
  323.                 ->setCount($item->getCount())
  324.                 ->setSubService($subService)
  325.                 ->setCustom($custom);
  326.             $em->remove($item);
  327.             $em->persist($customCart);
  328.         }
  329.         $custom->setCost($total);
  330.         $em->persist($custom);
  331.         $em->flush();
  332.         $result $fondy->initiatePayment(ceil($total 100), $user->getRecToken(), 'Services_Payment_'.$custom->getId());
  333.         $custom->setOrderId($result['order_id'] ?? '')
  334.             ->setStatus($result['order_status'] ?? '')
  335.             ->setPaymentId($result['payment_id'] ?? '');
  336.         $em->persist($custom);
  337.         $em->flush();
  338.         $mercure->sendMessageAboutCustom($custom);
  339.         return $this->statusOk(
  340.             null,
  341.             null,
  342.             [
  343.                 'items' => [],
  344.             ]
  345.         );
  346.     }
  347.     private function getTngTenderId($key)
  348.     {
  349.         $key strtolower($key);
  350.         $data = [
  351.             'cash' => '1',
  352.             'room charge' => '2',
  353.             'visa' => '3',
  354.             'mastercard' => '4',
  355.             'master card' => '4',
  356.             'american express' => '5',
  357.             'americanexpress' => '5',
  358.             'dinners club' => '6',
  359.             'jcb' => '7',
  360.             'voucher' => '8',
  361.             'deposit' => '9',
  362.         ];
  363.         return isset($data[$key]) ? $data[$key] : 1;
  364.     }
  365. }