-
Notifications
You must be signed in to change notification settings - Fork 0
/
CartRule.php
executable file
·1842 lines (1672 loc) · 86.1 KB
/
CartRule.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
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 [email protected] 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://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <[email protected]>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
/**
* Class CartRuleCore.
*/
class CartRuleCore extends ObjectModel
{
/* Filters used when retrieving the cart rules applied to a cart of when calculating the value of a reduction */
const FILTER_ACTION_ALL = 1;
const FILTER_ACTION_SHIPPING = 2;
const FILTER_ACTION_REDUCTION = 3;
const FILTER_ACTION_GIFT = 4;
const FILTER_ACTION_ALL_NOCAP = 5;
const BO_ORDER_CODE_PREFIX = 'BO_ORDER_';
/**
* This variable controls that a free gift is offered only once, even when multi-shippping is activated
* and the same product is delivered in both addresses.
*
* @var array
*/
protected static $only_one_gift = [];
public $id;
public $name;
public $id_customer;
public $date_from;
public $date_to;
public $description;
public $quantity = 1;
public $quantity_per_user = 1;
public $priority = 1;
/**
* @var bool
*/
public $partial_use = 1;
public $code;
public $minimum_amount;
/**
* @var bool
*/
public $minimum_amount_tax;
public $minimum_amount_currency;
/**
* @var bool
*/
public $minimum_amount_shipping;
/**
* @var bool
*/
public $country_restriction;
/**
* @var bool
*/
public $carrier_restriction;
/**
* @var bool
*/
public $group_restriction;
/**
* @var bool
*/
public $cart_rule_restriction;
/**
* @var bool
*/
public $product_restriction;
/**
* @var bool
*/
public $shop_restriction;
/**
* @var bool
*/
public $free_shipping;
public $reduction_percent;
public $reduction_amount;
/**
* @var bool is this voucher value tax included (false = tax excluded value)
*/
public $reduction_tax;
/**
* @var int
*/
public $reduction_currency;
public $reduction_product;
/**
* @var bool
*/
public $reduction_exclude_special;
public $gift_product;
public $gift_product_attribute;
/**
* @var bool
*/
public $highlight;
/**
* @var bool
*/
public $active = 1;
public $date_add;
public $date_upd;
protected static $cartAmountCache = [];
/**
* @see ObjectModel::$definition
*/
public static $definition = [
'table' => 'cart_rule',
'primary' => 'id_cart_rule',
'multilang' => true,
'fields' => [
'id_customer' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'date_from' => ['type' => self::TYPE_DATE, 'validate' => 'isDate', 'required' => true],
'date_to' => ['type' => self::TYPE_DATE, 'validate' => 'isDate', 'required' => true],
'description' => ['type' => self::TYPE_STRING, 'validate' => 'isCleanHtml', 'size' => 65534],
'quantity' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'],
'quantity_per_user' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'],
'priority' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'],
'partial_use' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'code' => ['type' => self::TYPE_STRING, 'validate' => 'isCleanHtml', 'size' => 254],
'minimum_amount' => ['type' => self::TYPE_FLOAT, 'validate' => 'isFloat'],
'minimum_amount_tax' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'minimum_amount_currency' => ['type' => self::TYPE_INT, 'validate' => 'isInt'],
'minimum_amount_shipping' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'country_restriction' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'carrier_restriction' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'group_restriction' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'cart_rule_restriction' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'product_restriction' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'shop_restriction' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'free_shipping' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'reduction_percent' => ['type' => self::TYPE_FLOAT, 'validate' => 'isPercentage'],
'reduction_amount' => ['type' => self::TYPE_FLOAT, 'validate' => 'isFloat'],
'reduction_tax' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'reduction_currency' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'reduction_product' => ['type' => self::TYPE_INT, 'validate' => 'isInt'],
'reduction_exclude_special' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'gift_product' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'gift_product_attribute' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'highlight' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'active' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'date_add' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
'date_upd' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
/* Lang fields */
'name' => [
'type' => self::TYPE_STRING,
'lang' => true,
'validate' => 'isCleanHtml',
'required' => true, 'size' => 254,
],
],
];
public static function resetStaticCache()
{
static::$cartAmountCache = [];
}
/**
* Adds current CartRule as a new Object to the database.
*
* @param bool $autodate Automatically set `date_upd` and `date_add` columns
* @param bool $null_values Whether we want to use NULL values instead of empty quotes values
*
* @return bool Indicates whether the CartRule has been successfully added
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function add($autodate = true, $null_values = false)
{
if (!$this->reduction_currency) {
$this->reduction_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT');
}
if (!parent::add($autodate, $null_values)) {
return false;
}
Configuration::updateGlobalValue('PS_CART_RULE_FEATURE_ACTIVE', '1');
return true;
}
/**
* Updates the current object in the database.
*
* @param bool $null_values Whether we want to use NULL values instead of empty quotes values
*
* @return bool Indicates whether the CartRule has been successfully updated
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function update($null_values = false)
{
Cache::clean('getContextualValue_' . $this->id . '_*');
if (!$this->reduction_currency) {
$this->reduction_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT');
}
if (!parent::update($null_values)) {
return false;
}
Configuration::updateGlobalValue(
'PS_CART_RULE_FEATURE_ACTIVE',
CartRule::isCurrentlyUsed($this->def['table'], true)
);
return true;
}
/**
* Deletes current CartRule from the database.
*
* @return bool True if delete was successful
*
* @throws PrestaShopException
*/
public function delete()
{
if (!parent::delete()) {
return false;
}
Configuration::updateGlobalValue(
'PS_CART_RULE_FEATURE_ACTIVE',
CartRule::isCurrentlyUsed($this->def['table'], true)
);
$r = Db::getInstance()->delete('cart_cart_rule', '`id_cart_rule` = ' . (int) $this->id);
$r &= Db::getInstance()->delete('cart_rule_carrier', '`id_cart_rule` = ' . (int) $this->id);
$r &= Db::getInstance()->delete('cart_rule_shop', '`id_cart_rule` = ' . (int) $this->id);
$r &= Db::getInstance()->delete('cart_rule_group', '`id_cart_rule` = ' . (int) $this->id);
$r &= Db::getInstance()->delete('cart_rule_country', '`id_cart_rule` = ' . (int) $this->id);
$r &= Db::getInstance()->delete('cart_rule_combination', '`id_cart_rule_1` = ' . (int) $this->id . ' OR `id_cart_rule_2` = ' . (int) $this->id);
$r &= Db::getInstance()->delete('cart_rule_product_rule_group', '`id_cart_rule` = ' . (int) $this->id);
$r &= Db::getInstance()->delete('cart_rule_product_rule', 'NOT EXISTS (SELECT 1 FROM `' . _DB_PREFIX_ . 'cart_rule_product_rule_group`
WHERE `' . _DB_PREFIX_ . 'cart_rule_product_rule`.`id_product_rule_group` = `' . _DB_PREFIX_ . 'cart_rule_product_rule_group`.`id_product_rule_group`)');
$r &= Db::getInstance()->delete('cart_rule_product_rule_value', 'NOT EXISTS (SELECT 1 FROM `' . _DB_PREFIX_ . 'cart_rule_product_rule`
WHERE `' . _DB_PREFIX_ . 'cart_rule_product_rule_value`.`id_product_rule` = `' . _DB_PREFIX_ . 'cart_rule_product_rule`.`id_product_rule`)');
return (bool) $r;
}
/**
* Copy conditions from one CartRule to another.
*
* @param int $id_cart_rule_source Source CartRule ID
* @param int $id_cart_rule_destination Destination CartRule ID
*/
public static function copyConditions($id_cart_rule_source, $id_cart_rule_destination)
{
Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'cart_rule_shop` (`id_cart_rule`, `id_shop`)
(SELECT ' . (int) $id_cart_rule_destination . ', id_shop FROM `' . _DB_PREFIX_ . 'cart_rule_shop` WHERE `id_cart_rule` = ' . (int) $id_cart_rule_source . ')');
Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'cart_rule_carrier` (`id_cart_rule`, `id_carrier`)
(SELECT ' . (int) $id_cart_rule_destination . ', id_carrier FROM `' . _DB_PREFIX_ . 'cart_rule_carrier` WHERE `id_cart_rule` = ' . (int) $id_cart_rule_source . ')');
Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'cart_rule_group` (`id_cart_rule`, `id_group`)
(SELECT ' . (int) $id_cart_rule_destination . ', id_group FROM `' . _DB_PREFIX_ . 'cart_rule_group` WHERE `id_cart_rule` = ' . (int) $id_cart_rule_source . ')');
Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'cart_rule_country` (`id_cart_rule`, `id_country`)
(SELECT ' . (int) $id_cart_rule_destination . ', id_country FROM `' . _DB_PREFIX_ . 'cart_rule_country` WHERE `id_cart_rule` = ' . (int) $id_cart_rule_source . ')');
Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'cart_rule_combination` (`id_cart_rule_1`, `id_cart_rule_2`)
(SELECT ' . (int) $id_cart_rule_destination . ', IF(id_cart_rule_1 != ' . (int) $id_cart_rule_source . ', id_cart_rule_1, id_cart_rule_2) FROM `' . _DB_PREFIX_ . 'cart_rule_combination`
WHERE `id_cart_rule_1` = ' . (int) $id_cart_rule_source . ' OR `id_cart_rule_2` = ' . (int) $id_cart_rule_source . ')');
// Todo : should be changed soon, be must be copied too
// Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'cart_rule_product_rule` WHERE `id_cart_rule` = '.(int)$this->id);
// Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'cart_rule_product_rule_value` WHERE `id_product_rule` NOT IN (SELECT `id_product_rule` FROM `'._DB_PREFIX_.'cart_rule_product_rule`)');
// Copy products/category filters
$products_rules_group_source = Db::getInstance()->executeS('
SELECT id_product_rule_group,quantity FROM `' . _DB_PREFIX_ . 'cart_rule_product_rule_group`
WHERE `id_cart_rule` = ' . (int) $id_cart_rule_source . ' ');
foreach ($products_rules_group_source as $product_rule_group_source) {
Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'cart_rule_product_rule_group` (`id_cart_rule`, `quantity`)
VALUES (' . (int) $id_cart_rule_destination . ',' . (int) $product_rule_group_source['quantity'] . ')');
$id_product_rule_group_destination = Db::getInstance()->Insert_ID();
$products_rules_source = Db::getInstance()->executeS('
SELECT id_product_rule,type FROM `' . _DB_PREFIX_ . 'cart_rule_product_rule`
WHERE `id_product_rule_group` = ' . (int) $product_rule_group_source['id_product_rule_group'] . ' ');
foreach ($products_rules_source as $product_rule_source) {
Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'cart_rule_product_rule` (`id_product_rule_group`, `type`)
VALUES (' . (int) $id_product_rule_group_destination . ',"' . pSQL($product_rule_source['type']) . '")');
$id_product_rule_destination = Db::getInstance()->Insert_ID();
$products_rules_values_source = Db::getInstance()->executeS('
SELECT id_item FROM `' . _DB_PREFIX_ . 'cart_rule_product_rule_value`
WHERE `id_product_rule` = ' . (int) $product_rule_source['id_product_rule'] . ' ');
foreach ($products_rules_values_source as $product_rule_value_source) {
Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'cart_rule_product_rule_value` (`id_product_rule`, `id_item`)
VALUES (' . (int) $id_product_rule_destination . ',' . (int) $product_rule_value_source['id_item'] . ')');
}
}
}
}
/**
* Retrieves the CartRule ID associated with the given voucher code.
*
* @param string $code Voucher code
*
* @return int|bool CartRule ID
* false if not found
*/
public static function getIdByCode($code)
{
if (!Validate::isCleanHtml($code)) {
return false;
}
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(
'SELECT `id_cart_rule` FROM `' . _DB_PREFIX_ . 'cart_rule` WHERE `code` = \'' . pSQL($code) . '\''
);
}
/**
* Check if some cart rules exists today for the given customer.
*
* @param int $idCustomer
*
* @return bool
*/
public static function haveCartRuleToday($idCustomer)
{
static $haveCartRuleToday = [];
if (!isset($haveCartRuleToday[$idCustomer])) {
$sql = '(SELECT 1 FROM `' . _DB_PREFIX_ . 'cart_rule` ' .
'WHERE date_to >= "' . date('Y-m-d 00:00:00') .
'" AND date_to <= "' . date('Y-m-d 23:59:59') .
'" AND `id_customer` IN (0,' . (int) $idCustomer . ') LIMIT 1)';
$sql .= 'UNION ALL (SELECT 1 FROM `' . _DB_PREFIX_ . 'cart_rule` ' .
'WHERE date_from >= "' . date('Y-m-d 00:00:00') .
'" AND date_from <= "' . date('Y-m-d 23:59:59') .
'" AND `id_customer` IN (0,' . (int) $idCustomer . ') LIMIT 1)';
$sql .= 'UNION ALL (SELECT 1 FROM `' . _DB_PREFIX_ . 'cart_rule` ' .
'WHERE date_from < "' . date('Y-m-d 00:00:00') .
'" AND date_to > "' . date('Y-m-d 23:59:59') .
'" AND `id_customer` IN (0,' . (int) $idCustomer . ') LIMIT 1) LIMIT 1';
$haveCartRuleToday[$idCustomer] = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
}
return !empty($haveCartRuleToday[$idCustomer]);
}
/**
* Get CartRules for the given Customer.
*
* @param int $id_lang Language ID
* @param int $id_customer Customer ID
* @param bool $active Active vouchers only
* @param bool $includeGeneric Include generic AND highlighted vouchers, regardless of highlight_only setting
* @param bool $inStock Vouchers in stock only
* @param Cart|null $cart Cart
* @param bool $free_shipping_only Free shipping only
* @param bool $highlight_only Highlighted vouchers only
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public static function getCustomerCartRules(
$id_lang,
$id_customer,
$active = false,
$includeGeneric = true,
$inStock = false,
Cart $cart = null,
$free_shipping_only = false,
$highlight_only = false
) {
if (!CartRule::isFeatureActive()
|| !CartRule::haveCartRuleToday($id_customer)
) {
return [];
}
$sql_part1 = '* FROM `' . _DB_PREFIX_ . 'cart_rule` cr
LEFT JOIN `' . _DB_PREFIX_ . 'cart_rule_lang` crl ON (cr.`id_cart_rule` = crl.`id_cart_rule` AND crl.`id_lang` = ' . (int) $id_lang . ')';
$sql_part2 = ' AND NOW() BETWEEN cr.date_from AND cr.date_to
' . ($active ? 'AND cr.`active` = 1' : '') . '
' . ($inStock ? 'AND cr.`quantity` > 0' : '');
if ($free_shipping_only) {
$sql_part2 .= ' AND free_shipping = 1 AND carrier_restriction = 1';
}
if ($highlight_only) {
$sql_part2 .= ' AND highlight = 1 AND code NOT LIKE "' . pSQL(CartRule::BO_ORDER_CODE_PREFIX) . '%"';
}
$sql = '(SELECT SQL_NO_CACHE ' . $sql_part1 . '
WHERE (cr.`id_customer` = ' . (int) $id_customer . '
OR (cr.`id_customer` = 0 AND (cr.`highlight` = 1 OR cr.`code` = "")))
' . $sql_part2 . ')';
if ($includeGeneric && (int) $id_customer != 0) {
$sql .= ' UNION (SELECT ' . $sql_part1 . ' WHERE cr.`id_customer` = 0 ' . $sql_part2 . ')';
}
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql, true, false);
if (empty($result)) {
return [];
}
// Remove cart rule that does not match the customer groups
$customerGroups = Customer::getGroupsStatic($id_customer);
foreach ($result as $key => $cart_rule) {
if ($cart_rule['group_restriction']) {
$cartRuleGroups = Db::getInstance()->executeS('SELECT id_group FROM ' . _DB_PREFIX_ . 'cart_rule_group WHERE id_cart_rule = ' . (int) $cart_rule['id_cart_rule']);
foreach ($cartRuleGroups as $cartRuleGroup) {
if (in_array($cartRuleGroup['id_group'], $customerGroups)) {
continue 2;
}
}
unset($result[$key]);
}
}
foreach ($result as &$cart_rule) {
if ($cart_rule['quantity_per_user']) {
$quantity_used = Order::getDiscountsCustomer((int) $id_customer, (int) $cart_rule['id_cart_rule']);
if (isset($cart, $cart->id)) {
$quantity_used += $cart->getDiscountsCustomer((int) $cart_rule['id_cart_rule']);
}
$cart_rule['quantity_for_user'] = $cart_rule['quantity_per_user'] - $quantity_used;
} else {
$cart_rule['quantity_for_user'] = 0;
}
}
unset($cart_rule);
foreach ($result as $key => $cart_rule) {
if ($cart_rule['shop_restriction']) {
$cartRuleShops = Db::getInstance()->executeS('SELECT id_shop FROM ' . _DB_PREFIX_ . 'cart_rule_shop WHERE id_cart_rule = ' . (int) $cart_rule['id_cart_rule']);
foreach ($cartRuleShops as $cartRuleShop) {
if (Shop::isFeatureActive() && ($cartRuleShop['id_shop'] == Context::getContext()->shop->id)) {
continue 2;
}
}
unset($result[$key]);
}
}
if (isset($cart, $cart->id)) {
foreach ($result as $key => $cart_rule) {
if ($cart_rule['product_restriction']) {
$cr = new CartRule((int) $cart_rule['id_cart_rule']);
$r = $cr->checkProductRestrictionsFromCart(Context::getContext()->cart, false, false);
if ($r !== false) {
continue;
}
unset($result[$key]);
}
}
}
$result_bak = $result;
$result = [];
$country_restriction = false;
foreach ($result_bak as $key => $cart_rule) {
if ($cart_rule['country_restriction']) {
$country_restriction = true;
$countries = Db::getInstance()->executeS(
'
SELECT `id_country`
FROM `' . _DB_PREFIX_ . 'address`
WHERE `id_customer` = ' . (int) $id_customer . '
AND `deleted` = 0'
);
if (is_array($countries) && count($countries)) {
foreach ($countries as $country) {
$id_cart_rule = (bool) Db::getInstance()->getValue('
SELECT crc.id_cart_rule
FROM ' . _DB_PREFIX_ . 'cart_rule_country crc
WHERE crc.id_cart_rule = ' . (int) $cart_rule['id_cart_rule'] . '
AND crc.id_country = ' . (int) $country['id_country']);
if ($id_cart_rule) {
$result[] = $result_bak[$key];
break;
}
}
}
} else {
$result[] = $result_bak[$key];
}
}
if (!$country_restriction) {
$result = $result_bak;
}
return $result;
}
public static function getCustomerHighlightedDiscounts(
$languageId,
$customerId,
Cart $cart
) {
return static::getCustomerCartRules(
$languageId,
$customerId,
$active = true,
$includeGeneric = true,
$inStock = true,
$cart,
$freeShippingOnly = false,
$highlightOnly = true
);
}
/**
* Check if the CartRule has been used by the given Customer.
*
* @param int $id_customer Customer ID
*
* @return bool Indicates if the CartRule has been used by a Customer
* The Cart must have been converted into an Order, otherwise it doesn't count
*/
public function usedByCustomer($id_customer)
{
return (bool) Db::getInstance()->getValue('
SELECT id_cart_rule
FROM `' . _DB_PREFIX_ . 'order_cart_rule` ocr
LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON ocr.`id_order` = o.`id_order`
WHERE ocr.`deleted` = 0 AND ocr.`id_cart_rule` = ' . (int) $this->id . '
AND o.`id_customer` = ' . (int) $id_customer);
}
/**
* Check if the CartRule exists.
*
* @param string $code CartRule code
*
* @return bool Indicates whether the CartRule can be found
*/
public static function cartRuleExists($code)
{
if (!CartRule::isFeatureActive()) {
return false;
}
return (bool) Db::getInstance()->getValue('
SELECT `id_cart_rule`
FROM `' . _DB_PREFIX_ . 'cart_rule`
WHERE `code` = \'' . pSQL($code) . '\'', false);
}
/**
* Delete CartRules by Customer ID.
*
* @param int $id_customer Customer ID
*
* @return bool Indicates if the CartRules were successfully deleted
*/
public static function deleteByIdCustomer($id_customer)
{
$return = true;
$cart_rules = new PrestaShopCollection('CartRule');
$cart_rules->where('id_customer', '=', $id_customer);
foreach ($cart_rules as $cart_rule) {
$return &= $cart_rule->delete();
}
return $return;
}
/**
* @return array
*/
public function getProductRuleGroups()
{
if (!Validate::isLoadedObject($this) || $this->product_restriction == 0) {
return [];
}
$productRuleGroups = [];
$result = Db::getInstance()->executeS('SELECT * FROM ' . _DB_PREFIX_ . 'cart_rule_product_rule_group WHERE id_cart_rule = ' . (int) $this->id);
foreach ($result as $row) {
if (!isset($productRuleGroups[$row['id_product_rule_group']])) {
$productRuleGroups[$row['id_product_rule_group']] = ['id_product_rule_group' => $row['id_product_rule_group'], 'quantity' => $row['quantity']];
}
$productRuleGroups[$row['id_product_rule_group']]['product_rules'] = $this->getProductRules($row['id_product_rule_group']);
}
return $productRuleGroups;
}
/**
* @param $id_product_rule_group
*
* @return array ('type' => ? , 'values' => ?)
*/
public function getProductRules($id_product_rule_group)
{
if (!Validate::isLoadedObject($this) || $this->product_restriction == 0) {
return [];
}
$productRules = [];
$results = Db::getInstance()->executeS('
SELECT *
FROM ' . _DB_PREFIX_ . 'cart_rule_product_rule pr
LEFT JOIN ' . _DB_PREFIX_ . 'cart_rule_product_rule_value prv ON pr.id_product_rule = prv.id_product_rule
WHERE pr.id_product_rule_group = ' . (int) $id_product_rule_group);
foreach ($results as $row) {
if (!isset($productRules[$row['id_product_rule']])) {
$productRules[$row['id_product_rule']] = ['type' => $row['type'], 'values' => []];
}
$productRules[$row['id_product_rule']]['values'][] = $row['id_item'];
}
return $productRules;
}
/**
* Check if this CartRule can be applied.
*
* @param Context $context Context instance
* @param bool $alreadyInCart Check if the voucher is already on the cart
* @param bool $display_error Display error
*
* @return bool|mixed|string
*/
public function checkValidity(Context $context, $alreadyInCart = false, $display_error = true, $check_carrier = true)
{
if (!CartRule::isFeatureActive()) {
return false;
}
$cart = $context->cart;
// All these checks are necessary when you add the cart rule the first time, so when it's not in cart yet
// However when it's in the cart and you are checking if the cart rule is still valid (when performing auto remove)
// these rules are outdated For example:
// - the cart rule can now be disabled but it was at the time it was applied, so it doesn't need to be removed
// - the current date is not in the range any more but it was at the time
// - the quantity is now zero but it was not when it was added
if (!$alreadyInCart) {
if (!$this->active) {
return (!$display_error) ? false : $this->trans('This voucher is disabled', [], 'Shop.Notifications.Error');
}
if (!$this->quantity) {
return (!$display_error) ? false : $this->trans('This voucher has already been used', [], 'Shop.Notifications.Error');
}
if (strtotime($this->date_from) > time()) {
return (!$display_error) ? false : $this->trans('This voucher is not valid yet', [], 'Shop.Notifications.Error');
}
if (strtotime($this->date_to) < time()) {
return (!$display_error) ? false : $this->trans('This voucher has expired', [], 'Shop.Notifications.Error');
}
}
if ($cart->id_customer) {
$quantityUsed = Db::getInstance()->getValue('
SELECT count(*)
FROM `' . _DB_PREFIX_ . 'orders` o
LEFT JOIN `' . _DB_PREFIX_ . 'order_cart_rule` ocr ON o.`id_order` = ocr.`id_order`
WHERE o.`id_customer` = ' . $cart->id_customer . '
AND ocr.`deleted` = 0
AND ocr.`id_cart_rule` = ' . (int) $this->id . '
AND ' . (int) Configuration::get('PS_OS_ERROR') . ' != o.`current_state`
');
// When checking the cart rules present in that cart the request result is accurate
// When we check if using the cart rule one more time is valid then we increment this value
if (!$alreadyInCart) {
++$quantityUsed;
}
if ($quantityUsed > $this->quantity_per_user) {
return (!$display_error) ? false : $this->trans('You cannot use this voucher anymore (usage limit reached)', [], 'Shop.Notifications.Error');
}
}
// Get an intersection of the customer groups and the cart rule groups (if the customer is not logged in, the default group is Visitors)
if ($this->group_restriction) {
$id_cart_rule = (int) Db::getInstance()->getValue('
SELECT crg.id_cart_rule
FROM ' . _DB_PREFIX_ . 'cart_rule_group crg
WHERE crg.id_cart_rule = ' . (int) $this->id . '
AND crg.id_group ' . ($cart->id_customer ? 'IN (SELECT cg.id_group FROM ' . _DB_PREFIX_ . 'customer_group cg WHERE cg.id_customer = ' . (int) $cart->id_customer . ')' : '= ' . (int) Configuration::get('PS_UNIDENTIFIED_GROUP')));
if (!$id_cart_rule) {
return (!$display_error) ? false : $this->trans('You cannot use this voucher', [], 'Shop.Notifications.Error');
}
}
// Check if the customer delivery address is usable with the cart rule
if ($this->country_restriction) {
if (!$cart->id_address_delivery) {
return (!$display_error) ? false : $this->trans('You must choose a delivery address before applying this voucher to your order', [], 'Shop.Notifications.Error');
}
$id_cart_rule = (int) Db::getInstance()->getValue('
SELECT crc.id_cart_rule
FROM ' . _DB_PREFIX_ . 'cart_rule_country crc
WHERE crc.id_cart_rule = ' . (int) $this->id . '
AND crc.id_country = (SELECT a.id_country FROM ' . _DB_PREFIX_ . 'address a WHERE a.id_address = ' . (int) $cart->id_address_delivery . ' LIMIT 1)');
if (!$id_cart_rule) {
return (!$display_error) ? false : $this->trans('You cannot use this voucher in your country of delivery', [], 'Shop.Notifications.Error');
}
}
// Check if the carrier chosen by the customer is usable with the cart rule
if ($this->carrier_restriction && $check_carrier) {
if (!$cart->id_carrier) {
return (!$display_error) ? false : $this->trans('You must choose a carrier before applying this voucher to your order', [], 'Shop.Notifications.Error');
}
$id_cart_rule = (int) Db::getInstance()->getValue('
SELECT crc.id_cart_rule
FROM ' . _DB_PREFIX_ . 'cart_rule_carrier crc
INNER JOIN ' . _DB_PREFIX_ . 'carrier c ON (c.id_reference = crc.id_carrier AND c.deleted = 0)
WHERE crc.id_cart_rule = ' . (int) $this->id . '
AND c.id_carrier = ' . (int) $cart->id_carrier);
if (!$id_cart_rule) {
return (!$display_error) ? false : $this->trans('You cannot use this voucher with this carrier', [], 'Shop.Notifications.Error');
}
}
if ($this->reduction_exclude_special) {
$products = $cart->getProducts();
$is_ok = false;
foreach ($products as $product) {
if (!$product['reduction_applies']) {
$is_ok = true;
break;
}
}
if (!$is_ok) {
return (!$display_error) ? false : $this->trans('You cannot use this voucher on products on sale', [], 'Shop.Notifications.Error');
}
}
// Check if the cart rules appliy to the shop browsed by the customer
if ($this->shop_restriction && $context->shop->id && Shop::isFeatureActive()) {
$id_cart_rule = (int) Db::getInstance()->getValue('
SELECT crs.id_cart_rule
FROM ' . _DB_PREFIX_ . 'cart_rule_shop crs
WHERE crs.id_cart_rule = ' . (int) $this->id . '
AND crs.id_shop = ' . (int) $context->shop->id);
if (!$id_cart_rule) {
return (!$display_error) ? false : $this->trans('You cannot use this voucher', [], 'Shop.Notifications.Error');
}
}
// Check if the products chosen by the customer are usable with the cart rule
if ($this->product_restriction) {
$r = $this->checkProductRestrictionsFromCart($context->cart, false, $display_error, $alreadyInCart);
if ($r !== false && $display_error) {
return $r;
} elseif (!$r && !$display_error) {
return false;
}
}
// Check if the cart rule is only usable by a specific customer, and if the current customer is the right one
if ($this->id_customer && $cart->id_customer != $this->id_customer) {
if (!Context::getContext()->customer->isLogged()) {
return (!$display_error) ? false : ($this->trans('You cannot use this voucher', [], 'Shop.Notifications.Error') . ' - ' . $this->trans('Please log in first', [], 'Shop.Notifications.Error'));
}
return (!$display_error) ? false : $this->trans('You cannot use this voucher', [], 'Shop.Notifications.Error');
}
if ($this->minimum_amount && $check_carrier) {
// Minimum amount is converted to the contextual currency
$minimum_amount = $this->minimum_amount;
if ($this->minimum_amount_currency != Context::getContext()->currency->id) {
$minimum_amount = Tools::convertPriceFull($minimum_amount, new Currency($this->minimum_amount_currency), Context::getContext()->currency);
}
$cartTotal = $cart->getOrderTotal($this->minimum_amount_tax, Cart::ONLY_PRODUCTS);
if ($this->minimum_amount_shipping) {
$cartTotal += $cart->getOrderTotal($this->minimum_amount_tax, Cart::ONLY_SHIPPING);
}
$products = $cart->getProducts();
$cart_rules = $cart->getCartRules(CartRule::FILTER_ACTION_ALL, false);
foreach ($cart_rules as $cart_rule) {
if ($cart_rule['gift_product']) {
foreach ($products as $key => &$product) {
if (empty($product['is_gift']) && $product['id_product'] == $cart_rule['gift_product'] && $product['id_product_attribute'] == $cart_rule['gift_product_attribute']) {
$cartTotal = Tools::ps_round($cartTotal - $product[$this->minimum_amount_tax ? 'price_wt' : 'price'], (int) $context->currency->decimals * Context::getContext()->getComputingPrecision());
}
}
}
}
if ($cartTotal < $minimum_amount) {
return (!$display_error) ? false : $this->trans('You have not reached the minimum amount required to use this voucher', [], 'Shop.Notifications.Error');
}
}
/* This loop checks:
- if the voucher is already in the cart
- if a non compatible voucher is in the cart
- if there are products in the cart (gifts excluded)
Important note: this MUST be the last check, because if the tested cart rule has priority over a non combinable one in the cart, we will switch them
*/
$nb_products = Cart::getNbProducts($cart->id);
$otherCartRules = [];
if ($check_carrier) {
$otherCartRules = $cart->getCartRules(CartRule::FILTER_ACTION_ALL, false);
}
if (count($otherCartRules)) {
foreach ($otherCartRules as $otherCartRule) {
if ($otherCartRule['id_cart_rule'] == $this->id && !$alreadyInCart) {
return (!$display_error) ? false : $this->trans('This voucher is already in your cart', [], 'Shop.Notifications.Error');
}
$giftProductQuantity = $cart->getProductQuantity($otherCartRule['gift_product'], $otherCartRule['gift_product_attribute']);
if ($otherCartRule['gift_product'] && !empty($giftProductQuantity['quantity'])) {
--$nb_products;
}
if ($this->cart_rule_restriction && $otherCartRule['cart_rule_restriction'] && $otherCartRule['id_cart_rule'] != $this->id) {
$combinable = Db::getInstance()->getValue('
SELECT id_cart_rule_1
FROM ' . _DB_PREFIX_ . 'cart_rule_combination
WHERE (id_cart_rule_1 = ' . (int) $this->id . ' AND id_cart_rule_2 = ' . (int) $otherCartRule['id_cart_rule'] . ')
OR (id_cart_rule_2 = ' . (int) $this->id . ' AND id_cart_rule_1 = ' . (int) $otherCartRule['id_cart_rule'] . ')');
if (!$combinable) {
$cart_rule = new CartRule((int) $otherCartRule['id_cart_rule'], $cart->id_lang);
// The cart rules are not combinable and the cart rule currently in the cart has priority over the one tested
if ($cart_rule->priority <= $this->priority) {
return (!$display_error) ? false : $this->trans('This voucher is not combinable with an other voucher already in your cart: %s', [$cart_rule->name], 'Shop.Notifications.Error');
} else {
// But if the cart rule that is tested has priority over the one in the cart, we remove the one in the cart and keep this new one
$cart->removeCartRule($cart_rule->id);
}
}
}
}
}
if (!$nb_products) {
return (!$display_error) ? false : $this->trans('Cart is empty', [], 'Shop.Notifications.Error');
}
// Check if order cart rule was removed from back office
$removed_order_cartRule_id = (int) Db::getInstance()->getValue('
SELECT ocr.`id_order_cart_rule`
FROM `' . _DB_PREFIX_ . 'order_cart_rule` ocr
LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON ocr.`id_order` = o.`id_order`
WHERE ocr.`id_cart_rule` = ' . (int) $this->id . '
AND ocr.`deleted` = 1
AND o.`id_cart` = ' . $cart->id);
if ($removed_order_cartRule_id) {
return (!$display_error) ? false : $this->trans('You cannot use this voucher because it has manually been removed.', [], 'Shop.Notifications.Error');
}
if (!$display_error) {
return true;
}
}
/**
* Checks if the products chosen by the customer are usable with the cart rule.
*
* @deprecated since 1.7.4.0
* @see self::checkProductRestrictionsFromCart
*
* @param \Context $context
* @param bool $returnProducts
* @param bool $displayError
* @param bool $alreadyInCart
*
* @return array|bool|string
*
* @throws PrestaShopDatabaseException
*/
public function checkProductRestrictions(Context $context, $returnProducts = false, $displayError = true, $alreadyInCart = false)
{
return $this->checkProductRestrictionsFromCart($context->cart, $returnProducts, $displayError, $alreadyInCart);
}
/**
* Checks if the products chosen by the customer are usable with the cart rule.
*
* @param \Cart $cart
* @param bool $returnProducts [default=false]
* If true, this method will return an array of eligible products.
* Otherwise, it returns TRUE on success and string|false on errors (depending on the value of $displayError)
* @param bool $displayError [default=false]
* If true, this method will return an error message instead of FALSE on errors.
* Otherwise, it returns FALSE on errors
* @param bool $alreadyInCart
*
* @return array|bool|string
*
* @throws PrestaShopDatabaseException
*/
public function checkProductRestrictionsFromCart(Cart $cart, $returnProducts = false, $displayError = true, $alreadyInCart = false)
{
$selected_products = [];
// Check if the products chosen by the customer are usable with the cart rule
if ($this->product_restriction) {
$product_rule_groups = $this->getProductRuleGroups();
foreach ($product_rule_groups as $id_product_rule_group => $product_rule_group) {
$eligible_products_list = [];
if (isset($cart) && is_object($cart) && is_array($products = $cart->getProducts())) {
foreach ($products as $product) {
$eligible_products_list[] = (int) $product['id_product'] . '-' . (int) $product['id_product_attribute'];
}
}
if (!count($eligible_products_list)) {
return (!$displayError) ? false : $this->trans('You cannot use this voucher in an empty cart', [], 'Shop.Notifications.Error');
}
$product_rules = $this->getProductRules($id_product_rule_group);
$countRulesProduct = count($product_rules);
$condition = 0;
foreach ($product_rules as $product_rule) {
switch ($product_rule['type']) {
case 'attributes':
$cart_attributes = Db::getInstance()->executeS('
SELECT cp.quantity, cp.`id_product`, pac.`id_attribute`, cp.`id_product_attribute`
FROM `' . _DB_PREFIX_ . 'cart_product` cp
LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON cp.id_product_attribute = pac.id_product_attribute
WHERE cp.`id_cart` = ' . (int) $cart->id . '
AND cp.`id_product` IN (' . implode(',', array_map('intval', $eligible_products_list)) . ')
AND cp.id_product_attribute > 0');
$count_matching_products = 0;
$matching_products_list = [];
foreach ($cart_attributes as $cart_attribute) {
if (in_array($cart_attribute['id_attribute'], $product_rule['values'])) {
$count_matching_products += $cart_attribute['quantity'];
if (
$alreadyInCart
&& $this->gift_product == $cart_attribute['id_product']
&& $this->gift_product_attribute == $cart_attribute['id_product_attribute']) {
--$count_matching_products;
}
$matching_products_list[] = $cart_attribute['id_product'] . '-' . $cart_attribute['id_product_attribute'];
}
}
if ($count_matching_products < $product_rule_group['quantity']) {
if ($countRulesProduct === 1) {
return (!$displayError) ? false : $this->trans('You cannot use this voucher with these products', [], 'Shop.Notifications.Error');
} else {
++$condition;
break;
}
}
$eligible_products_list = $this->filterProducts($eligible_products_list, $matching_products_list, $product_rule['type']);
break;
case 'products':
$cart_products = Db::getInstance()->executeS('
SELECT cp.quantity, cp.`id_product`
FROM `' . _DB_PREFIX_ . 'cart_product` cp
WHERE cp.`id_cart` = ' . (int) $cart->id . '
AND cp.`id_product` IN (' . implode(',', array_map('intval', $eligible_products_list)) . ')');
$count_matching_products = 0;
$matching_products_list = [];