src/Controller/BasketController.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Basket;
  4. use App\Entity\Basketitem;
  5. use App\Entity\Chilidocument;
  6. use App\Entity\Delivery;
  7. use App\Entity\Discountcode;
  8. use App\Service\LogService;
  9. use Detection\MobileDetect;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\HttpFoundation\Session\Session;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Csrf\CsrfTokenManager;
  17. class BasketController extends AbstractController
  18. {
  19.     private $csrfToken;
  20.     public function __construct() {
  21.         $csrfToken = new CsrfTokenManager();
  22.         $this->csrfToken $csrfToken->getToken('access');
  23.     }
  24.     public function getCurrentBasket() {
  25.         $basketcookie getBasketCookie();
  26.         $em $this->getDoctrine()->getManager();
  27.         if ($this->getUser()) {
  28.             $basket $em->getRepository(Basket::class)->findBy(['user' => $this->getUser()->getId(), 'is_order' => false]);
  29.         } else {
  30.             $basket $em->getRepository(Basket::class)->findBy(['csrftoken' => $basketcookie'is_order' => false]);
  31.         }
  32.         if ($basket) {
  33.             $basket $basket[0];
  34.         } else {
  35.             $basket = new Basket();
  36.         }
  37.         // Check for duplicates and clean up
  38.         // Make sure basket items is attached to correct basket
  39.         return $basket;
  40.     }
  41.     public function getNumberOfCurrentBasketItems() {
  42.         $number_of_basketitems 0;
  43.         $basket $this->getCurrentBasket();
  44.         if ($basket != null) {
  45.             if ($basket->getId() != null) {
  46.                 $number_of_basketitems $basket->getBasketitems()->count();
  47.             }
  48.         }
  49.         return new JsonResponse(array('num' => $number_of_basketitems));
  50.     }
  51.     private function getChilidocumentDefaultAmount($id) {
  52.         $product $this->getDoctrine()->getRepository(Chilidocument::class)->find($id);
  53.         $product_price $product->getPrice();
  54.         while ($product_price === null) {
  55.             $product $this->getDoctrine()->getRepository(Chilidocument::class)->findOneBy(['path' => $product->getMother()]);
  56.             $product_price $product->getPrice();
  57.         }
  58.         return $product_price->getDefaultAmount();
  59.     }
  60.     private function getChilidocumentPrice($id,$amount) {
  61.         $product $this->getDoctrine()->getRepository(Chilidocument::class)->find($id);
  62.         $product_price $product->getPrice();
  63.         while ($product_price === null) {
  64.             $product $this->getDoctrine()->getRepository(Chilidocument::class)->findOneBy(['path' => $product->getMother()]);
  65.             $product_price $product->getPrice();
  66.         }
  67.         switch ($product_price->getType()) {
  68.             case 'levels':
  69.                 $price_amount $product_price->getPriceAmount();
  70.                 $price_amount json_decode($price_amount,1);
  71.                 $price 0;
  72.                 foreach ($price_amount as $qty => $prc) {
  73.                     if ($amount >= $qty) {
  74.                         $price $prc;
  75.                     }
  76.                 }
  77.                 break;
  78.             case 'arbitrary':
  79.                 $price_amount $product_price->getPriceAmount();
  80.                 $price_amount json_decode($price_amount,1);
  81.                 $price 0;
  82.                 foreach ($price_amount as $qty => $prc) {
  83.                     if ($amount >= $qty) {
  84.                         $price $prc;
  85.                     }
  86.                 }
  87.                 break;
  88.         }
  89.         return $price;
  90.     }
  91.     private function getBasketWeight($basket) {
  92.         $w 0;
  93.         foreach($basket->getBasketitems() as $bi) {
  94.             $w = ($w + ($bi->getAmount() * $bi->getChilidocument()->getWeight()));
  95.         }
  96.         return $w;
  97.     }
  98.     private function clarifyDelivery($basket) {
  99.         $em $this->getDoctrine()->getManager();
  100.         $conn $em->getConnection();
  101.         $totalWeight $this->getBasketWeight($basket);
  102.         $sql 'select * from delivery where weightlimit = 0 or weightlimit > ' $totalWeight ' order by is_default desc,sortorder asc';
  103.         $sta $conn->prepare($sql);
  104. //        dd($sta);
  105.         //        $sta = $em->getConnection()->prepare($sql);
  106. //        $sta->execute();
  107.         $execute $sta->executeQuery();
  108.         $deliveries $execute->fetchAllAssociative();
  109. #        dd($deliveries);
  110.         if ($basket->getDelivery() == null) {
  111.             $default_delivery $em->getRepository(Delivery::class)->findOneBy(['id' => $deliveries[0]['id']]);
  112.             $basket->setDelivery($default_delivery);
  113.             $em->persist($basket);
  114.             $em->flush();
  115.         }
  116.         return $deliveries;
  117.     }
  118.     /**
  119.      * @Route("/Handlekurv", name="Handlekurv")
  120.      */
  121.     public function Handlekurv(Session $sessionLogService $log): Response
  122.     {
  123.         $log->addLog('info','Open basket');
  124.         $browser_width $session->get('browserwidth');
  125.         #dd($browser_width);
  126.         if ($browser_width == null) {
  127.             return $this->redirectToRoute('setbrowserwidth_page');
  128.         }
  129.         $basketcookie getBasketCookie();
  130.         $basket $this->getCurrentBasket();
  131.         $delivery $this->clarifyDelivery($basket);
  132.         return $this->render('theme_' config_theme '/basket.html.twig', [
  133.             'basketcookie' => $basketcookie,
  134.             'basket' => $basket,
  135.             'width' => $browser_width,
  136.             'stripe_pk' => config_stripe_Publishable_key,
  137.             'delivery' => $delivery,
  138.         ]);
  139.     }
  140.     /**
  141.      * @Route("/saveChilidocumentToBasket", name="saveChilidocumentToBasket")
  142.      */
  143.     public function saveChilidocumentToBasket(): Response
  144.     {
  145.         $em $this->getDoctrine()->getManager();
  146.         $post $_REQUEST;
  147.         #pre($post,1);
  148.         $doc_id $post['chilidocument_id'];
  149.         $basket $this->getCurrentBasket();
  150.         if ($basket->getId() == null) {
  151.             if ($this->getUser()) $basket->setUser($this->getUser());
  152.             $basket->setCsrftoken(getBasketCookie());
  153.             $basket->setIsOrder(false);
  154.             $em->persist($basket);
  155.             $em->flush();
  156.         }
  157.         $chilidocument $em->getRepository(Chilidocument::class)->find($doc_id);
  158.         $default_amount $this->getChilidocumentDefaultAmount($doc_id);
  159.         $price $this->getChilidocumentPrice($doc_id,$default_amount);
  160.         $basket_item $em->getRepository(Basketitem::class)->findBy(['basket' => $basket,'chilidocument' => $chilidocument]);
  161.         if (!$basket_item) {
  162.             $new_basketitem = new Basketitem();
  163.             $new_basketitem->setBasket($basket);
  164.             $new_basketitem->setIsChili(true);
  165.             $new_basketitem->setIsPhysical(false);
  166.             $new_basketitem->setChilidocument($chilidocument);
  167.             $new_basketitem->setChiliXml($post['chili_xml']);
  168.             $new_basketitem->setAmount($default_amount);
  169.             $new_basketitem->setPrice($price);
  170.             $em->persist($new_basketitem);
  171.             $em->flush();
  172.             $save_type 'Create';
  173.         } else {
  174.             $basket_item $basket_item[0];
  175.             $basket_item->setChiliXml($post['chili_xml']);
  176.             $em->persist($basket_item);
  177.             $em->flush();
  178.             $save_type 'Update';
  179.         }
  180.         return new JsonResponse(array('status' => 'success''save_type' => $save_type));
  181.     }
  182.     /**
  183.      * @Route("/deletebasketitem/{id}", name="deletebasketitem")
  184.      */
  185.     public function deletebasketitem($id): Response
  186.     {
  187.         $em $this->getDoctrine()->getManager();
  188.         $basketitem $em->getRepository(Basketitem::class)->find($id);
  189.         $the_basket $basketitem->getBasket();
  190.         $em->remove($basketitem);
  191.         $em->flush();
  192.         if (count($the_basket->getBasketitems()) == 0) {
  193.             $em->remove($the_basket);
  194.             $em->flush();
  195.         }
  196.         return $this->redirectToRoute('Handlekurv');
  197.     }
  198.     /**
  199.      * @Route("/emptybasket", name="emptybasket")
  200.      */
  201.     public function emptybasket(): Response
  202.     {
  203.         $basket $this->getCurrentBasket();
  204.         $em $this->getDoctrine()->getManager();
  205.         foreach ($basket->getBasketitems() as $basketitem) {
  206.             $em->remove($basketitem);
  207.             $em->flush();
  208.         }
  209.         $em->remove($basket);
  210.         $em->flush();
  211.         return $this->redirectToRoute('Handlekurv');
  212.     }
  213.     /**
  214.      * @Route("/orderbasket", name="orderbasket")
  215.      */
  216.     public function orderbasket(): Response
  217.     {
  218.         $now date('Y-m-d H:i:s');
  219.         $em $this->getDoctrine()->getManager();
  220.         $basket $this->getCurrentBasket();
  221.         $basket->setCsrftoken('');
  222.         $basket->setIsOrder(true);
  223.         $basket->setOrdertime(new \Datetime($now));
  224.         $em->persist($basket);
  225.         $em->flush();
  226.         return $this->redirectToRoute('Handlekurv');
  227.     }
  228.     /**
  229.      * @Route("/updateBasketAfterAmountChange",name="updateBasketAfterAmountChange")
  230.      */
  231.     public function updateBasketAfterAmountChange(): Response
  232.     {
  233.         $p $_POST;
  234.         #pre($p,1);
  235.         $em $this->getDoctrine()->getManager();
  236.         foreach ($p['amount_selector'] as $basketitem => $amount) {
  237.             $basketitem $em->getRepository(Basketitem::class)->find($basketitem);
  238.             $price $this->getChilidocumentPrice($basketitem->getChilidocument()->getId(),$amount);
  239.             $basketitem->setAmount($amount);
  240.             $basketitem->setPrice($price);
  241.             $em->persist($basketitem);
  242.             $em->flush();
  243.         }
  244.         return new JsonResponse(array('status' => 'success'));
  245.     }
  246.     /**
  247.      * @Route("/getProductPricing/{producttype}/{productid}/{amount}/{basketrowid}", name="getProductPricing")
  248.      */
  249.     public function getProductPricing($producttype,$productid,$amount,$basketrowid): Response
  250.     {
  251.         switch ($producttype) {
  252.             case 'chili':
  253.                 $product $this->getDoctrine()->getRepository(Chilidocument::class)->find($productid);
  254.                 $product_price $product->getPrice();
  255.                 #dd($product_price);
  256.                 while ($product_price === null) {
  257.                     $product $this->getDoctrine()->getRepository(Chilidocument::class)->findOneBy(['path' => $product->getMother()]);
  258.                     $product_price $product->getPrice();
  259.                 }
  260.                 break;
  261.         }
  262.         $pricetype $product_price->getType();
  263.         switch ($pricetype) {
  264.             case 'levels':
  265.                 $output $this->render('theme_' config_theme '/product_pricing_levels.html.twig', [
  266.                     'id' => $productid,
  267.                     'basketrowid' => $basketrowid,
  268.                     'price_amount' => json_decode($product_price->getPriceAmount(),1),
  269.                     'minimum' => $product_price->getMinimum(),
  270.                     'maximum' => $product_price->getMaximum(),
  271.                     'step' => $product_price->getStep(),
  272.                     'default_amount' => $product_price->getDefaultAmount(),
  273.                     'amount' => $amount
  274.                 ]);
  275.                 break;
  276.             case 'arbitrary':
  277.                 $output $this->render('theme_' config_theme '/product_pricing_arbitrary.html.twig', [
  278.                     'id' => $productid,
  279.                     'basketrowid' => $basketrowid,
  280.                     'price_amount' => json_decode($product_price->getPriceAmount(),1),
  281.                     'minimum' => $product_price->getMinimum(),
  282.                     'maximum' => $product_price->getMaximum(),
  283.                     'step' => $product_price->getStep(),
  284.                     'default_amount' => $product_price->getDefaultAmount(),
  285.                     'amount' => $amount
  286.                 ]);
  287.                 break;
  288.         }
  289.         return $output;
  290.     }
  291.     /**
  292.      * @Route("/activatediscountcode/{code}", name="activatediscountcode")
  293.      */
  294.     public function activatediscountcode($code): Response
  295.     {
  296.         $em $this->getDoctrine()->getManager();
  297.         $current_basket $this->getCurrentBasket();
  298.         if ($code == 'NULL') {
  299.             $current_basket->setDiscountcode(NULL);
  300.         } else {
  301.             $now date('Y-m-d H:i:s');
  302.             $conn $em->getConnection();
  303.             $sql 'select id from discountcode where code = "' $code '" and (user_id = ' $this->getUser()->getId() . ' or user_id is null) and (valid_from <= "' $now '" or valid_from is null) and (valid_to >= "' $now '" or valid_to is null)';
  304.             $sta $conn->prepare($sql);
  305.             $execute $sta->executeQuery();
  306.             $discount_code_id $execute->fetchAllAssociative();
  307.             if (!$discount_code_id) {
  308.                 return new JsonResponse(array('status' => 'error'));
  309.             }
  310.             $discount_code_id $discount_code_id[0]['id'];
  311.             $discount_code $em->getRepository(Discountcode::class)->find($discount_code_id);
  312.             $current_basket->setDiscountcode($discount_code);
  313.         }
  314.         $em->persist($current_basket);
  315.         $em->flush();
  316.         return new JsonResponse(array('status' => 'success'));
  317.     }
  318.     /**
  319.      * @Route("/betalmed/{type}", name="betalmedpage")
  320.      */
  321.     public function betalmed($type): Response
  322.     {
  323.         switch ($type) {
  324.             case 'vipps':
  325.                 return $this->redirectToRoute('vipps_pay', [
  326.                     'basket_token' => $this->getCurrentBasket()->getCsrftoken(),
  327.                 ]);
  328.                 break;
  329.             case 'klarna':
  330.                 return $this->redirectToRoute('klarnapay', [
  331.                     'basket_token' => $this->getCurrentBasket()->getCsrftoken(),
  332.                 ]);
  333.                 break;
  334.             case 'stripe':
  335.                 return $this->redirectToRoute('stripepay', [
  336.                     'basket_token' => $this->getCurrentBasket()->getCsrftoken(),
  337.                 ]);
  338.                 break;
  339.             case 'easy':
  340.                 return $this->redirectToRoute('easycheckout', [
  341.                     'basket_token' => $this->getCurrentBasket()->getCsrftoken(),
  342.                 ]);
  343.                 break;
  344.         }
  345.         dd($type);
  346.     }
  347.     /**
  348.      * @Route("/updateBasketAfterDelivery",name="updateBasketAfterDelivery")
  349.      */
  350.     public function updateBasketAfterDelivery(Request $request): Response
  351.     {
  352.         if ($request->getMethod() == 'POST') {
  353.             $p $_POST;
  354.             #pre($p,1);
  355.             $basket $this->getDoctrine()->getRepository(Basket::class)->find($p['basket']);
  356.             $delivery $this->getDoctrine()->getRepository(Delivery::class)->find($p['delivery']);
  357.             $basket->setDelivery($delivery);
  358.             $this->getDoctrine()->getManager()->persist($basket);
  359.             $this->getDoctrine()->getManager()->flush();
  360.             return new JsonResponse(array('status' => 'success'));
  361.         } else {
  362.             return new JsonResponse(array('status' => 'error''message' => 'No POST!'));
  363.         }
  364.     }
  365.     /**
  366.      * @Route("/savebasketmessage",name="savebasketmessage")
  367.      */
  368.     public function savebasketmessage(): Response
  369.     {
  370.         $p $_POST;
  371.         $basket $this->getCurrentBasket();
  372.         $em $this->getDoctrine()->getManager();
  373.         $basket->setMessage($p['message']);
  374.         $em->persist($basket);
  375.         $em->flush();
  376.         return new JsonResponse(array('status' => 'success'));
  377.     }
  378. }