Files
2025-08-02 16:30:27 +02:00

124 lines
3.2 KiB
PHP

<?php
namespace KupShop\KupShopBundle\Util\Price;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Context\VatContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Wrapper\PriceWrapper;
class PriceUtil
{
/**
* @var CurrencyContext
*/
private $currencyContext;
public function __construct(CurrencyContext $currencyContext)
{
$this->currencyContext = $currencyContext;
}
/**
* @param Price|PriceWrapper $input
*
* @return PriceWrapper|Price
*/
public static function recalculatePriceVatFromPriceWithVat($input, float $defaultVat, ?int $vat_id = null)
{
$price = $input;
if ($price instanceof PriceWrapper) {
$price = $price->getObject();
}
$defaultVat = toDecimal($defaultVat);
$priceVat = $price->getVat();
$vatContext = Contexts::get(VatContext::class);
if ($vatContext->getActive() == $vatContext::NO_VAT) {
$priceVat = ($vat_id ? $vatContext->getVat($vat_id) : $vatContext->getDefault());
$priceVat = toDecimal($priceVat['vat']);
}
if (!$defaultVat->equals($priceVat)) {
$price->setValue(
$price->getValue()->addVat($defaultVat)->removeVat($priceVat)
);
}
return $input;
}
public static function isProductPricesVatFromTop(): bool
{
return (\Settings::getDefault()->prod_vats_from_top ?? 'N') === 'Y' && !Contexts::get(UserContext::class)->isDealer();
}
/**
* @param Price|PriceWrapper $input
*
* @return PriceWrapper|Price
*/
public static function applyPriceVatFromTop($input, $product)
{
if (!self::isProductPricesVatFromTop()) {
return $input;
}
$originalVatId = $product->original_vat ?? $product->vat_id;
static::recalculatePriceVatFromPriceWithVat($input, (float) getVat($originalVatId));
return $input;
}
public static function updatePriceVat($price): Price
{
if ($price instanceof PriceWrapper) {
$price = $price->getObject();
}
$price->setValue(
$price->getValue()->addVat(21)->removeVat(19)
);
return $price;
}
/**
* @return Price
*/
public function getFromPriceArray(array $priceArray)
{
$price = $priceArray['value_without_vat'];
if (!empty($priceArray['currency_object'])) {
$currency = $priceArray['currency_object'];
} else {
$currency = $this->getCurrencyById($priceArray['currency']);
}
$vat = $priceArray['vat'];
return new Price($price, $currency, $vat);
}
/**
* @param bool $fallback
*
* @return \KupShop\I18nBundle\Entity\Currency|null
*/
public function getCurrencyById($id, $fallback = true)
{
$currencies = $this->currencyContext->getAll();
if (array_key_exists($id, $currencies)) {
return $currencies[$id];
}
if ($fallback) {
return $this->currencyContext->getActive();
}
return null;
}
}