/
Product.php
577 lines (514 loc) · 17.2 KB
/
Product.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
<?php
/**
* This is a standard Product page-type with fields like
* Price, Weight, Model and basic management of
* groups.
*
* It also has an associated Product_OrderItem class,
* an extension of OrderItem, which is the mechanism
* that links this page type class to the rest of the
* eCommerce platform. This means you can add an instance
* of this page type to the shopping cart.
*
* @package shop
*/
class Product extends Page implements Buyable
{
private static $db = array(
'InternalItemID' => 'Varchar(30)', //ie SKU, ProductID etc (internal / existing recognition of product)
'Model' => 'Varchar(30)',
'CostPrice' => 'Currency', // Wholesale cost of the product to the merchant
'BasePrice' => 'Currency', // Base retail price the item is marked at.
//physical properties
'Weight' => 'Float',
'Height' => 'Float',
'Width' => 'Float',
'Depth' => 'Float',
'Featured' => 'Boolean',
'AllowPurchase' => 'Boolean',
'Popularity' => 'Float' //storage for ClaculateProductPopularity task
);
private static $has_one = array(
'Image' => 'Image',
);
private static $many_many = array(
'ProductCategories' => 'ProductCategory',
);
private static $defaults = array(
'AllowPurchase' => true,
'ShowInMenus' => false,
);
private static $casting = array(
'Price' => 'Currency',
);
private static $summary_fields = array(
'InternalItemID',
'Title',
'BasePrice.NiceOrEmpty',
'canPurchase',
);
private static $searchable_fields = array(
'InternalItemID',
'Title' => array("title" => 'Title'),
'Featured',
);
private static $field_labels = array(
'InternalItemID' => 'SKU',
'Title' => 'Title',
'BasePrice' => 'Price',
'BasePrice.NiceOrEmpty' => 'Price',
'canPurchase' => 'Purchasable',
);
private static $singular_name = "Product";
private static $plural_name = "Products";
private static $icon = 'silvershop/images/icons/package';
private static $default_parent = 'ProductCategory';
private static $default_sort = '"Title" ASC';
private static $global_allow_purchase = true;
private static $allow_zero_price = false;
private static $order_item = "Product_OrderItem";
private static $min_opengraph_img_size = 0;
// Physical Measurement
private static $weight_unit = "kg";
private static $length_unit = "cm";
private static $indexes = array(
'Featured' => true,
'AllowPurchase' => true,
'InternalItemID' => true,
);
/**
* Add product fields to CMS
*
* @return FieldList updated field list
*/
public function getCMSFields()
{
self::disableCMSFieldsExtensions();
$fields = parent::getCMSFields();
$fields->fieldByName('Root.Main.Title')
->setTitle(_t('Product.PageTitle', 'Product Title'));
//general fields
$fields->addFieldsToTab(
'Root.Main',
array(
TextField::create('InternalItemID', _t('Product.InternalItemID', 'Product Code/SKU'), '', 30),
DropdownField::create('ParentID', _t("Product.Category", "Category"), $this->getCategoryOptions())
->setDescription(_t("Product.CategoryDescription", "This is the parent page or default category.")),
ListBoxField::create(
'ProductCategories',
_t("Product.AdditionalCategories", "Additional Categories"),
$this->getCategoryOptionsNoParent()
)->setMultiple(true),
TextField::create('Model', _t('Product.Model', 'Model'), '', 30),
CheckboxField::create('Featured', _t('Product.Featured', 'Featured Product')),
CheckboxField::create('AllowPurchase', _t('Product.AllowPurchase', 'Allow product to be purchased'), 1),
),
'Content'
);
//pricing
$fields->addFieldsToTab(
'Root.Pricing',
array(
TextField::create('BasePrice', _t('Product.db_BasePrice', 'Price'))
->setDescription(_t('Product.PriceDesc', "Base price to sell this product at."))
->setMaxLength(12),
TextField::create('CostPrice', _t('Product.db_CostPrice', 'Cost Price'))
->setDescription(_t('Product.CostPriceDescription', 'Wholesale price before markup.'))
->setMaxLength(12),
)
);
//physical measurements
$fieldSubstitutes = array(
'LengthUnit' => self::config()->length_unit
);
$fields->addFieldsToTab(
'Root.Shipping',
array(
TextField::create(
'Weight',
_t('Product.WeightWithUnit', 'Weight ({WeightUnit})', '', array(
'WeightUnit' => self::config()->weight_unit
)),
'',
12
),
TextField::create(
'Height',
_t('Product.HeightWithUnit', 'Height ({LengthUnit})', '', $fieldSubstitutes),
'',
12
),
TextField::create(
'Width',
_t('Product.WidthWithUnit', 'Width ({LengthUnit})', '', $fieldSubstitutes),
'',
12
),
TextField::create(
'Depth',
_t('Product.DepthWithUnit', 'Depth ({LengthUnit})', '', $fieldSubstitutes),
'',
12
),
)
);
if (!$fields->dataFieldByName('Image')) {
$fields->addFieldToTab(
'Root.Images',
UploadField::create('Image', _t('Product.Image', 'Product Image'))
);
}
self::enableCMSFieldsExtensions();
$this->extend('updateCMSFields', $fields);
return $fields;
}
/**
* Fix grid field heading displaying "page name"
*/
public function fieldLabels($includerelations = true)
{
$labels = parent::fieldLabels($includerelations);
$labels['Title'] = "Title";
return $labels;
}
/**
* Helper function for generating list of categories to select from.
*
* @return array categories
*/
private function getCategoryOptions()
{
$categories = ProductCategory::get()->map('ID', 'NestedTitle')->toArray();
$categories = array(
0 => _t("SiteTree.PARENTTYPE_ROOT", "Top-level page"),
) + $categories;
if ($this->ParentID && !($this->Parent() instanceof ProductCategory)) {
$categories = array(
$this->ParentID => $this->Parent()->Title . " (" . $this->Parent()->i18n_singular_name() . ")",
) + $categories;
}
return $categories;
}
/**
* Helper function for generating a list of additional categories excluding the main parent.
*
* @return array categories
*/
private function getCategoryOptionsNoParent()
{
$ancestors = $this->getAncestors()->map('ID', 'ID');
$categories = ProductCategory::get();
if (!empty($ancestors)) {
$categories->filter("ID:not", $ancestors);
}
return $categories->map('ID', 'NestedTitle')->toArray();
}
/**
* Get ids of all categories that this product appears in.
*
* @return array ids list
*/
public function getCategoryIDs()
{
$ids = array();
//ancestors
foreach ($this->getAncestors() as $ancestor) {
$ids[$ancestor->ID] = $ancestor->ID;
}
//additional categories
$ids += $this->ProductCategories()->getIDList();
return $ids;
}
/**
* Get all categories that this product appears in.
*
* @return DataList category data list
*/
public function getCategories()
{
return ProductCategory::get()->byIDs($this->getCategoryIDs());
}
/**
* Conditions for whether a product can be purchased:
* - global allow purchase is enabled
* - product AllowPurchase field is true
* - if variations, then one of them needs to be purchasable
* - if not variations, selling price must be above 0
*
* Other conditions may be added by decorating with the canPurcahse function
*
* @param Member $member
* @param int $quantity
*
* @throws ShopBuyableException
*
* @return boolean
*/
public function canPurchase($member = null, $quantity = 1)
{
$global = self::config()->global_allow_purchase;
if (!$global || !$this->AllowPurchase) {
return false;
}
$allowpurchase = false;
$extension = self::has_extension("ProductVariationsExtension");
if ($extension && ProductVariation::get()->filter("ProductID", $this->ID)->first()
) {
foreach ($this->Variations() as $variation) {
// TODO: 2.0, Remove exception handling
try {
if ($variation->canPurchase($member, $quantity)) {
$allowpurchase = true;
break;
}
} catch (ShopBuyableException $e) {
}
}
// if not allowed to buy after any variations then raise the last
// exception again
if (!$allowpurchase && isset($e)) {
Deprecation::notice('2.0', 'Throwing exceptions from within canPurchase will be removed');
throw $e;
return false;
}
} else {
if ($this->sellingPrice() > 0 || self::config()->allow_zero_price) {
$allowpurchase = true;
}
}
// Standard mechanism for accepting permission changes from decorators
$permissions = $this->extend('canPurchase', $member, $quantity);
$permissions[] = $allowpurchase;
return min($permissions);
}
/**
* Returns if the product is already in the shopping cart.
*
* @return boolean
*/
public function IsInCart()
{
$item = $this->Item();
return $item && $item->exists() && $item->Quantity > 0;
}
/**
* Returns the order item which contains the product
*
* @return OrderItem
*/
public function Item()
{
$filter = array();
$this->extend('updateItemFilter', $filter);
$item = ShoppingCart::singleton()->get($this, $filter);
if (!$item) {
//return dummy item so that we can still make use of Item
$item = $this->createItem();
}
$this->extend('updateDummyItem', $item);
return $item;
}
/**
* @see Buyable::createItem()
*/
public function createItem($quantity = 1, $filter = null)
{
$orderitem = self::config()->order_item;
$item = new $orderitem();
$item->ProductID = $this->ID;
if ($filter) {
//TODO: make this a bit safer, perhaps intersect with allowed fields
$item->update($filter);
}
$item->Quantity = $quantity;
return $item;
}
/**
* The raw retail price the visitor will get when they
* add to cart. Can include discounts or markups on the base price.
*/
public function sellingPrice()
{
$price = $this->BasePrice;
//TODO: this is not ideal, because prices manipulations will not happen in a known order
$this->extend("updateSellingPrice", $price);
//prevent negative values
$price = $price < 0 ? 0 : $price;
// NOTE: Ideally, this would be dependent on the locale but as of
// now the Silverstripe Currency field type has 2 hardcoded all over
// the place. In the mean time there is an issue where the displayed
// unit price can not exactly equal the multiplied price on an order
// (i.e. if the calculated price is 3.145 it will display as 3.15.
// so if I put 10 of them in my cart I will expect the price to be
// 31.50 not 31.45).
return round($price, Order::config()->rounding_precision);
}
/**
* This value is cased to Currency in temlates.
*/
public function getPrice()
{
return $this->sellingPrice();
}
public function setPrice($price)
{
$price = $price < 0 ? 0 : $price;
$this->setField("BasePrice", $price);
}
/**
* Allow orphaned products to be viewed.
*/
public function isOrphaned()
{
return false;
}
public function Link()
{
$link = parent::Link();
$this->extend('updateLink', $link);
return $link;
}
/**
* If the product does not have an image, and a default image
* is defined in SiteConfig, return that instead.
*
* @return Image
*/
public function Image()
{
$image = $this->getComponent('Image');
if ($image && $image->exists() && file_exists($image->getFullPath())) {
return $image;
}
$image = SiteConfig::current_site_config()->DefaultProductImage();
if ($image && $image->exists() && file_exists($image->getFullPath())) {
return $image;
}
return $this->model->Image->newObject();
}
/**
* Integration with opengraph module
*
* @see https://github.com/tractorcow/silverstripe-opengraph
* @return string opengraph type
*/
public function getOGType()
{
return 'product';
}
/**
* Integration with the opengraph module
*
* @return string url of product image
*/
public function getOGImage()
{
if ($image = $this->Image()) {
$min = self::config()->min_opengraph_img_size;
$image = $min && $image->getWidth() < $min ? $image->setWidth($min) : $image;
return Director::absoluteURL($image->URL);
}
}
/**
* Link to add this product to cart.
*
* @return string link
*/
public function addLink()
{
return ShoppingCart_Controller::add_item_link($this);
}
/**
* Link to remove one of this product from cart.
*
* @return string link
*/
public function removeLink()
{
return ShoppingCart_Controller::remove_item_link($this);
}
/**
* Link to remove all of this product from cart.
*
* @return string link
*/
public function removeallLink()
{
return ShoppingCart_Controller::remove_all_item_link($this);
}
}
class Product_Controller extends Page_Controller
{
private static $allowed_actions = array(
'Form',
'AddProductForm',
);
public $formclass = "AddProductForm"; //allow overriding the type of form used
public function Form()
{
$formclass = $this->formclass;
$form = new $formclass($this, "Form");
$this->extend('updateForm', $form);
return $form;
}
}
class Product_OrderItem extends OrderItem
{
private static $db = array(
'ProductVersion' => 'Int',
);
private static $has_one = array(
'Product' => 'Product',
);
/**
* the has_one join field to identify the buyable
*/
private static $buyable_relationship = "Product";
/**
* Get related product
* - live version if in cart, or
* - historical version if order is placed
*
* @param boolean $forcecurrent - force getting latest version of the product.
*
* @return Product
*/
public function Product($forcecurrent = false)
{
//TODO: this might need some unit testing to make sure it compliles with comment description
//ie use live if in cart (however I see no logic for checking cart status)
if ($this->ProductID && $this->ProductVersion && !$forcecurrent) {
return Versioned::get_version('Product', $this->ProductID, $this->ProductVersion);
} elseif (
$this->ProductID
&& $product = Versioned::get_one_by_stage(
"Product",
"Live",
"\"Product\".\"ID\" = " . $this->ProductID
)
) {
return $product;
}
return false;
}
public function onPlacement()
{
parent::onPlacement();
if ($product = $this->Product(true)) {
$this->ProductVersion = $product->Version;
}
}
public function TableTitle()
{
$product = $this->Product();
$tabletitle = ($product) ? $product->Title : $this->i18n_singular_name();
$this->extend('updateTableTitle', $tabletitle);
return $tabletitle;
}
public function Link()
{
if ($product = $this->Product()) {
return $product->Link();
}
}
}