Skip to content

Commit

Permalink
Merge pull request magento#4064 from magento-engcom/graphql-develop-prs
Browse files Browse the repository at this point in the history
[EngCom] Public Pull Requests - GraphQL
  • Loading branch information
naydav authored Apr 17, 2019
2 parents af6820c + 451deb9 commit 1ffd8c5
Show file tree
Hide file tree
Showing 12 changed files with 652 additions and 37 deletions.
49 changes: 49 additions & 0 deletions app/code/Magento/QuoteGraphQl/Model/Resolver/CartEmail.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?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\Exception\LocalizedException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Quote\Model\Quote;
use Magento\QuoteGraphQl\Model\Cart\GetCartForUser;

/**
* @inheritdoc
*/
class CartEmail implements ResolverInterface
{
/**
* @var GetCartForUser
*/
private $getCartForUser;

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

/**
* @inheritdoc
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
if (!isset($value['model'])) {
throw new LocalizedException(__('"model" value should be specified'));
}
/** @var Quote $cart */
$cart = $value['model'];

return $cart->getCustomerEmail();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?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\Exception\CouldNotSaveException;
use Magento\Framework\Exception\LocalizedException;
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\Framework\Validator\EmailAddress as EmailAddressValidator;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\QuoteGraphQl\Model\Cart\GetCartForUser;

/**
* @inheritdoc
*/
class SetGuestEmailOnCart implements ResolverInterface
{
/**
* @var CartRepositoryInterface
*/
private $cartRepository;

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

/**
* @var EmailAddressValidator
*/
private $emailValidator;

/**
* @param GetCartForUser $getCartForUser
* @param CartRepositoryInterface $cartRepository
* @param EmailAddressValidator $emailValidator
*/
public function __construct(
GetCartForUser $getCartForUser,
CartRepositoryInterface $cartRepository,
EmailAddressValidator $emailValidator
) {
$this->getCartForUser = $getCartForUser;
$this->cartRepository = $cartRepository;
$this->emailValidator = $emailValidator;
}

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

if (!isset($args['input']['email']) || empty($args['input']['email'])) {
throw new GraphQlInputException(__('Required parameter "email" is missing'));
}

if (false === $this->emailValidator->isValid($args['input']['email'])) {
throw new GraphQlInputException(__('Invalid email format'));
}
$email = $args['input']['email'];

$currentUserId = $context->getUserId();

if ($currentUserId !== 0) {
throw new GraphQlInputException(__('The request is not allowed for logged in customers'));
}

$cart = $this->getCartForUser->execute($maskedCartId, $currentUserId);
$cart->setCustomerEmail($email);

try {
$this->cartRepository->save($cart);
} catch (CouldNotSaveException $e) {
throw new LocalizedException(__($e->getMessage()), $e);
}

return [
'cart' => [
'model' => $cart,
],
];
}
}
11 changes: 11 additions & 0 deletions app/code/Magento/QuoteGraphQl/etc/schema.graphqls
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type Mutation {
setBillingAddressOnCart(input: SetBillingAddressOnCartInput): SetBillingAddressOnCartOutput @resolver(class: "\\Magento\\QuoteGraphQl\\Model\\Resolver\\SetBillingAddressOnCart")
setShippingMethodsOnCart(input: SetShippingMethodsOnCartInput): SetShippingMethodsOnCartOutput @resolver(class: "\\Magento\\QuoteGraphQl\\Model\\Resolver\\SetShippingMethodsOnCart")
setPaymentMethodOnCart(input: SetPaymentMethodOnCartInput): SetPaymentMethodOnCartOutput @resolver(class: "Magento\\QuoteGraphQl\\Model\\Resolver\\SetPaymentMethodOnCart")
setGuestEmailOnCart(input: SetGuestEmailOnCartInput): SetGuestEmailOnCartOutput @resolver(class: "Magento\\QuoteGraphQl\\Model\\Resolver\\SetGuestEmailOnCart")
placeOrder(input: PlaceOrderInput): PlaceOrderOutput @resolver(class: "\\Magento\\QuoteGraphQl\\Model\\Resolver\\PlaceOrder")
}

Expand Down Expand Up @@ -129,6 +130,11 @@ input PaymentMethodInput {
purchase_order_number: String @doc(description:"Purchase order number")
}

input SetGuestEmailOnCartInput {
cart_id: String!
email: String!
}

type CartPrices {
grand_total: Money
subtotal_including_tax: Money
Expand Down Expand Up @@ -169,6 +175,7 @@ type PlaceOrderOutput {
type Cart {
items: [CartItemInterface] @resolver(class: "\\Magento\\QuoteGraphQl\\Model\\Resolver\\CartItems")
applied_coupon: AppliedCoupon @resolver(class: "\\Magento\\QuoteGraphQl\\Model\\Resolver\\AppliedCoupon")
email: String @resolver (class: "\\Magento\\QuoteGraphQl\\Model\\Resolver\\CartEmail")
shipping_addresses: [CartAddress]! @resolver(class: "\\Magento\\QuoteGraphQl\\Model\\Resolver\\ShippingAddresses")
billing_address: CartAddress! @resolver(class: "\\Magento\\QuoteGraphQl\\Model\\Resolver\\BillingAddress")
available_payment_methods: [AvailablePaymentMethod] @resolver(class: "Magento\\QuoteGraphQl\\Model\\Resolver\\AvailablePaymentMethods") @doc(description: "Available payment methods")
Expand Down Expand Up @@ -272,6 +279,10 @@ type RemoveItemFromCartOutput {
cart: Cart!
}

type SetGuestEmailOnCartOutput {
cart: Cart!
}

type SimpleCartItem implements CartItemInterface @doc(description: "Simple Cart Item") {
customizable_options: [SelectedCustomizableOption] @resolver(class: "Magento\\QuoteGraphQl\\Model\\Resolver\\CustomizableOptions")
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\GraphQl\Quote\Customer;

use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;

/**
* Test for getting email from cart
*/
class GetCartEmailTest extends GraphQlAbstract
{
/**
* @var GetMaskedQuoteIdByReservedOrderId
*/
private $getMaskedQuoteIdByReservedOrderId;

/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;

protected function setUp()
{
$objectManager = Bootstrap::getObjectManager();
$this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class);
$this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class);
}

/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
*/
public function testGetCartEmail()
{
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote');

$query = $this->getQuery($maskedQuoteId);
$response = $this->graphQlQuery($query, [], '', $this->getHeaderMap());

$this->assertArrayHasKey('cart', $response);
$this->assertArrayHasKey('email', $response['cart']);
$this->assertEquals('customer@example.com', $response['cart']['email']);
}

/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @expectedException \Exception
* @expectedExceptionMessage Could not find a cart with ID "non_existent_masked_id"
*/
public function testGetCartEmailFromNonExistentCart()
{
$maskedQuoteId = 'non_existent_masked_id';
$query = $this->getQuery($maskedQuoteId);

$this->graphQlQuery($query, [], '', $this->getHeaderMap());
}

/**
* _security
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/set_guest_email.php
*/
public function testGetEmailFromGuestCart()
{
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote');
$query = $this->getQuery($maskedQuoteId);

$this->expectExceptionMessage(
"The current user cannot perform operations on cart \"{$maskedQuoteId}\""
);
$this->graphQlQuery($query, [], '', $this->getHeaderMap());
}

/**
* _security
* @magentoApiDataFixture Magento/Customer/_files/three_customers.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
*/
public function testGetEmailFromAnotherCustomerCart()
{
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('test_quote');
$query = $this->getQuery($maskedQuoteId);

$this->expectExceptionMessage(
"The current user cannot perform operations on cart \"{$maskedQuoteId}\""
);
$this->graphQlMutation($query, [], '', $this->getHeaderMap('customer3@search.example.com'));
}

/**
* @param string $maskedQuoteId
* @return string
*/
private function getQuery(string $maskedQuoteId): string
{
return <<<QUERY
{
cart(cart_id:"$maskedQuoteId") {
email
}
}
QUERY;
}

/**
* @param string $username
* @param string $password
* @return array
*/
private function getHeaderMap(string $username = 'customer@example.com', string $password = 'password'): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($username, $password);
$headerMap = ['Authorization' => 'Bearer ' . $customerToken];
return $headerMap;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,24 @@ public function testSetBillingAddressWithoutRequiredParameters(string $input, st
$this->graphQlMutation($query);
}

/**
* @return array
*/
public function dataProviderSetWithoutRequiredParameters(): array
{
return [
'missed_billing_address' => [
'cart_id: "cart_id_value"',
'Field SetBillingAddressOnCartInput.billing_address of required type BillingAddressInput!'
. ' was not provided.',
],
'missed_cart_id' => [
'billing_address: {}',
'Required parameter "cart_id" is missing'
]
];
}

/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
Expand Down Expand Up @@ -536,24 +554,6 @@ public function testSetNewBillingAddressWithRedundantStreetLine()
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}

/**
* @return array
*/
public function dataProviderSetWithoutRequiredParameters(): array
{
return [
'missed_billing_address' => [
'cart_id: "cart_id_value"',
'Field SetBillingAddressOnCartInput.billing_address of required type BillingAddressInput!'
. ' was not provided.',
],
'missed_cart_id' => [
'billing_address: {}',
'Required parameter "cart_id" is missing'
]
];
}

/**
* Verify the all the whitelisted fields for a New Address Object
*
Expand Down
Loading

0 comments on commit 1ffd8c5

Please sign in to comment.