Failed Conditions
Push — experimental/sf ( 93516f...49de0c )
by chihiro
402:37 queued 395:24
created

Eccube/Controller/Admin/Order/OrderController.php (5 issues)

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) LOCKON CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.lockon.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\Csv;
19
use Eccube\Entity\ExportCsvRow;
20
use Eccube\Entity\Master\CsvType;
21
use Eccube\Entity\OrderItem;
22
use Eccube\Entity\OrderPdf;
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\Service\CsvExportService;
36
use Eccube\Service\MailService;
37
use Eccube\Service\OrderPdfService;
38
use Eccube\Service\OrderStateMachine;
39
use Eccube\Util\FormUtil;
40
use Knp\Component\Pager\PaginatorInterface;
41
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
42
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
43
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
44
use Symfony\Component\Form\FormBuilder;
45
use Symfony\Component\HttpFoundation\Response;
46
use Symfony\Component\HttpFoundation\Request;
47
use Symfony\Component\HttpFoundation\StreamedResponse;
48
use Eccube\Entity\Master\OrderStatus;
49
use Symfony\Component\HttpFoundation\RedirectResponse;
50
use Eccube\Entity\Order;
51
use Eccube\Entity\Shipping;
52
use Eccube\Service\PurchaseFlow\PurchaseFlow;
53
use Symfony\Component\Validator\Constraints as Assert;
54
use Symfony\Component\Validator\Validator\ValidatorInterface;
55
56
class OrderController extends AbstractController
57
{
58
    /**
59
     * @var PurchaseFlow
60
     */
61
    protected $purchaseFlow;
62
63
    /**
64
     * @var CsvExportService
65
     */
66
    protected $csvExportService;
67
68
    /**
69
     * @var CustomerRepository
70
     */
71
    protected $customerRepository;
72
73
    /**
74
     * @var PaymentRepository
75
     */
76
    protected $paymentRepository;
77
78
    /**
79
     * @var SexRepository
80
     */
81
    protected $sexRepository;
82
83
    /**
84
     * @var OrderStatusRepository
85
     */
86
    protected $orderStatusRepository;
87
88
    /**
89
     * @var PageMaxRepository
90
     */
91
    protected $pageMaxRepository;
92
93
    /**
94
     * @var ProductStatusRepository
95
     */
96
    protected $productStatusRepository;
97
98
    /**
99
     * @var OrderRepository
100
     */
101
    protected $orderRepository;
102
103
    /** @var OrderPdfRepository */
104
    protected $orderPdfRepository;
105
106
    /** @var OrderPdfService */
107
    protected $orderPdfService;
108
109
    /**
110
     * @var ValidatorInterface
111
     */
112
    protected $validator;
113
114
    /**
115
     * @var OrderStateMachine
116
     */
117
    protected $orderStateMachine;
118
119
    /**
120
     * @var MailService
121
     */
122
    protected $mailService;
123
124
    /**
0 ignored issues
show
Doc comment for parameter "$mailService" missing
Loading history...
125
     * OrderController constructor.
126
     *
127
     * @param PurchaseFlow $orderPurchaseFlow
128
     * @param CsvExportService $csvExportService
129
     * @param CustomerRepository $customerRepository
130
     * @param PaymentRepository $paymentRepository
131
     * @param SexRepository $sexRepository
132
     * @param OrderStatusRepository $orderStatusRepository
133
     * @param PageMaxRepository $pageMaxRepository
134
     * @param ProductStatusRepository $productStatusRepository
135
     * @param OrderRepository $orderRepository
136
     * @param OrderPdfRepository $orderPdfRepository
0 ignored issues
show
Expected 6 spaces after parameter type; 1 found
Loading history...
137
     * @param OrderPdfService $orderPdfService
0 ignored issues
show
Expected 9 spaces after parameter type; 1 found
Loading history...
138
     * @param ValidatorInterface $validator
0 ignored issues
show
Expected 6 spaces after parameter type; 1 found
Loading history...
139
     * @param OrderStateMachine $orderStateMachine ;
0 ignored issues
show
Expected 7 spaces after parameter name; 1 found
Loading history...
140
     */
141 28
    public function __construct(
142
        PurchaseFlow $orderPurchaseFlow,
143
        CsvExportService $csvExportService,
144
        CustomerRepository $customerRepository,
145
        PaymentRepository $paymentRepository,
146
        SexRepository $sexRepository,
147
        OrderStatusRepository $orderStatusRepository,
148
        PageMaxRepository $pageMaxRepository,
149
        ProductStatusRepository $productStatusRepository,
150
        OrderRepository $orderRepository,
151
        OrderPdfRepository $orderPdfRepository,
152
        OrderPdfService $orderPdfService,
153
        ValidatorInterface $validator,
154
        OrderStateMachine $orderStateMachine,
155
        MailService $mailService
156
    ) {
157 28
        $this->purchaseFlow = $orderPurchaseFlow;
158 28
        $this->csvExportService = $csvExportService;
159 28
        $this->customerRepository = $customerRepository;
160 28
        $this->paymentRepository = $paymentRepository;
161 28
        $this->sexRepository = $sexRepository;
162 28
        $this->orderStatusRepository = $orderStatusRepository;
163 28
        $this->pageMaxRepository = $pageMaxRepository;
164 28
        $this->productStatusRepository = $productStatusRepository;
165 28
        $this->orderRepository = $orderRepository;
166 28
        $this->orderPdfRepository = $orderPdfRepository;
167 28
        $this->orderPdfService = $orderPdfService;
168 28
        $this->validator = $validator;
169 28
        $this->orderStateMachine = $orderStateMachine;
170 28
        $this->mailService = $mailService;
171
    }
172
173
    /**
174
     * 受注一覧画面.
175
     *
176
     * - 検索条件, ページ番号, 表示件数はセッションに保持されます.
177
     * - クエリパラメータでresume=1が指定された場合、検索条件, ページ番号, 表示件数をセッションから復旧します.
178
     * - 各データの, セッションに保持するアクションは以下の通りです.
179
     *   - 検索ボタン押下時
180
     *      - 検索条件をセッションに保存します
181
     *      - ページ番号は1で初期化し、セッションに保存します。
182
     *   - 表示件数変更時
183
     *      - クエリパラメータpage_countをセッションに保存します。
184
     *      - ただし, mtb_page_maxと一致しない場合, eccube_default_page_countが保存されます.
185
     *   - ページング時
186
     *      - URLパラメータpage_noをセッションに保存します.
187
     *   - 初期表示
188
     *      - 検索条件は空配列, ページ番号は1で初期化し, セッションに保存します.
189
     *
190
     * @Route("/%eccube_admin_route%/order", name="admin_order")
191
     * @Route("/%eccube_admin_route%/order/page/{page_no}", requirements={"page_no" = "\d+"}, name="admin_order_page")
192
     * @Template("@admin/Order/index.twig")
193
     */
194 10
    public function index(Request $request, $page_no = null, PaginatorInterface $paginator)
195
    {
196 10
        $builder = $this->formFactory
197 10
            ->createBuilder(SearchOrderType::class);
198
199 10
        $event = new EventArgs(
200
            [
201 10
                'builder' => $builder,
202
            ],
203 10
            $request
204
        );
205 10
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_INITIALIZE, $event);
206
207 10
        $searchForm = $builder->getForm();
208
209
        /**
210
         * ページの表示件数は, 以下の順に優先される.
211
         * - リクエストパラメータ
212
         * - セッション
213
         * - デフォルト値
214
         * また, セッションに保存する際は mtb_page_maxと照合し, 一致した場合のみ保存する.
215
         **/
216 10
        $page_count = $this->session->get('eccube.admin.order.search.page_count',
217 10
            $this->eccubeConfig->get('eccube_default_page_count'));
218
219 10
        $page_count_param = (int) $request->get('page_count');
220 10
        $pageMaxis = $this->pageMaxRepository->findAll();
221
222 10
        if ($page_count_param) {
223 1
            foreach ($pageMaxis as $pageMax) {
224 1
                if ($page_count_param == $pageMax->getName()) {
225
                    $page_count = $pageMax->getName();
226
                    $this->session->set('eccube.admin.order.search.page_count', $page_count);
227 1
                    break;
228
                }
229
            }
230
        }
231
232 10
        if ('POST' === $request->getMethod()) {
233 6
            $searchForm->handleRequest($request);
234
235 6
            if ($searchForm->isValid()) {
236
                /**
237
                 * 検索が実行された場合は, セッションに検索条件を保存する.
238
                 * ページ番号は最初のページ番号に初期化する.
239
                 */
240 5
                $page_no = 1;
241 5
                $searchData = $searchForm->getData();
242
243
                // 検索条件, ページ番号をセッションに保持.
244 5
                $this->session->set('eccube.admin.order.search', FormUtil::getViewData($searchForm));
245 5
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
246
            } else {
247
                // 検索エラーの際は, 詳細検索枠を開いてエラー表示する.
248
                return [
249 6
                    'searchForm' => $searchForm->createView(),
250
                    'pagination' => [],
251 1
                    'pageMaxis' => $pageMaxis,
252 1
                    'page_no' => $page_no,
253 1
                    'page_count' => $page_count,
254
                    'has_errors' => true,
255
                ];
256
            }
257
        } else {
258 5
            if (null !== $page_no || $request->get('resume')) {
259
                /*
260
                 * ページ送りの場合または、他画面から戻ってきた場合は, セッションから検索条件を復旧する.
261
                 */
262 1
                if ($page_no) {
263
                    // ページ送りで遷移した場合.
264 1
                    $this->session->set('eccube.admin.order.search.page_no', (int) $page_no);
265
                } else {
266
                    // 他画面から遷移した場合.
267
                    $page_no = $this->session->get('eccube.admin.order.search.page_no', 1);
268
                }
269 1
                $viewData = $this->session->get('eccube.admin.order.search', []);
270 1
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
271
            } else {
272
                /**
273
                 * 初期表示の場合.
274
                 */
275 4
                $page_no = 1;
276 4
                $viewData = [];
277
278 4
                if ($statusId = (int) $request->get('order_status_id')) {
279
                    $viewData = ['status' => $statusId];
280
                }
281
282 4
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
283
284
                // セッション中の検索条件, ページ番号を初期化.
285 4
                $this->session->set('eccube.admin.order.search', $viewData);
286 4
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
287
            }
288
        }
289
290 10
        $qb = $this->orderRepository->getQueryBuilderBySearchDataForAdmin($searchData);
291
292 10
        $event = new EventArgs(
293
            [
294 10
                'qb' => $qb,
295 10
                'searchData' => $searchData,
296
            ],
297 10
            $request
298
        );
299
300 10
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_SEARCH, $event);
301
302 10
        $pagination = $paginator->paginate(
303 10
            $qb,
304 10
            $page_no,
305 10
            $page_count
306
        );
307
308
        return [
309 10
            'searchForm' => $searchForm->createView(),
310 10
            'pagination' => $pagination,
311 10
            'pageMaxis' => $pageMaxis,
312 10
            'page_no' => $page_no,
313 10
            'page_count' => $page_count,
314
            'has_errors' => false,
315 10
            'OrderStatuses' => $this->orderStatusRepository->findBy([], ['sort_no' => 'ASC']),
316
        ];
317
    }
318
319
    /**
320
     * @Method("POST")
321
     * @Route("/%eccube_admin_route%/order/bulk_delete", name="admin_order_bulk_delete")
322
     */
323 1
    public function bulkDelete(Request $request)
324
    {
325 1
        $this->isTokenValid();
326 1
        $ids = $request->get('ids');
327 1
        foreach ($ids as $order_id) {
328 1
            $Order = $this->orderRepository
329 1
                ->find($order_id);
330 1
            if ($Order) {
331 1
                $this->entityManager->remove($Order);
332 1
                log_info('受注削除', [$Order->getId()]);
333
            }
334
        }
335
336 1
        $this->entityManager->flush();
337
338 1
        $this->addSuccess('admin.order.delete.complete', 'admin');
339
340 1
        return $this->redirect($this->generateUrl('admin_order', ['resume' => Constant::ENABLED]));
341
    }
342
343
    /**
344
     * 受注CSVの出力.
345
     *
346
     * @Route("/%eccube_admin_route%/order/export/order", name="admin_order_export_order")
347
     *
348
     * @param Request $request
349
     *
350
     * @return StreamedResponse
351
     */
352 1 View Code Duplication
    public function exportOrder(Request $request)
353
    {
354 1
        $filename = 'order_'.(new \DateTime())->format('YmdHis').'.csv';
355 1
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_ORDER, $filename);
356 1
        log_info('受注CSV出力ファイル名', [$filename]);
357
358 1
        return $response;
359
    }
360
361
    /**
362
     * 配送CSVの出力.
363
     *
364
     * @Route("/%eccube_admin_route%/order/export/shipping", name="admin_order_export_shipping")
365
     *
366
     * @param Request $request
367
     *
368
     * @return StreamedResponse
369
     */
370 View Code Duplication
    public function exportShipping(Request $request)
371
    {
372
        $filename = 'shipping_'.(new \DateTime())->format('YmdHis').'.csv';
373
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_SHIPPING, $filename);
374
        log_info('配送CSV出力ファイル名', [$filename]);
375
376
        return $response;
377
    }
378
379
    /**
380
     * @param Request $request
381
     * @param $csvTypeId
382
     * @param $fileName
383
     *
384
     * @return StreamedResponse
385
     */
386 1
    private function exportCsv(Request $request, $csvTypeId, $fileName)
387
    {
388
        // タイムアウトを無効にする.
389 1
        set_time_limit(0);
390
391
        // sql loggerを無効にする.
392 1
        $em = $this->entityManager;
393 1
        $em->getConfiguration()->setSQLLogger(null);
394
395 1
        $response = new StreamedResponse();
396 1
        $response->setCallback(function () use ($request, $csvTypeId) {
397
            // CSV種別を元に初期化.
398 1
            $this->csvExportService->initCsvType($csvTypeId);
399
400
            // ヘッダ行の出力.
401 1
            $this->csvExportService->exportHeader();
402
403
            // 受注データ検索用のクエリビルダを取得.
404 1
            $qb = $this->csvExportService
405 1
                ->getOrderQueryBuilder($request);
406
407
            // データ行の出力.
408 1
            $this->csvExportService->setExportQueryBuilder($qb);
409 1
            $this->csvExportService->exportData(function ($entity, $csvService) use ($request) {
410 1
                $Csvs = $csvService->getCsvs();
411
412 1
                $Order = $entity;
413 1
                $OrderItems = $Order->getOrderItems();
414
415 1
                foreach ($OrderItems as $OrderItem) {
416 1
                    $ExportCsvRow = new ExportCsvRow();
417
418
                    // CSV出力項目と合致するデータを取得.
419 1
                    foreach ($Csvs as $Csv) {
420
                        // 受注データを検索.
421 1
                        $ExportCsvRow->setData($csvService->getData($Csv, $Order));
422 1
                        if ($ExportCsvRow->isDataNull()) {
423
                            // 受注データにない場合は, 受注明細を検索.
424 1
                            $ExportCsvRow->setData($csvService->getData($Csv, $OrderItem));
425
                        }
426 1
                        if ($ExportCsvRow->isDataNull() && $Shipping = $OrderItem->getShipping()) {
427
                            // 受注明細データにない場合は, 出荷を検索.
428 1
                            $ExportCsvRow->setData($csvService->getData($Csv, $Shipping));
429
                        }
430
431 1
                        $event = new EventArgs(
432
                            [
433 1
                                'csvService' => $csvService,
434 1
                                'Csv' => $Csv,
435 1
                                'OrderItem' => $OrderItem,
436 1
                                'ExportCsvRow' => $ExportCsvRow,
437
                            ],
438 1
                            $request
439
                        );
440 1
                        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_CSV_EXPORT_ORDER, $event);
441
442 1
                        $ExportCsvRow->pushData();
443
                    }
444
445
                    //$row[] = number_format(memory_get_usage(true));
446
                    // 出力.
447 1
                    $csvService->fputcsv($ExportCsvRow->getRow());
448
                }
449 1
            });
450 1
        });
451
452 1
        $response->headers->set('Content-Type', 'application/octet-stream');
453 1
        $response->headers->set('Content-Disposition', 'attachment; filename='.$fileName);
454 1
        $response->send();
455
456 1
        return $response;
457
    }
458
459
    /**
460
     * Update to order status
461
     *
462
     * @Method("PUT")
463
     * @Route("/%eccube_admin_route%/shipping/{id}/order_status", requirements={"id" = "\d+"}, name="admin_shipping_update_order_status")
464
     *
465
     * @param Request $request
466
     * @param Shipping $shipping
467
     *
468
     * @return RedirectResponse
469
     */
470 2
    public function updateOrderStatus(Request $request, Shipping $Shipping)
471
    {
472 2
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
473
            return $this->json(['status' => 'NG'], 400);
474
        }
475
476 2
        $Order = $Shipping->getOrder();
477 2
        $OrderStatus = $this->entityManager->find(OrderStatus::class, $request->get('order_status'));
478
479 2
        if (!$OrderStatus) {
480 1
            return $this->json(['status' => 'NG'], 400);
481
        }
482
483 1
        $result = [];
484
        try {
485 1
            if ($Order->getOrderStatus()->getId() == $OrderStatus->getId()) {
486
                log_info('対応状況一括変更スキップ');
487
                $result = ['message' => sprintf('%s:  ステータス変更をスキップしました', $Shipping->getId())];
488
            } else {
489 1
                if ($this->orderStateMachine->can($Order, $OrderStatus)) {
490 1
                    $this->orderStateMachine->apply($Order, $OrderStatus);
491
492 1
                    if ($request->get('notificationMail')) { // for SimpleStatusUpdate
493 1
                        $this->mailService->sendShippingNotifyMail($Shipping);
494 1
                        $Shipping->setMailSendDate(new \DateTime());
495 1
                        $result['mail'] = true;
496
                    } else {
497
                        $result['mail'] = false;
498
                    }
499 1
                    $this->entityManager->flush($Shipping);
500 1
                    $this->entityManager->flush($Order);
501
502
                    // 会員の場合、購入回数、購入金額などを更新
503 1
                    if ($Customer = $Order->getCustomer()) {
504 1
                        $this->orderRepository->updateOrderSummary($Customer);
505 1
                        $this->entityManager->flush($Customer);
506
                    }
507
                } else {
508
                    $from = $Order->getOrderStatus()->getName();
509
                    $to = $OrderStatus->getName();
510
                    $result = ['message' => sprintf('%s: %s から %s へのステータス変更はできません', $Shipping->getId(), $from, $to)];
511
                }
512
513 1
                log_info('対応状況一括変更処理完了', [$Order->getId()]);
514
            }
515
        } catch (\Exception $e) {
516
            log_error('予期しないエラーです', [$e->getMessage()]);
517
518
            return $this->json(['status' => 'NG'], 500);
519
        }
520
521 1
        return $this->json(array_merge(['status' => 'OK'], $result));
522
    }
523
524
    /**
525
     * Update to Tracking number.
526
     *
527
     * @Method("PUT")
528
     * @Route("/%eccube_admin_route%/shipping/{id}/tracking_number", requirements={"id" = "\d+"}, name="admin_shipping_update_tracking_number")
529
     *
530
     * @param Request $request
531
     * @param Shipping $shipping
532
     *
533
     * @return Response
534
     */
535 2
    public function updateTrackingNumber(Request $request, Shipping $shipping)
536
    {
537 2
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
538
            return $this->json(['status' => 'NG'], 400);
539
        }
540
541 2
        $trackingNumber = mb_convert_kana($request->get('tracking_number'), 'a', 'utf-8');
542
        /** @var \Symfony\Component\Validator\ConstraintViolationListInterface $errors */
543 2
        $errors = $this->validator->validate(
544 2
            $trackingNumber,
545
            [
546 2
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
547 2
                new Assert\Regex(
548 2
                    ['pattern' => '/^[0-9a-zA-Z-]+$/u', 'message' => trans('form.type.admin.nottrackingnumberstyle')]
549
                ),
550
            ]
551
        );
552
553 2
        if ($errors->count() != 0) {
554 1
            log_info('送り状番号入力チェックエラー');
555 1
            $messages = [];
556
            /** @var \Symfony\Component\Validator\ConstraintViolationInterface $error */
557 1
            foreach ($errors as $error) {
558 1
                $messages[] = $error->getMessage();
559
            }
560
561 1
            return $this->json(['status' => 'NG', 'messages' => $messages], 400);
562
        }
563
564
        try {
565 1
            $shipping->setTrackingNumber($trackingNumber);
566 1
            $this->entityManager->flush($shipping);
567 1
            log_info('送り状番号変更処理完了', [$shipping->getId()]);
568 1
            $message = ['status' => 'OK', 'shipping_id' => $shipping->getId(), 'tracking_number' => $trackingNumber];
569
570 1
            return $this->json($message);
571
        } catch (\Exception $e) {
572
            log_error('予期しないエラー', [$e->getMessage()]);
573
574
            return $this->json(['status' => 'NG'], 500);
575
        }
576
    }
577
578
    /**
579
     * @Route("/%eccube_admin_route%/order/export/pdf", name="admin_order_export_pdf")
580
     * @Template("@admin/Order/order_pdf.twig")
581
     *
582
     * @param Request $request
583
     *
584
     * @return array|RedirectResponse
585
     */
586 13
    public function exportPdf(Request $request)
587
    {
588
        // requestから受注番号IDの一覧を取得する.
589 13
        $ids = $request->get('ids', []);
590
591 13
        if (count($ids) == 0) {
592 1
            $this->addError('admin.order.export.pdf.parameter.not.found', 'admin');
593 1
            log_info('The Order cannot found!');
594
595 1
            return $this->redirectToRoute('admin_order');
596
        }
597
598
        /** @var OrderPdf $OrderPdf */
599 12
        $OrderPdf = $this->orderPdfRepository->find($this->getUser());
600
601 12
        if (!$OrderPdf) {
602 11
            $OrderPdf = new OrderPdf();
603
            $OrderPdf
604 11
                ->setTitle(trans('admin.order.export.pdf.title.default'))
605 11
                ->setMessage1(trans('admin.order.export.pdf.message1.default'))
606 11
                ->setMessage2(trans('admin.order.export.pdf.message2.default'))
607 11
                ->setMessage3(trans('admin.order.export.pdf.message3.default'));
608
        }
609
610
        /**
611
         * @var FormBuilder
612
         */
613 12
        $builder = $this->formFactory->createBuilder(OrderPdfType::class, $OrderPdf);
614
615
        /* @var \Symfony\Component\Form\Form $form */
616 12
        $form = $builder->getForm();
617
618
        // Formへの設定
619 12
        $form->get('ids')->setData(implode(',', $ids));
620
621
        return [
622 12
            'form' => $form->createView(),
623
        ];
624
    }
625
626
    /**
627
     * @Route("/%eccube_admin_route%/order/export/pdf/download", name="admin_order_pdf_download")
628
     * @Template("@admin/Order/order_pdf.twig")
629
     *
630
     * @param Request $request
631
     *
632
     * @return Response
633
     */
634 10
    public function exportPdfDownload(Request $request)
635
    {
636
        /**
637
         * @var FormBuilder
638
         */
639 10
        $builder = $this->formFactory->createBuilder(OrderPdfType::class);
640
641
        /* @var \Symfony\Component\Form\Form $form */
642 10
        $form = $builder->getForm();
643 10
        $form->handleRequest($request);
644
645
        // Validation
646 10
        if (!$form->isValid()) {
647 7
            log_info('The parameter is invalid!');
648
649 7
            return $this->render('@admin/Order/order_pdf.twig', [
650 7
                'form' => $form->createView(),
651
            ]);
652
        }
653
654 3
        $arrData = $form->getData();
655
656
        // 購入情報からPDFを作成する
657 3
        $status = $this->orderPdfService->makePdf($arrData);
658
659
        // 異常終了した場合の処理
660 3
        if (!$status) {
661
            $this->addError('admin.order.export.pdf.download.failure', 'admin');
662
            log_info('Unable to create pdf files! Process have problems!');
663
664
            return $this->render('@admin/Order/order_pdf.twig', [
665
                'form' => $form->createView(),
666
            ]);
667
        }
668
669
        // ダウンロードする
670 3
        $response = new Response(
671 3
            $this->orderPdfService->outputPdf(),
672 3
            200,
673 3
            ['content-type' => 'application/pdf']
674
        );
675
676 3
        $downloadKind = $form->get('download_kind')->getData();
677
678
        // レスポンスヘッダーにContent-Dispositionをセットし、ファイル名を指定
679 3
        if ($downloadKind == 1) {
680 3
            $response->headers->set('Content-Disposition', 'attachment; filename="'.$this->orderPdfService->getPdfFileName().'"');
681
        } else {
682
            $response->headers->set('Content-Disposition', 'inline; filename="'.$this->orderPdfService->getPdfFileName().'"');
683
        }
684
685 3
        log_info('OrderPdf download success!', ['Order ID' => implode(',', $request->get('ids', []))]);
686
687 3
        $isDefault = isset($arrData['default']) ? $arrData['default'] : false;
688 3
        if ($isDefault) {
689
            // Save input to DB
690 1
            $arrData['admin'] = $this->getUser();
691 1
            $this->orderPdfRepository->save($arrData);
692
        }
693
694 3
        return $response;
695
    }
696
}
697