Failed Conditions
Pull Request — experimental/3.1 (#2159)
by Kentaro
39:20
created

EditController::searchCustomerHtml()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 82
Code Lines 52

Duplication

Lines 9
Ratio 10.98 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 52
nc 13
nop 3
dl 9
loc 82
ccs 0
cts 37
cp 0
crap 42
rs 8.3768
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
namespace Eccube\Controller\Admin\Order;
25
26
use Doctrine\Common\Collections\ArrayCollection;
27
use Eccube\Application;
28
use Eccube\Common\Constant;
29
use Eccube\Controller\AbstractController;
30
use Eccube\Entity\Master\DeviceType;
31
use Eccube\Entity\ShipmentItem;
32
use Eccube\Event\EccubeEvents;
33
use Eccube\Event\EventArgs;
34
use Eccube\Form\Type\AddCartType;
35
use Eccube\Form\Type\Admin\OrderType;
36
use Eccube\Form\Type\Admin\SearchCustomerType;
37
use Eccube\Form\Type\Admin\SearchProductType;
38
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
39
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
40
use Symfony\Component\Form\FormError;
41
use Symfony\Component\HttpFoundation\Request;
42
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
43
44
/**
45
 * TODO 管理画面のルーティングは動的に行う.おそらくコントローラのディレクトリをフロント/管理で分ける必要がある
46
 *
47
 * @Route("/admin/order")
48
 */
49
class EditController extends AbstractController
50
{
51
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
52
     * 受注登録/編集画面.
53
     *
54
     * @Route("/edit", name="admin_order_new")
55
     * @Route("/{id}/edit", requirements={"id" = "\d+"}, name="admin_order_edit")
56
     * @Template("Order/edit.twig")
57
     *
58
     * TODO templateアノテーションを利用するかどうか検討.http://symfony.com/doc/current/best_practices/controllers.html
59
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
60
    public function index(Application $app, Request $request, $id = null)
61
    {
62
        /* @var $softDeleteFilter \Eccube\Doctrine\Filter\SoftDeleteFilter */
63
        $softDeleteFilter = $app['orm.em']->getFilters()->getFilter('soft_delete');
64
        $softDeleteFilter->setExcludes(array(
65
            'Eccube\Entity\ProductClass',
66
            'Eccube\Entity\Product',
67
        ));
68
69
        $TargetOrder = null;
0 ignored issues
show
Unused Code introduced by
$TargetOrder is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
70
        $OriginOrder = null;
0 ignored issues
show
Unused Code introduced by
$OriginOrder is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
71
72
        if (is_null($id)) {
73
            // 空のエンティティを作成.
74
            $TargetOrder = $this->newOrder($app);
75
        } else {
76
            $TargetOrder = $app['eccube.repository.order']->find($id);
77
            if (is_null($TargetOrder)) {
78
                throw new NotFoundHttpException();
79
            }
80
        }
81
82
        // 編集前の受注情報を保持
83
        $OriginOrder = clone $TargetOrder;
84
        $OriginalOrderDetails = new ArrayCollection();
85
        // 編集前のお届け先情報を保持
86
        $OriginalShippings = new ArrayCollection();
87
        // 編集前のお届け先のアイテム情報を保持
88
        $OriginalShipmentItems = new ArrayCollection();
89
90
        foreach ($TargetOrder->getOrderDetails() as $OrderDetail) {
91
            $OriginalOrderDetails->add($OrderDetail);
92
        }
93
94
        // 編集前の情報を保持
95
        foreach ($TargetOrder->getShippings() as $tmpOriginalShippings) {
96
            foreach ($tmpOriginalShippings->getShipmentItems() as $tmpOriginalShipmentItem) {
97
                // アイテム情報
98
                $OriginalShipmentItems->add($tmpOriginalShipmentItem);
99
            }
100
            // お届け先情報
101
            $OriginalShippings->add($tmpOriginalShippings);
102
        }
103
104
        $builder = $app['form.factory']
105
            ->createBuilder(OrderType::class, $TargetOrder);
106
107
        $event = new EventArgs(
108
            array(
109
                'builder' => $builder,
110
                'OriginOrder' => $OriginOrder,
111
                'TargetOrder' => $TargetOrder,
112
                'OriginOrderDetails' => $OriginalOrderDetails,
113
            ),
114
            $request
115
        );
116
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_INITIALIZE, $event);
117
118
        $form = $builder->getForm();
119
        $form->handleRequest($request);
120
121
        if ($form->isSubmitted()) {
122
            $event = new EventArgs(
123
                array(
124
                    'builder' => $builder,
125
                    'OriginOrder' => $OriginOrder,
126
                    'TargetOrder' => $TargetOrder,
127
                    'OriginOrderDetails' => $OriginalOrderDetails,
128
                ),
129
                $request
130
            );
131
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_PROGRESS, $event);
132
133
            // 入力情報にもとづいて再計算.
134
            // TODO 購入フローのように、明細の自動生成をどこまで行うか検討する. 単純集計でよいような気がする
135
            // 集計は,この1行でいけるはず
136
            // プラグインで Strategy をセットしたりする
137
            // TODO 編集前のOrder情報が必要かもしれない
138
            $app['eccube.service.calculate']($TargetOrder, $TargetOrder->getCustomer())->calculate();
139
140
            // 登録ボタン押下
141
            switch ($request->get('mode')) {
142
                case 'register':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
143
144
                    log_info('受注登録開始', array($TargetOrder->getId()));
145
146
                    // TODO 在庫の有無や販売制限数のチェックなども行う必要があるため、完了処理もcaluclatorのように抽象化できないか検討する.
147
                    if ($TargetOrder->getTotal() > $app['config']['max_total_fee']) {
148
                        log_info('受注登録入力チェックエラー', array($TargetOrder->getId()));
149
                        $form['charge']->addError(new FormError('合計金額の上限を超えております。'));
150
                    } elseif ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
151
152
                        $BaseInfo = $app['eccube.repository.base_info']->get();
153
154
                        // TODO 後続にある会員情報の更新のように、完了処理もcaluclatorのように抽象化できないか検討する.
155
                        // 受注日/発送日/入金日の更新.
156
                        $this->updateDate($app, $TargetOrder, $OriginOrder);
157
158
                        // 画面上で削除された明細は、受注明細で削除されているものをremove
159
                        foreach ($OriginalOrderDetails as $OrderDetail) {
160
                            if (false === $TargetOrder->getOrderDetails()->contains($OrderDetail)) {
161
                                $app['orm.em']->remove($OrderDetail);
162
                            }
163
                        }
164
165
                        // 複数配送の場合,
166
                        if ($BaseInfo->getOptionMultipleShipping() == Constant::ENABLED) {
167
                            foreach ($TargetOrder->getOrderDetails() as $OrderDetail) {
168
                                $OrderDetail->setOrder($TargetOrder);
169
                            }
170
                            $Shippings = $TargetOrder->getShippings();
171
                            foreach ($Shippings as $Shipping) {
172
                                $shipmentItems = $Shipping->getShipmentItems();
173
                                foreach ($shipmentItems as $ShipmentItem) {
174
                                    // 削除予定から商品アイテムを外す
175
                                    $OriginalShipmentItems->removeElement($ShipmentItem);
176
                                    $ShipmentItem->setOrder($TargetOrder);
177
                                    $ShipmentItem->setShipping($Shipping);
178
                                    $app['orm.em']->persist($ShipmentItem);
179
                                }
180
                                // 削除予定からお届け先情報を外す
181
                                $OriginalShippings->removeElement($Shipping);
182
                                $Shipping->setOrder($TargetOrder);
183
                                $app['orm.em']->persist($Shipping);
184
                            }
185
                            // 商品アイテムを削除する
186
                            foreach ($OriginalShipmentItems as $OriginalShipmentItem) {
187
                                $app['orm.em']->remove($OriginalShipmentItem);
188
                            }
189
                            // お届け先情報削除する
190
                            foreach ($OriginalShippings as $OriginalShipping) {
191
                                $app['orm.em']->remove($OriginalShipping);
192
                            }
193
                        } else {
194
                            // 単一配送の場合, ShippimentItemsはOrderDetailの内容をコピーし、delete/insertで作り直す.
195
                            // TODO あまり本質的な処理ではないので簡略化したい.
196
                            $Shipping = $TargetOrder->getShippings()->first();
197
                            foreach ($Shipping->getShipmentItems() as $ShipmentItem) {
198
                                $Shipping->removeShipmentItem($ShipmentItem);
199
                                $app['orm.em']->remove($ShipmentItem);
200
                            }
201
                            foreach ($TargetOrder->getOrderDetails() as $OrderDetail) {
202
                                $OrderDetail->setOrder($TargetOrder);
203
                                if ($OrderDetail->getProduct()) {
204
                                    $ShipmentItem = new ShipmentItem();
205
                                    $ShipmentItem->copyProperties($OrderDetail);
206
                                    $ShipmentItem->setShipping($Shipping);
207
                                    $Shipping->addShipmentItem($ShipmentItem);
208
                                }
209
                            }
210
                        }
211
212
                        $app['orm.em']->persist($TargetOrder);
213
                        $app['orm.em']->flush();
214
215
                        // TODO 集計系に移動
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
216
//                        if ($Customer) {
217
//                            // 会員の場合、購入回数、購入金額などを更新
218
//                            $app['eccube.repository.customer']->updateBuyData($app, $Customer, $TargetOrder->getOrderStatus()->getId());
219
//                        }
220
221
                        $event = new EventArgs(
222
                            array(
223
                                'form' => $form,
224
                                'OriginOrder' => $OriginOrder,
225
                                'TargetOrder' => $TargetOrder,
226
                                'OriginOrderDetails' => $OriginalOrderDetails,
227
                                //'Customer' => $Customer,
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
228
                            ),
229
                            $request
230
                        );
231
                        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_COMPLETE, $event);
232
233
                        $app->addSuccess('admin.order.save.complete', 'admin');
234
235
                        log_info('受注登録完了', array($TargetOrder->getId()));
236
237
                        return $app->redirect($app->url('admin_order_edit', array('id' => $TargetOrder->getId())));
238
                    }
239
240
                    break;
241
242
                case 'add_delivery':
243
                    // お届け先情報の新規追加
244
245
                    $form = $builder->getForm();
246
247
                    $Shipping = new \Eccube\Entity\Shipping();
248
                    $TargetOrder->addShipping($Shipping);
249
250
                    $Shipping->setOrder($TargetOrder);
251
252
                    $form->setData($TargetOrder);
253
254
                    break;
255
256
                default:
257
                    break;
258
            }
259
        }
260
261
        // 会員検索フォーム
262
        $builder = $app['form.factory']
263
            ->createBuilder(SearchCustomerType::class);
264
265
        $event = new EventArgs(
266
            array(
267
                'builder' => $builder,
268
                'OriginOrder' => $OriginOrder,
269
                'TargetOrder' => $TargetOrder,
270
                'OriginOrderDetails' => $OriginalOrderDetails,
271
            ),
272
            $request
273
        );
274
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_INITIALIZE, $event);
275
276
        $searchCustomerModalForm = $builder->getForm();
277
278
        // 商品検索フォーム
279
        $builder = $app['form.factory']
280
            ->createBuilder(SearchProductType::class);
281
282
        $event = new EventArgs(
283
            array(
284
                'builder' => $builder,
285
                'OriginOrder' => $OriginOrder,
286
                'TargetOrder' => $TargetOrder,
287
                'OriginOrderDetails' => $OriginalOrderDetails,
288
            ),
289
            $request
290
        );
291
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_INITIALIZE, $event);
292
293
        $searchProductModalForm = $builder->getForm();
294
295
        // 配送業者のお届け時間
296
        $times = array();
297
        $deliveries = $app['eccube.repository.delivery']->findAll();
298
        foreach ($deliveries as $Delivery) {
299
            $deliveryTiems = $Delivery->getDeliveryTimes();
300
            foreach ($deliveryTiems as $DeliveryTime) {
301
                $times[$Delivery->getId()][$DeliveryTime->getId()] = $DeliveryTime->getDeliveryTime();
302
            }
303
        }
304
305
        return [
306
            'form' => $form->createView(),
307
            'searchCustomerModalForm' => $searchCustomerModalForm->createView(),
308
            'searchProductModalForm' => $searchProductModalForm->createView(),
309
            'Order' => $TargetOrder,
310
            'id' => $id,
311
            'shippingDeliveryTimes' => $app['serializer']->serialize($times, 'json'),
312
        ];
313
    }
314
315
    /**
316
     * 顧客情報を検索する.
317
     *
318
     * @param Application $app
319
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
320
     * @return \Symfony\Component\HttpFoundation\JsonResponse
321
     */
322
    public function searchCustomer(Application $app, Request $request)
323
    {
324
        if ($request->isXmlHttpRequest()) {
325
            $app['monolog']->addDebug('search customer start.');
326
327
            $searchData = array(
328
                'multi' => $request->get('search_word'),
329
            );
330
331
            $qb = $app['eccube.repository.customer']->getQueryBuilderBySearchData($searchData);
332
333
            $event = new EventArgs(
334
                array(
335
                    'qb' => $qb,
336
                    'data' => $searchData,
337
                ),
338
                $request
339
            );
340
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_SEARCH, $event);
341
342
            $Customers = $qb->getQuery()->getResult();
343
344
345
            if (empty($Customers)) {
346
                $app['monolog']->addDebug('search customer not found.');
347
            }
348
349
            $data = array();
350
351
            $formatTel = '%s-%s-%s';
352
            $formatName = '%s%s(%s%s)';
353 View Code Duplication
            foreach ($Customers as $Customer) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
354
                $data[] = array(
355
                    'id' => $Customer->getId(),
356
                    'name' => sprintf($formatName, $Customer->getName01(), $Customer->getName02(), $Customer->getKana01(),
357
                        $Customer->getKana02()),
358
                    'tel' => sprintf($formatTel, $Customer->getTel01(), $Customer->getTel02(), $Customer->getTel03()),
359
                    'email' => $Customer->getEmail(),
360
                );
361
            }
362
363
            $event = new EventArgs(
364
                array(
365
                    'data' => $data,
366
                    'Customers' => $Customers,
367
                ),
368
                $request
369
            );
370
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_COMPLETE, $event);
371
            $data = $event->getArgument('data');
372
373
            return $app->json($data);
374
        }
375
    }
376
377
    /**
378
     * 顧客情報を検索する.
379
     *
380
     * @param Application $app
381
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
382
     * @param integer $page_no
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
383
     * @return \Symfony\Component\HttpFoundation\JsonResponse
384
     */
385
    public function searchCustomerHtml(Application $app, Request $request, $page_no = null)
386
    {
387
        if ($request->isXmlHttpRequest()) {
388
            $app['monolog']->addDebug('search customer start.');
389
            $page_count = $app['config']['default_page_count'];
390
            $session = $app['session'];
391
392
            if ('POST' === $request->getMethod()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
393
394
                $page_no = 1;
395
396
                $searchData = array(
397
                    'multi' => $request->get('search_word'),
398
                );
399
400
                $session->set('eccube.admin.order.customer.search', $searchData);
401
                $session->set('eccube.admin.order.customer.search.page_no', $page_no);
402
            } else {
403
                $searchData = (array)$session->get('eccube.admin.order.customer.search');
0 ignored issues
show
Coding Style introduced by
As per coding-style, a cast statement should be followed by a single space.
Loading history...
404
                if (is_null($page_no)) {
405
                    $page_no = intval($session->get('eccube.admin.order.customer.search.page_no'));
406
                } else {
407
                    $session->set('eccube.admin.order.customer.search.page_no', $page_no);
408
                }
409
            }
410
411
            $qb = $app['eccube.repository.customer']->getQueryBuilderBySearchData($searchData);
412
413
            $event = new EventArgs(
414
                array(
415
                    'qb' => $qb,
416
                    'data' => $searchData,
417
                ),
418
                $request
419
            );
420
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_SEARCH, $event);
421
422
            /** @var \Knp\Component\Pager\Pagination\SlidingPagination $pagination */
423
            $pagination = $app['paginator']()->paginate(
424
                $qb,
425
                $page_no,
426
                $page_count,
427
                array('wrap-queries' => true)
428
            );
429
430
            /** @var $Customers \Eccube\Entity\Customer[] */
431
            $Customers = $pagination->getItems();
432
433
            if (empty($Customers)) {
434
                $app['monolog']->addDebug('search customer not found.');
435
            }
436
437
            $data = array();
438
439
            $formatTel = '%s-%s-%s';
440
            $formatName = '%s%s(%s%s)';
441 View Code Duplication
            foreach ($Customers as $Customer) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
442
                $data[] = array(
443
                    'id' => $Customer->getId(),
444
                    'name' => sprintf($formatName, $Customer->getName01(), $Customer->getName02(), $Customer->getKana01(),
445
                        $Customer->getKana02()),
446
                    'tel' => sprintf($formatTel, $Customer->getTel01(), $Customer->getTel02(), $Customer->getTel03()),
447
                    'email' => $Customer->getEmail(),
448
                );
449
            }
450
451
            $event = new EventArgs(
452
                array(
453
                    'data' => $data,
454
                    'Customers' => $pagination,
455
                ),
456
                $request
457
            );
458
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_COMPLETE, $event);
459
            $data = $event->getArgument('data');
460
461
            return $app->render('Order/search_customer.twig', array(
462
                'data' => $data,
463
                'pagination' => $pagination,
464
            ));
465
        }
466
    }
467
468
    /**
469
     * 顧客情報を検索する.
470
     *
471
     * @param Application $app
472
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
473
     * @return \Symfony\Component\HttpFoundation\JsonResponse
474
     */
475
    public function searchCustomerById(Application $app, Request $request)
476
    {
477
        if ($request->isXmlHttpRequest()) {
478
            $app['monolog']->addDebug('search customer by id start.');
479
480
            /** @var $Customer \Eccube\Entity\Customer */
481
            $Customer = $app['eccube.repository.customer']
482
                ->find($request->get('id'));
483
484
            $event = new EventArgs(
485
                array(
486
                    'Customer' => $Customer,
487
                ),
488
                $request
489
            );
490
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_BY_ID_INITIALIZE, $event);
491
492
            if (is_null($Customer)) {
493
                $app['monolog']->addDebug('search customer by id not found.');
494
495
                return $app->json(array(), 404);
496
            }
497
498
            $app['monolog']->addDebug('search customer by id found.');
499
500
            $data = array(
501
                'id' => $Customer->getId(),
502
                'name01' => $Customer->getName01(),
503
                'name02' => $Customer->getName02(),
504
                'kana01' => $Customer->getKana01(),
505
                'kana02' => $Customer->getKana02(),
506
                'zip01' => $Customer->getZip01(),
507
                'zip02' => $Customer->getZip02(),
508
                'pref' => is_null($Customer->getPref()) ? null : $Customer->getPref()->getId(),
509
                'addr01' => $Customer->getAddr01(),
510
                'addr02' => $Customer->getAddr02(),
511
                'email' => $Customer->getEmail(),
512
                'tel01' => $Customer->getTel01(),
513
                'tel02' => $Customer->getTel02(),
514
                'tel03' => $Customer->getTel03(),
515
                'fax01' => $Customer->getFax01(),
516
                'fax02' => $Customer->getFax02(),
517
                'fax03' => $Customer->getFax03(),
518
                'company_name' => $Customer->getCompanyName(),
519
            );
520
521
            $event = new EventArgs(
522
                array(
523
                    'data' => $data,
524
                    'Customer' => $Customer,
525
                ),
526
                $request
527
            );
528
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_BY_ID_COMPLETE, $event);
529
            $data = $event->getArgument('data');
530
531
            return $app->json($data);
532
        }
533
    }
534
535
    public function searchProduct(Application $app, Request $request, $page_no = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
536
    {
537
        if ($request->isXmlHttpRequest()) {
538
            $app['monolog']->addDebug('search product start.');
539
            $page_count = $app['config']['default_page_count'];
540
            $session = $app['session'];
541
542
            if ('POST' === $request->getMethod()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
543
544
                $page_no = 1;
545
546
                $searchData = array(
547
                    'id' => $request->get('id'),
548
                );
549
550
                if ($categoryId = $request->get('category_id')) {
551
                    $Category = $app['eccube.repository.category']->find($categoryId);
552
                    $searchData['category_id'] = $Category;
553
                }
554
555
                $session->set('eccube.admin.order.product.search', $searchData);
556
                $session->set('eccube.admin.order.product.search.page_no', $page_no);
557
            } else {
558
                $searchData = (array)$session->get('eccube.admin.order.product.search');
0 ignored issues
show
Coding Style introduced by
As per coding-style, a cast statement should be followed by a single space.
Loading history...
559
                if (is_null($page_no)) {
560
                    $page_no = intval($session->get('eccube.admin.order.product.search.page_no'));
561
                } else {
562
                    $session->set('eccube.admin.order.product.search.page_no', $page_no);
563
                }
564
            }
565
566
            $qb = $app['eccube.repository.product']
567
                ->getQueryBuilderBySearchDataForAdmin($searchData);
568
569
            $event = new EventArgs(
570
                array(
571
                    'qb' => $qb,
572
                    'searchData' => $searchData,
573
                ),
574
                $request
575
            );
576
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_SEARCH, $event);
577
578
            /** @var \Knp\Component\Pager\Pagination\SlidingPagination $pagination */
579
            $pagination = $app['paginator']()->paginate(
580
                $qb,
581
                $page_no,
582
                $page_count,
583
                array('wrap-queries' => true)
584
            );
585
586
            /** @var $Products \Eccube\Entity\Product[] */
587
            $Products = $pagination->getItems();
588
589
            if (empty($Products)) {
590
                $app['monolog']->addDebug('search product not found.');
591
            }
592
593
            $forms = array();
594
            foreach ($Products as $Product) {
595
                /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
596
                $builder = $app['form.factory']->createNamedBuilder('', AddCartType::class, null, array(
597
                    'product' => $Product,
598
                ));
599
                $addCartForm = $builder->getForm();
600
                $forms[$Product->getId()] = $addCartForm->createView();
601
            }
602
603
            $event = new EventArgs(
604
                array(
605
                    'forms' => $forms,
606
                    'Products' => $Products,
607
                    'pagination' => $pagination,
608
                ),
609
                $request
610
            );
611
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_COMPLETE, $event);
612
613
            return $app->render('Order/search_product.twig', array(
614
                'forms' => $forms,
615
                'Products' => $Products,
616
                'pagination' => $pagination,
617
            ));
618
        }
619
    }
620
621
    protected function newOrder(Application $app)
622
    {
623
        $Order = new \Eccube\Entity\Order();
624
        $Shipping = new \Eccube\Entity\Shipping();
625
        $Order->addShipping($Shipping);
626
        $Shipping->setOrder($Order);
627
628
        // device type
629
        $DeviceType = $app['eccube.repository.master.device_type']->find(DeviceType::DEVICE_TYPE_ADMIN);
630
        $Order->setDeviceType($DeviceType);
631
632
        return $Order;
633
    }
634
635
    /**
636
     * フォームからの入直内容に基づいて、受注情報の再計算を行う
637
     *
638
     * @param $app
639
     * @param $Order
640
     */
641
    protected function calculate($app, \Eccube\Entity\Order $Order)
642
    {
643
        $taxtotal = 0;
0 ignored issues
show
Unused Code introduced by
$taxtotal is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
644
        $subtotal = 0;
0 ignored issues
show
Unused Code introduced by
$subtotal is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
645
646
        // 受注明細データの税・小計を再計算
647
        /** @var $OrderDetails \Eccube\Entity\OrderDetail[] */
648
        $OrderDetails = $Order->getOrderDetails();
649 View Code Duplication
        foreach ($OrderDetails as $OrderDetail) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
Blank line found at start of control structure
Loading history...
650
651
            // 税
652
            $tax = $app['eccube.service.tax_rule']
653
                ->calcTax($OrderDetail->getPrice(), $OrderDetail->getTaxRate(), $OrderDetail->getTaxRule());
654
            $OrderDetail->setPriceIncTax($OrderDetail->getPrice() + $tax);
655
656
            // $taxtotal += $tax * $OrderDetail->getQuantity();
0 ignored issues
show
Unused Code Comprehensibility introduced by
44% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
657
658
            // // 小計
659
            // $subtotal += $OrderDetail->getTotalPrice();
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
660
        }
661
662
        $shippings = $Order->getShippings();
663
        /** @var \Eccube\Entity\Shipping $Shipping */
664
        foreach ($shippings as $Shipping) {
665
            $Shipping->setDelFlg(Constant::DISABLED);
666
        }
667
668
        // // 受注データの税・小計・合計を再計算
669
        // $Order->setTax($taxtotal);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
670
        // $Order->setSubtotal($subtotal);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
671
        // $Order->setTotal($subtotal + $Order->getCharge() + $Order->getDeliveryFeeTotal() - $Order->getDiscount());
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
672
        // // お支払い合計は、totalと同一金額(2系ではtotal - point)
673
        // $Order->setPaymentTotal($Order->getTotal());
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
674
675
        // 集計は,この1行でいけるはず
676
        // プラグインで Strategy をセットしたりする
677
        $app['eccube.service.calculate']($Order, $Order->getCustomer())->calculate();
678
    }
679
680
    /**
681
     * 受注ステータスに応じて, 受注日/入金日/発送日を更新する,
682
     * 発送済ステータスが設定された場合は, お届け先情報の発送日も更新を行う.
683
     *
684
     * 編集の場合
685
     * - 受注ステータスが他のステータスから発送済へ変更された場合に発送日を更新
686
     * - 受注ステータスが他のステータスから入金済へ変更された場合に入金日を更新
687
     *
688
     * 新規登録の場合
689
     * - 受注日を更新
690
     * - 受注ステータスが発送済に設定された場合に発送日を更新
691
     * - 受注ステータスが入金済に設定された場合に入金日を更新
692
     *
693
     *
694
     * @param $app
695
     * @param $TargetOrder
696
     * @param $OriginOrder
697
     */
698
    protected function updateDate($app, $TargetOrder, $OriginOrder)
699
    {
700
        $dateTime = new \DateTime();
701
702
        // 編集
703
        if ($TargetOrder->getId()) {
704
            // 発送済
705
            if ($TargetOrder->getOrderStatus()->getId() == $app['config']['order_deliv']) {
706
                // 編集前と異なる場合のみ更新
707
                if ($TargetOrder->getOrderStatus()->getId() != $OriginOrder->getOrderStatus()->getId()) {
708
                    $TargetOrder->setCommitDate($dateTime);
709
                    // お届け先情報の発送日も更新する.
710
                    $Shippings = $TargetOrder->getShippings();
711
                    foreach ($Shippings as $Shipping) {
712
                        $Shipping->setShippingCommitDate($dateTime);
713
                    }
714
                }
715
                // 入金済
716
            } elseif ($TargetOrder->getOrderStatus()->getId() == $app['config']['order_pre_end']) {
717
                // 編集前と異なる場合のみ更新
718
                if ($TargetOrder->getOrderStatus()->getId() != $OriginOrder->getOrderStatus()->getId()) {
719
                    $TargetOrder->setPaymentDate($dateTime);
720
                }
721
            }
722
            // 新規
723
        } else {
724
            // 発送済
725
            if ($TargetOrder->getOrderStatus()->getId() == $app['config']['order_deliv']) {
726
                $TargetOrder->setCommitDate($dateTime);
727
                // お届け先情報の発送日も更新する.
728
                $Shippings = $TargetOrder->getShippings();
729
                foreach ($Shippings as $Shipping) {
730
                    $Shipping->setShippingCommitDate($dateTime);
731
                }
732
                // 入金済
733
            } elseif ($TargetOrder->getOrderStatus()->getId() == $app['config']['order_pre_end']) {
734
                $TargetOrder->setPaymentDate($dateTime);
735
            }
736
            // 受注日時
737
            $TargetOrder->setOrderDate($dateTime);
738
        }
739
    }
740
}
741