app/Customize/Controller/CustomizeProductController.php line 140

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 Eccube\Controller\ProductController as BaseController;
  37. use Customize\Repository\CustomizeProductRepository;
  38. use Plugin\RecentlyViewedProducts\Service\RecentlyViewedProductService;
  39. class CustomizeProductController extends BaseController
  40. {
  41.     /**
  42.      * @var PurchaseFlow
  43.      */
  44.     protected $purchaseFlow;
  45.     /**
  46.      * @var CustomerFavoriteProductRepository
  47.      */
  48.     protected $customerFavoriteProductRepository;
  49.     /**
  50.      * @var CartService
  51.      */
  52.     protected $cartService;
  53.     /**
  54.      * @var ProductRepository
  55.      */
  56.     protected $productRepository;
  57.     /**
  58.      * @var BaseInfo
  59.      */
  60.     protected $BaseInfo;
  61.     /**
  62.      * @var AuthenticationUtils
  63.      */
  64.     protected $helper;
  65.     /**
  66.      * @var ProductListMaxRepository
  67.      */
  68.     protected $productListMaxRepository;
  69.     private $title '';
  70.     /**
  71.      * @var RecentlyViewedProductService
  72.      */
  73.     protected $recentlyViewedProductService;
  74.     /**
  75.      * ProductController constructor.
  76.      *
  77.      * @param PurchaseFlow $cartPurchaseFlow
  78.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  79.      * @param CartService $cartService
  80.      * @param ProductRepository $productRepository
  81.      * @param BaseInfoRepository $baseInfoRepository
  82.      * @param AuthenticationUtils $helper
  83.      * @param ProductListMaxRepository $productListMaxRepository
  84.      */
  85.     public function __construct(
  86.         PurchaseFlow $cartPurchaseFlow,
  87.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  88.         CartService $cartService,
  89.         ProductRepository $productRepository,
  90.         BaseInfoRepository $baseInfoRepository,
  91.         AuthenticationUtils $helper,
  92.         ProductListMaxRepository $productListMaxRepository,
  93.         RecentlyViewedProductService $recentlyViewedProductService,
  94.     ) {
  95.         $this->purchaseFlow $cartPurchaseFlow;
  96.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  97.         $this->cartService $cartService;
  98.         $this->productRepository $productRepository;
  99.         $this->BaseInfo $baseInfoRepository->get();
  100.         $this->helper $helper;
  101.         $this->productListMaxRepository $productListMaxRepository;
  102.         $this->recentlyViewedProductService $recentlyViewedProductService;
  103.     }
  104.     /**
  105.      * 商品一覧画面.
  106.      *
  107.      * @Route("/products/list", name="product_list", methods={"GET"})
  108.      * @Template("Product/list.twig")
  109.      */
  110.     public function index(Request $requestPaginatorInterface $paginator)
  111.     {
  112.         // Doctrine SQLFilter
  113.         if ($this->BaseInfo->isOptionNostockHidden()) {
  114.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  115.         }
  116.         // handleRequestは空のqueryの場合は無視するため
  117.         if ($request->getMethod() === 'GET') {
  118.             $request->query->set('pageno'$request->query->get('pageno'''));
  119.         }
  120.         // searchForm
  121.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  122.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  123.         if ($request->getMethod() === 'GET') {
  124.             $builder->setMethod('GET');
  125.         }
  126.         $event = new EventArgs(
  127.             [
  128.                 'builder' => $builder,
  129.             ],
  130.             $request
  131.         );
  132.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  133.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  134.         $searchForm $builder->getForm();
  135.         $searchForm->handleRequest($request);
  136.         // paginator
  137.         $searchData $searchForm->getData();
  138.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  139.         //ここからカスタマイズ
  140.         //paginationに、SaleType.idが1(書籍商品)しか渡さないようにする
  141.         $sub $this->entityManager->createQueryBuilder()
  142.             ->select('MIN(pc2.id)')
  143.             ->from(\Eccube\Entity\ProductClass::class, 'pc2')
  144.             ->where('pc2.Product = p')
  145.             ->getDQL();
  146.         $qb
  147.             ->innerJoin('p.ProductClasses''pc3')
  148.             ->innerJoin('pc3.SaleType''st')
  149.             ->andWhere($qb->expr()->eq('pc3.id''(' $sub ')'))
  150.             ->andWhere('st.id = 1');
  151.         //ここまでカスタマイズ
  152.         $event = new EventArgs(
  153.             [
  154.                 'searchData' => $searchData,
  155.                 'qb' => $qb,
  156.             ],
  157.             $request
  158.         );
  159.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  160.         $searchData $event->getArgument('searchData');
  161.         $query $qb->getQuery()
  162.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  163.         /** @var SlidingPagination $pagination */
  164.         $pagination $paginator->paginate(
  165.             $query,
  166.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  167.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  168.         );
  169.         $ids = [];
  170.         foreach ($pagination as $Product) {
  171.             $ids[] = $Product->getId();
  172.         }
  173.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  174.         // addCart form
  175.         $forms = [];
  176.         foreach ($pagination as $Product) {
  177.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  178.             $builder $this->formFactory->createNamedBuilder(
  179.                 '',
  180.                 AddCartType::class,
  181.                 null,
  182.                 [
  183.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  184.                     'allow_extra_fields' => true,
  185.                 ]
  186.             );
  187.             $addCartForm $builder->getForm();
  188.             $forms[$Product->getId()] = $addCartForm->createView();
  189.         }
  190.         $Category $searchForm->get('category_id')->getData();
  191.         return [
  192.             'subtitle' => $this->getPageTitle($searchData),
  193.             'pagination' => $pagination,
  194.             'search_form' => $searchForm->createView(),
  195.             'forms' => $forms,
  196.             'Category' => $Category,
  197.         ];
  198.     }
  199.     /**
  200.      * 商品詳細画面.
  201.      *
  202.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  203.      * @Template("Product/detail.twig")
  204.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  205.      *
  206.      * @param Request $request
  207.      * @param Product $Product
  208.      *
  209.      * @return array
  210.      */
  211.     public function detail(Request $requestProduct $Product)
  212.     {
  213.         if (!$this->checkVisibility($Product)) {
  214.             throw new NotFoundHttpException();
  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.         $event = new EventArgs(
  226.             [
  227.                 'builder' => $builder,
  228.                 'Product' => $Product,
  229.             ],
  230.             $request
  231.         );
  232.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  233.         $is_favorite false;
  234.         if ($this->isGranted('ROLE_USER')) {
  235.             $Customer $this->getUser();
  236.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  237.         }
  238.         $firstLevelCategories = [];
  239.         foreach ($Product->getProductCategories() as $productCategory) {
  240.             $category $productCategory->getCategory();
  241.             if ($category->getParent() === null) {
  242.             $firstLevelCategories[] = $category;
  243.             }
  244.         }
  245.         $qb $this->productRepository->createQueryBuilder('p')
  246.             ->leftJoin('p.ProductClasses''pc')
  247.             ->addSelect('pc')
  248.             ->orderBy('p.id''DESC');
  249.         $allProducts $qb->getQuery()->getResult();
  250.         //あなたへのおすすめ機能実装
  251.         $productRepository $this->getDoctrine()->getRepository(\Eccube\Entity\Product::class);
  252.         // ProductにTagもJOINして取得する
  253.         $qb $productRepository->createQueryBuilder('p')
  254.             ->leftJoin('p.ProductTag''pt')
  255.             ->leftJoin('pt.Tag''t')
  256.             ->leftJoin('p.ProductCategories''pc')
  257.             ->leftJoin('pc.Category''c')         
  258.             ->addSelect('pt')
  259.             ->addSelect('t')
  260.             ->addSelect('pc')                        
  261.             ->addSelect('c')                         
  262.             ->where('p.Status = 1')
  263.             ->orderBy('p.id''DESC');
  264.         $Products $qb->getQuery()->getResult();
  265.         $RecentlyViewedProducts array_map(function($RecentlyViewedProduct) {
  266.             return $RecentlyViewedProduct->getProduct();
  267.         }, $this->recentlyViewedProductService->getRecentlyViewedProducts());
  268.         $recommendProducts = [];
  269.         if($this->getUser()){
  270.           $Customer $this->getUser();
  271.           $recentlyViewedProductRepository $this->getDoctrine()->getRepository(\Plugin\RecentlyViewedProducts\Entity\RecentlyViewedProduct::class);
  272.           $histories $recentlyViewedProductRepository->findBy(
  273.             ['Customer' => $Customer->getId()],
  274.             ['viewed_date' => 'DESC'],
  275.             30
  276.           );
  277.           // 履歴のproduct_id一覧を作成
  278.           $viewedProductIds array_map(function($history) {
  279.               return $history->getProduct()->getId();
  280.           }, $histories);
  281.           $historyKeywords = [];
  282.           foreach ($histories as $history) {
  283.               $product $history->getProduct();
  284.               if (!$product) continue;
  285.           
  286.               // 検索ワード
  287.               if ($product->getSearchWord()) {
  288.                   $words array_map('trim'explode(','$product->getSearchWord()));
  289.                   $historyKeywords array_merge($historyKeywords$words);
  290.               }
  291.               // 著者
  292.               if ($product->getAuthor()) {
  293.                   $historyKeywords[] = $product->getAuthor();
  294.               }
  295.           }
  296.           // ユーザーの所属県
  297.           if ($Customer->getPref()) {
  298.               $historyKeywords[] = $Customer->getPref()->getName();
  299.           }
  300.           // 特徴キーワードをユニークにする
  301.           $historyKeywords array_unique($historyKeywords);
  302.           // 全商品を取得
  303.           $allProducts $productRepository->findAll();
  304.           // 各商品のスコアを計算
  305.           $productScores = [];
  306.           foreach ($allProducts as $product) {
  307.               $keywords = [];
  308.           
  309.               // 検索ワード
  310.               if ($product->getSearchWord()) {
  311.                   $words array_map('trim'explode(','$product->getSearchWord()));
  312.                   $keywords array_merge($keywords$words);
  313.               }
  314.           
  315.               // 著者
  316.               if ($product->getAuthor()) {
  317.                   $keywords[] = $product->getAuthor();
  318.               }
  319.           
  320.               // ここでは商品自体に「県」はないのでスキップ
  321.           
  322.               $keywords array_unique($keywords);
  323.           
  324.               // 閲覧履歴の特徴キーワードと比較して一致数をカウント
  325.               $commonCount count(array_intersect($historyKeywords$keywords));
  326.           
  327.               // スコアが高いものだけ残す(ここでは0でも一応保持)
  328.               $productScores[] = [
  329.                   'product' => $product,
  330.                   'score' => $commonCount,
  331.               ];
  332.           }
  333.           // スコア順にソート(スコア高い順)
  334.           usort($productScores, function($a$b) {
  335.               return $b['score'] <=> $a['score'];
  336.           });
  337.           
  338.           // Twigに渡す用のおすすめ商品リスト作成
  339.           $recommendProducts array_map(function($item) {
  340.               return $item['product'];
  341.           }, array_slice($productScores030)); // 例:おすすめ30件
  342.         }
  343.         return [
  344.             'title' => $this->title,
  345.             'subtitle' => $Product->getName(),
  346.             'form' => $builder->getForm()->createView(),
  347.             'Product' => $Product,
  348.             'is_favorite' => $is_favorite,
  349.             'firstLevelCategories' => $firstLevelCategories// ← 追加
  350.             'allProducts' => $allProducts// ← 追加
  351.             'recommendProducts' => $recommendProducts,  //← 追加
  352.         ];
  353.     }
  354.     /**
  355.      * お気に入り追加.
  356.      *
  357.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  358.      */
  359.     public function addFavorite(Request $requestProduct $Product)
  360.     {
  361.         $this->checkVisibility($Product);
  362.         $event = new EventArgs(
  363.             [
  364.                 'Product' => $Product,
  365.             ],
  366.             $request
  367.         );
  368.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  369.         if ($this->isGranted('ROLE_USER')) {
  370.             $Customer $this->getUser();
  371.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  372.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  373.             $event = new EventArgs(
  374.                 [
  375.                     'Product' => $Product,
  376.                 ],
  377.                 $request
  378.             );
  379.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  380.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  381.         } else {
  382.             // 非会員の場合、ログイン画面を表示
  383.             //  ログイン後の画面遷移先を設定
  384.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  385.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  386.             $event = new EventArgs(
  387.                 [
  388.                     'Product' => $Product,
  389.                 ],
  390.                 $request
  391.             );
  392.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  393.             return $this->redirectToRoute('mypage_login');
  394.         }
  395.     }
  396.     /**
  397.      * カートに追加.
  398.      *
  399.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  400.      */
  401.     public function addCart(Request $requestProduct $Product)
  402.     {
  403.         // エラーメッセージの配列
  404.         $errorMessages = [];
  405.         if (!$this->checkVisibility($Product)) {
  406.             throw new NotFoundHttpException();
  407.         }
  408.         $builder $this->formFactory->createNamedBuilder(
  409.             '',
  410.             AddCartType::class,
  411.             null,
  412.             [
  413.                 'product' => $Product,
  414.                 'id_add_product_id' => false,
  415.             ]
  416.         );
  417.         $event = new EventArgs(
  418.             [
  419.                 'builder' => $builder,
  420.                 'Product' => $Product,
  421.             ],
  422.             $request
  423.         );
  424.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  425.         /* @var $form \Symfony\Component\Form\FormInterface */
  426.         $form $builder->getForm();
  427.         $form->handleRequest($request);
  428.         if (!$form->isValid()) {
  429.             throw new NotFoundHttpException();
  430.         }
  431.         $addCartData $form->getData();
  432.         log_info(
  433.             'カート追加処理開始',
  434.             [
  435.                 'product_id' => $Product->getId(),
  436.                 'product_class_id' => $addCartData['product_class_id'],
  437.                 'quantity' => $addCartData['quantity'],
  438.             ]
  439.         );
  440.         // カートへ追加
  441.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  442.         // 明細の正規化
  443.         $Carts $this->cartService->getCarts();
  444.         foreach ($Carts as $Cart) {
  445.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  446.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  447.             if ($result->hasError()) {
  448.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  449.                 foreach ($result->getErrors() as $error) {
  450.                     $errorMessages[] = $error->getMessage();
  451.                 }
  452.             }
  453.             foreach ($result->getWarning() as $warning) {
  454.                 $errorMessages[] = $warning->getMessage();
  455.             }
  456.         }
  457.         $this->cartService->save();
  458.         log_info(
  459.             'カート追加処理完了',
  460.             [
  461.                 'product_id' => $Product->getId(),
  462.                 'product_class_id' => $addCartData['product_class_id'],
  463.                 'quantity' => $addCartData['quantity'],
  464.             ]
  465.         );
  466.         $event = new EventArgs(
  467.             [
  468.                 'form' => $form,
  469.                 'Product' => $Product,
  470.             ],
  471.             $request
  472.         );
  473.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  474.         if ($event->getResponse() !== null) {
  475.             return $event->getResponse();
  476.         }
  477.         if ($request->isXmlHttpRequest()) {
  478.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  479.             // 初期化
  480.             $messages = [];
  481.             if (empty($errorMessages)) {
  482.                 // エラーが発生していない場合
  483.                 $done true;
  484.                 array_push($messagestrans('front.product.add_cart_complete'));
  485.             } else {
  486.                 // エラーが発生している場合
  487.                 $done false;
  488.                 $messages $errorMessages;
  489.             }
  490.             return $this->json(['done' => $done'messages' => $messages]);
  491.         } else {
  492.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  493.             foreach ($errorMessages as $errorMessage) {
  494.                 $this->addRequestError($errorMessage);
  495.             }
  496.             return $this->redirectToRoute('cart');
  497.         }
  498.     }
  499.     /**
  500.      * ページタイトルの設定
  501.      *
  502.      * @param  array|null $searchData
  503.      *
  504.      * @return str
  505.      */
  506.     protected function getPageTitle($searchData)
  507.     {
  508.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  509.             return trans('front.product.search_result');
  510.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  511.             return $searchData['category_id']->getName();
  512.         } else {
  513.             return trans('front.product.all_products');
  514.         }
  515.     }
  516.     /**
  517.      * 閲覧可能な商品かどうかを判定
  518.      *
  519.      * @param Product $Product
  520.      *
  521.      * @return boolean 閲覧可能な場合はtrue
  522.      */
  523.     protected function checkVisibility(Product $Product)
  524.     {
  525.         $is_admin $this->session->has('_security_admin');
  526.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  527.         if (!$is_admin) {
  528.             // 在庫なし商品の非表示オプションが有効な場合.
  529.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  530.             //     if (!$Product->getStockFind()) {
  531.             //         return false;
  532.             //     }
  533.             // }
  534.             // 公開ステータスでない商品は表示しない.
  535.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  536.                 return false;
  537.             }
  538.         }
  539.         return true;
  540.     }
  541. }