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] Validate if product or variant is enabled #12579

Merged
merged 2 commits into from
May 5, 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
@@ -0,0 +1,26 @@
@checkout
Feature: Preventing adding to cart disabled products
In order to have correct products in cart when adding them
As a customer
I want to have the added products validated

Background:
Given the store operates on a single channel in "United States"
And the store has a product "PHP T-Shirt" priced at "$19.99"
And the store has a "Super Cool T-Shirt" configurable product
And this product has "Small", "Medium" and "Large" variants
And I am a logged in customer

@api
Scenario: Preventing customer from adding disabled product
Given the product "PHP T-Shirt" has been disabled
When I pick up my cart
And I try to add product "PHP T-Shirt" to the cart
Then I should be informed that product "PHP T-Shirt" is disabled

@api
Scenario: Preventing customer from adding disabled variant
Given the "Large" product variant is disabled
When I pick up my cart
And I try to add "Large" product variant
Then I should be informed that "Large" product variant is disabled
28 changes: 27 additions & 1 deletion src/Sylius/Behat/Context/Api/Shop/CheckoutContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\PaymentMethodInterface;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Core\Model\ShippingMethodInterface;
use Sylius\Component\Core\Model\ShopUserInterface;
use Sylius\Component\Core\OrderCheckoutStates;
Expand Down Expand Up @@ -777,6 +778,7 @@ public function iShouldBeNotifiedThatTheAndTheInShippingDetailsAreRequired(strin

/**
* @Then /^I should be informed that (this product) has been disabled$/
* @Then /^I should be informed that (product "[^"]+") is disabled$/
*/
public function iShouldBeInformedThatThisProductHasBeenDisabled(ProductInterface $product): void
{
Expand All @@ -786,6 +788,17 @@ public function iShouldBeInformedThatThisProductHasBeenDisabled(ProductInterface
));
}

/**
* @Then /^I should be informed that ("([^"]*)" product variant) is disabled$/
*/
public function iShouldBeInformedThatProductVariantIsDisabled(ProductVariantInterface $productVariant): void
{
Assert::true($this->isViolationWithMessageInResponse(
$this->ordersClient->getLastResponse(),
sprintf('This product %s has been disabled.', $productVariant->getName())
));
}

/**
* @Then I should not see the thank you page
*/
Expand Down Expand Up @@ -839,6 +852,15 @@ public function iTryToAddProductToCart(ProductInterface $product, string $tokenV
$this->putProductToCart($product, $tokenValue);
}

/**
* @When /^I try to add ("([^"]+)" product variant)$/
*/
public function iTryToAddProductVariant(ProductVariantInterface $productVariant): void
{
$tokenValue = $this->getCartTokenValue();
$this->putVariantToCart($productVariant, $tokenValue);
}

/**
* @When /^I try to remove (product "[^"]+") from the (cart)$/
*/
Expand Down Expand Up @@ -1100,6 +1122,11 @@ private function putProductToCart(ProductInterface $product, string $tokenValue,
{
Assert::notNull($productVariant = $this->productVariantResolver->getVariant($product));

$this->putVariantToCart($productVariant, $tokenValue, $quantity);
}

private function putVariantToCart(ProductVariantInterface $productVariant, string $tokenValue, int $quantity = 1): void
{
$request = Request::customItemAction(
'shop',
'orders',
Expand All @@ -1109,7 +1136,6 @@ private function putProductToCart(ProductInterface $product, string $tokenValue,
);

$request->setContent([
'productCode' => $product->getCode(),
'productVariant' => $this->iriConverter->getIriFromItem($productVariant),
'quantity' => $quantity,
]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@
<tag name="validator.constraint_validator" alias="sylius_api_validator_order_shipping_method_eligibility" />
</service>

<service id="sylius.api.validator.product_or_variant_enabled" class="Sylius\Bundle\ApiBundle\Validator\Constraints\ProductOrVariantEnabledValidator">
<argument type="service" id="sylius.repository.product_variant" />
<tag name="validator.constraint_validator" alias="sylius_api_validator_product_or_variant_enabled" />
</service>

<service id="sylius.api.validator.payment_method_eligibility" class="Sylius\Bundle\ApiBundle\Validator\Constraints\OrderPaymentMethodEligibilityValidator">
<argument type="service" id="sylius.repository.order" />
<tag name="validator.constraint_validator" alias="sylius_api_order_payment_method_eligibility" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@

<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/services/constraint-mapping-1.0.xsd">
<class name="Sylius\Bundle\ApiBundle\Command\Cart\AddItemToCart">
<constraint name="Sylius\Bundle\ApiBundle\Validator\Constraints\ProductOrVariantEnabled">
<option name="groups">
<value>sylius</value>
</option>
</constraint>
<property name="quantity">
<constraint name="Range">
<option name="min">1</option>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Sylius\Bundle\ApiBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/** @experimental */
final class ProductOrVariantEnabled extends Constraint
{
/** @var string */
public $message = 'sylius.order.product_eligibility';

public function validatedBy(): string
{
return 'sylius_api_validator_product_or_variant_enabled';
}

public function getTargets(): string
{
return self::CLASS_CONSTRAINT;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Sylius\Bundle\ApiBundle\Validator\Constraints;

use Sylius\Bundle\ApiBundle\Command\Cart\AddItemToCart;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Product\Repository\ProductVariantRepositoryInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Webmozart\Assert\Assert;

/** @experimental */
final class ProductOrVariantEnabledValidator extends ConstraintValidator
{
/** @var ProductVariantRepositoryInterface */
private $productVariantRepository;

public function __construct(ProductVariantRepositoryInterface $productVariantRepository)
{
$this->productVariantRepository = $productVariantRepository;
}

public function validate($value, Constraint $constraint)
{
Assert::isInstanceOf($value, AddItemToCart::class);

/** @var ProductOrVariantEnabled $constraint */
Assert::isInstanceOf($constraint, ProductOrVariantEnabled::class);

/** @var ProductVariantInterface $productVariant */
$productVariant = $this->productVariantRepository->findOneBy(['code' =>$value->productVariantCode]);

if (!$productVariant->getProduct()->isEnabled()) {
$this->context->addViolation(
$constraint->message,
['%productName%' => $productVariant->getProduct()->getName()]
);

return;
arti0090 marked this conversation as resolved.
Show resolved Hide resolved
}

if (!$productVariant->isEnabled()) {
$this->context->addViolation(
$constraint->message,
['%productName%' => $productVariant->getName()]
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
<?php

/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace spec\Sylius\Bundle\ApiBundle\Validator\Constraints;

use Doctrine\Common\Collections\ArrayCollection;
use PhpSpec\ObjectBehavior;
use Sylius\Bundle\ApiBundle\Command\Cart\AddItemToCart;
use Sylius\Bundle\ApiBundle\Command\Checkout\CompleteOrder;
use Sylius\Bundle\ApiBundle\Validator\Constraints\OrderNotEmpty;
use Sylius\Bundle\ApiBundle\Validator\Constraints\ProductOrVariantEnabled;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\OrderItemInterface;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
use Sylius\Component\Core\Repository\ProductVariantRepositoryInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

final class ProductOrVariantEnabledValidatorSpec extends ObjectBehavior
{
function let(ProductVariantRepositoryInterface $productVariantRepository): void
{
$this->beConstructedWith($productVariantRepository);
}

function it_is_a_constraint_validator(): void
{
$this->shouldImplement(ConstraintValidatorInterface::class);
}

function it_throws_an_exception_if_value_is_not_an_instance_of_product_or_variant_enabled_class(): void
{
$this
->shouldThrow(\InvalidArgumentException::class)
->during('validate', [new CompleteOrder(), new class() extends Constraint {
}])
;
}

function it_throws_an_exception_if_constraint_is_not_an_instance_of_add_item_to_cart(): void
{
$this
->shouldThrow(\InvalidArgumentException::class)
->during('validate', ['', new class() extends Constraint {
}])
;
}

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

$value = new AddItemToCart('productVariantCode', 1);
$constraint = new ProductOrVariantEnabled();
$constraint->message = 'message';

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

$product->isEnabled()->willReturn(false);
$product->getName()->willReturn('PRODUCTNAME');
$executionContext
->addViolation(
'message',
['%productName%' => 'PRODUCTNAME']
)
->shouldBeCalled();

$this->validate($value, $constraint);
}

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

$value = new AddItemToCart('productVariantCode', 1);
$constraint = new ProductOrVariantEnabled();
$constraint->message = 'message';

$productVariantRepository->findOneBy(['code' => 'productVariantCode'])->willReturn($productVariant);

$productVariant->getProduct()->willReturn($product);

$product->isEnabled()->willReturn(false);
$product->getName()->willReturn('PRODUCTNAME');
$executionContext
->addViolation(
'message',
['%productName%' => 'PRODUCTNAME']
)
->shouldBeCalled();

$productVariant->isEnabled()->willReturn(true);
$productVariant->getName()->willReturn('NAME');
$executionContext
->addViolation(
'message',
['%productName%' => 'NAME']
)
->shouldNotBeCalled();

$this->validate($value, $constraint);
}

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

$value = new AddItemToCart('productVariantCode', 1);
$constraint = new ProductOrVariantEnabled();
$constraint->message = 'message';

$productVariantRepository->findOneBy(['code' => 'productVariantCode'])->willReturn($productVariant);
$productVariant->isEnabled()->willReturn(true);
$productVariant->getName()->willReturn('NAME');
$executionContext
->addViolation(
'message',
['%productName%' => 'NAME']
)
->shouldNotBeCalled();

$productVariant->getProduct()->willReturn($product);

$product->isEnabled()->willReturn(true);
$product->getName()->willReturn('PRODUCTNAME');
$executionContext
->addViolation(
'message',
['%productName%' => 'PRODUCTNAME']
)
->shouldNotBeCalled();

$this->validate($value, $constraint);
}
}