From f611c33dc1eb66b0df8a3b199152eb9e7abd93dc Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Fri, 20 Sep 2024 13:37:54 +0300 Subject: [PATCH 01/13] [Analytics][Tracker] Feature #3340, add company_id and customer_group_id in tracking data --- .../Report/CustomerGroupSelector.php | 60 +++++++ .../Model/Report/Context.php | 10 ++ .../CustomerGroupIdFilterQueryProvider.php | 74 +++++++++ .../CustomerGroupIdFilterQueryProvider.php | 81 ++++++++++ src/module-elasticsuite-analytics/etc/di.xml | 18 ++- ...le_elasticsuite_analytics_search_usage.xml | 4 + .../report/customer_group_selector.phtml | 38 +++++ .../adminhtml/web/css/source/_module.less | 13 ++ .../web/js/report/customer-group-selector.js | 43 +++++ .../Block/Variables/Page/Customer.php | 151 ++++++++++++++++++ .../etc/elasticsuite_indices.xml | 6 + .../view/frontend/layout/default.xml | 3 + 12 files changed, 495 insertions(+), 6 deletions(-) create mode 100644 src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerGroupSelector.php create mode 100644 src/module-elasticsuite-analytics/Model/Report/Event/CustomerGroupIdFilterQueryProvider.php create mode 100644 src/module-elasticsuite-analytics/Model/Report/Session/CustomerGroupIdFilterQueryProvider.php create mode 100644 src/module-elasticsuite-analytics/view/adminhtml/templates/report/customer_group_selector.phtml create mode 100644 src/module-elasticsuite-analytics/view/adminhtml/web/js/report/customer-group-selector.js create mode 100644 src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php diff --git a/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerGroupSelector.php b/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerGroupSelector.php new file mode 100644 index 000000000..99170e56d --- /dev/null +++ b/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerGroupSelector.php @@ -0,0 +1,60 @@ + + * @copyright 2024 Smile + * @license Open Software License ("OSL") v. 3.0 + */ +namespace Smile\ElasticsuiteAnalytics\Block\Adminhtml\Report; + +use Magento\Framework\View\Element\Template; +use Magento\Customer\Model\ResourceModel\Group\CollectionFactory; + +/** + * Block used to display customer group selector in reports. + * + * @SuppressWarnings(PHPMD.CamelCasePropertyName) + * + * @category Smile + * @package Smile\ElasticsuiteAnalytics + * @author Vadym Honcharuk + */ +class CustomerGroupSelector extends Template +{ + /** + * @var CollectionFactory + */ + protected $customerGroupCollectionFactory; + + /** + * CustomerGroupSelector constructor. + * + * @param Template\Context $context The context of the template. + * @param CollectionFactory $customerGroupCollectionFactory Factory for creating customer group collection. + * @param array $data Additional block data. + */ + public function __construct( + Template\Context $context, + CollectionFactory $customerGroupCollectionFactory, + array $data = [] + ) { + $this->customerGroupCollectionFactory = $customerGroupCollectionFactory; + parent::__construct($context, $data); + } + + /** + * Get customer groups in an option array format. + * + * @return array + */ + public function getCustomerGroups() + { + return $this->customerGroupCollectionFactory->create()->toOptionArray(); + } +} diff --git a/src/module-elasticsuite-analytics/Model/Report/Context.php b/src/module-elasticsuite-analytics/Model/Report/Context.php index b326d5585..ede55322b 100644 --- a/src/module-elasticsuite-analytics/Model/Report/Context.php +++ b/src/module-elasticsuite-analytics/Model/Report/Context.php @@ -66,6 +66,16 @@ public function getStoreId() return $this->request->getParam('store'); } + /** + * Get customer group ID. + * + * @return mixed + */ + public function getCustomerGroupId() + { + return $this->request->getParam('customer_group'); + } + /** * Get date range. * diff --git a/src/module-elasticsuite-analytics/Model/Report/Event/CustomerGroupIdFilterQueryProvider.php b/src/module-elasticsuite-analytics/Model/Report/Event/CustomerGroupIdFilterQueryProvider.php new file mode 100644 index 000000000..a1ce55ce5 --- /dev/null +++ b/src/module-elasticsuite-analytics/Model/Report/Event/CustomerGroupIdFilterQueryProvider.php @@ -0,0 +1,74 @@ + + * @copyright 2024 Smile + * @license Open Software License ("OSL") v. 3.0 + */ +namespace Smile\ElasticsuiteAnalytics\Model\Report\Event; + +use Smile\ElasticsuiteAnalytics\Model\Report\QueryProviderInterface; +use Smile\ElasticsuiteCore\Search\Request\QueryInterface; +use Smile\ElasticsuiteCore\Search\Request\Query\QueryFactory; +use Smile\ElasticsuiteAnalytics\Model\Report\Context; + +/** + * Customer group id filter query provider. + * + * @category Smile + * @package Smile\ElasticsuiteAnalytics + */ +class CustomerGroupIdFilterQueryProvider implements QueryProviderInterface +{ + /** + * @var QueryFactory + */ + private $queryFactory; + + /** + * @var Context + */ + private $context; + + /** + * DateFilterQueryProvider constructor. + * + * @param QueryFactory $queryFactory Query factory. + * @param Context $context Report context. + */ + public function __construct(QueryFactory $queryFactory, Context $context) + { + $this->queryFactory = $queryFactory; + $this->context = $context; + } + + /** + * {@inheritDoc} + */ + public function getQuery() + { + // Get customer group ID from the context. + $customerGroupId = $this->context->getCustomerGroupId(); + + // Check if customer group ID is set and not 'all'. + if ($customerGroupId !== 'all' && $customerGroupId !== null) { + // Return a TERM query for the customer group ID. + return $this->queryFactory->create( + QueryInterface::TYPE_TERM, + [ + 'field' => 'customer.group_id', + 'value' => (int) $customerGroupId, + ] + ); + } + + // If 'all' is selected or no customer group ID is set, return null (no filtering). + return null; + } +} diff --git a/src/module-elasticsuite-analytics/Model/Report/Session/CustomerGroupIdFilterQueryProvider.php b/src/module-elasticsuite-analytics/Model/Report/Session/CustomerGroupIdFilterQueryProvider.php new file mode 100644 index 000000000..2a5f5b48a --- /dev/null +++ b/src/module-elasticsuite-analytics/Model/Report/Session/CustomerGroupIdFilterQueryProvider.php @@ -0,0 +1,81 @@ + + * @copyright 2024 Smile + * @license Open Software License ("OSL") v. 3.0 + */ +namespace Smile\ElasticsuiteAnalytics\Model\Report\Session; + +use Smile\ElasticsuiteAnalytics\Model\Report\QueryProviderInterface; +use Smile\ElasticsuiteCore\Search\Request\QueryInterface; +use Smile\ElasticsuiteCore\Search\Request\Query\QueryFactory; +use Smile\ElasticsuiteAnalytics\Model\Report\Context; + +/** + * Customer group id filter query provider. + * + * @category Smile + * @package Smile\ElasticsuiteAnalytics + */ +class CustomerGroupIdFilterQueryProvider implements QueryProviderInterface +{ + /** + * @var QueryFactory + */ + private $queryFactory; + + /** + * @var Context + */ + private $context; + + /** + * CustomerGroupIdFilterQueryProvider constructor. + * + * @param QueryFactory $queryFactory Query factory. + * @param Context $context Report context. + */ + public function __construct(QueryFactory $queryFactory, Context $context) + { + $this->queryFactory = $queryFactory; + $this->context = $context; + } + + /** + * {@inheritDoc} + */ + public function getQuery() + { + // Get customer group ID from the context. + $customerGroupId = $this->context->getCustomerGroupId(); + + // Check if customer group ID is set and not 'all'. + if ($customerGroupId !== 'all' && $customerGroupId !== null) { + // Return a TERM query for the customer group ID. + return $this->queryFactory->create( + QueryInterface::TYPE_BOOL, + [ + 'must' => [ + $this->queryFactory->create( + QueryInterface::TYPE_TERM, + [ + 'field' => 'customer_group_id', + 'value' => (int) $customerGroupId, + ] + ), + ], + ] + ); + } + + // If 'all' is selected or no customer group ID is set, return null (no filtering). + return null; + } +} diff --git a/src/module-elasticsuite-analytics/etc/di.xml b/src/module-elasticsuite-analytics/etc/di.xml index ef4acea8b..904617e20 100755 --- a/src/module-elasticsuite-analytics/etc/di.xml +++ b/src/module-elasticsuite-analytics/etc/di.xml @@ -23,6 +23,7 @@ Smile\ElasticsuiteAnalytics\Model\Report\Event\DateFilterQueryProvider + Smile\ElasticsuiteAnalytics\Model\Report\Event\CustomerGroupIdFilterQueryProvider @@ -41,6 +42,7 @@ Smile\ElasticsuiteAnalytics\Model\Report\Session\DateFilterQueryProvider + Smile\ElasticsuiteAnalytics\Model\Report\Session\CustomerGroupIdFilterQueryProvider tracking_log_session @@ -51,7 +53,7 @@ Smile\ElasticsuiteAnalytics\Model\Search\Usage\Kpi\ConversionRates\SearchRequestBuilder - + @@ -60,10 +62,11 @@ Smile\ElasticsuiteAnalytics\Model\Report\Event\DateFilterQueryProvider + Smile\ElasticsuiteAnalytics\Model\Report\Event\CustomerGroupIdFilterQueryProvider - + Smile\ElasticsuiteAnalytics\Model\Search\Usage\Terms\PopularTerms\SearchRequestBuilder @@ -72,7 +75,7 @@ - + @@ -82,10 +85,11 @@ Smile\ElasticsuiteAnalytics\Model\Search\Usage\Terms\SpellcheckedTerms\QueryProvider Smile\ElasticsuiteAnalytics\Model\Report\Event\DateFilterQueryProvider + Smile\ElasticsuiteAnalytics\Model\Report\Event\CustomerGroupIdFilterQueryProvider - + Smile\ElasticsuiteAnalytics\Model\Search\Usage\Terms\SpellcheckedTerms\SearchRequestBuilder @@ -94,7 +98,7 @@ - + @@ -104,10 +108,11 @@ Smile\ElasticsuiteAnalytics\Model\Report\Session\DateFilterQueryProvider + Smile\ElasticsuiteAnalytics\Model\Report\Session\CustomerGroupIdFilterQueryProvider - + Smile\ElasticsuiteAnalytics\Model\Search\Usage\Terms\NoResultTerms\SearchRequestBuilder @@ -122,6 +127,7 @@ Smile\ElasticsuiteAnalytics\Model\Report\Session\DateFilterQueryProvider + Smile\ElasticsuiteAnalytics\Model\Report\Session\CustomerGroupIdFilterQueryProvider diff --git a/src/module-elasticsuite-analytics/view/adminhtml/layout/smile_elasticsuite_analytics_search_usage.xml b/src/module-elasticsuite-analytics/view/adminhtml/layout/smile_elasticsuite_analytics_search_usage.xml index 087d04dba..a65aeb180 100644 --- a/src/module-elasticsuite-analytics/view/adminhtml/layout/smile_elasticsuite_analytics_search_usage.xml +++ b/src/module-elasticsuite-analytics/view/adminhtml/layout/smile_elasticsuite_analytics_search_usage.xml @@ -17,6 +17,7 @@ diff --git a/src/module-elasticsuite-analytics/view/adminhtml/web/css/source/_module.less b/src/module-elasticsuite-analytics/view/adminhtml/web/css/source/_module.less index fc3f9eafb..48bb9ec20 100644 --- a/src/module-elasticsuite-analytics/view/adminhtml/web/css/source/_module.less +++ b/src/module-elasticsuite-analytics/view/adminhtml/web/css/source/_module.less @@ -69,4 +69,17 @@ } } } + + .customer-group-selector { + color: #41362f; + float: left; + font-size: 1.3rem; + margin-top: .59rem; + margin-left: 4rem; + } + + .customer-group-selector label { + margin-right: 1rem; + font-weight: 700; + } } diff --git a/src/module-elasticsuite-analytics/view/adminhtml/web/js/report/customer-group-selector.js b/src/module-elasticsuite-analytics/view/adminhtml/web/js/report/customer-group-selector.js new file mode 100644 index 000000000..54089bc0e --- /dev/null +++ b/src/module-elasticsuite-analytics/view/adminhtml/web/js/report/customer-group-selector.js @@ -0,0 +1,43 @@ +/** + * DISCLAIMER + * + * Do not edit or add to this file if you wish to upgrade Smile ElasticSuite to newer + * versions in the future. + * + * @category Smile + * @package Smile\ElasticsuiteAnalytics + * @author Vadym Honcharuk + * @copyright 2024 Smile + * @license Open Software License ("OSL") v. 3.0 + */ + +define('Smile_ElasticsuiteAnalytics/js/report/customer-group-selector', [ + 'jquery', + 'mage/url' +], function($, urlBuilder) { + 'use strict'; + + return function() { + // !On document ready, set the selected value in the customer group dropdown. + $(document).ready(function() { + var urlParams = new URLSearchParams(window.location.search); + var selectedGroup = urlParams.get('customer_group'); + + if (selectedGroup) { + $('#customer_group').val(selectedGroup); + } + }); + + // Handle the customer group dropdown value change. + $('#customer_group').on('change', function() { + var selectedGroup = $(this).val(); + var newUrl = new URL(window.location.href); + + newUrl.searchParams.set('customer_group', selectedGroup); + + // Redirect to the new URL with the customer group filter. + window.location.href = newUrl.href; + }); + }; +}); + diff --git a/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php b/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php new file mode 100644 index 000000000..f9c591f84 --- /dev/null +++ b/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php @@ -0,0 +1,151 @@ + + * @copyright 2024 Smile + * @license Open Software License ("OSL") v. 3.0 + */ +namespace Smile\ElasticsuiteTracker\Block\Variables\Page; + +use Magento\Customer\Model\Group as CustomerGroup; +use Magento\Customer\Model\Session; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Json\Helper\Data; +use Magento\Framework\Module\Manager as ModuleManager; +use Magento\Framework\Registry; +use Magento\Framework\View\Element\Template; +use Smile\ElasticsuiteTracker\Helper\Data as TrackerHelper; + +/** + * Customer variables block for page tracking. + * + * @category Smile + * @package Smile\ElasticsuiteTracker + * @author Vadym Honcharuk + */ +class Customer extends \Smile\ElasticsuiteTracker\Block\Variables\Page\AbstractBlock +{ + /** + * @var Session + */ + private $customerSession; + + /** + * @var ModuleManager + */ + private $moduleManager; + + /** + * @var \Magento\Company\Api\CompanyRepositoryInterface|null + */ + private $companyRepository = null; + + /** + * Customer constructor. + * + * @param Template\Context $context Template Context. + * @param Data $jsonHelper Magento JSON Helper. + * @param TrackerHelper $trackerHelper Smile Tracker Helper. + * @param Registry $registry Magento Core Registry. + * @param Session $customerSession Customer Session. + * @param ModuleManager $moduleManager Magento Module Manager. + * @param array $data Additional data. + * @throws LocalizedException + */ + public function __construct( + Template\Context $context, + Data $jsonHelper, + TrackerHelper $trackerHelper, + Registry $registry, + Session $customerSession, + ModuleManager $moduleManager, + array $data = [] + ) { + $this->customerSession = $customerSession; + $this->moduleManager = $moduleManager; + + // Check if Magento_Company module is enabled before attempting to load the repository. + if ($this->moduleManager->isEnabled('Magento_Company')) { + if (interface_exists('\Magento\Company\Api\CompanyRepositoryInterface')) { + $this->companyRepository = $context->getObjectManager()->get(\Magento\Company\Api\CompanyRepositoryInterface::class); + } else { + throw new LocalizedException(__('CompanyRepositoryInterface is not available.')); + } + } + + parent::__construct($context, $jsonHelper, $trackerHelper, $registry, $data); + } + + /** + * Returns an array of customer-related variables (customer_group_id and company_id). + * + * @return array + */ + public function getVariables() + { + return array_merge( + $this->getCustomerGroupId(), + $this->getCustomerCompanyId() + ); + } + + /** + * Retrieve customer group ID. + * If the customer is logged in, fetch their group ID. + * Otherwise, assign the 'NOT LOGGED IN' group ID. + * + * @return array + */ + private function getCustomerGroupId() + { + $variables = []; + + if ($this->customerSession->isLoggedIn()) { + $customer = $this->customerSession->getCustomer(); + $variables['customer.group_id'] = $customer->getGroupId(); + } else { + // Guest user (NOT LOGGED IN). + $variables['customer.group_id'] = CustomerGroup::NOT_LOGGED_IN_ID; + } + + return $variables; + } + + /** + * Retrieve customer company ID. + * If the customer is logged in and Magento_Company module is enabled, fetch the company ID. + * Otherwise, return null for guests or when the module is not available. + * + * @return array + */ + private function getCustomerCompanyId() + { + $variables = []; + + // Check if the customer is logged in and Magento_Company is enabled. + if ($this->customerSession->isLoggedIn() && $this->companyRepository) { + $customer = $this->customerSession->getCustomer(); + + try { + // Retrieve company information by customer ID. + $company = $this->companyRepository->getByCustomerId($customer->getId()); + $variables['customer.company_id'] = $company->getId(); + } catch (NoSuchEntityException $e) { + // No company found for this customer. + $variables['customer.company_id'] = null; + } + } else { + // No company for guests or when the module is not available. + $variables['customer.company_id'] = null; + } + + return $variables; + } +} diff --git a/src/module-elasticsuite-tracker/etc/elasticsuite_indices.xml b/src/module-elasticsuite-tracker/etc/elasticsuite_indices.xml index 5cf078b30..8fd7dd34a 100644 --- a/src/module-elasticsuite-tracker/etc/elasticsuite_indices.xml +++ b/src/module-elasticsuite-tracker/etc/elasticsuite_indices.xml @@ -29,6 +29,10 @@ + + + + @@ -120,6 +124,8 @@ + + diff --git a/src/module-elasticsuite-tracker/view/frontend/layout/default.xml b/src/module-elasticsuite-tracker/view/frontend/layout/default.xml index ea0b0275d..85dcf343c 100644 --- a/src/module-elasticsuite-tracker/view/frontend/layout/default.xml +++ b/src/module-elasticsuite-tracker/view/frontend/layout/default.xml @@ -41,6 +41,9 @@ + From 2bbcb7b2e977f5ce6e7017458ceff575614970c9 Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Fri, 20 Sep 2024 13:47:31 +0300 Subject: [PATCH 02/13] [Analytics][Tracker] Feature #3340, phpcs warnings --- .../Block/Variables/Page/Customer.php | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php b/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php index f9c591f84..a8a620020 100644 --- a/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php +++ b/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php @@ -50,13 +50,14 @@ class Customer extends \Smile\ElasticsuiteTracker\Block\Variables\Page\AbstractB /** * Customer constructor. * - * @param Template\Context $context Template Context. - * @param Data $jsonHelper Magento JSON Helper. - * @param TrackerHelper $trackerHelper Smile Tracker Helper. - * @param Registry $registry Magento Core Registry. - * @param Session $customerSession Customer Session. - * @param ModuleManager $moduleManager Magento Module Manager. - * @param array $data Additional data. + * @param Template\Context $context Template Context. + * @param Data $jsonHelper Magento JSON Helper. + * @param TrackerHelper $trackerHelper Smile Tracker Helper. + * @param Registry $registry Magento Core Registry. + * @param Session $customerSession Customer Session. + * @param ModuleManager $moduleManager Magento Module Manager. + * @param array $data Additional data. + * * @throws LocalizedException */ public function __construct( From 1e4be654257c4e575e09595ad46dfc2832c3f0ee Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Fri, 20 Sep 2024 14:03:11 +0300 Subject: [PATCH 03/13] [Analytics][Tracker] Feature #3340, phpmd warnings --- .../Block/Variables/Page/Customer.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php b/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php index a8a620020..b8b4de246 100644 --- a/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php +++ b/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php @@ -59,6 +59,7 @@ class Customer extends \Smile\ElasticsuiteTracker\Block\Variables\Page\AbstractB * @param array $data Additional data. * * @throws LocalizedException + * @SuppressWarnings(PHPMD.ElseExpression) */ public function __construct( Template\Context $context, @@ -103,6 +104,7 @@ public function getVariables() * Otherwise, assign the 'NOT LOGGED IN' group ID. * * @return array + * @SuppressWarnings(PHPMD.ElseExpression) */ private function getCustomerGroupId() { @@ -125,6 +127,7 @@ private function getCustomerGroupId() * Otherwise, return null for guests or when the module is not available. * * @return array + * @SuppressWarnings(PHPMD.ElseExpression) */ private function getCustomerCompanyId() { From 107d5093a1244415c4e2bfaa434d0b980d2e774b Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Mon, 30 Sep 2024 13:17:46 +0300 Subject: [PATCH 04/13] [Analytics][Tracker] Feature #3340, code refactoring --- .../Block/Variables/Page/Customer.php | 155 ------------------ .../Model/CustomerDataTrackingManager.php | 53 ++++-- .../view/frontend/layout/default.xml | 3 - .../view/frontend/web/js/tracking.js | 3 +- 4 files changed, 41 insertions(+), 173 deletions(-) delete mode 100644 src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php diff --git a/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php b/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php deleted file mode 100644 index b8b4de246..000000000 --- a/src/module-elasticsuite-tracker/Block/Variables/Page/Customer.php +++ /dev/null @@ -1,155 +0,0 @@ - - * @copyright 2024 Smile - * @license Open Software License ("OSL") v. 3.0 - */ -namespace Smile\ElasticsuiteTracker\Block\Variables\Page; - -use Magento\Customer\Model\Group as CustomerGroup; -use Magento\Customer\Model\Session; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Framework\Json\Helper\Data; -use Magento\Framework\Module\Manager as ModuleManager; -use Magento\Framework\Registry; -use Magento\Framework\View\Element\Template; -use Smile\ElasticsuiteTracker\Helper\Data as TrackerHelper; - -/** - * Customer variables block for page tracking. - * - * @category Smile - * @package Smile\ElasticsuiteTracker - * @author Vadym Honcharuk - */ -class Customer extends \Smile\ElasticsuiteTracker\Block\Variables\Page\AbstractBlock -{ - /** - * @var Session - */ - private $customerSession; - - /** - * @var ModuleManager - */ - private $moduleManager; - - /** - * @var \Magento\Company\Api\CompanyRepositoryInterface|null - */ - private $companyRepository = null; - - /** - * Customer constructor. - * - * @param Template\Context $context Template Context. - * @param Data $jsonHelper Magento JSON Helper. - * @param TrackerHelper $trackerHelper Smile Tracker Helper. - * @param Registry $registry Magento Core Registry. - * @param Session $customerSession Customer Session. - * @param ModuleManager $moduleManager Magento Module Manager. - * @param array $data Additional data. - * - * @throws LocalizedException - * @SuppressWarnings(PHPMD.ElseExpression) - */ - public function __construct( - Template\Context $context, - Data $jsonHelper, - TrackerHelper $trackerHelper, - Registry $registry, - Session $customerSession, - ModuleManager $moduleManager, - array $data = [] - ) { - $this->customerSession = $customerSession; - $this->moduleManager = $moduleManager; - - // Check if Magento_Company module is enabled before attempting to load the repository. - if ($this->moduleManager->isEnabled('Magento_Company')) { - if (interface_exists('\Magento\Company\Api\CompanyRepositoryInterface')) { - $this->companyRepository = $context->getObjectManager()->get(\Magento\Company\Api\CompanyRepositoryInterface::class); - } else { - throw new LocalizedException(__('CompanyRepositoryInterface is not available.')); - } - } - - parent::__construct($context, $jsonHelper, $trackerHelper, $registry, $data); - } - - /** - * Returns an array of customer-related variables (customer_group_id and company_id). - * - * @return array - */ - public function getVariables() - { - return array_merge( - $this->getCustomerGroupId(), - $this->getCustomerCompanyId() - ); - } - - /** - * Retrieve customer group ID. - * If the customer is logged in, fetch their group ID. - * Otherwise, assign the 'NOT LOGGED IN' group ID. - * - * @return array - * @SuppressWarnings(PHPMD.ElseExpression) - */ - private function getCustomerGroupId() - { - $variables = []; - - if ($this->customerSession->isLoggedIn()) { - $customer = $this->customerSession->getCustomer(); - $variables['customer.group_id'] = $customer->getGroupId(); - } else { - // Guest user (NOT LOGGED IN). - $variables['customer.group_id'] = CustomerGroup::NOT_LOGGED_IN_ID; - } - - return $variables; - } - - /** - * Retrieve customer company ID. - * If the customer is logged in and Magento_Company module is enabled, fetch the company ID. - * Otherwise, return null for guests or when the module is not available. - * - * @return array - * @SuppressWarnings(PHPMD.ElseExpression) - */ - private function getCustomerCompanyId() - { - $variables = []; - - // Check if the customer is logged in and Magento_Company is enabled. - if ($this->customerSession->isLoggedIn() && $this->companyRepository) { - $customer = $this->customerSession->getCustomer(); - - try { - // Retrieve company information by customer ID. - $company = $this->companyRepository->getByCustomerId($customer->getId()); - $variables['customer.company_id'] = $company->getId(); - } catch (NoSuchEntityException $e) { - // No company found for this customer. - $variables['customer.company_id'] = null; - } - } else { - // No company for guests or when the module is not available. - $variables['customer.company_id'] = null; - } - - return $variables; - } -} diff --git a/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php b/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php index 2df256a25..d0f920bd6 100644 --- a/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php +++ b/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php @@ -13,11 +13,14 @@ */ namespace Smile\ElasticsuiteTracker\Model; -use DateTime; use Magento\Customer\Model\Session as CustomerSession; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Module\Manager as ModuleManager; /** - * Tracking Indices Manager + * Additional customer data tracking * * @category Smile * @package Smile\ElasticsuiteTracker @@ -30,12 +33,28 @@ class CustomerDataTrackingManager */ protected $customerSession; + /** + * @var \Magento\Company\Api\CompanyRepositoryInterface|null + */ + private $companyRepository = null; + /** * @param CustomerSession $customerSession Customer session + * @throws LocalizedException */ - public function __construct(CustomerSession $customerSession) + public function __construct(CustomerSession $customerSession, ModuleManager $moduleManager) { $this->customerSession = $customerSession; + // Check if Magento_Company module is enabled before attempting to load the repository. + if ($moduleManager->isEnabled('Magento_Company')) { + if (interface_exists('\Magento\Company\Api\CompanyRepositoryInterface')) { + $this->companyRepository = ObjectManager::getInstance()->get( + \Magento\Company\Api\CompanyRepositoryInterface::class + ); + } else { + throw new LocalizedException(__('CompanyRepositoryInterface is not available.')); + } + } } /** @@ -45,22 +64,28 @@ public function __construct(CustomerSession $customerSession) */ public function getCustomerDataToTrack() { + $variables = [ + 'group_id' => \Magento\Customer\Model\Group::NOT_LOGGED_IN_ID, + ]; + if (!$this->customerSession->getId()) { - return []; + return $variables; } $customer = $this->customerSession->getCustomer(); - $shippingAddress = $customer->getDefaultShippingAddress(); + $variables['group_id'] = (int) $customer->getGroupId() ?? \Magento\Customer\Model\Group::NOT_LOGGED_IN_ID; - $dob = new DateTime($customer->getDob() ?? ''); - $now = new DateTime(); + // Check if the customer is logged in and Magento_Company is enabled. + if ($this->customerSession->isLoggedIn() && (null !== $this->companyRepository)) { + try { + // Retrieve company information by customer ID. + $company = $this->companyRepository->getByCustomerId($customer->getId()); + $variables['company_id'] = (int) $company->getId(); + } catch (NoSuchEntityException $e) { + // No company found for this customer. + } + } - return [ - 'age' => (int) $now->format('Y') - (int) $dob->format('Y'), - 'gender' => $customer->getGender(), - 'zipcode' => $shippingAddress ? $shippingAddress->getPostcode() : '', - 'state' => $shippingAddress ? $shippingAddress->getRegion() : '', - 'country' => $shippingAddress ? $shippingAddress->getCountry() : '', - ]; + return $variables; } } diff --git a/src/module-elasticsuite-tracker/view/frontend/layout/default.xml b/src/module-elasticsuite-tracker/view/frontend/layout/default.xml index 85dcf343c..ea0b0275d 100644 --- a/src/module-elasticsuite-tracker/view/frontend/layout/default.xml +++ b/src/module-elasticsuite-tracker/view/frontend/layout/default.xml @@ -41,9 +41,6 @@ - diff --git a/src/module-elasticsuite-tracker/view/frontend/web/js/tracking.js b/src/module-elasticsuite-tracker/view/frontend/web/js/tracking.js index 2bc736e18..c5089e646 100644 --- a/src/module-elasticsuite-tracker/view/frontend/web/js/tracking.js +++ b/src/module-elasticsuite-tracker/view/frontend/web/js/tracking.js @@ -175,7 +175,7 @@ const smileTracker = (function () { } function getCustomerDataCodeToTrack() { - return ['age', 'gender', 'zipcode', 'state', 'country']; + return ['age', 'gender', 'zipcode', 'state', 'country', 'group_id', 'company_id']; } function setTrackerStyle(imgNode) { @@ -186,6 +186,7 @@ const smileTracker = (function () { // Append a transparent pixel to the body function sendTag(forceCollect = false) { initSession.bind(this)(); + initCustomerData.bind(this)(); if (this.config && this.config.hasOwnProperty('storeId')) { addPageVar.bind(this)('store_id', this.config.storeId); From 87a8ab905b6e25b8cb39b0b0e4c3968a46d777d5 Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Mon, 30 Sep 2024 13:22:52 +0300 Subject: [PATCH 05/13] [Analytics][Tracker] Feature #3340, phpcs warnings --- .../Model/CustomerDataTrackingManager.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php b/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php index d0f920bd6..63c52ec02 100644 --- a/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php +++ b/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php @@ -40,6 +40,7 @@ class CustomerDataTrackingManager /** * @param CustomerSession $customerSession Customer session + * @param ModuleManager $moduleManager Module manager * @throws LocalizedException */ public function __construct(CustomerSession $customerSession, ModuleManager $moduleManager) From 9c50a4341fe401781df69877297728b85c96c95b Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Mon, 30 Sep 2024 13:31:07 +0300 Subject: [PATCH 06/13] [Analytics][Tracker] Feature #3340, phpmd warnings --- .../Model/CustomerDataTrackingManager.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php b/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php index 63c52ec02..cd9c278ba 100644 --- a/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php +++ b/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php @@ -39,8 +39,12 @@ class CustomerDataTrackingManager private $companyRepository = null; /** - * @param CustomerSession $customerSession Customer session - * @param ModuleManager $moduleManager Module manager + * CustomerDataTrackingManager constructor. + * + * @SuppressWarnings(PHPMD.ElseExpression) + * + * @param CustomerSession $customerSession Customer session. + * @param ModuleManager $moduleManager Module manager. * @throws LocalizedException */ public function __construct(CustomerSession $customerSession, ModuleManager $moduleManager) From 95c4c837521b80d3b8a433b62c245fae46a624c7 Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Thu, 10 Oct 2024 15:45:57 +0300 Subject: [PATCH 07/13] [Analytics][Tracker] Feature #3340, add company_id in tracking data, minor code refactoring --- .../Report/CustomerCompanySelector.php | 105 ++++++++++++++++++ .../Model/Report/Context.php | 10 ++ .../CustomerCompanyIdFilterQueryProvider.php | 74 ++++++++++++ .../CustomerGroupIdFilterQueryProvider.php | 2 +- .../CustomerCompanyIdFilterQueryProvider.php | 81 ++++++++++++++ src/module-elasticsuite-analytics/etc/di.xml | 6 + ...le_elasticsuite_analytics_search_usage.xml | 9 +- .../view/adminhtml/requirejs-config.js | 0 .../report/customer_company_selector.phtml | 40 +++++++ .../report/customer_group_selector.phtml | 2 +- .../adminhtml/web/css/source/_module.less | 13 +++ .../js/report/customer-company-selector.js | 42 +++++++ .../Model/CustomerDataTrackingManager.php | 25 +++-- 13 files changed, 393 insertions(+), 16 deletions(-) create mode 100644 src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php create mode 100644 src/module-elasticsuite-analytics/Model/Report/Event/CustomerCompanyIdFilterQueryProvider.php create mode 100644 src/module-elasticsuite-analytics/Model/Report/Session/CustomerCompanyIdFilterQueryProvider.php create mode 100644 src/module-elasticsuite-analytics/view/adminhtml/requirejs-config.js create mode 100644 src/module-elasticsuite-analytics/view/adminhtml/templates/report/customer_company_selector.phtml create mode 100644 src/module-elasticsuite-analytics/view/adminhtml/web/js/report/customer-company-selector.js diff --git a/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php b/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php new file mode 100644 index 000000000..89e62bf61 --- /dev/null +++ b/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php @@ -0,0 +1,105 @@ + + * @copyright 2024 Smile + * @license Open Software License ("OSL") v. 3.0 + */ +namespace Smile\ElasticsuiteAnalytics\Block\Adminhtml\Report; + +use Magento\Company\Api\Data\CompanyInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\View\Element\Template; +use Magento\Framework\View\Element\Template\Context; +use Magento\Company\Api\CompanyRepositoryInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Api\SearchCriteriaBuilder; + +/** + * Block used to display customer company selector in reports. + * + * @category Smile + * @package Smile\ElasticsuiteAnalytics + * @author Vadym Honcharuk + */ +class CustomerCompanySelector extends Template +{ + /** + * Company status configuration path. + * + * @var string + */ + const CONFIG_IS_B2B_COMPANY_ACTIVE_XPATH = 'btob/website_configuration/company_active'; + + /** + * @var CompanyRepositoryInterface + */ + protected $companyRepository; + + /** + * @var ScopeConfigInterface + */ + protected $scopeConfig; + + /** + * @var SearchCriteriaBuilder + */ + protected $searchCriteriaBuilder; + + /** + * CustomerCompanySelector constructor. + * + * @param Context $context The template context. + * @param CompanyRepositoryInterface $companyRepository The company repository. + * @param ScopeConfigInterface $scopeConfig Scope configuration. + * @param SearchCriteriaBuilder $searchCriteriaBuilder The search criteria builder. + * @param array $data Additional block data. + */ + public function __construct( + Context $context, + CompanyRepositoryInterface $companyRepository, + ScopeConfigInterface $scopeConfig, + SearchCriteriaBuilder $searchCriteriaBuilder, + array $data = [] + ) { + $this->companyRepository = $companyRepository; + $this->scopeConfig = $scopeConfig; + $this->searchCriteriaBuilder = $searchCriteriaBuilder; + parent::__construct($context, $data); + } + + /** + * Check if the Company feature is enabled. + * + * @return bool + */ + public function isCompanyEnabled() + { + return $this->scopeConfig->isSetFlag(self::CONFIG_IS_B2B_COMPANY_ACTIVE_XPATH, + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + + /** + * Get the list of companies if the Company feature is enabled. + * + * @return CompanyInterface[]|array + * @throws LocalizedException + */ + public function getCompaniesList() + { + if ($this->isCompanyEnabled()) { + $searchCriteria = $this->searchCriteriaBuilder->create(); + + return $this->companyRepository->getList($searchCriteria)->getItems(); // Fetch company list. + } + + return []; + } +} diff --git a/src/module-elasticsuite-analytics/Model/Report/Context.php b/src/module-elasticsuite-analytics/Model/Report/Context.php index ede55322b..74ffd9d49 100644 --- a/src/module-elasticsuite-analytics/Model/Report/Context.php +++ b/src/module-elasticsuite-analytics/Model/Report/Context.php @@ -76,6 +76,16 @@ public function getCustomerGroupId() return $this->request->getParam('customer_group'); } + /** + * Get customer company ID. + * + * @return mixed + */ + public function getCustomerCompanyId() + { + return $this->request->getParam('company_id'); + } + /** * Get date range. * diff --git a/src/module-elasticsuite-analytics/Model/Report/Event/CustomerCompanyIdFilterQueryProvider.php b/src/module-elasticsuite-analytics/Model/Report/Event/CustomerCompanyIdFilterQueryProvider.php new file mode 100644 index 000000000..ad3cbe19d --- /dev/null +++ b/src/module-elasticsuite-analytics/Model/Report/Event/CustomerCompanyIdFilterQueryProvider.php @@ -0,0 +1,74 @@ + + * @copyright 2024 Smile + * @license Open Software License ("OSL") v. 3.0 + */ +namespace Smile\ElasticsuiteAnalytics\Model\Report\Event; + +use Smile\ElasticsuiteAnalytics\Model\Report\QueryProviderInterface; +use Smile\ElasticsuiteCore\Search\Request\QueryInterface; +use Smile\ElasticsuiteCore\Search\Request\Query\QueryFactory; +use Smile\ElasticsuiteAnalytics\Model\Report\Context; + +/** + * Customer company id filter query provider. + * + * @category Smile + * @package Smile\ElasticsuiteAnalytics + */ +class CustomerCompanyIdFilterQueryProvider implements QueryProviderInterface +{ + /** + * @var QueryFactory + */ + private $queryFactory; + + /** + * @var Context + */ + private $context; + + /** + * CustomerCompanyIdFilterQueryProvider constructor. + * + * @param QueryFactory $queryFactory Query factory. + * @param Context $context Report context. + */ + public function __construct(QueryFactory $queryFactory, Context $context) + { + $this->queryFactory = $queryFactory; + $this->context = $context; + } + + /** + * {@inheritDoc} + */ + public function getQuery() + { + // Get customer company ID from the context. + $customerCompanyId = $this->context->getCustomerCompanyId(); + + // Check if customer company ID is set and not 'all'. + if ($customerCompanyId !== 'all' && $customerCompanyId !== null) { + // Return a TERM query for the customer company ID. + return $this->queryFactory->create( + QueryInterface::TYPE_TERM, + [ + 'field' => 'customer.company_id', + 'value' => (int) $customerCompanyId, + ] + ); + } + + // If 'all' is selected or no customer company ID is set, return null (no filtering). + return null; + } +} diff --git a/src/module-elasticsuite-analytics/Model/Report/Event/CustomerGroupIdFilterQueryProvider.php b/src/module-elasticsuite-analytics/Model/Report/Event/CustomerGroupIdFilterQueryProvider.php index a1ce55ce5..74fe09112 100644 --- a/src/module-elasticsuite-analytics/Model/Report/Event/CustomerGroupIdFilterQueryProvider.php +++ b/src/module-elasticsuite-analytics/Model/Report/Event/CustomerGroupIdFilterQueryProvider.php @@ -37,7 +37,7 @@ class CustomerGroupIdFilterQueryProvider implements QueryProviderInterface private $context; /** - * DateFilterQueryProvider constructor. + * CustomerGroupIdFilterQueryProvider constructor. * * @param QueryFactory $queryFactory Query factory. * @param Context $context Report context. diff --git a/src/module-elasticsuite-analytics/Model/Report/Session/CustomerCompanyIdFilterQueryProvider.php b/src/module-elasticsuite-analytics/Model/Report/Session/CustomerCompanyIdFilterQueryProvider.php new file mode 100644 index 000000000..6b933c70f --- /dev/null +++ b/src/module-elasticsuite-analytics/Model/Report/Session/CustomerCompanyIdFilterQueryProvider.php @@ -0,0 +1,81 @@ + + * @copyright 2024 Smile + * @license Open Software License ("OSL") v. 3.0 + */ +namespace Smile\ElasticsuiteAnalytics\Model\Report\Session; + +use Smile\ElasticsuiteAnalytics\Model\Report\QueryProviderInterface; +use Smile\ElasticsuiteCore\Search\Request\QueryInterface; +use Smile\ElasticsuiteCore\Search\Request\Query\QueryFactory; +use Smile\ElasticsuiteAnalytics\Model\Report\Context; + +/** + * Customer company id filter query provider. + * + * @category Smile + * @package Smile\ElasticsuiteAnalytics + */ +class CustomerCompanyIdFilterQueryProvider implements QueryProviderInterface +{ + /** + * @var QueryFactory + */ + private $queryFactory; + + /** + * @var Context + */ + private $context; + + /** + * CustomerCompanyIdFilterQueryProvider constructor. + * + * @param QueryFactory $queryFactory Query factory. + * @param Context $context Report context. + */ + public function __construct(QueryFactory $queryFactory, Context $context) + { + $this->queryFactory = $queryFactory; + $this->context = $context; + } + + /** + * {@inheritDoc} + */ + public function getQuery() + { + // Get customer company ID from the context. + $customerCompanyId = $this->context->getCustomerCompanyId(); + + // Check if customer company ID is set and not 'all'. + if ($customerCompanyId !== 'all' && $customerCompanyId !== null) { + // Return a TERM query for the customer company ID. + return $this->queryFactory->create( + QueryInterface::TYPE_BOOL, + [ + 'must' => [ + $this->queryFactory->create( + QueryInterface::TYPE_TERM, + [ + 'field' => 'customer_company_id', + 'value' => (int) $customerCompanyId, + ] + ), + ], + ] + ); + } + + // If 'all' is selected or no customer company ID is set, return null (no filtering). + return null; + } +} diff --git a/src/module-elasticsuite-analytics/etc/di.xml b/src/module-elasticsuite-analytics/etc/di.xml index 904617e20..63c07dbe0 100755 --- a/src/module-elasticsuite-analytics/etc/di.xml +++ b/src/module-elasticsuite-analytics/etc/di.xml @@ -24,6 +24,7 @@ Smile\ElasticsuiteAnalytics\Model\Report\Event\DateFilterQueryProvider Smile\ElasticsuiteAnalytics\Model\Report\Event\CustomerGroupIdFilterQueryProvider + Smile\ElasticsuiteAnalytics\Model\Report\Event\CustomerCompanyIdFilterQueryProvider @@ -43,6 +44,7 @@ Smile\ElasticsuiteAnalytics\Model\Report\Session\DateFilterQueryProvider Smile\ElasticsuiteAnalytics\Model\Report\Session\CustomerGroupIdFilterQueryProvider + Smile\ElasticsuiteAnalytics\Model\Report\Session\CustomerCompanyIdFilterQueryProvider tracking_log_session @@ -63,6 +65,7 @@ Smile\ElasticsuiteAnalytics\Model\Report\Event\DateFilterQueryProvider Smile\ElasticsuiteAnalytics\Model\Report\Event\CustomerGroupIdFilterQueryProvider + Smile\ElasticsuiteAnalytics\Model\Report\Event\CustomerCompanyIdFilterQueryProvider @@ -86,6 +89,7 @@ Smile\ElasticsuiteAnalytics\Model\Search\Usage\Terms\SpellcheckedTerms\QueryProvider Smile\ElasticsuiteAnalytics\Model\Report\Event\DateFilterQueryProvider Smile\ElasticsuiteAnalytics\Model\Report\Event\CustomerGroupIdFilterQueryProvider + Smile\ElasticsuiteAnalytics\Model\Report\Event\CustomerCompanyIdFilterQueryProvider @@ -109,6 +113,7 @@ Smile\ElasticsuiteAnalytics\Model\Report\Session\DateFilterQueryProvider Smile\ElasticsuiteAnalytics\Model\Report\Session\CustomerGroupIdFilterQueryProvider + Smile\ElasticsuiteAnalytics\Model\Report\Session\CustomerCompanyIdFilterQueryProvider @@ -128,6 +133,7 @@ Smile\ElasticsuiteAnalytics\Model\Report\Session\DateFilterQueryProvider Smile\ElasticsuiteAnalytics\Model\Report\Session\CustomerGroupIdFilterQueryProvider + Smile\ElasticsuiteAnalytics\Model\Report\Session\CustomerCompanyIdFilterQueryProvider diff --git a/src/module-elasticsuite-analytics/view/adminhtml/layout/smile_elasticsuite_analytics_search_usage.xml b/src/module-elasticsuite-analytics/view/adminhtml/layout/smile_elasticsuite_analytics_search_usage.xml index a65aeb180..0c3b80a1e 100644 --- a/src/module-elasticsuite-analytics/view/adminhtml/layout/smile_elasticsuite_analytics_search_usage.xml +++ b/src/module-elasticsuite-analytics/view/adminhtml/layout/smile_elasticsuite_analytics_search_usage.xml @@ -17,7 +17,6 @@ diff --git a/src/module-elasticsuite-analytics/view/adminhtml/templates/report/customer_group_selector.phtml b/src/module-elasticsuite-analytics/view/adminhtml/templates/report/customer_group_selector.phtml index de860607f..b004c3bc5 100644 --- a/src/module-elasticsuite-analytics/view/adminhtml/templates/report/customer_group_selector.phtml +++ b/src/module-elasticsuite-analytics/view/adminhtml/templates/report/customer_group_selector.phtml @@ -32,7 +32,7 @@ $customerGroups = $block->getCustomerGroups(); diff --git a/src/module-elasticsuite-analytics/view/adminhtml/web/css/source/_module.less b/src/module-elasticsuite-analytics/view/adminhtml/web/css/source/_module.less index 48bb9ec20..bbe2edc27 100644 --- a/src/module-elasticsuite-analytics/view/adminhtml/web/css/source/_module.less +++ b/src/module-elasticsuite-analytics/view/adminhtml/web/css/source/_module.less @@ -82,4 +82,17 @@ margin-right: 1rem; font-weight: 700; } + + .customer-company-selector { + color: #41362f; + float: left; + font-size: 1.3rem; + margin-top: .59rem; + margin-left: 2rem; + } + + .customer-company-selector label { + margin-right: 1rem; + font-weight: 700; + } } diff --git a/src/module-elasticsuite-analytics/view/adminhtml/web/js/report/customer-company-selector.js b/src/module-elasticsuite-analytics/view/adminhtml/web/js/report/customer-company-selector.js new file mode 100644 index 000000000..40c5bb880 --- /dev/null +++ b/src/module-elasticsuite-analytics/view/adminhtml/web/js/report/customer-company-selector.js @@ -0,0 +1,42 @@ +/** + * DISCLAIMER + * + * Do not edit or add to this file if you wish to upgrade Smile ElasticSuite to newer + * versions in the future. + * + * @category Smile + * @package Smile\ElasticsuiteAnalytics + * @author Vadym Honcharuk + * @copyright 2024 Smile + * @license Open Software License ("OSL") v. 3.0 + */ + +define('Smile_ElasticsuiteAnalytics/js/report/customer-company-selector', [ + 'jquery', + 'mage/url' +], function($, urlBuilder) { + 'use strict'; + + return function() { + // On document ready, set the selected value in the company dropdown. + $(document).ready(function() { + var urlParams = new URLSearchParams(window.location.search); + var selectedCompany = urlParams.get('company_id'); + + if (selectedCompany) { + $('#company_id').val(selectedCompany); + } + }); + + // Handle the company dropdown value change. + $('#company_id').on('change', function() { + var selectedCompany = $(this).val(); + var newUrl = new URL(window.location.href); + + newUrl.searchParams.set('company_id', selectedCompany); + + // Redirect to the new URL with the company filter. + window.location.href = newUrl.href; + }); + }; +}); diff --git a/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php b/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php index cd9c278ba..2119987d1 100644 --- a/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php +++ b/src/module-elasticsuite-tracker/Model/CustomerDataTrackingManager.php @@ -34,9 +34,9 @@ class CustomerDataTrackingManager protected $customerSession; /** - * @var \Magento\Company\Api\CompanyRepositoryInterface|null + * @var \Magento\Company\Api\CompanyManagementInterface|null */ - private $companyRepository = null; + private $companyManagement = null; /** * CustomerDataTrackingManager constructor. @@ -52,12 +52,12 @@ public function __construct(CustomerSession $customerSession, ModuleManager $mod $this->customerSession = $customerSession; // Check if Magento_Company module is enabled before attempting to load the repository. if ($moduleManager->isEnabled('Magento_Company')) { - if (interface_exists('\Magento\Company\Api\CompanyRepositoryInterface')) { - $this->companyRepository = ObjectManager::getInstance()->get( - \Magento\Company\Api\CompanyRepositoryInterface::class + if (interface_exists('\Magento\Company\Api\CompanyManagementInterface')) { + $this->companyManagement = ObjectManager::getInstance()->get( + \Magento\Company\Api\CompanyManagementInterface::class ); } else { - throw new LocalizedException(__('CompanyRepositoryInterface is not available.')); + throw new LocalizedException(__('CompanyManagementInterface is not available.')); } } } @@ -80,12 +80,15 @@ public function getCustomerDataToTrack() $customer = $this->customerSession->getCustomer(); $variables['group_id'] = (int) $customer->getGroupId() ?? \Magento\Customer\Model\Group::NOT_LOGGED_IN_ID; - // Check if the customer is logged in and Magento_Company is enabled. - if ($this->customerSession->isLoggedIn() && (null !== $this->companyRepository)) { + if ($this->customerSession->isLoggedIn() && (null !== $this->companyManagement)) { try { - // Retrieve company information by customer ID. - $company = $this->companyRepository->getByCustomerId($customer->getId()); - $variables['company_id'] = (int) $company->getId(); + // Use CompanyUserManager to retrieve company information by customer ID. + $company = $this->companyManagement->getByCustomerId($customer->getId()); + + // If company is found, add the company ID to the variables array. + if ($company) { + $variables['company_id'] = (int) $company->getId(); + } } catch (NoSuchEntityException $e) { // No company found for this customer. } From 11217b8504cea82fa8944bacbfe0da40c1f527cf Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Thu, 10 Oct 2024 15:47:20 +0300 Subject: [PATCH 08/13] [Analytics][Tracker] Feature #3340, move scripts initialization to requirejs-config --- .../view/adminhtml/requirejs-config.js | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/module-elasticsuite-analytics/view/adminhtml/requirejs-config.js b/src/module-elasticsuite-analytics/view/adminhtml/requirejs-config.js index e69de29bb..e713a74b5 100644 --- a/src/module-elasticsuite-analytics/view/adminhtml/requirejs-config.js +++ b/src/module-elasticsuite-analytics/view/adminhtml/requirejs-config.js @@ -0,0 +1,20 @@ +/** + * DISCLAIMER + * + * Do not edit or add to this file if you wish to upgrade Smile ElasticSuite to newer + * versions in the future. + * + * @category Smile + * @package Smile\ElasticsuiteAnalytics + * @author Vadym Honcharuk + * @copyright 2024 Smile + * @license Open Software License ("OSL") v. 3.0 + */ +var config = { + map: { + '*': { + 'customerGroupSelector': 'Smile_ElasticsuiteAnalytics/js/report/customer-group-selector', + 'customerCompanySelector': 'Smile_ElasticsuiteAnalytics/js/report/customer-company-selector' + } + } +}; From a44e1e1d1a967d751dc10fdc9be3b2d6f4f07fe4 Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Thu, 10 Oct 2024 15:50:09 +0300 Subject: [PATCH 09/13] [Analytics][Tracker] Feature #3340, added customer data to the logging 'add to cart' events --- .../Plugin/QuotePlugin.php | 98 ++++++++++++++++--- 1 file changed, 87 insertions(+), 11 deletions(-) diff --git a/src/module-elasticsuite-tracker/Plugin/QuotePlugin.php b/src/module-elasticsuite-tracker/Plugin/QuotePlugin.php index 2adfbb5d9..f84e6da0f 100644 --- a/src/module-elasticsuite-tracker/Plugin/QuotePlugin.php +++ b/src/module-elasticsuite-tracker/Plugin/QuotePlugin.php @@ -14,6 +14,8 @@ namespace Smile\ElasticsuiteTracker\Plugin; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\View\Layout\PageType\Config as PageTypeConfig; use Magento\Quote\Model\Quote; @@ -46,6 +48,16 @@ class QuotePlugin */ private $pageTypeConfig; + /** + * @var \Magento\Customer\Model\Session + */ + private $customerSession; + + /** + * @var \Magento\Company\Api\CompanyManagementInterface|null + */ + private $companyManagement = null; + /** * @var \Psr\Log\LoggerInterface */ @@ -54,24 +66,42 @@ class QuotePlugin /** * Constructor. * - * @param \Smile\ElasticsuiteTracker\Api\CustomerTrackingServiceInterface $service Tracker service. - * @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager Cookie manager. - * @param \Smile\ElasticsuiteTracker\Helper\Data $trackerHelper Tracker helper. - * @param \Magento\Framework\View\Layout\PageType\Config $pageTypeConfig The Page Type Configuration - * @param \Psr\Log\LoggerInterface $logger Logger. + * @param \Smile\ElasticsuiteTracker\Api\CustomerTrackingServiceInterface $service Tracker service. + * @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager Cookie manager. + * @param \Smile\ElasticsuiteTracker\Helper\Data $trackerHelper Tracker helper. + * @param \Magento\Framework\View\Layout\PageType\Config $pageTypeConfig Page type configuration. + * @param \Magento\Customer\Model\Session $customerSession Customer session. + * @param \Psr\Log\LoggerInterface $logger Logger. + * @param \Magento\Framework\Module\Manager $moduleManager Module manager. + * + * @throws LocalizedException */ public function __construct( \Smile\ElasticsuiteTracker\Api\CustomerTrackingServiceInterface $service, \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager, \Smile\ElasticsuiteTracker\Helper\Data $trackerHelper, \Magento\Framework\View\Layout\PageType\Config $pageTypeConfig, - \Psr\Log\LoggerInterface $logger + \Magento\Customer\Model\Session $customerSession, + \Psr\Log\LoggerInterface $logger, + \Magento\Framework\Module\Manager $moduleManager ) { $this->service = $service; $this->cookieManager = $cookieManager; $this->trackerHelper = $trackerHelper; $this->pageTypeConfig = $pageTypeConfig; + $this->customerSession = $customerSession; $this->logger = $logger; + + // Check if Magento_Company module is enabled before attempting to load the repository. + if ($moduleManager->isEnabled('Magento_Company')) { + if (interface_exists('\Magento\Company\Api\CompanyManagementInterface')) { + $this->companyManagement = ObjectManager::getInstance()->get( + \Magento\Company\Api\CompanyManagementInterface::class + ); + } else { + throw new LocalizedException(__('CompanyManagementInterface is not available.')); + } + } } /** @@ -94,7 +124,14 @@ public function afterAddProduct( /** @var \Magento\Quote\Model\Quote\Item $result */ $product = $result->getProduct(); if ($product !== null) { - $this->logEvent($product->getId(), $product->getStoreId()); + // Retrieve the customer group ID from the product object. + $customerGroupId = $product->getCustomerGroupId(); + + // Retrieve the customer company ID rom the customer session. + $companyId = $this->getCompanyId(); + + // Log event with product, store, customer group and company ids. + $this->logEvent($product->getId(), $product->getStoreId(), $customerGroupId, $companyId); } } } catch (\Exception $e) { @@ -109,12 +146,14 @@ public function afterAddProduct( /** * Log the event. * - * @param int $productId Product Id - * @param int $storeId Store Id + * @param int $productId Product ID. + * @param int $storeId Store ID. + * @param int|null $customerGroupId Customer Group ID (null if non-logged-in). + * @param int|null $companyId Customer Company ID (null if non-logged-in or company is not available). * * @return void */ - private function logEvent(int $productId, int $storeId): void + private function logEvent(int $productId, int $storeId, ?int $customerGroupId, ?int $companyId): void { $pageData = [ 'identifier' => 'checkout_cart_add', @@ -123,11 +162,48 @@ private function logEvent(int $productId, int $storeId): void $pageData['store_id'] = $storeId; $pageData['cart']['product_id'] = $productId; - $eventData = ['page' => $pageData, 'session' => $this->getSessionData()]; + // Add customer information. + $customerData = []; + if ($customerGroupId !== null) { + $customerData['group_id'] = $customerGroupId; + } + if ($companyId !== null) { + $customerData['company_id'] = $companyId; + } + + $eventData = [ + 'page' => $pageData, + 'customer' => $customerData, + 'session' => $this->getSessionData(), + ]; $this->service->addEvent($eventData); } + /** + * Retrieve the company ID from the customer session. + * + * If the customer has an associated company, return the company ID, otherwise return null if no company is assigned. + * + * @return int|null + */ + private function getCompanyId(): ?int + { + if ($this->customerSession->isLoggedIn() && (null !== $this->companyManagement)) { + try { + $customer = $this->customerSession->getCustomer(); + $company = $this->companyManagement->getByCustomerId($customer->getId()); + + return $company ? $company->getId() : null; + } catch (\Exception $e) { + return null; + } + } + + // Return null if the user is non-logged-in or companyManagement is not available. + return null; + } + /** * Read session data. * From 99d906fa01961691febe1244e93bd0e031b38eb2 Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Thu, 10 Oct 2024 16:02:35 +0300 Subject: [PATCH 10/13] [Analytics][Tracker] Feature #3340, phpcs warning --- .../Block/Adminhtml/Report/CustomerCompanySelector.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php b/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php index 89e62bf61..840c172ca 100644 --- a/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php +++ b/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php @@ -81,7 +81,8 @@ public function __construct( */ public function isCompanyEnabled() { - return $this->scopeConfig->isSetFlag(self::CONFIG_IS_B2B_COMPANY_ACTIVE_XPATH, + return $this->scopeConfig->isSetFlag( + self::CONFIG_IS_B2B_COMPANY_ACTIVE_XPATH, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); } From 736ce976172d9fa1b357c670f0b047474babf2b5 Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Thu, 10 Oct 2024 16:09:50 +0300 Subject: [PATCH 11/13] [Analytics][Tracker] Feature #3340, phpmd warning --- src/module-elasticsuite-tracker/Plugin/QuotePlugin.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/module-elasticsuite-tracker/Plugin/QuotePlugin.php b/src/module-elasticsuite-tracker/Plugin/QuotePlugin.php index f84e6da0f..626c168bd 100644 --- a/src/module-elasticsuite-tracker/Plugin/QuotePlugin.php +++ b/src/module-elasticsuite-tracker/Plugin/QuotePlugin.php @@ -22,6 +22,8 @@ /** * Log add to cart events into the event queue. * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * * @category Smile * @package Smile\ElasticsuiteTracker * @author Aurelien FOUCRET @@ -66,6 +68,8 @@ class QuotePlugin /** * Constructor. * + * @SuppressWarnings(PHPMD.ElseExpression) + * * @param \Smile\ElasticsuiteTracker\Api\CustomerTrackingServiceInterface $service Tracker service. * @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager Cookie manager. * @param \Smile\ElasticsuiteTracker\Helper\Data $trackerHelper Tracker helper. From d7c36accd389f06669668b3ffec516919ce1641b Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Mon, 28 Oct 2024 19:33:18 +0200 Subject: [PATCH 12/13] [Analytics][Tracker] Feature #3340, add repository existence check before loading, minor styling fixes --- .../Report/CustomerCompanySelector.php | 37 +++++++++++++------ .../adminhtml/web/css/source/_module.less | 8 ++++ 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php b/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php index 840c172ca..b968c499a 100644 --- a/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php +++ b/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php @@ -13,13 +13,14 @@ */ namespace Smile\ElasticsuiteAnalytics\Block\Adminhtml\Report; -use Magento\Company\Api\Data\CompanyInterface; +use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ObjectManager; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Module\Manager as ModuleManager; use Magento\Framework\View\Element\Template; use Magento\Framework\View\Element\Template\Context; -use Magento\Company\Api\CompanyRepositoryInterface; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\Api\SearchCriteriaBuilder; + /** * Block used to display customer company selector in reports. @@ -37,11 +38,6 @@ class CustomerCompanySelector extends Template */ const CONFIG_IS_B2B_COMPANY_ACTIVE_XPATH = 'btob/website_configuration/company_active'; - /** - * @var CompanyRepositoryInterface - */ - protected $companyRepository; - /** * @var ScopeConfigInterface */ @@ -52,25 +48,42 @@ class CustomerCompanySelector extends Template */ protected $searchCriteriaBuilder; + /** + * @var \Magento\Company\Api\CompanyRepositoryInterface|null + */ + private $companyRepository = null; + /** * CustomerCompanySelector constructor. * * @param Context $context The template context. - * @param CompanyRepositoryInterface $companyRepository The company repository. + * @param ModuleManager $moduleManager Module manager. * @param ScopeConfigInterface $scopeConfig Scope configuration. * @param SearchCriteriaBuilder $searchCriteriaBuilder The search criteria builder. * @param array $data Additional block data. + * @throws LocalizedException */ public function __construct( Context $context, - CompanyRepositoryInterface $companyRepository, + ModuleManager $moduleManager, ScopeConfigInterface $scopeConfig, SearchCriteriaBuilder $searchCriteriaBuilder, array $data = [] ) { - $this->companyRepository = $companyRepository; $this->scopeConfig = $scopeConfig; $this->searchCriteriaBuilder = $searchCriteriaBuilder; + + // Check if Magento_Company module is enabled before attempting to load the repository. + if ($moduleManager->isEnabled('Magento_Company')) { + if (interface_exists('\Magento\Company\Api\CompanyRepositoryInterface')) { + $this->companyRepository = ObjectManager::getInstance()->get( + \Magento\Company\Api\CompanyRepositoryInterface::class + ); + } else { + throw new LocalizedException(__('CompanyRepositoryInterface is not available.')); + } + } + parent::__construct($context, $data); } diff --git a/src/module-elasticsuite-analytics/view/adminhtml/web/css/source/_module.less b/src/module-elasticsuite-analytics/view/adminhtml/web/css/source/_module.less index bbe2edc27..2fef48e3e 100644 --- a/src/module-elasticsuite-analytics/view/adminhtml/web/css/source/_module.less +++ b/src/module-elasticsuite-analytics/view/adminhtml/web/css/source/_module.less @@ -70,6 +70,10 @@ } } + .page-main-actions { + display: block; + } + .customer-group-selector { color: #41362f; float: left; @@ -95,4 +99,8 @@ margin-right: 1rem; font-weight: 700; } + + .page-actions-inner { + margin-top: .59rem; + } } From 244996dd833fb019726c338d492af132b41ced58 Mon Sep 17 00:00:00 2001 From: Vadym Honcharuk Date: Mon, 28 Oct 2024 19:40:46 +0200 Subject: [PATCH 13/13] [Analytics][Tracker] Feature #3340, phpcs warning --- .../Adminhtml/Report/CustomerCompanySelector.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php b/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php index b968c499a..abdd81d2a 100644 --- a/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php +++ b/src/module-elasticsuite-analytics/Block/Adminhtml/Report/CustomerCompanySelector.php @@ -21,7 +21,6 @@ use Magento\Framework\View\Element\Template; use Magento\Framework\View\Element\Template\Context; - /** * Block used to display customer company selector in reports. * @@ -56,11 +55,13 @@ class CustomerCompanySelector extends Template /** * CustomerCompanySelector constructor. * - * @param Context $context The template context. - * @param ModuleManager $moduleManager Module manager. - * @param ScopeConfigInterface $scopeConfig Scope configuration. - * @param SearchCriteriaBuilder $searchCriteriaBuilder The search criteria builder. - * @param array $data Additional block data. + * @SuppressWarnings(PHPMD.ElseExpression) + * + * @param Context $context The template context. + * @param ModuleManager $moduleManager Module manager. + * @param ScopeConfigInterface $scopeConfig Scope configuration. + * @param SearchCriteriaBuilder $searchCriteriaBuilder The search criteria builder. + * @param array $data Additional block data. * @throws LocalizedException */ public function __construct(