ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,77 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\Quote\Address;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
/**
* @var CustomerInterface $customer
* @var StoreInterface $store
* @var ProductInterface $product
*/
Resolver::getInstance()->requireDataFixture('Magento/Customer/Fixtures/customer_sec_website.php');
Resolver::getInstance()->requireDataFixture('Magento/Quote/Fixtures/simple_product.php');
/** @var ObjectManager $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var WebsiteRepositoryInterface $websiteRepository */
$websiteRepository = $objectManager->get(WebsiteRepositoryInterface::class);
$website = $websiteRepository->get('test');
/** @var CustomerRegistry $customerRegistry */
$customerRegistry = $objectManager->create(CustomerRegistry::class);
$customer = $customerRegistry->retrieveByEmail('customer.web@example.com', $website->getId());
/** @var ProductRepositoryInterface $productRepository */
$productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class);
$product = $productRepository->get('simple002');
$store = $objectManager->create(StoreInterface::class);
$store->load('fixture_second_store', 'code');
$addressData = include __DIR__ . '/../../Customer/Fixtures/address_data.php';
/** @var Address $shippingAddress */
$shippingAddress = $objectManager->create(Address::class, ['data' => $addressData[0]]);
$shippingAddress->setAddressType('shipping');
$billingAddress = clone $shippingAddress;
$billingAddress->setId(null)
->setAddressType('billing');
/** @var Quote $quote */
$quote = $objectManager->create(
Quote::class,
[
'data' => [
'customer_id' => $customer->getId(),
'store_id' => $store->getId(),
'reserved_order_id' => '0000032134',
'is_active' => true,
'is_multishipping' => false
]
]
);
$quote->setShippingAddress($shippingAddress)
->setBillingAddress($billingAddress)
->addProduct($product);
$quote->getPayment()
->setMethod('checkmo');
$quote->getShippingAddress()
->setShippingMethod('flatrate_flatrate')
->setCollectShippingRates(true);
$quote->collectTotals();
/** @var CartRepositoryInterface $repository */
$repository = $objectManager->get(CartRepositoryInterface::class);
$repository->save($quote);
@@ -0,0 +1,39 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Registry;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
/** @var ObjectManager $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var CartRepositoryInterface $quoteRepository */
$quoteRepository = $objectManager->get(CartRepositoryInterface::class);
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', '0000032134')
->create();
$items = $quoteRepository->getList($searchCriteria)
->getItems();
foreach ($items as $item) {
$quoteRepository->delete($item);
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
Resolver::getInstance()->requireDataFixture('Magento/Customer/Fixtures/customer_sec_website_rollback.php');
Resolver::getInstance()->requireDataFixture('Magento/Quote/Fixtures/simple_product_rollback.php');
@@ -0,0 +1,35 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Quote\Model\ResourceModel\Quote as QuoteResource;
use Magento\Quote\Model\QuoteFactory;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Sales/_files/quote_with_customer.php');
/** @var ObjectManager $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var QuoteFactory $quoteFactory */
$quoteFactory = $objectManager->get(QuoteFactory::class);
/** @var QuoteResource $quoteResource */
$quoteResource = $objectManager->get(QuoteResource::class);
$quote = $quoteFactory->create();
$quoteResource->load($quote, 'test01', 'reserved_order_id');
$quote->getPayment()
->setMethod('checkmo');
$quote->getShippingAddress()
->setShippingMethod('flatrate_flatrate')
->setCollectShippingRates(true);
$quote->collectTotals();
$quote->setCustomerEmail('');
/** @var CartRepositoryInterface $repository */
$repository = $objectManager->get(CartRepositoryInterface::class);
$repository->save($quote);
@@ -0,0 +1,39 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Visibility;
use Magento\CatalogInventory\Api\Data\StockItemInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
/** @var ObjectManager $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var Product $product */
$product = $objectManager->create(Product::class);
$product->setTypeId('simple')
->setAttributeSetId(4)
->setName('Simple Product')
->setSku('simple002')
->setPrice(10)
->setQty(100)
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED);
/** @var StockItemInterface $stockItem */
$stockItem = $objectManager->create(StockItemInterface::class);
$stockItem->setQty(100)
->setIsInStock(true);
$extensionAttributes = $product->getExtensionAttributes();
$extensionAttributes->setStockItem($stockItem);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$product = $productRepository->save($product);
@@ -0,0 +1,35 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
/** @var ObjectManager $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('sku', 'simple002')
->create();
$items = $productRepository->getList($searchCriteria)
->getItems();
foreach ($items as $product) {
$productRepository->delete($product);
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,91 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap as BootstrapHelper;
use PHPUnit\Framework\TestCase;
/**
* @magentoDbIsolation disabled
* @magentoAppArea adminhtml
*/
class CustomerManagementTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var CustomerManagement
*/
private $customerManagemet;
/**
* @var CustomerInterface
*/
private $customer;
protected function setUp(): void
{
$this->objectManager = BootstrapHelper::getObjectManager();
$this->customerManagemet = $this->objectManager->create(CustomerManagement::class);
$this->customer = $this->objectManager->create(CustomerInterface::class);
}
protected function tearDown(): void
{
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = $this->objectManager->create(CustomerRepositoryInterface::class);
$customer = $customerRepository->get('john1.doe001@test.com');
$customerRepository->delete($customer);
}
/**
* @magentoDataFixture Magento/Sales/_files/quote.php
*/
public function testCustomerAddressIdQuote(): void
{
$reservedOrderId = 'test01';
$this->customer->setEmail('john1.doe001@test.com')
->setFirstname('doe')
->setLastname('john');
$quote = $this->getQuote($reservedOrderId)->setCustomer($this->customer);
$this->customerManagemet->populateCustomerInfo($quote);
self::assertNotNull($quote->getBillingAddress()->getCustomerAddressId());
self::assertNotNull($quote->getShippingAddress()->getCustomerAddressId());
}
/**
* Gets quote by reserved order ID.
*
* @param string $reservedOrderId
* @return Quote
*/
private function getQuote(string $reservedOrderId): Quote
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', $reservedOrderId)
->create();
/** @var CartRepositoryInterface $quoteRepository */
$quoteRepository = $this->objectManager->get(CartRepositoryInterface::class);
$items = $quoteRepository->getList($searchCriteria)
->getItems();
return array_pop($items);
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model;
use Magento\TestFramework\Helper\Bootstrap as BootstrapHelper;
use Magento\Quote\Api\GuestCartManagementInterface;
class MaskedQuoteIdToQuoteIdTest extends \PHPUnit\Framework\TestCase
{
/**
* @var MaskedQuoteIdToQuoteIdInterface
*/
private $maskedQuoteIdToQuoteId;
/**
* @var GuestCartManagementInterface
*/
private $guestCartManagement;
protected function setUp(): void
{
$objectManager = BootstrapHelper::getObjectManager();
$this->maskedQuoteIdToQuoteId = $objectManager->create(MaskedQuoteIdToQuoteIdInterface::class);
$this->guestCartManagement = $objectManager->create(GuestCartManagementInterface::class);
}
public function testMaskedIdToQuoteId()
{
$maskedQuoteId = $this->guestCartManagement->createEmptyCart();
$quoteId = $this->maskedQuoteIdToQuoteId->execute($maskedQuoteId);
self::assertGreaterThan(0, $quoteId);
}
public function testMaskedQuoteIdToQuoteIdForNonExistentQuote()
{
self::expectException(\Magento\Framework\Exception\NoSuchEntityException::class);
$this->maskedQuoteIdToQuoteId->execute('test');
}
}
@@ -0,0 +1,130 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model\Plugin;
use Magento\Checkout\Model\Session;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\FunctionalTestingFramework\ObjectManagerInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Model\Quote;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Api\StoreCookieManagerInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Store\Model\StoreRepository;
use Magento\TestFramework\Helper\Bootstrap as BootstrapHelper;
/**
* @magentoAppArea frontend
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class UpdateQuoteStoreTest extends \PHPUnit\Framework\TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var CartRepositoryInterface
*/
private $quoteRepository;
protected function setUp(): void
{
$this->objectManager = BootstrapHelper::getObjectManager();
$this->quoteRepository = $this->objectManager->create(CartRepositoryInterface::class);
}
/**
* Tests that active quote store id updates after store cookie change.
*
* @magentoDataFixture Magento/Quote/_files/empty_quote.php
* @magentoDataFixture Magento/Store/_files/second_store.php
* @throws \ReflectionException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function testUpdateQuoteStoreAfterChangeStoreCookie()
{
$secondStoreCode = 'fixture_second_store';
$reservedOrderId = 'reserved_order_id';
/** @var StoreManagerInterface $storeManager */
$storeManager = $this->objectManager->get(StoreManagerInterface::class);
$currentStore = $storeManager->getStore();
$quote = $this->getQuote($reservedOrderId);
$this->assertEquals(
$currentStore->getId(),
$quote->getStoreId(),
'Current store id and quote store id are not match'
);
/** @var Session $checkoutSession */
$checkoutSession = $this->objectManager->get(Session::class);
$checkoutSession->setQuoteId($quote->getId());
$storeRepository = $this->objectManager->create(StoreRepository::class);
$secondStore = $storeRepository->get($secondStoreCode);
$storeCookieManager = $this->getStoreCookieManager($currentStore);
$storeCookieManager->setStoreCookie($secondStore);
$updatedQuote = $this->getQuote($reservedOrderId);
$this->assertEquals(
$secondStore->getId(),
$updatedQuote->getStoreId(),
'Active quote store id should be equal second store id'
);
}
/**
* Retrieves quote by reserved order id.
*
* @param string $reservedOrderId
* @return Quote
*/
private function getQuote(string $reservedOrderId): Quote
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', $reservedOrderId)
->create();
$items = $this->quoteRepository->getList($searchCriteria)->getItems();
return array_pop($items);
}
/**
* Returns instance of StoreCookieManagerInterface with mocked cookieManager dependency.
*
* Mock is needed since integration test framework use own cookie manager with
* behavior that differs from real environment.
*
* @param $currentStore
* @return StoreCookieManagerInterface
* @throws \ReflectionException
*/
private function getStoreCookieManager(StoreInterface $currentStore): StoreCookieManagerInterface
{
/** @var StoreCookieManagerInterface $storeCookieManager */
$storeCookieManager = $this->objectManager->get(StoreCookieManagerInterface::class);
$cookieManagerMock = $this->getMockBuilder(\Magento\Framework\Stdlib\Cookie\PhpCookieManager::class)
->disableOriginalConstructor()
->getMock();
$cookieManagerMock->method('getCookie')
->willReturn($currentStore->getCode());
$reflection = new \ReflectionClass($storeCookieManager);
$cookieManager = $reflection->getProperty('cookieManager');
$cookieManager->setAccessible(true);
$cookieManager->setValue($storeCookieManager, $cookieManagerMock);
return $storeCookieManager;
}
}
@@ -0,0 +1,75 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model\Product\Plugin;
use Magento\Catalog\Model\ResourceModel\Product as ProductResourceModel;
use Magento\Framework\ObjectManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Interception\PluginList;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use PHPUnit\Framework\TestCase;
/**
* Tests for remove quote items plugin.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class RemoveQuoteItemsTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var ProductResourceModel */
private $productResoure;
/** @var GetQuoteByReservedOrderId */
private $getQuoteByReservedOrderId;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->productResoure = $this->objectManager->get(ProductResourceModel::class);
$this->getQuoteByReservedOrderId = $this->objectManager->get(GetQuoteByReservedOrderId::class);
}
/**
* @return void
*/
public function testPluginIsRegistered(): void
{
$pluginInfo = $this->objectManager->get(PluginList::class)->get(ProductResourceModel::class);
$this->assertSame(
RemoveQuoteItems::class,
$pluginInfo['clean_quote_items_after_product_delete']['instance']
);
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_simple_product_saved.php
*
* @return void
*/
public function testDeleteProduct(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test_order_with_simple_product_without_address');
$this->assertNotNull($quote);
$quoteItems = $quote->getItems();
$quoteItem = current($quoteItems);
$this->assertNotNull($quoteItem);
$this->productResoure->delete($quoteItem->getProduct());
$quote = $this->getQuoteByReservedOrderId->execute('test_order_with_simple_product_without_address');
$this->assertNotNull($quote);
$this->assertEmpty($quote->getItems());
}
}
@@ -0,0 +1,81 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model\Product\Plugin;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Quote\Model\ResourceModel\Quote as QuoteResource;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use PHPUnit\Framework\TestCase;
/**
* Tests for update quote items plugin
*
* @magentoAppArea adminhtml
*/
class UpdateQuoteItemsTest extends TestCase
{
/**
* @var GetQuoteByReservedOrderId
*/
private $getQuoteByReservedOrderId;
/**
* @var ProductRepository
*/
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$objectManager = Bootstrap::getObjectManager();
$this->getQuoteByReservedOrderId = $objectManager->get(GetQuoteByReservedOrderId::class);
$this->productRepository = $objectManager->get(ProductRepository::class);
}
/**
* Test to mark the quote as need to recollect and doesn't update the field "updated_at" after change product price
*
* @magentoDataFixture Magento/Checkout/_files/quote_with_simple_product_saved.php
* @return void
*/
public function testMarkQuoteRecollectAfterChangeProductPrice(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test_order_with_simple_product_without_address');
$this->assertNotNull($quote);
$this->assertFalse((bool)$quote->getTriggerRecollect());
$this->assertNotEmpty($quote->getItems());
$quoteItem = current($quote->getItems());
$product = $quoteItem->getProduct();
$product->setPrice((float)$product->getPrice() + 10);
$this->productRepository->save($product);
/** @var QuoteResource $quoteResource */
$quoteResource = $quote->getResource();
/** @var AdapterInterface $connection */
$connection = $quoteResource->getConnection();
$select = $connection->select()
->from(
$quoteResource->getTable('quote'),
['updated_at', 'trigger_recollect']
)->where(
"reserved_order_id = 'test_order_with_simple_product_without_address'"
);
$quoteRow = $connection->fetchRow($select);
$this->assertNotEmpty($quoteRow);
$this->assertTrue((bool)$quoteRow['trigger_recollect']);
$this->assertEquals($quote->getUpdatedAt(), $quoteRow['updated_at']);
}
}
@@ -0,0 +1,102 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model\Product\Plugin;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Quote\Api\Data\CartItemInterfaceFactory;
use Magento\Catalog\Api\TierPriceStorageInterface;
use Magento\Catalog\Api\Data\TierPriceInterfaceFactory;
use PHPUnit\Framework\TestCase;
/**
* Tests for update quote plugin.
*/
class UpdateQuoteTest extends TestCase
{
/**
* @var GetQuoteByReservedOrderId
*/
private $getQuoteByReservedOrderId;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var CartItemInterfaceFactory */
private $itemFactory;
/**
* @var TierPriceStorageInterface
*/
private $tierPriceStorage;
/**
* @var TierPriceInterfaceFactory
*/
private $tierPriceFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$objectManager = Bootstrap::getObjectManager();
$this->getQuoteByReservedOrderId = $objectManager->get(GetQuoteByReservedOrderId::class);
$this->tierPriceStorage = $objectManager->get(TierPriceStorageInterface::class);
$this->tierPriceFactory = $objectManager->get(TierPriceInterfaceFactory::class);
$this->itemFactory = $objectManager->get(CartItemInterfaceFactory::class);
$this->productRepository = $objectManager->get(ProductRepositoryInterface::class);
}
/**
* Test to update the column trigger_recollect is 1 from quote table.
*
* @magentoDataFixture Magento/Sales/_files/quote.php
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @return void
*/
public function testUpdateQuoteRecollectAfterChangeProductPrice(): void
{
$quoteId = 'test01';
$productSku = 'simple';
$quote = $this->getQuoteByReservedOrderId->execute($quoteId);
$quoteItem = $this->itemFactory->create();
$product = $this->productRepository->get($productSku);
$quoteItem->setProduct($product);
$quoteItem->setProductId($product->getRowId());
$quote->addItem($quoteItem);
$quote->setTriggerRecollect(0);
$quote->save();
$this->assertNotNull($quote);
$this->assertFalse((bool)$quote->getTriggerRecollect());
$tierPrice = $this->tierPriceFactory->create();
$tierPrice->setPrice($product->getPrice());
$tierPrice->setPriceType('fixed');
$tierPrice->setWebsiteId(0);
$tierPrice->setSku($product->getSku());
$tierPrice->setCustomerGroup('ALL GROUPS');
$tierPrice->setQuantity(1);
$this->tierPriceStorage->update([$tierPrice]);
$quote = $this->getQuoteByReservedOrderId->execute($quoteId);
$this->assertNotEmpty($quote->getTriggerRecollect());
$this->assertTrue((bool)$quote->getTriggerRecollect());
}
}
@@ -0,0 +1,405 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Quote\Model\Quote;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\AddressInterfaceFactory;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Framework\Reflection\DataObjectProcessor;
use Magento\Quote\Model\Quote;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Indexer\TestCase;
/**
* Class to test Sales Quote address model functionality
*
* @magentoDataFixture Magento/Sales/_files/quote_with_customer.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
*/
class AddressTest extends TestCase
{
/** @var Quote $quote */
protected $_quote;
/** @var CustomerInterface $customer */
protected $_customer;
/** @var Address */
protected $_address;
/**@var CustomerRepositoryInterface $customerRepository */
protected $customerRepository;
/** @var AddressRepositoryInterface $addressRepository */
protected $addressRepository;
/** @var DataObjectProcessor */
protected $dataProcessor;
/**
* phpcs:ignoreFile
*/
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();
}
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->_quote = Bootstrap::getObjectManager()->create(
Quote::class
);
$this->_quote->load('test01', 'reserved_order_id');
$this->_quote->setIsMultiShipping('0');
$this->customerRepository = Bootstrap::getObjectManager()->create(
CustomerRepositoryInterface::class
);
$this->_customer = $this->customerRepository->getById(1);
/** @var \Magento\Sales\Model\Order\Address $address */
$this->_address = Bootstrap::getObjectManager()->create(
Address::class
);
$this->_address->setId(1);
$this->_address->load($this->_address->getId());
$this->_address->setQuote($this->_quote);
$this->addressRepository = Bootstrap::getObjectManager()->create(
AddressRepositoryInterface::class
);
$this->dataProcessor = Bootstrap::getObjectManager()->create(
DataObjectProcessor::class
);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
/** @var CustomerRegistry $customerRegistry */
$customerRegistry = Bootstrap::getObjectManager()
->get(CustomerRegistry::class);
//Cleanup customer from registry
$customerRegistry->remove(1);
}
/**
* same_as_billing must be equal 0 if billing address is being saved
*
* @param bool $unsetId
* @dataProvider unsetAddressIdDataProvider
*/
public function testSameAsBillingForBillingAddress($unsetId)
{
$this->_quote->setCustomer($this->_customer);
$address = $this->_quote->getBillingAddress();
if ($unsetId) {
$address->setId(null);
}
/** @var AddressRepositoryInterface $addressRepository */
$addressRepository = Bootstrap::getObjectManager()
->create(AddressRepositoryInterface::class);
$customerAddressData = $addressRepository->getById($this->_customer->getDefaultBilling());
$address->setSameAsBilling(0)->setCustomerAddressData($customerAddressData)->save();
$this->assertEquals(0, $this->_quote->getBillingAddress()->getSameAsBilling());
}
/**
* same_as_billing must be equal 1 if customer is guest
*
* @param bool $unsetId
* @dataProvider unsetAddressIdDataProvider
*/
public function testSameAsBillingWhenCustomerIsGuest($unsetId)
{
$shippingAddress = $this->_quote->getShippingAddress();
if ($unsetId) {
$shippingAddress->setId(null);
}
$shippingAddress->setSameAsBilling(0);
$shippingAddress->save();
$this->assertEquals((int)$unsetId, $shippingAddress->getSameAsBilling());
}
/**
* same_as_billing must be equal 1 if quote address has no customer address
*
* @param bool $unsetId
* @dataProvider unsetAddressIdDataProvider
*/
public function testSameAsBillingWhenQuoteAddressHasNoCustomerAddress($unsetId)
{
$this->_quote->setCustomer($this->_customer);
$shippingAddress = $this->_quote->getShippingAddress();
if ($unsetId) {
$shippingAddress->setId(null);
}
$shippingAddress->setSameAsBilling(0)
->setCustomerAddressData(null)
->save();
$this->assertEquals((int)$unsetId, $this->_quote->getShippingAddress()->getSameAsBilling());
}
/**
* same_as_billing must be equal 1 if customer registered and he has no default shipping address
*
* @param bool $unsetId
* @dataProvider unsetAddressIdDataProvider
* @magentoDbIsolation enabled
*/
public function testSameAsBillingWhenCustomerHasNoDefaultShippingAddress($unsetId)
{
/** @var AddressRepositoryInterface $addressRepository */
$addressRepository = Bootstrap::getObjectManager()
->create(AddressRepositoryInterface::class);
$this->_customer->setDefaultShipping(-1)
->setAddresses(
[
$addressRepository->getById($this->_address->getId()),
]
);
$this->_customer = $this->customerRepository->save($this->_customer);
// we should save the customer data in order to be able to use it
$this->_quote->setCustomer($this->_customer);
$this->_setCustomerAddressAndSave($unsetId);
$sameAsBilling = $this->_quote->getShippingAddress()->getSameAsBilling();
$this->assertEquals((int)$unsetId, $sameAsBilling);
}
/**
* same_as_billing must be equal 1 if customer has the same billing and shipping address
*
* @param bool $unsetId
* @dataProvider unsetAddressIdDataProvider
* @magentoDbIsolation enabled
*/
public function testSameAsBillingWhenCustomerHasBillingSameShipping($unsetId)
{
$this->_quote->setCustomer($this->_customer);
$this->_setCustomerAddressAndSave($unsetId);
$this->assertEquals((int)$unsetId, $this->_quote->getShippingAddress()->getSameAsBilling());
}
/**
* same_as_billing must be equal 0 if customer has default shipping address that differs from default billing
*
* @magentoDbIsolation enabled
*/
public function testSameAsBillingWhenCustomerHasDefaultShippingAddress()
{
/** @var AddressRepositoryInterface $addressRepository */
$addressRepository = Bootstrap::getObjectManager()
->create(AddressRepositoryInterface::class);
$this->_customer->setDefaultShipping(2)
->setAddresses([$addressRepository->getById($this->_address->getId())]);
$this->_customer = $this->customerRepository->save($this->_customer);
// we should save the customer data in order to be able to use it
$this->_quote->setCustomer($this->_customer);
$sameAsBilling = $this->_quote->getShippingAddress()->getSameAsBilling();
$this->assertEquals(1, $sameAsBilling);
}
/**
* Assign customer address to quote address and save quote address
*
* @param bool $unsetId
*/
protected function _setCustomerAddressAndSave($unsetId)
{
$shippingAddress = $this->_quote->getShippingAddress();
if ($unsetId) {
$shippingAddress->setId(null);
}
/** @var AddressRepositoryInterface $addressRepository */
$addressRepository = Bootstrap::getObjectManager()
->create(AddressRepositoryInterface::class);
$shippingAddress->setSameAsBilling(0)
->setCustomerAddressData($addressRepository->getById($this->_customer->getDefaultBilling()))
->save();
}
/**
* @return array
*/
public function unsetAddressIdDataProvider()
{
return [[true], [false]];
}
/**
* Test to get same as billing flag after change quote customer
*/
public function testSameAsBillingAfterCustomerWesChanged()
{
$shippingAddressId = 2;
$this->_quote->setCustomer($this->_customer);
/** Make different default shipping and default billing addresses */
$this->_customer->setDefaultShipping($shippingAddressId);
$this->_quote->getShippingAddress()->setCustomerAddressId($shippingAddressId);
/** Emulate to change customer */
$this->_quote->setOrigData('customer_id', null);
$shippingAddress = $this->_quote->getShippingAddress();
$shippingAddress->beforeSave();
$this->assertSame(0, $this->_quote->getShippingAddress()->getSameAsBilling());
}
/**
* Import customer address to quote address
*/
public function testImportCustomerAddressDataWithCustomer()
{
$customerIdFromFixture = 1;
$customerEmailFromFixture = 'customer@example.com';
$city = 'TestCity';
$street = 'Street1';
/** @var AddressInterfaceFactory $addressFactory */
$addressFactory = Bootstrap::getObjectManager()->create(
AddressInterfaceFactory::class
);
/** @var AddressRepositoryInterface $addressRepository */
$addressRepository = Bootstrap::getObjectManager()->create(
AddressRepositoryInterface::class
);
$addressData = $addressFactory->create()
->setCustomerId($customerIdFromFixture)
->setFirstname('John')
->setLastname('Doe')
->setTelephone('123456')
->setPostcode('12345')
->setCountryId('US')
->setCity($city)
->setStreet([$street]);
$addressData = $addressRepository->save($addressData);
$this->_address->setQuote($this->_quote);
$this->_address->importCustomerAddressData($addressData);
$this->assertEquals($customerEmailFromFixture, $this->_address->getEmail(), 'Email was imported incorrectly.');
$this->assertEquals($city, $this->_address->getCity(), 'City was imported incorrectly.');
$this->assertEquals($street, $this->_address->getStreetFull(), 'Imported street is invalid.');
}
/**
* Export customer address from quote address
*/
public function testExportCustomerAddressData()
{
$street = ['Street1'];
$company = 'TestCompany';
$this->_address->setStreet($street);
$this->_address->setCompany($company);
$customerAddress = $this->_address->exportCustomerAddress();
$this->assertEquals($street, $customerAddress->getStreet(), 'Street was exported incorrectly.');
$this->assertEquals($company, $customerAddress->getCompany(), 'Company was exported incorrectly.');
}
/**
* Test to Set the required fields
*/
public function testPopulateBeforeSaveData()
{
/** Preconditions */
$customerId = 1;
$customerAddressId = 1;
$this->_address->setQuote($this->_quote);
$this->assertNotEquals(
$customerId,
$this->_address->getCustomerId(),
"Precondition failed: Customer ID was not set."
);
$this->assertNotEquals(1, $this->_address->getQuoteId(), "Precondition failed: Quote ID was not set.");
$this->assertNotEquals(
$customerAddressId,
$this->_address->getCustomerAddressId(),
"Precondition failed: Customer address ID was not set."
);
/** @var AddressInterfaceFactory $addressFactory */
$addressFactory = Bootstrap::getObjectManager()->create(
AddressInterfaceFactory::class
);
$customerAddressData = $addressFactory->create()->setId($customerAddressId);
$this->_address->setCustomerAddressData($customerAddressData);
$this->_address->save();
$this->assertEquals($customerId, $this->_address->getCustomerId());
$this->assertEquals($this->_quote->getId(), $this->_address->getQuoteId());
$this->assertEquals($customerAddressId, $this->_address->getCustomerAddressId());
}
/**
* Test to retrieve applied taxes
*
* @param $taxes
* @param $expected
* @covers \Magento\Quote\Model\Quote\Address::setAppliedTaxes()
* @covers \Magento\Quote\Model\Quote\Address::getAppliedTaxes()
* @dataProvider appliedTaxesDataProvider
*/
public function testAppliedTaxes($taxes, $expected)
{
$this->_address->setAppliedTaxes($taxes);
$this->assertSame($expected, $this->_address->getAppliedTaxes());
}
/**
* Retrieve applied taxes data provider
*
* @return array
*/
public function appliedTaxesDataProvider()
{
return [
['test', 'test'],
[[123, true], [123, true]]
];
}
/**
* Test to sate shipping address without region
*/
public function testSaveShippingAddressWithEmptyRegionId()
{
$customerAddress = $this->addressRepository->getById(1);
$customerAddress->setRegionId(0);
$address = $this->dataProcessor->buildOutputDataArray(
$customerAddress,
AddressInterface::class
);
$shippingAddress = $this->_quote->getShippingAddress();
$shippingAddress->addData($address);
$shippingAddress->save();
$this->assertEquals(0, $shippingAddress->getRegionId());
$this->assertEquals(0, $shippingAddress->getRegion());
}
}
@@ -0,0 +1,172 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model\Quote\Item;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Api\Data\CartInterfaceFactory;
use Magento\Quote\Api\Data\CartItemInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use PHPUnit\Framework\TestCase;
/**
* Test for quote item persister model.
*
* @see \Magento\Quote\Model\Quote\Item\CartItemPersister
* @magentoDbIsolation enabled
*/
class CartItemPersisterTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var CartItemPersister */
private $model;
/** @var CartInterfaceFactory */
private $quoteFactory;
/** @var CartItemInterfaceFactory */
private $itemFactory;
/** @var GetQuoteByReservedOrderId */
private $getQuoteByReservedOrderId;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->model = $this->objectManager->get(CartItemPersister::class);
$this->quoteFactory = $this->objectManager->get(CartInterfaceFactory::class);
$this->itemFactory = $this->objectManager->get(CartItemInterfaceFactory::class);
$this->getQuoteByReservedOrderId = $this->objectManager->get(GetQuoteByReservedOrderId::class);
}
/**
* @magentoDataFixture Magento/Catalog/_files/simple_product_disabled.php
*
* @return void
* @throws InputException
* @throws LocalizedException
* @throws NoSuchEntityException
* @throws CouldNotSaveException
*/
public function testSaveDisabledItem(): void
{
$quote = $this->quoteFactory->create();
$item = $this->itemFactory->create();
$item->setSku('product_disabled')->setQty(1);
$this->expectExceptionObject(
new LocalizedException(__('Product that you are trying to add is not available.'))
);
$this->model->save($quote, $item);
}
/**
* @magentoDataFixture Magento/Quote/_files/quote_for_configurable_product.php
* @magentoDbIsolation enabled
*
* @return void
* @throws CouldNotSaveException
* @throws InputException
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function testSaveWithConfigurableProductWithoutException(): void
{
$quote = $this->quoteFactory->create();
$item = $this->itemFactory->create();
$item->setSku('simple_1')->setQty(1);
$this->model->save($quote, $item);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php
*
* @return void
* @throws CouldNotSaveException
* @throws InputException
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function testSaveQuoteItemWithoutQty(): void
{
$quote = $this->quoteFactory->create();
$item = $this->itemFactory->create();
$item->setSku('simple-1');
$this->expectExceptionObject(InputException::invalidFieldValue('qty', null));
$this->model->save($quote, $item);
}
/**
* @return void
* @throws CouldNotSaveException
* @throws InputException
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function testSaveQuoteItemWithNotExistingProduct(): void
{
$quote = $this->quoteFactory->create();
$item = $this->itemFactory->create();
$item->setSku('not_existing_product_sku')->setQty(1);
$this->expectExceptionObject(
new NoSuchEntityException(
__('The product that was requested doesn\'t exist. Verify the product and try again.')
)
);
$this->model->save($quote, $item);
}
/**
* @return void
* @throws CouldNotSaveException
* @throws InputException
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function testUpdateNotExistingQuoteItem(): void
{
$quote = $this->quoteFactory->create();
$item = $this->itemFactory->create();
$item->setItemId(989)->setQty(1);
$this->expectExceptionObject(
new NoSuchEntityException(
__('The %1 Cart doesn\'t contain the %2 item.', null, 989)
)
);
$this->model->save($quote, $item);
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_taxable_product_and_customer.php
*
* @return void
* @throws CouldNotSaveException
* @throws InputException
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function testUpdateQuoteItemMoreQty(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test_order_with_taxable_product');
$quoteItem = current($quote->getItems());
$item = $this->itemFactory->create();
$item->setQty(9999)->setSku($quoteItem->getSku())->setItemId($quoteItem->getItemId());
$this->expectExceptionObject(new LocalizedException(__('The requested qty is not available')));
$this->model->save($quote, $item);
}
}
@@ -0,0 +1,51 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Quote\Model\Quote\Item;
use Magento\TestFramework\Helper\Bootstrap;
class RepositoryTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoDataFixture Magento/Sales/_files/quote.php
*/
public function testGetList()
{
$expectedExtensionAttributes = [
'firstname' => 'firstname',
'lastname' => 'lastname',
'email' => 'admin@example.com'
];
/** @var \Magento\Quote\Api\CartItemRepositoryInterface $quoteItemRepository */
$quoteItemRepository = Bootstrap::getObjectManager()->create(
\Magento\Quote\Api\CartItemRepositoryInterface::class
);
/** @var \Magento\Quote\Model\Quote $quote */
$quote = Bootstrap::getObjectManager()->create(\Magento\Quote\Model\Quote::class);
$quoteId = $quote->load('test01', 'reserved_order_id')->getId();
/** @var \Magento\Quote\Api\Data\CartItemInterface[] $quoteItems */
$quoteItems = $quoteItemRepository->getList($quoteId);
/** @var \Magento\Quote\Api\Data\CartItemInterface $actualQuoteItem */
$actualQuoteItem = array_pop($quoteItems);
$this->assertInstanceOf(\Magento\Quote\Api\Data\CartItemInterface::class, $actualQuoteItem);
/** @var \Magento\User\Api\Data\UserInterface $testAttribute */
$testAttribute = $actualQuoteItem->getExtensionAttributes()->__toArray();
$this->assertEquals(
$expectedExtensionAttributes['firstname'],
$testAttribute['quoteItemTestAttribute']['firstname']
);
$this->assertEquals(
$expectedExtensionAttributes['lastname'],
$testAttribute['quoteItemTestAttribute']['lastname']
);
$this->assertEquals(
$expectedExtensionAttributes['email'],
$testAttribute['quoteItemTestAttribute']['email']
);
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model\Quote\Item;
use Magento\Quote\Api\CartItemRepositoryInterface;
use Magento\Quote\Api\Data\CartItemInterface;
use Magento\Quote\Model\Quote;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Tests \Magento\Quote\Model\Quote\Item\Updater
*/
class UpdaterTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Updater
*/
private $updater;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->updater = $this->objectManager->create(Updater::class);
}
/**
* @magentoDataFixture Magento/Sales/_files/quote_with_custom_price.php
* @return void
*/
public function testUpdate(): void
{
/** @var CartItemRepositoryInterface $quoteItemRepository */
$quoteItemRepository = $this->objectManager->create(CartItemRepositoryInterface::class);
/** @var Quote $quote */
$quote = $this->objectManager->create(Quote::class);
$quoteId = $quote->load('test01', 'reserved_order_id')->getId();
/** @var CartItemInterface[] $quoteItems */
$quoteItems = $quoteItemRepository->getList($quoteId);
/** @var CartItemInterface $actualQuoteItem */
$actualQuoteItem = array_pop($quoteItems);
$this->assertInstanceOf(CartItemInterface::class, $actualQuoteItem);
$this->updater->update($actualQuoteItem, ['qty' => 1]);
$this->assertNull(
$actualQuoteItem->getCustomPrice(),
'Item custom price has to be null'
);
}
}
@@ -0,0 +1,57 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\TestFramework\Helper\Bootstrap as BootstrapHelper;
use Magento\Quote\Model\ResourceModel\Quote as QuoteResource;
class QuoteIdToMaskedQuoteIdTest extends \PHPUnit\Framework\TestCase
{
/**
* @var QuoteResource
*/
private $quoteResource;
/**
* @var QuoteFactory
*/
private $quoteFactory;
/**
* @var QuoteIdToMaskedQuoteIdInterface
*/
private $quoteIdToMaskedQuoteId;
protected function setUp(): void
{
$objectManager = BootstrapHelper::getObjectManager();
$this->quoteIdToMaskedQuoteId = $objectManager->create(QuoteIdToMaskedQuoteIdInterface::class);
$this->quoteFactory = $objectManager->create(QuoteFactory::class);
$this->quoteResource = $objectManager->create(QuoteResource::class);
}
/**
* @magentoDataFixture Magento/Sales/_files/quote.php
*/
public function testMaskedQuoteId()
{
$quote = $this->quoteFactory->create();
$this->quoteResource->load($quote, 'test01', 'reserved_order_id');
$maskedQuoteId = $this->quoteIdToMaskedQuoteId->execute((int) $quote->getId());
self::assertNotEmpty($maskedQuoteId);
}
public function testMaskedQuoteIdWithNonExistentQuoteId()
{
self::expectException(NoSuchEntityException::class);
$this->quoteIdToMaskedQuoteId->execute(0);
}
}
@@ -0,0 +1,139 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class QuoteInfiniteLoopTest extends \PHPUnit\Framework\TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var \Magento\TestModuleQuoteTotalsObserver\Model\Config
*/
private $config;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->config = $this->objectManager->get(\Magento\TestModuleQuoteTotalsObserver\Model\Config::class);
$this->config->disableObserver();
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->config->disableObserver();
$this->objectManager->removeSharedInstance(\Magento\Checkout\Model\Session::class);
}
/**
* @dataProvider getLoadQuoteParametersProvider
*
* @param $triggerRecollect
* @param $observerEnabled
* @return void
*/
public function testLoadQuoteSuccessfully($triggerRecollect, $observerEnabled): void
{
$originalQuote = $this->generateQuote($triggerRecollect);
$quoteId = $originalQuote->getId();
$this->assertGreaterThan(0, $quoteId, "The quote should have a database id");
$this->assertEquals(
$triggerRecollect,
$originalQuote->getTriggerRecollect(),
"trigger_recollect failed to be set"
);
if ($observerEnabled) {
$this->config->enableObserver();
}
/** @var $session \Magento\Checkout\Model\Session */
$this->objectManager->removeSharedInstance(\Magento\Checkout\Model\Session::class);
$session = $this->objectManager->get(\Magento\Checkout\Model\Session::class);
$session->setQuoteId($quoteId);
$quote = $session->getQuote();
$this->assertEquals($quoteId, $quote->getId(), "The loaded quote should have the same ID as the initial quote");
$this->assertEquals(0, $quote->getTriggerRecollect(), "trigger_recollect should be unset after a quote reload");
}
/**
* @return array
*/
public function getLoadQuoteParametersProvider()
{
return [
[0, false],
[0, true],
[1, false],
//[1, true], this combination of trigger recollect and third party code causes the loop, tested separately
];
}
/**
*
* @return void
*/
public function testLoadQuoteWithTriggerRecollectInfiniteLoop(): void
{
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Infinite loop detected, review the trace for the looping path');
$originalQuote = $this->generateQuote();
$quoteId = $originalQuote->getId();
$this->assertGreaterThan(0, $quoteId, "The quote should have a database id");
$this->assertEquals(1, $originalQuote->getTriggerRecollect(), "The quote has trigger_recollect set");
// Enable an observer which gets the quote from the session
// The observer hooks into part of the collect totals process for an easy demonstration of the loop.
$this->config->enableObserver();
/** @var $session \Magento\Checkout\Model\Session */
$this->objectManager->removeSharedInstance(\Magento\Checkout\Model\Session::class);
$session = $this->objectManager->get(\Magento\Checkout\Model\Session::class);
$session->setQuoteId($quoteId);
$session->getQuote();
}
/**
* Generate a quote with trigger_recollect and save it in the database.
*
* @param int $triggerRecollect
* @return Quote
*/
private function generateQuote($triggerRecollect = 1)
{
//Fully init a quote with standard quote session procedure
/** @var $session \Magento\Checkout\Model\Session */
$session = $this->objectManager->create(\Magento\Checkout\Model\Session::class);
$session->setQuoteId(null);
$quote = $session->getQuote();
$quote->setTriggerRecollect($triggerRecollect);
/** @var \Magento\Quote\Api\CartRepositoryInterface $quoteRepository */
$quoteRepository = $this->objectManager->create('\Magento\Quote\Api\CartRepositoryInterface');
$quoteRepository->save($quote);
return $quote;
}
}
@@ -0,0 +1,440 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Type;
use Magento\Checkout\Api\PaymentInformationManagementInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Model\Vat;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\StateException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Api\CartManagementInterface;
use Magento\Quote\Api\Data\AddressInterface;
use Magento\Quote\Api\Data\PaymentInterface;
use Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver;
use Magento\Quote\Observer\Frontend\Quote\Address\VatValidator;
use Magento\Sales\Api\OrderManagementInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
/**
* Class for testing QuoteManagement model
*
* @see \Magento\Quote\Model\QuoteManagement
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class QuoteManagementTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var CartManagementInterface
*/
private $cartManagement;
/**
* @var OrderRepositoryInterface
*/
private $orderRepository;
/**
* @var GetQuoteByReservedOrderId
*/
private $getQuoteByReservedOrderId;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var PaymentInformationManagementInterface
*/
private $paymentManagement;
/**
* @var PaymentInterface
*/
private $payment;
/**
* @var AddressInterface
*/
private $address;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->cartManagement = $this->objectManager->get(CartManagementInterface::class);
$this->orderRepository = $this->objectManager->get(OrderRepositoryInterface::class);
$this->getQuoteByReservedOrderId = $this->objectManager->get(GetQuoteByReservedOrderId::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->customerRepository = $this->objectManager->get(CustomerRepositoryInterface::class);
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->paymentManagement = $this->objectManager->get(PaymentInformationManagementInterface::class);
$this->payment = $this->objectManager->get(PaymentInterface::class);
$this->address = $this->objectManager->get(AddressInterface::class);
}
/**
* Creates order with product that has child items.
*
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Sales/_files/quote_with_bundle.php
*
* @return void
*/
public function testSubmit(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test01');
$orderId = $this->cartManagement->placeOrder($quote->getId());
$order = $this->orderRepository->get($orderId);
$orderItems = $order->getItems();
$this->assertCount(3, $orderItems);
foreach ($orderItems as $orderItem) {
if ($orderItem->getProductType() == Type::TYPE_SIMPLE) {
$this->assertNotEmpty($orderItem->getParentItem(), 'Parent is not set for child product');
$this->assertNotEmpty($orderItem->getParentItemId(), 'Parent is not set for child product');
}
}
}
/**
* Verify guest customer place order with auto-group assigment.
*
* @magentoDataFixture Magento/Sales/_files/guest_quote_with_addresses.php
*
* @magentoConfigFixture default_store customer/create_account/auto_group_assign 1
* @magentoConfigFixture default_store customer/create_account/tax_calculation_address_type shipping
* @magentoConfigFixture default_store customer/create_account/viv_intra_union_group 2
* @magentoConfigFixture default_store customer/create_account/viv_on_each_transaction 1
*
* @return void
*/
public function testSubmitGuestCustomer(): void
{
$this->mockVatValidation();
$quote = $this->getQuoteByReservedOrderId->execute('guest_quote');
$this->cartManagement->placeOrder($quote->getId());
$quoteAfterOrderPlaced = $this->getQuoteByReservedOrderId->execute('guest_quote');
self::assertEquals(0, $quoteAfterOrderPlaced->getCustomerGroupId());
self::assertEquals(3, $quoteAfterOrderPlaced->getCustomerTaxClassId());
}
/**
* Creates order with purchase_order payment method
*
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Sales/_files/quote_with_purchase_order.php
*
* @return void
* @throws CouldNotSaveException
*/
public function testSubmitWithPurchaseOrder(): void
{
$paymentMethodName = 'purchaseorder';
$poNumber = '12345678';
$quote = $this->getQuoteByReservedOrderId->execute('test_order_1');
$quote->getPayment()->setPoNumber($poNumber);
$quote->collectTotals()->save();
$orderId = $this->cartManagement->placeOrder($quote->getId());
$order = $this->orderRepository->get($orderId);
$orderItems = $order->getItems();
$this->assertCount(1, $orderItems);
$payment = $order->getPayment();
$this->assertEquals($paymentMethodName, $payment->getMethod());
$this->assertEquals($poNumber, $payment->getPoNumber());
}
/**
* Creates order with purchase_order payment method without po_number
*
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Sales/_files/quote_with_purchase_order.php
*
* @return void
* @throws CouldNotSaveException
*/
public function testSubmitWithPurchaseOrderWithException(): void
{
$this->expectException(LocalizedException::class);
$this->expectExceptionMessage('Purchase order number is a required field.');
$quote = $this->getQuoteByReservedOrderId->execute('test_order_1');
$this->cartManagement->placeOrder($quote->getId());
}
/**
* Tries to create order with product that has child items and one of them was deleted.
*
* @magentoConfigFixture cataloginventory/options/enable_inventory_check 1
* @magentoAppArea adminhtml
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Sales/_files/quote_with_bundle.php
*/
public function testSubmitWithDeletedItem(): void
{
$this->productRepository->deleteById('simple-2');
$quote = $this->getQuoteByReservedOrderId->execute('test01');
$this->expectExceptionObject(
new LocalizedException(__('Some of the products below do not have all the required options.'))
);
$this->cartManagement->placeOrder($quote->getId());
}
/**
* Tries to create order with product that has child items and one of them
* was deleted when item data check is disabled on quote load.
* @magentoConfigFixture cataloginventory/options/enable_inventory_check 0
* @magentoAppArea adminhtml
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Sales/_files/quote_with_bundle.php
*/
public function testSubmitWithDeletedItemWithDisabledInventoryCheck(): void
{
$this->productRepository->deleteById('simple-2');
$quote = $this->getQuoteByReservedOrderId->execute('test01');
$this->cartManagement->placeOrder($quote->getId());
}
/**
* Tries to create order with item of stock during checkout.
* @magentoConfigFixture cataloginventory/options/enable_inventory_check 1
* @magentoDataFixture Magento/Sales/_files/quote.php
* @magentoDbIsolation enabled
*/
public function testSubmitWithItemOutOfStock(): void
{
$this->makeProductOutOfStock('simple');
$quote = $this->getQuoteByReservedOrderId->execute('test01');
$this->expectExceptionObject(new LocalizedException(__('Some of the products are out of stock.')));
$this->cartManagement->placeOrder($quote->getId());
}
/**
* Tries to create order with item of stock during checkout
* when item data check is disabled on quote load.
* @magentoConfigFixture cataloginventory/options/enable_inventory_check 0
* @magentoDataFixture Magento/Sales/_files/quote.php
* @magentoDbIsolation enabled
*/
public function testSubmitWithItemOutOfStockWithDisabledInventoryCheck(): void
{
$this->makeProductOutOfStock('simple');
$quote = $this->getQuoteByReservedOrderId->execute('test01');
$this->expectExceptionObject(
new LocalizedException(
__('The shipping method is missing. Select the shipping method and try again.')
)
);
$this->cartManagement->placeOrder($quote->getId());
}
/**
* Tries to create an order using quote with empty customer email.
*
* Order should not start placing if order validation is failed.
*
* @magentoDataFixture Magento/Quote/Fixtures/quote_without_customer_email.php
*
* @return void
*/
public function testSubmitWithEmptyCustomerEmail(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test01');
$orderManagement = $this->createMock(OrderManagementInterface::class);
$orderManagement->expects($this->never())
->method('place');
$cartManagement = $this->objectManager->create(
CartManagementInterface::class,
['orderManagement' => $orderManagement]
);
$this->expectExceptionObject(new LocalizedException(__('Email has a wrong format')));
try {
$cartManagement->placeOrder($quote->getId());
} catch (ExpectationFailedException $e) {
$this->fail('Place order method was not expected to be called if order validation is failed');
}
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_simple_product_saved.php
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testAssignCustomerToQuote(): void
{
$customer = $this->customerRepository->get('customer@example.com');
$quote = $this->getQuoteByReservedOrderId->execute('test_order_with_simple_product_without_address');
$result = $this->cartManagement->assignCustomer($quote->getId(), $customer->getId(), $customer->getStoreId());
$this->assertTrue($result);
$customerQuote = $this->cartManagement->getCartForCustomer($customer->getId());
$this->assertEquals($quote->getId(), $customerQuote->getId());
$this->assertEquals($customer->getId(), $customerQuote->getCustomerId());
$this->assertEquals($customer->getEmail(), $customerQuote->getCustomerEmail());
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_simple_product_saved.php
* @magentoDataFixture Magento/Customer/_files/customer_for_second_website.php
*
* @return void
*/
public function testAssignCustomerFromAnotherWebsiteToQuote(): void
{
$websiteId = $this->storeManager->getWebsite('test')->getId();
$customer = $this->customerRepository->get('customer@example.com', $websiteId);
$quote = $this->getQuoteByReservedOrderId->execute('test_order_with_simple_product_without_address');
$this->expectExceptionObject(
new StateException(
__('The customer can\'t be assigned to the cart. The cart belongs to a different store.')
)
);
$this->cartManagement->assignCustomer($quote->getId(), $customer->getId(), $quote->getStoreId());
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_customer_without_address.php
* @magentoDataFixture Magento/Customer/_files/customer_with_uk_address.php
*
* @return void
*/
public function testAssignCustomerToQuoteAlreadyHaveCustomer(): void
{
$customer = $this->customerRepository->get('customer_uk_address@test.com');
$quote = $this->getQuoteByReservedOrderId->execute('test_order_with_customer_without_address');
$this->expectExceptionObject(
new StateException(__('The customer can\'t be assigned to the cart because the cart isn\'t anonymous.'))
);
$this->cartManagement->assignCustomer($quote->getId(), $customer->getId(), $quote->getStoreId());
}
/**
* Makes provided product as out of stock.
*
* @param string $sku
* @return void
*/
private function makeProductOutOfStock(string $sku): void
{
$product = $this->productRepository->get($sku);
$extensionAttributes = $product->getExtensionAttributes();
$stockItem = $extensionAttributes->getStockItem();
$stockItem->setIsInStock(false);
$this->productRepository->save($product);
}
/**
* Makes customer vat validator 'check vat number' response successful.
*
* @return void
*/
private function mockVatValidation(): void
{
$vatMock = $this->getMockBuilder(Vat::class)
->setConstructorArgs(
[
'scopeConfig' => $this->objectManager->get(ScopeConfigInterface::class),
'logger' => $this->objectManager->get(LoggerInterface::class),
]
)
->onlyMethods(['checkVatNumber'])
->getMock();
$gatewayResponse = new DataObject([
'is_valid' => true,
'request_date' => 'testData',
'request_identifier' => 'testRequestIdentifier',
'request_success' => true,
]);
$vatMock->method('checkVatNumber')->willReturn($gatewayResponse);
$this->objectManager->removeSharedInstance(CollectTotalsObserver::class);
$this->objectManager->removeSharedInstance(VatValidator::class);
$this->objectManager->removeSharedInstance(Vat::class);
$this->objectManager->addSharedInstance($vatMock, Vat::class);
}
/**
* Creates order with purchase_order payment method
*
* @magentoDataFixture Magento/Sales/_files/quote_with_customer.php
* @magentoDbIsolation disabled
* @return void
* @throws CouldNotSaveException
*/
public function testCustomerAddressIdAfterPlacingOrder(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test01');
$quote->getBillingAddress()->setSaveInAddressBook(null);
$quote->getBillingAddress()->setCustomerAddressId(null);
$this->address->setFirstname($quote->getBillingAddress()->getFirstname());
$this->address->setLastname($quote->getBillingAddress()->getLastname());
$this->address->setCity($quote->getBillingAddress()->getCity());
$this->address->setCompany($quote->getBillingAddress()->getCompany());
$this->address->setCountryId($quote->getBillingAddress()->getCountryId());
$this->address->setRegionId($quote->getBillingAddress()->getRegionId());
$this->address->setCustomerId($quote->getBillingAddress()->getCustomerId());
$this->address->setPostcode($quote->getBillingAddress()->getPostcode());
$this->address->setTelephone($quote->getBillingAddress()->getTelephone());
$this->address->setStreet($quote->getBillingAddress()->getStreet());
$this->address->setSameAsBilling($quote->getBillingAddress()->getSameAsBilling());
$this->address->setCustomerAddressId($quote->getBillingAddress()->getCustomerAddressId());
$this->address->setSaveInAddressBook($quote->getBillingAddress()->getSaveInAddressBook());
$quote->getShippingAddress()
->setShippingMethod('flatrate_flatrate')
->setCollectShippingRates(true);
$quote->getShippingAddress()->setSameAsBilling(1);
$quote->getShippingAddress()->setSaveInAddressBook(1);
$this->payment->setMethod('checkmo');
$quote->save();
$orderId = $this->paymentManagement->savePaymentInformationAndPlaceOrder(
$quote->getId(),
$this->payment,
$this->address
);
$order = $this->orderRepository->get($orderId);
$billingAddress = $order->getBillingAddress();
$shippingAddress = $order->getShippingAddress();
$this->assertNotNull($billingAddress->getCustomerAddressId());
$this->assertNotNull($shippingAddress->getCustomerAddressId());
$this->assertEquals($billingAddress->getCustomerAddressId(), $shippingAddress->getCustomerAddressId());
}
}
@@ -0,0 +1,132 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\CatalogInventory\Api\StockItemRepositoryInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Api\CartManagementInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use PHPUnit\Framework\TestCase;
class QuoteManagementWithInventoryCheckDisabledTest extends TestCase
{
private const PURCHASE_ORDER_NUMBER = '12345678';
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/** @var ProductRepositoryInterface $productRepository */
private $productRepository;
/**
* @var GetQuoteByReservedOrderId
*/
private $getQuoteByReservedOrderId;
/**
* @var CartManagementInterface
*/
private $cartManagement;
/**
* @var OrderRepositoryInterface
*/
private $orderRepository;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->cartManagement = $this->objectManager->get(CartManagementInterface::class);
$this->getQuoteByReservedOrderId = $this->objectManager->get(GetQuoteByReservedOrderId::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->orderRepository = $this->objectManager->get(OrderRepositoryInterface::class);
}
/**
* Test order placement with disabled inventory check, different quantity and out of stock status.
*
* @param int $qty
* @param int $stockStatus
* @return void
* @magentoDataFixture Magento/Sales/_files/quote_with_purchase_order.php
* @magentoConfigFixture cataloginventory/options/enable_inventory_check 0
* @dataProvider getQtyAndStockStatusProvider
*/
public function testPlaceOrderWithDisabledInventoryCheck(int $qty, int $stockStatus): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test_order_1');
$quote->getPayment()->setPoNumber(self::PURCHASE_ORDER_NUMBER);
$quote->collectTotals()->save();
/** @var ProductInterface $product */
$product = $this->productRepository->get($quote->getItems()[0]->getSku(), false, null, true);
$this->productRepository->save($product);
$stockItem = $product->getExtensionAttributes()->getStockItem();
$stockItem->setQty($qty);
$stockItem->setIsInStock($stockStatus);
/** @var StockItemRepositoryInterface $stockItemRepository */
$stockItemRepository = $this->objectManager->get(StockItemRepositoryInterface::class);
$stockItemRepository->save($stockItem);
$this->expectException(LocalizedException::class);
$this->cartManagement->placeOrder($quote->getId());
}
/**
* @return array
*/
public function getQtyAndStockStatusProvider(): array
{
return [
[0, 0],
[100, 0],
];
}
/**
* Test order placement with disabled inventory check, positive quantity and in stock status.
*
* @magentoDataFixture Magento/Sales/_files/quote_with_purchase_order.php
* @magentoConfigFixture cataloginventory/options/enable_inventory_check 0
* @return void
*/
public function testSaveWithPositiveQuantityAndInStockWithInventoryCheckDisabled(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test_order_1');
$quote->getPayment()->setPoNumber(self::PURCHASE_ORDER_NUMBER);
$quote->collectTotals()->save();
/** @var ProductInterface $product */
$product = $this->productRepository->get($quote->getItems()[0]->getSku(), false, null, true);
$this->productRepository->save($product);
$stockItem = $product->getExtensionAttributes()->getStockItem();
$stockItem->setQty(100);
$stockItem->setIsInStock(1);
/** @var StockItemRepositoryInterface $stockItemRepository */
$stockItemRepository = $this->objectManager->get(StockItemRepositoryInterface::class);
$stockItemRepository->save($stockItem);
$orderId = $this->cartManagement->placeOrder($quote->getId());;
$order = $this->orderRepository->get($orderId);
$orderItems = $order->getItems();
$this->assertCount(1, $orderItems);
}
}
@@ -0,0 +1,97 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model;
use Magento\Quote\Api\GuestCartManagementInterface;
use Magento\TestFramework\Helper\Bootstrap as BootstrapHelper;
class QuoteMutexTest extends \PHPUnit\Framework\TestCase
{
/**
* @var GuestCartManagementInterface
*/
private $guestCartManagement;
/**
* @var QuoteMutexInterface
*/
private $quoteMutex;
protected function setUp(): void
{
$objectManager = BootstrapHelper::getObjectManager();
$this->quoteMutex = $objectManager->create(QuoteMutexInterface::class);
$this->guestCartManagement = $objectManager->create(GuestCartManagementInterface::class);
}
/**
* Tests quote mutex execution with different callables.
*
* @param callable $callable
* @param array $args
* @param mixed $expectedResult
* @return void
* @dataProvider callableDataProvider
*/
public function testSuccessfulExecution(callable $callable, array $args, $expectedResult): void
{
$maskedQuoteId = $this->guestCartManagement->createEmptyCart();
$result = $this->quoteMutex->execute([$maskedQuoteId], $callable, $args);
$this->assertEquals($expectedResult, $result);
}
/**
* @return array[]
*/
public function callableDataProvider(): array
{
$functionWithArgs = function (int $a, int $b) {
return $a + $b;
};
$functionWithoutArgs = function () {
return 'Function without args';
};
return [
['callable' => $functionWithoutArgs, 'args' => [], 'expectedResult' => 'Function without args'],
['callable' => $functionWithArgs, 'args' => [1,2], 'expectedResult' => 3],
[
'callable' => \Closure::fromCallable([$this, 'privateMethod']),
'args' => ['test'],
'expectedResult' => 'test'
],
];
}
/**
* Private method for data provider.
*
* @param string $var
* @return string
* @SuppressWarnings(PHPMD.UnusedPrivateMethod)
*/
private function privateMethod(string $var)
{
return $var;
}
/**
* Tests exception when empty maskIds array has been provided.
*
* @return void
*/
public function testWithEmptyMaskIdsArgument(): void
{
$this->expectException(\InvalidArgumentException::class);
$callable = function () {
};
$this->quoteMutex->execute([], $callable);
}
}
@@ -0,0 +1,281 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteria;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\Data\AddressInterfaceFactory;
use Magento\Quote\Api\Data\CartExtension;
use Magento\Quote\Api\Data\CartInterface;
use Magento\Quote\Api\Data\CartInterfaceFactory;
use Magento\Quote\Api\Data\CartItemInterfaceFactory;
use Magento\Quote\Api\Data\CartSearchResultsInterface;
use Magento\Quote\Api\Data\ShippingAssignmentInterface;
use Magento\Quote\Api\Data\ShippingInterface;
use Magento\Quote\Model\Quote\Address as QuoteAddress;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap as BootstrapHelper;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use PHPUnit\Framework\TestCase;
/**
* Test for quote repository
*
* @see \Magento\Quote\Model\QuoteRepository
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class QuoteRepositoryTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var CartRepositoryInterface
*/
private $quoteRepository;
/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* @var FilterBuilder
*/
private $filterBuilder;
/**
* @var GetQuoteByReservedOrderId
*/
private $getQuoteByReservedOrderId;
/**
* @var StoreRepositoryInterface
*/
private $storeRepository;
/**
* @var AddressInterfaceFactory
*/
private $addressFactory;
/**
* @var CartInterfaceFactory
*/
private $quoteFactory;
/**
* @var CartItemInterfaceFactory
*/
private $itemFactory;
/**
* @var CartInterface|null
*/
private $quote;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = BootstrapHelper::getObjectManager();
$this->quoteRepository = $this->objectManager->create(CartRepositoryInterface::class);
$this->searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$this->filterBuilder = $this->objectManager->get(FilterBuilder::class);
$this->getQuoteByReservedOrderId = $this->objectManager->get(GetQuoteByReservedOrderId::class);
$this->storeRepository = $this->objectManager->get(StoreRepositoryInterface::class);
$this->addressFactory = $this->objectManager->get(AddressInterfaceFactory::class);
$this->quoteFactory = $this->objectManager->get(CartInterfaceFactory::class);
$this->itemFactory = $this->objectManager->get(CartItemInterfaceFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
if ($this->quote instanceof CartInterface) {
$this->quoteRepository->delete($this->quote);
}
parent::tearDown();
}
/**
* Tests that quote saved with custom store id has same store id after getting via repository.
*
* @magentoDataFixture Magento/Sales/_files/quote.php
* @magentoDataFixture Magento/Store/_files/second_store.php
*
* @return void
*/
public function testGetQuoteWithCustomStoreId(): void
{
$secondStoreCode = 'fixture_second_store';
$reservedOrderId = 'test01';
$secondStore = $this->storeRepository->get($secondStoreCode);
$quote = $this->getQuoteByReservedOrderId->execute($reservedOrderId);
$quote->setStoreId($secondStore->getId());
$this->quoteRepository->save($quote);
$savedQuote = $this->quoteRepository->get($quote->getId());
$this->assertEquals(
$secondStore->getId(),
$savedQuote->getStoreId(),
'Quote store id should be equal with store id value in DB'
);
}
/**
* @magentoDataFixture Magento/Sales/_files/quote.php
*
* @return void
*/
public function testGetList(): void
{
$searchCriteria = $this->getSearchCriteria('test01');
$searchResult = $this->quoteRepository->getList($searchCriteria);
$this->performAssertions($searchResult);
}
/**
* @magentoDataFixture Magento/Sales/_files/quote.php
*
* @return void
*/
public function testGetListDoubleCall(): void
{
$searchCriteria1 = $this->getSearchCriteria('test01');
$searchCriteria2 = $this->getSearchCriteria('test02');
$searchResult = $this->quoteRepository->getList($searchCriteria1);
$this->performAssertions($searchResult);
$searchResult = $this->quoteRepository->getList($searchCriteria2);
$this->assertEmpty($searchResult->getItems());
}
/**
* @magentoAppIsolation enabled
*
* @return void
*/
public function testSaveWithNotExistingCustomerAddress(): void
{
$addressData = include __DIR__ . '/../../Sales/_files/address_data.php';
$billingAddress = $this->addressFactory->create(['data' => $addressData]);
$billingAddress->setAddressType(QuoteAddress::ADDRESS_TYPE_BILLING)->setCustomerAddressId('not_existing');
$shippingAddress = $this->addressFactory->create(['data' => $addressData]);
$shippingAddress->setAddressType(QuoteAddress::ADDRESS_TYPE_SHIPPING)->setCustomerAddressId('not_existing');
$shipping = $this->objectManager->get(ShippingInterface::class);
$shipping->setAddress($shippingAddress);
$shippingAssignment = $this->objectManager->get(ShippingAssignmentInterface::class);
$shippingAssignment->setItems([]);
$shippingAssignment->setShipping($shipping);
$extensionAttributes = $this->objectManager->get(CartExtension::class);
$extensionAttributes->setShippingAssignments([$shippingAssignment]);
$this->quote = $this->quoteFactory->create();
$this->quote->setStoreId(1)
->setIsActive(true)
->setIsMultiShipping(0)
->setBillingAddress($billingAddress)
->setShippingAddress($shippingAddress)
->setExtensionAttributes($extensionAttributes)
->save();
$this->quoteRepository->save($this->quote);
$this->assertNull($this->quote->getBillingAddress()->getCustomerAddressId());
$this->assertNull(
$this->quote->getExtensionAttributes()
->getShippingAssignments()[0]
->getShipping()
->getAddress()
->getCustomerAddressId()
);
}
/**
* @magentoDataFixture Magento/Catalog/_files/multiple_products.php
*
* @return void
*/
public function testSaveQuoteWithItems(): void
{
$items = $this->prepareQuoteItems(['simple1', 'simple2']);
$this->quote = $this->quoteFactory->create();
$this->quote->setItems($items);
$this->quoteRepository->save($this->quote);
$this->assertCount(2, $this->quote->getItemsCollection());
$this->assertEquals(2, $this->quote->getItemsCount());
$this->assertEquals(2, $this->quote->getItemsQty());
}
/**
* Prepare quote items by products sku.
*
* @param array $productsSku
* @return array
*/
private function prepareQuoteItems(array $productsSku): array
{
$items = [];
foreach ($productsSku as $sku) {
$item = $this->itemFactory->create();
$item->setSku($sku)->setQty(1);
$items[] = $item;
}
return $items;
}
/**
* Get search criteria
*
* @param string $filterValue
* @return SearchCriteria
*/
private function getSearchCriteria(string $filterValue): SearchCriteria
{
$filters = [];
$filters[] = $this->filterBuilder->setField('reserved_order_id')
->setConditionType('=')
->setValue($filterValue)
->create();
$this->searchCriteriaBuilder->addFilters($filters);
return $this->searchCriteriaBuilder->create();
}
/**
* Perform assertions
*
* @param CartSearchResultsInterface $searchResult
* @return void
*/
private function performAssertions(CartSearchResultsInterface $searchResult): void
{
$expectedExtensionAttributes = [
'firstname' => 'firstname',
'lastname' => 'lastname',
'email' => 'admin@example.com',
];
$items = $searchResult->getItems();
$actualQuote = array_pop($items);
$testAttribute = $actualQuote->getExtensionAttributes()->getQuoteTestAttribute();
$this->assertInstanceOf(CartInterface::class, $actualQuote);
$this->assertEquals('test01', $actualQuote->getReservedOrderId());
$this->assertEquals($expectedExtensionAttributes['firstname'], $testAttribute->getFirstName());
$this->assertEquals($expectedExtensionAttributes['lastname'], $testAttribute->getLastName());
$this->assertEquals($expectedExtensionAttributes['email'], $testAttribute->getEmail());
}
}
@@ -0,0 +1,812 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\GroupFactory;
use Magento\Customer\Model\GroupManagement;
use Magento\Customer\Model\ResourceModel\Customer as CustomerResourceModel;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\ExtensibleDataObjectConverter;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Api\Data\AddressInterface;
use Magento\Quote\Api\Data\AddressInterfaceFactory;
use Magento\Quote\Api\Data\CartInterface;
use Magento\Quote\Api\Data\CartItemInterface;
use Magento\Quote\Api\Data\CartItemInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use PHPUnit\Framework\TestCase;
/**
* Tests for quote model.
*
* @see \Magento\Quote\Model\Quote
*
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class QuoteTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var GetQuoteByReservedOrderId */
private $getQuoteByReservedOrderId;
/** @var QuoteFactory */
private $quoteFactory;
/** @var DataObjectHelper */
private $dataObjectHelper;
/** @var CustomerRepositoryInterface */
private $customerRepository;
/** @var CustomerInterfaceFactory */
private $customerDataFactory;
/** @var CustomerFactory */
private $customerFactory;
/** @var AddressInterfaceFactory */
private $addressFactory;
/** @var CartItemInterfaceFactory */
private $itemFactory;
/** @var CustomerResourceModel */
private $customerResourceModel;
/** @var int */
private $customerIdToDelete;
/** @var GroupFactory */
private $groupFactory;
/** @var ExtensibleDataObjectConverter */
private $extensibleDataObjectConverter;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->getQuoteByReservedOrderId = $this->objectManager->get(GetQuoteByReservedOrderId::class);
$this->quoteFactory = $this->objectManager->get(QuoteFactory::class);
$this->dataObjectHelper = $this->objectManager->get(DataObjectHelper::class);
$this->customerRepository = $this->objectManager->get(CustomerRepositoryInterface::class);
$this->customerDataFactory = $this->objectManager->get(CustomerInterfaceFactory::class);
$this->customerFactory = $this->objectManager->get(CustomerFactory::class);
$this->addressFactory = $this->objectManager->get(AddressInterfaceFactory::class);
$this->itemFactory = $this->objectManager->get(CartItemInterfaceFactory::class);
$this->customerResourceModel = $this->objectManager->get(CustomerResourceModel::class);
$this->groupFactory = $this->objectManager->get(GroupFactory::class);
$this->extensibleDataObjectConverter = $this->objectManager->get(ExtensibleDataObjectConverter::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
if ($this->customerIdToDelete) {
$this->customerRepository->deleteById($this->customerIdToDelete);
}
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Sales/_files/quote.php
* @magentoDataFixture Magento/Catalog/_files/product_virtual.php
* @return void
*/
public function testCollectTotalsWithVirtual(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test01');
$product = $this->productRepository->get('virtual-product', false, null, true);
$quote->addProduct($product);
$quote->collectTotals();
$this->assertEquals(2, $quote->getItemsQty());
$this->assertEquals(1, $quote->getVirtualItemsQty());
$this->assertEquals(20, $quote->getGrandTotal());
$this->assertEquals(20, $quote->getBaseGrandTotal());
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_virtual.php
*
* @return void
*/
public function testGetAddressWithVirtualProduct(): void
{
$quote = $this->objectManager->create(Quote::class);
$billingAddress = $this->addressFactory->create();
$billingAddress->setFirstname('Joe')
->setLastname('Doe')
->setCountryId('US')
->setRegion('TX')
->setCity('Austin')
->setStreet('1000 West Parmer Line')
->setPostcode('11501')
->setTelephone('123456789');
$quote->setBillingAddress($billingAddress);
$shippingAddress = $this->addressFactory->create();
$shippingAddress->setFirstname('Joe')
->setLastname('Doe')
->setCountryId('US')
->setRegion('NJ')
->setCity('Newark')
->setStreet('2775 Granville Lane')
->setPostcode('07102')
->setTelephone('9734685221');
$quote->setShippingAddress($shippingAddress);
$product = $this->productRepository->get('virtual-product', false, null, true);
$quote->addProduct($product);
$quote->save();
$expectedAddress = $quote->getBillingAddress();
$this->assertEquals($expectedAddress, $quote->getAllItems()[0]->getAddress());
}
/**
* @return void
*/
public function testSetCustomerData(): void
{
$quote = $this->quoteFactory->create();
$expected = $this->getCustomerDataArray();
$customer = $this->customerDataFactory->create();
$this->dataObjectHelper->populateWithArray($customer, $expected, CustomerInterfaceFactory::class);
$this->assertEquals($expected, $this->extensibleDataObjectConverter->toFlatArray($customer));
$quote->setCustomer($customer);
$customer = $quote->getCustomer();
$this->assertEquals($expected, $this->extensibleDataObjectConverter->toFlatArray($customer));
$this->assertEquals($expected[CustomerInterface::EMAIL], $quote->getCustomerEmail());
$this->assertEquals($expected[CustomerInterface::FIRSTNAME], $quote->getCustomerFirstname());
$this->assertEquals($expected[CustomerInterface::LASTNAME], $quote->getCustomerLastname());
$this->assertEquals($expected[CustomerInterface::MIDDLENAME], $quote->getCustomerMiddlename());
}
/**
* @magentoAppArea adminhtml
*
* @return void
*/
public function testUpdateCustomerData(): void
{
$quote = $this->quoteFactory->create();
$expected = $this->getCustomerDataArray();
unset($expected[CustomerInterface::ID]);
$customerDataSet = $this->customerDataFactory->create();
$this->dataObjectHelper->populateWithArray($customerDataSet, $expected, CustomerInterface::class);
$this->assertEquals($expected, $this->extensibleDataObjectConverter->toFlatArray($customerDataSet));
$customer = $this->customerRepository->save($customerDataSet);
$this->customerIdToDelete = $customer->getId();
$quote->setCustomer($customerDataSet);
$expected = $this->getCustomerDataArray();
$expected[CustomerInterface::EMAIL] = 'test@example.com';
$customerDataUpdated = $this->customerDataFactory->create();
$this->dataObjectHelper->populateWithArray($customerDataUpdated, $expected, CustomerInterface::class);
$quote->updateCustomerData($customerDataUpdated);
$customer = $quote->getCustomer();
$actual = $this->extensibleDataObjectConverter->toFlatArray($customer);
foreach ($expected as $item) {
$this->assertContains($item, $actual);
}
$this->assertEquals('test@example.com', $quote->getCustomerEmail());
}
/**
* Customer data is set to quote (which contains valid group ID).
*
* @return void
*/
public function testGetCustomerGroupFromCustomer(): void
{
$customerGroupId = 3;
$customerData = $this->customerDataFactory->create()->setId(1)->setGroupId($customerGroupId);
$quote = $this->quoteFactory->create();
$quote->setCustomer($customerData);
$quote->unsetData('customer_group_id');
$this->assertEquals($customerGroupId, $quote->getCustomerGroupId(), "Customer group ID is invalid");
}
/**
* @magentoDataFixture Magento/Customer/_files/customer_group.php
* @return void
*/
public function testGetCustomerTaxClassId(): void
{
$fixtureGroupCode = 'custom_group';
$fixtureTaxClassId = 3;
$fixtureGroupId = $this->groupFactory->create()->load($fixtureGroupCode, 'customer_group_code')->getId();
$quote = $this->quoteFactory->create();
$quote->setCustomerGroupId($fixtureGroupId);
$this->assertEquals($fixtureTaxClassId, $quote->getCustomerTaxClassId(), 'Customer tax class ID is invalid.');
}
/**
* Billing and shipping address arguments are not passed, customer has default billing and shipping addresses.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
* @return void
*/
public function testAssignCustomerWithAddressChangeAddressesNotSpecified(): void
{
$quote = $this->quoteFactory->create();
$customerData = $this->prepareQuoteForTestAssignCustomerWithAddressChange($quote);
$quote->assignCustomerWithAddressChange($customerData);
$fixtureCustomerId = 1;
$this->assertEquals($fixtureCustomerId, $quote->getCustomerId(), 'Customer ID in quote is invalid.');
$expectedBillingAddressData = [
AddressInterface::KEY_STREET => 'Green str, 67',
AddressInterface::KEY_TELEPHONE => 3468676,
AddressInterface::KEY_POSTCODE => 75477,
AddressInterface::KEY_COUNTRY_ID => 'US',
AddressInterface::KEY_CITY => 'CityM',
AddressInterface::KEY_LASTNAME => 'Smith',
AddressInterface::KEY_FIRSTNAME => 'John',
AddressInterface::KEY_CUSTOMER_ID => 1,
AddressInterface::CUSTOMER_ADDRESS_ID => 1,
AddressInterface::KEY_REGION_ID => 1,
];
$this->assertQuoteAddress($expectedBillingAddressData, $quote->getBillingAddress());
$expectedShippingAddressData = [
AddressInterface::CUSTOMER_ADDRESS_ID => 2,
AddressInterface::KEY_TELEPHONE => 3234676,
AddressInterface::KEY_POSTCODE => 47676,
AddressInterface::KEY_COUNTRY_ID => 'US',
AddressInterface::KEY_CITY => 'CityX',
AddressInterface::KEY_STREET => 'Black str, 48',
AddressInterface::KEY_LASTNAME => 'Smith',
AddressInterface::KEY_FIRSTNAME => 'John',
AddressInterface::KEY_CUSTOMER_ID => 1,
AddressInterface::KEY_REGION_ID => 1,
];
$this->assertQuoteAddress($expectedShippingAddressData, $quote->getShippingAddress());
}
/**
* Billing and shipping address arguments are passed, customer has default billing and shipping addresses.
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
* @return void
*/
public function testAssignCustomerWithAddressChange(): void
{
$quote = $this->quoteFactory->create();
$customerData = $this->prepareQuoteForTestAssignCustomerWithAddressChange($quote);
$expectedBillingAddressData = [
AddressInterface::KEY_STREET => 'Billing str, 67',
AddressInterface::KEY_TELEPHONE => 16546757,
AddressInterface::KEY_POSTCODE => 2425457,
AddressInterface::KEY_COUNTRY_ID => 'US',
AddressInterface::KEY_CITY => 'CityBilling',
AddressInterface::KEY_LASTNAME => 'LastBilling',
AddressInterface::KEY_FIRSTNAME => 'FirstBilling',
AddressInterface::KEY_REGION_ID => 1,
];
$quoteBillingAddress = $this->addressFactory->create();
$quoteBillingAddress->setData($expectedBillingAddressData);
$expectedShippingAddressData = [
AddressInterface::KEY_TELEPHONE => 787878787,
AddressInterface::KEY_POSTCODE => 117785,
AddressInterface::KEY_COUNTRY_ID => 'US',
AddressInterface::KEY_CITY => 'CityShipping',
AddressInterface::KEY_STREET => 'Shipping str, 48',
AddressInterface::KEY_LASTNAME => 'LastShipping',
AddressInterface::KEY_FIRSTNAME => 'FirstShipping',
AddressInterface::KEY_REGION_ID => 1,
];
$quoteShippingAddress = $this->addressFactory->create();
$quoteShippingAddress->setData($expectedShippingAddressData);
$quote->assignCustomerWithAddressChange($customerData, $quoteBillingAddress, $quoteShippingAddress);
$fixtureCustomerId = 1;
$this->assertEquals($fixtureCustomerId, $quote->getCustomerId(), 'Customer ID in quote is invalid.');
$this->assertQuoteAddress($expectedBillingAddressData, $quote->getBillingAddress());
$this->assertQuoteAddress($expectedShippingAddressData, $quote->getShippingAddress());
}
/**
* Customer has address with country which not allowed in website
*
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoDataFixture Magento/Backend/_files/allowed_countries_fr.php
* @return void
*/
public function testAssignCustomerWithAddressChangeWithNotAllowedCountry(): void
{
$quote = $this->quoteFactory->create();
$customerData = $this->prepareQuoteForTestAssignCustomerWithAddressChange($quote);
$quote->assignCustomerWithAddressChange($customerData);
$this->assertNull($quote->getBillingAddress()->getCountryId());
$this->assertNull($quote->getShippingAddress()->getCountryId());
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php
* @return void
*/
public function testAddProductUpdateItem(): void
{
$quote = $this->quoteFactory->create();
$productStockQty = 100;
$product = $this->productRepository->get('simple-1', false, null, true);
$quote->addProduct($product, 50);
$quote->setTotalsCollectedFlag(false)->collectTotals();
$this->assertEquals(50, $quote->getItemsQty());
$quote->addProduct($product, 50);
$quote->setTotalsCollectedFlag(false)->collectTotals();
$this->assertEquals(100, $quote->getItemsQty());
$params = [
'related_product' => '',
'product' => $product->getId(),
'qty' => 1,
'id' => 0,
];
$updateParams = new \Magento\Framework\DataObject($params);
$quote->updateItem($updateParams['id'], $updateParams);
$quote->setTotalsCollectedFlag(false)->collectTotals();
$this->assertEquals(1, $quote->getItemsQty());
$this->expectException(LocalizedException::class);
// TODO: fix test or implementation as described in https://github.com/magento-engcom/msi/issues/1037
// $this->expectExceptionMessage('The requested qty is not available');
$updateParams['qty'] = $productStockQty + 1;
$quote->updateItem($updateParams['id'], $updateParams);
}
/**
* Test to verify that reserved_order_id will be changed if it already in used
*
* @magentoDataFixture Magento/Sales/_files/order.php
* @magentoDataFixture Magento/Quote/_files/empty_quote.php
* @return void
*/
public function testReserveOrderId(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('reserved_order_id');
$quote->reserveOrderId();
$this->assertEquals('reserved_order_id', $quote->getReservedOrderId());
$quote->setReservedOrderId('100000001');
$quote->reserveOrderId();
$this->assertNotEquals('100000001', $quote->getReservedOrderId());
}
/**
* Test to verify that disabled product cannot be added to cart
* @magentoDataFixture Magento/Quote/_files/is_not_salable_product.php
* @return void
*/
public function testAddedProductToQuoteIsSalable(): void
{
$product = $this->productRepository->getById(99, false, null, true);
$this->expectException(LocalizedException::class);
$this->expectExceptionMessage((string)__('Product that you are trying to add is not available.'));
$this->quoteFactory->create()->addProduct($product);
}
/**
* @magentoDataFixture Magento/Sales/_files/quote.php
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @return void
*/
public function testGetItemById(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test01');
$quoteItem = $this->itemFactory->create();
$product = $this->productRepository->get('simple');
$quoteItem->setProduct($product);
$quote->addItem($quoteItem);
$quote->save();
$item = $quote->getItemById($quoteItem->getId());
$this->assertInstanceOf(CartItemInterface::class, $item);
$this->assertEquals($quoteItem->getId(), $item->getId());
}
/**
* Tests of quotes merging.
*
* @param int|null $guestItemGiftMessageId
* @param int|null $customerItemGiftMessageId
* @param int|null $guestOrderGiftMessageId
* @param int|null $customerOrderGiftMessageId
* @param int|null $expectedItemGiftMessageId
* @param int|null $expectedOrderGiftMessageId
*
* @magentoDataFixture Magento/Sales/_files/quote.php
* @dataProvider giftMessageDataProvider
* @return void
*/
public function testMerge(
?int $guestItemGiftMessageId,
?int $customerItemGiftMessageId,
?int $guestOrderGiftMessageId,
?int $customerOrderGiftMessageId,
?int $expectedItemGiftMessageId,
?int $expectedOrderGiftMessageId
): void {
$product = $this->productRepository->get('simple', false, null, true);
$guestQuote = $this->getQuoteByReservedOrderId->execute('test01');
$guestQuote->setGiftMessageId($guestOrderGiftMessageId);
$customerQuote = $this->quoteFactory->create();
$customerQuote->setReservedOrderId('test02')
->setStoreId($guestQuote->getStoreId())
->addProduct($product);
$customerQuote->setGiftMessageId($customerOrderGiftMessageId);
$guestItem = $guestQuote->getItemByProduct($product);
$guestItem->setGiftMessageId($guestItemGiftMessageId);
$customerItem = $customerQuote->getItemByProduct($product);
$customerItem->setGiftMessageId($customerItemGiftMessageId);
$customerQuote->merge($guestQuote);
$mergedItemItem = $customerQuote->getItemByProduct($product);
$this->assertEquals($expectedOrderGiftMessageId, $customerQuote->getGiftMessageId());
$this->assertEquals($expectedItemGiftMessageId, $mergedItemItem->getGiftMessageId());
}
/**
* Provides order- and item-level gift message Id.
*
* @return array
*/
public function giftMessageDataProvider(): array
{
return [
[
'guestItemId' => null,
'customerItemId' => 1,
'guestOrderId' => null,
'customerOrderId' => 11,
'expectedItemId' => 1,
'expectedOrderId' => 11,
],
[
'guestItemId' => 1,
'customerItemId' => 2,
'guestOrderId' => 11,
'customerOrderId' => 22,
'expectedItemId' => 1,
'expectedOrderId' => 11,
],
];
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_with_custom_file_option.php
*
* @return void
*/
public function testAddProductWithoutChosenOptions(): void
{
$quote = $this->quoteFactory->create();
$product = $this->productRepository->get('simple_with_custom_file_option');
$result = $quote->addProduct($product);
$this->assertEquals(
(string)__(
'The product\'s required option(s) weren\'t entered. Make sure the options are entered and try again.'
),
$result
);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php
*
* @return void
*/
public function testAddProductWithInvalidRequestParams(): void
{
$quote = $this->quoteFactory->create();
$product = $this->productRepository->get('simple-1');
$this->expectExceptionObject(
new LocalizedException(__('We found an invalid request for adding product to quote.'))
);
$quote->addProduct($product, '');
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_out_of_stock.php
*
* @return void
*/
public function testAddProductOutOfStock(): void
{
$quote = $this->quoteFactory->create();
$product = $this->productRepository->get('simple-out-of-stock');
$this->expectExceptionObject(
new LocalizedException(__('Product that you are trying to add is not available.'))
);
$quote->addProduct($product, 1);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php
*
* @return void
*/
public function testAddProductWithMoreQty(): void
{
$quote = $this->quoteFactory->create();
$product = $this->productRepository->get('simple-1');
$this->expectExceptionObject(new LocalizedException(__('The requested qty is not available')));
$quote->addProduct($product, 1500);
}
/**
* @magentoDataFixture Magento/Catalog/_files/simple_product_with_qty_increments.php
*
* @return void
*/
public function testAddProductWithQtyIncrements(): void
{
$quote = $this->quoteFactory->create();
$product = $this->productRepository->get('simple_product_with_qty_increments');
$this->expectExceptionObject(
new LocalizedException(__('You can buy this product only in quantities of %1 at a time.', 3))
);
$quote->addProduct($product, 1);
}
/**
* @magentoDataFixture Magento/Catalog/_files/simple_product_min_max_sale_qty.php
* @magentoAppIsolation enabled
*
* @return void
*/
public function testAddProductWithMinSaleQty(): void
{
$quote = $this->quoteFactory->create();
$product = $this->productRepository->get('simple_product_min_max_sale_qty');
$messages = [
(string)__('The fewest you may purchase is %1.', 5),
(string)__('The fewest you may purchase is %1', 5),
];
$this->expectException(LocalizedException::class);
$this->expectExceptionMessageMatches('/' . implode('|', $messages) . '/');
$quote->addProduct($product, 1);
}
/**
* @magentoDataFixture Magento/Catalog/_files/simple_product_min_max_sale_qty.php
*
* @return void
*/
public function testAddProductWithMaxSaleQty(): void
{
$quote = $this->quoteFactory->create();
$product = $this->productRepository->get('simple_product_min_max_sale_qty');
$messages = [
(string)__('The most you may purchase is %1.', 20),
(string)__('The requested qty exceeds the maximum qty allowed in shopping cart'),
];
$this->expectException(LocalizedException::class);
$this->expectExceptionMessageMatches('/' . implode('|', $messages) . '/');
$quote->addProduct($product, 25);
}
/**
* @magentoConfigFixture current_store cataloginventory/item_options/enable_qty_increments 1
* @magentoConfigFixture current_store cataloginventory/item_options/qty_increments 3
* @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php
* @magentoAppIsolation enabled
*
* @return void
*/
public function testAddProductWithConfigQtyIncrements(): void
{
$quote = $this->quoteFactory->create();
$product = $this->productRepository->get('simple-1');
$this->expectExceptionObject(
new LocalizedException(__('You can buy this product only in quantities of %1 at a time.', 3))
);
$quote->addProduct($product, 1);
}
/**
* @magentoConfigFixture current_store cataloginventory/item_options/min_sale_qty 5
* @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php
* @magentoAppIsolation enabled
*
* @return void
*/
public function testAddProductWithConfigMinSaleQty(): void
{
$quote = $this->quoteFactory->create();
$product = $this->productRepository->get('simple-1');
$messages = [
(string)__('The fewest you may purchase is %1.', 5),
(string)__('The fewest you may purchase is %1', 5),
];
$this->expectException(LocalizedException::class);
$this->expectExceptionMessageMatches('/' . implode('|', $messages) . '/');
$quote->addProduct($product, 1);
}
/**
* @magentoConfigFixture current_store cataloginventory/item_options/max_sale_qty 20
* @magentoDataFixture Magento/Catalog/_files/product_simple_duplicated.php
* @magentoAppIsolation enabled
*
* @return void
*/
public function testAddProductWithConfigMaxSaleQty(): void
{
$quote = $this->quoteFactory->create();
$product = $this->productRepository->get('simple-1');
$messages = [
(string)__('The most you may purchase is %1.', 20),
(string)__('The requested qty exceeds the maximum qty allowed in shopping cart'),
];
$this->expectException(LocalizedException::class);
$this->expectExceptionMessageMatches('/' . implode('|', $messages) . '/');
$quote->addProduct($product, 25);
}
/**
* Assert address in quote.
*
* @param array $expectedAddress
* @param AddressInterface $quoteAddress
* @return void
*/
private function assertQuoteAddress(array $expectedAddress, AddressInterface $quoteAddress): void
{
foreach ($expectedAddress as $field => $value) {
$this->assertEquals(
$value,
$quoteAddress->getData($field),
sprintf('"%s" value in quote %s address is invalid.', $field, $quoteAddress->getAddressType())
);
}
}
/**
* Prepare quote for testing assignCustomerWithAddressChange method.
* Customer with two addresses created. First address is default billing, second is default shipping.
*
* @param CartInterface $quote
* @return CustomerInterface
*/
private function prepareQuoteForTestAssignCustomerWithAddressChange(CartInterface $quote): CustomerInterface
{
$fixtureCustomerId = 1;
$fixtureSecondAddressId = 2;
$customer = $this->customerFactory->create();
$this->customerResourceModel->load($customer, $fixtureCustomerId);
$customer->setDefaultShipping($fixtureSecondAddressId);
$this->customerResourceModel->save($customer);
$customerData = $customer->getDataModel();
$this->assertEmpty(
$quote->getBillingAddress()->getId(),
"Precondition failed: billing address should be empty."
);
$this->assertEmpty(
$quote->getShippingAddress()->getId(),
"Precondition failed: shipping address should be empty."
);
return $customerData;
}
/**
* @return array
*/
private function getCustomerDataArray(): array
{
return [
CustomerInterface::CONFIRMATION => 'test',
CustomerInterface::CREATED_AT => '2/3/2014',
CustomerInterface::CREATED_IN => 'Default',
CustomerInterface::DEFAULT_BILLING => 'test',
CustomerInterface::DEFAULT_SHIPPING => 'test',
CustomerInterface::DOB => '2014-02-03 00:00:00',
CustomerInterface::EMAIL => 'qa@example.com',
CustomerInterface::FIRSTNAME => 'Joe',
CustomerInterface::GENDER => 0,
CustomerInterface::GROUP_ID => GroupManagement::NOT_LOGGED_IN_ID,
CustomerInterface::ID => 1,
CustomerInterface::LASTNAME => 'Dou',
CustomerInterface::MIDDLENAME => 'Ivan',
CustomerInterface::PREFIX => 'Dr.',
CustomerInterface::STORE_ID => 1,
CustomerInterface::SUFFIX => 'Jr.',
CustomerInterface::TAXVAT => 1,
CustomerInterface::WEBSITE_ID => 1,
];
}
/**
* @magentoConfigFixture current_store sales/minimum_order/active 1
* @magentoConfigFixture current_store sales/minimum_order/amount 5
* @magentoConfigFixture current_store sales/minimum_order/tax_including 1
* @magentoConfigFixture current_store sales/minimum_order/include_discount_amount 1
* @magentoConfigFixture current_store tax/calculation/price_includes_tax 1
* @magentoConfigFixture current_store tax/calculation/apply_after_discount 1
* @magentoConfigFixture current_store tax/calculation/cross_border_trade_enabled 1
* @magentoDataFixture Magento/SalesRule/_files/cart_rule_with_coupon_5_off_no_condition.php
* @magentoDataFixture Magento/Tax/_files/tax_rule_region_1_al.php
* @magentoDataFixture Magento/Checkout/_files/quote_with_taxable_product_and_customer.php
*/
public function testValidateMinimumAmountWithPriceInclTaxAndDiscount()
{
/** @var $quote \Magento\Quote\Model\Quote */
$quote = $this->getQuoteByReservedOrderId->execute('test_order_with_taxable_product');
$quote->setCouponCode('CART_FIXED_DISCOUNT_5');
$quote->collectTotals();
$this->assertEquals(-5, $quote->getShippingAddress()->getBaseDiscountAmount());
$this->assertEquals(9.3, $quote->getShippingAddress()->getBaseSubtotal());
$this->assertEquals(5, $quote->getShippingAddress()->getBaseGrandTotal());
$this->assertTrue($quote->validateMinimumAmount());
}
/**
* @magentoConfigFixture current_store multishipping/options/checkout_multiple 1
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Multishipping/Fixtures/quote_with_split_items.php
* @return void
*/
public function testIsMultiShippingModeEnabledAfterQuoteItemRemoved(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('multishipping_quote_id');
/** @var CheckoutSession $session */
$session = $this->objectManager->get(CheckoutSession::class);
$session->replaceQuote($quote);
$items = $quote->getAllItems();
$idToDelete = null;
foreach ($items as $item) {
if (!$item->getProduct()->isVirtual() && $item->getQty() == 1) {
$idToDelete = $item->getId();
}
}
if (!is_null($idToDelete)) {
$quoteShippingAddresses = $quote->getAllShippingAddresses();
foreach ($quoteShippingAddresses as $shippingAddress) {
if ($shippingAddress->getItemById($idToDelete)) {
$shippingAddress->removeItem($idToDelete);
$shippingAddress->setCollectShippingRates(true);
if (count($shippingAddress->getAllItems()) == 0) {
$shippingAddress->isDeleted(true);
}
}
}
$quote->removeItem($idToDelete);
$this->assertEquals(
1,
$quote->getIsMultiShipping(),
"Multi-shipping mode is disabled after quote item removal"
);
} else {
$this->assertTrue(
!is_null($idToDelete),
"No Simple Product item with qty 1 to delete exists"
);
}
}
}
@@ -0,0 +1,230 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Quote\Model;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\Data\AddressInterface;
use Magento\Quote\Model\Quote\Address\Rate;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class QuoteValidatorTest.
*
* @magentoDbIsolation enabled
*/
class QuoteValidatorTest extends \PHPUnit\Framework\TestCase
{
/**
* @var QuoteValidator
*/
private $quoteValidator;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->quoteValidator = Bootstrap::getObjectManager()->create(QuoteValidator::class);
}
/**
*/
public function testValidateBeforeSubmitShippingAddressInvalid()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('Please check the shipping address information.');
$quote = $this->getQuote();
$quote->getShippingAddress()->setPostcode('');
$this->quoteValidator->validateBeforeSubmit($quote);
}
/**
*/
public function testValidateBeforeSubmitCountryIsNotAllowed()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('Some addresses can\'t be used due to the configurations for specific countries.');
/** @magentoConfigFixture does not allow to change the value for the website scope */
Bootstrap::getObjectManager()->get(
\Magento\Framework\App\Config\MutableScopeConfigInterface::class
)->setValue(
'general/country/allow',
'US',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
$quote = $this->getQuote();
$quote->getShippingAddress()->setCountryId('AF');
$this->quoteValidator->validateBeforeSubmit($quote);
}
/**
*/
public function testValidateBeforeSubmitShippingMethodInvalid()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('The shipping method is missing. Select the shipping method and try again.');
$quote = $this->getQuote();
$quote->getShippingAddress()->setShippingMethod('NONE');
$this->quoteValidator->validateBeforeSubmit($quote);
}
/**
*/
public function testValidateBeforeSubmitBillingAddressInvalid()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('Please check the billing address information.');
$quote = $this->getQuote();
$quote->getBillingAddress()->setTelephone('');
$this->quoteValidator->validateBeforeSubmit($quote);
}
/**
*/
public function testValidateBeforeSubmitPaymentMethodInvalid()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('Enter a valid payment method and try again.');
$quote = $this->getQuote();
$quote->getPayment()->setMethod('');
$this->quoteValidator->validateBeforeSubmit($quote);
}
/**
* @magentoConfigFixture current_store sales/minimum_order/active 1
* @magentoConfigFixture current_store sales/minimum_order/amount 100
*/
public function testValidateBeforeSubmitMinimumAmountInvalid()
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$quote = $this->getQuote();
$quote->getShippingAddress()
->setBaseSubtotal(0);
$this->quoteValidator->validateBeforeSubmit($quote);
}
/**
* @return void
*/
public function testValidateBeforeSubmitWithoutMinimumOrderAmount()
{
$this->quoteValidator->validateBeforeSubmit($this->getQuote());
}
/**
* @magentoConfigFixture current_store sales/minimum_order/active 1
* @magentoConfigFixture current_store sales/minimum_order/amount 100
*/
public function testValidateBeforeSubmitWithMinimumOrderAmount()
{
$quote = $this->getQuote();
$quote->getShippingAddress()
->setBaseSubtotal(200);
$this->quoteValidator->validateBeforeSubmit($quote);
}
/**
* Checks a case when the default website has country restrictions and the quote created
* for the another website with different country restrictions.
*
* @magentoDataFixture Magento/Quote/Fixtures/quote_sec_website.php
* @magentoDbIsolation disabled
*/
public function testValidateBeforeSubmit()
{
$quote = $this->getQuoteById('0000032134');
$this->quoteValidator->validateBeforeSubmit($quote);
}
/**
* @return Quote
*/
private function getQuote(): Quote
{
/** @var Quote $quote */
$quote = Bootstrap::getObjectManager()->create(Quote::class);
/** @var AddressInterface $billingAddress */
$billingAddress = Bootstrap::getObjectManager()->create(AddressInterface::class);
$billingAddress->setFirstname('Joe')
->setLastname('Doe')
->setCountryId('US')
->setRegion('TX')
->setCity('Austin')
->setStreet('1000 West Parmer Line')
->setPostcode('11501')
->setTelephone('123456789');
$quote->setBillingAddress($billingAddress);
/** @var AddressInterface $shippingAddress */
$shippingAddress = Bootstrap::getObjectManager()->create(AddressInterface::class);
$shippingAddress->setFirstname('Joe')
->setLastname('Doe')
->setCountryId('US')
->setRegion('TX')
->setCity('Austin')
->setStreet('1000 West Parmer Line')
->setPostcode('11501')
->setTelephone('123456789');
$quote->setShippingAddress($shippingAddress);
$quote->getShippingAddress()
->setShippingMethod('flatrate_flatrate')
->setCollectShippingRates(true);
/** @var Rate $shippingRate */
$shippingRate = Bootstrap::getObjectManager()->create(Rate::class);
$shippingRate->setMethod('flatrate')
->setCarrier('flatrate')
->setPrice('5')
->setCarrierTitle('Flat Rate')
->setCode('flatrate_flatrate');
$quote->getShippingAddress()
->addShippingRate($shippingRate);
$quote->getPayment()->setMethod('CC');
/** @var QuoteRepository $quoteRepository */
$quoteRepository = Bootstrap::getObjectManager()->create(QuoteRepository::class);
$quoteRepository->save($quote);
return $quote;
}
/**
* Gets quote entity by reserved order id.
*
* @param string $reservedOrderId
* @return Quote
*/
private function getQuoteById(string $reservedOrderId): Quote
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = Bootstrap::getObjectManager()->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', $reservedOrderId)
->create();
/** @var CartRepositoryInterface $repository */
$repository = Bootstrap::getObjectManager()->get(CartRepositoryInterface::class);
$items = $repository->getList($searchCriteria)
->getItems();
return array_pop($items);
}
}
@@ -0,0 +1,590 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Quote\Model;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\Catalog\Test\Fixture\Virtual as VirtualProductFixture;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\GroupInterface;
use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Customer\Model\Vat;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Config\MutableScopeConfigInterface;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\Data\AddressInterfaceFactory;
use Magento\Quote\Api\Data\EstimateAddressInterface;
use Magento\Quote\Api\GuestShippingMethodManagementInterface;
use Magento\Quote\Api\ShippingMethodManagementInterface;
use Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver;
use Magento\Quote\Test\Fixture\AddProductToCart as AddProductToCartFixture;
use Magento\Quote\Test\Fixture\GuestCart as GuestCartFixture;
use Magento\Checkout\Test\Fixture\SetBillingAddress as SetBillingAddressFixture;
use Magento\Checkout\Test\Fixture\SetShippingAddress as SetShippingAddressFixture;
use Magento\SalesRule\Test\Fixture\AddressCondition as AddressConditionFixture;
use Magento\SalesRule\Test\Fixture\Rule as RuleFixture;
use Magento\Store\Model\ScopeInterface;
use Magento\Tax\Api\Data\TaxClassInterface;
use Magento\Tax\Api\TaxClassRepositoryInterface;
use Magento\Tax\Model\ClassModel;
use Magento\Tax\Model\Config as TaxConfig;
use Magento\TestFramework\Fixture\Config as ConfigFixture;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorage;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use PHPUnit\Framework\TestCase;
use Magento\Quote\Api\CouponManagementInterface;
use Magento\Customer\Model\Session;
/**
* Test for shipping methods management
*
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ShippingMethodManagementTest extends TestCase
{
/** @var ObjectManagerInterface $objectManager */
private $objectManager;
/** @var GroupRepositoryInterface $groupRepository */
private $groupRepository;
/** @var TaxClassRepositoryInterface $taxClassRepository */
private $taxClassRepository;
/**
* @var DataFixtureStorage
*/
private $fixtures;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->groupRepository = $this->objectManager->get(GroupRepositoryInterface::class);
$this->taxClassRepository = $this->objectManager->get(TaxClassRepositoryInterface::class);
$this->fixtures = $this->objectManager->get(DataFixtureStorageManager::class)->getStorage();
}
/**
* @magentoDataFixture Magento/SalesRule/_files/cart_rule_100_percent_off.php
* @magentoDataFixture Magento/Sales/_files/quote_with_customer.php
* @return void
* @throws NoSuchEntityException
*/
public function testRateAppliedToShipping(): void
{
$objectManager = Bootstrap::getObjectManager();
/** @var CartRepositoryInterface $quoteRepository */
$quoteRepository = $objectManager->create(CartRepositoryInterface::class);
$customerQuote = $quoteRepository->getForCustomer(1);
$this->assertEquals(0, $customerQuote->getBaseGrandTotal());
}
/**
* @magentoConfigFixture current_store carriers/tablerate/active 1
* @magentoConfigFixture current_store carriers/flatrate/active 0
* @magentoConfigFixture current_store carriers/freeshipping/active 0
* @magentoConfigFixture current_store carriers/tablerate/condition_name package_qty
* @magentoDataFixture Magento/SalesRule/_files/cart_rule_free_shipping_by_cart.php
* @magentoDataFixture Magento/Sales/_files/quote.php
* @magentoDataFixture Magento/OfflineShipping/_files/tablerates.php
* @return void
*/
public function testTableRateFreeShipping()
{
$objectManager = Bootstrap::getObjectManager();
/** @var Quote $quote */
$quote = $objectManager->get(Quote::class);
$quote->load('test01', 'reserved_order_id');
$cartId = $quote->getId();
if (!$cartId) {
$this->fail('quote fixture failed');
}
/** @var QuoteIdMask $quoteIdMask */
$quoteIdMask = Bootstrap::getObjectManager()
->create(QuoteIdMaskFactory::class)
->create();
$quoteIdMask->load($cartId, 'quote_id');
//Use masked cart Id
$cartId = $quoteIdMask->getMaskedId();
$data = [
'data' => [
'country_id' => "US",
'postcode' => null,
'region' => null,
'region_id' => null
]
];
/** @var EstimateAddressInterface $address */
$address = $objectManager->create(EstimateAddressInterface::class, $data);
/** @var GuestShippingMethodManagementInterface $shippingEstimation */
$shippingEstimation = $objectManager->get(GuestShippingMethodManagementInterface::class);
$result = $shippingEstimation->estimateByAddress($cartId, $address);
$this->assertNotEmpty($result);
$expectedResult = [
'method_code' => 'bestway',
'amount' => 0
];
foreach ($result as $rate) {
$this->assertEquals($expectedResult['amount'], $rate->getAmount());
$this->assertEquals($expectedResult['method_code'], $rate->getMethodCode());
}
}
/**
* @magentoDataFixture Magento/OfflineShipping/_files/tablerates_price.php
* @return void
* @throws NoSuchEntityException
*/
#[
ConfigFixture('carriers/tablerate/active', '1', 'store', 'default'),
ConfigFixture('carriers/flatrate/active', '0', 'store', 'default'),
ConfigFixture('carriers/tablerate/condition_name', 'package_value_with_discount', 'store'),
ConfigFixture('carriers/tablerate/include_virtual_price', '0', 'store', 'default'),
DataFixture(ProductFixture::class, ['sku' => 'simple', 'special_price' => 5.99], 'p1'),
DataFixture(VirtualProductFixture::class, ['sku' => 'virtual', 'weight' => 0], 'p2'),
DataFixture(GuestCartFixture::class, as: 'cart'),
DataFixture(AddProductToCartFixture::class, ['cart_id' => '$cart.id$', 'product_id' => '$p1.id$']),
DataFixture(AddProductToCartFixture::class, ['cart_id' => '$cart.id$', 'product_id' => '$p2.id$']),
DataFixture(SetBillingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetShippingAddressFixture::class, ['cart_id' => '$cart.id$']),
]
public function testTableRateWithoutIncludingVirtualProduct()
{
$cartId = (int)$this->fixtures->get('cart')->getId();
if (!$cartId) {
$this->fail('quote fixture failed');
}
/** @var QuoteRepository $quoteRepository */
$quoteRepository = $this->objectManager->get(QuoteRepository::class);
$quote = $quoteRepository->get($cartId);
/** @var QuoteIdToMaskedQuoteIdInterface $maskedQuoteId */
$maskedQuoteId = $this->objectManager->get(QuoteIdToMaskedQuoteIdInterface::class)->execute($cartId);
/** @var GuestShippingMethodManagementInterface $shippingEstimation */
$shippingEstimation = $this->objectManager->get(GuestShippingMethodManagementInterface::class);
$result = $shippingEstimation->estimateByExtendedAddress(
$maskedQuoteId,
$quote->getShippingAddress()
);
$this->assertCount(1, $result);
$rate = reset($result);
$expectedResult = [
'method_code' => 'bestway',
'amount' => 15,
];
$this->assertEquals($expectedResult['method_code'], $rate->getMethodCode());
$this->assertEquals($expectedResult['amount'], $rate->getAmount());
}
/**
* Test table rate amount for the cart that contains some items with free shipping applied.
*
* @magentoConfigFixture current_store carriers/tablerate/active 1
* @magentoConfigFixture current_store carriers/flatrate/active 0
* @magentoConfigFixture current_store carriers/freeshipping/active 0
* @magentoConfigFixture current_store carriers/tablerate/condition_name package_value_with_discount
* @magentoDataFixture Magento/Catalog/_files/categories.php
* @magentoDataFixture Magento/SalesRule/_files/cart_rule_free_shipping_by_category.php
* @magentoDataFixture Magento/Sales/_files/quote_with_multiple_products.php
* @magentoDataFixture Magento/OfflineShipping/_files/tablerates_price.php
* @return void
*/
public function testTableRateWithCartRuleForFreeShipping()
{
$objectManager = Bootstrap::getObjectManager();
$quote = $this->getQuote('tableRate');
$cartId = $quote->getId();
if (!$cartId) {
$this->fail('quote fixture failed');
}
/** @var QuoteIdMask $quoteIdMask */
$quoteIdMask = Bootstrap::getObjectManager()
->create(QuoteIdMaskFactory::class)
->create();
$quoteIdMask->load($cartId, 'quote_id');
//Use masked cart Id
$cartId = $quoteIdMask->getMaskedId();
$addressFactory = $this->objectManager->get(AddressInterfaceFactory::class);
/** @var \Magento\Quote\Api\Data\AddressInterface $address */
$address = $addressFactory->create();
$address->setCountryId('US');
/** @var GuestShippingMethodManagementInterface $shippingEstimation */
$shippingEstimation = $objectManager->get(GuestShippingMethodManagementInterface::class);
$result = $shippingEstimation->estimateByExtendedAddress($cartId, $address);
$this->assertCount(1, $result);
$rate = reset($result);
$expectedResult = [
'method_code' => 'bestway',
'amount' => 10
];
$this->assertEquals($expectedResult['method_code'], $rate->getMethodCode());
$this->assertEquals($expectedResult['amount'], $rate->getAmount());
}
/**
* Retrieves quote by reserved order id.
*
* @param string $reservedOrderId
* @return Quote
*/
private function getQuote(string $reservedOrderId): Quote
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', $reservedOrderId)
->create();
/** @var CartRepositoryInterface $quoteRepository */
$quoteRepository = $this->objectManager->get(CartRepositoryInterface::class);
$items = $quoteRepository->getList($searchCriteria)->getItems();
return array_pop($items);
}
/**
* @magentoConfigFixture current_store carriers/tablerate/active 1
* @magentoConfigFixture current_store carriers/tablerate/condition_name package_qty
* @magentoDataFixture Magento/SalesRule/_files/cart_rule_free_shipping.php
* @magentoDataFixture Magento/Sales/_files/quote.php
* @magentoDataFixture Magento/OfflineShipping/_files/tablerates.php
* @return void
*/
public function testEstimateByAddressWithCartPriceRuleByItem()
{
$this->executeTestFlow(0, 0);
}
/**
* @magentoConfigFixture current_store carriers/tablerate/active 1
* @magentoConfigFixture current_store carriers/tablerate/condition_name package_qty
* @magentoDataFixture Magento/SalesRule/_files/cart_rule_free_shipping_by_cart.php
* @magentoDataFixture Magento/Sales/_files/quote.php
* @magentoDataFixture Magento/OfflineShipping/_files/tablerates.php
* @return void
*/
public function testEstimateByAddressWithCartPriceRuleByShipment()
{
$this->markTestSkipped('According to MAGETWO-69940 it is an incorrect behavior');
// Rule applied to entire shipment should not overwrite flat or table rate shipping prices
// Only rules applied to specific items should modify those prices (MAGETWO-63844)
$this->executeTestFlow(5, 10);
}
/**
* @magentoConfigFixture current_store carriers/tablerate/active 1
* @magentoConfigFixture current_store carriers/tablerate/condition_name package_qty
* @magentoDataFixture Magento/Sales/_files/quote.php
* @magentoDataFixture Magento/OfflineShipping/_files/tablerates.php
* @return void
*/
public function testEstimateByAddress()
{
$this->executeTestFlow(5, 10);
}
/**
* Provide testing of shipping method estimation based on address
*
* @param int $flatRateAmount
* @param int $tableRateAmount
* @return void
*/
private function executeTestFlow($flatRateAmount, $tableRateAmount)
{
$objectManager = Bootstrap::getObjectManager();
/** @var Quote $quote */
$quote = $objectManager->get(Quote::class);
$quote->load('test01', 'reserved_order_id');
$cartId = $quote->getId();
if (!$cartId) {
$this->fail('quote fixture failed');
}
/** @var QuoteIdMask $quoteIdMask */
$quoteIdMask = Bootstrap::getObjectManager()
->create(QuoteIdMaskFactory::class)
->create();
$quoteIdMask->load($cartId, 'quote_id');
//Use masked cart Id
$cartId = $quoteIdMask->getMaskedId();
$data = [
'data' => [
'country_id' => "US",
'postcode' => null,
'region' => null,
'region_id' => null
]
];
/** @var EstimateAddressInterface $address */
$address = $objectManager->create(EstimateAddressInterface::class, $data);
/** @var GuestShippingMethodManagementInterface $shippingEstimation */
$shippingEstimation = $objectManager->get(GuestShippingMethodManagementInterface::class);
$result = $shippingEstimation->estimateByAddress($cartId, $address);
$this->assertNotEmpty($result);
$expectedResult = [
'tablerate' => [
'method_code' => 'bestway',
'amount' => $tableRateAmount
],
'flatrate' => [
'method_code' => 'flatrate',
'amount' => $flatRateAmount
]
];
foreach ($result as $rate) {
$this->assertEquals($expectedResult[$rate->getCarrierCode()]['amount'], $rate->getAmount());
$this->assertEquals($expectedResult[$rate->getCarrierCode()]['method_code'], $rate->getMethodCode());
}
}
/**
* Test for estimate shipping with tax and changed VAT customer group
*
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/Tax/_files/tax_classes_de.php
* @magentoDataFixture Magento/Sales/_files/quote_with_customer.php
* @magentoDataFixture Magento/Customer/_files/customer_group.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
* @magentoConfigFixture current_store customer/create_account/tax_calculation_address_type shipping
* @magentoConfigFixture current_store customer/create_account/default_group 1
* @magentoConfigFixture current_store customer/create_account/auto_group_assign 1
* @magentoConfigFixture current_store tax/calculation/price_includes_tax 1
* @magentoConfigFixture current_store tax/calculation/shipping_includes_tax 1
*/
public function testEstimateByAddressWithInclExclTaxAndVATGroup()
{
/** @var GroupInterface $customerGroup */
$customerGroup = $this->findCustomerGroupByCode('custom_group');
$this->mockCustomerVat((int)$customerGroup->getId());
$customerGroup->setTaxClassId($this->getTaxClass('CustomerTaxClass')->getClassId());
$this->groupRepository->save($customerGroup);
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = $this->objectManager->get(CustomerRepositoryInterface::class);
$customer = $customerRepository->get('customer@example.com');
$customer->setGroupId($customerGroup->getId());
$customer->setTaxvat('12');
$customerRepository->save($customer);
$this->setConfig($customerGroup->getId(), $this->getTaxClass('ProductTaxClass')->getClassId());
$this->changeCustomerAddress($customer->getDefaultShipping());
$quote = $this->objectManager->get(GetQuoteByReservedOrderId::class)->execute('test01');
$addressRepository = $this->objectManager->get(AddressRepositoryInterface::class);
$address = $addressRepository->getById(1);
$address->setIsDefaultShipping(true);
$customer->setAddresses([$address]);
$customerSession = $this->objectManager->get(Session::class);
$customerSession->loginById($customer->getId());
/** @var ShippingMethodManagementInterface $shippingEstimation */
$shippingEstimation = $this->objectManager->get(ShippingMethodManagementInterface::class);
$result = $shippingEstimation->estimateByAddressId($quote->getId(), (int)$customer->getDefaultShipping());
$this->assertEquals(6.05, $result[0]->getPriceInclTax());
$this->assertEquals(5.0, $result[0]->getPriceExclTax());
}
/**
* Create a test double fot customer vat class
*
* @param int $customerGroupId
*/
private function mockCustomerVat(int $customerGroupId): void
{
$gatewayResponse = new DataObject([
'is_valid' => false,
'request_date' => '',
'request_identifier' => '123123123',
'request_success' => false,
'request_message' => __('Error during VAT Number verification.'),
]);
$customerVat = $this->createPartialMock(
Vat::class,
[
'checkVatNumber',
'isCountryInEU',
'getCustomerGroupIdBasedOnVatNumber',
'getMerchantCountryCode',
'getMerchantVatNumber'
]
);
$customerVat->method('checkVatNumber')->willReturn($gatewayResponse);
$customerVat->method('isCountryInEU')->willReturn(true);
$customerVat->method('getMerchantCountryCode')->willReturn('GB');
$customerVat->method('getMerchantVatNumber')->willReturn('11111');
$customerVat->method('getCustomerGroupIdBasedOnVatNumber')->willReturn($customerGroupId);
$this->objectManager->removeSharedInstance(Vat::class);
$this->objectManager->addSharedInstance($customerVat, Vat::class);
// Remove instances where the customer vat object is cached
$this->objectManager->removeSharedInstance(CollectTotalsObserver::class);
}
/**
* Find the group with a given code.
*
* @param string $code
* @return GroupInterface
*/
protected function findCustomerGroupByCode(string $code): ?GroupInterface
{
/** @var SearchCriteriaBuilder $searchBuilder */
$searchBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchBuilder->addFilter('code', $code)
->create();
$groups = $this->groupRepository->getList($searchCriteria)
->getItems();
return array_shift($groups);
}
/**
* Change customer address
*
* @param int $customerAddressId
*
* @return AddressInterface
*/
private function changeCustomerAddress(int $customerAddressId): AddressInterface
{
$addressRepository = $this->objectManager->get(AddressRepositoryInterface::class);
$address = $addressRepository->getById($customerAddressId);
$address->setVatId(12345);
$address->setCountryId('DE');
$address->setRegionId(0);
$address->setPostcode(10178);
return $addressRepository->save($address);
}
/**
* Get tax class.
*
* @param string $name
*
* @return TaxClassInterface
*/
private function getTaxClass(string $name): ?TaxClassInterface
{
/** @var SearchCriteriaBuilder $searchBuilder */
$searchBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchBuilder->addFilter(ClassModel::KEY_NAME, $name)
->create();
$searchResults = $this->taxClassRepository->getList($searchCriteria)
->getItems();
return array_shift($searchResults);
}
/**
* Set the configuration.
*
* @param int $customerGroupId
* @param int $productTaxClassId
*
* @return void
*/
private function setConfig(int $customerGroupId, int $productTaxClassId): void
{
$configData = [
[
'path' => Vat::XML_PATH_CUSTOMER_VIV_INVALID_GROUP,
'value' => $customerGroupId,
'scope' => ScopeInterface::SCOPE_STORE,
],
[
'path' => TaxConfig::CONFIG_XML_PATH_SHIPPING_TAX_CLASS,
'value' => $productTaxClassId,
'scope' => ScopeInterface::SCOPE_STORE,
],
];
$config = $this->objectManager->get(MutableScopeConfigInterface::class);
foreach ($configData as $data) {
$config->setValue($data['path'], $data['value'], $data['scope']);
}
}
/**
*
* Test table rate with zero amount is available for the cart when discount coupon cart price rule to all items
* and freeshipping cart price rule is applied when order subtotal is greater than specified amount.
*
* @magentoConfigFixture default_store carriers/tablerate/active 1
* @magentoConfigFixture default_store carriers/flatrate/active 0
* @magentoConfigFixture default_store carriers/freeshipping/active 0
* @magentoConfigFixture default_store carriers/tablerate/condition_name package_value_with_discount
* @magentoDataFixture Magento/Sales/_files/quote_with_multiple_products.php
* @magentoDataFixture Magento/OfflineShipping/_files/tablerates_price.php
* @return void
*/
#[
DataFixture(
AddressConditionFixture::class,
['attribute' => 'base_subtotal', 'operator' => '>=', 'value' => 30],
'c1'
),
DataFixture(
RuleFixture::class,
['stop_rules_processing' => 0, 'simple_free_shipping' => 1, 'conditions' => ['$c1$']],
'r1'
),
DataFixture(
RuleFixture::class,
['stop_rules_processing' => 0, 'coupon_code' => '123', 'discount_amount' => 20],
'r1'
),
]
public function testTableRateWithZeroPriceShownWhenDiscountCouponAndFreeShippingCartRuleApplied()
{
$objectManager = Bootstrap::getObjectManager();
$quote = $this->getQuote('tableRate');
$cartId = $quote->getId();
if (!$cartId) {
$this->fail('quote fixture failed');
}
/** @var QuoteIdMask $quoteIdMask */
$quoteIdMask = Bootstrap::getObjectManager()
->create(QuoteIdMaskFactory::class)
->create();
$quoteIdMask->load($cartId, 'quote_id');
//Use masked cart Id
$cartId = $quoteIdMask->getMaskedId();
$addressFactory = $this->objectManager->get(AddressInterfaceFactory::class);
/** @var \Magento\Quote\Api\Data\AddressInterface $address */
$address = $addressFactory->create();
$address->setCountryId('US');
/** @var CouponManagementInterface $couponManagement */
$couponManagement = Bootstrap::getObjectManager()->get(CouponManagementInterface::class);
$couponManagement->set($quote->getId(), '123');
/** @var GuestShippingMethodManagementInterface $shippingEstimation */
$shippingEstimation = $objectManager->get(GuestShippingMethodManagementInterface::class);
$result = $shippingEstimation->estimateByExtendedAddress($cartId, $address);
$this->assertCount(1, $result);
$rate = reset($result);
$expectedResult = [
'method_code' => 'bestway',
'amount' => 0
];
$this->assertEquals($expectedResult['method_code'], $rate->getMethodCode());
$this->assertEquals($expectedResult['amount'], $rate->getAmount());
}
}
@@ -0,0 +1,182 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Quote\Observer\Frontend\Quote\Address;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Model\Customer;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Model\Group;
use Magento\Framework\Event\Observer;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\Quote\Address\Total;
use Magento\Quote\Model\Shipping;
use Magento\Quote\Model\ShippingAssignment;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test for \Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver.
*/
class CollectTotalsObserverTest extends TestCase
{
private const STUB_CUSTOMER_EMAIL = 'customer@example.com';
/**
* @var CollectTotalsObserver
*/
private $model;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheridoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->model = $this->objectManager->create(CollectTotalsObserver::class);
}
/**
* @magentoConfigFixture current_store customer/create_account/auto_group_assign 1
* @magentoConfigFixture current_store customer/create_account/default_group 1
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Sales/_files/quote.php
*
* @covers \Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver::execute
*/
public function testChangeQuoteCustomerGroupIdForCustomerWithDisabledAutomaticGroupChange(): void
{
/** @var ObjectManagerInterface $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var $customer Customer */
$customer = $objectManager->create(Customer::class);
$customer->load(1);
$customer->setDisableAutoGroupChange(1);
$customer->setGroupId(2);
$customer->save();
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = $objectManager->create(CustomerRepositoryInterface::class);
$customerData = $customerRepository->getById($customer->getId());
/** @var $quote Quote */
$quote = $objectManager->create(Quote::class);
$quote->load('test01', 'reserved_order_id');
$quote->setCustomer($customerData);
$quoteAddress = $quote->getBillingAddress();
$shippingAssignment = $this->objectManager->create(ShippingAssignment::class);
$shipping = $this->objectManager->create(Shipping::class);
$shipping->setAddress($quoteAddress);
$shippingAssignment->setShipping($shipping);
/** @var Total $total */
$total = $this->objectManager->create(Total::class);
$eventObserver = $objectManager->create(
Observer::class,
['data' => [
'quote' => $quote,
'shipping_assignment' => $shippingAssignment,
'total' => $total
]
]
);
$this->model->execute($eventObserver);
$this->assertEquals(2, $quote->getCustomer()->getGroupId());
}
/**
* @magentoConfigFixture current_store customer/create_account/auto_group_assign 1
* @magentoConfigFixture current_store customer/create_account/default_group 1
* @magentoDataFixture Magento/Customer/_files/customer.php
* @magentoDataFixture Magento/Sales/_files/quote.php
*
* @covers \Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver::execute
*/
public function testChangeQuoteCustomerGroupIdForCustomerWithEnabledAutomaticGroupChange(): void
{
/** @var ObjectManagerInterface $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var $customer Customer */
$customer = $objectManager->create(Customer::class);
$customer->load(1);
$customer->setDisableAutoGroupChange(0);
$customer->setGroupId(2);
$customer->save();
/** @var CustomerRegistry $customerRegistry */
$customerRegistry = $objectManager->get(CustomerRegistry::class);
$customerRegistry->remove($customer->getId());
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = $objectManager->create(CustomerRepositoryInterface::class);
$customerData = $customerRepository->getById($customer->getId());
/** @var $quote Quote */
$quote = $objectManager->create(Quote::class);
$quote->load('test01', 'reserved_order_id');
$quote->setCustomer($customerData);
$quoteAddress = $quote->getBillingAddress();
$shippingAssignment = $this->objectManager->create(ShippingAssignment::class);
$shipping = $this->objectManager->create(Shipping::class);
$shipping->setAddress($quoteAddress);
$shippingAssignment->setShipping($shipping);
/** @var Total $total */
$total = $this->objectManager->create(Total::class);
$eventObserver = $objectManager->create(
Observer::class,
['data' => ['quote' => $quote, 'shipping_assignment' => $shippingAssignment, 'total' => $total]]
);
$this->model->execute($eventObserver);
$this->assertEquals(2, $quote->getCustomer()->getGroupId());
}
/**
* Dispatch event with guest quote and check that email will not be override to null when auto group assign enabled
*
* @magentoConfigFixture current_store customer/create_account/auto_group_assign 1
*
* @return void
*/
public function testQuoteCustomerEmailNotChanged(): void
{
// prepare quote for guest
$quote = $this->objectManager->create(Quote::class);
$quote->setCustomerId(null)
->setCustomerEmail(self::STUB_CUSTOMER_EMAIL)
->setCustomerIsGuest(true)
->setCustomerGroupId(Group::NOT_LOGGED_IN_ID);
$quoteAddress = $quote->getBillingAddress();
$shippingAssignment = $this->objectManager->create(ShippingAssignment::class);
$shipping = $this->objectManager->create(Shipping::class);
$shipping->setAddress($quoteAddress);
$shippingAssignment->setShipping($shipping);
/** @var Total $total */
$total = $this->objectManager->create(Total::class);
$eventObserver = $this->objectManager->create(
Observer::class,
['data' => ['quote' => $quote, 'shipping_assignment' => $shippingAssignment, 'total' => $total]]
);
$this->model->execute($eventObserver);
$this->assertEquals(self::STUB_CUSTOMER_EMAIL, $quote->getCustomerEmail());
}
}
@@ -0,0 +1,23 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $objectManager->create(\Magento\Quote\Model\Quote::class);
$quote->setStoreId(1)
->setIsActive(true)
->setIsMultiShipping(false)
->setReservedOrderId('reserved_order_id')
->collectTotals()
->save();
/** @var \Magento\Quote\Model\QuoteIdMask $quoteIdMask */
$quoteIdMask = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Quote\Model\QuoteIdMaskFactory::class)
->create();
$quoteIdMask->setQuoteId($quote->getId());
$quoteIdMask->setDataChanges(true);
$quoteIdMask->save();
@@ -0,0 +1,13 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$quote = $objectManager->create(\Magento\Quote\Model\Quote::class);
$quote->load('reserved_order_id', 'reserved_order_id')
->delete();
$objectManager->create(\Magento\Quote\Model\QuoteIdMask::class)
->delete($quote->getId());
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$product = $objectManager->create(\Magento\Catalog\Model\Product::class);
$product->isObjectNew(true);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setId(99)
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product')
->setSku('simple-99')
->setPrice(10)
->setWeight(1)
->setShortDescription("Short description")
->setTaxClassId(0)
->setDescription('Description with <b>html tag</b>')
->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_DISABLED)
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
)
->setCanSaveCustomOptions(true)
->setHasOptions(true);
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepositoryFactory */
$productRepositoryFactory = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productRepositoryFactory->save($product);
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$product = $objectManager->create(\Magento\Catalog\Model\Product::class);
$product->isObjectNew(true);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setId(99)
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product')
->setSku('simple-99')
->setPrice(10)
->setWeight(1)
->setShortDescription("Short description")
->setTaxClassId(0)
->setDescription('Description with <b>html tag</b>')
->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)
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
)
->setCanSaveCustomOptions(true)
->setHasOptions(true);
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepositoryFactory */
$productRepositoryFactory = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productRepositoryFactory->save($product);
@@ -0,0 +1,90 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductExtensionInterfaceFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ProductFactory;
use Magento\ConfigurableProduct\Helper\Product\Options\Factory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/ConfigurableProduct/_files/configurable_attribute.php');
$objectManager = Bootstrap::getObjectManager();
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
/** @var ProductFactory $productFactory */
$productFactory = $objectManager->get(ProductFactory::class);
/** @var Factory $optionsFactory */
$optionsFactory = $objectManager->get(Factory::class);
/** @var ProductExtensionInterfaceFactory $productExtensionAttributes */
$productExtensionAttributesFactory = $objectManager->get(ProductExtensionInterfaceFactory::class);
/** @var WebsiteRepositoryInterface $websiteRepository */
$websiteRepository = $objectManager->get(WebsiteRepositoryInterface::class);
$defaultWebsiteId = $websiteRepository->get('base')->getId();
/** @var \Magento\Eav\Model\Config $eavConfig */
$eavConfig = $objectManager->get(\Magento\Eav\Model\Config::class);
$attribute = $eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, 'test_configurable');
$option = $attribute->getSource()->getOptionId('Option 1');
$product = $productFactory->create();
$product->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([$defaultWebsiteId])
->setName('Configurable Option 1')
->setSku('simple_1')
->setPrice(10.00)
->setTestConfigurable($option)
->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE)
->setStatus(Status::STATUS_ENABLED)
->setStockData([
'manage_stock' => 1,
'use_config_manage_stock' => 0,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
'use_config_max_sale_qty' => 0,
'max_sale_qty' => 2
]);
$product = $productRepository->save($product);
$configurableOptions = $optionsFactory->create(
[
[
'attribute_id' => $attribute->getId(),
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getStoreLabel(),
'position' => '0',
'values' => [['label' => 'test', 'attribute_id' => $attribute->getId(), 'value_index' => $option]],
],
]
);
$extensionConfigurableAttributes = $product->getExtensionAttributes() ?: $productExtensionAttributesFactory->create();
$extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
$extensionConfigurableAttributes->setConfigurableProductLinks([$product->getId()]);
$configurableProduct = $productFactory->create();
$configurableProduct->setExtensionAttributes($extensionConfigurableAttributes);
$configurableProduct->setTypeId(Configurable::TYPE_CODE)
->setAttributeSetId($configurableProduct->getDefaultAttributeSetId())
->setWebsiteIds([$defaultWebsiteId])
->setName('Configurable Product')
->setSku('configurable')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData([
'manage_stock' => 1,
'use_config_manage_stock' => 0,
'is_in_stock' => 1,
'use_config_max_sale_qty' => 0,
'max_sale_qty' => 2
]);
$productRepository->save($configurableProduct);
@@ -0,0 +1,33 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
foreach (['simple_1', 'configurable'] as $sku) {
try {
$product = $productRepository->get($sku);
$productRepository->delete($product);
} catch (NoSuchEntityException $e) {
//Product already removed
}
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
Resolver::getInstance()->requireDataFixture('Magento/ConfigurableProduct/_files/configurable_attribute_rollback.php');
@@ -0,0 +1,49 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\Quote\Address;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\Customer\Api\CustomerRepositoryInterface;
/** @var ObjectManager $objectManager */
$objectManager = Bootstrap::getObjectManager();
$customer = $objectManager->get(CustomerRepositoryInterface::class)->get('customer@example.com');
$store = $objectManager->get(StoreRepositoryInterface::class)->get('secondstore');
$addressData = include __DIR__ . '/../../Customer/Fixtures/address_data.php';
/** @var Address $shippingAddress */
$shippingAddress = $objectManager->create(Address::class, ['data' => $addressData[0]]);
$shippingAddress->setAddressType('shipping');
$billingAddress = clone $shippingAddress;
$billingAddress->setId(null)
->setAddressType('billing');
/** @var Quote $quote */
$quote = $objectManager->create(
Quote::class,
[
'data' => [
'customer_id' => $customer->getId(),
'store_id' => $store->getId(),
'reserved_order_id' => 'tsg-123456789',
'is_active' => true,
'is_multishipping' => false
],
]
);
$quote->setShippingAddress($shippingAddress)
->setBillingAddress($billingAddress);
/** @var CartRepositoryInterface $repository */
$repository = $objectManager->get(CartRepositoryInterface::class);
$repository->save($quote);
@@ -0,0 +1,29 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Framework\Registry;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
/** @var ObjectManager $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$quote = $objectManager->get(GetQuoteByReservedOrderId::class)->execute('tsg-123456789');
if ($quote !== null) {
/** @var CartRepositoryInterface $cartRepository */
$cartRepository = $objectManager->get(CartRepositoryInterface::class);
$cartRepository->delete($quote);
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,34 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
<extension_attributes for="Magento\Quote\Api\Data\CartInterface">
<attribute code="quoteTestAttribute" type="Magento\User\Api\Data\UserInterface">
<join reference_table="admin_user"
join_on_field="store_id"
reference_field="user_id"
>
<field>firstname</field>
<field>lastname</field>
<field>email</field>
</join>
</attribute>
</extension_attributes>
<extension_attributes for="Magento\Quote\Api\Data\CartItemInterface">
<attribute code="quoteItemTestAttribute" type="Magento\User\Api\Data\UserInterface">
<join reference_table="admin_user"
join_on_field="store_id"
reference_field="user_id"
>
<field>firstname</field>
<field>lastname</field>
<field>email</field>
</join>
</attribute>
</extension_attributes>
</config>