This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,649 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\Calculation;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Tax\Api\Data\TaxRateInterface;
use Magento\Tax\Model\Calculation\Rate;
use Magento\Tax\Model\TaxRuleFixtureFactory;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class RateRepositoryTest extends \PHPUnit\Framework\TestCase
{
/**
* Object Manager
*
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* TaxRate factory
*
* @var \Magento\Tax\Api\Data\TaxRateInterfaceFactory
*/
private $taxRateFactory;
/**
* TaxRateService
*
* @var \Magento\Tax\Api\TaxRateRepositoryInterface
*/
private $rateRepository;
/**
* Helps in creating required tax rules.
*
* @var TaxRuleFixtureFactory
*/
private $taxRateFixtureFactory;
/**
* @var \Magento\Directory\Model\CountryFactory
*/
private $countryFactory;
/**
* @var \Magento\Directory\Model\RegionFactory
*/
private $regionFactory;
/**
* @var \Magento\Framework\Api\DataObjectHelper
*/
private $dataObjectHelper;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->rateRepository = $this->objectManager->get(\Magento\Tax\Api\TaxRateRepositoryInterface::class);
$this->taxRateFactory = $this->objectManager->create(\Magento\Tax\Api\Data\TaxRateInterfaceFactory::class);
$this->dataObjectHelper = $this->objectManager->create(\Magento\Framework\Api\DataObjectHelper::class);
$this->taxRateFixtureFactory = new TaxRuleFixtureFactory();
$this->countryFactory = $this->objectManager->create(\Magento\Directory\Model\CountryFactory::class);
$this->regionFactory = $this->objectManager->create(\Magento\Directory\Model\RegionFactory::class);
}
/**
* @magentoDbIsolation enabled
*/
public function testSave()
{
$taxData = [
'tax_country_id' => 'US',
'tax_region_id' => '8',
'rate' => '8.25',
'code' => 'US-CA-*-Rate' . rand(),
'zip_is_range' => true,
'zip_from' => 78765,
'zip_to' => 78780,
];
// Tax rate data object created
$taxRate = $this->taxRateFactory->create();
$this->dataObjectHelper->populateWithArray($taxRate, $taxData, \Magento\Tax\Api\Data\TaxRateInterface::class);
//Tax rate service call
$taxRateServiceData = $this->rateRepository->save($taxRate);
//Assertions
$this->assertInstanceOf(\Magento\Tax\Api\Data\TaxRateInterface::class, $taxRateServiceData);
$this->assertEquals($taxData['tax_country_id'], $taxRateServiceData->getTaxCountryId());
$this->assertEquals($taxData['tax_region_id'], $taxRateServiceData->getTaxRegionId());
$this->assertEquals($taxData['rate'], $taxRateServiceData->getRate());
$this->assertEquals($taxData['code'], $taxRateServiceData->getCode());
$this->assertEquals($taxData['zip_from'], $taxRateServiceData->getZipFrom());
$this->assertEquals($taxData['zip_to'], $taxRateServiceData->getZipTo());
$this->assertEquals('78765-78780', $taxRateServiceData->getTaxPostcode());
$this->assertNotNull($taxRateServiceData->getId());
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveWithZeroValue()
{
$taxData = [
'tax_country_id' => 'US',
'tax_region_id' => '8',
'rate' => '0',
'code' => 'US-CA-*-Rate' . rand(),
'zip_is_range' => true,
'zip_from' => 78765,
'zip_to' => 78780,
];
// Tax rate data object created
$taxRate = $this->taxRateFactory->create();
$this->dataObjectHelper->populateWithArray($taxRate, $taxData, \Magento\Tax\Api\Data\TaxRateInterface::class);
//Tax rate service call
$taxRateServiceData = $this->rateRepository->save($taxRate);
//Assertions
$this->assertInstanceOf(\Magento\Tax\Api\Data\TaxRateInterface::class, $taxRateServiceData);
$this->assertEquals($taxData['tax_country_id'], $taxRateServiceData->getTaxCountryId());
$this->assertEquals($taxData['tax_region_id'], $taxRateServiceData->getTaxRegionId());
$this->assertEquals($taxData['rate'], $taxRateServiceData->getRate());
$this->assertEquals($taxData['code'], $taxRateServiceData->getCode());
$this->assertEquals($taxData['zip_from'], $taxRateServiceData->getZipFrom());
$this->assertEquals($taxData['zip_to'], $taxRateServiceData->getZipTo());
$this->assertEquals('78765-78780', $taxRateServiceData->getTaxPostcode());
$this->assertNotNull($taxRateServiceData->getId());
}
/**
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Store/_files/store.php
*/
public function testSaveWithTitles()
{
$store = $this->objectManager->get(\Magento\Store\Model\Store::class);
$store->load('test', 'code');
$taxData = [
'tax_country_id' => 'US',
'tax_region_id' => '8',
'rate' => '8.25',
'code' => 'US-CA-*-Rate' . rand(),
'zip_is_range' => true,
'zip_from' => 78765,
'zip_to' => 78780,
'titles' => [
[
'store_id' => $store->getId(),
'value' => 'random store title',
],
],
];
// Tax rate data object created
$taxRate = $this->taxRateFactory->create();
$this->dataObjectHelper->populateWithArray($taxRate, $taxData, \Magento\Tax\Api\Data\TaxRateInterface::class);
//Tax rate service call
$taxRateServiceData = $this->rateRepository->save($taxRate);
//Assertions
$this->assertInstanceOf(\Magento\Tax\Api\Data\TaxRateInterface::class, $taxRateServiceData);
$this->assertEquals($taxData['tax_country_id'], $taxRateServiceData->getTaxCountryId());
$this->assertEquals($taxData['tax_region_id'], $taxRateServiceData->getTaxRegionId());
$this->assertEquals($taxData['rate'], $taxRateServiceData->getRate());
$this->assertEquals($taxData['code'], $taxRateServiceData->getCode());
$this->assertEquals($taxData['zip_from'], $taxRateServiceData->getZipFrom());
$this->assertEquals($taxData['zip_to'], $taxRateServiceData->getZipTo());
$this->assertEquals('78765-78780', $taxRateServiceData->getTaxPostcode());
$this->assertNotNull($taxRateServiceData->getId());
$titles = $taxRateServiceData->getTitles();
$this->assertCount(1, $titles);
$this->assertEquals($store->getId(), $titles[0]->getStoreId());
$this->assertEquals($taxData['titles'][0]['value'], $titles[0]->getValue());
$taxRateServiceData = $this->rateRepository->get($taxRateServiceData->getId());
$titles = $taxRateServiceData->getTitles();
$this->assertCount(1, $titles);
$this->assertEquals($store->getId(), $titles[0]->getStoreId());
$this->assertEquals($taxData['titles'][0]['value'], $titles[0]->getValue());
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveThrowsExceptionIfTargetTaxRateDoesNotExist()
{
$this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class);
$this->expectExceptionMessage('No such entity with taxRateId = 9999');
$invalidTaxData = [
'id' => 9999,
'tax_country_id' => 'US',
'tax_region_id' => '8',
'rate' => '8.25',
'code' => 'US-CA-*-Rate' . rand(),
'zip_is_range' => true,
'zip_from' => 78765,
'zip_to' => 78780,
];
$taxRate = $this->taxRateFactory->create();
$this->dataObjectHelper->populateWithArray(
$taxRate,
$invalidTaxData,
\Magento\Tax\Api\Data\TaxRateInterface::class
);
$this->rateRepository->save($taxRate);
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveThrowsExceptionIfTaxRateWithCorrespondingCodeAlreadyExists()
{
$this->expectException(\Magento\Framework\Exception\AlreadyExistsException::class);
$this->expectExceptionMessage('Code already exists.');
$invalidTaxData = [
'tax_country_id' => 'US',
'tax_region_id' => '8',
'rate' => '8.25',
'code' => 'US-CA-*-Rate' . rand(),
'zip_is_range' => true,
'zip_from' => 78765,
'zip_to' => 78780,
];
$taxRate1 = $this->taxRateFactory->create();
$this->dataObjectHelper->populateWithArray(
$taxRate1,
$invalidTaxData,
\Magento\Tax\Api\Data\TaxRateInterface::class
);
$taxRate2 = $this->taxRateFactory->create();
$this->dataObjectHelper->populateWithArray(
$taxRate2,
$invalidTaxData,
\Magento\Tax\Api\Data\TaxRateInterface::class
);
//Service call initiated twice to add the same code
$this->rateRepository->save($taxRate1);
$this->rateRepository->save($taxRate2);
}
/**
* @param array $dataArray
* @param string $errorMessages
* @throws \Magento\Framework\Exception\InputException
*
* @dataProvider createDataProvider
* @magentoDbIsolation enabled
*/
public function testSaveThrowsExceptionIfGivenDataIsInvalid($dataArray, $errorMessages)
{
$this->expectException(\Magento\Framework\Exception\InputException::class);
$taxRate = $this->taxRateFactory->create();
$this->dataObjectHelper->populateWithArray($taxRate, $dataArray, \Magento\Tax\Api\Data\TaxRateInterface::class);
try {
$this->rateRepository->save($taxRate);
} catch (InputException $exception) {
$errors = $exception->getErrors();
foreach ($errors as $key => $error) {
$this->assertEquals($errorMessages[$key], $error->getMessage());
}
throw $exception;
}
}
/**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function createDataProvider()
{
return [
'invalidZipRange' => [
[
'zip_is_range' => true,
'zip_from' => 'from',
'zip_to' => 'to',
],
'error' => [
'"country_id" is required. Enter and try again.',
'"percentage_rate" is required. Enter and try again.',
'"code" is required. Enter and try again.',
'Invalid value of "from" provided for the zip_from field.',
'Invalid value of "to" provided for the zip_to field.',
],
],
'emptyZipRange' => [
[
'zip_is_range' => true,
'zip_from' => '',
'zip_to' => '',
],
'error' => [
'"country_id" is required. Enter and try again.',
'"percentage_rate" is required. Enter and try again.',
'"code" is required. Enter and try again.',
'Invalid value of "" provided for the zip_from field.',
'Invalid value of "" provided for the zip_to field.',
],
],
'empty' => [
[],
'error' => [
'"country_id" is required. Enter and try again.',
'"percentage_rate" is required. Enter and try again.',
'"code" is required. Enter and try again.',
'"postcode" is required. Enter and try again.',
],
],
'zipRangeAndPostcode' => [
[
'postcode' => 78727,
'zip_is_range' => true,
'zip_from' => 78765,
'zip_to' => 78780,
],
'error' => [
'"country_id" is required. Enter and try again.',
'"percentage_rate" is required. Enter and try again.',
'"code" is required. Enter and try again.',
],
],
'higherRange' => [
[
'zip_is_range' => true,
'zip_from' => 78765,
'zip_to' => 78780,
],
'error' => [
'"country_id" is required. Enter and try again.',
'"percentage_rate" is required. Enter and try again.',
'"code" is required. Enter and try again.',
'Range To should be equal or greater than Range From.',
],
],
'invalidCountry' => [
['tax_country_id' => 'XX'],
'error' => [
'Invalid value of "XX" provided for the country_id field.',
'"percentage_rate" is required. Enter and try again.',
'"code" is required. Enter and try again.',
'"postcode" is required. Enter and try again.',
],
],
'invalidCountry2' => [
['tax_country_id' => ' '],
'error' => [
'"country_id" is required. Enter and try again.',
'"percentage_rate" is required. Enter and try again.',
'"code" is required. Enter and try again.',
'"postcode" is required. Enter and try again.',
],
],
'invalidRegion1' => [
['tax_region_id' => '-'],
'error' => [
'"country_id" is required. Enter and try again.',
'Invalid value of "-" provided for the region_id field.',
'"percentage_rate" is required. Enter and try again.',
'"code" is required. Enter and try again.',
'"postcode" is required. Enter and try again.',
],
],
'spaceRegion' => [
['tax_region_id' => ' '],
'error' => [
'"country_id" is required. Enter and try again.',
'"percentage_rate" is required. Enter and try again.',
'"code" is required. Enter and try again.',
'"postcode" is required. Enter and try again.',
],
],
'emptyPercentageRate' => [
[
'tax_country_id' => 'US',
'tax_region_id' => '8',
'rate' => '',
'code' => 'US-CA-*-Rate' . rand(),
'zip_is_range' => true,
'zip_from' => 78765,
'zip_to' => 78780,
],
'error' => [
'"percentage_rate" is required. Enter and try again.',
],
]
];
}
/**
* @magentoDbIsolation enabled
*/
public function testGet()
{
$data = [
'tax_country_id' => 'US',
'tax_region_id' => '12',
'tax_postcode' => '*',
'code' => 'US_12_Code',
'rate' => '7.5',
];
$rate = $this->objectManager->create(\Magento\Tax\Model\Calculation\Rate::class)
->setData($data)
->save();
$taxRate = $this->rateRepository->get($rate->getId());
$this->assertEquals('US', $taxRate->getTaxCountryId());
$this->assertEquals(12, $taxRate->getTaxRegionId());
$this->assertEquals('*', $taxRate->getTaxPostcode());
$this->assertEquals('US_12_Code', $taxRate->getCode());
$this->assertEquals(7.5, $taxRate->getRate());
$this->assertNull($taxRate->getZipIsRange());
$this->assertNull($taxRate->getZipTo());
$this->assertNull($taxRate->getZipFrom());
}
/**
*/
public function testGetThrowsExceptionIfTargetTaxRateDoesNotExist()
{
$this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class);
$this->expectExceptionMessage('No such entity with taxRateId = 9999');
$this->rateRepository->get(9999);
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveUpdatesTaxRate()
{
$taxRate = $this->taxRateFactory->create();
$taxRate->setTaxCountryId('US')
->setTaxRegionId(42)
->setRate(8.25)
->setCode('UpdateTaxRates')
->setTaxPostcode('78780');
$taxRate = $this->rateRepository->save($taxRate);
$updatedTaxRate = $this->taxRateFactory->create();
$updatedTaxRate->setId($taxRate->getId())
->setCode('UpdateTaxRates')
->setTaxCountryId('US')
->setTaxRegionId(42)
->setRate(8.25)
->setZipIsRange(true)
->setZipFrom(78700)
->setZipTo(78780);
$updatedTaxRate = $this->rateRepository->save($updatedTaxRate);
$retrievedRate = $this->rateRepository->get($taxRate->getId());
// Expect the service to have filled in the new postcode for us
$this->assertEquals($updatedTaxRate->getTaxPostcode(), $retrievedRate->getTaxPostcode());
$this->assertNotEquals($taxRate->getTaxPostcode(), $retrievedRate->getTaxPostcode());
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveThrowsExceptionIfTargetTaxRateExistsButProvidedDataIsInvalid()
{
$this->expectException(\Magento\Framework\Exception\InputException::class);
$this->expectExceptionMessage('postcode');
$taxRate = $this->taxRateFactory->create();
$taxRate->setTaxCountryId('US')
->setTaxRegionId(42)
->setRate(8.25)
->setCode('UpdateTaxRates')
->setTaxPostcode('78780');
$taxRate = $this->rateRepository->save($taxRate);
$updatedTaxRate = $this->taxRateFactory->create();
$updatedTaxRate->setId($taxRate->getId())
->setTaxCountryId('US')
->setTaxRegionId(42)
->setRate(8.25)
->setCode('UpdateTaxRates')
->setTaxPostcode(null);
$this->rateRepository->save($updatedTaxRate);
}
/**
* @magentoDbIsolation enabled
*/
public function testDeleteById()
{
// Create a new tax rate
$taxRateData = $this->taxRateFactory->create();
$taxRateData->setCode('TX')
->setTaxCountryId('US')
->setRate(5)
->setTaxPostcode(77000)
->setTaxRegionId(1);
$taxRateId = $this->rateRepository->save($taxRateData)->getId();
// Delete the new tax rate
$this->assertTrue($this->rateRepository->deleteById($taxRateId));
// Get the new tax rate, this should fail
try {
$this->rateRepository->get($taxRateId);
$this->fail('NoSuchEntityException expected but not thrown');
} catch (NoSuchEntityException $e) {
$expectedParams = [
'fieldName' => 'taxRateId',
'fieldValue' => $taxRateId,
];
$this->assertEquals($expectedParams, $e->getParameters());
} catch (\Exception $e) {
$this->fail('Caught unexpected exception');
}
}
/**
* @magentoDbIsolation enabled
*/
public function testDeleteThrowsExceptionIfTargetTaxRateDoesNotExist()
{
// Create a new tax rate
$taxRateData = $this->taxRateFactory->create();
$taxRateData->setCode('TX')
->setTaxCountryId('US')
->setRate(6)
->setTaxPostcode(77001)
->setTaxRegionId(1);
$taxRateId = $this->rateRepository->save($taxRateData)->getId();
// Delete the new tax rate
$this->assertTrue($this->rateRepository->deleteById($taxRateId));
// Delete the new tax rate again, this should fail
try {
$this->rateRepository->deleteById($taxRateId);
$this->fail('NoSuchEntityException expected but not thrown');
} catch (NoSuchEntityException $e) {
$expectedParams = [
'fieldName' => 'taxRateId',
'fieldValue' => $taxRateId,
];
$this->assertEquals($expectedParams, $e->getParameters());
} catch (\Exception $e) {
$this->fail('Caught unexpected exception');
}
}
/**
* @param \Magento\Framework\Api\Filter[] $filters
* @param \Magento\Framework\Api\Filter[] $filterGroup
* @param $expectedRateCodes
*
* @magentoDbIsolation enabled
* @dataProvider searchTaxRatesDataProvider
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
public function testGetList($filters, $filterGroup, $expectedRateCodes)
{
$taxRates = $this->taxRateFixtureFactory->createTaxRates(
[
['percentage' => 7.5, 'country' => 'US', 'region' => '42'],
['percentage' => 7.5, 'country' => 'US', 'region' => '12'],
['percentage' => 22.0, 'country' => 'US', 'region' => '42'],
['percentage' => 10.0, 'country' => 'US', 'region' => '12'],
]
);
/** @var \Magento\Framework\Api\SearchCriteriaBuilder $searchBuilder */
$searchBuilder = Bootstrap::getObjectManager()
->create(\Magento\Framework\Api\SearchCriteriaBuilder::class);
foreach ($filters as $filter) {
$searchBuilder->addFilters([$filter]);
}
if ($filterGroup !== null) {
$searchBuilder->addFilters($filterGroup);
}
$searchCriteria = $searchBuilder->create();
$searchResults = $this->rateRepository->getList($searchCriteria);
$this->assertEquals($searchCriteria, $searchResults->getSearchCriteria());
$this->assertEquals(count($expectedRateCodes), $searchResults->getTotalCount());
foreach ($searchResults->getItems() as $rate) {
$this->assertContains($rate->getCode(), $expectedRateCodes);
}
}
public function searchTaxRatesDataProvider()
{
$filterBuilder = Bootstrap::getObjectManager()->create(\Magento\Framework\Api\FilterBuilder::class);
return [
'eq' => [
[$filterBuilder->setField(Rate::KEY_REGION_ID)->setValue(42)->create()],
null,
['US - 42 - 7.5', 'US - 42 - 22'],
],
'and' => [
[
$filterBuilder->setField(Rate::KEY_REGION_ID)->setValue(42)->create(),
$filterBuilder->setField(Rate::KEY_PERCENTAGE_RATE)->setValue(22.0)->create(),
],
[],
['US - 42 - 22'],
],
'or' => [
[],
[
$filterBuilder->setField(Rate::KEY_PERCENTAGE_RATE)->setValue(22.0)->create(),
$filterBuilder->setField(Rate::KEY_PERCENTAGE_RATE)->setValue(10.0)->create(),
],
['US - 42 - 22', 'US - 12 - 10'],
],
'like' => [
[
$filterBuilder->setField(Rate::KEY_CODE)->setValue('%7.5')->setConditionType('like')->create(),
],
[],
['US - 42 - 7.5', 'US - 12 - 7.5'],
],
'like_region_name' => [
[
$filterBuilder->setField(Rate::KEY_REGION_NAME)
->setValue('%NM%')
->setConditionType('like')
->create(),
],
null,
['US - 42 - 7.5', 'US - 42 - 22'],
],
];
}
}
@@ -0,0 +1,84 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
/**
* Class CalculationTest
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*/
class CalculationTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\TestFramework\ObjectManager
*/
protected $_objectManager;
/**
* @var CustomerRepositoryInterface
*/
protected $customerRepository;
/**
* @var AddressRepositoryInterface
*/
protected $addressRepository;
/**
* @var GroupRepositoryInterface
*/
protected $groupRepository;
const FIXTURE_CUSTOMER_ID = 1;
const FIXTURE_ADDRESS_ID = 1;
/**
* @var \Magento\Tax\Model\Calculation
*/
protected $_model;
protected function setUp(): void
{
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_model = $this->_objectManager->create(\Magento\Tax\Model\Calculation::class);
$this->customerRepository = $this->_objectManager->create(
\Magento\Customer\Api\CustomerRepositoryInterface::class
);
$this->addressRepository = $this->_objectManager->create(
\Magento\Customer\Api\AddressRepositoryInterface::class
);
$this->groupRepository = $this->_objectManager->create(\Magento\Customer\Api\GroupRepositoryInterface::class);
}
public function testDefaultCustomerTaxClass()
{
$defaultCustomerTaxClass = 3;
$this->assertEquals($defaultCustomerTaxClass, $this->_model->getDefaultCustomerTaxClass(null));
}
public function testGetDefaultRateRequest()
{
$customerDataSet = $this->customerRepository->getById(self::FIXTURE_CUSTOMER_ID);
$address = $this->addressRepository->getById(self::FIXTURE_ADDRESS_ID);
$rateRequest = $this->_model->getRateRequest(null, null, null, null, $customerDataSet->getId());
$this->assertNotNull($rateRequest);
$this->assertEquals($address->getCountryId(), $rateRequest->getCountryId());
$this->assertEquals($address->getRegion()->getRegionId(), $rateRequest->getRegionId());
$this->assertEquals($address->getPostcode(), $rateRequest->getPostcode());
$customerTaxClassId = $this->groupRepository->getById($customerDataSet->getGroupId())->getTaxClassId();
$this->assertEquals($customerTaxClassId, $rateRequest->getCustomerClassId());
}
}
@@ -0,0 +1,140 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model;
class ClassTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\TestFramework\ObjectManager
*/
protected $_objectManager;
protected function setUp(): void
{
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
/**
* @magentoDbIsolation enabled
*/
public function testCheckClassCanBeDeletedCustomerClassAssertException()
{
/** @var $model \Magento\Tax\Model\ClassModel */
$model = $this->_objectManager->create(
\Magento\Tax\Model\ClassModel::class
)->getCollection()->setClassTypeFilter(
\Magento\Tax\Model\ClassModel::TAX_CLASS_TYPE_CUSTOMER
)->getFirstItem();
$this->expectException(\Magento\Framework\Exception\CouldNotDeleteException::class);
$model->delete();
}
/**
* @magentoDbIsolation enabled
*/
public function testCheckClassCanBeDeletedProductClassAssertException()
{
/** @var $model \Magento\Tax\Model\ClassModel */
$model = $this->_objectManager->create(
\Magento\Tax\Model\ClassModel::class
)->getCollection()->setClassTypeFilter(
\Magento\Tax\Model\ClassModel::TAX_CLASS_TYPE_PRODUCT
)->getFirstItem();
$this->_objectManager->create(
\Magento\Catalog\Model\Product::class
)->setTypeId(
'simple'
)->setAttributeSetId(
4
)->setName(
'Simple Product'
)->setSku(
uniqid()
)->setPrice(
10
)->setMetaTitle(
'meta title'
)->setMetaKeyword(
'meta keyword'
)->setMetaDescription(
'meta description'
)->setVisibility(
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH
)->setStatus(
\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED
)->setTaxClassId(
$model->getId()
)->save();
$this->expectException(\Magento\Framework\Exception\CouldNotDeleteException::class);
$model->delete();
}
/**
* @magentoDbIsolation enabled
* @dataProvider classesDataProvider
*/
public function testCheckClassCanBeDeletedPositiveResult($classType)
{
/** @var $model \Magento\Tax\Model\ClassModel */
$model = $this->_objectManager->create(\Magento\Tax\Model\ClassModel::class);
$model->setClassName('TaxClass' . uniqid())->setClassType($classType)->isObjectNew(true);
$model->save();
$model->delete();
}
public function classesDataProvider()
{
return [
[\Magento\Tax\Model\ClassModel::TAX_CLASS_TYPE_CUSTOMER],
[\Magento\Tax\Model\ClassModel::TAX_CLASS_TYPE_PRODUCT]
];
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testCheckClassCanBeDeletedCustomerClassUsedInTaxRule()
{
/** @var $registry \Magento\Framework\Registry */
$registry = $this->_objectManager->get(\Magento\Framework\Registry::class);
/** @var $taxRule \Magento\Tax\Model\Calculation\Rule */
$taxRule = $registry->registry('_fixture/Magento_Tax_Model_Calculation_Rule');
$customerClasses = $taxRule->getCustomerTaxClasses();
/** @var $model \Magento\Tax\Model\ClassModel */
$model = $this->_objectManager->create(\Magento\Tax\Model\ClassModel::class)->load($customerClasses[0]);
$this->expectException(\Magento\Framework\Exception\CouldNotDeleteException::class);
$this->expectExceptionMessage('You cannot delete this tax class because it is used in' .
' Tax Rules. You have to delete the rules it is used in first.');
$model->delete();
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testCheckClassCanBeDeletedProductClassUsedInTaxRule()
{
/** @var $registry \Magento\Framework\Registry */
$registry = $this->_objectManager->get(\Magento\Framework\Registry::class);
/** @var $taxRule \Magento\Tax\Model\Calculation\Rule */
$taxRule = $registry->registry('_fixture/Magento_Tax_Model_Calculation_Rule');
$productClasses = $taxRule->getProductTaxClasses();
/** @var $model \Magento\Tax\Model\ClassModel */
$model = $this->_objectManager->create(\Magento\Tax\Model\ClassModel::class)->load($productClasses[0]);
$this->expectException(\Magento\Framework\Exception\CouldNotDeleteException::class);
$this->expectExceptionMessage('You cannot delete this tax class because it is used in' .
' Tax Rules. You have to delete the rules it is used in first.');
$model->delete();
}
}
@@ -0,0 +1,38 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model;
class ConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Tax\Model\Config
*/
protected $_model = null;
protected function setUp(): void
{
$this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Tax\Model\Config::class
);
}
public function testSetPriceIncludesTax()
{
$this->assertFalse($this->_model->priceIncludesTax());
$this->assertSame($this->_model, $this->_model->setPriceIncludesTax(1));
$this->assertTrue($this->_model->priceIncludesTax());
$this->_model->setPriceIncludesTax(null);
$this->assertFalse($this->_model->priceIncludesTax());
}
/**
* @magentoConfigFixture current_store tax/calculation/price_includes_tax 1
*/
public function testPriceIncludesTaxNonDefault()
{
$this->assertTrue($this->_model->priceIncludesTax());
}
}
@@ -0,0 +1,60 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\Rate;
use Magento\Tax\Model\Calculation\Rate;
use Magento\Tax\Model\Rate\Provider;
use Magento\Tax\Model\ResourceModel\Calculation\Rate\Collection;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\Api\SearchCriteriaBuilder;
/**
* Class ProviderTest provides coverage
* of Tax Rate model options provider.
*/
class ProviderTest extends \PHPUnit\Framework\TestCase
{
/**
* Test of requesting tax rates by search criteria.
*/
public function testToOptionArray()
{
$objectManager = Bootstrap::getObjectManager();
$optionsCount = 1;
/** @var Collection $collection */
$collection = $objectManager->get(Collection::class);
$expectedResult = [];
/** @var $taxRate Rate */
foreach ($collection as $taxRate) {
$expectedResult[] = ['value' => $taxRate->getId(), 'label' => $taxRate->getCode()];
if (count($expectedResult) >= $optionsCount) {
break;
}
}
/** @var Source $source */
if (empty($expectedResult)) {
$this->fail('Preconditions failed: At least one tax rate should be available.');
}
$provider = $objectManager->get(Provider::class);
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $objectManager->create(SearchCriteriaBuilder::class);
$searchCriteriaBuilder->setPageSize($optionsCount);
$searchCriteriaBuilder->setCurrentPage(1);
$searchCriteria = $searchCriteriaBuilder->create();
$this->assertEquals(
$expectedResult,
$provider->toOptionArray($searchCriteria),
'Tax rate options are invalid.'
);
}
}
@@ -0,0 +1,66 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\Rate;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Tax\Model\Rate\Provider;
class SourceTest extends \Magento\TestFramework\Indexer\TestCase
{
public static function setUpBeforeClass(): void
{
$db = Bootstrap::getInstance()->getBootstrap()
->getApplication()
->getDbInstance();
if (!$db->isDbDumpExists()) {
throw new \LogicException('DB dump does not exist.');
}
$db->restoreFromDbDump();
parent::setUpBeforeClass();
}
/**
* @magentoDbIsolation disabled
*/
public function testToOptionArray()
{
/** @var \Magento\Tax\Model\ResourceModel\Calculation\Rate\Collection $collection */
$collection = Bootstrap::getObjectManager()->get(
\Magento\Tax\Model\ResourceModel\Calculation\Rate\Collection::class
);
$taxRateProvider = Bootstrap::getObjectManager()->get(Provider::class);
$expectedResult = [];
/** @var $taxRate \Magento\Tax\Model\Calculation\Rate */
foreach ($collection as $taxRate) {
$expectedResult[] = ['value' => $taxRate->getId(), 'label' => $taxRate->getCode()];
if (count($expectedResult) >= $taxRateProvider->getPageSize()) {
break;
}
}
/** @var \Magento\Tax\Model\Rate\Source $source */
if (empty($expectedResult)) {
$this->fail('Preconditions failed: At least one tax rate should be available.');
}
$source = Bootstrap::getObjectManager()->get(\Magento\Tax\Model\Rate\Source::class);
$this->assertEquals(
$expectedResult,
$source->toOptionArray(),
'Tax rate options are invalid.'
);
}
/**
* teardown
*/
protected function tearDown(): void
{
parent::tearDown();
}
}
@@ -0,0 +1,67 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\ResourceModel\Calculation\Rule;
class CollectionTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\TestFramework\ObjectManager
*/
protected $_objectManager;
protected function setUp(): void
{
$this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
/**
* Test setClassTypeFilter with correct Class Type
*
* @param $classType
* @param $elementId
* @param $expected
*
* @dataProvider setClassTypeFilterDataProvider
*/
public function testSetClassTypeFilter($classType, $elementId, $expected)
{
$collection = $this->_objectManager->create(
\Magento\Tax\Model\ResourceModel\Calculation\Rule\Collection::class
);
$collection->setClassTypeFilter($classType, $elementId);
$this->assertMatchesRegularExpression($expected, (string)$collection->getSelect());
}
public function setClassTypeFilterDataProvider()
{
return [
[
\Magento\Tax\Model\ClassModel::TAX_CLASS_TYPE_PRODUCT,
1,
'/`?cd`?\.`?product_tax_class_id`? = [\S]{0,1}1[\S]{0,1}/',
],
[
\Magento\Tax\Model\ClassModel::TAX_CLASS_TYPE_CUSTOMER,
1,
'/`?cd`?\.`?customer_tax_class_id`? = [\S]{0,1}1[\S]{0,1}/'
]
];
}
/**
* Test setClassTypeFilter with wrong Class Type
*
*/
public function testSetClassTypeFilterWithWrongType()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$collection = $this->_objectManager->create(
\Magento\Tax\Model\ResourceModel\Calculation\Rule\Collection::class
);
$collection->setClassTypeFilter('WrongType', 1);
}
}
@@ -0,0 +1,113 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\ResourceModel;
use Magento\Framework\DataObject;
use Magento\Framework\Registry;
use Magento\Tax\Api\TaxRateRepositoryInterface;
use Magento\Tax\Api\TaxRuleRepositoryInterface;
use Magento\Tax\Test\Fixture\CustomerTaxClass as CustomerTaxClassFixture;
use Magento\Tax\Test\Fixture\ProductTaxClass as ProductTaxClassFixture;
use Magento\Tax\Test\Fixture\TaxRate as TaxRateFixture;
use Magento\Tax\Test\Fixture\TaxRule as TaxRuleFixture;
use Magento\TestFramework\Fixture\AppIsolation;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorage;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
class CalculationTest extends TestCase
{
/** @var $objectManager ObjectManager */
private $objectManager;
/**
* @var DataFixtureStorage
*/
private $fixtures;
/**
* @inheirtDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->fixtures = Bootstrap::getObjectManager()->get(DataFixtureStorageManager::class)->getStorage();
}
/**
* Test that Tax Rate applied only once
*
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testGetRate()
{
$taxRule = $this->objectManager->get(Registry::class)
->registry('_fixture/Magento_Tax_Model_Calculation_Rule');
$customerTaxClasses = $taxRule->getCustomerTaxClassIds();
$productTaxClasses = $taxRule->getProductTaxClassIds();
$taxRate = $this->objectManager->get(Registry::class)
->registry('_fixture/Magento_Tax_Model_Calculation_Rate');
$data = new DataObject();
$data->setData(
[
'tax_country_id' => 'US',
'taxregion_id' => '12',
'tax_postcode' => '5555',
'customer_class_id' => $customerTaxClasses[0],
'product_class_id' => $productTaxClasses[0],
]
);
$taxCalculation = $this->objectManager->get(Calculation::class);
$this->assertEquals($taxRate->getRateIds(), $taxCalculation->getRate($data));
}
#[
AppIsolation(true),
DataFixture(CustomerTaxClassFixture::class, as: 'c1'),
DataFixture(ProductTaxClassFixture::class, as: 'p1'),
DataFixture(
TaxRateFixture::class,
['tax_country_id' => 'PT', 'tax_postcode' => '96*', 'tax_region_id' => 12],
'rate'
),
DataFixture(
TaxRuleFixture::class,
[
'customer_tax_class_ids' => ['$c1.id$'],
'product_tax_class_ids' => ['$p1.id$'],
'tax_rate_ids' => ['$rate.id$']
],
'rule'
)
]
public function testGetRateForPortugal()
{
/** @var TaxRuleRepositoryInterface $taxRule */
$taxRule = $this->objectManager->get(TaxRuleRepositoryInterface::class);
$customerTaxClasses = $taxRule->get($this->fixtures->get('rule')->getId())->getCustomerTaxClassIds();
$productTaxClasses = $taxRule->get($this->fixtures->get('rule')->getId())->getProductTaxClassIds();
/** @var $taxRate TaxRateRepositoryInterface $taxRule */
$taxRate = $this->objectManager->get(TaxRateRepositoryInterface::class);
$data = new DataObject([
'country_id' => 'PT',
'region_id' => '12',
'postcode' => '9600-111',
'customer_class_id' => $customerTaxClasses[0],
'product_class_id' => $productTaxClasses[0],
]);
$taxCalculation = $this->objectManager->get(Calculation::class);
$this->assertEquals(
$taxRate->get($this->fixtures->get('rate')->getId())->getRate(),
$taxCalculation->getRate($data)
);
}
}
@@ -0,0 +1,38 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\ResourceModel\Report;
class CollectionTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Tax\Model\ResourceModel\Report\Collection
*/
private $_collection;
protected function setUp(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_collection = $objectManager->create(\Magento\Tax\Model\ResourceModel\Report\Collection::class);
$this->_collection->setPeriod('day')->setDateRange(null, null)->addStoreFilter([1]);
}
/**
* @magentoDataFixture Magento/Tax/_files/order_with_tax.php
* @magentoDataFixture Magento/Tax/_files/report_tax.php
*/
public function testGetItems()
{
$expectedResult = [
['code' => 'tax_code', 'percent' => 10, 'orders_count' => 1, 'tax_base_amount_sum' => 20],
];
$actualResult = [];
/** @var \Magento\Reports\Model\Item $reportItem */
foreach ($this->_collection->getItems() as $reportItem) {
$actualResult[] = array_intersect_key($reportItem->getData(), $expectedResult[0]);
}
$this->assertEquals($expectedResult, $actualResult);
}
}
@@ -0,0 +1,727 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\Sales\Total\Quote;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Quote\Model\Quote;
use Magento\Tax\Model\Config;
use Magento\Tax\Model\Calculation;
use Magento\Quote\Model\Quote\Item\Updater;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\Api\Filter;
use Magento\Framework\Api\Search\FilterGroup;
use Magento\Framework\Api\SearchCriteriaInterface;
/**
* Setup utility for quote
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class SetupUtil
{
/**
* Default tax related configurations
*
* @var array
*/
protected $defaultConfig = [
Config::CONFIG_XML_PATH_SHIPPING_TAX_CLASS => '0',
Config::CONFIG_XML_PATH_PRICE_INCLUDES_TAX => 0, //Excluding tax
Config::CONFIG_XML_PATH_SHIPPING_INCLUDES_TAX => 0, //Excluding tax
Config::CONFIG_XML_PATH_BASED_ON => 'shipping', // or 'billing'
Config::CONFIG_XML_PATH_APPLY_ON => '0',
Config::CONFIG_XML_PATH_APPLY_AFTER_DISCOUNT => '0',
Config::CONFIG_XML_PATH_DISCOUNT_TAX => '0',
Config::XML_PATH_ALGORITHM => Calculation::CALC_TOTAL_BASE,
//@TODO: add config for cross border trade
];
const TAX_RATE_TX = 'tax_rate_tx';
const TAX_RATE_AUSTIN = 'tax_rate_austin';
const TAX_RATE_SHIPPING = 'tax_rate_shipping';
const TAX_STORE_RATE = 'tax_store_rate';
const REGION_TX = '57';
const REGION_CA = '12';
const COUNTRY_US = 'US';
const AUSTIN_POST_CODE = '79729';
/**
* Tax rates
*
* @var array
*/
protected $taxRates = [
self::TAX_RATE_TX => [
'data' => [
'tax_country_id' => self::COUNTRY_US,
'tax_region_id' => self::REGION_TX,
'tax_postcode' => '*',
'code' => self::TAX_RATE_TX,
'rate' => '20',
],
'id' => null,
],
self::TAX_RATE_AUSTIN => [
'data' => [
'tax_country_id' => self::COUNTRY_US,
'tax_region_id' => self::REGION_TX,
'tax_postcode' => self::AUSTIN_POST_CODE,
'code' => self::TAX_RATE_AUSTIN,
'rate' => '5',
],
'id' => null,
],
self::TAX_RATE_SHIPPING => [
'data' => [
'tax_country_id' => self::COUNTRY_US,
'tax_region_id' => '*',
'tax_postcode' => '*',
'code' => self::TAX_RATE_SHIPPING,
'rate' => '7.5',
],
'id' => null,
],
self::TAX_STORE_RATE => [
'data' => [
'tax_country_id' => self::COUNTRY_US,
'tax_region_id' => self::REGION_CA,
'tax_postcode' => '*',
'code' => self::TAX_STORE_RATE,
'rate' => '8.25',
],
'id' => null,
],
];
const PRODUCT_TAX_CLASS_1 = 'product_tax_class_1';
const PRODUCT_TAX_CLASS_2 = 'product_tax_class_2';
const SHIPPING_TAX_CLASS = 'shipping_tax_class';
/**
* List of product tax class that will be created
*
* @var array
*/
protected $productTaxClasses = [
self::PRODUCT_TAX_CLASS_1 => null,
self::PRODUCT_TAX_CLASS_2 => null,
self::SHIPPING_TAX_CLASS => null,
];
const CUSTOMER_TAX_CLASS_1 = 'customer_tax_class_1';
const CUSTOMER_PASSWORD = 'password';
/**
* List of customer tax class to be created
*
* @var array
*/
protected $customerTaxClasses = [
self::CUSTOMER_TAX_CLASS_1 => null,
];
/**
* List of tax rules
*
* @var array
*/
protected $taxRules = [];
const CONFIG_OVERRIDES = 'config_overrides';
const TAX_RATE_OVERRIDES = 'tax_rate_overrides';
const TAX_RULE_OVERRIDES = 'tax_rule_overrides';
/**
* Default data for shopping cart rule
*
* @var array
*/
protected $defaultShoppingCartPriceRule = [
'name' => 'Shopping Cart Rule',
'is_active' => 1,
'customer_group_ids' => [\Magento\Customer\Model\GroupManagement::CUST_GROUP_ALL],
'coupon_type' => \Magento\SalesRule\Model\Rule::COUPON_TYPE_NO_COUPON,
'simple_action' => 'by_percent',
'discount_amount' => 40,
'discount_step' => 0,
'stop_rules_processing' => 1,
'apply_to_shipping' => 0,
'website_ids' => [1],
];
/**
* Object manager
*
* @var \Magento\Framework\ObjectManagerInterface
*/
public $objectManager;
/**
* @var \Magento\Customer\Api\CustomerRepositoryInterface
*/
protected $customerRepository;
/**
* @var \Magento\Customer\Api\AccountManagementInterface
*/
protected $accountManagement;
/**
* @param \Magento\Framework\ObjectManagerInterface $objectManager
*/
public function __construct($objectManager)
{
$this->objectManager = $objectManager;
$this->customerRepository = $this->objectManager->create(
\Magento\Customer\Api\CustomerRepositoryInterface::class
);
$this->accountManagement = $this->objectManager->create(
\Magento\Customer\Api\AccountManagementInterface::class
);
}
/**
* Create customer tax classes
*
* @return $this
*/
protected function createCustomerTaxClass()
{
foreach (array_keys($this->customerTaxClasses) as $className) {
$this->customerTaxClasses[$className] = $this->objectManager->create(\Magento\Tax\Model\ClassModel::class)
->setClassName($className)
->setClassType(\Magento\Tax\Model\ClassModel::TAX_CLASS_TYPE_CUSTOMER)
->save()
->getId();
}
return $this;
}
/**
* Create product tax classes
*
* @return $this
*/
protected function createProductTaxClass()
{
foreach (array_keys($this->productTaxClasses) as $className) {
$this->productTaxClasses[$className] = $this->objectManager->create(\Magento\Tax\Model\ClassModel::class)
->setClassName($className)
->setClassType(\Magento\Tax\Model\ClassModel::TAX_CLASS_TYPE_PRODUCT)
->save()
->getId();
}
return $this;
}
/**
* Set the configuration.
*
* @param array $configData
* @return $this
*/
protected function setConfig($configData)
{
/** @var \Magento\Config\Model\ResourceModel\Config $config */
$config = $this->objectManager->get(\Magento\Config\Model\ResourceModel\Config::class);
foreach ($configData as $path => $value) {
if ($path == Config::CONFIG_XML_PATH_SHIPPING_TAX_CLASS) {
$value = $this->productTaxClasses[$value];
}
$config->saveConfig(
$path,
$value,
ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
0
);
}
/** @var \Magento\Framework\App\Config\ReinitableConfigInterface $config */
$config = $this->objectManager->get(\Magento\Framework\App\Config\ReinitableConfigInterface::class);
$config->reinit();
return $this;
}
/**
* Create tax rates
*
* @param array $overrides
* @return $this
*/
protected function createTaxRates($overrides)
{
$taxRateOverrides = empty($overrides[self::TAX_RATE_OVERRIDES]) ? [] : $overrides[self::TAX_RATE_OVERRIDES];
foreach (array_keys($this->taxRates) as $taxRateCode) {
if (isset($taxRateOverrides[$taxRateCode])) {
$this->taxRates[$taxRateCode]['data']['rate'] = $taxRateOverrides[$taxRateCode];
}
$this->taxRates[$taxRateCode]['id'] = $this->objectManager->create(
\Magento\Tax\Model\Calculation\Rate::class
)
->setData($this->taxRates[$taxRateCode]['data'])
->save()
->getId();
}
return $this;
}
/**
* Convert the code to id for productTaxClass, customerTaxClass and taxRate in taxRuleOverrideData
*
* @param array $taxRuleOverrideData
* @param array $taxRateIds
* @return array
*/
protected function processTaxRuleOverrides($taxRuleOverrideData, $taxRateIds)
{
if (!empty($taxRuleOverrideData['customer_tax_class_ids'])) {
$customerTaxClassIds = [];
foreach ($taxRuleOverrideData['customer_tax_class_ids'] as $customerClassCode) {
$customerTaxClassIds[] = $this->customerTaxClasses[$customerClassCode];
}
$taxRuleOverrideData['customer_tax_class_ids'] = $customerTaxClassIds;
}
if (!empty($taxRuleOverrideData['product_tax_class_ids'])) {
$productTaxClassIds = [];
foreach ($taxRuleOverrideData['product_tax_class_ids'] as $productClassCode) {
$productTaxClassIds[] = $this->productTaxClasses[$productClassCode];
}
$taxRuleOverrideData['product_tax_class_ids'] = $productTaxClassIds;
}
if (!empty($taxRuleOverrideData['tax_rate_ids'])) {
$taxRateIdsForRule = [];
foreach ($taxRuleOverrideData['tax_rate_ids'] as $taxRateCode) {
$taxRateIdsForRule[] = $taxRateIds[$taxRateCode];
}
$taxRuleOverrideData['tax_rate_ids'] = $taxRateIdsForRule;
}
return $taxRuleOverrideData;
}
/**
* Return a list of product tax class ids NOT including shipping product tax class
*
* @return array
*/
protected function getProductTaxClassIds()
{
$productTaxClassIds = [];
foreach ($this->productTaxClasses as $productTaxClassName => $productTaxClassId) {
if ($productTaxClassName != self::SHIPPING_TAX_CLASS) {
$productTaxClassIds[] = $productTaxClassId;
}
}
return $productTaxClassIds;
}
/**
* Return a list of tax rate ids NOT including shipping tax rate
*
* @return array
*/
protected function getDefaultTaxRateIds()
{
$taxRateIds = [
$this->taxRates[self::TAX_RATE_TX]['id'],
$this->taxRates[self::TAX_STORE_RATE]['id'],
];
return $taxRateIds;
}
/**
* Return the default customer group tax class id
*
* @return int
*/
public function getDefaultCustomerTaxClassId()
{
/** @var \Magento\Customer\Api\GroupManagementInterface $groupManagement */
$groupManagement = $this->objectManager->get(\Magento\Customer\Api\GroupManagementInterface::class);
$defaultGroup = $groupManagement->getDefaultGroup();
return $defaultGroup->getTaxClassId();
}
/**
* Create tax rules
*
* @param array $overrides
* @return $this
*/
protected function createTaxRules($overrides)
{
$taxRateIds = [];
foreach ($this->taxRates as $taxRateCode => $taxRate) {
$taxRateIds[$taxRateCode] = $taxRate['id'];
}
//The default customer tax class id is used to calculate store tax rate
$customerClassIds = [
$this->customerTaxClasses[self::CUSTOMER_TAX_CLASS_1],
$this->getDefaultCustomerTaxClassId()
];
//By default create tax rule that covers all product tax classes except SHIPPING_TAX_CLASS
//The tax rule will cover all tax rates except TAX_RATE_SHIPPING
$taxRuleDefaultData = [
'code' => 'Test Rule',
'priority' => '0',
'position' => '0',
'customer_tax_class_ids' => $customerClassIds,
'product_tax_class_ids' => $this->getProductTaxClassIds(),
'tax_rate_ids' => $this->getDefaultTaxRateIds(),
];
//Create tax rules
if (empty($overrides[self::TAX_RULE_OVERRIDES])) {
//Create separate shipping tax rule
$shippingTaxRuleData = [
'code' => 'Shipping Tax Rule',
'priority' => '0',
'position' => '0',
'customer_tax_class_ids' => $customerClassIds,
'product_tax_class_ids' => [$this->productTaxClasses[self::SHIPPING_TAX_CLASS]],
'tax_rate_ids' => [$this->taxRates[self::TAX_RATE_SHIPPING]['id']],
];
$this->taxRules[$shippingTaxRuleData['code']] = $this->objectManager
->create(\Magento\Tax\Model\Calculation\Rule::class)
->setData($shippingTaxRuleData)
->save()
->getId();
//Create a default tax rule
$this->taxRules[$taxRuleDefaultData['code']] = $this->objectManager
->create(\Magento\Tax\Model\Calculation\Rule::class)
->setData($taxRuleDefaultData)
->save()
->getId();
} else {
foreach ($overrides[self::TAX_RULE_OVERRIDES] as $taxRuleOverrideData) {
//convert code to id for productTaxClass, customerTaxClass and taxRate
$taxRuleOverrideData = $this->processTaxRuleOverrides($taxRuleOverrideData, $taxRateIds);
$mergedTaxRuleData = array_merge($taxRuleDefaultData, $taxRuleOverrideData);
$this->taxRules[$mergedTaxRuleData['code']] = $this->objectManager
->create(\Magento\Tax\Model\Calculation\Rule::class)
->setData($mergedTaxRuleData)
->save()
->getId();
}
}
return $this;
}
/**
* Set up tax classes, tax rates and tax rules
* The override structure:
* override['self::CONFIG_OVERRIDES']
* [
* [config_path => config_value]
* ]
* override['self::TAX_RATE_OVERRIDES']
* [
* ['tax_rate_code' => tax_rate]
* ]
* override['self::TAX_RULE_OVERRIDES']
* [
* [
* 'code' => code //Required, has to be unique
* 'priority' => 0
* 'position' => 0
* 'tax_customer_class' => array of customer tax class names as defined in this class
* 'tax_product_class' => array of product tax class names as defined in this class
* 'tax_rate' => array of tax rate codes as defined in this class
* ]
* ]
*
* @param array $overrides
* @return void
*/
public function setupTax($overrides)
{
//Create product tax classes
$this->createProductTaxClass();
//Create customer tax classes
$this->createCustomerTaxClass();
//Create tax rates
$this->createTaxRates($overrides);
//Create tax rules
$this->createTaxRules($overrides);
//Tax calculation configuration
if (!empty($overrides[self::CONFIG_OVERRIDES])) {
$this->setConfig($overrides[self::CONFIG_OVERRIDES]);
}
}
/**
* Create a simple product with given sku, price and tax class
*
* @param string $sku
* @param float $price
* @param int $taxClassId
* @return \Magento\Catalog\Model\Product
*/
public function createSimpleProduct($sku, $price, $taxClassId)
{
/** @var \Magento\Catalog\Model\Product $product */
$product = $this->objectManager->create(\Magento\Catalog\Model\Product::class);
$product->isObjectNew(true);
$product->setTypeId('simple')
->setAttributeSetId(4)
->setName('Simple Product' . $sku)
->setSku($sku)
->setPrice($price)
->setTaxClassId($taxClassId)
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1
]
)->setMetaTitle('meta title')
->setMetaKeyword('meta keyword')
->setMetaDescription('meta description')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->save();
$product = $product->load($product->getId());
return $product;
}
/**
* Create a customer group and associated it with given customer tax class
*
* @param int $customerTaxClassId
* @return int
*/
protected function createCustomerGroup($customerTaxClassId)
{
/** @var \Magento\Customer\Api\GroupRepositoryInterface $groupRepository */
$groupRepository = $this->objectManager->create(\Magento\Customer\Api\GroupRepositoryInterface::class);
$customerGroupFactory = $this->objectManager->create(\Magento\Customer\Api\Data\GroupInterfaceFactory::class);
$customerGroup = $customerGroupFactory->create()
->setCode('custom_group')
->setTaxClassId($customerTaxClassId);
$customerGroupId = $groupRepository->save($customerGroup)->getId();
return $customerGroupId;
}
/**
* Create a customer
*
* @return \Magento\Customer\Api\Data\CustomerInterface
*/
protected function createCustomer()
{
$customerGroupId = $this->createCustomerGroup($this->customerTaxClasses[self::CUSTOMER_TAX_CLASS_1]);
/** @var \Magento\Customer\Model\Customer $customer */
$customer = $this->objectManager->create(\Magento\Customer\Model\Customer::class);
$customer->isObjectNew(true);
$customer->setWebsiteId(1)
->setEntityTypeId(1)
->setAttributeSetId(1)
->setEmail('customer@example.com')
->setPassword('password')
->setGroupId($customerGroupId)
->setStoreId(1)
->setIsActive(1)
->setFirstname('Firstname')
->setLastname('Lastname')
->save();
return $this->customerRepository->getById($customer->getId());
}
/**
* Create customer address
*
* @param array $addressOverride
* @param int $customerId
* @return \Magento\Customer\Model\Address
*/
protected function createCustomerAddress($addressOverride, $customerId)
{
$defaultAddressData = [
'attribute_set_id' => 2,
'telephone' => 3468676,
'postcode' => self::AUSTIN_POST_CODE,
'country_id' => self::COUNTRY_US,
'city' => 'CityM',
'company' => 'CompanyName',
'street' => ['Green str, 67'],
'lastname' => 'Smith',
'firstname' => 'John',
'parent_id' => 1,
'region_id' => self::REGION_TX,
];
$addressData = array_merge($defaultAddressData, $addressOverride);
/** @var \Magento\Customer\Model\Address $customerAddress */
$customerAddress = $this->objectManager->create(\Magento\Customer\Model\Address::class);
$customerAddress->setData($addressData)
->setCustomerId($customerId)
->save();
return $customerAddress;
}
/**
* Create shopping cart rule
*
* @param array $ruleDataOverride
* @return $this
*/
protected function createCartRule($ruleDataOverride)
{
/** @var \Magento\SalesRule\Model\Rule $salesRule */
$salesRule = $this->objectManager->create(\Magento\SalesRule\Model\Rule::class);
$ruleData = array_merge($this->defaultShoppingCartPriceRule, $ruleDataOverride);
$salesRule->setData($ruleData);
$salesRule->save();
return $this;
}
/**
* Create a quote object with customer
*
* @param array $quoteData
* @param \Magento\Customer\Api\Data\CustomerInterface $customer
* @return Quote
*/
protected function createQuote($quoteData, $customer)
{
/** @var \Magento\Customer\Api\AddressRepositoryInterface $addressService */
$addressService = $this->objectManager->create(\Magento\Customer\Api\AddressRepositoryInterface::class);
/** @var array $shippingAddressOverride */
$shippingAddressOverride = empty($quoteData['shipping_address']) ? [] : $quoteData['shipping_address'];
/** @var \Magento\Customer\Model\Address $shippingAddress */
$shippingAddress = $this->createCustomerAddress($shippingAddressOverride, $customer->getId());
/** @var \Magento\Quote\Model\Quote\Address $quoteShippingAddress */
$quoteShippingAddress = $this->objectManager->create(\Magento\Quote\Model\Quote\Address::class);
$quoteShippingAddress->importCustomerAddressData($addressService->getById($shippingAddress->getId()));
/** @var array $billingAddressOverride */
$billingAddressOverride = empty($quoteData['billing_address']) ? [] : $quoteData['billing_address'];
/** @var \Magento\Customer\Model\Address $billingAddress */
$billingAddress = $this->createCustomerAddress($billingAddressOverride, $customer->getId());
/** @var \Magento\Quote\Model\Quote\Address $quoteBillingAddress */
$quoteBillingAddress = $this->objectManager->create(\Magento\Quote\Model\Quote\Address::class);
$quoteBillingAddress->importCustomerAddressData($addressService->getById($billingAddress->getId()));
/** @var Quote $quote */
$quote = $this->objectManager->create(Quote::class);
$quote->setStoreId(1)
->setIsActive(true)
->setIsMultiShipping(false)
->assignCustomerWithAddressChange($customer, $quoteBillingAddress, $quoteShippingAddress)
->setCheckoutMethod('register')
->setPasswordHash($this->accountManagement->getPasswordHash(static::CUSTOMER_PASSWORD));
return $quote;
}
/**
* Add products to quote
*
* @param Quote $quote
* @param array $itemsData
* @return $this
*/
protected function addProductToQuote($quote, $itemsData)
{
foreach ($itemsData as $itemData) {
$sku = $itemData['sku'];
$price = $itemData['price'];
$qty = isset($itemData['qty']) ? $itemData['qty'] : 1;
$taxClassName =
isset($itemData['tax_class_name']) ? $itemData['tax_class_name'] : self::PRODUCT_TAX_CLASS_1;
$taxClassId = $this->productTaxClasses[$taxClassName];
$product = $this->createSimpleProduct($sku, $price, $taxClassId);
$quote->addProduct($product, $qty);
}
return $this;
}
/**
* Create a quote based on given data
*
* @param array $quoteData
*
* @return Quote
*/
public function setupQuote($quoteData)
{
$customer = $this->createCustomer();
$quote = $this->createQuote($quoteData, $customer);
$this->addProductToQuote($quote, $quoteData['items']);
if (isset($quoteData['update_items'])) {
$this->updateItems($quote, $quoteData['update_items']);
}
//Set shipping amount
if (isset($quoteData['shipping_method'])) {
$quote->getShippingAddress()->setShippingMethod($quoteData['shipping_method']);
$quote->getShippingAddress()->setCollectShippingRates(true);
}
//create shopping cart rules if necessary
if (!empty($quoteData['shopping_cart_rules'])) {
foreach ($quoteData['shopping_cart_rules'] as $ruleData) {
$ruleData['customer_group_ids'] = [$customer->getGroupId()];
$this->createCartRule($ruleData);
}
}
return $quote;
}
/**
* Update quote items
*
* @param Quote $quote
* @param array $items
*
* @return void
*/
private function updateItems(Quote $quote, array $items): void
{
$updater = $this->objectManager->get(Updater::class);
$productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$filter = $this->objectManager->create(Filter::class);
$filter->setField('sku')->setValue(array_keys($items));
$filterGroup = $this->objectManager->create(FilterGroup::class);
$filterGroup->setFilters([$filter]);
$searchCriteria = $this->objectManager->create(SearchCriteriaInterface::class);
$searchCriteria->setFilterGroups([$filterGroup]);
$products = $productRepository->getList($searchCriteria)->getItems();
/** @var ProductInterface $product */
foreach ($products as $product) {
$quoteItem = $quote->getItemByProduct($product);
$updater->update(
$quoteItem,
$items[$product->getSku()]
);
}
}
}
@@ -0,0 +1,406 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Magento\Tax\Model\Sales\Total\Quote;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test \Magento\Tax\Model\Sales\Total\Quote\Subtotal
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class SubtotalTest extends \Magento\TestFramework\Indexer\TestCase
{
/**
* Object Manager
*
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var \Magento\Catalog\Api\ProductRepositoryInterface
*/
private $productRepository;
public static function setUpBeforeClass(): void
{
$db = \Magento\TestFramework\Helper\Bootstrap::getInstance()->getBootstrap()
->getApplication()
->getDbInstance();
if (!$db->isDbDumpExists()) {
throw new \LogicException('DB dump does not exist.');
}
$db->restoreFromDbDump();
parent::setUpBeforeClass();
}
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
}
protected function getCustomerById($id)
{
/**
* @var $customerRepository \Magento\Customer\Api\CustomerRepositoryInterface
*/
$customerRepository = $this->objectManager->create(\Magento\Customer\Api\CustomerRepositoryInterface::class);
return $customerRepository->getById($id);
}
/**
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoDataFixture Magento/Tax/_files/tax_classes.php
* @magentoDataFixture Magento/Customer/_files/customer_group.php
* @magentoDataFixture Magento/Catalog/_files/products.php
* @magentoConfigFixture current_store tax/calculation/algorithm UNIT_BASE_CALCULATION
* @dataProvider collectUnitBasedDataProvider
* @param array $quoteItems
* @param array $expected
* @return void
*/
public function testCollectUnitBased(array $quoteItems, array $expected): void
{
$this->quote($quoteItems, $expected);
}
public function collectUnitBasedDataProvider(): array
{
return [
'one_item' => [
[
[
'sku' => 'simple',
'qty' => 2
],
],
[
[
'subtotal' => 20,
'subtotal_incl_tax' => 21.5,
'base_subtotal_total_incl_tax' => 21.5,
'tax_amount' => 1.5,
'discount_amount' => 0,
],
[
[
'tax_amount' => 1.5,
'price' => 10,
'price_incl_tax' => 10.75,
'row_total' => 20,
'row_total_incl_tax' => 21.5,
'tax_percent' => 7.5,
],
],
],
],
];
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoDataFixture Magento/Tax/_files/tax_classes.php
* @magentoDataFixture Magento/Customer/_files/customer_group.php
* @magentoDataFixture Magento/Bundle/_files/product.php
* @magentoConfigFixture current_store tax/calculation/algorithm UNIT_BASE_CALCULATION
* @dataProvider collectUnitBasedBundleProductDataProvider
* @param array $quoteItems
* @param array $expected
* @return void
*/
public function testCollectUnitBasedBundleProduct(array $quoteItems, array $expected): void
{
$productTaxClassId = $this->getProductTaxClassId();
/** @var \Magento\Catalog\Model\Product $product */
$childProduct = $this->productRepository->get('simple');
$childProduct->setTaxClassId($productTaxClassId)->save();
/** @var \Magento\Catalog\Model\Product $product */
$product = $this->productRepository->get('bundle-product');
$product->setTaxClassId($productTaxClassId)
->setPriceType(\Magento\Catalog\Model\Product\Type\AbstractType::CALCULATE_CHILD)
->save();
$quoteItems[0]['product'] = $product;
$this->quote($quoteItems, $expected);
}
public function collectUnitBasedBundleProductDataProvider(): array
{
return [
'one_item' => [
[
[
'sku' => 'bundle-product',
'qty' => 2
],
],
[
[
'subtotal' => 20,
'subtotal_incl_tax' => 21.5,
'base_subtotal_total_incl_tax' => 21.5,
'tax_amount' => 1.5,
'discount_amount' => 0,
],
[
[
'tax_amount' => 1.5,
'price' => 10,
'price_incl_tax' => 10.75,
'row_total' => 20,
'row_total_incl_tax' => 21.5,
'tax_percent' => null,
],
[
'tax_amount' => 1.5,
'price' => 10,
'price_incl_tax' => 10.75,
'row_total' => 20,
'row_total_incl_tax' => 21.5,
'tax_percent' => 7.5,
]
],
],
],
];
}
/**
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
* @magentoConfigFixture current_store tax/calculation/cross_border_trade_enabled 1
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoDataFixture Magento/Tax/_files/tax_classes.php
* @magentoDataFixture Magento/Customer/_files/customer_group.php
* @magentoDataFixture Magento/Catalog/_files/products.php
* @magentoConfigFixture current_store tax/calculation/algorithm UNIT_BASE_CALCULATION
* @magentoConfigFixture current_store tax/calculation/price_includes_tax 1
* @dataProvider collectUnitBasedPriceIncludesTaxDataProvider
* @param array $quoteItems
* @param array $expected
*/
public function testCollectUnitBasedPriceIncludesTax(array $quoteItems, array $expected): void
{
$this->quote($quoteItems, $expected);
}
/**
* @return array
*/
public function collectUnitBasedPriceIncludesTaxDataProvider(): array
{
return [
[
[
[
'sku' => 'simple',
'qty' => 1
],
],
[
[
'subtotal' => 9.3,
'subtotal_incl_tax' => 10,
'base_subtotal_total_incl_tax' => 10,
'tax_amount' => 0.7,
'discount_amount' => 0,
],
[
[
'tax_amount' => 0.7,
'price' => 9.3,
'price_incl_tax' => 10,
'row_total' => 9.3,
'row_total_incl_tax' => 10,
'tax_percent' => 7.5,
],
],
],
],
[
[
[
'sku' => 'simple',
'qty' => 2
],
],
[
[
'subtotal' => 18.6,
'subtotal_incl_tax' => 20,
'base_subtotal_total_incl_tax' => 20,
'tax_amount' => 1.4,
'discount_amount' => 0,
],
[
[
'tax_amount' => 1.4,
'price' => 9.3,
'price_incl_tax' => 10,
'row_total' => 18.6,
'row_total_incl_tax' => 20,
'tax_percent' => 7.5,
],
],
],
],
];
}
/**
* Create quote and assert totals values
*
* @param array $quoteItems
* @param array $expected
* @return void
*/
private function quote(array $quoteItems, array $expected): void
{
$customerTaxClassId = $this->getCustomerTaxClassId();
$fixtureCustomerId = 1;
/** @var \Magento\Customer\Model\Customer $customer */
$customer = $this->objectManager->create(\Magento\Customer\Model\Customer::class)->load($fixtureCustomerId);
/** @var \Magento\Customer\Model\Group $customerGroup */
$customerGroup = $this->objectManager->create(
\Magento\Customer\Model\Group::class
)->load(
'custom_group',
'customer_group_code'
);
$customerGroup->setTaxClassId($customerTaxClassId)->save();
$customer->setGroupId($customerGroup->getId())->save();
$productTaxClassId = $this->getProductTaxClassId();
$quoteShippingAddressDataObject = $this->getShippingAddressDataObject($fixtureCustomerId);
/** @var \Magento\Quote\Model\Quote\Address $quoteShippingAddress */
$quoteShippingAddress = $this->objectManager->create(\Magento\Quote\Model\Quote\Address::class);
$quoteShippingAddress->importCustomerAddressData($quoteShippingAddressDataObject);
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $this->objectManager->create(\Magento\Quote\Model\Quote::class);
$quote->setStoreId(
1
)->setIsActive(
true
)->setIsMultiShipping(
false
)->assignCustomerWithAddressChange(
$this->getCustomerById($customer->getId())
)->setShippingAddress(
$quoteShippingAddress
)->setBillingAddress(
$quoteShippingAddress
)->setCheckoutMethod(
$customer->getMode()
)->setPasswordHash(
$customer->encryptPassword($customer->getPassword())
);
foreach ($quoteItems as $quoteItem) {
$product = $quoteItem['product'] ?? null;
if ($product === null) {
/** @var \Magento\Catalog\Model\Product $product */
$product = $this->productRepository->get($quoteItem['sku'] ?? 'simple');
$product->setTaxClassId($productTaxClassId)->save();
}
$quote->addProduct($product, $quoteItem['qty']);
}
$address = $quote->getShippingAddress();
/** @var \Magento\Quote\Model\ShippingAssignment $shippingAssignment */
$shippingAssignment = $this->objectManager->create(\Magento\Quote\Model\ShippingAssignment::class);
$shipping = $this->objectManager->create(\Magento\Quote\Model\Shipping::class);
$shipping->setAddress($address);
$shippingAssignment->setShipping($shipping);
$shippingAssignment->setItems($address->getAllItems());
/** @var \Magento\Quote\Model\Quote\Address\Total $total */
$total = $this->objectManager->create(\Magento\Quote\Model\Quote\Address\Total::class);
/** @var \Magento\Quote\Model\Quote\Address\Total\Subtotal $addressSubtotalCollector */
$addressSubtotalCollector = $this->objectManager->create(
\Magento\Quote\Model\Quote\Address\Total\Subtotal::class
);
$addressSubtotalCollector->collect($quote, $shippingAssignment, $total);
/** @var \Magento\Tax\Model\Sales\Total\Quote\Subtotal $subtotalCollector */
$subtotalCollector = $this->objectManager->create(\Magento\Tax\Model\Sales\Total\Quote\Subtotal::class);
$subtotalCollector->collect($quote, $shippingAssignment, $total);
$this->assertEquals($address->getSubtotal(), $total->getSubtotal());
$this->assertEquals($address->getBaseSubtotal(), $total->getBaseSubtotal());
$this->assertEquals($address->getBaseSubtotalTotalInclTax(), $total->getBaseSubtotalTotalInclTax());
$this->assertEquals($expected[0], $total->toArray(array_keys($expected[0])));
$actualAddressItemsData = [];
if ($expected[1]) {
$keys = array_keys($expected[1][0]);
/** @var \Magento\Quote\Model\Quote\Address\Item $addressItem */
foreach ($address->getAllItems() as $addressItem) {
$actualAddressItemsData[] = array_intersect_key($addressItem->toArray($keys), array_flip($keys));
}
}
$this->assertEquals($expected[1], $actualAddressItemsData);
}
/**
* Get customer tax class id
*
* @return int
*/
protected function getCustomerTaxClassId()
{
$customerTaxClass = $this->objectManager->create(\Magento\Tax\Model\ClassModel::class);
$fixtureCustomerTaxClass = 'CustomerTaxClass2';
/** @var \Magento\Tax\Model\ClassModel $customerTaxClass */
$customerTaxClass->load($fixtureCustomerTaxClass, 'class_name');
return $customerTaxClass->getId();
}
/**
* Get product tax class id
*
* @return int
*/
protected function getProductTaxClassId()
{
/** @var \Magento\Tax\Model\ClassModel $productTaxClass */
$productTaxClass = $this->objectManager->create(\Magento\Tax\Model\ClassModel::class);
$fixtureProductTaxClass = 'ProductTaxClass1';
$productTaxClass->load($fixtureProductTaxClass, 'class_name');
return $productTaxClass->getId();
}
/**
* @param $fixtureCustomerId
* @return \Magento\Customer\Api\Data\AddressInterface
*/
protected function getShippingAddressDataObject($fixtureCustomerId)
{
$fixtureCustomerAddressId = 1;
$customerAddress = $this->objectManager->create(
\Magento\Customer\Model\Address::class
)->load($fixtureCustomerId);
/** Set data which corresponds tax class fixture */
$customerAddress->setCountryId('US')->setRegionId(12)->save();
/**
* @var $addressRepository \Magento\Customer\Api\AddressRepositoryInterface
*/
$addressRepository = $this->objectManager->get(\Magento\Customer\Api\AddressRepositoryInterface::class);
$quoteShippingAddressDataObject = $addressRepository->getById($fixtureCustomerAddressId);
return $quoteShippingAddressDataObject;
}
}
@@ -0,0 +1,365 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\Sales\Total\Quote;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Quote\Model\Quote\TotalsCollector;
use Magento\TestFramework\Helper\Bootstrap;
require_once __DIR__ . '/SetupUtil.php';
require_once __DIR__ . '/../../../../_files/tax_calculation_data_aggregated.php';
require_once __DIR__ . '/../../../../_files/full_discount_with_tax.php';
/**
* Class TaxTest
*
* Tests sales taxes with discounts/price rules during checkout.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class TaxTest extends \Magento\TestFramework\Indexer\TestCase
{
/**
* @var float
*/
private const EPSILON = 0.0000000001;
/**
* Utility object for setting up tax rates, tax classes and tax rules
*
* @var SetupUtil
*/
protected $setupUtil = null;
/**
* @var TotalsCollector
*/
private $totalsCollector;
/**
* test setup
*/
protected function setUp(): void
{
/** @var \Magento\Framework\ObjectManagerInterface $objectManager */
$objectManager = Bootstrap::getObjectManager();
$this->totalsCollector = $objectManager->create(TotalsCollector::class);
$this->setupUtil = new SetupUtil($objectManager);
parent::setUp();
}
/**
* Test taxes collection for quote.
*
* Quote has customer and product.
* Product tax class and customer group tax class along with billing address have corresponding tax rule.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoDataFixture Magento/Catalog/_files/products.php
* @magentoDataFixture Magento/Tax/_files/tax_classes.php
* @magentoDataFixture Magento/Customer/_files/customer_group.php
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
public function testCollect()
{
/** Preconditions */
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Tax\Model\ClassModel $customerTaxClass */
$customerTaxClass = $objectManager->create(\Magento\Tax\Model\ClassModel::class);
$fixtureCustomerTaxClass = 'CustomerTaxClass2';
$customerTaxClass->load($fixtureCustomerTaxClass, 'class_name');
$fixtureCustomerId = 1;
/** @var \Magento\Customer\Model\Customer $customer */
$customer = $objectManager->create(\Magento\Customer\Model\Customer::class)->load($fixtureCustomerId);
/** @var \Magento\Customer\Model\Group $customerGroup */
$customerGroup = $objectManager->create(\Magento\Customer\Model\Group::class)
->load('custom_group', 'customer_group_code');
$customerGroup->setTaxClassId($customerTaxClass->getId())->save();
$customer->setGroupId($customerGroup->getId())->save();
/** @var \Magento\Tax\Model\ClassModel $productTaxClass */
$productTaxClass = $objectManager->create(\Magento\Tax\Model\ClassModel::class);
$fixtureProductTaxClass = 'ProductTaxClass1';
$productTaxClass->load($fixtureProductTaxClass, 'class_name');
/** @var \Magento\Catalog\Model\Product $product */
$product = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class)->get('simple');
$product->setTaxClassId($productTaxClass->getId())->save();
$fixtureCustomerAddressId = 1;
$customerAddress = $objectManager->create(\Magento\Customer\Model\Address::class)->load($fixtureCustomerId);
/** Set data which corresponds tax class fixture */
$customerAddress->setCountryId('US')->setRegionId(12)->save();
/** @var \Magento\Quote\Model\Quote\Address $quoteShippingAddress */
$quoteShippingAddress = $objectManager->create(\Magento\Quote\Model\Quote\Address::class);
/** @var \Magento\Customer\Api\AddressRepositoryInterface $addressRepository */
$addressRepository = $objectManager->create(\Magento\Customer\Api\AddressRepositoryInterface::class);
$quoteShippingAddress->importCustomerAddressData($addressRepository->getById($fixtureCustomerAddressId));
/** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository */
$customerRepository = $objectManager->create(\Magento\Customer\Api\CustomerRepositoryInterface::class);
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $objectManager->create(\Magento\Quote\Model\Quote::class);
$quote->setStoreId(1)
->setIsActive(true)
->setIsMultiShipping(false)
->assignCustomerWithAddressChange($customerRepository->getById($customer->getId()))
->setShippingAddress($quoteShippingAddress)
->setBillingAddress($quoteShippingAddress)
->setCheckoutMethod($customer->getMode())
->setPasswordHash($customer->encryptPassword($customer->getPassword()))
->addProduct($product->load($product->getId()), 2);
/**
* Execute SUT.
* \Magento\Tax\Model\Sales\Total\Quote\Tax::collect cannot be called separately from
* \Magento\Tax\Model\Sales\Total\Quote\Subtotal::collect because tax to zero amount will be applied.
* That is why it make sense to call collectTotals() instead, which will call SUT in its turn.
*/
$quote->collectTotals();
/** Check results */
$this->assertEquals(
$customerTaxClass->getId(),
$quote->getCustomerTaxClassId(),
'Customer tax class ID in quote is invalid.'
);
$this->assertEquals(
21.5,
$quote->getGrandTotal(),
'Customer tax was collected by \Magento\Tax\Model\Sales\Total\Quote\Tax::collect incorrectly.'
);
}
/**
* Test taxes collection with full discount for quote.
*
* Test tax calculation and price when the discount may be bigger than total
* This method will test the collector through $quote->collectTotals() method
*
* @see \Magento\SalesRule\Model\Utility::deltaRoundingFix
* @magentoDataFixture Magento/Tax/_files/full_discount_with_tax.php
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
public function testFullDiscountWithDeltaRoundingFix()
{
global $fullDiscountIncTax;
$configData = $fullDiscountIncTax['config_data'];
$quoteData = $fullDiscountIncTax['quote_data'];
$expectedResults = $fullDiscountIncTax['expected_result'];
/** @var \Magento\Framework\ObjectManagerInterface $objectManager */
$objectManager = Bootstrap::getObjectManager();
//Setup tax configurations
$this->setupUtil = new SetupUtil($objectManager);
$this->setupUtil->setupTax($configData);
$quote = $this->setupUtil->setupQuote($quoteData);
$quote->collectTotals();
$quoteAddress = $quote->getShippingAddress();
$this->verifyResult($quoteAddress, $expectedResults);
}
/**
* Verify fields in quote item
*
* @param \Magento\Quote\Model\Quote\Address\Item $item
* @param array $expectedItemData
* @return $this
*/
protected function verifyItem($item, $expectedItemData)
{
foreach ($expectedItemData as $key => $value) {
$this->assertEqualsWithDelta($value, $item->getData($key), self::EPSILON, 'item ' . $key . ' is incorrect');
}
return $this;
}
/**
* Verify one tax rate in a tax row
*
* @param array $appliedTaxRate
* @param array $expectedAppliedTaxRate
* @return $this
*/
protected function verifyAppliedTaxRate($appliedTaxRate, $expectedAppliedTaxRate)
{
foreach ($expectedAppliedTaxRate as $key => $value) {
$this->assertEquals($value, $appliedTaxRate[$key], 'Applied tax rate ' . $key . ' is incorrect');
}
return $this;
}
/**
* Verify one row in the applied taxes
*
* @param array $appliedTax
* @param array $expectedAppliedTax
* @return $this
*/
protected function verifyAppliedTax($appliedTax, $expectedAppliedTax)
{
foreach ($expectedAppliedTax as $key => $value) {
if ($key == 'rates') {
foreach ($value as $index => $taxRate) {
$this->verifyAppliedTaxRate($appliedTax['rates'][$index], $taxRate);
}
} else {
$this->assertEquals($value, $appliedTax[$key], 'Applied tax ' . $key . ' is incorrect');
}
}
return $this;
}
/**
* Verify that applied taxes are correct
*
* @param array $appliedTaxes
* @param array $expectedAppliedTaxes
* @return $this
*/
protected function verifyAppliedTaxes($appliedTaxes, $expectedAppliedTaxes)
{
foreach ($expectedAppliedTaxes as $taxRateKey => $expectedTaxRate) {
$this->assertTrue(isset($appliedTaxes[$taxRateKey]), 'Missing tax rate ' . $taxRateKey);
$this->verifyAppliedTax($appliedTaxes[$taxRateKey], $expectedTaxRate);
}
return $this;
}
/**
* Verify fields in quote address
*
* @param \Magento\Quote\Model\Quote\Address $quoteAddress
* @param array $expectedAddressData
* @return $this
*/
protected function verifyQuoteAddress($quoteAddress, $expectedAddressData)
{
foreach ($expectedAddressData as $key => $value) {
if ($key == 'applied_taxes') {
$this->verifyAppliedTaxes($quoteAddress->getAppliedTaxes(), $value);
} else {
$this->assertEqualsWithDelta(
$value,
$quoteAddress->getData($key),
self::EPSILON,
'Quote address ' . $key . ' is incorrect'
);
}
}
return $this;
}
/**
* Verify fields in quote address and quote item are correct
*
* @param \Magento\Quote\Model\Quote\Address $quoteAddress
* @param array $expectedResults
* @return $this
*/
protected function verifyResult($quoteAddress, $expectedResults)
{
$addressData = $expectedResults['address_data'];
$this->verifyQuoteAddress($quoteAddress, $addressData);
$quoteItems = $quoteAddress->getAllItems();
foreach ($quoteItems as $item) {
/** @var \Magento\Quote\Model\Quote\Address\Item $item */
$sku = $item->getProduct()->getSku();
$expectedItemData = $expectedResults['items_data'][$sku];
$this->verifyItem($item, $expectedItemData);
}
return $this;
}
/**
* Test tax calculation with various configuration and combination of items
* This method will test various collectors through $quoteAddress->collectTotals() method
*
* @param array $configData
* @param array $quoteData
* @param array $expectedResults
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
* @dataProvider taxDataProvider
* @return void
*/
public function testTaxCalculation($configData, $quoteData, $expectedResults)
{
$db = \Magento\TestFramework\Helper\Bootstrap::getInstance()->getBootstrap()
->getApplication()
->getDbInstance();
if (!$db->isDbDumpExists()) {
throw new \LogicException('DB dump does not exist.');
}
$db->restoreFromDbDump();
//Setup tax configurations
$this->setupUtil->setupTax($configData);
$quote = $this->setupUtil->setupQuote($quoteData);
$quoteAddress = $quote->getShippingAddress();
$this->totalsCollector->collectAddressTotals($quote, $quoteAddress);
$this->verifyResult($quoteAddress, $expectedResults);
$skus = array_map(function ($item) {
return $item['sku'];
}, $quoteData['items'] ?? []);
$this->removeProducts($skus);
}
/**
* Read the array defined in ../../../../_files/tax_calculation_data_aggregated.php
* and feed it to testTaxCalculation
*
* @return array
*/
public function taxDataProvider()
{
global $taxCalculationData;
return $taxCalculationData;
}
/**
* Cleanup test by removing products.
*
* @param string[] $skus
* @return void
*/
private function removeProducts(array $skus): void
{
$objectManager = Bootstrap::getObjectManager();
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
$registry = $objectManager->get(\Magento\Framework\Registry::class);
/** @var ProductRepositoryInterface $productRepository */
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
foreach ($skus as $sku) {
try {
$productRepository->deleteById($sku);
} catch (NoSuchEntityException $e) {
// product already deleted
}
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,94 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\TaxClass;
use Magento\Tax\Api\Data\TaxClassInterfaceFactory;
use Magento\Tax\Api\Data\TaxClassKeyInterface;
use Magento\Tax\Api\TaxClassManagementInterface;
use Magento\Tax\Model\TaxClass\Key;
use Magento\TestFramework\Helper\Bootstrap;
class ManagementTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Repository
*/
private $taxClassRepository;
/**
* @var Management
*/
private $taxClassManagement;
/**
* @var TaxClassInterfaceFactory
*/
private $taxClassFactory;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var \Magento\Framework\Api\DataObjectHelper
*/
private $dataObjectHelper;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->taxClassRepository = $this->objectManager->create(\Magento\Tax\Api\TaxClassRepositoryInterface::class);
$this->taxClassManagement = $this->objectManager->create(\Magento\Tax\Api\TaxClassManagementInterface::class);
$this->taxClassFactory = $this->objectManager->create(\Magento\Tax\Api\Data\TaxClassInterfaceFactory::class);
$this->dataObjectHelper = $this->objectManager->create(\Magento\Framework\Api\DataObjectHelper::class);
}
/**
* @magentoDbIsolation enabled
*/
public function testGetTaxClassId()
{
$taxClassName = 'Get Me';
$taxClassDataObject = $this->taxClassFactory->create();
$taxClassDataObject->setClassName($taxClassName)
->setClassType(TaxClassManagementInterface::TYPE_CUSTOMER);
$taxClassId = $this->taxClassRepository->save($taxClassDataObject);
/** @var \Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory $taxClassKeyFactory */
$taxClassKeyFactory = $this->objectManager->create(\Magento\Tax\Api\Data\TaxClassKeyInterfaceFactory::class);
$taxClassKeyTypeId = $taxClassKeyFactory->create();
$this->dataObjectHelper->populateWithArray(
$taxClassKeyTypeId,
[
Key::KEY_TYPE => TaxClassKeyInterface::TYPE_ID,
Key::KEY_VALUE => $taxClassId,
],
\Magento\Tax\Api\Data\TaxClassKeyInterface::class
);
$this->assertEquals(
$taxClassId,
$this->taxClassManagement->getTaxClassId($taxClassKeyTypeId, TaxClassManagementInterface::TYPE_CUSTOMER)
);
$taxClassKeyTypeName = $taxClassKeyFactory->create();
$this->dataObjectHelper->populateWithArray(
$taxClassKeyTypeName,
[
Key::KEY_TYPE => TaxClassKeyInterface::TYPE_NAME,
Key::KEY_VALUE => $taxClassName,
],
\Magento\Tax\Api\Data\TaxClassKeyInterface::class
);
$this->assertEquals(
$taxClassId,
$this->taxClassManagement->getTaxClassId($taxClassKeyTypeId, TaxClassManagementInterface::TYPE_CUSTOMER)
);
$this->assertNull($this->taxClassManagement->getTaxClassId(null));
$this->assertNull(
$this->taxClassManagement->getTaxClassId($taxClassKeyTypeName, TaxClassManagementInterface::TYPE_PRODUCT)
);
}
}
@@ -0,0 +1,227 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\TaxClass;
use Magento\Framework\Exception\InputException;
use Magento\Tax\Api\Data\TaxClassInterfaceFactory;
use Magento\Tax\Api\TaxClassManagementInterface;
use Magento\Tax\Model\ClassModel as TaxClassModel;
use Magento\TestFramework\Helper\Bootstrap;
class RepositoryTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Repository
*/
private $taxClassRepository;
/**
* @var TaxClassInterfaceFactory
*/
private $taxClassFactory;
/**
* @var TaxClassModel
*/
private $taxClassModel;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var array
*/
private $predefinedTaxClasses;
const SAMPLE_TAX_CLASS_NAME = 'Wholesale Customer';
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->taxClassRepository = $this->objectManager->create(\Magento\Tax\Api\TaxClassRepositoryInterface::class);
$this->taxClassFactory = $this->objectManager->create(\Magento\Tax\Api\Data\TaxClassInterfaceFactory::class);
$this->taxClassModel = $this->objectManager->create(\Magento\Tax\Model\ClassModel::class);
$this->predefinedTaxClasses = [
TaxClassManagementInterface::TYPE_PRODUCT => 'Taxable Goods',
TaxClassManagementInterface::TYPE_CUSTOMER => 'Retail Customer',
];
}
/**
* @magentoDbIsolation enabled
*/
public function testSave()
{
$taxClassDataObject = $this->taxClassFactory->create();
$taxClassDataObject->setClassName(self::SAMPLE_TAX_CLASS_NAME)
->setClassType(TaxClassManagementInterface::TYPE_CUSTOMER);
$taxClassId = $this->taxClassRepository->save($taxClassDataObject);
$this->assertEquals(self::SAMPLE_TAX_CLASS_NAME, $this->taxClassModel->load($taxClassId)->getClassName());
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveThrowsExceptionIfGivenTaxClassNameIsNotUnique()
{
$this->expectException(\Magento\Framework\Exception\InputException::class);
$this->expectExceptionMessage('A class with the same name already exists for ClassType PRODUCT.');
//ClassType and name combination has to be unique.
//Testing against existing Tax classes which are already setup when the instance is installed
$taxClassDataObject = $this->taxClassFactory->create();
$taxClassDataObject->setClassName($this->predefinedTaxClasses[TaxClassModel::TAX_CLASS_TYPE_PRODUCT])
->setClassType(TaxClassManagementInterface::TYPE_PRODUCT);
$this->taxClassRepository->save($taxClassDataObject);
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveThrowsExceptionIfGivenDataIsInvalid()
{
$taxClassDataObject = $this->taxClassFactory->create();
$taxClassDataObject->setClassName(null)
->setClassType('');
try {
$this->taxClassRepository->save($taxClassDataObject);
} catch (InputException $e) {
$errors = $e->getErrors();
$this->assertEquals('"class_name" is required. Enter and try again.', $errors[0]->getMessage());
$this->assertEquals('"class_type" is required. Enter and try again.', $errors[1]->getMessage());
}
}
/**
* @magentoDbIsolation enabled
*/
public function testGet()
{
$taxClassName = 'Get Me';
$taxClassDataObject = $this->taxClassFactory->create();
$taxClassDataObject->setClassName($taxClassName)
->setClassType(TaxClassManagementInterface::TYPE_CUSTOMER);
$taxClassId = $this->taxClassRepository->save($taxClassDataObject);
$data = $this->taxClassRepository->get($taxClassId);
$this->assertEquals($taxClassId, $data->getClassId());
$this->assertEquals($taxClassName, $data->getClassName());
$this->assertEquals(TaxClassManagementInterface::TYPE_CUSTOMER, $data->getClassType());
}
/**
* @magentoDbIsolation enabled
*/
public function testGetList()
{
$taxClassName = 'Get Me';
$taxClassDataObject = $this->taxClassFactory->create();
$taxClassDataObject->setClassName($taxClassName)
->setClassType(TaxClassManagementInterface::TYPE_CUSTOMER);
$taxClassId = $this->taxClassRepository->save($taxClassDataObject);
/** @var \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = Bootstrap::getObjectManager()->create(
\Magento\Framework\Api\SearchCriteriaBuilder::class
);
/** @var \Magento\Tax\Api\Data\TaxClassSearchResultsInterface */
$searchResult = $this->taxClassRepository->getList($searchCriteriaBuilder->create());
$items = $searchResult->getItems();
/** @var \Magento\Tax\Api\Data\TaxClassInterface */
$taxClass = array_pop($items);
$this->assertInstanceOf(\Magento\Tax\Api\Data\TaxClassInterface::class, $taxClass);
$this->assertEquals($taxClassName, $taxClass->getClassName());
$this->assertEquals($taxClassId, $taxClass->getClassId());
$this->assertEquals(TaxClassManagementInterface::TYPE_CUSTOMER, $taxClass->getClassType());
}
/**
*/
public function testGetThrowsExceptionIfRequestedTaxClassDoesNotExist()
{
$this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class);
$this->expectExceptionMessage('No such entity with class_id = -9999');
$this->taxClassRepository->get(-9999);
}
/**
* @magentoDbIsolation enabled
*/
public function testDeleteById()
{
$taxClassName = 'Delete Me';
$taxClassDataObject = $this->taxClassFactory->create();
$taxClassDataObject->setClassName($taxClassName)
->setClassType(TaxClassModel::TAX_CLASS_TYPE_CUSTOMER);
$taxClassId = $this->taxClassRepository->save($taxClassDataObject);
$this->assertTrue($this->taxClassRepository->deleteById($taxClassId));
// Verify if the tax class is deleted
$this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class);
$this->expectExceptionMessage("No such entity with class_id = $taxClassId");
$this->taxClassRepository->deleteById($taxClassId);
}
/**
*/
public function testDeleteByIdThrowsExceptionIfTargetTaxClassDoesNotExist()
{
$this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class);
$this->expectExceptionMessage('No such entity with class_id = 99999');
$nonexistentTaxClassId = 99999;
$this->taxClassRepository->deleteById($nonexistentTaxClassId);
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveWithExistingTaxClass()
{
$taxClassName = 'New Class Name';
$taxClassDataObject = $this->taxClassFactory->create();
$taxClassDataObject->setClassName($taxClassName)
->setClassType(TaxClassModel::TAX_CLASS_TYPE_CUSTOMER);
$taxClassId = $this->taxClassRepository->save($taxClassDataObject);
$this->assertEquals($taxClassName, $this->taxClassModel->load($taxClassId)->getClassName());
$updatedTaxClassName = 'Updated Class Name';
$taxClassDataObject = $this->taxClassFactory->create();
$taxClassDataObject->setClassName($updatedTaxClassName)
->setClassId($taxClassId)
->setClassType(TaxClassModel::TAX_CLASS_TYPE_CUSTOMER);
$this->assertEquals($taxClassId, $this->taxClassRepository->save($taxClassDataObject));
$this->assertEquals($updatedTaxClassName, $this->taxClassModel->load($taxClassId)->getClassName());
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveThrowsExceptionIfTargetTaxClassHasDifferentClassType()
{
$this->expectException(\Magento\Framework\Exception\InputException::class);
$this->expectExceptionMessage('Updating classType is not allowed.');
$taxClassName = 'New Class Name';
$taxClassDataObject = $this->taxClassFactory->create();
$taxClassDataObject->setClassName($taxClassName)
->setClassType(TaxClassModel::TAX_CLASS_TYPE_CUSTOMER);
$taxClassId = $this->taxClassRepository->save($taxClassDataObject);
$this->assertEquals($taxClassName, $this->taxClassModel->load($taxClassId)->getClassName());
$updatedTaxClassName = 'Updated Class Name';
$taxClassDataObject = $this->taxClassFactory->create();
$taxClassDataObject->setClassName($updatedTaxClassName)
->setClassId($taxClassId)
->setClassType(TaxClassModel::TAX_CLASS_TYPE_PRODUCT);
$this->taxClassRepository->save($taxClassDataObject);
}
}
@@ -0,0 +1,58 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\TaxClass\Source;
use Magento\TestFramework\Helper\Bootstrap;
class CustomerTest extends \PHPUnit\Framework\TestCase
{
public function testGetAllOptions()
{
/** @var \Magento\Tax\Model\ResourceModel\TaxClass\Collection $collection */
$collection = Bootstrap::getObjectManager()->get(\Magento\Tax\Model\ResourceModel\TaxClass\Collection::class);
$expectedResult = [];
/** @var \Magento\Tax\Model\ClassModel $taxClass */
foreach ($collection as $taxClass) {
if ($taxClass->getClassType() == \Magento\Tax\Api\TaxClassManagementInterface::TYPE_CUSTOMER) {
$expectedResult[] = ['value' => $taxClass->getId(), 'label' => $taxClass->getClassName()];
}
}
if (empty($expectedResult)) {
$this->fail('Preconditions failed: At least one tax class should be available.');
}
/** @var \Magento\Tax\Model\TaxClass\Source\Product $source */
$source = Bootstrap::getObjectManager()->get(\Magento\Tax\Model\TaxClass\Source\Customer::class);
$this->assertEquals(
$expectedResult,
$source->getAllOptions(),
'Tax Class options are invalid.'
);
}
public function testGetAllOptionsWithDefaultValues()
{
/** @var \Magento\Tax\Model\ResourceModel\TaxClass\Collection $collection */
$collection = Bootstrap::getObjectManager()->get(\Magento\Tax\Model\ResourceModel\TaxClass\Collection::class);
$expectedResult = [];
/** @var \Magento\Tax\Model\ClassModel $taxClass */
foreach ($collection as $taxClass) {
if ($taxClass->getClassType() == \Magento\Tax\Api\TaxClassManagementInterface::TYPE_CUSTOMER) {
$expectedResult[] = ['value' => $taxClass->getId(), 'label' => $taxClass->getClassName()];
}
}
if (empty($expectedResult)) {
$this->fail('Preconditions failed: At least one tax class should be available.');
}
/** @var \Magento\Tax\Model\TaxClass\Source\Product $source */
$source = Bootstrap::getObjectManager()->get(\Magento\Tax\Model\TaxClass\Source\Customer::class);
$this->assertEquals(
$expectedResult,
$source->getAllOptions(true),
'Tax Class options are invalid.'
);
}
}
@@ -0,0 +1,59 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\TaxClass\Source;
use Magento\TestFramework\Helper\Bootstrap;
class ProductTest extends \PHPUnit\Framework\TestCase
{
public function testGetAllOptions()
{
/** @var \Magento\Tax\Model\ResourceModel\TaxClass\Collection $collection */
$collection = Bootstrap::getObjectManager()->get(\Magento\Tax\Model\ResourceModel\TaxClass\Collection::class);
$expectedResult = [];
/** @var \Magento\Tax\Model\ClassModel $taxClass */
foreach ($collection as $taxClass) {
if ($taxClass->getClassType() == \Magento\Tax\Api\TaxClassManagementInterface::TYPE_PRODUCT) {
$expectedResult[] = ['value' => $taxClass->getId(), 'label' => $taxClass->getClassName()];
}
}
if (empty($expectedResult)) {
$this->fail('Preconditions failed: At least one tax class should be available.');
}
/** @var \Magento\Tax\Model\TaxClass\Source\Product $source */
$source = Bootstrap::getObjectManager()->get(\Magento\Tax\Model\TaxClass\Source\Product::class);
$this->assertEquals(
$expectedResult,
$source->getAllOptions(false),
'Tax Class options are invalid.'
);
}
public function testGetAllOptionsWithDefaultValues()
{
/** @var \Magento\Tax\Model\ResourceModel\TaxClass\Collection $collection */
$collection = Bootstrap::getObjectManager()->get(\Magento\Tax\Model\ResourceModel\TaxClass\Collection::class);
$expectedResult = [];
/** @var \Magento\Tax\Model\ClassModel $taxClass */
foreach ($collection as $taxClass) {
if ($taxClass->getClassType() == \Magento\Tax\Api\TaxClassManagementInterface::TYPE_PRODUCT) {
$expectedResult[] = ['value' => $taxClass->getId(), 'label' => $taxClass->getClassName()];
}
}
if (empty($expectedResult)) {
$this->fail('Preconditions failed: At least one tax class should be available.');
}
$expectedResult = array_merge([['value' => '0', 'label' => __('None')]], $expectedResult);
/** @var \Magento\Tax\Model\TaxClass\Source\Product $source */
$source = Bootstrap::getObjectManager()->get(\Magento\Tax\Model\TaxClass\Source\Product::class);
$this->assertEquals(
$expectedResult,
$source->getAllOptions(true),
'Tax Class options are invalid.'
);
}
}
@@ -0,0 +1,45 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model\TaxClass\Type;
class CustomerTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\TestFramework\ObjectManager
*/
protected $_objectManager;
const GROUP_CODE = 'Test Group';
/**
* @magentoDbIsolation enabled
*/
public function testIsAssignedToObjects()
{
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$groupFactory = $this->_objectManager->create(\Magento\Customer\Api\Data\GroupInterfaceFactory::class);
/* Create a tax class */
$model = $this->_objectManager->create(\Magento\Tax\Model\ClassModel::class);
$model->setClassName("Test Group Tax Class")
->setClassType(\Magento\Tax\Model\ClassModel::TAX_CLASS_TYPE_CUSTOMER)
->isObjectNew(true);
$model->save();
$taxClassId = $model->getId();
$model->setId($taxClassId);
/** @var $groupRepository \Magento\Customer\Api\GroupRepositoryInterface */
$groupRepository = $this->_objectManager->create(\Magento\Customer\Api\GroupRepositoryInterface::class);
$group = $groupFactory->create()->setId(null)->setCode(self::GROUP_CODE)->setTaxClassId($taxClassId);
$groupRepository->save($group);
/** @var $model \Magento\Tax\Model\TaxClass\Type\Customer */
$model = $this->_objectManager->create(\Magento\Tax\Model\TaxClass\Type\Customer::class);
$model->setId($taxClassId);
$this->assertTrue($model->isAssignedToObjects());
}
}
@@ -0,0 +1,44 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model;
use Magento\TestFramework\Helper\Bootstrap;
class TaxRateCollectionTest extends \PHPUnit\Framework\TestCase
{
public function testCreateTaxRateCollectionItem()
{
/** @var \Magento\Tax\Model\ResourceModel\Calculation\Rate\Collection $collection */
$collection = Bootstrap::getObjectManager()->get(
\Magento\Tax\Model\ResourceModel\Calculation\Rate\Collection::class
);
$dbTaxRatesQty = $collection->count();
if (($dbTaxRatesQty == 0) || ($collection->getFirstItem()->getId() != 1)) {
$this->fail("Preconditions failed.");
}
/** @var \Magento\Tax\Model\TaxRateCollection $taxRatesCollection */
$taxRatesCollection = Bootstrap::getObjectManager()
->create(\Magento\Tax\Model\TaxRateCollection::class);
$collectionTaxRatesQty = $taxRatesCollection->count();
$this->assertEquals($dbTaxRatesQty, $collectionTaxRatesQty, 'Tax rates quantity is invalid.');
$taxRate = $taxRatesCollection->getFirstItem()->getData();
$expectedTaxRateData = [
'code' => 'US-CA-*-Rate 1',
'tax_calculation_rate_id' => '1',
'rate' => 8.25,
'region_name' => 'CA',
'tax_country_id' => 'US',
'tax_postcode' => '*',
'tax_region_id' => '12',
'titles' => [],
'zip_is_range' => null,
'zip_from' => null,
'zip_to' => null,
];
$this->assertEquals($expectedTaxRateData, $taxRate, 'Tax rate data is invalid.');
}
}
@@ -0,0 +1,113 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model;
use Magento\TestFramework\Helper\Bootstrap;
class TaxRateManagementTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Tax\Api\TaxRuleRepositoryInterface
*/
private $taxRuleRepository;
/**
* @var TaxRuleFixtureFactory
*/
private $taxRuleFixtureFactory;
/**
* Array of default tax classes ids
*
* Key is class name
*
* @var int[]
*/
private $taxClasses;
/**
* Array of default tax rates ids.
*
* Key is rate percentage as string.
*
* @var int[]
*/
private $taxRates;
/**
* Array of default tax rules ids.
*
* Key is rule code.
*
* @var int[]
*/
private $taxRules;
/**
* @var \Magento\Tax\Api\TaxRateRepositoryInterface
*/
private $taxRateRepository;
/**
* @var \Magento\Tax\Api\TaxRateManagementInterface
*/
private $taxRateManagement;
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->taxRuleRepository = $objectManager->get(\Magento\Tax\Api\TaxRuleRepositoryInterface::class);
$this->taxRateManagement = $objectManager->get(\Magento\Tax\Api\TaxRateManagementInterface::class);
$this->taxRateRepository = $objectManager->get(\Magento\Tax\Api\TaxRateRepositoryInterface::class);
$this->taxRuleFixtureFactory = new TaxRuleFixtureFactory();
}
/**
* @magentoDbIsolation enabled
*/
public function testGetRatesByCustomerAndProductTaxClassId()
{
$this->setUpDefaultRules();
$taxRateIds = $this->taxRuleRepository->get(current($this->taxRules))->getTaxRateIds();
$expectedRates = [];
foreach ($taxRateIds as $rateId) {
$expectedRates[] = $this->taxRateRepository->get($rateId);
}
$rates = $this->taxRateManagement->getRatesByCustomerAndProductTaxClassId(
$this->taxClasses['DefaultCustomerClass'],
$this->taxClasses['DefaultProductClass']
);
$this->assertCount(2, $rates);
$this->assertEquals($expectedRates, $rates);
}
private function setUpDefaultRules()
{
$this->taxRates = $this->taxRuleFixtureFactory->createTaxRates([
['percentage' => 7.5, 'country' => 'US', 'region' => 42],
['percentage' => 7.5, 'country' => 'US', 'region' => 12], // Default store rate
]);
$this->taxClasses = $this->taxRuleFixtureFactory->createTaxClasses([
['name' => 'DefaultCustomerClass', 'type' => ClassModel::TAX_CLASS_TYPE_CUSTOMER],
['name' => 'DefaultProductClass', 'type' => ClassModel::TAX_CLASS_TYPE_PRODUCT],
['name' => 'HigherProductClass', 'type' => ClassModel::TAX_CLASS_TYPE_PRODUCT],
]);
$this->taxRules = $this->taxRuleFixtureFactory->createTaxRules([
[
'code' => 'Default Rule',
'customer_tax_class_ids' => [$this->taxClasses['DefaultCustomerClass'], 3],
'product_tax_class_ids' => [$this->taxClasses['DefaultProductClass']],
'tax_rate_ids' => array_values($this->taxRates),
'sort_order' => 0,
'priority' => 0,
'calculate_subtotal' => 1,
],
]);
}
}
@@ -0,0 +1,53 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model;
use Magento\TestFramework\Helper\Bootstrap;
class TaxRuleCollectionTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testCreateTaxRuleCollectionItem()
{
/** @var \Magento\Tax\Model\ResourceModel\Calculation\Rule\Collection $collection */
$collection = Bootstrap::getObjectManager()->get(
\Magento\Tax\Model\ResourceModel\Calculation\Rule\Collection::class
);
$dbTaxRulesQty = $collection->count();
/** @var \Magento\Tax\Model\Calculation\Rule $firstTaxRuleFixture */
$firstTaxRuleFixture = Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class)
->registry('_fixture/Magento_Tax_Model_Calculation_Rule');
$expectedFirstTaxRuleId = $firstTaxRuleFixture->getId();
if (($dbTaxRulesQty == 0) || ($collection->getFirstItem()->getId() != $expectedFirstTaxRuleId)) {
$this->fail("Preconditions failed.");
}
/** @var \Magento\Tax\Model\TaxRuleCollection $taxRulesCollection */
$taxRulesCollection = Bootstrap::getObjectManager()
->create(\Magento\Tax\Model\TaxRuleCollection::class);
$collectionTaxRulesQty = $taxRulesCollection->count();
$this->assertEquals($dbTaxRulesQty, $collectionTaxRulesQty, 'Tax rules quantity is invalid.');
$taxRule = $taxRulesCollection->getFirstItem()->getData();
$expectedTaxRuleData = [
'tax_calculation_rule_id' => $expectedFirstTaxRuleId,
'code' => 'Test Rule',
'priority' => '0',
'position' => '0',
'calculate_subtotal' => '0',
'customer_tax_classes' => $firstTaxRuleFixture->getCustomerTaxClassIds(),
'product_tax_classes' => $firstTaxRuleFixture->getProductTaxClassIds(),
'tax_rates' => $firstTaxRuleFixture->getTaxRateIds(),
'tax_rates_codes' => $firstTaxRuleFixture->getTaxRatesCodes()
];
$this->assertEquals($expectedTaxRuleData, $taxRule, 'Tax rule data is invalid.');
}
}
@@ -0,0 +1,160 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model;
use Magento\TestFramework\Helper\Bootstrap;
/**
* TaxRuleFixtureFactory is meant to help in testing tax by creating/destroying tax rules/classes/rates easily.
*/
class TaxRuleFixtureFactory
{
/**
* Object Manager
*
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var \Magento\Framework\Api\DataObjectHelper
*/
private $dataObjectHelper;
public function __construct()
{
$this->objectManager = Bootstrap::getObjectManager();
$this->dataObjectHelper = $this->objectManager->create(\Magento\Framework\Api\DataObjectHelper::class);
}
/**
* Helper to create tax rules.
*
* @param array $rulesData Keys match populateWithArray
* @return array code => rule id
*/
public function createTaxRules($rulesData)
{
/** @var \Magento\Tax\Api\Data\TaxRuleInterfaceFactory $taxRuleFactory */
$taxRuleFactory = $this->objectManager->create(\Magento\Tax\Api\Data\TaxRuleInterfaceFactory::class);
/** @var \Magento\Tax\Api\TaxRuleRepositoryInterface $taxRuleService */
$taxRuleService = $this->objectManager->create(\Magento\Tax\Api\TaxRuleRepositoryInterface::class);
$rules = [];
foreach ($rulesData as $ruleData) {
$taxRule = $taxRuleFactory->create();
$this->dataObjectHelper->populateWithArray(
$taxRule,
$ruleData,
\Magento\Tax\Api\Data\TaxRuleInterface::class
);
$rules[$ruleData['code']] = $taxRuleService->save($taxRule)->getId();
}
return $rules;
}
/**
* Helper function that deletes tax rules
*
* @param int[] $ruleIds
*/
public function deleteTaxRules($ruleIds)
{
/** @var \Magento\Tax\Api\TaxRuleRepositoryInterface $taxRuleService */
$taxRuleService = $this->objectManager->create(\Magento\Tax\Api\TaxRuleRepositoryInterface::class);
foreach ($ruleIds as $ruleId) {
$taxRuleService->deleteById($ruleId);
}
}
/**
* Helper function that creates rates based on a set of input percentages.
*
* Returns a map of percentage => rate
*
* @param array $ratesData array of rate data, keys are 'country', 'region' and 'percentage'
* @return int[] Tax Rate Id
*/
public function createTaxRates($ratesData)
{
/** @var \Magento\Tax\Api\Data\TaxRateInterfaceFactory $taxRateFactory */
$taxRateFactory = $this->objectManager->create(\Magento\Tax\Api\Data\TaxRateInterfaceFactory::class);
/** @var \Magento\Tax\Api\TaxRateRepositoryInterface $taxRateService */
$taxRateService = $this->objectManager->create(\Magento\Tax\Api\TaxRateRepositoryInterface::class);
$rates = [];
foreach ($ratesData as $rateData) {
$code = "{$rateData['country']} - {$rateData['region']} - {$rateData['percentage']}";
$postcode = '*';
if (isset($rateData['postcode'])) {
$postcode = $rateData['postcode'];
$code = $code . " - " . $postcode;
}
$taxRate = $taxRateFactory->create();
$taxRate->setTaxCountryId($rateData['country'])
->setTaxRegionId($rateData['region'])
->setTaxPostcode($postcode)
->setCode($code)
->setRate($rateData['percentage']);
$rates[$code] = $taxRateService->save($taxRate)->getId();
}
return $rates;
}
/**
* Helper function that deletes tax rates
*
* @param int[] $rateIds
*/
public function deleteTaxRates($rateIds)
{
/** @var \Magento\Tax\Api\TaxRateRepositoryInterface $taxRateService */
$taxRateService = $this->objectManager->create(\Magento\Tax\Api\TaxRateRepositoryInterface::class);
foreach ($rateIds as $rateId) {
$taxRateService->deleteById($rateId);
}
}
/**
* Helper function that creates tax classes based on input.
*
* @param array $classesData Keys include 'name' and 'type'
* @return array ClassName => ClassId
*/
public function createTaxClasses($classesData)
{
$classes = [];
foreach ($classesData as $classData) {
/** @var \Magento\Tax\Model\ClassModel $class */
$class = $this->objectManager->create(\Magento\Tax\Model\ClassModel::class)
->setClassName($classData['name'])
->setClassType($classData['type'])
->save();
$classes[$classData['name']] = $class->getId();
}
return $classes;
}
/**
* Helper function that deletes tax classes
*
* @param int[] $classIds
*/
public function deleteTaxClasses($classIds)
{
/** @var \Magento\Tax\Model\ClassModel $class */
$class = $this->objectManager->create(\Magento\Tax\Model\ClassModel::class);
foreach ($classIds as $classId) {
$class->load($classId);
$class->delete();
}
}
}
@@ -0,0 +1,455 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Model;
use Magento\Framework\Api\Filter;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class TaxRuleRepositoryTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var \Magento\Tax\Api\Data\TaxRuleInterfaceFactory
*/
private $taxRuleFactory;
/**
* @var \Magento\Tax\Api\TaxRuleRepositoryInterface
*/
private $taxRuleRepository;
/**
* @var TaxRuleFixtureFactory
*/
private $taxRuleFixtureFactory;
/**
* Array of default tax classes ids
*
* Key is class name
*
* @var int[]
*/
private $taxClasses;
/**
* Array of default tax rates ids.
*
* Key is rate percentage as string.
*
* @var int[]
*/
private $taxRates;
/**
* Array of default tax rules ids.
*
* Key is rule code.
*
* @var int[]
*/
private $taxRules;
/**
* @var \Magento\Tax\Api\TaxRateRepositoryInterface
*/
private $taxRateRepository;
/**
* @var \Magento\Framework\Api\DataObjectHelper
*/
private $dataObjectHelper;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->taxRuleRepository = $this->objectManager->get(\Magento\Tax\Api\TaxRuleRepositoryInterface::class);
$this->taxRateRepository = $this->objectManager->get(\Magento\Tax\Api\TaxRateRepositoryInterface::class);
$this->taxRuleFactory = $this->objectManager->create(\Magento\Tax\Api\Data\TaxRuleInterfaceFactory::class);
$this->dataObjectHelper = $this->objectManager->create(\Magento\Framework\Api\DataObjectHelper::class);
$this->taxRuleFixtureFactory = new TaxRuleFixtureFactory();
}
/**
* @magentoDbIsolation enabled
*/
public function testSave()
{
// Tax rule data object created
$taxRuleDataObject = $this->createTaxRuleDataObject();
//Tax rule service call
$taxRule = $this->taxRuleRepository->save($taxRuleDataObject);
//Assertions
$this->assertInstanceOf(\Magento\Tax\Api\Data\TaxRuleInterface::class, $taxRule);
$this->assertEquals($taxRuleDataObject->getCode(), $taxRule->getCode());
$this->assertEquals(
$taxRuleDataObject->getCustomerTaxClassIds(),
$taxRule->getCustomerTaxClassIds()
);
$this->assertEquals($taxRuleDataObject->getProductTaxClassIds(), $taxRule->getProductTaxClassIds());
$this->assertEquals($taxRuleDataObject->getPriority(), $taxRule->getPriority());
$this->assertEquals($taxRuleDataObject->getPosition(), $taxRule->getPosition());
$this->assertNotNull($taxRule->getId());
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveThrowsExceptionIdIfTargetTaxRuleDoesNotExist()
{
$this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class);
$this->expectExceptionMessage('No such entity with taxRuleId = 9999');
$taxRuleDataObject = $this->taxRuleFactory->create();
$taxRuleDataObject->setId(9999)
->setCode('code')
->setCustomerTaxClassIds([3])
->setProductTaxClassIds([2])
->setTaxRateIds([2])
->setPriority(0)
->setPosition(1);
$this->taxRuleRepository->save($taxRuleDataObject);
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveThrowsExceptionIfProvidedTaxClassIdsAreInvalid()
{
$this->expectException(\Magento\Framework\Exception\CouldNotSaveException::class);
$this->expectExceptionMessage('No such entity');
$taxRuleData = [
'code' => 'code',
// These TaxClassIds exist, but '2' is should be a productTaxClassId and
// '3' should be a customerTaxClassId. See MAGETWO-25683.
'customer_tax_class_ids' => [2],
'product_tax_class_ids' => [3],
'tax_rate_ids' => [1],
'priority' => 0,
'position' => 0,
];
// Tax rule data object created
$taxRule = $this->taxRuleFactory->create();
$this->dataObjectHelper->populateWithArray(
$taxRule,
$taxRuleData,
\Magento\Tax\Api\Data\TaxRuleInterface::class
);
$this->taxRuleRepository->save($taxRule);
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveThrowsExceptionIfProvidedPositionIsInvalid()
{
$this->expectException(\Magento\Framework\Exception\CouldNotSaveException::class);
$this->expectExceptionMessage('The position value of "-1" must be greater than or equal to 0.');
$taxRuleData = [
'code' => 'code',
'customer_tax_class_ids' => [3],
'product_tax_class_ids' => [2],
'tax_rate_ids' => [1],
'priority' => 0,
'position' => -1,
];
// Tax rule data object created
$taxRule = $this->taxRuleFactory->create();
$this->dataObjectHelper->populateWithArray(
$taxRule,
$taxRuleData,
\Magento\Tax\Api\Data\TaxRuleInterface::class
);
//Tax rule service call
$this->taxRuleRepository->save($taxRule);
$this->fail('Did not throw expected InputException');
}
/**
* @magentoDbIsolation enabled
*/
public function testGetReturnsTaxRuleCreatedByRepository()
{
// Tax rule data object created
$taxRuleDataObject = $this->createTaxRuleDataObject();
//Tax rule service call to create rule
$ruleId = $this->taxRuleRepository->save($taxRuleDataObject)->getId();
// Call getTaxRule and verify
$taxRule = $this->taxRuleRepository->get($ruleId);
$this->assertEquals('code', $taxRule->getCode());
$this->assertEquals([3], $taxRule->getCustomerTaxClassIds());
$this->assertEquals([2], $taxRule->getProductTaxClassIds());
$this->assertEquals([2], $taxRule->getTaxRateIds());
$this->assertEquals(0, $taxRule->getPriority());
$this->assertEquals(1, $taxRule->getPosition());
}
/**
* @magentoDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testGetReturnsTaxRuleCreatedFromModel()
{
/** @var $registry \Magento\Framework\Registry */
$registry = $this->objectManager->get(\Magento\Framework\Registry::class);
/** @var $taxRuleModel \Magento\Tax\Model\Calculation\Rule */
$taxRuleModel = $registry->registry('_fixture/Magento_Tax_Model_Calculation_Rule');
$this->assertNotNull($taxRuleModel);
$ruleId = $taxRuleModel->getId();
$taxRateId = $registry->registry('_fixture/Magento_Tax_Model_Calculation_Rate')->getId();
$customerTaxClassIds = array_values(array_unique($taxRuleModel->getCustomerTaxClasses()));
// Call getTaxRule and verify
$taxRule = $this->taxRuleRepository->get($ruleId);
$this->assertEquals($customerTaxClassIds, $taxRule->getCustomerTaxClassIds());
$this->assertEquals([$taxRateId], $taxRule->getTaxRateIds());
}
/**
* @magentoDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testDeleteById()
{
$this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class);
$this->expectExceptionMessage('No such entity with taxRuleId');
/** @var $registry \Magento\Framework\Registry */
$registry = $this->objectManager->get(\Magento\Framework\Registry::class);
/** @var $taxRule \Magento\Tax\Model\Calculation\Rule */
$taxRule = $registry->registry('_fixture/Magento_Tax_Model_Calculation_Rule');
$this->assertNotNull($taxRule);
$ruleId = $taxRule->getId();
// Delete the new tax rate
$this->assertTrue($this->taxRuleRepository->deleteById($ruleId));
// Get the new tax rule, this should fail
$this->taxRuleRepository->get($ruleId);
}
/**
* @magentoDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testDeleteByIdThrowsExceptionIfTargetTaxRuleDoesNotExist()
{
$this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class);
$this->expectExceptionMessage('No such entity with taxRuleId');
/** @var $registry \Magento\Framework\Registry */
$registry = $this->objectManager->get(\Magento\Framework\Registry::class);
/** @var $taxRule \Magento\Tax\Model\Calculation\Rule */
$taxRule = $registry->registry('_fixture/Magento_Tax_Model_Calculation_Rule');
$this->assertNotNull($taxRule);
$ruleId = $taxRule->getId();
// Delete the new tax rule
$this->assertTrue($this->taxRuleRepository->deleteById($ruleId));
// Delete the new tax rule again, this should fail
$this->taxRuleRepository->deleteById($ruleId);
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveUpdatesExistingTaxRule()
{
$taxRule = $this->createTaxRuleDataObject();
//Tax rule service call
$taxRule = $this->taxRuleRepository->save($taxRule);
$taxRule->setCode('updated code');
$this->taxRuleRepository->save($taxRule);
$retrievedRule = $this->taxRuleRepository->get($taxRule->getId());
$this->assertEquals('updated code', $retrievedRule->getCode());
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveThrowsExceptionIsRequiredFieldsAreMissing()
{
$this->expectException(\Magento\Framework\Exception\CouldNotSaveException::class);
$this->expectExceptionMessage('"code" is required. Enter and try again.');
$taxRule = $this->taxRuleRepository->save($this->createTaxRuleDataObject());
$taxRule->setCode(null);
$this->taxRuleRepository->save($taxRule);
}
/**
*
* @param Filter[] $filters
* @param Filter[] $filterGroup
* @param string[] $expectedRuleCodes The codes of the tax rules that are expected to be found
*
* @magentoDbIsolation enabled
* @dataProvider searchTaxRulesDataProvider
*/
public function testGetList($filters, $filterGroup, $expectedRuleCodes)
{
$this->setUpDefaultRules();
/** @var \Magento\Framework\Api\SearchCriteriaBuilder $searchBuilder */
$searchBuilder = Bootstrap::getObjectManager()
->create(\Magento\Framework\Api\SearchCriteriaBuilder::class);
foreach ($filters as $filter) {
$searchBuilder->addFilters([$filter]);
}
if ($filterGroup !== null) {
$searchBuilder->addFilters($filterGroup);
}
$searchCriteria = $searchBuilder->create();
$searchResults = $this->taxRuleRepository->getList($searchCriteria);
$items = [];
foreach ($expectedRuleCodes as $ruleCode) {
$ruleId = $this->taxRules[$ruleCode];
$items[] = $this->taxRuleRepository->get($ruleId);
}
$this->assertEquals($searchCriteria, $searchResults->getSearchCriteria());
$this->assertEquals(count($expectedRuleCodes), $searchResults->getTotalCount());
foreach ($searchResults->getItems() as $rule) {
$this->assertContains($rule->getCode(), $expectedRuleCodes);
}
$this->tearDownDefaultRules();
}
public function searchTaxRulesDataProvider()
{
$filterBuilder = Bootstrap::getObjectManager()->create(\Magento\Framework\Api\FilterBuilder::class);
return [
'code eq "Default Rule"' => [
[$filterBuilder->setField('code')->setValue('Default Rule')->create()],
null,
['Default Rule'],
],
'customer_tax_class_ids eq 3 AND priority eq 0' => [
[
$filterBuilder->setField('customer_tax_class_ids')->setValue(3)->create(),
$filterBuilder->setField('priority')->setValue('0')->create(),
],
[],
['Default Rule', 'Higher Rate Rule'],
],
'code eq "Default Rule" OR code eq "Higher Rate Rule"' => [
[],
[
$filterBuilder->setField('code')->setValue('Default Rule')->create(),
$filterBuilder->setField('code')->setValue('Higher Rate Rule')->create(),
],
['Default Rule', 'Higher Rate Rule'],
],
'code like "%Rule"' => [
[
$filterBuilder->setField('code')->setValue('%Rule')->setConditionType('like')
->create(),
],
[],
['Default Rule', 'Higher Rate Rule'],
],
];
}
/**
* Helper function that sets up some default rules
*/
private function setUpDefaultRules()
{
$this->taxClasses = $this->taxRuleFixtureFactory->createTaxClasses([
['name' => 'DefaultCustomerClass', 'type' => ClassModel::TAX_CLASS_TYPE_CUSTOMER],
['name' => 'DefaultProductClass', 'type' => ClassModel::TAX_CLASS_TYPE_PRODUCT],
['name' => 'HigherProductClass', 'type' => ClassModel::TAX_CLASS_TYPE_PRODUCT],
]);
$this->taxRates = $this->taxRuleFixtureFactory->createTaxRates([
['percentage' => 7.5, 'country' => 'US', 'region' => 42],
['percentage' => 7.5, 'country' => 'US', 'region' => 12], // Default store rate
]);
$higherRates = $this->taxRuleFixtureFactory->createTaxRates([
['percentage' => 22, 'country' => 'US', 'region' => 42],
['percentage' => 10, 'country' => 'US', 'region' => 12], // Default store rate
]);
$this->taxRules = $this->taxRuleFixtureFactory->createTaxRules([
[
'code' => 'Default Rule',
'customer_tax_class_ids' => [$this->taxClasses['DefaultCustomerClass'], 3],
'product_tax_class_ids' => [$this->taxClasses['DefaultProductClass']],
'tax_rate_ids' => array_values($this->taxRates),
'sort_order' => 0,
'priority' => 0,
'calculate_subtotal' => 1,
],
[
'code' => 'Higher Rate Rule',
'customer_tax_class_ids' => [$this->taxClasses['DefaultCustomerClass'], 3],
'product_tax_class_ids' => [$this->taxClasses['HigherProductClass']],
'tax_rate_ids' => array_values($higherRates),
'sort_order' => 0,
'priority' => 0,
'calculate_subtotal' => 1,
],
[
'code' => 'Highest Rate',
'customer_tax_class_ids' => [$this->taxClasses['DefaultCustomerClass'], 3],
'product_tax_class_ids' => [$this->taxClasses['HigherProductClass']],
'tax_rate_ids' => array_values($higherRates),
'sort_order' => 1,
'priority' => 1,
'calculate_subtotal' => 0,
],
]);
// For cleanup
$this->taxRates = array_merge($this->taxRates, $higherRates);
}
/**
* Helper function that tears down some default rules
*/
private function tearDownDefaultRules()
{
$this->taxRuleFixtureFactory->deleteTaxRules(array_values($this->taxRules));
$this->taxRuleFixtureFactory->deleteTaxRates(array_values($this->taxRates));
$this->taxRuleFixtureFactory->deleteTaxClasses(array_values($this->taxClasses));
}
/**
* Creates Tax Rule Data Object
*
* @return \Magento\Tax\Api\Data\TaxRuleInterface
*/
private function createTaxRuleDataObject()
{
$taxRule = $this->taxRuleFactory->create();
$taxRule->setCode('code')
->setCustomerTaxClassIds([3])
->setProductTaxClassIds([2])
->setTaxRateIds([2])
->setPriority(0)
->setPosition(1);
return $taxRule;
}
}