Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[API]Add inStock serialization to productVariant #12639

Merged
merged 2 commits into from
May 17, 2021
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 @@ -6,9 +6,9 @@ Feature: Inability to add a specific product to the cart when it is out of stock

Background:
Given the store operates on a single channel in "United States"
And the store has a product "T-shirt banana" priced at "$12.54"
And the store has a product "T-shirt banana"

@ui
@ui @api
Scenario: Not being able to add a product to the cart when it is out of stock
Given the product "T-shirt banana" is out of stock
When I check this product's details
Expand Down
15 changes: 15 additions & 0 deletions src/Sylius/Behat/Context/Api/Shop/CartContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,21 @@ public function iShouldHaveEmptyCart(string $tokenValue): void
Assert::same(count($items), 0, 'There should be an empty cart');
}

/**
* @Then I should be unable to add it to the cart
*/
public function iShouldBeUnableToAddItToTheCart(): void
{
/** @var ProductVariantInterface $productVariant */
$productVariant = $this->sharedStorage->get('productVariant');

$tokenValue = $this->pickupCart();
$this->putProductVariantToCart($productVariant, $tokenValue);

$response = $this->cartsClient->getLastResponse();
Assert::same($response->getStatusCode(), 422);
Copy link
Contributor

Choose a reason for hiding this comment

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

can you check here validation message instead status code?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'd like to explain myself why I check status Code; the step is about 'unable to add it to the cart' and I dont think that this step cares why it happens (what validation message). This I think should be checked somewhere else, in add to cart validation behats 😃

}

/**
* @Then /^(this product) should have ([^"]+) "([^"]+)"$/
*/
Expand Down
15 changes: 15 additions & 0 deletions src/Sylius/Behat/Context/Api/Shop/ProductContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use Sylius\Behat\Client\ResponseCheckerInterface;
use Sylius\Behat\Service\SharedStorageInterface;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Product\Model\ProductVariantInterface;
use Sylius\Component\Taxonomy\Model\TaxonInterface;
use Symfony\Component\HttpFoundation\Request as HttpRequest;
use Webmozart\Assert\Assert;
Expand Down Expand Up @@ -58,6 +59,7 @@ public function __construct(
public function iOpenProductPage(ProductInterface $product): void
{
$this->client->show($product->getCode());
$this->sharedStorage->set('productVariant', current($product->getVariants()->getValues()));
}

/**
Expand Down Expand Up @@ -107,6 +109,19 @@ public function iShouldSeeTheProduct(string $name): void
));
}

/**
* @Then I should see that it is out of stock
*/
public function iShouldSeeItIsOutOfStock(): void
{
/** @var ProductVariantInterface $productVariant */
$productVariant = $this->sharedStorage->get('productVariant');

$variantResponse = $this->client->showByIri($this->iriConverter->getIriFromItem($productVariant));

Assert::false($this->responseChecker->getValue($variantResponse, 'inStock'));
}

/**
* @Then I should not see the product :name
*/
Expand Down
1 change: 1 addition & 0 deletions src/Sylius/Behat/Resources/config/suites.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ imports:
- suites/api/currency/managing_currencies.yml
- suites/api/currency/managing_exchange_rates.yml
- suites/api/homepage/viewing_products.yml
- suites/api/inventory/cart_inventory.yml
- suites/api/locale/managing_locales.yml
- suites/api/order/managing_orders.yml
- suites/api/payment/managing_payments.yml
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# This file is part of the Sylius package.
# (c) Paweł Jędrzejewski

default:
suites:
api_cart_inventory:
contexts:
- sylius.behat.context.hook.doctrine_orm

- sylius.behat.context.setup.channel
- sylius.behat.context.setup.product

- sylius.behat.context.transform.lexical
- sylius.behat.context.transform.product
- sylius.behat.context.transform.shared_storage

- sylius.behat.context.api.shop.cart
- sylius.behat.context.api.shop.product

arti0090 marked this conversation as resolved.
Show resolved Hide resolved
filters:
tags: "@cart_inventory && @api"
1 change: 1 addition & 0 deletions src/Sylius/Bundle/ApiBundle/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@
<argument type="service" id="api_platform.serializer.normalizer.item" />
<argument type="service" id="sylius.calculator.product_variant_price" />
<argument type="service" id="sylius.context.channel" />
<argument type="service" id="sylius.availability_checker" />
<tag name="serializer.normalizer" priority="64" />
</service>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
<service id="sylius.api.validator.adding_eligible_product_variant_to_cart" class="Sylius\Bundle\ApiBundle\Validator\Constraints\AddingEligibleProductVariantToCartValidator">
<argument type="service" id="sylius.repository.product_variant" />
<argument type="service" id="sylius.repository.order" />
<argument type="service" id="sylius.availability_checker" />
<tag name="validator.constraint_validator" alias="sylius_api_validator_adding_eligible_product_variant_to_cart" />
</service>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@ sylius:
not_exist: 'The product %productName% does not exist.'
product_variant:
not_exist: 'The product variant with %productVariantCode% does not exist.'
not_sufficient: 'The product variant with %productVariantCode% code does not have sufficient stock.'
shipment:
shipped: 'You cannot ship a shipment that was shipped before.'
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@

use Sylius\Component\Channel\Context\ChannelContextInterface;
use Sylius\Component\Channel\Context\ChannelNotFoundException;
use Sylius\Component\Core\Calculator\ProductVariantPriceCalculatorInterface;
use Sylius\Component\Core\Calculator\ProductVariantPricesCalculatorInterface;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Inventory\Checker\AvailabilityCheckerInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webmozart\Assert\Assert;
Expand All @@ -17,20 +18,25 @@ final class ProductVariantSerializer implements ContextAwareNormalizerInterface
/** @var NormalizerInterface */
private $objectNormalizer;

/** @var ProductVariantPriceCalculatorInterface */
/** @var ProductVariantPricesCalculatorInterface */
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Changed this Interface, as It shows as deprecated.

private $priceCalculator;

/** @var ChannelContextInterface */
private $channelContext;

/** @var AvailabilityCheckerInterface */
private $availabilityChecker;

public function __construct(
NormalizerInterface $objectNormalizer,
ProductVariantPriceCalculatorInterface $priceCalculator,
ChannelContextInterface $channelContext
ProductVariantPricesCalculatorInterface $priceCalculator,
ChannelContextInterface $channelContext,
AvailabilityCheckerInterface $availabilityChecker
) {
$this->objectNormalizer = $objectNormalizer;
$this->priceCalculator = $priceCalculator;
$this->channelContext = $channelContext;
$this->availabilityChecker = $availabilityChecker;
}

public function normalize($object, $format = null, array $context = [])
Expand All @@ -45,15 +51,17 @@ public function normalize($object, $format = null, array $context = [])
unset($data['price']);
}

$data['inStock'] = $this->availabilityChecker->isStockAvailable($object);
Copy link
Member

Choose a reason for hiding this comment

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

Is it also shown in api reference in swagger?


return $data;
}

public function supportsNormalization($data, $format = null, $context = []): bool
{
return $data instanceof ProductVariantInterface && $this->isAdminGetOperation($context);
return $data instanceof ProductVariantInterface && $this->isNotAdminGetOperation($context);
}

private function isAdminGetOperation(array $context): bool
private function isNotAdminGetOperation(array $context): bool
{
return !isset($context['item_operation_name']) || !($context['item_operation_name'] === 'admin_get');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ final class AddingEligibleProductVariantToCart extends Constraint
/** @var string */
public $productVariantNotExistMessage = 'sylius.product_variant.not_exist';

/** @var string */
public $productVariantNotSufficient = 'sylius.product_variant.not_sufficient';

public function validatedBy(): string
{
return 'sylius_api_validator_adding_eligible_product_variant_to_cart';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
use Sylius\Component\Inventory\Checker\AvailabilityCheckerInterface;
use Sylius\Component\Product\Repository\ProductVariantRepositoryInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
Expand All @@ -32,12 +33,17 @@ final class AddingEligibleProductVariantToCartValidator extends ConstraintValida
/** @var OrderRepositoryInterface */
private $orderRepository;

/** @var AvailabilityCheckerInterface */
private $availabilityChecker;

public function __construct(
ProductVariantRepositoryInterface $productVariantRepository,
OrderRepositoryInterface $orderRepository
OrderRepositoryInterface $orderRepository,
AvailabilityCheckerInterface $availabilityChecker
) {
$this->productVariantRepository = $productVariantRepository;
$this->orderRepository = $orderRepository;
$this->availabilityChecker = $availabilityChecker;
}

public function validate($value, Constraint $constraint)
Expand Down Expand Up @@ -79,6 +85,15 @@ public function validate($value, Constraint $constraint)
return;
}

if (!$this->availabilityChecker->isStockSufficient($productVariant, $value->quantity)) {
$this->context->addViolation(
$constraint->productVariantNotSufficient,
['%productVariantCode%' => $productVariant->getCode()]
);

return;
}

/** @var OrderInterface|null $cart */
$cart = $this->orderRepository->findCartByTokenValue($value->getOrderTokenValue());
Assert::notNull($cart);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Sylius\Component\Core\Calculator\ProductVariantPricesCalculatorInterface;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\ProductVariant;
use Sylius\Component\Inventory\Checker\AvailabilityCheckerInterface;
use Sylius\Component\Order\Model\Order;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

Expand All @@ -26,9 +27,10 @@ final class ProductVariantSerializerSpec extends ObjectBehavior
function let(
NormalizerInterface $objectNormalizer,
ProductVariantPricesCalculatorInterface $pricesCalculator,
ChannelContextInterface $channelContext
ChannelContextInterface $channelContext,
AvailabilityCheckerInterface $availabilityChecker
): void {
$this->beConstructedWith($objectNormalizer, $pricesCalculator, $channelContext);
$this->beConstructedWith($objectNormalizer, $pricesCalculator, $channelContext, $availabilityChecker);
}

function it_supports_only_product_variant_interface(): void
Expand All @@ -50,15 +52,17 @@ function it_serializes_product_variant_if_item_operation_name_is_different_that_
NormalizerInterface $objectNormalizer,
ProductVariantPricesCalculatorInterface $pricesCalculator,
ChannelInterface $channel,
ChannelContextInterface $channelContext
ChannelContextInterface $channelContext,
AvailabilityCheckerInterface $availabilityChecker
): void {
$variant = new ProductVariant();

$objectNormalizer->normalize($variant, null, [])->willReturn([]);

$channelContext->getChannel()->willReturn($channel);
$pricesCalculator->calculate($variant, ['channel' => $channel])->willReturn(1000);
$availabilityChecker->isStockAvailable($variant)->willReturn(true);

$this->normalize($variant, null, [])->shouldReturn(['price' => 1000]);
$this->normalize($variant, null, [])->shouldReturn(['price' => 1000, 'inStock' => true]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
use Sylius\Component\Core\Repository\ProductVariantRepositoryInterface;
use Sylius\Component\Inventory\Checker\AvailabilityCheckerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
Expand All @@ -31,9 +32,10 @@ final class AddingEligibleProductVariantToCartValidatorSpec extends ObjectBehavi
{
function let(
ProductVariantRepositoryInterface $productVariantRepository,
OrderRepositoryInterface $orderRepository
OrderRepositoryInterface $orderRepository,
AvailabilityCheckerInterface $availabilityChecker
): void {
$this->beConstructedWith($productVariantRepository, $orderRepository);
$this->beConstructedWith($productVariantRepository, $orderRepository, $availabilityChecker);
}

function it_is_a_constraint_validator(): void
Expand Down Expand Up @@ -129,14 +131,43 @@ function it_adds_violation_if_product_variant_is_disabled(
);
}

function it_adds_violation_if_product_variant_stock_is_not_sufficient(
ProductVariantRepositoryInterface $productVariantRepository,
ExecutionContextInterface $executionContext,
ProductVariantInterface $productVariant,
ProductInterface $product,
AvailabilityCheckerInterface $availabilityChecker
): void {
$this->initialize($executionContext);

$productVariantRepository->findOneBy(['code' => 'productVariantCode'])->willReturn($productVariant);
$productVariant->getCode()->willReturn('productVariantCode');
$productVariant->isEnabled()->willReturn(true);
$productVariant->getProduct()->willReturn($product);
$product->isEnabled()->willReturn(true);

$availabilityChecker->isStockSufficient($productVariant, 1)->willReturn(false);

$executionContext
->addViolation('sylius.product_variant.not_sufficient', ['%productVariantCode%' => 'productVariantCode'])
->shouldBeCalled()
;

$this->validate(
new AddItemToCart( 'productVariantCode', 1),
new AddingEligibleProductVariantToCart()
);
}

function it_adds_violation_if_product_is_not_available_in_channel(
ProductVariantRepositoryInterface $productVariantRepository,
OrderRepositoryInterface $orderRepository,
ExecutionContextInterface $executionContext,
ChannelInterface $channel,
ProductVariantInterface $productVariant,
ProductInterface $product,
OrderInterface $cart
OrderInterface $cart,
AvailabilityCheckerInterface $availabilityChecker
): void {
$this->initialize($executionContext);

Expand All @@ -149,6 +180,8 @@ function it_adds_violation_if_product_is_not_available_in_channel(
$productVariant->getProduct()->willReturn($product);

$product->isEnabled()->willReturn(true);
$availabilityChecker->isStockSufficient($productVariant, 1)->willReturn(true);

$product->hasChannel($channel)->willReturn(false);
$product->getName()->willReturn('PRODUCT NAME');

Expand All @@ -170,7 +203,8 @@ function it_does_nothing_if_product_and_variant_are_enabled_and_available_in_cha
ChannelInterface $channel,
ProductVariantInterface $productVariant,
ProductInterface $product,
OrderInterface $cart
OrderInterface $cart,
AvailabilityCheckerInterface $availabilityChecker
): void {
$this->initialize($executionContext);

Expand All @@ -183,6 +217,8 @@ function it_does_nothing_if_product_and_variant_are_enabled_and_available_in_cha
$productVariant->getProduct()->willReturn($product);

$product->isEnabled()->willReturn(true);
$availabilityChecker->isStockSufficient($productVariant, 1)->willReturn(true);

$product->hasChannel($channel)->willReturn(true);
$product->getName()->willReturn('PRODUCT NAME');

Expand All @@ -197,6 +233,10 @@ function it_does_nothing_if_product_and_variant_are_enabled_and_available_in_cha
->addViolation('sylius.product.not_exist', ['%productName%' => 'PRODUCT NAME'])
->shouldNotBeCalled()
;
$executionContext
->addViolation('sylius.product_variant.not_sufficient', ['%productVariantCode%' => 'productVariantCode'])
->shouldNotBeCalled()
;

$this->validate($command, new AddingEligibleProductVariantToCart());
}
Expand Down