Completed
Push — master ( ce75f7...bb033c )
by Kentaro
26s
created

AdminController::getOrderEachStatus()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 27
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 27
ccs 9
cts 9
cp 1
rs 8.8571
cc 2
eloc 12
nc 2
nop 2
crap 2
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
25
namespace Eccube\Controller\Admin;
26
27
use Doctrine\ORM\NoResultException;
28
use Doctrine\ORM\Query\ResultSetMapping;
29
use Eccube\Application;
30
use Eccube\Common\Constant;
31
use Eccube\Controller\AbstractController;
32
use Eccube\Event\EccubeEvents;
33
use Eccube\Event\EventArgs;
34
use Symfony\Component\HttpFoundation\Request;
35
36
class AdminController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
37
{
38 6
    public function login(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
39
    {
40 6
        if ($app->isGranted('ROLE_ADMIN')) {
41
            return $app->redirect($app->url('admin_homepage'));
42
        }
43
44
        /* @var $form \Symfony\Component\Form\FormInterface */
45 6
        $builder = $app['form.factory']
46 6
            ->createNamedBuilder('', 'admin_login');
47
48 6
        $event = new EventArgs(
49
            array(
50 6
                'builder' => $builder,
51
            ),
52
            $request
53
        );
54 6
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_LOGIN_INITIALIZE, $event);
55
56 6
        $form = $builder->getForm();
57
58 6
        return $app->render('login.twig', array(
59 6
            'error' => $app['security.last_error']($request),
60 6
            'form' => $form->createView(),
61
        ));
62
    }
63
64 3
    public function index(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
65
    {
66
        // install.phpのチェック.
67 3
        if (isset($app['config']['eccube_install']) && $app['config']['eccube_install'] == 1) {
68 3
            $file = $app['config']['root_dir'] . '/html/install.php';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
69 3
            if (file_exists($file)) {
70 3
                $app->addWarning('admin.install.warning', 'admin');
71
            }
72
        }
73
74
        // 受注マスター検索用フォーム
75 3
        $searchOrderBuilder = $app['form.factory']
76 3
            ->createBuilder('admin_search_order');
77
        // 商品マスター検索用フォーム
78 3
        $searchProductBuilder = $app['form.factory']
79 3
            ->createBuilder('admin_search_product');
80
        // 会員マスター検索用フォーム
81 3
        $searchCustomerBuilder = $app['form.factory']
82 3
            ->createBuilder('admin_search_customer');
83
84 3
        $event = new EventArgs(
85
            array(
86 3
                'searchOrderBuilder' => $searchOrderBuilder,
87 3
                'searchProductBuilder' => $searchProductBuilder,
88 3
                'searchCustomerBuilder' => $searchCustomerBuilder,
89
            ),
90
            $request
91
        );
92 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_INITIALIZE, $event);
93
94
        // 受注マスター検索用フォーム
95 3
        $searchOrderForm = $searchOrderBuilder->getForm();
96
97
        // 商品マスター検索用フォーム
98 3
        $searchProductForm = $searchProductBuilder->getForm();
99
100
        // 会員マスター検索用フォーム
101 3
        $searchCustomerForm = $searchCustomerBuilder->getForm();
102
103
        /**
104
         * 受注状況.
105
         */
106 3
        $excludes = array();
107 3
        $excludes[] = $app['config']['order_pending'];
108 3
        $excludes[] = $app['config']['order_processing'];
109 3
        $excludes[] = $app['config']['order_cancel'];
110 3
        $excludes[] = $app['config']['order_deliv'];
111
112 3
        $event = new EventArgs(
113
            array(
114 3
                'excludes' => $excludes,
115
            ),
116
            $request
117
        );
118 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_ORDER, $event);
119
120
        // 受注ステータスごとの受注件数.
121 3
        $Orders = $this->getOrderEachStatus($app['orm.em'], $excludes);
122
        // 受注ステータスの一覧.
123 3
        $OrderStatuses = $this->findOrderStatus($app['orm.em'], $excludes);
124
125
        /**
126
         * 売り上げ状況
127
         */
128 3
        $excludes = array();
129 3
        $excludes[] = $app['config']['order_processing'];
130 3
        $excludes[] = $app['config']['order_cancel'];
131 3
        $excludes[] = $app['config']['order_pending'];
132
133 3
        $event = new EventArgs(
134
            array(
135 3
                'excludes' => $excludes,
136
            ),
137
            $request
138
        );
139 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_SALES, $event);
140
141
        // 今日の売上/件数
142 3
        $salesToday = $this->getSalesByDay($app['orm.em'], new \DateTime(), $excludes);
143
        // 昨日の売上/件数
144 3
        $salesYesterday = $this->getSalesByDay($app['orm.em'], new \DateTime('-1 day'), $excludes);
145
        // 今月の売上/件数
146 3
        $salesThisMonth = $this->getSalesByMonth($app['orm.em'], new \DateTime(), $excludes);
147
148
        /**
149
         * ショップ状況
150
         */
151
        // 在庫切れ商品数
152 3
        $countNonStockProducts = $this->countNonStockProducts($app['orm.em']);
153
        // 本会員数
154 3
        $countCustomers = $this->countCustomers($app['orm.em']);
155
156 3
        $event = new EventArgs(
157
            array(
158 3
                'Orders' => $Orders,
159 3
                'OrderStatuses' => $OrderStatuses,
160 3
                'salesThisMonth' => $salesThisMonth,
161 3
                'salesToday' => $salesToday,
162 3
                'salesYesterday' => $salesYesterday,
163 3
                'countNonStockProducts' => $countNonStockProducts,
164 3
                'countCustomers' => $countCustomers,
165
            ),
166
            $request
167
        );
168 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_COMPLETE, $event);
169
170 3
        return $app->render('index.twig', array(
171 3
            'searchOrderForm' => $searchOrderForm->createView(),
172 3
            'searchProductForm' => $searchProductForm->createView(),
173 3
            'searchCustomerForm' => $searchCustomerForm->createView(),
174 3
            'Orders' => $Orders,
175 3
            'OrderStatuses' => $OrderStatuses,
176 3
            'salesThisMonth' => $salesThisMonth,
177 3
            'salesToday' => $salesToday,
178 3
            'salesYesterday' => $salesYesterday,
179 3
            'countNonStockProducts' => $countNonStockProducts,
180 3
            'countCustomers' => $countCustomers,
181
        ));
182
    }
183
184
    /**
185
     * パスワード変更画面
186
     *
187
     * @param Application $app
188
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
189
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
190
     */
191 2
    public function changePassword(Application $app, Request $request)
192
    {
193
        $builder = $app['form.factory']
194 2
            ->createBuilder('admin_change_password');
195 2
196 2
        $event = new EventArgs(
197
            array(
198 2
                'builder' => $builder,
199 2
            ),
200
            $request
201 2
        );
202
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_CHANGE_PASSWORD_INITIALIZE, $event);
203
204
        $form = $builder->getForm();
205
        $form->handleRequest($request);
206
207
        if ($form->isSubmitted() && $form->isValid()) {
208
            $password = $form->get('change_password')->getData();
209
210
            $Member = $app->user();
211
212
            $dummyMember = clone $Member;
213
            $dummyMember->setPassword($password);
214 2
            $salt = $dummyMember->getSalt();
215
            if (!isset($salt)) {
216
                $salt = $app['eccube.repository.member']->createSalt(5);
217 3
                $dummyMember->setSalt($salt);
218
            }
219
220 3
            $encryptPassword = $app['eccube.repository.member']->encryptPassword($dummyMember);
221 3
222
            $Member
223
                ->setPassword($encryptPassword)
224 3
                ->setSalt($salt);
225 3
226 3
            $status = $app['eccube.repository.member']->save($Member);
227
            if ($status) {
228
                $event = new EventArgs(
229 3
                    array(
230
                        'form' => $form,
231
                    ),
232
                    $request
233
                );
234
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIN_CHANGE_PASSWORD_COMPLETE, $event);
235
236
                $app->addSuccess('admin.change_password.save.complete', 'admin');
237
238
                return $app->redirect($app->url('admin_change_password'));
239
            }
240
241
            $app->addError('admin.change_password.save.error', 'admin');
242 3
        }
243 3
244 3
        return $app->render('change_password.twig', array(
245 3
            'form' => $form->createView(),
246 3
        ));
247 3
    }
248 3
249 3
    /**
250 3
     * 在庫なし商品の検索結果を表示する.
251 3
     *
252
     * @param Application $app
253
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
254 3
     * @return \Symfony\Component\HttpFoundation\Response
255
     */
256
    public function searchNonStockProducts(Application $app, Request $request)
257 3
    {
258
        // 商品マスター検索用フォーム
259
        $form = $app['form.factory']
260
            ->createBuilder('admin_search_product')
261
            ->getForm();
262
263
        if ('POST' === $request->getMethod()) {
264
            $form->handleRequest($request);
265
266
            if ($form->isValid()) {
267
                // 在庫なし商品の検索条件をセッションに付与し, 商品マスタへリダイレクトする.
268
                $searchData = array();
269
                $searchData['stock_status'] = Constant::DISABLED;
270
                $session = $request->getSession();
271
                $session->set('eccube.admin.product.search', $searchData);
272 3
273
                return $app->redirect($app->url('admin_product_page', array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
274
                    'page_no' => 1,
275 3
                    'status' => $app['config']['admin_product_stock_status'])));
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 16 spaces, but found 20.
Loading history...
276 3
            }
277 3
        }
278
279 3
        return $app->redirect($app->url('admin_homepage'));
280
    }
281 3
282 2
    protected function findOrderStatus($em, array $excludes)
283
    {
284
        $qb = $em
285 3
            ->getRepository('Eccube\Entity\Master\OrderStatus')
286
            ->createQueryBuilder('os');
287
288 3
        return $qb
289
            ->where($qb->expr()->notIn('os.id', $excludes))
290
            ->getQuery()
291
            ->getResult();
292
    }
293
294
    protected function getOrderEachStatus($em, array $excludes)
295
    {
296
        $sql = 'SELECT
297
                    t1.status as status,
298
                    COUNT(t1.order_id) as count
299
                FROM
300
                    dtb_order t1
301
                WHERE
302
                    t1.del_flg = 0
303 3
                    AND t1.status NOT IN (:excludes)
304
                GROUP BY
305
                    t1.status
306 3
                ORDER BY
307 3
                    t1.status';
308 3
        $rsm = new ResultSetMapping();;
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
309
        $rsm->addScalarResult('status', 'status');
310 3
        $rsm->addScalarResult('count', 'count');
311
        $query = $em->createNativeQuery($sql, $rsm);
312 3
        $query->setParameters(array(':excludes' => $excludes));
313 2
        $result = $query->getResult();
314
        $orderArray = array();
315
        foreach ($result as $row) {
316 3
            $orderArray[$row['status']] = $row['count'];
317
        }
318
319 3
        return $orderArray;
320
    }
321
322 3 View Code Duplication
    protected function getSalesByMonth($em, $dateTime, array $excludes)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
323 3
    {
324 3
        // concat... for pgsql
325 3
        // http://stackoverflow.com/questions/1091924/substr-does-not-work-with-datatype-timestamp-in-postgres-8-3
326 3
        $dql = 'SELECT
327 3
                  SUBSTRING(CONCAT(o.order_date, \'\'), 1, 7) AS order_month,
328
                  SUM(o.payment_total) AS order_amount,
329
                  COUNT(o) AS order_count
330 3
                FROM
331 3
                  Eccube\Entity\Order o
332
                WHERE
333
                    o.del_flg = 0
334 3
                    AND o.OrderStatus NOT IN (:excludes)
335
                    AND SUBSTRING(CONCAT(o.order_date, \'\'), 1, 7) = SUBSTRING(:targetDate, 1, 7)
336
                GROUP BY
337 3
                  order_month';
338 3
339
        $q = $em
340
            ->createQuery($dql)
341 3
            ->setParameter(':excludes', $excludes)
342 3
            ->setParameter(':targetDate', $dateTime);
343 3
344 3
        $result = array();
345 3
        try {
346
            $result = $q->getSingleResult();
347
        } catch (NoResultException $e) {
348 3
            // 結果がない場合は空の配列を返す.
349 3
        }
350
        return $result;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
351
    }
352
353 View Code Duplication
    protected function getSalesByDay($em, $dateTime, array $excludes)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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
    {
355
        // concat... for pgsql
356
        // http://stackoverflow.com/questions/1091924/substr-does-not-work-with-datatype-timestamp-in-postgres-8-3
357
        $dql = 'SELECT
358
                  SUBSTRING(CONCAT(o.order_date, \'\'), 1, 10) AS order_day,
359
                  SUM(o.payment_total) AS order_amount,
360
                  COUNT(o) AS order_count
361
                FROM
362
                  Eccube\Entity\Order o
363
                WHERE
364
                    o.del_flg = 0
365
                    AND o.OrderStatus NOT IN (:excludes)
366
                    AND SUBSTRING(CONCAT(o.order_date, \'\'), 1, 10) = SUBSTRING(:targetDate, 1, 10)
367
                GROUP BY
368
                  order_day';
369
370
        $q = $em
371
            ->createQuery($dql)
372
            ->setParameter(':excludes', $excludes)
373
            ->setParameter(':targetDate', $dateTime);
374
375
        $result = array();
376
        try {
377
            $result = $q->getSingleResult();
378
        } catch (NoResultException $e) {
379
            // 結果がない場合は空の配列を返す.
380
        }
381
        return $result;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
382
    }
383
384
    protected function countNonStockProducts($em)
385
    {
386
        /** @var $qb \Doctrine\ORM\QueryBuilder */
387
        $qb = $em->getRepository('Eccube\Entity\Product')
388
            ->createQueryBuilder('p')
389
            ->select('count(p.id)')
390
            ->innerJoin('p.ProductClasses', 'pc')
391
            ->where('pc.stock_unlimited = :StockUnlimited AND pc.stock = 0')
392
            ->setParameter('StockUnlimited', Constant::DISABLED);
393
394
        return $qb
395
            ->getQuery()
396
            ->getSingleScalarResult();
397
    }
398
399
    protected function countCustomers($em)
400
    {
401
        $Status = $em
402
            ->getRepository('Eccube\Entity\Master\CustomerStatus')
403
            ->find(2);
404
405
        /** @var $qb \Doctrine\ORM\QueryBuilder */
406
        $qb = $em->getRepository('Eccube\Entity\Customer')
407
            ->createQueryBuilder('c')
408
            ->select('count(c.id)')
409
            ->where('c.Status = :Status')
410
            ->setParameter('Status', $Status);
411
412
        return $qb
413
            ->getQuery()
414
            ->getSingleScalarResult();
415
    }
416
}