From 20ab05564ce76bb37b2f488a5cc3d68fc820314b Mon Sep 17 00:00:00 2001
From: Damien <damien.burel@maarch.org>
Date: Fri, 16 Mar 2018 11:00:20 +0100
Subject: [PATCH] [FEAT] #148 BatchHistory + Unit Test

---
 core/Test/HistoryControllerTest.php           | 44 ++++++++++-----
 rest/index.php                                | 32 +++++------
 .../controllers/BatchHistoryController.php    | 53 ++++++++++++++++++
 .../controllers/HistoryBatchController.php    | 35 ------------
 .../history/controllers/HistoryController.php | 13 +++--
 ...ryBatchModel.php => BatchHistoryModel.php} |  5 +-
 .../models/BatchHistoryModelAbstract.php      | 39 ++++++++++++++
 .../models/HistoryBatchModelAbstract.php      | 54 -------------------
 8 files changed, 149 insertions(+), 126 deletions(-)
 create mode 100644 src/app/history/controllers/BatchHistoryController.php
 delete mode 100644 src/app/history/controllers/HistoryBatchController.php
 rename src/app/history/models/{HistoryBatchModel.php => BatchHistoryModel.php} (65%)
 create mode 100644 src/app/history/models/BatchHistoryModelAbstract.php
 delete mode 100644 src/app/history/models/HistoryBatchModelAbstract.php

diff --git a/core/Test/HistoryControllerTest.php b/core/Test/HistoryControllerTest.php
index 5037ea3979d..81d60ad1d54 100755
--- a/core/Test/HistoryControllerTest.php
+++ b/core/Test/HistoryControllerTest.php
@@ -17,39 +17,55 @@ class HistoryControllerTest extends TestCase
         $request     = \Slim\Http\Request::createFromEnvironment($environment);
         $history     = new \History\controllers\HistoryController();
 
-        $response = $history->getByUserId($request, new \Slim\Http\Response(), ['userSerialId' => 1]);
+        $currentUser = \User\models\UserModel::getByUserId(['userId' => $GLOBALS['userId'], 'select' => ['id']]);
+        $response = $history->getByUserId($request, new \Slim\Http\Response(), ['userSerialId' => $currentUser['id']]);
 
         $responseBody = json_decode((string)$response->getBody());
 
-        $this->assertNotNull($responseBody->histories);
+        $this->assertNotEmpty($responseBody->histories);
     }
 
     public function testGetHistory()
     {
+        $history     = new \History\controllers\HistoryController();
+
+        //  GET
         $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']);
         $request     = \Slim\Http\Request::createFromEnvironment($environment);
-        $history     = new \History\controllers\HistoryController();
 
-        $response = $history->get($request, new \Slim\Http\Response(), ['date' => '2018-01-02']);
+        $aArgs = [
+            'startDate' => '1521100000',
+            'endDate'   => time()
+        ];
+        $fullRequest = $request->withQueryParams($aArgs);
 
+        $response = $history->get($fullRequest, new \Slim\Http\Response());
         $responseBody = json_decode((string)$response->getBody());
 
-        $this->assertNotNull($responseBody->filters->users);
-        $this->assertNotNull($responseBody->filters->eventType);
-        $this->assertNotNull($responseBody->historyList);
+        $this->assertInternalType('array', $responseBody->histories);
+        $this->assertInternalType('bool', $responseBody->limitExceeded);
+        $this->assertNotEmpty($responseBody->histories);
     }
 
-    public function testGetHistoryBatch()
+    public function testGetBatchHistory()
     {
-        $environment  = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']);
-        $request      = \Slim\Http\Request::createFromEnvironment($environment);
-        $historyBatch = new \History\controllers\HistoryBatchController();
+        $batchHistory     = new \History\controllers\BatchHistoryController();
+
+        //  GET
+        $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']);
+        $request     = \Slim\Http\Request::createFromEnvironment($environment);
 
-        $response = $historyBatch->get($request, new \Slim\Http\Response(), ['date' => '2018-01-02']);
+        $aArgs = [
+            'startDate' => '1521100000',
+            'endDate'   => time()
+        ];
+        $fullRequest = $request->withQueryParams($aArgs);
 
+        $response = $batchHistory->get($fullRequest, new \Slim\Http\Response());
         $responseBody = json_decode((string)$response->getBody());
 
-        $this->assertNotNull($responseBody->filters->modules);
-        $this->assertNotNull($responseBody->historyList);
+        $this->assertInternalType('array', $responseBody->batchHistories);
+        $this->assertInternalType('bool', $responseBody->limitExceeded);
+        $this->assertNotNull($responseBody->batchHistories);
     }
 }
diff --git a/rest/index.php b/rest/index.php
index d395fbdd1d4..efac0cf9752 100755
--- a/rest/index.php
+++ b/rest/index.php
@@ -141,6 +141,9 @@ $app->get('/baskets/{id}/groups/data', \Basket\controllers\BasketController::cla
 $app->get('/sortedBaskets', \Basket\controllers\BasketController::class . ':getSorted');
 $app->put('/sortedBaskets/{id}', \Basket\controllers\BasketController::class . ':updateSort');
 
+//BatchHistories
+$app->get('/batchHistories', \History\controllers\BatchHistoryController::class . ':get');
+
 //Contacts
 $app->post('/contacts', \Contact\controllers\ContactController::class . ':create');
 $app->get('/contacts/{contactId}/communication', \Contact\controllers\ContactController::class . ':getCommunicationByContactId');
@@ -191,6 +194,10 @@ $app->get('/groups/{id}/details', \Group\controllers\GroupController::class . ':
 $app->put('/groups/{id}/services/{serviceId}', \Group\controllers\GroupController::class . ':updateService');
 $app->put('/groups/{id}/reassign/{newGroupId}', \Group\controllers\GroupController::class . ':reassignUsers');
 
+//Histories
+$app->get('/histories', \History\controllers\HistoryController::class . ':get');
+$app->get('/histories/users/{userSerialId}', \History\controllers\HistoryController::class . ':getByUserId');
+
 //Links
 $app->get('/links/resId/{resId}', \Link\controllers\LinkController::class . ':getByResId');
 
@@ -246,15 +253,6 @@ $app->get('/administration/statuses/new', \Status\controllers\StatusController::
 //Templates
 $app->post('/templates/{id}/duplicate', \Template\controllers\TemplateController::class . ':duplicate');
 
-//Visa
-$app->get('/{basketId}/signatureBook/resList', \Visa\Controllers\VisaController::class . ':getResList');
-$app->get('/{basketId}/signatureBook/resList/details', \Visa\Controllers\VisaController::class . ':getDetailledResList');
-$app->get('/groups/{groupId}/baskets/{basketId}/signatureBook/{resId}', \Visa\Controllers\VisaController::class . ':getSignatureBook');
-$app->get('/signatureBook/{resId}/attachments', \Visa\Controllers\VisaController::class . ':getAttachmentsById');
-$app->get('/signatureBook/{resId}/incomingMailAttachments', \Visa\Controllers\VisaController::class . ':getIncomingMailAndAttachmentsById');
-$app->put('/{collId}/{resId}/unsign', \Visa\Controllers\VisaController::class . ':unsignFile');
-$app->put('/attachments/{id}/inSignatureBook', \Attachment\controllers\AttachmentController::class . ':setInSignatureBook');
-
 //Users
 $app->get('/users', \User\controllers\UserController::class . ':get');
 $app->post('/users', \User\controllers\UserController::class . ':create');
@@ -277,6 +275,15 @@ $app->post('/users/{id}/redirectedBaskets', \User\controllers\UserController::cl
 $app->delete('/users/{id}/redirectedBaskets/{basketId}', \User\controllers\UserController::class . ':deleteRedirectedBaskets');
 $app->put('/users/{id}/baskets', \User\controllers\UserController::class . ':updateBasketsDisplay');
 
+//Visa
+$app->get('/{basketId}/signatureBook/resList', \Visa\Controllers\VisaController::class . ':getResList');
+$app->get('/{basketId}/signatureBook/resList/details', \Visa\Controllers\VisaController::class . ':getDetailledResList');
+$app->get('/groups/{groupId}/baskets/{basketId}/signatureBook/{resId}', \Visa\Controllers\VisaController::class . ':getSignatureBook');
+$app->get('/signatureBook/{resId}/attachments', \Visa\Controllers\VisaController::class . ':getAttachmentsById');
+$app->get('/signatureBook/{resId}/incomingMailAttachments', \Visa\Controllers\VisaController::class . ':getIncomingMailAndAttachmentsById');
+$app->put('/{collId}/{resId}/unsign', \Visa\Controllers\VisaController::class . ':unsignFile');
+$app->put('/attachments/{id}/inSignatureBook', \Attachment\controllers\AttachmentController::class . ':setInSignatureBook');
+
 //CurrentUser
 $app->get('/currentUser/profile', \User\controllers\UserController::class . ':getProfile');
 $app->put('/currentUser/profile', \User\controllers\UserController::class . ':updateProfile');
@@ -286,13 +293,6 @@ $app->put('/currentUser/emailSignature/{id}', \User\controllers\UserController::
 $app->delete('/currentUser/emailSignature/{id}', \User\controllers\UserController::class . ':deleteCurrentUserEmailSignature');
 $app->put('/currentUser/groups/{groupId}/baskets/{basketId}', \User\controllers\UserController::class . ':updateBasketPreference');
 
-//History
-$app->get('/histories', \History\controllers\HistoryController::class . ':get');
-$app->get('/histories/users/{userSerialId}', \History\controllers\HistoryController::class . ':getByUserId');
-
-//HistoryBatch
-$app->get('/administration/historyBatch/eventDate/{date}', \History\controllers\HistoryBatchController::class . ':get');//TODO No date
-
 //Notifications
 $app->get('/notifications', \Notification\controllers\NotificationController::class . ':get');
 $app->post('/notifications', \Notification\controllers\NotificationController::class . ':create');
diff --git a/src/app/history/controllers/BatchHistoryController.php b/src/app/history/controllers/BatchHistoryController.php
new file mode 100644
index 00000000000..91f7dbdd443
--- /dev/null
+++ b/src/app/history/controllers/BatchHistoryController.php
@@ -0,0 +1,53 @@
+<?php
+
+/**
+* Copyright Maarch since 2008 under licence GPLv3.
+* See LICENCE.txt file at the root folder for more details.
+* This file is part of Maarch software.
+*
+*/
+
+/**
+* @brief Batch History Controller
+* @author dev@maarch.org
+*/
+
+namespace History\controllers;
+
+use Group\models\ServiceModel;
+use History\models\BatchHistoryModel;
+use Respect\Validation\Validator;
+use Slim\Http\Request;
+use Slim\Http\Response;
+
+class BatchHistoryController
+{
+    public function get(Request $request, Response $response)
+    {
+        if (!ServiceModel::hasService(['id' => 'view_history_batch', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'admin'])) {
+            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
+        }
+
+        $data = $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']);
+        }
+
+        $maxRequestSize = 10000;
+
+        $batchHistories = BatchHistoryModel::get([
+            'select'    => ['event_date', 'module_name', 'batch_id', 'total_processed', 'total_errors', 'info'],
+            '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
+        ]);
+
+        $limitExceeded = (count($batchHistories) == $maxRequestSize);
+
+        return $response->withJson(['batchHistories' => $batchHistories, 'limitExceeded' => $limitExceeded]);
+    }
+}
diff --git a/src/app/history/controllers/HistoryBatchController.php b/src/app/history/controllers/HistoryBatchController.php
deleted file mode 100644
index 5e37cc736be..00000000000
--- a/src/app/history/controllers/HistoryBatchController.php
+++ /dev/null
@@ -1,35 +0,0 @@
-<?php
-
-/**
-* Copyright Maarch since 2008 under licence GPLv3.
-* See LICENCE.txt file at the root folder for more details.
-* This file is part of Maarch software.
-*
-*/
-
-/**
-* @brief HistoryBatch Controller
-* @author dev@maarch.org
-*/
-
-namespace History\controllers;
-
-use Group\models\ServiceModel;
-use History\models\HistoryBatchModel;
-use Slim\Http\Request;
-use Slim\Http\Response;
-
-class HistoryBatchController
-{
-    public function get(Request $request, Response $response, array $aArgs)
-    {
-        if (!ServiceModel::hasService(['id' => 'view_history_batch', 'userId' => $GLOBALS['userId'], 'location' => 'apps', 'type' => 'admin'])) {
-            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
-        }
-
-        $historyList = HistoryBatchModel::get(['event_date' => $aArgs['date']]);
-        $historyListFilters['modules'] = HistoryBatchModel::getFilter(['select' => 'module_name', 'event_date' => $aArgs['date']]);
-        
-        return $response->withJson(['filters' => $historyListFilters, 'historyList' => $historyList]);
-    }
-}
diff --git a/src/app/history/controllers/HistoryController.php b/src/app/history/controllers/HistoryController.php
index 3caaa8792a0..af0bb61c7c5 100644
--- a/src/app/history/controllers/HistoryController.php
+++ b/src/app/history/controllers/HistoryController.php
@@ -34,20 +34,25 @@ class HistoryController
 
         $data = $request->getQueryParams();
 
-        $check = Validator::stringType()->notEmpty()->validate($data['startDate']);
-        $check = $check && Validator::stringType()->notEmpty()->validate($data['endDate']);
+        $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']);
         }
 
+        $maxRequestSize = 10000;
+
         $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'])],
-            'limit'     => 20000
+            'orderBy'   => ['event_date DESC'],
+            'limit'     => $maxRequestSize
         ]);
 
-        return $response->withJson(['histories' => $histories]);
+        $limitExceeded = (count($histories) == $maxRequestSize);
+
+        return $response->withJson(['histories' => $histories, 'limitExceeded' => $limitExceeded]);
     }
 
     public static function add(array $aArgs)
diff --git a/src/app/history/models/HistoryBatchModel.php b/src/app/history/models/BatchHistoryModel.php
similarity index 65%
rename from src/app/history/models/HistoryBatchModel.php
rename to src/app/history/models/BatchHistoryModel.php
index ac51f1bea70..1161d3c64be 100644
--- a/src/app/history/models/HistoryBatchModel.php
+++ b/src/app/history/models/BatchHistoryModel.php
@@ -8,13 +8,12 @@
 */
 
 /**
-* @brief HistoryBatch Model
+* @brief Batch History Model
 * @author dev@maarch.org
 */
 
 namespace History\models;
 
-class HistoryBatchModel extends HistoryBatchModelAbstract
+class BatchHistoryModel extends BatchHistoryModelAbstract
 {
-    // Do your stuff in this class
 }
diff --git a/src/app/history/models/BatchHistoryModelAbstract.php b/src/app/history/models/BatchHistoryModelAbstract.php
new file mode 100644
index 00000000000..2d665a34c54
--- /dev/null
+++ b/src/app/history/models/BatchHistoryModelAbstract.php
@@ -0,0 +1,39 @@
+<?php
+
+/**
+* Copyright Maarch since 2008 under licence GPLv3.
+* See LICENCE.txt file at the root folder for more details.
+* This file is part of Maarch software.
+*
+*/
+
+/**
+* @brief Batch History Model Abstract
+* @author dev@maarch.org
+*/
+
+namespace History\models;
+
+use SrcCore\models\ValidatorModel;
+use SrcCore\models\DatabaseModel;
+
+abstract class BatchHistoryModelAbstract
+{
+    public static function get(array $aArgs)
+    {
+        ValidatorModel::notEmpty($aArgs, ['select']);
+        ValidatorModel::arrayType($aArgs, ['select', 'where', 'data', 'orderBy']);
+        ValidatorModel::intVal($aArgs, ['limit']);
+
+        $aHistories = DatabaseModel::select([
+            'select'    => $aArgs['select'],
+            'table'     => ['history_batch'],
+            'where'     => $aArgs['where'],
+            'data'      => $aArgs['data'],
+            'order_by'  => $aArgs['orderBy'],
+            'limit'     => $aArgs['limit']
+        ]);
+
+        return $aHistories;
+    }
+}
diff --git a/src/app/history/models/HistoryBatchModelAbstract.php b/src/app/history/models/HistoryBatchModelAbstract.php
deleted file mode 100644
index c1db9c17f1f..00000000000
--- a/src/app/history/models/HistoryBatchModelAbstract.php
+++ /dev/null
@@ -1,54 +0,0 @@
-<?php
-
-/**
-* Copyright Maarch since 2008 under licence GPLv3.
-* See LICENCE.txt file at the root folder for more details.
-* This file is part of Maarch software.
-*
-*/
-
-/**
-* @brief HistoryBatch Model
-* @author dev@maarch.org
-*/
-
-namespace History\models;
-
-use SrcCore\models\ValidatorModel;
-use SrcCore\models\DatabaseModel;
-
-require_once('apps/maarch_entreprise/tools/log4php/Logger.php'); //TODO composer
-
-class HistoryBatchModelAbstract
-{
-    public static function get(array $aArgs = [])
-    {
-        ValidatorModel::notEmpty($aArgs, ['event_date']);
-
-        $aReturn = DatabaseModel::select([
-            'select'    => empty($aArgs['select']) ? ['*'] : $aArgs['select'],
-            'table'     => ['history_batch'],
-            'where'     => ["event_date >= date '".$aArgs['event_date']."'","event_date < date '".$aArgs['event_date']."' + interval '1 month'"],
-            'order_by'  => ['event_date DESC']
-        ]);
-
-        return $aReturn;
-    }
-
-    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_batch'],
-            'where'     => ["event_date >= date '".$aArgs['event_date']."'","event_date < date '".$aArgs['event_date']."' + interval '1 month'"],
-            'order_by'  => [$aArgs['select'].' ASC']
-            ]
-        );
-
-        return $aReturn;
-    }
-}
-- 
GitLab