/
Product.php
8136 lines (7363 loc) · 275 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
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* 2007-2016 PrestaShop
*
* thirty bees is an extension to the PrestaShop e-commerce software developed by PrestaShop SA
* Copyright (C) 2017-2018 thirty bees
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@thirtybees.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.thirtybees.com for more information.
*
* @author thirty bees <contact@thirtybees.com>
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2017-2018 thirty bees
* @copyright 2007-2016 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* PrestaShop is an internationally registered trademark & property of PrestaShop SA
*/
/**
* @deprecated 1.5.0.1
*/
define('_CUSTOMIZE_FILE_', 0);
/**
* @deprecated 1.5.0.1
*/
define('_CUSTOMIZE_TEXTFIELD_', 1);
/**
* Class ProductCore
*
* @since 1.0.0
*/
class ProductCore extends ObjectModel
{
const CUSTOMIZE_FILE = 0;
const CUSTOMIZE_TEXTFIELD = 1;
/**
* Note: prefix is "PTYPE" because TYPE_ is used in ObjectModel (definition)
*/
const PTYPE_SIMPLE = 0;
const PTYPE_PACK = 1;
const PTYPE_VIRTUAL = 2;
// @codingStandardsIgnoreStart
public static $_taxCalculationMethod = null;
protected static $_prices = [];
protected static $_pricesLevel2 = [];
protected static $_incat = [];
/**
* @deprecated 1.0.0
* @var array $_cart_quantity is deprecated since 1.0.0
*/
protected static $_cart_quantity = [];
protected static $_tax_rules_group = [];
protected static $_cacheFeatures = [];
protected static $_frontFeaturesCache = [];
protected static $producPropertiesCache = [];
/** @var array cache stock data in getStock() method */
protected static $cacheStock = [];
/** @var string Tax name */
public $tax_name;
/** @var string Tax rate */
public $tax_rate;
/** @var int Manufacturer id */
public $id_manufacturer;
/** @var int Supplier id */
public $id_supplier;
/** @var int default Category id */
public $id_category_default;
/** @var int default Shop id */
public $id_shop_default;
/** @var string Manufacturer name */
public $manufacturer_name;
/** @var string Supplier name */
public $supplier_name;
/** @var string Name */
public $name;
/** @var string Long description */
public $description;
/** @var string Short description */
public $description_short;
/** @var int Quantity available */
public $quantity = 0;
/** @var int Minimal quantity for add to cart */
public $minimal_quantity = 1;
/** @var string available_now */
public $available_now;
/** @var string available_later */
public $available_later;
/** @var float Price in euros */
public $price = 0;
public $specificPrice = 0;
/** @var float Additional shipping cost */
public $additional_shipping_cost = 0;
/** @var float Wholesale Price in euros */
public $wholesale_price = 0;
/** @var bool on_sale */
public $on_sale = false;
/** @var bool online_only */
public $online_only = false;
/** @var string unity */
public $unity = null;
/** @var float price for product's unity */
public $unit_price;
/** @var float price for product's unity ratio */
public $unit_price_ratio = 0;
/** @var float Ecotax */
public $ecotax = 0;
/** @var string Reference */
public $reference;
/** @var string Supplier Reference */
public $supplier_reference;
/** @var string Location */
public $location;
/** @var float Width in default width unit */
public $width = 0;
/** @var float Height in default height unit */
public $height = 0;
/** @var float Depth in default depth unit */
public $depth = 0;
/** @var float Weight in default weight unit */
public $weight = 0;
/** @var string Ean-13 barcode */
public $ean13;
/** @var string Upc barcode */
public $upc;
/** @var string Friendly URL */
public $link_rewrite;
/** @var string Meta tag description */
public $meta_description;
/** @var string Meta tag keywords */
public $meta_keywords;
/** @var string Meta tag title */
public $meta_title;
/** @var bool Product statuts */
public $quantity_discount = 0;
/** @var bool Product customization */
public $customizable;
/** @var bool Product is new */
public $new = null;
/** @var int Number of uploadable files (concerning customizable products) */
public $uploadable_files;
/** @var int Number of text fields */
public $text_fields;
/** @var bool Product statuts */
public $active = true;
/** @var bool Product statuts */
public $redirect_type = '';
/** @var bool Product statuts */
public $id_product_redirected = 0;
/** @var bool Product available for order */
public $available_for_order = true;
/** @var string Object available order date */
public $available_date = '0000-00-00';
/** @var string Enumerated (enum) product condition (new, used, refurbished) */
public $condition;
/** @var bool Show price of Product */
public $show_price = true;
/** @var bool is the product indexed in the search index? */
public $indexed = 0;
/** @var string ENUM('both', 'catalog', 'search', 'none') front office visibility */
public $visibility;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
/*** @var array Tags */
public $tags;
/**
* @var float Base price of the product
* @deprecated 1.6.0.13
*/
public $base_price;
public $id_tax_rules_group = 1;
/**
* We keep this variable for retrocompatibility for themes
*
* @deprecated 1.5.0
*/
public $id_color_default = 0;
/**
* @since 1.5.0
* @var bool Tells if the product uses the advanced stock management
*/
public $advanced_stock_management = 0;
public $out_of_stock;
public $depends_on_stock;
public $isFullyLoaded = false;
public $cache_is_pack;
public $cache_has_attachments;
public $is_virtual;
public $id_pack_product_attribute;
public $cache_default_attribute;
/**
* @var string If product is populated, this property contain the rewrite link of the default category
*/
public $category;
/**
* @var int tell the type of stock management to apply on the pack
*/
public $pack_stock_type = 3;
// @codingStandardsIgnoreEnd
public $packItems;
public $productDownload;
public static $definition = [
'table' => 'product',
'primary' => 'id_product',
'multilang' => true,
'multilang_shop' => true,
'fields' => [
/* Classic fields */
'id_shop_default' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'id_manufacturer' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'id_supplier' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'reference' => ['type' => self::TYPE_STRING, 'validate' => 'isReference', 'size' => 32],
'supplier_reference' => ['type' => self::TYPE_STRING, 'validate' => 'isReference', 'size' => 32],
'location' => ['type' => self::TYPE_STRING, 'validate' => 'isReference', 'size' => 64],
'width' => ['type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'],
'height' => ['type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'],
'depth' => ['type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'],
'weight' => ['type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'],
'quantity_discount' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'ean13' => ['type' => self::TYPE_STRING, 'validate' => 'isEan13', 'size' => 13],
'upc' => ['type' => self::TYPE_STRING, 'validate' => 'isUpc', 'size' => 12],
'cache_is_pack' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'cache_has_attachments' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'is_virtual' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
/* Shop fields */
'id_category_default' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'],
'id_tax_rules_group' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'],
'on_sale' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'],
'online_only' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'],
'ecotax' => ['type' => self::TYPE_PRICE, 'shop' => true, 'validate' => 'isPrice'],
'minimal_quantity' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedInt'],
'price' => ['type' => self::TYPE_PRICE, 'shop' => true, 'validate' => 'isPrice', 'required' => true],
'wholesale_price' => ['type' => self::TYPE_PRICE, 'shop' => true, 'validate' => 'isPrice'],
'unity' => ['type' => self::TYPE_STRING, 'shop' => true, 'validate' => 'isString'],
'unit_price_ratio' => ['type' => self::TYPE_FLOAT, 'shop' => true],
'additional_shipping_cost' => ['type' => self::TYPE_PRICE, 'shop' => true, 'validate' => 'isPrice'],
'customizable' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedInt'],
'text_fields' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedInt'],
'uploadable_files' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedInt'],
'active' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'],
'redirect_type' => ['type' => self::TYPE_STRING, 'shop' => true, 'validate' => 'isString'],
'id_product_redirected' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'],
'available_for_order' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'],
'available_date' => ['type' => self::TYPE_DATE, 'shop' => true, 'validate' => 'isDateFormat'],
'condition' => ['type' => self::TYPE_STRING, 'shop' => true, 'validate' => 'isGenericName', 'values' => ['new', 'used', 'refurbished'], 'default' => 'new'],
'show_price' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'],
'indexed' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'],
'visibility' => ['type' => self::TYPE_STRING, 'shop' => true, 'validate' => 'isProductVisibility', 'values' => ['both', 'catalog', 'search', 'none'], 'default' => 'both'],
'cache_default_attribute' => ['type' => self::TYPE_INT, 'shop' => true],
'advanced_stock_management' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'],
'date_add' => ['type' => self::TYPE_DATE, 'shop' => true, 'validate' => 'isDate'],
'date_upd' => ['type' => self::TYPE_DATE, 'shop' => true, 'validate' => 'isDate'],
'pack_stock_type' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedInt'],
/* Lang fields */
'meta_description' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 255],
'meta_keywords' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 255],
'meta_title' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 128],
'link_rewrite' => [
'type' => self::TYPE_STRING,
'lang' => true,
'validate' => 'isLinkRewrite',
'required' => true,
'size' => 128,
'ws_modifier' => [
'http_method' => WebserviceRequest::HTTP_POST,
'modifier' => 'modifierWsLinkRewrite',
],
],
'name' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isCatalogName', 'required' => true, 'size' => 128],
'description' => ['type' => self::TYPE_HTML, 'lang' => true, 'validate' => 'isCleanHtml'],
'description_short' => ['type' => self::TYPE_HTML, 'lang' => true, 'validate' => 'isCleanHtml'],
'available_now' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 255],
'available_later' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'IsGenericName', 'size' => 255],
],
'associations' => [
'manufacturer' => ['type' => self::HAS_ONE],
'supplier' => ['type' => self::HAS_ONE],
'default_category' => ['type' => self::HAS_ONE, 'field' => 'id_category_default', 'object' => 'Category'],
'tax_rules_group' => ['type' => self::HAS_ONE],
'categories' => ['type' => self::BELONGS_TO_MANY, 'object' => 'Category', 'joinTable' => 'category_product'],
'stock_availables' => ['type' => self::HAS_MANY, 'field' => 'id_product', 'foreignField' => 'id_product', 'object' => 'StockAvailable'],
],
];
protected $webserviceParameters = [
'objectMethods' => [
'add' => 'addWs',
'update' => 'updateWs',
],
'objectNodeNames' => 'products',
'fields' => [
'id_manufacturer' => [
'xlink_resource' => 'manufacturers',
],
'id_supplier' => [
'xlink_resource' => 'suppliers',
],
'id_category_default' => [
'xlink_resource' => 'categories',
],
'new' => [],
'cache_default_attribute' => [],
'id_default_image' => [
'getter' => 'getCoverWs',
'setter' => 'setCoverWs',
'xlink_resource' => [
'resourceName' => 'images',
'subResourceName' => 'products',
],
],
'id_default_combination' => [
'getter' => 'getWsDefaultCombination',
'setter' => 'setWsDefaultCombination',
'xlink_resource' => [
'resourceName' => 'combinations',
],
],
'id_tax_rules_group' => [
'xlink_resource' => [
'resourceName' => 'tax_rule_groups',
],
],
'position_in_category' => [
'getter' => 'getWsPositionInCategory',
'setter' => 'setWsPositionInCategory',
],
'manufacturer_name' => [
'getter' => 'getWsManufacturerName',
'setter' => false,
],
'quantity' => [
'getter' => false,
'setter' => false,
],
'type' => [
'getter' => 'getWsType',
'setter' => 'setWsType',
],
],
'associations' => [
'categories' => [
'resource' => 'category',
'fields' => [
'id' => ['required' => true],
],
],
'images' => [
'resource' => 'image',
'fields' => ['id' => []],
],
'combinations' => [
'resource' => 'combination',
'fields' => [
'id' => ['required' => true],
],
],
'product_option_values' => [
'resource' => 'product_option_value',
'fields' => [
'id' => ['required' => true],
],
],
'product_features' => [
'resource' => 'product_feature',
'fields' => [
'id' => ['required' => true],
'id_feature_value' => [
'required' => true,
'xlink_resource' => 'product_feature_values',
],
],
],
'tags' => [
'resource' => 'tag',
'fields' => [
'id' => ['required' => true],
],
],
'stock_availables' => [
'resource' => 'stock_available',
'fields' => [
'id' => ['required' => true],
'id_product_attribute' => ['required' => true],
],
'setter' => false,
],
'accessories' => [
'resource' => 'product',
'api' => 'products',
'fields' => [
'id' => [
'required' => true,
'xlink_resource' => 'product',
],
],
],
'product_bundle' => [
'resource' => 'product',
'api' => 'products',
'fields' => [
'id' => ['required' => true],
'quantity' => [],
],
],
],
];
/**
* ProductCore constructor.
*
* @param null $idProduct
* @param bool $full
* @param null $idLang
* @param null $idShop
* @param Context|null $context
*
* @since 1.0.0
* @version 1.0.0 Initial version
* @throws PrestaShopException
*/
public function __construct($idProduct = null, $full = false, $idLang = null, $idShop = null, Context $context = null)
{
parent::__construct($idProduct, $idLang, $idShop);
if ($full && $this->id) {
if (!$context) {
$context = Context::getContext();
}
$this->isFullyLoaded = $full;
$this->tax_name = 'deprecated'; // The applicable tax may be BOTH the product one AND the state one (moreover this variable is some deadcode)
$this->manufacturer_name = Manufacturer::getNameById((int) $this->id_manufacturer);
$this->supplier_name = Supplier::getNameById((int) $this->id_supplier);
$address = null;
if (is_object($context->cart) && $context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')} != null) {
$address = $context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
}
$this->tax_rate = $this->getTaxesRate(new Address($address));
$this->new = $this->isNew();
// Keep base price
$this->base_price = $this->price;
$this->price = static::getPriceStatic(
(int) $this->id,
false,
null,
_TB_PRICE_DATABASE_PRECISION_,
null,
false,
true,
1,
false,
null,
null,
null,
$this->specificPrice
);
$this->unit_price = ($this->unit_price_ratio != 0 ?
round(
$this->price / $this->unit_price_ratio,
_TB_PRICE_DATABASE_PRECISION_
) :
0
);
$this->tags = Tag::getProductTags((int) $this->id);
$this->loadStockData();
}
if ($this->id_category_default) {
$this->category = Category::getLinkRewrite((int) $this->id_category_default, (int) $idLang);
}
}
/**
* Returns tax rate.
*
* @param Address|null $address
*
* @return float The total taxes rate applied to the product
*
* @since 1.0.0
* @version 1.0.0 Initial version
* @throws PrestaShopException
*/
public function getTaxesRate(Address $address = null)
{
if (!$address || !$address->id_country) {
$address = Address::initialize();
}
$taxManager = TaxManagerFactory::getManager($address, $this->id_tax_rules_group);
$taxCalculator = $taxManager->getTaxCalculator();
return $taxCalculator->getTotalRate();
}
/**
* @return bool
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
* @since 1.0.0
* @version 1.0.0 Initial version
*/
public function isNew()
{
$result = Db::getInstance()->executeS(
'
SELECT p.id_product
FROM `'._DB_PREFIX_.'product` p
'.Shop::addSqlAssociation('product', 'p').'
WHERE p.id_product = '.(int) $this->id.'
AND DATEDIFF(
product_shop.`date_add`,
DATE_SUB(
"'.date('Y-m-d').' 00:00:00",
INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY
)
) > 0
', true, false
);
return count($result) > 0;
}
/**
* Returns product price
*
* @param int $idProduct Product id
* @param bool $usetax With taxes or not (optional)
* @param int|null $idProductAttribute Product attribute id (optional).
* If set to false, do not apply the combination price impact.
* NULL does apply the default combination price impact.
* @param int $decimals Number of decimals (optional)
* @param int|null $divisor Useful when paying many time without fees (optional)
* @param bool $onlyReduc Returns only the reduction amount
* @param bool $usereduc Set if the returned amount will include reduction
* @param int $quantity Required for quantity discount application (default value: 1)
* @param bool $forceAssociatedTax DEPRECATED - NOT USED Force to apply the associated tax.
* Only works when the parameter $usetax is true
* @param int|null $idCustomer Customer ID (for customer group reduction)
* @param int|null $idCart Cart ID. Required when the cookie is not accessible
* (e.g., inside a payment module, a cron task...)
* @param int|null $idAddress Customer address ID. Required for price (tax included)
* calculation regarding the guest localization
* @param null $specificPriceOutput If a specific price applies regarding the previous parameters,
* this variable is filled with the corresponding SpecificPrice object
* @param bool $withEcotax Insert ecotax in price output.
* @param bool $useGroupReduction
* @param Context $context
* @param bool $useCustomerPrice
*
* @return float Product price
*
* @since 1.0.0
* @version 1.0.0 Initial version
* @throws PrestaShopException
*/
public static function getPriceStatic(
$idProduct,
$usetax = true,
$idProductAttribute = null,
$decimals = _TB_PRICE_DATABASE_PRECISION_,
$divisor = null,
$onlyReduc = false,
$usereduc = true,
$quantity = 1,
$forceAssociatedTax = false,
$idCustomer = null,
$idCart = null,
$idAddress = null,
&$specificPriceOutput = null,
$withEcotax = true,
$useGroupReduction = true,
Context $context = null,
$useCustomerPrice = true
) {
if (!$context) {
$context = Context::getContext();
}
$curCart = $context->cart;
if ($divisor !== null) {
Tools::displayParameterAsDeprecated('divisor');
}
if (!Validate::isBool($usetax) || !Validate::isUnsignedId($idProduct)) {
die(Tools::displayError());
}
// Initializations
$idGroup = null;
if ($idCustomer) {
$idGroup = Customer::getDefaultGroupId((int) $idCustomer);
}
if (!$idGroup) {
$idGroup = (int) Group::getCurrent()->id;
}
// If there is cart in context or if the specified id_cart is different from the context cart id
if (!is_object($curCart) || (Validate::isUnsignedInt($idCart) && $idCart && $curCart->id != $idCart)) {
/*
* When a user (e.g., guest, customer, Google...) is on PrestaShop, he has already its cart as the global (see /init.php)
* When a non-user calls directly this method (e.g., payment module...) is on PrestaShop, he does not have already it BUT knows the cart ID
* When called from the back office, cart ID can be inexistant
*/
if (!$idCart && !isset($context->employee)) {
die(Tools::displayError());
}
$curCart = new Cart($idCart);
// Store cart in context to avoid multiple instantiations in BO
if (!Validate::isLoadedObject($context->cart)) {
$context->cart = $curCart;
}
}
$cartQuantity = 0;
if ((int) $idCart) {
$cacheId = 'Product::getPriceStatic_'.(int) $idProduct.'-'.(int) $idCart;
if (!Cache::isStored($cacheId) || ($cartQuantity = Cache::retrieve($cacheId) != (int) $quantity)) {
$sql = 'SELECT SUM(`quantity`)
FROM `'._DB_PREFIX_.'cart_product`
WHERE `id_product` = '.(int) $idProduct.'
AND `id_cart` = '.(int) $idCart;
$cartQuantity = (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql);
Cache::store($cacheId, $cartQuantity);
} else {
$cartQuantity = Cache::retrieve($cacheId);
}
}
$idCurrency = Validate::isLoadedObject($context->currency) ? (int) $context->currency->id : (int) Configuration::get('PS_CURRENCY_DEFAULT');
// retrieve address informations
$idCountry = (int) $context->country->id;
$idState = 0;
$zipcode = 0;
if (!$idAddress && Validate::isLoadedObject($curCart)) {
$idAddress = $curCart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
}
if ($idAddress) {
$addressInfos = Address::getCountryAndState($idAddress);
if ($addressInfos['id_country']) {
$idCountry = (int) $addressInfos['id_country'];
$idState = (int) $addressInfos['id_state'];
$zipcode = $addressInfos['postcode'];
}
} elseif (isset($context->customer->geoloc_id_country)) {
$idCountry = (int) $context->customer->geoloc_id_country;
$idState = (int) $context->customer->id_state;
$zipcode = $context->customer->postcode;
}
if (Tax::excludeTaxeOption()) {
$usetax = false;
}
// @TODO: Use a hook for this. Like:
// Hook::exec('isVatExemption', ['address' => &$address]);
if (Module::isEnabled('vatnumber') && $idAddress) {
require_once _PS_MODULE_DIR_.'/vatnumber/VATNumberTaxManager.php';
$address = new Address($idAddress);
$usetax = $usetax
&& ! VATNumberTaxManager::isAvailableForThisAddress($address);
}
if (is_null($idCustomer) && Validate::isLoadedObject($context->customer)) {
$idCustomer = $context->customer->id;
}
$return = static::priceCalculation(
$context->shop->id,
$idProduct,
$idProductAttribute,
$idCountry,
$idState,
$zipcode,
$idCurrency,
$idGroup,
$quantity,
$usetax,
$decimals,
$onlyReduc,
$usereduc,
$withEcotax,
$specificPriceOutput,
$useGroupReduction,
$idCustomer,
$useCustomerPrice,
$idCart,
$cartQuantity
);
return $return;
}
/**
* Price calculation / Get product price
*
* @param int $idShop Shop id
* @param int $idProduct Product id
* @param int $idProductAttribute Product attribute id
* @param int $idCountry Country id
* @param int $idState State id
* @param string $zipcode
* @param int $idCurrency Currency id
* @param int $idGroup Group id
* @param int $quantity Quantity Required for Specific prices : quantity discount application
* @param bool $useTax with (1) or without (0) tax
* @param int $decimals Number of decimals returned
* @param bool $onlyReduc Returns only the reduction amount
* @param bool $useReduc Set if the returned amount will include reduction
* @param bool $withEcotax insert ecotax in price output.
* @param null $specificPrice If a specific price applies regarding the previous parameters,
* this variable is filled with the corresponding SpecificPrice object
* @param bool $useGroupReduction
* @param int $idCustomer
* @param bool $useCustomerPrice
* @param int $idCart
* @param int $realQuantity
*
* @return float Product price
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
* @since 1.0.0
* @version 1.0.0 Initial version
*/
public static function priceCalculation(
$idShop,
$idProduct,
$idProductAttribute,
$idCountry,
$idState,
$zipcode,
$idCurrency,
$idGroup,
$quantity,
$useTax,
$decimals,
$onlyReduc,
$useReduc,
$withEcotax,
&$specificPrice,
$useGroupReduction,
$idCustomer = 0,
$useCustomerPrice = true,
$idCart = 0,
$realQuantity = 0
) {
static $address = null;
static $context = null;
if ($address === null) {
$address = new Address();
}
if ($context == null) {
$context = Context::getContext()->cloneContext();
}
if ($idShop !== null && $context->shop->id != (int) $idShop) {
$context->shop = new Shop((int) $idShop);
}
if (!$useCustomerPrice) {
$idCustomer = 0;
}
if ($idProductAttribute === null) {
$idProductAttribute = static::getDefaultAttribute($idProduct);
}
$cacheId = (int) $idProduct.'-'.(int) $idShop.'-'.(int) $idCurrency.'-'.(int) $idCountry.'-'.$idState.'-'.$zipcode.'-'.(int) $idGroup.
'-'.(int) $quantity.'-'.(int) $idProductAttribute.
'-'.(int) $withEcotax.'-'.(int) $idCustomer.'-'.(int) $useGroupReduction.'-'.(int) $idCart.'-'.(int) $realQuantity.
'-'.($onlyReduc ? '1' : '0').'-'.($useReduc ? '1' : '0').'-'.($useTax ? '1' : '0').'-'.(int) $decimals;
// reference parameter is filled before any returns
$specificPrice = SpecificPrice::getSpecificPrice(
(int) $idProduct,
$idShop,
$idCurrency,
$idCountry,
$idGroup,
$quantity,
$idProductAttribute,
$idCustomer,
$idCart,
$realQuantity
);
if (isset(static::$_prices[$cacheId])) {
/* Affect reference before returning cache */
if (isset($specificPrice['price']) && $specificPrice['price'] > 0) {
$specificPrice['price'] = static::$_prices[$cacheId];
}
return static::$_prices[$cacheId];
}
// fetch price & attribute price
$cacheId2 = $idProduct.'-'.$idShop;
if (!isset(static::$_pricesLevel2[$cacheId2])) {
$sql = new DbQuery();
$sql->select('product_shop.`price`, product_shop.`ecotax`');
$sql->from('product', 'p');
$sql->innerJoin('product_shop', 'product_shop', '(product_shop.id_product=p.id_product AND product_shop.id_shop = '.(int) $idShop.')');
$sql->where('p.`id_product` = '.(int) $idProduct);
if (Combination::isFeatureActive()) {
$sql->select('IFNULL(product_attribute_shop.id_product_attribute,0) id_product_attribute, product_attribute_shop.`price` AS attribute_price, product_attribute_shop.default_on');
$sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.id_product = p.id_product AND product_attribute_shop.id_shop = '.(int) $idShop.')');
} else {
$sql->select('0 as id_product_attribute');
}
$res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
if (is_array($res) && count($res)) {
foreach ($res as $row) {
$arrayTmp = [
'price' => $row['price'],
'ecotax' => $row['ecotax'],
'attribute_price' => (isset($row['attribute_price']) ? $row['attribute_price'] : null),
];
static::$_pricesLevel2[$cacheId2][(int) $row['id_product_attribute']] = $arrayTmp;
if (isset($row['default_on']) && $row['default_on'] == 1) {
static::$_pricesLevel2[$cacheId2][0] = $arrayTmp;
}
}
}
}
if (!isset(static::$_pricesLevel2[$cacheId2][(int) $idProductAttribute])) {
return;
}
$result = static::$_pricesLevel2[$cacheId2][(int) $idProductAttribute];
if (!$specificPrice || $specificPrice['price'] < 0) {
$price = (float) $result['price'];
} else {
$price = (float) $specificPrice['price'];
}
// convert only if the specific price is in the default currency (id_currency = 0)
if (!$specificPrice || !($specificPrice['price'] >= 0 && $specificPrice['id_currency'])) {
$price = Tools::convertPrice($price, $idCurrency);
if (isset($specificPrice['price']) && $specificPrice['price'] >= 0) {
$specificPrice['price'] = $price;
}
}
// Attribute price
if (is_array($result) && (!$specificPrice || !$specificPrice['id_product_attribute'] || $specificPrice['price'] < 0)) {
$attributePrice = Tools::convertPrice($result['attribute_price'] !== null ? (float) $result['attribute_price'] : 0, $idCurrency);
// If you want the default combination, please use NULL value instead
if ($idProductAttribute !== false) {
$price += $attributePrice;
}
}
// Tax
$address->id_country = $idCountry;
$address->id_state = $idState;
$address->postcode = $zipcode;
$taxManager = TaxManagerFactory::getManager($address, static::getIdTaxRulesGroupByIdProduct((int) $idProduct, $context));
$productTaxCalculator = $taxManager->getTaxCalculator();
// Add Tax
if ($useTax) {
$price = $productTaxCalculator->addTaxes($price);
}
// Eco Tax
if (($result['ecotax'] || isset($result['attribute_ecotax'])) && $withEcotax) {
$ecotax = $result['ecotax'];
if (isset($result['attribute_ecotax']) && $result['attribute_ecotax'] > 0) {
$ecotax = $result['attribute_ecotax'];
}
if ($idCurrency) {
$ecotax = Tools::convertPrice($ecotax, $idCurrency);
}
if ($useTax) {
// reinit the tax manager for ecotax handling
$taxManager = TaxManagerFactory::getManager(
$address,
(int) Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID')
);
$ecotaxTaxCalculator = $taxManager->getTaxCalculator();
$price += $ecotaxTaxCalculator->addTaxes($ecotax);
} else {
$price += $ecotax;
}
}
// Reduction
$specificPriceReduction = 0;
if (($onlyReduc || $useReduc) && $specificPrice) {
if ($specificPrice['reduction_type'] == 'amount') {
$reductionAmount = $specificPrice['reduction'];
if (!$specificPrice['id_currency']) {
$reductionAmount = Tools::convertPrice($reductionAmount, $idCurrency);
}
$specificPriceReduction = $reductionAmount;
// Adjust taxes if required
if (!$useTax && $specificPrice['reduction_tax']) {
if (!$productTaxCalculator->getTotalRate()) {
$tax = new Tax(Configuration::get('TB_DEFAULT_SPECIFIC_PRICE_RULE_TAX'));
if (Validate::isLoadedObject($tax)) {
$specificPriceReduction = round(
$specificPriceReduction / (1 + $tax->rate / 100),
_TB_PRICE_DATABASE_PRECISION_
);
}
} else {
$specificPriceReduction = $productTaxCalculator->removeTaxes($specificPriceReduction);
}
}
if ($useTax && !$specificPrice['reduction_tax']) {
$specificPriceReduction = $productTaxCalculator->addTaxes($specificPriceReduction);
}
} else {
$specificPriceReduction = round(
$price * $specificPrice['reduction'],
_TB_PRICE_DATABASE_PRECISION_
);
}
}
if ($useReduc) {
$price -= $specificPriceReduction;
}
// Group reduction
if ($useGroupReduction) {
$reductionFromCategory = GroupReduction::getValueForProduct($idProduct, $idGroup);
if ($reductionFromCategory !== false) {
$groupReduction = round(
$price * $reductionFromCategory,
_TB_PRICE_DATABASE_PRECISION_
);
} else {
// Apply group reduction if there is no group reduction for
// this category.
$reduc = Group::getReductionByIdGroup($idGroup);
$groupReduction = ($reduc ?
round($price * $reduc / 100, _TB_PRICE_DATABASE_PRECISION_) :
0
);
}
$price -= $groupReduction;
}
if ($onlyReduc) {
if ($decimals >= _TB_PRICE_DATABASE_PRECISION_) {
return round(
$specificPriceReduction,
_TB_PRICE_DATABASE_PRECISION_
);
} else {
return Tools::ps_round($specificPriceReduction, $decimals);
}
}
if ($decimals >= _TB_PRICE_DATABASE_PRECISION_) {