forked from silvershop/silvershop-core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Order.php
620 lines (555 loc) · 17.9 KB
/
Order.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
<?php
/**
* The order class is a databound object for handling Orders
* within SilverStripe.
*
* @package shop
*/
class Order extends DataObject
{
/**
* Status codes and what they mean:
*
* Unpaid (default): Order created but no successful payment by customer yet
* Query: Order not being processed yet (customer has a query, or could be out of stock)
* Paid: Order successfully paid for by customer
* Processing: Order paid for, package is currently being processed before shipping to customer
* Sent: Order paid for, processed for shipping, and now sent to the customer
* Complete: Order completed (paid and shipped). Customer assumed to have received their goods
* AdminCancelled: Order cancelled by the administrator
* MemberCancelled: Order cancelled by the customer (Member)
*/
private static $db = array(
'Total' => 'Currency',
'Reference' => 'Varchar', //allow for customised order numbering schemes
//status
'Placed' => "SS_Datetime", //date the order was placed (went from Cart to Order)
'Paid' => 'SS_Datetime', //no outstanding payment left
'ReceiptSent' => 'SS_Datetime', //receipt emailed to customer
'Printed' => 'SS_Datetime',
'Dispatched' => 'SS_Datetime', //products have been sent to customer
'Status' => "Enum('Unpaid,Paid,Processing,Sent,Complete,AdminCancelled,MemberCancelled,Cart','Cart')",
//customer (for guest orders)
'FirstName' => 'Varchar',
'Surname' => 'Varchar',
'Email' => 'Varchar',
'Notes' => 'Text',
'IPAddress' => 'Varchar(15)',
//separate shipping
'SeparateBillingAddress' => 'Boolean',
// keep track of customer locale
'Locale' => 'DBLocale',
);
private static $has_one = array(
'Member' => 'Member',
'ShippingAddress' => 'Address',
'BillingAddress' => 'Address',
);
private static $has_many = array(
'Items' => 'OrderItem',
'Modifiers' => 'OrderModifier',
'OrderStatusLogs' => 'OrderStatusLog',
);
private static $defaults = array(
'Status' => 'Cart',
);
private static $casting = array(
'FullBillingAddress' => 'Text',
'FullShippingAddress' => 'Text',
'Total' => 'Currency',
'SubTotal' => 'Currency',
'TotalPaid' => 'Currency',
'Shipping' => 'Currency',
'TotalOutstanding' => 'Currency',
);
private static $summary_fields = array(
'Reference' => 'Order No',
'Placed' => 'Date',
'Name' => 'Customer',
'LatestEmail' => 'Email',
'Total' => 'Total',
'Status' => 'Status',
);
private static $searchable_fields = array(
'Reference' => array(),
'FirstName' => array(
'title' => 'Customer Name',
),
'Email' => array(
'title' => 'Customer Email',
),
'Status' => array(
'filter' => 'ExactMatchFilter',
'field' => 'CheckboxSetField',
),
);
private static $singular_name = "Order";
private static $plural_name = "Orders";
private static $default_sort = "\"Placed\" DESC, \"Created\" DESC";
/**
* Statuses for orders that have been placed.
*/
private static $placed_status = array(
'Paid',
'Unpaid',
'Processing',
'Sent',
'Complete',
'MemberCancelled',
'AdminCancelled',
);
/**
* Statuses for which an order can be paid for
*/
private static $payable_status = array(
'Cart',
'Unpaid',
'Processing',
'Sent',
);
/**
* Statuses that shouldn't show in user account.
*/
private static $hidden_status = array('Cart');
/**
* Flags to determine when an order can be cancelled.
*/
private static $cancel_before_payment = true;
private static $cancel_before_processing = false;
private static $cancel_before_sending = false;
private static $cancel_after_sending = false;
/**
* Place an order before payment processing begins
*
* @var boolean
*/
private static $place_before_payment = false;
/**
* Modifiers represent the additional charges or
* deductions associated to an order, such as
* shipping, taxes, vouchers etc.
*/
private static $modifiers = array();
private static $rounding_precision = 2;
private static $reference_id_padding = 5;
/**
* @var boolean Will allow completion of orders with GrandTotal=0,
* which could be the case for orders paid with loyalty points or vouchers.
* Will send the "Paid" date on the order, even though no actual payment was taken.
* Will trigger the payment related extension points:
* Order->onPayment, OrderItem->onPayment, Order->onPaid.
*/
private static $allow_zero_order_total = false;
public static function get_order_status_options()
{
return singleton('Order')->dbObject('Status')->enumValues(false);
}
/**
* Create CMS fields for cms viewing and editing orders
*/
public function getCMSFields()
{
$fields = FieldList::create(TabSet::create('Root', Tab::create('Main')));
$fs = "<div class=\"field\">";
$fe = "</div>";
$parts = array(
DropdownField::create("Status", _t('Order.db_Status', "Status"), self::get_order_status_options()),
LiteralField::create('Customer', $fs . $this->renderWith("OrderAdmin_Customer") . $fe),
LiteralField::create('Addresses', $fs . $this->renderWith("OrderAdmin_Addresses") . $fe),
LiteralField::create('Content', $fs . $this->renderWith("OrderAdmin_Content") . $fe),
);
if ($this->Notes) {
$parts[] = LiteralField::create('Notes', $fs . $this->renderWith("OrderAdmin_Notes") . $fe);
}
$fields->addFieldsToTab('Root.Main', $parts);
$this->extend('updateCMSFields', $fields);
if ($payments = $fields->fieldByName("Root.Payments.Payments")) {
$fields->removeByName("Payments");
$fields->insertAfter($payments, "Content");
$payments->addExtraClass("order-payments");
}
return $fields;
}
/**
* Adjust scafolded search context
*
* @return SearchContext the updated search context
*/
public function getDefaultSearchContext()
{
$context = parent::getDefaultSearchContext();
$fields = $context->getFields();
$fields->push(
ListboxField::create("Status", _t('Order.db_Status', "Status"))
->setSource(
array_combine(
self::config()->placed_status,
self::config()->placed_status
)
)
->setMultiple(true)
);
//add date range filtering
$fields->insertBefore(
DateField::create("DateFrom", _t('Order.DATE_FROM', "Date from"))
->setConfig('showcalendar', true),
'Status'
);
$fields->insertBefore(
DateField::create("DateTo", _t('Order.DATE_TO', "Date to"))
->setConfig('showcalendar', true),
'Status'
);
//get the array, to maniplulate name, and fullname seperately
$filters = $context->getFilters();
$filters['DateFrom'] = GreaterThanFilter::create('Placed');
$filters['DateTo'] = LessThanFilter::create('Placed');
$context->setFilters($filters);
return $context;
}
/**
* Hack for swapping out relation list with OrderItemList
*/
public function getComponents($componentName, $filter = "", $sort = "", $join = "", $limit = null)
{
$components = parent::getComponents($componentName, $filter = "", $sort = "", $join = "", $limit = null);
if ($componentName === "Items" && get_class($components) !== "UnsavedRelationList") {
$query = $components->dataQuery();
$components = OrderItemList::create("OrderItem", "OrderID");
if ($this->model) {
$components->setDataModel($this->model);
}
$components->setDataQuery($query);
$components = $components->forForeignID($this->ID);
}
return $components;
}
/**
* Returns the subtotal of the items for this order.
*/
public function SubTotal()
{
if ($this->Items()->exists()) {
return $this->Items()->SubTotal();
}
return 0;
}
/**
* Calculate the total
*
* @return the final total
*/
public function calculate()
{
if (!$this->IsCart()) {
return $this->Total;
}
$calculator = new OrderTotalCalculator($this);
return $this->Total = $calculator->calculate();
}
/**
* This is needed to maintain backwards compatiability with
* some subsystems using modifiers. eg discounts
*/
public function getModifier($className, $forcecreate = false)
{
$calculator = new OrderTotalCalculator($this);
return $calculator->getModifier($className, $forcecreate);
}
/**
* Enforce rounding precision when setting total
*/
public function setTotal($val)
{
$this->setField("Total", round($val, self::$rounding_precision));
}
/**
* Get final value of order.
* Retrieves value from DataObject's record array.
*/
public function Total()
{
return $this->getField("Total");
}
/**
* Alias for Total.
*/
public function GrandTotal()
{
return $this->Total();
}
/**
* Calculate how much is left to be paid on the order.
* Enforces rounding precision.
*/
public function TotalOutstanding()
{
return round(
$this->GrandTotal() - $this->TotalPaid(),
self::config()->rounding_precision
);
}
/**
* Get the link for finishing order processing.
*/
public function Link()
{
if (Member::currentUser()) {
return Controller::join_links(AccountPage::find_link(), 'order', $this->ID);
}
return CheckoutPage::find_link(false, "order", $this->ID);
}
/**
* Returns TRUE if the order can be cancelled
* PRECONDITION: Order is in the DB.
*
* @return boolean
*/
public function canCancel()
{
switch ($this->Status) {
case 'Unpaid' :
return self::config()->cancel_before_payment;
case 'Paid' :
return self::config()->cancel_before_processing;
case 'Processing' :
return self::config()->cancel_before_sending;
case 'Sent' :
case 'Complete' :
return self::config()->cancel_after_sending;
}
return false;
}
/**
* Check if an order can be paid for.
*
* @return boolean
*/
public function canPay($member = null)
{
if (!in_array($this->Status, self::config()->payable_status)) {
return false;
}
if ($this->TotalOutstanding() > 0 && empty($this->Paid)) {
return true;
}
return false;
}
/*
* Prevent deleting orders.
* @return boolean
*/
public function canDelete($member = null)
{
return false;
}
/**
* Check if an order can be viewed.
*
* @return boolean
*/
public function canView($member = null)
{
return true;
}
/**
* Check if an order can be edited.
*
* @return boolean
*/
public function canEdit($member = null)
{
return true;
}
/**
* Prevent standard creation of orders.
*
* @return boolean
*/
public function canCreate($member = null, $context = array())
{
return false;
}
/**
* Return the currency of this order.
* Note: this is a fixed value across the entire site.
*
* @return string
*/
public function Currency()
{
return ShopConfig::get_site_currency();
}
/**
* Get the latest email for this order.
*/
public function getLatestEmail()
{
if ($this->MemberID && ($this->Member()->LastEdited > $this->LastEdited || !$this->Email)) {
return $this->Member()->Email;
}
return $this->getField('Email');
}
/**
* Gets the name of the customer.
*/
public function getName()
{
$firstname = $this->FirstName ? $this->FirstName : $this->Member()->FirstName;
$surname = $this->FirstName ? $this->Surname : $this->Member()->Surname;
return implode(" ", array_filter(array($firstname, $surname)));
}
public function getTitle()
{
return $this->Reference . " - " . $this->dbObject('Placed')->Nice();
}
/**
* Get shipping address, or member default shipping address.
*/
public function getShippingAddress()
{
return $this->getAddress('Shipping');
}
/**
* Get billing address, if marked to use seperate address, otherwise use shipping address,
* or the member default billing address.
*/
public function getBillingAddress()
{
if (!$this->SeparateBillingAddress && $this->ShippingAddressID === $this->BillingAddressID) {
return $this->getShippingAddress();
} else {
return $this->getAddress('Billing');
}
}
/**
* @param string $type - Billing or Shipping
* @return Address
* @throws Exception
*/
protected function getAddress($type)
{
$address = $this->getComponent($type . 'Address');
if (!$address || !$address->exists() && $this->Member()) {
$address = $this->Member()->{"Default${type}Address"}();
}
if (empty($address->Surname) && empty($address->FirstName)) {
$address->FirstName = $this->FirstName;
$address->Surname = $this->Surname;
}
return $address;
}
/**
* Check if the two addresses saved differ.
*
* @return boolean
*/
public function getAddressesDiffer()
{
return $this->SeparateBillingAddress || $this->ShippingAddressID !== $this->BillingAddressID;
}
/**
* Has this order been sent to the customer?
* (at "Sent" status).
*
* @return boolean
*/
public function IsSent()
{
return $this->Status == 'Sent';
}
/**
* Is this order currently being processed?
* (at "Sent" OR "Processing" status).
*
* @return boolean
*/
public function IsProcessing()
{
return $this->IsSent() || $this->Status == 'Processing';
}
/**
* Return whether this Order has been paid for (Status == Paid)
* or Status == Processing, where it's been paid for, but is
* currently in a processing state.
*
* @return boolean
*/
public function IsPaid()
{
return (boolean)$this->Paid || $this->Status == 'Paid';
}
public function IsCart()
{
return $this->Status == 'Cart';
}
/**
* Create a unique reference identifier string for this order.
*/
public function generateReference()
{
$reference = str_pad($this->ID, self::$reference_id_padding, '0', STR_PAD_LEFT);
$this->extend('generateReference', $reference);
$candidate = $reference;
//prevent generating references that are the same
$count = 0;
while (DataObject::get_one('Order', "\"Reference\" = '$candidate'")) {
$count++;
$candidate = $reference . "" . $count;
}
$this->Reference = $candidate;
}
/**
* Get the reference for this order, or fall back to order ID.
*/
public function getReference()
{
return $this->getField('Reference') ? $this->getField('Reference') : $this->ID;
}
/**
* Force creating an order reference
*/
public function onBeforeWrite()
{
parent::onBeforeWrite();
if (!$this->getField("Reference") && in_array($this->Status, self::$placed_status)) {
$this->generateReference();
}
// While the order is unfinished/cart, always store the current locale with the order.
// We do this everytime an order is saved, because the user might change locale (language-switch).
if ($this->Status == 'Cart') {
$this->Locale = ShopTools::get_current_locale();
}
}
/**
* delete attributes, statuslogs, and payments
*/
public function onBeforeDelete()
{
$this->Items()->removeAll();
$this->Modifiers()->removeAll();
$this->OrderStatusLogs()->removeAll();
$this->Payments()->removeAll();
parent::onBeforeDelete();
}
public function debug()
{
$val = "<div class='order'><h1>$this->class</h1>\n<ul>\n";
if ($this->record) {
foreach ($this->record as $fieldName => $fieldVal) {
$val .= "\t<li>$fieldName: " . Debug::text($fieldVal) . "</li>\n";
}
}
$val .= "</ul>\n";
$val .= "<div class='items'><h2>Items</h2>";
if ($items = $this->Items()) {
$val .= $this->Items()->debug();
}
$val .= "</div><div class='modifiers'><h2>Modifiers</h2>";
if ($modifiers = $this->Modifiers()) {
$val .= $modifiers->debug();
}
$val .= "</div></div>";
return $val;
}
}