feat(discounts): add discount logic for piece pricing

Implement discount calculations that apply to the piece (sold unit) for products invoiced by weight.
This commit is contained in:
Jérémy Munsch 2026-10-29 15:43:37 +01:00
parent 4d6ff9b726
commit b9999caf8d
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
7 changed files with 190 additions and 7 deletions

View file

@ -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(

View file

@ -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);

View file

@ -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.",

View file

@ -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.",

View file

@ -31,13 +31,16 @@
<div class="col-12 col-md-6 form-group">
<span class="col-form-label">
<b>{{ Str::ucfirst(__('validation.custom.attributes.discount_value')) }}*</b>
<span data-bs-toggle="tooltip" title="{{ __('The discount applies to the piece (sold unit).') }}">
<i class="fas fa-question-circle"></i>
</span>
</span>
{{-- INPUT MONTANT --}}
<div class="input-group {{ $isAmount ? '' : 'd-none' }} mb-3" id="wrapper-discount-amount">
<input class="form-control" id="discount-value-amount" name="value" data-money-input type="number"
value="{{ $isAmount ? old('value', $discount->value?->value()->getAmount() ?? '') : '' }}" step="0.01" min="0"
{{ $isAmount ? 'required' : 'disabled' }}>
aria-describedby="discount-value-help" {{ $isAmount ? 'required' : 'disabled' }}>
<span class="input-group-text">@currency()</span>
</div>
@ -45,11 +48,15 @@
<div class="input-group {{ $isPercent ? '' : 'd-none' }} mb-3" id="wrapper-discount-percent">
<input class="form-control" id="discount-value-percent" name="value" type="number"
value="{{ $isPercent ? old('value', $discount->value?->value() ?? '') : '' }}" step="1" min="0"
max="100" {{ $isPercent ? 'required' : 'disabled' }}>
max="100" aria-describedby="discount-value-help" {{ $isPercent ? 'required' : 'disabled' }}>
<span class="input-group-text">%</span>
</div>
@include('bo.modules.input-error', ['inputName' => 'value'])
@include('bo.modules.input-error', [
'inputName' => 'value',
'helperId' => 'discount-value-help',
'helper' => __('The discount applies to the piece (sold unit).'),
])
</div>
</div>

View file

@ -30,7 +30,7 @@
</p>
<p class="small fst-italic text-muted">
<span>{{ $productWithPricing->product->weight_variable ? __('Product sold by the kilo') : __('Price per kilo') }}</span> :
<span>{{ $productWithPricing->product->weight_variable ? '*' . __('Product sold by the kilo') : __('Price per kilo') }}</span> :
@include('fo.modules.guarded-currency', [
'money' => $productWithPricing->pricing->priceKgTtc(),
'product' => $productWithPricing->product,

View file

@ -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);
});
});