app/Customize/Controller/CustomizeProductController.php line 221

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