src/Eccube/Controller/Mypage/MypageController.php line 128

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 Eccube\Controller\Mypage;
  13. use Eccube\Controller\AbstractController;
  14. use Eccube\Entity\BaseInfo;
  15. use Eccube\Entity\Customer;
  16. use Eccube\Entity\Order;
  17. use Eccube\Entity\Product;
  18. use Eccube\Event\EccubeEvents;
  19. use Eccube\Event\EventArgs;
  20. use Eccube\Exception\CartException;
  21. use Eccube\Form\Type\Front\CustomerLoginType;
  22. use Eccube\Repository\BaseInfoRepository;
  23. use Eccube\Repository\CustomerFavoriteProductRepository;
  24. use Eccube\Repository\OrderRepository;
  25. use Eccube\Repository\ProductRepository;
  26. use Eccube\Service\CartService;
  27. use Eccube\Service\PurchaseFlow\PurchaseContext;
  28. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  29. use Knp\Component\Pager\PaginatorInterface;
  30. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  33. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  34. use Symfony\Component\Routing\Annotation\Route;
  35. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  36. use Eccube\Twig\Extension\EccubeExtension;
  37. /******カスタマイズ追加************************ */
  38. use PDO
  39. /********************************************* */
  40. class MypageController extends AbstractController
  41. {
  42.     /**
  43.      * @var ProductRepository
  44.      */
  45.     protected $productRepository;
  46.     /**
  47.      * @var CustomerFavoriteProductRepository
  48.      */
  49.     protected $customerFavoriteProductRepository;
  50.     /**
  51.      * @var BaseInfo
  52.      */
  53.     protected $BaseInfo;
  54.     /**
  55.      * @var CartService
  56.      */
  57.     protected $cartService;
  58.     /**
  59.      * @var OrderRepository
  60.      */
  61.     protected $orderRepository;
  62.     /**
  63.      * @var PurchaseFlow
  64.      */
  65.     protected $purchaseFlow;
  66.     /**
  67.      * @var EccubeExtension
  68.      */
  69.     protected $eccubeExtension;
  70.     /**
  71.      * MypageController constructor.
  72.      *
  73.      * @param OrderRepository $orderRepository
  74.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  75.      * @param CartService $cartService
  76.      * @param BaseInfoRepository $baseInfoRepository
  77.      * @param PurchaseFlow $purchaseFlow
  78.      * @param EccubeExtension $eccubeExtension
  79.      */
  80.     public function __construct(
  81.         OrderRepository $orderRepository,
  82.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  83.         CartService $cartService,
  84.         BaseInfoRepository $baseInfoRepository,
  85.         PurchaseFlow $purchaseFlow,
  86.         EccubeExtension $eccubeExtension
  87.     ) {
  88.         $this->orderRepository $orderRepository;
  89.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  90.         $this->BaseInfo $baseInfoRepository->get();
  91.         $this->cartService $cartService;
  92.         $this->purchaseFlow $purchaseFlow;
  93.         $this->eccubeExtension $eccubeExtension;
  94.     }
  95.     /**
  96.      * ログイン画面.
  97.      *
  98.      * @Route("/mypage/login", name="mypage_login", methods={"GET", "POST"})
  99.      * @Template("Mypage/login.twig")
  100.      */
  101.     public function login(Request $requestAuthenticationUtils $utils)
  102.     {
  103.         if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
  104.             log_info('認証済のためログイン処理をスキップ');
  105.             return $this->redirectToRoute('mypage');
  106.         }
  107.         /* @var $form \Symfony\Component\Form\FormInterface */
  108.         $builder $this->formFactory
  109.             ->createNamedBuilder(''CustomerLoginType::class);
  110.         $builder->get('login_memory')->setData((bool) $request->getSession()->get('_security.login_memory'));
  111.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  112.             $Customer $this->getUser();
  113.             if ($Customer instanceof Customer) {
  114.                 $builder->get('login_email')
  115.                     ->setData($Customer->getEmail());
  116.             }
  117.         }
  118.         $event = new EventArgs(
  119.             [
  120.                 'builder' => $builder,
  121.             ],
  122.             $request
  123.         );
  124.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_MYPAGE_MYPAGE_LOGIN_INITIALIZE);
  125.         $form $builder->getForm();
  126.         return [
  127.             'error' => $utils->getLastAuthenticationError(),
  128.             'form' => $form->createView(),
  129.         ];
  130.     }
  131.     /**
  132.      * マイページ.
  133.      *
  134.      * @Route("/mypage/", name="mypage", methods={"GET"})
  135.      * @Template("Mypage/index.twig")
  136.      */
  137.     public function index(Request $requestPaginatorInterface $paginator)
  138.     {
  139.         $Customer $this->getUser();
  140.         /************************************************************************************** 
  141.          カスタマイズここから  
  142.             1.DB接続
  143.             2.会員情報からcustomer_kbnを取得
  144.             3.sellerなら、セラー専用へジャンプ
  145.         ***************************************************************************************/
  146.         $userId $Customer $Customer->getId() : null;
  147.         $userEmail $Customer $Customer->getUsername() : null;
  148.    
  149.         $pgswitch=0;//管理専用マイページ切り替えフラグ(twig)
  150.         $servername "";
  151.         $username "";
  152.         $password "";
  153.         $dbname "";
  154.         $CustomerId $Customer $Customer->getId() : null;
  155.         // .envファイルを読み込む
  156.         $lines file('.env');
  157.         // 文字列「DATABASE_URL」を検索し、正規表現を使って情報を抽出 コメントアウトも拾うので以下の通り除外を入れる
  158.         foreach ($lines as $line) {
  159.         
  160.             // コメント除外
  161.             if (strpos($line'#') === 0) continue;
  162.             // DATABASE_URLだけ取得
  163.             if (strpos($line'DATABASE_URL=') === 0) {
  164.                 preg_match('/mysql:\/\/([^:]+):([^@]+)@([^\/]+)\/(.+)/'$line$matches);
  165.                 if (count($matches) == 5) {
  166.                     $username $matches[1];
  167.                     $password urldecode($matches[2]);
  168.                     $servername $matches[3];
  169.                     $dbname $matches[4];
  170.                     //デバッグ
  171.                     //var_dump($line);
  172.                     //exit;
  173.                 } else {
  174.                     echo "URLが正しくありません\n";
  175.                 }
  176.                 break;
  177.             }
  178.         } 
  179.         $sql "SELECT customer_kbn FROM dtb_customer WHERE id =:customerid";
  180.         try {
  181.             $conn = new PDO ("mysql:dbname=$dbname; host=$servername;port=3306; charset=utf8"$username$password);
  182.         } catch (PDOException $e) {
  183.             echo 'Connection failed: ' $e->getMessage();
  184.         }        
  185.         $stmt $conn->prepare($sql);
  186.         $stmt->bindParam(':customerid'$CustomerIdPDO::PARAM_INT);
  187.         $stmt->execute();
  188.         $result $stmt->fetch(PDO::FETCH_ASSOC);
  189.         //会員区分(バイヤー・セラー)
  190.         $customerkbn $result['customer_kbn'];
  191.         $pgswitch=0;
  192.         switch($customerkbn)
  193.         {
  194.             case 'deliveryrequestmanager':/* mail:deliveryrequestmanager@sandrea.jp mailpwd:DxGrAU]NAWh#Zx10S eccubepw:Qawe8NH3WwbY! */
  195.                 $pgswitch=1;/* マイページに管理用 hrefボタンをセットするためのフラグ */
  196.                 /* エラーになるのでカット
  197.                 $host = $_SERVER['HTTP_HOST']; 
  198.                 $Location = 'Location: https://' . $host . '/mypage'; 
  199.                 header($Location);    
  200.                 */
  201.                 break; 
  202.             case 'seller':
  203.                 $host $_SERVER['HTTP_HOST']; 
  204.                 //$Location = 'Location: https://' . $host . '/sellerorder'; /*デフォルトは受注一覧:ここが一番の利用ページ*/
  205.                 $Location 'Location: https://' $host;
  206.                 header($Location);    
  207.                 break; 
  208.             default:
  209.         }
  210.         /* カスタマイズここまで    ****************************************************************/
  211.         // 購入処理中/決済処理中ステータスの受注を非表示にする.
  212.         $this->entityManager
  213.             ->getFilters()
  214.             ->enable('incomplete_order_status_hidden');
  215.         // paginator
  216.         $qb $this->orderRepository->getQueryBuilderByCustomer($Customer);
  217.         $event = new EventArgs(
  218.             [
  219.                 'qb' => $qb,
  220.                 'Customer' => $Customer,
  221.             ],
  222.             $request
  223.         );
  224.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_MYPAGE_MYPAGE_INDEX_SEARCH);
  225.         $pagination $paginator->paginate(
  226.             $qb,
  227.             $request->get('pageno'1),
  228.             $this->eccubeConfig['eccube_search_pmax']
  229.         );
  230.         return [
  231.             'pagination' => $pagination,
  232.             'pgswitch'=> $pgswitch,
  233.             'userEmail'=> $userEmail,
  234.         ];
  235.     }
  236.     /**
  237.      * 購入履歴詳細を表示する.
  238.      *
  239.      * @Route("/mypage/history/{order_no}", name="mypage_history", methods={"GET"})
  240.      * @Template("Mypage/history.twig")
  241.      */
  242.     public function history(Request $request$order_no)
  243.     {
  244.         $this->entityManager->getFilters()
  245.             ->enable('incomplete_order_status_hidden');
  246.         $Order $this->orderRepository->findOneBy(
  247.             [
  248.                 'order_no' => $order_no,
  249.                 'Customer' => $this->getUser(),
  250.             ]
  251.         );
  252.         $event = new EventArgs(
  253.             [
  254.                 'Order' => $Order,
  255.             ],
  256.             $request
  257.         );
  258.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_MYPAGE_MYPAGE_HISTORY_INITIALIZE);
  259.         /** @var Order $Order */
  260.         $Order $event->getArgument('Order');
  261.         if (!$Order) {
  262.             throw new NotFoundHttpException();
  263.         }
  264.         $stockOrder true;
  265.         foreach ($Order->getOrderItems() as $orderItem) {
  266.             if ($orderItem->isProduct() && $orderItem->getQuantity() < 0) {
  267.                 $stockOrder false;
  268.                 break;
  269.             }
  270.         }
  271.         return [
  272.             'Order' => $Order,
  273.             'stockOrder' => $stockOrder,
  274.         ];
  275.     }
  276.     /**
  277.      * 再購入を行う.
  278.      *
  279.      * @Route("/mypage/order/{order_no}", name="mypage_order", methods={"PUT"})
  280.      */
  281.     public function order(Request $request$order_no)
  282.     {
  283.         $this->isTokenValid();
  284.         log_info('再注文開始', [$order_no]);
  285.         $Customer $this->getUser();
  286.         /* @var $Order \Eccube\Entity\Order */
  287.         $Order $this->orderRepository->findOneBy(
  288.             [
  289.                 'order_no' => $order_no,
  290.                 'Customer' => $Customer,
  291.             ]
  292.         );
  293.         $event = new EventArgs(
  294.             [
  295.                 'Order' => $Order,
  296.                 'Customer' => $Customer,
  297.             ],
  298.             $request
  299.         );
  300.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_MYPAGE_MYPAGE_ORDER_INITIALIZE);
  301.         if (!$Order) {
  302.             log_info('対象の注文が見つかりません', [$order_no]);
  303.             throw new NotFoundHttpException();
  304.         }
  305.         // エラーメッセージの配列
  306.         $errorMessages = [];
  307.         foreach ($Order->getOrderItems() as $OrderItem) {
  308.             try {
  309.                 if ($OrderItem->getProduct() && $OrderItem->getProductClass()) {
  310.                     $this->cartService->addProduct($OrderItem->getProductClass(), $OrderItem->getQuantity());
  311.                     // 明細の正規化
  312.                     $Carts $this->cartService->getCarts();
  313.                     foreach ($Carts as $Cart) {
  314.                         $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  315.                         // 復旧不可のエラーが発生した場合は追加した明細を削除.
  316.                         if ($result->hasError()) {
  317.                             $this->cartService->removeProduct($OrderItem->getProductClass());
  318.                             foreach ($result->getErrors() as $error) {
  319.                                 $errorMessages[] = $error->getMessage();
  320.                             }
  321.                         }
  322.                         foreach ($result->getWarning() as $warning) {
  323.                             $errorMessages[] = $warning->getMessage();
  324.                         }
  325.                     }
  326.                     $this->cartService->save();
  327.                 }
  328.             } catch (CartException $e) {
  329.                 log_info($e->getMessage(), [$order_no]);
  330.                 $this->addRequestError($e->getMessage());
  331.             }
  332.         }
  333.         foreach ($errorMessages as $errorMessage) {
  334.             $this->addRequestError($errorMessage);
  335.         }
  336.         $event = new EventArgs(
  337.             [
  338.                 'Order' => $Order,
  339.                 'Customer' => $Customer,
  340.             ],
  341.             $request
  342.         );
  343.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_MYPAGE_MYPAGE_ORDER_COMPLETE);
  344.         if ($event->getResponse() !== null) {
  345.             return $event->getResponse();
  346.         }
  347.         log_info('再注文完了', [$order_no]);
  348.         return $this->redirect($this->generateUrl('cart'));
  349.     }
  350.     /**
  351.      * お気に入り商品を表示する.
  352.      *
  353.      * @Route("/mypage/favorite", name="mypage_favorite", methods={"GET"})
  354.      * @Template("Mypage/favorite.twig")
  355.      */
  356.     public function favorite(Request $requestPaginatorInterface $paginator)
  357.     {
  358.         if (!$this->BaseInfo->isOptionFavoriteProduct()) {
  359.             throw new NotFoundHttpException();
  360.         }
  361.         $Customer $this->getUser();
  362.         // paginator
  363.         $qb $this->customerFavoriteProductRepository->getQueryBuilderByCustomer($Customer);
  364.         $event = new EventArgs(
  365.             [
  366.                 'qb' => $qb,
  367.                 'Customer' => $Customer,
  368.             ],
  369.             $request
  370.         );
  371.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_MYPAGE_MYPAGE_FAVORITE_SEARCH);
  372.         $pagination $paginator->paginate(
  373.             $qb,
  374.             $request->get('pageno'1),
  375.             $this->eccubeConfig['eccube_search_pmax'],
  376.             ['wrap-queries' => true]
  377.         );
  378.         return [
  379.             'pagination' => $pagination,
  380.         ];
  381.     }
  382.     /**
  383.      * お気に入り商品を削除する.
  384.      *
  385.      * @Route("/mypage/favorite/{id}/delete", name="mypage_favorite_delete", methods={"DELETE"}, requirements={"id" = "\d+"})
  386.      */
  387.     public function delete(Request $requestProduct $Product)
  388.     {
  389.         $this->isTokenValid();
  390.         $Customer $this->getUser();
  391.         log_info('お気に入り商品削除開始', [$Customer->getId(), $Product->getId()]);
  392.         $CustomerFavoriteProduct $this->customerFavoriteProductRepository->findOneBy(['Customer' => $Customer'Product' => $Product]);
  393.         if ($CustomerFavoriteProduct) {
  394.             $this->customerFavoriteProductRepository->delete($CustomerFavoriteProduct);
  395.         } else {
  396.             throw new BadRequestHttpException();
  397.         }
  398.         $event = new EventArgs(
  399.             [
  400.                 'Customer' => $Customer,
  401.                 'CustomerFavoriteProduct' => $CustomerFavoriteProduct,
  402.             ], $request
  403.         );
  404.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_MYPAGE_MYPAGE_DELETE_COMPLETE);
  405.         log_info('お気に入り商品削除完了', [$Customer->getId(), $CustomerFavoriteProduct->getId()]);
  406.         return $this->redirect($this->generateUrl('mypage_favorite'));
  407.     }
  408.     /**
  409.      * 印刷画面を表示する.
  410.      *
  411.      * @Route("/mypage/{order_no}/{print}/print", name="mypage_print")
  412.      *
  413.      * @param Request $request
  414.      * @param $order_no
  415.      * @param $print
  416.      * @return \Symfony\Component\HttpFoundation\Response
  417.      */
  418.     public function exportPrint(Request $request$order_no$print)
  419.     {
  420.         $Customer $this->getUser();
  421.         /* @var $Order \Eccube\Entity\Order */
  422.         $Order $this->orderRepository->findOneBy(
  423.             [
  424.                 'order_no' => $order_no,
  425.                 'Customer' => $Customer,
  426.             ]
  427.         );
  428.         if (!$Order) {
  429.             throw new NotFoundHttpException();
  430.         }
  431.         $message '';
  432.         foreach ($Order->getTotalByTaxRate() as $rate => $total) {
  433.             $message .= '('.$rate.'%対象: ';
  434.             $message .= $this->eccubeExtension->getPriceFilter($total);
  435.             $message .= ' 内消費税: '.$this->eccubeExtension->getPriceFilter($Order->getTaxByTaxRate()[$rate]).')'.PHP_EOL;
  436.         }
  437.         
  438.         return $this->render('Mypage/print_'.$print.'.twig', [
  439.             'Order' => $Order,
  440.             'message' =>  $message
  441.         ]);
  442.     }
  443. }