-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSource.php
More file actions
923 lines (757 loc) · 29.9 KB
/
Source.php
File metadata and controls
923 lines (757 loc) · 29.9 KB
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
<?php
namespace Mygento\Discount\Generator;
abstract class Source
{
const DISCOUNT_VERSION = '1.0.15';
public static function getConstants()
{
return [
'VERSION' => self::DISCOUNT_VERSION,
'NAME_UNIT_PRICE' => 'disc_hlpr_price',
'NAME_ROW_DIFF' => 'recalc_row_diff'
];
}
public static function getPublicProperties()
{
return [];
}
public static function getProtectedProperties()
{
return [
[
'name' => 'generalHelper',
'value' => null,
'comment' => ''
],
[
'name' => '_entity',
'value' => null,
'comment' => ''
],
[
'name' => '_taxValue',
'value' => null,
'comment' => ''
],
[
'name' => '_taxAttributeCode',
'value' => null,
'comment' => ''
],
[
'name' => '_shippingTaxValue',
'value' => null,
'comment' => ''
],
[
'name' => '_discountlessSum',
'value' => 0.0,
'comment' => ''
],
[
'name' => '_wryItemUnitPriceExists',
'value' => false,
'comment' => '@var bool Does item exist with price not divisible evenly? Есть ли item, цена которого не делится нацело'
],
[
'name' => 'isSplitItemsAllowed',
'value' => false,
'comment' => '@var bool Возможность разделять одну товарную позицию на 2, если цена не делится нацело'
],
[
'name' => 'doCalculation',
'value' => true,
'comment' => '@var bool Включить перерасчет?'
],
[
'name' => 'spreadDiscOnAllUnits',
'value' => false,
'comment' => '@var bool Размазывать ли скидку по всей позициям?'
],
];
}
public static function getPrivateProperties()
{
return [];
}
abstract public function getCopyright();
public function getMethod_getRecalculated()
{
$comment = <<<'NOW'
Returns all items of the entity (order|invoice|creditmemo) with properly calculated discount and properly calculated Sum
@param %s $entity
@param string $taxValue
@param string $taxAttributeCode Set it if info about tax is stored in product in certain attr
@param string $shippingTaxValue
@return array with calculated items and sum
@throws \Exception
NOW;
$body = <<<'PHP'
if (!$entity) {
return;
}
if (!extension_loaded('bcmath')) {
$this->generalHelper->addLog('Fatal Error: bcmath php extension is not available.');
throw new \Exception('BCMath extension is not available in this PHP version.');
}
$this->_entity = $entity;
$this->_taxValue = $taxValue;
$this->_taxAttributeCode = $taxAttributeCode;
$this->_shippingTaxValue = $shippingTaxValue;
%s
$globalDiscount = $this->getGlobalDiscount();
$this->generalHelper->addLog("== START == Recalculation of entity prices. Helper Version: " . self::VERSION . ". Entity class: " . get_class($entity) . ". Entity id: {$entity->getId()}");
$this->generalHelper->addLog("Do calculation: " . ($this->doCalculation ? 'Yes' : 'No'));
$this->generalHelper->addLog("Spread discount: " . ($this->spreadDiscOnAllUnits ? 'Yes' : 'No'));
$this->generalHelper->addLog("Split items: " . ($this->isSplitItemsAllowed ? 'Yes' : 'No'));
//Если есть RewardPoints - то калькуляцию применять необходимо принудительно
if ($globalDiscount !== 0.00) {
$this->doCalculation = true;
$this->generalHelper->addLog("SplitItems and DoCalculation set to true because of global Discount (e.g. reward points)");
}
switch (true) {
case (!$this->doCalculation):
$this->generalHelper->addLog("No calculation at all.");
break;
case ($this->checkSpread()):
$this->applyDiscount();
$this->generalHelper->addLog("'Apply Discount' logic was applied");
break;
default:
//Это случай, когда не нужно размазывать копейки по позициям
//и при этом, позиции могут иметь скидки, равномерно делимые.
$this->setSimplePrices();
$this->generalHelper->addLog("'Simple prices' logic was applied");
break;
}
$this->generalHelper->addLog("== STOP == Recalculation. Entity class: " . get_class($entity) . ". Entity id: {$entity->getId()}");
return $this->buildFinalArray();
PHP;
return [
'comments' => $comment,
'params' => [
'entity' => 'none',
'taxValue' => '',
'taxAttributeCode' => '',
'shippingTaxValue' => '',
],
'body' => $body
];
}
public function getMethod_applyDiscount()
{
$comment = <<<'NOW'
@SuppressWarnings(PHPMD.CyclomaticComplexity)
@SuppressWarnings(PHPMD.NPathComplexity)
NOW;
$body = <<<'PHP'
$subTotal = $this->_entity->getData('subtotal_incl_tax');
$discount = $this->_entity->getData('discount_amount');
/** @var float $superGrandDiscount Скидка на весь заказ. Например, rewardPoints или storeCredit */
$superGrandDiscount = $this->getGlobalDiscount();
//Bug NN-347. -1 коп в доставке, если Magento неверно посчитала grandTotal заказа
if ($superGrandDiscount && abs($superGrandDiscount) < 10.00) {
$this->preFixLowDiscount();
$superGrandDiscount = 0.00;
}
$grandDiscount = $superGrandDiscount;
//Если размазываем скидку - то размазываем всё: (скидки товаров + $superGrandDiscount)
if ($this->spreadDiscOnAllUnits) {
$grandDiscount = $discount + $this->getGlobalDiscount();
}
$percentageSum = 0;
$items = $this->getAllItems();
$itemsSum = 0.00;
foreach ($items as $item) {
if (!$this->isValidItem($item)) {
continue;
}
$price = $item->getData('price_incl_tax');
$qty = $item->getQty() ?: $item->getQtyOrdered();
$rowTotal = $item->getData('row_total_incl_tax');
$rowDiscount = round((-1.00) * $item->getDiscountAmount(), 2);
// ==== Start Calculate Percentage. The heart of logic. ====
/** @var float $denominator Это знаменатель дроби (rowTotal/сумма).
* Если скидка должна распространиться на все позиции - то это subTotal.
* Если же позиции без скидок должны остаться без изменений - то это
* subTotal за вычетом всех позиций без скидок.*/
$denominator = $subTotal - $this->_discountlessSum;
if ($this->spreadDiscOnAllUnits || ($subTotal == $this->_discountlessSum) || ($superGrandDiscount !== 0.00)) {
$denominator = $subTotal;
}
$rowPercentage = $rowTotal / $denominator;
// ==== End Calculate Percentage. ====
if (!$this->spreadDiscOnAllUnits && ($rowDiscount === 0.00) && ($superGrandDiscount === 0.00)) {
$rowPercentage = 0;
}
$percentageSum += $rowPercentage;
if ($this->spreadDiscOnAllUnits) {
$rowDiscount = 0;
}
$discountPerUnit = $this->slyCeil(($rowDiscount + $rowPercentage * $grandDiscount) / $qty);
$priceWithDiscount = bcadd($price, $discountPerUnit, 2);
//Set Recalculated unit price for the item
$item->setData(self::NAME_UNIT_PRICE, $priceWithDiscount);
$rowTotalNew = round($priceWithDiscount * $qty, 2);
$itemsSum += $rowTotalNew;
$rowDiscountNew = $rowDiscount + round($rowPercentage * $grandDiscount, 2);
$rowDiff = round($rowTotal + $rowDiscountNew - $rowTotalNew, 2) * 100;
$item->setData(self::NAME_ROW_DIFF, $rowDiff);
}
if ($this->spreadDiscOnAllUnits && $this->isSplitItemsAllowed) {
$this->postFixLowDiscount();
}
$this->generalHelper->addLog("Sum of all percentages: {$percentageSum}");
PHP;
return [
'comments' => $comment,
'params' => [],
'body' => $body
];
}
public function getMethod_getGlobalDiscount()
{
$comment = <<<'NOW'
Возвращает скидку на весь заказ (если есть). Например, rewardPoints или storeCredit.
Если нет скидки - возвращает 0.00
@return float
NOW;
$body = <<<'PHP'
$items = $this->getAllItems();
$totalItemsSum = 0;
foreach ($items as $item) {
$totalItemsSum += $item->getData('row_total_incl_tax');
}
$shippingAmount = $this->_entity->getData('shipping_incl_tax');
$grandTotal = $this->getGrandTotal();
$discount = round($this->_entity->getData('discount_amount'), 2);
$globDisc = round($grandTotal - $shippingAmount - $totalItemsSum - $discount, 2);
return $globDisc;
PHP;
return [
'comments' => $comment,
'params' => [],
'body' => $body,
'visibility' => 'protected'
];
}
public function getMethod_setSimplePrices()
{
$comment = <<<'NOW'
If everything is evenly divisible - set up prices without extra recalculations
like applyDiscount() method does.
NOW;
$body = <<<'PHP'
$items = $this->getAllItems();
foreach ($items as $item) {
if (!$this->isValidItem($item)) {
continue;
}
$qty = $item->getQty() ?: $item->getQtyOrdered();
$rowTotal = $item->getData('row_total_incl_tax');
$priceWithDiscount = ($rowTotal - $item->getData('discount_amount')) / $qty;
$item->setData(self::NAME_UNIT_PRICE, $priceWithDiscount);
}
PHP;
return [
'comments' => $comment,
'params' => [],
'body' => $body
];
}
public function getMethod_preFixLowDiscount()
{
$comment = <<<'NOW'
Calculates extra discounts and adds them to items $item->setData('discount_amount', ...)
@return int count of iterations
NOW;
$body = <<<'PHP'
$items = $this->getAllItems();
$globalDiscount = $this->getGlobalDiscount();
$sign = $globalDiscount / abs($globalDiscount);
$i = abs($globalDiscount) * 100;
$count = count($items);
$iter = 0;
while ($i > 0) {
$item = current($items);
$itDisc = $item->getData('discount_amount');
$itTotal = $item->getData('row_total_incl_tax');
$inc = $this->getDiscountIncrement($sign * $i, $count, $itTotal, $itDisc);
$item->setData('discount_amount', $itDisc - $inc / 100);
$i = (int)($i - abs($inc));
$next = next($items);
if (!$next) {
reset($items);
}
$iter++;
}
return $iter;
PHP;
return [
'comments' => $comment,
'params' => [],
'body' => $body,
'visibility' => 'protected',
];
}
public function getMethod_postFixLowDiscount()
{
$comment = <<<'NOW'
Calculates extra discounts and adds them to items rowDiscount value
@return int count of iterations
NOW;
$body = <<<'PHP'
$items = $this->getAllItems();
$grandTotal = $this->getGrandTotal();
$shippingAmount = $this->_entity->getData('shipping_incl_tax');
$newItemsSum = 0;
$rowDiffSum = 0;
foreach ($items as $item) {
$rowTotalNew = $item->getData(self::NAME_UNIT_PRICE) * $item->getQty() + ($item->getData(self::NAME_ROW_DIFF) / 100);
$rowDiffSum += $item->getData(self::NAME_ROW_DIFF);
$newItemsSum += $rowTotalNew;
}
$lostDiscount = round($grandTotal - $shippingAmount - $newItemsSum, 2);
$sign = $lostDiscount / abs($lostDiscount);
$i = abs($lostDiscount) * 100;
$count = count($items);
$iter = 0;
while ($i > 0) {
$item = current($items);
$qty = $item->getQty() ?: $item->getQtyOrdered();
$rowDiff = $item->getData(self::NAME_ROW_DIFF);
$itTotalNew = $item->getData(self::NAME_UNIT_PRICE) * $qty + $rowDiff / 100;
$inc = $this->getDiscountIncrement($sign * $i, $count, $itTotalNew, 0);
$item->setData(self::NAME_ROW_DIFF, $item->getData(self::NAME_ROW_DIFF) + $inc);
$i = (int)($i - abs($inc));
$next = next($items);
if (!$next) {
reset($items);
}
$iter++;
}
return $iter;
PHP;
return [
'comments' => $comment,
'params' => [],
'body' => $body,
'visibility' => 'protected',
];
}
public function getMethod_getDiscountIncrement()
{
$comment = <<<'NOW'
Calculates how many kopeyki can be added to item
considering number of items, rowTotal and rowDiscount
@param int $amountToSpread (in kops)
@param $itemsCount
@param $itemTotal
@param $itemDiscount
@return int
NOW;
$body = <<<'PHP'
$sign = $amountToSpread / abs($amountToSpread);
//Пытаемся размазать поровну
$discPerItem = (int)(abs($amountToSpread) / $itemsCount);
$inc = ($discPerItem > 1) && ($itemTotal - $itemDiscount) > $discPerItem
? $sign * $discPerItem
: $sign;
//Изменяем скидку позиции
if (($itemTotal - $itemDiscount) > abs($inc)) {
return $inc;
}
return 0;
PHP;
return [
'comments' => $comment,
'params' => [
'amountToSpread' => 'none',
'itemsCount' => 'none',
'itemTotal' => 'none',
'itemDiscount' => 'none',
],
'body' => $body,
'visibility' => 'public'
];
}
public function getMethod_buildFinalArray()
{
$body = <<<'PHP'
$grandTotal = $this->getGrandTotal();
$items = $this->getAllItems();
$itemsFinal = [];
$itemsSum = 0.00;
foreach ($items as $item) {
if (!$this->isValidItem($item)) {
continue;
}
$splitedItems = $this->getProcessedItem($item);
$itemsFinal = array_merge($itemsFinal, $splitedItems);
}
//Calculate sum
foreach ($itemsFinal as $item) {
$itemsSum += $item['sum'];
}
$receipt = [
'sum' => $itemsSum,
'origGrandTotal' => $grandTotal
];
$shippingAmount = $this->_entity->getData('shipping_incl_tax') + 0.00;
$itemsSumDiff = round($this->slyFloor($grandTotal - $itemsSum - $shippingAmount, 3), 2);
$this->generalHelper->addLog("Items sum: {$itemsSum}. Shipping increase: {$itemsSumDiff}");
$shippingItem = [
'name' => $this->getShippingName($this->_entity),
'price' => $shippingAmount + $itemsSumDiff,
'quantity' => 1.0,
'sum' => $shippingAmount + $itemsSumDiff,
'tax' => $this->_shippingTaxValue,
];
$itemsFinal['shipping'] = $shippingItem;
$receipt['items'] = $itemsFinal;
if (!$this->_checkReceipt($receipt)) {
$this->generalHelper->addLog("WARNING: Calculation error! Sum of items is not equal to grandTotal!");
}
$this->generalHelper->addLog("Final array:");
$this->generalHelper->addLog($receipt);
%s
PHP;
return [
'comments' => '',
'params' => [],
'body' => $body
];
}
public function getMethod__buildItem()
{
$body = <<<'PHP'
$qty = $item->getQty() ?: $item->getQtyOrdered();
if (!$qty) {
throw new \Exception('Divide by zero. Qty of the item is equal to zero! Item: ' . $item->getId());
}
$entityItem = [
'price' => round($price, 2),
'name' => $item->getName(),
'quantity' => round($qty, 2),
'sum' => round($price * $qty, 2),
'tax' => $taxValue,
];
if (!$this->doCalculation) {
$entityItem['sum'] = round($item->getData('row_total_incl_tax') - $item->getData('discount_amount'), 2);
$entityItem['price'] = 1;
}
$this->generalHelper->addLog("Item calculation details:");
$this->generalHelper->addLog("Item id: {$item->getId()}. Orig price: {$price} Item rowTotalInclTax: {$item->getData('row_total_incl_tax')} PriceInclTax of 1 piece: {$price}. Result of calc:");
$this->generalHelper->addLog($entityItem);
return $entityItem;
PHP;
return [
'comments' => '',
'params' => [
'item' => 'none',
'price' => 'none',
'taxValue' => '',
],
'body' => $body,
'visibility' => 'protected'
];
}
public function getMethod_getProcessedItem()
{
$comment = <<<'NOW'
Make item array and split (if needed) it into 2 items with different prices
@param type $item
@return array
NOW;
$body = <<<'PHP'
$final = [];
$taxValue = $this->_taxAttributeCode ? $this->addTaxValue($this->_taxAttributeCode, $this->_entity, $item) : $this->_taxValue;
$price = !is_null($item->getData(self::NAME_UNIT_PRICE)) ? $item->getData(self::NAME_UNIT_PRICE) : $item->getData('price_incl_tax');
$entityItem = $this->_buildItem($item, $price, $taxValue);
$rowDiff = $item->getData(self::NAME_ROW_DIFF);
if (!$rowDiff || !$this->isSplitItemsAllowed || !$this->doCalculation) {
$final[$item->getId()] = $entityItem;
return $final;
}
$qty = $item->getQty() ?: $item->getQtyOrdered();
/** @var int $qtyUpdate Сколько товаров из ряда нуждаются в увеличении цены
* Если $qtyUpdate =0 - то цена всех товаров должна быть увеличина
*/
$qtyUpdate = $rowDiff % $qty;
//2 кейса:
//$qtyUpdate == 0 - то всем товарам увеличить цену, не разделяя.
//$qtyUpdate > 0 - считаем сколько товаров будут увеличены
/** @var int "$inc + 1 коп" На столько должны быть увеличены цены */
$inc = (int)($rowDiff / $qty);
$this->generalHelper->addLog("Item {$item->getId()} has rowDiff={$rowDiff}.");
$this->generalHelper->addLog("qtyUpdate={$qtyUpdate}. inc={$inc} kop.");
$item1 = $entityItem;
$item2 = $entityItem;
$item1['price'] = $item1['price'] + $inc / 100;
$item1['quantity'] = $qty - $qtyUpdate;
$item1['sum'] = round($item1['quantity'] * $item1['price'], 2);
if ($qtyUpdate == 0) {
$final[$item->getId()] = $item1;
return $final;
}
$item2['price'] = $item2['price'] + 0.01 + $inc / 100;
$item2['quantity'] = $qtyUpdate;
$item2['sum'] = round($item2['quantity'] * $item2['price'], 2);
$final[$item->getId() . '_1'] = $item1;
$final[$item->getId() . '_2'] = $item2;
return $final;
PHP;
return [
'comments' => $comment,
'params' => [
'item' => 'none',
],
'body' => $body
];
}
public function getMethod_getShippingName()
{
$body = <<<'PHP'
return $entity->getShippingDescription()
?: ($entity->getOrder() ? $entity->getOrder()->getShippingDescription() : '');
PHP;
return [
'comments' => '',
'params' => [
'entity' => 'none',
],
'body' => $body
];
}
public function getMethod__checkReceipt()
{
$comment = <<<'NOW'
Validation method. It sums up all items and compares it to grandTotal.
@param array $receipt
@return bool True if all items price equal to grandTotal. False - if not.
NOW;
$body = <<<'PHP'
$sum = array_reduce($receipt['items'], function ($carry, $item) {
$carry += $item['sum'];
return $carry;
});
return bcsub($sum, $receipt['origGrandTotal'], 2) === '0.00';
PHP;
return [
'comments' => $comment,
'params' => [
'receipt' => 'none',
],
'body' => $body,
'visibility' => 'protected'
];
}
public function getMethod_isValidItem()
{
$body = <<<'PHP'
return $item->getData('row_total_incl_tax') !== null;
PHP;
return [
'comments' => '',
'params' => [
'item' => 'none',
],
'body' => $body
];
}
public function getMethod_slyFloor()
{
$body = <<<'PHP'
$factor = 1.00;
$divider = pow(10, $precision);
if ($val < 0) {
$factor = -1.00;
}
return (floor(abs($val) * $divider) / $divider) * $factor;
PHP;
return [
'comments' => '',
'params' => [
'val' => 'none',
'precision' => 2,
],
'body' => $body
];
}
public function getMethod_slyCeil()
{
$body = <<<'PHP'
$factor = 1.00;
$divider = pow(10, $precision);
if ($val < 0) {
$factor = -1.00;
}
return (ceil(abs($val) * $divider) / $divider) * $factor;
PHP;
return [
'comments' => '',
'params' => [
'val' => 'none',
'precision' => 2,
],
'body' => $body
];
}
public function getMethod_addTaxValue()
{
$body = <<<'PHP'
if (!$taxAttributeCode) {
return '';
}
%s
PHP;
return [
'comments' => '',
'params' => [
'taxAttributeCode' => 'none',
'entity' => 'none',
'item' => 'none',
],
'body' => $body,
'visibility' => 'protected'
];
}
public function getMethod_checkSpread()
{
$comment = <<<'NOW'
It checks do we need to spread discount on all units and sets flag $this->spreadDiscOnAllUnits
@return bool
NOW;
$body = <<<'PHP'
$items = $this->getAllItems();
$this->_discountlessSum = 0.00;
foreach ($items as $item) {
$qty = $item->getQty() ?: $item->getQtyOrdered();
$rowPrice = $item->getData('row_total_incl_tax') - $item->getData('discount_amount');
if ((float)$item->getData('discount_amount') === 0.00) {
$this->_discountlessSum += $item->getData('row_total_incl_tax');
}
/* Означает, что есть item, цена которого не делится нацело*/
if (!$this->_wryItemUnitPriceExists) {
$decimals = $this->getDecimalsCountAfterDiv($rowPrice, $qty);
$this->_wryItemUnitPriceExists = $decimals > 2 ? true : false;
}
}
//Есть ли общая скидка на Чек. bccomp returns 0 if operands are equal
if (bccomp($this->getGlobalDiscount(), 0.00, 2) !== 0) {
$this->generalHelper->addLog("1. Global discount on whole cheque.");
return true;
}
//ok, есть товар, который не делится нацело
if ($this->_wryItemUnitPriceExists) {
$this->generalHelper->addLog("2. Item with price which is not divisible evenly.");
return true;
}
if ($this->spreadDiscOnAllUnits) {
$this->generalHelper->addLog("3. SpreadDiscount = Yes.");
return true;
}
return false;
PHP;
return [
'comments' => $comment,
'params' => [],
'body' => $body
];
}
public function getMethod_getDecimalsCountAfterDiv()
{
$body = <<<'PHP'
$divRes = (string)round($x / $y, 20);
$decimals = strrchr($divRes, '.') ? strlen(strrchr($divRes, '.')) - 1 : 0;
return $decimals;
PHP;
return [
'comments' => '',
'params' => [
'x' => 'none',
'y' => 'none',
],
'body' => $body
];
}
public function getMethod_getAllItems()
{
$body = <<<'PHP'
return $this->_entity->getAllVisibleItems()
? $this->_entity->getAllVisibleItems()
: $this->_entity->getAllItems();
PHP;
return [
'comments' => '',
'params' => [],
'body' => $body
];
}
public function getMethod_setIsSplitItemsAllowed()
{
$comment = <<<'NOW'
@param bool $isSplitItemsAllowed
NOW;
$body = <<<'PHP'
$this->isSplitItemsAllowed = (bool)$isSplitItemsAllowed;
PHP;
return [
'comments' => $comment,
'params' => [
'isSplitItemsAllowed' => 'none'
],
'body' => $body
];
}
public function getMethod_setDoCalculation()
{
$comment = <<<'NOW'
@param bool $doCalculation
NOW;
$body = <<<'PHP'
$this->doCalculation = (bool)$doCalculation;
PHP;
return [
'comments' => $comment,
'params' => [
'doCalculation' => 'none'
],
'body' => $body
];
}
public function getMethod_setSpreadDiscOnAllUnits()
{
$comment = <<<'NOW'
@param bool $spreadDiscOnAllUnits
NOW;
$body = <<<'PHP'
$this->spreadDiscOnAllUnits = (bool)$spreadDiscOnAllUnits;
PHP;
return [
'comments' => $comment,
'params' => [
'spreadDiscOnAllUnits' => 'none'
],
'body' => $body
];
}
public function getMethod_getGrandTotal()
{
$comment = "Workaround to use GiftCards";
$body = <<<'PHP'
return round(
$this->_entity->getData('grand_total') + $this->_entity->getData(
'gift_cards_amount'
),
2
);
PHP;
return [
'comments' => $comment,
'params' => [],
'body' => $body,
'visibility' => 'protected',
];
}
}