-
Notifications
You must be signed in to change notification settings - Fork 803
/
sBasket.php
3325 lines (2914 loc) · 118 KB
/
sBasket.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
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
use Doctrine\DBAL\Connection;
use Shopware\Bundle\CartBundle\CartKey;
use Shopware\Bundle\CartBundle\CartPositionsMode;
use Shopware\Bundle\OrderBundle\Service\OrderListProductServiceInterface;
use Shopware\Bundle\StoreFrontBundle;
use Shopware\Bundle\StoreFrontBundle\Gateway\ListProductGatewayInterface;
use Shopware\Bundle\StoreFrontBundle\Service\AdditionalTextServiceInterface;
use Shopware\Bundle\StoreFrontBundle\Service\ContextServiceInterface;
use Shopware\Bundle\StoreFrontBundle\Service\ListProductServiceInterface;
use Shopware\Bundle\StoreFrontBundle\Struct\ListProduct;
use Shopware\Components\Cart\BasketHelperInterface;
use Shopware\Components\Cart\CartOrderNumberProviderInterface;
use Shopware\Components\Cart\Struct\CartItemStruct;
use Shopware\Components\Cart\Struct\DiscountContext;
use Shopware\Components\Random;
use Symfony\Component\HttpFoundation\Cookie;
/**
* Shopware Class that handles cart operations
*
* @phpstan-type BasketArray array{content?:array<array<string, mixed>>, Amount?:string, AmountNet?:string, Quantity?:int, AmountNumeric?:float, AmountNetNumeric?:float, AmountWithTax?:string, AmountWithTaxNumeric?:float}
*/
class sBasket implements \Enlight_Hook
{
/**
* Pointer to sSystem object
* Used for legacy purposes
*
* @var sSystem
*
* @deprecated
*/
public $sSYSTEM;
/**
* Database connection which used for each database operation in this class.
* Injected over the class constructor
*
* @var Enlight_Components_Db_Adapter_Pdo_Mysql
*/
private $db;
/**
* Event manager which is used for the event system of shopware.
* Injected over the class constructor
*
* @var Enlight_Event_EventManager
*/
private $eventManager;
/**
* Shopware configuration object which used for
* each config access in this class.
* Injected over the class constructor
*
* @var Shopware_Components_Config
*/
private $config;
/**
* Shopware session object.
* Injected over the class constructor
*
* @var Enlight_Components_Session_Namespace
*/
private $session;
/**
* Request wrapper object
*
* @var Enlight_Controller_Front
*/
private $front;
/**
* The snippet manager
*
* @var Shopware_Components_Snippet_Manager
*/
private $snippetManager;
/**
* Module manager for core class instances
*
* @var Shopware_Components_Modules
*/
private $moduleManager;
/**
* @var ContextServiceInterface
*/
private $contextService;
/**
* @var AdditionalTextServiceInterface
*/
private $additionalTextService;
/**
* @var Connection
*/
private $connection;
/**
* @var BasketHelperInterface
*/
private $basketHelper;
/**
* @var bool
*/
private $proportionalTaxCalculation;
/**
* @var StoreFrontBundle\Gateway\DBAL\FieldHelper
*/
private $fieldHelper;
/**
* @var OrderListProductServiceInterface
*/
private $orderListProductService;
/**
* @var CartOrderNumberProviderInterface
*/
private $cartOrderNumberProvider;
/**
* @throws \Exception
*/
public function __construct(
?Enlight_Components_Db_Adapter_Pdo_Mysql $db = null,
?Enlight_Event_EventManager $eventManager = null,
?Shopware_Components_Snippet_Manager $snippetManager = null,
?Shopware_Components_Config $config = null,
?Enlight_Components_Session_Namespace $session = null,
?Enlight_Controller_Front $front = null,
?Shopware_Components_Modules $moduleManager = null,
?sSystem $systemModule = null,
?ContextServiceInterface $contextService = null,
?AdditionalTextServiceInterface $additionalTextService = null
) {
$this->db = $db ?: Shopware()->Db();
$this->eventManager = $eventManager ?: Shopware()->Events();
$this->snippetManager = $snippetManager ?: Shopware()->Snippets();
$this->config = $config ?: Shopware()->Config();
$this->session = $session ?: Shopware()->Session();
$this->front = $front ?: Shopware()->Front();
$this->moduleManager = $moduleManager ?: Shopware()->Modules();
$this->sSYSTEM = $systemModule ?: Shopware()->System();
$this->contextService = $contextService;
$this->additionalTextService = $additionalTextService;
$this->connection = Shopware()->Container()->get(Connection::class);
if ($this->contextService === null) {
$this->contextService = Shopware()->Container()->get(ContextServiceInterface::class);
}
if ($this->additionalTextService === null) {
$this->additionalTextService = Shopware()->Container()->get(AdditionalTextServiceInterface::class);
}
if ($this->basketHelper === null) {
$this->basketHelper = Shopware()->Container()->get(BasketHelperInterface::class);
}
$this->proportionalTaxCalculation = $this->config->get('proportionalTaxCalculation');
$this->fieldHelper = Shopware()->Container()->get('shopware_storefront.field_helper_dbal');
$this->cartOrderNumberProvider = Shopware()->Container()->get(CartOrderNumberProviderInterface::class);
$this->orderListProductService = Shopware()->Container()->get(OrderListProductServiceInterface::class);
}
/**
* Get total value of current user's cart
* Used in multiple locations
*
* @return array Total amount of the user's cart
*/
public function sGetAmount()
{
$result = $this->db->fetchRow(
'SELECT SUM(quantity*(floor(price * 100 + .55)/100)) AS totalAmount
FROM s_order_basket
WHERE sessionID = ? GROUP BY sessionID',
[$this->session->get('sessionId')]
);
return $result === false ? [] : $result;
}
/**
* Get total value of current user's cart (only products)
* Used only internally in sBasket
*
* @return array Total amount of the user's cart (only products)
*/
public function sGetAmountArticles()
{
$queryBuilder = $this->connection->createQueryBuilder();
$queryBuilder->select('SUM(b.quantity*(floor(b.price * 100 + .55)/100)) AS totalAmount')
->from('s_order_basket', 'b')
->where('sessionID = :sessionId')
->andWhere('modus = 0')
->groupBy('sessionID')
->setParameter('sessionId', $this->session->get('sessionId'));
$this->eventManager->notify(
'Shopware_Modules_Basket_GetAmountArticles_QueryBuilder',
[
'queryBuilder' => $queryBuilder,
]
);
$result = $queryBuilder->execute()->fetch(\PDO::FETCH_ASSOC);
return $result === false ? [] : $result;
}
/**
* Check if all positions in cart are available
* Used in CheckoutController
*
* @return array
*/
public function sCheckBasketQuantities()
{
$result = $this->db->fetchAll(
'SELECT (d.instock - b.quantity) as diffStock, b.ordernumber,
d.laststock, IF(a.active=1, d.active, 0) as active
FROM s_order_basket b
LEFT JOIN s_articles_details d
ON d.ordernumber = b.ordernumber
AND d.articleID = b.articleID
LEFT JOIN s_articles a
ON a.id = d.articleID
WHERE b.sessionID = ?
AND b.modus = 0
GROUP BY b.ordernumber',
[$this->session->get('sessionId')]
);
$hideBasket = false;
$products = [];
foreach ($result as $product) {
if (empty($product['active'])
|| (!empty($product['laststock']) && $product['diffStock'] < 0)
) {
$hideBasket = true;
$products[$product['ordernumber']]['OutOfStock'] = true;
} else {
$products[$product['ordernumber']]['OutOfStock'] = false;
}
}
$products = $this->eventManager->filter('Shopware_Modules_Basket_CheckBasketQuantities_ProductsQuantity', $products, [
'subject' => $this,
'hideBasket' => $hideBasket,
]);
return ['hideBasket' => $hideBasket, 'articles' => $products];
}
/**
* Get cart amount for certain products / suppliers
* Used only internally in sBasket
*
* @param array|null $articles Products numbers to filter
* @param int $supplier Supplier id to filter
*
* @return array Amount of products in current basket that match the current filter
*/
public function sGetAmountRestrictedArticles($articles, $supplier)
{
if (!\is_array($articles) && empty($supplier)) {
return $this->sGetAmountArticles();
}
$extraConditions = [];
if (!empty($articles) && \is_array($articles)) {
$extraConditions[] = $this->db->quoteInto('ordernumber IN (?) ', $articles);
}
if (!empty($supplier)) {
$extraConditions[] = $this->db->quoteInto('s_articles.supplierID = ?', $supplier);
}
if (\count($extraConditions)) {
$sqlExtra = ' AND ( ' . implode(' OR ', $extraConditions) . ' ) ';
} else {
$sqlExtra = '';
}
$result = $this->db->fetchRow(
"SELECT SUM(quantity*(floor(price * 100 + .55)/100)) AS totalAmount
FROM s_order_basket, s_articles
WHERE sessionID = ?
AND modus = 0
AND s_order_basket.articleID = s_articles.id
$sqlExtra
GROUP BY sessionID",
[$this->session->get('sessionId')]
);
return $result === false ? [] : $result;
}
/**
* Update vouchers in cart
* Used only internally in sBasket
*
* @throws \Exception
* @throws \Enlight_Exception
* @throws \Enlight_Event_Exception
* @throws \Zend_Db_Adapter_Exception
*/
public function sUpdateVoucher()
{
$voucher = $this->sGetVoucher();
if ($voucher) {
$this->sDeleteArticle('voucher');
if (\is_array($this->sAddVoucher($voucher['code']))) {
$this->session->offsetSet('sBasketVoucherRemovedInCart', true);
}
}
}
/**
* Insert basket discount
* Used only internally in sBasket::sGetBasket()
*
* @throws \Enlight_Exception
* @throws \Enlight_Event_Exception
* @throws \Zend_Db_Adapter_Exception
*/
public function sInsertDiscount()
{
// Get possible discounts
$getDiscounts = $this->db->fetchAll(
'SELECT basketdiscount, basketdiscountstart
FROM s_core_customergroups_discounts
WHERE groupID = ?
ORDER BY basketdiscountstart ASC',
[$this->sSYSTEM->sUSERGROUPDATA['id']]
);
$this->db->query(
'DELETE FROM s_order_basket WHERE sessionID = ? AND modus = 3',
[$this->session->get('sessionId')]
);
// No discounts
if (!\count($getDiscounts)) {
return;
}
$sql = 'SELECT SUM(quantity*(floor(price * 100 + .55)/100)) AS totalAmount
FROM s_order_basket
WHERE sessionID = ? AND modus != 4
GROUP BY sessionID';
$params = [$this->session->get('sessionId')];
$sql = Shopware()->Events()->filter(
'Shopware_Modules_Basket_InsertDiscount_FilterSql_BasketAmount',
$sql,
['subject' => $this, 'params' => $params]
);
$basketAmount = (float) $this->db->fetchOne($sql, $params);
// If no products in basket, return
if (!$basketAmount) {
return;
}
$basketDiscount = 0.;
// Iterate through discounts and find nearly one
foreach ($getDiscounts as $discountRow) {
if ($basketAmount < $discountRow['basketdiscountstart']) {
break;
}
$basketDiscount = $discountRow['basketdiscount'];
}
if (!$basketDiscount) {
return;
}
$discount = $basketAmount / 100 * $basketDiscount;
$discount *= -1;
$discount = round($discount, 2);
$taxMode = $this->config->get('sTAXAUTOMODE');
if (!empty($taxMode)) {
$tax = $this->getMaxTax();
} else {
$tax = $this->config->get('sDISCOUNTTAX');
}
if (!$tax) {
$tax = 19;
}
if (!$this->sSYSTEM->sUSERGROUPDATA['tax'] && $this->sSYSTEM->sUSERGROUPDATA['id']) {
$discountNet = $discount;
} else {
$discountNet = round($discount / (100 + $tax) * 100, 3);
}
$this->sSYSTEM->sUSERGROUPDATA['basketdiscount'] = $basketDiscount;
$name = $this->cartOrderNumberProvider->get(CartOrderNumberProviderInterface::DISCOUNT);
$discountName = -$basketDiscount . ' % ' . $this->snippetManager
->getNamespace('backend/static/discounts_surcharges')
->get('discount_name');
$params = [
'sessionID' => $this->session->get('sessionId'),
'articlename' => $discountName,
'articleID' => 0,
'ordernumber' => $name,
'quantity' => 1,
'price' => $discount,
'netprice' => $discountNet,
'tax_rate' => $tax,
'datum' => date('Y-m-d H:i:s'),
'modus' => 3,
'currencyFactor' => $this->sSYSTEM->sCurrency['factor'],
];
$notifyUntilBeforeAdd = $this->eventManager->notifyUntil(
'Shopware_Modules_Basket_BeforeAddOrderDiscount',
[
'subject' => $this,
'discount' => $params,
]
);
if ($notifyUntilBeforeAdd) {
return;
}
if ($this->proportionalTaxCalculation && !$this->session->get('taxFree')) {
$this->basketHelper->addProportionalDiscount(
new DiscountContext(
$this->session->get('sessionId'),
BasketHelperInterface::DISCOUNT_PERCENT,
-$basketDiscount,
$discountName,
$name,
3,
$this->sSYSTEM->sCurrency['factor'],
!$this->sSYSTEM->sUSERGROUPDATA['tax'] && $this->sSYSTEM->sUSERGROUPDATA['id']
)
);
} else {
$params = $this->eventManager->filter(
'Shopware_Modules_Basket_InsertDiscount_FilterParams',
$params,
[
'subject' => $this,
'getDiscounts' => $getDiscounts,
'basketAmount' => $basketAmount,
'basketDiscount' => $basketDiscount,
]
);
$this->db->insert('s_order_basket', $params);
$this->db->insert('s_order_basket_attributes', ['basketID' => $this->db->lastInsertId()]);
}
}
/**
* Check if any discount is in the cart
* Used only internally in sBasket
*
* @return bool
*/
public function sCheckForDiscount()
{
$discount = $this->db->fetchOne(
'SELECT id FROM s_order_basket WHERE sessionID = ? AND modus = 3',
[$this->session->get('sessionId')]
);
return (bool) $discount;
}
/**
* Add premium products to cart
* Used internally in sBasket and in CheckoutController
*
* @throws \Zend_Db_Adapter_Exception
*
* @return bool|int
*/
public function sInsertPremium()
{
static $lastPremium;
$sBasketAmount = $this->sGetAmount();
$sBasketAmount = empty($sBasketAmount['totalAmount']) ? 0 : $sBasketAmount['totalAmount'];
$sBasketAmount = (float) $sBasketAmount;
$addPremium = $this->front->Request()->getQuery('sAddPremium');
if (empty($addPremium)) {
$deletePremium = $this->db->fetchCol(
'SELECT basket.id
FROM s_order_basket basket
LEFT JOIN s_articles a
ON a.id = basket.articleID
LEFT JOIN s_articles_details d
ON d.id = a.main_detail_id
LEFT JOIN s_addon_premiums premium
ON IF(a.configurator_set_id IS NULL,
premium.ordernumber_export = basket.ordernumber,
premium.ordernumber = d.ordernumber
)
AND premium.startprice <= ?
WHERE basket.modus = 1
AND premium.id IS NULL
AND basket.sessionID = ?',
[$sBasketAmount, $this->session->get('sessionId')]
);
if (empty($deletePremium)) {
return true;
}
$this->db->delete(
's_order_basket',
['id IN (?)' => $deletePremium]
);
return true;
}
if (isset($lastPremium) && $lastPremium == $addPremium) {
return false;
}
$lastPremium = $addPremium;
$this->db->delete(
's_order_basket',
[
'sessionID = ?' => $this->session->get('sessionId'),
'modus = 1',
]
);
$premium = $this->db->fetchRow(
'SELECT premium.id, detail.ordernumber, article.id as articleID, article.name as articleName,
article.main_detail_id,
detail.id as variantID, detail.additionaltext, premium.ordernumber_export,
article.configurator_set_id
FROM
s_addon_premiums premium,
s_articles_details detail,
s_articles article,
s_articles_details detail2
WHERE detail.ordernumber = ?
AND premium.startprice <= ?
AND premium.ordernumber = detail2.ordernumber
AND detail2.articleID = detail.articleID
AND detail.articleID = article.id',
[
$addPremium,
$sBasketAmount,
]
);
if (!$premium) {
return false;
}
// Load translations for product or variant
if ($premium['main_detail_id'] !== $premium['variantID']) {
$premium = $this->moduleManager->Articles()->sGetTranslation(
$premium,
$premium['variantID'],
'variant'
);
} else {
$premium = $this->moduleManager->Articles()->sGetTranslation(
$premium,
$premium['articleID'],
'article'
);
}
if ($premium['configurator_set_id'] > 0) {
$premium = $this->moduleManager->Articles()->sGetTranslation(
$premium,
$premium['variantID'],
'variant'
);
$product = new StoreFrontBundle\Struct\ListProduct(
$premium['articleID'],
$premium['variantID'],
$premium['ordernumber']
);
$product->setAdditional($premium['additionaltext']);
$context = $this->contextService->getShopContext();
$product = $this->additionalTextService->buildAdditionalText($product, $context);
$premium['additionaltext'] = $product->getAdditional();
}
if (!empty($premium['configurator_set_id'])) {
$number = $premium['ordernumber'];
} else {
$number = $premium['ordernumber_export'];
}
return $this->db->insert(
's_order_basket',
[
'sessionID' => $this->session->get('sessionId'),
'articlename' => trim($premium['articleName'] . ' ' . $premium['additionaltext']),
'articleID' => $premium['articleID'],
'ordernumber' => $number,
'quantity' => 1,
'price' => 0,
'netprice' => 0,
'tax_rate' => 0,
'datum' => new Zend_Date(),
'modus' => 1,
'currencyFactor' => $this->sSYSTEM->sCurrency['factor'],
]
);
}
/**
* Get the max tax rate in applied in the current basket
* Used in several places
*
* @return float|false May tax value, or false if none found
*/
public function getMaxTax()
{
$sessionId = $this->session->get('sessionId');
if (!\is_string($sessionId)) {
return false;
}
$qb = $this->connection->createQueryBuilder();
$qb
->select(['product.taxID'])
->from('s_order_basket', 'basket')
->join('basket', 's_articles', 'product', 'product.id = basket.articleID')
->where($qb->expr()->andX(
$qb->expr()->eq('basket.sessionID', ':sessionId'),
$qb->expr()->eq('basket.modus', CartPositionsMode::PRODUCT)
))
->orderBy('basket.tax_rate', 'DESC')
->setMaxResults(1)
->setParameter('sessionId', $sessionId)
;
$this->eventManager->notify(
'Shopware_Modules_Basket_GetMaxTax_QueryBuilder',
[
'sessionId' => $sessionId,
'queryBuilder' => $qb,
]
);
$maxTaxId = $qb->execute()->fetchOne();
if (!$maxTaxId) {
return false;
}
$tax = $this->contextService->getShopContext()->getTaxRule($maxTaxId);
return $tax->getTax();
}
/**
* Add voucher to cart
* Used in several places
*
* @param string $voucherCode Voucher code
* @param string $basket
*
* @throws \Exception
* @throws \Enlight_Exception
* @throws \Enlight_Event_Exception
* @throws \Zend_Db_Adapter_Exception
*
* @return array|bool True if successful, false if stopped by an event, array with error data if one occurred
*/
public function sAddVoucher($voucherCode, $basket = '')
{
if ($this->eventManager->notifyUntil(
'Shopware_Modules_Basket_AddVoucher_Start',
['subject' => $this, 'code' => $voucherCode, 'basket' => $basket]
)) {
return false;
}
$voucherCode = strtolower(trim(stripslashes($voucherCode)));
// Load the voucher details
$date = new DateTime();
$date = $date->format('Y-m-d');
$voucherDetails = $this->db->fetchRow(
'SELECT *
FROM s_emarketing_vouchers
WHERE modus != 1
AND LOWER(vouchercode) = :vouchercode
AND (
(valid_to >= :date OR valid_to IS NULL)
AND (valid_from <= :date OR valid_from IS NULL)
)',
['vouchercode' => $voucherCode, 'date' => $date]
) ?: [];
$individualCode = false;
$usedVoucherCount = [];
$userId = $this->session->get('sUserId');
// Check if voucher has already been cashed
$sErrorMessages = $this->filterUsedVoucher($userId, $voucherDetails);
if (!empty($sErrorMessages)) {
return ['sErrorFlag' => true, 'sErrorMessages' => $sErrorMessages];
}
if ($voucherDetails['id']) {
// If we have voucher details, it's a reusable code
// We need to check how many times it has already been used
$usedVoucherCount = $this->db->fetchRow(
'SELECT COUNT(id) AS vouchers
FROM s_order_details
WHERE articleordernumber = ?
AND s_order_details.ordernumber != \'0\'',
[$voucherDetails['ordercode']]
) ?: [];
} else {
// If we don't have voucher details yet, need to check if it's a one-time code
$voucherCodeDetails = $this->db->fetchRow(
'SELECT id, voucherID, code as vouchercode FROM s_emarketing_voucher_codes c WHERE c.code = ? AND c.cashed != 1 LIMIT 1;',
[$voucherCode]
) ?: [];
if ($voucherCodeDetails && $voucherCodeDetails['voucherID']) {
$voucherDetails = $this->db->fetchRow(
'SELECT description, numberofunits, customergroup, value, restrictarticles,
minimumcharge, shippingfree, bindtosupplier, taxconfig, valid_from,
valid_to, ordercode, modus, percental, strict, subshopID, customer_stream_ids
FROM s_emarketing_vouchers
WHERE modus = 1 AND id = :voucherId AND (
(valid_to >= :date OR valid_to IS NULL) AND (valid_from <= :date OR valid_from IS NULL)
) LIMIT 1',
['voucherId' => (int) $voucherCodeDetails['voucherID'], 'date' => $date]
) ?: [];
unset($voucherCodeDetails['voucherID']);
$voucherDetails = array_merge($voucherCodeDetails, $voucherDetails);
$individualCode = $voucherDetails && $voucherDetails['description'];
}
}
$streams = array_filter(explode('|', $voucherDetails['customer_stream_ids']));
if (!empty($streams)) {
$context = $this->contextService->getShopContext();
$allowed = array_intersect($context->getActiveCustomerStreamIds(), $streams);
if (empty($allowed)) {
$message = $this->snippetManager->getNamespace('frontend/basket/internalMessages')->get(
'VoucherFailureCustomerStreams',
'This voucher is not available for you'
);
return ['sErrorFlag' => true, 'sErrorMessages' => [$message]];
}
}
// Interrupt the operation if one of the following occurs:
// 1 - No voucher details were found (individual or reusable)
// 2 - No voucher code
// 3 - Voucher is reusable and has already been used to the limit
if (!$voucherDetails
|| !$voucherCode
|| ($voucherDetails['numberofunits'] <= $usedVoucherCount['vouchers'] && !$individualCode)
) {
$sErrorMessages[] = $this->snippetManager->getNamespace('frontend/basket/internalMessages')->get(
'VoucherFailureNotFound',
'Voucher could not be found or is not valid anymore'
);
return ['sErrorFlag' => true, 'sErrorMessages' => $sErrorMessages];
}
// If voucher is limited to a specific subshop, filter that and return on failure
$sErrorMessages = $this->filterSubShopVoucher($voucherDetails);
if (!empty($sErrorMessages)) {
return ['sErrorFlag' => true, 'sErrorMessages' => $sErrorMessages];
}
// Check if the basket already has a voucher, and break if it does
$chkBasket = $this->db->fetchRow(
'SELECT id
FROM s_order_basket
WHERE sessionID = ? AND modus = 2',
[$this->session->get('sessionId')]
);
if ($chkBasket) {
$sErrorMessages[] = $this->snippetManager->getNamespace('frontend/basket/internalMessages')->get(
'VoucherFailureOnlyOnes',
'Only one voucher can be processed in order'
);
return ['sErrorFlag' => true, 'sErrorMessages' => $sErrorMessages];
}
// Check if the voucher is limited to a certain customer group, and validate that
$sErrorMessages = $this->filterCustomerGroupVoucher($userId, $voucherDetails);
if (!empty($sErrorMessages)) {
return ['sErrorFlag' => true, 'sErrorMessages' => $sErrorMessages];
}
// Check if the voucher is limited to certain products, and validate that
[$sErrorMessages, $restrictedProducts] = $this->filterProductVoucher($voucherDetails);
if (!empty($sErrorMessages)) {
return ['sErrorFlag' => true, 'sErrorMessages' => $sErrorMessages];
}
// Check if the voucher is limited to certain supplier, and validate that
$sErrorMessages = $this->filterSupplierVoucher($voucherDetails);
if (!empty($sErrorMessages)) {
return ['sErrorFlag' => true, 'sErrorMessages' => $sErrorMessages];
}
// Calculate the amount in the basket
$restrictDiscount = !empty($voucherDetails['strict']);
$allowedSupplierId = $voucherDetails['bindtosupplier'];
if ($restrictDiscount && (!empty($restrictedProducts) || !empty($allowedSupplierId))) {
$amount = $this->sGetAmountRestrictedArticles($restrictedProducts, $allowedSupplierId);
} else {
$amount = $this->sGetAmountArticles();
}
// Including currency factor
$factor = 1;
if ($this->sSYSTEM->sCurrency['factor'] && empty($voucherDetails['percental'])) {
$factor = $this->sSYSTEM->sCurrency['factor'];
$voucherDetails['value'] *= $factor;
}
$basketValue = $amount['totalAmount'] / $factor;
// Check if the basket's value is above the voucher's
if ($basketValue < $voucherDetails['minimumcharge']) {
$snippet = $this->snippetManager->getNamespace('frontend/basket/internalMessages')->get(
'VoucherFailureMinimumCharge',
'The minimum charge for this voucher is {$sMinimumCharge|currency}'
);
$smarty = Shopware()->Container()->get(\Enlight_Template_Manager::class);
$template = $smarty->createTemplate(sprintf('string:%s', $snippet));
$template->assign('sMinimumCharge', $voucherDetails['minimumcharge']);
$sErrorMessages[] = $template->fetch();
return ['sErrorFlag' => true, 'sErrorMessages' => $sErrorMessages];
}
$timeInsert = date('Y-m-d H:i:s');
$voucherName = $this->snippetManager
->getNamespace('backend/static/discounts_surcharges')
->get('voucher_name', 'Voucher');
$voucherValue = 0.;
if ($voucherDetails['percental']) {
$voucherValue = $voucherDetails['value'];
$voucherName .= ' ' . $voucherValue . ' %';
$voucherDetails['value'] = ($amount['totalAmount'] / 100) * (float) $voucherValue;
}
// Tax calculation for vouchers
[$taxRate, $tax, $voucherDetails, $freeShipping] = $this->calculateVoucherValues($voucherDetails);
if ($this->proportionalTaxCalculation && !$this->session->get('taxFree') && $voucherDetails['taxconfig'] === 'auto') {
$taxCalculator = Shopware()->Container()->get('shopware.cart.proportional_tax_calculator');
$prices = $this->basketHelper->getPositionPrices(
new DiscountContext(
$this->session->get('sessionId'),
null,
null,
null,
null,
null,
null,
null
)
);
$hasMultipleTaxes = $taxCalculator->hasDifferentTaxes($prices);
if ($voucherDetails['percental']) {
$voucherPrices = $taxCalculator->recalculatePercentageDiscount(-$voucherValue, $prices, !$this->sSYSTEM->sUSERGROUPDATA['tax'] && $this->sSYSTEM->sUSERGROUPDATA['id']);
} else {
$voucherPrices = $taxCalculator->calculate($voucherDetails['value'], $prices, !$this->sSYSTEM->sUSERGROUPDATA['tax'] && $this->sSYSTEM->sUSERGROUPDATA['id']);
}
$voucherPrices = $this->eventManager->filter(
'Shopware_Modules_Basket_AddVoucher_VoucherPrices',
$voucherPrices,
[
'subject' => $this,
'voucher' => $voucherDetails,
'vouchername' => $voucherName,
'shippingfree' => $freeShipping,
'tax' => $tax,
'prices' => $prices,
'hasMultipleTaxes' => $hasMultipleTaxes,
]
);
foreach ($voucherPrices as $voucherPrice) {
$sql = '
INSERT INTO s_order_basket (
sessionID, articlename, articleID, ordernumber, shippingfree,
quantity, price, netprice,tax_rate, datum, modus, currencyFactor
)
VALUES (?,?,?,?,?,1,?,?,?,?,2,?)
';
$params = [
$this->session->get('sessionId'),
$voucherName . ($hasMultipleTaxes ? ' (' . $voucherPrice->getTaxRate() . '%)' : ''),
$voucherDetails['id'],
$voucherDetails['ordercode'],
$freeShipping,
$voucherPrice->getPrice(),
$voucherPrice->getNetPrice(),
$voucherPrice->getTaxRate(),
$timeInsert,
$this->sSYSTEM->sCurrency['factor'],
];
$sql = $this->eventManager->filter(
'Shopware_Modules_Basket_AddVoucher_FilterSql',
$sql,
[
'subject' => $this,
'params' => $params,
'voucher' => $voucherDetails,
'vouchername' => $voucherName,
'shippingfree' => $freeShipping,
'tax' => $tax,
]
);
$this->db->query($sql, $params);
$insertId = (int) $this->db->lastInsertId('s_order_basket');
$this->connection->insert('s_order_basket_attributes', ['basketID' => $insertId]);
}
return !empty($prices);
}
// Finally, add the discount entry to the basket
$sql = '
INSERT INTO s_order_basket (
sessionID, articlename, articleID, ordernumber, shippingfree,
quantity, price, netprice,tax_rate, datum, modus, currencyFactor
)
VALUES (?,?,?,?,?,1,?,?,?,?,2,?)
';
$params = [
$this->session->get('sessionId'),
$voucherName,
$voucherDetails['id'],
$voucherDetails['ordercode'],