feature #15028 Cover viewing product associations via API (TheMilek)

This PR was merged into the 1.13 branch.

Discussion
----------

| Q               | A                                                            |
|-----------------|--------------------------------------------------------------|
| Branch?         | 1.13 <!-- see the comment below -->                  |
| Bug fix?        | no                                                       |
| New feature?    | slighly                                                     |
| BC breaks?      | no                                                      |
| Deprecations?   | no <!-- don't forget to update the UPGRADE-*.md file --> |
| License         | MIT                                                          |

<!--
 - Bug fixes must be submitted against the 1.12 branch
 - Features and deprecations must be submitted against the 1.13 branch
 - Make sure that the correct base branch is set

 To be sure you are not breaking any Backward Compatibilities, check the documentation:
 https://docs.sylius.com/en/latest/book/organization/backward-compatibility-promise.html
-->
Until now, we were able to see all associated products for a given product, including those that were disabled. With the new implementation, only enabled products are displayed when accesing `ProductAssociation` endpoint

Commits
-------

c9bff1ca15 Cover viewing product associations via API
This commit is contained in:
Grzegorz Sadowski 2023-05-19 07:13:24 +02:00 committed by GitHub
commit e7f0f95ca3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 221 additions and 5 deletions

View file

@ -24,21 +24,21 @@ Feature: Viewing product's associations
Then I should see the product association "Accessories" with products "LG headphones" and "LG earphones"
And I should also see the product association "Alternatives" with products "LG G4" and "LG G5"
@ui
@ui @api
Scenario: Viewing a detailed page with product's associations after locale change
Given I am browsing channel "Smartphone Store"
When I view product "LG G3" in the "Polish (Poland)" locale
Then I should see the product association "Akcesoria" with products "LG headphones" and "LG earphones"
And I should also see the product association "Alternatywy" with products "LG G4" and "LG G5"
@ui
@ui @api
Scenario: Viewing a detailed page with product's associations within current channel
Given I am browsing channel "Notebook Store"
When I view product "LG Gram"
Then I should see the product association "Alternatives" with product "LG AC Adapter"
And I should not see the product association "Alternatives" with product "LG headphones"
@ui
@ui @api
Scenario: Viewing a detailed page with enabled associated products only
Given the "LG G4" product is disabled
And I am browsing channel "Smartphone Store"
@ -47,7 +47,7 @@ Feature: Viewing product's associations
And I should also see the product association "Alternatives" with product "LG G5"
And I should not see the product association "Alternatives" with product "LG G4"
@ui
@ui @api
Scenario: Viewing a detailed page while an empty association exists
Given products "LG G4" and "LG G5" are disabled
And I am browsing channel "Smartphone Store"

View file

@ -26,6 +26,7 @@ use Sylius\Component\Core\Formatter\StringInflector;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Core\Model\TaxonInterface;
use Sylius\Component\Product\Model\ProductAssociationTypeInterface;
use Sylius\Component\Product\Model\ProductVariantInterface;
use Symfony\Component\HttpFoundation\Request as HttpRequest;
use Symfony\Component\HttpFoundation\Response;
@ -605,13 +606,47 @@ final class ProductContext implements Context
*/
public function iShouldSeeTheProductAssociationWithProductsAnd(string $productAssociationName, array $products): void
{
Assert::true($this->isProductAssociationWithProductsAvailable($productAssociationName, $products));
}
/**
* @Then /^I should(?:| also) see the product association "([^"]+)" with (product "[^"]+")$/
*/
public function iShouldSeeTheProductAssociationWithProduct(string $productAssociationName, ProductInterface $product): void
{
Assert::true($this->isProductAssociationWithProductsAvailable($productAssociationName, [$product]));
}
/**
* @Then /^I should(?:| also) not see the product association "([^"]+)" with (product "[^"]+")$/
*/
public function iShouldNotSeeTheProductAssociationWithProduct(string $productAssociationName, ProductInterface $product): void
{
Assert::false($this->isProductAssociationWithProductsAvailable($productAssociationName, [$product]));
}
/**
* @Then /^I should not see the product (association "([^"]+)")$/
*/
public function iShouldNotSeeTheProductAssociation(ProductAssociationTypeInterface $productAssociationType): void
{
$productAssociationTypeIri = $this->iriConverter->getIriFromItem($productAssociationType);
/** @var ProductInterface $product */
$product = $this->sharedStorage->get('product');
$response = $this->client->show(Resources::PRODUCTS, $product->getCode());
$associations = $this->responseChecker->getValue($response, 'associations');
Assert::true($this->hasAssociationsWithProducts($associations, $productAssociationName, $products));
foreach ($associations as $association) {
$associationResponse = $this->client->showByIri($association);
if ($associationResponse->getStatusCode() === 200) {
$associationTypeIri = $this->responseChecker->getValue($associationResponse, 'type');
Assert::notSame($associationTypeIri, $productAssociationTypeIri);
}
}
}
/**
@ -798,4 +833,15 @@ final class ProductContext implements Context
{
return $this->responseChecker->getResponseContent($this->client->showByIri($iri));
}
private function isProductAssociationWithProductsAvailable(string $productAssociationName, array $associatedProducts): bool
{
/** @var ProductInterface $product */
$product = $this->sharedStorage->get('product');
$response = $this->client->show(Resources::PRODUCTS, $product->getCode());
$associations = $this->responseChecker->getValue($response, 'associations');
return $this->hasAssociationsWithProducts($associations, $productAssociationName, $associatedProducts);
}
}

View file

@ -0,0 +1,61 @@
<?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\Doctrine\QueryItemExtension;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryItemExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\QueryBuilder;
use Sylius\Bundle\ApiBundle\Context\UserContextInterface;
use Sylius\Bundle\ApiBundle\Serializer\ContextKeys;
use Sylius\Component\Core\Model\AdminUserInterface;
use Sylius\Component\Product\Model\ProductAssociationInterface;
use Webmozart\Assert\Assert;
/** @experimental */
final class EnabledProductInProductAssociationItemExtension implements QueryItemExtensionInterface
{
public function __construct(private UserContextInterface $userContext)
{
}
public function applyToItem(
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
string $resourceClass,
array $identifiers,
string $operationName = null,
array $context = [],
) {
if (!is_a($resourceClass, ProductAssociationInterface::class, true)) {
return;
}
$user = $this->userContext->getUser();
if ($user instanceof AdminUserInterface && in_array('ROLE_API_ACCESS', $user->getRoles(), true)) {
return;
}
Assert::keyExists($context, ContextKeys::CHANNEL);
$rootAlias = $queryBuilder->getRootAliases()[0];
$enabled = $queryNameGenerator->generateParameterName('enabled');
$channel = $queryNameGenerator->generateParameterName('channel');
$queryBuilder->addSelect('associatedProduct');
$queryBuilder->leftJoin(sprintf('%s.associatedProducts', $rootAlias), 'associatedProduct', 'WITH', sprintf('associatedProduct.enabled = :%s', $enabled));
$queryBuilder->innerJoin('associatedProduct.channels', 'channel', 'WITH', sprintf('channel = :%s', $channel));
$queryBuilder->setParameter($enabled, true);
$queryBuilder->setParameter($channel, $context[ContextKeys::CHANNEL]);
}
}

View file

@ -111,6 +111,11 @@
<tag name="api_platform.doctrine.orm.query_extension.item" />
</service>
<service id="Sylius\Bundle\ApiBundle\Doctrine\QueryItemExtension\EnabledProductInProductAssociationItemExtension">
<argument type="service" id="Sylius\Bundle\ApiBundle\Context\UserContextInterface" />
<tag name="api_platform.doctrine.orm.query_extension.item" />
</service>
<service id="Sylius\Bundle\ApiBundle\Doctrine\QueryExtension\ExchangeRateExtension">
<argument type="service" id="Sylius\Bundle\ApiBundle\Context\UserContextInterface" />
<tag name="api_platform.doctrine.orm.query_extension.collection" />

View file

@ -0,0 +1,104 @@
<?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\Doctrine\QueryItemExtension;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\QueryBuilder;
use PhpSpec\ObjectBehavior;
use Sylius\Bundle\ApiBundle\Context\UserContextInterface;
use Sylius\Bundle\ApiBundle\Serializer\ContextKeys;
use Sylius\Component\Core\Model\AdminUserInterface;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Product\Model\ProductAssociationInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;
final class EnabledProductInProductAssociationItemExtensionSpec extends ObjectBehavior
{
function let(UserContextInterface $userContext): void
{
$this->beConstructedWith($userContext);
}
function it_does_nothing_if_current_resource_is_not_a_product_association(
UserContextInterface $userContext,
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
): void {
$userContext->getUser()->shouldNotBeCalled();
$queryBuilder->getRootAliases()->shouldNotBeCalled();
$this->applyToItem(
$queryBuilder,
$queryNameGenerator,
ProductVariantInterface::class,
[],
Request::METHOD_GET,
);
}
function it_does_nothing_if_current_user_is_an_admin_user(
UserContextInterface $userContext,
AdminUserInterface $adminUser,
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
): void {
$userContext->getUser()->willReturn($adminUser);
$adminUser->getRoles()->willReturn(['ROLE_API_ACCESS']);
$queryBuilder->getRootAliases()->shouldNotBeCalled();
$this->applyToItem(
$queryBuilder,
$queryNameGenerator,
ProductAssociationInterface::class,
[],
Request::METHOD_GET,
);
}
function it_applies_conditions_for_customer(
UserContextInterface $userContext,
UserInterface $user,
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
ChannelInterface $channel,
): void {
$userContext->getUser()->willReturn($user);
$user->getRoles()->willReturn([]);
$queryNameGenerator->generateParameterName('enabled')->shouldBeCalled()->willReturn('enabled');
$queryNameGenerator->generateParameterName('channel')->shouldBeCalled()->willReturn('channel');
$queryBuilder->getRootAliases()->willReturn(['o']);
$queryBuilder->addSelect('associatedProduct')->shouldBeCalled()->willReturn($queryBuilder);
$queryBuilder->leftJoin('o.associatedProducts', 'associatedProduct', 'WITH', 'associatedProduct.enabled = :enabled')->shouldBeCalled()->willReturn($queryBuilder);
$queryBuilder->innerJoin('associatedProduct.channels', 'channel', 'WITH', 'channel = :channel')->shouldBeCalled()->willReturn($queryBuilder);
$queryBuilder->setParameter('enabled', true)->shouldBeCalled()->willReturn($queryBuilder);
$queryBuilder->setParameter('channel', $channel)->shouldBeCalled()->willReturn($queryBuilder);
$this->applyToItem(
$queryBuilder,
$queryNameGenerator,
ProductAssociationInterface::class,
[],
Request::METHOD_GET,
[
ContextKeys::CHANNEL => $channel->getWrappedObject(),
ContextKeys::HTTP_REQUEST_METHOD_TYPE => Request::METHOD_GET,
],
);
}
}