src/Application/Controller/CartController.php line 25

Open in your IDE?
  1. <?php
  2. namespace App\Application\Controller;
  3. use App\Admin\Document\Counterparty;
  4. use App\Admin\Document\Draft;
  5. use App\Admin\Document\Embedded\DraftItem;
  6. use App\Admin\Document\Product;
  7. use App\Admin\Document\PromoCode;
  8. use App\Admin\Document\Supplier;
  9. use App\Application\Cart\Cart;
  10. use AvenueAdminBundle\Util\DateUtil;
  11. use AvenueAdminBundle\Util\NumberUtil;
  12. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  13. use Symfony\Component\HttpFoundation\JsonResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use \Symfony\Component\Routing\Annotation\Route;
  17. class CartController extends AbstractController
  18. {
  19.     /**
  20.      * @Route("/cart", name="cart")
  21.      */
  22.     public function index(Request $requestCart $cart): Response
  23.     {
  24.         return $this->render(
  25.             'application/cart/index.html.twig'$this->getCartParams($cart)
  26.         );
  27.     }
  28.     private function getCartParams(Cart $cart) {
  29.         $relatedProducts = [];
  30.         foreach ($cart->getItems() as $cartItem) {
  31.             foreach ($cartItem->product->getActiveProducts() as $product) {
  32.                 if (!$cart->has($product->getId())) {
  33.                     $relatedProducts[$product->getId()] = $product;
  34.                 }
  35.             }
  36.         }
  37.         return ['relatedProducts' => array_values($relatedProducts)];
  38.     }
  39.     /**
  40.      * @Route("/cart-add-ajax", name="cart-add-ajax")
  41.      * @param Request $request
  42.      * @return \Symfony\Component\HttpFoundation\Response
  43.      */
  44.     public function add(Request $requestCart $cart)
  45.     {
  46.         $id $request->get('id');
  47.         $this->checkProduct($id);
  48.         $count $cart->add($id$request->get('count'));
  49.         return new JsonResponse([
  50.             'cartHtml' => $this->renderView('application/partial/cart.html.twig'),
  51.             'count' => $count
  52.         ]);
  53.     }
  54.     /**
  55.      * @Route("/compare-ajax", name="compare-ajax")
  56.      */
  57.     public function compareAjax(Request $requestCart $cart)
  58.     {
  59.         $id $request->get('id');
  60.         $this->checkProduct($id);
  61.         $cart->addInCompareList($id);
  62.         return new JsonResponse(
  63.             [
  64.                 'html' => $this->renderView('application/partial/compare.html.twig'),
  65.             ]
  66.         );
  67.     }
  68.     private function checkProduct($id) {
  69.         /**
  70.          * @var Product $product
  71.          */
  72.         $product $this->getDocumentRepository(Product::class)->find($id);
  73.         if (!$product || !$product->getActive()) {
  74.             throw $this->createNotFoundException("Product with id {$id} does not exist or not active");
  75.         }
  76.     }
  77.     /**
  78.      * @Route("/cart-put-ajax", name="cart-put-ajax")
  79.      * @param Request $request
  80.      * @return \Symfony\Component\HttpFoundation\Response
  81.      */
  82.     public function put(Request $requestCart $cart)
  83.     {
  84.         $cart->put($request->get('id'), $request->get('count'));
  85.         return new JsonResponse([
  86.             'cartHtml' => $this->renderView('application/partial/cart.html.twig'),
  87.             'itemsHtml' => $this->renderView('application/cart/items.html.twig'$this->getCartParams($cart)),
  88.         ]);
  89.     }
  90.     /**
  91.      * @Route("/cart-delete-ajax", name="cart-delete-ajax")
  92.      * @param Request $request
  93.      * @return \Symfony\Component\HttpFoundation\Response
  94.      */
  95.     public function delete(Request $requestCart $cart)
  96.     {
  97.         $cart->remove($request->get('id'));
  98.         return new JsonResponse([
  99.             'cartHtml' => $this->renderView('application/partial/cart.html.twig'),
  100.             'itemsHtml' => $this->renderView('application/cart/items.html.twig'$this->getCartParams($cart)),
  101.         ]);
  102.     }
  103.     /**
  104.      * @Route("/cart-clear-ajax", name="cart-clear-ajax")
  105.      * @param Request $request
  106.      * @return \Symfony\Component\HttpFoundation\Response
  107.      */
  108.     public function clear(Request $requestCart $cart)
  109.     {
  110.         $cart->clear();
  111.         return new JsonResponse([
  112.             'cartHtml' => $this->renderView('application/partial/cart.html.twig'),
  113.             'itemsHtml' => $this->renderView('application/cart/items.html.twig'),
  114.         ]);
  115.     }
  116.     /**
  117.      * @Route("/cart-load-retail-ajax", name="cart-load-retail-ajax")
  118.      * @param Request $request
  119.      * @return \Symfony\Component\HttpFoundation\Response
  120.      */
  121.     public function loadRetail(Request $requestCart $cart)
  122.     {
  123.         $user $this->getLoggedInUser();
  124.         if ($user) {
  125.             $cart->loadRetail($user);
  126.         }
  127.         return new JsonResponse([
  128.             'cartHtml' => $this->renderView('application/partial/cart.html.twig'),
  129.             'itemsHtml' => $this->renderView('application/cart/items.html.twig'$this->getCartParams($cart)),
  130.         ]);
  131.     }
  132.     /**
  133.      * @Route("/draft-save-ajax", name="draft-save-ajax")
  134.      * @param Request $request
  135.      * @return \Symfony\Component\HttpFoundation\Response
  136.      */
  137.     public function draftSave(Request $requestCart $cart)
  138.     {
  139.         $user $this->getLoggedInUser();
  140.         $draft = new Draft();
  141.         $this->getDocumentManager()->persist($draft);
  142.         $draft->setUserAccount($user);
  143.         $draft->setCounterparty($cart->getCounterparty());
  144.         $items = [];
  145.         foreach ($cart->getItems() as $cartItem) {
  146.             $item = new DraftItem();
  147.             $item->setProduct($cartItem->product);
  148.             $item->setQuantity($cartItem->quantity);
  149.             $item->setCounterparty($draft->getCounterparty());
  150.             $items[] = $item;
  151.         }
  152.         $draft->setItems($items);
  153.         $this->getDocumentManager()->flush();
  154.         return new JsonResponse();
  155.     }
  156.     /**
  157.      * @Route("/cart-set-counterparty-ajax", name="cart-set-counterparty-ajax")
  158.      * @param Request $request
  159.      * @return \Symfony\Component\HttpFoundation\Response
  160.      */
  161.     public function setCounterpartyAjax(Request $requestCart $cart)
  162.     {
  163.         $user $this->getLoggedInUser();
  164.         if ($user) {
  165.             $id $request->get('id');
  166.             if ($id) {
  167.                 $counterparty $this->getDocumentManager()->getRepository(Counterparty::class)->findOneBy([
  168.                     '_id' => $id,
  169.                     'client' => $user->getClient()->getId()
  170.                 ]);
  171.                 if (!$counterparty) {
  172.                     throw new \Exception('no Counterparty ' $id ' for client ' $user->getClient()->getId());
  173.                 }
  174.             } else {
  175.                 $counterparty null;
  176.             }
  177.             $user->setCartItemsByCounterparty($cart->getCounterpartyId(), $cart->getSessionItems());
  178.             $this->getDocumentManager()->flush();
  179.             $cart->setCounterparty($counterparty$user->getCartItemsByCounterparty($id));
  180.         }
  181.         return new JsonResponse();
  182.     }
  183.     /**
  184.      * @Route("/clear-promo-ajax", name="clear-promo-ajax")
  185.      * @param Request $request
  186.      * @return \Symfony\Component\HttpFoundation\Response
  187.      */
  188.     public function clearPromo(Request $requestCart $cart)
  189.     {
  190.         $cart->clearPromoCode();
  191.         return new JsonResponse();
  192.     }
  193.     /**
  194.      * @Route("/apply-promo-ajax", name="apply-promo-ajax")
  195.      * @param Request $request
  196.      * @return \Symfony\Component\HttpFoundation\Response
  197.      */
  198.     public function applyPromoAjax(Request $requestCart $cart)
  199.     {
  200.         $success false;
  201.         $code trim($request->get('promo'));
  202.         if ($code && $request->isMethod(Request::METHOD_POST)) {
  203.             $code mb_ereg_replace('[^\d]'''$code);
  204.             if ($code) {
  205.                 if (strlen($code) == 11 && substr($code01) == '7') {
  206.                     $code '8' substr($code1);
  207.                 }
  208.                 /**
  209.                  * @var PromoCode $promoCode
  210.                  */
  211.                 $promoCode $this->getDocumentRepository(PromoCode::class)->findOneBy(['code' => $code]);
  212.                 if ($promoCode) {
  213.                     if ($cart->setPromoCode($promoCode)) {
  214.                         $success true;
  215.                     }
  216.                 }
  217.             }
  218.         }
  219.         return new JsonResponse(['success' => $success]);
  220.     }
  221.     /**
  222.      * @Route("/cart/proposal", name="cart-proposal")
  223.      */
  224.     public function proposal(Request $requestCart $cart) {
  225.         if (!$this->getLoggedInUser()) {
  226.             return $this->redirectToRoute('login');
  227.         }
  228.         $type $request->get('type');
  229.         $html $this->renderView(
  230.             'application/pdf/order.html.twig', [
  231.                 'supplier' => $this->getDocumentRepository(Supplier::class)->findOneBy(['internalCode' => $type]),
  232.                 'user' => $this->getLoggedInUser(),
  233.                 'date' => new \DateTime(),
  234.             ]
  235.         );
  236.         $this->printPdf('Заказ'$html);
  237.     }
  238.     /**
  239.      * @Route("/cart/proposal-excel", name="cart-proposal-excel")
  240.      */
  241.     public function proposalExcel(Request $requestCart $cart) {
  242.         $user $this->getLoggedInUser();
  243.         if (!$user) {
  244.             return $this->redirectToRoute('login');
  245.         }
  246.         /**
  247.          * @var Supplier $supplier
  248.          */
  249.         $supplier $this->getDocumentRepository(Supplier::class)->findOneBy(['internalCode' => $type]);
  250.         $filePath tempnam(sys_get_temp_dir(), 'AvenueAdminExport');
  251.         $reader = new Xlsx();
  252.         $spreadsheet $reader->load(__DIR__ '/../../../excel/invoice.xlsx');
  253.         $sheet $spreadsheet->getActiveSheet();
  254.         $sheet->getCell('A1')->setValue('Заказ клиента от ' DateUtil::ruDate(new \DateTime(), 'j F Y') . ' г.');
  255.         $a = [$supplier->getName()];
  256.         if ($supplier->getInn()) {
  257.             $a[] = 'ИНН ' $supplier->getInn();
  258.         }
  259.         if ($supplier->getAddress()) {
  260.             $a[] = $supplier->getAddress();
  261.         }
  262.         $sheet->getCell('C2')->setValue(implode(', '$a));
  263.         $a = [$user->getFullName()];
  264.         if ($user->getPhone()) {
  265.             $a[] = $user->getPhone();
  266.         }
  267.         $sheet->getCell('C3')->setValue(implode(', '$a));
  268.         $sheet->getCell('G6')->setValue($cart->getAmount());
  269.         $sheet->getCell('H6')->setValue($cart->getDiscountAmount());
  270.         $sheet->getCell('I6')->setValue($cart->getAmountWithDiscount());
  271.         $items $cart->getItems();
  272.         $sheet->getCell('B8')->setValue('Всего наименований ' count($items)
  273.             . ', на сумму ' number_format($cart->getAmountWithDiscount(), 2','' ')
  274.             . ' руб.');
  275.         $sheet->getCell('B9')->setValue(NumberUtil::formatMoneyToWords($cart->getAmountWithDiscount()));
  276.         if ($cart->getVat()) {
  277.             $sheet->insertNewRowBefore(71);
  278.             $sheet->mergeCellsByColumnAndRow(1767);
  279.             $sheet->getCell('A7')->setValue('В т.ч. НДС (' $cart->getVat() . '%):');
  280.             $sheet->getCell('I7')->setValue($cart->getVatAmount());
  281.             $sheet->getCell('A8')->setValue('Итого с НДС:');
  282.             $sheet->getCell('I8')->setValue($cart->getAmountWithDiscount());
  283.         } else {
  284.             $sheet->getCell('A7')->setValue('Без налога (НДС)');
  285.             $sheet->getCell('I7')->setValue('-');
  286.         }
  287.         $firstRow 5;
  288.         $rowIndex $firstRow;
  289.         if (count($items) > 1) {
  290.             $sheet->insertNewRowBefore($rowIndex 1count($items) - 1);
  291.         }
  292.         for ($i 0$i count($items); $i++) {
  293.             $item $items[$i];
  294.             $sheet->getCell('A' $rowIndex)->setValue($i 1);
  295.             $sheet->getCell('B' $rowIndex)->setValue($item->product->getSku());
  296.             $sheet->getCell('C' $rowIndex)->setValue($item->product->getName());
  297.             $sheet->getCell('D' $rowIndex)->setValue($item->quantity);
  298.             $sheet->getCell('E' $rowIndex)->setValue('шт.');
  299.             $sheet->getCell('F' $rowIndex)->setValue($item->getPrice());
  300.             $sheet->getCell('G' $rowIndex)->setValue($item->getAmount());
  301.             $sheet->getCell('H' $rowIndex)->setValue($item->getDiscountAmount());
  302.             $sheet->getCell('I' $rowIndex)->setValue($item->getAmountWithDiscount());
  303.             $rowIndex++;
  304.         }
  305.         $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
  306.         $writer->save($filePath);
  307.         $fileName 'Заказ';
  308.         header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8');
  309.         header('Content-Disposition: attachment; filename="' $fileName '.xlsx"');
  310.         echo file_get_contents($filePath);
  311.         unlink($filePath);
  312.         exit;
  313.     }
  314. }