This commit is contained in:
fra-2107
2024-11-25 19:40:57 -05:00
parent c6fd49192e
commit f9dcfde1e2
3 changed files with 114 additions and 211 deletions

View File

@ -3,27 +3,26 @@
// initialisation // initialisation
let previousAlerts = []; let previousAlerts = [];
let sortOrder = {}; let sortOrder = {};
ajaxRequest('GET', 'php/request.php/alertes/', CheckNewAlerts);
// ajaxRequest('GET', 'php/request.php/alertes/', displayAlerts);
setInterval(() => {
ajaxRequest('GET', 'php/request.php/alertes/', CheckNewAlerts); ajaxRequest('GET', 'php/request.php/alertes/', CheckNewAlerts);
// Effectuer une requête AJAX pour récupérer les nouvelles alertes
}, 10000);
ajaxRequest('GET', 'php/request.php/devices/', fillSelectDevice); ajaxRequest('GET', 'php/request.php/devices/', fillSelectDevice);
fillSelectRisque(); fillSelectRisque();
// filtrage setInterval(() => {
ajaxRequest('GET', 'php/request.php/alertes/', CheckNewAlerts);
}, 10000);
// initialisation of the filters
$('#filter-button').click(() => { $('#filter-button').click(() => {
const params = []; // Initialise le tableau des paramètres const params = [];
const device = $('#device-select').val(); const device = $('#device-select').val();
const alertlvl = $('#risque-select').val(); const alertlvl = $('#risque-select').val();
// Ajouter les paramètres uniquement s'ils sont définis // enable parameters only if they are not empty
if (device) params.push(`device_product=${encodeURIComponent(device)}`); if (device) params.push(`device_product=${encodeURIComponent(device)}`);
if (alertlvl) params.push(`agent_severity=${encodeURIComponent(alertlvl)}`); if (alertlvl) params.push(`agent_severity=${encodeURIComponent(alertlvl)}`);
// Construire l'URL avec les paramètres // build the url
let url; let url;
if (params.length) { if (params.length) {
url = `php/request.php/alertes/?${params.join('&')}`; url = `php/request.php/alertes/?${params.join('&')}`;
@ -33,22 +32,11 @@ $('#filter-button').click(() => {
console.log(url); console.log(url);
} }
// Effectuer la requête AJAX
ajaxRequest('GET', url, displayAlerts); ajaxRequest('GET', url, displayAlerts);
} }
); );
// $('#tweets').on('click', '.del', () => {
// console.log('delete');
// ajaxRequest('DELETE', 'php/request.php/tweets/' +
// $(event.target).closest('.del').attr('value') + '?login=' + login, () => {
// ajaxRequest('GET', 'php/request.php/tweets/', displayTweets);
// }
// );
// }
// );
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
//--- displayAlerts ------------------------------------------------------------ //--- displayAlerts ------------------------------------------------------------
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -74,47 +62,60 @@ function displayAlerts(alerts) {
); );
} }
//------------------------------------------------------------------------------
//--- fillSelectDevice ------------------------------------------------------------
//------------------------------------------------------------------------------
// fill select with devices.
// \param devices The devices data received via the Ajax request.
function fillSelectDevice(devices) { function fillSelectDevice(devices) {
for (let device of devices) for (let device of devices)
$('#device-select').append($('<option>').text(device['device_product']).val(device['device_product'])); $('#device-select').append($('<option>').text(device['device_product']).val(device['device_product']));
} }
//------------------------------------------------------------------------------
//--- fillSelectRisque ------------------------------------------------------------
//------------------------------------------------------------------------------
// fill select with alertslvl.
function fillSelectRisque() { function fillSelectRisque() {
for (let i = 1; i <= 10; i++) for (let i = 1; i <= 10; i++)
$('#risque-select').append($('<option>').text(i).val(i)); $('#risque-select').append($('<option>').text(i).val(i));
} }
//------------------------------------------------------------------------------
//--- CheckNewAlerts ------------------------------------------------------------
//------------------------------------------------------------------------------
// checks if there is new alerts in the database and display if so.
// \param newAlerts The alerts data received via the Ajax request.
// \previousAlerts The old alerts data received via the Ajax request and stored.
function CheckNewAlerts(newAlerts) { function CheckNewAlerts(newAlerts) {
// Comparer les nouvelles alertes avec les anciennes
if (JSON.stringify(previousAlerts) !== JSON.stringify(newAlerts)) { if (JSON.stringify(previousAlerts) !== JSON.stringify(newAlerts)) {
// Si les alertes ont changé, mettre à jour l'interface
displayAlerts(newAlerts); displayAlerts(newAlerts);
// Mettre à jour les alertes précédentes
previousAlerts = newAlerts; previousAlerts = newAlerts;
} }
} }
// Fonction pour trier les alertes //------------------------------------------------------------------------------
//--- sortTable ------------------------------------------------------------
//------------------------------------------------------------------------------
// sort the table.
// \param columnName The name of the column to sort.
function sortTable(columnName) { function sortTable(columnName) {
const currentOrder = sortOrder[columnName] || 'asc'; const currentOrder = sortOrder[columnName] || 'asc';
const newOrder = currentOrder === 'asc' ? 'desc' : 'asc'; const newOrder = currentOrder === 'asc' ? 'desc' : 'asc';
sortOrder[columnName] = newOrder; sortOrder[columnName] = newOrder;
// Construire les paramètres de la requête pour l'orderby
const params = []; const params = [];
params.push(`orderby=${columnName}`); params.push(`orderby=${columnName}`);
params.push(`order=${newOrder}`); params.push(`order=${newOrder}`);
const url = `php/request.php/alertes/?${params.join('&')}`; const url = `php/request.php/alertes/?${params.join('&')}`;
// Effectuer la requête AJAX pour récupérer les alertes triées
ajaxRequest('GET', url, displayAlerts); ajaxRequest('GET', url, displayAlerts);
} }
// Ajouter des gestionnaires d'événements de clic sur les en-têtes de colonnes // sort the table when clicking on the column name
$('th').click(function () { $('th').click(function () {
let columnName = $(this).text().trim().toLowerCase().replace(/ /g, '_'); // Convertir le texte de l'en-tête en nom de colonne let columnName = $(this).text().trim().toLowerCase().replace(/ /g, '_');
console.log(columnName); console.log(columnName);
switch (columnName) { switch (columnName) {
case 'n°': case 'n°':

View File

@ -11,14 +11,14 @@
// \return False on error and the database otherwise. // \return False on error and the database otherwise.
function dbConnect() function dbConnect()
{ {
try try {
{ $db = new PDO(
$db = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME.';charset=utf8', 'mysql:host=' . DB_SERVER . ';dbname=' . DB_NAME . ';charset=utf8',
DB_USER, DB_PASSWORD); DB_USER,
DB_PASSWORD
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} } catch (PDOException $exception) {
catch (PDOException $exception)
{
error_log('Connection error: ' . $exception->getMessage()); error_log('Connection error: ' . $exception->getMessage());
return false; return false;
} }
@ -33,13 +33,10 @@
// \return The list of alertes. // \return The list of alertes.
function dbRequestAlerts($db, $filtres = null, $orderby, $order) function dbRequestAlerts($db, $filtres = null, $orderby, $order)
{ {
try try {
{
$request = 'SELECT * FROM alertes'; $request = 'SELECT * FROM alertes';
$params = []; $params = [];
// Si $filtres est non nul et non vide, appliquez les conditions
if (isset($filtres)) { if (isset($filtres)) {
$conditions = []; $conditions = [];
foreach ($filtres as $colonne => $valeur) { foreach ($filtres as $colonne => $valeur) {
@ -54,9 +51,7 @@
$statement = $db->prepare($request); $statement = $db->prepare($request);
$statement->execute($params); $statement->execute($params);
$result = $statement->fetchAll(PDO::FETCH_ASSOC); $result = $statement->fetchAll(PDO::FETCH_ASSOC);
} } catch (PDOException $exception) {
catch (PDOException $exception)
{
error_log('Request error: ' . $exception->getMessage()); error_log('Request error: ' . $exception->getMessage());
return false; return false;
} }
@ -66,105 +61,19 @@
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
//--- dbRequestDevices -------------------------------------------------------- //--- dbRequestDevices --------------------------------------------------------
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
// Function to get all alertes // Function to get all Devices
// \param db The connected database. // \param db The connected database.
// \return The list of alertes. // \return The list of Devices.
function dbRequestDevices($db) function dbRequestDevices($db)
{ {
try try {
{
$request = 'SELECT device_product FROM alertes GROUP BY device_product;'; $request = 'SELECT device_product FROM alertes GROUP BY device_product;';
$statement = $db->prepare($request); $statement = $db->prepare($request);
$statement->execute(); $statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC); $result = $statement->fetchAll(PDO::FETCH_ASSOC);
} } catch (PDOException $exception) {
catch (PDOException $exception)
{
error_log('Request error: ' . $exception->getMessage()); error_log('Request error: ' . $exception->getMessage());
return false; return false;
} }
return $result; return $result;
} }
//----------------------------------------------------------------------------
//--- dbAddCTweet ------------------------------------------------------------
//----------------------------------------------------------------------------
// Add a tweet.
// \param db The connected database.
// \param login The login of the user.
// \param text The tweet to add.
// \return True on success, false otherwise.
function dbAddTweet($db, $login, $text)
{
try
{
$request = 'INSERT INTO tweets(login, text) VALUES(:login, :text)';
$statement = $db->prepare($request);
$statement->bindParam(':login', $login, PDO::PARAM_STR, 20);
$statement->bindParam(':text', $text, PDO::PARAM_STR, 80);
$statement->execute();
}
catch (PDOException $exception)
{
error_log('Request error: '.$exception->getMessage());
return false;
}
return true;
}
//----------------------------------------------------------------------------
//--- dbModifyTweet ----------------------------------------------------------
//----------------------------------------------------------------------------
// Function to modify a tweet.
// \param db The connected database.
// \param id The id of the tweet to update.
// \param login The login of the user.
// \param text The new tweet.
// \return True on success, false otherwise.
function dbModifyTweet($db, $id, $login, $text)
{
try
{
$request = 'UPDATE tweets SET text=:text WHERE id=:id AND login=:login ';
$statement = $db->prepare($request);
$statement->bindParam(':id', $id, PDO::PARAM_INT);
$statement->bindParam(':login', $login, PDO::PARAM_STR, 20);
$statement->bindParam(':text', $text, PDO::PARAM_STR, 80);
$statement->execute();
}
catch (PDOException $exception)
{
error_log('Request error: '.$exception->getMessage());
return false;
}
return true;
}
//----------------------------------------------------------------------------
//--- dbDeleteTweet ----------------------------------------------------------
//----------------------------------------------------------------------------
// Delete a tweet.
// \param db The connected database.
// \param id The id of the tweet.
// \param login The login of the user.
// \return True on success, false otherwise.
function dbDeleteTweet($db, $id, $login)
{
try
{
$request = 'DELETE FROM tweets WHERE id=:id AND login=:login';
$statement = $db->prepare($request);
$statement->bindParam(':id', $id, PDO::PARAM_INT);
$statement->bindParam(':login', $login, PDO::PARAM_STR, 20);
$statement->execute();
}
catch (PDOException $exception)
{
error_log('Request error: '.$exception->getMessage());
return false;
}
return true;
}
?>

View File

@ -17,12 +17,11 @@ $requestMethod = $_SERVER['REQUEST_METHOD'];
$request = $_SERVER['PATH_INFO']; $request = $_SERVER['PATH_INFO'];
$request = explode('/', $request); $request = explode('/', $request);
if ($request[1] == 'alertes') { if ($request[1] == 'alertes') {
if ($requestMethod == 'GET') { if ($requestMethod == 'GET') {
$orderby = isset($_GET['orderby']) ? $_GET['orderby'] : 'date_alerte'; // Par défaut, trier par date_alerte $orderby = isset($_GET['orderby']) ? $_GET['orderby'] : 'date_alerte';
$order = isset($_GET['order']) && ($_GET['order'] == 'desc') ? 'DESC' : 'ASC'; // Par défaut, ordre croissant $order = isset($_GET['order']) && ($_GET['order'] == 'desc') ? 'DESC' : 'ASC';
$filtresArray = []; $filtresArray = [];
if (isset($_GET['device_product'])) if (isset($_GET['device_product']))
@ -36,12 +35,6 @@ if ($request[1] == 'alertes') {
$data = dbRequestAlerts($db, null, $orderby, $order); $data = dbRequestAlerts($db, null, $orderby, $order);
} }
} }
if ($requestMethod == 'PUT') {
parse_str(file_get_contents('php://input'), $_PUT);
if ($id != '' && isset($_PUT['login']) && isset($_PUT['text']))
$data = dbModifyTweet($db, $id, $_PUT['login'], strip_tags($_PUT['text']));
}
} }
if ($request[1] == 'devices') { if ($request[1] == 'devices') {