ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Model\MethodProvider;
class CodeMap
{
/**
* @var array
*/
private $map = [];
/**
* @param string $methodCode
* @param string $alias
* @return void
*/
public function set(string $methodCode, string $alias): void
{
$this->map[$alias] = $methodCode;
}
/**
* @param string $alias
* @return string|null
*/
public function get(string $alias): ?string
{
return $this->map[$alias] ?? null;
}
/**
* @return array [alias => methodCode, ...]
*/
public function getMap(): array
{
return $this->map;
}
/**
* @param array|null $map [alias => methodCode, ...]
*/
public function setMap(?array $map): void
{
$this->map = $map;
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Model\Resolver;
class ArgumentResolver
{
/**
* @param array $args
* @return array
*/
public function convertArgs(array $args): array
{
$result = [];
foreach ($args as $key => $arg) {
$result[$this->convertFromCamelCase($key)] = $arg;
}
return $result;
}
private function convertFromCamelCase(string $name): string
{
return strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $name));
}
}
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Model\Resolver;
use Magento\Framework\GraphQl\Query\Resolver\ContextInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
class FeaturedList implements ResolverInterface
{
public const AM_FEATURED_WIDGET = 'am_featured_widget';
/**
* @var \Amasty\Sorting\Block\Widget\Featured
*/
private $featured;
/**
* @var \Magento\Catalog\Helper\Product\Compare
*/
private $compareHelper;
/**
* @var ArgumentResolver
*/
private $argumentResolver;
public function __construct(
\Amasty\Sorting\Block\Widget\Featured $featured,
\Magento\Catalog\Helper\Product\Compare $compareHelper,
ArgumentResolver $argumentResolver
) {
$this->featured = $featured;
$this->compareHelper = $compareHelper;
$this->argumentResolver = $argumentResolver;
}
/**
* @param Field $field
* @param ContextInterface $context
* @param ResolveInfo $info
* @param array|null $value
* @param array|null $args
* @return array|\Magento\Framework\GraphQl\Query\Resolver\Value|mixed
*/
public function resolve(
Field $field,
$context,
ResolveInfo $info,
array $value = null,
array $args = null
) {
$storeId = (int) $context->getExtensionAttributes()->getStore()->getId();
try {
$data = $this->argumentResolver->convertArgs($args);
$this->setFeaturedData($data, $storeId);
} catch (\Exception $e) {
return [];
}
$data = [];
$productCollection = $this->featured->createCollection()->setFlag(self::AM_FEATURED_WIDGET, true);
$productCollection->setCurPage($data['current_page'] ?? 1);
foreach ($productCollection as $product) {
$data[] = $this->prepareData($product, $context);
}
return $data;
}
/**
* @param array $data
* @param int $storeId
* @return void
* @throws \Exception
*/
private function setFeaturedData(array $data, int $storeId): void
{
$this->featured->setNameInLayout('amsorting_featured_list');
$this->featured->setData($data);
$this->featured->setData('store_id', $storeId);
}
/**
* @param $product
* @param ContextInterface $context
* @return array
*/
private function prepareData($product, ContextInterface $context)
{
$data['id'] = $product->getEntityId();
$data['productUrl'] = $this->getRelativePath($this->featured->getProductUrl($product), $context);
$data['name'] = $product->getName();
$data['isSalable'] = $product->isSaleable() || $product->getIsSalable();
$data['hasRequiredOptions'] = $product->getTypeInstance()->hasRequiredOptions($product);
$data['addToCartUrl'] = $this->featured->getAddToCartUrl($product);
$data['addToCompareParams'] = $this->compareHelper->getPostDataParams($product);
$data['sku'] = $product->getSku();
$data['model'] = $product;
return $data;
}
private function getRelativePath(string $url, ContextInterface $context): string
{
$baseUrl = trim($context->getExtensionAttributes()->getStore()->getBaseUrl(), '/');
return str_replace($baseUrl, '', $url);
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Model\Resolver;
use Amasty\Sorting\Model\Catalog\Toolbar\GetDefaultDirection;
use Magento\Catalog\Model\Config as CatalogConfig;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\Resolver\ContextInterface;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
class GetAvailableOrders implements ResolverInterface
{
/**
* @var CatalogConfig
*/
private $catalogConfig;
/**
* @var GetDefaultDirection
*/
private $getDefaultDirection;
public function __construct(CatalogConfig $catalogConfig, GetDefaultDirection $getDefaultDirection)
{
$this->catalogConfig = $catalogConfig;
$this->getDefaultDirection = $getDefaultDirection;
}
/**
* @param Field $field
* @param ContextInterface $context
* @param ResolveInfo $info
* @param array|null $value
* @param array|null $args
* @return array
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
$result = [];
foreach ($this->catalogConfig->getAttributeUsedForSortByArray() as $code => $label) {
$result[] = [
'attribute' => $code,
'id' => $code,
'text' => $label,
'sortDirection' => strtoupper($this->getDefaultDirection->execute($code))
];
}
return $result;
}
}
@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Model\Resolver;
use Amasty\Sorting\Model\Catalog\Toolbar\GetDefaultDirection;
use Amasty\Sorting\Model\ConfigProvider;
use Amasty\Sorting\Model\Source\ListSort;
use Amasty\Sorting\Model\Source\SearchSort;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\Resolver\ContextInterface;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
class GetDefaultOrders implements ResolverInterface
{
public const CATEGORY_PAGE_TYPE = 'CATEGORY';
public const PAGE_TYPE_PARAM = 'pageType';
/**
* @var ConfigProvider
*/
private $config;
/**
* @var GetDefaultDirection
*/
private $getDefaultDirection;
/**
* @var ListSort
*/
private $listSort;
/**
* @var SearchSort
*/
private $searchListSort;
public function __construct(
ConfigProvider $config,
GetDefaultDirection $getDefaultDirection,
ListSort $listSort,
SearchSort $searchListSort
) {
$this->config = $config;
$this->getDefaultDirection = $getDefaultDirection;
$this->listSort = $listSort;
$this->searchListSort = $searchListSort;
}
/**
* @param Field $field
* @param ContextInterface $context
* @param ResolveInfo $info
* @param array|null $value
* @param array|null $args
* @return array
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
$result = [];
if ($args[self::PAGE_TYPE_PARAM] === self::CATEGORY_PAGE_TYPE) {
$sortOrders = $this->config->getDefaultSortingCategoryPages();
$labels = $this->getSortLabels($sortOrders, $this->listSort->getAllOptions());
} else {
$sortOrders = $this->config->getDefaultSortingSearchPages();
$labels = $this->getSortLabels($sortOrders, $this->searchListSort->toOptionArray());
}
foreach ($sortOrders as $sortOrderCode) {
if ($sortOrderCode) {
$result[] = [
'attribute' => $sortOrderCode,
'id' => $sortOrderCode,
'text' => $labels[$sortOrderCode],
'sortDirection' => strtoupper($this->getDefaultDirection->execute($sortOrderCode))
];
}
}
return $result;
}
private function getSortLabels(array $sortValues, array $sortOptions): array
{
$labels = [];
foreach ($sortOptions as $sortOption) {
if (in_array($sortOption['value'], $sortValues)) {
$labels[$sortOption['value']] = $sortOption['label'];
}
}
return $labels;
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Model\Resolver\Product;
use Exception;
use Magento\CatalogGraphQl\Model\Resolver\Product\ProductImage;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\Resolver\ContextInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
class Image extends ProductImage
{
public const IS_AMASTY_FLAG = 'is_amasty_query';
/**
* @param Field $field
* @param ContextInterface $context
* @param ResolveInfo $info
* @param array|null $value
* @param array|null $args
* @return array
* @throws Exception
*/
public function resolve(
Field $field,
$context,
ResolveInfo $info,
array $value = null,
array $args = null
): array {
$result = parent::resolve($field, $context, $info, $value, $args);
$result[self::IS_AMASTY_FLAG] = true;
return $result;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Model;
class SearchPageFlag
{
/**
* @var bool
*/
private $flag = false;
public function set(bool $flag): void
{
$this->flag = $flag;
}
public function get(): bool
{
return $this->flag;
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Plugin\Block\Widget\Featured;
use Amasty\Sorting\Block\Widget\Featured;
use Magento\Framework\Serialize\Serializer\Json;
class AddWidgetParams
{
/**
* @var Json
*/
private $json;
public function __construct(Json $json)
{
$this->json = $json;
}
/**
* Save widget parameters for variable,
* for future rerender widget with this parameters.
*
* @param Featured $subject
* @param string $html
* @return string
*/
public function afterToHtml(Featured $subject, string $html): string
{
$data = $subject->getData() + ['template' => $this->parseTemplateName($subject->getTemplate())];
$html = sprintf(
'<div class="amsorting-widget-wrapper"><script>var amSortingConfig%s = "%s"</script>%s</div>',
uniqid(),
$this->json->serialize($data),
$html
);
return $html;
}
private function parseTemplateName(string $template): string
{
return preg_replace('@Amasty_Sorting::widget/featured/(.*?).phtml@s', '$1', $template);
}
}
@@ -0,0 +1,45 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Plugin\Catalog\Model\ResourceModel\Product;
use Amasty\SortingGraphQl\Model\Resolver\FeaturedList;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
class CollectionPlugin
{
/**
* @var \Magento\CatalogInventory\Helper\Stock
*/
protected $stockHelper;
/**
* @param \Magento\CatalogInventory\Helper\Stock $stockHelper
*/
public function __construct(
\Magento\CatalogInventory\Helper\Stock $stockHelper
) {
$this->stockHelper = $stockHelper;
}
/**
* Add stock filter to collection.
*
* @param Collection $productCollection
* @param bool $printQuery
* @param bool $logQuery
* @return array
*/
public function beforeLoad(Collection $productCollection, $printQuery = false, $logQuery = false)
{
if ($productCollection->getFlag(FeaturedList::AM_FEATURED_WIDGET)) {
$this->stockHelper->addIsInStockFilterToCollection($productCollection);
}
return [$printQuery, $logQuery];
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Plugin\CatalogGraphQl\DataProvider\Product\SearchCriteriaBuilder;
use Amasty\Sorting\Model\Catalog\Toolbar\GetDefaultDirection;
use Amasty\Sorting\Model\ConfigProvider;
use Amasty\Sorting\Model\IsSearchPage;
use Magento\CatalogGraphQl\DataProvider\Product\SearchCriteriaBuilder;
use Magento\Framework\Api\SortOrder;
class AddDefaultOrders
{
/**
* @var IsSearchPage
*/
private $isSearchPage;
/**
* @var ConfigProvider
*/
private $configProvider;
/**
* @var GetDefaultDirection
*/
private $getDefaultDirection;
public function __construct(
IsSearchPage $isSearchPage,
ConfigProvider $configProvider,
GetDefaultDirection $getDefaultDirection
) {
$this->isSearchPage = $isSearchPage;
$this->configProvider = $configProvider;
$this->getDefaultDirection = $getDefaultDirection;
}
/**
* Add default orders.
* @see SearchCriteriaBuilder::build
*
* @param SearchCriteriaBuilder $subject
* @param array $args
* @param bool $includeAggregation
* @return array
*/
public function beforeBuild(SearchCriteriaBuilder $subject, array $args, bool $includeAggregation): array
{
$defaultOrders = $this->isSearchPage->execute()
? $this->configProvider->getDefaultSortingSearchPages()
: $this->configProvider->getDefaultSortingCategoryPages();
if (isset($args['sort'])) {
// first order already in array
array_shift($defaultOrders);
} else {
// if orders not passed , fill all with default
$args['sort'] = [];
}
foreach ($defaultOrders as $defaultOrder) {
$direction = $this->getDefaultDirection->execute($defaultOrder);
$args['sort'][$defaultOrder] = $direction === 'desc' ? SortOrder::SORT_DESC : SortOrder::SORT_ASC;
}
return [$args, $includeAggregation];
}
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Plugin\CatalogGraphQl\DataProvider\Product\SearchCriteriaBuilder;
use Amasty\Sorting\Model\MethodProvider;
use Amasty\SortingGraphQl\Model\MethodProvider\CodeMap;
use Magento\CatalogGraphQl\DataProvider\Product\SearchCriteriaBuilder;
class FixSortOrderCode
{
/**
* @var MethodProvider
*/
private $methodProvider;
/**
* @var CodeMap
*/
private $codeMap;
public function __construct(MethodProvider $methodProvider, CodeMap $codeMap)
{
$this->methodProvider = $methodProvider;
$this->codeMap = $codeMap;
}
/**
* Replace sort code with method alias(which used in catalogsearch_fulltext indexation) for elastic.
* @see SearchCriteriaBuilder::build
*
* @param SearchCriteriaBuilder $subject
* @param array $args
* @param bool $includeAggregation
* @return array
*/
public function beforeBuild(SearchCriteriaBuilder $subject, array $args, bool $includeAggregation): array
{
if (isset($args['sort'])) {
foreach ($args['sort'] as $sortCode => $direction) {
$method = $this->methodProvider->getMethodByCode($sortCode);
unset($args['sort'][$sortCode]);
if ($method) {
$alias = $method->getAlias();
$args['sort'][$alias] = $direction;
$this->codeMap->set($sortCode, $alias);
} else {
$args['sort'][$sortCode] = $direction;
}
}
}
return [$args, $includeAggregation];
}
}
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Plugin\CatalogGraphQl\Model\Resolver\Product\MediaGallery\Url;
use Amasty\SortingGraphQl\Model\Resolver\Product\Image as ProductImageResolver;
use Magento\CatalogGraphQl\Model\Resolver\Product\MediaGallery\Url;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
class CutBaseUrl
{
/**
* Store manager
*
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @param StoreManagerInterface $storeManager
*/
public function __construct(StoreManagerInterface $storeManager)
{
$this->storeManager = $storeManager;
}
/**
* @param Url $subject
* @param $result
* @param Field $field
* @param $context
* @param ResolveInfo $info
* @param null $value
* @return array
* @throws NoSuchEntityException
*/
public function afterResolve(
Url $subject,
$result,
Field $field,
$context,
ResolveInfo $info,
$value = null
) {
$isAmastyQuery = ($value[ProductImageResolver::IS_AMASTY_FLAG] ?? false);
if ($isAmastyQuery) {
$result = str_replace(
$this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA),
'',
$result
);
}
return $result;
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Plugin\CatalogGraphQl\Model\Resolver\Products\Query\Search;
use Amasty\SortingGraphQl\Model\SearchPageFlag;
use Magento\CatalogGraphQl\Model\Resolver\Products\Query\Search;
class SetSearchFlag
{
/**
* @var SearchPageFlag
*/
private $searchPageFlag;
public function __construct(SearchPageFlag $searchPageFlag)
{
$this->searchPageFlag = $searchPageFlag;
}
/**
* @param Search $subject
* @param array $args
* @return void
*/
public function beforeGetResult(Search $subject, array $args): void
{
if (isset($args['search'])) {
$this->searchPageFlag->set(true);
}
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Plugin\Sorting\Model\Elasticsearch\IsElasticSort;
use Amasty\Sorting\Model\Elasticsearch\IsElasticSort;
use Magento\Framework\App\Area;
use Magento\Framework\App\State;
/**
* Disabling elastic sorting for graphql, since a collection is created in the graphql area and plugins
* for the front-end collection do not work, which is why elastic sorting does not work and need to apply mysql sorting.
*/
class DisableElasticSortForGraphQl
{
/**
* @var State
*/
private $state;
public function __construct(
State $state
) {
$this->state = $state;
}
/**
* @see IsElasticSort::execute()
*/
public function aroundExecute(IsElasticSort $subject, callable $proceed): bool
{
if ($this->state->getAreaCode() === Area::AREA_GRAPHQL) {
return false;
}
return $proceed();
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Plugin\Sorting\Model\IsSearchPage;
use Amasty\Sorting\Model\IsSearchPage;
use Amasty\SortingGraphQl\Model\SearchPageFlag;
class DetectSearchPage
{
/**
* @var SearchPageFlag
*/
private $searchPageFlag;
public function __construct(SearchPageFlag $searchPageFlag)
{
$this->searchPageFlag = $searchPageFlag;
}
/**
* @param IsSearchPage $subject
* @return bool
*/
public function aroundExecute(IsSearchPage $subject): bool
{
return $this->searchPageFlag->get();
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Plugin\Sorting\Model\Method\GetAttributeCodesForSorting;
use Amasty\Sorting\Model\Method\GetAttributeCodesForSorting;
use Amasty\SortingGraphQl\Model\MethodProvider\CodeMap;
class DisableCodeMap
{
/**
* @var CodeMap
*/
private $codeMap;
public function __construct(CodeMap $codeMap)
{
$this->codeMap = $codeMap;
}
/**
* @see GetAttributeCodesForSorting::execute
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundExecute(GetAttributeCodesForSorting $subject, callable $proceed)
{
$codeMap = $this->codeMap->getMap();
$this->codeMap->setMap(null);
$result = $proceed();
$this->codeMap->setMap($codeMap);
return $result;
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Plugin\Sorting\Model\MethodProvider;
use Amasty\Sorting\Model\MethodProvider;
use Amasty\SortingGraphQl\Model\MethodProvider\CodeMap;
class FixMethodCode
{
/**
* @var CodeMap
*/
private $codeMap;
public function __construct(CodeMap $codeMap)
{
$this->codeMap = $codeMap;
}
/**
* Need in case when we replace order code in criteria for correct elastic search.
*
* @see MethodProvider::getMethodByCode
*
* @param MethodProvider $subject
* @param string $code
* @return array
*/
public function beforeGetMethodByCode(MethodProvider $subject, string $code): array
{
if ($originalCode = $this->codeMap->get($code)) {
$code = $originalCode;
}
return [$code];
}
}
@@ -0,0 +1,30 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Plugin\Sorting\Plugin\Catalog;
use Amasty\Sorting\Plugin\Catalog\Config;
class ConfigPlugin
{
/**
* @param Config $subject
* @param array $options
* @return array
*/
public function afterAfterGetAttributesUsedForSortBy(Config $subject, array $options)
{
foreach ($options as $key => $option) {
$options[$key] = [
'attribute_code' => $option->getData('attribute_code'),
'frontend_label' => $option->getStoreLabel()
];
}
return $options;
}
}
@@ -0,0 +1,149 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Test\GraphQl;
use Amasty\Sorting\Model\Indexer\Summary;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
class SortingAmFeaturedWidgetTest extends GraphQlAbstract
{
private const MAIN_RESPONSE_KEY = 'amfeaturedWidget';
/**
* @var Summary
*/
private $summary;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
protected function setUp(): void
{
parent::setUp();
$objectManager = Bootstrap::getObjectManager();
$this->summary = $objectManager->get(Summary::class);
$this->productRepository = $objectManager->get(ProductRepositoryInterface::class);
}
/**
* @group amasty_sorting
*
* @magentoApiDataFixture Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_products.php
*/
public function testSortingAmFeaturedWidget(): void
{
$this->summary->reindexAll();
// get main product data
$productSku = 'am_sort_simple_5';
$product = $this->productRepository->get($productSku);
$productId = (int)$product->getId();
$productName = $product->getName();
$productUrl = $product->getUrlKey();
$productPrice = (int)$product->getPrice();
$variables = [
'sortBy' => 'price',
'amsortingSortOrder' => 'desc',
'productsCount' => 4,
'conditions' => "[]",
'showPager' => false,
'productsPerPage' => 5,
'currentPage' => 3
];
$assertArrayItem = [
'id' => $productId,
'sku' => $productSku,
'productUrl' => '/' . $productUrl . '.html',
'thumbnail' => [
'label' => $productName
],
'name' => $productName,
'price_range' => [
'maximum_price' => [
'final_price' => [
'value' => $productPrice
]
],
'minimum_price' => [
'final_price' => [
'value' => $productPrice
]
]
],
'isSalable' => true,
'hasRequiredOptions' => false
];
$response = $this->graphQlQuery($this->getQuery(), $variables);
$this->assertArrayHasKey(self::MAIN_RESPONSE_KEY, $response);
$this->assertCount(4, $response[self::MAIN_RESPONSE_KEY]);
$this->assertResponseFields($response[self::MAIN_RESPONSE_KEY][1], $assertArrayItem);
$this->assertArrayHasKey('addToCartUrl', $response[self::MAIN_RESPONSE_KEY][1]);
$this->assertArrayHasKey('addToCompareParams', $response[self::MAIN_RESPONSE_KEY][1]);
}
private function getQuery(): string
{
return <<<'QUERY'
query AmFeaturedWidget (
$sortBy: String!,
$amsortingSortOrder: String!,
$productsCount: Int!,
$conditions: String!,
$showPager: Boolean,
$productsPerPage: Int,
$currentPage: Int
) {
amfeaturedWidget (
sortBy:$sortBy
amsortingSortOrder:$amsortingSortOrder
productsCount:$productsCount
conditions:$conditions
showPager:$showPager
productsPerPage:$productsPerPage
currentPage:$currentPage
) {
id
sku
productUrl
thumbnail {
label
}
name
price_range {
maximum_price {
final_price {
value
}
}
minimum_price {
final_price {
value
}
}
}
isSalable
hasRequiredOptions
addToCartUrl
addToCompareParams
}
}
QUERY;
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Test\GraphQl;
use Magento\TestFramework\TestCase\GraphQlAbstract;
class SortingAmOrderListTest extends GraphQlAbstract
{
private const MAIN_RESPONSE_KEY = 'amOrderList';
/**
* @group amasty_sorting
*/
public function testSortingAmOrderList(): void
{
$assertArrayItem = [
'attribute' => 'price',
'id' => 'price',
'sortDirection' => 'ASC',
'text' => 'Price'
];
$response = $this->graphQlQuery($this->getQuery());
$this->assertArrayHasKey(self::MAIN_RESPONSE_KEY, $response);
$this->assertGreaterThanOrEqual(1, count($response[self::MAIN_RESPONSE_KEY]));
$havePriceAttr = false;
foreach ($response[self::MAIN_RESPONSE_KEY] as $attr) {
if ($attr['attribute'] == 'price') {
$this->assertResponseFields($attr, $assertArrayItem);
$havePriceAttr = true;
break;
}
}
$this->assertTrue($havePriceAttr, 'List of orders not contains default attribute "Price".');
}
private function getQuery(): string
{
return <<<QUERY
query {
amOrderList {
attribute
id
sortDirection
text
}
}
QUERY;
}
}
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Test\GraphQl;
use Magento\TestFramework\TestCase\GraphQlAbstract;
class SortingDefaultSortingTest extends GraphQlAbstract
{
private const MAIN_RESPONSE_KEY = 'defaultSorting';
/**
* @group amasty_sorting
*
* @magentoConfigFixture default_store amsorting/default_sorting/category_1 price
*/
public function testSortingDefaultSortingCategory(): void
{
$assertResponse = [
[
'attribute' => 'price',
'id' => 'price',
'sortDirection' => 'ASC',
'text' => 'Price'
]
];
$response = $this->graphQlQuery($this->getQueryCategory());
$this->assertArrayHasKey(self::MAIN_RESPONSE_KEY, $response);
$this->assertResponseFields($response[self::MAIN_RESPONSE_KEY], $assertResponse);
}
/**
* @group amasty_sorting
*
* @magentoConfigFixture default_store amsorting/default_sorting/search_1 name
*/
public function testSortingDefaultSortingSearch(): void
{
$assertResponse = [
[
'attribute' => 'name',
'id' => 'name',
'sortDirection' => 'ASC',
'text' => 'Product Name'
]
];
$response = $this->graphQlQuery($this->getQuerySearch());
$this->assertArrayHasKey(self::MAIN_RESPONSE_KEY, $response);
$this->assertResponseFields($response[self::MAIN_RESPONSE_KEY], $assertResponse);
}
private function getQueryCategory(): string
{
return <<<QUERY
query {
defaultSorting(pageType:CATEGORY) {
attribute
id
sortDirection
text
}
}
QUERY;
}
private function getQuerySearch(): string
{
return <<<QUERY
query {
defaultSorting(pageType:SEARCH) {
attribute
id
sortDirection
text
}
}
QUERY;
}
}
@@ -0,0 +1,358 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
namespace Amasty\SortingGraphQl\Test\GraphQl;
use Amasty\Sorting\Model\Indexer\Summary;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Framework\Shell;
class SortingProductsTest extends GraphQlAbstract
{
private const MAIN_RESPONSE_KEY = 'products';
private const MAIN_SEARCH_WORD = 'Amasty';
/**
* @var Summary
*/
private $summary;
/**
* @var Shell
*/
private $shell;
protected function setUp(): void
{
parent::setUp();
$objectManager = Bootstrap::getObjectManager();
$this->summary = $objectManager->get(Summary::class);
$this->shell = Bootstrap::getObjectManager()->get(Shell::class);
}
/**
* @group amasty_sorting
*
* @magentoApiDataFixture Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_products.php
* @magentoApiDataFixture Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_wishlist.php
* @magentoApiDataFixture Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_wishlist_second.php
*/
public function testSortingProductsWished(): void
{
$this->summary->reindexAll();
$this->reindexCatalogProducts();
$assertArrayItems = [
'items' => [
[
'sku' => 'am_sort_virtual_1'
],
[
'sku' => 'am_sort_simple_4'
],
[
'sku' => 'am_sort_virtual_4'
],
]
];
$response = $this->graphQlQuery($this->getQueryWished(self::MAIN_SEARCH_WORD));
$this->assertArrayHasKey(self::MAIN_RESPONSE_KEY, $response);
$this->assertResponseFields($response[self::MAIN_RESPONSE_KEY], $assertArrayItems);
}
/**
* @group amasty_sorting
*
* @magentoApiDataFixture Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_products.php
*/
public function testSortingProductsPrice(): void
{
$this->summary->reindexAll();
$this->reindexCatalogProducts();
$assertArrayItems = [
'items' => [
[
'sku' => 'am_sort_virtual_1'
],
[
'sku' => 'am_sort_simple_1'
],
[
'sku' => 'am_sort_virtual_5'
],
]
];
$response = $this->graphQlQuery($this->getQueryPriceAsc(self::MAIN_SEARCH_WORD));
$this->assertArrayHasKey(self::MAIN_RESPONSE_KEY, $response);
$this->assertResponseFields($response[self::MAIN_RESPONSE_KEY], $assertArrayItems);
}
/**
* @group amasty_sorting
*
* @magentoApiDataFixture Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_products.php
*/
public function testSortingProductsNew(): void
{
$this->summary->reindexAll();
$this->reindexCatalogProducts();
$assertArrayItems = [
'items' => [
[
'sku' => 'am_sort_virtual_1'
],
[
'sku' => 'am_sort_virtual_4'
],
[
'sku' => 'am_sort_virtual_3'
],
]
];
$response = $this->graphQlQuery($this->getQueryNew(self::MAIN_SEARCH_WORD));
$this->assertArrayHasKey(self::MAIN_RESPONSE_KEY, $response);
$this->assertResponseFields($response[self::MAIN_RESPONSE_KEY], $assertArrayItems);
}
/**
* @group amasty_sorting
*
* @magentoApiDataFixture Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_customer_order.php
*/
public function testSortingProductsBestsellers(): void
{
$this->summary->reindexAll();
$this->reindexCatalogProducts();
$assertArrayItems = [
'items' => [
[
'sku' => 'am_sort_simple_4'
],
[
'sku' => 'am_sort_virtual_2'
],
[
'sku' => 'am_sort_virtual_1'
],
]
];
$response = $this->graphQlQuery($this->getQueryBestsellers(self::MAIN_SEARCH_WORD));
$this->assertArrayHasKey(self::MAIN_RESPONSE_KEY, $response);
$this->assertResponseFields($response[self::MAIN_RESPONSE_KEY], $assertArrayItems);
}
/**
* @group amasty_sorting
*
* @magentoApiDataFixture Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_customer_order.php
*/
public function testSortingProductsRevenue(): void
{
$this->summary->reindexAll();
$this->reindexCatalogProducts();
$assertArrayItems = [
'items' => [
[
'sku' => 'am_sort_simple_4'
],
[
'sku' => 'am_sort_virtual_2'
],
[
'sku' => 'am_sort_virtual_1'
],
]
];
$response = $this->graphQlQuery($this->getQueryRevenue(self::MAIN_SEARCH_WORD));
$this->assertArrayHasKey(self::MAIN_RESPONSE_KEY, $response);
$this->assertResponseFields($response[self::MAIN_RESPONSE_KEY], $assertArrayItems);
}
/**
* @group amasty_sorting
*
* @magentoApiDataFixture Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_customer_order.php
*/
public function testSortingProductsOtherSorts(): void
{
$this->summary->reindexAll();
$this->reindexCatalogProducts();
$assertArrayItems = [
'items' => [
[
'sku' => 'am_sort_virtual_1'
],
[
'sku' => 'am_sort_simple_1'
],
[
'sku' => 'am_sort_virtual_5'
],
]
];
$response = $this->graphQlQuery($this->getQueryOtherSorts(self::MAIN_SEARCH_WORD));
$this->assertArrayHasKey(self::MAIN_RESPONSE_KEY, $response);
$this->assertResponseFields($response[self::MAIN_RESPONSE_KEY], $assertArrayItems);
}
private function getQueryWished(string $search): string
{
return <<<QUERY
query {
products (
search: "$search"
pageSize: 3
sort: {
wished:DESC
}
) {
items {
sku
}
}
}
QUERY;
}
private function getQueryNew(string $search): string
{
return <<<QUERY
query {
products (
search: "$search"
pageSize: 3
sort: {
new:DESC
}
) {
items {
sku
}
}
}
QUERY;
}
private function getQueryPriceAsc(string $search): string
{
return <<<QUERY
query {
products (
search: "$search"
pageSize: 3
sort: {
price_desc:ASC
}
) {
items {
sku
}
}
}
QUERY;
}
private function getQueryBestsellers(string $search): string
{
return <<<QUERY
query {
products (
search: "$search"
pageSize: 3
sort: {
bestsellers:DESC
}
) {
items {
sku
}
}
}
QUERY;
}
private function getQueryRevenue(string $search): string
{
return <<<QUERY
query {
products (
search: "$search"
pageSize: 3
sort: {
revenue:DESC
}
) {
items {
sku
}
}
}
QUERY;
}
private function getQueryOtherSorts(string $search): string
{
return <<<QUERY
query {
products (
search: "$search"
pageSize: 3
sort: {
rating_summary:ASC
reviews_count:ASC
most_viewed:ASC
saving:ASC
price_asc:ASC
}
) {
items {
sku
}
}
}
QUERY;
}
private function reindexCatalogProducts():void
{
$indexes = [
'catalogrule_rule',
'catalogsearch_fulltext',
'catalog_category_product',
'catalog_product_attribute',
'inventory',
'catalog_product_price',
'cataloginventory_stock'
];
$parameters = implode(' ', $indexes);
$appDir = dirname(Bootstrap::getInstance()->getAppTempDir());
$this->shell->execute("php -f {$appDir}/bin/magento indexer:reindex {$parameters}");
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Quote\Api\CartManagementInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture(
'Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_customer_quote_for_order.php'
);
$objectManager = Bootstrap::getObjectManager();
/** @var CartRepositoryInterface $quoteRepository */
$quoteRepository = $objectManager->get(CartRepositoryInterface::class);
/** @var CartManagementInterface $quoteManagement */
$quoteManagement = $objectManager->get(CartManagementInterface::class);
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = $objectManager->get(CustomerRepositoryInterface::class);
$customer = $customerRepository->get('customer_with_addresses@test.com');
$quote = $quoteRepository->getActiveForCustomer($customer->getId());
$quoteManagement->placeOrder($quote->getId());
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
use Magento\Framework\Registry;
use Magento\Sales\Api\Data\OrderInterfaceFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
/** @var OrderRepositoryInterface $orderRepository */
$orderRepository = $objectManager->get(OrderRepositoryInterface::class);
/** @var OrderInterfaceFactory $orderFactory */
$orderFactory = $objectManager->get(OrderInterfaceFactory::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$order = $orderFactory->create()->loadByIncrementId('123456789');
if ($order->getId()) {
$orderRepository->delete($order);
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
Resolver::getInstance()->requireDataFixture(
'Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_customer_quote_for_order_rollback.php'
);
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Checkout\Model\Type\Onepage;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\Data\AddressInterface;
use Magento\Quote\Api\Data\AddressInterfaceFactory;
use Magento\Quote\Api\Data\CartInterface;
use Magento\Quote\Api\Data\CartInterfaceFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Customer/_files/customer_with_addresses.php');
Resolver::getInstance()->requireDataFixture('Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_products.php');
$objectManager = Bootstrap::getObjectManager();
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
/** @var CartRepositoryInterface $quoteRepository */
$quoteRepository = $objectManager->get(CartRepositoryInterface::class);
/** @var AddressInterface $quoteShippingAddress */
$quoteShippingAddress = $objectManager->get(AddressInterfaceFactory::class)->create();
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = $objectManager->get(CustomerRepositoryInterface::class);
/** @var AddressRepositoryInterface $addressRepository */
$addressRepository = $objectManager->get(AddressRepositoryInterface::class);
/** @var SearchCriteriaBuilder $searchCriteria */
$searchCriteria = $objectManager->get(SearchCriteriaBuilder::class);
$productRepository->cleanCache();
$searchCriteriaAddress = $searchCriteria->addFilter('postcode', '75477')
->addFilter('city', 'CityM')
->addFilter('country_id', 'US')
->addFilter('firstname', 'John')
->addFilter('street', 'CustomerAddress1')
->create();
$address = $addressRepository->getList($searchCriteriaAddress)->getItems()[0];
$quoteShippingAddress->importCustomerAddressData($address);
$customer = $customerRepository->get('customer_with_addresses@test.com');
/** @var CartInterface $quote */
$quote = $objectManager->get(CartInterfaceFactory::class)->create();
$quote->setStoreId(1)
->setIsActive(true)
->setIsMultiShipping(0)
->assignCustomerWithAddressChange($customer)
->setShippingAddress($quoteShippingAddress)
->setBillingAddress($quoteShippingAddress)
->setCheckoutMethod(Onepage::METHOD_CUSTOMER)
->setReservedOrderId('123456789')
->setEmail($customer->getEmail());
$quote->addProduct($productRepository->get('am_sort_simple_4'), 3);
$quote->addProduct($productRepository->get('am_sort_virtual_2'), 1);
$quote->getShippingAddress()->setShippingMethod('flatrate_flatrate');
$quote->getShippingAddress()->setCollectShippingRates(true);
$quote->getShippingAddress()->collectShippingRates();
$quote->getPayment()->setMethod('checkmo');
$quoteRepository->save($quote);
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Quote\Model\GetQuoteByReservedOrderId;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = Bootstrap::getObjectManager();
/** @var CartRepositoryInterface $quoteRepository */
$quoteRepository = $objectManager->get(CartRepositoryInterface::class);
/** @var GetQuoteByReservedOrderId $getQuoteByReservedOrderId */
$getQuoteByReservedOrderId = $objectManager->get(GetQuoteByReservedOrderId::class);
$quote = $getQuoteByReservedOrderId->execute('123456789');
if ($quote) {
$quoteRepository->delete($quote);
}
Resolver::getInstance()->requireDataFixture('Magento/Customer/_files/customer_with_addresses_rollback.php');
Resolver::getInstance()->requireDataFixture('Amasty_SortingGraphQl::Test/GraphQl/_files/am_sort_products_rollback.php');
@@ -0,0 +1,148 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\CategoryInterfaceFactory;
use Magento\Catalog\Api\Data\ProductInterfaceFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var ProductInterfaceFactory $productFactory */
$productFactory = $objectManager->get(ProductInterfaceFactory::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
/** @var CategoryInterfaceFactory $categoryFactory */
$categoryFactory = $objectManager->get(CategoryInterfaceFactory::class);
/** @var CategoryRepositoryInterface $categoryRepository */
$categoryRepository = $objectManager->get(CategoryRepositoryInterface::class);
// create first category
$category = $categoryFactory->create();
$category->isObjectNew(true);
$category->setName('Am Category Sorting One Test')
->setIsActive(true)
->setPosition(1);
$category = $categoryRepository->save($category);
$categoryId = $category->getId();
// create second category
$categorySecond = $categoryFactory->create();
$categorySecond->isObjectNew(true);
$categorySecond->setName('Am Category Sorting Second Test')
->setIsActive(true)
->setPosition(1);
$categorySecond = $categoryRepository->save($categorySecond);
$categorySecondId = $categorySecond->getId();
// create products data array
$productsData = [
[
'sku' => 'am_sort_simple_1',
'category' => [$categoryId],
'type' => Type::TYPE_SIMPLE,
'name' => 'Amasty Simple Product 1',
'price' => 1000
],
[
'sku' => 'am_sort_simple_2',
'category' => [$categorySecondId],
'type' => Type::TYPE_SIMPLE,
'name' => 'Amasty Simple Product 2',
'price' => 1200
],
[
'sku' => 'am_sort_simple_3',
'category' => [$categoryId],
'type' => Type::TYPE_SIMPLE,
'name' => 'Amasty Simple Product 3',
'price' => 1200
],
[
'sku' => 'am_sort_simple_4',
'category' => [$categorySecondId],
'type' => Type::TYPE_SIMPLE,
'name' => 'Amasty Simple Product 4',
'price' => 2000
],
[
'sku' => 'am_sort_simple_5',
'category' => [$categoryId],
'type' => Type::TYPE_SIMPLE,
'name' => 'Amasty Simple Product 5',
'price' => 5000
],
[
'sku' => 'am_sort_virtual_5',
'category' => [$categorySecondId],
'type' => Type::TYPE_VIRTUAL,
'name' => 'Amasty Virtual Product 1',
'price' => 1000
],
[
'sku' => 'am_sort_virtual_2',
'category' => [$categoryId],
'type' => Type::TYPE_VIRTUAL,
'name' => 'Amasty Virtual Product 2',
'price' => 2500
],
[
'sku' => 'am_sort_virtual_3',
'category' => [$categorySecondId],
'type' => Type::TYPE_VIRTUAL,
'name' => 'Amasty Virtual Product 3',
'price' => 2500
],
[
'sku' => 'am_sort_virtual_4',
'category' => [$categoryId],
'type' => Type::TYPE_VIRTUAL,
'name' => 'Amasty Virtual Product 4',
'price' => 50000
],
[
'sku' => 'am_sort_virtual_1',
'category' => [$categorySecondId],
'type' => Type::TYPE_VIRTUAL,
'name' => 'Amasty Virtual Product 5',
'price' => 800
]
];
// create products
foreach ($productsData as $productData) {
$product = $productFactory->create();
$product->setTypeId($productData['type'])
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([1])
->setName($productData['name'])
->setSku($productData['sku'])
->setPrice(10)
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setPrice($productData['price'])
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
)
->setCategoryIds($productData['category']);
$productRepository->save($product);
}
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\TestFramework\Catalog\Model\GetCategoryByName;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
/** @var CategoryRepositoryInterface $categoryRepository */
$categoryRepository = $objectManager->get(CategoryRepositoryInterface::class);
/** @var GetCategoryByName $getCategoryByName */
$getCategoryByName = $objectManager->create(GetCategoryByName::class);
$currentArea = $registry->registry('isSecureArea');
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
// get categories
$category = $getCategoryByName->execute('Am Category Sorting One Test');
$categorySecond = $getCategoryByName->execute('Am Category Sorting Second Test');
// delete categories
try {
$categoryRepository->delete($category);
$categoryRepository->delete($categorySecond);
} catch (NoSuchEntityException $e) {
// category already deleted.
}
// products sku data array
$skus = [
'am_sort_simple_1',
'am_sort_simple_2',
'am_sort_simple_3',
'am_sort_simple_4',
'am_sort_simple_5',
'am_sort_virtual_1',
'am_sort_virtual_2',
'am_sort_virtual_3',
'am_sort_virtual_4',
'am_sort_virtual_5'
];
// delete products
try {
foreach ($skus as $sku) {
$productRepository->delete($productRepository->get($sku));
}
} catch (NoSuchEntityException $e) {
// product already deleted.
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', $currentArea);
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Wishlist\Model\WishlistFactory;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Customer/_files/customer_with_addresses.php');
$objectManager = Bootstrap::getObjectManager();
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = Bootstrap::getObjectManager()->create(CustomerRepositoryInterface::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
/** @var WishlistFactory $wishlistFactory */
$wishlistFactory = $objectManager->get(WishlistFactory::class);
$customer = $customerRepository->get('customer_with_addresses@test.com');
$productOne = $productRepository->get('am_sort_simple_4');
$productTwo = $productRepository->get('am_sort_virtual_1');
$wishlist = $wishlistFactory->create();
$wishlist->loadByCustomerId($customer->getId(), true);
$wishlist->addNewItem($productOne);
$wishlist->addNewItem($productTwo);
$wishlist->save();
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Customer/_files/customer_with_addresses_rollback.php');
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Wishlist\Model\WishlistFactory;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Customer/_files/customer_with_uk_address.php');
$objectManager = Bootstrap::getObjectManager();
/** @var CustomerRepositoryInterface $customerRepository */
$customerRepository = Bootstrap::getObjectManager()->create(CustomerRepositoryInterface::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
/** @var WishlistFactory $wishlistFactory */
$wishlistFactory = $objectManager->get(WishlistFactory::class);
$customer = $customerRepository->get('customer_uk_address@test.com');
$product = $productRepository->get('am_sort_virtual_1');
$wishlist = $wishlistFactory->create();
$wishlist->loadByCustomerId($customer->getId(), true);
$wishlist->addNewItem($product);
$wishlist->save();
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Customer/_files/customer_with_uk_address_rollback.php');
+23
View File
@@ -0,0 +1,23 @@
{
"name": "amasty/improved-sorting-graphql",
"description": "Sorting Graphql By Amasty",
"require": {
"php": ">=7.3",
"amasty/base": ">=1.14.7",
"amasty/sorting": ">=2.9.1",
"magento/module-graph-ql": "*"
},
"type": "magento2-module",
"version": "1.1.4",
"license": [
"proprietary"
],
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"Amasty\\SortingGraphQl\\": ""
}
}
}
+55
View File
@@ -0,0 +1,55 @@
<?xml version="1.0"?>
<!--
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Block\Product\ProductList\Toolbar">
<plugin name="Amasty_SortingGraphQl::catalogToolbar" type="Amasty\Sorting\Plugin\Catalog\Product\ProductList\Toolbar"/>
</type>
<type name="Magento\Catalog\Model\ResourceModel\Product\Collection">
<plugin name="Amasty_SortingGraphQl::SortingMethodsProcessor" type="Amasty\Sorting\Plugin\Catalog\Product\Collection"/>
</type>
<!-- fix stock status for GraphQl-->
<type name="Magento\Catalog\Model\ResourceModel\Product\Collection">
<plugin name="Amasty_SortingGraphQl::add_stock_information"
type="Amasty\SortingGraphQl\Plugin\Catalog\Model\ResourceModel\Product\CollectionPlugin"/>
</type>
<type name="Amasty\Sorting\Block\Widget\Featured">
<plugin name="Amasty_SortingGraphQl::addConfig" type="Amasty\SortingGraphQl\Plugin\Block\Widget\Featured\AddWidgetParams" />
</type>
<type name="Magento\CatalogGraphQl\Model\Resolver\Product\MediaGallery\Url">
<plugin name="Amasty_SortingGraphQl::get-relative-path" type="Amasty\SortingGraphQl\Plugin\CatalogGraphQl\Model\Resolver\Product\MediaGallery\Url\CutBaseUrl" />
</type>
<!-- fix for elastic engine; because when elastic sorting is double! in elastic and after in mysql -->
<type name="Magento\CatalogGraphQl\DataProvider\Product\SearchCriteriaBuilder">
<plugin name="Amasty_SortingGraphQl::add-default-orders" type="Amasty\SortingGraphQl\Plugin\CatalogGraphQl\DataProvider\Product\SearchCriteriaBuilder\AddDefaultOrders" sortOrder="10" />
</type>
<type name="Magento\CatalogGraphQl\DataProvider\Product\SearchCriteriaBuilder">
<plugin name="Amasty_SortingGraphQl::fix-order-code" type="Amasty\SortingGraphQl\Plugin\CatalogGraphQl\DataProvider\Product\SearchCriteriaBuilder\FixSortOrderCode" sortOrder="11" />
</type>
<type name="Amasty\Sorting\Model\MethodProvider">
<plugin name="Amasty_SortingGraphQl::fix-method-code" type="Amasty\SortingGraphQl\Plugin\Sorting\Model\MethodProvider\FixMethodCode" />
</type>
<type name="Amasty\Sorting\Model\Method\GetAttributeCodesForSorting">
<plugin name="Amasty_SortingGraphQl::disable-code-map"
type="Amasty\SortingGraphQl\Plugin\Sorting\Model\Method\GetAttributeCodesForSorting\DisableCodeMap" />
</type>
<type name="Magento\CatalogGraphQl\Model\Resolver\Products\Query\Search">
<plugin name="Amasty_SortingGraphQl::detect-search-page" type="Amasty\SortingGraphQl\Plugin\CatalogGraphQl\Model\Resolver\Products\Query\Search\SetSearchFlag" />
</type>
<type name="Amasty\Sorting\Model\IsSearchPage">
<plugin name="Amasty_SortingGraphQl::detect-search-page" type="Amasty\SortingGraphQl\Plugin\Sorting\Model\IsSearchPage\DetectSearchPage" />
</type>
<type name="Amasty\Sorting\Model\Elasticsearch\IsElasticSort">
<plugin name="Amasty_SortingGraphQl::sort-in-mysql" type="Amasty\SortingGraphQl\Plugin\Sorting\Model\Elasticsearch\IsElasticSort\DisableElasticSortForGraphQl" />
</type>
</config>
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0"?>
<!--
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Amasty_SortingGraphQl" setup_version="1.0.0">
<sequence>
<module name="Magento_GraphQl"/>
<module name="Amasty_Sorting"/>
</sequence>
</module>
</config>
+67
View File
@@ -0,0 +1,67 @@
type Query {
amfeaturedWidget (
sortBy: String! @doc(description: "Order code."),
amsortingSortOrder: String! @doc(description: "Order direction."),
productsCount: Int! @doc(description: "Products count."),
conditions: String! @doc(description: "Conditions serialized."),
showPager: Boolean @doc(description: "Determine is pager enabled."),
productsPerPage: Int @doc(description: "Number of Products per Page"),
currentPage: Int @doc(description: "Current Page Nubmer.")
): [ProductData] @resolver(class: "Amasty\\SortingGraphQl\\Model\\Resolver\\FeaturedList")
amOrderList: [SortingOrder] @resolver(class: "Amasty\\SortingGraphQl\\Model\\Resolver\\GetAvailableOrders")
defaultSorting(
pageType: PageTypeEnum! @doc(description: "Page type.")
): [SortingOrder] @resolver(class: "Amasty\\SortingGraphQl\\Model\\Resolver\\GetDefaultOrders")
}
type SortingOrder {
attribute: String! @doc(description: "Order code."),
id: String! @doc(description: "Order id."),
text: String! @doc(description: "Order label."),
sortDirection: String! @doc(desctiption: "Default direction.")
}
type ProductData {
id: Int @doc(description: "Item id.")
sku: String! @doc(description: "Product SKU")
productUrl: String @doc(description: "Product URL.")
thumbnail: ProductImage @doc(description: "The relative path to the product's thumbnail image.") @resolver(class: "Amasty\\SortingGraphQl\\Model\\Resolver\\Product\\Image")
small_image: ProductImage @doc(description: "The relative path to the product's small image.") @resolver(class: "Amasty\\SortingGraphQl\\Model\\Resolver\\Product\\Image")
name: String @doc(description: "Product name.")
price_range: PriceRange! @doc(description: "A PriceRange object, indicating the range of prices for the product") @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\Product\\PriceRange")
isSalable: Boolean @doc(description: "Product is salable.")
hasRequiredOptions: Boolean @doc(description: "Product has required options.")
addToCartUrl: String @doc(description: "Product add to cart URL.")
addToCompareParams: String @doc(description: "Product add to compare params.")
}
input ProductSortInput @doc(description: "ProductSortInput specifies the attribute to use for sorting.") {
bestsellers: SortEnum @doc(description: "Is product bestsellers.")
revenue: SortEnum @doc(description: "Revenue.")
rating_summary: SortEnum @doc(description: "The product rating_summary.")
reviews_count: SortEnum @doc(description: "The product reviews_count.")
most_viewed: SortEnum @doc(description: "The product most_viewed.")
wished: SortEnum @doc(description: "Is product wished.")
new: SortEnum @doc(description: "Is product new.")
saving: SortEnum @doc(description: "The product saving.")
price_asc: SortEnum @doc(description: "The product price_asc.")
price_desc: SortEnum @doc(description: "The product price_desc.")
}
input ProductAttributeSortInput @doc(description: "ProductAttributeSortInput specifies the attribute to use for sorting.") {
bestsellers: SortEnum @doc(description: "Is product bestsellers.")
revenue: SortEnum @doc(description: "Revenue.")
rating_summary: SortEnum @doc(description: "The product rating_summary.")
reviews_count: SortEnum @doc(description: "The product reviews_count.")
most_viewed: SortEnum @doc(description: "The product most_viewed.")
wished: SortEnum @doc(description: "Is product wished.")
new: SortEnum @doc(description: "Is product new.")
saving: SortEnum @doc(description: "The product saving.")
price_asc: SortEnum @doc(description: "The product price_asc.")
price_desc: SortEnum @doc(description: "The product price_desc.")
}
enum PageTypeEnum {
CATEGORY
SEARCH
}
+1
View File
@@ -0,0 +1 @@
"Wrong parameter storeId.","Wrong parameter storeId."
1 Wrong parameter storeId. Wrong parameter storeId.
+14
View File
@@ -0,0 +1,14 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Amasty Improved Sorting GraphQl for Magento 2 (System)
*/
/**
* Copyright © 2019 Amasty. All rights reserved.
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Amasty_SortingGraphQl',
__DIR__
);