app/Customize/Controller/CustomProductController.php line 210

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 Eccube\Entity\BaseInfo;
  14. use Eccube\Entity\Master\ProductStatus;
  15. use Eccube\Entity\Product;
  16. use Eccube\Event\EccubeEvents;
  17. use Eccube\Event\EventArgs;
  18. use Eccube\Form\Type\AddCartType;
  19. use Eccube\Form\Type\SearchProductType;
  20. use Eccube\Repository\BaseInfoRepository;
  21. use Eccube\Repository\CustomerFavoriteProductRepository;
  22. use Eccube\Repository\Master\ProductListMaxRepository;
  23. use Eccube\Repository\ProductRepository;
  24. use Eccube\Service\CartService;
  25. use Eccube\Service\PurchaseFlow\PurchaseContext;
  26. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  27. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  28. use Knp\Component\Pager\PaginatorInterface;
  29. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  30. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  33. use Symfony\Component\Routing\Annotation\Route;
  34. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  35. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  36. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  37. use Symfony\Component\HttpFoundation\Response;
  38. use Eccube\Controller\AbstractController;
  39. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  40. use Customize\Repository\CustomProductClassRepository;
  41. use Customize\Repository\CustomProductRepository;
  42. class CustomProductController extends AbstractController
  43. {
  44.     /**
  45.      * @var PurchaseFlow
  46.      */
  47.     protected $purchaseFlow;
  48.     /**
  49.      * @var CustomerFavoriteProductRepository
  50.      */
  51.     protected $customerFavoriteProductRepository;
  52.     /**
  53.      * @var CartService
  54.      */
  55.     protected $cartService;
  56.     /**
  57.      * @var ProductRepository
  58.      */
  59.     protected $productRepository;
  60.     /**
  61.      * @var BaseInfo
  62.      */
  63.     protected $BaseInfo;
  64.     /**
  65.      * @var AuthenticationUtils
  66.      */
  67.     protected $helper;
  68.     /**
  69.      * @var ProductListMaxRepository
  70.      */
  71.     protected $productListMaxRepository;
  72.     /**
  73.      * @var ProductClassRepository
  74.      */
  75.     protected $customProductClassRepository;
  76.     /**
  77.      * @var CustomProductRepository
  78.      */
  79.     protected $customProductRepository;
  80.     private $title '';
  81.     /**
  82.      * ProductController constructor.
  83.      *
  84.      * @param PurchaseFlow $cartPurchaseFlow
  85.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  86.      * @param CartService $cartService
  87.      * @param ProductRepository $productRepository
  88.      * @param BaseInfoRepository $baseInfoRepository
  89.      * @param AuthenticationUtils $helper
  90.      * @param ProductListMaxRepository $productListMaxRepository
  91.      * @param CustomProductClassRepository $customProductClassRepository
  92.      * @param CustomProductRepository $customProductRepository
  93.      */
  94.     public function __construct(
  95.         PurchaseFlow $cartPurchaseFlow,
  96.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  97.         CartService $cartService,
  98.         ProductRepository $productRepository,
  99.         BaseInfoRepository $baseInfoRepository,
  100.         AuthenticationUtils $helper,
  101.         ProductListMaxRepository $productListMaxRepository,
  102.         CustomProductClassRepository $customProductClassRepository,
  103.         CustomProductRepository $customProductRepository
  104.     ) {
  105.         $this->purchaseFlow $cartPurchaseFlow;
  106.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  107.         $this->cartService $cartService;
  108.         $this->productRepository $productRepository;
  109.         $this->BaseInfo $baseInfoRepository->get();
  110.         $this->helper $helper;
  111.         $this->productListMaxRepository $productListMaxRepository;
  112.         $this->customProductClassRepository $customProductClassRepository;
  113.         $this->customProductRepository $customProductRepository;
  114.     }
  115.     /**
  116.      * 商品一覧画面.
  117.      *
  118.      * @Route("/products/list", name="product_list", methods={"GET"})
  119.      * @Template("Product/list.twig")
  120.      */
  121.     public function index(Request $requestPaginatorInterface $paginator)
  122.     {
  123.         // Doctrine SQLFilter
  124.         if ($this->BaseInfo->isOptionNostockHidden()) {
  125.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  126.         }
  127.         // handleRequestは空のqueryの場合は無視するため
  128.         if ($request->getMethod() === 'GET') {
  129.             $request->query->set('pageno'$request->query->get('pageno'''));
  130.         }
  131.         // searchForm
  132.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  133.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  134.         if ($request->getMethod() === 'GET') {
  135.             $builder->setMethod('GET');
  136.         }
  137.         $event = new EventArgs(
  138.             [
  139.                 'builder' => $builder,
  140.             ],
  141.             $request
  142.         );
  143.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  144.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  145.         $searchForm $builder->getForm();
  146.         $searchForm->handleRequest($request);
  147.         // paginator
  148.         $searchData $searchForm->getData();
  149.         // customGetQueryBuilderBySearchData を使う
  150.         $qb $this->customProductRepository->customGetQueryBuilderBySearchData($searchData);;
  151.         $event = new EventArgs(
  152.             [
  153.                 'searchData' => $searchData,
  154.                 'qb' => $qb,
  155.             ],
  156.             $request
  157.         );
  158.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  159.         $searchData $event->getArgument('searchData');
  160.         $query $qb->getQuery()
  161.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  162.         /** @var SlidingPagination $pagination */
  163.         $pagination $paginator->paginate(
  164.             $query,
  165.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  166.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  167.         );
  168.         $ids = [];
  169.         foreach ($pagination as $Product) {
  170.             $ids[] = $Product->getId();
  171.         }
  172.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  173.         // addCart form
  174.         $forms = [];
  175.         foreach ($pagination as $Product) {
  176.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  177.             $builder $this->formFactory->createNamedBuilder(
  178.                 '',
  179.                 AddCartType::class,
  180.                 null,
  181.                 [
  182.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  183.                     'allow_extra_fields' => true,
  184.                 ]
  185.             );
  186.             $addCartForm $builder->getForm();
  187.             $forms[$Product->getId()] = $addCartForm->createView();
  188.         }
  189.         $Category $searchForm->get('category_id')->getData();
  190.         return [
  191.             'subtitle' => $this->getPageTitle($searchData),
  192.             'pagination' => $pagination,
  193.             'search_form' => $searchForm->createView(),
  194.             'forms' => $forms,
  195.             'Category' => $Category,
  196.         ];
  197.     }
  198.     /**
  199.      * 商品詳細画面.
  200.      *
  201.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  202.      * @Template("Product/detail.twig")
  203.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  204.      *
  205.      * @param Request $request
  206.      * @param Product $Product
  207.      *
  208.      * @return array
  209.      */
  210.     public function detail(Request $requestProduct $Product)
  211.     {
  212.         if (!$this->checkVisibility($Product)) {
  213.             throw new NotFoundHttpException();
  214.         }
  215.         /*
  216.         $builder = $this->formFactory->createNamedBuilder(
  217.             '',
  218.             AddCartType::class,
  219.             null,
  220.             [
  221.                 'product' => $Product,
  222.                 'id_add_product_id' => false,
  223.             ]
  224.         );
  225.         */
  226.         $builder $this->formFactory->createBuilder( );
  227.         $builder
  228.             ->add(
  229.                 'data',
  230.                 CollectionType::class,
  231.                 [
  232.                     'entry_type' => AddCartType::class,
  233.                     'entry_options' => [
  234.                         'product' => $Product,
  235.                         'id_add_product_id' => false,
  236.                         'attr' => ['class' => 'oneclass'],
  237.                     ],
  238.                     'allow_add' => true,
  239.                     'allow_delete' => true,
  240.                     'label' => '',
  241.                 ]
  242.                 );
  243.         $event = new EventArgs(
  244.             [
  245.                 'builder' => $builder,
  246.                 'Product' => $Product,
  247.             ],
  248.             $request
  249.         );
  250.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  251.         $is_favorite false;
  252.         if ($this->isGranted('ROLE_USER')) {
  253.             $Customer $this->getUser();
  254.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  255.         }
  256.         return [
  257.             'title' => $this->title,
  258.             'subtitle' => $Product->getName(),
  259.             'form' => $builder->getForm()->createView(),
  260.             'Product' => $Product,
  261.             'is_favorite' => $is_favorite,
  262.         ];
  263.     }
  264.     /**
  265.      * カートに追加.(複数の場合あり)
  266.      *
  267.      * @Route("/products/addmulti_cart/{id}", name="product_addmulti_cart", methods={"POST"}, requirements={"id" = "\d+"})
  268.      */
  269.     public function addmultiCart(Request $requestProduct $Product)
  270.     {
  271.         // エラーメッセージの配列
  272.         $errorMessages = [];
  273.         if (!$this->checkVisibility($Product)) {
  274.             throw new NotFoundHttpException();
  275.         }
  276.         /*
  277.         $builder = $this->formFactory->createNamedBuilder(
  278.             '',
  279.             AddCartType::class,
  280.             null,
  281.             [
  282.                 'product' => $Product,
  283.                 'id_add_product_id' => false,
  284.             ]
  285.         );
  286.         */
  287.         $builder $this->formFactory->createBuilder( );
  288.         $builder
  289.             ->add(
  290.                 'data',
  291.                 CollectionType::class,
  292.                 [
  293.                     'entry_type' => AddCartType::class,
  294.                     'entry_options' => [
  295.                         'product' => $Product,
  296.                         'id_add_product_id' => false,
  297.                         'attr' => ['class' => 'oneclass'],
  298.                     ],
  299.                     'allow_add' => true,
  300.                     'allow_delete' => true,
  301.                     'label' => '',
  302.                 ]
  303.             );
  304.         $event = new EventArgs(
  305.             [
  306.                 'builder' => $builder,
  307.                 'Product' => $Product,
  308.             ],
  309.             $request
  310.         );
  311.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  312.         /* @var $form \Symfony\Component\Form\FormInterface */
  313.         $form $builder->getForm();
  314.         $form->handleRequest($request);
  315.         $addCartData $request->get('form');
  316.         //$addCartData = $form->getData();
  317.         $type $request->query->get('type');
  318.         if($addCartData) {
  319.             $added_product_class_id = array(); // 元に戻すときのためにカートに追加した商品を覚えておく
  320.             foreach ( $addCartData['data'] as $index => $oneItem ) {
  321.                 switch ($index) {
  322.                     case 0:
  323.                         if($type == "left" || $type == "set") {
  324.                             // 結婚指輪の場合
  325.                             $classcategory2 NULL;
  326.                             if (array_key_exists('classcategory_id2'$oneItem)) {
  327.                                 $classcategory2 = (int)$oneItem['classcategory_id2'];
  328.                             }
  329.                             $ProductClasses $this->customProductClassRepository->findByCategoryIds($Product, (int)$oneItem['classcategory_id1'], $classcategory2);
  330.                             foreach ($ProductClasses as $ProductClass) {
  331.                                 $oneItem['product_class_id'] = $ProductClass->getId();
  332.                                 $product_class $ProductClass;
  333.                             }
  334.                             // サイズによる割増料金の追加
  335.                             $size_price $this->calcSizePriceMarriageRing($oneItem['size']);
  336.                             log_info(
  337.                                 'カート追加処理開始',
  338.                                 [
  339.                                     'product_id' => $Product->getId(),
  340.                                     'product_class_id' => $oneItem['product_class_id'],
  341.                                     'quantity' => $oneItem['quantity'],
  342.                                 ]
  343.                             );
  344.                             //$this->cartService->addProduct($oneItem['product_class_id'], $oneItem['quantity']);
  345.                             $this->cartService->addCartItem($product_class$oneItem['quantity'], [
  346.                                 'size' => $oneItem['size'],
  347.                                 'size_price' => $size_price,
  348.                             ]);
  349.                             $added_product_class_id[] = $oneItem['product_class_id'];
  350.                         } elseif($type == "no_type") {
  351.                             // 婚約指輪の場合
  352.                             $classcategory1 NULL;
  353.                             $classcategory2 NULL;
  354.                             if (array_key_exists('classcategory_id1'$oneItem)) {
  355.                                 $classcategory1 = (int)$oneItem['classcategory_id1'];
  356.                             }
  357.                             if (array_key_exists('classcategory_id2'$oneItem)) {
  358.                                 $classcategory2 = (int)$oneItem['classcategory_id2'];
  359.                             }
  360.                             $ProductClasses $this->customProductClassRepository->findByCategoryIds($Product$classcategory1$classcategory2);
  361.                             foreach ($ProductClasses as $ProductClass) {
  362.                                 $oneItem['product_class_id'] = $ProductClass->getId();
  363.                                 $product_class $ProductClass;
  364.                             }
  365.                             // サイズによる割増料金の追加
  366.                             $size_price 0;
  367.                             if ($oneItem['product_id'] == 110 || $oneItem['product_id'] == 112) {
  368.                                 $size_price $this->calcSizePriceEngagementRing($oneItem['size']);
  369.                             }
  370.                             log_info(
  371.                                 'カート追加処理開始',
  372.                                 [
  373.                                     'product_id' => $Product->getId(),
  374.                                     'product_class_id' => $oneItem['product_class_id'],
  375.                                     'quantity' => $oneItem['quantity'],
  376.                                 ]
  377.                             );
  378.                             //$this->cartService->addProduct($oneItem['product_class_id'], $oneItem['quantity']);
  379.                             $this->cartService->addCartItem($product_class$oneItem['quantity'], [
  380.                                 'size' => $oneItem['size'],
  381.                                 'size_price' => $size_price,
  382.                             ]);
  383.                             $added_product_class_id[] = $oneItem['product_class_id'];
  384.                         }
  385.                         break;
  386.                     case 1:
  387.                         if($type == "right" || $type == "set") {
  388.                             $classcategory2 NULL;
  389.                             if (array_key_exists('classcategory_id2'$oneItem)) {
  390.                                 $classcategory2 = (int)$oneItem['classcategory_id2'];
  391.                             }
  392.                             $ProductClasses $this->customProductClassRepository->findByCategoryIds($Product, (int)$oneItem['classcategory_id1'], $classcategory2);
  393.                             foreach ($ProductClasses as $ProductClass) {
  394.                                 $oneItem['product_class_id'] = $ProductClass->getId();
  395.                                 $product_class $ProductClass;
  396.                             }
  397.                             // サイズによる割増料金の追加
  398.                             $size_price $this->calcSizePriceMarriageRing($oneItem['size']);
  399.                             log_info(
  400.                                 'カート追加処理開始',
  401.                                 [
  402.                                     'product_id' => $Product->getId(),
  403.                                     'product_class_id' => $oneItem['product_class_id'],
  404.                                     'quantity' => $oneItem['quantity'],
  405.                                 ]
  406.                             );
  407.                             //$this->cartService->addProduct($oneItem['product_class_id'], $oneItem['quantity']);
  408.                             $this->cartService->addCartItem($product_class$oneItem['quantity'], [
  409.                                 'size' => $oneItem['size'],
  410.                                 'size_price' => $size_price,
  411.                             ]);
  412.                             $added_product_class_id[] = $oneItem['product_class_id'];
  413.                         }
  414.                         break;
  415.                     default:
  416.                 }
  417.             }
  418.         }
  419.         // 明細の正規化
  420.         $Carts $this->cartService->getCarts();
  421.         foreach ($Carts as $Cart) {
  422.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  423.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  424.             if ($result->hasError()) {
  425.                 foreach ($added_product_class_id as $added_pcid) {
  426.                     $this->cartService->removeProduct($added_pcid);
  427.                 }
  428.                 //$this->cartService->removeProduct($addCartData['product_class_id']);
  429.                 foreach ($result->getErrors() as $error) {
  430.                     $errorMessages[] = $error->getMessage();
  431.                 }
  432.             }
  433.             foreach ($result->getWarning() as $warning) {
  434.                 $errorMessages[] = $warning->getMessage();
  435.             }
  436.         }
  437.         $this->cartService->save();
  438.         log_info(
  439.             'カート追加処理完了',
  440.             [
  441.                 'product_id' => $Product->getId(),
  442.             ]
  443.         );
  444.         $event = new EventArgs(
  445.             [
  446.                 'form' => $form,
  447.                 'Product' => $Product,
  448.             ],
  449.             $request
  450.         );
  451.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  452.         if ($event->getResponse() !== null) {
  453.             return $event->getResponse();
  454.         }
  455.         if ($request->isXmlHttpRequest()) {
  456.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  457.             // 初期化
  458.             $messages = [];
  459.             if (empty($errorMessages)) {
  460.                 // エラーが発生していない場合
  461.                 $done true;
  462.                 array_push($messagestrans('front.product.add_cart_complete'));
  463.             } else {
  464.                 // エラーが発生している場合
  465.                 $done false;
  466.                 $messages $errorMessages;
  467.             }
  468.             return $this->json(['done' => $done'messages' => $messages]);
  469.         } else {
  470.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  471.             foreach ($errorMessages as $errorMessage) {
  472.                 $this->addRequestError($errorMessage);
  473.             }
  474.             return $this->redirectToRoute('cart');
  475.         }
  476.     }
  477.     /**
  478.      * 結婚指輪のサイズによる割増料金(税込)を算出する
  479.      *
  480.      * @param float $size
  481.      *
  482.      * @return int
  483.      */
  484.     protected function calcSizePriceMarriageRing(float $size)
  485.     {
  486.         $add_price 0;
  487.         if ($size) {
  488.             if ($size >= 16.5) {
  489.                 // 割り増し料金
  490.                 $add_price 22000;
  491.             } elseif ($size >= 12.5) {
  492.                 // 割り増し料金
  493.                 $add_price 11000;
  494.             }
  495.         }
  496.         return($add_price);
  497.     }
  498.     /**
  499.      * 婚約指輪のサイズによる割増料金(税込)を算出する
  500.      * 商品ID 110,112 の商品のみ
  501.      *
  502.      * @param int $size
  503.      *
  504.      * @return int
  505.      */
  506.     protected function calcSizePriceEngagementRing(float $size)
  507.     {
  508.         $add_price 0;
  509.         if ($size) {
  510.             if ($size >= 16) {
  511.                 // 割り増し料金 2025.06 価格改定16500→22000
  512.                 $add_price 22000;
  513.             }
  514.         }
  515.         return($add_price);
  516.     }
  517.     /**
  518.      * 閲覧可能な商品かどうかを判定
  519.      *
  520.      * @param Product $Product
  521.      *
  522.      * @return boolean 閲覧可能な場合はtrue
  523.      */
  524.     protected function checkVisibility(Product $Product)
  525.     {
  526.         $is_admin $this->session->has('_security_admin');
  527.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  528.         if (!$is_admin) {
  529.             // 在庫なし商品の非表示オプションが有効な場合.
  530.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  531.             //     if (!$Product->getStockFind()) {
  532.             //         return false;
  533.             //     }
  534.             // }
  535.             // 公開ステータスでない商品は表示しない.
  536.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  537.                 return false;
  538.             }
  539.         }
  540.         return true;
  541.     }
  542.     /**
  543.      * ページタイトルの設定
  544.      *
  545.      * @param  array|null $searchData
  546.      *
  547.      * @return str
  548.      */
  549.     protected function getPageTitle($searchData)
  550.     {
  551.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  552.             return trans('front.product.search_result');
  553.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  554.             return $searchData['category_id']->getName();
  555.         } else {
  556.             return trans('front.product.all_products');
  557.         }
  558.     }
  559. }