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

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;