. * */ namespace Vvveb\System\Cart; use Vvveb\Sql\Tax_typeSQL; use Vvveb\System\Cache; class Tax { private $taxRates = []; public static function getInstance($options = []) { static $inst = null; if ($inst === null) { $inst = new Tax($options); } return $inst; } public function __construct($options = []) { } public function setRegionRules($country_id, $region_id, $based = 'store') { $cache = Cache::getInstance(); $rules = $cache->cache(APP,"tax_rates.$country_id.$region_id.$based",function () use ($country_id, $region_id, $based) { $taxType = new Tax_typeSQL(); $taxRules = $taxType->getRegionRules(['country_id' => $country_id, 'region_id' => $region_id, 'based' => $based]); return $taxRules['tax_rule'] ?? []; }, 259200); foreach ($rules as $rate) { $this->taxRates[$rate['tax_type_id']][$rate['tax_rate_id']] = [ 'tax_rate_id' => $rate['tax_rate_id'], 'name' => $rate['name'], 'rate' => $rate['rate'], 'type' => $rate['type'], 'priority' => $rate['priority'], 'based' => $based, ]; } } public function addTaxes($value, $taxTypeId, $onlyTax = false) { $amount = 0; if (isset($this->taxRates[$taxTypeId])) { foreach ($this->taxRates[$taxTypeId] as $taxRate) { $rate = (float)$taxRate['rate']; if ($taxRate['type'] == 'f') {//fixed $amount += $rate; } elseif ($taxRate['type'] == 'p') {//percent $amount += (($value / 100) * $rate); } } } if ($onlyTax) { return $amount; } return $value + $amount; } public function getRates($value, $taxTypeId) { $taxRate_data = []; if (isset($this->taxRates[$taxTypeId])) { foreach ($this->taxRates[$taxTypeId] as $taxRate) { if (isset($taxRate_data[$taxRate['tax_rate_id']])) { $amount = $taxRate_data[$taxRate['tax_rate_id']]['amount']; } else { $amount = 0; } $rate = (float)$taxRate['rate']; $value = (float)$value; if ($taxRate['type'] == 'f') { $amount += $rate; } elseif ($taxRate['type'] == 'p') { $amount += (($value / 100) * $rate); } $taxRate_data[$taxRate['tax_rate_id']] = [ 'tax_rate_id' => $taxRate['tax_rate_id'], 'name' => $taxRate['name'], 'rate' => $taxRate['rate'], 'type' => $taxRate['type'], 'amount' => $amount, ]; } } return $taxRate_data; } public function clear() { $this->taxRates = []; } }