Completed
Push — master ( 090cd7...64a1d5 )
by Ryo
56:45 queued 50:30
created

AdminController::countNonStockProducts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

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