app/Customize/Controller/ProductController.php line 247

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of EC-CUBE
  4.  *
  5.  * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
  6.  *
  7.  * http://www.ec-cube.co.jp/
  8.  *
  9.  * For the full copyright and license information, please view the LICENSE
  10.  * file that was distributed with this source code.
  11.  */
  12. namespace Customize\Controller;
  13. use Customize\Repository\OrderRepository;
  14. use Customize\Service\EcconnectfmService;
  15. use Eccube\Controller\AbstractController;
  16. use Eccube\Entity\BaseInfo;
  17. use Eccube\Entity\Master\ProductStatus;
  18. use Eccube\Entity\Product;
  19. use Eccube\Event\EccubeEvents;
  20. use Eccube\Event\EventArgs;
  21. use Eccube\Form\Type\AddCartType;
  22. use Eccube\Form\Type\SearchProductType;
  23. use Eccube\Repository\BaseInfoRepository;
  24. use Eccube\Repository\CustomerFavoriteProductRepository;
  25. use Eccube\Repository\Master\OrderStatusRepository;
  26. use Eccube\Repository\Master\ProductListMaxRepository;
  27. use Eccube\Repository\ProductRepository;
  28. use Eccube\Service\CartService;
  29. use Eccube\Service\PurchaseFlow\PurchaseContext;
  30. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  31. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  32. use Knp\Component\Pager\PaginatorInterface;
  33. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  34. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  35. use Symfony\Component\HttpFoundation\Request;
  36. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  37. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  38. use Symfony\Component\Routing\Annotation\Route;
  39. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  40. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  41. class ProductController extends AbstractController
  42. {
  43.     /**
  44.      * @var PurchaseFlow
  45.      */
  46.     protected $purchaseFlow;
  47.     /**
  48.      * @var CustomerFavoriteProductRepository
  49.      */
  50.     protected $customerFavoriteProductRepository;
  51.     /**
  52.      * @var CartService
  53.      */
  54.     protected $cartService;
  55.     /**
  56.      * @var ProductRepository
  57.      */
  58.     protected $productRepository;
  59.     /**
  60.      * @var BaseInfo
  61.      */
  62.     protected $BaseInfo;
  63.     /**
  64.      * @var AuthenticationUtils
  65.      */
  66.     protected $helper;
  67.     /**
  68.      * @var ProductListMaxRepository
  69.      */
  70.     protected $productListMaxRepository;
  71.     /**
  72.      * @var EcconnectfmService
  73.      */
  74.     private EcconnectfmService $ecconnectfmService;
  75.     /**
  76.      * @var OrderRepository
  77.      */
  78.     protected $orderRepository;
  79.     /**
  80.      * @var OrderStatusRepository
  81.      */
  82.     protected $orderStatusRepository;
  83.     private $title '';
  84.     /**
  85.      * ProductController constructor.
  86.      *
  87.      * @param PurchaseFlow $cartPurchaseFlow
  88.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  89.      * @param CartService $cartService
  90.      * @param ProductRepository $productRepository
  91.      * @param BaseInfoRepository $baseInfoRepository
  92.      * @param AuthenticationUtils $helper
  93.      * @param ProductListMaxRepository $productListMaxRepository
  94.      * @param EcconnectfmService $ecconnectfmService
  95.      * @param OrderRepository $orderRepository
  96.      * @param OrderStatusRepository $orderStatusRepository
  97.      */
  98.     public function __construct(
  99.         PurchaseFlow $cartPurchaseFlow,
  100.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  101.         CartService $cartService,
  102.         ProductRepository $productRepository,
  103.         BaseInfoRepository $baseInfoRepository,
  104.         AuthenticationUtils $helper,
  105.         ProductListMaxRepository $productListMaxRepository,
  106.         EcconnectfmService $ecconnectfmService,
  107.         OrderRepository $orderRepository,
  108.         OrderStatusRepository $orderStatusRepository
  109.     ) {
  110.         $this->purchaseFlow $cartPurchaseFlow;
  111.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  112.         $this->cartService $cartService;
  113.         $this->productRepository $productRepository;
  114.         $this->BaseInfo $baseInfoRepository->get();
  115.         $this->helper $helper;
  116.         $this->productListMaxRepository $productListMaxRepository;
  117.         $this->ecconnectfmService $ecconnectfmService;
  118.         $this->orderRepository $orderRepository;
  119.         $this->orderStatusRepository $orderStatusRepository;
  120.     }
  121.     /**
  122.      * 商品一覧画面.
  123.      *
  124.      * @Route("/products/list", name="product_list", methods={"GET"})
  125.      * @Template("Product/list.twig")
  126.      */
  127.     public function index(Request $requestPaginatorInterface $paginator)
  128.     {
  129.         // Doctrine SQLFilter
  130.         if ($this->BaseInfo->isOptionNostockHidden()) {
  131.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  132.         }
  133.         // handleRequestは空のqueryの場合は無視するため
  134.         if ($request->getMethod() === 'GET') {
  135.             $request->query->set('pageno'$request->query->get('pageno'''));
  136.         }
  137.         // searchForm
  138.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  139.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  140.         if ($request->getMethod() === 'GET') {
  141.             $builder->setMethod('GET');
  142.         }
  143.         $event = new EventArgs(
  144.             [
  145.                 'builder' => $builder,
  146.             ],
  147.             $request
  148.         );
  149.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  150.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  151.         $searchForm $builder->getForm();
  152.         $searchForm->handleRequest($request);
  153.         // paginator
  154.         $searchData $searchForm->getData();
  155.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  156.         $event = new EventArgs(
  157.             [
  158.                 'searchData' => $searchData,
  159.                 'qb' => $qb,
  160.             ],
  161.             $request
  162.         );
  163.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  164.         $searchData $event->getArgument('searchData');
  165.         $query $qb->getQuery()
  166.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  167.         /** @var SlidingPagination $pagination */
  168.         $pagination $paginator->paginate(
  169.             $query,
  170.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  171.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  172.         );
  173.         $ids = [];
  174.         foreach ($pagination as $Product) {
  175.             $ids[] = $Product->getId();
  176.         }
  177.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  178.         // addCart form
  179.         $forms = [];
  180.         foreach ($pagination as $Product) {
  181.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  182.             $builder $this->formFactory->createNamedBuilder(
  183.                 '',
  184.                 AddCartType::class,
  185.                 null,
  186.                 [
  187.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  188.                     'allow_extra_fields' => true,
  189.                 ]
  190.             );
  191.             $addCartForm $builder->getForm();
  192.             $forms[$Product->getId()] = $addCartForm->createView();
  193.         }
  194.         $Category $searchForm->get('category_id')->getData();
  195.         return [
  196.             'subtitle' => $this->getPageTitle($searchData),
  197.             'pagination' => $pagination,
  198.             'search_form' => $searchForm->createView(),
  199.             'forms' => $forms,
  200.             'Category' => $Category,
  201.         ];
  202.     }
  203.     /**
  204.      * 商品詳細画面.
  205.      *
  206.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  207.      * @Template("Product/detail.twig")
  208.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  209.      *
  210.      * @param Request $request
  211.      * @param Product $Product
  212.      *
  213.      * @return array
  214.      */
  215.     public function detail(Request $requestProduct $Product)
  216.     {
  217.         if (!$this->checkVisibility($Product)) {
  218.             throw new NotFoundHttpException();
  219.         }
  220.         // 最新在庫数を確認
  221.         $this->updateProductStock($Product);
  222.         $builder $this->formFactory->createNamedBuilder(
  223.             '',
  224.             AddCartType::class,
  225.             null,
  226.             [
  227.                 'product' => $Product,
  228.                 'id_add_product_id' => false,
  229.             ]
  230.         );
  231.         $event = new EventArgs(
  232.             [
  233.                 'builder' => $builder,
  234.                 'Product' => $Product,
  235.             ],
  236.             $request
  237.         );
  238.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  239.         $is_favorite false;
  240.         if ($this->isGranted('ROLE_USER')) {
  241.             $Customer $this->getUser();
  242.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  243.         }
  244.         return [
  245.             'title' => $this->title,
  246.             'subtitle' => $Product->getName(),
  247.             'form' => $builder->getForm()->createView(),
  248.             'Product' => $Product,
  249.             'is_favorite' => $is_favorite,
  250.             'ProductClass' => $Product->getProductClasses()[0// 必ず1クラス存在するの前提で実装
  251.         ];
  252.     }
  253.     /**
  254.      * お気に入り追加.
  255.      *
  256.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  257.      */
  258.     public function addFavorite(Request $requestProduct $Product)
  259.     {
  260.         $this->checkVisibility($Product);
  261.         $event = new EventArgs(
  262.             [
  263.                 'Product' => $Product,
  264.             ],
  265.             $request
  266.         );
  267.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  268.         if ($this->isGranted('ROLE_USER')) {
  269.             $Customer $this->getUser();
  270.             $favoriteAction $request->request->get('favorite_action');
  271.             if ($favoriteAction === 'remove_favorite') {
  272.                 // お気に入り商品を削除
  273.                 $CustomerFavoriteProduct $this->customerFavoriteProductRepository->findOneBy(['Customer' => $Customer'Product' => $Product]);
  274.                 if ($CustomerFavoriteProduct) {
  275.                     $this->customerFavoriteProductRepository->delete($CustomerFavoriteProduct);
  276.                 } else {
  277.                     throw new BadRequestHttpException();
  278.                 }
  279.             } else {
  280.                 $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  281.             }
  282.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  283.             $event = new EventArgs(
  284.                 [
  285.                     'Product' => $Product,
  286.                 ],
  287.                 $request
  288.             );
  289.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  290.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  291.         } else {
  292.             // 非会員の場合、ログイン画面を表示
  293.             //  ログイン後の画面遷移先を設定
  294.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  295.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  296.             $event = new EventArgs(
  297.                 [
  298.                     'Product' => $Product,
  299.                 ],
  300.                 $request
  301.             );
  302.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  303.             return $this->redirectToRoute('mypage_login');
  304.         }
  305.     }
  306.     /**
  307.      * 予約に追加.
  308.      *
  309.      * @Route("/products/add_reserve/{id}", name="product_add_reserve", methods={"POST"}, requirements={"id" = "\d+"})
  310.      */
  311.     public function addReserve(Request $request)
  312.     {
  313.         if (empty($request->request->get('product_id'))) {
  314.             throw new NotFoundHttpException();
  315.         }
  316.         $Product $this->productRepository->find($request->request->get('product_id'));
  317.         if (empty($Product)) {
  318.             throw new NotFoundHttpException();
  319.         }
  320.         // 最新在庫数を確認
  321.         $this->updateProductStock($Product);
  322.         // カートのフローを流用するのでAddCartTypeを使用
  323.         $builder $this->formFactory->createNamedBuilder(
  324.             '',
  325.             AddCartType::class,
  326.             null,
  327.             [
  328.                 'product' => $Product,
  329.                 'id_add_product_id' => false,
  330.             ]
  331.         );
  332.         $form $builder->getForm();
  333.         $form->handleRequest($request);
  334.         // csrfトークンの設定を無効にして登録処理
  335.         $addCartData $form->getData();
  336.         $addCartData->setPrice($Product->getPrice02IncTaxMin());
  337.         $addCartData->setQuantity($request->request->get('quantity'));
  338.         $addCartData->setProductClass($Product->getProductClasses()[0]); // 必ず1クラス存在するの前提で実装
  339.         $Customer $this->getUser();
  340.         $OrderStatus $this->orderStatusRepository->find(10);
  341.         $updateItems $this->orderRepository->saveReserve($Product$addCartData$Customer$OrderStatus);
  342.         $this->ecconnectfmService->updateFmProductStock($updateItems);
  343.         return $this->json(['done' => true]);
  344.     }
  345.     /**
  346.      * カートに追加.
  347.      *
  348.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  349.      */
  350.     public function addCart(Request $requestProduct $Product)
  351.     {
  352.         // エラーメッセージの配列
  353.         $errorMessages = [];
  354.         if (!$this->checkVisibility($Product)) {
  355.             throw new NotFoundHttpException();
  356.         }
  357.         // 最新在庫数を確認
  358.         $this->updateProductStock($Product);
  359.         $builder $this->formFactory->createNamedBuilder(
  360.             '',
  361.             AddCartType::class,
  362.             null,
  363.             [
  364.                 'product' => $Product,
  365.                 'id_add_product_id' => false,
  366.             ]
  367.         );
  368.         $event = new EventArgs(
  369.             [
  370.                 'builder' => $builder,
  371.                 'Product' => $Product,
  372.             ],
  373.             $request
  374.         );
  375.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  376.         /* @var $form \Symfony\Component\Form\FormInterface */
  377.         $form $builder->getForm();
  378.         $form->handleRequest($request);
  379.         if (!$form->isValid()) {
  380.             throw new NotFoundHttpException();
  381.         }
  382.         $addCartData $form->getData();
  383.         log_info(
  384.             'カート追加処理開始',
  385.             [
  386.                 'product_id' => $Product->getId(),
  387.                 'product_class_id' => $addCartData['product_class_id'],
  388.                 'quantity' => $addCartData['quantity'],
  389.             ]
  390.         );
  391.         // カートへ追加
  392.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  393.         // 明細の正規化
  394.         $Carts $this->cartService->getCarts();
  395.         foreach ($Carts as $Cart) {
  396.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  397.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  398.             if ($result->hasError()) {
  399.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  400.                 foreach ($result->getErrors() as $error) {
  401.                     $errorMessages[] = $error->getMessage();
  402.                 }
  403.             }
  404.             foreach ($result->getWarning() as $warning) {
  405.                 $errorMessages[] = $warning->getMessage();
  406.             }
  407.         }
  408.         $this->cartService->save();
  409.         log_info(
  410.             'カート追加処理完了',
  411.             [
  412.                 'product_id' => $Product->getId(),
  413.                 'product_class_id' => $addCartData['product_class_id'],
  414.                 'quantity' => $addCartData['quantity'],
  415.             ]
  416.         );
  417.         $event = new EventArgs(
  418.             [
  419.                 'form' => $form,
  420.                 'Product' => $Product,
  421.             ],
  422.             $request
  423.         );
  424.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  425.         if ($event->getResponse() !== null) {
  426.             return $event->getResponse();
  427.         }
  428.         if ($request->isXmlHttpRequest()) {
  429.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  430.             // 初期化
  431.             $messages = [];
  432.             if (empty($errorMessages)) {
  433.                 // エラーが発生していない場合
  434.                 $done true;
  435.                 array_push($messagestrans('front.product.add_cart_complete'));
  436.             } else {
  437.                 // エラーが発生している場合
  438.                 $done false;
  439.                 $messages $errorMessages;
  440.             }
  441.             return $this->json(['done' => $done'messages' => $messages]);
  442.         } else {
  443.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  444.             foreach ($errorMessages as $errorMessage) {
  445.                 $this->addRequestError($errorMessage);
  446.             }
  447.             return $this->redirectToRoute('cart');
  448.         }
  449.     }
  450.     /**
  451.      * ページタイトルの設定
  452.      *
  453.      * @param  array|null $searchData
  454.      *
  455.      * @return str
  456.      */
  457.     protected function getPageTitle($searchData)
  458.     {
  459.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  460.             return trans('front.product.search_result');
  461.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  462.             return $searchData['category_id']->getName();
  463.         } else {
  464.             return trans('front.product.all_products');
  465.         }
  466.     }
  467.     /**
  468.      * 閲覧可能な商品かどうかを判定
  469.      *
  470.      * @param Product $Product
  471.      *
  472.      * @return boolean 閲覧可能な場合はtrue
  473.      */
  474.     protected function checkVisibility(Product $Product)
  475.     {
  476.         $is_admin $this->session->has('_security_admin');
  477.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  478.         if (!$is_admin) {
  479.             // 在庫なし商品の非表示オプションが有効な場合.
  480.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  481.             //     if (!$Product->getStockFind()) {
  482.             //         return false;
  483.             //     }
  484.             // }
  485.             // 公開ステータスでない商品は表示しない.
  486.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  487.                 return false;
  488.             }
  489.         }
  490.         return true;
  491.     }
  492.     /**
  493.      * 最新在庫数を確認
  494.      * 
  495.      * @param Product $Product
  496.      */
  497.     protected function updateProductStock(Product $Product)
  498.     {
  499.         // FM在庫数を取得
  500.         $serials = [];
  501.         foreach ($Product->getProductClasses() as $ProductClass) {
  502.             $productStock $ProductClass->getProductStock();
  503.             $serials[] = $ProductClass->getSerialNo();
  504.         }
  505.         $fmStocks $this->ecconnectfmService->getFmProductStock($serials);
  506.         foreach ($Product->getProductClasses() as $ProductClass) {
  507.             $productStock $ProductClass->getProductStock();
  508.             // EC在庫数とFM在庫数が異なる場合は更新
  509.             $ecStock = (int) $productStock->getStock();
  510.             $fmStock $fmStocks[$ProductClass->getCode()] ?? 0;
  511.             if ($ecStock !== $fmStock) {
  512.                 $ProductClass->setStock($fmStock);
  513.                 $productStock->setStock($fmStock);
  514.                 $this->entityManager->persist($ProductClass);
  515.                 $this->entityManager->persist($productStock);
  516.                 $this->entityManager->flush();
  517.             }
  518.         }
  519.     }
  520. }