From 20973b27ecbf7fdc5fd15c84243bd92dbd2e0c4d Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Thu, 25 Aug 2022 14:33:15 +0530 Subject: [PATCH 01/73] MAGE-361 Add Recommend dashboard link in magento admin Recommend configuration --- Helper/Configuration/NoticeHelper.php | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Helper/Configuration/NoticeHelper.php b/Helper/Configuration/NoticeHelper.php index 6d06839d4..61d83447b 100644 --- a/Helper/Configuration/NoticeHelper.php +++ b/Helper/Configuration/NoticeHelper.php @@ -43,6 +43,7 @@ class NoticeHelper extends \Magento\Framework\App\Helper\AbstractHelper 'getVersionNotice', 'getClickAnalyticsNotice', 'getPersonalizationNotice', + 'getRecommendNotice', ]; /** @var array[] */ @@ -317,4 +318,26 @@ public function getNewVersionNotification() { return $this->extensionNotification->checkVersion(); } + + /** + * @return void + */ + protected function getRecommendNotice() + { + // If the integration is disabled in Magento Admin, no need to display a notice + if ($this->configHelper->getApplicationID()) { + return; + } + $noticeContent = ''; + + $selector = '#algoliasearch_recommend_recommend'; + $method = 'after'; + + $this->notices[] = [ + 'selector' => $selector, + 'method' => $method, + 'message' => $noticeContent, + ]; + } } From 442b55d02d99100f1764a4c95abb28c8ef50fa7d Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 26 Aug 2022 14:08:42 +0530 Subject: [PATCH 02/73] Updated message for recommend dashboard link --- Helper/Configuration/NoticeHelper.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Helper/Configuration/NoticeHelper.php b/Helper/Configuration/NoticeHelper.php index 61d83447b..2e23542ff 100644 --- a/Helper/Configuration/NoticeHelper.php +++ b/Helper/Configuration/NoticeHelper.php @@ -325,11 +325,11 @@ public function getNewVersionNotification() protected function getRecommendNotice() { // If the integration is disabled in Magento Admin, no need to display a notice - if ($this->configHelper->getApplicationID()) { + if (!$this->configHelper->getApplicationID()) { return; } - $noticeContent = ''; + $noticeContent = '

Algolia Dashboard

+

Configure your Recommend models on the Algolia Dashboard

'; $selector = '#algoliasearch_recommend_recommend'; $method = 'after'; From a16e3c12ab74f0bc953f0ea742a3832adb4328d6 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Mon, 29 Aug 2022 19:03:40 +0530 Subject: [PATCH 03/73] MAGE-362 Recommend Trending --- Block/Configuration.php | 7 + Block/Widget/TrendsItem.php | 29 ++++ Helper/ConfigHelper.php | 105 ++++++++++++ etc/adminhtml/system.xml | 79 +++++++++ etc/config.xml | 1 + .../frontend/layout/algolia_search_handle.xml | 2 + view/frontend/layout/catalog_product_view.xml | 4 - view/frontend/layout/checkout_cart_index.xml | 15 ++ .../templates/recommend/cart/trends.phtml | 7 + .../templates/recommend/products.phtml | 1 + .../recommend/widget/trends-item.phtml | 14 ++ view/frontend/web/recommend.js | 151 ++++++++++++++---- 12 files changed, 381 insertions(+), 34 deletions(-) create mode 100644 Block/Widget/TrendsItem.php create mode 100644 view/frontend/layout/checkout_cart_index.xml create mode 100644 view/frontend/templates/recommend/cart/trends.phtml create mode 100644 view/frontend/templates/recommend/widget/trends-item.phtml diff --git a/Block/Configuration.php b/Block/Configuration.php index c5f41b524..ea52f9c36 100755 --- a/Block/Configuration.php +++ b/Block/Configuration.php @@ -167,6 +167,13 @@ public function getConfiguration() 'enabledRelated' => $config->isRecommendRelatedProductsEnabled(), 'limitFBTProducts' => $config->getNumberOfFrequentlyBoughtTogetherProducts(), 'limitRelatedProducts' => $config->getNumberOfRelatedProducts(), + 'limitTrendingItems' => $config->getNumberOfTrendingItems(), + 'enabledTrendItems' => $config->isRecommendTrendingItemsEnabled(), + 'trendItemsType' => $config->getTrendingItemsType(), + 'trendItemFacetName' => $config->getTrendingItemsFacetName(), + 'trendItemFacetValue' => $config->getTrendingItemsFacetValue(), + 'isTrendItemsEnabledInPDP' => $config->isTrendItemsEnabledInPDP(), + 'isTrendItemsEnabledInCartPage' => $config->isTrendItemsEnabledInShoppingCart(), ], 'extensionVersion' => $config->getExtensionVersion(), 'applicationId' => $config->getApplicationID(), diff --git a/Block/Widget/TrendsItem.php b/Block/Widget/TrendsItem.php new file mode 100644 index 000000000..46b149b36 --- /dev/null +++ b/Block/Widget/TrendsItem.php @@ -0,0 +1,29 @@ +mathRandom = $mathRandom; + parent::__construct( + $context, + $data + ); + } + + public function generateUniqueToken() + { + return $this->mathRandom->getRandomString(5); + } + +} diff --git a/Helper/ConfigHelper.php b/Helper/ConfigHelper.php index 58e8871db..a308a7c33 100755 --- a/Helper/ConfigHelper.php +++ b/Helper/ConfigHelper.php @@ -115,6 +115,13 @@ class ConfigHelper public const NUM_OF_RECOMMEND_RELATED_PRODUCTS = 'algoliasearch_recommend/recommend/num_of_related_products'; public const IS_REMOVE_RELATED_PRODUCTS_BLOCK = 'algoliasearch_recommend/recommend/is_remove_core_related_products_block'; public const IS_REMOVE_UPSELL_PRODUCTS_BLOCK = 'algoliasearch_recommend/recommend/is_remove_core_upsell_products_block'; + protected const IS_RECOMMEND_TRENDING_ITEMS_ENABLED = 'algoliasearch_recommend/recommend/is_trending_items_enabled'; + protected const RECOMMEND_TRENDING_ITEMS_TYPE = 'algoliasearch_recommend/recommend/trending_items_type'; + protected const NUM_OF_TRENDING_ITEMS = 'algoliasearch_recommend/recommend/num_of_trending_items'; + protected const TREND_ITEMS_FACET_NAME = 'algoliasearch_recommend/recommend/facet_name'; + protected const TREND_ITEMS_FACET_VALUE = 'algoliasearch_recommend/recommend/facet_value'; + protected const IS_TREND_ITEMS_ENABLED_IN_PDP = 'algoliasearch_recommend/recommend/is_trending_items_enabled_on_pdp'; + protected const IS_TREND_ITEMS_ENABLED_IN_SHOPPING_CART = 'algoliasearch_recommend/recommend/is_trending_items_enabled_on_cart_page'; private $configInterface; private $objectManager; @@ -499,6 +506,104 @@ public function getNumberOfFrequentlyBoughtTogetherProducts($storeId = null) $storeId ); } + + /** + * @param int $storeId + * + * @return int + */ + public function isRecommendTrendingItemsEnabled($storeId = null) + { + return (int) $this->configInterface->getValue( + self::IS_RECOMMEND_TRENDING_ITEMS_ENABLED, + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + /** + * @param int $storeId + * + * @return int + */ + public function getNumberOfTrendingItems($storeId = null) + { + return (int) $this->configInterface->getValue( + self::NUM_OF_TRENDING_ITEMS, + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + /** + * @param int $storeId + * + * @return string + */ + public function getTrendingItemsType($storeId = null) + { + return $this->configInterface->getValue( + self::RECOMMEND_TRENDING_ITEMS_TYPE, + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + /** + * @param int $storeId + * + * @return string + */ + public function getTrendingItemsFacetName($storeId = null) + { + return $this->configInterface->getValue( + self::TREND_ITEMS_FACET_NAME, + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + /** + * @param int $storeId + * + * @return string + */ + public function getTrendingItemsFacetValue($storeId = null) + { + return $this->configInterface->getValue( + self::TREND_ITEMS_FACET_VALUE, + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + /** + * @param int $storeId + * + * @return int + */ + public function isTrendItemsEnabledInPDP($storeId = null) + { + return (int) $this->configInterface->getValue( + self::IS_TREND_ITEMS_ENABLED_IN_PDP, + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + /** + * @param int $storeId + * + * @return int + */ + public function isTrendItemsEnabledInShoppingCart($storeId = null) + { + return (int) $this->configInterface->getValue( + self::IS_TREND_ITEMS_ENABLED_IN_SHOPPING_CART, + ScopeInterface::SCOPE_STORE, + $storeId + ); + } public function useAdaptiveImage($storeId = null) { diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 4bb49c51a..0c38313a5 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -542,6 +542,85 @@ ]]> + + + Magento\Config\Model\Config\Source\Yesno + + + + + + + Algolia\AlgoliaSearch\Model\Source\TrendingItemType + + + + + + + required-entry validate-digits + + + + + 1 + + + + + required-entry + + + + + + trending_items_for_facets + + + + + required-entry + + + + + trending_items_for_facets + + + + + Magento\Config\Model\Config\Source\Yesno + + + + + 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + + + + 1 + +
diff --git a/etc/config.xml b/etc/config.xml index 766b52138..e1a34ec7c 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -46,6 +46,7 @@ 6 6 + 6 diff --git a/view/frontend/layout/algolia_search_handle.xml b/view/frontend/layout/algolia_search_handle.xml index 3bdab2932..07c562a7b 100755 --- a/view/frontend/layout/algolia_search_handle.xml +++ b/view/frontend/layout/algolia_search_handle.xml @@ -6,11 +6,13 @@ diff --git a/view/frontend/templates/recommend/widget/trends-item.phtml b/view/frontend/templates/recommend/widget/trends-item.phtml new file mode 100644 index 000000000..333f979a5 --- /dev/null +++ b/view/frontend/templates/recommend/widget/trends-item.phtml @@ -0,0 +1,14 @@ +generateUniqueToken(); +?> +
+ diff --git a/view/frontend/web/recommend.js b/view/frontend/web/recommend.js index 5d1d89403..f36626924 100644 --- a/view/frontend/web/recommend.js +++ b/view/frontend/web/recommend.js @@ -1,48 +1,139 @@ requirejs([ + 'jquery', 'recommend', 'recommendJs', 'algoliaBundle' -], function (recommend, recommendJs, algoliaBundle) { +], function ($, recommend, recommendJs, algoliaBundle) { this.config = algoliaConfig; this.defaultIndexName = algoliaConfig.indexName + '_products'; const appId = this.config.applicationId; const apiKey = this.config.apiKey; const recommendClient = recommend(appId, apiKey); const indexName = this.defaultIndexName; - // --- Add the current product objectID here --- - const currentObjectID = objectId; - if (this.config.recommend.enabledFBT) { - recommendJs.frequentlyBoughtTogether({ - container: '#frequentlyBoughtTogether', - recommendClient, - indexName, - objectIDs: [currentObjectID], - maxRecommendations: this.config.recommend.limitFBTProducts, - itemComponent({item, createElement, Fragment}) { - return createElement( - 'div', - null, - createElement( + if ($('body').hasClass('catalog-product-view')) { + // --- Add the current product objectID here --- + const currentObjectID = objectId; + if (this.config.recommend.enabledFBT) { + recommendJs.frequentlyBoughtTogether({ + container: '#frequentlyBoughtTogether', + recommendClient, + indexName, + objectIDs: [currentObjectID], + maxRecommendations: this.config.recommend.limitFBTProducts, + itemComponent({item, createElement, Fragment}) { + var correctFKey = getCookie('form_key'); + var action = config.instant.addToCartParams.action + 'product/' + item.objectID + '/'; + if(correctFKey != "" && config.instant.addToCartParams.formKey != correctFKey) { + config.instant.addToCartParams.formKey = correctFKey; + } + return createElement( + 'div', + null, + createElement( + 'div', + {className: "product-details"}, + createElement( + 'a', + {className: "product-url", href: item.url}, + createElement('img', {className: "product-img", src: item.image_url}, item.image_url), + createElement('p', {className: "product-name"}, item.name) + ) + ) + ); + }, + }); + } + if (this.config.recommend.enabledRelated) { + recommendJs.relatedProducts({ + container: '#relatedProducts', + recommendClient, + indexName, + objectIDs: [currentObjectID], + maxRecommendations: this.config.recommend.limitRelatedProducts, + itemComponent({item, createElement, Fragment}) { + var correctFKey = getCookie('form_key'); + var action = config.instant.addToCartParams.action + 'product/' + item.objectID + '/'; + if(correctFKey != "" && config.instant.addToCartParams.formKey != correctFKey) { + config.instant.addToCartParams.formKey = correctFKey; + } + return createElement( + 'div', + null, + createElement( + 'div', + {className: "product-details"}, + createElement( + 'a', + {className: "product-url", href: item.url}, + createElement('img', {className: "product-img", src: item.image_url}, item.image_url), + createElement('p', {className: "product-name"}, item.name) + ) + ) + ); + }, + }); + } + } + + if (this.config.recommend.enabledTrendItems && ((this.config.recommend.isTrendItemsEnabledInPDP && $('body').hasClass('catalog-product-view')) || (this.config.recommend.isTrendItemsEnabledInCartPage && $('body').hasClass('checkout-cart-index'))) ) { + if(this.config.recommend.trendItemsType == "trending_items_for_facets" && this.config.recommend.trendItemFacetName && this.config.recommend.trendItemFacetValue){ + recommendJs.trendingItems({ + container: '#trendItems', + facetName: this.config.recommend.trendItemFacetName, + facetValue: this.config.recommend.trendItemFacetValue, + recommendClient, + indexName, + maxRecommendations: this.config.recommend.limitTrendingItems, + itemComponent({item, createElement, Fragment}) { + return createElement( 'div', - {className: "product-details"}, + null, createElement( - 'a', - {className: "product-url", href: item.url}, - createElement('img', {className: "product-img", src: item.image_url}, item.image_url), - createElement('p', {className: "product-name"}, item.name) + 'div', + {className: "product-details"}, + createElement( + 'a', + {className: "product-url", href: item.url}, + createElement('img', {className: "product-img", src: item.image_url}, item.image_url), + createElement('p', {className: "product-name"}, item.name) + ) ) - ) - ); - }, - }); - } - if (this.config.recommend.enabledRelated) { - recommendJs.relatedProducts({ - container: '#relatedProducts', + ); + }, + }); + } else { + recommendJs.trendingItems({ + container: '#trendItems', + recommendClient, + indexName, + maxRecommendations: this.config.recommend.limitTrendingItems, + itemComponent({item, createElement, Fragment}) { + return createElement( + 'div', + null, + createElement( + 'div', + {className: "product-details"}, + createElement( + 'a', + {className: "product-url", href: item.url}, + createElement('img', {className: "product-img", src: item.image_url}, item.image_url), + createElement('p', {className: "product-name"}, item.name) + ) + ) + ); + }, + }); + } + }else if(this.config.recommend.enabledTrendItems && typeof recommendTrendContainer !== "undefined" && typeof facetName !== "undefined" && typeof facetValue !== "undefined"){ + let containerValue = "#"+recommendTrendContainer; + recommendJs.trendingItems({ + container: containerValue, + facetName: facetName, + facetValue: facetValue, recommendClient, indexName, - objectIDs: [currentObjectID], - maxRecommendations: this.config.recommend.limitRelatedProducts, + maxRecommendations: this.config.recommend.limitTrendingItems, itemComponent({item, createElement, Fragment}) { return createElement( 'div', From 18916f1154751fc46982e0931746df0b20eede6d Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Tue, 30 Aug 2022 18:00:50 +0530 Subject: [PATCH 04/73] Added Source System File --- Model/Source/TrendingItemType.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Model/Source/TrendingItemType.php diff --git a/Model/Source/TrendingItemType.php b/Model/Source/TrendingItemType.php new file mode 100644 index 000000000..e6838dcb6 --- /dev/null +++ b/Model/Source/TrendingItemType.php @@ -0,0 +1,16 @@ + 'trending_global_item', 'label' => __('Trending Global Items')], + ['value' => 'trending_items_for_facets', 'label' => __('Trending items for facets')] + ]; + } +} From 741412f1ad0ec28c6f3abc34e672642bd030038a Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Tue, 30 Aug 2022 18:11:23 +0530 Subject: [PATCH 05/73] Updated function message --- Helper/Configuration/NoticeHelper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Helper/Configuration/NoticeHelper.php b/Helper/Configuration/NoticeHelper.php index 2e23542ff..0738e8439 100644 --- a/Helper/Configuration/NoticeHelper.php +++ b/Helper/Configuration/NoticeHelper.php @@ -320,11 +320,11 @@ public function getNewVersionNotification() } /** + * Function created for adding the Algolia Dashboard link in the Magento recommend system configuration * @return void */ protected function getRecommendNotice() { - // If the integration is disabled in Magento Admin, no need to display a notice if (!$this->configHelper->getApplicationID()) { return; } From a733018bb69e067f5c46f9172c671ce98a49ceb1 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Mon, 5 Sep 2022 18:01:23 +0530 Subject: [PATCH 06/73] Updated Trends code and Php cs fixer --- Block/Widget/TrendsItem.php | 11 +- Model/Source/TrendingItemType.php | 2 +- Plugin/RemovePdpProductsBlock.php | 2 +- etc/adminhtml/system.xml | 295 +++++++++--------- etc/config.xml | 12 +- etc/widget.xml | 18 ++ .../recommend/widget/trends-item.phtml | 4 +- 7 files changed, 193 insertions(+), 151 deletions(-) create mode 100644 etc/widget.xml diff --git a/Block/Widget/TrendsItem.php b/Block/Widget/TrendsItem.php index 46b149b36..cbc303314 100644 --- a/Block/Widget/TrendsItem.php +++ b/Block/Widget/TrendsItem.php @@ -1,13 +1,15 @@ mathRandom->getRandomString(5); } - } diff --git a/Model/Source/TrendingItemType.php b/Model/Source/TrendingItemType.php index e6838dcb6..ee5305f18 100644 --- a/Model/Source/TrendingItemType.php +++ b/Model/Source/TrendingItemType.php @@ -10,7 +10,7 @@ public function toOptionArray() { return [ ['value' => 'trending_global_item', 'label' => __('Trending Global Items')], - ['value' => 'trending_items_for_facets', 'label' => __('Trending items for facets')] + ['value' => 'trending_items_for_facets', 'label' => __('Trending items for facets')], ]; } } diff --git a/Plugin/RemovePdpProductsBlock.php b/Plugin/RemovePdpProductsBlock.php index e765c6171..22b3ccb90 100644 --- a/Plugin/RemovePdpProductsBlock.php +++ b/Plugin/RemovePdpProductsBlock.php @@ -30,7 +30,7 @@ public function __construct(ConfigHelper $configHelper) */ public function afterToHtml(AbstractBlock $subject, $result) { - if (($subject->getNameInLayout() === self::RELATED_BLOCK_NAME && $this->_configHelper->isRemoveCoreRelatedProductsBlock()) || ($subject->getNameInLayout() === self::UPSELL_BLOCK_NAME && $this->_configHelper->isRemoveUpsellProductsBlock())) { + if (($subject->getNameInLayout() === self::RELATED_BLOCK_NAME && $this->_configHelper->isRecommendRelatedProductsEnabled() && $this->_configHelper->isRemoveCoreRelatedProductsBlock()) || ($subject->getNameInLayout() === self::UPSELL_BLOCK_NAME && $this->_configHelper->isRecommendFrequentlyBroughtTogetherEnabled() && $this->_configHelper->isRemoveUpsellProductsBlock())) { return ''; } diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 1e5eba4f6..c6258966a 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -468,7 +468,7 @@
-
+
algolia Algolia_AlgoliaSearch::algolia_algoliasearch @@ -479,148 +479,165 @@
]]> - - - Magento\Config\Model\Config\Source\Yesno - - Enabling Frequently Bought Together products can potentially break your design on PDP page and some work will be required to have a good integration with your theme. - ]]> - - - - validate-digits - - - + + + + Magento\Config\Model\Config\Source\Yesno + + Enabling frequently bought together products can potentially break your design on PDP page and some work will be required to have a good integration with your theme. + ]]> + + + + validate-digits + + + - - - 1 - - - - - Magento\Config\Model\Config\Source\Yesno - - Enabling Related Products can potentially break your design on PDP page and some work will be required to have a good integration with your theme. - ]]> - - - - - validate-digits - - - - - - 1 - - - - - Magento\Config\Model\Config\Source\Yesno - - - - - - - Magento\Config\Model\Config\Source\Yesno - - + + 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + - - - - - Magento\Config\Model\Config\Source\Yesno - - - - - - - Algolia\AlgoliaSearch\Model\Source\TrendingItemType - - - - - - - required-entry validate-digits - - - - - 1 - - - - - required-entry - - - - - - trending_items_for_facets - - - - - required-entry - - - - - trending_items_for_facets - - - - - Magento\Config\Model\Config\Source\Yesno - - - - - 1 - - - - - Magento\Config\Model\Config\Source\Yesno - - - - - 1 - - + + + 1 + + + + + + + + Magento\Config\Model\Config\Source\Yesno + + Enabling related products can potentially break your design on PDP page and some work will be required to have a good integration with your theme. + ]]> + + + + validate-digits + + + + + + 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + + + + 1 + + + + + + + + Magento\Config\Model\Config\Source\Yesno + + + + + + + Algolia\AlgoliaSearch\Model\Source\TrendingItemType + + + + + 1 + + + + + required-entry + + + + + + trending_items_for_facets + + + + + required-entry + + + + + trending_items_for_facets + + + + + required-entry validate-digits + + + + + 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + + + + 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + + + + 1 + + +
diff --git a/etc/config.xml b/etc/config.xml index e1a34ec7c..269d72f12 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -44,9 +44,15 @@ - 6 - 6 - 6 + + 6 + + + 6 + + + 6 + diff --git a/etc/widget.xml b/etc/widget.xml new file mode 100644 index 000000000..cb58f08ad --- /dev/null +++ b/etc/widget.xml @@ -0,0 +1,18 @@ + + + + + You can allow Algolia Recommend Trends item to appear anywhere you want + + + + + + + + + + + + + diff --git a/view/frontend/templates/recommend/widget/trends-item.phtml b/view/frontend/templates/recommend/widget/trends-item.phtml index 333f979a5..06d27d00c 100644 --- a/view/frontend/templates/recommend/widget/trends-item.phtml +++ b/view/frontend/templates/recommend/widget/trends-item.phtml @@ -3,7 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -$trendConstainer = "trendItems".$block->generateUniqueToken(); +$trendConstainer = 'trendItems' . $block->generateUniqueToken(); ?>
+ \ No newline at end of file From d3118a1cfb5a82929e7b7f29a4b4012323075c0a Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Tue, 6 Sep 2022 13:11:18 +0530 Subject: [PATCH 07/73] Fix Mage-374 autocomplete issue --- view/frontend/web/internals/autocomplete.css | 6 ++++++ view/frontend/web/internals/common.js | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/view/frontend/web/internals/autocomplete.css b/view/frontend/web/internals/autocomplete.css index b49dcc741..360916a10 100755 --- a/view/frontend/web/internals/autocomplete.css +++ b/view/frontend/web/internals/autocomplete.css @@ -472,6 +472,7 @@ } .aa-Panel li.aa-Item{ list-style-type: none; + display: flex; } .aa-Panel .aa-PanelLayout{ @@ -511,6 +512,11 @@ width: 220px !important; } } +@media (max-width: 768px) { + #algolia-autocomplete-container .aa-dropdown-menu .algoliasearch-autocomplete-hit .info, .aa-Panel .algoliasearch-autocomplete-hit .info{ + padding-left: 15px; + } +} @media (min-width: 769px) { .aa-Panel.productColumn2 .aa-PanelLayout section:nth-child(1){ grid-area: 1 / 1 / 2 / 2; diff --git a/view/frontend/web/internals/common.js b/view/frontend/web/internals/common.js index 9a07b1fb1..2408a139e 100755 --- a/view/frontend/web/internals/common.js +++ b/view/frontend/web/internals/common.js @@ -376,7 +376,7 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { ${components.Highlight({hit: _data, attribute: 'name'}) || ''}
${color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : - html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}`} + _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''}
@@ -395,7 +395,7 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { ${components.Highlight({hit: _data, attribute: 'name'}) || ''}
${color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : - html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}`} + _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''}
From 70b34222d0d39bb4691ef4f776410dd2c4472a6d Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 9 Sep 2022 16:08:00 +0530 Subject: [PATCH 08/73] Added addtocart button in recommends item and refactor recommend js --- Block/Configuration.php | 5 +- Helper/ConfigHelper.php | 71 ++++++++----- etc/adminhtml/system.xml | 77 +++++++++----- view/frontend/web/recommend.js | 181 ++++++++++++++------------------- 4 files changed, 175 insertions(+), 159 deletions(-) diff --git a/Block/Configuration.php b/Block/Configuration.php index ea52f9c36..3c6abf689 100755 --- a/Block/Configuration.php +++ b/Block/Configuration.php @@ -169,11 +169,14 @@ public function getConfiguration() 'limitRelatedProducts' => $config->getNumberOfRelatedProducts(), 'limitTrendingItems' => $config->getNumberOfTrendingItems(), 'enabledTrendItems' => $config->isRecommendTrendingItemsEnabled(), - 'trendItemsType' => $config->getTrendingItemsType(), 'trendItemFacetName' => $config->getTrendingItemsFacetName(), 'trendItemFacetValue' => $config->getTrendingItemsFacetValue(), 'isTrendItemsEnabledInPDP' => $config->isTrendItemsEnabledInPDP(), 'isTrendItemsEnabledInCartPage' => $config->isTrendItemsEnabledInShoppingCart(), + 'isAddToCartEnabledInFBT' => $config->isAddToCartEnabledInFrequentlyBoughtTogether(), + 'isAddToCartEnabledInRelatedProduct' => $config->isAddToCartEnabledInRelatedProducts(), + 'isAddToCartEnabledInTrendsItem' => $config->isAddToCartEnabledInTrendsItem(), + 'addToCartParams' => $addToCartParams, ], 'extensionVersion' => $config->getExtensionVersion(), 'applicationId' => $config->getApplicationID(), diff --git a/Helper/ConfigHelper.php b/Helper/ConfigHelper.php index a308a7c33..45113af21 100755 --- a/Helper/ConfigHelper.php +++ b/Helper/ConfigHelper.php @@ -109,19 +109,21 @@ class ConfigHelper public const DEFAULT_MAX_RECORD_SIZE = 10000; - public const IS_RECOMMEND_FREQUENTLY_BOUGHT_TOGETHER_ENABLED = 'algoliasearch_recommend/recommend/is_frequently_bought_together_enabled'; - public const IS_RECOMMEND_RELATED_PRODUCTS_ENABLED = 'algoliasearch_recommend/recommend/is_related_products_enabled'; - public const NUM_OF_RECOMMEND_FREQUENTLY_BOUGHT_TOGETHER_PRODUCTS = 'algoliasearch_recommend/recommend/num_of_frequently_bought_together_products'; - public const NUM_OF_RECOMMEND_RELATED_PRODUCTS = 'algoliasearch_recommend/recommend/num_of_related_products'; - public const IS_REMOVE_RELATED_PRODUCTS_BLOCK = 'algoliasearch_recommend/recommend/is_remove_core_related_products_block'; - public const IS_REMOVE_UPSELL_PRODUCTS_BLOCK = 'algoliasearch_recommend/recommend/is_remove_core_upsell_products_block'; - protected const IS_RECOMMEND_TRENDING_ITEMS_ENABLED = 'algoliasearch_recommend/recommend/is_trending_items_enabled'; - protected const RECOMMEND_TRENDING_ITEMS_TYPE = 'algoliasearch_recommend/recommend/trending_items_type'; - protected const NUM_OF_TRENDING_ITEMS = 'algoliasearch_recommend/recommend/num_of_trending_items'; - protected const TREND_ITEMS_FACET_NAME = 'algoliasearch_recommend/recommend/facet_name'; - protected const TREND_ITEMS_FACET_VALUE = 'algoliasearch_recommend/recommend/facet_value'; - protected const IS_TREND_ITEMS_ENABLED_IN_PDP = 'algoliasearch_recommend/recommend/is_trending_items_enabled_on_pdp'; - protected const IS_TREND_ITEMS_ENABLED_IN_SHOPPING_CART = 'algoliasearch_recommend/recommend/is_trending_items_enabled_on_cart_page'; + protected const IS_RECOMMEND_FREQUENTLY_BOUGHT_TOGETHER_ENABLED = 'algoliasearch_recommend/recommend/frequently_bought_together/is_frequently_bought_together_enabled'; + protected const IS_RECOMMEND_RELATED_PRODUCTS_ENABLED = 'algoliasearch_recommend/recommend/related_product/is_related_products_enabled'; + protected const NUM_OF_RECOMMEND_FREQUENTLY_BOUGHT_TOGETHER_PRODUCTS = 'algoliasearch_recommend/recommend/frequently_bought_together/num_of_frequently_bought_together_products'; + protected const NUM_OF_RECOMMEND_RELATED_PRODUCTS = 'algoliasearch_recommend/recommend/related_product/num_of_related_products'; + protected const IS_REMOVE_RELATED_PRODUCTS_BLOCK = 'algoliasearch_recommend/recommend/related_product/is_remove_core_related_products_block'; + protected const IS_REMOVE_UPSELL_PRODUCTS_BLOCK = 'algoliasearch_recommend/recommend/frequently_bought_together/is_remove_core_upsell_products_block'; + protected const IS_RECOMMEND_TRENDING_ITEMS_ENABLED = 'algoliasearch_recommend/recommend/trends_item/is_trending_items_enabled'; + protected const NUM_OF_TRENDING_ITEMS = 'algoliasearch_recommend/recommend/trends_item/num_of_trending_items'; + protected const TREND_ITEMS_FACET_NAME = 'algoliasearch_recommend/recommend/trends_item/facet_name'; + protected const TREND_ITEMS_FACET_VALUE = 'algoliasearch_recommend/recommend/trends_item/facet_value'; + protected const IS_TREND_ITEMS_ENABLED_IN_PDP = 'algoliasearch_recommend/recommend/trends_item/is_trending_items_enabled_on_pdp'; + protected const IS_TREND_ITEMS_ENABLED_IN_SHOPPING_CART = 'algoliasearch_recommend/recommend/trends_item/is_trending_items_enabled_on_cart_page'; + protected const IS_ADDTOCART_ENABLED_IN_FREQUENTLY_BOUGHT_TOGETHER = 'algoliasearch_recommend/recommend/frequently_bought_together/is_addtocart_enabled'; + protected const IS_ADDTOCART_ENABLED_IN_RELATED_PRODUCTS= 'algoliasearch_recommend/recommend/related_product/is_addtocart_enabled'; + protected const IS_ADDTOCART_ENABLED_IN_TRENDS_ITEM= 'algoliasearch_recommend/recommend/trends_item/is_addtocart_enabled'; private $configInterface; private $objectManager; @@ -535,19 +537,6 @@ public function getNumberOfTrendingItems($storeId = null) ); } - /** - * @param int $storeId - * - * @return string - */ - public function getTrendingItemsType($storeId = null) - { - return $this->configInterface->getValue( - self::RECOMMEND_TRENDING_ITEMS_TYPE, - ScopeInterface::SCOPE_STORE, - $storeId - ); - } /** * @param int $storeId @@ -605,6 +594,36 @@ public function isTrendItemsEnabledInShoppingCart($storeId = null) ); } + /** + * @param int $storeId + * + * @return int + */ + public function isAddToCartEnabledInFrequentlyBoughtTogether($storeId = null) + { + return $this->configInterface->isSetFlag(self::IS_ADDTOCART_ENABLED_IN_FREQUENTLY_BOUGHT_TOGETHER, ScopeInterface::SCOPE_STORE, $storeId); + } + + /** + * @param int $storeId + * + * @return int + */ + public function isAddToCartEnabledInRelatedProducts($storeId = null) + { + return $this->configInterface->isSetFlag(self::IS_ADDTOCART_ENABLED_IN_RELATED_PRODUCTS, ScopeInterface::SCOPE_STORE, $storeId); + } + + /** + * @param int $storeId + * + * @return int + */ + public function isAddToCartEnabledInTrendsItem($storeId = null) + { + return $this->configInterface->isSetFlag(self::IS_ADDTOCART_ENABLED_IN_TRENDS_ITEM, ScopeInterface::SCOPE_STORE, $storeId); + } + public function useAdaptiveImage($storeId = null) { return $this->configInterface->isSetFlag(self::USE_ADAPTIVE_IMAGE, ScopeInterface::SCOPE_STORE, $storeId); diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index c6258966a..2a38c3431 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -468,7 +468,7 @@
-
+
algolia Algolia_AlgoliaSearch::algolia_algoliasearch @@ -503,7 +503,19 @@ 1 - + + + Magento\Config\Model\Config\Source\Yesno + + + + + 1 + + + Magento\Config\Model\Config\Source\Yesno @@ -518,7 +530,7 @@ - + Magento\Config\Model\Config\Source\Yesno @@ -528,7 +540,7 @@ ]]> - + validate-digits @@ -540,7 +552,19 @@ 1 - + + + Magento\Config\Model\Config\Source\Yesno + + + + + 1 + + + Magento\Config\Model\Config\Source\Yesno @@ -555,7 +579,7 @@ - + Magento\Config\Model\Config\Source\Yesno @@ -564,44 +588,29 @@ ]]> - - - Algolia\AlgoliaSearch\Model\Source\TrendingItemType - - - - - 1 - - - + - required-entry - - trending_items_for_facets + 1 - + - required-entry - trending_items_for_facets + 1 - + required-entry validate-digits @@ -613,7 +622,7 @@ 1 - + Magento\Config\Model\Config\Source\Yesno @@ -625,7 +634,7 @@ 1 - + Magento\Config\Model\Config\Source\Yesno @@ -637,6 +646,18 @@ 1 + + + Magento\Config\Model\Config\Source\Yesno + + + + + 1 + +
diff --git a/view/frontend/web/recommend.js b/view/frontend/web/recommend.js index f36626924..709ee4320 100644 --- a/view/frontend/web/recommend.js +++ b/view/frontend/web/recommend.js @@ -2,8 +2,9 @@ requirejs([ 'jquery', 'recommend', 'recommendJs', - 'algoliaBundle' -], function ($, recommend, recommendJs, algoliaBundle) { + 'algoliaBundle', + 'mage/translate' +], function ($, recommend, recommendJs, algoliaBundle, $tr) { this.config = algoliaConfig; this.defaultIndexName = algoliaConfig.indexName + '_products'; const appId = this.config.applicationId; @@ -21,25 +22,11 @@ requirejs([ objectIDs: [currentObjectID], maxRecommendations: this.config.recommend.limitFBTProducts, itemComponent({item, createElement, Fragment}) { - var correctFKey = getCookie('form_key'); - var action = config.instant.addToCartParams.action + 'product/' + item.objectID + '/'; - if(correctFKey != "" && config.instant.addToCartParams.formKey != correctFKey) { - config.instant.addToCartParams.formKey = correctFKey; + if (config.recommend.isAddToCartEnabledInFBT) { + return renderRecommendDataWithAddToCart(item, createElement); + }else{ + return renderRecommendData(item, createElement); } - return createElement( - 'div', - null, - createElement( - 'div', - {className: "product-details"}, - createElement( - 'a', - {className: "product-url", href: item.url}, - createElement('img', {className: "product-img", src: item.image_url}, item.image_url), - createElement('p', {className: "product-name"}, item.name) - ) - ) - ); }, }); } @@ -51,105 +38,91 @@ requirejs([ objectIDs: [currentObjectID], maxRecommendations: this.config.recommend.limitRelatedProducts, itemComponent({item, createElement, Fragment}) { - var correctFKey = getCookie('form_key'); - var action = config.instant.addToCartParams.action + 'product/' + item.objectID + '/'; - if(correctFKey != "" && config.instant.addToCartParams.formKey != correctFKey) { - config.instant.addToCartParams.formKey = correctFKey; + if (config.recommend.isAddToCartEnabledInRelatedProduct) { + return renderRecommendDataWithAddToCart(item, createElement);; + }else{ + return renderRecommendData(item, createElement) } - return createElement( - 'div', - null, - createElement( - 'div', - {className: "product-details"}, - createElement( - 'a', - {className: "product-url", href: item.url}, - createElement('img', {className: "product-img", src: item.image_url}, item.image_url), - createElement('p', {className: "product-name"}, item.name) - ) - ) - ); }, }); } } if (this.config.recommend.enabledTrendItems && ((this.config.recommend.isTrendItemsEnabledInPDP && $('body').hasClass('catalog-product-view')) || (this.config.recommend.isTrendItemsEnabledInCartPage && $('body').hasClass('checkout-cart-index'))) ) { - if(this.config.recommend.trendItemsType == "trending_items_for_facets" && this.config.recommend.trendItemFacetName && this.config.recommend.trendItemFacetValue){ - recommendJs.trendingItems({ - container: '#trendItems', - facetName: this.config.recommend.trendItemFacetName, - facetValue: this.config.recommend.trendItemFacetValue, - recommendClient, - indexName, - maxRecommendations: this.config.recommend.limitTrendingItems, - itemComponent({item, createElement, Fragment}) { - return createElement( - 'div', - null, - createElement( - 'div', - {className: "product-details"}, - createElement( - 'a', - {className: "product-url", href: item.url}, - createElement('img', {className: "product-img", src: item.image_url}, item.image_url), - createElement('p', {className: "product-name"}, item.name) - ) - ) - ); - }, - }); - } else { - recommendJs.trendingItems({ - container: '#trendItems', - recommendClient, - indexName, - maxRecommendations: this.config.recommend.limitTrendingItems, - itemComponent({item, createElement, Fragment}) { - return createElement( - 'div', - null, - createElement( - 'div', - {className: "product-details"}, - createElement( - 'a', - {className: "product-url", href: item.url}, - createElement('img', {className: "product-img", src: item.image_url}, item.image_url), - createElement('p', {className: "product-name"}, item.name) - ) - ) - ); - }, - }); - } - }else if(this.config.recommend.enabledTrendItems && typeof recommendTrendContainer !== "undefined" && typeof facetName !== "undefined" && typeof facetValue !== "undefined"){ + recommendJs.trendingItems({ + container: '#trendItems', + facetName: this.config.recommend.trendItemFacetName ? this.config.recommend.trendItemFacetName : '', + facetValue: this.config.recommend.trendItemFacetValue ? this.config.recommend.trendItemFacetValue : '', + recommendClient, + indexName, + maxRecommendations: this.config.recommend.limitTrendingItems, + itemComponent({item, createElement, Fragment}) { + if (config.recommend.isAddToCartEnabledInTrendsItem) { + return renderRecommendDataWithAddToCart(item, createElement);; + }else{ + return renderRecommendData(item, createElement) + } + }, + }); + }else if(this.config.recommend.enabledTrendItems && typeof recommendTrendContainer !== "undefined"){ let containerValue = "#"+recommendTrendContainer; recommendJs.trendingItems({ container: containerValue, - facetName: facetName, - facetValue: facetValue, + facetName: facetName ? facetName : '', + facetValue: facetValue ? facetValue : '', recommendClient, indexName, maxRecommendations: this.config.recommend.limitTrendingItems, itemComponent({item, createElement, Fragment}) { - return createElement( - 'div', - null, - createElement( - 'div', - {className: "product-details"}, - createElement( - 'a', - {className: "product-url", href: item.url}, - createElement('img', {className: "product-img", src: item.image_url}, item.image_url), - createElement('p', {className: "product-name"}, item.name) - ) - ) - ); + if (config.recommend.isAddToCartEnabledInTrendsItem) { + return renderRecommendDataWithAddToCart(item, createElement);; + }else{ + return renderRecommendData(item, createElement) + } }, }); } + function renderRecommendData(item, createElement){ + return createElement( + 'div', + null, + createElement( + 'div', + {className: "product-details"}, + createElement( + 'a', + {className: "product-url", href: item.url}, + createElement('img', {className: "product-img", src: item.image_url}, item.image_url), + createElement('p', {className: "product-name"}, item.name) + ) + ) + ); + } + function renderRecommendDataWithAddToCart(item, createElement){ + let correctFKey = getCookie('form_key'); + let action = config.recommend.addToCartParams.action + 'product/' + item.objectID + '/'; + if(correctFKey != "" && config.recommend.addToCartParams.formKey != correctFKey) { + config.recommend.addToCartParams.formKey = correctFKey; + } + return createElement( + 'div', + null, + createElement( + 'div', + {className: "product-details"}, + createElement( + 'a', + {className: "product-url", href: item.url}, + createElement('img', {className: "product-img", src: item.image_url}, item.image_url), + createElement('p', {className: "product-name"}, item.name), + createElement('form', {className: 'addTocartForm', action: action, method: 'post'}, + createElement('input', {type: 'hidden', name: 'form_key',value: config.recommend.addToCartParams.formKey}), + createElement('input', {type: 'hidden', name:'unec', value: AlgoliaBase64.mageEncode(action)}), + createElement('input', {type: 'hidden', name:'product', value: item.objectID}), + createElement('button', {type: 'submit', className: 'action tocart primary'}, $tr('Add To Cart')) + ) + ) + ) + ); + } }); From 524a950abe64e6a41e9bdcdda4dc325eaa480e52 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 9 Sep 2022 19:04:56 +0530 Subject: [PATCH 09/73] Fixed Click analytics issue in Autocomplete --- view/frontend/web/autocomplete.js | 15 +++++++++++++++ view/frontend/web/insights.js | 3 ++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/view/frontend/web/autocomplete.js b/view/frontend/web/autocomplete.js index 082ded326..81e681505 100755 --- a/view/frontend/web/autocomplete.js +++ b/view/frontend/web/autocomplete.js @@ -200,6 +200,21 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { return autocompleteConfig; }, }); + //Written code for autocomplete insight + jQuery(document).on('click', '.algoliasearch-autocomplete-hit', function(){ + let itemUrl = jQuery(this).attr('href'); + let eventData = algoliaInsights.buildEventData( + 'Clicked', getHitsUrlParameter(itemUrl, 'objectID'), getHitsUrlParameter(itemUrl, 'indexName'), 1, getHitsUrlParameter(itemUrl, 'queryID') + ); + algoliaInsights.trackClick(eventData); + }); }); }); }); + +function getHitsUrlParameter(url, name) { + name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); + var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), + results = regex.exec(url); + return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); +} diff --git a/view/frontend/web/insights.js b/view/frontend/web/insights.js index 3eac5d0c7..61d9a600f 100644 --- a/view/frontend/web/insights.js +++ b/view/frontend/web/insights.js @@ -1,3 +1,4 @@ +var algoliaInsights; requirejs([ 'jquery', 'algoliaAnalytics', @@ -6,7 +7,7 @@ requirejs([ algoliaAnalytics = algoliaAnalyticsWrapper.default; - var algoliaInsights = { + algoliaInsights = { config: null, defaultIndexName: null, isTracking: false, From 92d59d40cc1d6d45d1941e432819606f93c1f969 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Mon, 12 Sep 2022 22:54:25 +0530 Subject: [PATCH 10/73] MAGE-407 Reindex product when last item purchased --- Observer/ReindexProductOnLastItemPurchase.php | 80 +++++++++++++++++++ etc/adminhtml/events.xml | 4 + etc/module.xml | 1 + 3 files changed, 85 insertions(+) create mode 100644 Observer/ReindexProductOnLastItemPurchase.php diff --git a/Observer/ReindexProductOnLastItemPurchase.php b/Observer/ReindexProductOnLastItemPurchase.php new file mode 100644 index 000000000..58b661f2c --- /dev/null +++ b/Observer/ReindexProductOnLastItemPurchase.php @@ -0,0 +1,80 @@ +defaultSourceProvider = $defaultSourceProvider; + $this->isSingleSourceMode = $isSingleSourceMode; + $this->getSourceItemsBySku = $getSourceItemsBySku; + $this->indexer = $indexerRegistry->get('algolia_products'); + } + /** + * @param EventObserver $observer + * @return void + */ + public function execute(EventObserver $observer) + { + /** @var \Magento\Sales\Model\Order\Shipment $shipment */ + $shipment = $observer->getEvent()->getShipment(); + if ($shipment->getOrigData('entity_id')) { + return; + } + + if (!empty($shipment->getExtensionAttributes()) + && !empty($shipment->getExtensionAttributes()->getSourceCode())) { + $sourceCode = $shipment->getExtensionAttributes()->getSourceCode(); + } elseif ($this->isSingleSourceMode->execute()) { + $sourceCode = $this->defaultSourceProvider->getCode(); + } + + foreach ($shipment->getAllItems() as $item) { + $sourceItemList = $this->getSourceItemsBySku->execute($item->getSku()); + foreach ($sourceItemList as $source) { + if ($source->getSourceCode() == $sourceCode) { + if ($source->getQuantity() < 1) { + $this->indexer->reindexRow($item->getProductId()); + } + } + } + } + } +} diff --git a/etc/adminhtml/events.xml b/etc/adminhtml/events.xml index 57336ec8d..5a2f5fe19 100755 --- a/etc/adminhtml/events.xml +++ b/etc/adminhtml/events.xml @@ -62,4 +62,8 @@ + + + + diff --git a/etc/module.xml b/etc/module.xml index defdf19a7..fd24eb437 100755 --- a/etc/module.xml +++ b/etc/module.xml @@ -26,6 +26,7 @@ + From 9a4fe43a51ac62b238d482601022bef7964d04cb Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Tue, 13 Sep 2022 16:48:30 +0530 Subject: [PATCH 11/73] MAGE-407 Product Index on last purchase item --- Observer/ReindexProductOnLastItemPurchase.php | 78 ++++++++++--------- ...xProductOnLastItemPurchaseIfMsiDisable.php | 67 ++++++++++++++++ etc/events.xml | 7 ++ 3 files changed, 117 insertions(+), 35 deletions(-) create mode 100644 Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php create mode 100644 etc/events.xml diff --git a/Observer/ReindexProductOnLastItemPurchase.php b/Observer/ReindexProductOnLastItemPurchase.php index 58b661f2c..aad054dc2 100644 --- a/Observer/ReindexProductOnLastItemPurchase.php +++ b/Observer/ReindexProductOnLastItemPurchase.php @@ -3,48 +3,47 @@ namespace Algolia\AlgoliaSearch\Observer; +use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Framework\Event\Observer as EventObserver; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Indexer\IndexerRegistry; -use Magento\InventoryCatalogApi\Api\DefaultSourceProviderInterface; -use Magento\InventoryCatalogApi\Model\IsSingleSourceModeInterface; -use Magento\InventoryShipping\Model\GetItemsToDeductFromShipment; -use Magento\InventoryApi\Api\GetSourceItemsBySkuInterface; +use Magento\Framework\Module\Manager; +use Magento\Framework\ObjectManagerInterface; class ReindexProductOnLastItemPurchase implements ObserverInterface { + protected $indexer; + /** - * @var IsSingleSourceModeInterface + * @var ObjectManagerInterface */ - private $isSingleSourceMode; + protected $objectManager; /** - * @var DefaultSourceProviderInterface + * @var Manager */ - private $defaultSourceProvider; + protected $moduleManager; /** - * @var GetItemsToDeductFromShipment + * @var ProductRepositoryInterface */ - private $getItemsToDeductFromShipment; + protected $productRepository; /** - * @var GetSourceItemsBySkuInterface + * @param IndexerRegistry $indexerRegistry + * @param ObjectManagerInterface $objectManager + * @param Manager $moduleManager + * @param ProductRepositoryInterface $productRepository */ - private $getSourceItemsBySku; - - - private $indexer; - public function __construct( - DefaultSourceProviderInterface $defaultSourceProvider, - IsSingleSourceModeInterface $isSingleSourceMode, - IndexerRegistry $indexerRegistry, - GetSourceItemsBySkuInterface $getSourceItemsBySku + ObjectManagerInterface $objectManager, + Manager $moduleManager, + ProductRepositoryInterface $productRepository, + IndexerRegistry $indexerRegistry ) { - $this->defaultSourceProvider = $defaultSourceProvider; - $this->isSingleSourceMode = $isSingleSourceMode; - $this->getSourceItemsBySku = $getSourceItemsBySku; + $this->objectManager = $objectManager; + $this->moduleManager = $moduleManager; + $this->productRepository = $productRepository; $this->indexer = $indexerRegistry->get('algolia_products'); } /** @@ -59,19 +58,28 @@ public function execute(EventObserver $observer) return; } - if (!empty($shipment->getExtensionAttributes()) - && !empty($shipment->getExtensionAttributes()->getSourceCode())) { - $sourceCode = $shipment->getExtensionAttributes()->getSourceCode(); - } elseif ($this->isSingleSourceMode->execute()) { - $sourceCode = $this->defaultSourceProvider->getCode(); - } + if ($this->moduleManager->isEnabled('Magento_Inventory')) + { + $isSingleMode = $this->objectManager->create(\Magento\InventoryCatalogApi\Model\IsSingleSourceModeInterface::class); + $defaultSourceProvider = $this->objectManager->create(\Magento\InventoryCatalogApi\Api\DefaultSourceProviderInterface::class); + if (!empty($shipment->getExtensionAttributes()) + && !empty($shipment->getExtensionAttributes()->getSourceCode())) { + $sourceCode = $shipment->getExtensionAttributes()->getSourceCode(); + } elseif ($isSingleMode->execute()) { + $sourceCode = $defaultSourceProvider->getCode(); + } - foreach ($shipment->getAllItems() as $item) { - $sourceItemList = $this->getSourceItemsBySku->execute($item->getSku()); - foreach ($sourceItemList as $source) { - if ($source->getSourceCode() == $sourceCode) { - if ($source->getQuantity() < 1) { - $this->indexer->reindexRow($item->getProductId()); + foreach ($shipment->getAllItems() as $item) { + $getSourceItemBySku = $this->objectManager->create(\Magento\InventoryApi\Api\GetSourceItemsBySkuInterface::class); + $sourceItemList = $getSourceItemBySku->execute($item->getSku()); + foreach ($sourceItemList as $source) + { + if ($source->getSourceCode() == $sourceCode) + { + if ($source->getQuantity() < 1) + { + $this->indexer->reindexRow($item->getProductId()); + } } } } diff --git a/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php b/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php new file mode 100644 index 000000000..4828f16ba --- /dev/null +++ b/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php @@ -0,0 +1,67 @@ +moduleManager = $moduleManager; + $this->productRepository = $productRepository; + $this->indexer = $indexerRegistry->get('algolia_products'); + } + + public function execute(Observer $observer) + { + if (!$this->moduleManager->isEnabled('Magento_Inventory')) { + $quote = $observer->getEvent()->getQuote(); + $productIds = []; + foreach ($quote->getAllItems() as $item) { + $productIds[$item->getProductId()] = $item->getProductId(); + $children = $item->getChildrenItems(); + if ($children) { + foreach ($children as $childItem) { + $productIds[$childItem->getProductId()] = $childItem->getProductId(); + } + } + } + + if($productIds) { + $productTobeReindex = []; + foreach ($productIds as $productId) { + $product = $this->productRepository->getById($productId); + $stockInfo = $product->getData('quantity_and_stock_status'); + if ($stockInfo['qty'] < 1) { + $productTobeReindex[] = $productId; + } + } + $this->indexer->reindexList($productTobeReindex); + } + } + } +} diff --git a/etc/events.xml b/etc/events.xml new file mode 100644 index 000000000..e20ffd004 --- /dev/null +++ b/etc/events.xml @@ -0,0 +1,7 @@ + + + + + + From ff1f1b04f1a60c92fed60828261dfda8284c8be3 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Wed, 14 Sep 2022 19:09:23 +0530 Subject: [PATCH 12/73] Updated code for adding frequently brought together and related products --- Block/Cart/Recommend.php | 49 ++++++++++++++++++ Block/Configuration.php | 2 + Helper/ConfigHelper.php | 22 ++++++++ etc/adminhtml/system.xml | 50 +++++++++++-------- etc/widget.xml | 6 +-- view/frontend/layout/checkout_cart_index.xml | 4 +- .../recommend/cart/recommend_items.phtml | 13 +++++ .../templates/recommend/cart/trends.phtml | 7 --- .../templates/recommend/products.phtml | 2 +- 9 files changed, 121 insertions(+), 34 deletions(-) create mode 100644 Block/Cart/Recommend.php create mode 100644 view/frontend/templates/recommend/cart/recommend_items.phtml delete mode 100644 view/frontend/templates/recommend/cart/trends.phtml diff --git a/Block/Cart/Recommend.php b/Block/Cart/Recommend.php new file mode 100644 index 000000000..a8d580702 --- /dev/null +++ b/Block/Cart/Recommend.php @@ -0,0 +1,49 @@ +checkoutSession = $checkoutSession; + $this->configHelper = $configHelper; + } + + public function getAllCartItems() + { + $cartItems = array(); + $itemCollection = $this->checkoutSession->getQuote()->getAllVisibleItems(); + foreach ( $itemCollection as $item) { + $cartItems[] = $item->getProductId(); + } + return array_unique($cartItems); + } + +} diff --git a/Block/Configuration.php b/Block/Configuration.php index 3c6abf689..61d1cbd39 100755 --- a/Block/Configuration.php +++ b/Block/Configuration.php @@ -165,6 +165,8 @@ public function getConfiguration() 'recommend' => [ 'enabledFBT' => $config->isRecommendFrequentlyBroughtTogetherEnabled(), 'enabledRelated' => $config->isRecommendRelatedProductsEnabled(), + 'enabledFBTInCart' => $config->isRecommendFrequentlyBroughtTogetherEnabledOnCartPage(), + 'enabledRelatedInCart' => $config->isRecommendRelatedProductsEnabledOnCartPage(), 'limitFBTProducts' => $config->getNumberOfFrequentlyBoughtTogetherProducts(), 'limitRelatedProducts' => $config->getNumberOfRelatedProducts(), 'limitTrendingItems' => $config->getNumberOfTrendingItems(), diff --git a/Helper/ConfigHelper.php b/Helper/ConfigHelper.php index 45113af21..0817ff877 100755 --- a/Helper/ConfigHelper.php +++ b/Helper/ConfigHelper.php @@ -111,6 +111,8 @@ class ConfigHelper protected const IS_RECOMMEND_FREQUENTLY_BOUGHT_TOGETHER_ENABLED = 'algoliasearch_recommend/recommend/frequently_bought_together/is_frequently_bought_together_enabled'; protected const IS_RECOMMEND_RELATED_PRODUCTS_ENABLED = 'algoliasearch_recommend/recommend/related_product/is_related_products_enabled'; + protected const IS_RECOMMEND_FREQUENTLY_BOUGHT_TOGETHER_ENABLED_ON_CART_PAGE = 'algoliasearch_recommend/recommend/frequently_bought_together/is_frequently_bought_together_enabled_in_cart_page'; + protected const IS_RECOMMEND_RELATED_PRODUCTS_ENABLED_ON_CART_PAGE = 'algoliasearch_recommend/recommend/related_product/is_related_products_enabled_in_cart_page'; protected const NUM_OF_RECOMMEND_FREQUENTLY_BOUGHT_TOGETHER_PRODUCTS = 'algoliasearch_recommend/recommend/frequently_bought_together/num_of_frequently_bought_together_products'; protected const NUM_OF_RECOMMEND_RELATED_PRODUCTS = 'algoliasearch_recommend/recommend/related_product/num_of_related_products'; protected const IS_REMOVE_RELATED_PRODUCTS_BLOCK = 'algoliasearch_recommend/recommend/related_product/is_remove_core_related_products_block'; @@ -461,6 +463,26 @@ public function isRecommendRelatedProductsEnabled($storeId = null) return $this->configInterface->isSetFlag(self::IS_RECOMMEND_RELATED_PRODUCTS_ENABLED, ScopeInterface::SCOPE_STORE, $storeId); } + /** + * @param int $storeId + * + * @return int + */ + public function isRecommendFrequentlyBroughtTogetherEnabledOnCartPage($storeId = null) + { + return $this->configInterface->isSetFlag(self::IS_RECOMMEND_FREQUENTLY_BOUGHT_TOGETHER_ENABLED_ON_CART_PAGE, ScopeInterface::SCOPE_STORE, $storeId); + } + + /** + * @param int $storeId + * + * @return int + */ + public function isRecommendRelatedProductsEnabledOnCartPage($storeId = null) + { + return $this->configInterface->isSetFlag(self::IS_RECOMMEND_RELATED_PRODUCTS_ENABLED_ON_CART_PAGE, ScopeInterface::SCOPE_STORE, $storeId); + } + /** * @param int $storeId * diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 2a38c3431..9bdd2c8c7 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -482,7 +482,7 @@ - + Magento\Config\Model\Config\Source\Yesno + + + Magento\Config\Model\Config\Source\Yesno + + Enabling frequently bought together products can potentially break your design on shopping cart page and some work will be required to have a good integration with your theme. + ]]> + + validate-digits - + - - 1 - - + Magento\Config\Model\Config\Source\Yesno - - 1 - @@ -531,7 +535,7 @@ - + Magento\Config\Model\Config\Source\Yesno + + + Magento\Config\Model\Config\Source\Yesno + + Enabling related products can potentially break your design on shopping cart page and some work will be required to have a good integration with your theme. + ]]> + + validate-digits @@ -548,21 +562,15 @@ How many products do you want to display in the related products? Default value is 6. ]]> - - 1 - - + Magento\Config\Model\Config\Source\Yesno - - 1 - @@ -578,7 +586,7 @@ - + Magento\Config\Model\Config\Source\Yesno @@ -623,7 +631,7 @@ - + Magento\Config\Model\Config\Source\Yesno - + Magento\Config\Model\Config\Source\Yesno - + Magento\Config\Model\Config\Source\Yesno - - You can allow Algolia Recommend Trends item to appear anywhere you want + + You can allow Algolia Recommend Trending items to appear anywhere you want - + diff --git a/view/frontend/layout/checkout_cart_index.xml b/view/frontend/layout/checkout_cart_index.xml index ccf36a6b3..9aa361755 100644 --- a/view/frontend/layout/checkout_cart_index.xml +++ b/view/frontend/layout/checkout_cart_index.xml @@ -7,8 +7,8 @@ --> - - + + diff --git a/view/frontend/templates/recommend/cart/recommend_items.phtml b/view/frontend/templates/recommend/cart/recommend_items.phtml new file mode 100644 index 000000000..e7d71437a --- /dev/null +++ b/view/frontend/templates/recommend/cart/recommend_items.phtml @@ -0,0 +1,13 @@ +getAllCartItems(); +?> +
+
+
+ diff --git a/view/frontend/templates/recommend/cart/trends.phtml b/view/frontend/templates/recommend/cart/trends.phtml deleted file mode 100644 index 36e779fed..000000000 --- a/view/frontend/templates/recommend/cart/trends.phtml +++ /dev/null @@ -1,7 +0,0 @@ - -
diff --git a/view/frontend/templates/recommend/products.phtml b/view/frontend/templates/recommend/products.phtml index 287719dac..034d4f755 100644 --- a/view/frontend/templates/recommend/products.phtml +++ b/view/frontend/templates/recommend/products.phtml @@ -9,6 +9,6 @@ $product = $block->getProduct();
From 82fe15e063e164ee9c5300632d2d537e598e7740 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Thu, 15 Sep 2022 14:35:04 +0530 Subject: [PATCH 13/73] Added data patch for recommend --- Block/Cart/Recommend.php | 5 ++ Block/Widget/TrendsItem.php | 13 +++- Model/Source/TrendingItemType.php | 16 ----- Setup/Patch/Schema/RecommendConfigPatch.php | 75 +++++++++++++++++++++ etc/adminhtml/system.xml | 7 +- 5 files changed, 92 insertions(+), 24 deletions(-) delete mode 100644 Model/Source/TrendingItemType.php create mode 100644 Setup/Patch/Schema/RecommendConfigPatch.php diff --git a/Block/Cart/Recommend.php b/Block/Cart/Recommend.php index a8d580702..884f64831 100644 --- a/Block/Cart/Recommend.php +++ b/Block/Cart/Recommend.php @@ -36,6 +36,11 @@ public function __construct( $this->configHelper = $configHelper; } + /** + * @return array + * @throws \Magento\Framework\Exception\LocalizedException + * @throws \Magento\Framework\Exception\NoSuchEntityException + */ public function getAllCartItems() { $cartItems = array(); diff --git a/Block/Widget/TrendsItem.php b/Block/Widget/TrendsItem.php index cbc303314..08dd0f336 100644 --- a/Block/Widget/TrendsItem.php +++ b/Block/Widget/TrendsItem.php @@ -10,7 +10,12 @@ class TrendsItem extends Template implements BlockInterface { protected $_template = 'recommend/widget/trends-item.phtml'; - + + /** + * @param Context $context + * @param Random $mathRandom + * @param array $data + */ public function __construct( Context $context, Random $mathRandom, @@ -22,7 +27,11 @@ public function __construct( $data ); } - + + /** + * @return string + * @throws \Magento\Framework\Exception\LocalizedException + */ public function generateUniqueToken() { return $this->mathRandom->getRandomString(5); diff --git a/Model/Source/TrendingItemType.php b/Model/Source/TrendingItemType.php deleted file mode 100644 index ee5305f18..000000000 --- a/Model/Source/TrendingItemType.php +++ /dev/null @@ -1,16 +0,0 @@ - 'trending_global_item', 'label' => __('Trending Global Items')], - ['value' => 'trending_items_for_facets', 'label' => __('Trending items for facets')], - ]; - } -} diff --git a/Setup/Patch/Schema/RecommendConfigPatch.php b/Setup/Patch/Schema/RecommendConfigPatch.php new file mode 100644 index 000000000..aa364b30f --- /dev/null +++ b/Setup/Patch/Schema/RecommendConfigPatch.php @@ -0,0 +1,75 @@ +config = $config; + $this->moduleDataSetup = $moduleDataSetup; + } + + /** + * @return array|string[] + */ + public static function getDependencies() + { + return []; + } + + /** + * @return array|string[] + */ + public function getAliases() + { + return []; + } + + /** + * @return RecommendConfigPatch|void + */ + public function apply() + { + $movedConfigDirectives = [ + 'algoliasearch_recommend/recommend/is_frequently_bought_together_enabled' => 'algoliasearch_recommend/recommend/frequently_bought_together/is_frequently_bought_together_enabled', + 'algoliasearch_recommend/recommend/is_related_products_enabled' => 'algoliasearch_recommend/recommend/related_product/is_related_products_enabled', + 'algoliasearch_recommend/recommend/num_of_frequently_bought_together_products' => 'algoliasearch_recommend/recommend/frequently_bought_together/num_of_frequently_bought_together_products', + 'algoliasearch_recommend/recommend/num_of_related_products' => 'algoliasearch_recommend/recommend/related_product/num_of_related_products', + 'algoliasearch_recommend/recommend/is_remove_core_related_products_block' => 'algoliasearch_recommend/recommend/related_product/is_remove_core_related_products_block', + 'algoliasearch_recommend/recommend/is_remove_core_upsell_products_block' => 'algoliasearch_recommend/recommend/frequently_bought_together/is_remove_core_upsell_products_block' + ]; + + $this->moduleDataSetup->getConnection()->startSetup(); + $connection = $this->moduleDataSetup->getConnection(); + $table = $connection->getTableName('core_config_data'); + foreach ($movedConfigDirectives as $from => $to) { + try { + $connection->query('UPDATE ' . $table . ' SET path = "' . $to . '" WHERE path = "' . $from . '"'); + } catch (\Magento\Framework\DB\Adapter\DuplicateException $e) { + // + } + } + $this->moduleDataSetup->getConnection()->endSetup(); + } +} diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 9bdd2c8c7..7c3143256 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -588,13 +588,8 @@ - + Magento\Config\Model\Config\Source\Yesno - - - From 3e2d1655f1f4bae368ad26044b872ae8e4059c1f Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 16 Sep 2022 10:51:40 +0530 Subject: [PATCH 14/73] Added data patch for recommend --- etc/adminhtml/system.xml | 22 +++++++++++----------- view/frontend/web/recommend.js | 12 ++++++------ 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 7c3143256..bce8d3d78 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -486,8 +486,8 @@ Magento\Config\Model\Config\Source\Yesno Enabling frequently bought together products can potentially break your design on PDP page and some work will be required to have a good integration with your theme. + Do you want the Frequently Bought Together products to display inside a product detail page after main product info? +
Enabling Frequently Bought Together products can potentially break your design on PDP page and some work will be required to have a good integration with your theme. ]]>
@@ -496,8 +496,8 @@ Magento\Config\Model\Config\Source\Yesno Enabling frequently bought together products can potentially break your design on shopping cart page and some work will be required to have a good integration with your theme. + Do you want the Frequently Bought Together products to display inside a shopping cart page? +
Enabling Frequently Bought Together products can potentially break your design on shopping cart page and some work will be required to have a good integration with your theme. ]]>
@@ -539,8 +539,8 @@ Magento\Config\Model\Config\Source\Yesno Enabling related products can potentially break your design on PDP page and some work will be required to have a good integration with your theme. + Do you want the Related Products to display inside a product detail page after main product info? +
Enabling Related Products can potentially break your design on PDP page and some work will be required to have a good integration with your theme. ]]>
@@ -549,8 +549,8 @@ Magento\Config\Model\Config\Source\Yesno Enabling related products can potentially break your design on shopping cart page and some work will be required to have a good integration with your theme. + Do you want the Related Products to display inside a shopping cart page? +
Enabling Related Products can potentially break your design on shopping cart page and some work will be required to have a good integration with your theme. ]]>
@@ -559,7 +559,7 @@ @@ -577,7 +577,7 @@ Magento\Config\Model\Config\Source\Yesno @@ -618,7 +618,7 @@ required-entry validate-digits diff --git a/view/frontend/web/recommend.js b/view/frontend/web/recommend.js index 709ee4320..6875aa008 100644 --- a/view/frontend/web/recommend.js +++ b/view/frontend/web/recommend.js @@ -11,15 +11,15 @@ requirejs([ const apiKey = this.config.apiKey; const recommendClient = recommend(appId, apiKey); const indexName = this.defaultIndexName; - if ($('body').hasClass('catalog-product-view')) { + if ($('body').hasClass('catalog-product-view') || $('body').hasClass('checkout-cart-index')) { // --- Add the current product objectID here --- const currentObjectID = objectId; - if (this.config.recommend.enabledFBT) { + if ((this.config.recommend.enabledFBT && $('body').hasClass('catalog-product-view')) || (this.config.recommend.enabledFBTInCart && $('body').hasClass('checkout-cart-index'))) { recommendJs.frequentlyBoughtTogether({ container: '#frequentlyBoughtTogether', recommendClient, indexName, - objectIDs: [currentObjectID], + objectIDs: currentObjectID, maxRecommendations: this.config.recommend.limitFBTProducts, itemComponent({item, createElement, Fragment}) { if (config.recommend.isAddToCartEnabledInFBT) { @@ -30,12 +30,12 @@ requirejs([ }, }); } - if (this.config.recommend.enabledRelated) { + if ((this.config.recommend.enabledRelated && $('body').hasClass('catalog-product-view')) || (this.config.recommend.enabledRelatedInCart && $('body').hasClass('checkout-cart-index'))) { recommendJs.relatedProducts({ container: '#relatedProducts', recommendClient, indexName, - objectIDs: [currentObjectID], + objectIDs: currentObjectID, maxRecommendations: this.config.recommend.limitRelatedProducts, itemComponent({item, createElement, Fragment}) { if (config.recommend.isAddToCartEnabledInRelatedProduct) { @@ -72,7 +72,7 @@ requirejs([ facetValue: facetValue ? facetValue : '', recommendClient, indexName, - maxRecommendations: this.config.recommend.limitTrendingItems, + maxRecommendations: numOfTrendsItem ? numOfTrendsItem : this.config.recommend.limitTrendingItems, itemComponent({item, createElement, Fragment}) { if (config.recommend.isAddToCartEnabledInTrendsItem) { return renderRecommendDataWithAddToCart(item, createElement);; From d2f759fd586e6f70eec3a46c02fe76ccc8b96d43 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Mon, 19 Sep 2022 12:06:59 +0530 Subject: [PATCH 15/73] Updated Proper cases --- etc/adminhtml/system.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index bce8d3d78..cb55c8e72 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -630,7 +630,7 @@ Magento\Config\Model\Config\Source\Yesno @@ -642,7 +642,7 @@ Magento\Config\Model\Config\Source\Yesno @@ -654,7 +654,7 @@ Magento\Config\Model\Config\Source\Yesno From 80d68dc5d15bdb22d2b033e0d957ebc5398ce2fc Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Mon, 19 Sep 2022 16:17:24 +0530 Subject: [PATCH 16/73] Updated UI code --- view/frontend/web/internals/recommend.css | 28 ++++++++++++++++++++++- view/frontend/web/recommend.js | 2 +- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/view/frontend/web/internals/recommend.css b/view/frontend/web/internals/recommend.css index 125f7ac87..4595bff76 100644 --- a/view/frontend/web/internals/recommend.css +++ b/view/frontend/web/internals/recommend.css @@ -27,9 +27,35 @@ color: inherit; display: block; } -#relatedProducts .product-name, #frequentlyBoughtTogether .product-name{ +#relatedProducts .product-name, #frequentlyBoughtTogether .product-name, #trendItems .product-name{ text-align: center; width: 150px; + text-overflow: ellipsis; + overflow: hidden; + max-height: 42px; + height: 42px; + white-space: normal; + line-height: 2rem; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + display: -webkit-box; +} +.auc-Recommend-item .product-details { + text-align: center; +} +#trendItems .auc-Recommend-list{ + flex-wrap: wrap; + justify-content: flex-start; +} +.product-details .action.primary, .action-primary{ + background: #f4f4f4; + border: 1px solid #f4f4f4; + color: #666666; +} +.product-details .action.primary:hover, .action-primary:hover { + border-color: #1979c3; + background: #1979c3; + color: #FFFFFF; } @media (min-width: 768px) and (max-width: 1023px) { #relatedProducts li, #frequentlyBoughtTogether li { diff --git a/view/frontend/web/recommend.js b/view/frontend/web/recommend.js index 6875aa008..20d591e1c 100644 --- a/view/frontend/web/recommend.js +++ b/view/frontend/web/recommend.js @@ -72,7 +72,7 @@ requirejs([ facetValue: facetValue ? facetValue : '', recommendClient, indexName, - maxRecommendations: numOfTrendsItem ? numOfTrendsItem : this.config.recommend.limitTrendingItems, + maxRecommendations: numOfTrendsItem ? parseInt(numOfTrendsItem) : this.config.recommend.limitTrendingItems, itemComponent({item, createElement, Fragment}) { if (config.recommend.isAddToCartEnabledInTrendsItem) { return renderRecommendDataWithAddToCart(item, createElement);; From b2a01045f7103676b85f72a8e41132fe04c7e230 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Tue, 20 Sep 2022 13:31:03 +0530 Subject: [PATCH 17/73] Added validation and fixed UI issue --- etc/adminhtml/system.xml | 66 +++++++++-------------- view/frontend/web/internals/recommend.css | 5 +- view/frontend/web/recommend.js | 2 +- 3 files changed, 29 insertions(+), 44 deletions(-) diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index cb55c8e72..ec242472c 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -502,7 +502,7 @@ - validate-digits + required-entry validate-digits validate-greater-than-zero - validate-digits + required-entry validate-digits validate-greater-than-zero - - + + Magento\Config\Model\Config\Source\Yesno - - - - - 1 - - - + + + Magento\Config\Model\Config\Source\Yesno - - 1 - - - - required-entry validate-digits + + + Magento\Config\Model\Config\Source\Yesno + + + - - 1 - - - - Magento\Config\Model\Config\Source\Yesno + + - - 1 - - - - Magento\Config\Model\Config\Source\Yesno + + + required-entry validate-digits validate-greater-than-zero - - 1 - - + Magento\Config\Model\Config\Source\Yesno @@ -657,9 +642,6 @@ Do you want to display an "Add To Cart" button in Trending Items? ]]> - - 1 -
diff --git a/view/frontend/web/internals/recommend.css b/view/frontend/web/internals/recommend.css index 4595bff76..8ccbd837c 100644 --- a/view/frontend/web/internals/recommend.css +++ b/view/frontend/web/internals/recommend.css @@ -38,7 +38,10 @@ line-height: 2rem; -webkit-line-clamp: 2; -webkit-box-orient: vertical; - display: -webkit-box; + display: -webkit-box; +} +#trendItems a, #trendItems a:hover{ + color:#333; } .auc-Recommend-item .product-details { text-align: center; diff --git a/view/frontend/web/recommend.js b/view/frontend/web/recommend.js index 20d591e1c..dff35e50c 100644 --- a/view/frontend/web/recommend.js +++ b/view/frontend/web/recommend.js @@ -48,7 +48,7 @@ requirejs([ } } - if (this.config.recommend.enabledTrendItems && ((this.config.recommend.isTrendItemsEnabledInPDP && $('body').hasClass('catalog-product-view')) || (this.config.recommend.isTrendItemsEnabledInCartPage && $('body').hasClass('checkout-cart-index'))) ) { + if ((this.config.recommend.isTrendItemsEnabledInPDP && $('body').hasClass('catalog-product-view')) || (this.config.recommend.isTrendItemsEnabledInCartPage && $('body').hasClass('checkout-cart-index'))) { recommendJs.trendingItems({ container: '#trendItems', facetName: this.config.recommend.trendItemFacetName ? this.config.recommend.trendItemFacetName : '', From 0f6bff239008b602d6f6665e7578f7185b4b6bf2 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Tue, 20 Sep 2022 17:59:38 +0530 Subject: [PATCH 18/73] Triggered Add to Cart Conversion for Configurable Product in Instant Search --- .../Insights/CheckoutCartProductAddAfter.php | 22 ++++++++++++++++--- .../Insights/CheckoutCartProductAddBefore.php | 11 +++++++++- view/frontend/templates/instant/hit.phtml | 1 + 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/Model/Observer/Insights/CheckoutCartProductAddAfter.php b/Model/Observer/Insights/CheckoutCartProductAddAfter.php index 227ae13fb..b929d30d3 100644 --- a/Model/Observer/Insights/CheckoutCartProductAddAfter.php +++ b/Model/Observer/Insights/CheckoutCartProductAddAfter.php @@ -7,6 +7,7 @@ use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Psr\Log\LoggerInterface; +use Magento\Framework\Session\SessionManagerInterface; class CheckoutCartProductAddAfter implements ObserverInterface { @@ -19,14 +20,25 @@ class CheckoutCartProductAddAfter implements ObserverInterface /** @var LoggerInterface */ private $logger; + /** @var SessionManagerInterface */ + private $_coreSession; + + /** + * @param Data $dataHelper + * @param InsightsHelper $insightsHelper + * @param LoggerInterface $logger + * @param SessionManagerInterface $coreSession + */ public function __construct( Data $dataHelper, InsightsHelper $insightsHelper, - LoggerInterface $logger + LoggerInterface $logger, + SessionManagerInterface $coreSession ) { $this->dataHelper = $dataHelper; $this->insightsHelper = $insightsHelper; $this->logger = $logger; + $this->_coreSession = $coreSession; } /** @@ -63,14 +75,18 @@ public function execute(Observer $observer) if ($this->getConfigHelper()->isClickConversionAnalyticsEnabled($storeId) && $this->getConfigHelper()->getConversionAnalyticsMode($storeId) === 'add_to_cart') { - if ($product->hasData('queryId')) { + $this->_coreSession->start(); + $queryId = $this->_coreSession->getQueryId(); + if ($product->hasData('queryId') || $queryId) { try { + $queryId = $product->getData('queryId') ?? $queryId; $userClient->convertedObjectIDsAfterSearch( __('Added to Cart'), $this->dataHelper->getIndexName('_products', $storeId), [$product->getId()], - $product->getData('queryId') + $queryId ); + $this->_coreSession->unsQueryId(); } catch (\Exception $e) { $this->logger->critical($e); } diff --git a/Model/Observer/Insights/CheckoutCartProductAddBefore.php b/Model/Observer/Insights/CheckoutCartProductAddBefore.php index ebce030d0..29c3c1c29 100644 --- a/Model/Observer/Insights/CheckoutCartProductAddBefore.php +++ b/Model/Observer/Insights/CheckoutCartProductAddBefore.php @@ -6,6 +6,7 @@ use Algolia\AlgoliaSearch\Helper\InsightsHelper; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\Session\SessionManagerInterface; class CheckoutCartProductAddBefore implements ObserverInterface { @@ -15,16 +16,22 @@ class CheckoutCartProductAddBefore implements ObserverInterface /** @var InsightsHelper */ private $insightsHelper; + /** @var SessionManagerInterface */ + private $_coreSession; + /** * @param ConfigHelper $configHelper * @param InsightsHelper $insightsHelper + * @param SessionManagerInterface $coreSession */ public function __construct( ConfigHelper $configHelper, - InsightsHelper $insightsHelper + InsightsHelper $insightsHelper, + SessionManagerInterface $coreSession ) { $this->configHelper = $configHelper; $this->insightsHelper = $insightsHelper; + $this->_coreSession = $coreSession; } /** @@ -38,6 +45,8 @@ public function execute(Observer $observer) $requestInfo = $observer->getEvent()->getInfo(); if (isset($requestInfo['queryID']) && $requestInfo['queryID'] != '') { + $this->_coreSession->start(); + $this->_coreSession->setQueryId($requestInfo['queryID']); $product->setData('queryId', $requestInfo['queryID']); } } diff --git a/view/frontend/templates/instant/hit.phtml b/view/frontend/templates/instant/hit.phtml index 05311a36e..35efc7562 100644 --- a/view/frontend/templates/instant/hit.phtml +++ b/view/frontend/templates/instant/hit.phtml @@ -90,6 +90,7 @@ $tierFormatedVar = $block->escapeHtml('price' . $priceKey . '_tier_formated'); {{#isAddToCartEnabled}}
+ From b655a09144384617811b0a6868440a11e7630181 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Tue, 20 Sep 2022 18:11:42 +0530 Subject: [PATCH 19/73] Updated UI for trends --- view/frontend/web/internals/recommend.css | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/view/frontend/web/internals/recommend.css b/view/frontend/web/internals/recommend.css index 8ccbd837c..34a5072ab 100644 --- a/view/frontend/web/internals/recommend.css +++ b/view/frontend/web/internals/recommend.css @@ -14,20 +14,20 @@ .recommend-component { margin-bottom: 80px; } -#relatedProducts .auc-Recommend-list, #frequentlyBoughtTogether .auc-Recommend-list{ +#relatedProducts .auc-Recommend-list, #frequentlyBoughtTogether .auc-Recommend-list, .trendsItem .auc-Recommend-list{ flex-wrap: wrap; justify-content: flex-start; } -#relatedProducts li, #frequentlyBoughtTogether li { +#relatedProducts li, #frequentlyBoughtTogether li, .trendsItem li { display: flex; justify-content: center; width: 16.66666667%; } -#relatedProducts li a, #frequentlyBoughtTogether li a { +#relatedProducts li a, #frequentlyBoughtTogether li a, .trendsItem li a { color: inherit; display: block; } -#relatedProducts .product-name, #frequentlyBoughtTogether .product-name, #trendItems .product-name{ +#relatedProducts .product-name, #frequentlyBoughtTogether .product-name, #trendItems .product-name, .trendsItem .product-name{ text-align: center; width: 150px; text-overflow: ellipsis; @@ -38,9 +38,9 @@ line-height: 2rem; -webkit-line-clamp: 2; -webkit-box-orient: vertical; - display: -webkit-box; + display: -webkit-box; } -#trendItems a, #trendItems a:hover{ +#trendItems a, #trendItems a:hover, .trendsItem a, .trendsItem a:hover{ color:#333; } .auc-Recommend-item .product-details { From 9770b4f607a78a4d49e4a54ad4ec065f4a18ad72 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Tue, 20 Sep 2022 18:29:45 +0530 Subject: [PATCH 20/73] Updated UI for trends --- etc/adminhtml/system.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index ec242472c..9c7178841 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -588,7 +588,7 @@ - + Magento\Config\Model\Config\Source\Yesno - + Magento\Config\Model\Config\Source\Yesno Date: Tue, 20 Sep 2022 19:16:13 +0530 Subject: [PATCH 21/73] Updated php client version in composer --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index ab0888f17..2bfab2f60 100644 --- a/composer.json +++ b/composer.json @@ -6,7 +6,7 @@ "version": "3.8.1", "require": { "magento/framework": "~102.0|~103.0", - "algolia/algoliasearch-client-php": "^3.2", + "algolia/algoliasearch-client-php": "3.2", "guzzlehttp/guzzle": "^6.3.3|^7.3.0", "ext-json": "*", "ext-PDO": "*", From f24b0eb0ef1337b3a56e467bcd0b942a95f34675 Mon Sep 17 00:00:00 2001 From: rachel-trott Date: Tue, 20 Sep 2022 10:24:48 -0500 Subject: [PATCH 22/73] Update Issues link to Support Link --- Helper/Configuration/AssetHelper.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Helper/Configuration/AssetHelper.php b/Helper/Configuration/AssetHelper.php index 15528de2e..2a1ec35db 100644 --- a/Helper/Configuration/AssetHelper.php +++ b/Helper/Configuration/AssetHelper.php @@ -71,8 +71,8 @@ class AssetHelper extends \Magento\Framework\App\Helper\AbstractHelper 'icon' => 'iconFaq', ], [ - 'title' => 'Issues', - 'url' => 'https://github.com/algolia/algoliasearch-magento-2/issues/', + 'title' => 'Support', + 'url' => 'https://www.algolia.com/support/?contact=', 'icon' => 'iconIssues', ], ], From 453ec61b3d3b9fa95ec61a59a43ff85b98a4e961 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Wed, 21 Sep 2022 12:29:55 +0530 Subject: [PATCH 23/73] Removed issues link in Credentials and Setup --- Helper/Configuration/AssetHelper.php | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Helper/Configuration/AssetHelper.php b/Helper/Configuration/AssetHelper.php index 15528de2e..088fe29fe 100644 --- a/Helper/Configuration/AssetHelper.php +++ b/Helper/Configuration/AssetHelper.php @@ -70,11 +70,6 @@ class AssetHelper extends \Magento\Framework\App\Helper\AbstractHelper 'url' => 'https://www.algolia.com/doc/integration/magento-2/troubleshooting/general-faq/?utm_source=magento&utm_medium=extension&utm_campaign=magento_2&utm_term=shop-owner&utm_content=doc-link', 'icon' => 'iconFaq', ], - [ - 'title' => 'Issues', - 'url' => 'https://github.com/algolia/algoliasearch-magento-2/issues/', - 'icon' => 'iconIssues', - ], ], 'algoliasearch_autocomplete' => [ [ From 48f58aae74c973fff58094f5df3b0ba0c9867195 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Wed, 21 Sep 2022 15:41:17 +0530 Subject: [PATCH 24/73] MAGE-374 --- view/frontend/web/internals/autocomplete.css | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/view/frontend/web/internals/autocomplete.css b/view/frontend/web/internals/autocomplete.css index 360916a10..5a05500dd 100755 --- a/view/frontend/web/internals/autocomplete.css +++ b/view/frontend/web/internals/autocomplete.css @@ -147,7 +147,7 @@ } #algolia-autocomplete-container .aa-dropdown-menu .algoliasearch-autocomplete-hit, .aa-Panel .algoliasearch-autocomplete-hit { - display: block; + display: inline-block; position: relative; padding: 5px 10px; color: #000; @@ -472,7 +472,6 @@ } .aa-Panel li.aa-Item{ list-style-type: none; - display: flex; } .aa-Panel .aa-PanelLayout{ From 5b5ac71f734c522d5f6610d9fe915547fb720f0e Mon Sep 17 00:00:00 2001 From: rachel-trott Date: Wed, 21 Sep 2022 17:39:49 -0500 Subject: [PATCH 25/73] reformatting code --- Observer/ReindexProductOnLastItemPurchase.php | 25 ++++++++++--------- ...xProductOnLastItemPurchaseIfMsiDisable.php | 17 ++++++++----- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/Observer/ReindexProductOnLastItemPurchase.php b/Observer/ReindexProductOnLastItemPurchase.php index aad054dc2..f86a10345 100644 --- a/Observer/ReindexProductOnLastItemPurchase.php +++ b/Observer/ReindexProductOnLastItemPurchase.php @@ -7,11 +7,14 @@ use Magento\Framework\Event\Observer as EventObserver; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Indexer\IndexerRegistry; -use Magento\Framework\Module\Manager; +use Magento\Framework\Module\Manager as ModuleManager; use Magento\Framework\ObjectManagerInterface; class ReindexProductOnLastItemPurchase implements ObserverInterface { + /** + * @var \Magento\Framework\Indexer\IndexerInterface + */ protected $indexer; /** @@ -20,7 +23,7 @@ class ReindexProductOnLastItemPurchase implements ObserverInterface protected $objectManager; /** - * @var Manager + * @var ModuleManager */ protected $moduleManager; @@ -32,12 +35,12 @@ class ReindexProductOnLastItemPurchase implements ObserverInterface /** * @param IndexerRegistry $indexerRegistry * @param ObjectManagerInterface $objectManager - * @param Manager $moduleManager + * @param ModuleManager $moduleManager * @param ProductRepositoryInterface $productRepository */ public function __construct( ObjectManagerInterface $objectManager, - Manager $moduleManager, + ModuleManager $moduleManager, ProductRepositoryInterface $productRepository, IndexerRegistry $indexerRegistry ) { @@ -46,6 +49,7 @@ public function __construct( $this->productRepository = $productRepository; $this->indexer = $indexerRegistry->get('algolia_products'); } + /** * @param EventObserver $observer * @return void @@ -58,10 +62,10 @@ public function execute(EventObserver $observer) return; } - if ($this->moduleManager->isEnabled('Magento_Inventory')) - { + if ($this->moduleManager->isEnabled('Magento_Inventory')) { $isSingleMode = $this->objectManager->create(\Magento\InventoryCatalogApi\Model\IsSingleSourceModeInterface::class); $defaultSourceProvider = $this->objectManager->create(\Magento\InventoryCatalogApi\Api\DefaultSourceProviderInterface::class); + if (!empty($shipment->getExtensionAttributes()) && !empty($shipment->getExtensionAttributes()->getSourceCode())) { $sourceCode = $shipment->getExtensionAttributes()->getSourceCode(); @@ -72,12 +76,9 @@ public function execute(EventObserver $observer) foreach ($shipment->getAllItems() as $item) { $getSourceItemBySku = $this->objectManager->create(\Magento\InventoryApi\Api\GetSourceItemsBySkuInterface::class); $sourceItemList = $getSourceItemBySku->execute($item->getSku()); - foreach ($sourceItemList as $source) - { - if ($source->getSourceCode() == $sourceCode) - { - if ($source->getQuantity() < 1) - { + foreach ($sourceItemList as $source) { + if ($source->getSourceCode() == $sourceCode) { + if ($source->getQuantity() < 1) { $this->indexer->reindexRow($item->getProductId()); } } diff --git a/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php b/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php index 4828f16ba..15f9278eb 100644 --- a/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php +++ b/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php @@ -6,28 +6,28 @@ use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Indexer\IndexerRegistry; -use Magento\Framework\Module\Manager; +use Magento\Framework\Module\ModuleManager; class ReindexProductOnLastItemPurchaseIfMsiDisable implements ObserverInterface { protected $indexer; - /** @var Manager */ + /** @var ModuleManager */ protected $moduleManager; /** @var ProductRepositoryInterface */ - protected $productRepository; + protected $productRepository; /** @var IndexerRegistry */ protected $indexerRegistry; /** - * @param Manager $moduleManager + * @param ModuleManager $moduleManager * @param ProductRepositoryInterface $productRepository * @param IndexerRegistry $indexerRegistry */ public function __construct( - Manager $moduleManager, + ModuleManager $moduleManager, ProductRepositoryInterface $productRepository, IndexerRegistry $indexerRegistry ) { @@ -36,6 +36,11 @@ public function __construct( $this->indexer = $indexerRegistry->get('algolia_products'); } + /** + * @param Observer $observer + * @return void + * @throws \Magento\Framework\Exception\NoSuchEntityException + */ public function execute(Observer $observer) { if (!$this->moduleManager->isEnabled('Magento_Inventory')) { @@ -51,7 +56,7 @@ public function execute(Observer $observer) } } - if($productIds) { + if ($productIds) { $productTobeReindex = []; foreach ($productIds as $productId) { $product = $this->productRepository->getById($productId); From 59c6c3f782c23aeef9d54e4eafb5375f83da9519 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Thu, 22 Sep 2022 12:15:20 +0530 Subject: [PATCH 26/73] MAGE-374 --- view/frontend/web/internals/autocomplete.css | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/view/frontend/web/internals/autocomplete.css b/view/frontend/web/internals/autocomplete.css index 5a05500dd..7c747eba5 100755 --- a/view/frontend/web/internals/autocomplete.css +++ b/view/frontend/web/internals/autocomplete.css @@ -24,8 +24,12 @@ font-size: 10px; color: #666; overflow: hidden; - white-space: nowrap; text-overflow: ellipsis; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + height: 30px; + max-height: 30px; + display: -webkit-box; } #algolia-autocomplete-container .aa-dropdown-menu .info-without-thumb .details em, .aa-Panel .info-without-thumb .details em { @@ -153,6 +157,8 @@ color: #000; text-align: left; text-decoration: none; + width: 96%; + overflow: hidden; } #algolia-autocomplete-container .aa-dropdown-menu .other-sections .aa-dataset-suggestions .algoliasearch-autocomplete-hit { From d7321f7e1d2c664b5a2318ade93cab2c88d49e6a Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Thu, 22 Sep 2022 13:18:41 +0530 Subject: [PATCH 27/73] Updated widget text field descriptions --- etc/widget.xml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/etc/widget.xml b/etc/widget.xml index 55cb0c94c..33549d88d 100644 --- a/etc/widget.xml +++ b/etc/widget.xml @@ -5,13 +5,17 @@ You can allow Algolia Recommend Trending items to appear anywhere you want - + + How many products do you want to display in the Trending Items?. + 6 + Please Input Valid facet attribute name EX:- color,size etc. + Please Enter Valid Facet Value. From c8912867c149fe5b384a07d4112205655ba32ff2 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Thu, 22 Sep 2022 13:53:00 +0530 Subject: [PATCH 28/73] Added the comment for observer --- Observer/ReindexProductOnLastItemPurchase.php | 3 +++ Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Observer/ReindexProductOnLastItemPurchase.php b/Observer/ReindexProductOnLastItemPurchase.php index f86a10345..26801e5ba 100644 --- a/Observer/ReindexProductOnLastItemPurchase.php +++ b/Observer/ReindexProductOnLastItemPurchase.php @@ -62,6 +62,9 @@ public function execute(EventObserver $observer) return; } + // Adding the Product to Queue if last item purchased + // Also Checking if user using the Magento MSI module or not. + // if user not using MSI then this feature handle in ReindexProductOnLastItemPurchaseIfMsiDisable Observer if ($this->moduleManager->isEnabled('Magento_Inventory')) { $isSingleMode = $this->objectManager->create(\Magento\InventoryCatalogApi\Model\IsSingleSourceModeInterface::class); $defaultSourceProvider = $this->objectManager->create(\Magento\InventoryCatalogApi\Api\DefaultSourceProviderInterface::class); diff --git a/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php b/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php index 15f9278eb..0e1ba1cdd 100644 --- a/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php +++ b/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php @@ -6,7 +6,7 @@ use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Indexer\IndexerRegistry; -use Magento\Framework\Module\ModuleManager; +use Magento\Framework\Module\Manager as ModuleManager; class ReindexProductOnLastItemPurchaseIfMsiDisable implements ObserverInterface { @@ -43,6 +43,9 @@ public function __construct( */ public function execute(Observer $observer) { + // Adding the Product to Queue if last item purchased + // Also Checking if user using the Magento MSI module or not. + // if user using MSI then this feature handle in ReindexProductOnLastItemPurchase Observer if (!$this->moduleManager->isEnabled('Magento_Inventory')) { $quote = $observer->getEvent()->getQuote(); $productIds = []; From 8f76cf0684e3a978573a42f5a7a3b874c283db1d Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 23 Sep 2022 13:57:34 +0530 Subject: [PATCH 29/73] Updated code to fix conversion issue for configurable product --- Model/Checkout/Cart.php | 86 +++++++++++++++++++ .../Insights/CheckoutCartProductAddAfter.php | 22 +---- .../Insights/CheckoutCartProductAddBefore.php | 11 +-- etc/di.xml | 2 + 4 files changed, 92 insertions(+), 29 deletions(-) create mode 100644 Model/Checkout/Cart.php diff --git a/Model/Checkout/Cart.php b/Model/Checkout/Cart.php new file mode 100644 index 000000000..ce86485f9 --- /dev/null +++ b/Model/Checkout/Cart.php @@ -0,0 +1,86 @@ +_getProduct($productInfo); + $productId = $product->getId(); + if ($productId) { + $request = $this->getQtyRequest($product, $requestInfo); + try { + $this->_eventManager->dispatch( + 'checkout_cart_product_add_before', + ['info' => $requestInfo, 'product' => $product] + ); + $result = $this->getQuote()->addProduct($product, $request); + } catch (\Magento\Framework\Exception\LocalizedException $e) { + $this->_checkoutSession->setUseNotice(false); + $result = $e->getMessage(); + } + /** + * String we can get if prepare process has error + */ + if (is_string($result)) { + if ($product->hasOptionsValidationFail()) { + $redirectUrl = $product->getUrlModel()->getUrl( + $product, + ['_query' => ['startcustomization' => 1]] + ); + } elseif (isset($requestInfo['queryID']) && $requestInfo['queryID'] != '') { + $redirectUrl = $product->getProductUrl()."?queryID=".$requestInfo['queryID']; + } else { + $redirectUrl = $product->getProductUrl(); + } + $this->_checkoutSession->setRedirectUrl($redirectUrl); + if ($this->_checkoutSession->getUseNotice() === null) { + $this->_checkoutSession->setUseNotice(true); + } + throw new \Magento\Framework\Exception\LocalizedException(__($result)); + } + } else { + throw new \Magento\Framework\Exception\LocalizedException(__('The product does not exist.')); + } + + $this->_eventManager->dispatch( + 'checkout_cart_product_add_after', + ['quote_item' => $result, 'product' => $product] + ); + $this->_checkoutSession->setLastAddedProductId($productId); + return $this; + } + + /** + * Get request quantity + * + * @param Product $product + * @param \Magento\Framework\DataObject|int|array $request + * @return int|DataObject + */ + private function getQtyRequest($product, $request = 0) + { + $request = $this->_getProductRequest($request); + $stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId()); + $minimumQty = $stockItem->getMinSaleQty(); + //If product quantity is not specified in request and there is set minimal qty for it + if ($minimumQty + && $minimumQty > 0 + && !$request->getQty() + ) { + $request->setQty($minimumQty); + } + + return $request; + } +} diff --git a/Model/Observer/Insights/CheckoutCartProductAddAfter.php b/Model/Observer/Insights/CheckoutCartProductAddAfter.php index b929d30d3..227ae13fb 100644 --- a/Model/Observer/Insights/CheckoutCartProductAddAfter.php +++ b/Model/Observer/Insights/CheckoutCartProductAddAfter.php @@ -7,7 +7,6 @@ use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Psr\Log\LoggerInterface; -use Magento\Framework\Session\SessionManagerInterface; class CheckoutCartProductAddAfter implements ObserverInterface { @@ -20,25 +19,14 @@ class CheckoutCartProductAddAfter implements ObserverInterface /** @var LoggerInterface */ private $logger; - /** @var SessionManagerInterface */ - private $_coreSession; - - /** - * @param Data $dataHelper - * @param InsightsHelper $insightsHelper - * @param LoggerInterface $logger - * @param SessionManagerInterface $coreSession - */ public function __construct( Data $dataHelper, InsightsHelper $insightsHelper, - LoggerInterface $logger, - SessionManagerInterface $coreSession + LoggerInterface $logger ) { $this->dataHelper = $dataHelper; $this->insightsHelper = $insightsHelper; $this->logger = $logger; - $this->_coreSession = $coreSession; } /** @@ -75,18 +63,14 @@ public function execute(Observer $observer) if ($this->getConfigHelper()->isClickConversionAnalyticsEnabled($storeId) && $this->getConfigHelper()->getConversionAnalyticsMode($storeId) === 'add_to_cart') { - $this->_coreSession->start(); - $queryId = $this->_coreSession->getQueryId(); - if ($product->hasData('queryId') || $queryId) { + if ($product->hasData('queryId')) { try { - $queryId = $product->getData('queryId') ?? $queryId; $userClient->convertedObjectIDsAfterSearch( __('Added to Cart'), $this->dataHelper->getIndexName('_products', $storeId), [$product->getId()], - $queryId + $product->getData('queryId') ); - $this->_coreSession->unsQueryId(); } catch (\Exception $e) { $this->logger->critical($e); } diff --git a/Model/Observer/Insights/CheckoutCartProductAddBefore.php b/Model/Observer/Insights/CheckoutCartProductAddBefore.php index 29c3c1c29..ebce030d0 100644 --- a/Model/Observer/Insights/CheckoutCartProductAddBefore.php +++ b/Model/Observer/Insights/CheckoutCartProductAddBefore.php @@ -6,7 +6,6 @@ use Algolia\AlgoliaSearch\Helper\InsightsHelper; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; -use Magento\Framework\Session\SessionManagerInterface; class CheckoutCartProductAddBefore implements ObserverInterface { @@ -16,22 +15,16 @@ class CheckoutCartProductAddBefore implements ObserverInterface /** @var InsightsHelper */ private $insightsHelper; - /** @var SessionManagerInterface */ - private $_coreSession; - /** * @param ConfigHelper $configHelper * @param InsightsHelper $insightsHelper - * @param SessionManagerInterface $coreSession */ public function __construct( ConfigHelper $configHelper, - InsightsHelper $insightsHelper, - SessionManagerInterface $coreSession + InsightsHelper $insightsHelper ) { $this->configHelper = $configHelper; $this->insightsHelper = $insightsHelper; - $this->_coreSession = $coreSession; } /** @@ -45,8 +38,6 @@ public function execute(Observer $observer) $requestInfo = $observer->getEvent()->getInfo(); if (isset($requestInfo['queryID']) && $requestInfo['queryID'] != '') { - $this->_coreSession->start(); - $this->_coreSession->setQueryId($requestInfo['queryID']); $product->setData('queryId', $requestInfo['queryID']); } } diff --git a/etc/di.xml b/etc/di.xml index e14a17af1..b97c90364 100755 --- a/etc/di.xml +++ b/etc/di.xml @@ -120,4 +120,6 @@ + + From 43ffcbfd7084db39b9c59083fef20a7facef8656 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 23 Sep 2022 16:47:38 +0530 Subject: [PATCH 30/73] Refactor the insight code --- Observer/.DS_Store | Bin 0 -> 6148 bytes .../Insights/CheckoutCartProductAddAfter.php | 94 +++++++++++++ .../Insights/CheckoutCartProductAddBefore.php | 25 ++++ ...CheckoutOnepageControllerSuccessAction.php | 129 ++++++++++++++++++ Observer/Insights/CustomerLogin.php | 38 ++++++ Observer/Insights/WishlistProductAddAfter.php | 71 ++++++++++ etc/frontend/events.xml | 10 +- 7 files changed, 362 insertions(+), 5 deletions(-) create mode 100644 Observer/.DS_Store create mode 100644 Observer/Insights/CheckoutCartProductAddAfter.php create mode 100644 Observer/Insights/CheckoutCartProductAddBefore.php create mode 100644 Observer/Insights/CheckoutOnepageControllerSuccessAction.php create mode 100644 Observer/Insights/CustomerLogin.php create mode 100644 Observer/Insights/WishlistProductAddAfter.php diff --git a/Observer/.DS_Store b/Observer/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..7dcd798813329876cfc86bbb1f9fc6c43a2f72d9 GIT binary patch literal 6148 zcmeHKyH3ME5S)b+mS|E^-WMS82S*f&)cFAvkOGorOC(Ucd)M~emN~vhS}KqVqynixDv%0XP#}6`b8~@{sZ<~p_@4^s z|Dn(oYvAB$zYY$1eAoO;QH^uEOAt$}YvAC>3{AY0=%o@@4DoWtOYmyo;OONL+nLXa zoh5E4V!Jb5j1H-eIi>=sz*vE6U(U7vKhl4=|Bs7ul?tQ+e@X$FE!WEhKPh_aC%mF_@@nAVXyuGsIWZ3cs!Lib@EZyo0R)U8sQ>@~ literal 0 HcmV?d00001 diff --git a/Observer/Insights/CheckoutCartProductAddAfter.php b/Observer/Insights/CheckoutCartProductAddAfter.php new file mode 100644 index 000000000..40bd9779f --- /dev/null +++ b/Observer/Insights/CheckoutCartProductAddAfter.php @@ -0,0 +1,94 @@ +dataHelper = $dataHelper; + $this->insightsHelper = $insightsHelper; + $this->logger = $logger; + $this->configHelper = $this->insightsHelper->getConfigHelper(); + } + + /** + * @param Observer $observer + * ['quote_item' => $result, 'product' => $product] + */ + public function execute(Observer $observer) + { + /** @var Item $quoteItem */ + $quoteItem = $observer->getEvent()->getQuoteItem(); + /** @var Product $product */ + $product = $observer->getEvent()->getProduct(); + $storeId = $quoteItem->getStoreId(); + + if (!$this->insightsHelper->isAddedToCartTracked($storeId) && !$this->insightsHelper->isOrderPlacedTracked($storeId)) { + return; + } + + $userClient = $this->insightsHelper->getUserInsightsClient(); + + if ($this->configHelper->isClickConversionAnalyticsEnabled($storeId) && $product->hasData('queryId')) { + $conversionAnalyticsMode = $this->configHelper->getConversionAnalyticsMode($storeId); + switch ($conversionAnalyticsMode) { + case 'place_order': + $quoteItem->setData('algoliasearch_query_param', $product->getData('queryId')); + break; + case 'add_to_cart': + try { + $userClient->convertedObjectIDsAfterSearch( + __('Added to Cart'), + $this->dataHelper->getIndexName('_products', $storeId), + [$product->getId()], + $product->getData('queryId') + ); + } catch (\Exception $e) { + $this->logger->critical($e); + } + } + } else { + try { + $userClient->convertedObjectIDs( + __('Added to Cart'), + $this->dataHelper->getIndexName('_products', $storeId), + [$product->getId()] + ); + } catch (\Exception $e) { + $this->logger->critical($e); + } + } + } +} diff --git a/Observer/Insights/CheckoutCartProductAddBefore.php b/Observer/Insights/CheckoutCartProductAddBefore.php new file mode 100644 index 000000000..3262862ab --- /dev/null +++ b/Observer/Insights/CheckoutCartProductAddBefore.php @@ -0,0 +1,25 @@ + $requestInfo, 'product' => $product] + */ + public function execute(Observer $observer) + { + /** @var Product $product */ + $product = $observer->getEvent()->getProduct(); + $requestInfo = $observer->getEvent()->getInfo(); + + if (isset($requestInfo['queryID']) && $requestInfo['queryID'] != '') { + $product->setData('queryId', $requestInfo['queryID']); + } + } +} diff --git a/Observer/Insights/CheckoutOnepageControllerSuccessAction.php b/Observer/Insights/CheckoutOnepageControllerSuccessAction.php new file mode 100644 index 000000000..e3a694b60 --- /dev/null +++ b/Observer/Insights/CheckoutOnepageControllerSuccessAction.php @@ -0,0 +1,129 @@ +dataHelper = $dataHelper; + $this->insightsHelper = $insightsHelper; + $this->orderFactory = $orderFactory; + $this->logger = $logger; + $this->configHelper = $this->insightsHelper->getConfigHelper(); + } + + /** + * @param Observer $observer + * + * @return $this + */ + public function execute(Observer $observer) + { + /** @var Order $order */ + $order = $observer->getEvent()->getOrder(); + + if (!$order) { + $orderId = $observer->getEvent()->getOrderIds()[0]; + $order = $this->orderFactory->create()->loadByIncrementId($orderId); + } + + if (!$order || !$this->insightsHelper->isOrderPlacedTracked($order->getStoreId())) { + return $this; + } + + $userClient = $this->insightsHelper->getUserInsightsClient(); + $orderItems = $order->getAllVisibleItems(); + + if ($this->configHelper->isClickConversionAnalyticsEnabled($order->getStoreId()) + && $this->configHelper->getConversionAnalyticsMode($order->getStoreId()) === 'place_order') { + $queryIds = []; + /** @var Item $item */ + foreach ($orderItems as $item) { + if ($item->hasData('algoliasearch_query_param')) { + $queryId = $item->getData('algoliasearch_query_param'); + $queryIds[$queryId][] = $item->getProductId(); + } + } + + if (count($queryIds) > 0) { + foreach ($queryIds as $queryId => $productIds) { + + // Event can't process more than 20 objects + $productIds = array_slice($productIds, 0, 20); + + try { + $userClient->convertedObjectIDsAfterSearch( + __('Placed Order'), + $this->dataHelper->getIndexName('_products', $order->getStoreId()), + $productIds, + $queryId + ); + } catch (Exception $e) { + $this->logger->critical($e); + continue; // skip item + } + } + } + } else { + $productIds = []; + /** @var Item $item */ + foreach ($orderItems as $item) { + $productIds[] = $item->getProductId(); + + // Event can't process more than 20 objects + if (count($productIds) > 20) { + break; + } + } + + try { + $userClient->convertedObjectIDs( + __('Placed Order'), + $this->dataHelper->getIndexName('_products', $order->getStoreId()), + $productIds + ); + } catch (Exception $e) { + $this->logger->critical($e); + } + } + + return $this; + } +} diff --git a/Observer/Insights/CustomerLogin.php b/Observer/Insights/CustomerLogin.php new file mode 100644 index 000000000..81e65e6e9 --- /dev/null +++ b/Observer/Insights/CustomerLogin.php @@ -0,0 +1,38 @@ +insightsHelper = $insightsHelper; + } + + /** + * @param Observer $observer + * ['customer' => $customer] + */ + public function execute(Observer $observer) + { + /** @var Customer $customer */ + $customer = $observer->getEvent()->getCustomer(); + + if ($this->insightsHelper->getPersonalizationHelper()->isPersoEnabled($customer->getStoreId())) { + $this->insightsHelper->setUserToken($customer); + } + } +} diff --git a/Observer/Insights/WishlistProductAddAfter.php b/Observer/Insights/WishlistProductAddAfter.php new file mode 100644 index 000000000..33baf8e19 --- /dev/null +++ b/Observer/Insights/WishlistProductAddAfter.php @@ -0,0 +1,71 @@ +dataHelper = $dataHelper; + $this->personalisationHelper = $personalisationHelper; + $this->insightsHelper = $insightsHelper; + } + + /** + * @param Observer $observer + * ['order' => $this] + */ + public function execute(Observer $observer) + { + /** @var Order $order */ + $items = $observer->getEvent()->getItems(); + /** @var Item $firstItem */ + $firstItem = $items[0]; + + if (!$this->personalisationHelper->isPersoEnabled($firstItem->getStoreId()) + || !$this->personalisationHelper->isWishlistAddTracked($firstItem->getStoreId())) { + return; + } + + $userClient = $this->insightsHelper->getUserInsightsClient(); + $productIds = []; + + /** @var Item $item */ + foreach ($items as $item) { + $productIds[] = $item->getProductId(); + } + + $userClient->convertedObjectIDs( + __('Added to Wishlist'), + $this->dataHelper->getIndexName('_products', $firstItem->getStoreId()), + $productIds + ); + } +} diff --git a/etc/frontend/events.xml b/etc/frontend/events.xml index 0b14a3beb..56a9b3447 100755 --- a/etc/frontend/events.xml +++ b/etc/frontend/events.xml @@ -9,19 +9,19 @@ - + - + - + - + - + \ No newline at end of file From 8f90e884b3c0412075aa090fe25d71417c9fdfa5 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 23 Sep 2022 16:51:58 +0530 Subject: [PATCH 31/73] Refactor the insight code --- Helper/Configuration/AssetHelper.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Helper/Configuration/AssetHelper.php b/Helper/Configuration/AssetHelper.php index 088fe29fe..15528de2e 100644 --- a/Helper/Configuration/AssetHelper.php +++ b/Helper/Configuration/AssetHelper.php @@ -70,6 +70,11 @@ class AssetHelper extends \Magento\Framework\App\Helper\AbstractHelper 'url' => 'https://www.algolia.com/doc/integration/magento-2/troubleshooting/general-faq/?utm_source=magento&utm_medium=extension&utm_campaign=magento_2&utm_term=shop-owner&utm_content=doc-link', 'icon' => 'iconFaq', ], + [ + 'title' => 'Issues', + 'url' => 'https://github.com/algolia/algoliasearch-magento-2/issues/', + 'icon' => 'iconIssues', + ], ], 'algoliasearch_autocomplete' => [ [ From b060d0bb8e2dfbd3c6189625a6560acb787e28f6 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 23 Sep 2022 16:52:34 +0530 Subject: [PATCH 32/73] Refactor the insight code --- Observer/.DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Observer/.DS_Store diff --git a/Observer/.DS_Store b/Observer/.DS_Store deleted file mode 100644 index 7dcd798813329876cfc86bbb1f9fc6c43a2f72d9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKyH3ME5S)b+mS|E^-WMS82S*f&)cFAvkOGorOC(Ucd)M~emN~vhS}KqVqynixDv%0XP#}6`b8~@{sZ<~p_@4^s z|Dn(oYvAB$zYY$1eAoO;QH^uEOAt$}YvAC>3{AY0=%o@@4DoWtOYmyo;OONL+nLXa zoh5E4V!Jb5j1H-eIi>=sz*vE6U(U7vKhl4=|Bs7ul?tQ+e@X$FE!WEhKPh_aC%mF_@@nAVXyuGsIWZ3cs!Lib@EZyo0R)U8sQ>@~ From a99ccba8749f1f0cdf4cca856bae848f10170cb7 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 23 Sep 2022 20:08:34 +0530 Subject: [PATCH 33/73] Fixed the conversion issue for grouped products --- Model/Checkout/Cart.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Model/Checkout/Cart.php b/Model/Checkout/Cart.php index ce86485f9..bceb597d8 100644 --- a/Model/Checkout/Cart.php +++ b/Model/Checkout/Cart.php @@ -34,12 +34,19 @@ public function addProduct($productInfo, $requestInfo = null) */ if (is_string($result)) { if ($product->hasOptionsValidationFail()) { + $cartQueryParams['startcustomization'] = 1; + if (isset($requestInfo['queryID'])) { + $cartQueryParams['queryID'] = $requestInfo['queryID']; + } $redirectUrl = $product->getUrlModel()->getUrl( $product, - ['_query' => ['startcustomization' => 1]] + ['_query' => $cartQueryParams] ); } elseif (isset($requestInfo['queryID']) && $requestInfo['queryID'] != '') { - $redirectUrl = $product->getProductUrl()."?queryID=".$requestInfo['queryID']; + $redirectUrl = $product->getUrlModel()->getUrl( + $product, + ['_query' => ['queryID' => $requestInfo['queryID'] ]] + ); } else { $redirectUrl = $product->getProductUrl(); } From 31b9c24b07cde973e1c43c9e215e4fc44b9386db Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Tue, 27 Sep 2022 11:11:24 +0530 Subject: [PATCH 34/73] Updated elements class for recommends --- view/frontend/templates/recommend/cart/recommend_items.phtml | 4 ++-- view/frontend/templates/recommend/products.phtml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/view/frontend/templates/recommend/cart/recommend_items.phtml b/view/frontend/templates/recommend/cart/recommend_items.phtml index e7d71437a..e72407c05 100644 --- a/view/frontend/templates/recommend/cart/recommend_items.phtml +++ b/view/frontend/templates/recommend/cart/recommend_items.phtml @@ -6,8 +6,8 @@ $cartItems = $this->getAllCartItems(); ?>
-
-
+
+
diff --git a/view/frontend/templates/recommend/products.phtml b/view/frontend/templates/recommend/products.phtml index 034d4f755..6bea0f51b 100644 --- a/view/frontend/templates/recommend/products.phtml +++ b/view/frontend/templates/recommend/products.phtml @@ -6,8 +6,8 @@ $product = $block->getProduct(); ?>
-
-
+
+
From 1a28624ac02a3fcaa76efc33f416b68c12817f8d Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Tue, 27 Sep 2022 11:28:35 +0530 Subject: [PATCH 35/73] Updated readme file for algolia phpclient --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5b68fd158..ae32641de 100755 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ Depending on the extension version you are using, you could have a different PHP | v1.x | [1.28.0](https://github.com/algolia/algoliasearch-client-php/tree/1.28.0) | | v2.x | [2.5.1](https://github.com/algolia/algoliasearch-client-php/tree/2.5.1) | | v3.x | [2.5.1](https://github.com/algolia/algoliasearch-client-php/tree/2.5.1) | -| v3.6.x | [3.2.0](https://github.com/algolia/algoliasearch-client-php/tree/3.2.0) | +| >=v3.6.x | [3.2.0](https://github.com/algolia/algoliasearch-client-php/tree/3.2.0) | Refer to these docs when customising your Algolia Magento extension backend: - [Indexing](https://www.algolia.com/doc/integration/magento-2/how-it-works/indexing/) From efe0d32c4c90bfbf6ef28642e3425b8914e94b93 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Tue, 27 Sep 2022 11:29:43 +0530 Subject: [PATCH 36/73] Updated readme file for algolia phpclient --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ae32641de..a3658a7e3 100755 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ Depending on the extension version you are using, you could have a different PHP | v1.x | [1.28.0](https://github.com/algolia/algoliasearch-client-php/tree/1.28.0) | | v2.x | [2.5.1](https://github.com/algolia/algoliasearch-client-php/tree/2.5.1) | | v3.x | [2.5.1](https://github.com/algolia/algoliasearch-client-php/tree/2.5.1) | -| >=v3.6.x | [3.2.0](https://github.com/algolia/algoliasearch-client-php/tree/3.2.0) | +| >= v3.6.x | [3.2.0](https://github.com/algolia/algoliasearch-client-php/tree/3.2.0) | Refer to these docs when customising your Algolia Magento extension backend: - [Indexing](https://www.algolia.com/doc/integration/magento-2/how-it-works/indexing/) From fc28c3c8e1c963dbb44128b621cf63c0c4412554 Mon Sep 17 00:00:00 2001 From: rachel-trott Date: Tue, 27 Sep 2022 14:18:55 -0500 Subject: [PATCH 37/73] reformatting code --- Observer/ReindexProductOnLastItemPurchase.php | 4 +--- .../ReindexProductOnLastItemPurchaseIfMsiDisable.php | 10 ++++------ 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/Observer/ReindexProductOnLastItemPurchase.php b/Observer/ReindexProductOnLastItemPurchase.php index 26801e5ba..9de3c6333 100644 --- a/Observer/ReindexProductOnLastItemPurchase.php +++ b/Observer/ReindexProductOnLastItemPurchase.php @@ -62,9 +62,7 @@ public function execute(EventObserver $observer) return; } - // Adding the Product to Queue if last item purchased - // Also Checking if user using the Magento MSI module or not. - // if user not using MSI then this feature handle in ReindexProductOnLastItemPurchaseIfMsiDisable Observer + // Add product to Algolia Indexing Queue if last item was purchased and check if Magento MSI related modules are enabled. if ($this->moduleManager->isEnabled('Magento_Inventory')) { $isSingleMode = $this->objectManager->create(\Magento\InventoryCatalogApi\Model\IsSingleSourceModeInterface::class); $defaultSourceProvider = $this->objectManager->create(\Magento\InventoryCatalogApi\Api\DefaultSourceProviderInterface::class); diff --git a/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php b/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php index 0e1ba1cdd..0bc528e9b 100644 --- a/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php +++ b/Observer/ReindexProductOnLastItemPurchaseIfMsiDisable.php @@ -43,9 +43,7 @@ public function __construct( */ public function execute(Observer $observer) { - // Adding the Product to Queue if last item purchased - // Also Checking if user using the Magento MSI module or not. - // if user using MSI then this feature handle in ReindexProductOnLastItemPurchase Observer + // Add product to Algolia Indexing Queue if last item was purchased and if Magento MSI related modules are disabled. if (!$this->moduleManager->isEnabled('Magento_Inventory')) { $quote = $observer->getEvent()->getQuote(); $productIds = []; @@ -60,15 +58,15 @@ public function execute(Observer $observer) } if ($productIds) { - $productTobeReindex = []; + $productToReindex = []; foreach ($productIds as $productId) { $product = $this->productRepository->getById($productId); $stockInfo = $product->getData('quantity_and_stock_status'); if ($stockInfo['qty'] < 1) { - $productTobeReindex[] = $productId; + $productToReindex[] = $productId; } } - $this->indexer->reindexList($productTobeReindex); + $this->indexer->reindexList($productToReindex); } } } From ad2f7800ebc1316ad5a12ee1dd787df881c153e7 Mon Sep 17 00:00:00 2001 From: rachel-trott Date: Tue, 27 Sep 2022 14:21:45 -0500 Subject: [PATCH 38/73] reformatting code --- etc/adminhtml/events.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/adminhtml/events.xml b/etc/adminhtml/events.xml index 5a2f5fe19..62132a089 100755 --- a/etc/adminhtml/events.xml +++ b/etc/adminhtml/events.xml @@ -63,7 +63,7 @@ - + From 8624964b93825906c072b3f3dc87eebe8e29b258 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Wed, 28 Sep 2022 19:07:34 +0530 Subject: [PATCH 39/73] Remove old insight files --- .../Insights/CheckoutCartProductAddAfter.php | 90 ------------ .../Insights/CheckoutCartProductAddBefore.php | 44 ------ ...CheckoutOnepageControllerSuccessAction.php | 128 ------------------ Model/Observer/Insights/CustomerLogin.php | 43 ------ .../Insights/WishlistProductAddAfter.php | 69 ---------- 5 files changed, 374 deletions(-) delete mode 100644 Model/Observer/Insights/CheckoutCartProductAddAfter.php delete mode 100644 Model/Observer/Insights/CheckoutCartProductAddBefore.php delete mode 100644 Model/Observer/Insights/CheckoutOnepageControllerSuccessAction.php delete mode 100644 Model/Observer/Insights/CustomerLogin.php delete mode 100644 Model/Observer/Insights/WishlistProductAddAfter.php diff --git a/Model/Observer/Insights/CheckoutCartProductAddAfter.php b/Model/Observer/Insights/CheckoutCartProductAddAfter.php deleted file mode 100644 index 227ae13fb..000000000 --- a/Model/Observer/Insights/CheckoutCartProductAddAfter.php +++ /dev/null @@ -1,90 +0,0 @@ -dataHelper = $dataHelper; - $this->insightsHelper = $insightsHelper; - $this->logger = $logger; - } - - /** - * @return \Algolia\AlgoliaSearch\Helper\ConfigHelper - */ - public function getConfigHelper() - { - return $this->insightsHelper->getConfigHelper(); - } - - /** - * @param Observer $observer - * ['quote_item' => $result, 'product' => $product] - */ - public function execute(Observer $observer) - { - /** @var \Magento\Quote\Model\Quote\Item $quoteItem */ - $quoteItem = $observer->getEvent()->getQuoteItem(); - /** @var \Magento\Catalog\Model\Product $product */ - $product = $observer->getEvent()->getProduct(); - $storeId = $quoteItem->getStoreId(); - - if ($this->getConfigHelper()->isClickConversionAnalyticsEnabled($storeId) - && $this->getConfigHelper()->getConversionAnalyticsMode($storeId) === 'place_order' - && $product->hasData('queryId')) { - $quoteItem->setData('algoliasearch_query_param', $product->getData('queryId')); - } - - if (!$this->insightsHelper->isAddedToCartTracked($storeId)) { - return; - } - - $userClient = $this->insightsHelper->getUserInsightsClient(); - - if ($this->getConfigHelper()->isClickConversionAnalyticsEnabled($storeId) - && $this->getConfigHelper()->getConversionAnalyticsMode($storeId) === 'add_to_cart') { - if ($product->hasData('queryId')) { - try { - $userClient->convertedObjectIDsAfterSearch( - __('Added to Cart'), - $this->dataHelper->getIndexName('_products', $storeId), - [$product->getId()], - $product->getData('queryId') - ); - } catch (\Exception $e) { - $this->logger->critical($e); - } - } - } else { - try { - $userClient->convertedObjectIDs( - __('Added to Cart'), - $this->dataHelper->getIndexName('_products', $storeId), - [$product->getId()] - ); - } catch (\Exception $e) { - $this->logger->critical($e); - } - } - } -} diff --git a/Model/Observer/Insights/CheckoutCartProductAddBefore.php b/Model/Observer/Insights/CheckoutCartProductAddBefore.php deleted file mode 100644 index ebce030d0..000000000 --- a/Model/Observer/Insights/CheckoutCartProductAddBefore.php +++ /dev/null @@ -1,44 +0,0 @@ -configHelper = $configHelper; - $this->insightsHelper = $insightsHelper; - } - - /** - * @param Observer $observer - * ['info' => $requestInfo, 'product' => $product] - */ - public function execute(Observer $observer) - { - /** @var \Magento\Catalog\Model\Product $product */ - $product = $observer->getEvent()->getProduct(); - $requestInfo = $observer->getEvent()->getInfo(); - - if (isset($requestInfo['queryID']) && $requestInfo['queryID'] != '') { - $product->setData('queryId', $requestInfo['queryID']); - } - } -} diff --git a/Model/Observer/Insights/CheckoutOnepageControllerSuccessAction.php b/Model/Observer/Insights/CheckoutOnepageControllerSuccessAction.php deleted file mode 100644 index b416a5fd6..000000000 --- a/Model/Observer/Insights/CheckoutOnepageControllerSuccessAction.php +++ /dev/null @@ -1,128 +0,0 @@ -dataHelper = $dataHelper; - $this->insightsHelper = $insightsHelper; - $this->orderFactory = $orderFactory; - $this->logger = $logger; - } - - /** - * @return \Algolia\AlgoliaSearch\Helper\ConfigHelper - */ - public function getConfigHelper() - { - return $this->insightsHelper->getConfigHelper(); - } - - /** - * @param Observer $observer - * - * @return $this|void - */ - public function execute(Observer $observer) - { - /** @var \Magento\Sales\Model\Order $order */ - $order = $observer->getEvent()->getOrder(); - - if (!$order) { - $orderId = $observer->getEvent()->getOrderIds()[0]; - $order = $this->orderFactory->create()->loadByIncrementId($orderId); - } - - if (!$order || !$this->insightsHelper->isOrderPlacedTracked($order->getStoreId())) { - return $this; - } - - $userClient = $this->insightsHelper->getUserInsightsClient(); - $orderItems = $order->getAllVisibleItems(); - - if ($this->getConfigHelper()->isClickConversionAnalyticsEnabled($order->getStoreId()) - && $this->getConfigHelper()->getConversionAnalyticsMode($order->getStoreId()) === 'place_order') { - $queryIds = []; - /** @var \Magento\Sales\Model\Order\Item $item */ - foreach ($orderItems as $item) { - if ($item->hasData('algoliasearch_query_param')) { - $queryId = $item->getData('algoliasearch_query_param'); - $queryIds[$queryId][] = $item->getProductId(); - } - } - - if (count($queryIds) > 0) { - foreach ($queryIds as $queryId => $productIds) { - - // Event can't process more than 20 objects - $productIds = array_slice($productIds, 0, 20); - - try { - $userClient->convertedObjectIDsAfterSearch( - __('Placed Order'), - $this->dataHelper->getIndexName('_products', $order->getStoreId()), - $productIds, - $queryId - ); - } catch (\Exception $e) { - continue; // skip item - } - } - } - } else { - $productIds = []; - /** @var \Magento\Sales\Model\Order\Item $item */ - foreach ($orderItems as $item) { - $productIds[] = $item->getProductId(); - - // Event can't process more than 20 objects - if (count($productIds) > 20) { - break; - } - } - - try { - $userClient->convertedObjectIDs( - __('Placed Order'), - $this->dataHelper->getIndexName('_products', $order->getStoreId()), - $productIds - ); - } catch (\Exception $e) { - $this->logger->critical($e); - } - } - - return $this; - } -} diff --git a/Model/Observer/Insights/CustomerLogin.php b/Model/Observer/Insights/CustomerLogin.php deleted file mode 100644 index 817ecee22..000000000 --- a/Model/Observer/Insights/CustomerLogin.php +++ /dev/null @@ -1,43 +0,0 @@ -configHelper = $configHelper; - $this->insightsHelper = $insightsHelper; - } - - /** - * @param Observer $observer - * ['customer' => $customer] - */ - public function execute(Observer $observer) - { - /** @var \Magento\Customer\Model\Customer $customer */ - $customer = $observer->getEvent()->getCustomer(); - - if ($this->insightsHelper->getPersonalizationHelper()->isPersoEnabled($customer->getStoreId())) { - $this->insightsHelper->setUserToken($customer); - } - } -} diff --git a/Model/Observer/Insights/WishlistProductAddAfter.php b/Model/Observer/Insights/WishlistProductAddAfter.php deleted file mode 100644 index 7133e9e5e..000000000 --- a/Model/Observer/Insights/WishlistProductAddAfter.php +++ /dev/null @@ -1,69 +0,0 @@ -dataHelper = $dataHelper; - $this->personalisationHelper = $personalisationHelper; - $this->insightsHelper = $insightsHelper; - } - - /** - * @param Observer $observer - * ['order' => $this] - */ - public function execute(Observer $observer) - { - /** @var \Magento\Sales\Model\Order $order */ - $items = $observer->getEvent()->getItems(); - /** @var \Magento\Wishlist\Model\Item $firstItem */ - $firstItem = $items[0]; - - if (!$this->personalisationHelper->isPersoEnabled($firstItem->getStoreId()) - || !$this->personalisationHelper->isWishlistAddTracked($firstItem->getStoreId())) { - return; - } - - $userClient = $this->insightsHelper->getUserInsightsClient(); - $productIds = []; - - /** @var \Magento\Wishlist\Model\Item $item */ - foreach ($items as $item) { - $productIds[] = $item->getProductId(); - } - - $userClient->convertedObjectIDs( - __('Added to Wishlist'), - $this->dataHelper->getIndexName('_products', $firstItem->getStoreId()), - $productIds - ); - } -} From d9f0c8e106184cd533faaf81ea4a030ad11cdd2d Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Wed, 28 Sep 2022 19:13:42 +0530 Subject: [PATCH 40/73] Fixed the Index name issue in query merchendizing --- view/adminhtml/templates/query/edit/merchandising.phtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/view/adminhtml/templates/query/edit/merchandising.phtml b/view/adminhtml/templates/query/edit/merchandising.phtml index 231935d5a..f52722c55 100644 --- a/view/adminhtml/templates/query/edit/merchandising.phtml +++ b/view/adminhtml/templates/query/edit/merchandising.phtml @@ -334,7 +334,7 @@ $isConfig = [ var initAutocomplete = function() { var client = algoliaAdminBundle.algoliasearch(config.appId, config.apiKey), - index = client.initIndex(config.indexName), + index = client.initIndex(window.algoliaSearch.helper.state.index), template = algoliaAdminBundle.Hogan.compile($('#algolia_merchandising_autocomplete_hit').html()), options = { hitsPerPage: config.searchParameters.hitsPerPage + 5, From b429e8f14dddd7180e074f9b2370ce27838f5b7c Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 30 Sep 2022 13:02:51 +0530 Subject: [PATCH 41/73] Updated code --- Model/Checkout/Cart.php | 93 ----------------------------------------- etc/di.xml | 2 - 2 files changed, 95 deletions(-) delete mode 100644 Model/Checkout/Cart.php diff --git a/Model/Checkout/Cart.php b/Model/Checkout/Cart.php deleted file mode 100644 index bceb597d8..000000000 --- a/Model/Checkout/Cart.php +++ /dev/null @@ -1,93 +0,0 @@ -_getProduct($productInfo); - $productId = $product->getId(); - if ($productId) { - $request = $this->getQtyRequest($product, $requestInfo); - try { - $this->_eventManager->dispatch( - 'checkout_cart_product_add_before', - ['info' => $requestInfo, 'product' => $product] - ); - $result = $this->getQuote()->addProduct($product, $request); - } catch (\Magento\Framework\Exception\LocalizedException $e) { - $this->_checkoutSession->setUseNotice(false); - $result = $e->getMessage(); - } - /** - * String we can get if prepare process has error - */ - if (is_string($result)) { - if ($product->hasOptionsValidationFail()) { - $cartQueryParams['startcustomization'] = 1; - if (isset($requestInfo['queryID'])) { - $cartQueryParams['queryID'] = $requestInfo['queryID']; - } - $redirectUrl = $product->getUrlModel()->getUrl( - $product, - ['_query' => $cartQueryParams] - ); - } elseif (isset($requestInfo['queryID']) && $requestInfo['queryID'] != '') { - $redirectUrl = $product->getUrlModel()->getUrl( - $product, - ['_query' => ['queryID' => $requestInfo['queryID'] ]] - ); - } else { - $redirectUrl = $product->getProductUrl(); - } - $this->_checkoutSession->setRedirectUrl($redirectUrl); - if ($this->_checkoutSession->getUseNotice() === null) { - $this->_checkoutSession->setUseNotice(true); - } - throw new \Magento\Framework\Exception\LocalizedException(__($result)); - } - } else { - throw new \Magento\Framework\Exception\LocalizedException(__('The product does not exist.')); - } - - $this->_eventManager->dispatch( - 'checkout_cart_product_add_after', - ['quote_item' => $result, 'product' => $product] - ); - $this->_checkoutSession->setLastAddedProductId($productId); - return $this; - } - - /** - * Get request quantity - * - * @param Product $product - * @param \Magento\Framework\DataObject|int|array $request - * @return int|DataObject - */ - private function getQtyRequest($product, $request = 0) - { - $request = $this->_getProductRequest($request); - $stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId()); - $minimumQty = $stockItem->getMinSaleQty(); - //If product quantity is not specified in request and there is set minimal qty for it - if ($minimumQty - && $minimumQty > 0 - && !$request->getQty() - ) { - $request->setQty($minimumQty); - } - - return $request; - } -} diff --git a/etc/di.xml b/etc/di.xml index b97c90364..e14a17af1 100755 --- a/etc/di.xml +++ b/etc/di.xml @@ -120,6 +120,4 @@ - - From 902e3fc699f93f4c8ba0c2eee684abaf1bb4d46d Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 30 Sep 2022 13:46:29 +0530 Subject: [PATCH 42/73] Updated code for cs fixer --- .../templates/recommend/cart/recommend_items.phtml | 7 ++++++- view/frontend/templates/recommend/products.phtml | 7 ++++++- .../templates/recommend/widget/trends-item.phtml | 13 +++++++++---- view/frontend/web/recommend.js | 2 +- 4 files changed, 22 insertions(+), 7 deletions(-) diff --git a/view/frontend/templates/recommend/cart/recommend_items.phtml b/view/frontend/templates/recommend/cart/recommend_items.phtml index e72407c05..1cd9b9335 100644 --- a/view/frontend/templates/recommend/cart/recommend_items.phtml +++ b/view/frontend/templates/recommend/cart/recommend_items.phtml @@ -9,5 +9,10 @@ $cartItems = $this->getAllCartItems();
diff --git a/view/frontend/templates/recommend/products.phtml b/view/frontend/templates/recommend/products.phtml index 6bea0f51b..57581d88f 100644 --- a/view/frontend/templates/recommend/products.phtml +++ b/view/frontend/templates/recommend/products.phtml @@ -9,6 +9,11 @@ $product = $block->getProduct();
diff --git a/view/frontend/templates/recommend/widget/trends-item.phtml b/view/frontend/templates/recommend/widget/trends-item.phtml index 06d27d00c..d15f6c577 100644 --- a/view/frontend/templates/recommend/widget/trends-item.phtml +++ b/view/frontend/templates/recommend/widget/trends-item.phtml @@ -7,8 +7,13 @@ $trendConstainer = 'trendItems' . $block->generateUniqueToken(); ?>
\ No newline at end of file diff --git a/view/frontend/web/recommend.js b/view/frontend/web/recommend.js index dff35e50c..b99a12ded 100644 --- a/view/frontend/web/recommend.js +++ b/view/frontend/web/recommend.js @@ -13,7 +13,7 @@ requirejs([ const indexName = this.defaultIndexName; if ($('body').hasClass('catalog-product-view') || $('body').hasClass('checkout-cart-index')) { // --- Add the current product objectID here --- - const currentObjectID = objectId; + const currentObjectID = algoliObjectId; if ((this.config.recommend.enabledFBT && $('body').hasClass('catalog-product-view')) || (this.config.recommend.enabledFBTInCart && $('body').hasClass('checkout-cart-index'))) { recommendJs.frequentlyBoughtTogether({ container: '#frequentlyBoughtTogether', From ab7f5fd4ddfba297593b7518918a51301e7dbca7 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 30 Sep 2022 15:34:10 +0530 Subject: [PATCH 43/73] Fixed the conversion issue for configurable product --- .../Insights/CheckoutCartProductAddAfter.php | 28 +++++++++++++------ .../Insights/CheckoutCartProductAddBefore.php | 17 +++++++++-- 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/Observer/Insights/CheckoutCartProductAddAfter.php b/Observer/Insights/CheckoutCartProductAddAfter.php index 40bd9779f..9b540994e 100644 --- a/Observer/Insights/CheckoutCartProductAddAfter.php +++ b/Observer/Insights/CheckoutCartProductAddAfter.php @@ -3,12 +3,14 @@ namespace Algolia\AlgoliaSearch\Observer\Insights; use Algolia\AlgoliaSearch\Helper\ConfigHelper; +use Algolia\AlgoliaSearch\Helper\Configuration\PersonalizationHelper; use Algolia\AlgoliaSearch\Helper\Data; use Algolia\AlgoliaSearch\Helper\InsightsHelper; use Exception; use Magento\Catalog\Model\Product; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\Session\SessionManagerInterface; use Magento\Quote\Model\Quote\Item; use Psr\Log\LoggerInterface; @@ -27,20 +29,30 @@ class CheckoutCartProductAddAfter implements ObserverInterface /** @var ConfigHelper */ protected ConfigHelper $configHelper; + /** @var PersonalizationHelper */ + private PersonalizationHelper $personalizationHelper; + + /** @var SessionManagerInterface */ + protected SessionManagerInterface $coreSession; + /** * @param Data $dataHelper * @param InsightsHelper $insightsHelper + * @param SessionManagerInterface $coreSession * @param LoggerInterface $logger */ public function __construct( Data $dataHelper, InsightsHelper $insightsHelper, + SessionManagerInterface $coreSession, LoggerInterface $logger ) { $this->dataHelper = $dataHelper; $this->insightsHelper = $insightsHelper; $this->logger = $logger; + $this->coreSession = $coreSession; $this->configHelper = $this->insightsHelper->getConfigHelper(); + $this->personalizationHelper = $this->insightsHelper->getPersonalizationHelper(); } /** @@ -60,12 +72,12 @@ public function execute(Observer $observer) } $userClient = $this->insightsHelper->getUserInsightsClient(); - - if ($this->configHelper->isClickConversionAnalyticsEnabled($storeId) && $product->hasData('queryId')) { + $queryId = $this->coreSession->getQueryId(); + if ($this->configHelper->isClickConversionAnalyticsEnabled($storeId) && $queryId) { $conversionAnalyticsMode = $this->configHelper->getConversionAnalyticsMode($storeId); switch ($conversionAnalyticsMode) { case 'place_order': - $quoteItem->setData('algoliasearch_query_param', $product->getData('queryId')); + $quoteItem->setData('algoliasearch_query_param', $queryId); break; case 'add_to_cart': try { @@ -73,22 +85,22 @@ public function execute(Observer $observer) __('Added to Cart'), $this->dataHelper->getIndexName('_products', $storeId), [$product->getId()], - $product->getData('queryId') + $queryId ); - } catch (\Exception $e) { + } catch (Exception $e) { $this->logger->critical($e); } } - } else { + } elseif ($this->personalizationHelper->isPersoEnabled($storeId) && $this->personalizationHelper->isCartAddTracked($storeId)) { try { $userClient->convertedObjectIDs( __('Added to Cart'), $this->dataHelper->getIndexName('_products', $storeId), [$product->getId()] ); - } catch (\Exception $e) { + } catch (Exception $e) { $this->logger->critical($e); } } } -} +} \ No newline at end of file diff --git a/Observer/Insights/CheckoutCartProductAddBefore.php b/Observer/Insights/CheckoutCartProductAddBefore.php index 3262862ab..59e933ff7 100644 --- a/Observer/Insights/CheckoutCartProductAddBefore.php +++ b/Observer/Insights/CheckoutCartProductAddBefore.php @@ -2,12 +2,24 @@ namespace Algolia\AlgoliaSearch\Observer\Insights; -use Magento\Catalog\Model\Product; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\Session\SessionManagerInterface; class CheckoutCartProductAddBefore implements ObserverInterface { + /** @var SessionManagerInterface */ + protected SessionManagerInterface $coreSession; + + /** + * @param SessionManagerInterface $coreSession + */ + public function __construct( + SessionManagerInterface $coreSession + ) { + $this->coreSession = $coreSession; + } + /** * @param Observer $observer * ['info' => $requestInfo, 'product' => $product] @@ -15,11 +27,10 @@ class CheckoutCartProductAddBefore implements ObserverInterface public function execute(Observer $observer) { /** @var Product $product */ - $product = $observer->getEvent()->getProduct(); $requestInfo = $observer->getEvent()->getInfo(); if (isset($requestInfo['queryID']) && $requestInfo['queryID'] != '') { - $product->setData('queryId', $requestInfo['queryID']); + $this->coreSession->setQueryId($requestInfo['queryID']); } } } From 71064b61a4fbb0d14e88cd452a39623bec5ae902 Mon Sep 17 00:00:00 2001 From: rachel-trott Date: Wed, 5 Oct 2022 01:31:49 -0500 Subject: [PATCH 44/73] fix duplicate object ids in place order conversion for config product reformatting code --- .../Configuration/PersonalizationHelper.php | 9 +++++-- .../Insights/CheckoutCartProductAddBefore.php | 1 - ...CheckoutOnepageControllerSuccessAction.php | 4 ++-- Observer/Insights/WishlistProductAddAfter.php | 24 ++++++++++++++----- 4 files changed, 27 insertions(+), 11 deletions(-) diff --git a/Helper/Configuration/PersonalizationHelper.php b/Helper/Configuration/PersonalizationHelper.php index 7088c8dd5..3112088b0 100644 --- a/Helper/Configuration/PersonalizationHelper.php +++ b/Helper/Configuration/PersonalizationHelper.php @@ -34,10 +34,15 @@ class PersonalizationHelper extends \Magento\Framework\App\Helper\AbstractHelper /** @var ConfigResourceInterface */ private $configResourceInterface; + /** + * @param \Magento\Framework\App\Helper\Context $context + * @param ScopeConfigInterface $configInterface + * @param ConfigResourceInterface $configResourceInterface + */ public function __construct( \Magento\Framework\App\Helper\Context $context, - ScopeConfigInterface $configInterface, - ConfigResourceInterface $configResourceInterface + ScopeConfigInterface $configInterface, + ConfigResourceInterface $configResourceInterface ) { $this->configInterface = $configInterface; $this->configResourceInterface = $configResourceInterface; diff --git a/Observer/Insights/CheckoutCartProductAddBefore.php b/Observer/Insights/CheckoutCartProductAddBefore.php index 59e933ff7..b9034b430 100644 --- a/Observer/Insights/CheckoutCartProductAddBefore.php +++ b/Observer/Insights/CheckoutCartProductAddBefore.php @@ -26,7 +26,6 @@ public function __construct( */ public function execute(Observer $observer) { - /** @var Product $product */ $requestInfo = $observer->getEvent()->getInfo(); if (isset($requestInfo['queryID']) && $requestInfo['queryID'] != '') { diff --git a/Observer/Insights/CheckoutOnepageControllerSuccessAction.php b/Observer/Insights/CheckoutOnepageControllerSuccessAction.php index e3a694b60..c688fed95 100644 --- a/Observer/Insights/CheckoutOnepageControllerSuccessAction.php +++ b/Observer/Insights/CheckoutOnepageControllerSuccessAction.php @@ -92,7 +92,7 @@ public function execute(Observer $observer) $userClient->convertedObjectIDsAfterSearch( __('Placed Order'), $this->dataHelper->getIndexName('_products', $order->getStoreId()), - $productIds, + array_unique($productIds), $queryId ); } catch (Exception $e) { @@ -117,7 +117,7 @@ public function execute(Observer $observer) $userClient->convertedObjectIDs( __('Placed Order'), $this->dataHelper->getIndexName('_products', $order->getStoreId()), - $productIds + array_unique($productIds) ); } catch (Exception $e) { $this->logger->critical($e); diff --git a/Observer/Insights/WishlistProductAddAfter.php b/Observer/Insights/WishlistProductAddAfter.php index 33baf8e19..1dc53ba62 100644 --- a/Observer/Insights/WishlistProductAddAfter.php +++ b/Observer/Insights/WishlistProductAddAfter.php @@ -5,10 +5,12 @@ use Algolia\AlgoliaSearch\Helper\Configuration\PersonalizationHelper; use Algolia\AlgoliaSearch\Helper\Data; use Algolia\AlgoliaSearch\Helper\InsightsHelper; +use Exception; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Sales\Model\Order; use Magento\Wishlist\Model\Item; +use Psr\Log\LoggerInterface; class WishlistProductAddAfter implements ObserverInterface { @@ -21,21 +23,27 @@ class WishlistProductAddAfter implements ObserverInterface /** @var InsightsHelper */ protected InsightsHelper $insightsHelper; + /** @var LoggerInterface */ + protected LoggerInterface $logger; + /** * CheckoutCartProductAddAfter constructor. * * @param Data $dataHelper * @param PersonalizationHelper $personalisationHelper * @param InsightsHelper $insightsHelper + * @param LoggerInterface $logger */ public function __construct( Data $dataHelper, PersonalizationHelper $personalisationHelper, - InsightsHelper $insightsHelper + InsightsHelper $insightsHelper, + LoggerInterface $logger ) { $this->dataHelper = $dataHelper; $this->personalisationHelper = $personalisationHelper; $this->insightsHelper = $insightsHelper; + $this->logger = $logger; } /** @@ -62,10 +70,14 @@ public function execute(Observer $observer) $productIds[] = $item->getProductId(); } - $userClient->convertedObjectIDs( - __('Added to Wishlist'), - $this->dataHelper->getIndexName('_products', $firstItem->getStoreId()), - $productIds - ); + try { + $userClient->convertedObjectIDs( + __('Added to Wishlist'), + $this->dataHelper->getIndexName('_products', $firstItem->getStoreId()), + $productIds + ); + } catch (Exception $e) { + $this->logger->critical($e); + } } } From 68847e5f58d70f1ec10183030ee00549c786fec6 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Fri, 7 Oct 2022 15:11:03 +0530 Subject: [PATCH 45/73] MAGE-374 --- view/frontend/web/internals/common.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/view/frontend/web/internals/common.js b/view/frontend/web/internals/common.js index 2408a139e..a3709bb7f 100755 --- a/view/frontend/web/internals/common.js +++ b/view/frontend/web/internals/common.js @@ -375,8 +375,8 @@ requirejs(['algoliaBundle'], function(algoliaBundle) {
${components.Highlight({hit: _data, attribute: 'name'}) || ''}
- ${color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : - _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''} + ${color && color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : + _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''}
@@ -394,8 +394,8 @@ requirejs(['algoliaBundle'], function(algoliaBundle) {
${components.Highlight({hit: _data, attribute: 'name'}) || ''}
- ${color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : - _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''} + ${color && color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : + _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''}
From 18f3eb7543ac1453731aec7982d4e55ea58d1396 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Fri, 7 Oct 2022 20:24:31 +0530 Subject: [PATCH 46/73] MAGE-448 --- view/frontend/requirejs-config.js | 5 +- view/frontend/web/autocomplete.js | 359 +++++++++++++++++- view/frontend/web/internals/common.js | 355 ----------------- .../web/internals/template/categories.js | 9 + view/frontend/web/internals/template/pages.js | 15 + .../web/internals/template/products.js | 49 +++ 6 files changed, 435 insertions(+), 357 deletions(-) create mode 100644 view/frontend/web/internals/template/categories.js create mode 100644 view/frontend/web/internals/template/pages.js create mode 100644 view/frontend/web/internals/template/products.js diff --git a/view/frontend/requirejs-config.js b/view/frontend/requirejs-config.js index 0c3ac208a..14fe9708f 100644 --- a/view/frontend/requirejs-config.js +++ b/view/frontend/requirejs-config.js @@ -4,7 +4,10 @@ var config = { 'algoliaAnalytics': 'Algolia_AlgoliaSearch/internals/search-insights', 'recommend': 'Algolia_AlgoliaSearch/internals/recommend.min', 'recommendJs': 'Algolia_AlgoliaSearch/internals/recommend-js.min', - 'rangeSlider': 'Algolia_AlgoliaSearch/navigation/range-slider-widget' + 'rangeSlider': 'Algolia_AlgoliaSearch/navigation/range-slider-widget', + 'pagesHtml': 'Algolia_AlgoliaSearch/internals/template/pages.js', + 'categoriesHtml': 'Algolia_AlgoliaSearch/internals/template/categories.js', + 'productsHtml': 'Algolia_AlgoliaSearch/internals/template/products.js' }, config: { mixins: { diff --git a/view/frontend/web/autocomplete.js b/view/frontend/web/autocomplete.js index 082ded326..6d585d33d 100755 --- a/view/frontend/web/autocomplete.js +++ b/view/frontend/web/autocomplete.js @@ -51,7 +51,7 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { var sources = [], i = 0; $.each(algoliaConfig.autocomplete.sections, function (name, section) { - var source = getAutocompleteSource(section, algolia_client, $, i); + var source = this.getAutocompleteSource(section, algolia_client, $, i); if (source) { sources.push(source); @@ -202,4 +202,361 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { }); }); }); + + // moving common.js autocomplete code to autocomplete.js + + window.transformAutocompleteHit = function (hit, price_key, helper) { + if (Array.isArray(hit.categories)) + hit.categories = hit.categories.join(', '); + + if (hit._highlightResult.categories_without_path && Array.isArray(hit.categories_without_path)) { + hit.categories_without_path = $.map(hit._highlightResult.categories_without_path, function (category) { + return category.value; + }); + + hit.categories_without_path = hit.categories_without_path.join(', '); + } + + var matchedColors = []; + + if (helper && algoliaConfig.useAdaptiveImage === true) { + if (hit.images_data && helper.state.facetsRefinements.color) { + matchedColors = helper.state.disjunctiveFacetsRefinements.color.slice(0); // slice to clone + } + + if (hit.images_data && helper.state.disjunctiveFacetsRefinements.color) { + matchedColors = helper.state.disjunctiveFacetsRefinements.color.slice(0); // slice to clone + } + } + + if (Array.isArray(hit.color)) { + var colors = []; + + $.each(hit._highlightResult.color, function (i, color) { + if (color.matchLevel === undefined || color.matchLevel === 'none') { + return; + } + + colors.push(color.value); + + if (algoliaConfig.useAdaptiveImage === true) { + var matchedColor = color.matchedWords.join(' '); + if (hit.images_data && color.fullyHighlighted && color.fullyHighlighted === true) { + matchedColors.push(matchedColor); + } + } + }); + + colors = colors.join(', '); + hit._highlightResult.color = { value: colors }; + } + else { + if (hit._highlightResult.color && hit._highlightResult.color.matchLevel === 'none') { + hit._highlightResult.color = { value: '' }; + } + } + + if (algoliaConfig.useAdaptiveImage === true) { + $.each(matchedColors, function (i, color) { + color = color.toLowerCase(); + + if (hit.images_data[color]) { + hit.image_url = hit.images_data[color]; + hit.thumbnail_url = hit.images_data[color]; + + return false; + } + }); + } + + if (hit._highlightResult.color && hit._highlightResult.color.value && hit.categories_without_path) { + if (hit.categories_without_path.indexOf('') === -1 && hit._highlightResult.color.value.indexOf('') !== -1) { + hit.categories_without_path = ''; + } + } + + if (Array.isArray(hit._highlightResult.name)) + hit._highlightResult.name = hit._highlightResult.name[0]; + + if (Array.isArray(hit.price)) + hit.price = hit.price[0]; + + if (hit['price'] !== undefined && price_key !== '.' + algoliaConfig.currencyCode + '.default' && hit['price'][algoliaConfig.currencyCode][price_key.substr(1) + '_formated'] !== hit['price'][algoliaConfig.currencyCode]['default_formated']) { + hit['price'][algoliaConfig.currencyCode][price_key.substr(1) + '_original_formated'] = hit['price'][algoliaConfig.currencyCode]['default_formated']; + } + + if (hit['price'][algoliaConfig.currencyCode]['default_original_formated'] + && hit['price'][algoliaConfig.currencyCode]['special_to_date']) { + var priceExpiration = hit['price'][algoliaConfig.currencyCode]['special_to_date']; + + if (algoliaConfig.now > priceExpiration + 1) { + hit['price'][algoliaConfig.currencyCode]['default_formated'] = hit['price'][algoliaConfig.currencyCode]['default_original_formated']; + hit['price'][algoliaConfig.currencyCode]['default_original_formated'] = false; + } + } + + // Add to cart parameters + var action = algoliaConfig.instant.addToCartParams.action + 'product/' + hit.objectID + '/'; + + var correctFKey = getCookie('form_key'); + + if(correctFKey != "" && algoliaConfig.instant.addToCartParams.formKey != correctFKey) { + algoliaConfig.instant.addToCartParams.formKey = correctFKey; + } + + hit.addToCart = { + 'action': action, + 'uenc': AlgoliaBase64.mageEncode(action), + 'formKey': algoliaConfig.instant.addToCartParams.formKey + }; + + if (hit.__autocomplete_queryID) { + + hit.urlForInsights = hit.url; + + if (algoliaConfig.ccAnalytics.enabled + && algoliaConfig.ccAnalytics.conversionAnalyticsMode !== 'disabled') { + var insightsDataUrlString = $.param({ + queryID: hit.__autocomplete_queryID, + objectID: hit.objectID, + indexName: hit.__autocomplete_indexName + }); + if (hit.url.indexOf('?') > -1) { + hit.urlForInsights += insightsDataUrlString + } else { + hit.urlForInsights += '?' + insightsDataUrlString; + } + } + } + + return hit; + }; + + window.getAutocompleteSource = function (section, algolia_client, $, i) { + if (section.hitsPerPage <= 0) + return null; + + var options = { + hitsPerPage: section.hitsPerPage, + analyticsTags: 'autocomplete', + clickAnalytics: true + }; + + var source; + + if (section.name === "products") { + options.facets = ['categories.level0']; + options.numericFilters = 'visibility_search=1'; + options.ruleContexts = ['magento_filters', '']; // Empty context to keep BC for already create rules in dashboard + + options = algolia.triggerHooks('beforeAutocompleteProductSourceOptions', options); + + source = { + name: section.name, + hitsPerPage: section.hitsPerPage, + paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), + templates: { + noResults() { + return 'No results.'; + }, + item({ item, components, html }) { + if(suggestionSection){ + algoliaAutocomplete.$('.aa-Panel').addClass('productColumn2'); + algoliaAutocomplete.$('.aa-Panel').removeClass('productColumn1'); + }else{ + algoliaAutocomplete.$('.aa-Panel').removeClass('productColumn2'); + algoliaAutocomplete.$('.aa-Panel').addClass('productColumn1'); + } + if(algoliaFooter && algoliaFooter !== undefined && algoliaFooter !== null && algoliaAutocomplete.$('#algoliaFooter').length === 0){ + algoliaAutocomplete.$('.aa-PanelLayout').append(algoliaFooter); + } + var _data = transformAutocompleteHit(item, algoliaConfig.priceKey); + var color = ''; + if (_data._highlightResult.color !== undefined) + { + color = _data._highlightResult.color.value; + } + var origFormatedVar = algoliaConfig.origFormatedVar; + var tierFormatedvar = algoliaConfig.tierFormatedVar; + if (algoliaConfig.priceGroup == null) { + return html` +
${_data.name || ''}
+
+ ${components.Highlight({hit: _data, attribute: 'name'}) || ''} +
+ ${color && color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : + _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''} +
+
+ + ${_data['price'][algoliaConfig.currencyCode]['default_formated']} + + + ${_data['price'][algoliaConfig.currencyCode]['default_original_formated'] != null ? + html `${_data['price'][algoliaConfig.currencyCode]['default_original_formated']}` : ''} +
+
+
`; + } else { + return html` +
${_data.name || ''}
+
+ ${components.Highlight({hit: _data, attribute: 'name'}) || ''} +
+ ${color && color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : + _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''} +
+
+ + ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_formated']} + + + ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_original_formated'] != null ? + html `${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_original_formated']}` : ''} + + ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_tier_formated'] != null ? + html ` As low as ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_tier_formated']}` : '' } +
+
+
`; + } + }, + footer({html}) { + var keys = []; + for (var i = 0; i 0) { + orsTab = []; + for (var i = 0; i < keys.length && i < 2; i++) { + orsTab.push( + { + url:keys[i].url, + name:keys[i].key + } + ); + } + } + + var allUrl = algoliaConfig.baseUrl + '/catalogsearch/result/?q=' + encodeURIComponent(productResult[0].query); + if(orsTab && orsTab.length > 0 && algoliaConfig.instant.enabled) { + return html ``; + }else{ + return html ``; + } + } + } + }; + } + else if (section.name === "categories") + { + if (section.name === "categories" && algoliaConfig.showCatsNotIncludedInNavigation === false) { + options.numericFilters = 'include_in_menu=1'; + } + source = { + name: section.name || i, + hitsPerPage: section.hitsPerPage, + paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), + templates: { + noResults() { + return 'No results.'; + }, + header() { + return section.name; + }, + item({ item, components, html }) { + return html`${components.Highlight({ hit: item, attribute: 'path' })} (${item.product_count})
` + } + } + }; + } + else if (section.name === "pages") + { + source = { + name: section.name || i, + hitsPerPage: section.hitsPerPage, + paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), + templates: { + noResults() { + return 'No results.'; + }, + header() { + return section.name; + }, + item({ item, components, html }) { + return html` +
+ ${components.Highlight({ hit: item, attribute: 'name' })} +
+ ${item.content} +
+
+
+
`; + } + } + }; + } + else if (section.name === "suggestions") + { + var suggestions_index = algolia_client.initIndex(algoliaConfig.indexName + "_suggestions"); + var products_index = algolia_client.initIndex(algoliaConfig.indexName + "_products"); + + source = { + displayKey: 'query', + name: section.name, + hitsPerPage: section.hitsPerPage, + paramName: suggestions_index, + templates: { + item({ item, html }) { + return html`
Suggestion List
`; + } + } + }; + } else { + /** If is not products, categories, pages or suggestions, it's additional section **/ + var index = algolia_client.initIndex(algoliaConfig.indexName + "_section_" + section.name); + + source = { + paramName: algolia_client.initIndex(algoliaConfig.indexName + "_section_" + section.name), + displayKey: 'value', + name: section.name || i, + hitsPerPage: section.hitsPerPage, + templates: { + noResults() { + return 'No results.'; + }, + header() { + return section.name; + }, + item({ item, components, html }) { + return html`${components.Highlight({ hit: item, attribute: 'value' })}`; + } + } + }; + } + + return source; + }; }); diff --git a/view/frontend/web/internals/common.js b/view/frontend/web/internals/common.js index a3709bb7f..542f646f1 100755 --- a/view/frontend/web/internals/common.js +++ b/view/frontend/web/internals/common.js @@ -196,361 +196,6 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { return hit; }; - window.transformAutocompleteHit = function (hit, price_key, helper) { - if (Array.isArray(hit.categories)) - hit.categories = hit.categories.join(', '); - - if (hit._highlightResult.categories_without_path && Array.isArray(hit.categories_without_path)) { - hit.categories_without_path = $.map(hit._highlightResult.categories_without_path, function (category) { - return category.value; - }); - - hit.categories_without_path = hit.categories_without_path.join(', '); - } - - var matchedColors = []; - - if (helper && algoliaConfig.useAdaptiveImage === true) { - if (hit.images_data && helper.state.facetsRefinements.color) { - matchedColors = helper.state.disjunctiveFacetsRefinements.color.slice(0); // slice to clone - } - - if (hit.images_data && helper.state.disjunctiveFacetsRefinements.color) { - matchedColors = helper.state.disjunctiveFacetsRefinements.color.slice(0); // slice to clone - } - } - - if (Array.isArray(hit.color)) { - var colors = []; - - $.each(hit._highlightResult.color, function (i, color) { - if (color.matchLevel === undefined || color.matchLevel === 'none') { - return; - } - - colors.push(color.value); - - if (algoliaConfig.useAdaptiveImage === true) { - var matchedColor = color.matchedWords.join(' '); - if (hit.images_data && color.fullyHighlighted && color.fullyHighlighted === true) { - matchedColors.push(matchedColor); - } - } - }); - - colors = colors.join(', '); - hit._highlightResult.color = { value: colors }; - } - else { - if (hit._highlightResult.color && hit._highlightResult.color.matchLevel === 'none') { - hit._highlightResult.color = { value: '' }; - } - } - - if (algoliaConfig.useAdaptiveImage === true) { - $.each(matchedColors, function (i, color) { - color = color.toLowerCase(); - - if (hit.images_data[color]) { - hit.image_url = hit.images_data[color]; - hit.thumbnail_url = hit.images_data[color]; - - return false; - } - }); - } - - if (hit._highlightResult.color && hit._highlightResult.color.value && hit.categories_without_path) { - if (hit.categories_without_path.indexOf('') === -1 && hit._highlightResult.color.value.indexOf('') !== -1) { - hit.categories_without_path = ''; - } - } - - if (Array.isArray(hit._highlightResult.name)) - hit._highlightResult.name = hit._highlightResult.name[0]; - - if (Array.isArray(hit.price)) - hit.price = hit.price[0]; - - if (hit['price'] !== undefined && price_key !== '.' + algoliaConfig.currencyCode + '.default' && hit['price'][algoliaConfig.currencyCode][price_key.substr(1) + '_formated'] !== hit['price'][algoliaConfig.currencyCode]['default_formated']) { - hit['price'][algoliaConfig.currencyCode][price_key.substr(1) + '_original_formated'] = hit['price'][algoliaConfig.currencyCode]['default_formated']; - } - - if (hit['price'][algoliaConfig.currencyCode]['default_original_formated'] - && hit['price'][algoliaConfig.currencyCode]['special_to_date']) { - var priceExpiration = hit['price'][algoliaConfig.currencyCode]['special_to_date']; - - if (algoliaConfig.now > priceExpiration + 1) { - hit['price'][algoliaConfig.currencyCode]['default_formated'] = hit['price'][algoliaConfig.currencyCode]['default_original_formated']; - hit['price'][algoliaConfig.currencyCode]['default_original_formated'] = false; - } - } - - // Add to cart parameters - var action = algoliaConfig.instant.addToCartParams.action + 'product/' + hit.objectID + '/'; - - var correctFKey = getCookie('form_key'); - - if(correctFKey != "" && algoliaConfig.instant.addToCartParams.formKey != correctFKey) { - algoliaConfig.instant.addToCartParams.formKey = correctFKey; - } - - hit.addToCart = { - 'action': action, - 'uenc': AlgoliaBase64.mageEncode(action), - 'formKey': algoliaConfig.instant.addToCartParams.formKey - }; - - if (hit.__autocomplete_queryID) { - - hit.urlForInsights = hit.url; - - if (algoliaConfig.ccAnalytics.enabled - && algoliaConfig.ccAnalytics.conversionAnalyticsMode !== 'disabled') { - var insightsDataUrlString = $.param({ - queryID: hit.__autocomplete_queryID, - objectID: hit.objectID, - indexName: hit.__autocomplete_indexName - }); - if (hit.url.indexOf('?') > -1) { - hit.urlForInsights += insightsDataUrlString - } else { - hit.urlForInsights += '?' + insightsDataUrlString; - } - } - } - - return hit; - }; - - window.getAutocompleteSource = function (section, algolia_client, $, i) { - if (section.hitsPerPage <= 0) - return null; - - var options = { - hitsPerPage: section.hitsPerPage, - analyticsTags: 'autocomplete', - clickAnalytics: true - }; - - var source; - - if (section.name === "products") { - options.facets = ['categories.level0']; - options.numericFilters = 'visibility_search=1'; - options.ruleContexts = ['magento_filters', '']; // Empty context to keep BC for already create rules in dashboard - - options = algolia.triggerHooks('beforeAutocompleteProductSourceOptions', options); - - source = { - name: section.name, - hitsPerPage: section.hitsPerPage, - paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), - templates: { - noResults() { - return 'No results.'; - }, - item({ item, components, html }) { - if(suggestionSection){ - algoliaAutocomplete.$('.aa-Panel').addClass('productColumn2'); - algoliaAutocomplete.$('.aa-Panel').removeClass('productColumn1'); - }else{ - algoliaAutocomplete.$('.aa-Panel').removeClass('productColumn2'); - algoliaAutocomplete.$('.aa-Panel').addClass('productColumn1'); - } - if(algoliaFooter && algoliaFooter !== undefined && algoliaFooter !== null && algoliaAutocomplete.$('#algoliaFooter').length === 0){ - algoliaAutocomplete.$('.aa-PanelLayout').append(algoliaFooter); - } - var _data = transformAutocompleteHit(item, algoliaConfig.priceKey); - var color = ''; - if (_data._highlightResult.color !== undefined) - { - color = _data._highlightResult.color.value; - } - var origFormatedVar = algoliaConfig.origFormatedVar; - var tierFormatedvar = algoliaConfig.tierFormatedVar; - if (algoliaConfig.priceGroup == null) { - return html` -
${_data.name || ''}
-
- ${components.Highlight({hit: _data, attribute: 'name'}) || ''} -
- ${color && color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : - _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''} -
-
- - ${_data['price'][algoliaConfig.currencyCode]['default_formated']} - - - ${_data['price'][algoliaConfig.currencyCode]['default_original_formated'] != null ? - html `${_data['price'][algoliaConfig.currencyCode]['default_original_formated']}` : ''} -
-
-
`; - } else { - return html` -
${_data.name || ''}
-
- ${components.Highlight({hit: _data, attribute: 'name'}) || ''} -
- ${color && color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : - _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''} -
-
- - ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_formated']} - - - ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_original_formated'] != null ? - html `${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_original_formated']}` : ''} - - ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_tier_formated'] != null ? - html ` As low as ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_tier_formated']}` : '' } -
-
-
`; - } - }, - footer({html}) { - var keys = []; - for (var i = 0; i 0) { - orsTab = []; - for (var i = 0; i < keys.length && i < 2; i++) { - orsTab.push( - { - url:keys[i].url, - name:keys[i].key - } - ); - } - } - - var allUrl = algoliaConfig.baseUrl + '/catalogsearch/result/?q=' + encodeURIComponent(productResult[0].query); - if(orsTab && orsTab.length > 0 && algoliaConfig.instant.enabled) { - return html ``; - }else{ - return html ``; - } - } - } - }; - } - else if (section.name === "categories") - { - if (section.name === "categories" && algoliaConfig.showCatsNotIncludedInNavigation === false) { - options.numericFilters = 'include_in_menu=1'; - } - source = { - name: section.name || i, - hitsPerPage: section.hitsPerPage, - paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), - templates: { - noResults() { - return 'No results.'; - }, - header() { - return section.name; - }, - item({ item, components, html }) { - return html`${components.Highlight({ hit: item, attribute: 'path' })} (${item.product_count})` - } - } - }; - } - else if (section.name === "pages") - { - source = { - name: section.name || i, - hitsPerPage: section.hitsPerPage, - paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), - templates: { - noResults() { - return 'No results.'; - }, - header() { - return section.name; - }, - item({ item, components, html }) { - return html` -
- ${components.Highlight({ hit: item, attribute: 'name' })} -
- ${item.content} -
-
-
-
`; - } - } - }; - } - else if (section.name === "suggestions") - { - var suggestions_index = algolia_client.initIndex(algoliaConfig.indexName + "_suggestions"); - var products_index = algolia_client.initIndex(algoliaConfig.indexName + "_products"); - - source = { - displayKey: 'query', - name: section.name, - hitsPerPage: section.hitsPerPage, - paramName: suggestions_index, - templates: { - item({ item, html }) { - return html`
Suggestion List
`; - } - } - }; - } else { - /** If is not products, categories, pages or suggestions, it's additional section **/ - var index = algolia_client.initIndex(algoliaConfig.indexName + "_section_" + section.name); - - source = { - paramName: algolia_client.initIndex(algoliaConfig.indexName + "_section_" + section.name), - displayKey: 'value', - name: section.name || i, - hitsPerPage: section.hitsPerPage, - templates: { - noResults() { - return 'No results.'; - }, - header() { - return section.name; - }, - item({ item, components, html }) { - return html`${components.Highlight({ hit: item, attribute: 'value' })}`; - } - } - }; - } - - return source; - }; - window.fixAutocompleteCssHeight = function () { if ($(document).width() > 768) { $(".other-sections").css('min-height', '0'); diff --git a/view/frontend/web/internals/template/categories.js b/view/frontend/web/internals/template/categories.js new file mode 100644 index 000000000..77efe767c --- /dev/null +++ b/view/frontend/web/internals/template/categories.js @@ -0,0 +1,9 @@ +define([], function () { + return { + getCategoriesHtml: function (item, components, html) { + return html ` + ${components.Highlight({ hit: item, attribute: 'path' })} (${item.product_count}) + `; + } + }; +}); diff --git a/view/frontend/web/internals/template/pages.js b/view/frontend/web/internals/template/pages.js new file mode 100644 index 000000000..02516c4db --- /dev/null +++ b/view/frontend/web/internals/template/pages.js @@ -0,0 +1,15 @@ +define([], function () { + return { + getPagesHtml: function (item, components, html) { + return html` +
+ ${components.Highlight({hit: item, attribute: 'name'})} +
+ ${components.Highlight({hit: item, attribute: 'content'})} +
+
+
+
`; + } + }; +}); diff --git a/view/frontend/web/internals/template/products.js b/view/frontend/web/internals/template/products.js new file mode 100644 index 000000000..e1bd70a9b --- /dev/null +++ b/view/frontend/web/internals/template/products.js @@ -0,0 +1,49 @@ +define([], function () { + return { + getProductsHtml: function (_data, components, html) { + if (_data._highlightResult.color !== undefined) { + color = _data._highlightResult.color.value; + } + if (algoliaConfig.priceGroup == null) { + return html` +
${_data.name || ''}
+
+ ${components.Highlight({hit: _data, attribute: 'name'}) || ''} +
+ ${color && color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : + _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''} +
+
+ + ${_data['price'][algoliaConfig.currencyCode]['default_formated']} + + ${_data['price'][algoliaConfig.currencyCode]['default_original_formated'] != null ? html` + ${_data['price'][algoliaConfig.currencyCode]['default_original_formated']}` : ''} +
+
+
`; + } else { + return html` +
${_data.name || ''}
+
+ ${components.Highlight({hit: _data, attribute: 'name'}) || ''} +
+ ${color && color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : + _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''} +
+
+ + ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup + '_formated']} + + ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup + '_original_formated'] != null ? html` + ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup + '_original_formated']}` : ''} + + ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup + '_tier_formated'] != null ? html` + As low as ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup + '_tier_formated']}` : ''} +
+
+
`; + } + } + }; +}); From d2cd9913559b7bb3e6344ae458397f10cc64c8bb Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Mon, 10 Oct 2022 21:33:04 +0530 Subject: [PATCH 47/73] MAGE-448 --- view/frontend/requirejs-config.js | 8 +- view/frontend/web/autocomplete.js | 104 +++--------------- .../internals/template/additional-section.js | 7 ++ .../web/internals/template/products.js | 3 + .../web/internals/template/suggestions.js | 9 ++ 5 files changed, 39 insertions(+), 92 deletions(-) create mode 100644 view/frontend/web/internals/template/additional-section.js create mode 100644 view/frontend/web/internals/template/suggestions.js diff --git a/view/frontend/requirejs-config.js b/view/frontend/requirejs-config.js index 14fe9708f..c328cba23 100644 --- a/view/frontend/requirejs-config.js +++ b/view/frontend/requirejs-config.js @@ -5,9 +5,11 @@ var config = { 'recommend': 'Algolia_AlgoliaSearch/internals/recommend.min', 'recommendJs': 'Algolia_AlgoliaSearch/internals/recommend-js.min', 'rangeSlider': 'Algolia_AlgoliaSearch/navigation/range-slider-widget', - 'pagesHtml': 'Algolia_AlgoliaSearch/internals/template/pages.js', - 'categoriesHtml': 'Algolia_AlgoliaSearch/internals/template/categories.js', - 'productsHtml': 'Algolia_AlgoliaSearch/internals/template/products.js' + 'pagesHtml': 'Algolia_AlgoliaSearch/internals/template/pages', + 'categoriesHtml': 'Algolia_AlgoliaSearch/internals/template/categories', + 'productsHtml': 'Algolia_AlgoliaSearch/internals/template/products', + 'suggestionsHtml': 'Algolia_AlgoliaSearch/internals/template/suggestions', + 'additionalHtml': 'Algolia_AlgoliaSearch/internals/template/additional-section' }, config: { mixins: { diff --git a/view/frontend/web/autocomplete.js b/view/frontend/web/autocomplete.js index 6d585d33d..08752488a 100755 --- a/view/frontend/web/autocomplete.js +++ b/view/frontend/web/autocomplete.js @@ -2,7 +2,7 @@ let algoliaAutocomplete; let suggestionSection = false; let algoliaFooter; let productResult = []; -requirejs(['algoliaBundle'], function(algoliaBundle) { +requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'suggestionsHtml', 'additionalHtml'], function(algoliaBundle, pagesHtml, categoriesHtml, productsHtml, suggestionsHtml, additionalHtml) { algoliaAutocomplete = algoliaBundle; algoliaBundle.$(function ($) { @@ -11,19 +11,6 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { return; } - /** - * Set autocomplete templates - * For templating is used Hogan library - * Docs: http://twitter.github.io/hogan.js/ - **/ - algoliaConfig.autocomplete.templates = { - suggestions: algoliaBundle.Hogan.compile($('#autocomplete_suggestions_template').html()), - products: algoliaBundle.Hogan.compile($('#autocomplete_products_template').html()), - categories: algoliaBundle.Hogan.compile($('#autocomplete_categories_template').html()), - pages: algoliaBundle.Hogan.compile($('#autocomplete_pages_template').html()), - additionalSection: algoliaBundle.Hogan.compile($('#autocomplete_extra_template').html()) - }; - /** * Initialise Algolia client * Docs: https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/ @@ -51,7 +38,7 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { var sources = [], i = 0; $.each(algoliaConfig.autocomplete.sections, function (name, section) { - var source = this.getAutocompleteSource(section, algolia_client, $, i); + var source = getAutocompleteSource(section, algolia_client, $, i); if (source) { sources.push(source); @@ -126,9 +113,7 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { }, item(params) { const { item, html } = params; - return html` - ${item.query} - `; + return suggestionsHtml.getSuggestionsHtml(item, html) }, }, }; @@ -158,7 +143,7 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { transformResponse({ results, hits }) { productResult = results; return hits; - }, + }, }); }, templates: data.templates, @@ -191,21 +176,20 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { placeholder: 'Search for products, categories, ...', detachedMediaQuery: 'none', plugins: [querySuggestionsPlugin], - onSubmit(data){ - if(data.state.query && data.state.query !== null && data.state.query !== ""){ - window.location.href = `/catalogsearch/result/?q=${data.state.query}`; - } - }, + onSubmit(data){ + if(data.state.query && data.state.query !== null && data.state.query !== ""){ + window.location.href = `/catalogsearch/result/?q=${data.state.query}`; + } + }, getSources({query, setContext}) { return autocompleteConfig; }, }); }); }); - // moving common.js autocomplete code to autocomplete.js - window.transformAutocompleteHit = function (hit, price_key, helper) { + window.transformAutocompleteHit = function (hit, price_key, $, helper) { if (Array.isArray(hit.categories)) hit.categories = hit.categories.join(', '); @@ -370,56 +354,8 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { if(algoliaFooter && algoliaFooter !== undefined && algoliaFooter !== null && algoliaAutocomplete.$('#algoliaFooter').length === 0){ algoliaAutocomplete.$('.aa-PanelLayout').append(algoliaFooter); } - var _data = transformAutocompleteHit(item, algoliaConfig.priceKey); - var color = ''; - if (_data._highlightResult.color !== undefined) - { - color = _data._highlightResult.color.value; - } - var origFormatedVar = algoliaConfig.origFormatedVar; - var tierFormatedvar = algoliaConfig.tierFormatedVar; - if (algoliaConfig.priceGroup == null) { - return html` -
${_data.name || ''}
-
- ${components.Highlight({hit: _data, attribute: 'name'}) || ''} -
- ${color && color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : - _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''} -
-
- - ${_data['price'][algoliaConfig.currencyCode]['default_formated']} - - - ${_data['price'][algoliaConfig.currencyCode]['default_original_formated'] != null ? - html `${_data['price'][algoliaConfig.currencyCode]['default_original_formated']}` : ''} -
-
-
`; - } else { - return html` -
${_data.name || ''}
-
- ${components.Highlight({hit: _data, attribute: 'name'}) || ''} -
- ${color && color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : - _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''} -
-
- - ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_formated']} - - - ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_original_formated'] != null ? - html `${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_original_formated']}` : ''} - - ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_tier_formated'] != null ? - html ` As low as ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup+'_tier_formated']}` : '' } -
-
-
`; - } + var _data = transformAutocompleteHit(item, algoliaConfig.priceKey, $); + return productsHtml.getProductsHtml(_data, components, html); }, footer({html}) { var keys = []; @@ -486,7 +422,7 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { return section.name; }, item({ item, components, html }) { - return html`${components.Highlight({ hit: item, attribute: 'path' })} (${item.product_count})` + return categoriesHtml.getCategoriesHtml(item, components, html); } } }; @@ -505,15 +441,7 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { return section.name; }, item({ item, components, html }) { - return html` -
- ${components.Highlight({ hit: item, attribute: 'name' })} -
- ${item.content} -
-
-
-
`; + return pagesHtml.getPagesHtml(item, components, html); } } }; @@ -536,8 +464,6 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { }; } else { /** If is not products, categories, pages or suggestions, it's additional section **/ - var index = algolia_client.initIndex(algoliaConfig.indexName + "_section_" + section.name); - source = { paramName: algolia_client.initIndex(algoliaConfig.indexName + "_section_" + section.name), displayKey: 'value', @@ -551,7 +477,7 @@ requirejs(['algoliaBundle'], function(algoliaBundle) { return section.name; }, item({ item, components, html }) { - return html`${components.Highlight({ hit: item, attribute: 'value' })}`; + return additionalHtml.getAdditionalHtml(item, components, html); } } }; diff --git a/view/frontend/web/internals/template/additional-section.js b/view/frontend/web/internals/template/additional-section.js new file mode 100644 index 000000000..04545b2aa --- /dev/null +++ b/view/frontend/web/internals/template/additional-section.js @@ -0,0 +1,7 @@ +define([], function () { + return { + getAdditionalHtml: function (item, components, html) { + return html`${components.Highlight({ hit: item, attribute: 'value' })}`; + } + }; +}); diff --git a/view/frontend/web/internals/template/products.js b/view/frontend/web/internals/template/products.js index e1bd70a9b..40638af9f 100644 --- a/view/frontend/web/internals/template/products.js +++ b/view/frontend/web/internals/template/products.js @@ -1,9 +1,12 @@ define([], function () { return { getProductsHtml: function (_data, components, html) { + var color = ''; if (_data._highlightResult.color !== undefined) { color = _data._highlightResult.color.value; } + var origFormatedVar = algoliaConfig.origFormatedVar; + var tierFormatedvar = algoliaConfig.tierFormatedVar; if (algoliaConfig.priceGroup == null) { return html`
${_data.name || ''}
diff --git a/view/frontend/web/internals/template/suggestions.js b/view/frontend/web/internals/template/suggestions.js new file mode 100644 index 000000000..68ad8876b --- /dev/null +++ b/view/frontend/web/internals/template/suggestions.js @@ -0,0 +1,9 @@ +define([], function () { + return { + getSuggestionsHtml: function (item, html) { + return html`
+ ${item.query} + `; + } + }; +}); From 68430e77413ad51b81e30b73c7a39549eab581bb Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Tue, 11 Oct 2022 17:46:19 +0530 Subject: [PATCH 48/73] Fixed the issue with add to cart conversion Personalization --- Observer/Insights/CheckoutCartProductAddAfter.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Observer/Insights/CheckoutCartProductAddAfter.php b/Observer/Insights/CheckoutCartProductAddAfter.php index 9b540994e..364244752 100644 --- a/Observer/Insights/CheckoutCartProductAddAfter.php +++ b/Observer/Insights/CheckoutCartProductAddAfter.php @@ -91,7 +91,9 @@ public function execute(Observer $observer) $this->logger->critical($e); } } - } elseif ($this->personalizationHelper->isPersoEnabled($storeId) && $this->personalizationHelper->isCartAddTracked($storeId)) { + } + + if ($this->personalizationHelper->isPersoEnabled($storeId) && $this->personalizationHelper->isCartAddTracked($storeId) && (!$this->configHelper->isClickConversionAnalyticsEnabled($storeId) || $this->configHelper->getConversionAnalyticsMode($storeId) != 'add_to_cart')) { try { $userClient->convertedObjectIDs( __('Added to Cart'), From 19284ef2fbba103c9be0d678da4aa72abd3547c7 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Tue, 11 Oct 2022 20:30:50 +0530 Subject: [PATCH 49/73] MAGE-448 --- view/frontend/web/autocomplete.js | 26 +++++++------------ .../internals/template/additional-section.js | 8 ++++++ .../web/internals/template/categories.js | 12 +++++++-- view/frontend/web/internals/template/pages.js | 8 ++++++ .../web/internals/template/products.js | 20 ++++++++++++++ .../web/internals/template/suggestions.js | 8 ++++++ 6 files changed, 63 insertions(+), 19 deletions(-) diff --git a/view/frontend/web/autocomplete.js b/view/frontend/web/autocomplete.js index 08752488a..b96eb8a01 100755 --- a/view/frontend/web/autocomplete.js +++ b/view/frontend/web/autocomplete.js @@ -175,6 +175,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg container: '#algoliaAutocomplete', placeholder: 'Search for products, categories, ...', detachedMediaQuery: 'none', + debug:algoliaConfig.autocomplete.isDebugEnabled, plugins: [querySuggestionsPlugin], onSubmit(data){ if(data.state.query && data.state.query !== null && data.state.query !== ""){ @@ -341,7 +342,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), templates: { noResults() { - return 'No results.'; + return productsHtml.getNoResultHtml(); }, item({ item, components, html }) { if(suggestionSection){ @@ -391,16 +392,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg } var allUrl = algoliaConfig.baseUrl + '/catalogsearch/result/?q=' + encodeURIComponent(productResult[0].query); - if(orsTab && orsTab.length > 0 && algoliaConfig.instant.enabled) { - return html ``; - }else{ - return html ``; - } + return productsHtml.getFooterHtml(html, orsTab, allUrl, productResult) } } }; @@ -416,10 +408,10 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), templates: { noResults() { - return 'No results.'; + return categoriesHtml.getNoResultHtml(); }, header() { - return section.name; + return categoriesHtml.getHeaderHtml(section); }, item({ item, components, html }) { return categoriesHtml.getCategoriesHtml(item, components, html); @@ -435,10 +427,10 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), templates: { noResults() { - return 'No results.'; + return pagesHtml.getNoResultHtml(); }, header() { - return section.name; + return pagesHtml.getHeaderHtml(section); }, item({ item, components, html }) { return pagesHtml.getPagesHtml(item, components, html); @@ -471,10 +463,10 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg hitsPerPage: section.hitsPerPage, templates: { noResults() { - return 'No results.'; + return additionalHtml.getNoResultHtml(); }, header() { - return section.name; + return additionalHtml.getHeaderHtml(section); }, item({ item, components, html }) { return additionalHtml.getAdditionalHtml(item, components, html); diff --git a/view/frontend/web/internals/template/additional-section.js b/view/frontend/web/internals/template/additional-section.js index 04545b2aa..ed161b942 100644 --- a/view/frontend/web/internals/template/additional-section.js +++ b/view/frontend/web/internals/template/additional-section.js @@ -2,6 +2,14 @@ define([], function () { return { getAdditionalHtml: function (item, components, html) { return html`${components.Highlight({ hit: item, attribute: 'value' })}`; + }, + + getHeaderHtml: function (section) { + return section.name; + }, + + getNoResultHtml: function () { + return 'No Results'; } }; }); diff --git a/view/frontend/web/internals/template/categories.js b/view/frontend/web/internals/template/categories.js index 77efe767c..090beafd1 100644 --- a/view/frontend/web/internals/template/categories.js +++ b/view/frontend/web/internals/template/categories.js @@ -2,8 +2,16 @@ define([], function () { return { getCategoriesHtml: function (item, components, html) { return html ` - ${components.Highlight({ hit: item, attribute: 'path' })} (${item.product_count}) - `; + ${components.Highlight({ hit: item, attribute: 'path' })} (${item.product_count}) + `; + }, + + getHeaderHtml: function (section) { + return section.name; + }, + + getNoResultHtml: function () { + return 'No Results'; } }; }); diff --git a/view/frontend/web/internals/template/pages.js b/view/frontend/web/internals/template/pages.js index 02516c4db..858059a80 100644 --- a/view/frontend/web/internals/template/pages.js +++ b/view/frontend/web/internals/template/pages.js @@ -10,6 +10,14 @@ define([], function () {
`; + }, + + getHeaderHtml: function (section) { + return section.name; + }, + + getNoResultHtml: function () { + return 'No Results'; } }; }); diff --git a/view/frontend/web/internals/template/products.js b/view/frontend/web/internals/template/products.js index 40638af9f..f75fef95c 100644 --- a/view/frontend/web/internals/template/products.js +++ b/view/frontend/web/internals/template/products.js @@ -47,6 +47,26 @@ define([], function () {
`; } + }, + + getHeaderHtml: function (section) { + return section.name; + }, + + getNoResultHtml: function () { + return 'No Results'; + }, + + getFooterHtml: function (html, orsTab, allUrl, productResult) { + if(orsTab && orsTab.length > 0 && algoliaConfig.instant.enabled) { + return html ``; + }else{ + return html ``; + } } }; }); diff --git a/view/frontend/web/internals/template/suggestions.js b/view/frontend/web/internals/template/suggestions.js index 68ad8876b..3b1d86344 100644 --- a/view/frontend/web/internals/template/suggestions.js +++ b/view/frontend/web/internals/template/suggestions.js @@ -4,6 +4,14 @@ define([], function () { return html` ${item.query} `; + }, + + getPagesHeaderHtml: function (section) { + return section.name; + }, + + getNoResultHtml: function () { + return 'No Results'; } }; }); From 97702b1c41f78bb9c0deda53ddd6df360c2f5425 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Wed, 12 Oct 2022 16:30:47 +0530 Subject: [PATCH 50/73] Added Releases notes in the magento dashboard --- Helper/Configuration/AssetHelper.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Helper/Configuration/AssetHelper.php b/Helper/Configuration/AssetHelper.php index 2a1ec35db..24bf60010 100644 --- a/Helper/Configuration/AssetHelper.php +++ b/Helper/Configuration/AssetHelper.php @@ -75,6 +75,11 @@ class AssetHelper extends \Magento\Framework\App\Helper\AbstractHelper 'url' => 'https://www.algolia.com/support/?contact=', 'icon' => 'iconIssues', ], + [ + 'title' => 'Release Notes', + 'url' => 'https://github.com/algolia/algoliasearch-magento-2/releases', + 'icon' => 'iconDocs', + ] ], 'algoliasearch_autocomplete' => [ [ From 1774906ed67cdea35f686154340c0047eae0d879 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Thu, 13 Oct 2022 19:21:12 +0530 Subject: [PATCH 51/73] MAGE-448 --- .../frontend/layout/algolia_search_handle.xml | 4 +- view/frontend/web/autocomplete.js | 108 +++++++++--------- view/frontend/web/insights.js | 5 +- 3 files changed, 60 insertions(+), 57 deletions(-) diff --git a/view/frontend/layout/algolia_search_handle.xml b/view/frontend/layout/algolia_search_handle.xml index 3bdab2932..cb720721b 100755 --- a/view/frontend/layout/algolia_search_handle.xml +++ b/view/frontend/layout/algolia_search_handle.xml @@ -23,12 +23,12 @@ - + diff --git a/view/frontend/web/autocomplete.js b/view/frontend/web/autocomplete.js index b96eb8a01..20447115a 100755 --- a/view/frontend/web/autocomplete.js +++ b/view/frontend/web/autocomplete.js @@ -34,36 +34,26 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg algoliaConfig.autocomplete.sections.unshift({ hitsPerPage: algoliaConfig.autocomplete.nbOfQueriesSuggestions, label: '', name: "suggestions"}); } - /** Setup autocomplete data sources **/ - var sources = [], - i = 0; - $.each(algoliaConfig.autocomplete.sections, function (name, section) { - var source = getAutocompleteSource(section, algolia_client, $, i); - - if (source) { - sources.push(source); - } - - /** Those sections have already specific placeholder, so do not use the default aa-dataset-{i} class **/ - if (section.name !== 'suggestions' && section.name !== 'products') { - i++; - } - }); - /** * Setup the autocomplete search input * For autocomplete feature is used Algolia's autocomplete.js library * Docs: https://github.com/algolia/autocomplete.js **/ $(algoliaConfig.autocomplete.selector).each(function (i) { - var menu = $(this); + let querySuggestionsPlugin = ""; var options = { - hint: false, - templates: { - dropdownMenu: '#menu-template' + container: '#algoliaAutocomplete', + placeholder: 'Search for products, categories, ...', + debug: algoliaConfig.autocomplete.isDebugEnabled, + detachedMediaQuery: 'none', + onSubmit(data){ + if(data.state.query && data.state.query !== null && data.state.query !== ""){ + window.location.href = `/catalogsearch/result/?q=${data.state.query}`; + } + }, + getSources({query, setContext}) { + return autocompleteConfig; }, - dropdownMenuContainer: "#algolia-autocomplete-container", - debug: algoliaConfig.autocomplete.isDebugEnabled }; if (isMobile() === true) { @@ -75,7 +65,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg algoliaFooter = ''; } - sources = algolia.triggerHooks('beforeAutocompleteSources', sources, algolia_client, algoliaBundle); + sources = algolia.triggerHooks('beforeAutocompleteSources', algoliaConfig.autocomplete.sections, algolia_client, algoliaBundle); options = algolia.triggerHooks('beforeAutocompleteOptions', options); // Keep for backward compatibility @@ -90,7 +80,22 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg options = hookResult.shift(); } - let querySuggestionsPlugin = ""; + /** Setup autocomplete data sources **/ + var sources = [], + i = 0; + $.each(algoliaConfig.autocomplete.sections, function (name, section) { + var source = getAutocompleteSource(section, algolia_client, $, i); + + if (source) { + sources.push(source); + } + + /** Those sections have already specific placeholder, so do not use the default aa-dataset-{i} class **/ + if (section.name !== 'suggestions' && section.name !== 'products') { + i++; + } + }); + let autocompleteConfig = []; sources.forEach(function(data){ if(data.name === "suggestions"){ @@ -129,15 +134,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg { indexName: data.paramName.indexName, query, - params: { - hitsPerPage: data.hitsPerPage, - distinct: true, - facets: ['categories.level0'], - numericFilters: 'visibility_search=1', - ruleContexts: ['magento_filters', ''], - analyticsTags: 'autocomplete', - clickAnalytics: true - }, + params: data.options, }, ], transformResponse({ results, hits }) { @@ -158,11 +155,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg { indexName: data.paramName.indexName, query, - params: { - hitsPerPage: data.hitsPerPage, - distinct: true, - numericFilters: data.name === "categories" && algoliaConfig.showCatsNotIncludedInNavigation === false ? 'include_in_menu=1' : '', - }, + params: data.options, }, ], }); @@ -171,20 +164,16 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg }) } }); - algoliaAutocomplete.autocomplete({ - container: '#algoliaAutocomplete', - placeholder: 'Search for products, categories, ...', - detachedMediaQuery: 'none', - debug:algoliaConfig.autocomplete.isDebugEnabled, - plugins: [querySuggestionsPlugin], - onSubmit(data){ - if(data.state.query && data.state.query !== null && data.state.query !== ""){ - window.location.href = `/catalogsearch/result/?q=${data.state.query}`; - } - }, - getSources({query, setContext}) { - return autocompleteConfig; - }, + + options.plugins = [querySuggestionsPlugin]; + algoliaAutocomplete.autocomplete(options); + //Written code for autocomplete insight + jQuery(document).on('click', '.algoliasearch-autocomplete-hit', function(){ + let itemUrl = jQuery(this).attr('href'); + let eventData = algoliaInsights.buildEventData( + 'Clicked', getHitsUrlParameter(itemUrl, 'objectID'), getHitsUrlParameter(itemUrl, 'indexName'), 1, getHitsUrlParameter(itemUrl, 'queryID') + ); + algoliaInsights.trackClick(eventData); }); }); }); @@ -324,7 +313,8 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg var options = { hitsPerPage: section.hitsPerPage, analyticsTags: 'autocomplete', - clickAnalytics: true + clickAnalytics: true, + distinct: true }; var source; @@ -340,6 +330,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg name: section.name, hitsPerPage: section.hitsPerPage, paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), + options:options, templates: { noResults() { return productsHtml.getNoResultHtml(); @@ -406,6 +397,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg name: section.name || i, hitsPerPage: section.hitsPerPage, paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), + options:options, templates: { noResults() { return categoriesHtml.getNoResultHtml(); @@ -425,6 +417,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg name: section.name || i, hitsPerPage: section.hitsPerPage, paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), + options:options, templates: { noResults() { return pagesHtml.getNoResultHtml(); @@ -448,6 +441,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg name: section.name, hitsPerPage: section.hitsPerPage, paramName: suggestions_index, + options:options, templates: { item({ item, html }) { return html`
Suggestion List
`; @@ -461,6 +455,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg displayKey: 'value', name: section.name || i, hitsPerPage: section.hitsPerPage, + options:options, templates: { noResults() { return additionalHtml.getNoResultHtml(); @@ -477,4 +472,11 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg return source; }; + + function getHitsUrlParameter(url, name) { + name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); + var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), + results = regex.exec(url); + return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); + } }); diff --git a/view/frontend/web/insights.js b/view/frontend/web/insights.js index 3eac5d0c7..421339491 100644 --- a/view/frontend/web/insights.js +++ b/view/frontend/web/insights.js @@ -1,3 +1,4 @@ +var algoliaInsights; requirejs([ 'jquery', 'algoliaAnalytics', @@ -6,7 +7,7 @@ requirejs([ algoliaAnalytics = algoliaAnalyticsWrapper.default; - var algoliaInsights = { + algoliaInsights = { config: null, defaultIndexName: null, isTracking: false, @@ -275,4 +276,4 @@ requirejs([ return algoliaInsights; -}); \ No newline at end of file +}); From 6c5a46a79e011231f3f945c23fdeaddb9debf0c0 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Fri, 14 Oct 2022 21:00:59 +0530 Subject: [PATCH 52/73] Fixed Click issue for personalization --- view/frontend/web/insights.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/view/frontend/web/insights.js b/view/frontend/web/insights.js index 61d9a600f..df152a3bf 100644 --- a/view/frontend/web/insights.js +++ b/view/frontend/web/insights.js @@ -109,7 +109,7 @@ requirejs([ }); - if (this.config.ccAnalytics.enabled || this.config.personalization.enabled) { + if (this.config.ccAnalytics.enabled) { $(document).on('click', this.config.ccAnalytics.ISSelector, function() { var $this = $(this); if ($this.data('clicked')) return; From d449dd71ef80fcedfbdd4a096ed2a303799ea7e6 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Fri, 14 Oct 2022 21:38:42 +0530 Subject: [PATCH 53/73] MAGE-448 --- Block/Configuration.php | 2 +- Helper/ConfigHelper.php | 2 +- Model/Observer.php | 26 ++++---- Observer/TopSearchTemplate.php | 36 +++++++++++ etc/frontend/events.xml | 6 +- .../frontend/layout/algolia_search_handle.xml | 8 --- view/frontend/templates/autocomplete.phtml | 10 +-- .../templates/autocomplete/attribute.phtml | 9 --- .../templates/autocomplete/category.phtml | 32 ---------- .../templates/autocomplete/menu.phtml | 17 ------ .../templates/autocomplete/page.phtml | 14 ----- .../templates/autocomplete/product.phtml | 61 ------------------- .../templates/autocomplete/suggestion.phtml | 28 --------- view/frontend/web/autocomplete.js | 4 +- 14 files changed, 64 insertions(+), 191 deletions(-) create mode 100644 Observer/TopSearchTemplate.php delete mode 100644 view/frontend/templates/autocomplete/attribute.phtml delete mode 100644 view/frontend/templates/autocomplete/category.phtml delete mode 100644 view/frontend/templates/autocomplete/menu.phtml delete mode 100644 view/frontend/templates/autocomplete/page.phtml delete mode 100644 view/frontend/templates/autocomplete/product.phtml delete mode 100644 view/frontend/templates/autocomplete/suggestion.phtml diff --git a/Block/Configuration.php b/Block/Configuration.php index c5f41b524..9e71f0f79 100755 --- a/Block/Configuration.php +++ b/Block/Configuration.php @@ -151,7 +151,7 @@ public function getConfiguration() ], 'autocomplete' => [ 'enabled' => $config->isAutoCompleteEnabled(), - 'selector' => $config->getAutocompleteSelector(), + 'selector' => '.algolia-search-input', 'sections' => $config->getAutocompleteSections(), 'nbOfProductsSuggestions' => $config->getNumberOfProductsSuggestions(), 'nbOfCategoriesSuggestions' => $config->getNumberOfCategoriesSuggestions(), diff --git a/Helper/ConfigHelper.php b/Helper/ConfigHelper.php index 58e8871db..193603749 100755 --- a/Helper/ConfigHelper.php +++ b/Helper/ConfigHelper.php @@ -194,7 +194,7 @@ public function getExtensionVersion() public function isDefaultSelector($storeId = null) { - return '.algolia-search-input' === $this->getAutocompleteSelector($storeId); + return 'top.search' === $this->getAutocompleteSelector($storeId); } public function getAutocompleteSelector($storeId = null) diff --git a/Model/Observer.php b/Model/Observer.php index ec1c9bff5..c70ce9078 100755 --- a/Model/Observer.php +++ b/Model/Observer.php @@ -14,12 +14,19 @@ */ class Observer implements ObserverInterface { - private $config; - private $registry; - private $storeManager; - private $pageConfig; - private $request; + protected $config; + protected $registry; + protected $storeManager; + protected $pageConfig; + protected $request; + /** + * @param ConfigHelper $configHelper + * @param Registry $registry + * @param StoreManagerInterface $storeManager + * @param PageConfig $pageConfig + * @param \Magento\Framework\App\Request\Http $http + */ public function __construct( ConfigHelper $configHelper, Registry $registry, @@ -44,15 +51,8 @@ public function execute(\Magento\Framework\Event\Observer $observer) if ($this->config->getApplicationID() && $this->config->getAPIKey()) { if ($this->config->isAutoCompleteEnabled() || $this->config->isInstantEnabled()) { /** @var Layout $layout */ - $layout = $observer->getData('layout'); + $layout = $observer->getData('layout'); $layout->getUpdate()->addHandle('algolia_search_handle'); - - if ($this->config->isDefaultSelector()) { - $layout->getUpdate()->addHandle('algolia_search_handle_with_topsearch'); - } else { - $layout->getUpdate()->addHandle('algolia_search_handle_no_topsearch'); - } - $this->loadPreventBackendRenderingHandle($layout); } } diff --git a/Observer/TopSearchTemplate.php b/Observer/TopSearchTemplate.php new file mode 100644 index 000000000..ff2584b4d --- /dev/null +++ b/Observer/TopSearchTemplate.php @@ -0,0 +1,36 @@ +config = $configHelper; + } + + /** + * @param Observer $observer + * @return void + */ + public function execute(Observer $observer) + { + /** @var Layout $layout */ + $layout = $observer->getData('layout'); + $block = $layout->getBlock($this->config->getAutocompleteSelector()); + if ($block) { + $block->setTemplate('Algolia_AlgoliaSearch::autocomplete.phtml'); + } + } +} diff --git a/etc/frontend/events.xml b/etc/frontend/events.xml index 0b14a3beb..bf8e3740c 100755 --- a/etc/frontend/events.xml +++ b/etc/frontend/events.xml @@ -24,4 +24,8 @@ - \ No newline at end of file + + + + + diff --git a/view/frontend/layout/algolia_search_handle.xml b/view/frontend/layout/algolia_search_handle.xml index cb720721b..1db0ab316 100755 --- a/view/frontend/layout/algolia_search_handle.xml +++ b/view/frontend/layout/algolia_search_handle.xml @@ -22,14 +22,6 @@
- - - diff --git a/view/frontend/templates/autocomplete.phtml b/view/frontend/templates/autocomplete.phtml index 104961653..ce69bdc04 100755 --- a/view/frontend/templates/autocomplete.phtml +++ b/view/frontend/templates/autocomplete.phtml @@ -3,13 +3,13 @@ * @var \Algolia\AlgoliaSearch\Block\Algolia $block */ -$config = $block->getConfigHelper(); - -$catalogSearchHelper = $block->getCatalogSearchHelper(); +$blockInstance= $block->getLayout()->createBlock('Algolia\AlgoliaSearch\Block\Algolia'); +$config = $blockInstance->getConfigHelper(); +$catalogSearchHelper = $blockInstance->getCatalogSearchHelper(); $placeholder = __('Search for products, categories, ...'); // Render form with autocomplete input -if ($config->isDefaultSelector()) : ?> +//if ($config->isDefaultSelector()) : ?> - + diff --git a/view/frontend/templates/autocomplete/attribute.phtml b/view/frontend/templates/autocomplete/attribute.phtml deleted file mode 100644 index ecaae82c1..000000000 --- a/view/frontend/templates/autocomplete/attribute.phtml +++ /dev/null @@ -1,9 +0,0 @@ - - \ No newline at end of file diff --git a/view/frontend/templates/autocomplete/category.phtml b/view/frontend/templates/autocomplete/category.phtml deleted file mode 100644 index 79c009e98..000000000 --- a/view/frontend/templates/autocomplete/category.phtml +++ /dev/null @@ -1,32 +0,0 @@ - - diff --git a/view/frontend/templates/autocomplete/menu.phtml b/view/frontend/templates/autocomplete/menu.phtml deleted file mode 100644 index 9ffb24012..000000000 --- a/view/frontend/templates/autocomplete/menu.phtml +++ /dev/null @@ -1,17 +0,0 @@ - - - \ No newline at end of file diff --git a/view/frontend/templates/autocomplete/page.phtml b/view/frontend/templates/autocomplete/page.phtml deleted file mode 100644 index 53909b668..000000000 --- a/view/frontend/templates/autocomplete/page.phtml +++ /dev/null @@ -1,14 +0,0 @@ - - \ No newline at end of file diff --git a/view/frontend/templates/autocomplete/product.phtml b/view/frontend/templates/autocomplete/product.phtml deleted file mode 100644 index aa9250fae..000000000 --- a/view/frontend/templates/autocomplete/product.phtml +++ /dev/null @@ -1,61 +0,0 @@ -getPriceKey(); - -$origFormatedVar = 'price' . $priceKey . '_original_formated'; -$tierFormatedVar = 'price' . $priceKey . '_tier_formated' - -?> - - - diff --git a/view/frontend/templates/autocomplete/suggestion.phtml b/view/frontend/templates/autocomplete/suggestion.phtml deleted file mode 100644 index 0f235cbad..000000000 --- a/view/frontend/templates/autocomplete/suggestion.phtml +++ /dev/null @@ -1,28 +0,0 @@ - - - - \ No newline at end of file diff --git a/view/frontend/web/autocomplete.js b/view/frontend/web/autocomplete.js index 20447115a..1ee85700d 100755 --- a/view/frontend/web/autocomplete.js +++ b/view/frontend/web/autocomplete.js @@ -166,7 +166,9 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg }); options.plugins = [querySuggestionsPlugin]; - algoliaAutocomplete.autocomplete(options); + /** Bind autocomplete feature to the input */ + var algoliaAutocompleteInstance = algoliaAutocomplete.autocomplete(options); + algoliaAutocompleteInstance = algolia.triggerHooks('afterAutocompleteStart', algoliaAutocompleteInstance); //Written code for autocomplete insight jQuery(document).on('click', '.algoliasearch-autocomplete-hit', function(){ let itemUrl = jQuery(this).attr('href'); From 796179784eaf9fcf9f45c80da9408cbfe28153e0 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Mon, 17 Oct 2022 11:02:42 +0530 Subject: [PATCH 54/73] MAGE-448 --- Block/Configuration.php | 2 +- Helper/ConfigHelper.php | 2 +- Model/Observer.php | 6 ++++ Observer/TopSearchTemplate.php | 36 ---------------------- etc/frontend/events.xml | 4 --- view/frontend/templates/autocomplete.phtml | 10 +++--- 6 files changed, 13 insertions(+), 47 deletions(-) delete mode 100644 Observer/TopSearchTemplate.php diff --git a/Block/Configuration.php b/Block/Configuration.php index 9e71f0f79..c5f41b524 100755 --- a/Block/Configuration.php +++ b/Block/Configuration.php @@ -151,7 +151,7 @@ public function getConfiguration() ], 'autocomplete' => [ 'enabled' => $config->isAutoCompleteEnabled(), - 'selector' => '.algolia-search-input', + 'selector' => $config->getAutocompleteSelector(), 'sections' => $config->getAutocompleteSections(), 'nbOfProductsSuggestions' => $config->getNumberOfProductsSuggestions(), 'nbOfCategoriesSuggestions' => $config->getNumberOfCategoriesSuggestions(), diff --git a/Helper/ConfigHelper.php b/Helper/ConfigHelper.php index 193603749..58e8871db 100755 --- a/Helper/ConfigHelper.php +++ b/Helper/ConfigHelper.php @@ -194,7 +194,7 @@ public function getExtensionVersion() public function isDefaultSelector($storeId = null) { - return 'top.search' === $this->getAutocompleteSelector($storeId); + return '.algolia-search-input' === $this->getAutocompleteSelector($storeId); } public function getAutocompleteSelector($storeId = null) diff --git a/Model/Observer.php b/Model/Observer.php index c70ce9078..38191ccf6 100755 --- a/Model/Observer.php +++ b/Model/Observer.php @@ -53,6 +53,12 @@ public function execute(\Magento\Framework\Event\Observer $observer) /** @var Layout $layout */ $layout = $observer->getData('layout'); $layout->getUpdate()->addHandle('algolia_search_handle'); + if ($this->config->isDefaultSelector()) { + $layout->getUpdate()->addHandle('algolia_search_handle_with_topsearch'); + } else { + $layout->getUpdate()->addHandle('algolia_search_handle_no_topsearch'); + } + $this->loadPreventBackendRenderingHandle($layout); } } diff --git a/Observer/TopSearchTemplate.php b/Observer/TopSearchTemplate.php deleted file mode 100644 index ff2584b4d..000000000 --- a/Observer/TopSearchTemplate.php +++ /dev/null @@ -1,36 +0,0 @@ -config = $configHelper; - } - - /** - * @param Observer $observer - * @return void - */ - public function execute(Observer $observer) - { - /** @var Layout $layout */ - $layout = $observer->getData('layout'); - $block = $layout->getBlock($this->config->getAutocompleteSelector()); - if ($block) { - $block->setTemplate('Algolia_AlgoliaSearch::autocomplete.phtml'); - } - } -} diff --git a/etc/frontend/events.xml b/etc/frontend/events.xml index bf8e3740c..16903e373 100755 --- a/etc/frontend/events.xml +++ b/etc/frontend/events.xml @@ -24,8 +24,4 @@ - - - - diff --git a/view/frontend/templates/autocomplete.phtml b/view/frontend/templates/autocomplete.phtml index ce69bdc04..104961653 100755 --- a/view/frontend/templates/autocomplete.phtml +++ b/view/frontend/templates/autocomplete.phtml @@ -3,13 +3,13 @@ * @var \Algolia\AlgoliaSearch\Block\Algolia $block */ -$blockInstance= $block->getLayout()->createBlock('Algolia\AlgoliaSearch\Block\Algolia'); -$config = $blockInstance->getConfigHelper(); -$catalogSearchHelper = $blockInstance->getCatalogSearchHelper(); +$config = $block->getConfigHelper(); + +$catalogSearchHelper = $block->getCatalogSearchHelper(); $placeholder = __('Search for products, categories, ...'); // Render form with autocomplete input -//if ($config->isDefaultSelector()) : ?> +if ($config->isDefaultSelector()) : ?> - + From b45e9162ae8203628659bd894e9a6f7657f46afd Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Mon, 17 Oct 2022 11:25:42 +0530 Subject: [PATCH 55/73] MAGE-448 --- Model/Observer.php | 3 ++- etc/frontend/events.xml | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Model/Observer.php b/Model/Observer.php index 38191ccf6..2d9a8a262 100755 --- a/Model/Observer.php +++ b/Model/Observer.php @@ -51,8 +51,9 @@ public function execute(\Magento\Framework\Event\Observer $observer) if ($this->config->getApplicationID() && $this->config->getAPIKey()) { if ($this->config->isAutoCompleteEnabled() || $this->config->isInstantEnabled()) { /** @var Layout $layout */ - $layout = $observer->getData('layout'); + $layout = $observer->getData('layout'); $layout->getUpdate()->addHandle('algolia_search_handle'); + if ($this->config->isDefaultSelector()) { $layout->getUpdate()->addHandle('algolia_search_handle_with_topsearch'); } else { diff --git a/etc/frontend/events.xml b/etc/frontend/events.xml index 16903e373..4faac48a7 100755 --- a/etc/frontend/events.xml +++ b/etc/frontend/events.xml @@ -24,4 +24,5 @@ + From 090c49a178a40d3b5f9f6b1a8810f1c2f1b56cdd Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Mon, 17 Oct 2022 11:26:31 +0530 Subject: [PATCH 56/73] MAGE-448 --- etc/frontend/events.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/etc/frontend/events.xml b/etc/frontend/events.xml index 4faac48a7..052efd5a5 100755 --- a/etc/frontend/events.xml +++ b/etc/frontend/events.xml @@ -23,6 +23,4 @@ - - From 05dbb2be4a0339ef1adfe4545df25b4559e5d1ab Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Mon, 17 Oct 2022 11:29:13 +0530 Subject: [PATCH 57/73] MAGE-448 --- etc/frontend/events.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/etc/frontend/events.xml b/etc/frontend/events.xml index 052efd5a5..16903e373 100755 --- a/etc/frontend/events.xml +++ b/etc/frontend/events.xml @@ -23,4 +23,5 @@ + From 88af1f4273bdd6b2c58a7729234728bb58b306de Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Tue, 18 Oct 2022 15:32:00 +0530 Subject: [PATCH 58/73] MAGE-448 --- view/frontend/web/autocomplete.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/view/frontend/web/autocomplete.js b/view/frontend/web/autocomplete.js index 1ee85700d..59cbe7bb0 100755 --- a/view/frontend/web/autocomplete.js +++ b/view/frontend/web/autocomplete.js @@ -90,7 +90,8 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg sources.push(source); } - /** Those sections have already specific placeholder, so do not use the default aa-dataset-{i} class **/ + /** Those sections have already specific placeholder, + * so do not use the default aa-dataset-{i} class to specify the placeholder **/ if (section.name !== 'suggestions' && section.name !== 'products') { i++; } @@ -169,7 +170,8 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg /** Bind autocomplete feature to the input */ var algoliaAutocompleteInstance = algoliaAutocomplete.autocomplete(options); algoliaAutocompleteInstance = algolia.triggerHooks('afterAutocompleteStart', algoliaAutocompleteInstance); - //Written code for autocomplete insight + + //Autocomplete insight click conversion jQuery(document).on('click', '.algoliasearch-autocomplete-hit', function(){ let itemUrl = jQuery(this).attr('href'); let eventData = algoliaInsights.buildEventData( @@ -179,8 +181,8 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg }); }); }); - // moving common.js autocomplete code to autocomplete.js + // autocomplete code moved from common.js to autocomplete.js window.transformAutocompleteHit = function (hit, price_key, $, helper) { if (Array.isArray(hit.categories)) hit.categories = hit.categories.join(', '); @@ -324,7 +326,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg if (section.name === "products") { options.facets = ['categories.level0']; options.numericFilters = 'visibility_search=1'; - options.ruleContexts = ['magento_filters', '']; // Empty context to keep BC for already create rules in dashboard + options.ruleContexts = ['magento_filters', '']; // Empty context to keep backward compatibility for already created rules in dashboard options = algolia.triggerHooks('beforeAutocompleteProductSourceOptions', options); From 96bb0add513a6be7de808146d50935cd982138d2 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Tue, 18 Oct 2022 18:00:46 +0530 Subject: [PATCH 59/73] MAGE-448-442 --- view/frontend/web/autocomplete.js | 23 ++++++++++--------- .../web/internals/template/products.js | 18 +++++++-------- 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/view/frontend/web/autocomplete.js b/view/frontend/web/autocomplete.js index 59cbe7bb0..91396e4b3 100755 --- a/view/frontend/web/autocomplete.js +++ b/view/frontend/web/autocomplete.js @@ -184,6 +184,7 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg // autocomplete code moved from common.js to autocomplete.js window.transformAutocompleteHit = function (hit, price_key, $, helper) { + //console.log(hit); if (Array.isArray(hit.categories)) hit.categories = hit.categories.join(', '); @@ -256,20 +257,20 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg if (Array.isArray(hit._highlightResult.name)) hit._highlightResult.name = hit._highlightResult.name[0]; - if (Array.isArray(hit.price)) + if (Array.isArray(hit.price)) { hit.price = hit.price[0]; + if (hit['price'] !== undefined && price_key !== '.' + algoliaConfig.currencyCode + '.default' && hit['price'][algoliaConfig.currencyCode][price_key.substr(1) + '_formated'] !== hit['price'][algoliaConfig.currencyCode]['default_formated']) { + hit['price'][algoliaConfig.currencyCode][price_key.substr(1) + '_original_formated'] = hit['price'][algoliaConfig.currencyCode]['default_formated']; + } - if (hit['price'] !== undefined && price_key !== '.' + algoliaConfig.currencyCode + '.default' && hit['price'][algoliaConfig.currencyCode][price_key.substr(1) + '_formated'] !== hit['price'][algoliaConfig.currencyCode]['default_formated']) { - hit['price'][algoliaConfig.currencyCode][price_key.substr(1) + '_original_formated'] = hit['price'][algoliaConfig.currencyCode]['default_formated']; - } - - if (hit['price'][algoliaConfig.currencyCode]['default_original_formated'] - && hit['price'][algoliaConfig.currencyCode]['special_to_date']) { - var priceExpiration = hit['price'][algoliaConfig.currencyCode]['special_to_date']; + if (hit['price'][algoliaConfig.currencyCode]['default_original_formated'] + && hit['price'][algoliaConfig.currencyCode]['special_to_date']) { + var priceExpiration = hit['price'][algoliaConfig.currencyCode]['special_to_date']; - if (algoliaConfig.now > priceExpiration + 1) { - hit['price'][algoliaConfig.currencyCode]['default_formated'] = hit['price'][algoliaConfig.currencyCode]['default_original_formated']; - hit['price'][algoliaConfig.currencyCode]['default_original_formated'] = false; + if (algoliaConfig.now > priceExpiration + 1) { + hit['price'][algoliaConfig.currencyCode]['default_formated'] = hit['price'][algoliaConfig.currencyCode]['default_original_formated']; + hit['price'][algoliaConfig.currencyCode]['default_original_formated'] = false; + } } } diff --git a/view/frontend/web/internals/template/products.js b/view/frontend/web/internals/template/products.js index f75fef95c..18ca3835b 100644 --- a/view/frontend/web/internals/template/products.js +++ b/view/frontend/web/internals/template/products.js @@ -14,15 +14,15 @@ define([], function () { ${components.Highlight({hit: _data, attribute: 'name'}) || ''}
${color && color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : - _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''} + _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''}
-
- + ${_data['price'] !== undefined ? html `
+ ${_data['price'][algoliaConfig.currencyCode]['default_formated']} ${_data['price'][algoliaConfig.currencyCode]['default_original_formated'] != null ? html` ${_data['price'][algoliaConfig.currencyCode]['default_original_formated']}` : ''} -
+
` : ''}
`; } else { @@ -32,10 +32,10 @@ define([], function () { ${components.Highlight({hit: _data, attribute: 'name'}) || ''}
${color && color != '' ? html `color : ${components.Highlight({hit: _data, attribute: 'color'})}` : - _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''} + _data.categories_without_path && _data.categories_without_path.length != 0 ? html `in ${components.Highlight({hit: _data, attribute: 'categories_without_path'})}` : ''}
-
- + ${_data['price'] !== undefined ? html `
+ ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup + '_formated']} ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup + '_original_formated'] != null ? html` @@ -43,7 +43,7 @@ define([], function () { ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup + '_tier_formated'] != null ? html` As low as ${_data['price'][algoliaConfig.currencyCode][algoliaConfig.priceGroup + '_tier_formated']}` : ''} -
+
` : ''}
`; } @@ -62,7 +62,7 @@ define([], function () { return html ``; }else{ return html ``; From dfcf870c10e839c66109d780fd1ed9b654ce3025 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Tue, 18 Oct 2022 18:02:31 +0530 Subject: [PATCH 60/73] MAGE-448 --- view/frontend/web/autocomplete.js | 1 - 1 file changed, 1 deletion(-) diff --git a/view/frontend/web/autocomplete.js b/view/frontend/web/autocomplete.js index 91396e4b3..c91e43035 100755 --- a/view/frontend/web/autocomplete.js +++ b/view/frontend/web/autocomplete.js @@ -184,7 +184,6 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg // autocomplete code moved from common.js to autocomplete.js window.transformAutocompleteHit = function (hit, price_key, $, helper) { - //console.log(hit); if (Array.isArray(hit.categories)) hit.categories = hit.categories.join(', '); From 1ed70094adc7da10816b42b197159724d4cf81c4 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Wed, 19 Oct 2022 13:14:52 +0530 Subject: [PATCH 61/73] MAGE-448 --- view/frontend/requirejs-config.js | 10 +++++----- .../template/{ => autocomplete}/additional-section.js | 0 .../template/{ => autocomplete}/categories.js | 0 .../web/internals/template/{ => autocomplete}/pages.js | 0 .../internals/template/{ => autocomplete}/products.js | 0 .../template/{ => autocomplete}/suggestions.js | 0 6 files changed, 5 insertions(+), 5 deletions(-) rename view/frontend/web/internals/template/{ => autocomplete}/additional-section.js (100%) rename view/frontend/web/internals/template/{ => autocomplete}/categories.js (100%) rename view/frontend/web/internals/template/{ => autocomplete}/pages.js (100%) rename view/frontend/web/internals/template/{ => autocomplete}/products.js (100%) rename view/frontend/web/internals/template/{ => autocomplete}/suggestions.js (100%) diff --git a/view/frontend/requirejs-config.js b/view/frontend/requirejs-config.js index c328cba23..4e181a7f6 100644 --- a/view/frontend/requirejs-config.js +++ b/view/frontend/requirejs-config.js @@ -5,11 +5,11 @@ var config = { 'recommend': 'Algolia_AlgoliaSearch/internals/recommend.min', 'recommendJs': 'Algolia_AlgoliaSearch/internals/recommend-js.min', 'rangeSlider': 'Algolia_AlgoliaSearch/navigation/range-slider-widget', - 'pagesHtml': 'Algolia_AlgoliaSearch/internals/template/pages', - 'categoriesHtml': 'Algolia_AlgoliaSearch/internals/template/categories', - 'productsHtml': 'Algolia_AlgoliaSearch/internals/template/products', - 'suggestionsHtml': 'Algolia_AlgoliaSearch/internals/template/suggestions', - 'additionalHtml': 'Algolia_AlgoliaSearch/internals/template/additional-section' + 'pagesHtml': 'Algolia_AlgoliaSearch/internals/template/autocomplete/pages', + 'categoriesHtml': 'Algolia_AlgoliaSearch/internals/template/autocomplete/categories', + 'productsHtml': 'Algolia_AlgoliaSearch/internals/template/autocomplete/products', + 'suggestionsHtml': 'Algolia_AlgoliaSearch/internals/template/autocomplete/suggestions', + 'additionalHtml': 'Algolia_AlgoliaSearch/internals/template/autocomplete/additional-section' }, config: { mixins: { diff --git a/view/frontend/web/internals/template/additional-section.js b/view/frontend/web/internals/template/autocomplete/additional-section.js similarity index 100% rename from view/frontend/web/internals/template/additional-section.js rename to view/frontend/web/internals/template/autocomplete/additional-section.js diff --git a/view/frontend/web/internals/template/categories.js b/view/frontend/web/internals/template/autocomplete/categories.js similarity index 100% rename from view/frontend/web/internals/template/categories.js rename to view/frontend/web/internals/template/autocomplete/categories.js diff --git a/view/frontend/web/internals/template/pages.js b/view/frontend/web/internals/template/autocomplete/pages.js similarity index 100% rename from view/frontend/web/internals/template/pages.js rename to view/frontend/web/internals/template/autocomplete/pages.js diff --git a/view/frontend/web/internals/template/products.js b/view/frontend/web/internals/template/autocomplete/products.js similarity index 100% rename from view/frontend/web/internals/template/products.js rename to view/frontend/web/internals/template/autocomplete/products.js diff --git a/view/frontend/web/internals/template/suggestions.js b/view/frontend/web/internals/template/autocomplete/suggestions.js similarity index 100% rename from view/frontend/web/internals/template/suggestions.js rename to view/frontend/web/internals/template/autocomplete/suggestions.js From 8f56940a9391e3a4824a52ae1ef20d35aaffc973 Mon Sep 17 00:00:00 2001 From: Mohit Choudhary Date: Wed, 19 Oct 2022 13:50:13 +0530 Subject: [PATCH 62/73] Updated data attribute in recommend --- view/frontend/web/recommend.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/view/frontend/web/recommend.js b/view/frontend/web/recommend.js index b99a12ded..7c32e4e23 100644 --- a/view/frontend/web/recommend.js +++ b/view/frontend/web/recommend.js @@ -83,6 +83,8 @@ requirejs([ }); } function renderRecommendData(item, createElement){ + this.config = algoliaConfig; + this.defaultIndexName = algoliaConfig.indexName + '_products'; return createElement( 'div', null, @@ -91,7 +93,7 @@ requirejs([ {className: "product-details"}, createElement( 'a', - {className: "product-url", href: item.url}, + {className: "recommend-item product-url", href: item.url, 'data-objectId': item.objectID, 'data-index': this.defaultIndexName}, createElement('img', {className: "product-img", src: item.image_url}, item.image_url), createElement('p', {className: "product-name"}, item.name) ) @@ -104,6 +106,8 @@ requirejs([ if(correctFKey != "" && config.recommend.addToCartParams.formKey != correctFKey) { config.recommend.addToCartParams.formKey = correctFKey; } + this.config = algoliaConfig; + this.defaultIndexName = algoliaConfig.indexName + '_products'; return createElement( 'div', null, @@ -112,7 +116,7 @@ requirejs([ {className: "product-details"}, createElement( 'a', - {className: "product-url", href: item.url}, + {className: "recommend-item product-url", href: item.url, 'data-objectId': item.objectID, 'data-index': this.defaultIndexName}, createElement('img', {className: "product-img", src: item.image_url}, item.image_url), createElement('p', {className: "product-name"}, item.name), createElement('form', {className: 'addTocartForm', action: action, method: 'post'}, From b331d4dfd0c9975fb3546f556b29cfbb78109db1 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Wed, 19 Oct 2022 16:25:55 +0530 Subject: [PATCH 63/73] MAGE-448 --- view/frontend/templates/autocomplete.phtml | 36 +++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/view/frontend/templates/autocomplete.phtml b/view/frontend/templates/autocomplete.phtml index 104961653..f4a4a8d04 100755 --- a/view/frontend/templates/autocomplete.phtml +++ b/view/frontend/templates/autocomplete.phtml @@ -10,6 +10,40 @@ $catalogSearchHelper = $block->getCatalogSearchHelper(); $placeholder = __('Search for products, categories, ...'); // Render form with autocomplete input +if ($config->isAutoCompleteEnabled()) : if ($config->isDefaultSelector()) : ?> - + + + + From cdcb3b4090883e249f51b98ec5add62106aaa93f Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Wed, 19 Oct 2022 17:00:17 +0530 Subject: [PATCH 64/73] MAGE-448 --- view/frontend/web/autocomplete.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/view/frontend/web/autocomplete.js b/view/frontend/web/autocomplete.js index c91e43035..a2ef8b7b4 100755 --- a/view/frontend/web/autocomplete.js +++ b/view/frontend/web/autocomplete.js @@ -2,7 +2,7 @@ let algoliaAutocomplete; let suggestionSection = false; let algoliaFooter; let productResult = []; -requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'suggestionsHtml', 'additionalHtml'], function(algoliaBundle, pagesHtml, categoriesHtml, productsHtml, suggestionsHtml, additionalHtml) { +requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'suggestionsHtml', 'additionalHtml', 'domReady!'], function(algoliaBundle, pagesHtml, categoriesHtml, productsHtml, suggestionsHtml, additionalHtml) { algoliaAutocomplete = algoliaBundle; algoliaBundle.$(function ($) { From ec5f526ceaec901e35541182611242cabe560a6d Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Wed, 19 Oct 2022 18:09:44 +0530 Subject: [PATCH 65/73] MAGE-448 --- view/frontend/web/autocomplete.js | 589 +++++++++++++++--------------- 1 file changed, 294 insertions(+), 295 deletions(-) diff --git a/view/frontend/web/autocomplete.js b/view/frontend/web/autocomplete.js index a2ef8b7b4..be866f05a 100755 --- a/view/frontend/web/autocomplete.js +++ b/view/frontend/web/autocomplete.js @@ -20,6 +20,300 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg var searchClient = algoliaBundle.algoliasearch(algoliaConfig.applicationId, algoliaConfig.apiKey); + // autocomplete code moved from common.js to autocomplete.js + window.transformAutocompleteHit = function (hit, price_key, $, helper) { + if (Array.isArray(hit.categories)) + hit.categories = hit.categories.join(', '); + + if (hit._highlightResult.categories_without_path && Array.isArray(hit.categories_without_path)) { + hit.categories_without_path = $.map(hit._highlightResult.categories_without_path, function (category) { + return category.value; + }); + + hit.categories_without_path = hit.categories_without_path.join(', '); + } + + var matchedColors = []; + + if (helper && algoliaConfig.useAdaptiveImage === true) { + if (hit.images_data && helper.state.facetsRefinements.color) { + matchedColors = helper.state.disjunctiveFacetsRefinements.color.slice(0); // slice to clone + } + + if (hit.images_data && helper.state.disjunctiveFacetsRefinements.color) { + matchedColors = helper.state.disjunctiveFacetsRefinements.color.slice(0); // slice to clone + } + } + + if (Array.isArray(hit.color)) { + var colors = []; + + $.each(hit._highlightResult.color, function (i, color) { + if (color.matchLevel === undefined || color.matchLevel === 'none') { + return; + } + + colors.push(color.value); + + if (algoliaConfig.useAdaptiveImage === true) { + var matchedColor = color.matchedWords.join(' '); + if (hit.images_data && color.fullyHighlighted && color.fullyHighlighted === true) { + matchedColors.push(matchedColor); + } + } + }); + + colors = colors.join(', '); + hit._highlightResult.color = { value: colors }; + } + else { + if (hit._highlightResult.color && hit._highlightResult.color.matchLevel === 'none') { + hit._highlightResult.color = { value: '' }; + } + } + + if (algoliaConfig.useAdaptiveImage === true) { + $.each(matchedColors, function (i, color) { + color = color.toLowerCase(); + + if (hit.images_data[color]) { + hit.image_url = hit.images_data[color]; + hit.thumbnail_url = hit.images_data[color]; + + return false; + } + }); + } + + if (hit._highlightResult.color && hit._highlightResult.color.value && hit.categories_without_path) { + if (hit.categories_without_path.indexOf('') === -1 && hit._highlightResult.color.value.indexOf('') !== -1) { + hit.categories_without_path = ''; + } + } + + if (Array.isArray(hit._highlightResult.name)) + hit._highlightResult.name = hit._highlightResult.name[0]; + + if (Array.isArray(hit.price)) { + hit.price = hit.price[0]; + if (hit['price'] !== undefined && price_key !== '.' + algoliaConfig.currencyCode + '.default' && hit['price'][algoliaConfig.currencyCode][price_key.substr(1) + '_formated'] !== hit['price'][algoliaConfig.currencyCode]['default_formated']) { + hit['price'][algoliaConfig.currencyCode][price_key.substr(1) + '_original_formated'] = hit['price'][algoliaConfig.currencyCode]['default_formated']; + } + + if (hit['price'][algoliaConfig.currencyCode]['default_original_formated'] + && hit['price'][algoliaConfig.currencyCode]['special_to_date']) { + var priceExpiration = hit['price'][algoliaConfig.currencyCode]['special_to_date']; + + if (algoliaConfig.now > priceExpiration + 1) { + hit['price'][algoliaConfig.currencyCode]['default_formated'] = hit['price'][algoliaConfig.currencyCode]['default_original_formated']; + hit['price'][algoliaConfig.currencyCode]['default_original_formated'] = false; + } + } + } + + // Add to cart parameters + var action = algoliaConfig.instant.addToCartParams.action + 'product/' + hit.objectID + '/'; + + var correctFKey = getCookie('form_key'); + + if(correctFKey != "" && algoliaConfig.instant.addToCartParams.formKey != correctFKey) { + algoliaConfig.instant.addToCartParams.formKey = correctFKey; + } + + hit.addToCart = { + 'action': action, + 'uenc': AlgoliaBase64.mageEncode(action), + 'formKey': algoliaConfig.instant.addToCartParams.formKey + }; + + if (hit.__autocomplete_queryID) { + + hit.urlForInsights = hit.url; + + if (algoliaConfig.ccAnalytics.enabled + && algoliaConfig.ccAnalytics.conversionAnalyticsMode !== 'disabled') { + var insightsDataUrlString = $.param({ + queryID: hit.__autocomplete_queryID, + objectID: hit.objectID, + indexName: hit.__autocomplete_indexName + }); + if (hit.url.indexOf('?') > -1) { + hit.urlForInsights += insightsDataUrlString + } else { + hit.urlForInsights += '?' + insightsDataUrlString; + } + } + } + + return hit; + }; + + window.getAutocompleteSource = function (section, algolia_client, $, i) { + if (section.hitsPerPage <= 0) + return null; + + var options = { + hitsPerPage: section.hitsPerPage, + analyticsTags: 'autocomplete', + clickAnalytics: true, + distinct: true + }; + + var source; + + if (section.name === "products") { + options.facets = ['categories.level0']; + options.numericFilters = 'visibility_search=1'; + options.ruleContexts = ['magento_filters', '']; // Empty context to keep backward compatibility for already created rules in dashboard + + options = algolia.triggerHooks('beforeAutocompleteProductSourceOptions', options); + + source = { + name: section.name, + hitsPerPage: section.hitsPerPage, + paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), + options:options, + templates: { + noResults() { + return productsHtml.getNoResultHtml(); + }, + item({ item, components, html }) { + if(suggestionSection){ + algoliaAutocomplete.$('.aa-Panel').addClass('productColumn2'); + algoliaAutocomplete.$('.aa-Panel').removeClass('productColumn1'); + }else{ + algoliaAutocomplete.$('.aa-Panel').removeClass('productColumn2'); + algoliaAutocomplete.$('.aa-Panel').addClass('productColumn1'); + } + if(algoliaFooter && algoliaFooter !== undefined && algoliaFooter !== null && algoliaAutocomplete.$('#algoliaFooter').length === 0){ + algoliaAutocomplete.$('.aa-PanelLayout').append(algoliaFooter); + } + var _data = transformAutocompleteHit(item, algoliaConfig.priceKey, $); + return productsHtml.getProductsHtml(_data, components, html); + }, + footer({html}) { + var keys = []; + for (var i = 0; i 0) { + orsTab = []; + for (var i = 0; i < keys.length && i < 2; i++) { + orsTab.push( + { + url:keys[i].url, + name:keys[i].key + } + ); + } + } + + var allUrl = algoliaConfig.baseUrl + '/catalogsearch/result/?q=' + encodeURIComponent(productResult[0].query); + return productsHtml.getFooterHtml(html, orsTab, allUrl, productResult) + } + } + }; + } + else if (section.name === "categories") + { + if (section.name === "categories" && algoliaConfig.showCatsNotIncludedInNavigation === false) { + options.numericFilters = 'include_in_menu=1'; + } + source = { + name: section.name || i, + hitsPerPage: section.hitsPerPage, + paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), + options:options, + templates: { + noResults() { + return categoriesHtml.getNoResultHtml(); + }, + header() { + return categoriesHtml.getHeaderHtml(section); + }, + item({ item, components, html }) { + return categoriesHtml.getCategoriesHtml(item, components, html); + } + } + }; + } + else if (section.name === "pages") + { + source = { + name: section.name || i, + hitsPerPage: section.hitsPerPage, + paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), + options:options, + templates: { + noResults() { + return pagesHtml.getNoResultHtml(); + }, + header() { + return pagesHtml.getHeaderHtml(section); + }, + item({ item, components, html }) { + return pagesHtml.getPagesHtml(item, components, html); + } + } + }; + } + else if (section.name === "suggestions") + { + var suggestions_index = algolia_client.initIndex(algoliaConfig.indexName + "_suggestions"); + var products_index = algolia_client.initIndex(algoliaConfig.indexName + "_products"); + + source = { + displayKey: 'query', + name: section.name, + hitsPerPage: section.hitsPerPage, + paramName: suggestions_index, + options:options, + templates: { + item({ item, html }) { + return html`
Suggestion List
`; + } + } + }; + } else { + /** If is not products, categories, pages or suggestions, it's additional section **/ + source = { + paramName: algolia_client.initIndex(algoliaConfig.indexName + "_section_" + section.name), + displayKey: 'value', + name: section.name || i, + hitsPerPage: section.hitsPerPage, + options:options, + templates: { + noResults() { + return additionalHtml.getNoResultHtml(); + }, + header() { + return additionalHtml.getHeaderHtml(section); + }, + item({ item, components, html }) { + return additionalHtml.getAdditionalHtml(item, components, html); + } + } + }; + } + + return source; + }; /** Add products and categories that are required sections **/ /** Add autocomplete menu sections **/ if (algoliaConfig.autocomplete.nbOfProductsSuggestions > 0) { @@ -182,301 +476,6 @@ requirejs(['algoliaBundle', 'pagesHtml', 'categoriesHtml', 'productsHtml', 'sugg }); }); - // autocomplete code moved from common.js to autocomplete.js - window.transformAutocompleteHit = function (hit, price_key, $, helper) { - if (Array.isArray(hit.categories)) - hit.categories = hit.categories.join(', '); - - if (hit._highlightResult.categories_without_path && Array.isArray(hit.categories_without_path)) { - hit.categories_without_path = $.map(hit._highlightResult.categories_without_path, function (category) { - return category.value; - }); - - hit.categories_without_path = hit.categories_without_path.join(', '); - } - - var matchedColors = []; - - if (helper && algoliaConfig.useAdaptiveImage === true) { - if (hit.images_data && helper.state.facetsRefinements.color) { - matchedColors = helper.state.disjunctiveFacetsRefinements.color.slice(0); // slice to clone - } - - if (hit.images_data && helper.state.disjunctiveFacetsRefinements.color) { - matchedColors = helper.state.disjunctiveFacetsRefinements.color.slice(0); // slice to clone - } - } - - if (Array.isArray(hit.color)) { - var colors = []; - - $.each(hit._highlightResult.color, function (i, color) { - if (color.matchLevel === undefined || color.matchLevel === 'none') { - return; - } - - colors.push(color.value); - - if (algoliaConfig.useAdaptiveImage === true) { - var matchedColor = color.matchedWords.join(' '); - if (hit.images_data && color.fullyHighlighted && color.fullyHighlighted === true) { - matchedColors.push(matchedColor); - } - } - }); - - colors = colors.join(', '); - hit._highlightResult.color = { value: colors }; - } - else { - if (hit._highlightResult.color && hit._highlightResult.color.matchLevel === 'none') { - hit._highlightResult.color = { value: '' }; - } - } - - if (algoliaConfig.useAdaptiveImage === true) { - $.each(matchedColors, function (i, color) { - color = color.toLowerCase(); - - if (hit.images_data[color]) { - hit.image_url = hit.images_data[color]; - hit.thumbnail_url = hit.images_data[color]; - - return false; - } - }); - } - - if (hit._highlightResult.color && hit._highlightResult.color.value && hit.categories_without_path) { - if (hit.categories_without_path.indexOf('') === -1 && hit._highlightResult.color.value.indexOf('') !== -1) { - hit.categories_without_path = ''; - } - } - - if (Array.isArray(hit._highlightResult.name)) - hit._highlightResult.name = hit._highlightResult.name[0]; - - if (Array.isArray(hit.price)) { - hit.price = hit.price[0]; - if (hit['price'] !== undefined && price_key !== '.' + algoliaConfig.currencyCode + '.default' && hit['price'][algoliaConfig.currencyCode][price_key.substr(1) + '_formated'] !== hit['price'][algoliaConfig.currencyCode]['default_formated']) { - hit['price'][algoliaConfig.currencyCode][price_key.substr(1) + '_original_formated'] = hit['price'][algoliaConfig.currencyCode]['default_formated']; - } - - if (hit['price'][algoliaConfig.currencyCode]['default_original_formated'] - && hit['price'][algoliaConfig.currencyCode]['special_to_date']) { - var priceExpiration = hit['price'][algoliaConfig.currencyCode]['special_to_date']; - - if (algoliaConfig.now > priceExpiration + 1) { - hit['price'][algoliaConfig.currencyCode]['default_formated'] = hit['price'][algoliaConfig.currencyCode]['default_original_formated']; - hit['price'][algoliaConfig.currencyCode]['default_original_formated'] = false; - } - } - } - - // Add to cart parameters - var action = algoliaConfig.instant.addToCartParams.action + 'product/' + hit.objectID + '/'; - - var correctFKey = getCookie('form_key'); - - if(correctFKey != "" && algoliaConfig.instant.addToCartParams.formKey != correctFKey) { - algoliaConfig.instant.addToCartParams.formKey = correctFKey; - } - - hit.addToCart = { - 'action': action, - 'uenc': AlgoliaBase64.mageEncode(action), - 'formKey': algoliaConfig.instant.addToCartParams.formKey - }; - - if (hit.__autocomplete_queryID) { - - hit.urlForInsights = hit.url; - - if (algoliaConfig.ccAnalytics.enabled - && algoliaConfig.ccAnalytics.conversionAnalyticsMode !== 'disabled') { - var insightsDataUrlString = $.param({ - queryID: hit.__autocomplete_queryID, - objectID: hit.objectID, - indexName: hit.__autocomplete_indexName - }); - if (hit.url.indexOf('?') > -1) { - hit.urlForInsights += insightsDataUrlString - } else { - hit.urlForInsights += '?' + insightsDataUrlString; - } - } - } - - return hit; - }; - - window.getAutocompleteSource = function (section, algolia_client, $, i) { - if (section.hitsPerPage <= 0) - return null; - - var options = { - hitsPerPage: section.hitsPerPage, - analyticsTags: 'autocomplete', - clickAnalytics: true, - distinct: true - }; - - var source; - - if (section.name === "products") { - options.facets = ['categories.level0']; - options.numericFilters = 'visibility_search=1'; - options.ruleContexts = ['magento_filters', '']; // Empty context to keep backward compatibility for already created rules in dashboard - - options = algolia.triggerHooks('beforeAutocompleteProductSourceOptions', options); - - source = { - name: section.name, - hitsPerPage: section.hitsPerPage, - paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), - options:options, - templates: { - noResults() { - return productsHtml.getNoResultHtml(); - }, - item({ item, components, html }) { - if(suggestionSection){ - algoliaAutocomplete.$('.aa-Panel').addClass('productColumn2'); - algoliaAutocomplete.$('.aa-Panel').removeClass('productColumn1'); - }else{ - algoliaAutocomplete.$('.aa-Panel').removeClass('productColumn2'); - algoliaAutocomplete.$('.aa-Panel').addClass('productColumn1'); - } - if(algoliaFooter && algoliaFooter !== undefined && algoliaFooter !== null && algoliaAutocomplete.$('#algoliaFooter').length === 0){ - algoliaAutocomplete.$('.aa-PanelLayout').append(algoliaFooter); - } - var _data = transformAutocompleteHit(item, algoliaConfig.priceKey, $); - return productsHtml.getProductsHtml(_data, components, html); - }, - footer({html}) { - var keys = []; - for (var i = 0; i 0) { - orsTab = []; - for (var i = 0; i < keys.length && i < 2; i++) { - orsTab.push( - { - url:keys[i].url, - name:keys[i].key - } - ); - } - } - - var allUrl = algoliaConfig.baseUrl + '/catalogsearch/result/?q=' + encodeURIComponent(productResult[0].query); - return productsHtml.getFooterHtml(html, orsTab, allUrl, productResult) - } - } - }; - } - else if (section.name === "categories") - { - if (section.name === "categories" && algoliaConfig.showCatsNotIncludedInNavigation === false) { - options.numericFilters = 'include_in_menu=1'; - } - source = { - name: section.name || i, - hitsPerPage: section.hitsPerPage, - paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), - options:options, - templates: { - noResults() { - return categoriesHtml.getNoResultHtml(); - }, - header() { - return categoriesHtml.getHeaderHtml(section); - }, - item({ item, components, html }) { - return categoriesHtml.getCategoriesHtml(item, components, html); - } - } - }; - } - else if (section.name === "pages") - { - source = { - name: section.name || i, - hitsPerPage: section.hitsPerPage, - paramName:algolia_client.initIndex(algoliaConfig.indexName + "_" + section.name), - options:options, - templates: { - noResults() { - return pagesHtml.getNoResultHtml(); - }, - header() { - return pagesHtml.getHeaderHtml(section); - }, - item({ item, components, html }) { - return pagesHtml.getPagesHtml(item, components, html); - } - } - }; - } - else if (section.name === "suggestions") - { - var suggestions_index = algolia_client.initIndex(algoliaConfig.indexName + "_suggestions"); - var products_index = algolia_client.initIndex(algoliaConfig.indexName + "_products"); - - source = { - displayKey: 'query', - name: section.name, - hitsPerPage: section.hitsPerPage, - paramName: suggestions_index, - options:options, - templates: { - item({ item, html }) { - return html`
Suggestion List
`; - } - } - }; - } else { - /** If is not products, categories, pages or suggestions, it's additional section **/ - source = { - paramName: algolia_client.initIndex(algoliaConfig.indexName + "_section_" + section.name), - displayKey: 'value', - name: section.name || i, - hitsPerPage: section.hitsPerPage, - options:options, - templates: { - noResults() { - return additionalHtml.getNoResultHtml(); - }, - header() { - return additionalHtml.getHeaderHtml(section); - }, - item({ item, components, html }) { - return additionalHtml.getAdditionalHtml(item, components, html); - } - } - }; - } - - return source; - }; - function getHitsUrlParameter(url, name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), From dd060efb948c39de2eae24e7603bd07418ac02b6 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Thu, 20 Oct 2022 16:56:15 +0530 Subject: [PATCH 66/73] MAGE-448 --- view/frontend/web/internals/autocomplete.css | 1 + 1 file changed, 1 insertion(+) diff --git a/view/frontend/web/internals/autocomplete.css b/view/frontend/web/internals/autocomplete.css index 7c747eba5..036ddc75e 100755 --- a/view/frontend/web/internals/autocomplete.css +++ b/view/frontend/web/internals/autocomplete.css @@ -466,6 +466,7 @@ position: absolute; right: 0px; height: 32px; + box-shadow: none; } #algoliaAutocomplete .aa-ClearButton{ position: absolute; From 869b0f858ef7064f99a932611a8cad2f75cd0898 Mon Sep 17 00:00:00 2001 From: Ratikant Singh Date: Thu, 20 Oct 2022 17:40:30 +0530 Subject: [PATCH 67/73] MAGE-448 --- view/frontend/templates/autocomplete.phtml | 4 ++-- view/frontend/web/internals/autocomplete.css | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/view/frontend/templates/autocomplete.phtml b/view/frontend/templates/autocomplete.phtml index f4a4a8d04..b41df5b00 100755 --- a/view/frontend/templates/autocomplete.phtml +++ b/view/frontend/templates/autocomplete.phtml @@ -11,8 +11,8 @@ $placeholder = __('Search for products, categories, ...'); // Render form with autocomplete input if ($config->isAutoCompleteEnabled()) : -if ($config->isDefaultSelector()) : ?> - + if ($config->isDefaultSelector()) : ?> +