Completed
Pull Request — master (#1968)
by
unknown
76:25
created

AdminController::searchNonStockProducts()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3

Importance

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