Skip to content
This repository was archived by the owner on Dec 19, 2019. It is now read-only.

Query for retrieving shopping cart information #266

Merged
merged 5 commits into from
Feb 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,11 @@ public function execute(Quote $cart): array
];
}

$appliedCoupon = $cart->getCouponCode();

return [
'items' => $items,
'applied_coupon' => $appliedCoupon ? ['code' => $appliedCoupon] : null
];
}
}
67 changes: 67 additions & 0 deletions app/code/Magento/QuoteGraphQl/Model/Resolver/Cart.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\QuoteGraphQl\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\QuoteGraphQl\Model\Cart\GetCartForUser;
use Magento\QuoteGraphQl\Model\Cart\ExtractDataFromCart;

/**
* @inheritdoc
*/
class Cart implements ResolverInterface
{
/**
* @var ExtractDataFromCart
*/
private $extractDataFromCart;

/**
* @var GetCartForUser
*/
private $getCartForUser;

/**
* @param GetCartForUser $getCartForUser
* @param ExtractDataFromCart $extractDataFromCart
*/
public function __construct(
GetCartForUser $getCartForUser,
ExtractDataFromCart $extractDataFromCart
) {
$this->getCartForUser = $getCartForUser;
$this->extractDataFromCart = $extractDataFromCart;
}

/**
* @inheritdoc
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
if (!isset($args['cart_id'])) {
throw new GraphQlInputException(__('Required parameter "cart_id" is missing'));
}
$maskedCartId = $args['cart_id'];

$currentUserId = $context->getUserId();
$cart = $this->getCartForUser->execute($maskedCartId, $currentUserId);

$data = array_merge(
[
'cart_id' => $maskedCartId,
'model' => $cart
],
$this->extractDataFromCart->execute($cart)
);

return $data;
}
}
6 changes: 1 addition & 5 deletions app/code/Magento/QuoteGraphQl/etc/schema.graphqls
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# See COPYING.txt for license details.

type Query {
getAvailableShippingMethodsOnCart(input: AvailableShippingMethodsOnCartInput): AvailableShippingMethodsOnCartOutput @doc(description:"Returns available shipping methods for cart by address/address_id")
Cart(cart_id: String!): Cart @resolver (class: "\\Magento\\QuoteGraphQl\\Model\\Resolver\\Cart") @doc(description:"Returns information about shopping cart")
}

type Mutation {
Expand Down Expand Up @@ -84,10 +84,6 @@ input AvailableShippingMethodsOnCartInput {
address: CartAddressInput
}

type AvailableShippingMethodsOnCartOutput {
available_shipping_methods: [CheckoutShippingMethod]
}

input ApplyCouponToCartInput {
cart_id: String!
coupon_code: String!
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\GraphQl\Quote;

use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\QuoteIdToMaskedQuoteIdInterface;
use Magento\Quote\Model\ResourceModel\Quote as QuoteResource;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;

/**
* Test for getting cart information
*/
class GetCartTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;

/**
* @var QuoteResource
*/
private $quoteResource;

/**
* @var Quote
*/
private $quote;

/**
* @var QuoteIdToMaskedQuoteIdInterface
*/
private $quoteIdToMaskedId;

/**
* @inheritdoc
*/
protected function setUp()
{
$objectManager = Bootstrap::getObjectManager();
$this->quoteResource = $objectManager->create(QuoteResource::class);
$this->quote = $objectManager->create(Quote::class);
$this->quoteIdToMaskedId = $objectManager->create(QuoteIdToMaskedQuoteIdInterface::class);
$this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class);
}

/**
* @magentoApiDataFixture Magento/Checkout/_files/quote_with_items_saved.php
*/
public function testGetOwnCartForRegisteredCustomer()
{
$reservedOrderId = 'test_order_item_with_items';
$this->quoteResource->load(
$this->quote,
$reservedOrderId,
'reserved_order_id'
);

$maskedQuoteId = $this->quoteIdToMaskedId->execute((int)$this->quote->getId());
$query = $this->prepareGetCartQuery($maskedQuoteId);

$response = $this->sendRequestWithToken($query);

self::assertArrayHasKey('Cart', $response);
self::assertNotEmpty($response['Cart']['items']);
self::assertNotEmpty($response['Cart']['addresses']);
}

/**
* @magentoApiDataFixture Magento/Checkout/_files/quote_with_items_saved.php
*/
public function testGetCartFromAnotherCustomer()
{
$reservedOrderId = 'test_order_item_with_items';
$this->quoteResource->load(
$this->quote,
$reservedOrderId,
'reserved_order_id'
);


$maskedQuoteId = $this->quoteIdToMaskedId->execute((int)$this->quote->getId());
$query = $this->prepareGetCartQuery($maskedQuoteId);

self::expectExceptionMessage("The current user cannot perform operations on cart \"$maskedQuoteId\"");

$this->graphQlQuery($query);
}

/**
* @magentoApiDataFixture Magento/Checkout/_files/active_quote.php
*/
public function testGetCartForGuest()
{
$reservedOrderId = 'test_order_1';
$this->quoteResource->load(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to load Quote?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me shed some light here.
I use this fixture because we perform tests for this quote. I use this fixture since it assigns maskedQuoteId to the quote. Also, this fixture provides a guest quote (it's not assigned to a customer)
So, the flow is: we load the guest quote, we perform tests for the guest quote.

As for the model loading, we need to get maskedQuoteId somehow but we don't have a quoteId that can be used for quoteIdToMaskedId service (only reservedOrderId). So, I load the model for retrieving quoteId.

$this->quote,
$reservedOrderId,
'reserved_order_id'
);

$maskedQuoteId = $this->quoteIdToMaskedId->execute((int)$this->quote->getId());
$query = $this->prepareGetCartQuery($maskedQuoteId);

$response = $this->graphQlQuery($query);

self::assertArrayHasKey('Cart', $response);
}

public function testGetNonExistentCart()
{
$maskedQuoteId = 'non_existent_masked_id';
$query = $this->prepareGetCartQuery($maskedQuoteId);

self::expectExceptionMessage("Could not find a cart with ID \"$maskedQuoteId\"");

$this->graphQlQuery($query);
}

/**
* Generates query for setting the specified shipping method on cart
*
* @param string $maskedQuoteId
* @return string
*/
private function prepareGetCartQuery(
string $maskedQuoteId
) : string {
return <<<QUERY
{
Cart(cart_id: "$maskedQuoteId") {
applied_coupon {
code
}
items {
id
}
addresses {
firstname,
lastname,
address_type
}
}
}

QUERY;
}

/**
* Sends a GraphQL request with using a bearer token
*
* @param string $query
* @return array
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function sendRequestWithToken(string $query): array
{

$customerToken = $this->customerTokenService->createCustomerAccessToken('[email protected]', 'password');
$headerMap = ['Authorization' => 'Bearer ' . $customerToken];

return $this->graphQlQuery($query, [], '', $headerMap);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,11 @@
->setIsMultiShipping(false)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, add rollback for this fixture

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The rollback for the mentioned fixture exists (active_quote_rollback.php). As for masked id - the corresponding database entry is being removed when the quote is removed, so the current rollback works for masked ids as well (have just double checked this behavior)

->setReservedOrderId('test_order_1')
->save();

/** @var \Magento\Quote\Model\QuoteIdMask $quoteIdMask */
$quoteIdMask = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Quote\Model\QuoteIdMaskFactory::class)
->create();
$quoteIdMask->setQuoteId($quote->getId());
$quoteIdMask->setDataChanges(true);
$quoteIdMask->save();