From ff26b99ff324e272e3a25c0bf4a79d092f7bd105 Mon Sep 17 00:00:00 2001
From: Damien <damien.burel@maarch.org>
Date: Mon, 20 Jan 2020 14:50:27 +0100
Subject: [PATCH] FEAT #11882 TIME 1:45 History filters

---
 rest/index.php                                | 11 ++-
 .../PreProcessActionController.php            |  2 +-
 .../history/controllers/HistoryController.php | 94 ++++++++++++++++---
 .../history/models/HistoryModelAbstract.php   | 36 ++-----
 .../history-administration.component.ts       | 10 +-
 .../history-workflow-resume.component.ts      |  4 +-
 src/frontend/app/profile.component.ts         |  2 +-
 7 files changed, 104 insertions(+), 55 deletions(-)

diff --git a/rest/index.php b/rest/index.php
index 865cb1802d1..3d519becce0 100755
--- a/rest/index.php
+++ b/rest/index.php
@@ -250,11 +250,12 @@ $app->delete('/groups/{id}/privileges/{privilegeId}', \Group\controllers\Privile
 $app->put('/groups/{id}/privileges/{privilegeId}/parameters', \Group\controllers\PrivilegeController::class . ':updateParameters');
 $app->get('/groups/{id}/privileges/{privilegeId}/parameters', \Group\controllers\PrivilegeController::class . ':getParameters');
 
-//Histories
-$app->get('/histories', \History\controllers\HistoryController::class . ':get');
-$app->get('/histories/users/{userSerialId}', \History\controllers\HistoryController::class . ':getByUserId');
-$app->get('/histories/resources/{resId}', \History\controllers\HistoryController::class . ':getByResourceId');
-$app->get('/histories/resources/{resId}/workflow', \History\controllers\HistoryController::class . ':getWorkflowByResourceId');
+//History
+$app->get('/history', \History\controllers\HistoryController::class . ':get');
+$app->get('/history/availableEventTypes', \History\controllers\HistoryController::class . ':getAvailableEventTypes');
+$app->get('/history/users/{userSerialId}', \History\controllers\HistoryController::class . ':getByUserId');
+$app->get('/history/resources/{resId}', \History\controllers\HistoryController::class . ':getByResourceId');
+$app->get('/history/resources/{resId}/workflow', \History\controllers\HistoryController::class . ':getWorkflowByResourceId');
 
 //Header
 $app->get('/header', \SrcCore\controllers\CoreController::class . ':getHeader');
diff --git a/src/app/action/controllers/PreProcessActionController.php b/src/app/action/controllers/PreProcessActionController.php
index e2fbfc23c5a..5ce0996bd6d 100755
--- a/src/app/action/controllers/PreProcessActionController.php
+++ b/src/app/action/controllers/PreProcessActionController.php
@@ -1030,7 +1030,7 @@ class PreProcessActionController
                 continue;
             }
 
-            $note = str_replace('['._TO_AVIS.']', '', $opinionNote[0]['note_text']);
+            $note = str_replace('['._TO_AVIS.'] ', '', $opinionNote[0]['note_text']);
             $userInfo = UserModel::getLabelledUserById(['id' => $opinionNote[0]['user_id']]);
             $resourcesInformation['success'][] = ['alt_identifier' => $resource['alt_identifier'], 'res_id' => $resource['res_id'], 'avisUserAsk' => $userInfo, 'note' => $note, 'opinionLimitDate' => $resource['opinion_limit_date']];
         }
diff --git a/src/app/history/controllers/HistoryController.php b/src/app/history/controllers/HistoryController.php
index 409c74c068e..40e4757832f 100755
--- a/src/app/history/controllers/HistoryController.php
+++ b/src/app/history/controllers/HistoryController.php
@@ -14,6 +14,7 @@
 
 namespace History\controllers;
 
+use Action\models\ActionModel;
 use Group\controllers\PrivilegeController;
 use Resource\controllers\ResController;
 use Respect\Validation\Validator;
@@ -33,27 +34,64 @@ class HistoryController
             return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
         }
 
-        $data = $request->getQueryParams();
+        $queryParams = $request->getQueryParams();
 
-        $check = Validator::floatVal()->notEmpty()->validate($data['startDate']);
-        $check = $check && Validator::floatVal()->notEmpty()->validate($data['endDate']);
-        if (!$check) {
-            return $response->withStatus(400)->withJson(['errors' => 'Bad Request']);
+        $limit = 25;
+        if (!empty($queryParams['limit']) && is_numeric($queryParams['limit'])) {
+            $limit = (int)$queryParams['limit'];
+        }
+        $offset = 0;
+        if (!empty($queryParams['offset']) && is_numeric($queryParams['offset'])) {
+            $offset = (int)$queryParams['offset'];
+        }
+
+        $where = [];
+        $data = [];
+        if (!empty($queryParams['users']) && is_array($queryParams['users'])) {
+            foreach ($queryParams['users'] as $user) {
+                if (!is_numeric($user)) {
+                    return $response->withStatus(400)->withJson(['errors' => 'Query params users : one of is not numeric']);
+                }
+            }
+            $users = UserModel::get(['select' => ['user_id'], 'where' => ['id in (?)'], 'data' => [$queryParams['users']]]);
+            $users = array_column($users, 'user_id');
+            $where[] = 'user_id in (?)';
+            $data[] = $users;
+        }
+        if (!empty($queryParams['startDate'])) {
+            $where[] = 'event_date > ?';
+            $data[] = date('Y-m-d H:i:s', $queryParams['startDate']);
+        }
+        if (!empty($queryParams['endDate'])) {
+            $where[] = 'event_date < ?';
+            $data[] = date('Y-m-d H:i:s', $queryParams['endDate']);
+        }
+        if (!empty($queryParams['actions']) && is_array($queryParams['actions'])) {
+            $actions = [];
+            foreach ($queryParams['actions'] as $action) {
+                if (is_numeric($action)) {
+                    $actions[] = "ACTION#{$action}";
+                } else {
+                    $actions[] = $action;
+                }
+            }
+            $where[] = 'event_type in (?)';
+            $data[] = $actions;
         }
 
-        $maxRequestSize = 25000;
+        $order = !in_array($queryParams['order'], ['asc', 'desc']) ? '' : $queryParams['order'];
+        $orderBy = !in_array($queryParams['orderBy'], ['event_date', 'user_id', 'info']) ? ['event_date DESC'] : ["{$queryParams['orderBy']} {$order}"];
 
-        $histories = HistoryModel::get([
-            'select'    => ['event_date', 'event_type', 'user_id', 'info', 'remote_ip'],
-            'where'     => ['event_date > ?', 'event_date < ?'],
-            'data'      => [date('Y-m-d H:i:s', $data['startDate']), date('Y-m-d H:i:s', $data['endDate'])],
-            'orderBy'   => ['event_date DESC'],
-            'limit'     => $maxRequestSize
+        $history = HistoryModel::get([
+            'select'    => ['event_date', 'user_id', 'info', 'remote_ip'],
+            'where'     => $where,
+            'data'      => $data,
+            'orderBy'   => $orderBy,
+            'offset'    => $offset,
+            'limit'     => $limit
         ]);
 
-        $limitExceeded = (count($histories) == $maxRequestSize);
-
-        return $response->withJson(['histories' => $histories, 'limitExceeded' => $limitExceeded]);
+        return $response->withJson(['history' => $history]);
     }
 
     public static function add(array $aArgs)
@@ -134,4 +172,30 @@ class HistoryController
 
         return $response->withJson(['history' => $history]);
     }
+
+    public function getAvailableEventTypes(Request $request, Response $response)
+    {
+        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'view_history', 'userId' => $GLOBALS['id']])) {
+            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
+        }
+
+        $eventTypes = HistoryModel::get([
+            'select'    => ['DISTINCT(event_type)']
+        ]);
+
+        $actions = [];
+        $systemActions = [];
+        foreach ($eventTypes as $eventType) {
+            if (strpos($eventType['event_type'], 'ACTION#') === 0) {
+                $exp = explode('#', $eventType['event_type']);
+                $action = ActionModel::getById(['select' => ['label_action'], 'id' => $exp[1]]);
+                $label = !empty($action) ? $action['label_action'] : null;
+                $actions[] = ['id' => $exp[1], 'label' => $label];
+            } else {
+                $systemActions[] = ['id' => $eventType['event_type'], 'label' => null];
+            }
+        }
+
+        return $response->withJson(['actions' => $actions, 'systemActions' => $systemActions]);
+    }
 }
diff --git a/src/app/history/models/HistoryModelAbstract.php b/src/app/history/models/HistoryModelAbstract.php
index 04655a19b26..923468c8601 100755
--- a/src/app/history/models/HistoryModelAbstract.php
+++ b/src/app/history/models/HistoryModelAbstract.php
@@ -19,19 +19,20 @@ use SrcCore\models\DatabaseModel;
 
 abstract class HistoryModelAbstract
 {
-    public static function get(array $aArgs)
+    public static function get(array $args)
     {
-        ValidatorModel::notEmpty($aArgs, ['select']);
-        ValidatorModel::arrayType($aArgs, ['select', 'where', 'data', 'orderBy']);
-        ValidatorModel::intVal($aArgs, ['limit']);
+        ValidatorModel::notEmpty($args, ['select']);
+        ValidatorModel::arrayType($args, ['select', 'where', 'data', 'orderBy']);
+        ValidatorModel::intVal($args, ['offset', 'limit']);
 
         $aHistories = DatabaseModel::select([
-            'select'    => $aArgs['select'],
+            'select'    => $args['select'],
             'table'     => ['history'],
-            'where'     => empty($aArgs['where']) ? [] : $aArgs['where'],
-            'data'      => empty($aArgs['data']) ? [] : $aArgs['data'],
-            'order_by'  => empty($aArgs['orderBy']) ? [] : $aArgs['orderBy'],
-            'limit'     => empty($aArgs['limit']) ? 0 : $aArgs['limit']
+            'where'     => $args['where'] ?? [],
+            'data'      => $args['data'] ?? [],
+            'order_by'  => $args['orderBy'] ?? [],
+            'offset'    => $args['offset'] ?? 0,
+            'limit'     => $args['limit'] ?? 0
         ]);
 
         return $aHistories;
@@ -111,21 +112,4 @@ abstract class HistoryModelAbstract
 
         return $history;
     }
-
-    public static function getFilter(array $aArgs = [])
-    {
-        ValidatorModel::notEmpty($aArgs, ['select','event_date']);
-        ValidatorModel::stringType($aArgs, ['select']);
-
-        $aReturn = DatabaseModel::select(
-            [
-            'select'   => ['DISTINCT('.$aArgs['select'].')'],
-            'table'    => ['history'],
-            'where'    => ["event_date >= date '".$aArgs['event_date']."'","event_date < date '".$aArgs['event_date']."' + interval '1 month'"],
-            'order_by' => [$aArgs['select'].' ASC']
-            ]
-        );
-
-        return $aReturn;
-    }
 }
diff --git a/src/frontend/app/administration/history/history-administration.component.ts b/src/frontend/app/administration/history/history-administration.component.ts
index 4a656d05dcb..1c898e27e56 100755
--- a/src/frontend/app/administration/history/history-administration.component.ts
+++ b/src/frontend/app/administration/history/history-administration.component.ts
@@ -78,9 +78,9 @@ export class HistoryAdministrationComponent implements OnInit {
 
         this.loading = true;
 
-        this.http.get('../../rest/histories', {params: {"startDate" : (this.startDate.getTime() / 1000).toString(), "endDate" : (this.endDate.getTime() / 1000).toString()}})
+        this.http.get('../../rest/history', {params: {"startDate" : (this.startDate.getTime() / 1000).toString(), "endDate" : (this.endDate.getTime() / 1000).toString()}})
             .subscribe((data: any) => {
-                this.data = data['histories'];
+                this.data = data['history'];
                 this.limitExceeded = data['limitExceeded'];
                 this.loading = false;
                 setTimeout(() => {
@@ -111,7 +111,7 @@ export class HistoryAdministrationComponent implements OnInit {
                 }, 0);
             }, (data: any) => {
                 if(data['error'].errors == 'Service forbidden'){
-                        this.loading = false
+                        this.loading = false;
                         this.accessBatchHistory = false;
                 } else {
                     location.href = "index.php";
@@ -144,9 +144,9 @@ export class HistoryAdministrationComponent implements OnInit {
         if (historyType == 'normal') {
             this.startDate.setHours(0,0,0,0);
             this.endDate.setHours(23,59,59,59);
-            this.http.get('../../rest/histories', {params: {"startDate" : (this.startDate.getTime() / 1000).toString(), "endDate" : (this.endDate.getTime() / 1000).toString()}})
+            this.http.get('../../rest/history', {params: {"startDate" : (this.startDate.getTime() / 1000).toString(), "endDate" : (this.endDate.getTime() / 1000).toString()}})
                 .subscribe((data: any) => {
-                    this.data = data['histories'];
+                    this.data = data['history'];
                     this.limitExceeded = data['limitExceeded'];
                     this.loading = false;
                     setTimeout(() => {
diff --git a/src/frontend/app/history/history-workflow-resume/history-workflow-resume.component.ts b/src/frontend/app/history/history-workflow-resume/history-workflow-resume.component.ts
index 520465cd0e4..0bfa3e74501 100644
--- a/src/frontend/app/history/history-workflow-resume/history-workflow-resume.component.ts
+++ b/src/frontend/app/history/history-workflow-resume/history-workflow-resume.component.ts
@@ -40,7 +40,7 @@ export class HistoryWorkflowResumeComponent implements OnInit {
 
     loadHistory(resId: number) {
         this.loading = true;
-        this.http.get(`../../rest/histories/resources/${resId}/workflow?limit=3`).pipe(
+        this.http.get(`../../rest/history/resources/${resId}/workflow?limit=3`).pipe(
             tap((data: any) => {
                 this.histories = data.history;
             }),
@@ -55,4 +55,4 @@ export class HistoryWorkflowResumeComponent implements OnInit {
     showMore() {
         this.goTo.emit();
     }
-}
\ No newline at end of file
+}
diff --git a/src/frontend/app/profile.component.ts b/src/frontend/app/profile.component.ts
index 3de50d5b0a0..dde85ab969b 100755
--- a/src/frontend/app/profile.component.ts
+++ b/src/frontend/app/profile.component.ts
@@ -201,7 +201,7 @@ export class ProfileComponent implements OnInit {
                 this.sidenavRight.open();
             } 
             //if (this.histories.length == 0) {
-                this.http.get('../../rest/histories/users/' + this.user.id)
+                this.http.get('../../rest/history/users/' + this.user.id)
                     .subscribe((data: any) => {
                         this.histories = data.histories;
                         setTimeout(() => {
-- 
GitLab