craftcms / commerce

Fully integrated ecommerce for Craft CMS.
https://craftcms.com/commerce
Other
219 stars 170 forks source link

[5.x]: TaxRates service does not account for tax rate store when searching for tax zone when saving tax rate #3461

Closed stanislavprokopov closed 5 months ago

stanislavprokopov commented 5 months ago

What happened?

Description

We have a queue job that syncs tax rates from an external source for different site stores, when it tries to save tax rate for a specific store it gets an error No tax zone exists with the ID “XXX” - TaxRates.php at 151

The job basically looks like this:

$store = \craft\commerce\Plugin::getInstance()->getStores()->getStoreByHandle('storeTwo');

$taxZone = new TaxAddressZone();
$taxZone->storeId = $store->id;
$taxZone->name = 'Zone 2';
$taxZone->description = 'Store 2 Tax Zone 2';

if (!\craft\commerce\Plugin::getInstance()->getTaxZones()->saveTaxZone($taxZone)) {
    throw new \Exception('Failed to save tax zone');
}

$taxRate = new TaxRate();
$taxRate->storeId = $store->id;
$taxRate->taxZoneId = $taxZone->id;
$taxRate->code = 'rate1';
$taxRate->name = 'Rate 1;
$taxRate->taxable = 'price';
$taxRate->isVat = true;
$taxRate->rate = 22;
$taxRate->taxCategoryId = \craft\commerce\Plugin::getInstance()->getTaxCategories()->getDefaultTaxCategory()->id;

if (!\craft\commerce\Plugin::getInstance()->getTaxRates()->saveTaxRate($taxRate)) {
    throw new \Exception('Failed to save tax rate');
}

The issue is at src/services/TaxRates.php line $taxZone = Plugin::getInstance()->getTaxZones()->getTaxZoneById($record->taxZoneId); the getTaxZoneById has an optional second argument $storeId, if its not provided then it defaults to Plugin::getInstance()->getStores()->getCurrentStore()->id this current store could be anything but in this example we are actually saving the zone and rate for storeTwo and if it does not match with current store then it fails to find the zone by id.

The fix would be to add $record->storeId as the last argument to the getTaxZoneById call.

Craft CMS version

5.0.0

Craft Commerce version

5.0.0-beta.3

PHP version

No response

Operating system and version

No response

Database type and version

No response

Image driver and version

No response

Installed plugins and versions

-

linear[bot] commented 5 months ago

PT-1650 [5.x]: TaxRates service does not account for tax rate store when searching for tax zone when saving tax rate

lukeholder commented 5 months ago

Thank you for bringing this to our attention. We have pushed a fix for this which will be included in the next release of Commerce 5 beta.

To get this early, change your craftcms/commerce requirement in your project's composer.json to:

"require": {
  "craftcms/commerce": "5.0.x-dev#aed7d9092196d5f939a6409b073e5bc6daa45200 as 5.0.0-beta.3",
  "...": "..."
}

Then run composer update.

Alternatively you can wait for the next beta or release.

Thanks!