EditController   C
last analyzed

Complexity

Total Complexity 64

Size/Duplication

Total Lines 731
Duplicated Lines 2.46 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 46.94%

Importance

Changes 0
Metric Value
dl 18
loc 731
rs 5
c 0
b 0
f 0
ccs 23
cts 49
cp 0.4694
wmc 64
lcom 1
cbo 11

8 Methods

Rating   Name   Duplication   Size   Complexity  
F index() 0 306 29
A searchCustomer() 9 54 4
B searchCustomerHtml() 9 82 6
B searchCustomerById() 0 59 4
C searchProduct() 0 85 7
A newOrder() 0 14 1
B calculate() 0 33 3
D updateDate() 0 42 10

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like EditController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use EditController, and based on these observations, apply Extract Interface, too.

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\OrderDetail;
32
use Eccube\Entity\ShipmentItem;
33
use Eccube\Entity\Shipping;
34
use Eccube\Event\EccubeEvents;
35
use Eccube\Event\EventArgs;
36
use Symfony\Component\Form\FormError;
37 4
use Symfony\Component\HttpFoundation\Request;
38
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
39 4
40 4
class EditController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
41
{
42
    public function index(Application $app, Request $request, $id = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
43
    {
44
        /* @var $softDeleteFilter \Eccube\Doctrine\Filter\SoftDeleteFilter */
45
        $softDeleteFilter = $app['orm.em']->getFilters()->getFilter('soft_delete');
46
        $softDeleteFilter->setExcludes(array(
47
            'Eccube\Entity\ProductClass',
48
            'Eccube\Entity\Product',
49
        ));
50 2
51
        $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...
52
        $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...
53 4
54
        if (is_null($id)) {
55
            // 空のエンティティを作成.
56 4
            $TargetOrder = $this->newOrder($app);
57
        } else {
58 2
            $TargetOrder = $app['eccube.repository.order']->find($id);
59
            if (is_null($TargetOrder)) {
60
                throw new NotFoundHttpException();
61
            }
62
        }
63
64
        // 編集前の受注情報を保持
65
        $OriginOrder = clone $TargetOrder;
66
        $OriginalOrderDetails = new ArrayCollection();
67
        // 編集前のお届け先情報を保持
68
        $OriginalShippings = new ArrayCollection();
69
        // 編集前のお届け先のアイテム情報を保持
70
        $OriginalShipmentItems = new ArrayCollection();
71
72 2
        // Save previous value before calculate
73 2
        $arrOldOrder = array();
74
75
        /** @var $OrderDetail OrderDetail*/
76
        foreach ($TargetOrder->getOrderDetails() as $OrderDetail) {
77
            $OriginalOrderDetails->add($OrderDetail);
78
            $arrOldOrder['OrderDetails'][$OrderDetail->getId()]['quantity'] = $OrderDetail->getQuantity();
79
        }
80
81
        // 編集前の情報を保持
82
        /** @var $tmpOriginalShippings Shipping*/
83
        foreach ($TargetOrder->getShippings() as $key => $tmpOriginalShippings) {
84
            $arrOldOrder['Shippings'][$key]['shipping_delivery_date'] = $tmpOriginalShippings->getShippingDeliveryDate();
85
            /** @var $tmpOriginalShipmentItem ShipmentItem*/
86
            foreach ($tmpOriginalShippings->getShipmentItems() as $tmpOriginalShipmentItem) {
87
                // アイテム情報
88
                $OriginalShipmentItems->add($tmpOriginalShipmentItem);
89
                $arrOldOrder['Shippings'][$key]['ShipmentItems'][$tmpOriginalShipmentItem->getId()]['quantity'] = $tmpOriginalShipmentItem->getQuantity();
90
            }
91
            // お届け先情報
92
            $OriginalShippings->add($tmpOriginalShippings);
93
        }
94
95
        $builder = $app['form.factory']
96
            ->createBuilder('order', $TargetOrder);
97
98
        $event = new EventArgs(
99
            array(
100
                'builder' => $builder,
101
                'OriginOrder' => $OriginOrder,
102
                'TargetOrder' => $TargetOrder,
103
                'OriginOrderDetails' => $OriginalOrderDetails,
104
            ),
105
            $request
106
        );
107
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_INITIALIZE, $event);
108
109
        $form = $builder->getForm();
110
111
        if ('POST' === $request->getMethod()) {
112
            $form->handleRequest($request);
113
114
            $event = new EventArgs(
115
                array(
116
                    'builder' => $builder,
117
                    'OriginOrder' => $OriginOrder,
118
                    'TargetOrder' => $TargetOrder,
119
                    'OriginOrderDetails' => $OriginalOrderDetails,
120
                ),
121
                $request
122
            );
123
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_PROGRESS, $event);
124
125
            // 入力情報にもとづいて再計算.
126
            $this->calculate($app, $TargetOrder);
127
128
            // 登録ボタン押下
129
            switch ($request->get('mode')) {
130
                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...
131
132
                    log_info('受注登録開始', array($TargetOrder->getId()));
133
134
                    if ($TargetOrder->getTotal() > $app['config']['max_total_fee']) {
135
                        log_info('受注登録入力チェックエラー', array($TargetOrder->getId()));
136
                        $form['charge']->addError(new FormError('合計金額の上限を超えております。'));
137
                    } elseif ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
138
139
                        $BaseInfo = $app['eccube.repository.base_info']->get();
140
141
                        // お支払い方法の更新
142
                        $TargetOrder->setPaymentMethod($TargetOrder->getPayment()->getMethod());
143
144
                        // 配送業者・お届け時間の更新
145
                        $Shippings = $TargetOrder->getShippings();
146
                        foreach ($Shippings as $Shipping) {
147
                            $Shipping->setShippingDeliveryName($Shipping->getDelivery()->getName());
148
                            if (!is_null($Shipping->getDeliveryTime())) {
149
                                $Shipping->setShippingDeliveryTime($Shipping->getDeliveryTime()->getDeliveryTime());
150
                            } else {
151
                                $Shipping->setShippingDeliveryTime(null);
152
                            }
153
                        }
154
155
156
                        // 受注日/発送日/入金日の更新.
157
                        $this->updateDate($app, $TargetOrder, $OriginOrder);
158
159
                        // 受注明細で削除されているものをremove
160
                        foreach ($OriginalOrderDetails as $OrderDetail) {
161
                            if (false === $TargetOrder->getOrderDetails()->contains($OrderDetail)) {
162
                                $app['orm.em']->remove($OrderDetail);
163
                            }
164
                        }
165
166
167
                        if ($BaseInfo->getOptionMultipleShipping() == Constant::ENABLED) {
168
                            foreach ($TargetOrder->getOrderDetails() as $OrderDetail) {
169
                                /** @var $OrderDetail \Eccube\Entity\OrderDetail */
170
                                $OrderDetail->setOrder($TargetOrder);
171
                            }
172
173
                            /** @var \Eccube\Entity\Shipping $Shipping */
174
                            foreach ($Shippings as $Shipping) {
175
                                $shipmentItems = $Shipping->getShipmentItems();
176
                                /** @var \Eccube\Entity\ShipmentItem $ShipmentItem */
177
                                foreach ($shipmentItems as $ShipmentItem) {
178
                                    // 削除予定から商品アイテムを外す
179 2
                                    $OriginalShipmentItems->removeElement($ShipmentItem);
180
                                    $ShipmentItem->setOrder($TargetOrder);
181
                                    $ShipmentItem->setShipping($Shipping);
182
                                    $app['orm.em']->persist($ShipmentItem);
183
                                }
184
                                // 削除予定からお届け先情報を外す
185
                                $OriginalShippings->removeElement($Shipping);
186
                                $Shipping->setOrder($TargetOrder);
187
                                $app['orm.em']->persist($Shipping);
188
                            }
189
                            // 商品アイテムを削除する
190
                            foreach ($OriginalShipmentItems as $OriginalShipmentItem) {
191
                                $app['orm.em']->remove($OriginalShipmentItem);
192
                            }
193
                            // お届け先情報削除する
194
                            foreach ($OriginalShippings as $OriginalShipping) {
195
                                $app['orm.em']->remove($OriginalShipping);
196 2
                            }
197
                        } else {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
198
199
                            $NewShipmentItems = new ArrayCollection();
200
201
                            foreach ($TargetOrder->getOrderDetails() as $OrderDetail) {
202
                                /** @var $OrderDetail \Eccube\Entity\OrderDetail */
203
                                $OrderDetail->setOrder($TargetOrder);
204
205
                                $NewShipmentItem = new ShipmentItem();
206
                                $NewShipmentItem
207
                                    ->setProduct($OrderDetail->getProduct())
208
                                    ->setProductClass($OrderDetail->getProductClass())
209
                                    ->setProductName($OrderDetail->getProduct()->getName())
210
                                    ->setProductCode($OrderDetail->getProductClass()->getCode())
211 4
                                    ->setClassCategoryName1($OrderDetail->getClassCategoryName1())
212
                                    ->setClassCategoryName2($OrderDetail->getClassCategoryName2())
213
                                    ->setClassName1($OrderDetail->getClassName1())
214
                                    ->setClassName2($OrderDetail->getClassName2())
215
                                    ->setPrice($OrderDetail->getPrice())
216
                                    ->setQuantity($OrderDetail->getQuantity())
217
                                    ->setOrder($TargetOrder);
218
                                $NewShipmentItems[] = $NewShipmentItem;
219
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
220 4
                            }
221 4
                            // 配送商品の更新. delete/insert.
222 4
                            $Shippings = $TargetOrder->getShippings();
223 4
                            foreach ($Shippings as $Shipping) {
224
                                $ShipmentItems = $Shipping->getShipmentItems();
225
                                foreach ($ShipmentItems as $ShipmentItem) {
226
                                    $app['orm.em']->remove($ShipmentItem);
227
                                }
228 4
                                $ShipmentItems->clear();
229
                                foreach ($NewShipmentItems as $NewShipmentItem) {
230
                                    $NewShipmentItem->setShipping($Shipping);
231
                                    $ShipmentItems->add($NewShipmentItem);
232
                                }
233
                            }
234
                        }
235
236
                        $Customer = $TargetOrder->getCustomer();
237
                        if ($Customer) {
238
                            // 受注情報の会員情報を更新
239
                            $TargetOrder->setSex($Customer->getSex());
240
                            $TargetOrder->setJob($Customer->getJob());
241
                            $TargetOrder->setBirth($Customer->getBirth());
242
                        }
243
244
                        $app['orm.em']->persist($TargetOrder);
245
                        $app['orm.em']->flush();
246
247
                        if ($Customer) {
248
                            // 会員の場合、購入回数、購入金額などを更新
249
                            $app['eccube.repository.customer']->updateBuyData($app, $Customer, $TargetOrder->getOrderStatus()->getId());
250
                        }
251
252
                        $event = new EventArgs(
253
                            array(
254
                                'form' => $form,
255
                                'OriginOrder' => $OriginOrder,
256
                                'TargetOrder' => $TargetOrder,
257
                                'OriginOrderDetails' => $OriginalOrderDetails,
258
                                'Customer' => $Customer,
259
                            ),
260
                            $request
261
                        );
262
                        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_COMPLETE, $event);
263
264
                        $app->addSuccess('admin.order.save.complete', 'admin');
265
266
                        log_info('受注登録完了', array($TargetOrder->getId()));
267
268
                        return $app->redirect($app->url('admin_order_edit', array('id' => $TargetOrder->getId())));
269
                    }
270
271
                    break;
272
273
                case 'add_delivery':
274
                    // お届け先情報の新規追加
275
276
                    $form = $builder->getForm();
277
278
                    $Shipping = new \Eccube\Entity\Shipping();
279
                    $Shipping->setDelFlg(Constant::DISABLED);
280
281
                    $TargetOrder->addShipping($Shipping);
282
283
                    $Shipping->setOrder($TargetOrder);
284
285
                    $form->setData($TargetOrder);
286
287
                    break;
288
289
                default:
290
                    break;
291
            }
292
        }
293
294
        // 会員検索フォーム
295
        $builder = $app['form.factory']
296
            ->createBuilder('admin_search_customer');
297
298
        $event = new EventArgs(
299
            array(
300
                'builder' => $builder,
301
                'OriginOrder' => $OriginOrder,
302
                'TargetOrder' => $TargetOrder,
303
                'OriginOrderDetails' => $OriginalOrderDetails,
304
            ),
305
            $request
306
        );
307
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_INITIALIZE, $event);
308
309
        $searchCustomerModalForm = $builder->getForm();
310
311
        // 商品検索フォーム
312
        $builder = $app['form.factory']
313
            ->createBuilder('admin_search_product');
314
315
        $event = new EventArgs(
316
            array(
317
                'builder' => $builder,
318
                'OriginOrder' => $OriginOrder,
319
                'TargetOrder' => $TargetOrder,
320
                'OriginOrderDetails' => $OriginalOrderDetails,
321
            ),
322
            $request
323
        );
324
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_INITIALIZE, $event);
325
326
        $searchProductModalForm = $builder->getForm();
327
328
        // 配送業者のお届け時間
329
        $times = array();
330
        $deliveries = $app['eccube.repository.delivery']->findAll();
331
        foreach ($deliveries as $Delivery) {
332
            $deliveryTiems = $Delivery->getDeliveryTimes();
333
            foreach ($deliveryTiems as $DeliveryTime) {
334
                $times[$Delivery->getId()][$DeliveryTime->getId()] = $DeliveryTime->getDeliveryTime();
335
            }
336
        }
337
338
        return $app->render('Order/edit.twig', array(
339
            'form' => $form->createView(),
340
            'searchCustomerModalForm' => $searchCustomerModalForm->createView(),
341
            'searchProductModalForm' => $searchProductModalForm->createView(),
342
            'Order' => $TargetOrder,
343
            'id' => $id,
344
            'shippingDeliveryTimes' => $app['serializer']->serialize($times, 'json'),
345
            'arrOldOrder' => $arrOldOrder,
346
        ));
347
    }
348
349
    /**
350
     * 顧客情報を検索する.
351
     *
352
     * @param Application $app
353
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
354
     * @return \Symfony\Component\HttpFoundation\JsonResponse
355
     */
356
    public function searchCustomer(Application $app, Request $request)
357
    {
358
        if ($request->isXmlHttpRequest()) {
359
            $app['monolog']->addDebug('search customer start.');
360
361
            $searchData = array(
362 2
                'multi' => $request->get('search_word'),
363
            );
364
365
            $qb = $app['eccube.repository.customer']->getQueryBuilderBySearchData($searchData);
366
367
            $event = new EventArgs(
368
                array(
369
                    'qb' => $qb,
370
                    'data' => $searchData,
371
                ),
372
                $request
373
            );
374 2
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_SEARCH, $event);
375
376
            $Customers = $qb->getQuery()->getResult();
377
378
379
            if (empty($Customers)) {
380
                $app['monolog']->addDebug('search customer not found.');
381
            }
382
383 2
            $data = array();
384
385 2
            $formatTel = '%s-%s-%s';
386 2
            $formatName = '%s%s(%s%s)';
387 View Code Duplication
            foreach ($Customers as $Customer) {
388
                $data[] = array(
389
                    'id' => $Customer->getId(),
390
                    'name' => sprintf($formatName, $Customer->getName01(), $Customer->getName02(), $Customer->getKana01(),
391
                        $Customer->getKana02()),
392
                    'tel' => sprintf($formatTel, $Customer->getTel01(), $Customer->getTel02(), $Customer->getTel03()),
393
                    'email' => $Customer->getEmail(),
394
                );
395
            }
396
397
            $event = new EventArgs(
398
                array(
399
                    'data' => $data,
400
                    'Customers' => $Customers,
401
                ),
402
                $request
403
            );
404
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_COMPLETE, $event);
405
            $data = $event->getArgument('data');
406
407
            return $app->json($data);
408
        }
409
    }
410
411
    /**
412
     * 顧客情報を検索する.
413
     *
414
     * @param Application $app
415
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
416
     * @param integer $page_no
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
417
     * @return \Symfony\Component\HttpFoundation\JsonResponse
418 1
     */
419
    public function searchCustomerHtml(Application $app, Request $request, $page_no = null)
420
    {
421
        if ($request->isXmlHttpRequest()) {
422 1
            $app['monolog']->addDebug('search customer start.');
423
            $page_count = $app['config']['default_page_count'];
424
            $session = $app['session'];
425
426
            if ('POST' === $request->getMethod()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
427
428
                $page_no = 1;
429
430
                $searchData = array(
431
                    'multi' => $request->get('search_word'),
432
                );
433
434
                $session->set('eccube.admin.order.customer.search', $searchData);
435
                $session->set('eccube.admin.order.customer.search.page_no', $page_no);
436
            } else {
437
                $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...
438
                if (is_null($page_no)) {
439
                    $page_no = intval($session->get('eccube.admin.order.customer.search.page_no'));
440
                } else {
441
                    $session->set('eccube.admin.order.customer.search.page_no', $page_no);
442
                }
443
            }
444
445
            $qb = $app['eccube.repository.customer']->getQueryBuilderBySearchData($searchData);
446
447 1
            $event = new EventArgs(
448
                array(
449
                    'qb' => $qb,
450
                    'data' => $searchData,
451
                ),
452
                $request
453
            );
454
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_SEARCH, $event);
455
456
            /** @var \Knp\Component\Pager\Pagination\SlidingPagination $pagination */
457
            $pagination = $app['paginator']()->paginate(
458
                $qb,
459
                $page_no,
460
                $page_count,
461
                array('wrap-queries' => true)
462
            );
463
464
            /** @var $Customers \Eccube\Entity\Customer[] */
465
            $Customers = $pagination->getItems();
466
467
            if (empty($Customers)) {
468
                $app['monolog']->addDebug('search customer not found.');
469
            }
470
471
            $data = array();
472
473
            $formatTel = '%s-%s-%s';
474
            $formatName = '%s%s(%s%s)';
475 View Code Duplication
            foreach ($Customers as $Customer) {
476
                $data[] = array(
477
                    'id' => $Customer->getId(),
478
                    'name' => sprintf($formatName, $Customer->getName01(), $Customer->getName02(), $Customer->getKana01(),
479
                        $Customer->getKana02()),
480
                    'tel' => sprintf($formatTel, $Customer->getTel01(), $Customer->getTel02(), $Customer->getTel03()),
481
                    'email' => $Customer->getEmail(),
482
                );
483
            }
484
485
            $event = new EventArgs(
486
                array(
487
                    'data' => $data,
488
                    'Customers' => $pagination,
489
                ),
490
                $request
491
            );
492
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_COMPLETE, $event);
493
            $data = $event->getArgument('data');
494
495
            return $app->render('Order/search_customer.twig', array(
496
                'data' => $data,
497
                'pagination' => $pagination,
498
            ));
499
        }
500
    }
501
502
    /**
503
     * 顧客情報を検索する.
504
     *
505
     * @param Application $app
506
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
507
     * @return \Symfony\Component\HttpFoundation\JsonResponse
508
     */
509
    public function searchCustomerById(Application $app, Request $request)
510
    {
511
        if ($request->isXmlHttpRequest()) {
512
            $app['monolog']->addDebug('search customer by id start.');
513
514
            /** @var $Customer \Eccube\Entity\Customer */
515
            $Customer = $app['eccube.repository.customer']
516
                ->find($request->get('id'));
517
518
            $event = new EventArgs(
519
                array(
520
                    'Customer' => $Customer,
521
                ),
522
                $request
523
            );
524
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_BY_ID_INITIALIZE, $event);
525
526
            if (is_null($Customer)) {
527
                $app['monolog']->addDebug('search customer by id not found.');
528
529
                return $app->json(array(), 404);
530
            }
531
532
            $app['monolog']->addDebug('search customer by id found.');
533
534
            $data = array(
535
                'id' => $Customer->getId(),
536
                'name01' => $Customer->getName01(),
537
                'name02' => $Customer->getName02(),
538
                'kana01' => $Customer->getKana01(),
539
                'kana02' => $Customer->getKana02(),
540
                'zip01' => $Customer->getZip01(),
541
                'zip02' => $Customer->getZip02(),
542
                'pref' => is_null($Customer->getPref()) ? null : $Customer->getPref()->getId(),
543
                'addr01' => $Customer->getAddr01(),
544
                'addr02' => $Customer->getAddr02(),
545
                'email' => $Customer->getEmail(),
546
                'tel01' => $Customer->getTel01(),
547
                'tel02' => $Customer->getTel02(),
548
                'tel03' => $Customer->getTel03(),
549
                'fax01' => $Customer->getFax01(),
550
                'fax02' => $Customer->getFax02(),
551
                'fax03' => $Customer->getFax03(),
552
                'company_name' => $Customer->getCompanyName(),
553
            );
554
555
            $event = new EventArgs(
556
                array(
557
                    'data' => $data,
558
                    'Customer' => $Customer,
559
                ),
560
                $request
561
            );
562
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_BY_ID_COMPLETE, $event);
563
            $data = $event->getArgument('data');
564
565
            return $app->json($data);
566
        }
567
    }
568
569
    public function searchProduct(Application $app, Request $request, $page_no = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
570
    {
571
        if ($request->isXmlHttpRequest()) {
572
            $app['monolog']->addDebug('search product start.');
573
            $page_count = $app['config']['default_page_count'];
574
            $session = $app['session'];
575
576
            if ('POST' === $request->getMethod()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
577
578
                $page_no = 1;
579
580
                $searchData = array(
581
                    'id' => $request->get('id'),
582
                );
583
584
                if ($categoryId = $request->get('category_id')) {
585
                    $Category = $app['eccube.repository.category']->find($categoryId);
586
                    $searchData['category_id'] = $Category;
587
                }
588
589
                $session->set('eccube.admin.order.product.search', $searchData);
590
                $session->set('eccube.admin.order.product.search.page_no', $page_no);
591
            } else {
592
                $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...
593
                if (is_null($page_no)) {
594
                    $page_no = intval($session->get('eccube.admin.order.product.search.page_no'));
595
                } else {
596
                    $session->set('eccube.admin.order.product.search.page_no', $page_no);
597
                }
598
            }
599
600
            $qb = $app['eccube.repository.product']
601
                ->getQueryBuilderBySearchDataForAdmin($searchData);
602
603
            $event = new EventArgs(
604
                array(
605
                    'qb' => $qb,
606
                    'searchData' => $searchData,
607
                ),
608
                $request
609
            );
610
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_SEARCH, $event);
611
612
            /** @var \Knp\Component\Pager\Pagination\SlidingPagination $pagination */
613
            $pagination = $app['paginator']()->paginate(
614
                $qb,
615
                $page_no,
616
                $page_count,
617
                array('wrap-queries' => true)
618
            );
619
620
            /** @var $Products \Eccube\Entity\Product[] */
621
            $Products = $pagination->getItems();
622
623
            if (empty($Products)) {
624
                $app['monolog']->addDebug('search product not found.');
625
            }
626
627
            $forms = array();
628
            foreach ($Products as $Product) {
629
                /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
630
                $builder = $app['form.factory']->createNamedBuilder('', 'add_cart', null, array(
631
                    'product' => $Product,
632
                ));
633
                $addCartForm = $builder->getForm();
634
                $forms[$Product->getId()] = $addCartForm->createView();
635
            }
636
637
            $event = new EventArgs(
638
                array(
639
                    'forms' => $forms,
640
                    'Products' => $Products,
641
                    'pagination' => $pagination,
642
                ),
643
                $request
644
            );
645
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_COMPLETE, $event);
646
647
            return $app->render('Order/search_product.twig', array(
648
                'forms' => $forms,
649
                'Products' => $Products,
650
                'pagination' => $pagination,
651
            ));
652
        }
653
    }
654
655
    protected function newOrder(Application $app)
656
    {
657
        $Order = new \Eccube\Entity\Order();
658
        $Shipping = new \Eccube\Entity\Shipping();
659
        $Shipping->setDelFlg(0);
660
        $Order->addShipping($Shipping);
661
        $Shipping->setOrder($Order);
662
663
        // device type
664
        $DeviceType = $app['eccube.repository.master.device_type']->find(DeviceType::DEVICE_TYPE_ADMIN);
665
        $Order->setDeviceType($DeviceType);
666
667
        return $Order;
668
    }
669
670
    /**
671
     * フォームからの入直内容に基づいて、受注情報の再計算を行う
672
     *
673
     * @param $app
674
     * @param $Order
675
     */
676
    protected function calculate($app, \Eccube\Entity\Order $Order)
677
    {
678
        $taxtotal = 0;
679
        $subtotal = 0;
680
681
        // 受注明細データの税・小計を再計算
682
        /** @var $OrderDetails \Eccube\Entity\OrderDetail[] */
683
        $OrderDetails = $Order->getOrderDetails();
684
        foreach ($OrderDetails as $OrderDetail) {
685
            // 税
686
            $tax = $app['eccube.service.tax_rule']
687
                ->calcTax($OrderDetail->getPrice(), $OrderDetail->getTaxRate(), $OrderDetail->getTaxRule());
688
            $OrderDetail->setPriceIncTax($OrderDetail->getPrice() + $tax);
689
690
            $taxtotal += $tax * $OrderDetail->getQuantity();
691
692
            // 小計
693
            $subtotal += $OrderDetail->getTotalPrice();
694
        }
695
696
        $shippings = $Order->getShippings();
697
        /** @var \Eccube\Entity\Shipping $Shipping */
698
        foreach ($shippings as $Shipping) {
699
            $Shipping->setDelFlg(Constant::DISABLED);
700
        }
701
702
        // 受注データの税・小計・合計を再計算
703
        $Order->setTax($taxtotal);
704
        $Order->setSubtotal($subtotal);
705
        $Order->setTotal($subtotal + $Order->getCharge() + $Order->getDeliveryFeeTotal() - $Order->getDiscount());
706
        // お支払い合計は、totalと同一金額(2系ではtotal - point)
707
        $Order->setPaymentTotal($Order->getTotal());
708
    }
709
710
    /**
711
     * 受注ステータスに応じて, 受注日/入金日/発送日を更新する,
712
     * 発送済ステータスが設定された場合は, お届け先情報の発送日も更新を行う.
713
     *
714
     * 編集の場合
715
     * - 受注ステータスが他のステータスから発送済へ変更された場合に発送日を更新
716
     * - 受注ステータスが他のステータスから入金済へ変更された場合に入金日を更新
717
     *
718
     * 新規登録の場合
719
     * - 受注日を更新
720
     * - 受注ステータスが発送済に設定された場合に発送日を更新
721
     * - 受注ステータスが入金済に設定された場合に入金日を更新
722
     *
723
     *
724
     * @param $app
725
     * @param $TargetOrder
726
     * @param $OriginOrder
727
     */
728
    protected function updateDate($app, $TargetOrder, $OriginOrder)
729
    {
730
        $dateTime = new \DateTime();
731
732
        // 編集
733
        if ($TargetOrder->getId()) {
734
            // 発送済
735
            if ($TargetOrder->getOrderStatus()->getId() == $app['config']['order_deliv']) {
736
                // 編集前と異なる場合のみ更新
737
                if ($TargetOrder->getOrderStatus()->getId() != $OriginOrder->getOrderStatus()->getId()) {
738
                    $TargetOrder->setCommitDate($dateTime);
739
                    // お届け先情報の発送日も更新する.
740
                    $Shippings = $TargetOrder->getShippings();
741
                    foreach ($Shippings as $Shipping) {
742
                        $Shipping->setShippingCommitDate($dateTime);
743
                    }
744
                }
745
                // 入金済
746
            } elseif ($TargetOrder->getOrderStatus()->getId() == $app['config']['order_pre_end']) {
747
                // 編集前と異なる場合のみ更新
748
                if ($TargetOrder->getOrderStatus()->getId() != $OriginOrder->getOrderStatus()->getId()) {
749
                    $TargetOrder->setPaymentDate($dateTime);
750
                }
751
            }
752
            // 新規
753
        } else {
754
            // 発送済
755
            if ($TargetOrder->getOrderStatus()->getId() == $app['config']['order_deliv']) {
756
                $TargetOrder->setCommitDate($dateTime);
757
                // お届け先情報の発送日も更新する.
758
                $Shippings = $TargetOrder->getShippings();
759
                foreach ($Shippings as $Shipping) {
760
                    $Shipping->setShippingCommitDate($dateTime);
761
                }
762
                // 入金済
763
            } elseif ($TargetOrder->getOrderStatus()->getId() == $app['config']['order_pre_end']) {
764
                $TargetOrder->setPaymentDate($dateTime);
765
            }
766
            // 受注日時
767
            $TargetOrder->setOrderDate($dateTime);
768
        }
769
    }
770
}
771