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,168 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Api\OrderAddressRepositoryInterface;
use Magento\Sales\Model\Order\Address as AddressType;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Class check address save action
*
* @see \Magento\Sales\Controller\Adminhtml\Order\AddressSave
*
* @magentoDbIsolation disabled
* @magentoAppArea adminhtml
*/
class AddressSaveTest extends AbstractBackendController
{
/** @var OrderInterfaceFactory */
private $orderFactory;
/** @var OrderAddressRepositoryInterface */
private $orderAddressRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->orderFactory = $this->_objectManager->get(OrderInterfaceFactory::class);
$this->orderAddressRepository = $this->_objectManager->get(OrderAddressRepositoryInterface::class);
}
/**
* @dataProvider addressTypeProvider
*
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @param string $type
* @return void
*/
public function testSave(string $type): void
{
$data = [
OrderAddressInterface::FIRSTNAME => 'New test name',
OrderAddressInterface::LASTNAME => 'New test lastname',
OrderAddressInterface::STREET => ['new test street'],
OrderAddressInterface::CITY => 'New Test City',
OrderAddressInterface::COUNTRY_ID => 'UA',
OrderAddressInterface::REGION => '1111',
OrderAddressInterface::POSTCODE => '97203',
OrderAddressInterface::TELEPHONE => '5555555555',
];
$order = $this->orderFactory->create()->loadByIncrementId(100000001);
$addressId = $this->getAddressIdByType($order, $type);
$this->dispatchWithParams(
['address_id' => $addressId],
$data
);
$this->assertSessionMessages(
$this->containsEqual((string)__('You updated the order address.'))
);
$this->assertRedirect(
$this->stringContains(sprintf('sales/order/view/order_id/%s/', $order->getId()))
);
$this->assertAddressData($addressId, $data);
}
/**
* @return array
*/
public function addressTypeProvider(): array
{
return [
'billing_address' => [
AddressType::TYPE_BILLING,
],
'shipping_address' => [
AddressType::TYPE_SHIPPING,
]
];
}
/**
* @dataProvider wrongRequestDataProvider
*
* @param array $params
* @param array $post
* @return void
*/
public function testInvalidRequest(array $params, array $post = []): void
{
$this->dispatchWithParams($params, $post);
$this->assertRedirect($this->stringContains('backend/sales/order/index/'));
}
/**
* @return array
*/
public function wrongRequestDataProvider(): array
{
return [
'empty_post' => [
['address_id' => 1],
],
'wrong_address_id' => [
['address_id' => 7852147],
],
];
}
/**
* Check updated address data
*
* @param int $addressId
* @param array $expectedData
* @return void
*/
private function assertAddressData(int $addressId, array $expectedData): void
{
$address = $this->orderAddressRepository->get($addressId);
foreach ($expectedData as $key => $value) {
$key === OrderAddressInterface::STREET
? $this->assertEquals(reset($value), $address->getData($key))
: $this->assertEquals($value, $address->getData($key));
}
}
/**
* Get address id by address type
*
* @param OrderInterface $order
* @param string $type
* @return int
*/
private function getAddressIdByType(OrderInterface $order, string $type): int
{
return $type === AddressType::TYPE_BILLING
? (int)$order->getBillingAddressId()
: (int)$order->getShippingAddressId();
}
/**
* Dispatch with params
*
* @param array $params
* @param array $post
* @return void
*/
private function dispatchWithParams(array $params, array $post): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParams($params);
$this->getRequest()->setPostValue($post);
$this->dispatch('backend/sales/order/addressSave');
}
}
@@ -0,0 +1,76 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Registry;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Class check address edit action
*
* @see \Magento\Sales\Controller\Adminhtml\Order\Address
*
* @magentoDbIsolation disabled
* @magentoAppArea adminhtml
*/
class AddressTest extends AbstractBackendController
{
/** @var OrderInterfaceFactory */
private $orderFactory;
/** @var Registry */
private $registry;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->orderFactory = $this->_objectManager->get(OrderInterfaceFactory::class);
$this->registry = $this->_objectManager->get(Registry::class);
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testSuccessfulEdit(): void
{
$order = $this->orderFactory->create()->loadByIncrementId(100000001);
$this->dispatchWithAddressId((int)$order->getBillingAddressId());
$this->assertInstanceOf(OrderAddressInterface::class, $this->registry->registry('order_address'));
}
/**
* @return void
*/
public function testWithNotExistingAddressId(): void
{
$this->dispatchWithAddressId(51728);
$this->assertRedirect($this->stringContains('backend/sales/order/index/'));
}
/**
* Dispatch request with address_id param
*
* @param int $addressId
* @return void
*/
private function dispatchWithAddressId(int $addressId): void
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParam('address_id', $addressId);
$this->dispatch('backend/sales/order/address');
}
}
@@ -0,0 +1,21 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Controller\Adminhtml\Order;
class AuthorizationMock extends \Magento\Framework\Authorization
{
/**
* Check current user permission on resource and privilege
*
* @param string $resource
* @param string $privilege
* @return boolean
*/
public function isAllowed($resource, $privilege = null)
{
return $resource == 'Magento_Sales::create' ? false : parent::isAllowed($resource, $privilege);
}
}
@@ -0,0 +1,75 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Create;
use Magento\Backend\Model\Session\Quote;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Registry;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Class checks create order index controller.
*
* @see \Magento\Sales\Controller\Adminhtml\Order\Create\Index
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class IndexTest extends AbstractBackendController
{
/** @var Registry */
private $registry;
/** @var StoreManagerInterface */
private $storeManager;
/** @var Quote */
private $quoteSession;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->registry = $this->_objectManager->get(Registry::class);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
$this->quoteSession = $this->_objectManager->get(Quote::class);
}
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*
* @return void
*/
public function testExecute(): void
{
$customerId = 1;
$editingOrderId = 10;
$this->getRequest()->setMethod(Http::METHOD_GET);
$this->getRequest()->setParam('customer_id', $customerId);
$this->quoteSession->setOrderId($editingOrderId);
$this->assertEquals($editingOrderId, $this->quoteSession->getOrderId());
$this->dispatch('backend/sales/order_create/index');
// Check that existing order in session was cleared
$this->assertEquals(null, $this->quoteSession->getOrderId());
$store = $this->storeManager->getStore();
$this->assertEquals($customerId, $this->quoteSession->getCustomerId());
$ruleData = $this->registry->registry('rule_data');
$this->assertNotNull($ruleData);
$this->assertEquals(
['store_id' => $store->getId(), 'website_id' => $store->getWebsiteId(), 'customer_group_id' => 1],
$ruleData->getData()
);
}
}
@@ -0,0 +1,487 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Create;
use Magento\Backend\Model\Session\Quote;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\Data\CartInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use Magento\TestFramework\TestCase\AbstractBackendController;
use Magento\Wishlist\Model\Wishlist;
/**
* Class checks create order load block controller.
*
* @see \Magento\Sales\Controller\Adminhtml\Order\Create\LoadBlock
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class LoadBlockTest extends AbstractBackendController
{
/** @var LayoutInterface */
private $layout;
/** @var GetQuoteByReservedOrderId */
private $getQuoteByReservedOrderId;
/** @var Quote */
private $session;
/** @var CartRepositoryInterface */
private $quoteRepository;
/** @var StoreManagerInterface */
private $storeManager;
/** @var array */
private $quoteIdsToRemove;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->layout = $this->_objectManager->get(LayoutInterface::class);
$this->getQuoteByReservedOrderId = $this->_objectManager->get(GetQuoteByReservedOrderId::class);
$this->session = $this->_objectManager->get(Quote::class);
$this->quoteRepository = $this->_objectManager->get(CartRepositoryInterface::class);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->quoteIdsToRemove[] = $this->session->getQuote()->getId();
foreach ($this->quoteIdsToRemove as $quoteId) {
try {
$this->quoteRepository->delete($this->quoteRepository->get($quoteId));
} catch (NoSuchEntityException $e) {
//do nothing
}
}
$this->session->clearStorage();
parent::tearDown();
}
/**
* @dataProvider responseFlagsProvider
*
* @magentoDataFixture Magento/Checkout/_files/quote_with_customer_without_address.php
*
* @param bool $asJson
* @param bool $asJsVarname
* @return void
*/
public function testAddProductToOrderFromShoppingCart(bool $asJson, bool $asJsVarname): void
{
$oldQuote = $this->getQuoteByReservedOrderId->execute('test_order_with_customer_without_address');
$params = $this->hydrateParams([
'json' => $asJson,
'as_js_varname' => $asJsVarname,
]);
$itemId = $oldQuote->getItemsCollection()->getFirstItem()->getId();
$post = $this->hydratePost([
'sidebar' => [
'add_cart_item' => [
$itemId => 1,
],
],
]);
$this->dispatchWitParams($params, $post);
$this->checkHandles(explode(',', $params['block']), $asJson);
$newQuote = $this->session->getQuote();
$newQuoteItemsCollection = $newQuote->getItemsCollection(false);
$this->assertNotNull($newQuoteItemsCollection->getItemByColumnValue('sku', 'simple2'));
if ($asJsVarname) {
$this->assertRedirect($this->stringContains('sales/order_create/showUpdateResult'));
$body = (string) $this->_objectManager->get(\Magento\Backend\Model\Session::class)->getUpdateResult();
} elseif ($asJson) {
$body = json_decode($this->getResponse()->getBody(), true, 512, JSON_THROW_ON_ERROR)['sidebar'];
} else {
$body = $this->getResponse()->getBody();
}
$this->assertStringNotContainsString("sidebar[add_cart_item][$itemId]", $body);
}
/**
* @return array
*/
public function responseFlagsProvider(): array
{
return [
'as_json' => [
'as_json' => true,
'as_js_varname' => false,
],
'as_plain' => [
'as_json' => false,
'as_js_varname' => true,
],
];
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_customer_without_address.php
*
* @return void
*/
public function testRemoveProductFromShoppingCart(): void
{
$oldQuote = $this->getQuoteByReservedOrderId->execute('test_order_with_customer_without_address');
$post = $this->hydratePost([
'sidebar' => [
'remove' => [
$oldQuote->getItemsCollection()->getFirstItem()->getId() => 'cart',
],
],
]);
$params = $this->hydrateParams();
$this->dispatchWitParams($params, $post);
$this->checkHandles(explode(',', $params['block']));
$this->checkQuotes($oldQuote);
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_customer_without_address.php
*
* @return void
*/
public function testClearShoppingCart(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test_order_with_customer_without_address');
$post = $this->hydratePost([
'sidebar' => [
'empty_customer_cart' => '1',
],
]);
$params = $this->hydrateParams();
$this->dispatchWitParams($params, $post);
$this->checkHandles(explode(',', $params['block']));
$this->assertEmpty($quote->getItemsCollection(false)->getItems());
}
/**
* @magentoDataFixture Magento/Checkout/_files/inactive_quote_with_customer.php
*
* @return void
*/
public function testMoveFromOrderToShoppingCart(): void
{
$quote = $this->getQuoteByReservedOrderId->execute('test_order_with_customer_inactive_quote');
$this->session->setQuoteId($quote->getId());
$post = $this->hydratePost([
'update_items' => '1',
'item' => [
$quote->getItemsCollection()->getFirstItem()->getId() => [
'qty' => '1',
'use_discount' => '1',
'action' => 'cart',
],
],
]);
$params = $this->hydrateParams(['blocks' => null]);
$this->dispatchWitParams($params, $post);
$customerCart = $this->quoteRepository->getForCustomer(1);
$cartItems = $customerCart->getItemsCollection();
$this->assertCount(1, $cartItems->getItems());
$this->assertEquals('taxable_product', $cartItems->getFirstItem()->getSku());
$this->quoteIdsToRemove[] = $customerCart->getId();
}
/**
* Check that Wishlist item is deleted after it has been added to Order.
*
* @return void
* @magentoDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
* @magentoDbIsolation disabled
*/
public function testAddProductToOrderFromWishList(): void
{
/** @var Wishlist $wishlist */
$wishlist = $this->_objectManager->create(Wishlist::class);
$wishlistItems = $wishlist->loadByCustomerId(1)->getItemCollection();
$this->assertCount(1, $wishlistItems);
$itemId = $wishlistItems->getFirstItem()->getId();
$post = $this->hydratePost([
'sidebar' => [
'add_wishlist_item' => [
$itemId => 1,
],
],
]);
$params = $this->hydrateParams([
'json' => false,
'as_js_varname' => false,
]);
$this->dispatchWitParams($params, $post);
$body = $this->getResponse()->getBody();
$this->assertStringNotContainsString("sidebar[add_wishlist_item][$itemId]", $body);
$quoteItems = $this->session->getQuote()->getItemsCollection();
$this->assertCount(1, $quoteItems);
}
/**
* Check that customer notification is NOT disabled after comment is updated.
*
* @return void
* @magentoDataFixture Magento/Checkout/_files/quote_with_customer_without_address.php
*/
public function testUpdateCustomerNote(): void
{
$customerNote = 'Example Comment';
$quoteId = $this->getQuoteByReservedOrderId->execute('test_order_with_customer_without_address')->getId();
$this->session->setQuoteId($quoteId);
$params = [
'json' => false,
'block' => 'totals',
'as_js_varname' => false,
];
$post = $this->hydratePost([
'order' => [
'comment' => [
CartInterface::KEY_CUSTOMER_NOTE => $customerNote
],
],
]);
$this->dispatchWitParams($params, $post);
$quote = $this->session->getQuote();
$this->assertEquals($customerNote, $quote->getCustomerNote());
$this->assertTrue((bool)$quote->getCustomerNoteNotify());
preg_match('/id="notify_customer"(?<attributes>.*?)\/>/s', $this->getResponse()->getBody(), $matches);
$this->assertArrayHasKey('attributes', $matches);
$this->assertStringContainsString('checked="checked"', $matches['attributes']);
}
/**
* Check that specific store id is setting into the current stores.
*
* @return void
* @magentoDataFixture Magento/Store/_files/second_website_with_store_group_and_store.php
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
* @throws NoSuchEntityException
*/
public function testSetSpecificStoreIdIntoCurrentStore()
{
$params = [];
$post = ['store_id' => $this->storeManager->getStore('fixture_second_store')->getId()];
$this->dispatchWitParams($params, $post);
$this->assertEquals('fixture_second_store', $this->storeManager->getStore()->getCode());
}
/**
* @magentoDataFixture Magento/Checkout/_files/quote_with_address.php
*/
public function testThatItemsTransferredFromShoppingCartAreDeletedAfterOrderIsCreated(): void
{
$oldQuote = $this->getQuoteByReservedOrderId->execute('test_order_1');
$this->assertNotEmpty($oldQuote->getItemsCollection(false)->getItems());
$itemId = $oldQuote->getItemsCollection()->getFirstItem()->getId();
$params = $this->hydrateParams();
$post = $this->hydratePost([
'sidebar' => [
'add_cart_item' => [
$itemId => 1,
],
],
]);
$this->dispatchWitParams($params, $post);
$this->assertNotEmpty($oldQuote->getItemsCollection(false)->getItems());
$this->placeOrder();
$this->assertEmpty($oldQuote->getItemsCollection(false)->getItems());
}
/**
* @magentoDataFixture Magento/Wishlist/_files/wishlist_with_simple_product.php
* @magentoDataFixture Magento/Customer/_files/customer_address.php
*/
public function testThatItemsTransferredFromWishlistAreDeletedAfterOrderIsCreated(): void
{
/** @var Wishlist $wishlist */
$wishlist = $this->_objectManager->create(Wishlist::class);
$wishlistItems = $wishlist->loadByCustomerId(1)->getItemCollection();
$this->assertCount(1, $wishlistItems);
$itemId = $wishlistItems->getFirstItem()->getId();
$post = $this->hydratePost([
'sidebar' => [
'add_wishlist_item' => [
$itemId => 1,
],
],
]);
$params = $this->hydrateParams();
$this->dispatchWitParams($params, $post);
$wishlist = $this->_objectManager->create(Wishlist::class);
$wishlistItems = $wishlist->loadByCustomerId(1)->getItemCollection();
$this->assertCount(1, $wishlistItems);
$this->placeOrder();
$wishlist = $this->_objectManager->create(Wishlist::class);
$wishlistItems = $wishlist->loadByCustomerId(1)->getItemCollection();
$this->assertCount(0, $wishlistItems);
}
/**
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function placeOrder(): void
{
$this->_request = null;
$this->_response = null;
Bootstrap::getInstance()->getBootstrap()->getApplication()->reinitialize();
Bootstrap::getInstance()->loadArea('adminhtml');
$this->_objectManager = Bootstrap::getObjectManager();
$this->getRequest()
->setMethod(\Magento\Framework\App\Request\Http::METHOD_POST)
->setPostValue([
'order' => [
'account' => [
'email' => 'john.doe001@test.com',
],
'shipping_method' => 'flatrate_flatrate',
'payment_method' => 'checkmo',
],
'collect_shipping_rates' => true
]);
$this->dispatch('backend/sales/order_create/save');
$this->assertSessionMessages(
$this->isEmpty(),
MessageInterface::TYPE_ERROR
);
$this->assertSessionMessages(
$this->equalTo([(string)__('You created the order.')]),
MessageInterface::TYPE_SUCCESS
);
}
/**
* Check customer quotes
*
* @param CartInterface $oldQuote
* @param string|null $expectedSku
* @return void
*/
private function checkQuotes(CartInterface $oldQuote, ?string $expectedSku = null): void
{
$newQuote = $this->session->getQuote();
$oldQuoteItemCollection = $oldQuote->getItemsCollection(false);
$this->assertEmpty($oldQuoteItemCollection->getItems());
$newQuoteItemsCollection = $newQuote->getItemsCollection(false);
if ($expectedSku !== null) {
$this->assertNotNull($newQuoteItemsCollection->getItemByColumnValue('sku', $expectedSku));
} else {
$this->assertEmpty($newQuoteItemsCollection->getItems());
}
}
/**
* Check that all required handles were applied
*
* @param array $blocks
* @param bool $asJson
* @return void
*/
private function checkHandles(array $blocks, bool $asJson = true): void
{
$handles = $this->layout->getUpdate()->getHandles();
if ($asJson) {
$this->assertContains('sales_order_create_load_block_message', $handles);
$this->assertContains('sales_order_create_load_block_json', $handles);
} else {
$this->assertContains('sales_order_create_load_block_plain', $handles);
}
foreach ($blocks as $block) {
$this->assertContains(
'sales_order_create_load_block_' . $block,
$handles
);
}
}
/**
* Fill post params array to proper state
*
* @param array $inputArray
* @return array
*/
private function hydratePost(array $inputArray = []): array
{
return array_merge(
[
'customer_id' => 1,
'store_id' => $this->storeManager->getStore('default')->getId(),
'sidebar' => [],
],
$inputArray
);
}
/**
* Fill params array to proper state
*
* @param array $inputArray
* @return array
*/
private function hydrateParams(array $inputArray = []): array
{
return array_merge(
[
'json' => true,
'block' => 'sidebar,items,shipping_method,billing_method,totals,giftmessage',
'as_js_varname' => true,
],
$inputArray
);
}
/**
* Dispatch request with params
*
* @param array $params
* @param array $postParams
* @return void
*/
private function dispatchWitParams(array $params, array $postParams): void
{
$this->getRequest()->setMethod(Http::METHOD_POST)
->setPostValue($postParams)
->setParams($params);
$this->dispatch('backend/sales/order_create/loadBlock');
}
}
@@ -0,0 +1,211 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Create;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\Data\CartInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\Request;
use Magento\TestFramework\TestCase\AbstractBackendController;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Framework\App\Request\Http;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\OrderFactory;
use Magento\TestFramework\Helper\Xpath;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
/**
* Test for reorder controller.
*
* @see \Magento\Sales\Controller\Adminhtml\Order\Create\Reorder
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ReorderTest extends AbstractBackendController
{
/** @var OrderInterfaceFactory */
private $orderFactory;
/** @var CartRepositoryInterface */
private $quoteRepository;
/** @var CartInterface */
private $quote;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @var array
*/
private $customerIds = [];
/**
* @var OrderRepositoryInterface
*/
private $orderRepository;
/**
* @var CustomerInterfaceFactory
*/
private $customerFactory;
/**
* @var AccountManagementInterface
*/
private $accountManagement;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->orderFactory = $this->_objectManager->get(OrderInterfaceFactory::class);
$this->quoteRepository = $this->_objectManager->get(CartRepositoryInterface::class);
$this->orderRepository = $this->_objectManager->get(OrderRepositoryInterface::class);
$this->customerFactory = $this->_objectManager->get(CustomerInterfaceFactory::class);
$this->accountManagement = $this->_objectManager->get(AccountManagementInterface::class);
$this->customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
if ($this->quote instanceof CartInterface) {
$this->quoteRepository->delete($this->quote);
}
foreach ($this->customerIds as $customerId) {
try {
$this->customerRepository->deleteById($customerId);
} catch (NoSuchEntityException $e) {
//customer already deleted
}
}
parent::tearDown();
}
/**
* Reorder with JS calendar options
*
* @magentoConfigFixture current_store catalog/custom_options/use_calendar 1
* @magentoDataFixture Magento/Sales/_files/order_with_date_time_option_product.php
*
* @return void
*/
public function testReorderAfterJSCalendarEnabled(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->dispatchReorderRequest((int)$order->getId());
$this->assertRedirect($this->stringContains('backend/sales/order_create'));
$this->quote = $this->getQuote('customer@example.com');
$this->assertTrue(!empty($this->quote));
}
/**
* Test load billing address by reorder for delegating customer
*
* @magentoDataFixture Magento/Customer/_files/attribute_user_defined_address.php
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testLoadBillingAddressAfterReorderWithDelegatingCustomer(): void
{
$orderId = $this->getOrderWithDelegatingCustomer()->getId();
$this->getRequest()->setMethod(Http::METHOD_GET);
$this->getRequest()->setParam('order_id', $orderId);
$this->dispatch('backend/sales/order_create/loadBlock/block/billing_address');
$html = $this->getResponse()->getBody();
$this->assertEquals(
0,
Xpath::getElementsCountForXpath(
'//*[@id="order-billing_address_save_in_address_book" and contains(@checked, "checked")]',
$html
),
'Billing address checked "Save in address book"'
);
}
/**
* Get Order with delegating customer
*
* @return OrderInterface
*/
private function getOrderWithDelegatingCustomer(): OrderInterface
{
$orderAutoincrementId = '100000001';
/** @var Order $orderModel */
$orderModel = $this->orderFactory->create();
$orderModel->loadByIncrementId($orderAutoincrementId);
//Saving new customer with prepared data from order.
/** @var CustomerInterface $customer */
$customer = $this->customerFactory->create();
$customer->setWebsiteId(1)
->setEmail('customer_order_delegate@example.com')
->setGroupId(1)
->setStoreId(1)
->setPrefix('Mr.')
->setFirstname('John')
->setMiddlename('A')
->setLastname('Smith')
->setSuffix('Esq.')
->setTaxvat('12')
->setGender(0);
$createdCustomer = $this->accountManagement->createAccount(
$customer,
'12345abcD'
);
$this->customerIds[] = $createdCustomer->getId();
$orderModel->setCustomerId($createdCustomer->getId());
return $this->orderRepository->save($orderModel);
}
/**
* Dispatch reorder request.
*
* @param null|int $orderId
* @return void
*/
private function dispatchReorderRequest(?int $orderId = null): void
{
$this->getRequest()->setMethod(Request::METHOD_GET);
$this->getRequest()->setParam('order_id', $orderId);
$this->dispatch('backend/sales/order_create/reorder');
}
/**
* Gets quote by reserved order id.
*
* @return \Magento\Quote\Api\Data\CartInterface
*/
private function getQuote(string $customerEmail): \Magento\Quote\Api\Data\CartInterface
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->_objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('customer_email', $customerEmail)
->create();
/** @var CartRepositoryInterface $quoteRepository */
$quoteRepository = $this->_objectManager->get(CartRepositoryInterface::class);
$items = $quoteRepository->getList($searchCriteria)->getItems();
return array_pop($items);
}
}
@@ -0,0 +1,266 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Controller\Adminhtml\Order\Create;
use Magento\Backend\Model\Session\Quote;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Message\MessageInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Model\OrderRepository;
use Magento\Sales\Model\Service\OrderService;
use Magento\TestFramework\Mail\Template\TransportBuilderMock;
use Magento\TestFramework\TestCase\AbstractBackendController;
use PHPUnit\Framework\Constraint\StringContains;
use PHPUnit\Framework\MockObject\MockObject as MockObject;
/**
* Class test backend order save.
*
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class SaveTest extends AbstractBackendController
{
/**
* @var TransportBuilderMock
*/
private $transportBuilder;
/**
* @var FormKey
*/
private $formKey;
/**
* @var string
*/
protected $resource = 'Magento_Sales::create';
/**
* @var string
*/
protected $uri = 'backend/sales/order_create/save';
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->transportBuilder = $this->_objectManager->get(TransportBuilderMock::class);
$this->formKey = $this->_objectManager->get(FormKey::class);
}
/**
* Checks a case when order creation is failed on payment method processing but new customer already created
* in the database and after new controller dispatching the customer should be already loaded in session
* to prevent invalid validation.
*
* @magentoDataFixture Magento/Sales/_files/quote_with_new_customer.php
*/
public function testExecuteWithPaymentOperation()
{
/** @var OrderService|MockObject $orderService */
$orderService = $this->getMockBuilder(OrderService::class)
->disableOriginalConstructor()
->getMock();
$orderService->method('place')
->willThrowException(new LocalizedException(__('Transaction has been declined.')));
$this->_objectManager->addSharedInstance($orderService, OrderService::class);
$quote = $this->getQuote('2000000001');
$session = $this->_objectManager->get(Quote::class);
$session->setQuoteId($quote->getId());
$session->setCustomerId(0);
$email = 'john.doe001@test.com';
$data = [
'account' => [
'email' => $email,
]
];
$this->getRequest()->setMethod(Http::METHOD_POST);
$this->getRequest()->setPostValue(['order' => $data]);
$this->dispatch('backend/sales/order_create/save');
$this->assertSessionMessages(
self::equalTo(['Transaction has been declined.']),
MessageInterface::TYPE_ERROR
);
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class);
$customer = $customerRepository->get($email);
self::assertNotEmpty($session->getCustomerId());
self::assertEquals($customer->getId(), $session->getCustomerId());
$this->_objectManager->removeSharedInstance(OrderService::class);
}
/**
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Sales/_files/guest_quote_with_addresses.php
*
* @return void
*/
public function testSendEmailOnOrderSave(): void
{
$this->prepareRequest(['send_confirmation' => true]);
$this->dispatch('backend/sales/order_create/save');
$this->assertSessionMessages(
$this->equalTo([(string)__('You created the order.')]),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains('sales/order/view/'));
$orderId = $this->getOrderId();
if ($orderId === false) {
$this->fail('Order is not created.');
}
$order = $this->getOrder($orderId);
$message = $this->transportBuilder->getSentMessage();
$subject = __('Your %1 order confirmation', $order->getStore()->getFrontendName())->render();
$assert = $this->logicalAnd(
new StringContains($order->getBillingAddress()->getName()),
new StringContains(
'Thank you for your order from ' . $order->getStore()->getFrontendName()
),
new StringContains(
"Your Order <span class=\"no-link\">#{$order->getIncrementId()}</span>"
)
);
$this->assertEquals($message->getSubject(), $subject);
$this->assertThat($message->getBody()->getParts()[0]->getRawContent(), $assert);
}
/**
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Sales/_files/guest_quote_with_addresses.php
*
* @return void
*/
public function testNotSendEmailOnOrderSave(): void
{
$this->prepareRequest();
$this->dispatch('backend/sales/order_create/save');
$this->assertSessionMessages(
$this->equalTo([(string)__('You created the order.')]),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains('sales/order/view/'));
$orderId = $this->getOrderId();
if ($orderId === false) {
$this->fail('Order is not created.');
}
$this->assertNull($this->transportBuilder->getSentMessage());
}
/**
* Gets quote by reserved order id.
*
* @param string $reservedOrderId
* @return \Magento\Quote\Api\Data\CartInterface
*/
private function getQuote(string $reservedOrderId): \Magento\Quote\Api\Data\CartInterface
{
/** @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);
}
/**
* @inheritdoc
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Sales/_files/guest_quote_with_addresses.php
*/
public function testAclHasAccess()
{
$this->prepareRequest();
parent::testAclHasAccess();
}
/**
* @inheritdoc
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Sales/_files/guest_quote_with_addresses.php
*/
public function testAclNoAccess()
{
$this->prepareRequest();
parent::testAclNoAccess();
}
/**
* @param int $orderId
* @return OrderInterface
*/
private function getOrder(int $orderId): OrderInterface
{
return $this->_objectManager->get(OrderRepository::class)->get($orderId);
}
/**
* @param array $params
* @return void
*/
private function prepareRequest(array $params = []): void
{
$quote = $this->getQuote('guest_quote');
$session = $this->_objectManager->get(Quote::class);
$session->setQuoteId($quote->getId());
$session->setCustomerId(0);
$email = 'john.doe001@test.com';
$data = [
'account' => [
'email' => $email,
],
];
$data = array_replace_recursive($data, $params);
$this->getRequest()
->setMethod('POST')
->setParams(['form_key' => $this->formKey->getFormKey()])
->setPostValue(['order' => $data]);
}
/**
* @return string|bool
*/
protected function getOrderId()
{
$currentUrl = $this->getResponse()->getHeader('Location');
$orderId = false;
if (preg_match('/order_id\/(?<order_id>\d+)/', $currentUrl, $matches)) {
$orderId = $matches['order_id'] ?? '';
}
return $orderId;
}
}
@@ -0,0 +1,448 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Controller\Adminhtml\Order;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Backend\Model\Session\Quote as SessionQuote;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Config\MutableScopeConfigInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Quote\Model\Quote;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Api\Data\WebsiteInterface;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\Store\Model\ScopeInterface;
/**
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class CreateTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @var \Magento\Catalog\Api\ProductRepositoryInterface
*/
protected $productRepository;
/**
* @inheritDoc
*
* @throws \Magento\Framework\Exception\AuthenticationException
*/
protected function setUp(): void
{
parent::setUp();
$this->productRepository = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
}
/**
* Test LoadBlock being dispatched.
*/
public function testLoadBlockAction()
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParam('block', ',');
$this->getRequest()->setParam('json', 1);
$this->dispatch('backend/sales/order_create/loadBlock');
$this->assertStringContainsString('"message":""}', $this->getResponse()->getBody());
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testLoadBlockActionData()
{
$product = $this->productRepository->get('simple');
$this->_objectManager->get(
\Magento\Sales\Model\AdminOrder\Create::class
)->addProducts(
[$product->getId() => ['qty' => 1]]
);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParam('block', 'data');
$this->getRequest()->setParam('json', 1);
$this->dispatch('backend/sales/order_create/loadBlock');
$html = $this->getResponse()->getBody();
$this->assertStringContainsString('<div id=\"sales_order_create_search_grid\"', $html);
$this->assertStringContainsString('<div id=\"order-billing_method_form\"', $html);
$this->assertStringContainsString('id=\"shipping-method-overlay\"', $html);
$this->assertStringContainsString('id=\"coupons:code\"', $html);
}
/**
* Tests that shipping method 'Table rates' shows rates according to selected website.
*
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Quote/Fixtures/quote_sec_website.php
* @magentoDataFixture Magento/OfflineShipping/_files/tablerates_second_website.php
* @magentoDbIsolation disabled
*/
public function testLoadBlockShippingMethod()
{
$store = $this->getStore('fixture_second_store');
/** @var MutableScopeConfigInterface $mutableScopeConfig */
$mutableScopeConfig = $this->_objectManager->get(MutableScopeConfigInterface::class);
$mutableScopeConfig->setValue(
'carriers/tablerate/active',
1,
ScopeInterface::SCOPE_STORE,
$store->getCode()
);
$mutableScopeConfig->setValue(
'carriers/tablerate/condition_name',
'package_qty',
ScopeInterface::SCOPE_STORE,
$store->getCode()
);
$website = $this->getWebsite('test');
$customer = $this->getCustomer('customer.web@example.com', (int)$website->getId());
$quote = $this->getQuoteById('0000032134');
$session = $this->_objectManager->get(SessionQuote::class);
$session->setQuoteId($quote->getId());
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
[
'customer_id' => $customer->getId(),
'collect_shipping_rates' => 1,
'store_id' => $store->getId(),
'json' => true
]
);
$this->dispatch('backend/sales/order_create/loadBlock/block/shipping_method');
$body = $this->getResponse()->getBody();
$expectedTableRatePrice = '<span class=\"price\">$20.00<\/span>';
$this->assertStringContainsString($expectedTableRatePrice, $body, '');
}
/**
* Tests LoadBlock actions.
*
* @param string $block Block name.
* @param string $expected Contains HTML.
*
* @dataProvider loadBlockActionsDataProvider
*/
public function testLoadBlockActions($block, $expected)
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParam('block', $block);
$this->getRequest()->setParam('json', 1);
$this->dispatch('backend/sales/order_create/loadBlock');
$html = $this->getResponse()->getBody();
$this->assertStringContainsString($expected, $html);
}
/**
* @return array
*/
public function loadBlockActionsDataProvider()
{
return [
'shipping_method' => ['shipping_method', 'id=\"shipping-method-overlay\"'],
'billing_method' => ['billing_method', '<div id=\"order-billing_method_form\">'],
'newsletter' => ['newsletter', 'name=\"newsletter:subscribe\"'],
'search' => ['search', '<div id=\"sales_order_create_search_grid\"'],
'search_grid' => ['search', '<div id=\"sales_order_create_search_grid\"']
];
}
/**
* Tests action items.
*
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testLoadBlockActionItems()
{
$product = $this->productRepository->get('simple');
$this->_objectManager->get(
\Magento\Sales\Model\AdminOrder\Create::class
)->addProducts(
[$product->getId() => ['qty' => 1]]
);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setParam('block', 'items');
$this->getRequest()->setParam('json', 1);
$this->dispatch('backend/sales/order_create/loadBlock');
$html = $this->getResponse()->getBody();
$this->assertStringContainsString('id=\"coupons:code\"', $html);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoAppArea adminhtml
*/
public function testIndexAction()
{
$product = $this->productRepository->get('simple');
/** @var $order \Magento\Sales\Model\AdminOrder\Create */
$order = $this->_objectManager->get(\Magento\Sales\Model\AdminOrder\Create::class);
$order->addProducts([$product->getId() => ['qty' => 1]]);
$this->dispatch('backend/sales/order_create/index');
$html = $this->getResponse()->getBody();
$this->assertGreaterThanOrEqual(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//div[@id="order-customer-selector"]',
$html
)
);
$this->assertGreaterThanOrEqual(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@data-grid-id="sales_order_create_customer_grid"]',
$html
)
);
$this->assertGreaterThanOrEqual(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//div[@id="order-billing_method_form"]',
$html
)
);
$this->assertGreaterThanOrEqual(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@id="shipping-method-overlay"]',
$html
)
);
$this->assertGreaterThanOrEqual(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//div[@id="sales_order_create_search_grid"]',
$html
)
);
$this->assertGreaterThanOrEqual(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath('//*[@id="coupons:code"]', $html)
);
}
/**
* Tests ACL.
*
* @param string $actionName
* @param boolean $reordered
* @param string $expectedResult
*
* @dataProvider getAclResourceDataProvider
* @magentoAppIsolation enabled
*/
public function testGetAclResource($actionName, $reordered, $expectedResult)
{
$this->_objectManager->get(SessionQuote::class)->setReordered($reordered);
$orderController = $this->_objectManager->get(
\Magento\Sales\Controller\Adminhtml\Order\Stub\OrderCreateStub::class
);
$this->getRequest()->setActionName($actionName);
$method = new \ReflectionMethod(\Magento\Sales\Controller\Adminhtml\Order\Create::class, '_getAclResource');
$method->setAccessible(true);
$result = $method->invoke($orderController);
$this->assertEquals($result, $expectedResult);
}
/**
* @return array
*/
public function getAclResourceDataProvider()
{
return [
['index', false, 'Magento_Sales::create'],
['index', true, 'Magento_Sales::reorder'],
['save', false, 'Magento_Sales::create'],
['save', true, 'Magento_Sales::reorder'],
['reorder', false, 'Magento_Sales::reorder'],
['reorder', true, 'Magento_Sales::reorder'],
['cancel', false, 'Magento_Sales::cancel'],
['cancel', true, 'Magento_Sales::reorder'],
['', false, 'Magento_Sales::actions'],
['', true, 'Magento_Sales::actions']
];
}
/**
* @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php
* @magentoAppArea adminhtml
*/
public function testConfigureProductToAddAction()
{
$product = $this->productRepository->get('configurable');
$this->getRequest()->setParam('id', $product->getEntityId())
->setParam('isAjax', true);
$this->dispatch('backend/sales/order_create/configureProductToAdd');
$body = $this->getResponse()->getBody();
$this->assertNotEmpty($body);
$this->assertStringContainsString('><span>Quantity</span></label>', $body);
$this->assertStringContainsString('>Test Configurable</label>', $body);
$this->assertStringContainsString('"code":"test_configurable","label":"Test Configurable"', $body);
$this->assertStringContainsString(sprintf('"productId":"%s"', $product->getEntityId()), $body);
}
/**
* Test not allowing to save.
*
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function testDeniedSaveAction()
{
$this->_objectManager->configure(
[\Magento\Backend\App\Action\Context::class => [
'arguments' => [
'authorization' => [
'instance' => \Magento\Sales\Controller\Adminhtml\Order\AuthorizationMock::class,
],
],
],
]
);
\Magento\TestFramework\Helper\Bootstrap::getInstance()
->loadArea('adminhtml');
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/sales/order_create/save');
$this->assertEquals('403', $this->getResponse()->getHttpResponseCode());
}
/**
* Checks a case when shipping is the same as billing and billing address details was changed by request.
* Both billing and shipping addresses should be updated.
*
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Sales/_files/quote_with_customer.php
*/
public function testSyncBetweenQuoteAddresses()
{
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = $this->_objectManager->get(CustomerRepositoryInterface::class);
$customer = $customerRepository->get('customer@example.com');
/** @var CartRepositoryInterface $quoteRepository */
$quoteRepository = $this->_objectManager->get(CartRepositoryInterface::class);
$quote = $quoteRepository->getActiveForCustomer($customer->getId());
$session = $this->_objectManager->get(SessionQuote::class);
$session->setQuoteId($quote->getId());
$data = [
'firstname' => 'John',
'lastname' => 'Doe',
'street' => ['Soborna 23'],
'city' => 'Kyiv',
'country_id' => 'UA',
'region' => 'Kyivska',
'region_id' => 1
];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
[
'order' => ['billing_address' => $data],
'reset_shipping' => 1,
'customer_id' => $customer->getId(),
'store_id' => 1,
'json' => true
]
);
$this->dispatch('backend/sales/order_create/loadBlock/block/shipping_address');
self::assertEquals(200, $this->getResponse()->getHttpResponseCode());
$updatedQuote = $quoteRepository->get($quote->getId());
$billingAddress = $updatedQuote->getBillingAddress();
self::assertEquals($data['region_id'], $billingAddress->getRegionId());
self::assertEquals($data['country_id'], $billingAddress->getCountryId());
$shippingAddress = $updatedQuote->getShippingAddress();
self::assertEquals($data['city'], $shippingAddress->getCity());
self::assertEquals($data['street'], $shippingAddress->getStreet());
}
/**
* Gets quote entity by reserved order id.
*
* @param string $reservedOrderId
* @return Quote
*/
private function getQuoteById(string $reservedOrderId): Quote
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->_objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', $reservedOrderId)
->create();
/** @var CartRepositoryInterface $repository */
$repository = $this->_objectManager->get(CartRepositoryInterface::class);
$items = $repository->getList($searchCriteria)
->getItems();
return array_pop($items);
}
/**
* Gets website entity.
*
* @param string $code
* @return WebsiteInterface
* @throws NoSuchEntityException
*/
private function getWebsite(string $code): WebsiteInterface
{
/** @var WebsiteRepositoryInterface $repository */
$repository = $this->_objectManager->get(WebsiteRepositoryInterface::class);
return $repository->get($code);
}
/**
* Gets customer entity.
*
* @param string $email
* @param int $websiteId
* @return CustomerInterface
* @throws NoSuchEntityException
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function getCustomer(string $email, int $websiteId): CustomerInterface
{
/** @var CustomerRepositoryInterface $repository */
$repository = $this->_objectManager->get(CustomerRepositoryInterface::class);
return $repository->get($email, $websiteId);
}
/**
* Gets store by code.
*
* @param string $code
* @return StoreInterface
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
private function getStore(string $code): StoreInterface
{
/** @var StoreRepositoryInterface $repository */
$repository = $this->_objectManager->get(StoreRepositoryInterface::class);
return $repository->get($code);
}
}
@@ -0,0 +1,92 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Creditmemo;
use Magento\Framework\Api\SearchCriteria;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Data\Form\FormKey;
use Magento\Sales\Api\Data\CreditmemoInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Model\OrderRepository;
use Magento\TestFramework\Mail\Template\TransportBuilderMock;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Abstract backend creditmemo test.
*/
class AbstractCreditmemoControllerTest extends AbstractBackendController
{
/**
* @var TransportBuilderMock
*/
protected $transportBuilder;
/**
* @var OrderRepository
*/
protected $orderRepository;
/**
* @var FormKey
*/
protected $formKey;
/**
* @var string
*/
protected $resource = 'Magento_Sales::sales_creditmemo';
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->transportBuilder = $this->_objectManager->get(TransportBuilderMock::class);
$this->orderRepository = $this->_objectManager->get(OrderRepository::class);
$this->formKey = $this->_objectManager->get(FormKey::class);
}
/**
* @param string $incrementalId
* @return OrderInterface|null
*/
protected function getOrder(string $incrementalId)
{
/** @var SearchCriteria $searchCriteria */
$searchCriteria = $this->_objectManager->create(SearchCriteriaBuilder::class)
->addFilter(OrderInterface::INCREMENT_ID, $incrementalId)
->create();
$orders = $this->orderRepository->getList($searchCriteria)->getItems();
/** @var OrderInterface|null $order */
$order = reset($orders);
return $order;
}
/**
* @param OrderInterface $order
* @return CreditmemoInterface
*/
protected function getCreditMemo(OrderInterface $order): CreditmemoInterface
{
/** @var \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Collection $creditMemoCollection */
$creditMemoCollection = $this->_objectManager->create(
\Magento\Sales\Model\ResourceModel\Order\Creditmemo\CollectionFactory::class
)->create();
/** @var CreditmemoInterface $creditMemo */
$creditMemo = $creditMemoCollection
->setOrderFilter($order)
->setPageSize(1)
->getFirstItem();
return $creditMemo;
}
}
@@ -0,0 +1,102 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Creditmemo;
use PHPUnit\Framework\Constraint\RegularExpression;
use PHPUnit\Framework\Constraint\StringContains;
/**
* Class verifies creditmemo add comment functionality.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Sales/_files/creditmemo_for_get.php
*/
class AddCommentTest extends AbstractCreditmemoControllerTest
{
/**
* @var string
*/
protected $uri = 'backend/sales/order_creditmemo/addComment';
/**
* @return void
*/
public function testSendEmailOnAddCreditmemoComment(): void
{
$comment = 'Test Credit Memo Comment';
$order = $this->prepareRequest(
[
'comment' => ['comment' => $comment, 'is_customer_notified' => true],
]
);
$this->dispatch('backend/sales/order_creditmemo/addComment');
$html = $this->getResponse()->getBody();
$this->assertStringContainsString($comment, $html);
$message = $this->transportBuilder->getSentMessage();
$subject =__('Update to your %1 credit memo', $order->getStore()->getFrontendName())->render();
$messageConstraint = $this->logicalAnd(
new StringContains($order->getCustomerName()),
new RegularExpression(
sprintf(
"/Your order #%s has been updated with a status of.*%s/",
$order->getIncrementId(),
$order->getFrontendStatusLabel()
)
),
new StringContains($comment)
);
$this->assertEquals($message->getSubject(), $subject);
$this->assertThat($message->getBody()->getParts()[0]->getRawContent(), $messageConstraint);
}
/**
* @inheritdoc
*/
public function testAclHasAccess()
{
$this->prepareRequest(['comment' => ['comment' => 'Comment']]);
parent::testAclHasAccess();
}
/**
* @inheritdoc
*/
public function testAclNoAccess()
{
$this->prepareRequest(['comment' => ['comment' => 'Comment']]);
parent::testAclNoAccess();
}
/**
* @param array $params
* @return \Magento\Sales\Api\Data\OrderInterface|null
*/
private function prepareRequest(array $params = [])
{
$order = $this->getOrder('100000001');
$creditmemo = $this->getCreditMemo($order);
$this->getRequest()->setMethod('POST');
$this->getRequest()->setParams(
[
'id' => $creditmemo->getEntityId(),
'form_key' => $this->formKey->getFormKey(),
]
);
$data = $params ?? [];
$this->getRequest()->setPostValue($data);
return $order;
}
}
@@ -0,0 +1,114 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Creditmemo;
use Magento\Sales\Api\Data\CreditmemoInterface;
use Magento\Sales\Model\ResourceModel\Order\Creditmemo\CollectionFactory;
use Magento\Sales\Controller\Adminhtml\Order\ExportBase;
/**
* Tests for creditmemo export via admin grids.
*/
class ExportTest extends ExportBase
{
/**
* @var CollectionFactory
*/
private $creditmemoCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->creditmemoCollectionFactory = $this->_objectManager->get(CollectionFactory::class);
}
/**
* @magentoDbIsolation disabled
* @magentoAppArea adminhtml
* @magentoConfigFixture general/locale/timezone America/Chicago
* @magentoConfigFixture test_website general/locale/timezone America/Adak
* @magentoDataFixture Magento/Sales/_files/order_with_invoice_shipment_creditmemo_on_second_website.php
* @dataProvider exportCreditmemoDataProvider
* @param string $format
* @param bool $addIdToUrl
* @param string $namespace
* @return void
*/
public function testExportCreditmemo(
string $format,
bool $addIdToUrl,
string $namespace
): void {
$order = $this->getOrder('200000001');
$url = $this->getExportUrl($format, $addIdToUrl ? (int)$order->getId() : null);
$response = $this->dispatchExport(
$url,
['namespace' => $namespace, 'filters' => ['order_increment_id' => '200000001']]
);
$creditmemos = $this->parseResponse($format, $response);
$creditmemo = $this->getCreditmemo('200000001');
$exportedCreditmemo = reset($creditmemos);
$this->assertNotFalse($exportedCreditmemo);
$this->assertEquals(
$this->prepareDate($creditmemo->getCreatedAt(), 'America/Chicago'),
$exportedCreditmemo['Created']
);
$this->assertEquals(
$this->prepareDate($order->getCreatedAt(), 'America/Chicago'),
$exportedCreditmemo['Order Date']
);
}
/**
* @return array
*/
public function exportCreditmemoDataProvider(): array
{
return [
'creditmemo_grid_in_csv' => [
'format' => ExportBase::CSV_FORMAT,
'add_id_to_url' => false,
'namespace' => 'sales_order_creditmemo_grid',
],
'creditmemo_grid_in_csv_from_order_view' => [
'format' => ExportBase::CSV_FORMAT,
'add_id_to_url' => true,
'namespace' => 'sales_order_view_creditmemo_grid',
],
'creditmemo_grid_in_xml' => [
'format' => ExportBase::XML_FORMAT,
'add_id_to_url' => false,
'namespace' => 'sales_order_creditmemo_grid',
],
'creditmemo_grid_in_xml_from_order_view' => [
'format' => ExportBase::XML_FORMAT,
'add_id_to_url' => true,
'namespace' => 'sales_order_view_creditmemo_grid',
],
];
}
/**
* Returns creditmemo by increment id.
*
* @param string $incrementId
* @return CreditmemoInterface
*/
private function getCreditmemo(string $incrementId): CreditmemoInterface
{
/** @var CreditmemoInterface $creditmemo */
$creditmemo = $this->creditmemoCollectionFactory->create()
->addAttributeToFilter(CreditmemoInterface::INCREMENT_ID, $incrementId)
->getFirstItem();
return $creditmemo;
}
}
@@ -0,0 +1,189 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Creditmemo;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Sales\Api\Data\OrderItemInterface;
use Magento\Sales\Model\Order;
use PHPUnit\Framework\Constraint\StringContains;
/**
* Provide tests for CreditMemo save controller.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Sales/_files/invoice.php
*/
class SaveTest extends AbstractCreditmemoControllerTest
{
/**
* @var string
*/
protected $uri = 'backend/sales/order_creditmemo/save';
/**
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Sales/_files/invoice.php
* @return void
*/
public function testSendEmailOnCreditmemoSave(): void
{
$order = $this->prepareRequest(['creditmemo' => ['send_email' => true]]);
$this->dispatch($this->uri);
$this->assertSessionMessages(
$this->equalTo([(string)__('You created the credit memo.')]),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains('sales/order/view/order_id/' . $order->getEntityId()));
$creditMemo = $this->getCreditMemo($order);
$message = $this->transportBuilder->getSentMessage();
$subject = __('Credit memo for your %1 order', $order->getStore()->getFrontendName())->render();
$messageConstraint = $this->logicalAnd(
new StringContains($order->getBillingAddress()->getName()),
new StringContains(
'Thank you for your order from ' . $creditMemo->getStore()->getFrontendName()
),
new StringContains(
"Your Credit Memo #{$creditMemo->getIncrementId()} for Order #{$order->getIncrementId()}"
)
);
$this->assertEquals($message->getSubject(), $subject);
$this->assertThat($message->getBody()->getParts()[0]->getRawContent(), $messageConstraint);
}
/**
* Test order will keep same(custom) status after partial refund, if state has not been changed.
*
* @magentoDataFixture Magento/Sales/_files/order_with_invoice_and_custom_status.php
*/
public function testOrderStatusPartialRefund()
{
/** @var Order $existingOrder */
$existingOrder = $this->_objectManager->create(Order::class)->loadByIncrementId('100000001');
$items = $this->getOrderItems($existingOrder, 1);
$postParams = [
'creditmemo' => [
'items' => $items,
'do_offline' => '1',
'comment_text' => '',
'shipping_amount' => '0',
'adjustment_positive' => '0',
'adjustment_negative' => '0',
],
'order_id' => $existingOrder->getId(),
];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST)
->setPostValue($postParams);
$this->dispatch($this->uri);
/** @var Order $updatedOrder */
$updatedOrder = $this->_objectManager->create(Order::class)
->loadByIncrementId($existingOrder->getIncrementId());
$this->assertSame('custom_processing', $updatedOrder->getStatus());
$this->assertSame('processing', $updatedOrder->getState());
}
/**
* Test order will change custom status after total refund, when state has been changed.
*
* @magentoDataFixture Magento/Sales/_files/order_with_invoice_and_custom_status.php
*/
public function testOrderStatusTotalRefund()
{
/** @var Order $existingOrder */
$existingOrder = $this->_objectManager->create(Order::class)->loadByIncrementId('100000001');
$postParams = [
'creditmemo' => [
'items' => $this->getOrderItems($existingOrder),
'do_offline' => '1',
'comment_text' => '',
'shipping_amount' => '0',
'adjustment_positive' => '0',
'adjustment_negative' => '0',
],
'order_id' => $existingOrder->getId(),
];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST)
->setPostValue($postParams);
$this->dispatch($this->uri);
/** @var Order $updatedOrder */
$updatedOrder = $this->_objectManager->create(Order::class)
->loadByIncrementId($existingOrder->getIncrementId());
$this->assertSame('complete', $updatedOrder->getStatus());
$this->assertSame('complete', $updatedOrder->getState());
}
/**
* Gets all items of given Order in proper format.
*
* @param Order $order
* @param int $subQty
* @return array
*/
private function getOrderItems(Order $order, int $subQty = 0)
{
$items = [];
/** @var OrderItemInterface $item */
foreach ($order->getAllItems() as $item) {
$items[$item->getItemId()] = [
'qty' => $item->getQtyOrdered() - $subQty,
];
}
return $items;
}
/**
* @inheritdoc
*/
public function testAclHasAccess()
{
$this->prepareRequest();
parent::testAclHasAccess();
}
/**
* @inheritdoc
*/
public function testAclNoAccess()
{
$this->prepareRequest();
parent::testAclNoAccess();
}
/**
* @param array $params
* @return \Magento\Sales\Api\Data\OrderInterface|null
*/
private function prepareRequest(array $params = [])
{
$order = $this->getOrder('100000001');
$this->getRequest()->setMethod('POST');
$this->getRequest()->setParams(
[
'order_id' => $order->getEntityId(),
'form_key' => $this->formKey->getFormKey(),
]
);
$data = ['creditmemo' => ['do_offline' => true]];
$data = array_replace_recursive($data, $params);
$this->getRequest()->setPostValue($data);
return $order;
}
}
@@ -0,0 +1,45 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Controller\Adminhtml\Order;
/**
* @magentoAppArea adminhtml
*/
class CreditmemoTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @magentoConfigFixture current_store cataloginventory/item_options/auto_return 1
* @magentoDataFixture Magento/Sales/_files/order_info.php
*/
public function testAddCommentAction()
{
$this->markTestSkipped('https://github.com/magento-engcom/msi/issues/393');
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\CatalogInventory\Api\StockIndexInterface $stockIndex */
$stockIndex = $objectManager->get(\Magento\CatalogInventory\Api\StockIndexInterface::class);
$stockIndex->rebuild(1, 1);
/** @var \Magento\CatalogInventory\Api\StockStateInterface $stockState */
$stockState = $objectManager->create(\Magento\CatalogInventory\Api\StockStateInterface::class);
$this->assertEquals(95, $stockState->getStockQty(1, 1));
/** @var \Magento\Sales\Model\Order $order */
$order = $objectManager->create(\Magento\Sales\Model\Order::class);
$order->load('100000001', 'increment_id');
$items = $order->getCreditmemosCollection()->getItems();
$creditmemo = array_shift($items);
$comment = 'Test Comment 02';
$this->getRequest()->setParam('creditmemo_id', $creditmemo->getId());
$this->getRequest()->setPostValue('comment', ['comment' => $comment]);
$this->dispatch('backend/sales/order_creditmemo/addComment/id/' . $creditmemo->getId());
$html = $this->getResponse()->getBody();
$this->assertContains($comment, $html);
/** @var \Magento\CatalogInventory\Api\StockStateInterface $stockState */
$stockState = $objectManager->create(\Magento\CatalogInventory\Api\StockStateInterface::class);
$this->assertEquals(95, $stockState->getStockQty(1, 1));
}
}
@@ -0,0 +1,136 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order;
use Magento\Framework\Api\SearchCriteria;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Model\OrderRepository;
use Magento\TestFramework\Mail\Template\TransportBuilderMock;
use PHPUnit\Framework\Constraint\StringContains;
/**
* Class verifies order send email functionality.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Sales/_files/order.php
*/
class EmailTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @var OrderRepository
*/
private $orderRepository;
/**
* @var TransportBuilderMock
*/
private $transportBuilder;
/**
* @var string
*/
protected $resource = 'Magento_Sales::email';
/**
* @var string
*/
protected $uri = 'backend/sales/order/email';
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->orderRepository = $this->_objectManager->get(OrderRepository::class);
$this->transportBuilder = $this->_objectManager->get(TransportBuilderMock::class);
}
/**
* @return void
*/
public function testSendOrderEmail(): void
{
$order = $this->prepareRequest();
$this->dispatch('backend/sales/order/email');
$this->assertSessionMessages(
$this->equalTo([(string)__('You sent the order email.')]),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$redirectUrl = 'sales/order/view/order_id/' . $order->getEntityId();
$this->assertRedirect($this->stringContains($redirectUrl));
$message = $this->transportBuilder->getSentMessage();
$subject = __('Your %1 order confirmation', $order->getStore()->getFrontendName())->render();
$assert = $this->logicalAnd(
new StringContains($order->getBillingAddress()->getName()),
new StringContains(
'Thank you for your order from ' . $order->getStore()->getFrontendName()
),
new StringContains(
"Your Order <span class=\"no-link\">#{$order->getIncrementId()}</span>"
)
);
$this->assertEquals($message->getSubject(), $subject);
$this->assertThat($message->getBody()->getParts()[0]->getRawContent(), $assert);
}
/**
* @inheritdoc
*/
public function testAclHasAccess()
{
$this->prepareRequest();
parent::testAclHasAccess();
}
/**
* @inheritdoc
*/
public function testAclNoAccess()
{
$this->prepareRequest();
parent::testAclNoAccess();
}
/**
* @param string $incrementalId
* @return OrderInterface|null
*/
private function getOrder(string $incrementalId)
{
/** @var SearchCriteria $searchCriteria */
$searchCriteria = $this->_objectManager->create(SearchCriteriaBuilder::class)
->addFilter(OrderInterface::INCREMENT_ID, $incrementalId)
->create();
$orders = $this->orderRepository->getList($searchCriteria)->getItems();
/** @var OrderInterface|null $order */
$order = reset($orders);
return $order;
}
/**
* @return OrderInterface|null
*/
private function prepareRequest()
{
$order = $this->getOrder('100000001');
$this->getRequest()->setParams(['order_id' => $order->getEntityId()]);
return $order;
}
}
@@ -0,0 +1,162 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order;
use Magento\Framework\App\Request\Http;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Tests for order/invoice/shipment/credit memo export via admin grids.
*
* @magentoDbIsolation disabled
*/
class ExportBase extends AbstractBackendController
{
const CSV_FORMAT = 'csv';
const XML_FORMAT = 'xml';
/**
* @var OrderInterfaceFactory
*/
private $orderFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->orderFactory = $this->_objectManager->get(OrderInterfaceFactory::class);
}
/**
* Dispatches export request.
*
* @param string $url
* @param array $params
* @return string
*/
protected function dispatchExport(string $url, array $params): string
{
$this->_auth->getAuthStorage()->setIsFirstPageAfterLogin(false);
$this->getRequest()->setParams($params);
$this->getRequest()->setMethod(Http::METHOD_POST);
ob_start();
$this->dispatch($url);
return ob_get_clean();
}
/**
* Parses string response depends of format.
*
* @param string $format
* @param string $response
* @return array
*/
protected function parseResponse(string $format, string $response): array
{
$result = [];
if ($format === ExportBase::CSV_FORMAT) {
$result = $this->parseCsvResponse($response);
} elseif ($format === ExportBase::XML_FORMAT) {
$result = $this->parseXmlResponse($response);
}
return $result;
}
/**
* Converts string in scv format to assoc array.
*
* @param string $data
* @return array
*/
protected function parseCsvResponse(string $data): array
{
$result = [];
$data = str_getcsv($data, PHP_EOL);
$headers = str_getcsv(array_shift($data), ',', '"');
foreach ($data as $row) {
$result[] = array_combine($headers, str_getcsv($row, ',', '"'));
}
return $result;
}
/**
* Converts string in xml format to assoc array.
*
* @param string $data
* @return array
*/
protected function parseXmlResponse(string $data): array
{
$xml = simplexml_load_string($data);
$xmlAsArray = [];
foreach ($xml->Worksheet->Table->Row as $item) {
$row = [];
foreach ($item->Cell as $cell) {
$data = (array)$cell->Data;
$row[] = reset($data);
}
$xmlAsArray[] = $row;
}
$result = [];
$headers = array_shift($xmlAsArray);
foreach ($xmlAsArray as $row) {
$result[] = array_combine($headers, $row);
}
return $result;
}
/**
* Returns order purchase date in timezone.
*
* @param string $date
* @param string $timezone
* @return string
*/
protected function prepareDate(string $date, string $timezone): string
{
$date = new \DateTime($date, new \DateTimeZone('UTC'));
$date->setTimezone(new \DateTimeZone($timezone));
return $date->format('M j, Y h:i:s A');
}
/**
* Returns order by increment id.
*
* @param string $incrementId
* @return OrderInterface
*/
protected function getOrder(string $incrementId): OrderInterface
{
return $this->orderFactory->create()->loadByIncrementId($incrementId);
}
/**
* Returns export url.
*
* @param string $format
* @param int|null $orderId
* @return string
*/
protected function getExportUrl(string $format, ?int $orderId = null): string
{
$url = $format === self::CSV_FORMAT
? 'backend/mui/export/gridToCsv/'
: 'backend/mui/export/gridToXml/';
return $orderId ? $url . 'order_id/' . $orderId : $url;
}
}
@@ -0,0 +1,52 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order;
/**
* Tests for order export via admin grid.
*/
class ExportTest extends ExportBase
{
/**
* @magentoDbIsolation disabled
* @magentoAppArea adminhtml
* @magentoConfigFixture general/locale/timezone America/Chicago
* @magentoConfigFixture test_website general/locale/timezone America/Adak
* @magentoDataFixture Magento/Sales/_files/order_with_invoice_shipment_creditmemo_on_second_website.php
* @dataProvider exportOrderDataProvider
* @param string $format
* @return void
*/
public function testExportOrder(string $format): void
{
$order = $this->getOrder('200000001');
$url = $this->getExportUrl($format, null);
$response = $this->dispatchExport(
$url,
['namespace' => 'sales_order_grid', 'filters' => ['increment_id' => '200000001']]
);
$orders = $this->parseResponse($format, $response);
$exportedOrder = reset($orders);
$this->assertNotFalse($exportedOrder);
$this->assertEquals(
$this->prepareDate($order->getCreatedAt(), 'America/Chicago'),
$exportedOrder['Purchase Date']
);
}
/**
* @return array
*/
public function exportOrderDataProvider(): array
{
return [
'order_grid_in_csv' => ['format' => ExportBase::CSV_FORMAT],
'order_grid_in_xml' => ['format' => ExportBase::XML_FORMAT],
];
}
}
@@ -0,0 +1,118 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Invoice;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Request\Http;
use Magento\Sales\Api\Data\InvoiceInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Model\OrderRepository;
use Magento\Sales\Model\ResourceModel\Order\Invoice\CollectionFactory;
use Magento\TestFramework\Mail\Template\TransportBuilderMock;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Abstract backend invoice test.
*/
abstract class AbstractInvoiceControllerTest extends AbstractBackendController
{
/** @var TransportBuilderMock */
protected $transportBuilder;
/** @var string */
protected $resource = 'Magento_Sales::sales_invoice';
/** @var OrderRepository */
private $orderRepository;
/** @var SearchCriteriaBuilder */
private $searchCriteriaBuilder;
/** @var CollectionFactory */
private $invoiceCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->transportBuilder = $this->_objectManager->get(TransportBuilderMock::class);
$this->orderRepository = $this->_objectManager->get(OrderRepository::class);
$this->searchCriteriaBuilder = $this->_objectManager->get(SearchCriteriaBuilder::class);
$this->invoiceCollectionFactory = $this->_objectManager->get(CollectionFactory::class);
}
/**
* Retrieve order
*
* @param string $incrementalId
* @return OrderInterface|null
*/
protected function getOrder(string $incrementalId): ?OrderInterface
{
$searchCriteria = $this->searchCriteriaBuilder->addFilter(OrderInterface::INCREMENT_ID, $incrementalId)
->create();
$orders = $this->orderRepository->getList($searchCriteria)->getItems();
return reset($orders);
}
/**
* Get firs order invoice
*
* @param OrderInterface|int $order
* @return InvoiceInterface
*/
protected function getInvoiceByOrder($order): InvoiceInterface
{
$invoiceCollection = $this->invoiceCollectionFactory->create();
return $invoiceCollection->setOrderFilter($order)->setPageSize(1)->getFirstItem();
}
/**
* Prepare request
*
* @param array $postParams
* @param array $params
* @return void
*/
protected function prepareRequest(array $postParams = [], array $params = []): void
{
$this->getRequest()->setMethod(Http::METHOD_POST);
$this->getRequest()->setParams($params);
$this->getRequest()->setPostValue($postParams);
}
/**
* Normalize post parameters
*
* @param array $items
* @param string $commentText
* @param bool $doShipment
* @param bool $sendEmail
* @return array
*/
protected function hydratePost(
array $items,
string $commentText = '',
$doShipment = false,
$sendEmail = false
): array {
return [
'invoice' => [
'items' => $items,
'comment_text' => $commentText,
'do_shipment' => $doShipment,
'send_email' => $sendEmail
],
];
}
}
@@ -0,0 +1,83 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Invoice;
use PHPUnit\Framework\Constraint\RegularExpression;
use PHPUnit\Framework\Constraint\StringContains;
/**
* Class verifies invoice add comment functionality.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Sales/_files/invoice.php
*/
class AddCommentTest extends AbstractInvoiceControllerTest
{
/**
* @var string
*/
protected $uri = 'backend/sales/order_invoice/addComment';
/**
* @return void
*/
public function testSendEmailOnAddInvoiceComment(): void
{
$comment = 'Test Invoice Comment';
$order = $this->getOrder('100000001');
$invoice = $this->getInvoiceByOrder($order);
$this->prepareRequest(
['comment' => ['comment' => $comment, 'is_customer_notified' => true]],
['id' => $invoice->getEntityId()]
);
$this->dispatch('backend/sales/order_invoice/addComment');
$html = $this->getResponse()->getBody();
$this->assertStringContainsString($comment, $html);
$message = $this->transportBuilder->getSentMessage();
$this->assertNotNull($message);
$subject = __('Update to your %1 invoice', $order->getStore()->getFrontendName())->render();
$messageConstraint = $this->logicalAnd(
new StringContains($order->getCustomerName()),
new RegularExpression(
sprintf(
"/Your order #%s has been updated with a status of.*%s/",
$order->getIncrementId(),
$order->getFrontendStatusLabel()
)
),
new StringContains($comment)
);
$this->assertEquals($message->getSubject(), $subject);
$bodyParts = $message->getBody()->getParts();
$this->assertThat(reset($bodyParts)->getRawContent(), $messageConstraint);
}
/**
* @inheritdoc
*/
public function testAclHasAccess()
{
$this->prepareRequest();
parent::testAclHasAccess();
}
/**
* @inheritdoc
*/
public function testAclNoAccess()
{
$this->prepareRequest();
parent::testAclNoAccess();
}
}
@@ -0,0 +1,88 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Invoice;
use PHPUnit\Framework\Constraint\StringContains;
/**
* Class verifies invoice send email functionality.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Sales/_files/invoice.php
*/
class EmailTest extends AbstractInvoiceControllerTest
{
/**
* @var string
*/
protected $uri = 'backend/sales/order_invoice/email';
/**
* @return void
*/
public function testSendInvoiceEmail(): void
{
$order = $this->getOrder('100000001');
$invoice = $this->getInvoiceByOrder($order);
$this->getRequest()->setParams(['invoice_id' => $invoice->getEntityId()]);
$this->dispatch('backend/sales/order_invoice/email');
$this->assertSessionMessages(
$this->equalTo([(string)__('You sent the message.')]),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$redirectUrl = sprintf(
'sales/invoice/view/order_id/%s/invoice_id/%s',
$order->getEntityId(),
$invoice->getEntityId()
);
$this->assertRedirect($this->stringContains($redirectUrl));
$message = $this->transportBuilder->getSentMessage();
$subject = __('Invoice for your %1 order', $order->getStore()->getFrontendName())->render();
$messageConstraint = $this->logicalAnd(
new StringContains($invoice->getBillingAddress()->getName()),
new StringContains(
'Thank you for your order from ' . $invoice->getStore()->getFrontendName()
),
new StringContains(
"Your Invoice #{$invoice->getIncrementId()} for Order #{$order->getIncrementId()}"
)
);
$this->assertEquals($message->getSubject(), $subject);
$this->assertThat($message->getBody()->getParts()[0]->getRawContent(), $messageConstraint);
}
/**
* @inheritdoc
*/
public function testAclHasAccess()
{
$order = $this->getOrder('100000001');
$invoice = $this->getInvoiceByOrder($order);
$this->uri .= '/invoice_id/' . $invoice->getEntityId();
parent::testAclHasAccess();
}
/**
* @inheritdoc
*/
public function testAclNoAccess()
{
$order = $this->getOrder('100000001');
$invoice = $this->getInvoiceByOrder($order);
$this->uri .= '/invoice_id/' . $invoice->getEntityId();
parent::testAclNoAccess();
}
}
@@ -0,0 +1,109 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Invoice;
use Magento\Sales\Api\Data\InvoiceInterface;
use Magento\Sales\Api\Data\InvoiceInterfaceFactory;
use Magento\Sales\Controller\Adminhtml\Order\ExportBase;
/**
* Tests for invoice export via admin grids.
*/
class ExportTest extends ExportBase
{
/**
* @var InvoiceInterfaceFactory
*/
private $invoiceFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->invoiceFactory = $this->_objectManager->get(InvoiceInterfaceFactory::class);
}
/**
* @magentoDbIsolation disabled
* @magentoAppArea adminhtml
* @magentoConfigFixture general/locale/timezone America/Chicago
* @magentoConfigFixture test_website general/locale/timezone America/Adak
* @magentoDataFixture Magento/Sales/_files/order_with_invoice_shipment_creditmemo_on_second_website.php
* @dataProvider exportInvoiceDataProvider
* @param string $format
* @param bool $addIdToUrl
* @param string $namespace
* @return void
*/
public function testExportInvoice(
string $format,
bool $addIdToUrl,
string $namespace
): void {
$order = $this->getOrder('200000001');
$url = $this->getExportUrl($format, $addIdToUrl ? (int)$order->getId() : null);
$response = $this->dispatchExport(
$url,
['namespace' => $namespace, 'filters' => ['order_increment_id' => '200000001']]
);
$invoices = $this->parseResponse($format, $response);
$invoice = $this->getInvoice('200000001');
$exportedInvoice = reset($invoices);
$this->assertNotFalse($exportedInvoice);
$this->assertEquals(
$this->prepareDate($invoice->getCreatedAt(), 'America/Chicago'),
$exportedInvoice['Invoice Date']
);
$this->assertEquals(
$this->prepareDate($order->getCreatedAt(), 'America/Chicago'),
$exportedInvoice['Order Date']
);
}
/**
* @return array
*/
public function exportInvoiceDataProvider(): array
{
return [
'invoice_grid_in_csv' => [
'format' => ExportBase::CSV_FORMAT,
'add_id_to_url' => false,
'namespace' => 'sales_order_invoice_grid',
],
'invoice_grid_in_csv_from_order_view' => [
'format' => ExportBase::CSV_FORMAT,
'add_id_to_url' => true,
'namespace' => 'sales_order_view_invoice_grid',
],
'invoice_grid_in_xml' => [
'format' => ExportBase::XML_FORMAT,
'add_id_to_url' => false,
'namespace' => 'sales_order_invoice_grid',
],
'invoice_grid_in_xml_from_order_view' => [
'format' => ExportBase::XML_FORMAT,
'add_id_to_url' => true,
'namespace' => 'sales_order_view_invoice_grid',
],
];
}
/**
* Returns invoice by increment id.
*
* @param string $incrementId
* @return InvoiceInterface
*/
private function getInvoice(string $incrementId): InvoiceInterface
{
return $this->invoiceFactory->create()->loadByIncrementId($incrementId);
}
}
@@ -0,0 +1,78 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Invoice;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Escaper;
use Magento\Framework\Message\MessageInterface;
use Magento\Sales\Model\OrderFactory;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Test for new invoice action
*
* @see \Magento\Sales\Controller\Adminhtml\Order\Invoice\NewAction
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class NewActionTest extends AbstractBackendController
{
/** @var OrderFactory */
private $orderFactory;
/** @var Escaper */
private $escaper;
/**
* @inheridoc
*/
protected function setUp(): void
{
parent::setUp();
$this->orderFactory = $this->_objectManager->get(OrderFactory::class);
$this->escaper = $this->_objectManager->get(Escaper::class);
}
/**
* @return void
*/
public function testWithNoExistingOrder(): void
{
$this->dispatchWithOrderId(863521);
$expectedMessage = (string)__("The entity that was requested doesn't exist. Verify the entity and try again.");
$this->assertSessionMessages($this->containsEqual($this->escaper->escapeHtml($expectedMessage)));
}
/**
* @magentoDataFixture Magento/Sales/_files/order_with_bundle_and_invoiced.php
*
* @return void
*/
public function testCanNotInvoice(): void
{
$expectedMessage = __('The order does not allow an invoice to be created.');
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->dispatchWithOrderId((int)$order->getEntityId());
$this->assertSessionMessages($this->containsEqual((string)$expectedMessage), MessageInterface::TYPE_ERROR);
}
/**
* Dispatch request with order_id param
*
* @param int $orderId
* @return void
*/
private function dispatchWithOrderId(int $orderId): void
{
$this->getRequest()->setMethod(Http::METHOD_GET)
->setParams(['order_id' => $orderId]);
$this->dispatch('backend/sales/order_invoice/new');
}
}
@@ -0,0 +1,351 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Invoice;
use Magento\Framework\Escaper;
use Magento\Sales\Api\Data\InvoiceInterface;
use Magento\Sales\Api\Data\OrderItemInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\ResourceModel\Order\Item;
use PHPUnit\Framework\Constraint\StringContains;
/**
* Class tests invoice creation in admin panel.
*
* @see \Magento\Sales\Controller\Adminhtml\Order\Invoice\Save
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
*/
class SaveTest extends AbstractInvoiceControllerTest
{
/** @var string */
protected $uri = 'backend/sales/order_invoice/save';
/** @var Escaper */
private $escaper;
/** @var Item */
private $orderItemResource;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->escaper = $this->_objectManager->get(Escaper::class);
$this->orderItemResource = $this->_objectManager->get(Item::class);
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testSendEmailOnInvoiceSave(): void
{
$order = $this->getOrder('100000001');
$itemId = $order->getItemsCollection()->getFirstItem()->getId();
$post = $this->hydratePost([$itemId => 2]);
$this->prepareRequest($post, ['order_id' => $order->getEntityId()]);
$this->dispatch('backend/sales/order_invoice/save');
$invoice = $this->getInvoiceByOrder($order);
$this->checkSuccess($invoice, 2);
$this->assertNull($this->transportBuilder->getSentMessage());
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testSendEmailOnInvoiceSaveEmailCopyOfInvoice(): void
{
$order = $this->getOrder('100000001');
$itemId = $order->getItemsCollection()->getFirstItem()->getId();
$post = $this->hydratePost([$itemId => 2], "", false, "1");
$this->prepareRequest(
$post,
['order_id' => $order->getEntityId()]
);
$this->dispatch('backend/sales/order_invoice/save');
$invoice = $this->getInvoiceByOrder($order);
$this->checkSuccess($invoice, 2);
$message = $this->transportBuilder->getSentMessage();
$this->assertNotNull($message);
$subject = __('Invoice for your %1 order', $order->getStore()->getFrontendName())->render();
$messageConstraint = $this->logicalAnd(
new StringContains($invoice->getBillingAddress()->getName()),
new StringContains(
'Thank you for your order from ' . $invoice->getStore()->getFrontendName()
),
new StringContains(
"Your Invoice #{$invoice->getIncrementId()} for Order #{$order->getIncrementId()}"
)
);
$this->assertEquals($message->getSubject(), $subject);
$bodyParts = $message->getBody()->getParts();
$this->assertThat(reset($bodyParts)->getRawContent(), $messageConstraint);
}
/**
* @magentoConfigFixture current_store sales_email/invoice/enabled 0
*
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testSendEmailOnInvoiceSaveWithDisabledConfig(): void
{
$order = $this->getOrder('100000001');
$post = $this->hydratePost([$order->getItemsCollection()->getFirstItem()->getId() => 2]);
$this->prepareRequest($post, ['order_id' => $order->getEntityId()]);
$this->dispatch('backend/sales/order_invoice/save');
$this->checkSuccess($this->getInvoiceByOrder($order), 2);
$this->assertNull($this->transportBuilder->getSentMessage());
}
/**
* @dataProvider invoiceDataProvider
*
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @param int $invoicedItemsQty
* @param string $commentMessage
* @param bool $doShipment
* @return void
*/
public function testSuccessfulInvoice(
int $invoicedItemsQty,
string $commentMessage = '',
bool $doShipment = false
): void {
$order = $this->getOrder('100000001');
$post = $this->hydratePost(
[$order->getItemsCollection()->getFirstItem()->getId() => $invoicedItemsQty],
$commentMessage,
$doShipment
);
$this->prepareRequest($post, ['order_id' => $order->getEntityId()]);
$this->dispatch('backend/sales/order_invoice/save');
$this->checkSuccess($this->getInvoiceByOrder($order), $invoicedItemsQty, $commentMessage, $doShipment);
}
/**
* @return array
*/
public function invoiceDataProvider(): array
{
return [
'with_comment_message' => [
'invoiced_items_qty' => 2,
'comment_message' => 'test comment message',
],
'partial_invoice' => [
'invoiced_items_qty' => 1,
],
'with_do_shipment' => [
'invoiced_items_qty' => 2,
'comment_message' => '',
'do_shipment' => true,
],
];
}
/**
* @return void
*/
public function testWitNoExistingOrder(): void
{
$expectedMessage = (string)__('The order no longer exists.');
$this->prepareRequest(['order_id' => 899989]);
$this->dispatch('backend/sales/order_invoice/save');
$this->assertErrorResponse($expectedMessage);
}
/**
* @magentoDataFixture Magento/Sales/_files/order_with_bundle_and_invoiced.php
*
* @return void
*/
public function testCanNotInvoiceOrder(): void
{
$expectedMessage = (string)__('The order does not allow an invoice to be created.');
$order = $this->getOrder('100000001');
$this->prepareRequest([], ['order_id' => $order->getEntityId()]);
$this->dispatch('backend/sales/order_invoice/save');
$this->assertErrorResponse($expectedMessage);
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testInvoiceWithoutQty(): void
{
$expectedMessage = (string)__('The invoice can\'t be created without products. Add products and try again.');
$order = $this->getOrder('100000001');
$post = $this->hydratePost([$order->getItemsCollection()->getFirstItem()->getId() => '0']);
$this->prepareRequest($post, ['order_id' => $order->getEntityId()]);
$this->dispatch('backend/sales/order_invoice/save');
$this->assertErrorResponse($this->escaper->escapeHtml($expectedMessage));
}
/**
* @magentoDataFixture Magento/Sales/_files/order_configurable_product.php
*
* @return void
*/
public function testPartialInvoiceWitConfigurableProduct(): void
{
$order = $this->getOrder('100000001');
$post = $this->hydratePost([$order->getItemsCollection()->getFirstItem()->getId() => '1']);
$this->prepareRequest($post, ['order_id' => $order->getEntityId()]);
$this->dispatch($this->uri);
$this->assertSessionMessages($this->containsEqual((string)__('The invoice has been created.')));
$orderItems = $this->getOrderItemsQtyInvoiced((int)$order->getEntityId());
$this->assertCount(2, $orderItems);
$this->assertEquals(1, (int)$orderItems[0]);
$this->assertEquals($orderItems[0], $orderItems[1]);
}
/**
* @magentoDataFixture Magento/Sales/_files/order_with_bundle_dynamic_price_no.php
*
* @return void
*/
public function testOrderItemsQtyInvoicedForBundleDynamicPriceFalse(): void
{
$order = $this->getOrder('100000001');
$entityId = $order->getEntityId();
$this->prepareRequest([], ['order_id' => $entityId]);
$this->dispatch('backend/sales/order_invoice/save');
$ordered = $this->getOrderItemsQtyOrdered((int)$entityId);
$invoiced = $this->getOrderItemsQtyInvoiced((int)$entityId);
$this->assertEquals($ordered, $invoiced);
}
/**
* @inheritdoc
*/
public function testAclHasAccess()
{
$this->prepareRequest();
parent::testAclHasAccess();
}
/**
* @inheritdoc
*/
public function testAclNoAccess()
{
$this->prepareRequest();
parent::testAclNoAccess();
}
/**
* Checks that order protect code is not changing after invoice submitting
*
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testOrderProtectCodePreserveAfterInvoiceSave(): void
{
$order = $this->getOrder('100000001');
$this->prepareRequest([], ['order_id' => $order->getEntityId()]);
$protectCode = $order->getProtectCode();
$this->dispatch($this->uri);
$invoicedOrder = $this->getOrder('100000001');
$this->assertEquals($protectCode, $invoicedOrder->getProtectCode());
}
/**
* Check error response
*
* @param string $expectedMessage
* @return void
*/
private function assertErrorResponse(string $expectedMessage): void
{
$this->assertRedirect($this->stringContains('sales/order_invoice/new'));
$this->assertSessionMessages($this->containsEqual($expectedMessage));
}
/**
* Check that invoice was successfully created
*
* @param InvoiceInterface $invoice
* @param int $invoicedItemsQty
* @param string|null $commentMessage
* @param bool $doShipment
* @return void
*/
private function checkSuccess(
InvoiceInterface $invoice,
int $invoicedItemsQty,
?string $commentMessage = null,
bool $doShipment = false
): void {
$message = $doShipment ? 'You created the invoice and shipment.' : 'The invoice has been created.';
$expectedState = $doShipment ? Order::STATE_COMPLETE : Order::STATE_PROCESSING;
$this->assertNotNull($invoice->getEntityId());
$this->assertEquals($invoicedItemsQty, (int)$invoice->getTotalQty());
$order = $invoice->getOrder();
$this->assertEquals($expectedState, $order->getState());
if ($commentMessage) {
$this->assertEquals($commentMessage, $invoice->getCustomerNote());
}
$this->assertRedirect(
$this->stringContains(sprintf('sales/order/view/order_id/%u', (int)$order->getEntityId()))
);
$this->assertSessionMessages($this->containsEqual((string)__($message)));
}
/**
* Get order items qty invoiced
*
* @param int $orderId
* @return array
*/
private function getOrderItemsQtyInvoiced(int $orderId): array
{
$connection = $this->orderItemResource->getConnection();
$select = $connection->select()
->from($this->orderItemResource->getMainTable(), OrderItemInterface::QTY_INVOICED)
->where(OrderItemInterface::ORDER_ID . ' = ?', $orderId);
return $connection->fetchCol($select);
}
/**
* Get order items qty ordered
*
* @param int $orderId
* @return array
*/
private function getOrderItemsQtyOrdered(int $orderId): array
{
$connection = $this->orderItemResource->getConnection();
$select = $connection->select()
->from($this->orderItemResource->getMainTable(), OrderItemInterface::QTY_ORDERED)
->where(OrderItemInterface::ORDER_ID . ' = ?', $orderId);
return $connection->fetchCol($select);
}
}
@@ -0,0 +1,66 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Invoice;
use Magento\Backend\Model\Session;
use Magento\Framework\App\Request\Http;
use Magento\Sales\Model\OrderFactory;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Test for invoice start action
*
* @see \Magento\Sales\Controller\Adminhtml\Order\Invoice\Start
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class StartTest extends AbstractBackendController
{
/** @var OrderFactory */
private $orderFactory;
/** @var Session */
private $session;
/**
* @inheridoc
*/
protected function setUp(): void
{
parent::setUp();
$this->orderFactory = $this->_objectManager->get(OrderFactory::class);
$this->session = $this->_objectManager->get(Session::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->session->getInvoiceItemQtys(true);
parent::tearDown();
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testExecute(): void
{
$order = $this->orderFactory->create()->loadByIncrementId('100000001');
$this->session->setInvoiceItemQtys('test');
$this->getRequest()->setMethod(Http::METHOD_GET)->setParams(['order_id' => $order->getEntityId()]);
$this->dispatch('backend/sales/order_invoice/start');
$this->assertRedirect($this->stringContains('sales/order_invoice/new'));
$this->assertNull($this->session->getInvoiceItemQtys());
}
}
@@ -0,0 +1,123 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Invoice;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\TestFramework\Helper\Xpath;
/**
* Class tests invoice items qty update.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
*/
class UpdateQtyTest extends AbstractInvoiceControllerTest
{
/** @var SerializerInterface */
private $json;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->json = $this->_objectManager->get(SerializerInterface::class);
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testSuccess(): void
{
$order = $this->getOrder('100000001');
$itemId = $order->getItemsCollection()->getFirstItem()->getId();
$qtyToInvoice = 1;
$invoicedItemsXpath = sprintf(
"//input[contains(@class, 'qty-input') and @name='invoice[items][%u]' and @value='%u']",
$itemId,
$qtyToInvoice
);
$post = $this->hydratePost([$itemId => $qtyToInvoice]);
$this->prepareRequest($post, ['order_id' => $order->getEntityId()]);
$this->dispatch('backend/sales/order_invoice/updateQty');
$this->assertEquals(
1,
Xpath::getElementsCountForXpath($invoicedItemsXpath, $this->getResponse()->getContent())
);
}
/**
* @magentoDataFixture Magento/Sales/_files/order_with_bundle_and_invoiced.php
*
* @return void
*/
public function testCanNotInvoice(): void
{
$order = $this->getOrder('100000001');
$itemId = $order->getItemsCollection()->getFirstItem()->getId();
$post = $this->hydratePost([$itemId => '1']);
$this->prepareRequest($post, ['order_id' => $order->getEntityId()]);
$this->dispatch('backend/sales/order_invoice/updateQty');
$this->assertErrorResponse('The order does not allow an invoice to be created.');
}
/**
* @magentoDataFixture Magento/Sales/_files/order.php
*
* @return void
*/
public function testWithoutQty(): void
{
$order = $this->getOrder('100000001');
$itemId = $order->getItemsCollection()->getFirstItem()->getId();
$post = $this->hydratePost([$itemId => '0']);
$this->prepareRequest($post, ['order_id' => $order->getEntityId()]);
$this->dispatch('backend/sales/order_invoice/updateQty');
$this->assertErrorResponse(
'The invoice can\'t be created without products. Add products and try again.'
);
}
/**
* @return void
*/
public function testWithNoExistingOrderId(): void
{
$post = $this->hydratePost([
'invoice' => [
'items' => [
'1' => '3',
],
],
]);
$this->prepareRequest($post, ['order_id' => 6543265]);
$this->dispatch('backend/sales/order_invoice/updateQty');
$this->assertErrorResponse('The order no longer exists.');
}
/**
* Check error response
*
* @param string $expectedMessage
* @return void
*/
private function assertErrorResponse(string $expectedMessage): void
{
$expectedResponse = [
'error' => true,
'message' => (string)__($expectedMessage),
];
$response = $this->getResponse()->getContent();
$this->assertNotEmpty($response);
$this->assertEquals($expectedResponse, $this->json->unserialize($response));
}
}
@@ -0,0 +1,109 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Sales\Controller\Adminhtml\Order\Shipment;
use Magento\Sales\Api\Data\ShipmentInterface;
use Magento\Sales\Api\Data\ShipmentInterfaceFactory;
use Magento\Sales\Controller\Adminhtml\Order\ExportBase;
/**
* Tests for shipment export via admin grids.
*/
class ExportTest extends ExportBase
{
/**
* @var ShipmentInterfaceFactory
*/
private $shipmentFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->shipmentFactory = $this->_objectManager->get(ShipmentInterfaceFactory::class);
}
/**
* @magentoDbIsolation disabled
* @magentoAppArea adminhtml
* @magentoConfigFixture general/locale/timezone America/Chicago
* @magentoConfigFixture test_website general/locale/timezone America/Adak
* @magentoDataFixture Magento/Sales/_files/order_with_invoice_shipment_creditmemo_on_second_website.php
* @dataProvider exportShipmentDataProvider
* @param string $format
* @param bool $addIdToUrl
* @param string $namespace
* @return void
*/
public function testExportShipment(
string $format,
bool $addIdToUrl,
string $namespace
): void {
$order = $this->getOrder('200000001');
$url = $this->getExportUrl($format, $addIdToUrl ? (int)$order->getId() : null);
$response = $this->dispatchExport(
$url,
['namespace' => $namespace, 'filters' => ['order_increment_id' => '200000001']]
);
$shipments = $this->parseResponse($format, $response);
$shipment = $this->getShipment('200000001');
$exportedShipment = reset($shipments);
$this->assertNotFalse($exportedShipment);
$this->assertEquals(
$this->prepareDate($shipment->getCreatedAt(), 'America/Chicago'),
$exportedShipment['Ship Date']
);
$this->assertEquals(
$this->prepareDate($order->getCreatedAt(), 'America/Chicago'),
$exportedShipment['Order Date']
);
}
/**
* @return array
*/
public function exportShipmentDataProvider(): array
{
return [
'shipment_grid_in_csv' => [
'format' => ExportBase::CSV_FORMAT,
'add_id_to_url' => false,
'namespace' => 'sales_order_shipment_grid',
],
'shipment_grid_in_csv_from_order_view' => [
'format' => ExportBase::CSV_FORMAT,
'add_id_to_url' => true,
'namespace' => 'sales_order_view_shipment_grid',
],
'shipment_grid_in_xml' => [
'format' => ExportBase::XML_FORMAT,
'add_id_to_url' => false,
'namespace' => 'sales_order_shipment_grid',
],
'shipment_grid_in_xml_from_order_view' => [
'format' => ExportBase::XML_FORMAT,
'add_id_to_url' => true,
'namespace' => 'sales_order_view_shipment_grid',
],
];
}
/**
* Returns shipment by increment id.
*
* @param string $incrementId
* @return ShipmentInterface
*/
private function getShipment(string $incrementId): ShipmentInterface
{
return $this->shipmentFactory->create()->loadByIncrementId($incrementId);
}
}
@@ -0,0 +1,15 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Controller\Adminhtml\Order\Stub;
class OrderCreateStub extends \Magento\Sales\Controller\Adminhtml\Order\Create
{
public function execute()
{
// Empty method stub for test
}
}