<?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
*
* http://www.ec-cube.co.jp/
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eccube\Controller;
use Eccube\Entity\BaseInfo;
use Eccube\Entity\Master\ProductStatus;
use Eccube\Entity\Product;
use Eccube\Entity\FavoriteKey; //@##ADD 2021-11-21 upseek
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Eccube\Form\Type\AddCartType;
use Eccube\Form\Type\SearchProductType;
use Eccube\Repository\BaseInfoRepository;
use Eccube\Repository\CustomerFavoriteProductRepository;
use Eccube\Repository\FavoriteKeyRepository; //@##ADD 2021-11-21 upseek
use Eccube\Repository\FavoriteProductRepository; //@##ADD 2021-11-21 upseek
use Eccube\Repository\Master\ProductListMaxRepository;
use Eccube\Repository\ProductRepository;
use Eccube\Repository\ProductClassRepository; //@##ADD 2023-02-10 upseek
use Eccube\Service\CalculatePriceService; //@##ADD 2021-11-05 upseek
use Eccube\Service\CartService;
use Eccube\Service\PurchaseFlow\PurchaseContext;
use Eccube\Service\PurchaseFlow\PurchaseFlow;
use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
use Knp\Component\Pager\PaginatorInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Plugin\ShelvingOption4\Entity\ShelvingOptionFavoriteProduct; //@##ADD 2022-11-16 upseek
use Plugin\ShelvingOption4\Entity\ShelvingOptionCustomerFavoriteProduct; //@##ADD 2022-11-16 upseek
class ProductController extends AbstractController
{
/**
* @var PurchaseFlow
*/
protected $purchaseFlow;
/**
* @var CustomerFavoriteProductRepository
*/
protected $customerFavoriteProductRepository;
//@##ADD START 2021-11-21
/**
* @var FavoriteKeyRepository
*/
protected $favoriteKeyRepository;
/**
* @var FavoriteProductRepository
*/
protected $favoriteProductRepository;
//@##ADD END
/**
* @var CartService
*/
protected $cartService;
/**
* @var CalculatePriceService
*/
protected $calculatePriceService;
/**
* @var ProductRepository
*/
protected $productRepository;
//@##ADD START 2023-02-10
protected $productClassRepository;
//@##ADD END
/**
* @var BaseInfo
*/
protected $BaseInfo;
/**
* @var AuthenticationUtils
*/
protected $helper;
/**
* @var ProductListMaxRepository
*/
protected $productListMaxRepository;
private $title = '';
/**
* ProductController constructor.
*
* @param PurchaseFlow $cartPurchaseFlow
* @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
* @param FavoriteKeyRepository $favoriteKeyRepository
* @param FavoriteProductRepository $favoriteProductRepository
* @param CartService $cartService
* @param CalculatePriceService $calculatePriceService
* @param ProductRepository $productRepository
* @param ProductClassRepository $productClassRepository
* @param BaseInfoRepository $baseInfoRepository
* @param AuthenticationUtils $helper
* @param ProductListMaxRepository $productListMaxRepository
*/
public function __construct(
PurchaseFlow $cartPurchaseFlow,
CustomerFavoriteProductRepository $customerFavoriteProductRepository,
FavoriteKeyRepository $favoriteKeyRepository, //@##ADD 2021-11-21
FavoriteProductRepository $favoriteProductRepository, //@##ADD 2021-11-21
CartService $cartService,
CalculatePriceService $calculatePriceService,
ProductRepository $productRepository,
ProductClassRepository $productClassRepository, //@##ADD 2023-02-10
BaseInfoRepository $baseInfoRepository,
AuthenticationUtils $helper,
ProductListMaxRepository $productListMaxRepository
) {
$this->purchaseFlow = $cartPurchaseFlow;
$this->customerFavoriteProductRepository = $customerFavoriteProductRepository;
$this->favoriteKeyRepository = $favoriteKeyRepository; //@##ADD 2021-11-21
$this->favoriteProductRepository = $favoriteProductRepository; //@##ADD 2021-11-21
$this->cartService = $cartService;
$this->calculatePriceService = $calculatePriceService;
$this->productRepository = $productRepository;
$this->productClassRepository = $productClassRepository; //@##ADD 2023-02-10
$this->BaseInfo = $baseInfoRepository->get();
$this->helper = $helper;
$this->productListMaxRepository = $productListMaxRepository;
}
/**
* 商品一覧画面.
*
* @Route("/products/list", name="product_list", methods={"GET"})
* @Template("Product/list.twig")
*/
public function index(Request $request, PaginatorInterface $paginator)
{
// Doctrine SQLFilter
if ($this->BaseInfo->isOptionNostockHidden()) {
$this->entityManager->getFilters()->enable('option_nostock_hidden');
}
// handleRequestは空のqueryの場合は無視するため
if ($request->getMethod() === 'GET') {
$request->query->set('pageno', $request->query->get('pageno', ''));
}
// searchForm
/* @var $builder \Symfony\Component\Form\FormBuilderInterface */
$builder = $this->formFactory->createNamedBuilder('', SearchProductType::class);
if ($request->getMethod() === 'GET') {
$builder->setMethod('GET');
}
$event = new EventArgs(
[
'builder' => $builder,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
/* @var $searchForm \Symfony\Component\Form\FormInterface */
$searchForm = $builder->getForm();
$searchForm->handleRequest($request);
// paginator
$searchData = $searchForm->getData();
$qb = $this->productRepository->getQueryBuilderBySearchData($searchData);
$event = new EventArgs(
[
'searchData' => $searchData,
'qb' => $qb,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
$searchData = $event->getArgument('searchData');
$query = $qb->getQuery()
->useResultCache(true, $this->eccubeConfig['eccube_result_cache_lifetime_short']);
/** @var SlidingPagination $pagination */
$pagination = $paginator->paginate(
$query,
!empty($searchData['pageno']) ? $searchData['pageno'] : 1,
!empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
);
$ids = [];
foreach ($pagination as $Product) {
$ids[] = $Product->getId();
}
$ProductsAndClassCategories = $this->productRepository->findProductsWithSortedClassCategories($ids, 'p.id');
// addCart form
$forms = [];
foreach ($pagination as $Product) {
/* @var $builder \Symfony\Component\Form\FormBuilderInterface */
$builder = $this->formFactory->createNamedBuilder(
'',
AddCartType::class,
null,
[
'product' => $ProductsAndClassCategories[$Product->getId()],
'allow_extra_fields' => true,
]
);
$addCartForm = $builder->getForm();
$forms[$Product->getId()] = $addCartForm->createView();
}
$Category = $searchForm->get('category_id')->getData();
//@##ADD START 2021-10-25
$Category0 = $searchForm->get('c0')->getData();
$Category1 = $searchForm->get('c1')->getData();
$Category2 = $searchForm->get('c2')->getData();
$Category3 = $searchForm->get('c3')->getData();
$Category4 = $searchForm->get('c4')->getData();
$Category5 = $searchForm->get('c5')->getData();
$Category6 = $searchForm->get('c6')->getData();
$Category7 = $searchForm->get('c7')->getData();
$Category8 = $searchForm->get('c8')->getData();
$Category9 = $searchForm->get('c9')->getData();
//@##ADD END
return [
'subtitle' => $this->getPageTitle($searchData),
'pagination' => $pagination,
'search_form' => $searchForm->createView(),
'forms' => $forms,
'Category' => $Category,
//@##ADD START 2021-10-25
'Category0' => $Category0,
'Category1' => $Category1,
'Category2' => $Category2,
'Category3' => $Category3,
'Category4' => $Category4,
'Category5' => $Category5,
'Category6' => $Category6,
'Category7' => $Category7,
'Category8' => $Category8,
'Category9' => $Category9,
//@##ADD END
//@##ADD START 2021-10-31
'color_id' => $searchData['color_id'],
'w' => $searchData['w'],
'h' => $searchData['h'],
//@##ADD END 2021-10-31
];
}
/**
* 商品詳細画面.
*
* @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
* @Template("Product/detail.twig")
* @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
*
* @param Request $request
* @param Product $Product
*
* @return array
*/
public function detail(Request $request, Product $Product)
{
if (!$this->checkVisibility($Product)) {
throw new NotFoundHttpException();
}
//@##ADD START 2022-01-17
$cfp = $request->query->get('cfp');
$fp = $request->query->get('fp');
if($cfp) {
$CustomerFavoriteProduct = $this->customerFavoriteProductRepository->find($cfp);
if($CustomerFavoriteProduct) {
if($Product->getShelvingOption() && $CustomerFavoriteProduct->getShelvingOption()) {
$Product->getShelvingOption()->setPattern( $CustomerFavoriteProduct->getShelvingOption()->getPattern() );
$Product->getShelvingOption()->setHeightList( $CustomerFavoriteProduct->getShelvingOption()->getHeightList() );
$Product->getShelvingOption()->setWidthList( $CustomerFavoriteProduct->getShelvingOption()->getWidthList() );
$Product->getShelvingOption()->setFullHeight( $CustomerFavoriteProduct->getShelvingOption()->getFullHeight() );
$Product->getShelvingOption()->setFullWidth( $CustomerFavoriteProduct->getShelvingOption()->getFullWidth() );
$Product->getShelvingOption()->setItems( $CustomerFavoriteProduct->getShelvingOption()->getItems() );
$Product->getShelvingOption()->setRowDoors( $CustomerFavoriteProduct->getShelvingOption()->getRowDoors() );
$Product->getShelvingOption()->setRowDrawers( $CustomerFavoriteProduct->getShelvingOption()->getRowDrawers() );
$Product->getShelvingOption()->setDepth( $CustomerFavoriteProduct->getShelvingOption()->getDepth() );
$Product->getShelvingOption()->setBackPanel( $CustomerFavoriteProduct->getShelvingOption()->getBackPanel() );
$Product->getShelvingOption()->setTexture( $CustomerFavoriteProduct->getShelvingOption()->getTexture() );
$Product->getShelvingOption()->setColorId( $CustomerFavoriteProduct->getShelvingOption()->getColorId() );
$Product->getShelvingOption()->setDoorSwing( $CustomerFavoriteProduct->getShelvingOption()->getDoorSwing() );
//※ファイルは連携しない
}
}
} else if($fp) {
$FavoriteProduct = $this->favoriteProductRepository->find($fp);
if($FavoriteProduct) {
if($Product->getShelvingOption() && $FavoriteProduct->getShelvingOption()) {
$Product->getShelvingOption()->setPattern( $FavoriteProduct->getShelvingOption()->getPattern() );
$Product->getShelvingOption()->setHeightList( $FavoriteProduct->getShelvingOption()->getHeightList() );
$Product->getShelvingOption()->setWidthList( $FavoriteProduct->getShelvingOption()->getWidthList() );
$Product->getShelvingOption()->setFullHeight( $FavoriteProduct->getShelvingOption()->getFullHeight() );
$Product->getShelvingOption()->setFullWidth( $FavoriteProduct->getShelvingOption()->getFullWidth() );
$Product->getShelvingOption()->setItems( $FavoriteProduct->getShelvingOption()->getItems() );
$Product->getShelvingOption()->setRowDoors( $FavoriteProduct->getShelvingOption()->getRowDoors() );
$Product->getShelvingOption()->setRowDrawers( $FavoriteProduct->getShelvingOption()->getRowDrawers() );
$Product->getShelvingOption()->setDepth( $FavoriteProduct->getShelvingOption()->getDepth() );
$Product->getShelvingOption()->setBackPanel( $FavoriteProduct->getShelvingOption()->getBackPanel() );
$Product->getShelvingOption()->setTexture( $FavoriteProduct->getShelvingOption()->getTexture() );
$Product->getShelvingOption()->setColorId( $FavoriteProduct->getShelvingOption()->getColorId() );
$Product->getShelvingOption()->setDoorSwing( $FavoriteProduct->getShelvingOption()->getDoorSwing() );
//※ファイルは連携しない
}
}
}
//@##ADD END
//@##ADD START 2023-02-07 2023-03-17 2023-04-04 Product追加
//メタproduct:price:amountのデフォルト値(最小販売価格 税込)
//<meta property="product:price:amount" content="{{ Product.getPrice02IncTaxMin }}"/>
$Product->meta_product_price_amount = $Product->getPrice02IncTaxMin();
//codeパラメータから規格情報を取得してデフォルト表示
$code = $request->query->get('code');
$classcategory_id1 = '';
$classcategory_id2 = '';
if($code) {
//log_warning('code [' . $code . ']');
$productClasses = $this->productClassRepository->findBy(['Product' => $Product, 'code' => $code, 'visible' => 1]);
if(count($productClasses)) {
$productClass = current($productClasses);
if($productClass->getClassCategory1() && $productClass->getClassCategory1()->getId()) {
$classcategory_id1 = $productClass->getClassCategory1()->getId();
}
if($productClass->getClassCategory2() && $productClass->getClassCategory2()->getId()) {
$classcategory_id2 = $productClass->getClassCategory2()->getId();
}
//規格管理の販売価格(税込)をセット
$Product->meta_product_price_amount = $productClass->getPrice02IncTax();
}
//log_warning('@classcategory_id1=[' . $classcategory_id1 . ']');
//log_warning('@classcategory_id2=[' . $classcategory_id2 . ']');
}
//@##ADD END
$builder = $this->formFactory->createNamedBuilder(
'',
AddCartType::class,
null,
[
'product' => $Product,
'id_add_product_id' => false,
]
);
$event = new EventArgs(
[
'builder' => $builder,
'Product' => $Product,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
$is_favorite = false;
if ($this->isGranted('ROLE_USER')) {
$Customer = $this->getUser();
$is_favorite = $this->customerFavoriteProductRepository->isFavorite($Customer, $Product);
}
return [
'title' => $this->title,
'subtitle' => $Product->getName(),
'form' => $builder->getForm()->createView(),
'Product' => $Product,
'is_favorite' => $is_favorite,
//@##ADD 2023-02-07
'classcategory_id1' => $classcategory_id1,
'classcategory_id2' => $classcategory_id2,
//@##ADD END
];
}
/**
* お気に入り追加.
*
* @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
*/
public function addFavorite(Request $request, Product $Product)
{
$this->checkVisibility($Product);
$event = new EventArgs(
[
'Product' => $Product,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
if ($this->isGranted('ROLE_USER')) {
$Customer = $this->getUser();
//@##CHG START 2022-01-17
// $this->customerFavoriteProductRepository->addFavorite($Customer, $Product);
$ShelvingOption = null;
$shelving_option = $request->query->get('shelving_option');
if($shelving_option) {
$height_list = [];
$width_list = [];
$row_doors = [];
$row_drawers = [];
$items = [];
$filename = '';
$back_panel = false;
if($shelving_option['height_list']) {
$height_list = explode(',', str_replace(['[',']'], '', $shelving_option['height_list']));
}
if($shelving_option['width_list']) {
$width_list = explode(',', str_replace(['[',']'], '', $shelving_option['width_list']));
}
if($shelving_option['row_doors']) {
$row_doors = explode(',', str_replace(['[',']'], '', $shelving_option['row_doors']));
}
if($shelving_option['row_drawers']) {
$row_drawers = explode(',', str_replace(['[',']'], '', $shelving_option['row_drawers']));
}
if($shelving_option['items']) {
$item1s = explode("],[", $shelving_option['items']);
foreach($item1s as $item) {
$items[]= array_map('intval', explode(',', str_replace(['[',']'], '', $item)));
}
}
if(!empty($shelving_option['file_name'])) {
$filename = $shelving_option['file_name'];
if(file_exists($this->eccubeConfig['eccube_temp_shelving_image_dir'] . '/' . $filename)) {
rename($this->eccubeConfig['eccube_temp_shelving_image_dir'] . '/' . $filename, $this->eccubeConfig['eccube_save_shelving_image_dir'] . '/' . $filename);
}
}
if($shelving_option['back_panel']) {
if($shelving_option['back_panel'] == 'true') {
$back_panel = true;
}
}
$ShelvingOption = new ShelvingOptionCustomerFavoriteProduct();
$ShelvingOption->setPattern( $shelving_option['pattern'] );
$ShelvingOption->setHeightList( $height_list );
$ShelvingOption->setWidthList( $width_list );
$ShelvingOption->setFullHeight( $shelving_option['full_height'] );
$ShelvingOption->setFullWidth( $shelving_option['full_width'] );
$ShelvingOption->setItems( $items );
$ShelvingOption->setRowDoors( $row_doors );
$ShelvingOption->setRowDrawers( $row_drawers );
$ShelvingOption->setDepth( $shelving_option['depth'] );
$ShelvingOption->setBackPanel( $back_panel );
$ShelvingOption->setTexture( $shelving_option['texture'] );
$ShelvingOption->setColorId( $shelving_option['color_id'] );
$ShelvingOption->setDoorSwing( $shelving_option['door_swing'] );
$ShelvingOption->setFileName( $filename );
}
$this->customerFavoriteProductRepository->addFavorite($Customer, $Product, $ShelvingOption);
//@##CHG END
$this->session->getFlashBag()->set('product_detail.just_added_favorite', $Product->getId());
$event = new EventArgs(
[
'Product' => $Product,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
} else {
/*
// 非会員の場合、ログイン画面を表示
// ログイン後の画面遷移先を設定
$this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
$this->session->getFlashBag()->set('eccube.add.favorite', true);
$event = new EventArgs(
[
'Product' => $Product,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
return $this->redirectToRoute('mypage_login');
*/
// 非会員の場合
$FavoriteKey = null;
$cookieKey = $request->cookies->get('eccube_favorite');
if($cookieKey) {
$FavoriteKey = $this->favoriteKeyRepository->findWithCookieKey($cookieKey);
}
if(!$FavoriteKey) {
$FavoriteKey = $this->favoriteKeyRepository->createFavoriteKey();
}
setcookie('eccube_favorite', $FavoriteKey->getCookieKey(), (time() + 60 * 60 * 24 * 30), $this->eccubeConfig['env(ECCUBE_COOKIE_PATH)']);
log_warning('add_favorite Product=[' . $Product->getId() . '] cookie_key=[' . $FavoriteKey->getCookieKey() . ']');
$ShelvingOption = null;
$shelving_option = $request->query->get('shelving_option');
if($shelving_option) {
$height_list = [];
$width_list = [];
$row_doors = [];
$row_drawers = [];
$items = [];
$filename = '';
$back_panel = false;
if($shelving_option['height_list']) {
$height_list = explode(',', str_replace(['[',']'], '', $shelving_option['height_list']));
}
if($shelving_option['width_list']) {
$width_list = explode(',', str_replace(['[',']'], '', $shelving_option['width_list']));
}
if($shelving_option['row_doors']) {
$row_doors = explode(',', str_replace(['[',']'], '', $shelving_option['row_doors']));
}
if($shelving_option['row_drawers']) {
$row_drawers = explode(',', str_replace(['[',']'], '', $shelving_option['row_drawers']));
}
if($shelving_option['items']) {
$item1s = explode("],[", $shelving_option['items']);
foreach($item1s as $item) {
$items[]= array_map('intval', explode(',', str_replace(['[',']'], '', $item)));
}
}
if(!empty($shelving_option['file_name'])) {
$filename = $shelving_option['file_name'];
if(file_exists($this->eccubeConfig['eccube_temp_shelving_image_dir'] . '/' . $filename)) {
rename($this->eccubeConfig['eccube_temp_shelving_image_dir'] . '/' . $filename, $this->eccubeConfig['eccube_save_shelving_image_dir'] . '/' . $filename);
}
}
if($shelving_option['back_panel']) {
if($shelving_option['back_panel'] == 'true') {
$back_panel = true;
}
}
$ShelvingOption = new ShelvingOptionFavoriteProduct();
$ShelvingOption->setPattern( $shelving_option['pattern'] );
$ShelvingOption->setHeightList( $height_list );
$ShelvingOption->setWidthList( $width_list );
$ShelvingOption->setFullHeight( $shelving_option['full_height'] );
$ShelvingOption->setFullWidth( $shelving_option['full_width'] );
$ShelvingOption->setItems( $items );
$ShelvingOption->setRowDoors( $row_doors );
$ShelvingOption->setRowDrawers( $row_drawers );
$ShelvingOption->setDepth( $shelving_option['depth'] );
$ShelvingOption->setBackPanel( $back_panel );
$ShelvingOption->setTexture( $shelving_option['texture'] );
$ShelvingOption->setColorId( $shelving_option['color_id'] );
$ShelvingOption->setDoorSwing( $shelving_option['door_swing'] );
$ShelvingOption->setFileName( $filename );
}
$this->favoriteProductRepository->addFavorite($FavoriteKey, $Product, $ShelvingOption);
$this->session->getFlashBag()->set('product_detail.just_added_favorite', $Product->getId());
$event = new EventArgs(
[
'Product' => $Product,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
}
}
/**
* カートに追加.
*
* @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
*/
public function addCart(Request $request, Product $Product)
{
// エラーメッセージの配列
$errorMessages = [];
if (!$this->checkVisibility($Product)) {
throw new NotFoundHttpException();
}
$builder = $this->formFactory->createNamedBuilder(
'',
AddCartType::class,
null,
[
'product' => $Product,
'id_add_product_id' => false,
]
);
$event = new EventArgs(
[
'builder' => $builder,
'Product' => $Product,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
/* @var $form \Symfony\Component\Form\FormInterface */
$form = $builder->getForm();
$form->handleRequest($request);
if (!$form->isValid()) {
throw new NotFoundHttpException();
}
$addCartData = $form->getData();
log_info(
'カート追加処理開始',
[
'product_id' => $Product->getId(),
'product_class_id' => $addCartData['product_class_id'],
'quantity' => $addCartData['quantity'],
'shelving_option' => $addCartData['shelving_option'], //@##ADD 2021-11-05 upseek
]
);
// カートへ追加
//@##CHG START 2021-11-05 upseek
//$this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
$this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity'], $addCartData['shelving_option']);
if($addCartData['shelving_option'] != null) {
log_warning('addCart [' . $Product->getId() . '] image=[' . $addCartData['shelving_option']->getFileName() . ']');
$filename = $addCartData['shelving_option']->getFileName();
if(file_exists($this->eccubeConfig['eccube_temp_shelving_image_dir'] . '/' . $filename)) {
rename($this->eccubeConfig['eccube_temp_shelving_image_dir'] . '/' . $filename, $this->eccubeConfig['eccube_save_shelving_image_dir'] . '/' . $filename);
}
}
//@##CHG END
// 明細の正規化
$Carts = $this->cartService->getCarts();
foreach ($Carts as $Cart) {
$result = $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart, $this->getUser()));
// 復旧不可のエラーが発生した場合は追加した明細を削除.
if ($result->hasError()) {
$this->cartService->removeProduct($addCartData['product_class_id']);
foreach ($result->getErrors() as $error) {
$errorMessages[] = $error->getMessage();
}
}
foreach ($result->getWarning() as $warning) {
$errorMessages[] = $warning->getMessage();
}
}
$this->cartService->save();
log_info(
'カート追加処理完了',
[
'product_id' => $Product->getId(),
'product_class_id' => $addCartData['product_class_id'],
'quantity' => $addCartData['quantity'],
]
);
$event = new EventArgs(
[
'form' => $form,
'Product' => $Product,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
if ($event->getResponse() !== null) {
return $event->getResponse();
}
if ($request->isXmlHttpRequest()) {
// ajaxでのリクエストの場合は結果をjson形式で返す。
// 初期化
$messages = [];
if (empty($errorMessages)) {
// エラーが発生していない場合
$done = true;
array_push($messages, trans('front.product.add_cart_complete'));
} else {
// エラーが発生している場合
$done = false;
$messages = $errorMessages;
}
return $this->json(['done' => $done, 'messages' => $messages]);
} else {
// ajax以外でのリクエストの場合はカート画面へリダイレクト
foreach ($errorMessages as $errorMessage) {
$this->addRequestError($errorMessage);
}
return $this->redirectToRoute('cart');
}
}
/**
* ページタイトルの設定
*
* @param array|null $searchData
*
* @return str
*/
protected function getPageTitle($searchData)
{
if (isset($searchData['name']) && !empty($searchData['name'])) {
return trans('front.product.search_result');
} elseif (isset($searchData['category_id']) && $searchData['category_id']) {
return $searchData['category_id']->getName();
} else {
return trans('front.product.all_products');
}
}
/**
* 閲覧可能な商品かどうかを判定
*
* @param Product $Product
*
* @return boolean 閲覧可能な場合はtrue
*/
protected function checkVisibility(Product $Product)
{
$is_admin = $this->session->has('_security_admin');
// 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
if (!$is_admin) {
// 在庫なし商品の非表示オプションが有効な場合.
// if ($this->BaseInfo->isOptionNostockHidden()) {
// if (!$Product->getStockFind()) {
// return false;
// }
// }
// 公開ステータスでない商品は表示しない.
if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
return false;
}
}
return true;
}
//@##ADD START 2021-11-05 upseek
/**
* 棚の値段算出する.
*
* @Route("/products/price", name="product_price", methods={"POST"})
*
* @param Request $request
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function calcPrice(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return $this->json(['status' => 'NG'], 500);
}
log_warning('calc shelving price.');
if (is_null($request)) {
log_error('cannot calc shelving price.');
return $this->json([], 404);
}
log_debug('validate for calc shelving price.');
$params = json_decode($request->getContent());
$pattern = $params->pattern ?? null;
$heightList = $params->heightList ?? null;
$widthList = $params->widthList ?? null;
$items = $params->items ?? null;
$depth = $params->depth ?? null;
$backPanel = $params->backPanel ?? null;
$colorId = $params->colorId ?? null;
$includeTax = true;
if (!isset(
$pattern,
$heightList,
$widthList,
$items,
$depth,
$backPanel,
$colorId
)) {
log_error('invalid params for calc shelving price.');
return $this->json(['status' => 'NG'], 403);
}
try {
$price = $this->calculatePriceService->calculate(
$pattern,
$heightList,
$widthList,
$items,
$depth,
$backPanel,
$colorId,
$includeTax
);
} catch (\RuntimeException $error) {
return $this->json(['status' => 'NG', 'message' => $error->getMessage()], 403);
} catch (\Throwable $th) {
// return $this->json(['status' => 'NG', 'message' => $th->getMessage()], 403);
return $this->json(['status' => 'NG'], 500);
}
return $this->json([
'price' => $price,
]);
}
//@##ADD END
//@##ADD START 2021-11-08 upseek
/**
* シミュレーション画像を保存する
*
* @Route("/product/image/add", name="product_image_add", methods={"POST"})
*/
public function addImage(Request $request)
{
if (!$request->isXmlHttpRequest()) {
throw new BadRequestHttpException();
}
$product_id = $request->get('id');
$image_base64 = $request->get('image');
$allowExtensions = ['gif', 'jpg', 'jpeg', 'png'];
$data_image_png_base64 = 'data:image/png;base64,';
$file = '';
if($product_id && $image_base64 && substr($image_base64, 0, strlen($data_image_png_base64)) == $data_image_png_base64) {
$image = str_replace($data_image_png_base64, '', $image_base64);
$image = str_replace(' ', '+', $image);
$image = base64_decode($image);
$extension = 'png';
$filename = $product_id . '_' . date('mdHis').uniqid('_') . '.' . $extension;
file_put_contents($this->eccubeConfig['eccube_temp_shelving_image_dir'] . '/' . $filename, $image);
$file = $filename;
log_warning('addImage product_id=[' . $product_id . '] filename=[' . $filename . ']');
} else {
log_error('addImage invalid parameter');
}
$event = new EventArgs(
[
// 'image' => $image,
'file' => $file,
],
$request
);
// $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_PRODUCT_ADD_IMAGE_COMPLETE, $event);
$file = $event->getArgument('file');
return $this->json(['file' => $file], 200);
}
//@## ADD END
}