src/Eccube/Controller/ProductController.php line 241

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 Eccube\Controller;
  13. use Eccube\Entity\BaseInfo;
  14. use Eccube\Entity\Customer;
  15. use Eccube\Entity\Master\ProductStatus;
  16. use Eccube\Entity\Product;
  17. use Eccube\Entity\ProductMakerSpec;
  18. use Eccube\Event\EccubeEvents;
  19. use Eccube\Event\EventArgs;
  20. use Eccube\Form\Type\AddCartType;
  21. use Eccube\Form\Type\Front\ProductDetailContactType;
  22. use Eccube\Form\Type\Master\ProductListMaxType;
  23. use Eccube\Form\Type\Master\ProductListOrderByType;
  24. use Eccube\Form\Type\SearchProductType;
  25. use Eccube\Repository\BaseInfoRepository;
  26. use Eccube\Repository\CustomerFavoriteProductRepository;
  27. use Eccube\Repository\Master\ProductListMaxRepository;
  28. use Eccube\Repository\ProductClassRepository;
  29. use Eccube\Repository\ProductRepository;
  30. use Eccube\Service\CartService;
  31. use Eccube\Service\MailService;
  32. use Eccube\Service\PurchaseFlow\PurchaseContext;
  33. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  34. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  35. use Knp\Component\Pager\PaginatorInterface;
  36. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  37. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  38. use Symfony\Component\HttpFoundation\Request;
  39. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  40. use Symfony\Component\Routing\Annotation\Route;
  41. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  42. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  43. use Psr\Log\LoggerInterface;
  44. class ProductController extends AbstractController
  45. {
  46.     /**
  47.      * @var MailService
  48.      */
  49.     protected $mailService;
  50.     /**
  51.      * @var PurchaseFlow
  52.      */
  53.     protected $purchaseFlow;
  54.     /**
  55.      * @var CustomerFavoriteProductRepository
  56.      */
  57.     protected $customerFavoriteProductRepository;
  58.     /**
  59.      * @var CartService
  60.      */
  61.     protected $cartService;
  62.     /**
  63.      * @var ProductRepository
  64.      */
  65.     protected $productRepository;
  66.     /**
  67.      * @var ProductClassRepository
  68.      */
  69.     protected $productClassRepository;
  70.     /**
  71.      * @var BaseInfo
  72.      */
  73.     protected $BaseInfo;
  74.     /**
  75.      * @var AuthenticationUtils
  76.      */
  77.     protected $helper;
  78.     /**
  79.      * @var ProductListMaxRepository
  80.      */
  81.     protected $productListMaxRepository;
  82.     private $title '';
  83.     /**
  84.      * ProductController constructor.
  85.      *
  86.      * @param PurchaseFlow $cartPurchaseFlow
  87.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  88.      * @param CartService $cartService
  89.      * @param ProductRepository $productRepository
  90.      * @param ProductClassRepository $productClassRepository
  91.      * @param BaseInfoRepository $baseInfoRepository
  92.      * @param AuthenticationUtils $helper
  93.      * @param ProductListMaxRepository $productListMaxRepository
  94.      * @param MailService $mailService
  95.      */
  96.     public function __construct(
  97.         PurchaseFlow $cartPurchaseFlow,
  98.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  99.         CartService $cartService,
  100.         ProductRepository $productRepository,
  101.         ProductClassRepository $productClassRepository,
  102.         BaseInfoRepository $baseInfoRepository,
  103.         AuthenticationUtils $helper,
  104.         ProductListMaxRepository $productListMaxRepository,
  105.         MailService $mailService
  106.     ) {
  107.         $this->purchaseFlow $cartPurchaseFlow;
  108.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  109.         $this->cartService $cartService;
  110.         $this->productRepository $productRepository;
  111.         $this->productClassRepository $productClassRepository;
  112.         $this->BaseInfo $baseInfoRepository->get();
  113.         $this->helper $helper;
  114.         $this->productListMaxRepository $productListMaxRepository;
  115.         $this->mailService $mailService;
  116.     }
  117.     /**
  118.      * 商品一覧画面.
  119.      *
  120.      * @Route("/products/list", name="product_list", methods={"GET"})
  121.      * @Template("Product/list.twig")
  122.      */
  123.     public function index(Request $requestPaginatorInterface $paginator)
  124.     {
  125.         // Doctrine SQLFilter
  126.         if ($this->BaseInfo->isOptionNostockHidden()) {
  127.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  128.         }
  129.         // handleRequestは空のqueryの場合は無視するため
  130.         if ($request->getMethod() === 'GET') {
  131.             $request->query->set('pageno'$request->query->get('pageno'''));
  132.         }
  133.         // searchForm
  134.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  135.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  136.         if ($request->getMethod() === 'GET') {
  137.             $builder->setMethod('GET');
  138.         }
  139.         $event = new EventArgs(
  140.             [
  141.                 'builder' => $builder,
  142.             ],
  143.             $request
  144.         );
  145.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  146.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  147.         $searchForm $builder->getForm();
  148.         $searchForm->handleRequest($request);
  149.         // paginator
  150.         $searchData $searchForm->getData();
  151.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  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.         // メンテナンスフラグを確認
  214.         $maintenanceMode env('MAINTENANCE_MODE'false);
  215.         if ($maintenanceMode) {
  216.             return $this->redirectToRoute('maintenance_page');
  217.         }
  218.         $builder $this->formFactory->createBuilder(ProductDetailContactType::class);
  219.         if ($this->isGranted('ROLE_USER')) {
  220.             /** @var Customer $user */
  221.             $user $this->getUser();
  222.             $builder->setData(
  223.                 [
  224.                     'email' => $user->getEmail(),
  225.                 ]
  226.             );
  227.         }
  228.         // FRONT_CONTACT_INDEX_INITIALIZE
  229.         $event = new EventArgs(
  230.             [
  231.                 'builder' => $builder,
  232.             ],
  233.             $request
  234.         );
  235.         $this->eventDispatcher->dispatch($event,EccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  236.         $contactform $builder->getForm();
  237.         $contactform->handleRequest($request);
  238.         if ($contactform->isSubmitted() && $contactform->isValid()) {
  239.             switch ($request->get('mode')) {
  240.                 case 'confirm':
  241.                     return $this->redirectToRoute('product_detail_contact', array(
  242.                         'request' => $request,
  243.                     ), 307);
  244.             }
  245.         }
  246.         if (!$this->checkVisibility($Product)) {
  247.             throw new NotFoundHttpException();
  248.         }
  249.         $builder $this->formFactory->createNamedBuilder(
  250.             '',
  251.             AddCartType::class,
  252.             null,
  253.             [
  254.                 'product' => $Product,
  255.                 'id_add_product_id' => false,
  256.             ]
  257.         );
  258.         $event = new EventArgs(
  259.             [
  260.                 'builder' => $builder,
  261.                 'Product' => $Product,
  262.             ],
  263.             $request
  264.         );
  265.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  266.         $is_favorite false;
  267.         if ($this->isGranted('ROLE_USER')) {
  268.             $Customer $this->getUser();
  269.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  270.         }
  271.         return [
  272.             'title' => $this->title,
  273.             'subtitle' => $Product->getName(),
  274.             'form' => $builder->getForm()->createView(),
  275.             'contactform' => $contactform->createView(),
  276.             'Product' => $Product,
  277.             'is_favorite' => $is_favorite,
  278.         ];
  279.     }
  280.     /**
  281.      * メンテナンス画面.
  282.      *
  283.      * @Route("/maintenance", name="maintenance_page", methods={"GET"})
  284.      * @Template("Product/maintenance.twig")
  285.      *
  286.      * @return array
  287.      */
  288.     public function maintenance()
  289.     {
  290.         return  [
  291.             'maintenance_period' => '2024/12/23 - 2024/12/27',
  292.             'phone' => '0748-31-0711',
  293.             'email' => 'printer@up-tempo.co.jp',
  294.         ];
  295.     }
  296.     /**
  297. * 商品詳細問い合わせ画面.
  298.      *
  299.      * @Route("/products/contact", name="product_detail_contact", methods={"POST"})
  300.      * @Template("Product/Contact/confirm.twig")
  301.      *
  302.      * @param Request $request
  303.      *
  304.      * @return array
  305.      */
  306.     public function contact(Request $request)
  307.     {
  308.         $builder $this->formFactory->createBuilder(ProductDetailContactType::class);
  309.         $builder->setData(
  310.             [
  311.                 'email' => $request->request->get('contact')['email'],
  312.                 'contents' => $request->request->get('contact')['contents'],
  313.             ]
  314.         );
  315.         // FRONT_CONTACT_INDEX_INITIALIZE
  316.         $event = new EventArgs(
  317.             [
  318.                 'builder' => $builder,
  319.             ],
  320.             $request
  321.         );
  322.         $this->eventDispatcher->dispatch($event,EccubeEvents::FRONT_PRODUCT_DETAIL_CONTACT);
  323.         $form $builder->getForm();
  324.         $form->handleRequest($request);
  325.         if ($form->isSubmitted() && $form->isValid()) {
  326.             switch ($request->get('mode')) {
  327.                 case 'confirm':
  328.                     $form $builder->getForm();
  329.                     $form->handleRequest($request);
  330.                     return $this->render('Product/Contact/confirm.twig', [
  331.                         'form' => $form->createView(),
  332.                     ]);
  333.                 case 'complete':
  334.                     $data $form->getData();
  335.                     $event = new EventArgs(
  336.                         [
  337.                             'form' => $form,
  338.                             'data' => $data,
  339.                         ],
  340.                         $request
  341.                     );
  342.                     $this->eventDispatcher->dispatch($event,EccubeEvents::FRONT_CONTACT_INDEX_COMPLETE);
  343.                     $data $event->getArgument('data');
  344.                     // メール送信
  345.                     $this->mailService->sendContactMail($data);
  346.                     return $this->redirect($this->generateUrl('contact_complete'));
  347.             }
  348.         }
  349.         return [
  350.             'form' => $builder->getForm()->createView(),
  351.         ];
  352.     }
  353.     /**
  354.      * お問い合わせ完了画面.
  355.      *
  356.      * @Route("/contact/complete", name="contact_complete")
  357.      * @Template("Contact/complete.twig")
  358.      */
  359.     public function complete()
  360.     {
  361.         return [];
  362.     }
  363.     /**
  364.      * お気に入り追加.
  365.      *
  366.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  367.      */
  368.     public function addFavorite(Request $requestProduct $Product)
  369.     {
  370.         $this->checkVisibility($Product);
  371.         $event = new EventArgs(
  372.             [
  373.                 'Product' => $Product,
  374.             ],
  375.             $request
  376.         );
  377.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  378.         if ($this->isGranted('ROLE_USER')) {
  379.             $Customer $this->getUser();
  380.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  381.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  382.             $event = new EventArgs(
  383.                 [
  384.                     'Product' => $Product,
  385.                 ],
  386.                 $request
  387.             );
  388.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  389.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  390.         } else {
  391.             // 非会員の場合、ログイン画面を表示
  392.             //  ログイン後の画面遷移先を設定
  393.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  394.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  395.             $event = new EventArgs(
  396.                 [
  397.                     'Product' => $Product,
  398.                 ],
  399.                 $request
  400.             );
  401.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  402.             return $this->redirectToRoute('mypage_login');
  403.         }
  404.     }
  405.     /**
  406.      * カートに追加.
  407.      *
  408.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  409.      */
  410.     public function addCart(Request $requestProduct $ProductLoggerInterface $logger)
  411.     {
  412.         $logger->info("LOG TEST STARTED NIBIRU");
  413.         $logger->info(
  414.             'Request Data',
  415.             [
  416.                 'request' => $request->request->all(),
  417.             ]
  418.         );
  419.         // エラーメッセージの配列
  420.         $errorMessages = [];
  421.         if (!$this->checkVisibility($Product)) {
  422.             throw new NotFoundHttpException();
  423.         }
  424.         $builder $this->formFactory->createNamedBuilder(
  425.             '',
  426.             AddCartType::class,
  427.             null,
  428.             [
  429.                 'product' => $Product,
  430.                 'id_add_product_id' => false,
  431.             ]
  432.         );
  433.         $event = new EventArgs(
  434.             [
  435.                 'builder' => $builder,
  436.                 'Product' => $Product,
  437.             ],
  438.             $request
  439.         );
  440.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  441.         /* @var $form \Symfony\Component\Form\FormInterface */
  442.         $form $builder->getForm();
  443.         $form->handleRequest($request);
  444.         $logger->info(
  445.             'Form Data before Validation',
  446.             [
  447.                 'formData' => $form->getData(),
  448.             ]
  449.         );
  450.         if (!$form->isValid()) {
  451.             $logger->info(
  452.                 'AddCartType Validation Errors',
  453.                 [
  454.                     'errors' => (string) $form->getErrors(truefalse),
  455.                 ]
  456.             );
  457.             throw new NotFoundHttpException();
  458.         }
  459.         // フォームデータを取得
  460.         $addCartData $form->getData();
  461.         // 商品クラスを条件に基づいて検索
  462.         $productClassId = (int) $request->request->get('product_class_id');
  463.         $classCategoryId1 = (int) $request->request->get('classcategory_id1');
  464.         $classCategoryId2 = (int) $request->request->get('classcategory_id2');
  465.         $quantity = (int) $request->request->get('quantity');
  466.         $logger->info('検索条件', [
  467.             'product_id' => $Product->getId(),
  468.             'class_category_id1' => $classCategoryId1,
  469.             'class_category_id2' => $classCategoryId2,
  470.             'quantity' => $quantity,
  471.         ]);
  472.         $ProductClass $this->cartService->findProductClassByConditions(
  473.             $Product->getId(),
  474.             $classCategoryId1,
  475.             $classCategoryId2,
  476.             $logger
  477.         );
  478.         if (!$ProductClass) {
  479.             $logger->error('ProductClass not found', [
  480.                 'product_id' => $Product->getId(),
  481.                 'class_category_id1' => $classCategoryId1,
  482.                 'class_category_id2' => $classCategoryId2,
  483.                 'quantity' => $quantity,
  484.             ]);
  485.             throw new NotFoundHttpException('商品クラスが見つかりません。');
  486.         }
  487.         $logger->info(
  488.             'カート追加処理開始',
  489.             [
  490.                 'product_id' => $Product->getId(),
  491.                 'product_class_id' => $ProductClass->getId(),
  492.                 'quantity' => $addCartData['quantity'],
  493.             ]
  494.         );
  495.         // カートへ追加
  496.         $this->cartService->addProduct($ProductClass, (int)$addCartData['quantity']);
  497.         // 明細の正規化
  498.         $Carts $this->cartService->getCarts();
  499.         foreach ($Carts as $Cart) {
  500.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  501.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  502.             if ($result->hasError()) {
  503.                 $this->cartService->removeProduct($ProductClass);
  504.                 foreach ($result->getErrors() as $error) {
  505.                     $errorMessages[] = $error->getMessage();
  506.                 }
  507.             }
  508.             foreach ($result->getWarning() as $warning) {
  509.                 $errorMessages[] = $warning->getMessage();
  510.             }
  511.         }
  512.         $this->cartService->save();
  513.         $logger->info(
  514.             'カート追加処理完了',
  515.             [
  516.                 'product_id' => $Product->getId(),
  517.                 'product_class_id' => $ProductClass->getId(),
  518.                 'quantity' => $addCartData['quantity'],
  519.             ]
  520.         );
  521.         $event = new EventArgs(
  522.             [
  523.                 'form' => $form,
  524.                 'Product' => $Product,
  525.             ],
  526.             $request
  527.         );
  528.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  529.         if ($event->getResponse() !== null) {
  530.             return $event->getResponse();
  531.         }
  532.         if ($request->isXmlHttpRequest()) {
  533.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  534.             $done = empty($errorMessages);
  535.             $messages $done ? [trans('front.product.add_cart_complete')] : $errorMessages;
  536.             if (!$done) {
  537.                 $logger->info(
  538.                     'カート追加処理失敗',
  539.                     [
  540.                         'messages' => $messages,
  541.                     ]
  542.                 );
  543.             }
  544.             return $this->json(['done' => $done'messages' => $messages]);
  545.         } else {
  546.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  547.             foreach ($errorMessages as $errorMessage) {
  548.                 $this->addRequestError($errorMessage);
  549.             }
  550.             return $this->redirectToRoute('cart');
  551.         }
  552.     }
  553.     /**
  554.      * ページタイトルの設定
  555.      *
  556.      * @param  null|array $searchData
  557.      *
  558.      * @return str
  559.      */
  560.     protected function getPageTitle($searchData)
  561.     {
  562.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  563.             return trans('front.product.search_result');
  564.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  565.             return $searchData['category_id']->getName();
  566.         } else {
  567.             return trans('front.product.all_products');
  568.         }
  569.     }
  570.     /**
  571.      * 閲覧可能な商品かどうかを判定
  572.      *
  573.      * @param Product $Product
  574.      *
  575.      * @return boolean 閲覧可能な場合はtrue
  576.      */
  577.     protected function checkVisibility(Product $Product)
  578.     {
  579.         $is_admin $this->session->has('_security_admin');
  580.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  581.         if (!$is_admin) {
  582.             // 在庫なし商品の非表示オプションが有効な場合.
  583.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  584.             //     if (!$Product->getStockFind()) {
  585.             //         return false;
  586.             //     }
  587.             // }
  588.             // 公開ステータスでない商品は表示しない.
  589.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  590.                 return false;
  591.             }
  592.         }
  593.         return true;
  594.     }
  595. }