Created `historyDefault` module and `history` repo (to implement and complete) + create twig view `history` and refactored history view with database

This commit is contained in:
xdrm-brackets 2017-01-11 16:28:21 +01:00
parent 88f4839cd3
commit 8c6d7269ec
7 changed files with 470 additions and 54 deletions

View File

@ -0,0 +1,114 @@
<?php
namespace api\module;
use \database\core\DatabaseDriver;
use \manager\sessionManager;
use \error\core\Error;
use \database\core\Repo;
class historyDefault{
/* CREATION D'UNE NOUVELLE ENTREE DANS LA BDD
*
* @id_user<int> UID de l'utilisateur
* @id_machine<int> UID la machine
* @id_action<int> UID de l'action
* @timestamp<int> timestamp de l'action
*
* @return status<Boolean> Retourne si oui ou non, tout s'est bien passe
*
*/
public static function create($params){
extract($params);
/* [1] Creation de l'utilisateur
=========================================================*/
$create_entry = new Repo('history/create', [
$id_entry,
$id_machine,
$id_action,
$timestamp
]);
$id_entry = $create_entry->answer();
// Si une erreur est retournee, on retourne une erreur
if( $id_entry === false )
return ['ModuleError' => Error::ModuleError];
/* [2] Gestion du retour
=========================================================*/
return [
'id_history' => $id_entry
];
}
/* RENVOIE UN UTILISATEUR EN FONCTION D'UN MOT CLE
*
* @keywords<String> Element de recherche
*
* @return users<Array> Retourne la liste des utilisateurs trouves
*
*/
public static function search($params){
extract($params);
// On recupere les donnees
$user = new Repo('history/search', [
$_SESSION['WAREHOUSE']['id'],
$keywords
]);
return [ 'history' => $user->answer() ];
}
/* RENVOIE LA LISTE EXHAUSTIVE DES ACCES
*
* @return history<Array> Liste des entrées de l'historique
*
*/
public static function getAll(){
// On recupere les donnees
$entries = new Repo('history/getAll', [ $_SESSION['WAREHOUSE']['id'] ]);
return [ 'history' => $entries->answer() ];
}
/* SUPPRIME UNE ENTREE
*
* @id_history<int> UID de l'entree en question
*
* @return status<Boolean> Retourne si oui ou non tout s'est bien deroule
*
*/
public static function delete($params){
extract($params);
/* [1] On supprime l'utilisateur
=========================================================*/
$del_entry = new Repo('history/delete', [
$_SESSION['WAREHOUSE']['id'],
$id_history
]);
$deleted_entry = $del_entry->answer();
return [ 'status' => $deleted_entry ];
}
}
?>

View File

@ -0,0 +1,164 @@
<?php
namespace database\repo;
use \database\core\DatabaseDriver;
use \orm\core\Table;
use \orm\core\Rows;
class history extends parentRepo{
protected static function table_name(){ static $table_name = 'history'; return $table_name; }
/* CREATION D'UNE ENTREE DANS L'HISTORIQUE
*
* @id_user<int> UID de l'utilisateur
* @id_machine<int> UID de la machine
* @id_action<int> UID de l'action
* @timestamp<int> Timestamp de l'action
*
* @return id_history<int> Renvoie l'UID de l'entree cree
* Renvoie FALSE si une erreur occure
*
*/
public static function create($id_user, $id_machine, $id_action, $timestamp){
/* [1] On retourne l'id_history ou FALSE si erreur
=========================================================*/
$inserted = Table::get('history')->insert([
'id_history' => Rows::INSERT_DEFAULT,
'id_user' => $id_user,
'id_machine' => $id_machine,
'id_action' => $id_action,
'timestamp' => $timestamp
]);
// Si erreur d'insertion, erreur
if( !$inserted )
return false; // Si pb d'unicité du code ou username (car sont uniques) ou autre
/* [2] On récupère l'id_history
=========================================================*/
$check_history = self::getByTimestamp($timestamp);
// Si on trouve pas, erreur
if( $check_history === false )
return false;
// Sinon, on retourne son id
return $check_history['id_history'];
}
/* SUPPRIME UNE ENTREE DONNEE
*
* @id_history<int> UID de l'entreee
*
* @return status<Boolean> Retourne si oui ou non l'entree a bien ete supprimee
*
*/
public static function delete($id_history){
/* [1] On redige/execute la requete
=========================================================*/
$delete = Table::get('history')
->whereId($id_history);
// On retourne l'état
return $delete->delete();
}
/* RETOURNE UNE ENTREE SPECIFIQUE
*
* @id_history<int> UID de l'entree
*
* @return entry<Array> Données de l'entree
* FALSE si aucun résultat
*
*/
public static function getById($id_history){
/* [1] On rédige/execute la requête
=========================================================*/
$user = Table::get('user')
->whereIdWarehouse($id_warehouse)
->whereIdUser($id_user)
->select('*')
->unique();
return $user->fetch();
}
/* RETOURNE TOUT L'HISTORIQUE DE L'ENTREPOT
*
* @id_warehouse<int> UID de l'entrepot
*
* @return entries<Array> Entrees de l'historique
*
*/
public static function getAll($id_warehouse){
/* [1] On rédige/execute la requête
=========================================================*/
$users = Table::get('user')
->whereIdWarehouse($id_warehouse)
->select('id_user')
->select('username', null, null, 'user_name')
->select('firstname', null, null, 'user_firstname')
->select('lastname', null, null, 'user_lastname');
$machines = Table::get('machine')
->whereIdWarehouse($id_warehouse)
->select('id_machine')
->select('name', null, null, 'machine_name');
$actions = Table::get('action')
->select('id_action')
->select('name', null, null, 'action_name');
$history = Table::get('history')
->join('id_user', $users)
->join('id_machine', $machines)
->join('id_action', $actions)
->select('id_history')
->select('timestamp')
->orderby('timestamp', Rows::ORDER_ASC);
return $history->fetch();
}
}
?>

View File

@ -0,0 +1,127 @@
<?php
namespace viewer\view\history;
use \api\core\ModuleRequest;
use \error\core\Error;
class history_view{
public static function render(){
/* [1] Init Twig
=========================================================*/
$loader = new \Twig_Loader_Filesystem(__BUILD__.'/viewer/view');
$twig = new \Twig_Environment($loader, []);
/* [2] Store variables
=========================================================*/
$variables = [
'p_theme' => $_SESSION['WAREHOUSE']['theme']
];
/* [3] Store functions
=========================================================*/
$twig->addFunction(new \Twig_Function('f_history', function(){
$req = new ModuleRequest('historyDefault/getAll', []);
$res = $req->dispatch();
// si erreur, on retourne rien par défaut
if( $res->error != Error::Success )
return [];
return $res->get('history');
}));
$twig->addFilter(new \Twig_Filter('f_tsformat', function($ts){
return date('d/m/Y H:i:s', $ts);
}));
$twig->addFilter(new \Twig_Filter('f_tsrelative', function($ts){
$r = self::relativetime($ts);
// if only one
$o = $r[0] <= 1;
switch($r[1]){
case 'Y': return $r[0].' an'.($o?'':'s'); break;
case 'm': return $r[0].' mois'; break;
case 'd': return $r[0].' jour'.($o?'':'s'); break;
case 'H': return $r[0].' heure'.($o?'':'s'); break;
case 'i': return $r[0].' minute'.($o?'':'s'); break;
case 's': return $r[0].' seconde'.($o?'':'s'); break;
default: return 'peu de temps'; break;
}
}));
/* [4] Build the whole stuff
=========================================================*/
return $twig->render('history/history_view.twig', [
'p_theme' => $variables['p_theme']
]);
}
/* RETURNS A RELATIVE HUMAN-READABLE TIME
*
* @ts<int> Timestamp to process
*
* @return relative<Array> human-readable relative time [value, unit]
*
*/
private static function relativetime($ts){
/* [1] Explode time into human-readable time units
=========================================================*/
$units = [];
/* (1) Date units */
$units['year'] = (int) date('Y', $ts);
$units['month'] = (int) date('m', $ts);
$units['day'] = (int) date('d', $ts);
/* (2) Time units */
$units['hour'] = (int) date('H', $ts);
$units['minute'] = (int) date('i', $ts);
$units['second'] = (int) date('s', $ts);
/* [2] Calculate relative time for each unit
=========================================================*/
/* (1) Date units */
$units['year'] = intval(date('Y')) - $units['year'];
$units['month'] = intval(date('m')) - $units['month'];
$units['day'] = intval(date('d')) - $units['day'];
/* (2) Time units */
$units['hour'] = intval(date('H')) - $units['hour'];
$units['minute'] = intval(date('i')) - $units['minute'];
$units['second'] = intval(date('s')) - $units['second'];
/* [3] Return significative relative time
=========================================================*/
/* (1) Date units */
if( $units['year'] > 0 ) return [ $units['year'], 'Y' ];
if( $units['month'] > 0 ) return [ $units['month'], 'm' ];
if( $units['day'] > 0 ) return [ $units['day'], 'd' ];
/* (2) Time units */
if( $units['hour'] > 0 ) return [ $units['hour'], 'H' ];
if( $units['minute'] > 0 ) return [ $units['minute'], 'i' ];
if( $units['second'] > 0 ) return [ $units['second'], 's' ];
/* (3) Default value */
return [0, '.'];
}
}

View File

@ -0,0 +1,37 @@
<input type='text' class='searchbar' placeholder='Recherche'>
<article class='inline-row' style='border: 0; box-shadow: none;background: transparent;'>
<span>Machine</span>
<span>Dernière utilisation</span>
<span>Utilisateur</span>
<span>Action</span>
<span>Historique détaillé</span>
</article>
{% for entry in f_history() %}
<article class='inline-row' data-history='{{ entry.id_history }}'>
<span class='title'><span>#{{ entry.machine_name }}</span></span>
<span>
<span>{{ entry.timestamp | f_tsformat }}</span>
<span style='color:#aaa;'>Il y a {{ entry.timestamp | f_tsrelative }}</span>
</span>
<span>
<span>{{ entry.user_name }}</span>
<span style='color:#aaa;'>{{ entry.user_firstname }} {{ entry.user_lastname }}</span>
</span>
<span>
<span>{{ entry.action_name }}</span>
</span>
<span>
<button class='search'>Détails</button>
</span>
</article>
{% endfor %}

View File

@ -452,6 +452,17 @@
} }
} }
},
"historyDefault": {
"getAll": {
"description": "Retourne l'historique complet",
"permissions": ["warehouse", "admin"],
"parameters": {},
"output": {
"history": { "description": "Données de l'historique", "type": "array" }
}
}
} }
} }

View File

@ -1,4 +1,17 @@
{ {
"history": [
"create",
"delete",
"search",
"getAll",
"getByUser",
"getByMachine",
"getByCluster"
],
"user": [ "user": [
"create", "create",
"edit", "edit",

View File

@ -4,6 +4,7 @@
use \error\core\Error; use \error\core\Error;
use \database\core\DatabaseDriver; use \database\core\DatabaseDriver;
use \database\core\Repo; use \database\core\Repo;
use \viewer\core\Viewer;
use \orm\core\Table; use \orm\core\Rows; use \orm\core\Table; use \orm\core\Rows;
?> ?>
@ -41,62 +42,11 @@
/* [1] VIEW -> Liste des utilisateurs /* [1] VIEW -> Liste des acces
=========================================================*/ =========================================================*/
$getusers = new ModuleRequest('userDefault/getAll'); // On utilise la methode 'getAll' du module 'userDefault'
$nbusers = count( $getusers->dispatch()->get('users') ); // On recupere la reponse
$getmachines = new ModuleRequest('machineDefault/getAll'); // On utilise la methode 'getAll' du module 'machineDefault'
$nbmachines = count( $getmachines->dispatch()->get('machines') ); // On recupere la reponse
echo "<section data-sublink='view' class='list fstart'>"; echo "<section data-sublink='view' class='list fstart'>";
// Barre de recherche $view = new Viewer('history.view', []);
echo "<input type='text' class='searchbar' placeholder='Recherche'>"; $view->view();
/* (1) On récupère les données
---------------------------------------------------------*/
$mac = Table::get('machine')
->select('*');
$selected = Table::get('history')
->join('id_machine', $mac)
->select('timestamp', Rows::SEL_MAX)
->select('id_history')
->fetch();
echo "<article class='inline-row' style='border: 0; box-shadow: none;background: transparent;'>";
echo "<span>Machine</span>";
echo "<span>Dernière utilisation</span>";
echo "<span>Conducteurs</span>";
echo "<span>Historique détaillé</span>";
echo "</article>";
foreach($selected as $m=>$mac){
echo "<article class='inline-row' data-history='".$mac['id_history']."'>";
echo "<span class='title'><span>#".$mac['name']."</span></span>";
echo "<span>";
echo "<span>".date('d/m/Y H:i:s', $mac['timestamp'])."</span>";
echo "<span style='color:#aaa;'>Il y a xx jours et yy heures</span>";
echo "</span>";
echo "<span>";
echo "<span>".$mac['agg_id_history']." conducteur(s)</span>";
echo "<span>test</span>";
echo "</span>";
echo "<span>";
echo "<button class='search'>Détails</button>";
echo "</span>";
echo "</article>";
}
echo '</section>'; echo '</section>';