Skip to content

Commit

Permalink
Merge pull request #269 from PrestaSafe/pr/268-fixes-optimise
Browse files Browse the repository at this point in the history
Pr/268 fixes optimise
  • Loading branch information
PrestaSafe authored Oct 17, 2024
2 parents f5a3d04 + 3492d0a commit e6d4ea7
Show file tree
Hide file tree
Showing 12 changed files with 329 additions and 2 deletions.
2 changes: 2 additions & 0 deletions _dev/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import './index.css'
import { verifyConnectedEmployees } from './scripts/editorManager';

const app = createApp(App).use(createPinia())
app.mount('#app')

Expand Down
53 changes: 53 additions & 0 deletions _dev/src/scripts/editorManager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { createToaster } from '@meforma/vue-toaster'
const toaster = createToaster();
let numberOfEditors = 1;
import { HttpClient } from '../services/HttpClient.js';
import { trans } from '../scripts/trans.js';
/**
*
* Checks the number of employees connected to the prettyblocks backoffice.
* If there is more than one employee, an alert is displayed.
*
*/
export function verifyConnectedEmployees() {

let formData = new FormData();
formData.append('action', 'employeeAlert');
formData.append('session_id', sessionToken);
formData.append('ajax', 1);

if (typeof ajaxEditingUrl == "undefined") {
console.error('Url is missing.')
return;
}

HttpClient.post(ajaxEditingUrl, Object.fromEntries(formData))
.then(data => {
if (data.success && data.number_of_editors) {
numberOfEditors = data.number_of_editors;
let alert_message = trans('alert_message').replace('{{ number }}', numberOfEditors);
if (numberOfEditors > 1) {
toaster.error(
alert_message,
{
position: "bottom",
duration: 5000,
max: 1,
}
);
}
} else {
console.error('Error : ', data.error);
}
})
.catch(e => {
console.error('Error during HTTP request: ', e);
});
}

// Run first time
verifyConnectedEmployees();


// Run every 40 seconds
setInterval(verifyConnectedEmployees, 40000);
7 changes: 7 additions & 0 deletions config/routes.yml
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,10 @@ prettyblocks_theme_settings:
_legacy_controller: AdminThemeManagerController
_legacy_link: AdminThemeManagerController

prettyblocks_get_connected_employees:
path: prettyblocks/get_connected_employees/
methods: [GET,POST]
defaults:
_controller: 'PrestaSafe\PrettyBlocks\Controller\AdminThemeManagerController::getConnectedEmployeesAction'
_legacy_controller: AdminThemeManagerController
_legacy_link: AdminThemeManagerController
24 changes: 23 additions & 1 deletion prettyblocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,14 @@ class PrettyBlocks extends Module implements WidgetInterface
'ActionCmsPageGridDefinitionModifier',
'BeforeRenderingPrettyblocksFeaturedProduct',
'BeforeRenderingPrettyBlocksRenderModule',
'moduleRoutes',
];

public function __construct()
{
$this->name = 'prettyblocks';
$this->tab = 'administration';
$this->version = '3.1.1';
$this->version = '3.1.2';
$this->author = 'PrestaSafe';
$this->need_instance = 1;
$this->js_path = $this->_path . 'views/js/';
Expand Down Expand Up @@ -209,10 +210,30 @@ private function createBlockDb()
$isOk &= Db::getInstance()->execute($sql);
}
$isOk &= $this->makeSettingsTable();
$isOk &= $this->makeConnectedEmployee();

return $isOk;
}

/**
* Create table to store editors of the page
*
* @return bool
*/
public function makeConnectedEmployee()
{
// Creating a table to store editors of the page
$sql = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'prettyblocks_connected_employee` (
`id_edit` int(11) NOT NULL AUTO_INCREMENT,
`id_user` int(11) NOT NULL,
`session_id` varchar(255) NOT NULL UNIQUE,
`last_update` TIMESTAMP NOT NULL,
PRIMARY KEY (`id_edit`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;';

return Db::getInstance()->execute($sql);
}

public function makeSettingsTable()
{
$sql = 'CREATE TABLE `' . _DB_PREFIX_ . 'prettyblocks_settings` (
Expand All @@ -238,6 +259,7 @@ private function removeDb()
$db[] = 'DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'prettyblocks`';
$db[] = 'DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'prettyblocks_lang`';
$db[] = 'DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'prettyblocks_settings`';
$db[] = 'DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'prettyblocks_connected_employee`';

$isOk = true;
foreach ($db as $sql) {
Expand Down
52 changes: 52 additions & 0 deletions src/Controller/AdminThemeManagerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
namespace PrestaSafe\PrettyBlocks\Controller;

// use Doctrine\Common\Cache\CacheProvider;
use PrestaSafe\PrettyBlocks\DataPersister\ConnectedEmployeeDataPersister;
use PrestaSafe\PrettyBlocks\DataProvider\ConnectedEmployeeDataProvider;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\JsonResponse;
Expand Down Expand Up @@ -166,6 +168,15 @@ public function indexAction()
{
$context = $this->get('prestashop.adapter.legacy.context')->getContext();

$id_user = $context->employee->id;
$session_token = $context->cookie->session_token;

// Insert to new employee
ConnectedEmployeeDataPersister::insert($id_user, $session_token);

// get number of editor
$number_of_editors = ConnectedEmployeeDataProvider::get();

$shop = $context->shop;
$domain = \Tools::getShopDomainSsl(true);

Expand Down Expand Up @@ -209,6 +220,7 @@ public function indexAction()
$collectionURL = $this->getSFUrl('prettyblocks_collection');
$link = new \Link();
$blockUrl = $link->getModuleLink('prettyblocks', 'ajax');
$ajax_editing_url = $this->getSFUrl('prettyblocks_get_connected_employees');
$blockAvailableUrls = $this->getSFUrl('prettyblocks_api_get_blocks_available');
$settingsUrls = $this->getSFUrl('prettyblocks_theme_settings');
$shop_url = $context->shop->getBaseUrl(true) . $this->getLangLink($context->language->id, $context, $context->shop->id);
Expand Down Expand Up @@ -268,6 +280,7 @@ public function indexAction()
'theme_settings' => $settingsUrls,
'startup_url' => $startup_url,
'prettyblocks_route_generator' => $this->getSFUrl('prettyblocks_route_generator'),
'ajax_editing_url' => $ajax_editing_url,
],
'trans_app' => [
'current_shop' => $translator->trans('Shop in modification', [], 'Modules.Prettyblocks.Admin'),
Expand Down Expand Up @@ -304,6 +317,7 @@ public function indexAction()
'duplicate_state_error' => $translator->trans('An error occurred while duplicating the element', [], 'Modules.Prettyblocks.Admin'),
'get_pro' => $translator->trans('Get Pro Blocks', [], 'Modules.Prettyblocks.Admin'),
'search_zone' => $translator->trans('Search zone', [], 'Modules.Prettyblocks.Admin'),
'alert_message' => $translator->trans('Careful, %number% users are on this page.', ['%number%' => '{{ number }}'], 'Modules.Prettyblocks.Admin'),
],
'security_app' => [
'ajax_token' => \Configuration::getGlobalValue('_PRETTYBLOCKS_TOKEN_'),
Expand All @@ -314,6 +328,9 @@ public function indexAction()
'css_build' => $css,
'js_build' => $js,
'js_entry' => $js_entry,

'session_token' => $session_token,
'number_of_editors' => $number_of_editors,
]);
}

Expand Down Expand Up @@ -694,4 +711,39 @@ public function routeGeneratorAction(Request $request)
'url' => $url,
]);
}

/**
* Get the number of connected employees
*
* @param Request $request
*
* @return JsonResponse
*/
public function getConnectedEmployeesAction(Request $request)
{
$posts = json_decode($request->getContent(), true);
$sessionId = $posts['session_id'];

if (!$sessionId) {
return (new JsonResponse())->setData([
'success' => false,
]);
}

ConnectedEmployeeDataPersister::update($sessionId);

$connectedEmployees = ConnectedEmployeeDataProvider::get();
if (null === $connectedEmployees) {
// autocreate table if not exists
ConnectedEmployeeDataPersister::tableExists();
return (new JsonResponse())->setData([
'success' => false,
]);
}

return (new JsonResponse())->setData([
'success' => true,
'number_of_editors' => $connectedEmployees,
]);
}
}
95 changes: 95 additions & 0 deletions src/DataPersister/ConnectedEmployeeDataPersister.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?php

namespace PrestaSafe\PrettyBlocks\DataPersister;

use Module;
use PrettyBlocksMigrate;

final class ConnectedEmployeeDataPersister
{
/**
* Delete old employee and insert new
*
* @param int $id_user
* @param string $session_id
*
* @return bool
*/
public static function insert(int $id_user, string $session_id): bool
{
try {
// Delete old employee (more than 1 min)
ConnectedEmployeeDataPersister::cleanData();

return \Db::getInstance()->execute(
'
INSERT INTO `' . _DB_PREFIX_ . 'prettyblocks_connected_employee` (id_user, session_id, last_update)
VALUES (' .
(int) pSQL($id_user) . ', "' .
pSQL($session_id) . '", "' .
date('Y-m-d H:i:s') .
'")
ON DUPLICATE KEY UPDATE last_update = "' . date('Y-m-d H:i:s') . '"'
);
} catch (\Exception $e) {
new \PrestaShopException('Error while inserting connected employee', 0, $e);
return false;
}
}

/**
* Update the date of the connected employee
*
* @param string $session_id
*
* @return bool
*/
public static function update(string $session_id): bool
{
try {
ConnectedEmployeeDataPersister::cleanData();

return \Db::getInstance()->update(
'prettyblocks_connected_employee',
['last_update' => date('Y-m-d H:i:s')],
'session_id = \'' . pSQL($session_id) . '\''
);
} catch (\Exception $e) {

new \PrestaShopException('Error while updating connected employee', 0, $e);
return false;
}
}

/**
* Delete old employee (more than 1 min)
*
* @return bool
*/
public static function cleanData(): bool
{
try {
$database = \Db::getInstance();
$thresholdTime = date('Y-m-d H:i:s', strtotime('-1 minute'));

$sql = '
DELETE FROM ' . _DB_PREFIX_ . 'prettyblocks_connected_employee
WHERE last_update < "' . pSQL($thresholdTime) . '"'
;

return $database->execute($sql);
} catch (\Exception $e) {

new \PrestaShopException('Error while cleaning connected employee', 0, $e);
return false;
}
}

public static function tableExists(): void
{
if (!PrettyBlocksMigrate::tableExists('prettyblocks_connected_employee')) {
dump('table not exists');
Module::getInstanceByName('prettyblocks')->makeConnectedEmployee();
}
}
}
11 changes: 11 additions & 0 deletions src/DataPersister/index.php
Original file line number Diff line number Diff line change
@@ -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;
26 changes: 26 additions & 0 deletions src/DataProvider/ConnectedEmployeeDataProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace PrestaSafe\PrettyBlocks\DataProvider;

final class ConnectedEmployeeDataProvider
{
/**
* Return the number of connected employees on the page
*
* @return int|null
*/
public static function get(): ?int
{
try {
$sql = '
SELECT COUNT(*)
FROM `' . _DB_PREFIX_ . 'prettyblocks_connected_employee`
WHERE last_update > DATE_SUB(NOW(), INTERVAL 60 SECOND)
';

return (int) \Db::getInstance()->getValue($sql);
} catch (\Exception $e) {
return null;
}
}
}
11 changes: 11 additions & 0 deletions src/DataProvider/index.php
Original file line number Diff line number Diff line change
@@ -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;
5 changes: 5 additions & 0 deletions translations/fr-FR/ModulesPrettyblocksAdmin.fr-FR.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
<file original="admin-dev" source-language="fr-FR" target-language="fr-FR" datatype="plaintext">
<body>
<trans-unit id="eddf5d79de2de71a80d17ea9aa077136">
<source>Careful, %number% users are on this page.</source>
<target>Careful, %number% users are on this page.</target>
<note>Line: </note>
</trans-unit>
<trans-unit id="8290adcd899d3ef604fb3a6c291a0046">
<source>PrettyBlocks</source>
<target>PrettyBlocks</target>
Expand Down
Loading

0 comments on commit e6d4ea7

Please sign in to comment.