Completed
Push — master ( f5c0e7...735609 )
by Nicolaas
03:21
created

code/model/config/EcommerceDBConfig.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/**
4
 * Database Settings for E-commerce
5
 * Similar to SiteConfig but then for E-commerce
6
 * To access a singleton here, use: EcommerceDBConfig::current_ecommerce_db_config().
7
 *
8
 * @authors: Nicolaas [at] Sunny Side Up .co.nz
9
 * @package: ecommerce
10
 * @sub-package: tasks
11
 * @inspiration: Silverstripe Ltd, Jeremy
12
 **/
13
class EcommerceDBConfig extends DataObject implements EditableEcommerceObject
14
{
15
    /**
16
     * Standard SS Variable.
17
     *
18
     * @var array
19
     */
20
    private static $db = array(
21
        'Title' => 'Varchar(30)',
22
        'UseThisOne' => 'Boolean',
23
        'ShopClosed' => 'Boolean',
24
        'ShopPricesAreTaxExclusive' => 'Boolean',
25
        'InvoiceTitle' => 'Varchar(200)',
26
        'InvoiceMessage' => 'HTMLText',
27
        'PackingSlipTitle' => 'Varchar(200)',
28
        'PackingSlipNote' => 'HTMLText',
29
        'ShopPhysicalAddress' => 'HTMLText',
30
        'ReceiptEmail' => 'Varchar(255)',
31
        'PostalCodeURL' => 'Varchar(255)',
32
        'PostalCodeLabel' => 'Varchar(255)',
33
        'NumberOfProductsPerPage' => 'Int',
34
        'ProductsAlsoInOtherGroups' => 'Boolean',
35
        'OnlyShowProductsThatCanBePurchased' => 'Boolean',
36
        'NotForSaleMessage' => 'HTMLText',
37
        'ProductsHaveWeight' => 'Boolean',
38
        'ProductsHaveModelNames' => 'Boolean',
39
        'ProductsHaveQuantifiers' => 'Boolean',
40
        //"ProductsHaveVariations" => "Boolean",
41
        'CurrenciesExplanation' => 'HTMLText',
42
        'AllowFreeProductPurchase' => 'Boolean',
43
    );
44
45
    /**
46
     * Standard SS Variable.
47
     *
48
     * @var array
49
     */
50
    private static $has_one = array(
51
        'EmailLogo' => 'Image',
52
        'DefaultProductImage' => 'Product_Image',
53
    );
54
55
    /**
56
     * Standard SS Variable.
57
     *
58
     * @var array
59
     */
60
    private static $indexes = array(
61
        'UseThisOne' => true,
62
        'ShopClosed' => true,
63
        'ShopPricesAreTaxExclusive' => true,
64
        'NumberOfProductsPerPage' => true,
65
        'OnlyShowProductsThatCanBePurchased' => true,
66
    );
67
68
    /**
69
     * Standard SS Variable.
70
     *
71
     * @var array
72
     */
73
    private static $casting = array(
74
        'UseThisOneNice' => 'Varchar',
75
    ); //adds computed fields that can also have a type (e.g.
76
77
    /**
78
     * Standard SS Variable.
79
     *
80
     * @var array
81
     */
82
    private static $searchable_fields = array(
83
        'Title' => 'PartialMatchFilter',
84
    );
85
86
    /**
87
     * Standard SS Variable.
88
     *
89
     * @var array
90
     */
91
    private static $field_labels = array();
92
93
    /**
94
     * Standard SS Variable.
95
     *
96
     * @var array
97
     */
98
    private static $summary_fields = array(
99
        'Title' => 'Title',
100
        'UseThisOneNice' => 'Use this configuration set',
101
    ); //note no => for relational fields
102
103
    /**
104
     * Standard SS Method.
105
     *
106
     * @param Member $member
107
     *
108
     * @var bool
109
     */
110
    public function canCreate($member = null)
111
    {
112
        if (! $member) {
113
            $member = Member::currentUser();
114
        }
115
        $extended = $this->extendedCan(__FUNCTION__, $member);
116
        if ($extended !== null) {
117
            return $extended;
118
        }
119
        if(EcommerceDBConfig::get()->count() > 0) {
120
            return false;
121
        }
122
        return $this->canEdit($member);
123
    }
124
125
    /**
126
     * Standard SS Method.
127
     *
128
     * @param Member $member
129
     *
130
     * @var bool
131
     */
132
    public function canView($member = null)
133
    {
134
        if (! $member) {
135
            $member = Member::currentUser();
136
        }
137
        $extended = $this->extendedCan(__FUNCTION__, $member);
138
        if ($extended !== null) {
139
            return $extended;
140
        }
141
142
        return $this->canEdit($member);
143
    }
144
145
    /**
146
     * Standard SS Method.
147
     *
148
     * @param Member $member
149
     *
150
     * @var bool
151
     */
152
    public function canEdit($member = null)
153
    {
154
        if (! $member) {
155
            $member = Member::currentUser();
156
        }
157
        $extended = $this->extendedCan(__FUNCTION__, $member);
158
        if ($extended !== null) {
159
            return $extended;
160
        }
161
        if (Permission::checkMember($member, Config::inst()->get('EcommerceRole', 'admin_permission_code'))) {
162
            return true;
163
        }
164
165
        return parent::canEdit($member);
166
    }
167
168
    /**
169
     * Standard SS Method.
170
     *
171
     * @param Member $member
172
     *
173
     * @var bool
174
     */
175
    public function canDelete($member = null)
176
    {
177
        if ($this->UseThisOne) {
178
            return false;
179
        } else {
180
            if (! $member) {
181
                $member = Member::currentUser();
182
            }
183
            $extended = $this->extendedCan(__FUNCTION__, $member);
184
            if ($extended !== null) {
185
                return $extended;
186
            }
187
            if (Permission::checkMember($member, Config::inst()->get('EcommerceRole', 'admin_permission_code'))) {
188
                return true;
189
            }
190
191
            return parent::canEdit($member);
192
        }
193
    }
194
195
    /**
196
     * Standard SS variable.
197
     *
198
     * @var string
199
     */
200
    private static $default_sort = '"UseThisOne" DESC, "Created" ASC';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
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...
201
202
    /**
203
     * Standard SS variable.
204
     *
205
     * @var array
206
     */
207
    private static $defaults = array(
208
        'Title' => 'Ecommerce Site Config',
209
        'UseThisOne' => true,
210
        'ShopClosed' => false,
211
        'ShopPricesAreTaxExclusive' => false,
212
        'InvoiceTitle' => 'Invoice',
213
        'InvoiceMessage' => '<p>Thank you for your order</p>',
214
        'PackingSlipTitle' => 'Package Contents',
215
        'PackingSlipNote' => 'Please make sure that all items are contained in this package.',
216
        'ShopPhysicalAddress' => '<p>Enter your shop address here.</p>',
217
        //"ReceiptEmail" => "Varchar(255)", - see populate defaults
218
        'PostalCodeURL' => '',
219
        'PostalCodeLabel' => '',
220
        'NumberOfProductsPerPage' => 12,
221
        'ProductsAlsoInOtherGroups' => false,
222
        'OnlyShowProductsThatCanBePurchased' => false,
223
        'NotForSaleMessage' => '<p>Not for sale, please contact us for more information.</p>',
224
        'ProductsHaveWeight' => false,
225
        'ProductsHaveModelNames' => false,
226
        'ProductsHaveQuantifiers' => false,
227
        //"ProductsHaveVariations" => false,
228
        'CurrenciesExplanation' => '<p>Apart from our main currency, you can view prices in a number of other currencies. The exchange rate is indicative only.</p>',
229
        'AllowFreeProductPurchase' => true,
230
    );
231
232
    /**
233
     * Standard SS Method.
234
     *
235
     * @var array
236
     */
237
    public function populateDefaults()
238
    {
239
        parent::populateDefaults();
240
        $this->ReceiptEmail = Email::config()->admin_email;
241
    }
242
243
    /**
244
     * Standard SS variable.
245
     *
246
     * @var string
247
     */
248
    private static $singular_name = 'Main E-commerce Configuration';
249
    public function i18n_singular_name()
250
    {
251
        return _t('EcommerceDBConfig.ECOMMERCECONFIGURATION', 'Main E-commerce Configuration');
252
    }
253
254
    /**
255
     * Standard SS variable.
256
     *
257
     * @var string
258
     */
259
    private static $plural_name = 'Main E-commerce Configurations';
260
    public function i18n_plural_name()
261
    {
262
        return _t('EcommerceDBConfig.ECOMMERCECONFIGURATIONS', 'Main E-commerce Configurations');
263
    }
264
265
    /**
266
     * Standard SS variable.
267
     *
268
     * @var string
269
     */
270
    private static $description = 'A set of configurations for the shop. Each shop needs to have one or more of these settings.';
271
272
    /**
273
     * static holder for its own (or other EcommerceDBConfig) class.
274
     *
275
     * @var string | NULL
276
     */
277
    private static $_my_current_one = null;
278
    public static function reset_my_current_one()
279
    {
280
        self::$_my_current_one = null;
281
    }
282
283
    /**
284
     * implements singleton pattern.
285
     * Gets the current USE THIS ONE e-commerce option.
286
     *
287
     * @return EcommerceDBConfig | Object
288
     */
289
    public static function current_ecommerce_db_config()
290
    {
291
        if (!self::$_my_current_one) {
292
            $className = EcommerceConfig::get('EcommerceDBConfig', 'ecommerce_db_config_class_name');
293
            if (!class_exists('EcommerceDBConfig')) {
294
                $class = 'EcommerceDBConfig';
295
            }
296
            self::$_my_current_one = DataObject::get_one(
297
                $className,
298
                array('UseThisOne' => 1),
299
                $cacheDataObjectGetOne = false
300
            );
301
            if ( ! self::$_my_current_one) {
302
                self::$_my_current_one = $className::create();
303
            }
304
        }
305
306
        return self::$_my_current_one;
307
    }
308
309
    /**
310
     * standard SS method for decorators.
311
     *
312
     * @param bool $includerelations
313
     *
314
     * @return array
315
     */
316
    public function fieldLabels($includerelations = true)
317
    {
318
        $defaultLabels = parent::fieldLabels();
319
        $newLabels = $this->customFieldLabels();
320
        $labels = array_merge($defaultLabels, $newLabels);
321
        $extendedLabels = $this->extend('updateFieldLabels', $labels);
322
        if ($extendedLabels !== null && is_array($extendedLabels) && count($extendedLabels)) {
323
            foreach ($extendedLabels as $extendedLabelsUpdate) {
324
                $labels = array_merge($labels, $extendedLabelsUpdate);
325
            }
326
        }
327
328
        return $labels;
329
    }
330
331
    /**
332
     * definition of field lables
333
     * TODO: is this a common SS method?
334
     *
335
     * @return array
336
     */
337
    public function customFieldLabels()
338
    {
339
        $newLabels = array(
340
            'Title' => _t('EcommerceDBConfig.TITLE', 'Name of settings'),
341
            'UseThisOne' => _t('EcommerceDBConfig.USETHISONE', 'Use these configuration settings'),
342
            'ShopClosed' => _t('EcommerceDBConfig.SHOPCLOSED', 'Shop Closed'),
343
            'ShopPricesAreTaxExclusive' => _t('EcommerceDBConfig.SHOPPRICESARETAXEXCLUSIVE', 'Shop prices are tax exclusive'),
344
            'InvoiceTitle' => _t('EcommerceDBConfig.INVOICETITLE', 'Default Email title'),
345
            'InvoiceMessage' => _t('EcommerceDBConfig.INVOICEMESSAGE', 'Default Email Message'),
346
            'PackingSlipTitle' => _t('EcommerceDBConfig.PACKING_SLIP_TITLE', 'Packing slip title'),
347
            'PackingSlipNote' => _t('EcommerceDBConfig.PACKING_SLIP_NOTE', 'Packing slip notes'),
348
            'ShopPhysicalAddress' => _t('EcommerceDBConfig.SHOPPHYSICALADDRESS', 'Shop physical address'),
349
            'ReceiptEmail' => _t('EcommerceDBConfig.RECEIPTEMAIL', 'Shop Email Address'),
350
            'PostalCodeURL' => _t('EcommerceDBConfig.POSTALCODEURL', 'Postal code link'),
351
            'PostalCodeLabel' => _t('EcommerceDBConfig.POSTALCODELABEL', 'Postal code link label'),
352
            'NumberOfProductsPerPage' => _t('EcommerceDBConfig.NUMBEROFPRODUCTSPERPAGE', 'Number of products per page'),
353
            'OnlyShowProductsThatCanBePurchased' => _t('EcommerceDBConfig.ONLYSHOWPRODUCTSTHATCANBEPURCHASED', 'Only show products that can be purchased.'),
354
            'NotForSaleMessage' => _t('EcommerceDBConfig.NOTFORSALEMESSAGE', 'Not for sale message'),
355
            'ProductsHaveWeight' => _t('EcommerceDBConfig.PRODUCTSHAVEWEIGHT', 'Products have weight (e.g. 1.2kg)'),
356
            'ProductsHaveModelNames' => _t('EcommerceDBConfig.PRODUCTSHAVEMODELNAMES', 'Products have model names / numbers / codes'),
357
            'ProductsHaveQuantifiers' => _t('EcommerceDBConfig.PRODUCTSHAVEQUANTIFIERS', 'Products have quantifiers (e.g. per year, each, per dozen, etc...)'),
358
            'ProductsAlsoInOtherGroups' => _t('EcommerceDBConfig.PRODUCTSALSOINOTHERGROUPS', 'Allow products to show in multiple product groups'),
359
            //"ProductsHaveVariations" => _t("EcommerceDBConfig.PRODUCTSHAVEVARIATIONS", "Products have variations (e.g. size, colour, etc...)."),
360
            'CurrenciesExplanation' => _t('EcommerceDBConfig.CURRENCIESEXPLANATION', 'Currency explanation'),
361
            'EmailLogo' => _t('EcommerceDBConfig.EMAILLOGO', 'Email Logo'),
362
            'DefaultProductImage' => _t('EcommerceDBConfig.DEFAULTPRODUCTIMAGE', 'Default Product Image'),
363
            'DefaultThumbnailImageSize' => _t('EcommerceDBConfig.DEFAULTTHUMBNAILIMAGESIZE', 'Product Thumbnail Optimised Size'),
364
            'DefaultSmallImageSize' => _t('EcommerceDBConfig.DEFAULTSMALLIMAGESIZE', 'Product Small Image Optimised Size'),
365
            'DefaultContentImageSize' => _t('EcommerceDBConfig.DEFAULTCONTENTIMAGESIZE', 'Product Content Image Optimised Size'),
366
            'DefaultLargeImageSize' => _t('EcommerceDBConfig.DEFAULTLARGEIMAGESIZE', 'Product Large Image Optimised Size'),
367
            'AllowFreeProductPurchase' => _t('EcommerceDBConfig.ALLOWFREEPRODUCTPURCHASE', 'Allow free products to be purchased? '),
368
        );
369
370
        return $newLabels;
371
    }
372
373
    /**
374
     * definition of field lables
375
     * TODO: is this a common SS method?
376
     *
377
     * @return array
378
     */
379
    public function customDescriptionsForFields()
380
    {
381
        $newLabels = array(
382
            'Title' => _t('EcommerceDBConfig.TITLE_DESCRIPTION', 'For internal use only.'),
383
            'UseThisOne' => _t('EcommerceDBConfig.USETHISONE_DESCRIPTION', 'You can create several setting records so that you can switch between configurations.'),
384
            'ShopPricesAreTaxExclusive' => _t('EcommerceDBConfig.SHOPPRICESARETAXEXCLUSIVE_DESCRIPTION', 'If this option is NOT ticked, it is assumed that prices are tax inclusive.'),
385
            'ReceiptEmail' => _t('EcommerceDBConfig.RECEIPTEMAIL_DESCRIPTION_DESCRIPTION', 'e.g. [email protected], you can also use something like: "Our Shop Name Goes Here" &lt;[email protected]&gt;'),
386
            'AllowFreeProductPurchase' => _t('EcommerceDBConfig.ALLOWFREEPRODUCTPURCHASE_DESCRIPTION', 'This is basically a protection to disallow sales of products that do not have a price entered yet. '),
387
            'CurrenciesExplanation' => _t('EcommerceDBConfig.CURRENCIESEXPLANATION_DESCRIPTION', 'Explain how the user can switch between currencies and how the exchange rates are worked out.'),
388
            'PackingSlipTitle' => _t('EcommerceDBConfig.PACKINGSLIPTITLE_DESCRIPTION', 'e.g. Package Contents'),
389
            'PackingSlipNote' => _t('EcommerceDBConfig.PACKING_SLIP_NOTE_DESCRIPTION', 'e.g. a disclaimer'),
390
            'InvoiceTitle' => _t('EcommerceDBConfig.INVOICETITLE_DESCRIPTION', 'e.g. Tax Invoice or Update for your recent order on www.yoursite.co.nz'),
391
            'InvoiceMessage' => _t('EcommerceDBConfig.INVOICEMESSAGE_DESCRIPTION', 'e.g. Thank you for your order.'),
392
        );
393
394
        return $newLabels;
395
    }
396
397
    /**
398
     * standard SS method.
399
     *
400
     * @return FieldList
401
     */
402
    public function getCMSFields()
403
    {
404
        $fields = parent::getCMSFields();
405
406
        $self = $this;
407
        $self->beforeUpdateCMSFields(
408
            function ($fields) use ($self) {
409
                foreach ($self->customFieldLabels() as $name => $label) {
410
                    $fields->removeByName($name);
411
                }
412
                //new section
413
                $fieldDescriptions = $self->customDescriptionsForFields();
414
                $fieldLabels = $self->fieldLabels();
415
                $productImage = new Product_Image();
416
                $versionInfo = EcommerceConfigDefinitions::create();
417
                $fields->addFieldToTab('Root.Main', new TextField('Title', $fieldLabels['Title']));
418
                $fields->addFieldsToTab('Root', array(
419
                    Tab::create(
420
                        'Pricing',
421
                        _t('EcommerceDBConfig.PRICING', 'Pricing'),
422
                        new CheckboxField('ShopPricesAreTaxExclusive', $fieldLabels['ShopPricesAreTaxExclusive']),
423
                        new CheckboxField('AllowFreeProductPurchase', $fieldLabels['AllowFreeProductPurchase']),
424
                        $htmlEditorField1 = new HTMLEditorField('CurrenciesExplanation', $fieldLabels['CurrenciesExplanation'])
425
                    ),
426
                    Tab::create(
427
                        'Products',
428
                        _t('EcommerceDBConfig.PRODUCTS', 'Products'),
429
                        new NumericField('NumberOfProductsPerPage', $fieldLabels['NumberOfProductsPerPage']),
430
                        new CheckboxField('ProductsAlsoInOtherGroups', $fieldLabels['ProductsAlsoInOtherGroups']),
431
                        new CheckboxField('OnlyShowProductsThatCanBePurchased', $fieldLabels['OnlyShowProductsThatCanBePurchased']),
432
                        $htmlEditorField2 = new HTMLEditorField('NotForSaleMessage', $fieldLabels['NotForSaleMessage']),
433
                        new CheckboxField('ProductsHaveWeight', $fieldLabels['ProductsHaveWeight']),
434
                        new CheckboxField('ProductsHaveModelNames', $fieldLabels['ProductsHaveModelNames']),
435
                        new CheckboxField('ProductsHaveQuantifiers', $fieldLabels['ProductsHaveQuantifiers'])
436
                        //new CheckboxField("ProductsHaveVariations", $fieldLabels["ProductsHaveVariations"])
437
                    ),
438
                    Tab::create(
439
                        'ProductImages',
440
                        _t('EcommerceDBConfig.PRODUCT_IMAGES', 'Product Images'),
441
                        //new Product_ProductImageUploadField("DefaultProductImage", $fieldLabels["DefaultProductImage"], null, null, null, "default-product-image"),
442
                        new ReadonlyField('DefaultThumbnailImageSize', $fieldLabels['DefaultThumbnailImageSize'], $productImage->ThumbWidth().'px x '.$productImage->ThumbHeight().'px '),
443
                        new ReadonlyField('DefaultSmallImageSize', $fieldLabels['DefaultSmallImageSize'], $productImage->SmallWidth().'px x '.$productImage->SmallHeight().'px '),
444
                        new ReadonlyField('DefaultContentImageSize', $fieldLabels['DefaultContentImageSize'], $productImage->ContentWidth().'px wide'),
445
                        new ReadonlyField('DefaultLargeImageSize', $fieldLabels['DefaultLargeImageSize'], $productImage->LargeWidth().'px wide')
446
                    ),
447
                    Tab::create(
448
                        'AddressAndDelivery',
449
                        _t('EcommerceDBConfig.ADDRESS_AND_DELIVERY', 'Address and Delivery'),
450
                        new TextField('PostalCodeURL', $fieldLabels['PostalCodeURL']),
451
                        new TextField('PostalCodeLabel', $fieldLabels['PostalCodeLabel']),
452
                        $htmlEditorField3 = new HTMLEditorField('ShopPhysicalAddress', $fieldLabels['ShopPhysicalAddress']),
453
                        new TextField('PackingSlipTitle', $fieldLabels['PackingSlipTitle']),
454
                        $htmlEditorField4 = new HTMLEditorField('PackingSlipNote', $fieldLabels['PackingSlipNote'])
455
                    ),
456
                    Tab::create(
457
                        'Emails',
458
                        _t('EcommerceDBConfig.EMAILS', 'Emails'),
459
                        new TextField('ReceiptEmail', $fieldLabels['ReceiptEmail']),
460
                        new UploadField('EmailLogo', $fieldLabels['EmailLogo'],  null, null, null, 'logos'),
461
                        new TextField('InvoiceTitle', $fieldLabels['InvoiceTitle']),
462
                        $htmlEditorField5 = new HTMLEditorField('InvoiceMessage', $fieldLabels['InvoiceMessage'])
463
                    ),
464
                    Tab::create(
465
                        'Process',
466
                        _t('EcommerceDBConfig.PROCESS', 'Process'),
467
                        $self->getOrderStepsField()
468
                    ),
469
                    Tab::create(
470
                        'Advanced',
471
                        _t('EcommerceDBConfig.ADVANCED', 'Advanced'),
472
                        new LiteralField(
473
                            'ReviewHardcodedSettings',
474
                            '<p>
475
                                Your developer has pre-set some configurations for you.
476
                                You can
477
                                <a href="/dev/ecommerce/ecommercetaskcheckconfiguration" data-popup="true">review these settings</a>
478
                                but you will need to ask your developer to change them if they are not right.
479
                                The reason they can not be set is that changing them can break your application.
480
                            </p>'
481
                        )
482
                    )
483
                ));
484
                $mappingArray = Config::inst()->get('BillingAddress', 'fields_to_google_geocode_conversion');
485
                if (is_array($mappingArray) && count($mappingArray)) {
486
                    $mappingArray = Config::inst()->get('ShippingAddress', 'fields_to_google_geocode_conversion');
487
                    if (is_array($mappingArray) && count($mappingArray)) {
488
                        $fields->removeByName('PostalCodeURL');
489
                        $fields->removeByName('PostalCodeLabel');
490
                    }
491
                }
492
                $htmlEditorField1->setRows(3);
493
                $htmlEditorField2->setRows(3);
494
                $htmlEditorField3->setRows(3);
495
                $htmlEditorField4->setRows(3);
496
                $htmlEditorField5->setRows(3);
497
                $fields->addFieldsToTab(
498
                    'Root.Main',
499
                    array(
500
                        new CheckboxField('UseThisOne', $fieldLabels['UseThisOne']),
501
                        new CheckboxField('ShopClosed', $fieldLabels['ShopClosed']),
502
                    )
503
                );
504
                //set cols
505
                if ($f = $fields->dataFieldByName('CurrenciesExplanation')) {
506
                    $f->setRows(2);
507
                }
508
                if ($f = $fields->dataFieldByName('NotForSaleMessage')) {
509
                    $f->setRows(2);
510
                }
511
                if ($f = $fields->dataFieldByName('ShopPhysicalAddress')) {
512
                    $f->setRows(2);
513
                }
514
                foreach ($fields->dataFields() as $field) {
515
                    if (isset($fieldDescriptions[$field->getName()])) {
516
                        if ($field instanceof CheckboxField) {
517
                            $field->setDescription($fieldDescriptions[$field->Name]);
518
                        } else {
519
                            $field->setRightTitle($fieldDescriptions[$field->Name]);
520
                        }
521
                    }
522
                }
523
                Requirements::block('ecommerce/javascript/EcomPrintAndMail.js');
524
                if (strnatcmp(phpversion(), '5.5.1') >= 0) {
525
                    $fields->addFieldToTab('Root.ProductImages', new Product_ProductImageUploadField('DefaultProductImage', $fieldLabels['DefaultProductImage'], null, null, null, 'default-product-image'));
526
                }
527
            }
528
        );
529
530
        return parent::getCMSFields();
531
    }
532
533
    /**
534
     * link to edit the record.
535
     *
536
     * @param string | Null $action - e.g. edit
537
     *
538
     * @return string
539
     */
540
    public function CMSEditLink($action = null)
541
    {
542
        return '/admin/shop/EcommerceDBConfig/';
543
    }
544
545
    public function getOrderStepsField()
546
    {
547
        $gridFieldConfig = GridFieldConfig::create()->addComponents(
548
            new GridFieldToolbarHeader(),
549
            new GridFieldSortableHeader(),
550
            new GridFieldDataColumns(10),
551
            new GridFieldPaginator(10),
552
            new GridFieldEditButton(),
553
            new GridFieldDeleteAction(),
554
            new GridFieldDetailForm()
555
        );
556
557
        return new GridField('OrderSteps', _t('OrderStep.PLURALNAME', 'Order Steps'), OrderStep::get(), $gridFieldConfig);
558
    }
559
560
    /**
561
     * tells us if a Class Name is a buyable.
562
     *
563
     * @todo: consider using Ecomerce Configuration instead?
564
     * In EcomConfig we only list base classes.
565
     *
566
     * @param string $className - name of the class to be tested
567
     *
568
     * @return bool
569
     */
570
    public static function is_buyable($className)
571
    {
572
        $implementorsArray = class_implements($className);
573
        if (is_array($implementorsArray) && in_array('BuyableModel', $implementorsArray)) {
574
            return true;
575
        }
576
577
        return false;
578
    }
579
580
    /**
581
     * Returns the Current Member.
582
     */
583
    public function Customer()
584
    {
585
        return Member::currentUser();
586
    }
587
588
    /**
589
     * Returns the Current Member.
590
     */
591
    public function CustomerForOrder()
592
    {
593
        $order = ShoppingCart::current_order();
594
595
        return $order->Member();
596
    }
597
598
    /**
599
     * Return the currency being used on the site e.g. "NZD" or "USD".
600
     *
601
     * @return string
602
     */
603
    public function Currency()
604
    {
605
        return EcommerceConfig::get('EcommerceCurrency', 'default_currency');
606
    }
607
608
    /**
609
     * return null if there is less than two currencies in use
610
     * on the site.
611
     *
612
     * @return DataList | Null
613
     */
614
    public function Currencies()
615
    {
616
        $list = EcommerceCurrency::get_list();
617
        if ($list && $list->count() > 1) {
618
            return $list;
619
        }
620
    }
621
622
    /**
623
     * @return string (URLSegment)
624
     **/
625
    public function AccountPageLink()
626
    {
627
        return AccountPage::find_link();
628
    }
629
630
    /**
631
     * @return string (URLSegment)
632
     **/
633
    public function CheckoutLink()
634
    {
635
        return CheckoutPage::find_link();
636
    }
637
638
    /**
639
     *@return string (URLSegment)
640
     **/
641
    public function CartPageLink()
642
    {
643
        return CartPage::find_link();
644
    }
645
646
    /**
647
     *@return string (URLSegment)
648
     **/
649
    public function OrderConfirmationPageLink()
650
    {
651
        return OrderConfirmationPage::find_link();
652
    }
653
654
    /**
655
     * Returns a link to a default image.
656
     * If a default image is set in the site config then this link is returned
657
     * Otherwise, a standard link is returned.
658
     *
659
     * @return string
660
     */
661
    public function DefaultImageLink()
662
    {
663
        if ($this->DefaultProductImageID) {
664
            $defaultImage = $this->DefaultProductImage();
665
            if ($defaultImage && $defaultImage->exists()) {
666
                return $defaultImage->Link();
667
            }
668
        }
669
670
        return 'ecommerce/images/productPlaceHolderThumbnail.gif';
671
    }
672
673
    /**
674
     * Returns the default image or a dummy one if it does not exists.
675
     *
676
     * @return string
677
     */
678
    public function DefaultImage()
679
    {
680
        if ($this->DefaultProductImageID) {
681
            if ($defaultImage = $this->DefaultProductImage()) {
682
                if ($defaultImage->exists()) {
683
                    return $defaultImage;
684
                }
685
            }
686
        }
687
        $obj = Product_Image::create();
688
        $obj->Link = $this->DefaultImageLink();
689
        $obj->URL = $this->DefaultImageLink();
690
691
        return $obj;
692
    }
693
694
    /**
695
     * standard SS method.
696
     */
697
    public function onAfterWrite()
698
    {
699
        if ($this->UseThisOne) {
700
            $configs = EcommerceDBConfig::get()
701
                ->Filter(array('UseThisOne' => 1))
702
                ->Exclude(array('ID' => $this->ID));
703
            if ($configs->count()) {
704
                foreach ($configs as $config) {
705
                    $config->UseThisOne = 0;
706
                    $config->write();
707
                }
708
            }
709
        }
710
        $configs = EcommerceDBConfig::get()
711
            ->Filter(array('Title' => $this->Title))
712
            ->Exclude(array('ID' => $this->ID));
713
        if ($configs->count()) {
714
            foreach ($configs as $key => $config) {
715
                $config->Title = $config->Title.'_'.$config->ID;
716
                $config->write();
717
            }
718
        }
719
    }
720
721
    /**
722
     * standard SS Method.
723
     */
724
    public function requireDefaultRecords()
725
    {
726
        parent::requireDefaultRecords();
727
        if (!self::current_ecommerce_db_config()) {
728
            $obj = self::create();
729
            $obj->write();
730
        }
731
        DB::alteration_message('
732
            <hr /><hr /><hr /><hr /><hr />
733
            <h1 style="color: darkRed">Please make sure to review your <a href="/dev/ecommerce/">e-commerce settings</a>.</h1>
734
            <hr /><hr /><hr /><hr /><hr />',
735
            'edited'
736
        );
737
    }
738
739
    /**
740
     * returns site config.
741
     *
742
     * @return SiteConfig
743
     */
744
    public function SiteConfig()
745
    {
746
        return SiteConfig::current_site_config();
747
    }
748
749
    /**
750
     * Casted Variable.
751
     *
752
     * @return string
753
     */
754
    public function UseThisOneNice()
755
    {
756
        return $this->UseThisOne ? 'YES' : 'NO';
757
    }
758
}
759