<?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 Customize\Controller\Admin\SetProduct;
use Customize\Repository\SchoolRepository;
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
use Eccube\Common\Constant;
use Eccube\Controller\AbstractController;
use Eccube\Entity\BaseInfo;
use Eccube\Entity\Master\ProductStatus;
use Eccube\Entity\Product;
use Eccube\Entity\ProductCategory;
use Eccube\Entity\ProductClass;
use Eccube\Entity\ProductStock;
use Customize\Entity\SetProductImage;
use Customize\Entity\SetProduct;
use Eccube\Event\EccubeEvents;
use Eccube\Entity\ProductImage;
use Eccube\Event\EventArgs;
use Customize\Form\Type\Admin\SetProductType;
use Customize\Form\Type\Admin\SearchSetProductType;
use Eccube\Repository\BaseInfoRepository;
use Eccube\Repository\CategoryRepository;
use Eccube\Repository\Master\PageMaxRepository;
use Eccube\Repository\Master\ProductStatusRepository;
use Customize\Repository\SetProductRepository;
use Customize\Repository\SetProductImageRepository;
use Customize\Repository\SetProductProductRepository;
use Customize\Repository\RecommendRepository;
use Eccube\Repository\ProductImageRepository;
use Eccube\Repository\ProductRepository;
use Eccube\Repository\ProductClassRepository;
use Eccube\Repository\ProductStockRepository;
use Eccube\Repository\Master\SaleTypeRepository;
use Eccube\Util\CacheUtil;
use Eccube\Util\FormUtil;
use Knp\Component\Pager\PaginatorInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\RouterInterface;
class SetProductController extends AbstractController
{
/**
* @var SetProductImageRepository
*/
protected $setProductImageRepository;
/**
* @var ProductImageRepository
*/
protected $productImageRepository;
/**
* @var CategoryRepository
*/
protected $categoryRepository;
/**
* @var SetProductRepository
*/
protected $setProductRepository;
/**
* @var SetProductProductRepository
*/
protected $setProductProductRepository;
/**
* @var ProductRepository
*/
protected $productRepository;
/**
* @var ProductClassRepository
*/
protected $productClassRepository;
/**
* @var ProductStockRepository
*/
protected $productStockRepository;
/**
* @var BaseInfo
*/
protected $BaseInfo;
/**
* @var PageMaxRepository
*/
protected $pageMaxRepository;
/**
* @var ProductStatusRepository
*/
protected $productStatusRepository;
/**
* @var SchoolRepository
*/
protected $schoolRepository;
/**
* @var SaleTypeRepository
*/
protected $saleTypeRepository;
/**
* @var RecommendRepository
*/
protected $recommendRepository;
/**
* SetProductController constructor.
*
* @param SetProductImageRepository $setProductImageRepository
* @param CategoryRepository $categoryRepository
* @param ProductRepository $productRepository
* @param BaseInfoRepository $baseInfoRepository
* @param PageMaxRepository $pageMaxRepository
* @param ProductStatusRepository $productStatusRepository
* @param SchoolRepository $schoolRepository
* @param SetProductProductRepository $setProductProductRepository
* @param ProductClassRepository $productClassRepository
* @param ProductStockRepository $productStockRepository
* @param ProductImageRepository $productImageRepository
* @param RecommendRepository $recommendRepository
*/
public function __construct(
SetProductImageRepository $setProductImageRepository,
CategoryRepository $categoryRepository,
ProductRepository $productRepository,
BaseInfoRepository $baseInfoRepository,
PageMaxRepository $pageMaxRepository,
ProductStatusRepository $productStatusRepository,
SchoolRepository $schoolRepository,
SetProductRepository $setProductRepository,
SetProductProductRepository $setProductProductRepository,
ProductClassRepository $productClassRepository,
ProductStockRepository $productStockRepository,
SaleTypeRepository $saleTypeRepository,
ProductImageRepository $productImageRepository,
RecommendRepository $recommendRepository
) {
$this->setProductImageRepository = $setProductImageRepository;
$this->categoryRepository = $categoryRepository;
$this->productRepository = $productRepository;
$this->BaseInfo = $baseInfoRepository->get();
$this->pageMaxRepository = $pageMaxRepository;
$this->productStatusRepository = $productStatusRepository;
$this->schoolRepository = $schoolRepository;
$this->setProductRepository = $setProductRepository;
$this->setProductProductRepository = $setProductProductRepository;
$this->productClassRepository = $productClassRepository;
$this->productStockRepository = $productStockRepository;
$this->saleTypeRepository = $saleTypeRepository;
$this->productImageRepository = $productImageRepository;
$this->recommendRepository = $recommendRepository;
}
/**
* @Route("/%eccube_admin_route%/product/set_product", name="admin_set_product", methods={"GET", "POST"})
* @Route("/%eccube_admin_route%/product/set_product/page/{page_no}", requirements={"page_no" = "\d+"}, name="admin_set_product_page", methods={"GET", "POST"})
* @Template("@admin/SetProduct/index.twig")
*/
public function index(Request $request, PaginatorInterface $paginator, $page_no = null)
{
$builder = $this->formFactory
->createBuilder(SearchSetProductType::class);
$event = new EventArgs(
[
'builder' => $builder,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::ADMIN_SET_PRODUCT_INDEX_INITIALIZE);
$searchForm = $builder->getForm();
/**
* ページの表示件数は, 以下の順に優先される.
* - リクエストパラメータ
* - セッション
* - デフォルト値
* また, セッションに保存する際は mtb_page_maxと照合し, 一致した場合のみ保存する.
**/
$page_count = $this->session->get(
'eccube.admin.set_product.search.page_count',
$this->eccubeConfig->get('eccube_default_page_count')
);
$page_count_param = (int) $request->get('page_count');
$pageMaxis = $this->pageMaxRepository->findAll();
if ($page_count_param) {
foreach ($pageMaxis as $pageMax) {
if ($page_count_param == $pageMax->getName()) {
$page_count = $pageMax->getName();
$this->session->set('eccube.admin.set_product.search.page_count', $page_count);
break;
}
}
}
if ('POST' === $request->getMethod()) {
$searchForm->handleRequest($request);
if ($searchForm->isValid()) {
/**
* 検索が実行された場合は, セッションに検索条件を保存する.
* ページ番号は最初のページ番号に初期化する.
*/
$page_no = 1;
$searchData = $searchForm->getData();
// 検索条件, ページ番号をセッションに保持.
$this->session->set('eccube.admin.set_product.search', FormUtil::getViewData($searchForm));
$this->session->set('eccube.admin.set_product.search.page_no', $page_no);
} else {
// 検索エラーの際は, 詳細検索枠を開いてエラー表示する.
return [
'searchForm' => $searchForm->createView(),
'pagination' => [],
'pageMaxis' => $pageMaxis,
'page_no' => $page_no,
'page_count' => $page_count,
'has_errors' => true,
];
}
} else {
if (null !== $page_no || $request->get('resume')) {
/*
* ページ送りの場合または、他画面から戻ってきた場合は, セッションから検索条件を復旧する.
*/
if ($page_no) {
// ページ送りで遷移した場合.
$this->session->set('eccube.admin.set_product.search.page_no', (int) $page_no);
} else {
// 他画面から遷移した場合.
$page_no = $this->session->get('eccube.admin.set_product.search.page_no', 1);
}
$viewData = $this->session->get('eccube.admin.set_product.search', []);
$searchData = FormUtil::submitAndGetData($searchForm, $viewData);
} else {
/**
* 初期表示の場合.
*/
$page_no = 1;
// submit default value
$viewData = FormUtil::getViewData($searchForm);
$searchData = FormUtil::submitAndGetData($searchForm, $viewData);
// セッション中の検索条件, ページ番号を初期化.
$this->session->set('eccube.admin.set_product.search', $viewData);
$this->session->set('eccube.admin.set_product.search.page_no', $page_no);
}
}
$qb = $this->setProductRepository->getQueryBuilderBySearchDataForAdmin($searchData);
$event = new EventArgs(
[
'qb' => $qb,
'searchData' => $searchData,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::ADMIN_SET_PRODUCT_INDEX_SEARCH);
$sortKey = $searchData['sortkey'];
if (empty($this->productRepository::COLUMNS[$sortKey]) || $sortKey == 'code' || $sortKey == 'status') {
$pagination = $paginator->paginate(
$qb,
$page_no,
$page_count
);
} else {
$pagination = $paginator->paginate(
$qb,
$page_no,
$page_count,
['wrap-queries' => true]
);
}
foreach ($pagination as $key => $set_product) {
$product_for_set = $this->productRepository->findOneBy(['set_product_id' => $set_product->getId(), 'product_type' => 'set']);
if ($product_for_set) {
$pagination[$key]->pid = $product_for_set->getId();
}
}
return [
'searchForm' => $searchForm->createView(),
'pagination' => $pagination,
'pageMaxis' => $pageMaxis,
'page_no' => $page_no,
'page_count' => $page_count,
'has_errors' => false,
];
}
private function getProductByCateogory($cat_id)
{
$searchData = [];
$searchData['category_id'] = $this->categoryRepository->findOneById($cat_id);
$qb = $this->productRepository->getQueryBuilderBySearchDataForAdmin($searchData);
$products = $qb
->getQuery()
->useResultCache(true, $this->eccubeConfig['eccube_result_cache_lifetime_short'])
->getResult();
$result = array();
foreach ($products as $p) {
array_push($result, ['id' => $p->getID(), 'name' => $p->getName(), 'price' => $p->getPrice02Min()]);
}
return $result;
}
/**
* @Route("/%eccube_admin_route%/product/set_product/get_category_product", name="admin_set_product_category_product", methods={"GET"})
*/
public function ajaxGetProductByCateogory(Request $request)
{
return $this->json(['products' => $this->getProductByCateogory($request->get('category_id'))], 200);
}
/**
* @Route("/%eccube_admin_route%/product/set_product/image/add", name="admin_set_product_image_add", methods={"POST"})
*/
public function addImage(Request $request)
{
if (!$request->isXmlHttpRequest() && $this->isTokenValid()) {
throw new BadRequestHttpException();
}
$images = $request->files->get('admin_set_product');
$allowExtensions = ['gif', 'jpg', 'jpeg', 'png'];
$files = [];
if (count($images) > 0) {
foreach ($images as $img) {
foreach ($img as $image) {
//ファイルフォーマット検証
$mimeType = $image->getMimeType();
if (0 !== strpos($mimeType, 'image')) {
throw new UnsupportedMediaTypeHttpException();
}
// 拡張子
$extension = $image->getClientOriginalExtension();
if (!in_array(strtolower($extension), $allowExtensions)) {
throw new UnsupportedMediaTypeHttpException();
}
$filename = date('mdHis') . uniqid('_') . '.' . $extension;
$image->move($this->eccubeConfig['eccube_temp_image_dir'], $filename);
$files[] = $filename;
}
}
}
$event = new EventArgs(
[
'images' => $images,
'files' => $files,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::ADMIN_SET_PRODUCT_ADD_IMAGE_COMPLETE);
$files = $event->getArgument('files');
return $this->json(['files' => $files], 200);
}
/**
* @Route("/%eccube_admin_route%/product/set_product/new", name="admin_product_set_product_new", methods={"GET", "POST"})
* @Route("/%eccube_admin_route%/product/set_product/{id}/edit", requirements={"id" = "\d+"}, name="admin_product_set_product_edit", methods={"GET", "POST"})
* @Template("@admin/SetProduct/set_product.twig")
*/
public function edit(Request $request, RouterInterface $router, CacheUtil $cacheUtil, $id = null)
{
$has_class = false;
if (is_null($id)) {
$SetProduct = new SetProduct();
$SetProductStatus = $this->productStatusRepository->find(ProductStatus::DISPLAY_HIDE);
$SetProduct
->setStatus($SetProductStatus);
} else {
$SetProduct = $this->setProductRepository->find($id);
if (!$SetProduct) {
throw new NotFoundHttpException();
}
}
//Create Product to process Set as One Product
$Product = $this->productRepository->findOneBy(['set_product_id' => $SetProduct->getId(), 'product_type' => 'set']);
if (!$Product) {
$Product = new Product();
}
$builder = $this->formFactory
->createBuilder(SetProductType::class, $SetProduct);
$event = new EventArgs(
[
'builder' => $builder,
'SetProduct' => $SetProduct,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::ADMIN_SET_PRODUCT_EDIT_INITIALIZE);
$form = $builder->getForm();
// ファイルの登録
$images = [];
$SetProductImages = $SetProduct->getSetProductImage();
foreach ($SetProductImages as $SetProductImage) {
$images[] = $SetProductImage->getFileName();
}
$form['images']->setData($images);
//学校インプットのデーターを用意
$School = [];
$SetProductSchools = $SetProduct->getSetProductSchool();
foreach ($SetProductSchools as $SetProductSchool) {
$School[] = $SetProductSchool->getSchool();
}
$form['school']->setData($School);
$ProductList = [];
$ProductsInSet = $SetProduct->getSetProductProduct();
foreach ($ProductsInSet as $ProductInSet) {
$product_content = [];
$cat_id = $ProductInSet->getCategory()->getId();
$product_content['item_cat'] = $cat_id;
$product_content['item_pct'] = $ProductInSet->getProduct()->getId();
$product_content['item_price'] = $ProductInSet->getSetProductPrice();
$product_content['category_products'] = $this->getProductByCateogory($cat_id);
$ProductList[] = $product_content;
}
$form['product_list']->setData($ProductList);
$categories = [];
$AllCategories = $this->categoryRepository->findAll();
foreach ($AllCategories as $category) {
$categories[] = $category;
}
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
log_info('商品登録開始', [$id]);
$SetProduct = $form->getData();
$Schools = $form->get('school')->getData();
$this->entityManager->persist($SetProduct);
$this->entityManager->flush();
// 学校の登録
// 一度クリア
foreach ($SetProduct->getSetProductSchool() as $SetProductSchool) {
$SetProduct->removeSetProductSchool($SetProductSchool);
$this->entityManager->remove($SetProductSchool);
}
$this->entityManager->persist($SetProduct);
$this->entityManager->flush();
// 学校の保存
foreach ($Schools as $School) {
$SetProductSchool = new \Customize\Entity\SetProductSchool();
$SetProductSchool
->setSetProduct($SetProduct)
->setSchool($School);
$SetProduct->addSetProductSchool($SetProductSchool);
$this->entityManager->persist($SetProductSchool);
}
// 画像の登録
$add_images = $form->get('add_images')->getData();
foreach ($add_images as $add_image) {
$SetProductImage = new \Customize\Entity\SetProductImage();
$SetProductImage
->setFileName($add_image)
->setSetProduct($SetProduct)
->setSortNo(1);
$SetProduct->addSetProductImage($SetProductImage);
$this->entityManager->persist($SetProductImage);
// 移動
$file = new File($this->eccubeConfig['eccube_temp_image_dir'] . '/' . $add_image);
$file->move($this->eccubeConfig['eccube_save_image_dir']);
}
// 画像の削除
$delete_images = $form->get('delete_images')->getData();
$fs = new Filesystem();
foreach ($delete_images as $delete_image) {
$SetProductImage = $this->setProductImageRepository->findOneBy([
'SetProduct' => $SetProduct,
'file_name' => $delete_image,
]);
if ($SetProductImage instanceof SetProductImage) {
$SetProduct->removeSetProductImage($SetProductImage);
$this->entityManager->remove($SetProductImage);
$this->entityManager->flush();
// 他に同じ画像を参照する商品がなければ画像ファイルを削除
if (!$this->setProductImageRepository->findOneBy(['file_name' => $delete_image])) {
$fs->remove($this->eccubeConfig['eccube_save_image_dir'] . '/' . $delete_image);
}
} else {
// 追加してすぐに削除した画像は、Entityに追加されない
$fs->remove($this->eccubeConfig['eccube_temp_image_dir'] . '/' . $delete_image);
}
}
$this->entityManager->flush();
$this->setProductRepository->emptySetProductProduct($SetProduct);
$params_for_input = $request->request->all();
$cat_ids = $params_for_input['item_cats'];
$pct_ids = $params_for_input['item_ids'];
$pct_prices = $params_for_input['item_prices'];
$new_set_price = 0;
for ($i = 0; $i < count($pct_ids); $i++) {
$ProductItem = $this->productRepository->findOneBy(['id' => $pct_ids[$i]]);
$ProductCategory = $this->categoryRepository->findOneBy(['id' => $cat_ids[$i]]);
$SetProductProduct = new \Customize\Entity\SetProductProduct();
$SetProductProduct
->setSetProduct($SetProduct)
->setCategory($ProductCategory)
->setProduct($ProductItem)
->setSetProductPrice($pct_prices[$i])
->setSortNo($i + 1);
$new_set_price += $pct_prices[$i];
$this->entityManager->persist($SetProductProduct);
}
$this->entityManager->flush();
$SetProduct->setFee(isset($params_for_input['fee']) ? array_sum($params_for_input['fee']) : 0);
$SetProduct->setShippingFee(isset($params_for_input['shipping_fee']) ? array_sum($params_for_input['shipping_fee']) : 0);
$SetProduct->setDiscount(isset($params_for_input['discount']) ? array_sum($params_for_input['discount']) : 0);
$new_set_price += $SetProduct->getFee() + $SetProduct->getShippingFee() + $SetProduct->getDiscount();
$SetProduct->setTotal($new_set_price);
$this->entityManager->persist($SetProduct);
$this->entityManager->flush();
$sortNos = $request->get('sort_no_images');
if ($sortNos) {
foreach ($sortNos as $sortNo) {
list($filename, $sortNo_val) = explode('//', $sortNo);
$SetProductImage = $this->setProductImageRepository
->findOneBy([
'file_name' => $filename,
'SetProduct' => $SetProduct,
]);
$SetProductImage->setSortNo($sortNo_val);
$this->entityManager->persist($SetProductImage);
}
}
$this->entityManager->flush();
$SetProduct->setUpdateDate(new \DateTime());
$this->entityManager->flush();
if ($SetProduct->getSex())
$set_target_sex = $SetProduct->getSex()->getId() == 1 ? "男子" : "女子";
else
$set_target_sex = "";
$Product->setSetProductId($SetProduct->getId())
->setProductType('set')
->setName($SetProduct->getSetName())
->setStatus($SetProduct->getStatus())
->setNote($SetProduct->getNote())
->setDescriptionList($SetProduct->getDescriptionList())
->setDescriptionDetail($SetProduct->getDescriptionDetail())
->setSearchWord($set_target_sex . $SetProduct->getSearchWord())
->setFreeArea($SetProduct->getFreeArea());
$this->entityManager->persist($Product);
$this->entityManager->flush();
foreach ($Product->getProductSchool() as $ProductSchool) {
$Product->removeProductSchool($ProductSchool);
$this->entityManager->remove($ProductSchool);
}
$this->entityManager->persist($Product);
$this->entityManager->flush();
foreach ($Schools as $School) {
$ProductSchool = new \Customize\Entity\ProductSchool();
$ProductSchool
->setProduct($Product)
->setSchool($School);
$Product->addProductSchool($ProductSchool);
$this->entityManager->persist($ProductSchool);
}
$this->entityManager->flush();
// 画像の登録
foreach ($add_images as $add_image) {
$ProductImage = new \Eccube\Entity\ProductImage();
$ProductImage
->setFileName($add_image)
->setProduct($Product)
->setSortNo(1);
$Product->addProductImage($ProductImage);
$this->entityManager->persist($ProductImage);
}
// 画像の削除
foreach ($delete_images as $delete_image) {
$ProductImage = $this->productImageRepository->findOneBy([
'Product' => $Product,
'file_name' => $delete_image,
]);
if ($ProductImage instanceof ProductImage) {
$Product->removeProductImage($ProductImage);
$this->entityManager->remove($ProductImage);
$this->entityManager->flush();
}
}
$ProductClass = $this->productClassRepository->findOneBy(['Product' => $Product]);
if (!$ProductClass) {
$ProductClass = new ProductClass();
}
$SaleType = $this->saleTypeRepository->findOneBy([], ['sort_no' => 'ASC']);
$ProductClass->setProduct($Product)
->setProductType('set')
->setVisible(1)
->setStockUnlimited(1)
->setSaleType($SaleType)
->setPrice02($SetProduct->getTotal());
$this->entityManager->persist($ProductClass);
$this->entityManager->flush();
$ProductStock = $this->productStockRepository->findOneBy(['ProductClass' => $ProductClass]);
if (!$ProductStock) {
$ProductStock = new ProductStock();
}
$ProductStock->setProductClass($ProductClass);
$this->entityManager->persist($ProductStock);
$this->entityManager->flush();
log_info('商品登録完了', [$id]);
// $event = new EventArgs(
// [
// 'form' => $form,
// 'SetProduct' => $SetProduct,
// ],
// $request
// );
// $this->eventDispatcher->dispatch($event, EccubeEvents::ADMIN_PRODUCT_EDIT_COMPLETE);
$this->addSuccess('admin.common.save_complete', 'admin');
if ($returnLink = $form->get('return_link')->getData()) {
try {
// $returnLinkはpathの形式で渡される. pathが存在するかをルータでチェックする.
$pattern = '/^' . preg_quote($request->getBasePath(), '/') . '/';
$returnLink = preg_replace($pattern, '', $returnLink);
$result = $router->match($returnLink);
// パラメータのみ抽出
$params = array_filter($result, function ($key) {
return 0 !== \strpos($key, '_');
}, ARRAY_FILTER_USE_KEY);
// pathからurlを再構築してリダイレクト.
return $this->redirectToRoute($result['_route'], $params);
} catch (\Exception $e) {
// マッチしない場合はログ出力してスキップ.
log_warning('URLの形式が不正です。');
}
}
$cacheUtil->clearDoctrineCache();
return $this->redirectToRoute('admin_product_set_product_edit', ['id' => $SetProduct->getId()]);
}
}
//
// 検索結果の保持
$builder = $this->formFactory
->createBuilder(SearchSetProductType::class);
$event = new EventArgs(
[
'builder' => $builder,
'SetProduct' => $SetProduct,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::ADMIN_SET_PRODUCT_EDIT_SEARCH);
$searchForm = $builder->getForm();
$AllSchools = $this->schoolRepository->findAll();
if ('POST' === $request->getMethod()) {
$searchForm->handleRequest($request);
}
return [
'SetProduct' => $SetProduct,
'form' => $form->createView(),
'searchForm' => $searchForm->createView(),
'id' => $id,
'all_schools' => $AllSchools,
'all_categories' => $categories,
'ProductForSet' => $Product,
];
}
/**
* @Route("/%eccube_admin_route%/product/set_product/{id}/delete", requirements={"id" = "\d+"}, name="admin_product_set_product_delete", methods={"DELETE"})
*/
public function delete(Request $request, $id = null, CacheUtil $cacheUtil)
{
$this->isTokenValid();
$session = $request->getSession();
$page_no = intval($session->get('eccube.admin.set_product.search.page_no'));
$page_no = $page_no ? $page_no : Constant::ENABLED;
$message = null;
$success = false;
if (!is_null($id)) {
/* @var $SetProduct \Customize\Entity\SetProduct */
$SetProduct = $this->setProductRepository->find($id);
if (!$SetProduct) {
if ($request->isXmlHttpRequest()) {
$message = trans('admin.common.delete_error_already_deleted');
return $this->json(['success' => $success, 'message' => $message]);
} else {
$this->deleteMessage();
$rUrl = $this->generateUrl('admin_set_product_page', ['page_no' => $page_no]) . '?resume=' . Constant::ENABLED;
return $this->redirect($rUrl);
}
}
if ($SetProduct instanceof SetProduct) {
log_info('商品削除開始', [$id]);
$deleteImages = $SetProduct->getSetProductImage();
$deleteProductForSet = $this->productRepository->findOneBy(['set_product_id' => $SetProduct->getId(), 'product_type' => 'set']);
try {
$this->setProductRepository->delete($SetProduct);
if ($deleteProductForSet)
$this->productRepository->delete($deleteProductForSet);
$this->entityManager->flush();
$event = new EventArgs(
[
'Product' => $SetProduct,
'ProductClass' => null,
'deleteImages' => $deleteImages,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::ADMIN_SET_PRODUCT_DELETE_COMPLETE);
$deleteImages = $event->getArgument('deleteImages');
// 画像ファイルの削除(commit後に削除させる)
/** @var SetProductImage $deleteImage */
foreach ($deleteImages as $deleteImage) {
if ($this->setProductImageRepository->findOneBy(['file_name' => $deleteImage->getFileName()])) {
continue;
}
try {
$fs = new Filesystem();
$fs->remove($this->eccubeConfig['eccube_save_image_dir'] . '/' . $deleteImage);
} catch (\Exception $e) {
// エラーが発生しても無視する
}
}
log_info('商品削除完了', [$id]);
$success = true;
$message = trans('admin.common.delete_complete');
$cacheUtil->clearDoctrineCache();
} catch (ForeignKeyConstraintViolationException $e) {
log_info('商品削除エラー', [$id]);
$message = trans('admin.common.delete_error_foreign_key', ['%name%' => $SetProduct->getSetName()]);
}
} else {
log_info('商品削除エラー', [$id]);
$message = trans('admin.common.delete_error');
}
} else {
log_info('商品削除エラー', [$id]);
$message = trans('admin.common.delete_error');
}
if ($request->isXmlHttpRequest()) {
return $this->json(['success' => $success, 'message' => $message]);
} else {
if ($success) {
$this->addSuccess($message, 'admin');
} else {
$this->addError($message, 'admin');
}
$rUrl = $this->generateUrl('admin_set_product_page', ['page_no' => $page_no]) . '?resume=' . Constant::ENABLED;
return $this->redirect($rUrl);
}
}
/**
* Bulk public action
*
* @Route("/%eccube_admin_route%/product/bulk/set_product-status/{id}", requirements={"id" = "\d+"}, name="admin_product_bulk_set_product_status", methods={"POST"})
*
* @param Request $request
* @param ProductStatus $ProductStatus
*
* @return RedirectResponse
*/
public function bulkProductStatus(Request $request, ProductStatus $ProductStatus, CacheUtil $cacheUtil)
{
$this->isTokenValid();
/** @var Product[] $SetProducts */
$SetProducts = $this->setProductRepository->findBy(['set_product_id' => $request->get('ids')]);
$count = 0;
foreach ($SetProducts as $SetProduct) {
try {
$SetProduct->setStatus($ProductStatus);
$this->setProductRepository->save($SetProduct);
$Product = $this->productRepository->findOneBy(['set_product_id' => $SetProduct->getId(), 'product_type' => 'set']);
if ($Product) {
$Product->setStatus($ProductStatus);
$this->productRepository->save($Product);
}
$count++;
} catch (\Exception $e) {
$this->addError($e->getMessage(), 'admin');
}
}
try {
if ($count) {
$this->entityManager->flush();
$msg = $this->translator->trans('admin.product.bulk_change_status_complete', [
'%count%' => $count,
'%status%' => $ProductStatus->getName(),
]);
$this->addSuccess($msg, 'admin');
$cacheUtil->clearDoctrineCache();
}
} catch (\Exception $e) {
$this->addError($e->getMessage(), 'admin');
}
return $this->redirectToRoute('admin_set_product', ['resume' => Constant::ENABLED]);
}
/**
* @Route("/%eccube_admin_route%/product/set_product/{id}/copy", requirements={"id" = "\d+"}, name="admin_product_set_product_copy", methods={"POST"})
*/
public function copy(Request $request, $id = null)
{
$this->isTokenValid();
if (!is_null($id)) {
$SetProduct = $this->setProductRepository->find($id);
if ($SetProduct instanceof SetProduct) {
$CopyProduct = clone $SetProduct;
$CopyProduct->copy();
$ProductStatus = $this->productStatusRepository->find(ProductStatus::DISPLAY_HIDE);
$CopyProduct->setStatus($ProductStatus);
$Images = $CopyProduct->getSetProductImage();
foreach ($Images as $Image) {
// 画像ファイルを新規作成
$extension = pathinfo($Image->getFileName(), PATHINFO_EXTENSION);
$filename = date('mdHis') . uniqid('_') . '.' . $extension;
try {
$fs = new Filesystem();
$fs->copy($this->eccubeConfig['eccube_save_image_dir'] . '/' . $Image->getFileName(), $this->eccubeConfig['eccube_save_image_dir'] . '/' . $filename);
} catch (\Exception $e) {
// エラーが発生しても無視する
}
$Image->setFileName($filename);
$this->entityManager->persist($Image);
}
$this->entityManager->persist($CopyProduct);
$this->entityManager->flush();
$event = new EventArgs(
[
'SetProduct' => $SetProduct,
'CopyProduct' => $CopyProduct,
'images' => $Images
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::ADMIN_PRODUCT_COPY_COMPLETE);
$this->addSuccess('admin.product.copy_complete', 'admin');
return $this->redirectToRoute('admin_product_set_product_edit', ['id' => $CopyProduct->getId()]);
} else {
$this->addError('admin.product.copy_error', 'admin');
}
} else {
$msg = trans('admin.product.copy_error');
$this->addError($msg, 'admin');
}
return $this->redirectToRoute('admin_product');
}
}