From b9999caf8df28a8a2b088ea338f6a190558fe0c1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?=
Date: Thu, 29 Oct 2026 15:43:37 +0100
Subject: [PATCH] feat(discounts): add discount logic for piece pricing
Implement discount calculations that apply to the piece (sold unit) for products invoiced by weight.
---
domain/Models/ValueObjects/DiscountValue.php | 5 +
domain/Services/PricingService.php | 45 +++++-
lang/en.json | 1 +
lang/fr.json | 1 +
resources/views/bo/discounts/form.blade.php | 13 +-
.../pages/products/show-price-info.blade.php | 2 +-
.../Domain/Services/PricingServiceTest.php | 130 +++++++++++++++++-
7 files changed, 190 insertions(+), 7 deletions(-)
diff --git a/domain/Models/ValueObjects/DiscountValue.php b/domain/Models/ValueObjects/DiscountValue.php
index b151f572..ea49196b 100644
--- a/domain/Models/ValueObjects/DiscountValue.php
+++ b/domain/Models/ValueObjects/DiscountValue.php
@@ -8,6 +8,11 @@ use Domain\Enums\DiscountType;
use Domain\Services\PricingService;
use Money\Money;
+/**
+ * Represents a product discount (either a percentage or a fixed amount).
+ *
+ * Business rule: All discounts apply to the piece (sold unit), regardless of the product's invoicing unit.
+ */
final readonly class DiscountValue
{
private function __construct(
diff --git a/domain/Services/PricingService.php b/domain/Services/PricingService.php
index b9e58e0c..6ff6ffba 100644
--- a/domain/Services/PricingService.php
+++ b/domain/Services/PricingService.php
@@ -18,14 +18,27 @@ class PricingService
private const GRAMS_PER_KG = 1000;
+ /**
+ * Calculates all pricing values (base, discounted, per-kg, and discount rate) for a product.
+ *
+ * Business rules:
+ * - When a product is invoiced by the kilo (InvoicingUnit::KGM) and sold by the piece (SellUnit::PCE),
+ * $product->price is the reference price per kg HT, while $basePriceHt is the price of the piece HT.
+ * - All discounts (percentage or fixed amount) always apply to the piece (sold unit).
+ */
public function calculateForProduct(Product $product): ProductPricing
{
$basePriceHt = $this->priceHt($product);
$basePriceTtc = $this->applyTax($basePriceHt, $product->tax_rate);
+ // * All discounts apply to the piece ($basePriceHt), capped at the piece price to prevent negative prices
$discountAmountHt = $product->validDiscount?->calculateDiscountAmount($basePriceHt)
?? new Money(0, $basePriceHt->getCurrency());
+ if ($discountAmountHt->greaterThan($basePriceHt)) {
+ $discountAmountHt = $basePriceHt;
+ }
+
$discountedPriceHt = $basePriceHt->subtract($discountAmountHt);
$discountedPriceTtc = $this->applyTax($discountedPriceHt, $product->tax_rate);
@@ -47,7 +60,7 @@ class PricingService
private function priceHt(Product $product): Money
{
if ($product->invoicing_unit === InvoicingUnit::KGM && $product->sell_unit === SellUnit::PCE && $product->product_weight) {
- // * Price per kg => price of the piece: price × grams ÷ 1000 (single rounding, no float)
+ // * Price per kg => price of the piece: price x grams / 1000 (single rounding, no float)
return $product->price
->multiply($product->product_weight->toGrams())
->divide(self::GRAMS_PER_KG, PricingService::ROUNDING);
@@ -58,12 +71,40 @@ class PricingService
private function calculatePriceKgTtc(Money $discountedPriceHt, Product $product): Money
{
+ if ($product->invoicing_unit === InvoicingUnit::KGM) {
+ // * The product price is already a price per kg: it is the reference for the kg price
+ $discountAmountKgHt = $product->validDiscount?->calculateDiscountAmount($product->price)
+ ?? new Money(0, $product->price->getCurrency());
+
+ $grams = $product->product_weight?->toGrams() ?? 0;
+
+ if (
+ $product->validDiscount !== null
+ && ! $product->validDiscount->isPercentage()
+ && $product->sell_unit === SellUnit::PCE
+ && $grams > 0
+ ) {
+ // * A fixed amount applies to the piece: bring it back to a per-kg amount
+ $discountAmountKgHt = $discountAmountKgHt
+ ->multiply(self::GRAMS_PER_KG)
+ ->divide($grams, self::ROUNDING);
+ }
+
+ $discountedKgPriceHt = $product->price->subtract($discountAmountKgHt);
+
+ if ($discountedKgPriceHt->isNegative()) {
+ $discountedKgPriceHt = new Money(0, $product->price->getCurrency());
+ }
+
+ return $this->applyTax($discountedKgPriceHt, $product->tax_rate);
+ }
+
$priceTtc = $this->applyTax($discountedPriceHt, $product->tax_rate);
$grams = $product->product_weight?->toGrams() ?? 0;
if ($grams > 0 && $product->status && $product->invoicing_unit === InvoicingUnit::PCE) {
- // * Price of the piece => price per kg: price × 1000 ÷ grams (single rounding, no float)
+ // * Price of the piece => price per kg: price x 1000 / grams (single rounding, no float)
return $priceTtc
->multiply(self::GRAMS_PER_KG)
->divide($grams, self::ROUNDING);
diff --git a/lang/en.json b/lang/en.json
index df22da51..8b6dc795 100644
--- a/lang/en.json
+++ b/lang/en.json
@@ -730,6 +730,7 @@
"The answer": "The answer",
"The brand associated with the product": "The brand associated with the product",
"The customer account was not found.": "The customer account was not found.",
+ "The discount applies to the piece (sold unit).": "The discount applies to the piece (sold unit).",
"The employee sync job has been dispatched": "The employee sync job has been dispatched",
"The existing encrypted environment file is not in readable format. Use --force to overwrite it.": "The existing encrypted environment file is not in readable format. Use --force to overwrite it.",
"The existing encryption key is required to update the encrypted environment file.": "The existing encryption key is required to update the encrypted environment file.",
diff --git a/lang/fr.json b/lang/fr.json
index 3e1c47e9..e3eaf7fc 100644
--- a/lang/fr.json
+++ b/lang/fr.json
@@ -719,6 +719,7 @@
"The answer": "La réponse",
"The brand associated with the product": "La marque associée au produit",
"The customer account was not found.": "Le compte client n'est pas trouvé.",
+ "The discount applies to the piece (sold unit).": "La remise s'applique à la pièce (unité de vente).",
"The employee sync job has been dispatched": "Le job de synchronisation des salariés a été lancé",
"The existing encrypted environment file is not in readable format. Use --force to overwrite it.": "The existing encrypted environment file is not in readable format. Use --force to overwrite it.",
"The existing encryption key is required to update the encrypted environment file.": "The existing encryption key is required to update the encrypted environment file.",
diff --git a/resources/views/bo/discounts/form.blade.php b/resources/views/bo/discounts/form.blade.php
index a83a14eb..85df1b12 100644
--- a/resources/views/bo/discounts/form.blade.php
+++ b/resources/views/bo/discounts/form.blade.php
@@ -31,13 +31,16 @@
diff --git a/resources/views/fo/pages/products/show-price-info.blade.php b/resources/views/fo/pages/products/show-price-info.blade.php
index 18bc336e..8d25878a 100644
--- a/resources/views/fo/pages/products/show-price-info.blade.php
+++ b/resources/views/fo/pages/products/show-price-info.blade.php
@@ -30,7 +30,7 @@
- {{ $productWithPricing->product->weight_variable ? __('Product sold by the kilo') : __('Price per kilo') }} :
+ {{ $productWithPricing->product->weight_variable ? '*' . __('Product sold by the kilo') : __('Price per kilo') }} :
@include('fo.modules.guarded-currency', [
'money' => $productWithPricing->pricing->priceKgTtc(),
'product' => $productWithPricing->product,
diff --git a/tests/Unit/Domain/Services/PricingServiceTest.php b/tests/Unit/Domain/Services/PricingServiceTest.php
index 70963236..9536924b 100644
--- a/tests/Unit/Domain/Services/PricingServiceTest.php
+++ b/tests/Unit/Domain/Services/PricingServiceTest.php
@@ -17,6 +17,21 @@ use Money\Currency;
use Money\Money;
use Ramsey\Uuid\Uuid;
+/**
+ * @param array{
+ * id?: \Domain\Models\ValueObjects\Entities\ProductId,
+ * price?: \Money\Money,
+ * tax_rate?: \Domain\Enums\TaxRate,
+ * product_weight?: \Domain\Models\ValueObjects\ProductWeight|null,
+ * invoicing_unit?: \Domain\Enums\Units\InvoicingUnit,
+ * sell_unit?: \Domain\Enums\SellUnit,
+ * validDiscount?: \Domain\Models\ValueObjects\DiscountValue|null,
+ * status?: bool,
+ * orderable_start?: \Carbon\CarbonImmutable|null,
+ * orderable_end?: \Carbon\CarbonImmutable|null,
+ * hasInco?: bool,
+ * } $attributes
+ */
function createBaseProduct(array $attributes = []): Product
{
$currency = new Currency('EUR');
@@ -44,7 +59,7 @@ function createBaseProduct(array $attributes = []): Product
product_weight: $data['product_weight'],
invoicing_unit: $data['invoicing_unit'],
sell_unit: $data['sell_unit'],
- validDiscount: $data['validDiscount'] ? clone $data['validDiscount'] : null,
+ validDiscount: $data['validDiscount'] instanceof DiscountValue ? clone $data['validDiscount'] : null,
status: $data['status'],
orderable_start: $data['orderable_start'],
orderable_end: $data['orderable_end'],
@@ -231,4 +246,117 @@ describe(PricingService::class, function (): void {
// THEN
expect($result->discountRate->basisPoints())->toBe(0);
});
+
+ it('calculates the price per KG TTC for a product invoiced by KGM and sold by PCE', function (): void {
+ // GIVEN
+ $currency = new Currency('EUR');
+ $product = createBaseProduct([
+ 'price' => new Money(865, $currency), // 8.65 €/kg
+ 'tax_rate' => TaxRate::TVA_5_5,
+ 'invoicing_unit' => InvoicingUnit::KGM,
+ 'sell_unit' => SellUnit::PCE,
+ 'product_weight' => createWeight(360), // 360g
+ 'status' => true,
+ ]);
+
+ $service = new PricingService();
+
+ // WHEN
+ $result = $service->calculateForProduct($product);
+
+ // THEN
+ expect($result->basePriceHt()->getAmount())->toBe('312')
+ ->and($result->basePriceTtc()->getAmount())->toBe('330')
+ ->and($result->priceKgTtc()->getAmount())->toBe('913');
+ });
+
+ it('calculates the price per KG TTC for a product invoiced by KGM with percentage discount', function (): void {
+ // GIVEN
+ $currency = new Currency('EUR');
+ $discount = createDiscount(
+ amount: new Money(0, $currency),
+ isPercentage: true,
+ percentageRate: 10.0
+ );
+
+ $product = createBaseProduct([
+ 'price' => new Money(865, $currency), // 8.65 €/kg
+ 'tax_rate' => TaxRate::TVA_5_5,
+ 'invoicing_unit' => InvoicingUnit::KGM,
+ 'sell_unit' => SellUnit::PCE,
+ 'product_weight' => createWeight(360), // 360g
+ 'validDiscount' => $discount,
+ 'status' => true,
+ ]);
+
+ $service = new PricingService();
+
+ // WHEN
+ $result = $service->calculateForProduct($product);
+
+ // THEN
+ expect($result->discountedPriceHt()->getAmount())->toBe('280')
+ ->and($result->discountedPriceTtc()->getAmount())->toBe('296')
+ ->and($result->priceKgTtc()->getAmount())->toBe('821');
+ });
+
+ it('calculates the price per KG TTC for a product invoiced by KGM with fixed amount discount', function (): void {
+ // GIVEN
+ $currency = new Currency('EUR');
+ $discount = createDiscount(
+ amount: new Money(50, $currency),
+ isPercentage: false
+ );
+
+ $product = createBaseProduct([
+ 'price' => new Money(865, $currency), // 8.65 €/kg
+ 'tax_rate' => TaxRate::TVA_5_5,
+ 'invoicing_unit' => InvoicingUnit::KGM,
+ 'sell_unit' => SellUnit::PCE,
+ 'product_weight' => createWeight(360),
+ 'validDiscount' => $discount,
+ 'status' => true,
+ ]);
+
+ $service = new PricingService();
+
+ // WHEN
+ $result = $service->calculateForProduct($product);
+
+ // THEN
+ // 50 cts off a 360 g piece => 139 cts off per kg (rounded up): (865 - 139) HT x 1.055
+ expect($result->discountedPriceTtc()->getAmount())->toBe('277')
+ ->and($result->priceKgTtc()->getAmount())->toBe('766');
+ });
+
+ it('caps the discount at the piece price when a fixed discount exceeds the piece price', function (): void {
+ // GIVEN
+ $currency = new Currency('EUR');
+ $discount = createDiscount(
+ amount: new Money(500, $currency), // 5.00 € discount on a 3.12 € piece
+ isPercentage: false
+ );
+
+ $product = createBaseProduct([
+ 'price' => new Money(865, $currency), // 8.65 €/kg => 3.12 € HT for 360g
+ 'tax_rate' => TaxRate::TVA_5_5,
+ 'invoicing_unit' => InvoicingUnit::KGM,
+ 'sell_unit' => SellUnit::PCE,
+ 'product_weight' => createWeight(360),
+ 'validDiscount' => $discount,
+ 'status' => true,
+ ]);
+
+ $service = new PricingService();
+
+ // WHEN
+ $result = $service->calculateForProduct($product);
+
+ // THEN
+ expect($result->discountAmountHt()->getAmount())->toBe('312')
+ ->and($result->discountedPriceHt()->getAmount())->toBe('0')
+ ->and($result->discountedPriceTtc()->getAmount())->toBe('0')
+ ->and($result->priceKgTtc()->getAmount())->toBe('0')
+ ->and($result->discountRate->basisPoints())->toBe(10000);
+ });
});