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

AdminController::getSalesByDay()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 30
Code Lines 11

Duplication

Lines 30
Ratio 100 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 30
loc 30
ccs 9
cts 9
cp 1
rs 8.8571
cc 2
eloc 11
nc 2
nop 3
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 Doctrine\ORM\QueryBuilder;
30
use Eccube\Application;
31
use Eccube\Common\Constant;
32
use Eccube\Controller\AbstractController;
33
use Eccube\Event\EccubeEvents;
34
use Eccube\Event\EventArgs;
35
use Eccube\Form\Type\Admin\ChangePasswordType;
36
use Eccube\Form\Type\Admin\LoginType;
37
use Eccube\Form\Type\Admin\SearchCustomerType;
38
use Eccube\Form\Type\Admin\SearchOrderType;
39
use Eccube\Form\Type\Admin\SearchProductType;
40
use Symfony\Component\Form\Form;
41
use Symfony\Component\HttpFoundation\Request;
42
43 6
class AdminController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
44
{
45 6
    public function login(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
46
    {
47
        if ($app->isGranted('ROLE_ADMIN')) {
48
            return $app->redirect($app->url('admin_homepage'));
49
        }
50 6
51 6
        /* @var $form \Symfony\Component\Form\FormInterface */
52
        $builder = $app['form.factory']
53 6
            ->createNamedBuilder('', LoginType::class);
54
55 6
        $event = new EventArgs(
56
            array(
57
                'builder' => $builder,
58
            ),
59 6
            $request
60
        );
61 6
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_LOGIN_INITIALIZE, $event);
62
63 6
        $form = $builder->getForm();
64 6
65 6
        return $app->render('login.twig', array(
66
            'error' => $app['security.last_error']($request),
67
            'form' => $form->createView(),
68
        ));
69 3
    }
70
71
    public function index(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
72 3
    {
73 3
        // install.phpのチェック.
74 3
        if (isset($app['config']['eccube_install']) && $app['config']['eccube_install'] == 1) {
75 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...
76 3 View Code Duplication
            if (file_exists($file)) {
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...
77
                $message = $app->trans('admin.install.warning', array('installphpPath' => 'html/install.php'));
78 3
                $app->addWarning($message, 'admin');
79 3
            }
80
            $fileOnRoot = $app['config']['root_dir'] . '/install.php';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
81 View Code Duplication
            if (file_exists($fileOnRoot)) {
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...
82
                $message = $app->trans('admin.install.warning', array('installphpPath' => 'install.php'));
83
                $app->addWarning($message, 'admin');
84
            }
85
        }
86 3
87 3
        // 受注マスター検索用フォーム
88
        $searchOrderBuilder = $app['form.factory']
89 3
            ->createBuilder(SearchOrderType::class);
90 3
        // 商品マスター検索用フォーム
91
        $searchProductBuilder = $app['form.factory']
92 3
            ->createBuilder(SearchProductType::class);
93 3
        // 会員マスター検索用フォーム
94
        $searchCustomerBuilder = $app['form.factory']
95 3
            ->createBuilder(SearchCustomerType::class);
96
97 3
        $event = new EventArgs(
98 3
            array(
99 3
                'searchOrderBuilder' => $searchOrderBuilder,
100
                'searchProductBuilder' => $searchProductBuilder,
101
                'searchCustomerBuilder' => $searchCustomerBuilder,
102
            ),
103 3
            $request
104
        );
105
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_INITIALIZE, $event);
106 3
107
        // 受注マスター検索用フォーム
108
        $searchOrderForm = $searchOrderBuilder->getForm();
109 3
110
        // 商品マスター検索用フォーム
111
        $searchProductForm = $searchProductBuilder->getForm();
112 3
113
        // 会員マスター検索用フォーム
114
        $searchCustomerForm = $searchCustomerBuilder->getForm();
115
116
        /**
117 3
         * 受注状況.
118 3
         */
119 3
        $excludes = array();
120 3
        $excludes[] = $app['config']['order_pending'];
121 3
        $excludes[] = $app['config']['order_processing'];
122
        $excludes[] = $app['config']['order_cancel'];
123 3
        $excludes[] = $app['config']['order_deliv'];
124
125 3
        $event = new EventArgs(
126
            array(
127
                'excludes' => $excludes,
128
            ),
129 3
            $request
130
        );
131
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_ORDER, $event);
132 3
        $excludes = $event->getArgument('excludes');
133
134 3
        // 受注ステータスごとの受注件数.
135
        $Orders = $this->getOrderEachStatus($app['orm.em'], $excludes);
136
        // 受注ステータスの一覧.
137
        $OrderStatuses = $this->findOrderStatus($app['orm.em'], $excludes);
138
139 3
        /**
140 3
         * 売り上げ状況
141 3
         */
142 3
        $excludes = array();
143
        $excludes[] = $app['config']['order_processing'];
144 3
        $excludes[] = $app['config']['order_cancel'];
145
        $excludes[] = $app['config']['order_pending'];
146 3
147
        $event = new EventArgs(
148
            array(
149
                'excludes' => $excludes,
150 3
            ),
151
            $request
152
        );
153 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_SALES, $event);
154
        $excludes = $event->getArgument('excludes');
155 3
156
        // 今日の売上/件数
157 3
        $salesToday = $this->getSalesByDay($app['orm.em'], new \DateTime(), $excludes);
158
        // 昨日の売上/件数
159
        $salesYesterday = $this->getSalesByDay($app['orm.em'], new \DateTime('-1 day'), $excludes);
160
        // 今月の売上/件数
161
        $salesThisMonth = $this->getSalesByMonth($app['orm.em'], new \DateTime(), $excludes);
162
163 3
        /**
164
         * ショップ状況
165 3
         */
166
        // 在庫切れ商品数
167 3
        $countNonStockProducts = $this->countNonStockProducts($app['orm.em']);
168
        // 本会員数
169 3
        $countCustomers = $this->countCustomers($app['orm.em']);
170 3
171 3
        $event = new EventArgs(
172 3
            array(
173 3
                'Orders' => $Orders,
174 3
                'OrderStatuses' => $OrderStatuses,
175 3
                'salesThisMonth' => $salesThisMonth,
176
                'salesToday' => $salesToday,
177
                'salesYesterday' => $salesYesterday,
178
                'countNonStockProducts' => $countNonStockProducts,
179 3
                'countCustomers' => $countCustomers,
180
            ),
181 3
            $request
182 3
        );
183 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_COMPLETE, $event);
184 3
185 3
        return $app->render('index.twig', array(
186 3
            'searchOrderForm' => $searchOrderForm->createView(),
187 3
            'searchProductForm' => $searchProductForm->createView(),
188 3
            'searchCustomerForm' => $searchCustomerForm->createView(),
189 3
            'Orders' => $Orders,
190 3
            'OrderStatuses' => $OrderStatuses,
191 3
            'salesThisMonth' => $salesThisMonth,
192
            'salesToday' => $salesToday,
193
            'salesYesterday' => $salesYesterday,
194
            'countNonStockProducts' => $countNonStockProducts,
195
            'countCustomers' => $countCustomers,
196
        ));
197
    }
198
199
    /**
200
     * パスワード変更画面
201
     *
202 3
     * @param Application $app
203
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
204 3
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
205 3
     */
206
    public function changePassword(Application $app, Request $request)
207 3
    {
208
        $builder = $app['form.factory']
209 3
            ->createBuilder(ChangePasswordType::class);
210
211
        $event = new EventArgs(
212
            array(
213 3
                'builder' => $builder,
214
            ),
215 3
            $request
216 3
        );
217
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_CHANGE_PASSWORD_INITIALIZE, $event);
218 3
219 1
        $form = $builder->getForm();
220
        $form->handleRequest($request);
221 1
222
        if ($form->isSubmitted() && $form->isValid()) {
223 1
            $password = $form->get('change_password')->getData();
224 1
225 1
            $Member = $app->user();
226 1
227
            $dummyMember = clone $Member;
228
            $dummyMember->setPassword($password);
229
            $salt = $dummyMember->getSalt();
230
            if (!isset($salt)) {
231 1
                $salt = $app['eccube.repository.member']->createSalt(5);
232
                $dummyMember->setSalt($salt);
233
            }
234 1
235 1
            $encryptPassword = $app['eccube.repository.member']->encryptPassword($dummyMember);
236
237 1
            $Member
238 1
                ->setPassword($encryptPassword)
239 1
                ->setSalt($salt);
240
241 1
            $status = $app['eccube.repository.member']->save($Member);
242
            if ($status) {
243
                $event = new EventArgs(
244
                    array(
245 1
                        'form' => $form,
246
                    ),
247 1
                    $request
248
                );
249 1
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIN_CHANGE_PASSWORD_COMPLETE, $event);
250
251
                $app->addSuccess('admin.change_password.save.complete', 'admin');
252
253
                return $app->redirect($app->url('admin_change_password'));
254
            }
255 2
256 2
            $app->addError('admin.change_password.save.error', 'admin');
257
        }
258
259
        return $app->render('change_password.twig', array(
260
            'form' => $form->createView(),
261
        ));
262
    }
263
264
    /**
265
     * 在庫なし商品の検索結果を表示する.
266
     *
267 2
     * @param Application $app
268
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
269
     * @return \Symfony\Component\HttpFoundation\Response
270 2
     */
271 2
    public function searchNonStockProducts(Application $app, Request $request)
272 2
    {
273
        // 商品マスター検索用フォーム
274 2
        /* @var Form $form */
275 2
        $form = $app['form.factory']
276
            ->createBuilder(SearchProductType::class)
277 2
            ->getForm();
278
279
        $form->handleRequest($request);
280
        if ($form->isSubmitted() && $form->isValid()) {
281
            // 在庫なし商品の検索条件をセッションに付与し, 商品マスタへリダイレクトする.
282
            $searchData = array();
283
            $searchData['stock_status'] = Constant::DISABLED;
284
            $session = $request->getSession();
285
            $session->set('eccube.admin.product.search', $searchData);
286
287
            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...
288
                'page_no' => 1,
289
                '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 12 spaces, but found 16.
Loading history...
290 2
        }
291
292
        return $app->redirect($app->url('admin_homepage'));
293 3
    }
294
295
    protected function findOrderStatus($em, array $excludes)
296 3
    {
297 3
        /* @var $qb QueryBuilder */
298
        $qb = $em
299
            ->getRepository('Eccube\Entity\Master\OrderStatus')
300 3
            ->createQueryBuilder('os');
301 3
302 3
        return $qb
303
            ->where($qb->expr()->notIn('os.id', $excludes))
304
            ->orderBy('os.rank', 'ASC')
305 3
            ->getQuery()
306
            ->getResult();
307
    }
308
309
    protected function getOrderEachStatus($em, array $excludes)
310
    {
311
        $sql = 'SELECT
312
                    t1.status as status,
313
                    COUNT(t1.order_id) as count
314
                FROM
315
                    dtb_order t1
316
                WHERE
317
                    t1.del_flg = 0
318 3
                    AND t1.status NOT IN (:excludes)
319 3
                GROUP BY
320 3
                    t1.status
321 3
                ORDER BY
322 3
                    t1.status';
323 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...
324 3
        $rsm->addScalarResult('status', 'status');
325 3
        $rsm->addScalarResult('count', 'count');
326 3
        $query = $em->createNativeQuery($sql, $rsm);
327 3
        $query->setParameters(array(':excludes' => $excludes));
328
        $result = $query->getResult();
329
        $orderArray = array();
330 3
        foreach ($result as $row) {
331
            $orderArray[$row['status']] = $row['count'];
332
        }
333 3
334
        return $orderArray;
335
    }
336
337 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...
338
    {
339
        // concat... for pgsql
340
        // http://stackoverflow.com/questions/1091924/substr-does-not-work-with-datatype-timestamp-in-postgres-8-3
341
        $dql = 'SELECT
342
                  SUBSTRING(CONCAT(o.order_date, \'\'), 1, 7) AS order_month,
343
                  SUM(o.payment_total) AS order_amount,
344
                  COUNT(o) AS order_count
345
                FROM
346
                  Eccube\Entity\Order o
347
                WHERE
348 3
                    o.del_flg = 0
349
                    AND o.OrderStatus NOT IN (:excludes)
350
                    AND SUBSTRING(CONCAT(o.order_date, \'\'), 1, 7) = SUBSTRING(:targetDate, 1, 7)
351 3
                GROUP BY
352 3
                  order_month';
353 3
354
        $q = $em
355 3
            ->createQuery($dql)
356
            ->setParameter(':excludes', $excludes)
357 3
            ->setParameter(':targetDate', $dateTime);
358 2
359
        $result = array();
360
        try {
361 3
            $result = $q->getSingleResult();
362
        } catch (NoResultException $e) {
363
            // 結果がない場合は空の配列を返す.
364 3
        }
365
        return $result;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
366
    }
367
368 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...
369
    {
370
        // concat... for pgsql
371
        // http://stackoverflow.com/questions/1091924/substr-does-not-work-with-datatype-timestamp-in-postgres-8-3
372
        $dql = 'SELECT
373
                  SUBSTRING(CONCAT(o.order_date, \'\'), 1, 10) AS order_day,
374
                  SUM(o.payment_total) AS order_amount,
375
                  COUNT(o) AS order_count
376
                FROM
377
                  Eccube\Entity\Order o
378
                WHERE
379 3
                    o.del_flg = 0
380
                    AND o.OrderStatus NOT IN (:excludes)
381
                    AND SUBSTRING(CONCAT(o.order_date, \'\'), 1, 10) = SUBSTRING(:targetDate, 1, 10)
382 3
                GROUP BY
383 3
                  order_day';
384 3
385
        $q = $em
386 3
            ->createQuery($dql)
387
            ->setParameter(':excludes', $excludes)
388 3
            ->setParameter(':targetDate', $dateTime);
389 2
390
        $result = array();
391
        try {
392 3
            $result = $q->getSingleResult();
393
        } catch (NoResultException $e) {
394
            // 結果がない場合は空の配列を返す.
395 3
        }
396
        return $result;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
397
    }
398 3
399 3
    protected function countNonStockProducts($em)
400 3
    {
401 3
        /** @var $qb \Doctrine\ORM\QueryBuilder */
402 3
        $qb = $em->getRepository('Eccube\Entity\Product')
403 3
            ->createQueryBuilder('p')
404
            ->select('count(DISTINCT p.id)')
405
            ->innerJoin('p.ProductClasses', 'pc')
406 3
            ->where('pc.stock_unlimited = :StockUnlimited AND pc.stock = 0')
407 3
            ->setParameter('StockUnlimited', Constant::DISABLED);
408
409
        return $qb
410 3
            ->getQuery()
411
            ->getSingleScalarResult();
412
    }
413 3
414 3
    protected function countCustomers($em)
415
    {
416
        $Status = $em
417 3
            ->getRepository('Eccube\Entity\Master\CustomerStatus')
418 3
            ->find(2);
419 3
420 3
        /** @var $qb \Doctrine\ORM\QueryBuilder */
421 3
        $qb = $em->getRepository('Eccube\Entity\Customer')
422
            ->createQueryBuilder('c')
423
            ->select('count(c.id)')
424 3
            ->where('c.Status = :Status')
425 3
            ->setParameter('Status', $Status);
426
427
        return $qb
428
            ->getQuery()
429
            ->getSingleScalarResult();
430
    }
431
}
432