This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,649 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Exception\AuthenticationException;
use Magento\GraphQl\GetCustomerAuthenticationHeader;
use Magento\GraphQl\Sales\Fixtures\CustomerPlaceOrder;
use Magento\Sales\Api\CreditmemoRepositoryInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\CreditmemoFactory;
use Magento\Sales\Model\ResourceModel\Order\Collection as OrderCollection;
use Magento\Sales\Model\ResourceModel\Order\Creditmemo\Collection;
use Magento\Sales\Model\Service\CreditmemoService;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test for credit memo functionality
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CreditmemoTest extends GraphQlAbstract
{
/**
* @var GetCustomerAuthenticationHeader
*/
private $customerAuthenticationHeader;
/** @var CreditmemoFactory */
private $creditMemoFactory;
/** @var Order */
private $order;
/** @var OrderCollection */
private $orderCollection;
/** @var CreditmemoService */
private $creditMemoService;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var OrderRepositoryInterface */
private $orderRepository;
/** @var SearchCriteriaBuilder */
private $searchCriteriaBuilder;
/**
* Set up
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->customerAuthenticationHeader = $objectManager->get(
GetCustomerAuthenticationHeader::class
);
$this->productRepository = $objectManager->get(ProductRepositoryInterface::class);
$this->creditMemoFactory = $objectManager->get(CreditmemoFactory::class);
$this->order = $objectManager->create(Order::class);
$this->searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);
$this->orderCollection = $objectManager->get(OrderCollection::class);
$this->orderRepository = $objectManager->get(OrderRepositoryInterface::class);
$this->creditMemoService = $objectManager->get(CreditmemoService::class);
}
protected function tearDown(): void
{
$this->cleanUpCreditMemos();
$this->deleteOrder();
}
/**
* @magentoApiDataFixture Magento/Sales/_files/customer_creditmemo_with_two_items.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreditMemoForLoggedInCustomerQuery(): void
{
$response = $this->getCustomerOrderWithCreditMemoQuery();
$expectedCreditMemoData = [
[
'comments' => [
['message' => 'some_comment']
],
'items' => [
[
'product_name' => 'Simple Related Product',
'product_sku' => 'simple',
'product_sale_price' => [
'value' => 10
],
'discounts' => [],
'quantity_refunded' => 1
],
[
'product_name' => 'Simple Product With Related Product',
'product_sku' => 'simple_with_cross',
'product_sale_price' => [
'value' => 10
],
'discounts' => [],
'quantity_refunded' => 1
]
],
'total' => [
'subtotal' => [
'value' => 20
],
'grand_total' => [
'value' => 20,
'currency' => 'USD'
],
'base_grand_total' => [
'value' => 10,
'currency' => 'EUR'
],
'total_shipping' => [
'value' => 0
],
'total_tax' => [
'value' => 0
],
'shipping_handling' => [
'amount_including_tax' => [
'value' => 0
],
'amount_excluding_tax' => [
'value' => 0
],
'total_amount' => [
'value' => 0
],
'taxes' => [],
'discounts' => [],
],
'adjustment' => [
'value' => 1.23
]
]
]
];
$firstOrderItem = current($response['customer']['orders']['items'] ?? []);
$this->assertArrayHasKey('credit_memos', $firstOrderItem);
$creditMemos = $firstOrderItem['credit_memos'];
$this->assertResponseFields($creditMemos, $expectedCreditMemoData);
}
/**
* Test customer refund details from order for bundle product with a partial refund
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Bundle/_files/bundle_product_two_dropdown_options.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreditMemoForBundledProductsWithPartialRefund()
{
//Place order with bundled product
/** @var CustomerPlaceOrder $bundleProductOrderFixture */
$bundleProductOrderFixture = Bootstrap::getObjectManager()->create(CustomerPlaceOrder::class);
$placeOrderResponse = $bundleProductOrderFixture->placeOrderWithBundleProduct(
['email' => 'customer@example.com', 'password' => 'password'],
['sku' => 'bundle-product-two-dropdown-options', 'quantity' => 2]
);
$orderNumber = $placeOrderResponse['placeOrder']['order']['order_number'];
$this->prepareInvoice($orderNumber, 2);
$order = $this->order->loadByIncrementId($orderNumber);
/** @var Order\Item $orderItem */
$orderItem = current($order->getAllItems());
$orderItem->setQtyRefunded(1);
$order->addItem($orderItem);
$order->save();
// Create a credit memo
$creditMemo = $this->creditMemoFactory->createByOrder($order, $order->getData());
$creditMemo->setOrder($order);
$creditMemo->setState(1);
$creditMemo->setSubtotal(15);
$creditMemo->setBaseSubTotal(15);
$creditMemo->setShippingAmount(10);
$creditMemo->setBaseGrandTotal(23);
$creditMemo->setGrandTotal(23);
$creditMemo->setAdjustment(-2.00);
$creditMemo->addComment("Test comment for partial refund", false, true);
$creditMemo->save();
$this->creditMemoService->refund($creditMemo, true);
$response = $this->getCustomerOrderWithCreditMemoQuery();
$expectedInvoicesData = [
[
'items' => [
[
'product_name' => 'Bundle Product With Two dropdown options',
'product_sku' => 'bundle-product-two-dropdown-options-simple1-simple2',
'product_sale_price' => [
'value' => 15
],
'discounts' => [],
'bundle_options' => [
[
'label' => 'Drop Down Option 1',
'values' => [
[
'product_name' => 'Simple Product1',
'product_sku' => 'simple1',
'quantity' => 1,
'price' => ['value' => 1, 'currency' => 'USD']
]
]
],
[
'label' => 'Drop Down Option 2',
'values' => [
[
'product_name' => 'Simple Product2',
'product_sku' => 'simple2',
'quantity' => 2,
'price' => ['value' => 2, 'currency' => 'USD']
]
]
]
],
'quantity_invoiced' => 2
],
]
]
];
$expectedCreditMemoData = [
[
'comments' => [
['message' => 'Test comment for partial refund']
],
'items' => [
[
'product_name' => 'Bundle Product With Two dropdown options',
'product_sku' => 'bundle-product-two-dropdown-options-simple1-simple2',
'product_sale_price' => [
'value' => 15
],
'discounts' => [],
'bundle_options' => [
[
'label' => 'Drop Down Option 1',
'values' => [
[
'product_name' => 'Simple Product1',
'product_sku' => 'simple1',
'quantity' => 1,
'price' => ['value' => 1, 'currency' => 'USD']
]
]
],
[
'label' => 'Drop Down Option 2',
'values' => [
[
'product_name' => 'Simple Product2',
'product_sku' => 'simple2',
'quantity' => 2,
'price' => ['value' => 2, 'currency' => 'USD']
]
]
]
],
'quantity_refunded' => 1
],
],
'total' => [
'subtotal' => [
'value' => 15
],
'grand_total' => [
'value' => 23,
'currency' => 'USD'
],
'base_grand_total' => [
'value' => 23,
'currency' => 'USD'
],
'total_shipping' => [
'value' => 10
],
'total_tax' => [
'value' => 0
],
'shipping_handling' => [
'amount_including_tax' => [
'value' => 10
],
'amount_excluding_tax' => [
'value' => 10
],
'total_amount' => [
'value' => 10
],
'taxes' => [],
'discounts' => [],
],
'adjustment' => [
'value' => 2
]
]
]
];
$firstOrderItem = current($response['customer']['orders']['items'] ?? []);
$this->assertArrayHasKey('invoices', $firstOrderItem);
$invoices = $firstOrderItem['invoices'];
$this->assertResponseFields($invoices, $expectedInvoicesData);
$this->assertArrayHasKey('credit_memos', $firstOrderItem);
$creditMemos = $firstOrderItem['credit_memos'];
$this->assertResponseFields($creditMemos, $expectedCreditMemoData);
}
/**
* Test customer order with credit memo details for bundle products with taxes and discounts
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Bundle/_files/bundle_product_two_dropdown_options.php
* @magentoApiDataFixture Magento/GraphQl/Tax/_files/tax_rule_for_region_1.php
* @magentoApiDataFixture Magento/SalesRule/_files/cart_rule_10_percent_off_with_discount_on_shipping.php
* @magentoApiDataFixture Magento/GraphQl/Tax/_files/tax_calculation_shipping_excludeTax_order_display_settings.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testCreditMemoForBundleProductWithTaxesAndDiscounts()
{
//Place order with bundled product
/** @var CustomerPlaceOrder $bundleProductOrderFixture */
$bundleProductOrderFixture = Bootstrap::getObjectManager()->create(CustomerPlaceOrder::class);
$placeOrderResponse = $bundleProductOrderFixture->placeOrderWithBundleProduct(
['email' => 'customer@example.com', 'password' => 'password'],
['sku' => 'bundle-product-two-dropdown-options', 'quantity' => 2]
);
$orderNumber = $placeOrderResponse['placeOrder']['order']['order_number'];
$this->prepareInvoice($orderNumber, 2);
$order = $this->order->loadByIncrementId($orderNumber);
/** @var Order\Item $orderItem */
$orderItem = current($order->getAllItems());
$orderItem->setQtyRefunded(1);
$order->addItem($orderItem);
$order->save();
$creditMemo = $this->creditMemoFactory->createByOrder($order, $order->getData());
$creditMemo->setOrder($order);
$creditMemo->setState(1);
$creditMemo->setSubtotal(15);
$creditMemo->setBaseSubTotal(15);
$creditMemo->setShippingAmount(10);
$creditMemo->setTaxAmount(1.69);
$creditMemo->setBaseGrandTotal(24.19);
$creditMemo->setGrandTotal(24.19);
$creditMemo->setAdjustment(0.00);
$creditMemo->setDiscountAmount(-2.5);
$creditMemo->setDiscountDescription('Discount Label for 10% off');
$creditMemo->addComment("Test comment for refund with taxes and discount", false, true);
$creditMemo->save();
$this->creditMemoService->refund($creditMemo, true);
$response = $this->getCustomerOrderWithCreditMemoQuery();
$expectedCreditMemoData = [
[
'comments' => [
['message' => 'Test comment for refund with taxes and discount']
],
'items' => [
[
'product_name' => 'Bundle Product With Two dropdown options',
'product_sku' => 'bundle-product-two-dropdown-options-simple1-simple2',
'product_sale_price' => [
'value' => 15
],
'discounts' => [
[
'amount' => [
'value' => 3,
'currency' => "USD"
],
'label' => 'Discount Label for 10% off'
]
],
'bundle_options' => [
[
'label' => 'Drop Down Option 1',
'values' => [
[
'product_name' => 'Simple Product1',
'product_sku' => 'simple1',
'quantity' => 1,
'price' => ['value' => 1, 'currency' => 'USD']
]
]
],
[
'label' => 'Drop Down Option 2',
'values' => [
[
'product_name' => 'Simple Product2',
'product_sku' => 'simple2',
'quantity' => 2,
'price' => ['value' => 2, 'currency' => 'USD']
]
]
]
],
'quantity_refunded' => 1
],
],
'total' => [
'subtotal' => [
'value' => 15
],
'grand_total' => [
'value' => 24.19,
'currency' => 'USD'
],
'base_grand_total' => [
'value' => 24.19,
'currency' => 'USD'
],
'total_shipping' => [
'value' => 10
],
'total_tax' => [
'value'=> 1.69
],
'shipping_handling' => [
'amount_including_tax' => [
'value' => 10.75
],
'amount_excluding_tax' => [
'value' => 10
],
'total_amount' => [
'value' => 10
],
'taxes'=> [
0 => [
'amount' => ['value' => 0.67],
'title' => 'US-TEST-*-Rate-1',
'rate' => 7.5
]
],
'discounts' => [
[
'amount'=> ['value'=> 1]
]
],
],
'adjustment' => [
'value' => 0
]
]
]
];
$firstOrderItem = current($response['customer']['orders']['items'] ?? []);
$this->assertArrayHasKey('credit_memos', $firstOrderItem);
$creditMemos = $firstOrderItem['credit_memos'];
$this->assertResponseFields($creditMemos, $expectedCreditMemoData);
}
/**
* Prepare invoice for the order
*
* @param string $orderNumber
* @param int|null $qty
*/
private function prepareInvoice(string $orderNumber, int $qty = null)
{
/** @var \Magento\Sales\Model\Order $order */
$order = Bootstrap::getObjectManager()
->create(\Magento\Sales\Model\Order::class)->loadByIncrementId($orderNumber);
$orderItem = current($order->getItems());
$orderService = Bootstrap::getObjectManager()->create(
\Magento\Sales\Api\InvoiceManagementInterface::class
);
$invoice = $orderService->prepareInvoice($order, [$orderItem->getId() => $qty]);
$invoice->register();
$order = $invoice->getOrder();
$order->setIsInProcess(true);
$transactionSave = Bootstrap::getObjectManager()
->create(\Magento\Framework\DB\Transaction::class);
$transactionSave->addObject($invoice)->addObject($order)->save();
}
/**
* @return void
*/
private function deleteOrder(): void
{
/** @var \Magento\Framework\Registry $registry */
$registry = Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var $order \Magento\Sales\Model\Order */
$orderCollection = Bootstrap::getObjectManager()->create(OrderCollection::class);
foreach ($orderCollection as $order) {
$this->orderRepository->delete($order);
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
}
/**
* @return void
*/
private function cleanUpCreditMemos(): void
{
/** @var \Magento\Framework\Registry $registry */
$registry = Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$creditmemoRepository = Bootstrap::getObjectManager()->get(CreditmemoRepositoryInterface::class);
$creditmemoCollection = Bootstrap::getObjectManager()->create(Collection::class);
foreach ($creditmemoCollection as $creditmemo) {
$creditmemoRepository->delete($creditmemo);
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
}
/**
* Get CustomerOrder with credit memo details
*
* @return array
* @throws AuthenticationException
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
private function getCustomerOrderWithCreditMemoQuery(): array
{
$query =
<<<QUERY
query {
customer {
orders {
items {
invoices {
items {
product_name
product_sku
product_sale_price {
value
}
... on BundleInvoiceItem {
bundle_options {
label
values {
product_sku
product_name
quantity
price {
value
currency
}
}
}
}
discounts { amount{value currency} label }
quantity_invoiced
discounts { amount{value currency} label }
}
}
credit_memos {
comments {
message
}
items {
product_name
product_sku
product_sale_price {
value
}
... on BundleCreditMemoItem {
bundle_options {
label
values {
product_sku
product_name
quantity
price {
value
currency
}
}
}
}
discounts { amount{value currency} label }
quantity_refunded
}
total {
subtotal {
value
}
base_grand_total {
value
currency
}
grand_total {
value
currency
}
total_shipping {
value
}
total_tax {
value
}
shipping_handling {
amount_including_tax{value}
amount_excluding_tax{value}
total_amount{value}
taxes {amount{value} title rate}
discounts {amount{value}}
}
adjustment {
value
}
}
}
}
}
}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$response = $this->graphQlQuery(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
return $response;
}
}
@@ -0,0 +1,126 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales\CustomerOrders;
use Exception;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class OrdersTest
*/
class CustomerOrdersTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Sales/_files/orders_with_customer.php
*/
public function testOrdersQuery()
{
$query =
<<<QUERY
query {
customer {
orders(filter: {}) {
items {
number
status
created_at
}
}
}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$response = $this->graphQlQuery($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
$expectedData = [
[
'number' => '100000002',
'status' => 'Processing',
'created_at' => "2022-09-04 00:00:00"
],
[
'number' => '100000004',
'status' => 'Closed',
'created_at' => "2022-09-05 00:00:00"
],
[
'number' => '100000005',
'status' => 'Complete',
'created_at' => "2022-09-08 00:00:00"
],
[
'number' => '100000006',
'status' => 'Complete',
'created_at' => "2022-09-09 00:00:00"
]
];
$actualData = $response['customer']['orders']['items'];
foreach ($expectedData as $key => $data) {
$this->assertEquals(
$data['number'],
$actualData[$key]['number'],
"order_number is different than the expected for order - " . $data['number']
);
$this->assertEquals(
$data['created_at'],
$actualData[$key]['created_at'],
"created_at is different than the expected for order - " . $data['created_at']
);
}
}
/**
*/
public function testCustomerOrdersQueryNotAuthorized()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$query = <<<QUERY
{
customerOrders {
items {
increment_id
grand_total
}
}
}
QUERY;
$this->graphQlQuery($query);
}
/**
* @param string $email
* @param string $password
* @return array
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
}
@@ -0,0 +1,375 @@
<?php
/**
* Copyright 2020 Adobe
* All rights reserved.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales\CustomerOrders;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\Checkout\Test\Fixture\PlaceOrder as PlaceOrderFixture;
use Magento\Checkout\Test\Fixture\SetBillingAddress;
use Magento\Checkout\Test\Fixture\SetDeliveryMethod as SetDeliveryMethodFixture;
use Magento\Checkout\Test\Fixture\SetPaymentMethod as SetPaymentMethodFixture;
use Magento\Checkout\Test\Fixture\SetShippingAddress;
use Magento\Customer\Test\Fixture\Customer;
use Magento\Framework\DB\Transaction;
use Magento\Framework\Registry;
use Magento\GraphQl\GetCustomerAuthenticationHeader;
use Magento\GraphQl\Sales\Fixtures\CustomerPlaceOrder;
use Magento\Quote\Test\Fixture\AddProductToCart;
use Magento\Quote\Test\Fixture\CustomerCart;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Shipment;
use Magento\Sales\Model\Order\ShipmentFactory;
use Magento\Sales\Model\ResourceModel\Order\Collection as OrderCollection;
use Magento\Sales\Test\Fixture\Invoice as InvoiceFixture;
use Magento\Sales\Test\Fixture\Shipment as ShipmentFixture;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
class OrderShipmentsTest extends GraphQlAbstract
{
/**
* @var GetCustomerAuthenticationHeader
*/
private $getCustomerAuthHeader;
/**
* @var OrderRepositoryInterface
*/
private $orderRepository;
protected function setUp(): void
{
$this->getCustomerAuthHeader = Bootstrap::getObjectManager()->get(GetCustomerAuthenticationHeader::class);
$this->orderRepository = Bootstrap::getObjectManager()->get(OrderRepositoryInterface::class);
}
protected function tearDown(): void
{
$this->cleanupOrders();
}
/**
* @magentoApiDataFixture Magento/GraphQl/Sales/_files/customer_order_with_simple_shipment.php
*/
public function testGetOrderShipment()
{
$query = $this->getQuery('100000555');
$authHeader = $this->getCustomerAuthHeader->execute('customer_uk_address@test.com', 'password');
$orderModel = $this->fetchOrderModel('100000555');
$result = $this->graphQlQuery($query, [], '', $authHeader);
$this->assertArrayNotHasKey('errors', $result);
$this->assertCount(1, $result['customer']['orders']['items']);
$order = $result['customer']['orders']['items'][0];
$this->assertEquals('Flat Rate', $order['carrier']);
$this->assertEquals('Flat Rate - Fixed', $order['shipping_method']);
$this->assertArrayHasKey('shipments', $order);
/** @var Shipment $orderShipmentModel */
$orderShipmentModel = $orderModel->getShipmentsCollection()->getFirstItem();
$shipment = $order['shipments'][0];
$this->assertEquals(base64_encode($orderShipmentModel->getIncrementId()), $shipment['id']);
$this->assertEquals($orderShipmentModel->getIncrementId(), $shipment['number']);
//Check Tracking
$this->assertCount(1, $shipment['tracking']);
$tracking = $shipment['tracking'][0];
$this->assertEquals('ups', $tracking['carrier']);
$this->assertEquals('United Parcel Service', $tracking['title']);
$this->assertEquals('1234567890', $tracking['number']);
//Check Items
$this->assertCount(2, $shipment['items']);
foreach ($orderShipmentModel->getItems() as $expectedItem) {
$sku = $expectedItem->getSku();
$findItem = array_filter($shipment['items'], function ($item) use ($sku) {
return $item['product_sku'] === $sku;
});
$this->assertCount(1, $findItem);
$actualItem = reset($findItem);
$expectedEncodedId = base64_encode($expectedItem->getEntityId());
$this->assertEquals($expectedEncodedId, $actualItem['id']);
$this->assertEquals($expectedItem->getSku(), $actualItem['product_sku']);
$this->assertEquals($expectedItem->getName(), $actualItem['product_name']);
$this->assertEquals($expectedItem->getPrice(), $actualItem['product_sale_price']['value']);
$this->assertEquals('USD', $actualItem['product_sale_price']['currency']);
$this->assertEquals('1', $actualItem['quantity_shipped']);
//Check correct order_item
$this->assertNotEmpty($actualItem['order_item']);
$this->assertEquals($expectedItem->getSku(), $actualItem['order_item']['product_sku']);
}
//Check comments
$this->assertCount(1, $shipment['comments']);
$this->assertEquals('This comment is visible to the customer', $shipment['comments'][0]['message']);
$this->assertNotEmpty($shipment['comments'][0]['timestamp']);
}
/**
* @magentoApiDataFixture Magento/GraphQl/Sales/_files/customer_order_with_multiple_shipments.php
*/
#[
DataFixture(ProductFixture::class, as: 'product1'),
DataFixture(ProductFixture::class, as: 'product2'),
DataFixture(Customer::class, as: 'customer'),
DataFixture(CustomerCart::class, ['customer_id' => '$customer.id$'], as: 'quote'),
DataFixture(AddProductToCart::class, ['cart_id' => '$quote.id$', 'product_id' => '$product1.id$', 'qty' => 1]),
DataFixture(AddProductToCart::class, ['cart_id' => '$quote.id$', 'product_id' => '$product2.id$', 'qty' => 1]),
DataFixture(SetBillingAddress::class, ['cart_id' => '$quote.id$']),
DataFixture(SetShippingAddress::class, ['cart_id' => '$quote.id$']),
DataFixture(SetDeliveryMethodFixture::class, ['cart_id' => '$quote.id$']),
DataFixture(SetPaymentMethodFixture::class, ['cart_id' => '$quote.id$']),
DataFixture(PlaceOrderFixture::class, ['cart_id' => '$quote.id$'], 'order'),
DataFixture(InvoiceFixture::class, ['order_id' => '$order.id$'], 'invoice'),
DataFixture(
ShipmentFixture::class,
[
'order_id' => '$order.id$',
'items' => [['product_id' => '$product1.id$']]
],
'shipment1'
),
DataFixture(
ShipmentFixture::class,
[
'order_id' => '$order.id$',
'items' => [['product_id' => '$product2.id$']]
],
'shipment2'
),
]
public function testGetOrderShipmentsMultiple()
{
$shipmentNumber1 = DataFixtureStorageManager::getStorage()->get('shipment1')->getIncrementId();
$shipmentNumber2 = DataFixtureStorageManager::getStorage()->get('shipment2')->getIncrementId();
$orderNumber = DataFixtureStorageManager::getStorage()->get('order')->getIncrementId();
$customerEmail = DataFixtureStorageManager::getStorage()->get('customer')->getEmail();
$query = $this->getQuery($orderNumber);
$authHeader = $this->getCustomerAuthHeader->execute($customerEmail, 'password');
$result = $this->graphQlQuery($query, [], '', $authHeader);
$this->assertArrayNotHasKey('errors', $result);
$order = $result['customer']['orders']['items'][0];
$shipments = $order['shipments'];
$this->assertCount(2, $shipments);
$this->assertEquals($shipmentNumber1, $shipments[0]['number']);
$this->assertCount(1, $shipments[0]['items']);
$this->assertEquals($shipmentNumber2, $shipments[1]['number']);
$this->assertCount(1, $shipments[1]['items']);
}
/**
* @magentoConfigFixture default_store carriers/ups/active 1
* @magentoApiDataFixture Magento/GraphQl/Sales/_files/customer_order_with_ups_shipping.php
*/
public function testOrderShipmentWithUpsCarrier()
{
$query = $this->getQuery('100000001');
$authHeader = $this->getCustomerAuthHeader->execute('customer@example.com', 'password');
$result = $this->graphQlQuery($query, [], '', $authHeader);
$this->assertArrayNotHasKey('errors', $result);
$this->assertEquals('UPS Next Day Air', $result['customer']['orders']['items'][0]['shipping_method']);
$this->assertEquals('United Parcel Service', $result['customer']['orders']['items'][0]['carrier']);
$shipments = $result['customer']['orders']['items'][0]['shipments'];
$expectedTracking = [
'title' => 'United Parcel Service',
'carrier' => 'ups',
'number' => '987654321'
];
$this->assertEquals($expectedTracking, $shipments[0]['tracking'][0]);
}
/**
* @magentoConfigFixture default_store carriers/ups/active 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Bundle/_files/bundle_product_two_dropdown_options.php
*/
public function testOrderShipmentWithBundleProduct()
{
//Place order with bundled product
/** @var CustomerPlaceOrder $bundleProductOrderFixture */
$bundleProductOrderFixture = Bootstrap::getObjectManager()->create(CustomerPlaceOrder::class);
$placeOrderResponse = $bundleProductOrderFixture->placeOrderWithBundleProduct(
['email' => 'customer@example.com', 'password' => 'password'],
['sku' => 'bundle-product-two-dropdown-options']
);
$orderNumber = $placeOrderResponse['placeOrder']['order']['order_number'];
$this->shipOrder($orderNumber);
$result = $this->graphQlQuery(
$this->getQuery(),
[],
'',
$this->getCustomerAuthHeader->execute('customer@example.com', 'password')
);
$this->assertArrayNotHasKey('errors', $result);
$shipments = $result['customer']['orders']['items'][0]['shipments'];
$shipmentBundleItem = $shipments[0]['items'][0];
$shipmentItemAssertionMap = [
'order_item' => [
'product_sku' => 'bundle-product-two-dropdown-options-simple1-simple2'
],
'product_name' => 'Bundle Product With Two dropdown options',
'product_sku' => 'bundle-product-two-dropdown-options-simple1-simple2',
'product_sale_price' => [
'value' => 15,
'currency' => 'USD'
],
'bundle_options' => [
[
'label' => 'Drop Down Option 1',
'values' => [
[
'product_name' => 'Simple Product1',
'product_sku' => 'simple1',
'quantity' => 1,
'price' => ['value' => 1]
]
]
],
[
'label' => 'Drop Down Option 2',
'values' => [
[
'product_name' => 'Simple Product2',
'product_sku' => 'simple2',
'quantity' => 2,
'price' => ['value' => 2]
]
]
]
]
];
$this->assertResponseFields($shipmentBundleItem, $shipmentItemAssertionMap);
}
/**
* Get query that fetch orders and shipment information
*
* @param string|null $orderId
* @return string
*/
private function getQuery(string $orderId = null)
{
$filter = $orderId ? "(filter:{number:{eq:\"$orderId\"}})" : "";
return <<<QUERY
{
customer {
orders {$filter}{
items {
number
status
items {
product_sku
}
carrier
shipping_method
shipments {
id
number
tracking {
title
carrier
number
}
items {
id
order_item {
product_sku
}
product_name
product_sku
product_sale_price {
value
currency
}
... on BundleShipmentItem {
bundle_options {
label
values {
product_name
product_sku
quantity
price {
value
}
}
}
}
quantity_shipped
}
comments {
timestamp
message
}
}
}
}
}
}
QUERY;
}
/**
* Get model instance for order by number
*
* @param string $orderNumber
* @return Order
*/
private function fetchOrderModel(string $orderNumber): Order
{
/** @var Order $order */
$order = Bootstrap::getObjectManager()->get(Order::class);
$order->loadByIncrementId($orderNumber);
return $order;
}
/**
* Create shipment for order
*
* @param string $orderNumber
*/
private function shipOrder(string $orderNumber): void
{
$order = $this->fetchOrderModel($orderNumber);
$order->setIsInProcess(true);
/** @var Transaction $transaction */
$transaction = Bootstrap::getObjectManager()->create(Transaction::class);
$items = [];
foreach ($order->getItems() as $orderItem) {
$items[$orderItem->getId()] = $orderItem->getQtyOrdered();
}
$shipment = Bootstrap::getObjectManager()->get(ShipmentFactory::class)->create($order, $items);
$shipment->register();
$transaction->addObject($shipment)->addObject($order)->save();
}
/**
* Clean up orders
*/
private function cleanupOrders()
{
$registry = Bootstrap::getObjectManager()->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var $order \Magento\Sales\Model\Order */
$orderCollection = Bootstrap::getObjectManager()->create(OrderCollection::class);
foreach ($orderCollection as $order) {
$this->orderRepository->delete($order);
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
}
}
@@ -0,0 +1,228 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Magento\Catalog\Helper\Data;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\Checkout\Test\Fixture\PlaceOrder as PlaceOrderFixture;
use Magento\Checkout\Test\Fixture\SetBillingAddress;
use Magento\Checkout\Test\Fixture\SetDeliveryMethod as SetDeliveryMethodFixture;
use Magento\Checkout\Test\Fixture\SetPaymentMethod as SetPaymentMethodFixture;
use Magento\Checkout\Test\Fixture\SetShippingAddress;
use Magento\Customer\Test\Fixture\Customer;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Quote\Test\Fixture\AddProductToCart;
use Magento\Quote\Test\Fixture\CustomerCart;
use Magento\Store\Test\Fixture\Group as StoreGroupFixture;
use Magento\Store\Test\Fixture\Store as StoreFixture;
use Magento\Store\Test\Fixture\Website as WebsiteFixture;
use Magento\TestFramework\Fixture\Config;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorage;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* GraphQl tests for @see \Magento\SalesGraphQl\Model\Resolver\CustomerOrders.
*/
class CustomerOrdersTest extends GraphQlAbstract
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var DataFixtureStorage
*/
private $fixtures;
/**
* @inheridoc
* @throws LocalizedException
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->fixtures = $this->objectManager->get(DataFixtureStorageManager::class)->getStorage();
}
/**
* Test graphql customer orders
*
* @throws LocalizedException
*/
#[
Config(Data::XML_PATH_PRICE_SCOPE, Data::PRICE_SCOPE_WEBSITE),
DataFixture(WebsiteFixture::class, as: 'website2'),
DataFixture(StoreGroupFixture::class, ['website_id' => '$website2.id$'], 'store_group2'),
DataFixture(StoreFixture::class, ['store_group_id' => '$store_group2.id$'], 'store2'),
DataFixture(StoreFixture::class, ['store_group_id' => '$store_group2.id$'], 'store3'),
DataFixture(ProductFixture::class, ['website_ids' => [1, '$website2.id$' ]], as: 'product'),
DataFixture(
Customer::class,
[
'store_id' => '$store2.id$',
'website_id' => '$website2.id$',
'addresses' => [[]]
],
as: 'customer'
),
DataFixture(CustomerCart::class, ['customer_id' => '$customer.id$'], as: 'quote1', scope: 'store2'),
DataFixture(AddProductToCart::class, ['cart_id' => '$quote1.id$', 'product_id' => '$product.id$', 'qty' => 1]),
DataFixture(SetBillingAddress::class, ['cart_id' => '$quote1.id$']),
DataFixture(SetShippingAddress::class, ['cart_id' => '$quote1.id$']),
DataFixture(SetDeliveryMethodFixture::class, ['cart_id' => '$quote1.id$']),
DataFixture(SetPaymentMethodFixture::class, ['cart_id' => '$quote1.id$']),
DataFixture(PlaceOrderFixture::class, ['cart_id' => '$quote1.id$'], 'order1'),
DataFixture(CustomerCart::class, ['customer_id' => '$customer.id$'], as: 'quote2', scope: 'store3'),
DataFixture(AddProductToCart::class, ['cart_id' => '$quote2.id$', 'product_id' => '$product.id$', 'qty' => 1]),
DataFixture(SetBillingAddress::class, ['cart_id' => '$quote2.id$']),
DataFixture(SetShippingAddress::class, ['cart_id' => '$quote2.id$']),
DataFixture(SetDeliveryMethodFixture::class, ['cart_id' => '$quote2.id$']),
DataFixture(SetPaymentMethodFixture::class, ['cart_id' => '$quote2.id$']),
DataFixture(PlaceOrderFixture::class, ['cart_id' => '$quote2.id$'], 'order2')
]
public function testGetCustomerOrders()
{
$store2 = $this->fixtures->get('store2');
$store3 = $this->fixtures->get('store3');
$customer = $this->fixtures->get('customer');
$currentEmail = $customer->getEmail();
$currentPassword = 'password';
$generateToken = $this->generateCustomerToken($currentEmail, $currentPassword);
$tokenResponse = $this->graphQlMutationWithResponseHeaders(
$generateToken,
[],
'',
['Store' => $store2->getCode()]
);
$customerToken = $tokenResponse['body']['generateCustomerToken']['token'];
$query = $this->getCustomerOrdersQuery('STORE');
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerHeaders($customerToken, $store2->getCode())
);
$this->assertEquals(2, count($response['customer']['orders']['items']));
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerHeaders($customerToken, $store3->getCode())
);
$this->assertEquals(2, count($response['customer']['orders']['items']));
$query = $this->getCustomerOrdersQuery('WEBSITE');
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerHeaders($customerToken, $store2->getCode())
);
$this->assertEquals(2, count($response['customer']['orders']['items']));
$query = $this->getCustomerOrdersQuery('GLOBAL');
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerHeaders($customerToken, null)
);
$this->assertEquals(2, count($response['customer']['orders']['items']));
$query = $this->getCustomerOrdersQuery();
$response = $this->graphQlQuery(
$query,
[],
'',
$this->getCustomerHeaders($customerToken, null)
);
$this->assertEquals(0, count($response['customer']['orders']['items']));
}
/**
* Generate graphql query headers for customer orders
*
* @param string $token
* @param string|null $storeCode
*
* @return array
*/
private function getCustomerHeaders(string $token, ?string $storeCode): array
{
return ['Authorization' => 'Bearer ' . $token, 'Store' => $storeCode ?? 'default'];
}
/**
* Generate graphql query body for customer orders
*
* @param string|null $scope
*
* @return array|string
*/
private function getCustomerOrdersQuery(?string $scope = null): array|string
{
$query = <<<QUERY
query {
customer {
orders(
pageSize: 20,
{{scope}}
) {
items {
id
order_number
order_date
total {
grand_total
{ value currency }}
status
}
}
}
}
QUERY;
$query = str_replace("{{scope}}", isset($scope) ? "scope: $scope" : '', $query);
return $query;
}
/**
* Get customer login token
*
* @param string $email
* @param string $password
* @return string
*/
private function generateCustomerToken(string $email, string $password) : string
{
return <<<MUTATION
mutation {
generateCustomerToken(
email: "{$email}"
password: "{$password}"
) {
token
}
}
MUTATION;
}
}
@@ -0,0 +1,375 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales\Fixtures;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\TestCase\GraphQl\Client;
class CustomerPlaceOrder
{
/**
* @var Client
*/
private $gqlClient;
/**
* @var CustomerTokenServiceInterface
*/
private $tokenService;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var string
*/
private $authHeader;
/**
* @var string
*/
private $cartId;
/**
* @var array
*/
private $customerLogin;
/**
* @param Client $gqlClient
* @param CustomerTokenServiceInterface $tokenService
* @param ProductRepositoryInterface $productRepository
*/
public function __construct(
Client $gqlClient,
CustomerTokenServiceInterface $tokenService,
ProductRepositoryInterface $productRepository
) {
$this->gqlClient = $gqlClient;
$this->tokenService = $tokenService;
$this->productRepository = $productRepository;
}
/**
* Place order for a bundled product
*
* @param array $customerLogin
* @param array $productData
* @param array|null $addressData
* @return array
*/
public function placeOrderWithBundleProduct(
array $customerLogin,
array $productData,
?array $addressData = null
): array {
$this->customerLogin = $customerLogin;
$this->createCustomerCart();
$this->addBundleProduct($productData);
$this->setBillingAddress($addressData);
$shippingMethod = $this->setShippingAddress($addressData);
$paymentMethod = $this->setShippingMethod($shippingMethod);
$this->setPaymentMethod($paymentMethod);
return $this->doPlaceOrder();
}
/**
* Make GraphQl POST request
*
* @param string $query
* @param array $additionalHeaders
* @return array
*/
private function makeRequest(string $query, array $additionalHeaders = []): array
{
$headers = array_merge([$this->getAuthHeader()], $additionalHeaders);
return $this->gqlClient->post($query, [], '', $headers);
}
/**
* Get header for authenticated requests
*
* @return string
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function getAuthHeader(): string
{
if (empty($this->authHeader)) {
$customerToken = $this->tokenService
->createCustomerAccessToken($this->customerLogin['email'], $this->customerLogin['password']);
$this->authHeader = "Authorization: Bearer {$customerToken}";
}
return $this->authHeader;
}
/**
* Get cart id
*
* @return string
*/
private function getCartId(): string
{
if (empty($this->cartId)) {
$this->cartId = $this->createCustomerCart();
}
return $this->cartId;
}
/**
* Create empty cart for the customer
*
* @return array
*/
private function createCustomerCart(): string
{
//Create empty cart
$createEmptyCart = <<<QUERY
mutation {
createEmptyCart
}
QUERY;
$result = $this->makeRequest($createEmptyCart);
return $result['createEmptyCart'];
}
/**
* Add a bundle product to the cart
*
* @param array $productData
* @return array
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
private function addBundleProduct(array $productData)
{
$productSku = $productData['sku'];
$qty = $productData['quantity'] ?? 1;
/** @var Product $bundleProduct */
$bundleProduct = $this->productRepository->get($productSku);
/** @var \Magento\Bundle\Model\Product\Type $typeInstance */
$typeInstance = $bundleProduct->getTypeInstance();
$optionId1 = (int)$typeInstance->getOptionsCollection($bundleProduct)->getFirstItem()->getId();
$optionId2 = (int)$typeInstance->getOptionsCollection($bundleProduct)->getLastItem()->getId();
$selectionId1 = (int)$typeInstance->getSelectionsCollection([$optionId1], $bundleProduct)
->getFirstItem()
->getSelectionId();
$selectionId2 = (int)$typeInstance->getSelectionsCollection([$optionId2], $bundleProduct)
->getLastItem()
->getSelectionId();
$addProduct = <<<QUERY
mutation {
addBundleProductsToCart(input:{
cart_id:"{$this->getCartId()}"
cart_items:[
{
data:{
sku:"{$productSku}"
quantity:{$qty}
}
bundle_options:[
{
id:{$optionId1}
quantity:1
value:["{$selectionId1}"]
}
{
id:$optionId2
quantity:2
value:["{$selectionId2}"]
}
]
}
]
}) {
cart {
items {quantity product {sku}}
}
}
}
QUERY;
return $this->makeRequest($addProduct);
}
/**
* Set the billing address on the cart
*
* @param array $addressData
* @return array
*/
private function setBillingAddress(?array $addressData = null): array
{
$telephone = $addressData['telephone'] ?? '5123456677';
$setBillingAddress = <<<QUERY
mutation {
setBillingAddressOnCart(
input: {
cart_id: "{$this->getCartId()}"
billing_address: {
address: {
firstname: "John"
lastname: "Smith"
company: "Test company"
street: ["test street 1", "test street 2"]
city: "Texas City"
postcode: "78717"
telephone: "{$telephone}"
region: "TX"
country_code: "US"
}
}
}
) {
cart {
billing_address {
__typename
}
}
}
}
QUERY;
return $this->makeRequest($setBillingAddress);
}
/**
* Set the shipping address on the cart and return an available shipping method
*
* @param array|null $addressData
* @return array
*/
private function setShippingAddress(?array $addressData): array
{
$telephone = $addressData['telephone'] ?? '5123456677';
$setShippingAddress = <<<QUERY
mutation {
setShippingAddressesOnCart(
input: {
cart_id: "{$this->getCartId()}"
shipping_addresses: [
{
address: {
firstname: "test shipFirst"
lastname: "test shipLast"
company: "test company"
street: ["test street 1", "test street 2"]
city: "Montgomery"
region: "AL"
postcode: "36013"
country_code: "US"
telephone: "{$telephone}"
}
}
]
}
) {
cart {
shipping_addresses {
available_shipping_methods {
carrier_code
method_code
amount {value}
}
}
}
}
}
QUERY;
$result = $this->makeRequest($setShippingAddress);
$shippingMethod = $result['setShippingAddressesOnCart']
['cart']['shipping_addresses'][0]['available_shipping_methods'][0];
return $shippingMethod;
}
/**
* Set the shipping method on the cart and return an available payment method
*
* @param array|null $shippingMethod
* @return array
*/
private function setShippingMethod(?array $shippingMethod): array
{
$setShippingMethod = <<<QUERY
mutation {
setShippingMethodsOnCart(input: {
cart_id: "{$this->getCartId()}",
shipping_methods: [
{
carrier_code: "{$shippingMethod['carrier_code']}"
method_code: "{$shippingMethod['method_code']}"
}
]
}) {
cart {
available_payment_methods {
code
title
}
}
}
}
QUERY;
$result = $this->makeRequest($setShippingMethod);
$paymentMethod = $result['setShippingMethodsOnCart']['cart']['available_payment_methods'][0];
return $paymentMethod;
}
/**
* Set the payment method on the cart
*
* @param array $paymentMethod
* @return array
*/
private function setPaymentMethod(array $paymentMethod): array
{
$setPaymentMethod = <<<QUERY
mutation {
setPaymentMethodOnCart(
input: {
cart_id: "{$this->getCartId()}"
payment_method: {
code: "{$paymentMethod['code']}"
}
}
) {
cart {
selected_payment_method {
code
}
}
}
}
QUERY;
return $this->makeRequest($setPaymentMethod);
}
/**
* Place the order
*
* @return array
*/
private function doPlaceOrder(): array
{
$placeOrder = <<<QUERY
mutation {
placeOrder(
input: {
cart_id: "{$this->getCartId()}"
}
) {
order {
order_number
}
}
}
QUERY;
return $this->makeRequest($placeOrder);
}
}
@@ -0,0 +1,284 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales\Fixtures;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Downloadable\Api\Data\LinkInterface;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\TestCase\GraphQl\Client;
class CustomerPlaceOrderWithDownloadable
{
/**
* @var Client
*/
private $gqlClient;
/**
* @var CustomerTokenServiceInterface
*/
private $tokenService;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var string
*/
private $authHeader;
/**
* @var string
*/
private $cartId;
/**
* @var array
*/
private $customerLogin;
/**
* @param Client $gqlClient
* @param CustomerTokenServiceInterface $tokenService
* @param ProductRepositoryInterface $productRepository
*/
public function __construct(
Client $gqlClient,
CustomerTokenServiceInterface $tokenService,
ProductRepositoryInterface $productRepository
) {
$this->gqlClient = $gqlClient;
$this->tokenService = $tokenService;
$this->productRepository = $productRepository;
}
/**
* Place order for a downloadable product
*
* @param array $customerLogin
* @param array $productData
* @return array
*/
public function placeOrderWithDownloadableProduct(array $customerLogin, array $productData): array
{
$this->customerLogin = $customerLogin;
$this->createCustomerCart();
$this->addDownloadableProduct($productData);
$this->setBillingAddress();
$paymentMethodCode ='checkmo';
$this->setPaymentMethod($paymentMethodCode);
return $this->doPlaceOrder();
}
/**
* Make GraphQl POST request
*
* @param string $query
* @param array $additionalHeaders
* @return array
*/
private function makeRequest(string $query, array $additionalHeaders = []): array
{
$headers = array_merge([$this->getAuthHeader()], $additionalHeaders);
return $this->gqlClient->post($query, [], '', $headers);
}
/**
* Get header for authenticated requests
*
* @return string
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function getAuthHeader(): string
{
if (empty($this->authHeader)) {
$customerToken = $this->tokenService
->createCustomerAccessToken($this->customerLogin['email'], $this->customerLogin['password']);
$this->authHeader = "Authorization: Bearer {$customerToken}";
}
return $this->authHeader;
}
/**
* Get cart id
*
* @return string
*/
private function getCartId(): string
{
if (empty($this->cartId)) {
$this->cartId = $this->createCustomerCart();
}
return $this->cartId;
}
/**
* Create empty cart for the customer
*
* @return array
*/
private function createCustomerCart(): string
{
//Create empty cart
$createEmptyCart = <<<QUERY
mutation {
createEmptyCart
}
QUERY;
$result = $this->makeRequest($createEmptyCart);
return $result['createEmptyCart'];
}
/**
* Add downloadable product with link to the cart
*
* @param array $productData
* @return array
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
private function addDownloadableProduct(array $productData)
{
$productSku = $productData['sku'];
$qty = $productData['quantity'] ?? 1;
/** @var Product $downloadableProduct */
$downloadableProduct = $this->productRepository->get($productSku);
/** @var LinkInterface $downloadableProductLinks */
$downloadableProductLinks = $downloadableProduct->getExtensionAttributes()->getDownloadableProductLinks();
$linkId = $downloadableProductLinks[0]->getId();
$addProduct = <<<QUERY
mutation {
addDownloadableProductsToCart(
input: {
cart_id: "{$this->getCartId()}",
cart_items: [
{
data: {
quantity: {$qty},
sku: "{$productSku}"
},
downloadable_product_links: [
{
link_id: {$linkId}
}
]
}
]
}
) {
cart {
items {
quantity
... on DownloadableCartItem {
links {
title
link_type
price
}
}
}
}
}
}
QUERY;
return $this->makeRequest($addProduct);
}
/**
* Set the billing address on the cart
*
* @return array
*/
private function setBillingAddress(): array
{
$setBillingAddress = <<<QUERY
mutation {
setBillingAddressOnCart(
input: {
cart_id: "{$this->getCartId()}"
billing_address: {
address: {
firstname: "John"
lastname: "Smith"
company: "Test company"
street: ["test street 1", "test street 2"]
city: "Texas City"
postcode: "78717"
telephone: "5123456677"
region: "TX"
country_code: "US"
}
}
}
) {
cart {
billing_address {
__typename
}
}
}
}
QUERY;
return $this->makeRequest($setBillingAddress);
}
/**
* Set the payment method on the cart
*
* @param string $paymentMethodCode
* @return array
*/
private function setPaymentMethod(string $paymentMethodCode): array
{
$setPaymentMethod = <<<QUERY
mutation {
setPaymentMethodOnCart(
input: {
cart_id: "{$this->getCartId()}"
payment_method: {
code: "{$paymentMethodCode}"
}
}
) {
cart {
selected_payment_method {
code
}
}
}
}
QUERY;
return $this->makeRequest($setPaymentMethod);
}
/**
* Place the order
*
* @return array
*/
private function doPlaceOrder(): array
{
$placeOrder = <<<QUERY
mutation {
placeOrder(
input: {
cart_id: "{$this->getCartId()}"
}
) {
order {
order_number
}
}
}
QUERY;
return $this->makeRequest($placeOrder);
}
}
@@ -0,0 +1,158 @@
<?php
/**
* Copyright 2024 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\Checkout\Test\Fixture\PlaceOrder as PlaceOrderFixture;
use Magento\Checkout\Test\Fixture\SetBillingAddress as SetBillingAddressFixture;
use Magento\Checkout\Test\Fixture\SetDeliveryMethod as SetDeliveryMethodFixture;
use Magento\Checkout\Test\Fixture\SetGuestEmail as SetGuestEmailFixture;
use Magento\Checkout\Test\Fixture\SetPaymentMethod as SetPaymentMethodFixture;
use Magento\Checkout\Test\Fixture\SetShippingAddress as SetShippingAddressFixture;
use Magento\Customer\Test\Fixture\Customer;
use Magento\Quote\Test\Fixture\AddProductToCart as AddProductToCartFixture;
use Magento\Quote\Test\Fixture\CustomerCart;
use Magento\Quote\Test\Fixture\GuestCart;
use Magento\Quote\Test\Fixture\QuoteIdMask;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\SalesGraphQl\Model\Order\Token;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test for guestOrderByToken query
*/
class GuestOrderByTokenTest extends GraphQlAbstract
{
private const GUEST_ORDER_BY_TOKEN = <<<QUERY
{
guestOrderByToken(input: {
token: "%token"
}) {
number
email
billing_address {
firstname
lastname
}
}
}
QUERY;
private const PLACE_ORDER = <<<QUERY
mutation {
placeOrder(input: {
cart_id: "%cart_id"
}) {
orderV2 {
number
email
billing_address {
firstname
lastname
}
token
}
}
}
QUERY;
#[
DataFixture(ProductFixture::class, as: 'product'),
DataFixture(GuestCart::class, as: 'cart'),
DataFixture(AddProductToCartFixture::class, ['cart_id' => '$cart.id$', 'product_id' => '$product.id$']),
DataFixture(SetBillingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetShippingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetGuestEmailFixture::class, ['cart_id' => '$cart.id$'], 'email'),
DataFixture(SetDeliveryMethodFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetPaymentMethodFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(QuoteIdMask::class, ['cart_id' => '$cart.id$'], 'quoteIdMask'),
]
public function testGuestOrder(): void
{
$maskedQuoteId = DataFixtureStorageManager::getStorage()->get('quoteIdMask')->getMaskedId();
$placeOrderQuery = strtr(
self::PLACE_ORDER,
[
'%cart_id' => $maskedQuoteId
]
);
$placeOrderResponse = $this->graphQlMutation($placeOrderQuery);
$this->assertNotEmpty($placeOrderResponse['placeOrder']['orderV2']['number']);
$this->assertNotEmpty($placeOrderResponse['placeOrder']['orderV2']['token']);
$this->assertNotEmpty($placeOrderResponse['placeOrder']['orderV2']['email']);
$this->assertNotEmpty($placeOrderResponse['placeOrder']['orderV2']['billing_address']['firstname']);
$this->assertNotEmpty($placeOrderResponse['placeOrder']['orderV2']['billing_address']['lastname']);
$query = strtr(
self::GUEST_ORDER_BY_TOKEN,
[
'%token' => $placeOrderResponse['placeOrder']['orderV2']['token'],
]
);
$response = $this->graphQlQuery($query);
self::assertEquals(
[
'guestOrderByToken' => [
'number' => $placeOrderResponse['placeOrder']['orderV2']['number'],
'email' => $placeOrderResponse['placeOrder']['orderV2']['email'],
'billing_address' => [
'firstname' => $placeOrderResponse['placeOrder']['orderV2']['billing_address']['firstname'],
'lastname' => $placeOrderResponse['placeOrder']['orderV2']['billing_address']['lastname']
]
]
],
$response
);
}
#[
DataFixture(Customer::class, as: 'customer'),
DataFixture(ProductFixture::class, as: 'product'),
DataFixture(CustomerCart::class, ['customer_id' => '$customer.id$'], as: 'cart'),
DataFixture(AddProductToCartFixture::class, ['cart_id' => '$cart.id$', 'product_id' => '$product.id$']),
DataFixture(SetBillingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetShippingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetGuestEmailFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetDeliveryMethodFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetPaymentMethodFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(PlaceOrderFixture::class, ['cart_id' => '$cart.id$'], 'order'),
]
public function testCustomerOrder(): void
{
$this->expectExceptionMessage('Please login to view the order.');
/** @var OrderInterface $order */
$order = DataFixtureStorageManager::getStorage()->get('order');
$query = strtr(
self::GUEST_ORDER_BY_TOKEN,
[
'%token' => Bootstrap::getObjectManager()->get(Token::class)->encrypt(
$order->getIncrementId(),
$order->getBillingAddress()->getEmail(),
$order->getBillingAddress()->getPostcode()
)
]
);
$this->graphQlQuery($query);
}
public function testGuestOrderIncorrectToken(): void
{
$this->expectExceptionMessage('We couldn\'t locate an order with the information provided.');
$query = strtr(
self::GUEST_ORDER_BY_TOKEN,
[
'%token' => 'incorrect'
]
);
$this->graphQlQuery($query);
}
}
@@ -0,0 +1,141 @@
<?php
/**
* Copyright 2024 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\Checkout\Test\Fixture\PlaceOrder as PlaceOrderFixture;
use Magento\Checkout\Test\Fixture\SetBillingAddress as SetBillingAddressFixture;
use Magento\Checkout\Test\Fixture\SetDeliveryMethod as SetDeliveryMethodFixture;
use Magento\Checkout\Test\Fixture\SetGuestEmail as SetGuestEmailFixture;
use Magento\Checkout\Test\Fixture\SetPaymentMethod as SetPaymentMethodFixture;
use Magento\Checkout\Test\Fixture\SetShippingAddress as SetShippingAddressFixture;
use Magento\Customer\Test\Fixture\Customer;
use Magento\Quote\Test\Fixture\AddProductToCart as AddProductToCartFixture;
use Magento\Quote\Test\Fixture\CustomerCart;
use Magento\Quote\Test\Fixture\GuestCart;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test for guestOrder query
*/
class GuestOrderTest extends GraphQlAbstract
{
private const GUEST_ORDER = <<<QUERY
{
guestOrder(input: {
number: "%number",
email: "%email",
postcode: "%postcode"
}) {
number
email
billing_address {
firstname
lastname
}
}
}
QUERY;
#[
DataFixture(ProductFixture::class, as: 'product'),
DataFixture(GuestCart::class, as: 'cart'),
DataFixture(AddProductToCartFixture::class, ['cart_id' => '$cart.id$', 'product_id' => '$product.id$']),
DataFixture(SetBillingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetShippingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetGuestEmailFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetDeliveryMethodFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetPaymentMethodFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(PlaceOrderFixture::class, ['cart_id' => '$cart.id$'], 'order'),
]
public function testGuestOrder(): void
{
/** @var OrderInterface $order */
$order = DataFixtureStorageManager::getStorage()->get('order');
$query = strtr(
self::GUEST_ORDER,
[
'%number' => $order->getIncrementId(),
'%email' => $order->getBillingAddress()->getEmail(),
'%postcode' => $order->getBillingAddress()->getPostcode(),
]
);
$response = $this->graphQlQuery($query);
self::assertEquals(
[
'guestOrder' => [
'number' => $order->getIncrementId(),
'email' => $order->getBillingAddress()->getEmail(),
'billing_address' => [
'firstname' => $order->getBillingAddress()->getFirstname(),
'lastname' => $order->getBillingAddress()->getLastname()
]
]
],
$response
);
}
#[
DataFixture(Customer::class, as: 'customer'),
DataFixture(ProductFixture::class, as: 'product'),
DataFixture(CustomerCart::class, ['customer_id' => '$customer.id$'], as: 'cart'),
DataFixture(AddProductToCartFixture::class, ['cart_id' => '$cart.id$', 'product_id' => '$product.id$']),
DataFixture(SetBillingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetShippingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetGuestEmailFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetDeliveryMethodFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetPaymentMethodFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(PlaceOrderFixture::class, ['cart_id' => '$cart.id$'], 'order'),
]
public function testCustomerOrder(): void
{
$this->expectExceptionMessage('Please login to view the order.');
/** @var OrderInterface $order */
$order = DataFixtureStorageManager::getStorage()->get('order');
$query = strtr(
self::GUEST_ORDER,
[
'%number' => $order->getIncrementId(),
'%email' => $order->getBillingAddress()->getEmail(),
'%postcode' => $order->getBillingAddress()->getPostcode(),
]
);
$this->graphQlQuery($query);
}
#[
DataFixture(ProductFixture::class, as: 'product'),
DataFixture(GuestCart::class, as: 'cart'),
DataFixture(AddProductToCartFixture::class, ['cart_id' => '$cart.id$', 'product_id' => '$product.id$']),
DataFixture(SetBillingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetShippingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetGuestEmailFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetDeliveryMethodFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetPaymentMethodFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(PlaceOrderFixture::class, ['cart_id' => '$cart.id$'], 'order'),
]
public function testGuestOrderIncorrectEmail(): void
{
$this->expectExceptionMessage('We couldn\'t locate an order with the information provided.');
/** @var OrderInterface $order */
$order = DataFixtureStorageManager::getStorage()->get('order');
$query = strtr(
self::GUEST_ORDER,
[
'%number' => $order->getIncrementId(),
'%email' => 'incorrect' . $order->getBillingAddress()->getEmail(),
'%postcode' => $order->getBillingAddress()->getPostcode(),
]
);
$this->graphQlQuery($query);
}
}
@@ -0,0 +1,952 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\Checkout\Test\Fixture\PlaceOrder as PlaceOrderFixture;
use Magento\Checkout\Test\Fixture\SetBillingAddress as SetBillingAddressFixture;
use Magento\Checkout\Test\Fixture\SetDeliveryMethod as SetDeliveryMethodFixture;
use Magento\Checkout\Test\Fixture\SetGuestEmail as SetGuestEmailFixture;
use Magento\Checkout\Test\Fixture\SetPaymentMethod as SetPaymentMethodFixture;
use Magento\Checkout\Test\Fixture\SetShippingAddress as SetShippingAddressFixture;
use Magento\Customer\Test\Fixture\Customer;
use Magento\Framework\Registry;
use Magento\Quote\Test\Fixture\AddProductToCart as AddProductToCartFixture;
use Magento\Quote\Test\Fixture\CustomerCart;
use Magento\Quote\Test\Fixture\GuestCart as GuestCartFixture;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\ResourceModel\Order\Collection;
use Magento\Sales\Test\Fixture\Invoice as InvoiceFixture;
use Magento\Sales\Test\Fixture\InvoiceComment as InvoiceCommentFixture ;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\GraphQl\GetCustomerAuthenticationHeader;
/**
* Tests the Invoice query
*/
class InvoiceTest extends GraphQlAbstract
{
/** @var GetCustomerAuthenticationHeader */
private $customerAuthenticationHeader;
/** @var OrderRepositoryInterface */
private $orderRepository;
protected function setUp(): void
{
$this->customerAuthenticationHeader
= Bootstrap::getObjectManager()->get(GetCustomerAuthenticationHeader::class);
$this->orderRepository = Bootstrap::getObjectManager()->get(OrderRepositoryInterface::class);
}
/**
* @magentoApiDataFixture Magento/Sales/_files/customer_invoice_with_two_products_and_custom_options.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testSingleInvoiceForLoggedInCustomerQuery()
{
$response = $this->getCustomerInvoicesBasedOnOrderNumber('100000001');
$expectedOrdersData = [
'status' => 'Processing',
'grand_total' => 100.00
];
$expectedInvoiceData = [
[
'items' => [
[
'product_name' => 'Simple Related Product',
'product_sku' => 'simple',
'product_sale_price' => [
'value' => 10,
'currency' => 'USD'
],
'quantity_invoiced' => 1,
'discounts' => []
],
[
'product_name' => 'Simple Product With Related Product',
'product_sku' => 'simple_with_cross',
'product_sale_price' => [
'value' => 10,
'currency' => 'USD'
],
'quantity_invoiced' => 1,
'discounts' => []
]
],
'total' => [
'subtotal' => [
'value' => 100,
'currency' => 'USD'
],
'grand_total' => [
'value' => 100,
'currency' => 'USD'
],
'total_shipping' => [
'value' => 0,
'currency' => 'USD'
],
'shipping_handling' => [
'total_amount' => [
'value' => 0,
'currency' => 'USD'
],
'amount_including_tax' => [
'value' => 0,
'currency' => 'USD'
],
'amount_excluding_tax' => [
'value' => 0,
'currency' => 'USD'
],
'taxes' => [],
'discounts' => []
],
'taxes' => [],
'discounts' => [],
'base_grand_total' => [
'value' => 100,
'currency' => 'EUR'
],
'total_tax' => [
'value' => 0,
'currency' => 'USD'
],
]
]
];
$this->assertOrdersData($response, $expectedOrdersData);
$invoices = $response[0]['invoices'];
$this->assertResponseFields($invoices, $expectedInvoiceData);
}
/**
* @magentoApiDataFixture Magento/Sales/_files/customer_multiple_invoices_with_two_products_and_custom_options.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testMultipleInvoiceForLoggedInCustomerQuery()
{
$response = $this->getCustomerInvoicesBasedOnOrderNumber('100000002');
$expectedOrdersData = [
'status' => 'Processing',
'grand_total' => 60.00
];
$expectedInvoiceData = [
[
'items' => [
[
'product_name' => 'Simple Related Product',
'product_sku' => 'simple',
'product_sale_price' => [
'value' => 10,
'currency' => 'USD'
],
'quantity_invoiced' => 3,
'discounts'=> []
]
],
'total' => [
'subtotal' => [
'value' => 30,
'currency' => 'USD'
],
'grand_total' => [
'value' => 50,
'currency' => 'USD'
],
'total_shipping' => [
'value' => 20,
'currency' => 'USD'
],
'base_grand_total' => [
'value' => 50,
'currency' => 'EUR'
],
'total_tax' => [
'value' => 0,
'currency' => 'USD'
],
'shipping_handling' => [
'total_amount' => [
'value' => 20,
'currency' => 'USD'
],
'amount_including_tax' => [
'value' => 25,
'currency' => 'USD'
],
'amount_excluding_tax' => [
'value' => 20,
'currency' => 'USD'
],
'taxes' => [],
'discounts' => [],
],
'taxes' => [],
'discounts' => [],
]
],
[
'items' => [
[
'product_name' => 'Simple Product With Related Product',
'product_sku' => 'simple_with_cross',
'product_sale_price' => [
'value' => 10,
'currency' => 'USD'
],
'quantity_invoiced' => 1,
'discounts' => []
]
],
'total' => [
'subtotal' => [
'value' => 10,
'currency' => 'USD'
],
'grand_total' => [
'value' => 10,
'currency' => 'USD'
],
'base_grand_total' => [
'value' => 0,
'currency' => 'EUR'
],
'total_tax' => [
'value' => 0,
'currency' => 'USD'
],
'total_shipping' => [
'value' => 0,
'currency' => 'USD'
],
'shipping_handling' => [
'total_amount' => [
'value' => 0,
'currency' => 'USD'
],
'amount_including_tax' => [
'value' => 0,
'currency' => 'USD'
],
'amount_excluding_tax' => [
'value' => 0,
'currency' => 'USD'
],
'taxes' => [],
'discounts' => [],
],
'taxes' => [],
'discounts' => [],
]
]
];
$this->assertOrdersData($response, $expectedOrdersData);
$invoices = $response[0]['invoices'];
$this->assertResponseFields($invoices, $expectedInvoiceData);
}
/**
* @magentoApiDataFixture Magento/Sales/_files/customers_with_invoices.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testMultipleCustomersWithInvoicesQuery()
{
$query =
<<<QUERY
{
customer
{
orders {
items {
status
total {
grand_total {
value
currency
}
}
invoices {
items{
product_name
product_sku
product_sale_price {
value
currency
}
quantity_invoiced
}
total {
subtotal {
value
currency
}
grand_total {
value
currency
}
total_shipping {
value
currency
}
}
}
}
}
}
}
QUERY;
$currentEmail = 'customer@search.example.com';
$currentPassword = 'password';
$response = $this->graphQlQuery(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
$expectedOrdersData = [
'status' => 'Processing',
'grand_total' => 100.00
];
$expectedInvoiceData = [
[
'items' => [
[
'product_name' => 'Simple Product',
'product_sku' => 'simple',
'product_sale_price' => [
'value' => 10,
'currency' => 'USD'
],
'quantity_invoiced' => 1
]
],
'total' => [
'subtotal' => [
'value' => 100,
'currency' => 'USD'
],
'grand_total' => [
'value' => 100,
'currency' => 'USD'
],
'total_shipping' => [
'value' => 0,
'currency' => 'USD'
]
]
]
];
$this->assertOrdersData($response['customer']['orders']['items'], $expectedOrdersData);
$invoices = $response['customer']['orders']['items'][0]['invoices'];
$this->assertResponseFields($invoices, $expectedInvoiceData);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple_with_url_key.php
* @magentoApiDataFixture Magento/GraphQl/Tax/_files/tax_rule_for_region_1.php
* @magentoApiDataFixture Magento/GraphQl/Tax/_files/tax_calculation_shipping_and_order_display_settings.php
* @magentoApiDataFixture Magento/SalesRule/_files/cart_rule_10_percent_off_with_discount_on_shipping.php
*/
public function testInvoiceForCustomerWithTaxesAndDiscounts()
{
$quantity = 2;
$sku = 'simple1';
$cartId = $this->createEmptyCart();
$this->addProductToCart($cartId, $quantity, $sku);
$this->setBillingAddress($cartId);
$shippingMethod = $this->setShippingAddress($cartId);
$paymentMethod = $this->setShippingMethod($cartId, $shippingMethod);
$this->setPaymentMethod($cartId, $paymentMethod);
$orderNumber = $this->placeOrder($cartId);
$this->prepareInvoice($orderNumber, 2);
$customerOrderResponse = $this->getCustomerInvoicesBasedOnOrderNumber($orderNumber);
$customerOrderItem = $customerOrderResponse[0];
$invoice = $customerOrderItem['invoices'][0];
$this->assertEquals(3, $invoice['total']['discounts'][0]['amount']['value']);
$this->assertEquals('USD', $invoice['total']['discounts'][0]['amount']['currency']);
$this->assertEquals(
'Discount Label for 10% off',
$invoice['total']['discounts'][0]['label']
);
$this->assertTotalsAndShippingWithTaxesAndDiscounts($customerOrderItem['invoices'][0]['total']);
$this->deleteOrder();
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple_with_url_key.php
* @magentoApiDataFixture Magento/GraphQl/Tax/_files/tax_rule_for_region_1.php
* @magentoApiDataFixture Magento/GraphQl/Tax/_files/tax_calculation_shipping_and_order_display_settings.php
* @magentoApiDataFixture Magento/SalesRule/_files/cart_rule_10_percent_off_with_discount_on_shipping.php
*/
public function testPartialInvoiceForCustomerWithTaxesAndDiscounts()
{
$quantity = 2;
$sku = 'simple1';
$cartId = $this->createEmptyCart();
$this->addProductToCart($cartId, $quantity, $sku);
$this->setBillingAddress($cartId);
$shippingMethod = $this->setShippingAddress($cartId);
$paymentMethod = $this->setShippingMethod($cartId, $shippingMethod);
$this->setPaymentMethod($cartId, $paymentMethod);
$orderNumber = $this->placeOrder($cartId);
$this->prepareInvoice($orderNumber, 1);
$customerOrderResponse = $this->getCustomerInvoicesBasedOnOrderNumber($orderNumber);
$customerOrderItem = $customerOrderResponse[0];
$invoice = $customerOrderItem['invoices'][0];
$invoiceItem = $invoice['items'][0];
$this->assertEquals(1, $invoiceItem['discounts'][0]['amount']['value']);
$this->assertEquals('USD', $invoiceItem['discounts'][0]['amount']['currency']);
$this->assertEquals('Discount Label for 10% off', $invoiceItem['discounts'][0]['label']);
$this->assertEquals(2, $invoice['total']['discounts'][0]['amount']['value']);
$this->assertEquals('USD', $invoice['total']['discounts'][0]['amount']['currency']);
$this->assertEquals(
'Discount Label for 10% off',
$invoice['total']['discounts'][0]['label']
);
$this->assertTotalsAndShippingWithTaxesAndDiscountsForOneQty($customerOrderItem['invoices'][0]['total']);
$this->deleteOrder();
}
#[
DataFixture(Customer::class, ['email' => 'customer@search.example.com'], as: 'customer'),
DataFixture(ProductFixture::class, as: 'product'),
DataFixture(CustomerCart::class, ['customer_id' => '$customer.id$'], as: 'cart'),
DataFixture(AddProductToCartFixture::class, ['cart_id' => '$cart.id$', 'product_id' => '$product.id$']),
DataFixture(SetBillingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetShippingAddressFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetGuestEmailFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetDeliveryMethodFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(SetPaymentMethodFixture::class, ['cart_id' => '$cart.id$']),
DataFixture(PlaceOrderFixture::class, ['cart_id' => '$cart.id$'], 'order'),
DataFixture(InvoiceFixture::class, ['order_id' => '$order.id$'], 'invoice'),
DataFixture(InvoiceCommentFixture::class, [
'parent_id' => '$invoice.id$',
'comment' => 'visible_comment',
'is_visible_on_front' => 1,
]),
DataFixture(InvoiceCommentFixture::class, [
'parent_id' => '$invoice.id$',
'comment' => 'non_visible_comment',
'is_visible_on_front' => 0,
]),
]
public function testInvoiceCommentsQuery()
{
$query =
<<<QUERY
{
customer {
orders {
items {
invoices {
comments {
message
timestamp
}
}
}
}
}
}
QUERY;
$currentEmail = 'customer@search.example.com';
$currentPassword = 'password';
$response = $this->graphQlQuery(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
$invoice = $response['customer']['orders']['items'][0]['invoices'][0];
$this->assertCount(1, $invoice['comments']);
$this->assertEquals('visible_comment', $invoice['comments'][0]['message']);
$this->assertNotEmpty($invoice['comments'][0]['timestamp']);
}
/**
* Prepare invoice for the order
*
* @param string $orderNumber
* @param int|null $qty
*/
private function prepareInvoice(string $orderNumber, int $qty = null)
{
/** @var \Magento\Sales\Model\Order $order */
$order = Bootstrap::getObjectManager()
->create(\Magento\Sales\Model\Order::class)->loadByIncrementId($orderNumber);
$orderItem = current($order->getItems());
$orderService = Bootstrap::getObjectManager()->create(
\Magento\Sales\Api\InvoiceManagementInterface::class
);
$invoice = $orderService->prepareInvoice($order, [$orderItem->getId() => $qty]);
$invoice->register();
$order = $invoice->getOrder();
$order->setIsInProcess(true);
$transactionSave = Bootstrap::getObjectManager()
->create(\Magento\Framework\DB\Transaction::class);
$transactionSave->addObject($invoice)->addObject($order)->save();
}
/**
* Check order totals an shipping amounts with taxes
*
* @param array $customerOrderItemTotal
*/
private function assertTotalsAndShippingWithTaxesAndDiscounts(array $customerOrderItemTotal): void
{
$this->assertCount(1, $customerOrderItemTotal['taxes']);
$taxData = $customerOrderItemTotal['taxes'][0];
$this->assertEquals('USD', $taxData['amount']['currency']);
$this->assertEquals(2.03, $taxData['amount']['value']);
$this->assertEquals('US-TEST-*-Rate-1', $taxData['title']);
$this->assertEquals(7.5, $taxData['rate']);
unset($customerOrderItemTotal['taxes']);
$assertionMap = [
'base_grand_total' => ['value' => 29.1, 'currency' =>'USD'],
'grand_total' => ['value' => 29.1, 'currency' =>'USD'],
'total_tax' => ['value' => 2.03, 'currency' =>'USD'],
'subtotal' => ['value' => 20, 'currency' =>'USD'],
'total_shipping' => ['value' => 10, 'currency' =>'USD'],
'shipping_handling' => [
'amount_including_tax' => ['value' => 10.75, 'currency' =>'USD'],
'amount_excluding_tax' => ['value' => 10, 'currency' =>'USD'],
'total_amount' => ['value' => 10, 'currency' =>'USD'],
'taxes'=> [
0 => [
'amount'=>['value' => 0.68],
'title' => 'US-TEST-*-Rate-1',
'rate' => 7.5
]
],
'discounts'=> [
0 => ['amount'=>['value' => 1, 'currency'=> 'USD']]
],
]
];
$this->assertResponseFields($customerOrderItemTotal, $assertionMap);
}
/**
* Check order totals an shipping amounts with taxes
*
* @param array $customerOrderItemTotal
*/
private function assertTotalsAndShippingWithTaxesAndDiscountsForOneQty(array $customerOrderItemTotal): void
{
$this->assertCount(1, $customerOrderItemTotal['taxes']);
$taxData = $customerOrderItemTotal['taxes'][0];
$this->assertEquals('USD', $taxData['amount']['currency']);
$this->assertEquals(1.36, $taxData['amount']['value']);
$this->assertEquals('US-TEST-*-Rate-1', $taxData['title']);
$this->assertEquals(7.5, $taxData['rate']);
unset($customerOrderItemTotal['taxes']);
$assertionMap = [
'base_grand_total' => ['value' => 19.43, 'currency' =>'USD'],
'grand_total' => ['value' => 19.43, 'currency' =>'USD'],
'total_tax' => ['value' => 1.36, 'currency' =>'USD'],
'subtotal' => ['value' => 10, 'currency' =>'USD'],
'total_shipping' => ['value' => 10, 'currency' =>'USD'],
'shipping_handling' => [
'amount_including_tax' => ['value' => 10.75, 'currency' =>'USD'],
'amount_excluding_tax' => ['value' => 10, 'currency' =>'USD'],
'total_amount' => ['value' => 10, 'currency' =>'USD'],
'taxes'=> [
0 => [
'amount'=>['value' => 0.68],
'title' => 'US-TEST-*-Rate-1',
'rate' => 7.5
]
],
'discounts'=> [['amount'=>['value' => 1, 'currency'=> 'USD']]
],
]
];
$this->assertResponseFields($customerOrderItemTotal, $assertionMap);
}
/**
* Create an empty cart with GraphQl mutation
*
* @return string
*/
private function createEmptyCart(): string
{
$query = <<<QUERY
mutation {
createEmptyCart
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$response = $this->graphQlMutation(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
return $response['createEmptyCart'];
}
/**
* Add product to cart with GraphQl query
*
* @param string $cartId
* @param float $qty
* @param string $sku
* @return void
*/
private function addProductToCart(string $cartId, float $qty, string $sku): void
{
$query = <<<QUERY
mutation {
addSimpleProductsToCart(
input: {
cart_id: "{$cartId}"
cart_items: [
{
data: {
quantity: {$qty}
sku: "{$sku}"
}
}
]
}
) {
cart {items{quantity product {sku}}}}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$this->graphQlMutation(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
}
/**
* Set billing address on cart with GraphQL mutation
*
* @param string $cartId
* @return void
*/
private function setBillingAddress(string $cartId): void
{
$query = <<<QUERY
mutation {
setBillingAddressOnCart(
input: {
cart_id: "{$cartId}"
billing_address: {
address: {
firstname: "John"
lastname: "Smith"
company: "Test company"
street: ["test street 1", "test street 2"]
city: "Texas City"
postcode: "78717"
telephone: "5123456677"
region: "TX"
country_code: "US"
}
}
}
) {
cart {
billing_address {
__typename
}
}
}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$this->graphQlMutation(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
}
/**
* Set shipping address on cart with GraphQl query
*
* @param string $cartId
* @return array
*/
private function setShippingAddress(string $cartId): array
{
$query = <<<QUERY
mutation {
setShippingAddressesOnCart(
input: {
cart_id: "$cartId"
shipping_addresses: [
{
address: {
firstname: "test shipFirst"
lastname: "test shipLast"
company: "test company"
street: ["test street 1", "test street 2"]
city: "Montgomery"
region: "AL"
postcode: "36013"
country_code: "US"
telephone: "3347665522"
}
}
]
}
) {
cart {
shipping_addresses {
available_shipping_methods {
carrier_code
method_code
amount {value}
}
}
}
}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$response = $this->graphQlMutation(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
$shippingAddress = current($response['setShippingAddressesOnCart']['cart']['shipping_addresses']);
$availableShippingMethod = current($shippingAddress['available_shipping_methods']);
return $availableShippingMethod;
}
/**
* Set shipping method on cart with GraphQl mutation
*
* @param string $cartId
* @param array $method
* @return array
*/
private function setShippingMethod(string $cartId, array $method): array
{
$query = <<<QUERY
mutation {
setShippingMethodsOnCart(input: {
cart_id: "{$cartId}",
shipping_methods: [
{
carrier_code: "{$method['carrier_code']}"
method_code: "{$method['method_code']}"
}
]
}) {
cart {
available_payment_methods {
code
title
}
}
}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$response = $this->graphQlMutation(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
$availablePaymentMethod = current($response['setShippingMethodsOnCart']['cart']['available_payment_methods']);
return $availablePaymentMethod;
}
/**
* Set payment method on cart with GrpahQl mutation
*
* @param string $cartId
* @param array $method
* @return void
*/
private function setPaymentMethod(string $cartId, array $method): void
{
$query = <<<QUERY
mutation {
setPaymentMethodOnCart(
input: {
cart_id: "{$cartId}"
payment_method: {
code: "{$method['code']}"
}
}
) {
cart {selected_payment_method {code}}
}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$this->graphQlMutation(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
}
/**
* Place order using GraphQl mutation
*
* @param string $cartId
* @return string
*/
private function placeOrder(string $cartId): string
{
$query = <<<QUERY
mutation {
placeOrder(
input: {
cart_id: "{$cartId}"
}
) {
order {
order_number
}
}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$response = $this->graphQlMutation(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
return $response['placeOrder']['order']['order_number'];
}
/**
* Get customer order query
*
* @param string $orderNumber
* @return array
*/
private function getCustomerInvoicesBasedOnOrderNumber($orderNumber): array
{
$query =
<<<QUERY
{
customer {
email
orders(filter:{number:{eq:"{$orderNumber}"}}) {
total_count
items {
status
total {
grand_total{value currency}
}
invoices {
items{
product_name product_sku product_sale_price{value currency}quantity_invoiced
discounts {amount{value currency} label}
}
total {
base_grand_total{value currency}
grand_total{value currency}
total_tax{value currency}
subtotal { value currency }
taxes {amount{value currency} title rate}
discounts {amount{value currency} label}
total_shipping{value currency}
shipping_handling
{
amount_including_tax{value currency}
amount_excluding_tax{value currency}
total_amount{value currency}
taxes {amount{value} title rate}
discounts {amount{value currency}}
}
}
}
}
}
}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$response = $this->graphQlQuery(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
$this->assertArrayHasKey('orders', $response['customer']);
$this->assertArrayHasKey('items', $response['customer']['orders']);
return $response['customer']['orders']['items'];
}
private function assertOrdersData($response, $expectedOrdersData): void
{
$actualData = $response[0];
$this->assertEquals(
$expectedOrdersData['grand_total'],
$actualData['total']['grand_total']['value'],
"grand_total is different than the expected for order"
);
$this->assertEquals(
$expectedOrdersData['status'],
$actualData['status'],
"status is different than the expected for order"
);
}
/**
* Clean up orders
*
* @return void
*/
private function deleteOrder(): void
{
/** @var Registry $registry */
$registry = Bootstrap::getObjectManager()->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var $order \Magento\Sales\Model\Order */
$orderCollection = Bootstrap::getObjectManager()->create(Collection::class);
foreach ($orderCollection as $order) {
$this->orderRepository->delete($order);
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
}
}
@@ -0,0 +1,134 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Exception;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class OrdersTest
*/
class OrdersTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Sales/_files/orders_with_customer.php
*/
public function testOrdersQuery()
{
$query =
<<<QUERY
query {
customerOrders {
items {
order_number
grand_total
status
}
}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$response = $this->graphQlQuery($query, [], '', $this->getCustomerAuthHeaders($currentEmail, $currentPassword));
$expectedData = [
[
'order_number' => '100000002',
'status' => 'processing',
'grand_total' => 120.00
],
[
'order_number' => '100000003',
'status' => 'processing',
'grand_total' => 130.00
],
[
'order_number' => '100000004',
'status' => 'closed',
'grand_total' => 140.00
],
[
'order_number' => '100000005',
'status' => 'complete',
'grand_total' => 150.00
],
[
'order_number' => '100000006',
'status' => 'complete',
'grand_total' => 160.00
]
];
$actualData = $response['customerOrders']['items'];
foreach ($expectedData as $key => $data) {
$this->assertEquals(
$data['order_number'],
$actualData[$key]['order_number'],
"order_number is different than the expected for order - " . $data['order_number']
);
$this->assertEquals(
$data['grand_total'],
$actualData[$key]['grand_total'],
"grand_total is different than the expected for order - " . $data['order_number']
);
$this->assertEquals(
$data['status'],
$actualData[$key]['status'],
"status is different than the expected for order - " . $data['order_number']
);
}
}
/**
*/
public function testOrdersQueryNotAuthorized()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$query = <<<QUERY
{
customerOrders {
items {
increment_id
grand_total
}
}
}
QUERY;
$this->graphQlQuery($query);
}
/**
* @param string $email
* @param string $password
* @return array
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
}
@@ -0,0 +1,338 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Magento\CatalogInventory\Model\StockRegistryStorage;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* Test Reorder with and without products overlay in shopping cart.
*/
class ReorderConfigurableWithVariationsTest extends GraphQlAbstract
{
/**
* Customer Id
*/
private const CUSTOMER_ID = 1;
/**
* Order Number
*/
private const ORDER_NUMBER = '100000001';
/**
* Customer email
*/
private const CUSTOMER_EMAIL = 'customer@example.com';
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var CartRepositoryInterface
*/
private $cartRepository;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
// be sure previous tests didn't left customer quote
/** @var CartRepositoryInterface $cartRepository */
$this->cartRepository = Bootstrap::getObjectManager()->get(CartRepositoryInterface::class);
try {
$quote = $this->cartRepository->getForCustomer(self::CUSTOMER_ID);
$this->cartRepository->delete($quote);
} catch (NoSuchEntityException $e) {
}
}
/**
* @magentoApiDataFixture Magento/Sales/_files/order_with_two_configurable_variations.php
*/
public function testVariations()
{
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $repository */
$productRepository = Bootstrap::getObjectManager()
->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productSku = 'simple_20';
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $productRepository->get($productSku);
$this->assertValidVariations();
$this->assertWithOutOfStockVariation($productRepository, $product);
}
/**
* Assert 2 variations of configurable product.
*
* @return void
* @throws NoSuchEntityException
*/
private function assertValidVariations(): void
{
$response = $this->makeReorderForDefaultCustomer(self::ORDER_NUMBER);
$expectedResponse = [
'userInputErrors' => [],
'cart' => [
'email' => 'customer@example.com',
'total_quantity' => 2,
'items' => [
[
'quantity' => 1,
'product' => [
'sku' => 'configurable',
],
'configurable_options' => [
[
'option_label' => 'Test Configurable',
'value_label' => 'Option 1',
]
],
],
[
'quantity' => 1,
'product' => [
'sku' => 'configurable',
],
'configurable_options' => [
[
'option_label' => 'Test Configurable',
'value_label' => 'Option 2',
],
],
],
],
],
];
$this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse);
$this->cartRepository->delete($this->cartRepository->getForCustomer(self::CUSTOMER_ID));
}
/**
* Assert reorder with out of stock variation.
*
* @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
* @param \Magento\Catalog\Api\Data\ProductInterface $product
* @return void
* @throws NoSuchEntityException
* @throws \Magento\Framework\Exception\CouldNotSaveException
* @throws \Magento\Framework\Exception\InputException
* @throws \Magento\Framework\Exception\StateException
* @throws NoSuchEntityException
*/
private function assertWithOutOfStockVariation(
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Catalog\Api\Data\ProductInterface $product
): void {
/** @var $stockRegistryStorage StockRegistryStorage */
$stockRegistryStorage = Bootstrap::getObjectManager()->get(StockRegistryStorage::class);
// clean stock registry
$stockRegistryStorage->clean();
// make product available in stock but disable and make reorder
$product->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 0,
'is_qty_decimal' => 0,
'is_in_stock' => 0,
]
);
$productRepository->save($product);
$response = $this->makeReorderForDefaultCustomer(self::ORDER_NUMBER);
$this->assetProductNotSalable($response);
$this->cartRepository->delete($this->cartRepository->getForCustomer(self::CUSTOMER_ID));
}
/**
* Assert reorder with "out of stock" variation.
*
* @magentoApiDataFixture Magento/Sales/_files/order_with_two_configurable_variations.php
* @return void
* @throws \Magento\Framework\Exception\StateException
* @throws NoSuchEntityException
*/
public function testWithDeletedVariation(): void
{
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $repository */
$productRepository = Bootstrap::getObjectManager()
->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productSku = 'simple_20';
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $productRepository->get($productSku);
// delete a product and make reorder
/** @var \Magento\Framework\Registry $registry */
$registry = Bootstrap::getObjectManager()
->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$productRepository->delete($product);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
$response = $this->makeReorderForDefaultCustomer(self::ORDER_NUMBER);
$this->assetProductUndefined($response);
$this->cartRepository->delete($this->cartRepository->getForCustomer(self::CUSTOMER_ID));
}
/**
* Assert that variation is not salable.
*
* @param array $response
* @return void
*/
private function assetProductNotSalable(array $response)
{
$expectedResponse = [
'userInputErrors' => [
[
'path' => [
'orderNumber',
],
'code' => 'NOT_SALABLE',
],
],
'cart' => [
'email' => 'customer@example.com',
'total_quantity' => 1,
'items' => [
[
'quantity' => 1,
'product' => [
'sku' => 'configurable',
],
'configurable_options' => [
[
'option_label' => 'Test Configurable',
'value_label' => 'Option 1',
],
],
],
],
],
];
$this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse);
}
/**
* Assert condition that variation is undefined.
*
* @param array $response
* @return void
*/
private function assetProductUndefined(array $response): void
{
$expectedResponse = [
'userInputErrors' => [
[
'path' => [
'orderNumber',
],
'code' => 'UNDEFINED',
],
],
'cart' => [
'email' => 'customer@example.com',
'total_quantity' => 1,
'items' => [
[
'quantity' => 1,
'product' => [
'sku' => 'configurable',
],
'configurable_options' => [
[
'option_label' => 'Test Configurable',
'value_label' => 'Option 1',
],
],
],
],
],
];
$this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse);
}
/**
* @param string $email
* @param string $password
* @return array
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
/**
* Execute GraphQL Mutation for default customer (make reorder)
*
* @param string $orderId
* @return array|bool|float|int|string
* @throws \Exception
*/
private function makeReorderForDefaultCustomer(string $orderId = self::ORDER_NUMBER)
{
$query = $this->getQuery($orderId);
$currentPassword = 'password';
return $this->graphQlMutation(
$query,
[],
'',
$this->getCustomerAuthHeaders(self::CUSTOMER_EMAIL, $currentPassword)
);
}
/**
* @param string $orderNumber
* @return string
*/
protected function getQuery($orderNumber): string
{
return
<<<MUTATION
mutation {
reorderItems(orderNumber: "{$orderNumber}") {
userInputErrors {
path
code
}
cart {
email
total_quantity
items {
quantity
product {
sku
}
... on ConfigurableCartItem {
configurable_options {
option_label
value_label
}
}
}
}
}
}
MUTATION;
}
}
@@ -0,0 +1,214 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test Reorder with different types of product.
*/
class ReorderMultipleProductsTest extends GraphQlAbstract
{
/**
* Customer Id
*/
private const CUSTOMER_ID = 1;
/**
* Order Number
*/
private const ORDER_NUMBER = '100000001';
/**
* Customer email
*/
private const CUSTOMER_EMAIL = 'customer@example.com';
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
// be sure previous tests didn't left customer quote
/** @var CartRepositoryInterface $cartRepository */
$cartRepository = Bootstrap::getObjectManager()->get(CartRepositoryInterface::class);
try {
$quote = $cartRepository->getForCustomer(self::CUSTOMER_ID);
$cartRepository->delete($quote);
} catch (NoSuchEntityException $e) {
}
}
/**
* @magentoApiDataFixture Magento/Sales/_files/order_with_different_types_of_product.php
*/
public function testMutplipleProducts()
{
$response = $this->makeReorderForDefaultCustomer(self::ORDER_NUMBER);
$expectedResponse = [
'userInputErrors' => [],
'cart' => [
'email' => 'customer@example.com',
'total_quantity' => 5,
'items' => [
[
'quantity' => 1,
'product' => [
'sku' => 'simple-2',
],
],
[
'quantity' => 1,
'product' => [
'sku' => 'configurable-1',
],
'configurable_options' => [
[
'option_label' => 'Test Configurable',
'value_label' => 'Option 1',
],
],
],
[
'quantity' => 1,
'product' =>
[
'sku' => 'virtual_product',
],
],
[
'quantity' => 1,
'product' => [
'sku' => 'bundle-product-radio-required-option',
],
'bundle_options' => [
[
'label' => 'Radio Options',
'type' => 'radio',
'values' => [
[
'label' => 'Simple Product',
'price' => 10,
'quantity' => 1,
],
],
],
],
],
[
'quantity' => 1,
'product' => [
'sku' => 'downloadable-product',
],
'links' => [
[
'title' => 'Downloadable Product Link',
],
],
],
],
],
];
$this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse);
}
/**
* @param string $email
* @param string $password
* @return array
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
/**
* Execute GraphQL Mutation for default customer (make reorder)
*
* @param string $orderId
* @return array|bool|float|int|string
* @throws \Exception
*/
private function makeReorderForDefaultCustomer(string $orderId = self::ORDER_NUMBER)
{
$query = $this->getQuery($orderId);
$currentPassword = 'password';
return $this->graphQlMutation(
$query,
[],
'',
$this->getCustomerAuthHeaders(self::CUSTOMER_EMAIL, $currentPassword)
);
}
/**
* @param string $orderNumber
* @return string
*/
protected function getQuery($orderNumber): string
{
return
<<<MUTATION
mutation {
reorderItems(orderNumber: "{$orderNumber}") {
userInputErrors {
path
code
}
cart {
email
total_quantity
items {
quantity
product {
sku
}
... on ConfigurableCartItem {
configurable_options {
option_label
value_label
}
}
... on BundleCartItem {
bundle_options {
label
type
values {
label
price
quantity
}
}
}
... on DownloadableCartItem {
links {
title
}
}
}
}
}
}
MUTATION;
}
}
@@ -0,0 +1,208 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test Reorder with and without products overlay in shopping cart.
*/
class ReorderOverlayProductTest extends GraphQlAbstract
{
/**
* Customer Id
*/
private const CUSTOMER_ID = 1;
/**
* Order Number
*/
private const ORDER_NUMBER = '100000001';
/**
* Customer email
*/
private const CUSTOMER_EMAIL = 'customer@example.com';
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
// be sure previous tests didn't left customer quote
/** @var CartRepositoryInterface $cartRepository */
$cartRepository = Bootstrap::getObjectManager()->get(CartRepositoryInterface::class);
try {
$quote = $cartRepository->getForCustomer(self::CUSTOMER_ID);
$cartRepository->delete($quote);
} catch (NoSuchEntityException $e) {
}
}
/**
* @magentoApiDataFixture Magento/Sales/_files/customer_order_item_with_product_and_custom_options.php
* @magentoApiDataFixture Magento/Catalog/_files/product_simple_without_custom_options.php
* @throws NoSuchEntityException
*/
public function testWithoutOverlay()
{
$response = $this->addProductToCartAndReorder();
$expectedResponse = [
'userInputErrors' => [],
'cart' => [
'email' => 'customer@example.com',
'total_quantity' => 2,
'items' => [
[
'quantity' => 1,
'product' => [
'sku' => 'simple-2',
],
],
[
'quantity' => 1,
'product' => [
'sku' => 'simple',
],
],
],
],
];
$this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse);
}
/**
* @magentoApiDataFixture Magento/Sales/_files/order_with_two_simple_products.php
* @throws NoSuchEntityException
*/
public function testWithOverlay()
{
$response = $this->addProductToCartAndReorder();
$expectedResponse = [
'userInputErrors' => [],
'cart' => [
'email' => 'customer@example.com',
'total_quantity' => 3,
'items' => [
[
'quantity' => 2,
'product' => [
'sku' => 'simple-2',
],
],
[
'quantity' => 1,
'product' => [
'sku' => 'simple',
],
],
],
],
];
$this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse);
}
/**
* @return array|bool|float|int|string
* @throws NoSuchEntityException
* @throws \Exception
*/
private function addProductToCartAndReorder()
{
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = Bootstrap::getObjectManager()
->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$product = $productRepository->get('simple-2');
/** @var CartRepositoryInterface $cartRepository */
$cartRepository = Bootstrap::getObjectManager()->get(CartRepositoryInterface::class);
/** @var \Magento\QuoteGraphQl\Model\Cart\CreateEmptyCartForCustomer $emptyCartForCustomer */
$emptyCartForCustomer = Bootstrap::getObjectManager()
->create(\Magento\QuoteGraphQl\Model\Cart\CreateEmptyCartForCustomer::class);
$emptyCartForCustomer->execute(self::CUSTOMER_ID);
$quote = $cartRepository->getForCustomer(self::CUSTOMER_ID);
$quote->addProduct($product, 1);
$cartRepository->save($quote);
return $this->makeReorderForDefaultCustomer(self::ORDER_NUMBER);
}
/**
* @param string $email
* @param string $password
* @return array
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
/**
* Execute GraphQL Mutation for default customer (make reorder)
*
* @param string $orderId
* @return array|bool|float|int|string
* @throws \Exception
*/
private function makeReorderForDefaultCustomer(string $orderId = self::ORDER_NUMBER)
{
$query = $this->getQuery($orderId);
$currentPassword = 'password';
return $this->graphQlMutation(
$query,
[],
'',
$this->getCustomerAuthHeaders(self::CUSTOMER_EMAIL, $currentPassword)
);
}
/**
* @param string $orderNumber
* @return string
*/
protected function getQuery($orderNumber): string
{
return
<<<MUTATION
mutation {
reorderItems(orderNumber: "{$orderNumber}") {
userInputErrors {
path
code
}
cart {
email
total_quantity
items {
quantity
product {
sku
}
}
}
}
}
MUTATION;
}
}
@@ -0,0 +1,350 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Magento\Customer\Model\ResourceModel\CustomerRepository;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Model\QuoteRepository;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test Reorder
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ReorderTest extends GraphQlAbstract
{
/**
* Customer Id
*/
private const CUSTOMER_ID = 1;
/**
* Order Number
*/
private const ORDER_NUMBER = '100000001';
/**
* Customer email
*/
private const CUSTOMER_EMAIL = 'customer@example.com';
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->customerTokenService = Bootstrap::getObjectManager()->get(CustomerTokenServiceInterface::class);
// be sure previous tests didn't left customer quote
/** @var CartRepositoryInterface $cartRepository */
$cartRepository = Bootstrap::getObjectManager()->get(\Magento\Quote\Api\CartRepositoryInterface::class);
try {
$quote = $cartRepository->getForCustomer(self::CUSTOMER_ID);
$cartRepository->delete($quote);
} catch (NoSuchEntityException $e) {
}
}
/**
* @magentoApiDataFixture Magento/Sales/_files/customer_order_item_with_product_and_custom_options.php
*/
public function testReorderMutation()
{
$response = $this->makeReorderForDefaultCustomer();
$this->assertResponseFields(
$response['reorderItems'] ?? [],
[
'cart' => [
'email' => self::CUSTOMER_EMAIL,
'total_quantity' => 1,
'items' => [
[
'quantity' => 1,
'product' => [
'sku' => 'simple',
],
]
],
],
'userInputErrors' => []
]
);
}
/**
* @magentoApiDataFixture Magento/Sales/_files/customer_order_item_with_product_and_custom_options.php
*/
public function testReorderWithoutAuthorisedCustomer()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The current customer isn\'t authorized.');
$query = $this->getQuery(self::ORDER_NUMBER);
$this->graphQlMutation($query);
}
/**
* Test reorder when simple product is out of stock/disabled/deleted
*
* @magentoApiDataFixture Magento/Sales/_files/order_with_product_out_of_stock.php
* @throws \Magento\Framework\Exception\CouldNotSaveException
* @throws \Magento\Framework\Exception\InputException
* @throws \Magento\Framework\Exception\StateException
*/
public function testSimpleProductOutOfStock()
{
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $repository */
$productRepository = Bootstrap::getObjectManager()
->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productSku = 'simple-2';
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $productRepository->get($productSku);
$this->assertProductNotAvailable();
$this->assertDisabledProduct($productRepository, $product);
$this->assertWithDeletedProduct($productRepository, $product);
}
/**
* Test reorder when simple product qty is 0, with allowed backorders configured to below 0
*
* @magentoApiDataFixture Magento/Sales/_files/order_with_zero_qty_product.php
* @throws \Exception
*/
public function testBackorderWithOutOfStock()
{
$response = $this->makeReorderForDefaultCustomer();
$expectedResponse = [
'userInputErrors' => [],
'cart' => [
'email' => 'customer@example.com',
'total_quantity' => 2,
'items' => [
[
'quantity' => 1,
'product' => [
'sku' => 'simple'
]
],
[
'quantity' => 1,
'product' => [
'sku' => 'simple-2'
]
]
],
],
];
$this->assertResponseFields($response['reorderItems'], $expectedResponse);
}
/**
* Test reorder with low stock for simple product
*
* @magentoApiDataFixture Magento/Sales/_files/order_with_1_qty_product.php
* @throws \Exception
*/
public function testReorderWithLowStock()
{
$response = $this->makeReorderForDefaultCustomer();
$expectedResponse = [
'userInputErrors' => [
[
'path' => ['orderNumber'],
'code' => 'INSUFFICIENT_STOCK',
],
],
'cart' => [
'email' => 'customer@example.com',
'total_quantity' => 10,
'items' => [
[
'quantity' => 10,
'product' => [
'sku' => 'simple-2'
]
]
],
],
];
$this->assertResponseFields($response['reorderItems'], $expectedResponse);
$response = $this->makeReorderForDefaultCustomer();
$expectedResponse['cart']['total_quantity'] = 20;
$expectedResponse['cart']['items'][0]['quantity'] = 20;
$this->assertResponseFields($response['reorderItems'], $expectedResponse);
$customer = ObjectManager::getInstance()->get(CustomerRepository::class)
->get(self::CUSTOMER_EMAIL);
$quoteRepository = ObjectManager::getInstance()->get(QuoteRepository::class);
$quote = $quoteRepository->getActiveForCustomer($customer->getId());
$quote->setIsActive(false);
$quoteRepository->save($quote);
}
/**
* Assert that simple product is not available
*/
private function assertProductNotAvailable()
{
$response = $this->makeReorderForDefaultCustomer();
$expectedResponse = [
'userInputErrors' => [
[
'path' => [
'orderNumber'
],
'code' => 'NOT_SALABLE',
],
],
'cart' => [
'email' => 'customer@example.com',
'total_quantity' => 0,
'items' => [],
],
];
$this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse);
}
/**
* Assert reorder with disabled product.
*
* @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
* @param \Magento\Catalog\Api\Data\ProductInterface $product
* @throws \Magento\Framework\Exception\CouldNotSaveException
* @throws \Magento\Framework\Exception\InputException
* @throws \Magento\Framework\Exception\StateException
* @return void
*/
private function assertDisabledProduct(
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Catalog\Api\Data\ProductInterface $product
): void {
// make product available in stock but disable and make reorder
$product->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
$productRepository->save($product);
$this->assertProductNotAvailable();
}
/**
* Assert reorder with deleted product.
*
* @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
* @param \Magento\Catalog\Api\Data\ProductInterface $product
* @throws \Magento\Framework\Exception\StateException
* @return void
*/
private function assertWithDeletedProduct(
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Catalog\Api\Data\ProductInterface $product
): void {
// delete a product and make reorder
/** @var \Magento\Framework\Registry $registry */
$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$productRepository->delete($product);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
$expectedResponse = [
'userInputErrors' => [
[
'path' => ['orderNumber'],
'code' => 'PRODUCT_NOT_FOUND',
],
],
'cart' => [
'email' => 'customer@example.com',
'total_quantity' => 0,
'items' => [],
],
];
$response = $this->makeReorderForDefaultCustomer();
$this->assertResponseFields($response['reorderItems'] ?? [], $expectedResponse);
}
/**
* @param string $email
* @param string $password
* @return array
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function getCustomerAuthHeaders(string $email, string $password): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($email, $password);
return ['Authorization' => 'Bearer ' . $customerToken];
}
/**
* Execute GraphQL Mutation for default customer (make reorder)
*
* @param string $orderId
* @return array|bool|float|int|string
* @throws \Exception
*/
private function makeReorderForDefaultCustomer(string $orderId = self::ORDER_NUMBER)
{
$query = $this->getQuery($orderId);
$currentPassword = 'password';
return $this->graphQlMutation(
$query,
[],
'',
$this->getCustomerAuthHeaders(self::CUSTOMER_EMAIL, $currentPassword)
);
}
/**
* @param string $orderNumber
* @return string
*/
protected function getQuery($orderNumber): string
{
$query =
<<<MUTATION
mutation {
reorderItems(orderNumber: "{$orderNumber}") {
userInputErrors {
path
code
}
cart {
email
total_quantity
items {
quantity
product {
sku
}
}
}
}
}
MUTATION;
return $query;
}
}
@@ -0,0 +1,361 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Exception\AuthenticationException;
use Magento\GraphQl\GetCustomerAuthenticationHeader;
use Magento\GraphQl\Sales\Fixtures\CustomerPlaceOrder;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\ResourceModel\Order\Collection;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test for orders with bundle product
*/
class RetrieveOrdersWithBundleProductByOrderNumberTest extends GraphQlAbstract
{
/** @var OrderRepositoryInterface */
private $orderRepository;
/** @var SearchCriteriaBuilder */
private $searchCriteriaBuilder;
/** @var GetCustomerAuthenticationHeader */
private $customerAuthenticationHeader;
/** @var ProductRepositoryInterface */
private $productRepository;
protected function setUp():void
{
parent::setUp();
$objectManager = Bootstrap::getObjectManager();
$this->customerAuthenticationHeader = $objectManager->get(GetCustomerAuthenticationHeader::class);
$this->orderRepository = $objectManager->get(OrderRepositoryInterface::class);
$this->searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);
$this->productRepository = $objectManager->get(ProductRepositoryInterface::class);
}
protected function tearDown(): void
{
$this->deleteOrder();
}
/**
* Test customer order details with bundle product with child items
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Bundle/_files/bundle_product_two_dropdown_options.php
*/
public function testGetCustomerOrderBundleProduct()
{
//Place order with bundled product
$qty = 1;
$bundleSku = 'bundle-product-two-dropdown-options';
/** @var CustomerPlaceOrder $bundleProductOrderFixture */
$bundleProductOrderFixture = Bootstrap::getObjectManager()->create(CustomerPlaceOrder::class);
$orderResponse = $bundleProductOrderFixture->placeOrderWithBundleProduct(
['email' => 'customer@example.com', 'password' => 'password'],
['sku' => $bundleSku, 'quantity' => $qty]
);
$orderNumber = $orderResponse['placeOrder']['order']['order_number'];
//End place order with bundled product
$customerOrderResponse = $this->getCustomerOrderQueryBundleProduct($orderNumber);
$customerOrderItems = $customerOrderResponse[0];
$this->assertEquals("Pending", $customerOrderItems['status']);
$bundledItemInTheOrder = $customerOrderItems['items'][0];
$this->assertEquals(
'bundle-product-two-dropdown-options-simple1-simple2',
$bundledItemInTheOrder['product_sku']
);
$priceOfBundledItemInOrder = $bundledItemInTheOrder['product_sale_price']['value'];
$this->assertEquals(15, $priceOfBundledItemInOrder);
$this->assertArrayHasKey('bundle_options', $bundledItemInTheOrder);
$bundleOptionsFromResponse = $bundledItemInTheOrder['bundle_options'];
$this->assertNotEmpty($bundleOptionsFromResponse);
$this->assertEquals(2, count($bundleOptionsFromResponse));
$expectedBundleOptions =
[
[ '__typename' => 'ItemSelectedBundleOption',
'label' => 'Drop Down Option 1',
'values' => [
[
'product_sku' => 'simple1',
'product_name' => 'Simple Product1',
'quantity'=> 1,
'price' => [
'value' => 1,
'currency' => 'USD'
]
]
]
],
[ '__typename' => 'ItemSelectedBundleOption',
'label' => 'Drop Down Option 2',
'values' => [
[
'product_sku' => 'simple2',
'product_name' => 'Simple Product2',
'quantity'=> 2,
'price' => [
'value' => 2,
'currency' => 'USD'
]
]
]
],
];
$this->assertEquals($expectedBundleOptions, $bundleOptionsFromResponse);
}
/**
* Test customer order with bundle product and no telephone in address
*
* @magentoApiDataFixture Magento/Customer/_files/attribute_telephone_not_required_address.php
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Bundle/_files/bundle_product_two_dropdown_options.php
*/
public function testOrderBundleProductWithNoTelephoneInAddress()
{
//Place order with bundled product
$qty = 1;
$bundleSku = 'bundle-product-two-dropdown-options';
/** @var CustomerPlaceOrder $bundleProductOrderFixture */
$bundleProductOrderFixture = Bootstrap::getObjectManager()->create(CustomerPlaceOrder::class);
$orderResponse = $bundleProductOrderFixture->placeOrderWithBundleProduct(
['email' => 'customer@example.com', 'password' => 'password'],
['sku' => $bundleSku, 'quantity' => $qty],
['telephone' => '']
);
$orderNumber = $orderResponse['placeOrder']['order']['order_number'];
$customerOrderResponse = $this->getCustomerOrderQueryBundleProduct($orderNumber);
$customerOrderItems = $customerOrderResponse[0];
$this->assertEquals("Pending", $customerOrderItems['status']);
$billingAddress = $customerOrderItems['billing_address'];
$shippingAddress = $customerOrderItems['shipping_address'];
$this->assertNull($billingAddress['telephone']);
$this->assertNull($shippingAddress['telephone']);
}
/**
* Test customer order details with bundle products
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Bundle/_files/bundle_product_two_dropdown_options.php
* @magentoApiDataFixture Magento/GraphQl/Tax/_files/tax_rule_for_region_1.php
* @magentoApiDataFixture Magento/SalesRule/_files/cart_rule_10_percent_off_with_discount_on_shipping.php
* @magentoApiDataFixture Magento/GraphQl/Tax/_files/tax_calculation_shipping_excludeTax_order_display_settings.php
*/
public function testGetCustomerOrderBundleProductWithTaxesAndDiscounts()
{
//Place order with bundled product
$qty = 4;
$bundleSku = 'bundle-product-two-dropdown-options';
/** @var CustomerPlaceOrder $bundleProductOrderFixture */
$bundleProductOrderFixture = Bootstrap::getObjectManager()->create(CustomerPlaceOrder::class);
$orderResponse = $bundleProductOrderFixture->placeOrderWithBundleProduct(
['email' => 'customer@example.com', 'password' => 'password'],
['sku' => $bundleSku, 'quantity' => $qty]
);
$orderNumber = $orderResponse['placeOrder']['order']['order_number'];
//End place order with bundled product
$customerOrderResponse = $this->getCustomerOrderQueryBundleProduct($orderNumber);
$customerOrderItems = $customerOrderResponse[0];
$this->assertEquals("Pending", $customerOrderItems['status']);
$bundledItemInTheOrder = $customerOrderItems['items'][0];
$this->assertEquals(
'bundle-product-two-dropdown-options-simple1-simple2',
$bundledItemInTheOrder['product_sku']
);
$this->assertEquals(6, $bundledItemInTheOrder['discounts'][0]['amount']['value']);
$this->assertEquals(
'Discount Label for 10% off',
$bundledItemInTheOrder["discounts"][0]['label']
);
$this->assertArrayHasKey('bundle_options', $bundledItemInTheOrder);
$childItemsInTheOrder = $bundledItemInTheOrder['bundle_options'];
$this->assertNotEmpty($childItemsInTheOrder);
$this->assertCount(2, $childItemsInTheOrder);
$this->assertEquals('Drop Down Option 1', $childItemsInTheOrder[0]['label']);
$this->assertEquals('Drop Down Option 2', $childItemsInTheOrder[1]['label']);
$this->assertEquals('simple1', $childItemsInTheOrder[0]['values'][0]['product_sku']);
$this->assertEquals('simple2', $childItemsInTheOrder[1]['values'][0]['product_sku']);
$this->assertTotalsOnBundleProductWithTaxesAndDiscounts($customerOrderItems['total']);
}
/**
* @param array $customerOrderItemTotal
*/
private function assertTotalsOnBundleProductWithTaxesAndDiscounts(array $customerOrderItemTotal): void
{
$this->assertCount(1, $customerOrderItemTotal['taxes']);
$taxData = $customerOrderItemTotal['taxes'][0];
$this->assertEquals('USD', $taxData['amount']['currency']);
$this->assertEquals(5.4, $taxData['amount']['value']);
$this->assertEquals('US-TEST-*-Rate-1', $taxData['title']);
$this->assertEquals(7.5, $taxData['rate']);
unset($customerOrderItemTotal['taxes']);
$assertionMap = [
'base_grand_total' => ['value' => 77.4, 'currency' =>'USD'],
'grand_total' => ['value' => 77.4, 'currency' =>'USD'],
'subtotal' => ['value' => 60, 'currency' =>'USD'],
'total_tax' => ['value' => 5.4, 'currency' =>'USD'],
'total_shipping' => ['value' => 20, 'currency' =>'USD'],
'shipping_handling' => [
'amount_including_tax' => ['value' => 21.5],
'amount_excluding_tax' => ['value' => 20],
'total_amount' => ['value' => 20],
'discounts' => [
0 => ['amount'=>['value'=> 2]]
],
'taxes'=> [
0 => [
'amount'=>['value' => 1.35],
'title' => 'US-TEST-*-Rate-1',
'rate' => 7.5
]
]
],
'discounts' => [
0 => ['amount' => [ 'value' => 8, 'currency' =>'USD'],
'label' => 'Discount Label for 10% off'
]
]
];
$this->assertResponseFields($customerOrderItemTotal, $assertionMap);
}
/**
* Get customer order query for bundle order items
*
* @param $orderNumber
* @return mixed
* @throws AuthenticationException
*/
private function getCustomerOrderQueryBundleProduct($orderNumber)
{
$query =
<<<QUERY
{
customer {
orders(filter:{number:{eq:"{$orderNumber}"}}) {
total_count
items {
id
number
order_date
status
items{
__typename
product_sku
product_name
product_url_key
product_sale_price{value}
quantity_ordered
discounts{amount{value} label}
... on BundleOrderItem{
bundle_options{
__typename
label
values {
product_sku
product_name
quantity
price {
value
currency
}
}
}
}
}
total {
base_grand_total{value currency}
grand_total{value currency}
subtotal {value currency }
total_tax{value currency}
taxes {amount{value currency} title rate}
total_shipping{value currency}
shipping_handling
{
amount_including_tax{value}
amount_excluding_tax{value}
total_amount{value}
discounts{amount{value}}
taxes {amount{value} title rate}
}
discounts {amount{value currency} label}
}
billing_address {
firstname
lastname
street
city
region
region_id
postcode
telephone
country_code
}
shipping_address {
firstname
lastname
street
city
region
region_id
postcode
telephone
country_code
}
}
}
}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$response = $this->graphQlQuery(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
$this->assertArrayHasKey('orders', $response['customer']);
$this->assertArrayHasKey('items', $response['customer']['orders']);
$customerOrderItemsInResponse = $response['customer']['orders']['items'];
return $customerOrderItemsInResponse;
}
/**
* @return void
*/
private function deleteOrder(): void
{
/** @var \Magento\Framework\Registry $registry */
$registry = Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var $order \Magento\Sales\Model\Order */
$orderCollection = Bootstrap::getObjectManager()->create(Collection::class);
foreach ($orderCollection as $order) {
$this->orderRepository->delete($order);
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
}
}
@@ -0,0 +1,168 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Registry;
use Magento\GraphQl\GetCustomerAuthenticationHeader;
use Magento\GraphQl\Sales\Fixtures\CustomerPlaceOrder;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\ResourceModel\Order\Collection;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test for orders with bundle product.
*/
class RetrieveOrdersWithBundleProductOptionsTest extends GraphQlAbstract
{
/** @var OrderRepositoryInterface */
private $orderRepository;
/** @var GetCustomerAuthenticationHeader */
private $customerAuthenticationHeader;
protected function setUp(): void
{
parent::setUp();
$objectManager = Bootstrap::getObjectManager();
$this->customerAuthenticationHeader = $objectManager->get(GetCustomerAuthenticationHeader::class);
$this->orderRepository = $objectManager->get(OrderRepositoryInterface::class);
}
protected function tearDown(): void
{
$this->deleteOrder();
}
/**
* Test customer order details for bundle product single child item
*
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Bundle/_files/bundle_product_single_dropdown_option.php
*/
public function testGetCustomerOrderBundleProduct(): void
{
$qty = 1;
$bundleSku = 'bundle-product-single-dropdown-option';
/** @var CustomerPlaceOrder $bundleProductOrderFixture */
$bundleProductOrderFixture = Bootstrap::getObjectManager()->create(CustomerPlaceOrder::class);
$bundleProductOrderFixture->placeOrderWithBundleProduct(
['email' => 'customer@example.com', 'password' => 'password'],
['sku' => $bundleSku, 'quantity' => $qty]
);
$customerOrderResponse = $this->getCustomerOrderQueryBundleProduct();
$customerOrderItems = $customerOrderResponse[0];
$this->assertEquals("Pending", $customerOrderItems['status']);
$bundledItemInTheOrder = $customerOrderItems['items'][0];
$this->assertEquals(
'bundle-product-single-dropdown-option-simple1',
$bundledItemInTheOrder['product_sku']
);
$this->assertArrayHasKey('bundle_options', $bundledItemInTheOrder);
$bundleOptionsFromResponse = $bundledItemInTheOrder['bundle_options'];
$this->assertNotEmpty($bundleOptionsFromResponse);
$this->assertEquals(1, count($bundleOptionsFromResponse));
$expectedBundleOptions =
[
['__typename' => 'ItemSelectedBundleOption',
'label' => 'Drop Down Option 1',
'values' => [
[
'product_name' => 'Simple Product1',
'product_sku' => 'simple1',
'price' => [
'value' => 1,
'currency' => 'USD'
]
]
]
],
];
$this->assertEquals($expectedBundleOptions, $bundleOptionsFromResponse);
}
/**
* Get customer order query for bundle order items
*
* @return mixed
* @throws AuthenticationException
*/
private function getCustomerOrderQueryBundleProduct()
{
$query =
<<<QUERY
{
customer {
orders(pageSize: 20) {
items {
id
order_date
items {
product_name
product_sku
... on BundleOrderItem {
bundle_options {
__typename
label
values {
product_name
product_sku
price {
value
currency
}
}
}
}
}
total {
grand_total {
value
currency
}
}
status
}
}
}
}
QUERY;
$response = $this->graphQlQuery(
$query,
[],
'',
$this->customerAuthenticationHeader->execute('customer@example.com', 'password')
);
$this->assertArrayHasKey('orders', $response['customer']);
$this->assertArrayHasKey('items', $response['customer']['orders']);
return $response['customer']['orders']['items'];
}
/**
* @return void
*/
private function deleteOrder(): void
{
/** @var Registry $registry */
$registry = Bootstrap::getObjectManager()->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var $order Order */
$orderCollection = Bootstrap::getObjectManager()->create(Collection::class);
foreach ($orderCollection as $order) {
$this->orderRepository->delete($order);
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
}
}
@@ -0,0 +1,488 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Sales;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Downloadable\Api\Data\LinkInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\GraphQl\GetCustomerAuthenticationHeader;
use Magento\GraphQl\Sales\Fixtures\CustomerPlaceOrderWithDownloadable;
use Magento\Sales\Api\CreditmemoRepositoryInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\CreditmemoFactory;
use Magento\Sales\Model\ResourceModel\Order\Collection as OrderCollection;
use Magento\Sales\Model\ResourceModel\Order\Creditmemo\Collection as CreditmemoCollection;
use Magento\Sales\Model\Service\CreditmemoService;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Sales\Model\Order\Creditmemo\ItemFactory;
use Magento\Framework\Registry;
use Magento\Framework\DB\Transaction;
use Magento\Sales\Api\InvoiceManagementInterface;
/**
* Tests downloadable product fields in Orders, Invoices, CreditMemo and Shipments
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class RetrieveOrdersWithDownloadableProductTest extends GraphQlAbstract
{
/** @var OrderRepositoryInterface */
private $orderRepository;
/** @var SearchCriteriaBuilder */
private $searchCriteriaBuilder;
/** @var GetCustomerAuthenticationHeader */
private $customerAuthenticationHeader;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var CreditmemoService */
private $creditMemoService;
/** @var Order */
private $order;
/** @var CreditmemoFactory */
private $creditMemoFactory;
/** @var ItemFactory */
private $creditmemoItemFactory;
/** @var CustomerPlaceOrderWithDownloadable */
private $customerPlaceOrderWithDownloadable;
/** @var InvoiceManagementInterface */
private $invoiceManagement;
/** @var OrderCollection */
private $orderCollection;
/** @var CreditmemoRepositoryInterface */
private $creditmemoRepository;
/** @var CreditmemoCollection */
private $creditmemoCollection;
/** @var Registry */
private $registry;
/** @var Transaction */
private $transaction;
protected function setUp():void
{
$objectManager = Bootstrap::getObjectManager();
$this->customerAuthenticationHeader = $objectManager->get(GetCustomerAuthenticationHeader::class);
$this->orderRepository = $objectManager->get(OrderRepositoryInterface::class);
$this->searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);
$this->productRepository = $objectManager->get(ProductRepositoryInterface::class);
$this->order = $objectManager->create(Order::class);
$this->creditMemoService = $objectManager->get(CreditmemoService::class);
$this->creditMemoFactory = $objectManager->get(CreditmemoFactory::class);
$this->creditmemoItemFactory = $objectManager->create(ItemFactory::class);
$this->customerPlaceOrderWithDownloadable = $objectManager->create(CustomerPlaceOrderWithDownloadable::class);
$this->invoiceManagement = $objectManager->create(InvoiceManagementInterface::class);
$this->orderCollection = $objectManager->create(OrderCollection::class);
$this->creditmemoRepository = $objectManager->get(CreditmemoRepositoryInterface::class);
$this->creditmemoCollection = $objectManager->create(CreditmemoCollection::class);
$this->registry = $objectManager->get(Registry::class);
$this->transaction = $objectManager->create(Transaction::class);
}
protected function tearDown(): void
{
$this->cleanUpCreditMemos();
$this->deleteOrder();
}
/**
* @magentoApiDataFixture Magento/Downloadable/_files/order_with_customer_and_downloadable_product.php
* @magentoApiDataFixture Magento/Downloadable/_files/customer_order_with_invoice_downloadable_product.php
*/
public function testGetCustomerOrdersDownloadableProduct()
{
$orderNumber = '100000001';
$customerOrders = $this->getCustomersOrderQuery($orderNumber);
$customerOrderItemsInResponse = $customerOrders[0]['items'];
$this->assertNotEmpty($customerOrderItemsInResponse);
$downloadableItemInTheOrder = $customerOrderItemsInResponse[0];
$this->assertEquals(
'downloadable-product',
$downloadableItemInTheOrder['product_sku']
);
$priceOfDownloadableItemInOrder = $downloadableItemInTheOrder['product_sale_price']['value'];
$this->assertEquals(10, $priceOfDownloadableItemInOrder);
$this->assertArrayHasKey('downloadable_links', $downloadableItemInTheOrder);
$downloadableLinksFromResponse = $downloadableItemInTheOrder['downloadable_links'];
$this->assertNotEmpty($downloadableLinksFromResponse);
$downloadableProduct = $this->productRepository->get('downloadable-product');
/** @var LinkInterface $downloadableProductLinks */
$downloadableProductLinks = $downloadableProduct->getExtensionAttributes()->getDownloadableProductLinks();
$linkId = $downloadableProductLinks[0]->getId();
$expectedDownloadableLinksData =
[
[
'title' =>'Downloadable Product Link',
'sort_order' => 1,
'uid'=> base64_encode("downloadable/{$linkId}")
]
];
$this->assertResponseFields($expectedDownloadableLinksData, $downloadableLinksFromResponse);
// invoices assertions
$customerOrderItemsInvoicesResponse = $customerOrders[0]['invoices'][0];
$this->assertNotEmpty($customerOrderItemsInvoicesResponse);
$this->assertNotEmpty($customerOrderItemsInvoicesResponse['number']);
$customerOrderItemsInvoicesItemsResponse = $customerOrderItemsInvoicesResponse['items'][0];
$this->assertEquals('Downloadable Product', $customerOrderItemsInvoicesItemsResponse['product_name']);
$this->assertEquals(10, $customerOrderItemsInvoicesItemsResponse['product_sale_price']['value']);
$this->assertEquals(1, $customerOrderItemsInvoicesItemsResponse['quantity_invoiced']);
$downloadableItemLinks = $customerOrderItemsInvoicesItemsResponse['downloadable_links'];
$this->assertNotEmpty($downloadableItemLinks);
$downloadableProduct = $this->productRepository->get('downloadable-product');
/** @var LinkInterface $downloadableProductLinks */
$downloadableProductLinks = $downloadableProduct->getExtensionAttributes()->getDownloadableProductLinks();
$linkId = $downloadableProductLinks[0]->getId();
$expectedDownloadableLinksData =
[
[
'title' =>'Downloadable Product Link',
'sort_order' => 1,
'uid'=> base64_encode("downloadable/{$linkId}")
]
];
$this->assertResponseFields($expectedDownloadableLinksData, $downloadableItemLinks);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_purchased_separately_links.php
*/
public function testGetCustomerOrdersAndCreditMemoDownloadable()
{
//Place order with downloadable product
$qty = 1;
$downloadableSku = 'downloadable-product-with-purchased-separately-links';
$orderResponse = $this->customerPlaceOrderWithDownloadable->placeOrderWithDownloadableProduct(
['email' => 'customer@example.com', 'password' => 'password'],
['sku' => $downloadableSku, 'quantity' => $qty]
);
$orderNumber = $orderResponse['placeOrder']['order']['order_number'];
//End place order with downloadable product
// prepare invoice
$this->prepareInvoice($orderNumber, 1);
$order = $this->order->loadByIncrementId($orderNumber);
// Create a credit memo
$creditMemo = $this->creditMemoFactory->createByOrder($order, $order->getData());
$creditMemo->setOrder($order);
$creditMemo->setState(1);
$creditMemo->setSubtotal(12);
$creditMemo->setBaseSubTotal(12);
$creditMemo->setBaseGrandTotal(12);
$creditMemo->setGrandTotal(12);
$creditMemo->setAdjustment(-2.00);
$creditMemo->addComment("Test comment for downloadable refund", false, true);
$creditMemo->save();
$this->creditMemoService->refund($creditMemo, true);
$response = $this->getCustomerOrderWithCreditMemoQuery();
$downloadableProduct = $this->productRepository->get('downloadable-product-with-purchased-separately-links');
/** @var LinkInterface $downloadableProductLinks */
$downloadableProductLinks = $downloadableProduct->getExtensionAttributes()->getDownloadableProductLinks();
$linkId = $downloadableProductLinks[0]->getId();
$expectedCreditMemoData = [
[
'comments' => [
['message' => 'Test comment for downloadable refund']
],
'items' => [
[
'product_name'=> 'Downloadable Product (Links can be purchased separately)',
'product_sku' => 'downloadable-product-with-purchased-separately-links',
'product_sale_price' => ['value' => 12],
'discounts' => [],
'quantity_refunded' => 1,
'downloadable_links' => [
[
'uid'=> base64_encode("downloadable/{$linkId}"),
'title' => 'Downloadable Product Link 1']
]
]
],
'total' => [
'subtotal' => [
'value' => 12
],
'grand_total' => [
'value' => 12,
'currency' => 'USD'
],
'base_grand_total' => [
'value' => 12,
'currency' => 'USD'
],
'total_shipping' => [
'value' => 0
],
'total_tax' => [
'value' => 0
],
'shipping_handling' => [
'amount_including_tax' => [
'value' => 0
],
'amount_excluding_tax' => [
'value' => 0
],
'total_amount' => [
'value' => 0
],
'taxes' => []
],
'adjustment' => [
'value' => 2
]
]
]
];
$firstOrderItem = current($response['customer']['orders']['items'] ?? []);
$this->assertArrayHasKey('credit_memos', $firstOrderItem);
$creditMemos = $firstOrderItem['credit_memos'];
$this->assertResponseFields($creditMemos, $expectedCreditMemoData);
}
/**
* Prepare invoice for the order
*
* @param string $orderNumber
* @param int|null $qty
*/
private function prepareInvoice(string $orderNumber, int $qty = null)
{
/** @var Order $order */
$order = $this->order->loadByIncrementId($orderNumber);
$orderItem = current($order->getItems());
$invoice = $this->invoiceManagement->prepareInvoice($order, [$orderItem->getId() => $qty]);
$invoice->register();
$order = $invoice->getOrder();
$order->setIsInProcess(true);
$this->transaction->addObject($invoice)->addObject($order)->save();
}
/**
* Get customer order query with invoices
*
* @param string $orderNumber
* @return array
*/
private function getCustomersOrderQuery($orderNumber): array
{
$query =
<<<QUERY
{
customer {
orders(filter:{number:{eq:"{$orderNumber}"}}) {
total_count
items {
id
number
order_date
status
items{
__typename
product_sku
product_name
product_url_key
product_sale_price{value}
quantity_ordered
discounts{amount{value} label}
... on DownloadableOrderItem{
downloadable_links{
title
sort_order
uid
}
entered_options{value label}
product_sku
product_name
quantity_ordered
}
}
total {
base_grand_total{value currency}
grand_total{value currency}
subtotal {value currency }
total_tax{value currency}
taxes {amount{value currency} title rate}
total_shipping{value currency}
shipping_handling
{
amount_including_tax{value}
amount_excluding_tax{value}
total_amount{value}
discounts{amount{value}}
taxes {amount{value} title rate}
}
discounts {amount{value currency} label}
}
invoices {
number
items {
product_name
product_sale_price{value currency}
quantity_invoiced
... on DownloadableInvoiceItem {
downloadable_links
{
sort_order
title
uid
}
id
product_name
product_sale_price{value}
quantity_invoiced
}
}
}
}
}
}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$response = $this->graphQlQuery(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
$this->assertArrayHasKey('orders', $response['customer']);
$this->assertArrayHasKey('items', $response['customer']['orders']);
$this->assertNotEmpty($response['customer']['orders']['items']);
$customerOrderItemsInResponse = $response['customer']['orders']['items'];
return $customerOrderItemsInResponse;
}
/**
* Get CustomerOrder with credit memo details
*
* @return array
*/
private function getCustomerOrderWithCreditMemoQuery(): array
{
$query =
<<<QUERY
query {
customer {
orders {
items {
credit_memos {
comments { message}
items {
product_name
product_sku
product_sale_price {value }
discounts { amount{value currency} label }
quantity_refunded
... on DownloadableCreditMemoItem
{
product_name
discounts{amount{value}}
downloadable_links{
uid
title
}
quantity_refunded
}
}
total {
subtotal {
value
}
base_grand_total {
value
currency
}
grand_total {
value
currency
}
total_shipping {
value
}
total_tax {
value
}
shipping_handling {
amount_including_tax{value}
amount_excluding_tax{value}
total_amount{value}
taxes {amount{value} title rate}
}
adjustment {
value
}
}
}
}
}
}
}
QUERY;
$currentEmail = 'customer@example.com';
$currentPassword = 'password';
$response = $this->graphQlQuery(
$query,
[],
'',
$this->customerAuthenticationHeader->execute($currentEmail, $currentPassword)
);
return $response;
}
/**
* @return void
*/
private function deleteOrder(): void
{
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', true);
foreach ($this->orderCollection as $order) {
$this->orderRepository->delete($order);
}
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', false);
}
/**
* @return void
*/
private function cleanUpCreditMemos(): void
{
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', true);
foreach ($this->creditmemoCollection as $creditmemo) {
$this->creditmemoRepository->delete($creditmemo);
}
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', false);
}
}