<?php
/*
* Plugin Name : SalesRestrictions4
*
* Copyright (C) BraTech Co., Ltd. All Rights Reserved.
* http://www.bratech.co.jp/
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Plugin\SalesRestrictions4;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Eccube\Event\TemplateEvent;
use Eccube\Service\CartService;
use Plugin\SalesRestrictions4\Repository\ProductCustomerRankRepository;
use Plugin\SalesRestrictions4\Service\SalesRestrictionsService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Doctrine\ORM\EntityManagerInterface;
class SalesRestrictionsEvent implements EventSubscriberInterface
{
private $entityManager;
private $authorizationChecker;
private $tokenStorage;
private $cartService;
private $productCustomerRankRepository;
private $salesRestrictionsService;
public function __construct(
EntityManagerInterface $entityManager,
AuthorizationCheckerInterface $authorizationChecker,
TokenStorageInterface $tokenStorage,
CartService $cartService,
ProductCustomerRankRepository $productCustomerRankRepository,
SalesRestrictionsService $salesRestrictionsService
)
{
$this->entityManager = $entityManager;
$this->authorizationChecker = $authorizationChecker;
$this->tokenStorage = $tokenStorage;
$this->cartService = $cartService;
$this->productCustomerRankRepository = $productCustomerRankRepository;
$this->salesRestrictionsService = $salesRestrictionsService;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
'@admin/Product/product.twig' => 'onTemplateAdminProductEdit',
EccubeEvents::ADMIN_PRODUCT_COPY_COMPLETE => 'hookAdminProductCopyComplete',
EccubeEvents::ADMIN_PRODUCT_CSV_EXPORT => 'hookAdminProductCsvExport',
'Product/list.twig' => 'onTemplateProductList',
'Product/detail.twig' => 'onTemplateProductDetail',
EccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE => 'hookProductCartAddComplete',
'csvimportproductext.admin.product.csv.import.product.descriptions' => 'hookAdminProductCsvImportProductDescriptions',
'csvimportproductext.admin.product.csv.import.product.check'=> 'hookAdminProductCsvImportProductCheck',
'csvimportproductext.admin.product.csv.import.product.process' => 'hookAdminProductCsvImportProductProcess',
];
}
public function onTemplateAdminProductEdit(TemplateEvent $event)
{
$source = $event->getSource();
if(preg_match("/\{\%\sfor\sf\sin\sform\sif\sf\.vars\.eccube\_form\_options\.auto\_render\s\%\}/",$source, $result)){
$search = $result[0];
$replace = "{{ include('@SalesRestrictions4/admin/Product/ext_edit.twig') }}" . $search;
$source = str_replace($search, $replace, $source);
}
$event->setSource($source);
}
public function hookAdminProductCopyComplete(EventArgs $event)
{
$Product = $event->getArgument('Product');
$CopyProduct = $event->getArgument('CopyProduct');
$plgProducts = $this->productCustomerRankRepository->findBy(['Product' => $Product]);
if($plgProducts){
foreach($plgProducts as $plgProduct){
$copyPlgProduct = new \Plugin\SalesRestrictions4\Entity\ProductCustomerRank();
$copyPlgProduct->setProduct($CopyProduct);
$copyPlgProduct->setCustomerRankId($plgProduct->getCustomerRankId());
$this->entityManager->persist($copyPlgProduct);
}
$this->entityManager->flush();
}
}
public function hookProductCartAddComplete(EventArgs $event)
{
$Carts = $this->cartService->getCarts();
foreach ($Carts as $Cart){
foreach ($Cart->getCartItems() as $CartItem) {
$ProductClass = $CartItem->getProductClass();
if ($ProductClass) {
$flg = true;
$Product = $ProductClass->getProduct();
$plgProducts = $this->productCustomerRankRepository->getRankIdsforProduct($Product);
if (count($plgProducts) > 0 && !$this->authorizationChecker->isGranted('ROLE_USER')) {
$flg = false;
}
if($this->salesRestrictionsService->checkInstallPlugin('CustomerRank')){
if($this->authorizationChecker->isGranted('ROLE_USER')){
$Customer = $this->tokenStorage->getToken()->getUser();
$CustomerRank = $Customer->getCustomerRank();
if($CustomerRank){
$customer_rank_id = $CustomerRank->getId();
}else{
$customer_rank_id = 0;
}
if(in_array($customer_rank_id, $plgProducts)){
$flg = false;
}
}
}
if(!$flg){
$this->cartService->removeProduct($ProductClass);
}
}
}
}
$this->cartService->save();
}
public function onTemplateProductList(TemplateEvent $event)
{
$parameters = $event->getParameters();
$Products = $parameters['pagination'];
$hiddenIds = [];
foreach($Products as $Product){
$plgProducts = $this->productCustomerRankRepository->getRankIdsforProduct($Product);
if(!$plgProducts)continue;
if($this->salesRestrictionsService->checkInstallPlugin('CustomerRank')){
if ($this->authorizationChecker->isGranted('ROLE_USER')) {
if(count($plgProducts) == 1 && in_array(-1, $plgProducts))continue;
$Customer = $this->tokenStorage->getToken()->getUser();
$CustomerRank = $Customer->getCustomerRank();
if($CustomerRank){
$customer_rank_id = $CustomerRank->getId();
}else{
$customer_rank_id = 0;
}
if(!in_array($customer_rank_id, $plgProducts))continue;
}
}else{
if ($this->authorizationChecker->isGranted('ROLE_USER') || !in_array(-1, $plgProducts))continue;
}
$hiddenIds[] = $Product->getId();
}
$parameters['hiddenIds'] = json_encode($hiddenIds);
$event->setParameters($parameters);
$event->addSnippet('@SalesRestrictions4/default/Product/restrictions_js.twig');
}
public function onTemplateProductDetail(TemplateEvent $event)
{
$parameters = $event->getParameters();
$Product = $parameters['Product'];
$plgProducts = $this->productCustomerRankRepository->getRankIdsforProduct($Product);
if(!$plgProducts)return;
if($this->salesRestrictionsService->checkInstallPlugin('CustomerRank')){
if ($this->authorizationChecker->isGranted('ROLE_USER')) {
if(count($plgProducts) == 1 && in_array(-1, $plgProducts))return;
$Customer = $this->tokenStorage->getToken()->getUser();
$CustomerRank = $Customer->getCustomerRank();
if($CustomerRank){
$customer_rank_id = $CustomerRank->getId();
}else{
$customer_rank_id = 0;
}
if(!in_array($customer_rank_id, $plgProducts))return;
}
}else{
if ($this->authorizationChecker->isGranted('ROLE_USER') || !in_array(-1, $plgProducts))return;
}
$source = $event->getSource();
if(preg_match('/<form.*id="form1".*>/',$source, $result)){
$search = $result[0];
$start_idx = strpos($source,$search);
$sub_source = substr($source,$start_idx);
if(preg_match('/<\/form>/',$sub_source, $result)){
$search = $result[0];
$end_idx = strpos($sub_source,$search);
$target = substr($sub_source,0,$end_idx+strlen($search));
$replace = "{{ include('Product/sales_restrictions_cart.twig') }}";
$source = str_replace($target,$replace,$source);
}
}
$event->setSource($source);
}
public function hookAdminProductCsvExport(EventArgs $event)
{
$ExportCsvRow = $event->getArgument('ExportCsvRow');
if ($ExportCsvRow->isDataNull()) {
$csvService = $event->getArgument('csvService');
$ProductClass = $event->getArgument('ProductClass');
$Product = $ProductClass->getProduct();
$Csv = $event->getArgument('Csv');
$csvEntityName = str_replace('\\\\', '\\', $Csv->getEntityName());
if($csvEntityName == 'Plugin\SalesRestrictions4\Entity\ProductCustomerRank'){
$plgProducts = $this->productCustomerRankRepository->findBy(['Product' => $Product]);
$ret = [];
foreach($plgProducts as $plgProduct){
if($Csv->getFieldName() == 'id'){
$ret[] = $plgProduct->getCustomerRankId();
}elseif($Csv->getFieldName() == 'name'){
$rank_id = $plgProduct->getCustomerRankId();
if($rank_id == -1){
$ret[] = trans('salesrestrictions.form.product.choice.guest');
}else {
if($this->salesRestrictionsService->checkInstallPlugin('CustomerRank')){
if($rank_id == 0){
$ret[] = trans('salesrestrictions.form.product.choice.empty');
}else{
$customerRankRepository = $this->entityManager->getRepository('Plugin\CustomerRank\Entity\CustomerRank');
$CustomerRanks = $customerRankRepository->getList();
foreach($CustomerRanks as $CustomerRank){
if($CustomerRank->getId() == $rank_id)
$ret[] = $CustomerRank->getName();
}
}
}
}
}
}
$value = implode(',', $ret);
$ExportCsvRow->setData($value);
}
}
}
public function hookAdminProductCsvImportProductDescriptions(EventArgs $event)
{
$header = $event->getArgument('header');
$key = $event->getArgument('key');
if($key == trans('salesrestrictions.csv.common.id')){
$header['description'] = trans('salesrestrictions.csv.product.sales_restrictions.description');
$header['required'] = false;
}
$event->setArgument('header',$header);
}
public function hookAdminProductCsvImportProductCheck(EventArgs $event)
{
$row = $event->getArgument('row');
$data = $event->getArgument('data');
$errors = $event->getArgument('errors');
if(isset($row[trans('salesrestrictions.csv.common.id')])){
if($row[trans('salesrestrictions.csv.common.id')] !== ''){
$sales_restrictions = explode(',', $row[trans('salesrestrictions.csv.common.id')]);
foreach($sales_restrictions as $value){
if($value != '' && !is_numeric($value)){
$message = trans('salesrestrictions.csv.product.sales_restrictions.error', [
'%line%' => $data->key() + 1,
'%name%' => trans('salesrestrictions.csv.common.id'),
]);
$errors[] = $message;
break;
}
}
}
}
$event->setArgument('errors',$errors);
}
public function hookAdminProductCsvImportProductProcess(EventArgs $event)
{
$row = $event->getArgument('row');
$data = $event->getArgument('data');
$ProductClass = $event->getArgument('ProductClass');
if(isset($row[trans('salesrestrictions.csv.common.id')])){
$Product = $ProductClass->getProduct();
$plgProducts = $this->productCustomerRankRepository->findBy(['Product' => $Product]);
foreach($plgProducts as $plgProduct){
$this->entityManager->remove($plgProduct);
}
$this->entityManager->flush();
$sales_restrictions = explode(',', $row[trans('salesrestrictions.csv.common.id')]);
if(count($sales_restrictions) > 0){
foreach($sales_restrictions as $value){
if(is_numeric($value)){
$plgProduct = new \Plugin\SalesRestrictions4\Entity\ProductCustomerRank();
$plgProduct->setProduct($Product);
$plgProduct->setCustomerRankId($value);
$this->entityManager->persist($plgProduct);
}
}
$this->entityManager->flush();
}
}
}
}