Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Init/Init.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
use Okay\Admin\Helpers\BackendOrdersHelper;
use Okay\Modules\Sviat\Promo\Services\AdminOrderPromoApplier;
use Okay\Modules\Sviat\Promo\Services\AdminPurchasePriceRounder;
use Okay\Modules\Sviat\Promo\Services\PromoDiscountForDb;
use Okay\Modules\Sviat\Promo\Services\PurchasePriceRounder;

class Init extends AbstractInit
Expand Down Expand Up @@ -237,6 +238,11 @@ public function init(): void
['class' => PromoCartHooks::class, 'method' => 'getPromoGiftPurchases']
);

$this->registerChainExtension(
['class' => DiscountsHelper::class, 'method' => 'prepareForDB'],
['class' => PromoDiscountForDb::class, 'method' => 'keepActualAmount']
);

$this->registerChainExtension(
['class' => Purchase::class, 'method' => 'getForDB'],
['class' => PurchasePriceRounder::class, 'method' => 'normalize']
Expand Down
2 changes: 1 addition & 1 deletion Init/module.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"Okay": "4.5.3",
"version": "1.0.19",
"version": "1.0.20",
"moduleName": "Promo: акції та знижки",
"vendor": {
"email": "devsviat@proton.me",
Expand Down
5 changes: 5 additions & 0 deletions Init/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Okay\Modules\Sviat\Promo\Services\CartDiscountPipeline;
use Okay\Modules\Sviat\Promo\Services\PromoFeedPriceResolver;
use Okay\Modules\Sviat\Promo\Services\PromoProductDisplayService;
use Okay\Modules\Sviat\Promo\Services\PromoDiscountForDb;
use Okay\Modules\Sviat\Promo\Services\PurchasePriceRounder;
use Okay\Modules\Sviat\Promo\Services\AdminOrderPromoApplier;
use Okay\Modules\Sviat\Promo\Services\AdminPurchasePriceRounder;
Expand Down Expand Up @@ -69,6 +70,10 @@
new SR(EntityFactory::class),
],
],
PromoDiscountForDb::class => [
'class' => PromoDiscountForDb::class,
'arguments' => [],
],
PurchasePriceRounder::class => [
'class' => PurchasePriceRounder::class,
'arguments' => [
Expand Down
41 changes: 41 additions & 0 deletions Services/PromoDiscountForDb.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace Okay\Modules\Sviat\Promo\Services;

use Okay\Core\Classes\Discount;
use Okay\Core\Modules\Extender\ExtensionInterface;

/**
* Зберігає в БД знижку, яка дає ту саму ціну при перерахунку.
*
* Форма замовлення постить усі знижки, і ядро заново рахує ціну з type і value.
* Якщо кінцеву ціну округлено, вихідний відсоток дає іншу суму, тож збереження
* замовлення без змін міняло б ціну й суму. Шлях адмін-замовлень робить те саме
* в AdminOrderPromoApplier.
*/
class PromoDiscountForDb implements ExtensionInterface
{
private const float PRECISION = 0.005;

/**
* @param array{0: object, 1: mixed} $result обʼєкт знижки для БД і переклади
*/
public function keepActualAmount(array $result, Discount $discount, $entity, $entityId): array
{
if ($discount->sign !== 'sviat_promo') {
return $result;
}

$configured = $discount->type === 'percent'
? (float) $discount->priceBeforeDiscount * (float) $discount->value / 100
: (float) $discount->value;
$actual = (float) $discount->absoluteDiscount;

if (abs($configured - $actual) > self::PRECISION) {
$result[0]->type = 'absolute';
$result[0]->value = $actual;
}

return $result;
}
}
94 changes: 94 additions & 0 deletions tests/PromoDiscountForDbTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

namespace Modules\Sviat\Promo;

use Okay\Core\Classes\Discount;
use Okay\Modules\Sviat\Promo\Services\PromoDiscountForDb;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

/** Збереження замовлення без змін не має міняти ціну, округлену акцією. */
class PromoDiscountForDbTest extends TestCase
{
private function discount(string $type, float $value, float $before, float $after, string $sign = 'sviat_promo'): Discount
{
$discount = new Discount();
$discount->sign = $sign;
$discount->type = $type;
$discount->value = $value;
$discount->priceBeforeDiscount = $before;
$discount->priceAfterDiscount = $after;
$discount->absoluteDiscount = round($before - $after, 2);

return $discount;
}

private function forDb(Discount $discount): object
{
$row = (object) ['type' => $discount->type, 'value' => $discount->value];

return new PromoDiscountForDb()->keepActualAmount([$row, []], $discount, 'purchase', 1)[0];
}

/** Те, що робить ядро при збереженні замовлення: новий Discount із рядка БД. */
private function recalculatedPrice(object $row, float $before): float
{
$restored = new Discount();
$restored->type = $row->type;
$restored->value = (float) $row->value;
$restored->calculate($before);

return round($before - $restored->absoluteDiscount, 2);
}

/** @return array<string, array{string, float, float, float}> */
public static function roundedCases(): array
{
return [
'percent rounded up' => ['percent', 8.75, 1000.0, 913.0],
'percent rounded down' => ['percent', 8.8, 1000.2, 912.0],
'fixed rounded' => ['absolute', 100.0, 1000.5, 901.0],
];
}

#[DataProvider('roundedCases')]
public function testRoundedPriceSurvivesRecalculation(string $type, float $value, float $before, float $after): void
{
$row = $this->forDb($this->discount($type, $value, $before, $after));

self::assertSame('absolute', $row->type);
self::assertSame($after, $this->recalculatedPrice($row, $before));
}

public function testExactPercentStaysPercent(): void
{
$row = $this->forDb($this->discount('percent', 10.0, 1000.0, 900.0));

self::assertSame('percent', $row->type);
self::assertSame(10.0, $row->value);
}

public function testExactFixedStaysConfigured(): void
{
$row = $this->forDb($this->discount('absolute', 100.0, 1000.0, 900.0));

self::assertSame(100.0, $row->value);
}

public function testForeignDiscountsAreLeftAlone(): void
{
$row = $this->forDb($this->discount('percent', 8.75, 1000.0, 913.0, 'coupon'));

self::assertSame('percent', $row->type);
}

public function testRegistrationPointsAtTheCoreMethod(): void
{
$init = (string) file_get_contents(__DIR__ . '/../../../../Okay/Modules/Sviat/Promo/Init/Init.php');

self::assertMatchesRegularExpression(
"/DiscountsHelper::class, 'method' => 'prepareForDB'\\],\\s*\\['class' => PromoDiscountForDb::class, 'method' => 'keepActualAmount'\\]/",
$init
);
}
}
Loading