Skip to content

Commit

Permalink
[Analytics][Tracker] Feature Smile-SA#3340, merge 2.10.x branch, solv…
Browse files Browse the repository at this point in the history
…e merge conflicts
  • Loading branch information
vahonc committed Oct 29, 2024
2 parents 244996d + f584cd0 commit 322ec6b
Show file tree
Hide file tree
Showing 55 changed files with 717 additions and 68 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/99-no-response.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ on:
issue_comment:
types: [created]
schedule:
- cron: '30 * * * *'
- cron: '0 1 * * *'

jobs:
noResponse:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value
'current_page' => $searchResult->getCurrentPage(),
'total_pages' => $searchResult->getTotalPages(),
'is_spellchecked' => $searchResult->isSpellchecked(),
'query_id' => $searchResult->getQueryId(),
],
'search_result' => $searchResult,
'layer_type' => $layerType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ public function getResult(array $args, ResolveInfo $info, ContextInterface $cont
'currentPage' => $searchCriteria->getCurrentPage(),
'totalPages' => $maxPages,
'isSpellchecked' => $searchResults->__toArray()['is_spellchecked'] ?? false,
'queryId' => $searchResults->__toArray()['query_id'] ?? null,
]);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,12 @@ public function isSpellchecked()
{
return (bool) $this->data['isSpellchecked'] ?? false;
}

/**
* @return ?int
*/
public function getQueryId()
{
return $this->data['queryId'] ?? null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ type ViewMoreResult @doc(description: "The Products object is the top-level obje
type SearchResultPageInfo
{
is_spellchecked: Boolean
query_id: Int
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,18 @@ public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as &$item) {
$value = '';
$config = $this->serializer->unserialize($item['config']);
$value = $config['constant_score_value'] ? ($config['constant_score_value'] . '%') : '';
$type = $item['model'] ?? 'constant_score';
if ($type === 'constant_score') {
$value = $config['constant_score_value'] ? ($config['constant_score_value'] . '%') : '';
} elseif ($type === 'attribute_value') {
$factor = $config['scale_factor'] ?? '';
$modifier = $config['scale_function'] ?? '';
$field = $config['attribute_code'] ?? '';
$value = sprintf("%s(%s * %s)", $modifier, $factor, $field);
}

$item[$this->getData('name')] = $value;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@

use Magento\Catalog\Block\Product\ProductList\Toolbar as ProductListToolbar;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;

/**
* Plugin which is modified the behavior of sorting arrows based on the custom sort direction attribute.
Expand All @@ -26,6 +30,8 @@
*/
class SortDirectionPerCategoryPlugin
{
const XML_PATH_LIST_DEFAULT_SORT_DIRECTION_BY = 'catalog/frontend/default_sort_direction_by';

/**
* @var CategoryRepositoryInterface
*/
Expand All @@ -36,18 +42,38 @@ class SortDirectionPerCategoryPlugin
*/
private $request;

/**
* Scope configuration.
*
* @var ScopeConfigInterface
*/
private $scopeConfig;

/**
* Store manager.
*
* @var StoreManagerInterface
*/
protected $storeManager;

/**
* Toolbar constructor.
*
* @param CategoryRepositoryInterface $categoryRepository Category Repository.
* @param Http $request Http request.
* @param ScopeConfigInterface $scopeConfig Scope configuration.
* @param StoreManagerInterface $storeManager Store manager.
*/
public function __construct(
CategoryRepositoryInterface $categoryRepository,
Http $request
Http $request,
ScopeConfigInterface $scopeConfig,
StoreManagerInterface $storeManager
) {
$this->categoryRepository = $categoryRepository;
$this->request = $request;
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
}

/**
Expand All @@ -57,6 +83,7 @@ public function __construct(
* @param mixed $collection Collection.
*
* @return array
* @throws NoSuchEntityException
*/
public function beforeSetCollection(ProductListToolbar $subject, $collection)
{
Expand All @@ -69,30 +96,55 @@ public function beforeSetCollection(ProductListToolbar $subject, $collection)
return [$collection];
}

/**
* Retrieve Product List Default Sort Direction By
*
* @return string|null
* @throws NoSuchEntityException
*/
private function getProductListDefaultSortDirectionBy()
{
// Get the current store ID.
$storeId = $this->storeManager->getStore()->getId();

// Fetch system configuration value for 'default_sort_direction_by' at the store level.
return $this->scopeConfig->getValue(
self::XML_PATH_LIST_DEFAULT_SORT_DIRECTION_BY,
ScopeInterface::SCOPE_STORE,
$storeId
);
}

/**
* Get the custom sort direction from the current category.
*
* @return string|null
* @throws NoSuchEntityException
*/
private function getCustomSortDirection()
{
$categoryId = $this->request->getParam('id');

if (!$categoryId) {
return null; // Return null if category ID is not available.
return $this->getProductListDefaultSortDirectionBy(); // Fallback to system config value if no category ID.
}

try {
$category = $this->categoryRepository->get($categoryId);

// Check if the category has a custom sort direction set.
$customDirection = $category->getSortDirection();

// If a custom sort direction exists for the category and is valid, return it.
if ($customDirection && in_array($customDirection, ['asc', 'desc'])) {
return $customDirection;
}
} catch (\Exception $e) {
return null; // Handle category not found or other exceptions.
// Handle exceptions (e.g., category not found) by falling back to the system config.
return $this->getProductListDefaultSortDirectionBy();
}

return null;
// If no custom sort direction for the category, return the default system config.
return $this->getProductListDefaultSortDirectionBy();
}
}
2 changes: 1 addition & 1 deletion src/module-elasticsuite-catalog/i18n/nl_NL.csv
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"Save and Continue Edit","Opslaan en Doorgaan"
"Save","Opslaan"
"1 product","1 artikel"
"<%- count %> products","<%- aantal %> producten"
"<%- count %> products","<%- count %> producten"
"No products in the selected range.","Geen producten in het geselecteerde bereik."
"Search Configuration","Zoekconfiguratie"
"Can be used only with catalog input type Text field, Dropdown, Multiple Select and Price.","Kan alleen gebruikt worden met invoertype catalogus, tekstveld, Dropdown, Multiple select en Prijs."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ interface ClientConfigurationInterface
*/
public function getServerList();

/**
* Indicates whether the body of requests in error should be logged or not.
*
* @return boolean
*/
public function isLoggingErrorRequest();

/**
* Indicates whether the debug node is enabled or not.
*
Expand Down
29 changes: 26 additions & 3 deletions src/module-elasticsuite-core/Client/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
namespace Smile\ElasticsuiteCore\Client;

use Elasticsearch\Common\Exceptions\Missing404Exception;
use Psr\Log\LoggerInterface;
use Smile\ElasticsuiteCore\Api\Client\ClientConfigurationInterface;
use Smile\ElasticsuiteCore\Api\Client\ClientInterface;

Expand Down Expand Up @@ -44,16 +45,26 @@ class Client implements ClientInterface
*/
private $clientBuilder;

/**
* @var LoggerInterface
*/
private $logger;

/**
* Constructor.
*
* @param ClientConfigurationInterface $clientConfiguration Client configuration factory.
* @param ClientBuilder $clientBuilder ES client builder.
* @param LoggerInterface $logger Logger.
*/
public function __construct(ClientConfigurationInterface $clientConfiguration, ClientBuilder $clientBuilder)
{
public function __construct(
ClientConfigurationInterface $clientConfiguration,
ClientBuilder $clientBuilder,
LoggerInterface $logger
) {
$this->clientConfiguration = $clientConfiguration;
$this->clientBuilder = $clientBuilder;
$this->logger = $logger;
}

/**
Expand Down Expand Up @@ -201,10 +212,22 @@ public function bulk($bulkParams)

/**
* {@inheritDoc}
* @throws \Exception
*/
public function search($params)
{
return $this->getEsClient()->search($params);
try {
$response = $this->getEsClient()->search($params);
} catch (\Exception $e) {
if ($this->clientConfiguration->isLoggingErrorRequest()) {
$requestInfo = json_encode($params, JSON_PRESERVE_ZERO_FRACTION + JSON_INVALID_UTF8_SUBSTITUTE);
$this->logger->error(sprintf("Search Request Failure [error] : %s", $e->getMessage()));
$this->logger->error(sprintf("Search Request Failure [request] : %s", $requestInfo));
}
throw $e;
}

return $response;
}

/**
Expand Down
8 changes: 8 additions & 0 deletions src/module-elasticsuite-core/Client/ClientConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ public function getServerList()
return explode(',', $this->getElasticsearchClientConfigParam('servers') ?? '');
}

/**
* {@inheritDoc}
*/
public function isLoggingErrorRequest()
{
return (bool) $this->getElasticsearchClientConfigParam('enable_error_request_logging');
}

/**
* {@inheritdoc}
*/
Expand Down
40 changes: 28 additions & 12 deletions src/module-elasticsuite-core/Model/Search.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@

namespace Smile\ElasticsuiteCore\Model;

use Magento\Framework\Search\SearchEngineInterface;
use Magento\Framework\Search\SearchResponseBuilder;
use Smile\ElasticsuiteCore\Api\Search\ContextInterface;
use Smile\ElasticsuiteCore\Model\Search\RequestBuilder;

/**
* SearchInterface implementation using elasticsuite.
*
Expand All @@ -24,35 +29,43 @@
class Search implements \Magento\Search\Api\SearchInterface
{
/**
* @var \Smile\ElasticsuiteCore\Model\Search\RequestBuilder
* @var RequestBuilder
*/
private $searchRequestBuilder;

/**
* @var \Magento\Framework\Search\SearchEngineInterface
* @var SearchEngineInterface
*/
private $searchEngine;

/**
* @var \Magento\Framework\Search\SearchResponseBuilder
* @var SearchResponseBuilder
*/
private $searchResponseBuilder;

/**
* @var ContextInterface
*/
private $searchContext;

/**
* Constructor.
*
* @param \Magento\Framework\Search\SearchEngineInterface $searchEngine Search engine.
* @param \Smile\ElasticsuiteCore\Model\Search\RequestBuilder $searchRequestBuilder Search request builder.
* @param \Magento\Framework\Search\SearchResponseBuilder $searchResponseBuilder Search response builder.
* @param SearchEngineInterface $searchEngine Search engine.
* @param RequestBuilder $searchRequestBuilder Search request builder.
* @param SearchResponseBuilder $searchResponseBuilder Search response builder.
* @param ContextInterface $searchContext Search context.
*/
public function __construct(
\Magento\Framework\Search\SearchEngineInterface $searchEngine,
\Smile\ElasticsuiteCore\Model\Search\RequestBuilder $searchRequestBuilder,
\Magento\Framework\Search\SearchResponseBuilder $searchResponseBuilder
SearchEngineInterface $searchEngine,
RequestBuilder $searchRequestBuilder,
SearchResponseBuilder $searchResponseBuilder,
ContextInterface $searchContext
) {
$this->searchRequestBuilder = $searchRequestBuilder;
$this->searchEngine = $searchEngine;
$this->searchResponseBuilder = $searchResponseBuilder;
$this->searchRequestBuilder = $searchRequestBuilder;
$this->searchEngine = $searchEngine;
$this->searchResponseBuilder = $searchResponseBuilder;
$this->searchContext = $searchContext;
}

/**
Expand All @@ -68,10 +81,13 @@ public function search(\Magento\Framework\Api\Search\SearchCriteriaInterface $se
$searchResponse = $this->searchEngine->search($searchRequest);
$searchResult = $this->searchResponseBuilder->build($searchResponse);

$query = $this->searchContext->getCurrentSearchQuery();

$totalCount = $searchResponse->count();
$searchResult->setTotalCount($totalCount);
$searchResult->setSearchCriteria($searchCriteria);
$searchResult->setData('is_spellchecked', (bool) $searchRequest->isSpellchecked());
$searchResult->setData('query_id', ($query && $query->getId()) ? (int) $query->getId() : null);

return $searchResult;
}
Expand Down
Loading

0 comments on commit 322ec6b

Please sign in to comment.