CustomerReport::query()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 14
c 2
b 0
f 0
nc 2
nop 1
dl 0
loc 24
rs 9.7998
1
<?php
2
3
namespace SilverShop\Reports;
4
5
use SilverStripe\Security\Member;
6
7
/**
8
 * List top customers, especially those who spend alot, and those who buy alot.
9
 *
10
 * @todo customer making the most purchases
11
 * @todo customer who has spent the most money
12
 * @todo new registrations graph
13
 * @todo demographics
14
 */
15
class CustomerReport extends ShopPeriodReport
16
{
17
    protected $title = 'Customers';
18
    protected $description = 'Understand which customers spend the most.';
19
20
    protected $dataClass = Member::class;
21
22
    protected $periodfield = '"SilverShop_Order"."Paid"';
23
24
    public function columns()
25
    {
26
        return [
27
            'FirstName' => 'First Name',
28
            'Surname' => 'Surname',
29
            'Email' => 'Email',
30
            'Created' => 'Joined',
31
            'Spent' => 'Spent',
32
            'Orders' => 'Orders',
33
            'edit' => [
34
                'title' => 'Edit',
35
                'formatting' => '<a href=\"admin/security/EditForm/field/Members/item/$ID/edit\" target=\"_new\">edit</a>',
36
            ],
37
        ];
38
    }
39
40
    public function getReportField()
41
    {
42
        $field = parent::getReportField();
43
        return $field;
44
    }
45
46
    public function query($params)
47
    {
48
        $query = parent::query($params);
49
        $query->selectField($this->periodfield, 'FilterPeriod')
50
            ->addSelect(
51
                ['"Member"."ID"', '"Member"."FirstName"', '"Member"."Surname"', '"Member"."Email"', '"Member"."Created"']
52
            )
53
            ->selectField('COUNT("SilverShop_Order"."ID")', 'Orders')
54
            ->selectField('SUM("SilverShop_Order"."Total")', 'Spent');
55
56
        $query->addInnerJoin('SilverShop_Order', '"Member"."ID" = "SilverShop_Order"."MemberID"');
57
58
        $query->addGroupBy('"Member"."ID"');
59
60
        if (!$query->getOrderBy()) {
61
            $query->setOrderBy(
62
                [
63
                'Spent' => 'DESC',
64
                'Orders' => 'DESC'
65
                ]
66
            );
67
        }
68
        $query->setLimit(50);
69
        return $query;
70
    }
71
}
72