Completed
Push — master ( aa83e2...f8f77e )
by Jason
22:25 queued 07:26
created

Order::parseOrder()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
ccs 6
cts 6
cp 1
cc 2
eloc 9
nc 2
nop 0
crap 2
1
<?php
2
3
class Order extends DataObject implements PermissionProvider
4
{
5
6
    private static $db = array(
7
        'Order_ID' => 'Int',
8
        'TransactionDate' => 'SS_Datetime',
9
        'ProductTotal' => 'Currency',
10
        'TaxTotal' => 'Currency',
11
        'ShippingTotal' => 'Currency',
12
        'OrderTotal' => 'Currency',
13
        'ReceiptURL' => 'Varchar(255)',
14
        'OrderStatus' => 'Varchar(255)',
15
        'Response' => 'Text'
16
    );
17
18
    private static $has_one = array(
19
        'Member' => 'Member'
20
    );
21
22
    private static $has_many = array(
23
        'Details' => 'OrderDetail'
24
    );
25
26
    private static $singular_name = 'Order';
27
    private static $plural_name = 'Orders';
28
    private static $description = 'Orders from FoxyCart Datafeed';
29
    private static $default_sort = 'TransactionDate DESC, ID DESC';
0 ignored issues
show
Unused Code introduced by
The property $default_sort is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
30
31
    private static $summary_fields = array(
32
        'Order_ID',
33
        'TransactionDate.NiceUS',
34
        'Member.Name',
35
        'ProductTotal.Nice',
36
        'ShippingTotal.Nice',
37
        'TaxTotal.Nice',
38
        'OrderTotal.Nice',
39
        'ReceiptLink'
40
    );
41
42
    private static $searchable_fields = array(
43
        'Order_ID',
44
        'TransactionDate' => array(
45
            "field" => "DateField",
46
            "filter" => "PartialMatchFilter"
47
        ),
48
        'Member.ID',
49
        'OrderTotal',
50
        'Details.ProductID'
51
    );
52
53
    private static $casting = array(
54
        'ReceiptLink' => 'HTMLVarchar'
55
    );
56
    
57
    private static $indexes = array(
58
        'Order_ID' => true // make unique
59
    );
60
61 1
    public function fieldLabels($includerelations = true)
62
    {
63 1
        $labels = parent::fieldLabels();
64
65 1
        $labels['Order_ID'] = _t('Order.Order_ID', 'Order ID#');
66 1
        $labels['TransactionDate'] = _t('Order.TransactionDate', "Date");
67 1
        $labels['TransactionDate.NiceUS'] = _t('Order.TransactionDate', "Date");
68 1
        $labels['Member.Name'] = _t('Order.MemberName', 'Customer');
69 1
        $labels['Member.ID'] = _t('Order.MemberName', 'Customer');
70 1
        $labels['ProductTotal.Nice'] = _t('Order.ProductTotal', 'Sub Total');
71 1
        $labels['TaxTotal.Nice'] = _t('Order.TaxTotal', 'Tax');
72 1
        $labels['ShippingTotal.Nice'] = _t('Order.ShippingTotal', 'Shipping');
73 1
        $labels['OrderTotal'] = _t('Order.OrderTotal', 'Total');
74 1
        $labels['OrderTotal.Nice'] = _t('Order.OrderTotal', 'Total');
75 1
        $labels['ReceiptLink'] = _t('Order.ReceiptLink', 'Invoice');
76 1
        $labels['Details.ProductID'] = _t('Order.Details.ProductID', 'Product');
77
78 1
        return $labels;
79
    }
80
81 1
    public function ReceiptLink()
82
    {
83 1
        return $this->getReceiptLink();
84
    }
85
86 1
    public function getReceiptLink()
87
    {
88 1
        $obj= HTMLVarchar::create();
89 1
        $obj->setValue('<a href="' . $this->ReceiptURL . '" target="_blank" class="cms-panel-link action external-link">view</a>');
90 1
        return $obj;
91
    }
92
93 1
    public function getDecryptedResponse() {
94
        $decrypted = urldecode($this->Response);
95 1
        return rc4crypt::decrypt(FoxyCart::getStoreKey(), $decrypted);
96
    }
97
98 1
    public function onBeforeWrite() {
99
100
        $this->parseOrder();
101 1
        parent::onBeforeWrite();
102
    }
103
104 1
    public function parseOrder() {
105
106 1
        if ($this->getDecryptedResponse()) {
107
108
            $response = new SimpleXMLElement($this->getDecryptedResponse());
109
110 1
            $this->parseOrderInfo($response);
111
            $this->parseOrderCustomer($response);
112 1
            $this->parseOrderDetails($response);
113
114
            return true;
115 1
116
        } else {
117
118
            return false;
119 1
120
        }
121
    }
122 1
123
    public function parseOrderInfo($response) {
124
125
        foreach ($response->transactions->transaction as $transaction) {
126
127
            // Record transaction data from FoxyCart Datafeed:
128
            $this->Store_ID = (int) $transaction->store_id;
129
            $this->TransactionDate = (string) $transaction->transaction_date;
130
            $this->ProductTotal = (float) $transaction->product_total;
131
            $this->TaxTotal = (float) $transaction->tax_total;
132
            $this->ShippingTotal = (float) $transaction->shipping_total;
133
            $this->OrderTotal = (float) $transaction->order_total;
134
            $this->ReceiptURL = (string) $transaction->receipt_url;
135
            $this->OrderStatus = (string) $transaction->status;
136
137
            $this->extend('handleOrderInfo', $order, $response);
0 ignored issues
show
Bug introduced by
The variable $order does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
138
        }
139
    }
140
141
    public function parseOrderCustomer($response) {
142
143
        foreach ($response->transactions->transaction as $transaction) {
144
145
            // if not a guest transaction in FoxyCart
146
            if (isset($transaction->customer_email) && $transaction->is_anonymous == 0) {
147
148
                // if Customer is existing member, associate with current order
149
                if(Member::get()->filter('Email', $transaction->customer_email)->First()) {
150
151
                    $customer = Member::get()->filter('Email', $transaction->customer_email)->First();
152
153
                    // if new customer, create account with data from FoxyCart
154
                } else {
155
156
                    // set PasswordEncryption to 'none' so imported, encrypted password is not encrypted again
157
                    Config::inst()->update('Security', 'password_encryption_algorithm', 'none');
158
159
                    // create new Member, set password info from FoxyCart
160
                    $customer = Member::create();
161
                    $customer->Customer_ID = (int) $transaction->customer_id;
162
                    $customer->FirstName = (string) $transaction->customer_first_name;
163
                    $customer->Surname = (string) $transaction->customer_last_name;
164
                    $customer->Email = (string) $transaction->customer_email;
165
                    $customer->Password = (string) $transaction->customer_password;
166
                    $customer->Salt = (string) $transaction->customer_password_salt;
167
                    $customer->PasswordEncryption = 'none';
168
169
                    // record member record
170
                    $customer->write();
171
                }
172
173
                // set Order MemberID
174
                $this->MemberID = $customer->ID;
175
176
                $this->extend('handleOrderCustomer', $order, $response, $customer);
0 ignored issues
show
Bug introduced by
The variable $order does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
177
178
            }
179
        }
180
    }
181
182
    public function parseOrderDetails($response) {
183
184
        // remove previous OrderDetails and OrderOptions so we don't end up with duplicates
185
        foreach ($this->Details() as $detail) {
186
            foreach ($detail->OrderOptions() as $orderOption) {
187
                $orderOption->delete();
188
            }
189
            $detail->delete();
190
        }
191
192
        foreach ($response->transactions->transaction as $transaction) {
193
194
            // Associate ProductPages, Options, Quantity with Order
195
            foreach ($transaction->transaction_details->transaction_detail as $detail) {
196
197
                $OrderDetail = OrderDetail::create();
198
199
                $OrderDetail->Quantity = (int) $detail->product_quantity;
200
                $OrderDetail->ProductName = (string) $detail->product_name;
201
                $OrderDetail->ProductCode = (string) $detail->product_code;
202
                $OrderDetail->ProductImage = (string) $detail->image;
203
                $OrderDetail->ProductCategory = (string) $detail->category_code;
204
                $priceModifier = 0;
205
206
                // parse OrderOptions
207
                foreach ($detail->transaction_detail_options->transaction_detail_option as $option) {
208
209
                    // Find product via product_id custom variable
210
                    if ($option->product_option_name == 'product_id') {
211
212
                        // if product is found, set relation to OrderDetail
213
                        $OrderProduct = ProductPage::get()->byID((int) $option->product_option_value);
214
                        if ($OrderProduct) $OrderDetail->ProductID = $OrderProduct->ID;
215
216
                    } else {
217
218
                        $OrderOption = OrderOption::create();
219
                        $OrderOption->Name = (string) $option->product_option_name;
220
                        $OrderOption->Value = (string) $option->product_option_value;
221
                        $OrderOption->write();
222
                        $OrderDetail->OrderOptions()->add($OrderOption);
223
224
                        $priceModifier += $option->price_mod;
225
                    }
226
227
                }
228
229
                $OrderDetail->Price = (float) $detail->product_price + (float) $priceModifier;
230
231
                // extend OrderDetail parsing, allowing for recording custom fields from FoxyCart
232
                $this->extend('handleOrderItem', $order, $response, $OrderDetail);
0 ignored issues
show
Bug introduced by
The variable $order does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
233
234
                // write
235
                $OrderDetail->write();
236
237
                // associate with this order
238
                $this->Details()->add($OrderDetail);
239
            }
240
        }
241
    }
242
243
244
	public function canView($member = false) {
245
		return Permission::check('Product_ORDERS');
246
	}
247
248
	public function canEdit($member = null) {
249
        return false;
250
        //return Permission::check('Product_ORDERS');
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
251
	}
252
253
    public function canDelete($member = null)
254
    {
255
        return false;
256
        //return Permission::check('Product_ORDERS');
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
257
    }
258
259
    public function canCreate($member = null)
260
    {
261
        return false;
262
    }
263
264
    public function providePermissions()
265
    {
266
        return array(
267
            'Product_ORDERS' => 'Allow user to manage Orders and related objects'
268
        );
269
    }
270
}