Completed
Push — 4.0 ( 268f2c...88f012 )
by Hideki
05:48 queued 10s
created

Eccube/Controller/Admin/Order/OrderController.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.ec-cube.co.jp/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Eccube\Controller\Admin\Order;
15
16
use Eccube\Common\Constant;
17
use Eccube\Controller\AbstractController;
18
use Eccube\Entity\ExportCsvRow;
19
use Eccube\Entity\Master\CsvType;
20
use Eccube\Entity\Master\OrderStatus;
21
use Eccube\Entity\OrderPdf;
22
use Eccube\Entity\Shipping;
23
use Eccube\Event\EccubeEvents;
24
use Eccube\Event\EventArgs;
25
use Eccube\Form\Type\Admin\OrderPdfType;
26
use Eccube\Form\Type\Admin\SearchOrderType;
27
use Eccube\Repository\CustomerRepository;
28
use Eccube\Repository\Master\OrderStatusRepository;
29
use Eccube\Repository\Master\PageMaxRepository;
30
use Eccube\Repository\Master\ProductStatusRepository;
31
use Eccube\Repository\Master\SexRepository;
32
use Eccube\Repository\OrderPdfRepository;
33
use Eccube\Repository\OrderRepository;
34
use Eccube\Repository\PaymentRepository;
35
use Eccube\Repository\ProductStockRepository;
36
use Eccube\Service\CsvExportService;
37
use Eccube\Service\MailService;
38
use Eccube\Service\OrderPdfService;
39
use Eccube\Service\OrderStateMachine;
40
use Eccube\Service\PurchaseFlow\PurchaseFlow;
41
use Eccube\Util\FormUtil;
42
use Knp\Component\Pager\PaginatorInterface;
43
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
44
use Symfony\Component\Form\FormBuilder;
45
use Symfony\Component\HttpFoundation\RedirectResponse;
46
use Symfony\Component\HttpFoundation\Request;
47
use Symfony\Component\HttpFoundation\Response;
48
use Symfony\Component\HttpFoundation\StreamedResponse;
49
use Symfony\Component\Routing\Annotation\Route;
50
use Symfony\Component\Validator\Constraints as Assert;
51
use Symfony\Component\Validator\Validator\ValidatorInterface;
52
53
class OrderController extends AbstractController
54
{
55
    /**
56
     * @var PurchaseFlow
57
     */
58
    protected $purchaseFlow;
59
60
    /**
61
     * @var CsvExportService
62
     */
63
    protected $csvExportService;
64
65
    /**
66
     * @var CustomerRepository
67
     */
68
    protected $customerRepository;
69
70
    /**
71
     * @var PaymentRepository
72
     */
73
    protected $paymentRepository;
74
75
    /**
76
     * @var SexRepository
77
     */
78
    protected $sexRepository;
79
80
    /**
81
     * @var OrderStatusRepository
82
     */
83
    protected $orderStatusRepository;
84
85
    /**
86
     * @var PageMaxRepository
87
     */
88
    protected $pageMaxRepository;
89
90
    /**
91
     * @var ProductStatusRepository
92
     */
93
    protected $productStatusRepository;
94
95
    /**
96
     * @var OrderRepository
97
     */
98
    protected $orderRepository;
99
100
    /** @var OrderPdfRepository */
101
    protected $orderPdfRepository;
102
103
    /**
104
     * @var ProductStockRepository
105
     */
106
    protected $productStockRepository;
107
108
    /** @var OrderPdfService */
109
    protected $orderPdfService;
110
111
    /**
112
     * @var ValidatorInterface
113
     */
114
    protected $validator;
115
116
    /**
117
     * @var OrderStateMachine
118
     */
119
    protected $orderStateMachine;
120
121
    /**
122
     * @var MailService
123
     */
124
    protected $mailService;
125
126
    /**
127
     * OrderController constructor.
128
     *
129
     * @param PurchaseFlow $orderPurchaseFlow
130
     * @param CsvExportService $csvExportService
131
     * @param CustomerRepository $customerRepository
132
     * @param PaymentRepository $paymentRepository
133
     * @param SexRepository $sexRepository
134
     * @param OrderStatusRepository $orderStatusRepository
135
     * @param PageMaxRepository $pageMaxRepository
136
     * @param ProductStatusRepository $productStatusRepository
137
     * @param ProductStockRepository $productStockRepository
138
     * @param OrderRepository $orderRepository
139 28
     * @param OrderPdfRepository $orderPdfRepository
140
     * @param ValidatorInterface $validator
141
     * @param OrderStateMachine $orderStateMachine ;
142
     */
143
    public function __construct(
144
        PurchaseFlow $orderPurchaseFlow,
145
        CsvExportService $csvExportService,
146
        CustomerRepository $customerRepository,
147
        PaymentRepository $paymentRepository,
148
        SexRepository $sexRepository,
149
        OrderStatusRepository $orderStatusRepository,
150
        PageMaxRepository $pageMaxRepository,
151
        ProductStatusRepository $productStatusRepository,
152
        ProductStockRepository $productStockRepository,
153
        OrderRepository $orderRepository,
154
        OrderPdfRepository $orderPdfRepository,
155 28
        ValidatorInterface $validator,
156 28
        OrderStateMachine $orderStateMachine,
157 28
        MailService $mailService
158 28
    ) {
159 28
        $this->purchaseFlow = $orderPurchaseFlow;
160 28
        $this->csvExportService = $csvExportService;
161 28
        $this->customerRepository = $customerRepository;
162 28
        $this->paymentRepository = $paymentRepository;
163 28
        $this->sexRepository = $sexRepository;
164 28
        $this->orderStatusRepository = $orderStatusRepository;
165 28
        $this->pageMaxRepository = $pageMaxRepository;
166 28
        $this->productStatusRepository = $productStatusRepository;
167 28
        $this->productStockRepository = $productStockRepository;
168 28
        $this->orderRepository = $orderRepository;
169
        $this->orderPdfRepository = $orderPdfRepository;
170
        $this->validator = $validator;
171
        $this->orderStateMachine = $orderStateMachine;
172
        $this->mailService = $mailService;
173
    }
174
175
    /**
176
     * 受注一覧画面.
177
     *
178
     * - 検索条件, ページ番号, 表示件数はセッションに保持されます.
179
     * - クエリパラメータでresume=1が指定された場合、検索条件, ページ番号, 表示件数をセッションから復旧します.
180
     * - 各データの, セッションに保持するアクションは以下の通りです.
181
     *   - 検索ボタン押下時
182
     *      - 検索条件をセッションに保存します
183
     *      - ページ番号は1で初期化し、セッションに保存します。
184
     *   - 表示件数変更時
185
     *      - クエリパラメータpage_countをセッションに保存します。
186
     *      - ただし, mtb_page_maxと一致しない場合, eccube_default_page_countが保存されます.
187
     *   - ページング時
188
     *      - URLパラメータpage_noをセッションに保存します.
189
     *   - 初期表示
190
     *      - 検索条件は空配列, ページ番号は1で初期化し, セッションに保存します.
191
     *
192 10
     * @Route("/%eccube_admin_route%/order", name="admin_order")
193
     * @Route("/%eccube_admin_route%/order/page/{page_no}", requirements={"page_no" = "\d+"}, name="admin_order_page")
194 10
     * @Template("@admin/Order/index.twig")
195 10
     */
196
    public function index(Request $request, $page_no = null, PaginatorInterface $paginator)
197 10
    {
198
        $builder = $this->formFactory
199 10
            ->createBuilder(SearchOrderType::class);
200
201 10
        $event = new EventArgs(
202
            [
203 10
                'builder' => $builder,
204
            ],
205 10
            $request
206
        );
207
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_INITIALIZE, $event);
208
209
        $searchForm = $builder->getForm();
210
211
        /**
212
         * ページの表示件数は, 以下の順に優先される.
213
         * - リクエストパラメータ
214 10
         * - セッション
215 10
         * - デフォルト値
216
         * また, セッションに保存する際は mtb_page_maxと照合し, 一致した場合のみ保存する.
217 10
         **/
218 10
        $page_count = $this->session->get('eccube.admin.order.search.page_count',
219
            $this->eccubeConfig->get('eccube_default_page_count'));
220 10
221 1
        $page_count_param = (int) $request->get('page_count');
222 1
        $pageMaxis = $this->pageMaxRepository->findAll();
223
224 View Code Duplication
        if ($page_count_param) {
225 1
            foreach ($pageMaxis as $pageMax) {
226
                if ($page_count_param == $pageMax->getName()) {
227
                    $page_count = $pageMax->getName();
228
                    $this->session->set('eccube.admin.order.search.page_count', $page_count);
229
                    break;
230 10
                }
231 6
            }
232
        }
233 6
234
        if ('POST' === $request->getMethod()) {
235
            $searchForm->handleRequest($request);
236
237 View Code Duplication
            if ($searchForm->isValid()) {
238 5
                /**
239 5
                 * 検索が実行された場合は, セッションに検索条件を保存する.
240
                 * ページ番号は最初のページ番号に初期化する.
241
                 */
242 5
                $page_no = 1;
243 5
                $searchData = $searchForm->getData();
244
245
                // 検索条件, ページ番号をセッションに保持.
246
                $this->session->set('eccube.admin.order.search', FormUtil::getViewData($searchForm));
247 6
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
248
            } else {
249 1
                // 検索エラーの際は, 詳細検索枠を開いてエラー表示する.
250 1
                return [
251 1
                    'searchForm' => $searchForm->createView(),
252
                    'pagination' => [],
253
                    'pageMaxis' => $pageMaxis,
254
                    'page_no' => $page_no,
255
                    'page_count' => $page_count,
256 5
                    'has_errors' => true,
257
                ];
258
            }
259
        } else {
260 1
            if (null !== $page_no || $request->get('resume')) {
261
                /*
262 1
                 * ページ送りの場合または、他画面から戻ってきた場合は, セッションから検索条件を復旧する.
263
                 */
264
                if ($page_no) {
265
                    // ページ送りで遷移した場合.
266
                    $this->session->set('eccube.admin.order.search.page_no', (int) $page_no);
267 1
                } else {
268 1
                    // 他画面から遷移した場合.
269
                    $page_no = $this->session->get('eccube.admin.order.search.page_no', 1);
270
                }
271
                $viewData = $this->session->get('eccube.admin.order.search', []);
272
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
273 4
            } else {
274 4
                /**
275
                 * 初期表示の場合.
276 4
                 */
277
                $page_no = 1;
278
                $viewData = [];
279
280 4
                if ($statusId = (int) $request->get('order_status_id')) {
281
                    $viewData = ['status' => $statusId];
282
                }
283 4
284 4
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
285
286
                // セッション中の検索条件, ページ番号を初期化.
287
                $this->session->set('eccube.admin.order.search', $viewData);
288 10
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
289
            }
290 10
        }
291
292 10
        $qb = $this->orderRepository->getQueryBuilderBySearchDataForAdmin($searchData);
293 10
294
        $event = new EventArgs(
295 10
            [
296
                'qb' => $qb,
297
                'searchData' => $searchData,
298 10
            ],
299
            $request
300 10
        );
301 10
302 10
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_SEARCH, $event);
303 10
304
        $pagination = $paginator->paginate(
305
            $qb,
306
            $page_no,
307 10
            $page_count
308 10
        );
309 10
310 10
        return [
311 10
            'searchForm' => $searchForm->createView(),
312
            'pagination' => $pagination,
313 10
            'pageMaxis' => $pageMaxis,
314
            'page_no' => $page_no,
315
            'page_count' => $page_count,
316
            'has_errors' => false,
317
            'OrderStatuses' => $this->orderStatusRepository->findBy([], ['sort_no' => 'ASC']),
318
        ];
319
    }
320
321 1
    /**
322
     * @Route("/%eccube_admin_route%/order/bulk_delete", name="admin_order_bulk_delete", methods={"POST"})
323 1
     */
324 1
    public function bulkDelete(Request $request)
325 1
    {
326 1
        $this->isTokenValid();
327 1
        $ids = $request->get('ids');
328 1
        foreach ($ids as $order_id) {
329 1
            $Order = $this->orderRepository
0 ignored issues
show
Are you sure the assignment to $Order is correct as $this->orderRepository->find($order_id) (which targets Doctrine\ORM\EntityRepository::find()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
330 1
                ->find($order_id);
331
            if ($Order) {
332
                $this->entityManager->remove($Order);
333
                log_info('受注削除', [$Order->getId()]);
334 1
            }
335
        }
336 1
337
        $this->entityManager->flush();
338 1
339
        $this->addSuccess('admin.common.delete_complete', 'admin');
340
341
        return $this->redirect($this->generateUrl('admin_order', ['resume' => Constant::ENABLED]));
342
    }
343
344
    /**
345
     * 受注CSVの出力.
346
     *
347
     * @Route("/%eccube_admin_route%/order/export/order", name="admin_order_export_order")
348
     *
349
     * @param Request $request
350 1
     *
351
     * @return StreamedResponse
352 1
     */
353 1 View Code Duplication
    public function exportOrder(Request $request)
354 1
    {
355
        $filename = 'order_'.(new \DateTime())->format('YmdHis').'.csv';
356 1
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_ORDER, $filename);
357
        log_info('受注CSV出力ファイル名', [$filename]);
358
359
        return $response;
360
    }
361
362
    /**
363
     * 配送CSVの出力.
364
     *
365
     * @Route("/%eccube_admin_route%/order/export/shipping", name="admin_order_export_shipping")
366
     *
367
     * @param Request $request
368
     *
369
     * @return StreamedResponse
370
     */
371 View Code Duplication
    public function exportShipping(Request $request)
372
    {
373
        $filename = 'shipping_'.(new \DateTime())->format('YmdHis').'.csv';
374
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_SHIPPING, $filename);
375
        log_info('配送CSV出力ファイル名', [$filename]);
376
377
        return $response;
378
    }
379
380
    /**
381
     * @param Request $request
382
     * @param $csvTypeId
383
     * @param string $fileName
384 1
     *
385
     * @return StreamedResponse
386
     */
387 1
    protected function exportCsv(Request $request, $csvTypeId, $fileName)
388
    {
389
        // タイムアウトを無効にする.
390 1
        set_time_limit(0);
391 1
392
        // sql loggerを無効にする.
393 1
        $em = $this->entityManager;
394 1
        $em->getConfiguration()->setSQLLogger(null);
395
396 1
        $response = new StreamedResponse();
397
        $response->setCallback(function () use ($request, $csvTypeId) {
398
            // CSV種別を元に初期化.
399 1
            $this->csvExportService->initCsvType($csvTypeId);
400
401
            // ヘッダ行の出力.
402 1
            $this->csvExportService->exportHeader();
403 1
404
            // 受注データ検索用のクエリビルダを取得.
405
            $qb = $this->csvExportService
406 1
                ->getOrderQueryBuilder($request);
407 1
408 1
            // データ行の出力.
409
            $this->csvExportService->setExportQueryBuilder($qb);
410 1
            $this->csvExportService->exportData(function ($entity, $csvService) use ($request) {
411 1
                $Csvs = $csvService->getCsvs();
412
413 1
                $Order = $entity;
414 1
                $OrderItems = $Order->getOrderItems();
415
416
                foreach ($OrderItems as $OrderItem) {
417 1
                    $ExportCsvRow = new ExportCsvRow();
418
419 1
                    // CSV出力項目と合致するデータを取得.
420 1
                    foreach ($Csvs as $Csv) {
421
                        // 受注データを検索.
422 1
                        $ExportCsvRow->setData($csvService->getData($Csv, $Order));
423
                        if ($ExportCsvRow->isDataNull()) {
424 1
                            // 受注データにない場合は, 受注明細を検索.
425
                            $ExportCsvRow->setData($csvService->getData($Csv, $OrderItem));
426 1
                        }
427
                        if ($ExportCsvRow->isDataNull() && $Shipping = $OrderItem->getShipping()) {
428
                            // 受注明細データにない場合は, 出荷を検索.
429 1
                            $ExportCsvRow->setData($csvService->getData($Csv, $Shipping));
430
                        }
431 1
432 1
                        $event = new EventArgs(
433 1
                            [
434 1
                                'csvService' => $csvService,
435
                                'Csv' => $Csv,
436 1
                                'OrderItem' => $OrderItem,
437
                                'ExportCsvRow' => $ExportCsvRow,
438 1
                            ],
439
                            $request
440 1
                        );
441
                        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_CSV_EXPORT_ORDER, $event);
442
443
                        $ExportCsvRow->pushData();
444
                    }
445 1
446
                    //$row[] = number_format(memory_get_usage(true));
447 1
                    // 出力.
448 1
                    $csvService->fputcsv($ExportCsvRow->getRow());
449
                }
450 1
            });
451 1
        });
452 1
453
        $response->headers->set('Content-Type', 'application/octet-stream');
454 1
        $response->headers->set('Content-Disposition', 'attachment; filename='.$fileName);
455
        $response->send();
456
457
        return $response;
458
    }
459
460
    /**
461
     * Update to order status
462
     *
463
     * @Route("/%eccube_admin_route%/shipping/{id}/order_status", requirements={"id" = "\d+"}, name="admin_shipping_update_order_status", methods={"PUT"})
464
     *
465
     * @param Request $request
466
     * @param Shipping $Shipping
467
     *
468 2
     * @return \Symfony\Component\HttpFoundation\JsonResponse
469
     */
470 2
    public function updateOrderStatus(Request $request, Shipping $Shipping)
471
    {
472
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
473
            return $this->json(['status' => 'NG'], 400);
474 2
        }
475 2
476
        $Order = $Shipping->getOrder();
477 2
        $OrderStatus = $this->entityManager->find(OrderStatus::class, $request->get('order_status'));
478 1
479
        if (!$OrderStatus) {
480
            return $this->json(['status' => 'NG'], 400);
481 1
        }
482
483 1
        $result = [];
484
        try {
485
            if ($Order->getOrderStatus()->getId() == $OrderStatus->getId()) {
486
                log_info('対応状況一括変更スキップ');
487 1
                $result = ['message' => trans('admin.order.skip_change_status', ['%name%' => $Shipping->getId()])];
488 1
            } else {
489 1
                if ($this->orderStateMachine->can($Order, $OrderStatus)) {
490 1
                    if ($OrderStatus->getId() == OrderStatus::DELIVERED) {
491
                        if (!$Shipping->isShipped()) {
492 1
                            $Shipping->setShippingDate(new \DateTime());
493 1
                        }
494 1
                        $allShipped = true;
495
                        foreach ($Order->getShippings() as $Ship) {
496 1
                            if (!$Ship->isShipped()) {
497
                                $allShipped = false;
498
                                break;
499 1
                            }
500 1
                        }
501
                        if ($allShipped) {
502
                            $this->orderStateMachine->apply($Order, $OrderStatus);
503
                        }
504
                    } else {
505
                        $this->orderStateMachine->apply($Order, $OrderStatus);
506 1
                    }
507 1
508 1
                    if ($request->get('notificationMail')) { // for SimpleStatusUpdate
509 1
                        $this->mailService->sendShippingNotifyMail($Shipping);
510
                        $Shipping->setMailSendDate(new \DateTime());
511
                        $result['mail'] = true;
512
                    } else {
513 1
                        $result['mail'] = false;
514 1
                    }
515
                    // 対応中・キャンセルの更新時は商品在庫を増減させているので商品情報を更新
516
                    if ($OrderStatus->getId() == OrderStatus::IN_PROGRESS || $OrderStatus->getId() == OrderStatus::CANCEL) {
517 1
                        foreach ($Order->getOrderItems() as $OrderItem) {
518 1
                            $ProductClass = $OrderItem->getProductClass();
519 1
                            if ($OrderItem->isProduct() && !$ProductClass->isStockUnlimited()) {
520
                                $this->entityManager->flush($ProductClass);
521
                                $ProductStock = $this->productStockRepository->findOneBy(['ProductClass' => $ProductClass]);
522
                                $this->entityManager->flush($ProductStock);
523
                            }
524
                        }
525
                    }
526
                    $this->entityManager->flush($Order);
527 1
                    $this->entityManager->flush($Shipping);
528
529
                    // 会員の場合、購入回数、購入金額などを更新
530
                    if ($Customer = $Order->getCustomer()) {
531
                        $this->orderRepository->updateOrderSummary($Customer);
532
                        $this->entityManager->flush($Customer);
533
                    }
534 View Code Duplication
                } else {
535 1
                    $from = $Order->getOrderStatus()->getName();
536
                    $to = $OrderStatus->getName();
537
                    $result = ['message' => trans('admin.order.failed_to_change_status', [
538
                        '%name%' => $Shipping->getId(),
539
                        '%from%' => $from,
540
                        '%to%' => $to,
541
                    ])];
542
                }
543
544
                log_info('対応状況一括変更処理完了', [$Order->getId()]);
545
            }
546
        } catch (\Exception $e) {
547
            log_error('予期しないエラーです', [$e->getMessage()]);
548
549 2
            return $this->json(['status' => 'NG'], 500);
550
        }
551 2
552
        return $this->json(array_merge(['status' => 'OK'], $result));
553
    }
554
555 2
    /**
556
     * Update to Tracking number.
557 2
     *
558 2
     * @Route("/%eccube_admin_route%/shipping/{id}/tracking_number", requirements={"id" = "\d+"}, name="admin_shipping_update_tracking_number", methods={"PUT"})
559
     *
560 2
     * @param Request $request
561 2
     * @param Shipping $shipping
562 2
     *
563
     * @return Response
564
     */
565
    public function updateTrackingNumber(Request $request, Shipping $shipping)
566
    {
567 2
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
568 1
            return $this->json(['status' => 'NG'], 400);
569 1
        }
570
571 1
        $trackingNumber = mb_convert_kana($request->get('tracking_number'), 'a', 'utf-8');
572 1
        /** @var \Symfony\Component\Validator\ConstraintViolationListInterface $errors */
573
        $errors = $this->validator->validate(
574
            $trackingNumber,
575 1
            [
576
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
577
                new Assert\Regex(
578
                    ['pattern' => '/^[0-9a-zA-Z-]+$/u', 'message' => trans('admin.order.tracking_number_error')]
579 1
                ),
580 1
            ]
581 1
        );
582 1
583
        if ($errors->count() != 0) {
584 1
            log_info('送り状番号入力チェックエラー');
585
            $messages = [];
586
            /** @var \Symfony\Component\Validator\ConstraintViolationInterface $error */
587
            foreach ($errors as $error) {
588
                $messages[] = $error->getMessage();
589
            }
590
591
            return $this->json(['status' => 'NG', 'messages' => $messages], 400);
592
        }
593
594
        try {
595
            $shipping->setTrackingNumber($trackingNumber);
596
            $this->entityManager->flush($shipping);
597
            log_info('送り状番号変更処理完了', [$shipping->getId()]);
598
            $message = ['status' => 'OK', 'shipping_id' => $shipping->getId(), 'tracking_number' => $trackingNumber];
599
600 13
            return $this->json($message);
601
        } catch (\Exception $e) {
602
            log_error('予期しないエラー', [$e->getMessage()]);
603 13
604
            return $this->json(['status' => 'NG'], 500);
605 13
        }
606 1
    }
607 1
608
    /**
609 1
     * @Route("/%eccube_admin_route%/order/export/pdf", name="admin_order_export_pdf")
610
     * @Template("@admin/Order/order_pdf.twig")
611
     *
612
     * @param Request $request
613 12
     *
614
     * @return array|RedirectResponse
615 12
     */
616 11
    public function exportPdf(Request $request)
617
    {
618 11
        // requestから出荷番号IDの一覧を取得する.
619 11
        $ids = $request->get('ids', []);
620 11
621 11
        if (count($ids) == 0) {
622
            $this->addError('admin.order.delivery_note_parameter_error', 'admin');
623
            log_info('The Order cannot found!');
624
625
            return $this->redirectToRoute('admin_order');
626
        }
627 12
628
        /** @var OrderPdf $OrderPdf */
629
        $OrderPdf = $this->orderPdfRepository->find($this->getUser());
630 12
631
        if (!$OrderPdf) {
632
            $OrderPdf = new OrderPdf();
633 12
            $OrderPdf
634
                ->setTitle(trans('admin.order.delivery_note_title__default'))
635
                ->setMessage1(trans('admin.order.delivery_note_message__default1'))
636 12
                ->setMessage2(trans('admin.order.delivery_note_message__default2'))
637
                ->setMessage3(trans('admin.order.delivery_note_message__default3'));
638
        }
639
640
        /**
641
         * @var FormBuilder
642
         */
643
        $builder = $this->formFactory->createBuilder(OrderPdfType::class, $OrderPdf);
644
645
        /* @var \Symfony\Component\Form\Form $form */
646
        $form = $builder->getForm();
647
648 10
        // Formへの設定
649
        $form->get('ids')->setData(implode(',', $ids));
650
651
        return [
652
            'form' => $form->createView(),
653 10
        ];
654
    }
655
656 10
    /**
657 10
     * @Route("/%eccube_admin_route%/order/export/pdf/download", name="admin_order_pdf_download")
658
     * @Template("@admin/Order/order_pdf.twig")
659
     *
660 10
     * @param Request $request
661 7
     *
662
     * @return Response
663 7
     */
664 7
    public function exportPdfDownload(Request $request, OrderPdfService $orderPdfService)
665
    {
666
        /**
667
         * @var FormBuilder
668 3
         */
669
        $builder = $this->formFactory->createBuilder(OrderPdfType::class);
670
671 3
        /* @var \Symfony\Component\Form\Form $form */
672
        $form = $builder->getForm();
673
        $form->handleRequest($request);
674 3
675
        // Validation
676
        if (!$form->isValid()) {
677
            log_info('The parameter is invalid!');
678
679
            return $this->render('@admin/Order/order_pdf.twig', [
680
                'form' => $form->createView(),
681
            ]);
682
        }
683
684 3
        $arrData = $form->getData();
685 3
686 3
        // 購入情報からPDFを作成する
687 3
        $status = $orderPdfService->makePdf($arrData);
688
689
        // 異常終了した場合の処理
690 3
        if (!$status) {
691
            $this->addError('admin.order.export.pdf.download.failure', 'admin');
692
            log_info('Unable to create pdf files! Process have problems!');
693 3
694 3
            return $this->render('@admin/Order/order_pdf.twig', [
695
                'form' => $form->createView(),
696
            ]);
697
        }
698
699 3
        // ダウンロードする
700
        $response = new Response(
701 3
            $orderPdfService->outputPdf(),
702 3
            200,
703
            ['content-type' => 'application/pdf']
704 1
        );
705 1
706
        $downloadKind = $form->get('download_kind')->getData();
707
708 3
        // レスポンスヘッダーにContent-Dispositionをセットし、ファイル名を指定
709
        if ($downloadKind == 1) {
710
            $response->headers->set('Content-Disposition', 'attachment; filename="'.$orderPdfService->getPdfFileName().'"');
711
        } else {
712
            $response->headers->set('Content-Disposition', 'inline; filename="'.$orderPdfService->getPdfFileName().'"');
713
        }
714
715
        log_info('OrderPdf download success!', ['Order ID' => implode(',', $request->get('ids', []))]);
716
717
        $isDefault = isset($arrData['default']) ? $arrData['default'] : false;
718
        if ($isDefault) {
719
            // Save input to DB
720
            $arrData['admin'] = $this->getUser();
721
            $this->orderPdfRepository->save($arrData);
722
        }
723
724
        return $response;
725
    }
726
}
727