feat(domain): introduce DiscountRate VO and eliminate float rounding in pricing calculations

This commit is contained in:
Jérémy Munsch 2026-10-03 11:30:52 +02:00
parent 4165bfecb5
commit 17f898e3f9
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
21 changed files with 387 additions and 92 deletions

View file

@ -111,7 +111,7 @@ class StoreDiscountRequest extends FormRequest
'type' => ['required', new Enum(DiscountType::class)],
'value' => [
'required',
'numeric',
'integer',
'min:0',
Rule::when(
$this->input('type') == DiscountType::PERCENT->value(),

View file

@ -46,7 +46,7 @@ class BasketProductResource extends JsonResource
url($this->basketProduct->picture) : null,
'description' => $this->basketProduct->description,
'weight_variable' => $this->basketProduct->weightVariable,
'discountRate' => $this->basketProduct->discountRate,
'discountRate' => $this->basketProduct->discountRate->ratio(),
'taxRate' => $this->basketProduct->taxRate->percent(),
'weightGrams' => $this->basketProduct->weightGrams,

View file

@ -39,10 +39,21 @@ enum TaxRate: int
return $this->percent() / 100;
}
/**
* Exact decimal multiplier (1 + rate), as a string to avoid any float rounding.
*
* @return numeric-string
*/
public function multiplier(): string
{
return match ($this) {
self::TVA_20 => '1.2',
self::TVA_5_5 => '1.055',
};
}
public function applyTo(Money $price): Money
{
$multiplier = (string) (1 + $this->rate());
return $price->multiply($multiplier, PricingService::ROUNDING);
return $price->multiply($this->multiplier(), PricingService::ROUNDING);
}
}

View file

@ -28,7 +28,7 @@ final readonly class BasketProduct
public ?string $picture,
public ?string $description,
public bool $weightVariable,
public float $discountRate,
public DiscountRate $discountRate,
public Money $priceKgTtc,
/** @var array<string,mixed> */
public array $options = []
@ -51,9 +51,6 @@ final readonly class BasketProduct
if (! $priceKgTtc->isPositive()) {
throw new \DomainException('priceKgTtc has to be positive');
}
if ($discountRate < 0 || $discountRate > 1) {
throw new \DomainException('discountRate has to be between 0 and 1');
}
}
public function unitPriceHt(): Money

View file

@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
namespace Domain\Models\ValueObjects;
use Money\Money;
use Webmozart\Assert\Assert;
/**
* Taux de remise exprimé en points de base (1 bp = 0,01 %), pour éviter toute imprécision en virgule flottante.
*/
final readonly class DiscountRate implements \Stringable
{
public const MAX_BASIS_POINTS = 10000;
public function __construct(
private int $basisPoints
) {
Assert::range($basisPoints, 0, self::MAX_BASIS_POINTS, 'Discount rate has to be between 0 and 100 percent.');
}
public static function zero(): self
{
return new self(0);
}
public static function fromBasisPoints(int $basisPoints): self
{
return new self($basisPoints);
}
/** @param int|float $percentage Percentage between 0 and 100 (ex: 15 for 15 %) */
public static function fromPercentage(int | float $percentage): self
{
return new self((int) round($percentage * 100));
}
/** @param float $ratio Ratio between 0 and 1 (ex: 0.15 for 15 %) */
public static function fromRatio(float $ratio): self
{
return new self((int) round($ratio * self::MAX_BASIS_POINTS));
}
/**
* Computes the effective rate represented by a fixed discount amount on a base price.
* The result is capped at 100 %.
*/
public static function fromAmounts(Money $discountAmount, Money $basePrice): self
{
if (! $basePrice->isPositive() || ! $discountAmount->isPositive()) {
return self::zero();
}
$basisPoints = intdiv(
((int) $discountAmount->getAmount() * self::MAX_BASIS_POINTS * 2) + (int) $basePrice->getAmount(),
(int) $basePrice->getAmount() * 2
);
return new self(min($basisPoints, self::MAX_BASIS_POINTS));
}
public function basisPoints(): int
{
return $this->basisPoints;
}
/** Ratio between 0.0 and 1.0 */
public function ratio(): float
{
return $this->basisPoints / self::MAX_BASIS_POINTS;
}
/** Percentage between 0.0 and 100.0 */
public function percentage(): float
{
return $this->basisPoints / 100;
}
public function isZero(): bool
{
return $this->basisPoints === 0;
}
public function equals(self $other): bool
{
return $this->basisPoints === $other->basisPoints;
}
/**
* Returns the discount amount produced by this rate on the given amount.
*
* @param Money::ROUND_* $roundingMode
*/
public function applyTo(Money $amount, int $roundingMode = Money::ROUND_UP): Money
{
return $amount->multiply((string) $this->basisPoints)->divide(self::MAX_BASIS_POINTS, $roundingMode);
}
#[\Override]
public function __toString(): string
{
return rtrim(rtrim(number_format($this->percentage(), 2, '.', ''), '0'), '.') . ' %';
}
}

View file

@ -15,7 +15,7 @@ final readonly class ProductPricing
private Money $discountedPriceHt,
private Money $discountedPriceTtc,
private Money $priceKgTtc,
public float $discountRate,
public DiscountRate $discountRate,
public bool $hasDiscount
) {
if ($basePriceHt->isNegative()) {
@ -36,9 +36,6 @@ final readonly class ProductPricing
if ($priceKgTtc->isNegative()) {
throw new \DomainException('priceKgTtc cannot be negative');
}
if ($discountRate < 0) {
throw new \DomainException('discountRate cannot be negative');
}
}
public function basePriceHt(): Money

View file

@ -8,6 +8,7 @@ use Domain\Enums\SellUnit;
use Domain\Enums\TaxRate;
use Domain\Enums\Units\InvoicingUnit;
use Domain\Models\Entities\Product;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\ProductPricing;
use Money\Money;
@ -15,6 +16,8 @@ class PricingService
{
public const ROUNDING = Money::ROUND_UP;
private const GRAMS_PER_KG = 1000;
public function calculateForProduct(Product $product): ProductPricing
{
$basePriceHt = $this->priceHt($product);
@ -44,7 +47,10 @@ class PricingService
private function priceHt(Product $product): Money
{
if ($product->invoicing_unit === InvoicingUnit::KGM && $product->sell_unit === SellUnit::PCE && $product->product_weight) {
return $product->price->multiply(strval($product->product_weight->toGrams() / 1000), PricingService::ROUNDING);
// * Price per kg => price of the piece: price × grams ÷ 1000 (single rounding, no float)
return $product->price
->multiply($product->product_weight->toGrams())
->divide(self::GRAMS_PER_KG, PricingService::ROUNDING);
}
return $product->price;
@ -57,9 +63,10 @@ class PricingService
$grams = $product->product_weight?->toGrams() ?? 0;
if ($grams > 0 && $product->status && $product->invoicing_unit === InvoicingUnit::PCE) {
$ratio = 1000 / $grams;
return $priceTtc->multiply((string) $ratio, self::ROUNDING);
// * Price of the piece => price per kg: price × 1000 ÷ grams (single rounding, no float)
return $priceTtc
->multiply(self::GRAMS_PER_KG)
->divide($grams, self::ROUNDING);
}
return $priceTtc;
@ -70,18 +77,14 @@ class PricingService
return $taxRate->applyTo($price);
}
private function calculateDiscountRate(Money $priceHt, Money $discountAmount, Product $product): float
private function calculateDiscountRate(Money $priceHt, Money $discountAmount, Product $product): DiscountRate
{
$discount = $product->validDiscount;
if ($discount?->isPercentage()) {
return $discount->getPercentageRate();
return DiscountRate::fromPercentage($discount->getPercentage());
}
if ($priceHt->isPositive()) {
return (float) ($discountAmount->getAmount() * 100) / (float) $priceHt->getAmount();
}
return 0.0;
return DiscountRate::fromAmounts($discountAmount, $priceHt);
}
}

View file

@ -9,6 +9,7 @@ use Domain\Enums\TaxRate;
use Domain\Enums\Units\OrderUnit;
use Domain\Models\Entities\Basket;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\ProductId;
use Domain\Models\ValueObjects\IncoId;
@ -40,7 +41,7 @@ class BasketSerializer
'picture' => $item->picture,
'description' => $item->description,
'weightVariable' => $item->weightVariable,
'discountRate' => $item->discountRate,
'discountRateBp' => $item->discountRate->basisPoints(),
'priceKgTtc' => $item->priceKgTtc,
'options' => $item->options,
],
@ -75,8 +76,7 @@ class BasketSerializer
$picture = Arr::get($itemData, 'picture');
$description = Arr::get($itemData, 'description');
$weightVariable = Arr::boolean($itemData, 'weightVariable');
$discountRateVal = Arr::get($itemData, 'discountRate', 0.0);
$discountRate = is_numeric($discountRateVal) ? (float) $discountRateVal : 0.0;
$discountRate = $this->hydrateDiscountRate($itemData);
$priceKgTtc = Arr::array($itemData, 'priceKgTtc');
$priceKgTtcCurrency = Arr::string($priceKgTtc, 'currency');
$options = Arr::array($itemData, 'options', []);
@ -126,4 +126,24 @@ class BasketSerializer
items: $hydratedItems
);
}
/**
* Reads the discount rate in basis points; falls back to the legacy float ratio
* (key "discountRate") stored in sessions created before the DiscountRate value object.
*
* @param array<array-key,mixed> $itemData
*/
private function hydrateDiscountRate(array $itemData): DiscountRate
{
$basisPoints = Arr::get($itemData, 'discountRateBp');
if (is_int($basisPoints)) {
return DiscountRate::fromBasisPoints($basisPoints);
}
$legacyRatio = Arr::get($itemData, 'discountRate', 0.0);
return is_numeric($legacyRatio)
? DiscountRate::fromRatio(min(max((float) $legacyRatio, 0.0), 1.0))
: DiscountRate::zero();
}
}

View file

@ -6,6 +6,7 @@ use App\Models\Product;
use Domain\Enums\Units\OrderUnit;
use Domain\Models\Entities\Product as DomainProduct;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Entities\ProductId;
use Domain\Models\ValueObjects\ProductPricing;
use Domain\Services\PricingService;
@ -92,7 +93,7 @@ it('retrieves a basket product', function () {
discountedPriceHt: new Money(90, $currency),
discountedPriceTtc: new Money(108, $currency),
priceKgTtc: new Money(5, $currency),
discountRate: 0.1,
discountRate: DiscountRate::fromRatio(0.1),
hasDiscount: true
);

View file

@ -9,6 +9,7 @@ use Domain\Enums\TaxRate;
use Domain\Enums\Units\OrderUnit;
use Domain\Models\Entities\Basket;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\ProductId;
use Domain\Models\ValueObjects\IncoId;
@ -66,7 +67,7 @@ describe('SessionBasketRepository', function () {
->and($retrievedProduct->picture)->toBe($product->picture)
->and($retrievedProduct->description)->toBe($product->description)
->and($retrievedProduct->weightVariable)->toBe($product->weightVariable)
->and($retrievedProduct->discountRate)->toBe($product->discountRate)
->and($retrievedProduct->discountRate->basisPoints())->toBe($product->discountRate->basisPoints())
->and($retrievedProduct->priceKgTtc->getAmount())->toBe($product->priceKgTtc->getAmount())
->and($retrievedProduct->options)->toBe($product->options);
})->with([
@ -85,7 +86,7 @@ describe('SessionBasketRepository', function () {
picture: 'poulet.jpg',
description: 'Un bon poulet',
weightVariable: true,
discountRate: 0.05,
discountRate: DiscountRate::fromRatio(0.05),
priceKgTtc: new Money(1500, new Currency('EUR')),
options: ['cut' => 'halves']
),
@ -104,7 +105,7 @@ describe('SessionBasketRepository', function () {
picture: null,
description: null,
weightVariable: false,
discountRate: 0.0,
discountRate: DiscountRate::fromRatio(0.0),
priceKgTtc: new Money(400, new Currency('EUR')),
options: []
),

View file

@ -8,6 +8,7 @@ use App\Policies\Frontend\BasketPolicy;
use Domain\Enums\TaxRate;
use Domain\Enums\Units\OrderUnit;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Entities\ProductId;
use Domain\Services\ProductAvailabilityService;
use Money\Money;
@ -32,7 +33,7 @@ function createDummyBasketProduct(): BasketProduct
null,
null,
false,
0.0,
DiscountRate::zero(),
Money::EUR(1000)
);
}

View file

@ -9,6 +9,7 @@ use Domain\Enums\TaxRate;
use Domain\Enums\Units\OrderUnit;
use Domain\Models\Entities\Basket;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\ProductId;
use Domain\Models\ValueObjects\IncoId;
@ -34,7 +35,7 @@ describe('Basket and BasketProduct', function (): void {
'picture' => 'images/poulet.jpg',
'description' => 'Un bon poulet rôti',
'weightVariable' => true,
'discountRate' => 0.2,
'discountRate' => DiscountRate::fromRatio(0.2),
'priceKgTtc' => Money::EUR(1500),
'options' => ['extra' => 'crispy'],
], $overrides);
@ -67,7 +68,7 @@ describe('Basket and BasketProduct', function (): void {
picture: 'images/poulet.jpg',
description: 'Un bon poulet rôti',
weightVariable: true,
discountRate: 0.2,
discountRate: DiscountRate::fromRatio(0.2),
priceKgTtc: $priceKgTtc,
options: ['extra' => 'crispy']
);
@ -87,7 +88,7 @@ describe('Basket and BasketProduct', function (): void {
expect($item->picture)->toBe('images/poulet.jpg');
expect($item->description)->toBe('Un bon poulet rôti');
expect($item->weightVariable)->toBeTrue();
expect($item->discountRate)->toBe(0.2);
expect($item->discountRate->basisPoints())->toBe(2000);
expect($item->priceKgTtc->getAmount())->toBe('1500');
expect($item->options)->toBe(['extra' => 'crispy']);
});
@ -118,7 +119,7 @@ describe('Basket and BasketProduct', function (): void {
expect($updatedItem->picture)->toBe('images/poulet.jpg');
expect($updatedItem->description)->toBe('Un bon poulet rôti');
expect($updatedItem->weightVariable)->toBeTrue();
expect($updatedItem->discountRate)->toBe(0.2);
expect($updatedItem->discountRate->basisPoints())->toBe(2000);
expect($updatedItem->priceKgTtc->getAmount())->toBe('1500');
expect($updatedItem->options)->toBe(['extra' => 'crispy']);
});

View file

@ -8,6 +8,7 @@ use Domain\Enums\ProductBrand;
use Domain\Enums\TaxRate;
use Domain\Enums\Units\OrderUnit;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Entities\ProductId;
use Money\Currency;
use Money\Money;
@ -37,7 +38,7 @@ describe('BasketProduct', function () {
'picture' => null,
'description' => null,
'weightVariable' => false,
'discountRate' => 0.1,
'discountRate' => DiscountRate::fromRatio(0.1),
'priceKgTtc' => getMoney(240),
], $overrides);
@ -62,7 +63,7 @@ describe('BasketProduct', function () {
$picture = null;
$description = null;
$weightVariable = false;
$discountRate = 0.1;
$discountRate = DiscountRate::fromRatio(0.1);
$priceKgTtc = getMoney(240);
// WHEN
@ -173,34 +174,6 @@ describe('BasketProduct', function () {
expect($action)->toThrow(\DomainException::class);
});
it('throws exception if discountRate is less than 0 or greater than 1', function () {
// GIVEN
$discountRate = -0.1;
// WHEN
$action = fn () => getNewProduct([
'discountRate' => $discountRate,
]);
// THEN
expect($action)->toThrow(\DomainException::class);
});
it('throws exception if discountRate is greater than 1', function () {
// GIVEN
$discountRate = 1.1;
// WHEN
$action = fn () => getNewProduct([
'discountRate' => $discountRate,
]);
// THEN
expect($action)->toThrow(\DomainException::class);
});
// --- Tests des méthodes de calcul et de logique métier ---
it('returns a clone of unitPriceHt', function () {

View file

@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
use Domain\Models\ValueObjects\DiscountRate;
use Money\Money;
describe(DiscountRate::class, function (): void {
it('instantiates from basis points and exposes ratio and percentage', function (): void {
// GIVEN
$basisPoints = 1550;
// WHEN
$rate = DiscountRate::fromBasisPoints($basisPoints);
// THEN
expect($rate->basisPoints())->toBe(1550)
->and($rate->ratio())->toBe(0.155)
->and($rate->percentage())->toBe(15.5)
->and($rate->isZero())->toBeFalse();
});
it('creates a zero rate', function (): void {
// GIVEN / WHEN
$rate = DiscountRate::zero();
// THEN
expect($rate->basisPoints())->toBe(0)
->and($rate->isZero())->toBeTrue();
});
it('creates a rate from a percentage', function (int | float $percentage, int $expectedBasisPoints): void {
// GIVEN / WHEN
$rate = DiscountRate::fromPercentage($percentage);
// THEN
expect($rate->basisPoints())->toBe($expectedBasisPoints);
})->with([
'integer percent' => [15, 1500],
'decimal percent' => [5.5, 550],
'zero' => [0, 0],
'full' => [100, 10000],
]);
it('creates a rate from a ratio without float drift', function (float $ratio, int $expectedBasisPoints): void {
// GIVEN / WHEN
$rate = DiscountRate::fromRatio($ratio);
// THEN
expect($rate->basisPoints())->toBe($expectedBasisPoints);
})->with([
'ten percent' => [0.1, 1000],
'classic drift' => [0.29, 2900], // 0.29 * 10000 = 2899.9999999999995 in IEEE 754
'five point five' => [0.055, 550],
]);
it('computes the rate of a fixed amount discount on a base price', function (): void {
// GIVEN
$basePrice = Money::EUR(1000);
$discount = Money::EUR(200);
// WHEN
$rate = DiscountRate::fromAmounts($discount, $basePrice);
// THEN
expect($rate->basisPoints())->toBe(2000)
->and($rate->ratio())->toBe(0.2);
});
it('rounds the rate of a fixed amount discount to the nearest basis point', function (): void {
// GIVEN
$basePrice = Money::EUR(300);
$discount = Money::EUR(100); // 33.333...%
// WHEN
$rate = DiscountRate::fromAmounts($discount, $basePrice);
// THEN
expect($rate->basisPoints())->toBe(3333);
});
it('caps a fixed amount discount greater than the base price at 100 percent', function (): void {
// GIVEN
$basePrice = Money::EUR(500);
$discount = Money::EUR(900);
// WHEN
$rate = DiscountRate::fromAmounts($discount, $basePrice);
// THEN
expect($rate->basisPoints())->toBe(10000);
});
it('returns a zero rate when the base price or the discount is not positive', function (): void {
// GIVEN / WHEN
$noPrice = DiscountRate::fromAmounts(Money::EUR(100), Money::EUR(0));
$noDiscount = DiscountRate::fromAmounts(Money::EUR(0), Money::EUR(1000));
// THEN
expect($noPrice->isZero())->toBeTrue()
->and($noDiscount->isZero())->toBeTrue();
});
it('applies the rate to an amount', function (): void {
// GIVEN
$rate = DiscountRate::fromPercentage(15);
$amount = Money::EUR(1000);
// WHEN
$discount = $rate->applyTo($amount);
// THEN
expect($discount->getAmount())->toBe('150');
});
it('formats the rate as a percentage', function (int $basisPoints, string $expected): void {
// GIVEN
$rate = DiscountRate::fromBasisPoints($basisPoints);
// WHEN
$formatted = (string) $rate;
// THEN
expect($formatted)->toBe($expected);
})->with([
'integer' => [1500, '15 %'],
'decimal' => [550, '5.5 %'],
'zero' => [0, '0 %'],
'hundred' => [10000, '100 %'],
]);
it('compares two rates', function (): void {
// GIVEN
$a = DiscountRate::fromPercentage(10);
$b = DiscountRate::fromRatio(0.1);
$c = DiscountRate::fromPercentage(20);
// WHEN / THEN
expect($a->equals($b))->toBeTrue()
->and($a->equals($c))->toBeFalse();
});
it('throws when the rate is negative or above 100 percent', function (int $basisPoints): void {
// GIVEN / WHEN
$action = fn () => DiscountRate::fromBasisPoints($basisPoints);
// THEN
expect($action)->toThrow(\InvalidArgumentException::class);
})->with([
'negative' => [-1],
'above 100%' => [10001],
]);
});

View file

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Tests\Unit\Domain\Models\ValueObjects;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\ProductPricing;
use Money\Currency;
use Money\Money;
@ -24,7 +25,7 @@ describe('ProductPricing', function () {
'discountedPriceHt' => getPricingMoney(900),
'discountedPriceTtc' => getPricingMoney(1080),
'priceKgTtc' => getPricingMoney(2000),
'discountRate' => 0.1,
'discountRate' => DiscountRate::fromRatio(0.1),
'hasDiscount' => false,
], $overrides);
@ -108,17 +109,6 @@ describe('ProductPricing', function () {
expect($action)->toThrow(\DomainException::class);
});
it('throws exception if discountRate is negative', function () {
// GIVEN
$discountRate = -0.5;
// WHEN
$action = fn () => getNewProductPricing(['discountRate' => $discountRate]);
// THEN
expect($action)->toThrow(\DomainException::class);
});
it('returns clones of money objects', function () {
// GIVEN
$price = getPricingMoney(1000);
@ -142,7 +132,7 @@ describe('ProductPricing methods', function (): void {
discountedPriceHt: Money::EUR(90),
discountedPriceTtc: Money::EUR(108),
priceKgTtc: Money::EUR(150),
discountRate: 0.1,
discountRate: DiscountRate::fromRatio(0.1),
hasDiscount: true
);
// WHEN

View file

@ -9,6 +9,7 @@ use Domain\Enums\TaxRate;
use Domain\Enums\Units\OrderUnit;
use Domain\Models\Entities\Basket;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\ProductId;
use Domain\Models\ValueObjects\IncoId;
@ -38,7 +39,7 @@ function makeBasketProduct(array $overrides = []): BasketProduct
'picture' => 'images/poulet.jpg',
'description' => 'Un bon poulet',
'weightVariable' => false,
'discountRate' => 0.0,
'discountRate' => DiscountRate::fromRatio(0.0),
'priceKgTtc' => Money::EUR(1500),
], $overrides);

View file

@ -15,6 +15,7 @@ use Domain\Models\Entities\Shop;
use Domain\Models\Entities\Shopper;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Email;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\OrderId;
@ -148,7 +149,7 @@ describe('Order Creation', function () {
picture: 'images/poulet.jpg',
description: 'Un bon poulet',
weightVariable: false,
discountRate: 0.1,
discountRate: DiscountRate::fromRatio(0.1),
priceKgTtc: Money::EUR(1500)
);
$basket->addOrUpdate($basketProduct);
@ -256,7 +257,7 @@ describe('Order Creation', function () {
picture: null,
description: null,
weightVariable: false,
discountRate: 0.1,
discountRate: DiscountRate::fromRatio(0.1),
priceKgTtc: Money::EUR(1500)
);
$basket->addOrUpdate($basketProduct);

View file

@ -16,6 +16,7 @@ use Domain\Models\Entities\Order;
use Domain\Models\Entities\Shop;
use Domain\Models\Entities\Shopper;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Email;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\ProductId;
@ -69,7 +70,7 @@ function createTestBasket(int $qty = 0): Basket
picture: null,
description: null,
weightVariable: false,
discountRate: 0.0,
discountRate: DiscountRate::fromRatio(0.0),
priceKgTtc: Money::EUR(120)
);
$items[(string) $productId->value] = $basketProduct;
@ -129,7 +130,7 @@ function createOrderTunnelService(
picture: null,
description: null,
weightVariable: false,
discountRate: 0.0,
discountRate: DiscountRate::fromRatio(0.0),
priceKgTtc: Money::EUR(120)
);
})->byDefault();
@ -700,7 +701,7 @@ describe('OrderTunnelService', function (): void {
picture: null,
description: null,
weightVariable: false,
discountRate: 0.0,
discountRate: DiscountRate::fromRatio(0.0),
priceKgTtc: Money::EUR(240)
);
});

View file

@ -95,7 +95,7 @@ describe(PricingService::class, function (): void {
->and($result->discountAmountHt()->getAmount())->toBe('0')
->and($result->discountedPriceHt()->getAmount())->toBe('1000')
->and($result->discountedPriceTtc()->getAmount())->toBe('1200')
->and($result->discountRate)->toBe(0.0)
->and($result->discountRate->basisPoints())->toBe(0)
->and($result->hasDiscount)->toBeFalse();
});
@ -141,7 +141,7 @@ describe(PricingService::class, function (): void {
->and($result->discountAmountHt()->getAmount())->toBe('200')
->and($result->discountedPriceHt()->getAmount())->toBe('800')
->and($result->discountedPriceTtc()->getAmount())->toBe('960')
->and($result->discountRate)->toBe(20.0);
->and($result->discountRate->basisPoints())->toBe(2000);
});
it('applies a percentage discount and uses the specific rate from the discount object', function (): void {
@ -167,7 +167,7 @@ describe(PricingService::class, function (): void {
expect($result->hasDiscount)->toBeTrue()
->and($result->discountAmountHt()->getAmount())->toBe('150')
->and($result->discountedPriceHt()->getAmount())->toBe('850')
->and($result->discountRate)->toBe(0.15);
->and($result->discountRate->basisPoints())->toBe(1500);
});
it('calculates the virtual price per KG TTC for a PCE product with a defined weight', function (): void {
@ -229,6 +229,6 @@ describe(PricingService::class, function (): void {
$result = $service->calculateForProduct($product);
// THEN
expect($result->discountRate)->toBe(0.0);
expect($result->discountRate->basisPoints())->toBe(0);
});
});

View file

@ -11,6 +11,7 @@ use Domain\Enums\Units\InvoicingUnit;
use Domain\Enums\Units\OrderUnit;
use Domain\Models\Entities\Product;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Entities\ProductId;
use Domain\Ports\Repositories\ProductRepository;
use Domain\Services\ProductAvailabilityService;
@ -56,7 +57,7 @@ function createTestBasketProduct(ProductId $id): BasketProduct
picture: null,
description: null,
weightVariable: false,
discountRate: 0.0,
discountRate: DiscountRate::fromRatio(0.0),
priceKgTtc: Money::EUR(100),
options: []
);

View file

@ -7,6 +7,7 @@ use Domain\Enums\TaxRate;
use Domain\Enums\Units\OrderUnit;
use Domain\Models\Entities\Basket;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\ProductId;
use Domain\Models\ValueObjects\IncoId;
@ -38,7 +39,7 @@ it('serializes and deserializes basket correctly', function () {
picture: 'pic.png',
description: 'desc',
weightVariable: true,
discountRate: 0.1,
discountRate: DiscountRate::fromRatio(0.1),
priceKgTtc: new Money(2000, new Currency('EUR')),
options: ['color' => 'red']
);
@ -63,9 +64,46 @@ it('serializes and deserializes basket correctly', function () {
->and($deserializedBasket->items())->toHaveCount(1)
->and($deserializedBasket->items()[$productIdStr]->name)->toBe('Product 1')
->and($deserializedBasket->items()[$productIdStr]->weightVariable)->toBeTrue()
->and($deserializedBasket->items()[$productIdStr]->options)->toBe(['color' => 'red']);
->and($deserializedBasket->items()[$productIdStr]->options)->toBe(['color' => 'red'])
->and($array['items'][0]['discountRateBp'])->toBe(1000)
->and($deserializedBasket->items()[$productIdStr]->discountRate->basisPoints())->toBe(1000);
});
it('hydrates the discount rate from the legacy float ratio stored in older sessions', function (float $legacyRatio, int $expectedBasisPoints) {
// GIVEN
$serializer = new BasketSerializer();
$productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122();
$data = [
'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(),
'items' => [
[
'id' => $productIdStr,
'name' => 'Test',
'qty' => 1,
'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'],
'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'],
'taxRate' => TaxRate::TVA_20->value,
'weightGrams' => 500,
'orderUnit' => OrderUnit::PCE->value,
'slug' => 'test',
'weightVariable' => false,
'discountRate' => $legacyRatio,
'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'],
],
],
];
// WHEN
$basket = $serializer->fromArray($data);
// THEN
expect($basket->items()[$productIdStr]->discountRate->basisPoints())->toBe($expectedBasisPoints);
})->with([
'regular ratio' => [0.15, 1500],
'no discount' => [0.0, 0],
'out of range value is clamped' => [20.0, 10000],
]);
it('throws exception if currency is missing during deserialization', function () {
// GIVEN
$serializer = new BasketSerializer();