app/Customize/Controller/ProductController.php line 161

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