app/Customize/Controller/MyOrderListController.php line 112

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\Controller\AbstractController;
  14. use Eccube\Entity\BaseInfo;
  15. use Eccube\Entity\Master\ProductStatus;
  16. use Eccube\Entity\Product;
  17. use Eccube\Event\EccubeEvents;
  18. use Eccube\Event\EventArgs;
  19. use Eccube\Form\Type\AddCartType;
  20. use Eccube\Form\Type\SearchProductType;
  21. use Eccube\Repository\BaseInfoRepository;
  22. use Eccube\Repository\CustomerFavoriteProductRepository;
  23. use Eccube\Repository\Master\ProductListMaxRepository;
  24. use Eccube\Repository\OrderRepository;
  25. use Eccube\Repository\ProductRepository;
  26. use Eccube\Service\CartService;
  27. use Eccube\Service\PurchaseFlow\PurchaseContext;
  28. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  29. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  30. use Knp\Component\Pager\PaginatorInterface;
  31. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  32. use Symfony\Component\HttpFoundation\Request;
  33. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  34. use Symfony\Component\Routing\Annotation\Route;
  35. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  36. class MyOrderListController extends AbstractController
  37. {
  38.     /**
  39.      * @var PurchaseFlow
  40.      */
  41.     protected $purchaseFlow;
  42.     /**
  43.      * @var CustomerFavoriteProductRepository
  44.      */
  45.     protected $customerFavoriteProductRepository;
  46.     /**
  47.      * @var CartService
  48.      */
  49.     protected $cartService;
  50.     /**
  51.      * @var ProductRepository
  52.      */
  53.     protected $productRepository;
  54.     /**
  55.      * @var BaseInfo
  56.      */
  57.     protected $BaseInfo;
  58.     /**
  59.      * @var ProductListMaxRepository
  60.      */
  61.     protected $productListMaxRepository;
  62.     /**
  63.      * @var OrderRepository
  64.      */
  65.     protected $orderRepository;
  66.     /**
  67.      * MyOrderListController constructor.
  68.      *
  69.      * @param PurchaseFlow $cartPurchaseFlow
  70.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  71.      * @param CartService $cartService
  72.      * @param ProductRepository $productRepository
  73.      * @param BaseInfoRepository $baseInfoRepository
  74.      * @param ProductListMaxRepository $productListMaxRepository
  75.      * @param OrderRepository $orderRepository
  76.      */
  77.     public function __construct(
  78.         PurchaseFlow $cartPurchaseFlow,
  79.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  80.         CartService $cartService,
  81.         ProductRepository $productRepository,
  82.         BaseInfoRepository $baseInfoRepository,
  83.         ProductListMaxRepository $productListMaxRepository,
  84.         OrderRepository $orderRepository
  85.     ) {
  86.         $this->purchaseFlow $cartPurchaseFlow;
  87.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  88.         $this->cartService $cartService;
  89.         $this->productRepository $productRepository;
  90.         $this->BaseInfo $baseInfoRepository->get();
  91.         $this->productListMaxRepository $productListMaxRepository;
  92.         $this->orderRepository $orderRepository;
  93.     }
  94.     /**
  95.      * お気に入り商品一覧画面.
  96.      *
  97.      * @Route("/my_order_list/favorite", name="my_order_list_favorite", methods={"GET"})
  98.      * @Template("MyOrderList/favorite.twig")
  99.      */
  100.     public function index(Request $requestPaginatorInterface $paginator)
  101.     {
  102.         if (!$this->BaseInfo->isOptionFavoriteProduct()) {
  103.             throw new NotFoundHttpException();
  104.         }
  105.         if (!$this->isGranted('ROLE_USER')) {
  106.             $this->setLoginTargetPath($this->generateUrl('my_order_list_favorite', [], UrlGeneratorInterface::ABSOLUTE_URL));
  107.             return $this->redirectToRoute('mypage_login');
  108.         }
  109.         $Customer $this->getUser();
  110.         // Doctrine SQLFilter
  111.         if ($this->BaseInfo->isOptionNostockHidden()) {
  112.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  113.         }
  114.         // handleRequestは空のqueryの場合は無視するため
  115.         if ($request->getMethod() === 'GET') {
  116.             $request->query->set('pageno'$request->query->get('pageno'''));
  117.         }
  118.         // searchForm
  119.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  120.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  121.         if ($request->getMethod() === 'GET') {
  122.             $builder->setMethod('GET');
  123.         }
  124.         $event = new EventArgs(
  125.             [
  126.                 'builder' => $builder,
  127.             ],
  128.             $request
  129.         );
  130.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  131.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  132.         $searchForm $builder->getForm();
  133.         $searchForm->handleRequest($request);
  134.         // paginator
  135.         $searchData $searchForm->getData();
  136.         $qb $this->customerFavoriteProductRepository->getQueryBuilderByCustomerWithSearchData($Customer$searchData);
  137.         $event = new EventArgs(
  138.             [
  139.                 'searchData' => $searchData,
  140.                 'qb' => $qb,
  141.                 'Customer' => $Customer,
  142.             ],
  143.             $request
  144.         );
  145.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_MYPAGE_MYPAGE_FAVORITE_SEARCH);
  146.         $searchData $event->getArgument('searchData');
  147.         $query $qb->getQuery();
  148.         /** @var SlidingPagination $pagination */
  149.         $pagination $paginator->paginate(
  150.             $query,
  151.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  152.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId(),
  153.             ['wrap-queries' => true]
  154.         );
  155.         $ids = [];
  156.         foreach ($pagination as $FavoriteProduct) {
  157.             $ids[] = $FavoriteProduct->getProduct()->getId();
  158.         }
  159.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  160.         // 注文回数を計算
  161.         $orderCounts = [];
  162.         // 前回注文情報を取得
  163.         $lastOrders = [];
  164.         if (!empty($ids)) {
  165.             $qb $this->entityManager->createQueryBuilder();
  166.             $qb->select('p.id as product_id, COUNT(DISTINCT oi.id) as order_count')
  167.                 ->from('Eccube\Entity\OrderItem''oi')
  168.                 ->innerJoin('oi.Order''o')
  169.                 ->innerJoin('oi.OrderItemType''oit')
  170.                 ->innerJoin('oi.Product''p')
  171.                 ->where('p.id IN (:product_ids)')
  172.                 ->andWhere('o.Customer = :customer')
  173.                 ->andWhere('o.order_date IS NOT NULL')
  174.                 ->andWhere('o.OrderStatus IN (:orderStatuses)')
  175.                 ->andWhere('oit.id = :productItemType')
  176.                 ->setParameter('product_ids'$ids)
  177.                 ->setParameter('customer'$Customer)
  178.                 ->setParameter('productItemType'\Eccube\Entity\Master\OrderItemType::PRODUCT)
  179.                 ->setParameter('orderStatuses', [
  180.                     \Eccube\Entity\Master\OrderStatus::NEW,
  181.                     \Eccube\Entity\Master\OrderStatus::PAID,
  182.                     \Eccube\Entity\Master\OrderStatus::IN_PROGRESS,
  183.                     \Eccube\Entity\Master\OrderStatus::DELIVERED,
  184.                 ])
  185.                 ->groupBy('p.id');
  186.             $results $qb->getQuery()->getResult();
  187.             foreach ($results as $result) {
  188.                 $orderCounts[$result['product_id']] = (int)$result['order_count'];
  189.             }
  190.             // 前回注文情報を取得(各商品の最新の注文)
  191.             $qb $this->entityManager->createQueryBuilder();
  192.             $qb->select('p.id as product_id, o.order_date as order_date, oi.quantity as quantity, pc.id as product_class_id, st.name as unit_name, cc1.name as class_category_name1, cc2.name as class_category_name2')
  193.                 ->from('Eccube\Entity\OrderItem''oi')
  194.                 ->innerJoin('oi.Order''o')
  195.                 ->innerJoin('oi.OrderItemType''oit')
  196.                 ->innerJoin('oi.Product''p')
  197.                 ->leftJoin('oi.ProductClass''pc')
  198.                 ->leftJoin('pc.SaleType''st')
  199.                 ->leftJoin('pc.ClassCategory1''cc1')
  200.                 ->leftJoin('pc.ClassCategory2''cc2')
  201.                 ->where('p.id IN (:product_ids)')
  202.                 ->andWhere('o.Customer = :customer')
  203.                 ->andWhere('o.order_date IS NOT NULL')
  204.                 ->andWhere('o.OrderStatus IN (:orderStatuses)')
  205.                 ->andWhere('oit.id = :productItemType')
  206.                 ->setParameter('product_ids'$ids)
  207.                 ->setParameter('customer'$Customer)
  208.                 ->setParameter('productItemType'\Eccube\Entity\Master\OrderItemType::PRODUCT)
  209.                 ->setParameter('orderStatuses', [
  210.                     \Eccube\Entity\Master\OrderStatus::NEW,
  211.                     \Eccube\Entity\Master\OrderStatus::PAID,
  212.                     \Eccube\Entity\Master\OrderStatus::IN_PROGRESS,
  213.                     \Eccube\Entity\Master\OrderStatus::DELIVERED,
  214.                 ])
  215.                 ->orderBy('o.order_date''DESC');
  216.             $lastOrderResults $qb->getQuery()->getResult();
  217.             // 各商品について最新の注文を取得
  218.             foreach ($lastOrderResults as $result) {
  219.                 $productId $result['product_id'];
  220.                 if (!isset($lastOrders[$productId])) {
  221.                     $lastOrders[$productId] = [
  222.                         'date' => $result['order_date'],
  223.                         'quantity' => $result['quantity'],
  224.                         'product_class_id' => $result['product_class_id'],
  225.                         'unit_name' => $result['unit_name'] ?: '',
  226.                         'class_category_name1' => $result['class_category_name1'] ?: '1',
  227.                         'class_category_name2' => $result['class_category_name2'] ?: '1',
  228.                     ];
  229.                 }
  230.             }
  231.         }
  232.         // addCart form
  233.         $forms = [];
  234.         foreach ($pagination as $FavoriteProduct) {
  235.             $Product $FavoriteProduct->getProduct();
  236.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  237.             $builder $this->formFactory->createNamedBuilder(
  238.                 '',
  239.                 AddCartType::class,
  240.                 null,
  241.                 [
  242.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  243.                     'allow_extra_fields' => true,
  244.                 ]
  245.             );
  246.             $addCartForm $builder->getForm();
  247.             $forms[$Product->getId()] = $addCartForm->createView();
  248.         }
  249.         $Category $searchForm->get('category_id')->getData();
  250.         return [
  251.             'subtitle' => $this->getPageTitle($searchData),
  252.             'pagination' => $pagination,
  253.             'search_form' => $searchForm->createView(),
  254.             'forms' => $forms,
  255.             'Category' => $Category,
  256.             'order_counts' => $orderCounts,
  257.             'last_orders' => $lastOrders,
  258.         ];
  259.     }
  260.     /**
  261.      * 注文履歴一覧画面.
  262.      *
  263.      * @Route("/my_order_list/history", name="my_order_list_history", methods={"GET"})
  264.      * @Template("MyOrderList/history.twig")
  265.      */
  266.     public function history(Request $requestPaginatorInterface $paginator)
  267.     {
  268.         if (!$this->isGranted('ROLE_USER')) {
  269.             $this->setLoginTargetPath($this->generateUrl('my_order_list_history', [], UrlGeneratorInterface::ABSOLUTE_URL));
  270.             return $this->redirectToRoute('mypage_login');
  271.         }
  272.         $Customer $this->getUser();
  273.         // 購入処理中/決済処理中ステータスの受注を非表示にする
  274.         $this->entityManager->getFilters()->enable('incomplete_order_status_hidden');
  275.         // SearchProductType で GET パラメータ(stock, price_range, pageno)を取得
  276.         if ($request->getMethod() === 'GET') {
  277.             $request->query->set('pageno'$request->query->get('pageno'''));
  278.         }
  279.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class)->setMethod('GET');
  280.         $searchForm $builder->getForm();
  281.         $searchForm->handleRequest($request);
  282.         $searchData $searchForm->getData();
  283.         $qb $this->orderRepository->getQueryBuilderByCustomerWithSearchData($Customer$searchData);
  284.         $hasStock = isset($searchData['stock']) && $searchData['stock'];
  285.         $hasPriceRange = isset($searchData['price_range']) && !empty($searchData['price_range']) && is_array($searchData['price_range']);
  286.         $pageno max(1, (int) (!empty($searchData['pageno']) ? $searchData['pageno'] : $request->get('pageno'1)));
  287.         $pagination $paginator->paginate(
  288.             $qb,
  289.             $pageno,
  290.             $this->eccubeConfig['eccube_search_pmax']
  291.         );
  292.         // 注文×商品ごとに1フォームを用意(同一フォームの二重レンダーを防ぐ)。絞り込み時は条件を満たす OrderItem のみ追加
  293.         $orderItemFormsByOrder = [];
  294.         $orders $pagination->getItems();
  295.         $productIds = [];
  296.         foreach ($orders as $Order) {
  297.             foreach ($Order->getProductOrderItems() as $OrderItem) {
  298.                 $Product $OrderItem->getProduct();
  299.                 if (!$Product) {
  300.                     continue;
  301.                 }
  302.                 if ($hasStock || $hasPriceRange) {
  303.                     if (!$this->orderRepository->productMatchesHistoryFilters($Product$searchData)) {
  304.                         continue;
  305.                     }
  306.                 }
  307.                 $productIds[] = $Product->getId();
  308.             }
  309.         }
  310.         $productIds array_unique($productIds);
  311.         $ProductsAndClassCategories = !empty($productIds)
  312.             ? $this->productRepository->findProductsWithSortedClassCategories($productIds'p.id')
  313.             : [];
  314.         foreach ($orders as $Order) {
  315.             $orderItemFormsByOrder[$Order->getId()] = [];
  316.             foreach ($Order->getProductOrderItems() as $OrderItem) {
  317.                 $Product $OrderItem->getProduct();
  318.                 if (!$Product || !isset($ProductsAndClassCategories[$Product->getId()])) {
  319.                     continue;
  320.                 }
  321.                 if ($hasStock || $hasPriceRange) {
  322.                     if (!$this->orderRepository->productMatchesHistoryFilters($Product$searchData)) {
  323.                         continue;
  324.                     }
  325.                 }
  326.                 $builder $this->formFactory->createNamedBuilder(
  327.                     '',
  328.                     AddCartType::class,
  329.                     null,
  330.                     [
  331.                         'product' => $ProductsAndClassCategories[$Product->getId()],
  332.                         'allow_extra_fields' => true,
  333.                     ]
  334.                 );
  335.                 $addCartForm $builder->getForm();
  336.                 $addCartForm->get('quantity')->setData($OrderItem->getQuantity());
  337.                 $orderItemFormsByOrder[$Order->getId()][] = [
  338.                     'orderItem' => $OrderItem,
  339.                     'form' => $addCartForm->createView(),
  340.                 ];
  341.             }
  342.         }
  343.         return [
  344.             'pagination' => $pagination,
  345.             'orderItemFormsByOrder' => $orderItemFormsByOrder,
  346.         ];
  347.     }
  348.     /**
  349.      * ページタイトルの設定
  350.      *
  351.      * @param  array|null $searchData
  352.      *
  353.      * @return str
  354.      */
  355.     protected function getPageTitle($searchData)
  356.     {
  357.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  358.             return trans('front.product.search_result');
  359.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  360.             return $searchData['category_id']->getName();
  361.         } else {
  362.             return trans('front.mypage.nav__favorite');
  363.         }
  364.     }
  365. }