first commit

This commit is contained in:
2024-12-17 13:43:22 +01:00
commit 8e6cd8b410
21292 changed files with 3514826 additions and 0 deletions

3
modules/ps_metrics/.env Normal file
View File

@@ -0,0 +1,3 @@
ACTIVE_CACHE="true"
ANALYTICS_API="https://analytics-api.psessentials.net"
SEGMENT_API_KEY="Vxk9VEvePTRlBmjkjzbUG6saW5yAmgb2"

View File

@@ -0,0 +1,57 @@
![alt tag](views/img/logo-ps-metrics.png)
## About
Module for Prestashop Metrics
## Contributing
Prestashop Metrics is compatible with all versions of PrestaShop 1.7 and 1.6
### Requirements
Contributors **must** follow the following rules:
- **Make your Pull Request on the "master" branch**.
- Do NOT update the module's version number.
- Follow [the coding standards][1].
- Commit rules
_ref : https://www.conventionalcommits.org/en/v1.0.0/#summary_
**_type[optional scope]:_**
**_[optional body]_**
**_[optional footer(s)]_**
The commit contains the following structural elements, to communicate intent to the consumers of your library:
- fix: a commit of the type fix patches a bug in your codebase (this correlates with PATCH in semantic versioning).
- feat: a commit of the type feat introduces a new feature to the codebase (this correlates with MINOR in semantic versioning).
- BREAKING CHANGE: a commit that has a footer BREAKING CHANGE:, or appends a ! after the type/scope, introduces a breaking API change (correlating with MAJOR in semantic versioning). A BREAKING CHANGE can be part of commits of any type.
- types other than fix: and feat: are allowed, for example @commitlint/config-conventional (based on the the Angular convention) recommends build:, chore:, ci:, docs:, style:, refactor:, perf:, test:, and others.
- footers other than BREAKING CHANGE: may be provided and follow a convention similar to git trailer format.
### Process in details
Contributors wishing to edit a module's files should follow the following process:
1. Create your GitHub account, if you do not have one already.
2. Fork the ps_googleanalytics project to your GitHub account.
3. Clone your fork to your local machine in the `/modules` directory of your PrestaShop installation.
4. Create a branch in your local clone of the module for your changes.
5. Change the files in your branch. Be sure to follow [the coding standards][1]!
6. Push your changed branch to your fork in your GitHub account.
7. Create a pull request for your changes **on the _'dev'_ branch** of the module's project. Be sure to follow [the commit message norm][2] in your pull request. If you need help to make a pull request, read the [Github help page about creating pull requests][3].
8. Wait for one of the core developers either to include your change in the codebase, or to comment on possible improvements you should make to your code.
That's it: you have contributed to this open-source project! Congratulations!
[1]: http://doc.prestashop.com/display/PS16/Coding+Standards
[2]: http://doc.prestashop.com/display/PS16/How+to+write+a+commit+message
[3]: https://help.github.com/articles/using-pull-requests
[4]: https://support.google.com/analytics/answer/6032539

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" ?>
<module>
<name>ps_metrics</name>
<displayName><![CDATA[Prestashop Metrics]]></displayName>
<version><![CDATA[1.3.3]]></version>
<description><![CDATA[Module for Prestashop Metrics.]]></description>
<author><![CDATA[PrestaShop]]></author>
<tab><![CDATA[advertising_marketing]]></tab>
<confirmUninstall><![CDATA[Are you sure you want to uninstall this module?]]></confirmUninstall>
<is_configurable>1</is_configurable>
<need_instance>0</need_instance>
<limited_countries></limited_countries>
</module>

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,333 @@
services:
ps_metrics.module:
class: 'Ps_metrics'
factory: [ 'Module', 'getInstanceByName' ]
arguments:
- 'ps_metrics'
ps_metrics.context.prestashop:
class: 'PrestaShop\Module\Ps_metrics\Context\PrestaShopContext'
public: true
ps_metrics.tracker.segment:
class: 'PrestaShop\Module\Ps_metrics\Tracker\Segment'
arguments:
- '@ps_metrics.env.segment'
- '@ps_metrics.helper.segment'
- '@ps_metrics.context.prestashop'
- '@ps_metrics.helper.shop'
ps_metrics.env.segment:
class: 'PrestaShop\Module\Ps_metrics\Environment\SegmentEnv'
ps_metrics.env.cache:
class: 'PrestaShop\Module\Ps_metrics\Environment\CacheEnv'
ps_metrics.env.analytics:
class: 'PrestaShop\Module\Ps_metrics\Environment\AnalyticsEnv'
ps_metrics.validation.retrievedata:
class: 'PrestaShop\Module\Ps_metrics\Validation\RetrieveData'
ps_metrics.validation.processselectaccountanalytics:
class: 'PrestaShop\Module\Ps_metrics\Validation\SelectAccountAnalytics'
ps_metrics.translation.dashboard:
class: 'PrestaShop\Module\Ps_metrics\Translation\DashboardTranslation'
arguments:
- '@ps_metrics.module'
- '@ps_metrics.context.prestashop'
ps_metrics.translation.settings:
class: 'PrestaShop\Module\Ps_metrics\Translation\SettingsTranslation'
arguments:
- '@ps_metrics.module'
- '@ps_metrics.context.prestashop'
ps_metrics.cache.data:
class: 'PrestaShop\Module\Ps_metrics\Cache\DataCache'
arguments:
- '@ps_metrics.cache.directory'
- '@ps_metrics.env.cache'
- '@ps_metrics.helper.json'
- '@ps_metrics.helper.logger'
ps_metrics.cache.directory:
class: 'PrestaShop\Module\Ps_metrics\Cache\DirectoryCache'
ps_metrics.adapter.link:
class: 'PrestaShop\Module\Ps_metrics\Adapter\LinkAdapter'
arguments:
- '@ps_metrics.module'
- '@ps_metrics.context.prestashop'
- '@ps_metrics.helper.tools'
ps_metrics.repository.configuration:
class: 'PrestaShop\Module\Ps_metrics\Repository\ConfigurationRepository'
arguments:
- '@ps_metrics.context.prestashop'
ps_metrics.repository.hookmodule:
class: 'PrestaShop\Module\Ps_metrics\Repository\HookModuleRepository'
ps_metrics.repository.orders:
class: 'PrestaShop\Module\Ps_metrics\Repository\OrdersRepository'
arguments:
- '@ps_metrics.helper.db'
- '@ps_metrics.helper.shop'
- '@ps_metrics.context.prestashop'
-
ps_metrics.repository.payment:
class: 'PrestaShop\Module\Ps_metrics\Repository\PaymentRepository'
ps_metrics.provider.shops:
class: 'PrestaShop\Module\Ps_metrics\Provider\ShopsProvider'
arguments:
- '@ps_metrics.helper.tools'
- '@ps_metrics.helper.shop'
ps_metrics.provider.analyticsaccountslist:
class: 'PrestaShop\Module\Ps_metrics\Provider\AnalyticsAccountsListProvider'
arguments:
- '@ps_metrics.repository.configuration'
- '@ps_metrics.helper.json'
- '@ps_metrics.api.analytics'
ps_metrics.provider.googletag:
class: 'PrestaShop\Module\Ps_metrics\Provider\GoogleTagProvider'
arguments:
- '@ps_metrics.api.http'
ps_metrics.module.install:
class: 'PrestaShop\Module\Ps_metrics\Module\Install'
arguments:
- '@ps_metrics.module'
- '@ps_metrics.repository.configuration'
- '@ps_metrics.repository.hookmodule'
ps_metrics.module.uninstall:
class: 'PrestaShop\Module\Ps_metrics\Module\Uninstall'
arguments:
- '@ps_metrics.module'
- '@ps_metrics.repository.configuration'
- '@ps_metrics.helper.json'
- '@ps_metrics.helper.module'
- '@ps_metrics.helper.logger'
- '@ps_metrics.api.analytics'
ps_metrics.module.dashboard.modules:
class: 'PrestaShop\Module\Ps_metrics\Module\DashboardModules'
arguments:
- '@ps_metrics.module'
- '@ps_metrics.repository.configuration'
ps_metrics.module.gainstaller:
class: 'PrestaShop\Module\Ps_metrics\Module\GAInstaller'
arguments:
- '@ps_metrics.adapter.link'
- '@ps_metrics.helper.module'
- '@ps_metrics.helper.tools'
ps_metrics.helper.number:
class: 'PrestaShop\Module\Ps_metrics\Helper\NumberHelper'
ps_metrics.helper.module:
class: 'PrestaShop\Module\Ps_metrics\Helper\ModuleHelper'
ps_metrics.helper.tools:
class: 'PrestaShop\Module\Ps_metrics\Helper\ToolsHelper'
ps_metrics.helper.shop:
class: 'PrestaShop\Module\Ps_metrics\Helper\ShopHelper'
ps_metrics.helper.logger:
class: 'PrestaShop\Module\Ps_metrics\Helper\LoggerHelper'
ps_metrics.helper.segment:
class: 'PrestaShop\Module\Ps_metrics\Helper\SegmentHelper'
arguments:
- '@ps_metrics.env.segment'
ps_metrics.helper.json:
class: 'PrestaShop\Module\Ps_metrics\Helper\JsonHelper'
arguments:
- '@ps_metrics.helper.logger'
ps_metrics.helper.data:
class: 'PrestaShop\Module\Ps_metrics\Helper\DataHelper'
ps_metrics.helper.db:
class: 'PrestaShop\Module\Ps_metrics\Helper\DbHelper'
arguments:
- '@ps_metrics.cache.data'
ps_metrics.presenter.store.store:
class: 'PrestaShop\Module\Ps_metrics\Presenter\Store\StorePresenter'
arguments:
- '@ps_metrics.module'
- '@ps_metrics.context.prestashop'
- '@ps_metrics.presenter.store.context'
- '@ps_metrics.presenter.store.dashboard'
- '@ps_metrics.presenter.store.settings'
ps_metrics.presenter.store.context:
class: 'PrestaShop\Module\Ps_metrics\Presenter\Store\Context\ContextPresenter'
arguments:
- '@ps_metrics.module'
- '@ps_metrics.context.prestashop'
- '@ps_metrics.adapter.link'
- '@ps_metrics.repository.configuration'
- '@ps_metrics.provider.shops'
- '@ps_metrics.module.dashboard.modules'
ps_metrics.presenter.store.dashboard:
class: 'PrestaShop\Module\Ps_metrics\Presenter\Store\Dashboard\DashboardPresenter'
arguments:
- '@ps_metrics.module'
- '@ps_metrics.context.prestashop'
- '@ps_metrics.translation.dashboard'
- '@ps_metrics.adapter.link'
ps_metrics.presenter.store.settings:
class: 'PrestaShop\Module\Ps_metrics\Presenter\Store\Settings\SettingsPresenter'
arguments:
- '@ps_metrics.module'
- '@ps_metrics.context.prestashop'
- '@ps_metrics.translation.settings'
- '@ps_metrics.adapter.link'
- '@ps_metrics.repository.configuration'
- '@ps_metrics.provider.shops'
- '@ps_metrics.provider.analyticsaccountslist'
- '@ps_metrics.provider.googletag'
- '@ps_metrics.module.gainstaller'
- '@ps_metrics.api.http'
ps_metrics.data.tipscards:
class: 'PrestaShop\Module\Ps_metrics\Data\TipsCardsData'
arguments:
- '@ps_metrics.api.analytics'
ps_metrics.kpi.configuration:
class: 'PrestaShop\Module\Ps_metrics\Kpi\Configuration\KpiConfiguration'
ps_metrics.kpi.kpi:
class: 'PrestaShop\Module\Ps_metrics\Kpi\Kpi'
arguments:
- '@ps_metrics.kpi.configuration'
ps_metrics.kpi.manager:
class: 'PrestaShop\Module\Ps_metrics\Kpi\KpiManager'
arguments:
- '@ps_metrics.kpi.configuration'
ps_metrics.kpi.strategyinterface:
class: 'PrestaShop\Module\Ps_metrics\Kpi\KpiStrategyInterface'
ps_metrics.kpi.visits:
class: 'PrestaShop\Module\Ps_metrics\Kpi\VisitsKpi'
arguments:
- '@ps_metrics.kpi.configuration'
- '@ps_metrics.helper.data'
- '@ps_metrics.cache.data'
- '@ps_metrics.repository.configuration'
- '@ps_metrics.api.analytics'
ps_metrics.kpi.total:
class: 'PrestaShop\Module\Ps_metrics\Kpi\TotalKpi'
arguments:
- '@ps_metrics.kpi.configuration'
- '@ps_metrics.kpi.visits'
- '@ps_metrics.kpi.orders'
- '@ps_metrics.kpi.revenues'
ps_metrics.kpi.revenues:
class: 'PrestaShop\Module\Ps_metrics\Kpi\RevenuesKpi'
arguments:
- '@ps_metrics.kpi.configuration'
- '@ps_metrics.helper.data'
- '@ps_metrics.repository.orders'
ps_metrics.kpi.orders:
class: 'PrestaShop\Module\Ps_metrics\Kpi\OrdersKpi'
arguments:
- '@ps_metrics.kpi.configuration'
- '@ps_metrics.helper.data'
- '@ps_metrics.repository.orders'
- '@ps_metrics.helper.number'
- '@ps_metrics.kpi.revenues'
- '@ps_metrics.repository.payment'
ps_metrics.kpi.conversion:
class: 'PrestaShop\Module\Ps_metrics\Kpi\ConversionKpi'
arguments:
- '@ps_metrics.kpi.configuration'
- '@ps_metrics.helper.number'
- '@ps_metrics.repository.configuration'
- '@ps_metrics.kpi.visits'
- '@ps_metrics.kpi.orders'
- '@ps_metrics.kpi.revenues'
ps_metrics.middleware:
class: 'PrestaShop\Module\Ps_metrics\Middleware\Middleware'
ps_metrics.middleware.sentry:
class: 'PrestaShop\Module\Ps_metrics\Middleware\SentryMiddleware'
ps_metrics.middleware.response:
class: 'PrestaShop\Module\Ps_metrics\Middleware\ResponseMiddleware'
ps_metrics.middleware.log:
class: 'PrestaShop\Module\Ps_metrics\Middleware\LogMiddleware'
arguments:
- '@ps_metrics.helper.logger'
ps_metrics.middleware.response.default:
class: 'PrestaShop\Module\Ps_metrics\Middleware\CheckResponseMiddleware'
arguments:
- '@ps_metrics.helper.json'
ps_metrics.api.client.factory:
class: 'PrestaShop\Module\Ps_metrics\Api\Client\ClientManager'
arguments:
- '@ps_metrics.middleware.response.default'
- '@ps_metrics.middleware.log'
- '@ps_metrics.middleware.sentry'
- '@ps_metrics.middleware.response'
- '@ps_metrics.handler.guzzleapi'
ps_metrics.api.client.http:
class: 'PrestaShop\Module\Ps_metrics\Api\Client\HttpClient'
arguments:
- '@ps_metrics.middleware.response.default'
- '@ps_metrics.middleware.log'
- '@ps_metrics.middleware.sentry'
- '@ps_metrics.middleware.response'
- '@ps_metrics.handler.guzzleapi'
ps_metrics.api.client.analytics:
class: 'PrestaShop\Module\Ps_metrics\Api\Client\AnalyticsClient'
arguments:
- '@ps_metrics.middleware.response.default'
- '@ps_metrics.middleware.log'
- '@ps_metrics.middleware.sentry'
- '@ps_metrics.middleware.response'
- '@ps_metrics.handler.guzzleapi'
ps_metrics.api.manager:
class: 'PrestaShop\Module\Ps_metrics\Api\ApiManager'
ps_metrics.api.analytics:
class: 'PrestaShop\Module\Ps_metrics\Api\AnalyticsApi'
arguments:
- '@ps_metrics.api.client.analytics'
- '@ps_metrics.context.prestashop'
- '@ps_metrics.env.analytics'
- '@ps_metrics.helper.json'
ps_metrics.api.http:
class: 'PrestaShop\Module\Ps_metrics\Api\HttpApi'
arguments:
- '@ps_metrics.api.client.http'
ps_metrics.handler.guzzleapi:
class: 'PrestaShop\Module\Ps_metrics\Handler\GuzzleApiResponseExceptionHandler'

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" ?>
<module>
<name>ps_metrics</name>
<displayName><![CDATA[PrestaShop Metrics]]></displayName>
<version><![CDATA[1.3.3]]></version>
<description><![CDATA[Moduł do PrestaShop Metrics.]]></description>
<author><![CDATA[PrestaShop]]></author>
<tab><![CDATA[advertising_marketing]]></tab>
<confirmUninstall><![CDATA[Czy na pewno chcesz odinstalować ten moduł?]]></confirmUninstall>
<is_configurable>1</is_configurable>
<need_instance>0</need_instance>
<limited_countries></limited_countries>
</module>

View File

@@ -0,0 +1,204 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
use PrestaShop\Module\Ps_metrics\Data\TipsCardsData;
use PrestaShop\Module\Ps_metrics\Helper\JsonHelper;
use PrestaShop\Module\Ps_metrics\Helper\ToolsHelper;
use PrestaShop\Module\Ps_metrics\Kpi\ConversionKpi;
use PrestaShop\Module\Ps_metrics\Kpi\KpiManager;
use PrestaShop\Module\Ps_metrics\Kpi\KpiStrategyInterface;
use PrestaShop\Module\Ps_metrics\Kpi\OrdersKpi;
use PrestaShop\Module\Ps_metrics\Kpi\RevenuesKpi;
use PrestaShop\Module\Ps_metrics\Kpi\TotalKpi;
use PrestaShop\Module\Ps_metrics\Kpi\VisitsKpi;
use PrestaShop\Module\Ps_metrics\Module\DashboardModules;
use PrestaShop\Module\Ps_metrics\Validation\RetrieveData;
class AdminAjaxDashboardController extends ModuleAdminController
{
const DEFAULT_DATA_TYPE = '';
const DEFAULT_DATE_RANGE = '{startDate: "", endDate: ""}';
const DEFAULT_GRANULARITY = 'days';
/**
* @var Ps_metrics
*/
public $module;
/**
* Load JsonHelper to avoid jsonEncode issues on AjaxDie
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* ajaxProcessGetExistingGoogleTags
*
* @return void
*/
public function ajaxProcessRetrieveData()
{
/** @var ToolsHelper $toolsHelper */
$toolsHelper = $this->module->getService('ps_metrics.helper.tools');
/** @var JsonHelper $jsonHelper */
$jsonHelper = $this->module->getService('ps_metrics.helper.json');
/** @var KpiManager $kpiManager */
$kpiManager = $this->module->getService('ps_metrics.kpi.manager');
$dataType = $toolsHelper->getValue('type', self::DEFAULT_DATA_TYPE);
$kpi = $toolsHelper->getValue('type', self::DEFAULT_DATA_TYPE);
$dateRange = $jsonHelper->jsonDecode(
$toolsHelper->getValue('dateRange', self::DEFAULT_DATE_RANGE)
);
$granularity = $toolsHelper->getValue('granularity', self::DEFAULT_GRANULARITY);
$this->verifyRetrievedData($dataType, $dateRange, $granularity);
$kpiManager->setKpi($this->dictionaryKpi($kpi));
$kpiManager->getConfiguration()->setDateRange($dateRange);
$kpiManager->getConfiguration()->setGranularity($granularity);
$data = $kpiManager->present();
$this->ajaxDie($jsonHelper->jsonEncode($data));
}
/**
* Instantiate the correct KPI
*
* @param string $kpi
*
* @return KpiStrategyInterface
*/
private function dictionaryKpi($kpi)
{
$dictionary = [
'total' => function () {
/** @var TotalKpi $totalKpi */
$totalKpi = $this->module->getService('ps_metrics.kpi.total');
return $totalKpi;
},
'revenues' => function () {
/** @var RevenuesKpi $revenuesKpi */
$revenuesKpi = $this->module->getService('ps_metrics.kpi.revenues');
return $revenuesKpi;
},
'orders' => function () {
/** @var OrdersKpi $ordersKpi */
$ordersKpi = $this->module->getService('ps_metrics.kpi.orders');
return $ordersKpi;
},
'visits' => function () {
/** @var VisitsKpi $visitsKpi */
$visitsKpi = $this->module->getService('ps_metrics.kpi.visits');
return $visitsKpi;
},
'conversion' => function () {
/** @var ConversionKpi $conversionKpi */
$conversionKpi = $this->module->getService('ps_metrics.kpi.conversion');
return $conversionKpi;
},
];
return call_user_func($dictionary[$kpi]);
}
/**
* ajaxProcessRetrieveTipsCards
*
* @return void
*/
public function ajaxProcessRetrieveTipsCards()
{
/** @var JsonHelper $jsonHelper */
$jsonHelper = $this->module->getService('ps_metrics.helper.json');
/** @var TipsCardsData $tipsCardsData */
$tipsCardsData = $this->module->getService('ps_metrics.data.tipscards');
$this->ajaxDie($jsonHelper->jsonEncode([
'tipsCards' => $tipsCardsData->getAll(),
]));
}
/**
* Toggle dashboard modules
*
* @return void
*/
public function ajaxProcessToggleDashboardModules()
{
/** @var DashboardModules $dashboardModule */
$dashboardModule = $this->module->getService('ps_metrics.module.dashboard.modules');
if ($dashboardModule->modulesIsEnabled()) {
$dashboardModule->disableModules();
} else {
$dashboardModule->enableModules();
}
/** @var JsonHelper $jsonHelper */
$jsonHelper = $this->module->getService('ps_metrics.helper.json');
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => true,
]));
}
/**
* Use AjaxDie if there's an error on ajaxProcessRetrieveData
*
* @param string $dataType
* @param array $dateRange
* @param string $granularity
*
* @return void
*/
private function verifyRetrievedData($dataType, array $dateRange, $granularity)
{
/** @var RetrieveData $serviceRetrieveData */
$serviceRetrieveData = $this->module->getService('ps_metrics.validation.retrievedata');
/** @var JsonHelper $jsonHelper */
$jsonHelper = $this->module->getService('ps_metrics.helper.json');
$dataTypeError = $serviceRetrieveData->dataType($dataType);
$dateRangeError = $serviceRetrieveData->dateRange($dateRange);
$granularityError = $serviceRetrieveData->granularity($granularity);
if (false === $dataTypeError || false === $dateRangeError || false === $granularityError) {
$this->ajaxDie($jsonHelper->jsonEncode([
'dataTypeError' => $dataTypeError,
'dateRangeError' => $dateRangeError,
'granularityError' => $granularityError,
]));
}
}
}

View File

@@ -0,0 +1,283 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
use PrestaShop\AccountsAuth\Service\PsBillingService;
use PrestaShop\Module\Ps_metrics\Api\AnalyticsApi;
use PrestaShop\Module\Ps_metrics\Cache\DataCache;
use PrestaShop\Module\Ps_metrics\Context\PrestaShopContext;
use PrestaShop\Module\Ps_metrics\Helper\JsonHelper;
use PrestaShop\Module\Ps_metrics\Helper\ToolsHelper;
use PrestaShop\Module\Ps_metrics\Module\DashboardModules;
use PrestaShop\Module\Ps_metrics\Module\Uninstall;
use PrestaShop\Module\Ps_metrics\Provider\AnalyticsAccountsListProvider;
use PrestaShop\Module\Ps_metrics\Provider\GoogleTagProvider;
use PrestaShop\Module\Ps_metrics\Provider\ShopsProvider;
use PrestaShop\Module\Ps_metrics\Repository\ConfigurationRepository;
use PrestaShop\Module\Ps_metrics\Validation\SelectAccountAnalytics;
class AdminAjaxSettingsController extends ModuleAdminController
{
/**
* @var Ps_metrics
*/
public $module;
/**
* Load JsonHelper to avoid jsonEncode issues on AjaxDie
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Get all existing Google Tags in Front End shop and retrieve them
*
* @return void
*/
public function ajaxProcessGetExistingGoogleTags()
{
/** @var ConfigurationRepository $configurationRepository */
$configurationRepository = $this->module->getService('ps_metrics.repository.configuration');
/** @var ShopsProvider $shopsProvider */
$shopsProvider = $this->module->getService('ps_metrics.provider.shops');
/** @var PrestaShopContext $prestashopContext */
$prestashopContext = $this->module->getService('ps_metrics.context.prestashop');
/** @var JsonHelper $jsonHelper */
$jsonHelper = $this->module->getService('ps_metrics.helper.json');
/** @var GoogleTagProvider $googleTagProvider */
$googleTagProvider = $this->module->getService('ps_metrics.provider.googletag');
// If google Tag is already set as linked, we avoid to retrieve the Google Tag
// Only the PSL will tell us if we should retrieve TAGS again
if (true === $configurationRepository->getGoogleTagLinkedValue()) {
$this->ajaxDie('true');
}
$currentShop = $shopsProvider->getShopUrl($prestashopContext->getShopId());
$googleTagProvider->setBaseUrl($currentShop['url']);
$this->ajaxDie($jsonHelper->jsonEncode([
'analytics' => $googleTagProvider->findGoogleTagsAnalytics(),
'manager' => $googleTagProvider->findGoogleTagsManager(),
]));
}
/**
* Select a Google Account for psessentials
* Need webPropertyId and viewId. Returns 201 if done
*
* @return void
*/
public function ajaxProcessSelectAccountAnalytics()
{
/** @var JsonHelper $jsonHelper */
$jsonHelper = $this->module->getService('ps_metrics.helper.json');
/** @var ToolsHelper $toolsHelper */
$toolsHelper = $this->module->getService('ps_metrics.helper.tools');
/** @var AnalyticsApi $apiAnalytics */
$apiAnalytics = $this->module->getService('ps_metrics.api.analytics');
/** @var SelectAccountAnalytics $serviceProcessSelectAccountAnalytics */
$serviceProcessSelectAccountAnalytics = $this->module->getService('ps_metrics.validation.processselectaccountanalytics');
$this->deleteExistingCache();
$validateData = $serviceProcessSelectAccountAnalytics->validate([
'webPropertyId' => $toolsHelper->getValue('webPropertyId'),
'viewId' => $toolsHelper->getValue('viewId'),
]);
if (false === $validateData) {
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => false,
]));
}
$serviceResult = $apiAnalytics->setAccountSelection([
'webPropertyId' => $toolsHelper->getValue('webPropertyId'),
'viewId' => $toolsHelper->getValue('viewId'),
]);
if (false === $serviceResult) {
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => false,
'googleAccount' => [],
]));
}
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => true,
'googleAccount' => [
'webPropertyId' => $toolsHelper->getValue('webPropertyId'),
'view_id' => $toolsHelper->getValue('viewId'),
'username' => $toolsHelper->getValue('username'),
'webPropertyName' => $toolsHelper->getValue('webPropertyName'),
],
]));
}
/**
* Google Analytics Logout must enable disabled modules, unsubscribe from PsEssentials
* Also, it must reset configuration's values
*
* @return void
*/
public function ajaxProcessLogOut()
{
/** @var JsonHelper $jsonHelper */
$jsonHelper = $this->module->getService('ps_metrics.helper.json');
$this->deleteExistingCache();
/** @var Uninstall $uninstallGoogleAccount */
$uninstallGoogleAccount = $this->module->getService('ps_metrics.module.uninstall');
if (false === $uninstallGoogleAccount->unsubscribePsEssentials()) {
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => false,
'googleLinked' => true,
]));
}
if (false === $uninstallGoogleAccount->resetConfigurationValues()) {
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => false,
'googleLinked' => true,
]));
}
/** @var DashboardModules $dashboardModule */
$dashboardModule = $this->module->getService('ps_metrics.module.dashboard.modules');
$dashboardModule->enableModules();
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => true,
'googleLinked' => false,
]));
}
/**
* Google Analytics Logout must enable disabled modules, unsubscribe from PsEssentials
* Also, it must reset configuration's values
*
* @return void
*/
public function ajaxProcessRefreshGA()
{
/** @var JsonHelper $jsonHelper */
$jsonHelper = $this->module->getService('ps_metrics.helper.json');
/** @var AnalyticsApi $apiAnalytics */
$apiAnalytics = $this->module->getService('ps_metrics.api.analytics');
$serviceResult = $apiAnalytics->refreshGA();
if (!empty($serviceResult['error'])) {
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => false,
'message' => $serviceResult['error'],
]));
}
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => true,
]));
}
/**
* Google Analytics Property List
*
* @return void
*/
public function ajaxProcessListProperty()
{
/** @var JsonHelper $jsonHelper */
$jsonHelper = $this->module->getService('ps_metrics.helper.json');
/** @var AnalyticsAccountsListProvider $analyticsAccountListProvider */
$analyticsAccountListProvider = $this->module->getService('ps_metrics.provider.analyticsaccountslist');
$serviceResult = $analyticsAccountListProvider->getAccountsList();
if (empty($serviceResult)) {
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => false,
'listProperty' => [],
'error' => 'No property list on this account',
]));
}
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => true,
'listProperty' => $serviceResult,
]));
}
/**
* Init Billing Free
*
* @return void
*/
public function ajaxProcessBillingFree()
{
/** @var JsonHelper $jsonHelper */
$jsonHelper = $this->module->getService('ps_metrics.helper.json');
$billingService = new PsBillingService();
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip_address = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { //whether ip is from proxy
$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else { //whether ip is from remote address
$ip_address = $_SERVER['REMOTE_ADDR'];
}
$result = $billingService->subscribeToFreePlan('ps_analytics', 'metrics-free', false, $ip_address);
if (empty($result)) {
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => false,
]));
}
$this->ajaxDie($jsonHelper->jsonEncode([
'success' => true,
'billing' => $result,
]));
}
/**
* Delete metrics cache
*
* @return bool
*/
private function deleteExistingCache()
{
/** @var DataCache $dataCache */
$dataCache = $this->module->getService('ps_metrics.cache.data');
return $dataCache->deleteAllCache();
}
}

View File

@@ -0,0 +1,206 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
use PrestaShop\AccountsAuth\Service\PsAccountsService;
use PrestaShop\Module\Ps_metrics\Adapter\LinkAdapter;
use PrestaShop\Module\Ps_metrics\Api\AnalyticsApi;
use PrestaShop\Module\Ps_metrics\Helper\JsonHelper;
use PrestaShop\Module\Ps_metrics\Helper\ModuleHelper;
use PrestaShop\Module\Ps_metrics\Helper\ToolsHelper;
use PrestaShop\Module\Ps_metrics\Module\DashboardModules;
use PrestaShop\Module\Ps_metrics\Repository\ConfigurationRepository;
class AdminOauthCallbackController extends ModuleAdminController
{
/**
* @var Ps_metrics
*/
public $module;
/**
* Load JsonHelper to avoid jsonEncode issues on AjaxDie
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Main method
*
* @return void
*/
public function display()
{
/** @var ToolsHelper $toolsHelper */
$toolsHelper = $this->module->getService('ps_metrics.helper.tools');
/** @var ConfigurationRepository $configurationRepository */
$configurationRepository = $this->module->getService('ps_metrics.repository.configuration');
/** @var LinkAdapter $linkAdapter */
$linkAdapter = $this->module->getService('ps_metrics.adapter.link');
if ('PS' === $toolsHelper->getValue('from')) {
$this->redirectToGoogleAuthentication();
}
$configurationRepository->saveActionGoogleLinked(true);
if (false === $this->isGoogleAuthenticationDone()) {
$configurationRepository->saveActionGoogleLinked(false);
}
/** @var DashboardModules $dashboardModule */
$dashboardModule = $this->module->getService('ps_metrics.module.dashboard.modules');
$dashboardModule->disableModules();
$toolsHelper->redirectAdmin(
$linkAdapter->getAdminLink(
'AdminModules',
true,
[],
[
'configure' => $this->module->name,
'google_message_error' => $toolsHelper->getValue('message'),
'countProperty' => $toolsHelper->getValue('count'),
]
)
);
}
/**
* Connexion to Google OAuth by redirecting to psessentials service
*
* @return void
*/
private function redirectToGoogleAuthentication()
{
/** @var AnalyticsApi $apiAnalytics */
$apiAnalytics = $this->module->getService('ps_metrics.api.analytics');
/** @var LinkAdapter $linkAdapter */
$linkAdapter = $this->module->getService('ps_metrics.adapter.link');
/** @var JsonHelper $jsonHelper */
$jsonHelper = $this->module->getService('ps_metrics.helper.json');
/** @var ToolsHelper $toolsHelper */
$toolsHelper = $this->module->getService('ps_metrics.helper.tools');
$serviceResult = $apiAnalytics->generateAuthUrl([
'state' => $this->getGoogleApiState(
$linkAdapter->getAdminLink($this->module->oauthAdminController),
(new PsAccountsService())->getShopUuidV4()
),
]);
if (empty($serviceResult)) {
$toolsHelper->redirectAdmin(
$linkAdapter->getAdminLink(
'AdminModules',
true,
[],
[
'configure' => $this->module->name,
'google_message_error' => $toolsHelper->getValue('message'),
'countProperty' => $toolsHelper->getValue('count'),
]
)
);
}
$toolsHelper->redirect($serviceResult['authorizeUrl']);
}
/**
* The service psessentials returns a param "status=ok" when the connection is done and valid
*
* @return bool
*/
private function isGoogleAuthenticationDone()
{
/** @var ToolsHelper $toolsHelper */
$toolsHelper = $this->module->getService('ps_metrics.helper.tools');
if ('ok' === $toolsHelper->getValue('status')) {
return true;
}
return false;
}
/**
* Google State is a base64 json encoded
*
* @param string $shopRedirectUri
* @param string|false $shopId
*
* @return string
*/
private function getGoogleApiState($shopRedirectUri, $shopId)
{
// the use of base64_encode is necessary for the api
return base64_encode(
'{"redirectUri":"' . $shopRedirectUri . '","shopId":"' . $shopId . '"}'
);
}
/**
* Get the module enabled status
*
* @return string|false
*/
private function getModuleListState()
{
$moduleListState = [];
/** @var ModuleHelper $moduleHelper */
$moduleHelper = $this->module->getService('ps_metrics.helper.module');
foreach ($this->module->moduleSubstitution as $moduleName) {
$isModuleEnabled = $moduleHelper->isEnabled($moduleName);
$moduleListState[$moduleName] = $isModuleEnabled;
}
return json_encode($moduleListState);
}
/**
* Disable dashboard module list moduleSubstitution when the Google Account is linked
*
* @return void
*/
private function disableDashboardModuleList()
{
/** @var ModuleHelper $moduleHelper */
$moduleHelper = $this->module->getService('ps_metrics.helper.module');
foreach ($this->module->moduleSubstitution as $moduleName) {
$module = $moduleHelper->getInstanceByName($moduleName);
// $module returns false if module doesn't exist
if (false !== $module) {
$module->disable();
}
}
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

BIN
modules/ps_metrics/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

View File

@@ -0,0 +1,251 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/vendor/autoload.php';
class Ps_metrics extends Module
{
/** @var string */
public $oauthAdminController;
/** @var array */
public $controllers;
/** @var bool */
public $psVersionIs17;
/** @var array */
public $moduleSubstitution;
/** @var string */
public $ajaxDashboardController;
/** @var string */
public $ajaxSettingsController;
/** @var bool */
public $bootstrap;
/** @var string */
public $confirmUninstall;
/** @var PrestaShop\ModuleLibServiceContainer\DependencyInjection\ServiceContainer */
private $container;
/** @var string */
public $idPsAccounts;
public function __construct()
{
$this->name = 'ps_metrics';
$this->tab = 'advertising_marketing';
$this->version = '1.3.3';
$this->author = 'PrestaShop';
$this->need_instance = 0;
$this->module_key = '697657ffe038d20741105e95a10b12d1';
$this->bootstrap = false;
$this->oauthAdminController = 'AdminOauthCallback';
$this->ajaxDashboardController = 'AdminAjaxDashboard';
$this->ajaxSettingsController = 'AdminAjaxSettings';
$this->idPsAccounts = '49648';
$this->controllers = [
$this->oauthAdminController,
$this->ajaxDashboardController,
$this->ajaxSettingsController,
];
$this->moduleSubstitution = [
'dashactivity',
'dashtrends',
'dashgoals',
'dashproducts',
];
parent::__construct();
$this->displayName = $this->l('Prestashop Metrics');
$this->description = $this->l('Module for Prestashop Metrics.');
$this->psVersionIs17 = (bool) version_compare(_PS_VERSION_, '1.7', '>=');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall this module?');
$this->ps_versions_compliancy = ['min' => '1.6', 'max' => _PS_VERSION_];
if ($this->container === null) {
$this->container = new \PrestaShop\ModuleLibServiceContainer\DependencyInjection\ServiceContainer($this->name, $this->getLocalPath());
}
}
/**
* This method is trigger at the installation of the module
*
* @return bool
*/
public function install()
{
/** @var PrestaShop\Module\Ps_metrics\Module\Install $installModule */
$installModule = $this->getService('ps_metrics.module.install');
return parent::install() &&
$this->registerHook('dashboardZoneTwo') &&
$installModule->updateModuleHookPosition('dashboardZoneTwo', 0) &&
$installModule->setConfigurationValues() &&
$installModule->installTabs() &&
(new PrestaShop\AccountsAuth\Installer\Install())->installPsAccounts();
}
/**
* Triggered at the uninstall of the module
*
* @return bool
*/
public function uninstall()
{
/** @var PrestaShop\Module\Ps_metrics\Module\Uninstall $uninstallModule */
$uninstallModule = $this->getService('ps_metrics.module.uninstall');
/** @var PrestaShop\Module\Ps_metrics\Tracker\Segment $segment */
$segment = $this->container->getService('ps_metrics.tracker.segment');
$segment->setMessage('Uninstall module');
$segment->track();
/** @var PrestaShop\Module\Ps_metrics\Module\DashboardModules $dashboardModules */
$dashboardModules = $this->container->getService('ps_metrics.module.dashboard.modules');
return parent::uninstall() &&
$uninstallModule->resetConfigurationValues() &&
$uninstallModule->uninstallTabs() &&
$uninstallModule->unsubscribePsEssentials() &&
$dashboardModules->enableModules();
}
/**
* Activate current module.
*
* @param bool $force_all If true, enable module for all shop
*
* @return bool
*/
public function enable($force_all = false)
{
/** @var PrestaShop\Module\Ps_metrics\Tracker\Segment $segment */
$segment = $this->container->getService('ps_metrics.tracker.segment');
$segment->setMessage('Enable module');
$segment->track();
return parent::enable($force_all);
}
/**
* Desactivate current module.
*
* @param bool $force_all If true, disable module for all shop
*
* @return bool
*/
public function disable($force_all = false)
{
/** @var PrestaShop\Module\Ps_metrics\Tracker\Segment $segment */
$segment = $this->container->getService('ps_metrics.tracker.segment');
$segment->setMessage('Disable module');
$segment->track();
return parent::disable($force_all);
}
/**
* Load the configuration form.
*
* @return string
*/
public function getContent()
{
$this->loadAssets(\Tools::getValue('google_message_error'), \Tools::getValue('countProperty'));
$this->loadPsAccountsAssets();
return $this->display(__FILE__, '/views/templates/admin/app.tpl');
}
/**
* hookDashboardZoneTwo
*
* @return string
*/
public function hookDashboardZoneTwo()
{
$this->loadAssets();
return $this->display(__FILE__, '/views/templates/hook/HookDashboardZoneTwo.tpl');
}
/**
* Load VueJs App and set JS variable for Vuex
*
* @param string $responseApiMessage
* @param int $countProperty
*
* @return void
*/
protected function loadAssets($responseApiMessage = 'null', $countProperty = 0)
{
$this->context->smarty->assign('pathVendor', $this->_path . 'views/js/chunk-vendors.js');
$this->context->smarty->assign('pathApp', $this->_path . 'views/js/app.js');
/** @var PrestaShop\Module\Ps_metrics\Presenter\Store\StorePresenter $storePresenter */
$storePresenter = $this->getService('ps_metrics.presenter.store.store');
$storePresenter->setProperties(null, (string) $responseApiMessage, (int) $countProperty);
Media::addJsDef([
'storePsMetrics' => $storePresenter->present(),
]);
}
/**
* See https://github.com/PrestaShopCorp/prestashop_accounts_auth
*
* @return void
*/
protected function loadPsAccountsAssets()
{
Media::addJsDef([
'contextPsAccounts' => (new PrestaShop\AccountsAuth\Presenter\PsAccountsPresenter($this->name))->present(),
]);
}
/**
* Retrieve service
*
* @param string $serviceName
*
* @return object|null
*/
public function getService($serviceName)
{
if ($this->container === null) {
$this->container = new \PrestaShop\ModuleLibServiceContainer\DependencyInjection\ServiceContainer(
$this->name,
$this->getLocalPath()
);
}
return $this->container->getService($serviceName);
}
}

View File

@@ -0,0 +1,84 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Adapter;
use Link;
use PrestaShop\Module\Ps_metrics\Context\PrestaShopContext;
use PrestaShop\Module\Ps_metrics\Helper\ToolsHelper;
use Ps_metrics;
class LinkAdapter
{
/**
* @var Link
*/
private $link;
/**
* @var Ps_metrics
*/
private $module;
/**
* @var ToolsHelper
*/
private $toolsHelper;
/**
* __construct
*
* @param Ps_metrics $module
* @param PrestaShopContext $prestashopContext
* @param ToolsHelper $toolsHelper
*
* @return void
*/
public function __construct(Ps_metrics $module, PrestaShopContext $prestashopContext, ToolsHelper $toolsHelper)
{
$this->link = $prestashopContext->getLink();
$this->module = $module;
$this->toolsHelper = $toolsHelper;
}
/**
* Adapter for getAdminLink from prestashop link class
*
* @param string $controller controller name
* @param bool $withToken include or not the token in the url
* @param array $sfRouteParams
* @param array $params
*
* @return string
*/
public function getAdminLink($controller, $withToken = true, $sfRouteParams = [], $params = [])
{
if ($this->module->psVersionIs17) {
return $this->link->getAdminLink($controller, $withToken, $sfRouteParams, $params);
}
$paramsAsString = '';
foreach ($params as $key => $value) {
$paramsAsString .= "&$key=$value";
}
return $this->toolsHelper->getShopDomainSsl(true) . __PS_BASE_URI__ . basename(_PS_ADMIN_DIR_) . '/' . $this->link->getAdminLink($controller, $withToken) . $paramsAsString;
}
}

View File

@@ -0,0 +1,29 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,205 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Api;
use PrestaShop\Module\Ps_metrics\Api\Client\AnalyticsClient;
use PrestaShop\Module\Ps_metrics\Context\PrestaShopContext;
use PrestaShop\Module\Ps_metrics\Environment\AnalyticsEnv;
use PrestaShop\Module\Ps_metrics\Helper\JsonHelper;
class AnalyticsApi
{
/**
* @var AnalyticsClient
*/
private $client;
/**
* @var PrestaShopContext
*/
private $prestaShopContext;
/**
* @var AnalyticsEnv
*/
private $analyticsEnv;
/**
* @var JsonHelper
*/
private $jsonHelper;
/**
* AnalyticsApi constructor.
*
* @param AnalyticsClient $analyticsClient
* @param PrestaShopContext $prestaShopContext
* @param AnalyticsEnv $analyticsEnv
* @param JsonHelper $jsonHelper
*/
public function __construct(
AnalyticsClient $analyticsClient,
PrestaShopContext $prestaShopContext,
AnalyticsEnv $analyticsEnv,
JsonHelper $jsonHelper
) {
$this->client = $analyticsClient;
$this->prestaShopContext = $prestaShopContext;
$this->analyticsEnv = $analyticsEnv;
$this->jsonHelper = $jsonHelper;
$this->client->setUrl($this->getServiceUrl());
$this->client->setMiddlewares();
$this->client->setHeader($this->client->getHeader());
}
/**
* @return string
*/
private function getServiceUrl()
{
return $this->analyticsEnv->getServiceUrl();
}
/**
* @return false|string
*/
private function getShopId()
{
return $this->client->getShopId();
}
/**
* @return string
*/
private function getLanguageIsoCode()
{
return $this->prestaShopContext->getLanguageIsoCode();
}
/**
* getTipsCardsList
*
* @return mixed
*/
public function getTipsCardsList()
{
$this->client->setRoute('/tipscards/' . $this->getLanguageIsoCode());
$tipscards = $this->client->get();
return (!empty($tipscards['error'])) ? [] : $this->jsonHelper->jsonEncode($tipscards['body']);
}
/**
* get reportings by date
*
* @param array $data
*
* @return array
*/
public function getReportingByDate(array $data)
{
$this->client->setRoute('/shops/' . $this->getShopId() . '/reportings');
$reportings = $this->client->post([
'json' => $data,
]);
return (!empty($reportings['error'])) ? [] : $reportings;
}
/**
* getAccountsList
*
* @return array
*/
public function getAccountsList()
{
$this->client->setRoute('/shops/' . $this->getShopId() . '/accounts/list');
$accounts = $this->client->get();
return (!empty($accounts['error'])) ? [] : $accounts['body'];
}
/**
* setAccountSelection
*
* @param array $data
*
* @return array|false
*/
public function setAccountSelection(array $data)
{
$this->client->setRoute('/shops/' . $this->getShopId() . '/accounts/selection');
$accountSelected = $this->client->post([
'json' => $data,
]);
return (!empty($accountSelected['error'])) ? false : $accountSelected['body'];
}
/**
* unsubscribe
*
* @return bool
*/
public function unsubscribe()
{
$this->client->setRoute('/shops/' . $this->getShopId() . '/accounts/unsubscribe');
$unsubscribed = $this->client->post();
return empty($unsubscribed['error']);
}
/**
* refreshGA
*
* @return array
*/
public function refreshGA()
{
$this->client->setRoute('/shops/' . $this->getShopId() . '/accounts/refresh');
return $this->client->post();
}
/**
* authUrl
*
* @param array $data
*
* @return array
*/
public function generateAuthUrl(array $data)
{
$this->client->setRoute('/shops/' . $this->getShopId() . '/accounts/generate-auth-url');
$generated = $this->client->post([
'json' => $data,
]);
return (!empty($generated['error'])) ? [] : $generated['body'];
}
}

View File

@@ -0,0 +1,94 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Api\Client;
use PrestaShop\AccountsAuth\Service\PsAccountsService;
use PrestaShop\Module\Ps_metrics\Handler\GuzzleApiResponseExceptionHandler;
use PrestaShop\Module\Ps_metrics\Middleware\CheckResponseMiddleware;
use PrestaShop\Module\Ps_metrics\Middleware\LogMiddleware;
use PrestaShop\Module\Ps_metrics\Middleware\ResponseMiddleware;
use PrestaShop\Module\Ps_metrics\Middleware\SentryMiddleware;
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class AnalyticsClient extends ClientFactory
{
/**
* @var PsAccountsService
*/
private $psAccountService;
/**
* AnalyticsClient constructor.
*
* @param CheckResponseMiddleware $checkResponseMiddleware
* @param LogMiddleware $logMiddleware
* @param SentryMiddleware $sentryMiddleware
* @param ResponseMiddleware $responseMiddleWare
* @param GuzzleApiResponseExceptionHandler $guzzleApiResponseExceptionHandler
*/
public function __construct(
CheckResponseMiddleware $checkResponseMiddleware,
LogMiddleware $logMiddleware,
SentryMiddleware $sentryMiddleware,
ResponseMiddleWare $responseMiddleWare,
GuzzleApiResponseExceptionHandler $guzzleApiResponseExceptionHandler
) {
parent::__construct($checkResponseMiddleware, $logMiddleware, $sentryMiddleware, $responseMiddleWare, $guzzleApiResponseExceptionHandler);
$this->psAccountService = new PsAccountsService();
}
/**
* @return string[]
*/
public function getHeader()
{
return [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $this->psAccountService->getOrRefreshToken(),
];
}
/**
* @return string|false
*/
public function getShopId()
{
return $this->psAccountService->getShopUuidV4();
}
}

View File

@@ -0,0 +1,260 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Api\Client;
/*
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Ring\Exception\RingException;
use PrestaShop\Module\Ps_metrics\Handler\GuzzleApiResponseExceptionHandler;
use PrestaShop\Module\Ps_metrics\Middleware\CheckResponseMiddleware;
use PrestaShop\Module\Ps_metrics\Middleware\LogMiddleware;
use PrestaShop\Module\Ps_metrics\Middleware\Middleware;
use PrestaShop\Module\Ps_metrics\Middleware\ResponseMiddleware;
use PrestaShop\Module\Ps_metrics\Middleware\SentryMiddleware;
class ClientFactory
{
/**
* @var array
*/
private $header;
/**
* @var string
*/
private $url;
/**
* @var string
*/
private $route = '';
/**
* @var Middleware
*/
private $middlewareManager;
/**
* @var CheckResponseMiddleware
*/
private $checkResponseMiddleware;
/**
* @var LogMiddleware
*/
private $logMiddleware;
/**
* @var SentryMiddleware
*/
private $sentryMiddleware;
/**
* @var ResponseMiddleware
*/
private $responseMiddleWare;
/**
* @var GuzzleApiResponseExceptionHandler
*/
private $guzzleApiResponseExceptionHandler;
/**
* ClientFactory constructor.
*
* @param CheckResponseMiddleware $checkResponseMiddleware
* @param LogMiddleware $logMiddleware
* @param SentryMiddleware $sentryMiddleware
* @param ResponseMiddleware $responseMiddleWare
* @param GuzzleApiResponseExceptionHandler $guzzleApiResponseExceptionHandler
*/
public function __construct(
CheckResponseMiddleware $checkResponseMiddleware,
LogMiddleware $logMiddleware,
SentryMiddleware $sentryMiddleware,
ResponseMiddleWare $responseMiddleWare,
GuzzleApiResponseExceptionHandler $guzzleApiResponseExceptionHandler
) {
$this->checkResponseMiddleware = $checkResponseMiddleware;
$this->logMiddleware = $logMiddleware;
$this->sentryMiddleware = $sentryMiddleware;
$this->responseMiddleWare = $responseMiddleWare;
$this->guzzleApiResponseExceptionHandler = $guzzleApiResponseExceptionHandler;
}
/**
* @return mixed
*/
public function get()
{
$client = new Client([
'base_url' => $this->getUrl() . $this->getRoute(),
'defaults' => [
'timeout' => 10,
'exceptions' => false,
'headers' => $this->getHeader(),
],
]);
try {
$response = $client->get();
} catch (RequestException $e) {
//for localhost/docker request guzzle can't access
$response = $this->guzzleApiResponseExceptionHandler->get($e->getMessage());
} catch (RingException $e) {
$response = $this->guzzleApiResponseExceptionHandler->get($e->getMessage());
}
return $this->getMiddlewareManager()->execute($response);
}
/**
* @param array $options
*
* @return mixed
*/
public function post($options = [])
{
$client = new Client([
'base_url' => $this->getUrl(),
'defaults' => [
'timeout' => 10,
'exceptions' => false,
'headers' => $this->getHeader(),
],
]);
try {
$response = $client->post($this->getRoute(), $options);
} catch (RequestException $e) {
//for localhost/docker request guzzle can't access
$response = $this->guzzleApiResponseExceptionHandler->get($e->getMessage());
} catch (RingException $e) {
$response = $this->guzzleApiResponseExceptionHandler->get($e->getMessage());
}
return $this->getMiddlewareManager()->execute($response);
}
/**
* @return mixed
*/
public function getUrl()
{
return $this->url;
}
/**
* @param string $url
*
* @return void
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* @return mixed
*/
public function getRoute()
{
return $this->route;
}
/**
* @param string $route
*
* @return void
*/
public function setRoute($route)
{
$this->route = $route;
}
/**
* @return mixed
*/
public function getHeader()
{
return $this->header;
}
/**
* @param mixed $header
*
* @return void
*/
public function setHeader($header)
{
$this->header = $header;
}
/**
* @return mixed
*/
public function getMiddlewareManager()
{
return $this->middlewareManager;
}
/**
* @param mixed $middlewareManager
*
* @return void
*/
public function setMiddlewareManager($middlewareManager)
{
$this->middlewareManager = $middlewareManager;
}
/**
* @return void
*/
public function setMiddlewares()
{
$middlewareManager = $this->checkResponseMiddleware;
$middlewareManager
->linkWith($this->logMiddleware)
->linkWith($this->sentryMiddleware)
->linkWith($this->responseMiddleWare);
$this->setMiddlewareManager($middlewareManager);
}
}

View File

@@ -0,0 +1,67 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Api\Client;
use PrestaShop\Module\Ps_metrics\Handler\GuzzleApiResponseExceptionHandler;
use PrestaShop\Module\Ps_metrics\Middleware\CheckResponseMiddleware;
use PrestaShop\Module\Ps_metrics\Middleware\LogMiddleware;
use PrestaShop\Module\Ps_metrics\Middleware\ResponseMiddleware;
use PrestaShop\Module\Ps_metrics\Middleware\SentryMiddleware;
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class HttpClient extends ClientFactory
{
/**
* AnalyticsClient constructor.
*
* @param CheckResponseMiddleware $checkResponseMiddleware
* @param LogMiddleware $logMiddleware
* @param SentryMiddleware $sentryMiddleware
* @param ResponseMiddleware $responseMiddleWare
* @param GuzzleApiResponseExceptionHandler $guzzleApiResponseExceptionHandler
*/
public function __construct(
CheckResponseMiddleware $checkResponseMiddleware,
LogMiddleware $logMiddleware,
SentryMiddleware $sentryMiddleware,
ResponseMiddleWare $responseMiddleWare,
GuzzleApiResponseExceptionHandler $guzzleApiResponseExceptionHandler
) {
parent::__construct($checkResponseMiddleware, $logMiddleware, $sentryMiddleware, $responseMiddleWare, $guzzleApiResponseExceptionHandler);
}
}

View File

@@ -0,0 +1,11 @@
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Location: ../");
exit;

View File

@@ -0,0 +1,73 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Api;
use PrestaShop\Module\Ps_metrics\Api\Client\HttpClient;
class HttpApi
{
/**
* @var HttpClient
*/
private $client;
/**
* HttpApi constructor.
*
* @param HttpClient $httpClient
*/
public function __construct(
HttpClient $httpClient
) {
$this->client = $httpClient;
$this->client->setMiddlewares();
}
/**
* @param string $moduleKey
* @param string $isoCode
* @param string $psVersion
*
* @return mixed
*/
public function getFaq($moduleKey, $isoCode, $psVersion)
{
$url = 'https://api.addons.prestashop.com/request/faq/' . $moduleKey . '/' . $isoCode . '/' . $psVersion;
$this->client->setUrl($url);
$faq = $this->client->get();
return (!empty($faq['error'])) ? null : $faq['body'];
}
/**
* @param string $url
*
* @return mixed
*/
public function getSourcePage($url)
{
$this->client->setUrl($url);
$source = $this->client->get();
return (!empty($source['error'])) ? null : $source['body'];
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,225 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Cache;
use PrestaShop\Module\Ps_metrics\Environment\CacheEnv;
use PrestaShop\Module\Ps_metrics\Helper\JsonHelper;
use PrestaShop\Module\Ps_metrics\Helper\LoggerHelper;
class DataCache
{
const CACHE_TIME = 3600;
/**
* @var JsonHelper
*/
private $jsonHelper;
/**
* @var array|string
*/
private $param;
/**
* @var DirectoryCache
*/
private $directoryCache;
/**
* @var CacheEnv
*/
private $cacheEnv;
/**
* @var LoggerHelper
*/
private $loggerHelper;
/**
* __construct
*
* @param DirectoryCache $directoryCache
* @param CacheEnv $cacheEnv
* @param JsonHelper $jsonHelper
* @param LoggerHelper $loggerHelper
*/
public function __construct(
DirectoryCache $directoryCache,
CacheEnv $cacheEnv,
JsonHelper $jsonHelper,
LoggerHelper $loggerHelper
) {
$this->jsonHelper = $jsonHelper;
$this->directoryCache = $directoryCache;
$this->cacheEnv = $cacheEnv;
$this->loggerHelper = $loggerHelper;
}
/**
* Get cache if exists
*
* @param array|string $param
*
* @return mixed
*/
public function get($param)
{
// If cache disabled, return false directly
if (false === $this->cacheEnv->getCacheEnv()) {
return false;
}
if (false === $this->directoryCache->isReadable()) {
$this->loggerHelper->addLog('[PS_METRICS] Cache folder is not readable', 3);
return false;
}
$this->setParam($param);
$cacheFileName = $this->directoryCache->getPath() . $this->getCacheFileName();
if ($this->cacheExists($cacheFileName)) {
return $this->jsonHelper->jsonDecode(
file_get_contents($cacheFileName),
true
);
}
return false;
}
/**
* Set cache
*
* @param mixed $data
* @param string $cacheName
*
* @return mixed
*/
public function set($data, $cacheName = null)
{
// If cache disabled, return $data directly
if (false === $this->cacheEnv->getCacheEnv()) {
return $data;
}
if (false === $this->directoryCache->isWritable()) {
$this->loggerHelper->addLog('[PS_METRICS] Cache folder is not writable', 3);
return $data;
}
if (null === $cacheName) {
$this->setParam($data);
} else {
$this->setParam($cacheName);
}
$cacheFileName = $this->directoryCache->getPath() . $this->getCacheFileName();
$jsonData = $this->jsonHelper->jsonEncode($data);
if (false === @file_put_contents($cacheFileName, $jsonData)) {
$this->loggerHelper->addLog('[PS_METRICS] Unable to create data cache', 3);
}
return $data;
}
/**
* Cache File name
*
* @return string
*/
private function getCacheFileName()
{
return md5($this->getParam()) . '.ps_metrics.cache';
}
/**
* Check if cache exist and if last time modified < 1hour
*
* @param string $cacheFile
*
* @return bool
*/
private function cacheExists($cacheFile)
{
if (!file_exists($cacheFile)) {
return false;
}
if (filemtime($cacheFile) < (time() - self::CACHE_TIME)) {
return false;
}
return true;
}
/**
* setParam
*
* @param array|string $param
*
* @return void
*/
private function setParam($param)
{
$this->param = $param;
}
/**
* Return a string by transforming param to json if is array
*
* @return string
*/
private function getParam()
{
if (is_array($this->param)) {
return $this->jsonHelper->jsonEncode($this->param);
}
return $this->param;
}
/**
* Delete all metrics cache
*
* @return bool
*/
public function deleteAllCache()
{
if (false === $this->directoryCache->isWritable()) {
$this->loggerHelper->addLog('[PS_METRICS] Not able to delete the cache. Cache folder is not writable', 3);
return false;
}
$files = glob($this->directoryCache->getPath() . '*.ps_metrics.cache');
foreach ($files as $file) {
if (file_exists($file)) {
unlink($file);
}
}
return true;
}
}

View File

@@ -0,0 +1,98 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Cache;
/**
* Class responsible for returning cache directory path.
*/
class DirectoryCache
{
/**
* @var string PrestaShop version
*/
private $psVersion;
/**
* @var string PrestaShop path
*/
private $psPath;
/**
* @var bool PrestaShop Debug Mode
*/
private $psIsDebugMode;
/**
* __construct
*
* @return void
*/
public function __construct()
{
$this->psVersion = _PS_VERSION_;
$this->psPath = _PS_ROOT_DIR_;
$this->psIsDebugMode = _PS_MODE_DEV_;
}
/**
* @return string
*/
public function getPath()
{
if (defined('_PS_CACHE_DIR_')) {
return constant('_PS_CACHE_DIR_');
}
$path = '/var/cache/' . $this->getEnvName();
if (version_compare($this->psVersion, '1.7.0.0', '<')) {
$path = '/cache';
} elseif (version_compare($this->psVersion, '1.7.4.0', '<')) {
$path = '/app/cache/' . $this->getEnvName();
}
return $this->psPath . $path;
}
/**
* @return bool
*/
public function isWritable()
{
return is_writable($this->getPath());
}
/**
* @return bool
*/
public function isReadable()
{
return is_readable($this->getPath());
}
/**
* @return string
*/
private function getEnvName()
{
return $this->psIsDebugMode ? 'dev' : 'prod';
}
}

View File

@@ -0,0 +1,29 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,148 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Context;
use ContextCore as Context;
/**
* Class PrestaShopContext used to get information from PrestaShop Context
*/
class PrestaShopContext
{
/**
* @var Context
*/
private $context;
/**
* PrestaShopContext constructor.
*
* @return void
*/
public function __construct()
{
$this->context = Context::getContext();
}
/**
* Get the isoCode from the context language, if null, send 'en' as default value
*
* @return string
*/
public function getLanguageIsoCode()
{
return $this->context->language !== null ? $this->context->language->iso_code : 'en';
}
/**
* Get current language
*
* @return mixed
*/
public function getLanguage()
{
return $this->context->language;
}
/**
* Get current language code
*
* @return string
*/
public function getLanguageCode()
{
return $this->context->language !== null ? $this->context->language->language_code : 'en';
}
/**
* Get currency code
*
* @return string
*/
public function getCurrencyIsoCode()
{
return $this->context->currency !== null ? $this->context->currency->iso_code : 'EUR';
}
/**
* Get current locale
*
* @return string
*
* @todo implement currentLocale for version > 1.7.3.X
*/
public function getCurrentLocale()
{
return $this->getLanguageIsoCode();
//return $this->context->currentLocale !== null ? $this->context->currentLocale : 'en';
}
/**
* Get controller name
*
* @return string
*/
public function getControllerName()
{
/** @var \AdminControllerCore $adminController */
$adminController = $this->context->controller;
return (!empty($adminController->controller_name)) ? $adminController->controller_name : '';
}
/**
* Get context link
*
* @return \Link
*/
public function getLink()
{
return $this->context->link;
}
/**
* Get shop id
*
* @return mixed
*/
public function getShopId()
{
return (int) $this->context->shop->id;
}
/**
* Get shop domain
*
* @return mixed
*/
public function getShopDomain()
{
return $this->context->shop->domain;
}
/**
* @return int
*/
public function getEmployeeIdLang()
{
return (int) $this->context->employee->id_lang;
}
}

View File

@@ -0,0 +1,29 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,55 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Data;
use PrestaShop\Module\Ps_metrics\Api\Analytics\TipsCards;
use PrestaShop\Module\Ps_metrics\Api\AnalyticsApi;
class TipsCardsData
{
/**
* @var AnalyticsApi
*/
private $analyticsApi;
/**
* TipsCardsData constructor.
*
* @param AnalyticsApi $analyticsApi
*
* @return void
*/
public function __construct(
AnalyticsApi $analyticsApi
) {
$this->analyticsApi = $analyticsApi;
}
/**
* get all tipscards
*
* @return string|false
*/
public function getAll()
{
return $this->analyticsApi->getTipsCardsList();
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,64 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Environment;
class AnalyticsEnv extends Env
{
/**
* Url service analytics (prod and test)
*
* @var string
*/
private $serviceUrl;
/**
* AnalyticsEnv constructor.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->setServiceUrl($_ENV['ANALYTICS_API']);
}
/**
* getServiceUrl
*
* @return string
*/
public function getServiceUrl()
{
return $this->serviceUrl;
}
/**
* setter for serviceUrl
*
* @param string $url
*
* @return void
*/
private function setServiceUrl($url)
{
$this->serviceUrl = $url;
}
}

View File

@@ -0,0 +1,65 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Environment;
class CacheEnv extends Env
{
/**
* @var string
*/
private $cacheEnv = '';
/**
* __construct
*
* @return void
*/
public function __construct()
{
parent::__construct();
$activeCache = getenv('ACTIVE_CACHE');
if ($activeCache) {
$this->setCacheEnv($activeCache);
}
}
/**
* getCacheEnv
*
* @return bool
*/
public function getCacheEnv()
{
return ('false' === $this->cacheEnv) ? false : true;
}
/**
* setter for CacheEnv
*
* @param string $cacheActive
*
* @return void
*/
private function setCacheEnv($cacheActive)
{
$this->cacheEnv = $cacheActive;
}
}

View File

@@ -0,0 +1,98 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Environment;
use Dotenv\Dotenv;
class Env
{
const MODULE_NAME = 'ps_metrics';
/**
* Const that define all environment possible to use.
* Top of the list are taken in first if they exist in the project.
* eg: If .env.test is present in the module it will be loaded, if not present
* we try to load the next one etc ...
*
* @var array
*/
const FILE_ENV_LIST = [
'test' => '.env.test',
'prod' => '.env',
];
/**
* Environment name: can be 'prod' or 'test'
*
* @var string
*/
protected $name;
/**
* Environment mode: can be 'live' or 'sandbox'
*
* @var string
*/
protected $mode;
/**
* Env constructor.
*
* @return void
*/
public function __construct()
{
foreach (self::FILE_ENV_LIST as $env => $fileName) {
if (!file_exists(_PS_MODULE_DIR_ . self::MODULE_NAME . '/' . $fileName)) {
continue;
}
$dotenv = Dotenv::create(_PS_MODULE_DIR_ . self::MODULE_NAME . '/', $fileName);
$dotenv->load();
$this->setName($env);
break;
}
}
/**
* getName
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* setName
*
* @param string $name
*
* @return void
*/
private function setName($name)
{
$this->name = $name;
}
}

View File

@@ -0,0 +1,64 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Environment;
class SegmentEnv extends Env
{
/**
* Firebase public api key
*
* @var string
*/
private $segmentApiKey;
/**
* SegmentEnv constructor.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->setSegmentApiKey($_ENV['SEGMENT_API_KEY']);
}
/**
* getter for segmentApiKey
*
* @return string
*/
public function getSegmentApiKey()
{
return $this->segmentApiKey;
}
/**
* setter for segmentApiKey
*
* @param string $apiKey
*
* @return void
*/
private function setSegmentApiKey($apiKey)
{
$this->segmentApiKey = $apiKey;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,114 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Handler;
class GuzzleApiResponseExceptionHandler
{
/**
* @var string
*/
private $reasonPhrase;
/**
* @var mixed
*/
private $body;
/**
* @var int
*/
private $statusCode;
/**
* @return string
*/
public function getReasonPhrase()
{
return $this->reasonPhrase;
}
/**
* @param string $reasonPhrase
*
* @return void
*/
public function setReasonPhrase($reasonPhrase)
{
$this->reasonPhrase = $reasonPhrase;
}
/**
* @return mixed
*/
public function getBody()
{
return $this->body;
}
/**
* @param mixed $body
*
* @return void
*/
public function setBody($body)
{
$this->body = $body;
}
/**
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* @param int $statusCode
*
* @return void
*/
public function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;
}
/**
* GuzzleApiResponseExceptionHandler constructor.
*/
public function __construct()
{
}
/**
* @param string $errorMessage
*
* @return $this
*/
public function get($errorMessage)
{
$this->setStatusCode(500);
$this->setBody(null);
$this->setReasonPhrase($errorMessage);
return $this;
}
}

View File

@@ -0,0 +1,11 @@
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Location: ../");
exit;

View File

@@ -0,0 +1,194 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Helper;
class DataHelper
{
/**
* Return an array with the date for array key
* Return initial array if $value['date'] doesn't exist
*
* @param array $array
* @param string $fromKey (example : 'date')
*
* @return array
*/
public function modifyArrayMainKeys(array $array, $fromKey)
{
if (empty($array)) {
return $array;
}
$newArray = [];
foreach ($array as $key => $value) {
if (empty($value[$fromKey])) {
return $array;
}
$newArray[$value[$fromKey]] = $array[$key];
}
return $newArray;
}
/**
* transformToGranularityWeeks
*
* @param array $array
* @param array $fromKeys (example : ['revenues', 'shipping'])
*
* @todo : refacto this - do sum in front ?!
*
* @return array
*/
public function transformToGranularityWeeks(array $array, array $fromKeys)
{
if (empty($array)) {
return $array;
}
$allDataByWeek = [];
/* Reorder array by weeks */
foreach ($array as $values) {
$weekNumber = (new \DateTime($values['date']))->format('Y-W');
$allDataByWeek[$weekNumber][] = $values;
}
$finalArrayRevenueByWeek = [];
/* Sum all data in a week */
foreach ($allDataByWeek as $keyWeek => $weekValues) {
$finalValue = [];
foreach ($weekValues as $valueKey) {
foreach ($fromKeys as $fromKey) {
if (!array_key_exists($fromKey, $finalValue)) {
$finalValue[$fromKey] = 0;
}
$finalValue[$fromKey] += $valueKey[$fromKey];
}
}
$finalArrayRevenueByWeek[$keyWeek] = ['date' => $keyWeek];
foreach ($fromKeys as $fromKey) {
$finalArrayRevenueByWeek[$keyWeek][$fromKey] = $finalValue[$fromKey];
}
}
return $finalArrayRevenueByWeek;
}
/**
* transformToGranularityWeeks
*
* @param array $array
* @param array $fromKeys (example : ['revenues', 'shipping'])
*
* @todo : refacto this
*
* @return array
*/
public function transformToGranularityHours(array $array, array $fromKeys)
{
if (empty($array)) {
return $array;
}
$allDataByHours = [];
/* Reorder array with only key hours */
foreach ($array as $values) {
$hour = $values['date'] . ':00:00';
$allDataByHours[$hour] = $values;
}
$finalArrayRevenueByHour = [];
/* Sum all data in a week */
foreach ($allDataByHours as $keyHour => $hourValues) {
$finalArrayRevenueByHour[$keyHour] = ['date' => $keyHour];
foreach ($fromKeys as $fromKey) {
$finalArrayRevenueByHour[$keyHour][$fromKey] = $hourValues[$fromKey];
}
}
return $finalArrayRevenueByHour;
}
/**
* Subtract data recursively.
* For example: total paid - refunds
*
* @param array $array
* @param string $toKey
* @param string $fromKey
*
* @return array
*/
public function subtractDataRecursively(array $array, $toKey, $fromKey)
{
if (empty($array)) {
return $array;
}
foreach ($array as $key => $value) {
$array[$key][$toKey] = $value[$toKey];
unset($array[$key][$fromKey]);
}
return $array;
}
/**
* Sort a Multidimensional array by a specific key
*
* @param array $array
* @param string $sortBy
*
* @return array
*/
public function arrayMultiSort(array $array, $sortBy)
{
if (empty($array)) {
return $array;
}
$keys = array_column($array, $sortBy);
array_multisort($keys, SORT_DESC, $array);
return $array;
}
/**
* Build list of elements based on array key
*
* @param string $key
* @param array $array
*
* @return array
*/
public function BuildKeyListFromArray($key, array $array)
{
return array_map(function ($item) use ($key) {
return $item[$key];
}, $array);
}
}

View File

@@ -0,0 +1,101 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Helper;
use Db;
use PrestaShop\Module\Ps_metrics\Cache\DataCache;
class DbHelper
{
/**
* @var DataCache
*/
private $dataCache;
/**
* __construct
*
* @param DataCache $dataCache
*
* @return void
*/
public function __construct(DataCache $dataCache)
{
$this->dataCache = $dataCache;
}
/**
* Retrieve cache data if exist or request a "dbRequestType"
*
* @param string $dbRequestType
* @param string $sql
*
* @return mixed
*/
private function request($dbRequestType, $sql)
{
$sqlCache = $this->dataCache->get($sql);
if (false !== $sqlCache) {
return $sqlCache;
}
return $this->dataCache->set(
Db::getInstance()->{$dbRequestType}($sql)
);
}
/**
* Executes return the result of $sql as array by requesting
*
* @param string $sql
*
* @return array
*/
public function executeS($sql)
{
return $this->request('executeS', $sql);
}
/**
* Returns a value from the first row, first column of a SELECT query
*
* @param string $sql
*
* @return mixed
*/
public function getValue($sql)
{
return $this->request('getValue', $sql);
}
/**
* Returns an associative array containing the first row of the query This function automatically adds "LIMIT 1" to the query.
*
* @param string $sql
*
* @return array
*/
public function getRow($sql)
{
return $this->request('getRow', $sql);
}
}

View File

@@ -0,0 +1,83 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Helper;
class JsonHelper
{
/**
* @var LoggerHelper
*/
private $loggerHelper;
/**
* JsonHelper constructor.
*
* @param LoggerHelper $loggerHelper
*/
public function __construct(LoggerHelper $loggerHelper)
{
$this->loggerHelper = $loggerHelper;
}
/**
* Encode the data to json and check and force the return to empty string if false
*
* @param mixed $data
*
* @return string
*/
public function jsonEncode($data)
{
$json = json_encode($data);
if (empty($data)) {
$json = json_encode($data, JSON_FORCE_OBJECT);
}
if (false !== $json) {
return $json;
}
$this->loggerHelper->addLog('[PS_METRICS] Unable to encode Json', 3);
return '';
}
/**
* Check if the json is valid and returns an empty data if not
*
* @param mixed $json
* @param bool $assoc
*
* @return array $data
*/
public function jsonDecode($json, $assoc = true)
{
$data = json_decode($json, $assoc);
if (JSON_ERROR_NONE === json_last_error()) {
return $data;
}
$this->loggerHelper->addLog('[PS_METRICS] Unable to decode Json', 3);
return [];
}
}

View File

@@ -0,0 +1,38 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Helper;
use PrestaShopLogger;
class LoggerHelper
{
/**
* @param string $message
* @param int $severity
*
* @return void
*/
public function addLog($message, $severity)
{
PrestaShopLogger::addLog($message, $severity);
}
}

View File

@@ -0,0 +1,56 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Helper;
use ModuleCore;
class ModuleHelper
{
/**
* @param string $moduleName
*
* @return bool
*/
public function isInstalled($moduleName)
{
return \ModuleCore::isInstalled($moduleName);
}
/**
* @param string $moduleName
*
* @return bool
*/
public function isEnabled($moduleName)
{
return \ModuleCore::isInstalled($moduleName);
}
/**
* @param string $moduleName
*
* @return false|\Module
*/
public function getInstanceByName($moduleName)
{
return ModuleCore::getInstanceByName($moduleName);
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Helper;
class NumberHelper
{
/**
* Prevent division by 0
*
* @param int|float $number
* @param int|float $byNumber
*
* @return int|float
*/
public function division($number, $byNumber)
{
if (0 === $number) {
return 0;
}
if (0 === $byNumber) {
$byNumber = 1;
}
return $number / $byNumber;
}
}

View File

@@ -0,0 +1,74 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Helper;
use PrestaShop\Module\Ps_metrics\Environment\SegmentEnv;
use Segment;
class SegmentHelper
{
/**
* @var SegmentEnv
*/
private $segmentEnv;
/**
* SegmentHelper constructor.
*
* @param SegmentEnv $segmentEnv
*
* @return void
*/
public function __construct(SegmentEnv $segmentEnv)
{
$this->segmentEnv = $segmentEnv;
}
/**
* Init segment
*
* @return void
*/
public function init()
{
Segment::init($this->segmentEnv->getSegmentApiKey());
}
/**
* @param array $message
*
* @return void
*/
public function track($message)
{
Segment::track($message);
}
/**
* Flush segment
*
* @return void
*/
public function flush()
{
Segment::flush();
}
}

View File

@@ -0,0 +1,75 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Helper;
use Shop;
class ShopHelper
{
/**
* @param int $shopId
*
* @return array
*/
public function getShop($shopId)
{
return Shop::getShop($shopId);
}
/**
* @param bool $active
* @param int|null $id_shop_group
* @param false $get_as_list_id
*
* @return array
*/
public function getShops($active = true, $id_shop_group = null, $get_as_list_id = false)
{
return Shop::getShops($active = true, $id_shop_group = null, $get_as_list_id = false);
}
/**
* @return int|null
*/
public function getContextShopGroupID()
{
return Shop::getContextShopGroupID();
}
/**
* @return int
*/
public function getContext()
{
return Shop::getContext();
}
/**
* @param false $share
* @param string|null $alias
*
* @return string
*/
public function addSqlRestriction($share = false, $alias = null)
{
return Shop::addSqlRestriction($share, $alias);
}
}

View File

@@ -0,0 +1,75 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Helper;
use Tools;
class ToolsHelper
{
/**
* @param bool $http
*
* @return string
*/
public function getShopDomainSsl($http)
{
return Tools::getShopDomainSsl($http);
}
/**
* @return bool
*/
public function usingSecureMode()
{
return Tools::usingSecureMode();
}
/**
* @param string $value
* @param mixed $default_value
*
* @return false|mixed
*/
public function getValue($value, $default_value = false)
{
return Tools::getValue($value, $default_value);
}
/**
* @param string $url
*
* @return void
*/
public function redirectAdmin($url)
{
Tools::redirectAdmin($url);
}
/**
* @param string $url
*
* @return void
*/
public function redirect($url)
{
Tools::redirect($url);
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,133 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Kpi\Configuration;
class KpiConfiguration
{
/**
* @var array
*/
public $dateRange;
/**
* @var array
*/
public $granularity;
/**
* @var array
*/
public $compareDateRange = null;
/**
* @return array
*/
public function getDateRange()
{
return $this->dateRange;
}
/**
* @param array $dateRange
*
* @return void
*/
public function setDateRange($dateRange)
{
$this->dateRange = $dateRange;
}
/**
* @return array
*/
public function getGranularity()
{
return $this->granularity;
}
/**
* @param string $granularity
*
* @return void
*/
public function setGranularity($granularity)
{
$this->granularity = $this->getGranularityForSqlDates($granularity);
}
/**
* @return array
*/
public function getCompareDateRange()
{
return $this->compareDateRange;
}
/**
* @param array $compareDateRange
*
* @return void
*/
public function setCompareDateRange($compareDateRange)
{
$this->compareDateRange = $compareDateRange;
}
/**
* getGranularityForSqlDates
*
* @param string $granularity
*
* @return array
*/
private function getGranularityForSqlDates($granularity)
{
if ('weeks' === $granularity) {
// for day : 0000-00-00
return [
'type' => 'weeks',
'forSql' => 10,
];
}
if ('months' === $granularity) {
// for month : 0000-00
return [
'type' => 'months',
'forSql' => 7,
];
}
if ('hours' === $granularity) {
// for hours : 0000-00-00 00
return [
'type' => 'hours',
'forSql' => 13,
];
}
// for day : 0000-00-00
return [
'type' => 'days',
'forSql' => 10,
];
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,169 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Kpi;
use PrestaShop\Module\Ps_metrics\Helper\NumberHelper;
use PrestaShop\Module\Ps_metrics\Kpi\Configuration\KpiConfiguration;
use PrestaShop\Module\Ps_metrics\Repository\ConfigurationRepository;
class ConversionKpi extends Kpi implements KpiStrategyInterface
{
/**
* @var NumberHelper
*/
private $numberHelper;
/**
* @var ConfigurationRepository
*/
private $configurationRepository;
/**
* @var VisitsKpi
*/
private $visitsKpi;
/**
* @var OrdersKpi
*/
private $ordersKpi;
/**
* @var RevenuesKpi
*/
private $revenuesKpi;
/**
* ConversionKpi constructor.
*
* @param KpiConfiguration $kpiConfiguration
* @param NumberHelper $numberHelper
* @param ConfigurationRepository $configurationRepository
* @param VisitsKpi $visitsKpi
* @param OrdersKpi $ordersKpi
* @param RevenuesKpi $revenuesKpi
*/
public function __construct(
KpiConfiguration $kpiConfiguration,
NumberHelper $numberHelper,
ConfigurationRepository $configurationRepository,
VisitsKpi $visitsKpi,
OrdersKpi $ordersKpi,
RevenuesKpi $revenuesKpi
) {
parent::__construct($kpiConfiguration);
$this->numberHelper = $numberHelper;
$this->configurationRepository = $configurationRepository;
$this->visitsKpi = $visitsKpi;
$this->ordersKpi = $ordersKpi;
$this->revenuesKpi = $revenuesKpi;
}
/**
* Return data
*
* @return array
*/
public function present()
{
$gaIsOnboarded = (bool) $this->configurationRepository->getGoogleLinkedValue();
if (!$gaIsOnboarded) {
return [];
}
$this->visitsKpi->setConfiguration($this->getConfiguration());
$visitsData = $this->visitsKpi->present();
$visitsData = $visitsData['visits'];
$this->ordersKpi->setOnlyOrderPaidOnWebsite(true);
$this->ordersKpi->setConfiguration($this->getConfiguration());
$ordersData = $this->ordersKpi->present();
$this->revenuesKpi->setConfiguration($this->getConfiguration());
if (empty($visitsData)) {
return [
'conversionRate' => [],
'conversionRateTotal' => [],
'revenuesCustomers' => $this->revenuesKpi->getTotalCustomersRevenues(),
'revenuesPaymentMethod' => $this->revenuesKpi->getTotalPaymentMethodsRevenues(),
];
}
return [
'conversionRate' => $this->getConversionRate($visitsData['byDate'], $ordersData['orders']),
'conversionRateTotal' => $this->getConversionRateTotal($visitsData['total'], $ordersData['total']),
'revenuesCustomers' => $this->revenuesKpi->getTotalCustomersRevenues(),
'revenuesPaymentMethod' => $this->revenuesKpi->getTotalPaymentMethodsRevenues(),
];
}
/**
* getConversionRate
*
* @param array $sessionsByDate
* @param array $ordersByDate
*
* @return array
*/
private function getConversionRate(array $sessionsByDate, array $ordersByDate)
{
$conversionList = [];
foreach ($sessionsByDate as $session) {
$conversion = 0;
foreach ($ordersByDate as $order) {
if ($session['date_analytics'] === $order['date']) {
$conversion += $this->numberHelper->division($order['orders'], $session['sessions_by_account']) * 100;
} else {
$conversion += 0;
}
}
$conversionList[$session['date_analytics']] = [
'date' => $session['date_analytics'],
'conversion' => $conversion,
];
}
return $conversionList;
}
/**
* getConversionRateTotal
*
* @param array $sessionsTotal
* @param int $ordersTotal
*
* @return array
*/
private function getConversionRateTotal(array $sessionsTotal, $ordersTotal)
{
return [
'sessions' => $this->numberHelper->division($ordersTotal, $sessionsTotal['session']) * 100,
'sessionsUnique' => $this->numberHelper->division($ordersTotal, $sessionsTotal['uniqueUser']) * 100,
];
}
}

View File

@@ -0,0 +1,61 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Kpi;
use PrestaShop\Module\Ps_metrics\Kpi\Configuration\KpiConfiguration;
class Kpi
{
/**
* @var KpiConfiguration
*/
private $configuration;
/**
* TotalKpi constructor.
*
* @param KpiConfiguration $kpiConfiguration
*
* @return void
*/
public function __construct(KpiConfiguration $kpiConfiguration)
{
$this->setConfiguration($kpiConfiguration);
}
/**
* @return KpiConfiguration
*/
public function getConfiguration()
{
return $this->configuration;
}
/**
* @param KpiConfiguration $configuration
*
* @return void
*/
public function setConfiguration(KpiConfiguration $configuration)
{
$this->configuration = $configuration;
}
}

View File

@@ -0,0 +1,74 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Kpi;
use PrestaShop\Module\Ps_metrics\Kpi\Configuration\KpiConfiguration;
class KpiManager extends Kpi
{
/**
* @var KpiStrategyInterface
*/
private $kpi;
/**
* KpiManager constructor.
*
* @param KpiConfiguration $kpiConfiguration
*
* @return void
*/
public function __construct(KpiConfiguration $kpiConfiguration)
{
parent::__construct($kpiConfiguration);
}
/**
* Present data
*
* @return array
*/
public function present()
{
$this->kpi->setConfiguration($this->getConfiguration());
return $this->kpi->present();
}
/**
* @param KpiStrategyInterface $kpi
*
* @return void
*/
public function setKpi(KpiStrategyInterface $kpi)
{
$this->kpi = $kpi;
}
/**
* @return KpiStrategyInterface $kpi
*/
public function getKpi()
{
return $this->kpi;
}
}

View File

@@ -0,0 +1,39 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Kpi;
use PrestaShop\Module\Ps_metrics\Kpi\Configuration\KpiConfiguration;
interface KpiStrategyInterface
{
/**
* @return array
*/
public function present();
/**
* @param KpiConfiguration $configuration
*
* @return void
*/
public function setConfiguration(KpiConfiguration $configuration);
}

View File

@@ -0,0 +1,259 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Kpi;
use PrestaShop\Module\Ps_metrics\Helper\DataHelper;
use PrestaShop\Module\Ps_metrics\Helper\NumberHelper;
use PrestaShop\Module\Ps_metrics\Kpi\Configuration\KpiConfiguration;
use PrestaShop\Module\Ps_metrics\Repository\OrdersRepository;
use PrestaShop\Module\Ps_metrics\Repository\PaymentRepository;
class OrdersKpi extends Kpi implements KpiStrategyInterface
{
/**
* @var DataHelper
*/
private $dataHelper;
/**
* @var OrdersRepository
*/
private $ordersRepository;
/**
* @var NumberHelper
*/
private $numberHelper;
/**
* @var RevenuesKpi
*/
private $revenuesKpi;
/**
* @var PaymentRepository
*/
private $paymentRepository;
/**
* @var bool
*/
private $onlyOrderPaidOnWebsite;
/**
* Orders kpi constructor.
*
* @param KpiConfiguration|null $configuration
* @param DataHelper $dataHelper
* @param OrdersRepository $ordersRepository
* @param NumberHelper $numberHelper
* @param RevenuesKpi $revenuesKpi
* @param PaymentRepository $paymentRepository
*/
public function __construct(
KpiConfiguration $configuration = null,
DataHelper $dataHelper,
OrdersRepository $ordersRepository,
NumberHelper $numberHelper,
RevenuesKpi $revenuesKpi,
PaymentRepository $paymentRepository
) {
$this->ordersRepository = $ordersRepository;
$this->dataHelper = $dataHelper;
$this->numberHelper = $numberHelper;
$this->revenuesKpi = $revenuesKpi;
$this->paymentRepository = $paymentRepository;
$this->onlyOrderPaidOnWebsite = false;
if ($configuration !== null) {
$this->setConfiguration($configuration);
}
}
/**
* Return all orders data
*
* @return array
*/
public function present()
{
$orders = $this->ordersRepository->findAllOrdersByDateAndGranularity();
if ($this->onlyOrderPaidOnWebsite) {
$orders = $this->keepOrdersWithPaymentMethodsActivatedInFront($orders);
}
if ('weeks' === $this->getConfiguration()->granularity['type']) {
$orders = $this->dataHelper->transformToGranularityWeeks($orders, ['orders']);
}
if ('hours' === $this->getConfiguration()->granularity['type']) {
$orders = $this->dataHelper->transformToGranularityHours($orders, ['orders']);
}
$cartsOrdered = $this->ordersRepository->findAllCartsOrderedByDate();
$total = $this->getTotalShopOrders($orders);
$this->revenuesKpi->setConfiguration($this->getConfiguration());
$revenuesTotal = $this->revenuesKpi->getTotal();
return [
'orders' => $this->dataHelper->modifyArrayMainKeys($orders, 'date'),
'total' => $total,
'orderCartAverage' => $this->numberHelper->division($revenuesTotal, $total),
'ordersAbandonedCarts' => $this->getAbandonedCarts($cartsOrdered),
'topOrderedProduct' => $this->ordersRepository->findTopOrderedProduct(),
];
}
/**
* Get total orders
*
* @return int
*/
public function getTotal()
{
return $this->getTotalShopOrders(
$this->ordersRepository->findAllOrdersByDateAndGranularity()
);
}
/**
* @return int|void
*/
public function getTotalForConversion()
{
$orders = $this->keepOrdersWithPaymentMethodsActivatedInFront(
$this->ordersRepository->findAllOrdersByDateAndGranularity()
);
$nb_orders = 0;
foreach ($orders as $order) {
$nb_orders += $order['orders'];
}
return $nb_orders;
}
/**
* getTotalShopOrders
*
* @param array $orders
*
* @return int
*/
public function getTotalShopOrders(array $orders = [])
{
if (empty($orders)) {
return 0;
}
$total = 0;
foreach ($orders as $order) {
$total += (int) $order['orders'];
}
return $total;
}
/**
* getAbandonedCarts
*
* @param array $cartsOrdered
*
* @return float
*/
public function getAbandonedCarts(array $cartsOrdered)
{
// To prevent division by 0
if ($cartsOrdered['all_cart'] !== 0 && $cartsOrdered['ordered'] === 0) {
return 100;
}
if ($cartsOrdered['all_cart'] == 0) {
return 0;
}
// Get the percentage of abandoned carts
$percent = 100 - ($cartsOrdered['ordered'] / $cartsOrdered['all_cart']) * 100;
return round($percent, 2);
}
/**
* @param KpiConfiguration $configuration
*/
public function setConfiguration(KpiConfiguration $configuration)
{
parent::setConfiguration($configuration);
$this->ordersRepository->setFilters(
$this->getConfiguration()->dateRange['startDate'],
$this->getConfiguration()->dateRange['endDate'],
$this->getConfiguration()->granularity['forSql']
);
}
/**
* Filter orders with payment methods name
*
* @param array $orders
*
* @return array
*/
public function keepOrdersWithPaymentMethodsActivatedInFront($orders)
{
$paymentsMethods = $this->getActivePaymentMethodNameList();
//keep by active payment method
return array_filter($orders, function ($order) use ($paymentsMethods) {
if (in_array($order['payment_module'], $paymentsMethods)) {
return $order;
}
});
}
/**
* Get all payment methods name actived on the website
*
* @return array
*/
public function getActivePaymentMethodNameList()
{
return $paymentsMethods = $this->dataHelper->BuildKeyListFromArray(
'name',
$this->paymentRepository->getActivePaymentModule()
);
}
/**
* Set true to filter render by orders only paid on website
*
* @param bool $value
*
* @return void
*/
public function setOnlyOrderPaidOnWebsite($value)
{
$this->onlyOrderPaidOnWebsite = $value;
}
}

View File

@@ -0,0 +1,288 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Kpi;
use PrestaShop\Module\Ps_metrics\Helper\DataHelper;
use PrestaShop\Module\Ps_metrics\Kpi\Configuration\KpiConfiguration;
use PrestaShop\Module\Ps_metrics\Repository\OrdersRepository;
class RevenuesKpi extends Kpi implements KpiStrategyInterface
{
/**
* @var OrdersRepository
*/
private $ordersRepository;
/**
* @var DataHelper
*/
private $dataHelper;
/**
* Revenues kpi constructor.
*
* @param KpiConfiguration|null $configuration
* @param DataHelper $dataHelper
* @param OrdersRepository $ordersRepository
*/
public function __construct(
KpiConfiguration $configuration = null,
DataHelper $dataHelper,
OrdersRepository $ordersRepository
) {
$this->ordersRepository = $ordersRepository;
$this->dataHelper = $dataHelper;
if ($configuration !== null) {
$this->setConfiguration($configuration);
}
}
/**
* Return all revenues data
*
* @return array
*/
public function present()
{
return [
'revenues' => $this->dataHelper->modifyArrayMainKeys($this->getRevenues(), 'date'),
'revenuesCategory' => $this->getRevenuesPerCategoryFinalArray(),
'revenuesExploded' => $this->dataHelper->modifyArrayMainKeys($this->getRevenuesTaxAndShipExcluded(), 'date'),
];
}
/**
* getTotalRevenues
*
* @return float
*/
public function getTotal()
{
$revenues = $this->getRevenues();
if (empty($revenues)) {
return 0;
}
$total = 0;
foreach ($revenues as $revenue) {
$total += (float) $revenue['revenues'];
}
return $total;
}
/**
* Complete a revenue table for customers without orders and customers with orders
*
* @return array
*/
public function getTotalCustomersRevenues()
{
$revenues = $this->dataHelper->subtractDataRecursively(
$this->ordersRepository->findAllRevenuesByCustomerByDateAndGranularity(),
'revenues',
'refund'
);
$totalRevenuesWithOrders = 0;
$totalRevenuesWithoutOrders = 0;
$totalCustomersWithOrders = 0;
$totalCustomersWithoutOrders = 0;
$revenuesSorted = [];
foreach ($revenues as $revenue) {
$date = ('weeks' === $this->getConfiguration()->granularity['type']) ?
(new \DateTime($revenue['date']))->format('Y-W') : $revenue['date'];
if (!array_key_exists($date, $revenuesSorted)) {
$revenuesSorted[$date] = [];
}
if (!array_key_exists($revenue['id_customer'], $revenuesSorted[$date])) {
$totalRevenuesWithoutOrders += $revenue['revenues'];
++$totalCustomersWithoutOrders;
$revenuesSorted[$date][$revenue['id_customer']] = true;
} else {
$totalRevenuesWithOrders += $revenue['revenues'];
++$totalCustomersWithOrders;
}
}
return [
'with_orders' => [
'revenues' => $this->presentRevenue('revenues_with_orders', $totalRevenuesWithOrders, $totalRevenuesWithOrders + $totalRevenuesWithoutOrders),
'customers' => $this->presentRevenue('customers_with_orders', $totalCustomersWithOrders, $totalCustomersWithOrders + $totalCustomersWithoutOrders),
],
'without_orders' => [
'revenues' => $this->presentRevenue('revenues_without_orders', $totalRevenuesWithoutOrders, $totalRevenuesWithOrders + $totalRevenuesWithoutOrders),
'customers' => $this->presentRevenue('customers_without_orders', $totalCustomersWithoutOrders, $totalCustomersWithOrders + $totalCustomersWithoutOrders),
],
];
}
/**
* Present datas
*
* @param string $label
* @param float $value
* @param float $total
*
* @return array
*/
public function presentRevenue($label, $value, $total)
{
// to fix divised by 0 if no datas
$total = (0 == $total) ? 1 : $total;
return [
'label' => $label,
'value' => $value,
'percent' => ((100 * $value) / $total),
];
}
/**
* Retrieve revenues
*
* @return array
*/
private function getRevenues()
{
$revenues = $this->dataHelper->subtractDataRecursively(
$this->ordersRepository->findAllRevenuesByDateAndGranularity(),
'revenues',
'refund'
);
if ('weeks' === $this->getConfiguration()->granularity['type']) {
$revenues = $this->dataHelper->transformToGranularityWeeks($revenues, ['revenues']);
}
if ('hours' === $this->getConfiguration()->granularity['type']) {
$revenues = $this->dataHelper->transformToGranularityHours($revenues, ['revenues']);
}
return $revenues;
}
/**
* Retrieve revenues, taxes and shipment in separated fields
*
* @return array
*/
private function getRevenuesTaxAndShipExcluded()
{
$revenues = $this->ordersRepository->findAllRevenuesByDateAndGranularityTaxExcluded();
if ('weeks' === $this->getConfiguration()->granularity['type']) {
$revenues = $this->dataHelper->transformToGranularityWeeks($revenues, ['revenues', 'shipping', 'refund', 'tax']);
}
if ('hours' === $this->getConfiguration()->granularity['type']) {
$revenues = $this->dataHelper->transformToGranularityHours($revenues, ['revenues', 'shipping', 'refund', 'tax']);
}
return $revenues;
}
/**
* getRevenuesPerCategoryFinalArray
*
* @return array
*/
private function getRevenuesPerCategoryFinalArray()
{
$revenuesPerCategory = $this->dataHelper->subtractDataRecursively(
$this->ordersRepository->findAllBestCategoriesRevenuesByDate(),
'revenues',
'refund'
);
$revenuesPerCategory = $this->dataHelper->arrayMultiSort($revenuesPerCategory, 'revenues');
$finalArray = [];
$dateRangeStart = date('Y-m-d', strtotime($this->getConfiguration()->dateRange['startDate']));
$dateRangeEnd = date('Y-m-d', strtotime($this->getConfiguration()->dateRange['endDate']));
foreach ($revenuesPerCategory as $category) {
$dateOrder = date('Y-m-d', strtotime($category['date_add']));
if (($dateOrder >= $dateRangeStart) && ($dateOrder <= $dateRangeEnd)) {
$finalArray[] = [
'name' => $category['name'],
'value' => ($category['revenues']),
];
}
}
return array_splice($finalArray, 0, 10);
}
/**
* @param KpiConfiguration $configuration
*/
public function setConfiguration(KpiConfiguration $configuration)
{
parent::setConfiguration($configuration);
$this->ordersRepository->setFilters(
$this->getConfiguration()->dateRange['startDate'],
$this->getConfiguration()->dateRange['endDate'],
$this->getConfiguration()->granularity['forSql']
);
}
/**
* Get datas from payment methods
*
* @return array[]
*/
public function getTotalPaymentMethodsRevenues()
{
$payments_methods = [
'labels' => [],
'values' => [],
'percents' => [],
];
$revenues = $this->dataHelper->subtractDataRecursively(
$this->ordersRepository->findAllRevenuesByPaymentMethodsByDateAndGranularity(),
'revenues',
'refund'
);
if (!empty($revenues)) {
// get total revenues
// to fix divised by 0 if no datas
$totalRevenues = array_sum(array_column($revenues, 'revenues'));
$totalRevenues = (0 == $totalRevenues) ? 1 : $totalRevenues;
//% of revenue by payment method
foreach ($revenues as $payment_method) {
$payments_methods['labels'][] = $payment_method['payment_method'];
$payments_methods['values'][] = round($payment_method['revenues'], 2);
$payments_methods['percents'][] = round(((100 * $payment_method['revenues']) / $totalRevenues), 2);
}
}
return $payments_methods;
}
}

View File

@@ -0,0 +1,81 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Kpi;
use PrestaShop\Module\Ps_metrics\Kpi\Configuration\KpiConfiguration;
class TotalKpi extends Kpi implements KpiStrategyInterface
{
/**
* @var VisitsKpi
*/
private $visitsKpi;
/**
* @var OrdersKpi
*/
private $ordersKpi;
/**
* @var RevenuesKpi
*/
private $revenuesKpi;
/**
* TotalKpi constructor.
*
* @param KpiConfiguration $kpiConfiguration
* @param VisitsKpi $visitsKpi
* @param OrdersKpi $ordersKpi
* @param RevenuesKpi $revenuesKpi
*/
public function __construct(
KpiConfiguration $kpiConfiguration,
VisitsKpi $visitsKpi,
OrdersKpi $ordersKpi,
RevenuesKpi $revenuesKpi
) {
parent::__construct($kpiConfiguration);
$this->visitsKpi = $visitsKpi;
$this->ordersKpi = $ordersKpi;
$this->revenuesKpi = $revenuesKpi;
}
/**
* Return all revenues data
*
* @return array
*/
public function present()
{
$this->revenuesKpi->setConfiguration($this->getConfiguration());
$this->ordersKpi->setConfiguration($this->getConfiguration());
$this->visitsKpi->setConfiguration($this->getConfiguration());
return [
'revenuesTotal' => $this->revenuesKpi->getTotal(),
'ordersTotal' => $this->ordersKpi->getTotal(),
'ordersTotalForConversion' => $this->ordersKpi->getTotalForConversion(),
'visits' => $this->visitsKpi->getTotal(),
];
}
}

View File

@@ -0,0 +1,203 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Kpi;
use PrestaShop\Module\Ps_metrics\Api\AnalyticsApi;
use PrestaShop\Module\Ps_metrics\Cache\DataCache;
use PrestaShop\Module\Ps_metrics\Helper\DataHelper;
use PrestaShop\Module\Ps_metrics\Kpi\Configuration\KpiConfiguration;
use PrestaShop\Module\Ps_metrics\Repository\ConfigurationRepository;
class VisitsKpi extends Kpi implements KpiStrategyInterface
{
/**
* @var DataHelper
*/
private $dataHelper;
/**
* @var DataCache
*/
private $dataCache;
/**
* @var ConfigurationRepository
*/
private $configurationRepository;
/**
* @var AnalyticsApi
*/
private $analyticsApi;
/**
* Visits kpi constructor.
*
* @param KpiConfiguration|null $configuration
* @param DataHelper $dataHelper
* @param DataCache $dataCache
* @param ConfigurationRepository $configurationRepository
* @param AnalyticsApi $analyticsApi
*/
public function __construct(
KpiConfiguration $configuration = null,
DataHelper $dataHelper,
DataCache $dataCache,
ConfigurationRepository $configurationRepository,
AnalyticsApi $analyticsApi
) {
$this->dataHelper = $dataHelper;
$this->dataCache = $dataCache;
$this->configurationRepository = $configurationRepository;
$this->analyticsApi = $analyticsApi;
if ($configuration !== null) {
$this->setConfiguration($configuration);
}
}
/**
* Return all visits data
*
* @return array
*/
public function present()
{
return $this->getData();
}
/**
* Return all visits data
*
* @return array
*/
public function getTotal()
{
$total = $this->getData();
return $total['visits'];
}
/**
* Return all visits data
*
* @return array
*
* @todo Better way to user granularity['type'] for request
*/
private function getData()
{
$gaIsOnboarded = (bool) $this->configurationRepository->getGoogleLinkedValue();
if (!$gaIsOnboarded) {
return [
'visits' => $this->setEmptyVisitsData(),
];
}
$dataCacheName = 'visits' . implode($this->getConfiguration()->dateRange) . $this->getConfiguration()->granularity['type'];
$visitsCache = $this->dataCache->get($dataCacheName);
if (false !== $visitsCache) {
return [
'visits' => $visitsCache,
];
}
$reportings = $this->analyticsApi->getReportingByDate([
'dateRange' => $this->getConfiguration()->dateRange,
'granularity' => $this->getConfiguration()->granularity['type'],
]);
if (false == $reportings) {
return [
'visits' => $this->setEmptyVisitsData(),
];
}
return [
'visits' => $this->dataCache->set(
$this->getReworkedGoogleVisitsArray($reportings),
$dataCacheName
),
];
}
/**
* Rework $googleVisits array to get 'byDate' with date key
*
* @param array $googleVisits
*
* @return array
*/
private function getReworkedGoogleVisitsArray(array $googleVisits)
{
if (empty($googleVisits['body'])) {
return $this->setEmptyVisitsData();
}
if ($this->getConfiguration()->granularity['type'] == 'hours') {
$googleVisits['body']['byDate'] = $this->ConvertHoursFormat($googleVisits['body']['byDate']);
}
$googleVisits['body']['byDate'] = $this->dataHelper->modifyArrayMainKeys($googleVisits['body']['byDate'], 'date_analytics');
return $googleVisits['body'];
}
/**
* Convert hours returned by google to date : 01 -> YYYY-MM-DD HH:II:SS
*
* @param array $googleVisits
*
* @return array
*/
private function ConvertHoursFormat(array $googleVisits)
{
$visits_ = [];
foreach ($googleVisits as $visit) {
$visit_ = $visit;
$visit_['date_analytics'] = $visit['start_date'] . ' ' . (int) $visit['date_analytics'] . ':00:00';
array_push($visits_, $visit_);
}
return $visits_;
}
/**
* setEmptyVisitsData
*
* @return array
*/
private function setEmptyVisitsData()
{
return [
'byCategory' => [],
'byDate' => [],
'bySource' => [],
'total' => [
'session' => 0,
'uniqueUser' => 0,
],
];
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,71 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Middleware;
use PrestaShop\Module\Ps_metrics\Helper\JsonHelper;
class CheckResponseMiddleware extends Middleware
{
/**
* @var JsonHelper
*/
private $jsonHelper;
/**
* CheckResponseAnalyticsMiddleware constructor.
*
* @param JsonHelper $jsonHelper
*
* @return void
*/
public function __construct(JsonHelper $jsonHelper)
{
$this->jsonHelper = $jsonHelper;
}
/**
* @param mixed $response
*
* @return array
*/
public function execute($response)
{
$responseFormatted = [
'code' => $response->getStatusCode(),
'body' => [],
'error' => '',
];
if (
200 != $response->getStatusCode() &&
201 != $response->getStatusCode()
) {
$responseFormatted['error'] = $response->getReasonPhrase();
}
if (!empty($response->getBody())) {
$responseFormatted['body'] = $this->jsonHelper->jsonDecode($response->getBody()->getContents(), true);
}
return parent::execute($responseFormatted);
}
}

View File

@@ -0,0 +1,51 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Middleware;
use PrestaShop\Module\Ps_metrics\Helper\LoggerHelper;
class LogMiddleware extends Middleware
{
/**
* @var LoggerHelper
*/
private $loggerHelper;
public function __construct(LoggerHelper $loggerHelper)
{
$this->loggerHelper = $loggerHelper;
}
/**
* @param array $response
*
* @return array
*/
public function execute($response)
{
if (!empty($response['error'])) {
$this->loggerHelper->addLog($response['error'], $response['code']);
}
// Do nothing for the moment
return parent::execute($response);
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Middleware;
abstract class Middleware
{
/**
* @var Middleware
*/
private $next;
/**
* Middleware constructor.
*/
public function __construct()
{
}
/**
* @param Middleware $next
*
* @return Middleware
*/
public function linkWith(Middleware $next)
{
$this->next = $next;
return $next;
}
/**
* @param array $response
*
* @return array
*/
public function execute($response)
{
if (empty($this->next)) {
return $response;
}
return $this->next->execute($response);
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Middleware;
class ResponseMiddleware extends Middleware
{
/**
* @param array $response
*
* @return array
*/
public function execute($response)
{
return parent::execute($response);
}
}

View File

@@ -0,0 +1,36 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Middleware;
class SentryMiddleware extends Middleware
{
/**
* @param array $response
*
* @return array
*/
public function execute($response)
{
// do nothing for the moment
return parent::execute($response);
}
}

View File

@@ -0,0 +1,11 @@
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Location: ../");
exit;

View File

@@ -0,0 +1,157 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Module;
use PrestaShop\Module\Ps_metrics\Repository\ConfigurationRepository;
use PrestaShop\Module\Ps_metrics\Tracker\Segment;
class DashboardModules
{
/**
* @var \Ps_metrics
*/
private $module;
/**
* @var ConfigurationRepository
*/
private $configurationRepository;
/**
* @var array
*/
private $moduleList = [
'dashactivity',
'dashtrends',
'dashgoals',
'dashproducts',
];
/**
* DashboardModules constructor.
*
* @param \Ps_metrics $module
* @param ConfigurationRepository $configurationRepository
*/
public function __construct(
\Ps_metrics $module,
ConfigurationRepository $configurationRepository
) {
$this->module = $module;
$this->configurationRepository = $configurationRepository;
}
/**
* Enable back dashboard modules
*
* @return array|bool return the list of module that has been enabled or true if there no module to enable back
*/
public function enableModules()
{
// retrieve module list to enable
$moduleListToEnable = $this->configurationRepository->getDashboardModulesToToggle();
// if the module list is empty, do nothing
if (empty($moduleListToEnable)) {
return true;
}
foreach ($moduleListToEnable as $moduleName) {
$module = \Module::getInstanceByName($moduleName);
if (false !== $module) {
$module->enable();
}
}
// now that modules has been enabled back again, reset the list from database
$this->configurationRepository->saveDashboardModulesToToggle();
/** @var Segment $segment */
$segment = $this->module->getService('ps_metrics.tracker.segment');
$segment->setMessage('Enable stats modules');
$segment->track();
return $moduleListToEnable;
}
/**
* Disable dashboard modules
*
* @return array return the list of module that has been disabled
*/
public function disableModules()
{
// get module to disable
$modulesToDisable = $this->getModuleToToggle();
$disabledModuleList = [];
foreach ($modulesToDisable as $moduleName => $isEnabled) {
// only disable modules that is currently enable
if ($isEnabled) {
$module = \Module::getInstanceByName($moduleName);
if (false !== $module) {
$module->disable();
array_push($disabledModuleList, $moduleName);
}
}
}
// save to database the list of module that has been disable by metrics in order to be able
// to turn it on if needed
$this->configurationRepository->saveDashboardModulesToToggle($disabledModuleList);
/** @var Segment $segment */
$segment = $this->module->getService('ps_metrics.tracker.segment');
$segment->setMessage('Disable stats modules');
$segment->track();
return $disabledModuleList;
}
/**
* Get the current state of dashboard modules
* We presuming that modules is enabled if the disabled module list in database is empty
*
* @return bool
*/
public function modulesIsEnabled()
{
return empty($this->configurationRepository->getDashboardModulesToToggle());
}
/**
* Create a list of module from the default list in order to know which modules is
* currently enabled or disabled on the shop
*
* @return array
*/
private function getModuleToToggle()
{
$modules = [];
foreach ($this->moduleList as $moduleName) {
$isModuleEnabled = \Module::isEnabled($moduleName);
$modules[$moduleName] = $isModuleEnabled;
}
return $modules;
}
}

View File

@@ -0,0 +1,180 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Module;
use PrestaShop\Module\Ps_metrics\Adapter\LinkAdapter;
use PrestaShop\Module\Ps_metrics\Helper\ModuleHelper;
use PrestaShop\Module\Ps_metrics\Helper\ToolsHelper;
class GAInstaller
{
/**
* @var string
*/
private $moduleName = 'ps_googleanalytics';
/**
* @var LinkAdapter
*/
private $linkAdapter;
/**
* @var ModuleHelper
*/
private $moduleHelper;
/**
* @var ToolsHelper
*/
private $toolsHelper;
/**
* @var \Symfony\Component\DependencyInjection\ContainerInterface
*/
protected $container;
/**
* GAInstaller constructor.
*
* @param LinkAdapter $linkAdapter
* @param ModuleHelper $moduleHelper
* @param ToolsHelper $toolsHelper
*
* @return void
*/
public function __construct(LinkAdapter $linkAdapter, ModuleHelper $moduleHelper, ToolsHelper $toolsHelper)
{
$this->linkAdapter = $linkAdapter;
$this->moduleHelper = $moduleHelper;
$this->toolsHelper = $toolsHelper;
}
/**
* Return shop is on 1.7
*
* @return bool
*/
private function isShop173()
{
return version_compare(_PS_VERSION_, '1.7.3.0', '>=');
}
/**
* Check if google analytics module is installed or not
*
* @return bool
*/
public function isInstalled()
{
return $this->moduleHelper->isInstalled($this->moduleName);
}
/**
* Check if google analytics module is enabled or not
*
* @return bool
*/
public function isEnabled()
{
return $this->moduleHelper->isEnabled($this->moduleName);
}
/**
* returns the installation link of the ps_googleanalytics module if it is not installed. If installed, returns an empty string
*
* @return string
*/
public function getInstallLink()
{
if (true === $this->moduleHelper->isInstalled($this->moduleName)) {
return '';
}
if ($this->isShop173()) {
$router = $this->get('router');
return substr($this->toolsHelper->getShopDomainSsl(true) . __PS_BASE_URI__, 0, -1) . $router->generate('admin_module_manage_action', [
'action' => 'install',
'module_name' => $this->moduleName,
]);
}
return $this->linkAdapter->getAdminLink('AdminModules', true, [], [
'module_name' => $this->moduleName,
'install' => $this->moduleName,
]);
}
/**
* Override of native function to always retrieve Symfony container instead of legacy admin container on legacy context.
*
* @param string $serviceName
*
* @return mixed
*/
private function get($serviceName)
{
if (null === $this->container) {
$this->container = \PrestaShop\PrestaShop\Adapter\SymfonyContainer::getInstance();
}
return $this->container->get($serviceName);
}
/**
* returns the enable link of the ps_googleanalytics module if it is not enabled. If enabled, returns an empty string
*
* @return string
*/
public function getEnableLink()
{
if (true === $this->moduleHelper->isEnabled($this->moduleName)) {
return '';
}
if ($this->isShop173()) {
$router = $this->get('router');
return substr($this->toolsHelper->getShopDomainSsl(true) . __PS_BASE_URI__, 0, -1) . $router->generate('admin_module_manage_action', [
'action' => 'enable',
'module_name' => $this->moduleName,
]);
}
return $this->linkAdapter->getAdminLink('AdminModules', true, [], [
'module_name' => $this->moduleName,
'enable' => '1',
]);
}
/**
* returns the configuration link of the ps_googleanalytics module if it is not configured. If configured, returns an empty string
*
* @return string
*/
public function getConfigLink()
{
return $this->linkAdapter->getAdminLink('AdminModules', true, [], [
'configure' => $this->moduleName,
]);
}
}

View File

@@ -0,0 +1,124 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Module;
use Hook;
use Language;
use PrestaShop\Module\Ps_metrics\Repository\ConfigurationRepository;
use PrestaShop\Module\Ps_metrics\Repository\HookModuleRepository;
use Ps_metrics;
use Tab;
class Install
{
/**
* @var Ps_metrics
*/
private $module;
/**
* @var ConfigurationRepository
*/
private $configurationRepository;
/**
* @var HookModuleRepository
*/
private $hookModuleRepository;
/**
* Install constructor.
*
* @param Ps_metrics $module
* @param ConfigurationRepository $configurationRepository
* @param HookModuleRepository $hookModuleRepository
*
* @return void
*/
public function __construct(Ps_metrics $module, ConfigurationRepository $configurationRepository, HookModuleRepository $hookModuleRepository)
{
$this->module = $module;
$this->configurationRepository = $configurationRepository;
$this->hookModuleRepository = $hookModuleRepository;
}
/**
* updateModuleHookPosition
*
* @param string $hookName
* @param int $position
*
* @return bool
*/
public function updateModuleHookPosition($hookName, $position)
{
$hookId = Hook::getIdByName($hookName);
if (false == $hookId) {
return false;
}
return $this->hookModuleRepository->setModuleHookPosition($hookId, $this->module->id, $position);
}
/**
* setConfigurationValues
*
* @return bool
*/
public function setConfigurationValues()
{
return $this->configurationRepository->saveActionGoogleLinked(false) &&
$this->configurationRepository->saveGoogleTagLinked(false) &&
$this->configurationRepository->saveDashboardModulesToToggle();
}
/**
* This method is often use to create an ajax controller
*
* @return bool
*
* @todo Change Language by context lang ?
*/
public function installTabs()
{
$installTabCompleted = true;
foreach ($this->module->controllers as $controllerName) {
if (Tab::getIdFromClassName($controllerName)) {
continue;
}
$tab = new Tab();
$tab->class_name = $controllerName;
$tab->active = true;
$tab->name = array_fill_keys(
Language::getIDs(false),
$this->module->displayName
);
$tab->id_parent = -1;
$tab->module = $this->module->name;
$installTabCompleted = $installTabCompleted && $tab->add();
}
return $installTabCompleted;
}
}

View File

@@ -0,0 +1,153 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Module;
use Module;
use PrestaShop\AccountsAuth\Service\PsAccountsService;
use PrestaShop\Module\Ps_metrics\Api\AnalyticsApi;
use PrestaShop\Module\Ps_metrics\Helper\JsonHelper;
use PrestaShop\Module\Ps_metrics\Helper\LoggerHelper;
use PrestaShop\Module\Ps_metrics\Helper\ModuleHelper;
use PrestaShop\Module\Ps_metrics\Repository\ConfigurationRepository;
use Ps_metrics;
use Tab;
use Validate;
class Uninstall
{
/**
* @var Ps_metrics|Module
*/
private $module;
/**
* @var ConfigurationRepository
*/
private $configurationRepository;
/**
* @var JsonHelper
*/
private $jsonHelper;
/**
* @var ModuleHelper
*/
private $moduleHelper;
/**
* @var LoggerHelper
*/
private $loggerHelper;
/**
* @var AnalyticsApi
*/
private $analyticsApi;
/**
* Uninstall constructor.
*
* @param Module $module
* @param ConfigurationRepository $configurationRepository
* @param JsonHelper $jsonHelper
* @param ModuleHelper $moduleHelper
* @param LoggerHelper $loggerHelper
* @param AnalyticsApi $analyticsApi
*/
public function __construct(
Module $module,
ConfigurationRepository $configurationRepository,
JsonHelper $jsonHelper,
ModuleHelper $moduleHelper,
LoggerHelper $loggerHelper,
AnalyticsApi $analyticsApi
) {
$this->module = $module;
$this->configurationRepository = $configurationRepository;
$this->jsonHelper = $jsonHelper;
$this->moduleHelper = $moduleHelper;
$this->loggerHelper = $loggerHelper;
$this->analyticsApi = $analyticsApi;
}
/**
* resetConfigurationValues
*
* @return bool
*/
public function resetConfigurationValues()
{
return $this->configurationRepository->saveActionGoogleLinked(false);
}
/**
* uninstall tabs
*
* @return bool
*/
public function uninstallTabs()
{
$uninstallTabCompleted = true;
foreach ($this->module->controllers as $controllerName) {
$idTab = (int) Tab::getIdFromClassName($controllerName);
$tab = new Tab($idTab);
if (Validate::isLoadedObject($tab)) {
$uninstallTabCompleted = $uninstallTabCompleted && $tab->delete();
}
}
return $uninstallTabCompleted;
}
/**
* unsubscribePsEssentials
*
* @return bool
*/
public function unsubscribePsEssentials()
{
// if the user is not onboarded, don't process unsubscribe
if (!$this->isOnboardedWithAccountAndGoogle()) {
return true;
}
return $this->analyticsApi->unsubscribe();
}
/**
* Check if the user is onboarded on prestashop account and google
*
* @return bool
*/
private function isOnboardedWithAccountAndGoogle()
{
if (false === (new PsAccountsService())->getShopUuidV4() &&
false === $this->configurationRepository->getGoogleLinkedValue()
) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,34 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Presenter;
/**
* Interface StorePresenter defines methods for store presenter.
*/
interface PresenterInterface
{
/**
* Present store
*
* @return array
*/
public function present();
}

View File

@@ -0,0 +1,173 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Presenter\Store\Context;
use PrestaShop\AccountsAuth\Service\PsAccountsService;
use PrestaShop\Module\Ps_metrics\Adapter\LinkAdapter;
use PrestaShop\Module\Ps_metrics\Context\PrestaShopContext;
use PrestaShop\Module\Ps_metrics\Module\DashboardModules;
use PrestaShop\Module\Ps_metrics\Presenter\PresenterInterface;
use PrestaShop\Module\Ps_metrics\Provider\ShopsProvider;
use PrestaShop\Module\Ps_metrics\Repository\ConfigurationRepository;
use Ps_metrics;
class ContextPresenter implements PresenterInterface
{
/**
* @var Ps_metrics
*/
private $module;
/**
* @var PrestaShopContext
*/
private $context;
/**
* @var LinkAdapter
*/
private $linkAdapter;
/**
* @var ConfigurationRepository
*/
private $configurationRepository;
/**
* @var ShopsProvider
*/
private $shopsProvider;
/**
* @var DashboardModules;
*/
private $dashboardModules;
public function __construct(
Ps_metrics $module,
PrestaShopContext $context,
LinkAdapter $linkAdapter,
ConfigurationRepository $configurationRepository,
ShopsProvider $shopsProvider,
DashboardModules $dashboardModules
) {
$this->module = $module;
$this->context = $context;
$this->linkAdapter = $linkAdapter;
$this->configurationRepository = $configurationRepository;
$this->shopsProvider = $shopsProvider;
$this->dashboardModules = $dashboardModules;
}
/**
* Tells if we can show the Dashboard App by checking if there's a refresh token and Google Linked Value
*
* @return bool
*/
protected function canShowDashboardApp()
{
$psxService = new PsAccountsService();
if (null === $psxService->getFirebaseRefreshToken()) {
return false;
}
if (false === $this->configurationRepository->getGoogleLinkedValue()) {
return false;
}
return true;
}
/**
* Present the Context Vuex
*
* @return array
*/
public function present()
{
$psAccountsService = new PsAccountsService();
$currentShop = $this->shopsProvider->getShopUrl($this->context->getShopId());
return [
'context' => [
'app' => $this->getCurrentVueApp(),
'canShowDashboard' => $this->canShowDashboardApp(),
'user' => [
'email' => $psAccountsService->getEmail(),
'emailIsValidated' => $psAccountsService->isEmailValidated(),
'isSuperAdmin' => $psAccountsService->getContext()->employee->isSuperAdmin(),
'gaIsOnboarded' => (bool) $this->configurationRepository->getGoogleLinkedValue(),
],
'dashboardModulesState' => $this->dashboardModules->modulesIsEnabled(),
'version_ps' => _PS_VERSION_,
'version_module' => $this->module->version,
'shopId' => $psAccountsService->getShopUuidV4(),
'isShop17' => version_compare(_PS_VERSION_, '1.7.3.0', '>='),
'configurationLink' => $this->linkAdapter->getAdminLink('AdminModules', true, [], ['configure' => $this->module->name]),
'controllersLinks' => [
'dashboard' => $this->linkAdapter->getAdminLink($this->module->ajaxDashboardController),
'settings' => $this->linkAdapter->getAdminLink($this->module->ajaxSettingsController),
],
'i18n' => [
'isoCode' => $this->context->getLanguageIsoCode(),
'languageLocale' => $this->context->getLanguageCode(),
'currencyIsoCode' => $this->context->getCurrencyIsoCode(),
],
'shop' => [
'domain' => $currentShop['domain'],
'url' => $currentShop['url'],
],
'readmeUrl' => $this->getReadme(),
],
];
}
/**
* Get Vue App to use in terms of context Controller Name
*
* @return string
*/
private function getCurrentVueApp()
{
if ('AdminDashboard' === $this->context->getControllerName()) {
return 'dashboard';
}
return 'settings';
}
/**
* Get the documentation url depending on the current language
*
* @return string path of the doc
*/
private function getReadme()
{
$isoCode = $this->context->getLanguageIsoCode();
if (!file_exists(_PS_ROOT_DIR_ . _MODULE_DIR_ . $this->module->name . '/docs/readme_' . $isoCode . '.pdf')) {
$isoCode = 'en';
}
return _MODULE_DIR_ . $this->module->name . '/docs/readme_' . $isoCode . '.pdf';
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,85 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Presenter\Store\Dashboard;
use PrestaShop\Module\Ps_metrics\Adapter\LinkAdapter;
use PrestaShop\Module\Ps_metrics\Context\PrestaShopContext;
use PrestaShop\Module\Ps_metrics\Presenter\PresenterInterface;
use PrestaShop\Module\Ps_metrics\Translation\DashboardTranslation;
use Ps_metrics;
class DashboardPresenter implements PresenterInterface
{
/**
* @var Ps_metrics
*/
private $module;
/**
* @var PrestaShopContext
*/
private $context;
/**
* @var DashboardTranslation
*/
private $translations;
/**
* @var LinkAdapter
*/
private $linkAdapter;
/**
* DashboardPresenter constructor.
*
* @param Ps_metrics $module
* @param PrestaShopContext $context
* @param DashboardTranslation $dashboardTranslation
* @param LinkAdapter $linkAdapter
*/
public function __construct(
Ps_metrics $module,
PrestaShopContext $context,
DashboardTranslation $dashboardTranslation,
LinkAdapter $linkAdapter
) {
$this->module = $module;
$this->context = $context;
$this->translations = $dashboardTranslation;
$this->linkAdapter = $linkAdapter;
}
/**
* Present the Dashboard App Vuex
*
* @return array
*/
public function present()
{
return [
'dashboard' => [
'translations' => $this->translations->getTranslations(),
'linkAdminCarts' => $this->linkAdapter->getAdminLink('AdminCarts', true, [], []),
],
];
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,183 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Presenter\Store\Settings;
use PrestaShop\Module\Ps_metrics\Adapter\LinkAdapter;
use PrestaShop\Module\Ps_metrics\Api\HttpApi;
use PrestaShop\Module\Ps_metrics\Context\PrestaShopContext;
use PrestaShop\Module\Ps_metrics\Module\GAInstaller;
use PrestaShop\Module\Ps_metrics\Presenter\PresenterInterface;
use PrestaShop\Module\Ps_metrics\Provider\AnalyticsAccountsListProvider;
use PrestaShop\Module\Ps_metrics\Provider\GoogleTagProvider;
use PrestaShop\Module\Ps_metrics\Provider\ShopsProvider;
use PrestaShop\Module\Ps_metrics\Repository\ConfigurationRepository;
use PrestaShop\Module\Ps_metrics\Translation\SettingsTranslation;
use Ps_metrics;
class SettingsPresenter implements PresenterInterface
{
/**
* @var Ps_metrics
*/
private $module;
/**
* @var PrestaShopContext
*/
private $context;
/**
* @var string
*/
private $responseApiMessage;
/**
* @var int
*/
private $countProperty;
/**
* @var SettingsTranslation
*/
private $translations;
/**
* @var LinkAdapter
*/
private $linkAdapter;
/**
* @var ConfigurationRepository
*/
private $configurationRepository;
/**
* @var ShopsProvider
*/
private $shopsProvider;
/**
* @var AnalyticsAccountsListProvider
*/
private $analyticsAccountsListProvider;
/**
* @var GoogleTagProvider
*/
private $googleTagProvider;
/**
* @var GAInstaller
*/
private $gaInstaller;
/**
* @var HttpApi
*/
private $httpApi;
/**
* SettingsPresenter constructor.
*
* @param Ps_metrics $module
* @param PrestaShopContext $context
* @param SettingsTranslation $settingsTranslation
* @param LinkAdapter $linkAdapter
* @param ConfigurationRepository $configurationRepository
* @param ShopsProvider $shopsProvider
* @param AnalyticsAccountsListProvider $analyticsAccountsListProvider
* @param GoogleTagProvider $googleTagProvider
* @param GAInstaller $gaInstaller
* @param HttpApi $httpApi
*/
public function __construct(
Ps_metrics $module,
PrestaShopContext $context,
SettingsTranslation $settingsTranslation,
LinkAdapter $linkAdapter,
ConfigurationRepository $configurationRepository,
ShopsProvider $shopsProvider,
AnalyticsAccountsListProvider $analyticsAccountsListProvider,
GoogleTagProvider $googleTagProvider,
GAInstaller $gaInstaller,
HttpApi $httpApi
) {
$this->module = $module;
$this->context = $context;
$this->translations = $settingsTranslation;
$this->linkAdapter = $linkAdapter;
$this->configurationRepository = $configurationRepository;
$this->shopsProvider = $shopsProvider;
$this->analyticsAccountsListProvider = $analyticsAccountsListProvider;
$this->googleTagProvider = $googleTagProvider;
$this->gaInstaller = $gaInstaller;
$this->httpApi = $httpApi;
}
/**
* @param string $responseApiMessage
* @param int $countProperty
*
* @return void
*/
public function setSettings($responseApiMessage, $countProperty = 0)
{
$this->responseApiMessage = $responseApiMessage;
$this->countProperty = $countProperty;
}
/**
* Present the Setting App Vuex
*
* @return array
*/
public function present()
{
$currentShop = $this->shopsProvider->getShopUrl($this->context->getShopId());
$this->googleTagProvider->setBaseUrl($currentShop['url']);
$faq = $this->httpApi->getFaq($this->module->module_key, $this->context->getLanguageIsoCode(), _PS_VERSION_);
return [
'settings' => [
'faq' => $faq,
'translations' => $this->translations->getTranslations(),
'googleLinked' => (bool) $this->configurationRepository->getGoogleLinkedValue(),
'countProperty' => $this->countProperty,
'googleLinkedUrl' => $this->linkAdapter->getAdminLink($this->module->oauthAdminController, true, [], ['from' => 'PS']),
'googleAccountsList' => $this->analyticsAccountsListProvider->getAccountsList(),
'googleAccount' => $this->analyticsAccountsListProvider->getSelectedAccount(),
'googleUserName' => $this->analyticsAccountsListProvider->getUserName(),
'GTAAvailable' => $this->googleTagProvider->findGoogleTagsAnalytics(),
'GTMAvailable' => $this->googleTagProvider->findGoogleTagsManager(),
'gaModule' => [
'isInstalled' => $this->gaInstaller->isInstalled(),
'isEnabled' => $this->gaInstaller->isEnabled(),
'installLink' => $this->gaInstaller->getInstallLink(),
'enableLink' => $this->gaInstaller->getEnableLink(),
'configLink' => $this->gaInstaller->getConfigLink(),
],
'oAuthGoogleErrorMessage' => $this->responseApiMessage,
'linkDashboard' => $this->linkAdapter->getAdminLink('AdminDashboard', true, [], []),
],
];
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,150 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Presenter\Store;
use PrestaShop\Module\Ps_metrics\Context\PrestaShopContext;
use PrestaShop\Module\Ps_metrics\Presenter\PresenterInterface;
use PrestaShop\Module\Ps_metrics\Presenter\Store\Context\ContextPresenter;
use PrestaShop\Module\Ps_metrics\Presenter\Store\Dashboard\DashboardPresenter;
use PrestaShop\Module\Ps_metrics\Presenter\Store\Settings\SettingsPresenter;
use Ps_metrics;
/**
* Present the store to the vuejs app (vuex)
*/
class StorePresenter implements PresenterInterface
{
/**
* @var Ps_metrics
*/
private $module;
/**
* @var PrestaShopContext
*/
private $context;
/**
* @var array
*/
private $store;
/**
* @var string
*/
private $responseApiMessage;
/**
* @var int
*/
private $countProperty;
/**
* @var ContextPresenter
*/
private $contextPresenter;
/**
* @var DashboardPresenter
*/
private $dashboardPresenter;
/**
* @var SettingsPresenter
*/
private $settingsPresenter;
/**
* StorePresenter constructor.
*
* @param Ps_metrics $module
* @param PrestaShopContext $context
* @param ContextPresenter $contextPresenter
* @param DashboardPresenter $dashboardPresenter
* @param SettingsPresenter $settingsPresenter
*
* @return void
*/
public function __construct(
Ps_metrics $module,
PrestaShopContext $context,
ContextPresenter $contextPresenter,
DashboardPresenter $dashboardPresenter,
SettingsPresenter $settingsPresenter
) {
$this->module = $module;
$this->context = $context;
$this->contextPresenter = $contextPresenter;
$this->dashboardPresenter = $dashboardPresenter;
$this->settingsPresenter = $settingsPresenter;
}
/**
* Set properties of presenter
*
* @param array|null $store
* @param string $responseApiMessage
* @param int $countProperty
*
* @return void
*/
public function setProperties($store = null, $responseApiMessage, $countProperty)
{
// Allow to set a custom store for tests purpose
if (null !== $store) {
$this->store = $store;
}
$this->responseApiMessage = $responseApiMessage;
$this->countProperty = $countProperty;
$this->settingsPresenter->setSettings($responseApiMessage, $countProperty);
}
/**
* Build the store required by vuex
*
* @return array
*/
public function present()
{
if (null !== $this->store) {
return $this->store;
}
$contextPresenter = $this->contextPresenter->present();
// Load a presenter depending on the application to load (dashboard | settings)
if ('dashboard' === $contextPresenter['context']['app']) {
$this->store = array_merge(
$contextPresenter,
$this->dashboardPresenter->present()
);
} else {
$this->store = array_merge(
$contextPresenter,
$this->settingsPresenter->present()
);
}
return $this->store;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,140 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Provider;
use PrestaShop\Module\Ps_metrics\Api\AnalyticsApi;
use PrestaShop\Module\Ps_metrics\Helper\JsonHelper;
use PrestaShop\Module\Ps_metrics\Repository\ConfigurationRepository;
class AnalyticsAccountsListProvider
{
/**
* @var array
*/
private $accountsList;
/**
* @var JsonHelper
*/
private $jsonHelper;
/**
* @var ConfigurationRepository
*/
private $configurationRepository;
/**
* @var AnalyticsApi
*/
private $analyticsApi;
/**
* AnalyticsAccountsListProvider constructor.
*
* @param ConfigurationRepository $configurationRepository
* @param JsonHelper $jsonHelper
* @param AnalyticsApi $analyticsApi
*/
public function __construct(
ConfigurationRepository $configurationRepository,
JsonHelper $jsonHelper,
AnalyticsApi $analyticsApi
) {
$this->analyticsApi = $analyticsApi;
$this->accountsList = [];
$this->configurationRepository = $configurationRepository;
$this->jsonHelper = $jsonHelper;
}
/**
* getAccountsList
*
* @return array
*/
public function getAccountsList()
{
if (false === $this->configurationRepository->getGoogleLinkedValue()) {
return [];
}
$apiReturn = $this->analyticsApi->getAccountsList();
return $this->formatAccountListArray(
$apiReturn
);
}
/**
* Get the selected account from the account list
*
* @return mixed
*/
public function getSelectedAccount()
{
foreach ($this->accountsList as $uaTag => $accountData) {
if (true === $accountData['selected']) {
$accountData['webPropertyId'] = $uaTag;
return $accountData;
}
}
return (object) [];
}
/**
* Get username
*
* @return string
*/
public function getUserName()
{
if (false === empty($this->accountsList)) {
$webPropertyList = array_keys($this->accountsList);
$firstWebProperty = current($webPropertyList);
return $this->accountsList[$firstWebProperty]['username'];
}
return '';
}
/**
* retrieveAccountsList
*
* @param array $accountList
*
* @return array
*/
private function formatAccountListArray($accountList)
{
if (empty($accountList)) {
return [];
}
foreach ($accountList as $accounts) {
foreach ($accounts as $account) {
$this->accountsList = array_merge($account, $this->accountsList);
}
}
return $this->accountsList;
}
}

View File

@@ -0,0 +1,98 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Provider;
use PrestaShop\Module\Ps_metrics\Api\HttpApi;
class GoogleTagProvider
{
/**
* @var array|null
*/
private $shopSource;
/**
* @var HttpApi
*/
private $httpApi;
/**
* __construct
*
* @param HttpApi $httpApi
*/
public function __construct(HttpApi $httpApi)
{
$this->httpApi = $httpApi;
}
/**
* Set base url
*
* @param string $baseUrl
*
* @return void
*/
public function setBaseUrl($baseUrl)
{
$this->shopSource = $this->httpApi->getSourcePage($baseUrl);
}
/**
* Find by Regex if a Google Tag Analytics (UA-XXXXXXXXX-X) exists in source aimed page
*
* @return array
*/
public function findGoogleTagsAnalytics()
{
if (empty($this->shopSource)) {
return [];
}
preg_match_all(
'/UA-\d{6,}-\d/m',
isset($this->shopSource['body']) ? $this->shopSource['body'] : [],
$matches
);
return $matches[0];
}
/**
* Find by Regex if a Google Tag Manager (GTM-XXXXXXX) exists in source aimed page
*
* @return array
*/
public function findGoogleTagsManager()
{
if (empty($this->shopSource)) {
return [];
}
preg_match_all(
'/GTM-\w{6,}/m',
isset($this->shopSource['body']) ? $this->shopSource['body'] : [],
$matches
);
return $matches[0];
}
}

View File

@@ -0,0 +1,112 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Provider;
use PrestaShop\Module\Ps_metrics\Helper\ShopHelper;
use PrestaShop\Module\Ps_metrics\Helper\ToolsHelper;
use Shop;
class ShopsProvider
{
/**
* @var ToolsHelper
*/
private $toolsHelper;
/**
* @var ShopHelper
*/
private $shopHelper;
/**
* ShopsProvider constructor.
*
* @param ToolsHelper $toolsHelper
* @param ShopHelper $shopHelper
*
* @return void
*/
public function __construct(ToolsHelper $toolsHelper, ShopHelper $shopHelper)
{
$this->toolsHelper = $toolsHelper;
$this->shopHelper = $shopHelper;
}
/**
* Get one Shop Url
*
* @param int $shopId
*
* @return array
*/
public function getShopUrl($shopId)
{
$shop = $this->shopHelper->getShop($shopId);
$protocol = $this->getShopsProtocolInformations();
return [
'id_shop' => $shop['id_shop'],
'domain' => $shop[$protocol['domain_type']],
'url' => $protocol['protocol'] . $shop[$protocol['domain_type']] . $shop['uri'],
];
}
/**
* Get all shops Urls
*
* @return array
*/
public function getShopsUrl()
{
$shopList = $this->shopHelper->getShops();
$protocol = $this->getShopsProtocolInformations();
$urlList = [];
foreach ($shopList as $shop) {
$urlList[] = [
'id_shop' => $shop['id_shop'],
'url' => $protocol['protocol'] . $shop[$protocol['domain_type']] . $shop['uri'],
];
}
return $urlList;
}
/**
* getShopsProtocol
*
* @return array
*/
protected function getShopsProtocolInformations()
{
if (true === $this->toolsHelper->usingSecureMode()) {
return [
'domain_type' => 'domain_ssl',
'protocol' => 'https://',
];
}
return [
'domain_type' => 'domain',
'protocol' => 'http://',
];
}
}

View File

@@ -0,0 +1,29 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,158 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Repository;
use Configuration;
use PrestaShop\Module\Ps_metrics\Context\PrestaShopContext;
class ConfigurationRepository
{
const ACCOUNT_MODULES_STATES = 'PS_METRICS_MODULES_STATES';
const ACCOUNT_LINKED = 'PS_METRICS_ACCOUNT_LINKED';
const ACCOUNT_GOOGLETAG_LINKED = 'PS_METRICS_GOOGLETAG_LINKED';
/**
* @var int
*/
private $shopId;
/**
* ConfigurationRepository constructor.
*
* @param PrestaShopContext $prestashopContext
*
* @return void
*/
public function __construct(PrestaShopContext $prestashopContext)
{
$this->shopId = (int) $prestashopContext->getShopId();
}
/**
* saveActionGoogleLinked
*
* @param bool $action
*
* @return bool
*/
public function saveActionGoogleLinked($action)
{
return Configuration::updateValue(
self::ACCOUNT_LINKED,
$action,
false,
null,
$this->shopId
);
}
/**
* getGoogleLinkedValue
*
* @return bool
*/
public function getGoogleLinkedValue()
{
return (bool) Configuration::get(
self::ACCOUNT_LINKED,
null,
null,
$this->shopId
);
}
/**
* getShopDomain
*
* @return string
*/
public function getShopDomain()
{
return Configuration::get(
'PS_SHOP_DOMAIN',
null,
null,
$this->shopId
);
}
/**
* saveGoogleTagLinked
*
* @param bool $action
*
* @return bool
*/
public function saveGoogleTagLinked($action)
{
return Configuration::updateValue(
self::ACCOUNT_GOOGLETAG_LINKED,
$action,
false,
null,
$this->shopId
);
}
/**
* getGoogleTagLinkedValue
*
* @return bool
*/
public function getGoogleTagLinkedValue()
{
return (bool) Configuration::get(
self::ACCOUNT_GOOGLETAG_LINKED,
null,
null,
$this->shopId
);
}
/**
* saveModuleListState
*
* @param array $moduleList
*
* @return bool
*/
public function saveDashboardModulesToToggle($moduleList = [])
{
return Configuration::updateValue(
self::ACCOUNT_MODULES_STATES,
json_encode($moduleList)
);
}
/**
* getModuleListState
*
* @return array
*/
public function getDashboardModulesToToggle()
{
return json_decode(Configuration::get(
self::ACCOUNT_MODULES_STATES,
null,
null
));
}
}

View File

@@ -0,0 +1,48 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Repository;
use Db;
class HookModuleRepository
{
const TABLE_NAME = 'hook_module';
/**
* setModuleHookPosition
*
* @param int $hookId
* @param int $moduleId
* @param int $position
*
* @return bool
*/
public function setModuleHookPosition($hookId, $moduleId, $position)
{
return Db::getInstance()->update(
self::TABLE_NAME,
[
'position' => $position,
],
'id_hook = ' . (int) $hookId . ' AND id_module = ' . (int) $moduleId
);
}
}

View File

@@ -0,0 +1,322 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Repository;
use PrestaShop\Module\Ps_metrics\Context\PrestaShopContext;
use PrestaShop\Module\Ps_metrics\Helper\DbHelper;
use PrestaShop\Module\Ps_metrics\Helper\ShopHelper;
use Shop;
class OrdersRepository
{
/**
* @var string
*/
private $startDate;
/**
* @var string
*/
private $endDate;
/**
* @var int
*/
private $granularity;
/**
* @var DbHelper
*/
private $dbHelper;
/**
* @var ShopHelper
*/
private $shopHelper;
/**
* @var PrestaShopContext
*/
private $prestaShopContext;
/**
* __construct
*
* @param DbHelper $dbHelper
* @param ShopHelper $shopHelper
* @param PrestaShopContext $prestaShopContext
*/
public function __construct(DbHelper $dbHelper, ShopHelper $shopHelper, PrestaShopContext $prestaShopContext)
{
$this->dbHelper = $dbHelper;
$this->shopHelper = $shopHelper;
$this->prestaShopContext = $prestaShopContext;
}
/**
* @param string $startDate
* @param string $endDate
* @param int $granularity
*
* @return void
*/
public function setFilters($startDate, $endDate, $granularity)
{
$this->startDate = $startDate . ' 00:00:00';
$this->endDate = $endDate . ' 23:59:59';
$this->granularity = $granularity;
}
/**
* findAllRevenuesByDateAndGranularity
*
* @return array
*/
public function findAllRevenuesByDateAndGranularity()
{
return $this->dbHelper->executeS(
'SELECT
o.id_customer,
LEFT(o.date_add, ' . $this->granularity . ') as date,
SUM(o.total_paid_tax_incl / o.conversion_rate) as revenues,
SUM(oslip.total_products_tax_incl / oslip.conversion_rate) as refund
FROM ' . _DB_PREFIX_ . 'orders o
INNER JOIN ' . _DB_PREFIX_ . 'order_state os ON (o.current_state = os.id_order_state)
LEFT JOIN ' . _DB_PREFIX_ . 'order_slip oslip ON (o.id_order = oslip.id_order)
WHERE
o.date_add BETWEEN "' . pSQL($this->startDate) . '" AND "' . pSQL($this->endDate) . '"
AND os.logable = 1
' . $this->shopHelper->addSqlRestriction(false, 'o') . '
GROUP BY date'
);
}
/**
* findAllRevenuesByDateAndGranularityTaxExcluded
*
* @return array
*/
public function findAllRevenuesByDateAndGranularityTaxExcluded()
{
return $this->dbHelper->executeS(
'SELECT
o.id_customer,
LEFT(o.date_add, ' . $this->granularity . ') as date,
SUM(o.total_paid_tax_excl / o.conversion_rate) as revenues,
SUM(o.total_shipping_tax_excl / o.conversion_rate) as shipping,
SUM((o.total_paid_tax_incl + o.total_shipping_tax_incl - o.total_paid_tax_excl - o.total_shipping_tax_excl) / o.conversion_rate) as tax,
SUM(oslip.total_products_tax_incl / oslip.conversion_rate) as refund
FROM ' . _DB_PREFIX_ . 'orders o
INNER JOIN ' . _DB_PREFIX_ . 'order_state os ON (o.current_state = os.id_order_state)
LEFT JOIN ' . _DB_PREFIX_ . 'order_slip oslip ON (o.id_order = oslip.id_order)
WHERE
o.date_add BETWEEN "' . pSQL($this->startDate) . '" AND "' . pSQL($this->endDate) . '"
AND os.logable = 1
' . Shop::addSqlRestriction(false, 'o') . '
GROUP BY date'
);
}
/**
* findAllRevenuesByCustomerByDateAndGranularity
*
* @return array
*/
public function findAllRevenuesByCustomerByDateAndGranularity()
{
return $this->dbHelper->executeS(
'SELECT
o.id_order,
o.id_customer,
LEFT(o.date_add, ' . $this->granularity . ') as date,
SUM(total_paid_tax_incl / o.conversion_rate) as revenues,
SUM(oslip.total_products_tax_incl / oslip.conversion_rate) as refund
FROM ' . _DB_PREFIX_ . 'orders o
INNER JOIN ' . _DB_PREFIX_ . 'order_state os ON (o.current_state = os.id_order_state)
LEFT JOIN ' . _DB_PREFIX_ . 'order_slip oslip ON (o.id_order = oslip.id_order)
WHERE
o.date_add BETWEEN "' . pSQL($this->startDate) . '" AND "' . pSQL($this->endDate) . '"
AND os.logable = 1
' . $this->shopHelper->addSqlRestriction(false, 'o') . '
GROUP BY id_order'
);
}
/**
* Find all revenues grouped by payment method
*
* @return array
*/
public function findAllRevenuesByPaymentMethodsByDateAndGranularity()
{
return $this->dbHelper->executeS(
'SELECT
op.payment_method,
LEFT(o.date_add, ' . $this->granularity . ') as date,
SUM(total_paid_tax_incl / o.conversion_rate) as revenues,
SUM(oslip.total_products_tax_incl / oslip.conversion_rate) as refund
FROM ' . _DB_PREFIX_ . 'orders o
INNER JOIN ' . _DB_PREFIX_ . 'order_state os ON (o.current_state = os.id_order_state)
LEFT JOIN ' . _DB_PREFIX_ . 'order_slip oslip ON (o.id_order = oslip.id_order)
LEFT JOIN ' . _DB_PREFIX_ . 'order_payment op ON (o.reference = op.order_reference)
WHERE
o.date_add BETWEEN "' . pSQL($this->startDate) . '" AND "' . pSQL($this->endDate) . '"
AND os.logable = 1
' . Shop::addSqlRestriction(false, 'o') . '
GROUP BY op.payment_method'
);
}
/**
* findAllCategoriesByDate
*
* @return array
*/
public function findAllBestCategoriesRevenuesByDate()
{
return $this->dbHelper->executeS(
'SELECT
od.id_order_detail,
SUM((od.unit_price_tax_incl / o.conversion_rate) * od.product_quantity) as revenues,
SUM(osd.amount_tax_incl / oslip.conversion_rate) as refund,
o.date_add,
cl.name
FROM ' . _DB_PREFIX_ . 'order_detail od
INNER JOIN ' . _DB_PREFIX_ . 'orders o ON (od.id_order = o.id_order)
LEFT JOIN ' . _DB_PREFIX_ . 'order_slip_detail osd ON (od.id_order_detail = osd.id_order_detail)
LEFT JOIN ' . _DB_PREFIX_ . 'order_slip oslip ON (o.id_order = oslip.id_order)
INNER JOIN ' . _DB_PREFIX_ . 'order_state os ON (o.current_state = os.id_order_state)
INNER JOIN ' . _DB_PREFIX_ . 'product p ON (od.product_id = p.id_product)
INNER JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (p.id_category_default = cl.id_category)
WHERE
o.date_add BETWEEN "' . pSQL($this->startDate) . '" AND "' . pSQL($this->endDate) . '"
AND os.logable = 1
AND cl.id_lang = ' . $this->prestaShopContext->getEmployeeIdLang() . '
' . $this->shopHelper->addSqlRestriction(false, 'o') . '
GROUP BY cl.id_category'
);
}
/**
* Find top 10 ordered product
*
* @return array
*/
public function findTopOrderedProduct()
{
$query = 'SELECT od.product_id as productId, SUM(od.product_quantity) as quantity
FROM ' . _DB_PREFIX_ . 'order_detail od
INNER JOIN ' . _DB_PREFIX_ . 'orders o ON (od.id_order = o.id_order)
WHERE o.date_add BETWEEN "' . pSQL($this->startDate) . '" AND "' . pSQL($this->endDate) . '"
GROUP BY od.product_id
ORDER BY quantity DESC
LIMIT 10';
$result = $this->dbHelper->executeS($query);
if (count($result) === 0) {
return [];
}
foreach ($result as $key => $product) {
$result[$key]['productName'] = \Product::getProductName($product['productId']);
}
$data['data'] = array_column($result, 'quantity');
$data['labels'] = array_column($result, 'productName');
return $data;
}
/**
* findAllOrdersByDateAndGranularity
*
* @return array
*/
public function findAllOrdersByDateAndGranularity()
{
return $this->dbHelper->executeS(
'SELECT
LEFT(o.date_add, ' . $this->granularity . ') as date,
COUNT(o.id_order) as orders,
o.module as payment_module
FROM ' . _DB_PREFIX_ . 'orders o
INNER JOIN ' . _DB_PREFIX_ . 'order_state os ON (o.current_state = os.id_order_state)
WHERE
o.date_add BETWEEN "' . pSQL($this->startDate) . '" AND "' . pSQL($this->endDate) . '"
AND os.logable = 1
' . $this->shopHelper->addSqlRestriction(false, 'o') . '
GROUP BY date, o.module'
);
}
/**
* findCustomerInvoiceDateBySpecificDate
*
* @param int $customerId
* @param string $date
*
* @return string|false|null
*/
public function findCustomerInvoiceDateBySpecificDate($customerId, $date)
{
return $this->dbHelper->getValue(
'SELECT COUNT(o.date_add)
FROM ' . _DB_PREFIX_ . 'orders o
INNER JOIN ' . _DB_PREFIX_ . 'order_state os ON (o.current_state = os.id_order_state)
INNER JOIN ' . _DB_PREFIX_ . 'customer c ON (o.id_customer = c.id_customer)
WHERE
c.id_customer = ' . (int) $customerId . '
AND o.date_add <= "' . pSQL($date) . '"
AND os.logable = 1
' . $this->shopHelper->addSqlRestriction(false, 'o') . '
ORDER BY o.date_add ASC'
);
}
/**
* Get all cart from existing in a date range AND get all abandoned carts in that range
* Get datas without orders only
*
* @return array
*/
public function findAllCartsOrderedByDate()
{
// In Prestashop, a cart is abandoned when the cart is not updated for, at least, 24 hours
return $this->dbHelper->getRow(
'SELECT COUNT(all_cart.id_cart) AS all_cart, COUNT(abandon_cart.id_cart) AS ordered
FROM `' . _DB_PREFIX_ . 'cart` all_cart
LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON (all_cart.id_cart = o.id_cart AND all_cart.id_shop = o.id_shop)
LEFT JOIN `' . _DB_PREFIX_ . 'cart` abandon_cart ON (
all_cart.id_cart = abandon_cart.id_cart
AND abandon_cart.date_upd >= DATE_ADD("' . pSQL($this->startDate) . '", INTERVAL 1 HOUR)
AND abandon_cart.date_upd <= DATE_ADD("' . pSQL($this->endDate) . '", INTERVAL 1 HOUR)
AND abandon_cart.id_cart = o.id_cart
AND abandon_cart.id_shop = ' . $this->prestaShopContext->getShopId() . '
)
WHERE 1
AND all_cart.date_upd >= DATE_ADD("' . pSQL($this->startDate) . '", INTERVAL 1 HOUR)
AND all_cart.date_upd <= DATE_ADD("' . pSQL($this->endDate) . '", INTERVAL 1 HOUR)
AND all_cart.id_shop = ' . $this->prestaShopContext->getShopId()
);
}
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Repository;
class PaymentRepository
{
/**
* Get payment methods activate on site
*
* @return array
*/
public function getActivePaymentModule()
{
return \PaymentModuleCore::getInstalledPaymentModules();
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,242 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Tracker;
use PrestaShop\Module\Ps_metrics\Context\PrestaShopContext;
use PrestaShop\Module\Ps_metrics\Environment\SegmentEnv;
use PrestaShop\Module\Ps_metrics\Helper\SegmentHelper;
use PrestaShop\Module\Ps_metrics\Helper\ShopHelper;
class Segment implements TrackerInterface
{
/**
* @var string
*/
private $message = '';
/**
* @var array
*/
private $options = [];
/**
* @var SegmentEnv
*/
private $segmentEnv;
/**
* @var SegmentHelper
*/
private $segmentHelper;
/**
* @var PrestaShopContext
*/
private $prestaShopContext;
/**
* @var ShopHelper
*/
private $shopHelper;
/**
* Segment constructor.
*
* @param SegmentEnv $segmentEnv
* @param SegmentHelper $segmentHelper
* @param PrestaShopContext $prestaShopContext
* @param ShopHelper $shopHelper
*/
public function __construct(
SegmentEnv $segmentEnv,
SegmentHelper $segmentHelper,
PrestaShopContext $prestaShopContext,
ShopHelper $shopHelper
) {
$this->segmentEnv = $segmentEnv;
$this->segmentHelper = $segmentHelper;
$this->prestaShopContext = $prestaShopContext;
$this->shopHelper = $shopHelper;
$this->init();
}
/**
* Init segment client with the api key
*
* @return void
*/
private function init()
{
$this->segmentHelper->init();
}
/**
* Track event on segment
*
* @return bool
*
* @throws \PrestaShopException
*/
public function track()
{
if (empty($this->message)) {
throw new \PrestaShopException('Message cannot be empty. Need to set it with setMessage() method.');
}
// Dispatch track depending on context shop
$this->dispatchTrack();
return true;
}
/**
* Add track
*
* @param int $userId
*
* @return void
*/
private function segmentTrack($userId)
{
$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$this->segmentHelper->track([
'userId' => $userId,
'event' => $this->message,
'channel' => 'browser',
'context' => [
'ip' => $ip,
'userAgent' => $userAgent,
'locale' => \Context::getContext()->language->iso_code,
'page' => [
'referrer' => $referer,
'url' => $url,
],
],
'properties' => array_merge([
'module' => 'ps_metrics',
], $this->options),
]);
$this->segmentHelper->flush();
}
/**
* Handle tracking differently depending on the shop context
*
* @return mixed
*
* @todo how to refacto dictionnary with helper ?
*/
private function dispatchTrack()
{
$dictionary = [
\Shop::CONTEXT_SHOP => function () {
$this->trackShop();
},
\Shop::CONTEXT_GROUP => function () {
$this->trackShopGroup();
},
\Shop::CONTEXT_ALL => function () {
$this->trackAllShops();
},
];
return call_user_func($dictionary[$this->shopHelper->getContext()]);
}
/**
* Send track segment only for the current shop
*
* @return void
*/
private function trackShop()
{
$userId = $this->prestaShopContext->getShopDomain();
$this->segmentTrack($userId);
}
/**
* Send track segment for each shop in the current shop group
*
* @return void
*/
private function trackShopGroup()
{
$shops = $this->shopHelper->getShops(true, $this->shopHelper->getContextShopGroupID());
foreach ($shops as $shop) {
$this->segmentTrack($shop['domain']);
}
}
/**
* Send track segment for all shops
*
* @return void
*/
private function trackAllShops()
{
$shops = $this->shopHelper->getShops();
foreach ($shops as $shop) {
$this->segmentTrack($shop['domain']);
}
}
/**
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* @param string $message
*
* @return void
*/
public function setMessage($message)
{
$this->message = $message;
}
/**
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* @param array $options
*
* @return void
*/
public function setOptions($options)
{
$this->options = $options;
}
}

View File

@@ -0,0 +1,29 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\Ps_metrics\Tracker;
interface TrackerInterface
{
/**
* @return void
*/
public function track();
}

Some files were not shown because too many files have changed in this diff Show More