app/Customize/Controller/ProductController.php line 111

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 Customize\Service\CountryWidgetService;
  14. use Customize\Form\Type\SearchProductType;
  15. use Eccube\Controller\ProductController as BaseProductController;
  16. use Eccube\Repository\CategoryRepository;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use Psr\Container\ContainerInterface;
  19. use Knp\Component\Pager\PaginatorInterface;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  23. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  24. use Eccube\Repository\CustomerFavoriteProductRepository;
  25. use Eccube\Service\CartService;
  26. use Customize\Repository\ProductRepository;
  27. use Eccube\Repository\BaseInfoRepository;
  28. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  29. use Eccube\Repository\Master\ProductListMaxRepository;
  30. use Eccube\Helper\PageNameHelper;
  31. use Customize\Service\BreadcrumbService;
  32. class ProductController extends BaseProductController
  33. {
  34.     /**
  35.      * @var CountryWidgetService
  36.      */
  37.     protected $countryWidgetService;
  38.     /**
  39.      * @var CategoryRepository
  40.      */
  41.     protected $categoryRepository;
  42.     /**
  43.      * @var EntityManagerInterface
  44.      */
  45.     protected $entityManager;
  46.     /**
  47.      * ProductController constructor.
  48.      *
  49.      * @param PurchaseFlow $cartPurchaseFlow
  50.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  51.      * @param CartService $cartService
  52.      * @param ProductRepository $productRepository
  53.      * @param BaseInfoRepository $baseInfoRepository
  54.      * @param AuthenticationUtils $helper
  55.      * @param ProductListMaxRepository $productListMaxRepository
  56.      * @param PageNameHelper $pageNameHelper
  57.      * @param BreadcrumbService $breadcrumbService
  58.      * @param CountryWidgetService $countryWidgetService
  59.      * @param CategoryRepository $categoryRepository
  60.      * @param EntityManagerInterface $entityManager
  61.      */
  62.     public function __construct(
  63.         PurchaseFlow $cartPurchaseFlow,
  64.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  65.         CartService $cartService,
  66.         ProductRepository $productRepository,
  67.         BaseInfoRepository $baseInfoRepository,
  68.         AuthenticationUtils $helper,
  69.         ProductListMaxRepository $productListMaxRepository,
  70.         PageNameHelper $pageNameHelper,
  71.         BreadcrumbService $breadcrumbService,
  72.         CountryWidgetService $countryWidgetService,
  73.         CategoryRepository $categoryRepository,
  74.         EntityManagerInterface $entityManager
  75.     ) {
  76.         parent::__construct(
  77.             $cartPurchaseFlow,
  78.             $customerFavoriteProductRepository,
  79.             $cartService,
  80.             $productRepository,
  81.             $baseInfoRepository,
  82.             $helper,
  83.             $productListMaxRepository,
  84.             $pageNameHelper,
  85.             $breadcrumbService
  86.         );
  87.         $this->countryWidgetService $countryWidgetService;
  88.         $this->categoryRepository $categoryRepository;
  89.         $this->entityManager $entityManager;
  90.     }
  91.     /**
  92.      * 商品一覧画面.
  93.      *
  94.      * @Route("/products/list", name="product_list", methods={"GET"})
  95.      * @Template("Product/list.twig")
  96.      */
  97.     public function index(Request $requestPaginatorInterface $paginator)
  98.     {
  99.         // Doctrine SQLFilter
  100.         if ($this->BaseInfo->isOptionNostockHidden()) {
  101.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  102.         }
  103.         // handleRequestは空のqueryの場合は無視するため
  104.         if ($request->getMethod() === 'GET') {
  105.             $request->query->set('pageno'$request->query->get('pageno'''));
  106.         }
  107.         // searchForm - Sử dụng custom SearchProductType
  108.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  109.         $searchProductType = new \Customize\Form\Type\SearchProductType(
  110.             $this->categoryRepository,
  111.             $this->entityManager
  112.         );
  113.         $builder $this->formFactory->createNamedBuilder(''get_class($searchProductType));
  114.         if ($request->getMethod() === 'GET') {
  115.             $builder->setMethod('GET');
  116.         }
  117.         $event = new \Eccube\Event\EventArgs(
  118.             [
  119.                 'builder' => $builder,
  120.             ],
  121.             $request
  122.         );
  123.         $this->eventDispatcher->dispatch($event, \Eccube\Event\EccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  124.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  125.         $searchForm $builder->getForm();
  126.         $searchForm->handleRequest($request);
  127.         // paginator
  128.         $searchData $searchForm->getData();
  129.         // Lấy category_filter[] từ request nếu có
  130.         $categoryFilters $request->query->get('category_filter', []);
  131.         if (!empty($categoryFilters)) {
  132.             $searchData['category_filter'] = is_array($categoryFilters) ? $categoryFilters : [$categoryFilters];
  133.         }
  134.         // Sử dụng custom ProductRepository để có logic filter theo country
  135.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  136.         $event = new \Eccube\Event\EventArgs(
  137.             [
  138.                 'searchData' => $searchData,
  139.                 'qb' => $qb,
  140.             ],
  141.             $request
  142.         );
  143.         $this->eventDispatcher->dispatch($event, \Eccube\Event\EccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  144.         $searchData $event->getArgument('searchData');
  145.         $query $qb->getQuery()
  146.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  147.         // Xác định số sản phẩm mỗi trang: mặc định là 12
  148.         // Chỉ sử dụng giá trị từ form nếu user thực sự chọn (có trong request parameter)
  149.         $itemsPerPage 12// Mặc định 12 sản phẩm
  150.         $dispNumberFromRequest $request->query->get('disp_number');
  151.         if (!empty($dispNumberFromRequest)) {
  152.             // Nếu có giá trị từ request, tìm ProductListMax entity
  153.             $selectedDispNumber $this->entityManager->getRepository(\Eccube\Entity\Master\ProductListMax::class)->find($dispNumberFromRequest);
  154.             if ($selectedDispNumber) {
  155.                 $itemsPerPage $selectedDispNumber->getId(); // ID chính là số sản phẩm
  156.             }
  157.         }
  158.         // Bỏ qua giá trị từ searchData vì form có thể tự động set giá trị mặc định (10)
  159.         // Chỉ dùng giá trị từ request parameter nếu user thực sự chọn
  160.         /** @var SlidingPagination $pagination */
  161.         $pagination $paginator->paginate(
  162.             $query,
  163.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  164.             $itemsPerPage
  165.         );
  166.         $ids = [];
  167.         foreach ($pagination as $Product) {
  168.             $ids[] = $Product->getId();
  169.         }
  170.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  171.         // addCart form
  172.         $forms = [];
  173.         foreach ($pagination as $Product) {
  174.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  175.             $builder $this->formFactory->createNamedBuilder(
  176.                 '',
  177.                 \Eccube\Form\Type\AddCartType::class,
  178.                 null,
  179.                 [
  180.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  181.                     'allow_extra_fields' => true,
  182.                 ]
  183.             );
  184.             $addCartForm $builder->getForm();
  185.             $forms[$Product->getId()] = $addCartForm->createView();
  186.         }
  187.         $Category $searchForm->get('category_id')->getData();
  188.         $FreeArea '';
  189.         $ListProductAttribute null;
  190.         // Kiểm tra nếu có sản phẩm trong pagination thì lấy FreeArea từ sản phẩm đầu tiên
  191.         if ($pagination->count() > 0) {
  192.             $firstProduct $pagination->getItems()[0] ?? null;
  193.             if ($firstProduct) {
  194.                 $FreeArea $firstProduct->getFreeArea();
  195.                 if ($FreeArea) {
  196.                     $ListProductAttribute = [];
  197.                     $lines preg_split('/\r\n|\r|\n/'$FreeArea);
  198.                     foreach ($lines as $line) {
  199.                         if (trim($line) === '') continue;
  200.                         $parts explode(':'$line2);
  201.                         if (count($parts) == 2) {
  202.                             $ListProductAttribute[] = [trim($parts[0]), trim($parts[1])];
  203.                         }
  204.                     }
  205.                     if (count($ListProductAttribute) === 0) {
  206.                         $ListProductAttribute null;
  207.                     }
  208.                 }
  209.             }
  210.         }
  211.         $categoryId null;
  212.         $prefix null;
  213.         if ($Category !== null) {
  214.             $categoryId $Category->getId();
  215.             if ($categoryId !== null) {
  216.                 $prefix = \Eccube\Entity\Category::getCategoryPageName($categoryId);
  217.             }
  218.         }
  219.         $pageName $this->pageNameHelper->createPageName($prefix);
  220.         // Tạo breadcrumb
  221.         $breadcrumbs $this->breadcrumbService->getProductListBreadcrumb($Category);
  222.         // Thêm country_categories vào result
  223.         $country_categories $this->countryWidgetService->getCountryList();
  224.         // Lấy tất cả categories có is_searchable = 1 và group theo parent
  225.         $searchableCategories $this->getSearchableCategoriesGrouped();
  226.         return [
  227.             'subtitle' => $this->getPageTitle($searchData),
  228.             'pageName' => $pageName,
  229.             'pagination' => $pagination,
  230.             'search_form' => $searchForm->createView(),
  231.             'forms' => $forms,
  232.             'Category' => $Category,
  233.             'ListProductAttribute' => $ListProductAttribute,
  234.             'FreeArea' => $FreeArea,
  235.             'breadcrumbs' => $breadcrumbs,
  236.             'country_categories' => $country_categories,
  237.             'searchable_categories' => $searchableCategories,
  238.         ];
  239.     }
  240.     /**
  241.      * カートに追加 - Override để thêm logic kiểm tra IMEI trùng lặp
  242.      *
  243.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  244.      */
  245.     public function addCart(Request $request, \Eccube\Entity\Product $Product)
  246.     {
  247.         // エラーメッセージの配列
  248.         $errorMessages = [];
  249.         if (!$this->checkVisibility($Product)) {
  250.             throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
  251.         }
  252.         $builder $this->formFactory->createNamedBuilder(
  253.             '',
  254.             \Eccube\Form\Type\AddCartType::class,
  255.             null,
  256.             [
  257.                 'product' => $Product,
  258.                 'id_add_product_id' => false,
  259.             ]
  260.         );
  261.         $event = new \Eccube\Event\EventArgs(
  262.             [
  263.                 'builder' => $builder,
  264.                 'Product' => $Product,
  265.             ],
  266.             $request
  267.         );
  268.         $this->eventDispatcher->dispatch($event, \Eccube\Event\EccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  269.         /* @var $form \Symfony\Component\Form\FormInterface */
  270.         $form $builder->getForm();
  271.         $form->handleRequest($request);
  272.         if (!$form->isValid()) {
  273.             // Lưu form data và errors vào session để hiển thị lại
  274.             $this->session->set('product_detail_form_data'$request->request->all());
  275.             $this->session->set('product_detail_form_errors'$this->getFormErrors($form));
  276.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  277.         }
  278.         $addCartData $form->getData();
  279.         // Lấy user_imei từ CartItem object
  280.         $user_imei null;
  281.         if ($Product->hasUserImeiCategory() && $addCartData instanceof \Eccube\Entity\CartItem) {
  282.             $user_imei $addCartData->getUserImei();
  283.             // Kiểm tra IMEI trùng lặp trong giỏ hàng
  284.             if ($user_imei && $this->cartService->isImeiDuplicate($user_imei)) {
  285.                 if ($request->isXmlHttpRequest()) {
  286.                     return $this->json([
  287.                         'done' => false,
  288.                         'error_code' => 'DUPLICATE_IMEI',
  289.                         'messages' => ['front.shopping.duplicate_imei']
  290.                     ]);
  291.                 } else {
  292.                     $this->session->getFlashBag()->set('eccube.front.error''front.shopping.duplicate_imei');
  293.                     return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  294.                 }
  295.             }
  296.         }
  297.         log_info(
  298.             'カート追加処理開始',
  299.             [
  300.                 'product_id' => $Product->getId(),
  301.                 'product_class_id' => $addCartData->getProductClass()->getId(),
  302.                 'quantity' => $addCartData->getQuantity(),
  303.                 'user_imei' => $user_imei,
  304.             ]
  305.         );
  306.         // Kiểm tra tồn kho trước khi thêm vào giỏ
  307.         $shouldAddToCart true;
  308.         $ProductClass $addCartData->getProductClass();
  309.         if ($ProductClass && !$ProductClass->isStockUnlimited()) {
  310.             $currentStock = (int) $ProductClass->getStock();
  311.             $requestedQty = (int) $addCartData->getQuantity();
  312.             $quantityInCart $this->cartService->getProductClassQuantityInCart($ProductClass);
  313.             $totalRequiredQty $quantityInCart $requestedQty;
  314.             if ($currentStock <= 0) {
  315.                 $shouldAddToCart false;
  316.                 $errorMessages[] = trans('front.shopping.out_of_stock_zero', ['%product%' => $Product->getName()]);
  317.             } elseif ($currentStock $totalRequiredQty) {
  318.                 $shouldAddToCart false;
  319.                 $errorMessages[] = trans('front.shopping.out_of_stock', ['%product%' => $Product->getName()]);
  320.             }
  321.         }
  322.         if ($shouldAddToCart) {
  323.             // カートへ追加
  324.             $this->cartService->addProduct($addCartData->getProductClass()->getId(), $addCartData->getQuantity(), $user_imei);
  325.             // 明細の正規化
  326.             $Carts $this->cartService->getCarts();
  327.             foreach ($Carts as $Cart) {
  328.                 $result $this->purchaseFlow->validate($Cart, new \Eccube\Service\PurchaseFlow\PurchaseContext($Cart$this->getUser()));
  329.                 // 復旧不可のエラーが発生した場合は追加した明細を削除.
  330.                 if ($result->hasError()) {
  331.                     $this->cartService->removeProduct($addCartData->getProductClass()->getId(), $user_imei);
  332.                     foreach ($result->getErrors() as $error) {
  333.                         $errorMessages[] = $error->getMessage();
  334.                     }
  335.                 }
  336.                 foreach ($result->getWarning() as $warning) {
  337.                     $errorMessages[] = $warning->getMessage();
  338.                 }
  339.             }
  340.             $this->cartService->save();
  341.             log_info(
  342.                 'カート追加処理完了',
  343.                 [
  344.                     'product_id' => $Product->getId(),
  345.                     'product_class_id' => $addCartData->getProductClass()->getId(),
  346.                     'quantity' => $addCartData->getQuantity(),
  347.                 ]
  348.             );
  349.         }
  350.         $event = new \Eccube\Event\EventArgs(
  351.             [
  352.                 'form' => $form,
  353.                 'Product' => $Product,
  354.             ],
  355.             $request
  356.         );
  357.         $this->eventDispatcher->dispatch($event, \Eccube\Event\EccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  358.         if ($event->getResponse() !== null) {
  359.             return $event->getResponse();
  360.         }
  361.         if ($request->isXmlHttpRequest()) {
  362.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  363.             // 初期化
  364.             $messages = [];
  365.             $errorCode null;
  366.             $stockLeft null;
  367.             if (empty($errorMessages)) {
  368.                 // エラーが発生していない場合
  369.                 $done true;
  370.                 array_push($messagestrans('front.product.add_cart_complete'));
  371.             } else {
  372.                 // エラーが発生している場合
  373.                 $done false;
  374.                 $messages $errorMessages;
  375.                 // 在庫エラー用の追加情報を付与
  376.                 // 直近追加を試みた商品規格の在庫とリクエスト数量から判定
  377.                 $ProductClass $addCartData->getProductClass();
  378.                 if ($ProductClass && !$ProductClass->isStockUnlimited()) {
  379.                     $currentStock = (int) $ProductClass->getStock();
  380.                     $requestedQty = (int) $addCartData->getQuantity();
  381.                     $quantityInCart $this->cartService->getProductClassQuantityInCart($ProductClass);
  382.                     $totalRequiredQty $quantityInCart $requestedQty;
  383.                     if ($currentStock <= 0) {
  384.                         $errorCode = \Customize\Constant\ErrorCodes::OUT_OF_STOCK_ZERO;
  385.                         $stockLeft 0;
  386.                     } elseif ($currentStock $totalRequiredQty) {
  387.                         $errorCode = \Customize\Constant\ErrorCodes::OUT_OF_STOCK;
  388.                         $stockLeft $currentStock;
  389.                     }
  390.                 }
  391.             }
  392.             $response = ['done' => $done'messages' => $messages];
  393.             if (!$done) {
  394.                 $response['error_code'] = $errorCode;
  395.                 if ($stockLeft !== null) {
  396.                     $response['stock_left'] = $stockLeft;
  397.                 }
  398.             }
  399.             return $this->json($response);
  400.         } else {
  401.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  402.             foreach ($errorMessages as $errorMessage) {
  403.                 $this->addRequestError($errorMessage);
  404.             }
  405.             return $this->redirectToRoute('cart');
  406.         }
  407.     }
  408.     /**
  409.      * Lấy tất cả lỗi từ form
  410.      *
  411.      * @param \Symfony\Component\Form\FormInterface $form
  412.      * @return array
  413.      */
  414.     protected function getFormErrors($form)
  415.     {
  416.         $errors = [];
  417.         foreach ($form->getErrors(true) as $error) {
  418.             $errors[] = $error->getMessage();
  419.         }
  420.         return $errors;
  421.     }
  422.     /**
  423.      * Lấy tất cả categories có is_searchable = 1 và group theo parent
  424.      *
  425.      * @return array
  426.      */
  427.     protected function getSearchableCategoriesGrouped()
  428.     {
  429.         $qb $this->categoryRepository->createQueryBuilder('c')
  430.             ->leftJoin('c.Parent''p')
  431.             ->where('c.isSearchable = :isSearchable')
  432.             ->setParameter('isSearchable'1)
  433.             ->orderBy('c.sort_no''DESC')
  434.             ->addOrderBy('c.id''ASC');
  435.         $allCategories $qb->getQuery()->getResult();
  436.         $grouped = [];
  437.         foreach ($allCategories as $category) {
  438.             $parent $category->getParent();
  439.             if ($parent === null) {
  440.                 // Category cha có is_searchable = 1
  441.                 $parentId $category->getId();
  442.                 if (!isset($grouped[$parentId])) {
  443.                     $grouped[$parentId] = [
  444.                         'parent' => $category,
  445.                         'children' => []
  446.                     ];
  447.                 }
  448.             } else {
  449.                 // Category con - lấy parent (dù parent có is_searchable hay không)
  450.                 $parentId $parent->getId();
  451.                 if (!isset($grouped[$parentId])) {
  452.                     // Lấy parent từ database nếu chưa có
  453.                     $parentEntity $this->categoryRepository->find($parentId);
  454.                     $grouped[$parentId] = [
  455.                         'parent' => $parentEntity,
  456.                         'children' => []
  457.                     ];
  458.                 }
  459.                 $grouped[$parentId]['children'][] = $category;
  460.             }
  461.         }
  462.         // Sắp xếp lại theo sort_no của parent (DESC), sau đó sort children theo sort_no
  463.         uasort($grouped, function($a$b) {
  464.             $parentSortCompare $b['parent']->getSortNo() <=> $a['parent']->getSortNo();
  465.             if ($parentSortCompare !== 0) {
  466.                 return $parentSortCompare;
  467.             }
  468.             // Nếu sort_no bằng nhau, sắp xếp theo ID
  469.             return $a['parent']->getId() <=> $b['parent']->getId();
  470.         });
  471.         // Sắp xếp children trong mỗi group
  472.         foreach ($grouped as &$group) {
  473.             usort($group['children'], function($a$b) {
  474.                 $sortCompare $b->getSortNo() <=> $a->getSortNo();
  475.                 if ($sortCompare !== 0) {
  476.                     return $sortCompare;
  477.                 }
  478.                 return $a->getId() <=> $b->getId();
  479.             });
  480.         }
  481.         unset($group);
  482.         return $grouped;
  483.     }
  484. }