87 lines
2.8 KiB
PHP
87 lines
2.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Domain\Services;
|
|
|
|
use Domain\Enums\SellUnit;
|
|
use Domain\Enums\TaxRate;
|
|
use Domain\Enums\Units\InvoicingUnit;
|
|
use Domain\Models\Entities\Product;
|
|
use Domain\Models\ValueObjects\ProductPricing;
|
|
use Money\Money;
|
|
|
|
class PricingService
|
|
{
|
|
public const ROUNDING = Money::ROUND_UP;
|
|
|
|
public function calculateForProduct(Product $product): ProductPricing
|
|
{
|
|
$basePriceHt = $this->priceHt($product);
|
|
$basePriceTtc = $this->applyTax($basePriceHt, $product->tax_rate);
|
|
|
|
$discountAmountHt = $product->validDiscount?->calculateDiscountAmount($basePriceHt)
|
|
?? new Money(0, $basePriceHt->getCurrency());
|
|
|
|
$discountedPriceHt = $basePriceHt->subtract($discountAmountHt);
|
|
$discountedPriceTtc = $this->applyTax($discountedPriceHt, $product->tax_rate);
|
|
|
|
$priceKgTtc = $this->calculatePriceKgTtc($discountedPriceHt, $product);
|
|
$discountRate = $this->calculateDiscountRate($basePriceHt, $discountAmountHt, $product);
|
|
|
|
return new ProductPricing(
|
|
basePriceHt: $basePriceHt,
|
|
basePriceTtc: $basePriceTtc,
|
|
discountAmountHt: $discountAmountHt,
|
|
discountedPriceHt: $discountedPriceHt,
|
|
discountedPriceTtc: $discountedPriceTtc,
|
|
priceKgTtc: $priceKgTtc,
|
|
discountRate: $discountRate,
|
|
hasDiscount: $product->validDiscount !== null
|
|
);
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
return $product->price;
|
|
}
|
|
|
|
private function calculatePriceKgTtc(Money $discountedPriceHt, Product $product): Money
|
|
{
|
|
$priceTtc = $this->applyTax($discountedPriceHt, $product->tax_rate);
|
|
|
|
$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);
|
|
}
|
|
|
|
return $priceTtc;
|
|
}
|
|
|
|
private function applyTax(Money $price, TaxRate $taxRate): Money
|
|
{
|
|
return $taxRate->applyTo($price);
|
|
}
|
|
|
|
private function calculateDiscountRate(Money $priceHt, Money $discountAmount, Product $product): float
|
|
{
|
|
$discount = $product->validDiscount;
|
|
|
|
if ($discount?->isPercentage()) {
|
|
return $discount->getPercentageRate();
|
|
}
|
|
|
|
if ($priceHt->isPositive()) {
|
|
return (float) ($discountAmount->getAmount() * 100) / (float) $priceHt->getAmount();
|
|
}
|
|
|
|
return 0.0;
|
|
}
|
|
}
|