From 38ec00ff48f2046dd48533f8e5699b25b0c42484 Mon Sep 17 00:00:00 2001
From: Damien <damien.burel@maarch.org>
Date: Mon, 30 Sep 2019 14:59:10 +0200
Subject: [PATCH] FEAT #11933 Note controller update + delete + refactoring sql

---
 apps/maarch_entreprise/actions/close_mail.php |   3 +-
 migration/19.12/1912.sql                      |  16 +-
 .../ReceiveMessageExchangeController.php      |   2 +-
 rest/index.php                                |   2 +
 .../controllers/ActionMethodController.php    |   2 +-
 .../controllers/MergeController.php           |   2 +-
 src/app/note/controllers/NoteController.php   | 131 ++++++++++++++-
 src/app/note/models/NoteEntityModel.php       |  16 +-
 src/app/note/models/NoteModel.php             | 151 +++++++++++-------
 .../resource/controllers/ResController.php    |   2 +-
 .../controllers/ResourceListController.php    |   2 +-
 .../controllers/SummarySheetController.php    |   5 +-
 .../controllers/SignatureBookController.php   |   2 +-
 src/app/tag/controllers/TagController.php     |  96 +++++------
 .../template/models/TemplateModelAbstract.php |  22 +--
 src/core/lang/lang-en.php                     |   2 +
 src/core/lang/lang-fr.php                     |   2 +
 src/core/lang/lang-nl.php                     |   2 +
 18 files changed, 322 insertions(+), 138 deletions(-)

diff --git a/apps/maarch_entreprise/actions/close_mail.php b/apps/maarch_entreprise/actions/close_mail.php
index db041e3ecc6..7ba64faa509 100755
--- a/apps/maarch_entreprise/actions/close_mail.php
+++ b/apps/maarch_entreprise/actions/close_mail.php
@@ -132,7 +132,8 @@ function manage_form($arr_id, $history, $id_action, $label_action, $status, $col
         
         # save note
         if ($formValues['note_content_to_users'] != '') {
-            \Note\models\NoteModel::create(['resId' => $res_id, 'login' => $_SESSION['user']['UserId'], 'note_text' => $formValues['note_content_to_users']]);
+            $user = \User\models\UserModel::getByLogin(['login' => $_SESSION['user']['UserId'], 'select' => ['id']]);
+            \Note\models\NoteModel::create(['resId' => $res_id, 'user_id' => $user['id'], 'note_text' => $formValues['note_content_to_users']]);
         }
 
         if (\SrcCore\models\CurlModel::isEnabled(['curlCallId' => 'closeResource'])) {
diff --git a/migration/19.12/1912.sql b/migration/19.12/1912.sql
index 856022cd4c1..97927d93b91 100644
--- a/migration/19.12/1912.sql
+++ b/migration/19.12/1912.sql
@@ -179,7 +179,7 @@ DO $$ BEGIN
 	  ALTER TABLE doctypes ADD COLUMN delay2 INTEGER;
 	  ALTER TABLE doctypes ADD COLUMN process_mode CHARACTER VARYING(256);
 	  UPDATE doctypes SET process_delay = (SELECT process_delay FROM mlb_doctype_ext where doctypes.type_id = mlb_doctype_ext.type_id);
-    UPDATE doctypes SET process_delay = 30 WHERE process_delay is null;
+	  UPDATE doctypes SET process_delay = 30 WHERE process_delay is null;
 	  UPDATE doctypes SET delay1 = (SELECT delay1 FROM mlb_doctype_ext where doctypes.type_id = mlb_doctype_ext.type_id);
     UPDATE doctypes SET delay1 = 14 WHERE delay1 is null;
 	  UPDATE doctypes SET delay2 = (SELECT delay2 FROM mlb_doctype_ext where doctypes.type_id = mlb_doctype_ext.type_id);
@@ -194,6 +194,20 @@ DO $$ BEGIN
 END$$;
 
 
+/* NOTES */
+DO $$ BEGIN
+    IF (SELECT count(attname) FROM pg_attribute WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = 'notes') AND attname = 'type') THEN
+        ALTER TABLE notes ADD COLUMN user_tmp_id integer;
+        UPDATE notes set user_tmp_id = (select id FROM users where users.user_id = notes.user_id);
+        UPDATE notes set user_tmp_id = 0 WHERE user_tmp_id IS NULL;
+        ALTER TABLE notes ALTER COLUMN user_tmp_id set not null;
+        ALTER TABLE notes DROP COLUMN IF EXISTS user_id;
+        ALTER TABLE notes RENAME COLUMN user_tmp_id TO user_id;
+        ALTER TABLE notes DROP COLUMN IF EXISTS type;
+    END IF;
+END$$;
+
+
 /* REFACTORING DATA */
 DO $$ BEGIN
   IF (SELECT count(attname) FROM pg_attribute WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = 'usergroups') AND attname = 'enabled') THEN
diff --git a/modules/sendmail/Controllers/ReceiveMessageExchangeController.php b/modules/sendmail/Controllers/ReceiveMessageExchangeController.php
index 9411abec794..baed0a6ab73 100755
--- a/modules/sendmail/Controllers/ReceiveMessageExchangeController.php
+++ b/modules/sendmail/Controllers/ReceiveMessageExchangeController.php
@@ -349,7 +349,7 @@ class ReceiveMessageExchangeController
         foreach ($aArgs['dataObject']->Comment as $value) {
             NoteModel::create([
                 "resId" => $aArgs['resId'],
-                "login"    => "superadmin",
+                "user_id"    => 0,
                 "note_text"  => $value->value
             ]);
 
diff --git a/rest/index.php b/rest/index.php
index b157c7bbf8f..9990010a686 100755
--- a/rest/index.php
+++ b/rest/index.php
@@ -267,6 +267,8 @@ $app->put('/listTemplates/types/{typeId}/roles', \Entity\controllers\ListTemplat
 $app->get('/notes/templates', \Note\controllers\NoteController::class . ':getTemplates');
 $app->get('/res/{resId}/notes', \Note\controllers\NoteController::class . ':getByResId');
 $app->post('/res/{resId}/notes', \Note\controllers\NoteController::class . ':create');
+$app->put('/resources/{resId}/notes/{id}', \Note\controllers\NoteController::class . ':update');
+$app->delete('/resources/{resId}/notes/{id}', \Note\controllers\NoteController::class . ':delete');
 
 //Parameters
 $app->get('/parameters', \Parameter\controllers\ParameterController::class . ':get');
diff --git a/src/app/action/controllers/ActionMethodController.php b/src/app/action/controllers/ActionMethodController.php
index 33dc89016b0..a7d802226ea 100644
--- a/src/app/action/controllers/ActionMethodController.php
+++ b/src/app/action/controllers/ActionMethodController.php
@@ -74,7 +74,7 @@ class ActionMethodController
             if (!empty(trim($aArgs['note']))) {
                 NoteModel::create([
                     'resId'     => $resource,
-                    'login'     => $GLOBALS['userId'],
+                    'user_id'   => $GLOBALS['id'],
                     'note_text' => $aArgs['note']
                 ]);
             }
diff --git a/src/app/contentManagement/controllers/MergeController.php b/src/app/contentManagement/controllers/MergeController.php
index 12c714ed742..7d5f2fe00c8 100644
--- a/src/app/contentManagement/controllers/MergeController.php
+++ b/src/app/contentManagement/controllers/MergeController.php
@@ -144,7 +144,7 @@ class MergeController
         $mergedNote = '';
         $notes = NoteModel::getByUserIdForResource(['select' => ['note_text', 'creation_date', 'user_id'], 'resId' => $args['resId'], 'userId' => $args['userId']]);
         foreach ($notes as $note) {
-            $labelledUser = UserModel::getLabelledUserById(['login' => $note['user_id']]);
+            $labelledUser = UserModel::getLabelledUserById(['id' => $note['user_id']]);
             $creationDate = TextFormatModel::formatDate($note['creation_date'], 'd/m/Y');
             $mergedNote .= "{$labelledUser} : {$creationDate} : {$note['note_text']}\n";
         }
diff --git a/src/app/note/controllers/NoteController.php b/src/app/note/controllers/NoteController.php
index ca3f7052a70..943d38923d7 100755
--- a/src/app/note/controllers/NoteController.php
+++ b/src/app/note/controllers/NoteController.php
@@ -46,10 +46,10 @@ class NoteController
         $aNotes = NoteModel::getByUserIdForResource(['select' => ['*'], 'resId' => $aArgs['resId'], 'userId' => $user['id']]);
         
         foreach ($aNotes as $key => $aNote) {
-            $aUser = UserModel::getByLogin(['select' => ['firstname', 'lastname'], 'login' => $aNote['user_id']]);
-            $primaryEntity = UserModel::getPrimaryEntityByUserId(['userId' => $aNote['user_id']]);
-            $aNotes[$key]['firstname'] = $aUser['firstname'];
-            $aNotes[$key]['lastname'] = $aUser['lastname'];
+            $user = UserModel::getById(['select' => ['firstname', 'lastname', 'user_id'], 'id' => $aNote['user_id']]);
+            $primaryEntity = UserModel::getPrimaryEntityByUserId(['userId' => $user['user_id']]);
+            $aNotes[$key]['firstname'] = $user['firstname'];
+            $aNotes[$key]['lastname'] = $user['lastname'];
             $aNotes[$key]['entity_label'] = $primaryEntity['entity_label'];
         }
 
@@ -87,7 +87,7 @@ class NoteController
 
         $noteId = NoteModel::create([
             'resId'     => $aArgs['resId'],
-            'login'     => $GLOBALS['userId'],
+            'user_id'   => $GLOBALS['id'],
             'note_text' => $data['note_text']
         ]);
     
@@ -101,7 +101,6 @@ class NoteController
             'tableName' => "notes",
             'recordId'  => $noteId,
             'eventType' => "ADD",
-            'userId'    => $GLOBALS['userId'],
             'info'      => _NOTE_ADDED . " (" . $noteId . ")",
             'moduleId'  => 'notes',
             'eventId'   => 'noteadd'
@@ -110,6 +109,99 @@ class NoteController
         return $response->withJson(['noteId' => $noteId]);
     }
 
+    public function update(Request $request, Response $response, array $args)
+    {
+        if (!ResController::hasRightByResId(['resId' => [$args['resId']], 'userId' => $GLOBALS['id']])) {
+            return $response->withStatus(403)->withJson(['errors' => 'Document out of perimeter']);
+        }
+
+        $note = NoteModel::getById(['select' => ['user_id'], 'id' => $args['id']]);
+        if (empty($note) || $note['user_id'] != $GLOBALS['id']) {
+            return $response->withStatus(403)->withJson(['errors' => 'Note out of perimeter']);
+        }
+
+        $body = $request->getParsedBody();
+
+        if (!Validator::stringType()->notEmpty()->validate($body['value'])) {
+            return $response->withStatus(400)->withJson(['errors' => 'Body value is empty or not a string']);
+        }
+
+        if (!empty($body['entities'])) {
+            if (!Validator::arrayType()->validate($body['entities'])) {
+                return $response->withStatus(400)->withJson(['errors' => 'Body entities is not an array']);
+            }
+            foreach ($body['entities'] as $entityId) {
+                $entities = Entitymodel::get(['select' => ['count(1)'], 'where' => ['entity_id in (?)'], 'data' => [$body['entities']]]);
+                if ($entities[0]['count'] != count($body['entities'])) {
+                    return $response->withStatus(400)->withJson(['errors' => 'Body entities : one or more entities do not exist']);
+                }
+            }
+        }
+
+        NoteModel::update([
+            'set' => [
+                'note_text' => $body['value']
+            ],
+            'where' => ['id = ?'],
+            'data'  => [$args['id']]
+        ]);
+
+        NoteEntityModel::delete([
+            'where' => ['note_id = ?'],
+            'data'  => [$args['id']]
+        ]);
+
+        if (!empty($body['entities'])) {
+            foreach ($body['entities'] as $entity) {
+                NoteEntityModel::create(['item_id' => $entity, 'note_id' => $args['id']]);
+            }
+        }
+
+        HistoryController::add([
+            'tableName' => 'notes',
+            'recordId'  => $args['id'],
+            'eventType' => "UP",
+            'info'      => _NOTE_UPDATED,
+            'moduleId'  => 'notes',
+            'eventId'   => 'noteModification'
+        ]);
+
+        return $response->withStatus(204);
+    }
+
+    public function delete(Request $request, Response $response, array $args)
+    {
+        if (!ResController::hasRightByResId(['resId' => [$args['resId']], 'userId' => $GLOBALS['id']])) {
+            return $response->withStatus(403)->withJson(['errors' => 'Document out of perimeter']);
+        }
+
+        $note = NoteModel::getById(['select' => ['user_id'], 'id' => $args['id']]);
+        if (empty($note) || $note['user_id'] != $GLOBALS['id']) {
+            return $response->withStatus(403)->withJson(['errors' => 'Note out of perimeter']);
+        }
+
+        NoteModel::delete([
+            'where' => ['id = ?'],
+            'data'  => [$args['id']]
+        ]);
+
+        NoteEntityModel::delete([
+            'where' => ['note_id = ?'],
+            'data'  => [$args['id']]
+        ]);
+
+        HistoryController::add([
+            'tableName' => 'notes',
+            'recordId'  => $args['id'],
+            'eventType' => "DEL",
+            'info'      => _NOTE_DELETED,
+            'moduleId'  => 'notes',
+            'eventId'   => 'noteSuppression'
+        ]);
+
+        return $response->withStatus(204);
+    }
+
     public static function getEncodedPdfByIds(array $aArgs)
     {
         ValidatorModel::notEmpty($aArgs, ['ids']);
@@ -122,7 +214,7 @@ class NoteController
         foreach ($aArgs['ids'] as $noteId) {
             $note = NoteModel::getById(['id' => $noteId, 'select' => ['note_text', 'creation_date', 'user_id']]);
 
-            $user = UserModel::getByLogin(['login' => $note['user_id'], 'select' => ['firstname', 'lastname']]);
+            $user = UserModel::getById(['id' => $note['user_id'], 'select' => ['firstname', 'lastname']]);
             $date = new \DateTime($note['creation_date']);
             $date = $date->format('d-m-Y H:i');
 
@@ -162,4 +254,29 @@ class NoteController
 
         return $response->withJson(['templates' => $templates]);
     }
+
+    public static function hasRightById(array $args)
+    {
+        ValidatorModel::notEmpty($args, ['id', 'userId']);
+        ValidatorModel::intVal($args, ['id', 'userId']);
+
+        $note = NoteModel::getById(['select' => ['user_id'], 'id' => $args['id']]);
+        if ($note['user_id'] == $args['userId']) {
+            return true;
+        }
+
+        $user = UserModel::getById(['select' => ['user_id'], 'id' => $args['userId']]);
+        $userEntities = EntityModel::getByLogin(['login' => $user['user_id'], 'select' => ['entity_id']]);
+        $userEntities = array_column($userEntities, 'entity_id');
+        if (empty($userEntities)) {
+            return false;
+        }
+
+        $noteEntities = NoteEntityModel::get(['select' => [1], 'where' => ['note_id = ?', 'item_id in (?)'], 'data' => [$args['id'], $userEntities]]);
+        if (empty($noteEntities)) {
+            return false;
+        }
+
+        return true;
+    }
 }
diff --git a/src/app/note/models/NoteEntityModel.php b/src/app/note/models/NoteEntityModel.php
index ff426decdbb..95ac0478493 100644
--- a/src/app/note/models/NoteEntityModel.php
+++ b/src/app/note/models/NoteEntityModel.php
@@ -50,6 +50,20 @@ class NoteEntityModel
         return true;
     }
 
+    public static function delete(array $args)
+    {
+        ValidatorModel::notEmpty($args, ['where', 'data']);
+        ValidatorModel::arrayType($args, ['where', 'data']);
+
+        DatabaseModel::delete([
+            'table' => 'note_entities',
+            'where' => $args['where'],
+            'data'  => $args['data']
+        ]);
+
+        return true;
+    }
+
     public static function getWithEntityInfo(array $aArgs = [])
     {
         ValidatorModel::arrayType($aArgs, ['select', 'where', 'data']);
@@ -64,4 +78,4 @@ class NoteEntityModel
 
         return $noteEntities;
     }
-}
\ No newline at end of file
+}
diff --git a/src/app/note/models/NoteModel.php b/src/app/note/models/NoteModel.php
index 024d03efd16..de119d870cc 100755
--- a/src/app/note/models/NoteModel.php
+++ b/src/app/note/models/NoteModel.php
@@ -38,17 +38,17 @@ class NoteModel
         return $notes;
     }
 
-    public static function getById(array $aArgs)
+    public static function getById(array $args)
     {
-        ValidatorModel::notEmpty($aArgs, ['id']);
-        ValidatorModel::intVal($aArgs, ['id']);
-        ValidatorModel::arrayType($aArgs, ['select']);
+        ValidatorModel::notEmpty($args, ['id']);
+        ValidatorModel::intVal($args, ['id']);
+        ValidatorModel::arrayType($args, ['select']);
 
         $note = DatabaseModel::select([
-            'select'    => empty($aArgs['select']) ? ['*'] : $aArgs['select'],
+            'select'    => empty($args['select']) ? ['*'] : $args['select'],
             'table'     => ['notes'],
             'where'     => ['id = ?'],
-            'data'      => [$aArgs['id']],
+            'data'      => [$args['id']],
         ]);
 
         if (empty($note[0])) {
@@ -58,73 +58,55 @@ class NoteModel
         return $note[0];
     }
 
-    public static function countByResId(array $aArgs)
+    public static function create(array $args)
     {
-        ValidatorModel::notEmpty($aArgs, ['resId', 'login']);
-        ValidatorModel::intVal($aArgs, ['resId']);
-        ValidatorModel::stringType($aArgs, ['login']);
+        ValidatorModel::notEmpty($args, ['resId', 'note_text', 'user_id']);
+        ValidatorModel::intVal($args, ['resId', 'user_id']);
+        ValidatorModel::stringType($args, ['note_text']);
 
-        $nb = 0;
-        $countedNotes = [];
-        $entities = [];
+        $nextSequenceId = DatabaseModel::getNextSequenceValue(['sequenceId' => 'notes_id_seq']);
 
-        $aEntities = DatabaseModel::select([
-            'select'    => ['entity_id'],
-            'table'     => ['users_entities'],
-            'where'     => ['user_id = ?'],
-            'data'      => [$aArgs['login']]
+        DatabaseModel::insert([
+            'table'         => 'notes',
+            'columnsValues' => [
+                'id'            => $nextSequenceId,
+                'identifier'    => $args['resId'],
+                'user_id'       => $args['user_id'],
+                'creation_date' => 'CURRENT_TIMESTAMP',
+                'note_text'     => $args['note_text']
+            ]
         ]);
 
-        foreach ($aEntities as $value) {
-            $entities[] = $value['entity_id'];
-        }
+        return $nextSequenceId;
+    }
 
-        $aNotes = DatabaseModel::select([
-            'select'    => ['notes.id', 'user_id', 'item_id'],
-            'table'     => ['notes', 'note_entities'],
-            'left_join' => ['notes.id = note_entities.note_id'],
-            'where'     => ['identifier = ?'],
-            'data'      => [$aArgs['resId']]
+    public static function update(array $args)
+    {
+        ValidatorModel::notEmpty($args, ['set', 'where', 'data']);
+        ValidatorModel::arrayType($args, ['set', 'where', 'data']);
+
+        DatabaseModel::update([
+            'table' => 'notes',
+            'set'   => $args['set'],
+            'where' => $args['where'],
+            'data'  => $args['data']
         ]);
 
-        foreach ($aNotes as $value) {
-            if (empty($value['item_id']) && !in_array($value['id'], $countedNotes)) {
-                ++$nb;
-                $countedNotes[] = $value['id'];
-            } elseif (!empty($value['item_id'])) {
-                if ($value['user_id'] == $aArgs['login'] && !in_array($value['id'], $countedNotes)) {
-                    ++$nb;
-                    $countedNotes[] = $value['id'];
-                } elseif (in_array($value['item_id'], $entities) && !in_array($value['id'], $countedNotes)) {
-                    ++$nb;
-                    $countedNotes[] = $value['id'];
-                }
-            }
-        }
-
-        return $nb;
+        return true;
     }
 
-    public static function create(array $aArgs)
+    public static function delete(array $args)
     {
-        ValidatorModel::notEmpty($aArgs, ['resId', 'note_text', 'login']);
-        ValidatorModel::intVal($aArgs, ['resId']);
-        ValidatorModel::stringType($aArgs, ['login', 'note_text']);
+        ValidatorModel::notEmpty($args, ['where', 'data']);
+        ValidatorModel::arrayType($args, ['where', 'data']);
 
-        $nextSequenceId = DatabaseModel::getNextSequenceValue(['sequenceId' => 'notes_id_seq']);
-
-        DatabaseModel::insert([
-            'table'         => 'notes',
-            'columnsValues' => [
-                'id'            => $nextSequenceId,
-                'identifier'    => $aArgs['resId'],
-                'user_id'       => $aArgs['login'],
-                'creation_date' => 'CURRENT_TIMESTAMP',
-                'note_text'     => $aArgs['note_text']
-            ]
+        DatabaseModel::delete([
+            'table' => 'notes',
+            'where' => $args['where'],
+            'data'  => $args['data']
         ]);
 
-        return $nextSequenceId;
+        return true;
     }
 
     public static function getByResId(array $aArgs = [])
@@ -136,7 +118,7 @@ class NoteModel
         $aReturn = DatabaseModel::select([
             'select'    => empty($aArgs['select']) ? ['*'] : $aArgs['select'],
             'table'     => ['notes', 'users', 'users_entities', 'entities'],
-            'left_join' => ['notes.user_id = users.user_id', 'users.user_id = users_entities.user_id', 'users_entities.entity_id = entities.entity_id'],
+            'left_join' => ['notes.user_id = users.id', 'users.user_id = users_entities.user_id', 'users_entities.entity_id = entities.entity_id'],
             'where'     => ['notes.identifier = ?', '(users_entities.primary_entity=\'Y\' or notes.user_id = \'superadmin\')'],
             'data'      => [$aArgs['resId']],
             'order_by'  => empty($aArgs['orderBy']) ? ['creation_date'] : $aArgs['orderBy']
@@ -172,6 +154,53 @@ class NoteModel
         return $aReturn;
     }
 
+    public static function countByResId(array $aArgs)
+    {
+        ValidatorModel::notEmpty($aArgs, ['resId', 'login', 'userId']);
+        ValidatorModel::intVal($aArgs, ['resId', 'userId']);
+        ValidatorModel::stringType($aArgs, ['login']);
+
+        $nb = 0;
+        $countedNotes = [];
+        $entities = [];
+
+        $aEntities = DatabaseModel::select([
+            'select'    => ['entity_id'],
+            'table'     => ['users_entities'],
+            'where'     => ['user_id = ?'],
+            'data'      => [$aArgs['login']]
+        ]);
+
+        foreach ($aEntities as $value) {
+            $entities[] = $value['entity_id'];
+        }
+
+        $aNotes = DatabaseModel::select([
+            'select'    => ['notes.id', 'user_id', 'item_id'],
+            'table'     => ['notes', 'note_entities'],
+            'left_join' => ['notes.id = note_entities.note_id'],
+            'where'     => ['identifier = ?'],
+            'data'      => [$aArgs['resId']]
+        ]);
+
+        foreach ($aNotes as $value) {
+            if (empty($value['item_id']) && !in_array($value['id'], $countedNotes)) {
+                ++$nb;
+                $countedNotes[] = $value['id'];
+            } elseif (!empty($value['item_id'])) {
+                if ($value['user_id'] == $aArgs['userId'] && !in_array($value['id'], $countedNotes)) {
+                    ++$nb;
+                    $countedNotes[] = $value['id'];
+                } elseif (in_array($value['item_id'], $entities) && !in_array($value['id'], $countedNotes)) {
+                    ++$nb;
+                    $countedNotes[] = $value['id'];
+                }
+            }
+        }
+
+        return $nb;
+    }
+
     public static function getByUserIdForResource(array $aArgs)
     {
         ValidatorModel::notEmpty($aArgs, ['userId', 'resId', 'select']);
@@ -197,7 +226,7 @@ class NoteModel
         foreach ($allNotes as $note) {
             $allowed = false;
 
-            if ($note['user_id'] == $user['user_id']) {
+            if ($note['user_id'] == $aArgs['userId']) {
                 $allowed = true;
             }
 
diff --git a/src/app/resource/controllers/ResController.php b/src/app/resource/controllers/ResController.php
index 7339d35e9aa..81da74b3316 100755
--- a/src/app/resource/controllers/ResController.php
+++ b/src/app/resource/controllers/ResController.php
@@ -584,7 +584,7 @@ class ResController
 
     public function getNotesCountForCurrentUserById(Request $request, Response $response, array $aArgs)
     {
-        return $response->withJson(NoteModel::countByResId(['resId' => $aArgs['resId'], 'login' => $GLOBALS['userId']]));
+        return $response->withJson(NoteModel::countByResId(['resId' => $aArgs['resId'], 'userId' => $GLOBALS['id'], 'login' => $GLOBALS['userId']]));
     }
 
     public static function getEncodedDocument(array $aArgs)
diff --git a/src/app/resource/controllers/ResourceListController.php b/src/app/resource/controllers/ResourceListController.php
index b80d62031b4..1a7aae99d3b 100644
--- a/src/app/resource/controllers/ResourceListController.php
+++ b/src/app/resource/controllers/ResourceListController.php
@@ -859,7 +859,7 @@ class ResourceListController
                     break;
                 }
             }
-            $formattedResources[$key]['countNotes'] = NoteModel::countByResId(['resId' => $resource['res_id'], 'login' => $currentUser['user_id']]);
+            $formattedResources[$key]['countNotes'] = NoteModel::countByResId(['resId' => $resource['res_id'], 'login' => $currentUser['user_id'], 'userId' => $args['userId']]);
 
             if (!empty($args['checkLocked'])) {
                 $isLocked = true;
diff --git a/src/app/resource/controllers/SummarySheetController.php b/src/app/resource/controllers/SummarySheetController.php
index 55b5e17f8c2..1c70920fd61 100755
--- a/src/app/resource/controllers/SummarySheetController.php
+++ b/src/app/resource/controllers/SummarySheetController.php
@@ -518,12 +518,13 @@ class SummarySheetController
             } elseif ($unit['unit'] == 'notes') {
                 $notes = [];
                 $found = false;
+                $user = UserModel::getByLogin(['select' => ['id'], 'login' => $args['login']]);
                 foreach ($args['data']['notes'] as $noteKey => $rawNote) {
                     if ($found && $rawNote['identifier'] != $resource['res_id']) {
                         break;
                     } elseif ($rawNote['identifier'] == $resource['res_id']) {
                         $allowed = false;
-                        if ($rawNote['user_id'] == $args['login']) {
+                        if ($rawNote['user_id'] == $user['id']) {
                             $allowed = true;
                         } else {
                             $noteEntities = NoteEntityModel::get(['select' => ['item_id'], 'where' => ['note_id = ?'], 'data' => [$rawNote['id']]]);
@@ -540,7 +541,7 @@ class SummarySheetController
                         }
                         if ($allowed) {
                             $notes[] = [
-                                'user'  => UserModel::getLabelledUserById(['login' => $rawNote['user_id']]),
+                                'user'  => UserModel::getLabelledUserById(['id' => $rawNote['user_id']]),
                                 'date'  => TextFormatModel::formatDate($rawNote['creation_date']),
                                 'note'  => $rawNote['note_text']
                             ];
diff --git a/src/app/signatureBook/controllers/SignatureBookController.php b/src/app/signatureBook/controllers/SignatureBookController.php
index b6db0b5b874..8c7ae3ed7cd 100755
--- a/src/app/signatureBook/controllers/SignatureBookController.php
+++ b/src/app/signatureBook/controllers/SignatureBookController.php
@@ -105,7 +105,7 @@ class SignatureBookController
         $datas['documents']             = $documents;
         $datas['currentAction']         = $currentAction;
         $datas['resList']               = $resources;
-        $datas['nbNotes']               = NoteModel::countByResId(['resId' => $resId, 'login' => $GLOBALS['userId']]);
+        $datas['nbNotes']               = NoteModel::countByResId(['resId' => $resId, 'userId' => $GLOBALS['id'], 'login' => $GLOBALS['userId']]);
         $datas['nbLinks']               = count(LinkModel::getByResId(['resId' => $resId]));
         $datas['signatures']            = UserSignatureModel::getByUserSerialId(['userSerialid' => $currentUser['id']]);
         $datas['consigne']              = UserModel::getCurrentConsigneById(['resId' => $resId]);
diff --git a/src/app/tag/controllers/TagController.php b/src/app/tag/controllers/TagController.php
index 90c35a1a1af..8bf33b01ad9 100644
--- a/src/app/tag/controllers/TagController.php
+++ b/src/app/tag/controllers/TagController.php
@@ -22,6 +22,31 @@ use Tag\models\TagModel;
 
 class TagController
 {
+    public function get(Request $request, Response $response)
+    {
+        if (!ServiceModel::hasService(['id' => 'admin_tag', 'userId' => $GLOBALS['userId'], 'location' => 'tags', 'type' => 'admin'])) {
+            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
+        }
+
+        $tags = TagModel::get();
+
+        return $response->withJson(['tags' => $tags]);
+    }
+
+    public function getById(Request $request, Response $response, array $args)
+    {
+        if (!ServiceModel::hasService(['id' => 'admin_tag', 'userId' => $GLOBALS['userId'], 'location' => 'tags', 'type' => 'admin'])) {
+            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
+        }
+
+        $tag = TagModel::getById(['id' => $args['id']]);
+        if (empty($tag)) {
+            return $response->withStatus(404)->withJson(['errors' => 'id not found']);
+        }
+
+        return $response->withJson($tag);
+    }
+
     public function create(Request $request, Response $response)
     {
         if (!ServiceModel::hasService(['id' => 'admin_tag', 'userId' => $GLOBALS['userId'], 'location' => 'tags', 'type' => 'admin'])) {
@@ -49,86 +74,61 @@ class TagController
         return $response->withJson(['id' => $id]);
     }
 
-    public function delete(Request $request, Response $response, array $args)
+    public function update(Request $request, Response $response, array $args)
     {
         if (!ServiceModel::hasService(['id' => 'admin_tag', 'userId' => $GLOBALS['userId'], 'location' => 'tags', 'type' => 'admin'])) {
             return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
         }
 
-        $tag = TagModel::getById(['select' => ['label'], 'id' => $args['id']]);
-        if (empty($tag)) {
-            return $response->withStatus(400)->withJson(['errors' => 'Tag does not exist']);
+        $body = $request->getParsedBody();
+
+        if (!Validator::stringType()->notEmpty()->validate($body['label'])) {
+            return $response->withStatus(400)->withJson(['errors' => 'Body label is empty or not a string']);
         }
 
-        TagModel::delete([
+        TagModel::update([
+            'set' => [
+                'label' => $body['label']
+            ],
             'where' => ['id = ?'],
-            'data'  => [$args['id']]
+            'data' => [$args['id']]
         ]);
 
         HistoryController::add([
             'tableName' => 'tags',
             'recordId'  => $args['id'],
-            'eventType' => 'DEL',
-            'info'      =>  _TAG_DELETED . " : {$tag['label']}",
-            'eventId'   => 'tagSuppression',
+            'eventType' => 'UP',
+            'info'      =>  _TAG_UPDATED . " : {$body['label']}",
+            'eventId'   => 'tagModification',
         ]);
 
-        return $response->withStatus(201);
+        return $response->withStatus(204);
     }
 
-    public function getById(Request $request, Response $response, array $args)
+    public function delete(Request $request, Response $response, array $args)
     {
         if (!ServiceModel::hasService(['id' => 'admin_tag', 'userId' => $GLOBALS['userId'], 'location' => 'tags', 'type' => 'admin'])) {
             return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
         }
 
-        $tag = TagModel::getById(['id' => $args['id']]);
+        $tag = TagModel::getById(['select' => ['label'], 'id' => $args['id']]);
         if (empty($tag)) {
-            return $response->withStatus(404)->withJson(['errors' => 'id not found']);
-        }
-
-        return $response->withJson($tag);
-    }
-
-    public function get(Request $request, Response $response)
-    {
-        if (!ServiceModel::hasService(['id' => 'admin_tag', 'userId' => $GLOBALS['userId'], 'location' => 'tags', 'type' => 'admin'])) {
-            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
-        }
-
-        $tags = TagModel::get();
-
-        return $response->withJson(["tags" => $tags]);
-    }
-
-    public function update(Request $request, Response $response, array $args)
-    {
-        if (!ServiceModel::hasService(['id' => 'admin_tag', 'userId' => $GLOBALS['userId'], 'location' => 'tags', 'type' => 'admin'])) {
-            return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']);
-        }
-
-        $body = $request->getParsedBody();
-
-        if (!Validator::stringType()->notEmpty()->validate($body['label'])) {
-            return $response->withStatus(400)->withJson(['errors' => 'Body label is empty or not a string']);
+            return $response->withStatus(400)->withJson(['errors' => 'Tag does not exist']);
         }
 
-        TagModel::update([
-            'set' => [
-                'label' => $body['label']
-            ],
+        TagModel::delete([
             'where' => ['id = ?'],
-            'data' => [$args['id']]
+            'data'  => [$args['id']]
         ]);
 
         HistoryController::add([
             'tableName' => 'tags',
             'recordId'  => $args['id'],
-            'eventType' => 'UP',
-            'info'      =>  _TAG_UPDATED . " : {$body['label']}",
-            'eventId'   => 'tagModification',
+            'eventType' => 'DEL',
+            'info'      =>  _TAG_DELETED . " : {$tag['label']}",
+            'eventId'   => 'tagSuppression',
         ]);
 
-        return $response->withStatus(200);
+        return $response->withStatus(204);
     }
 }
diff --git a/src/app/template/models/TemplateModelAbstract.php b/src/app/template/models/TemplateModelAbstract.php
index cb85e526ce5..abdb9122607 100755
--- a/src/app/template/models/TemplateModelAbstract.php
+++ b/src/app/template/models/TemplateModelAbstract.php
@@ -113,30 +113,30 @@ abstract class TemplateModelAbstract
         return $nextSequenceId;
     }
 
-    public static function update(array $aArgs)
+    public static function update(array $args)
     {
-        ValidatorModel::notEmpty($aArgs, ['set', 'where', 'data']);
-        ValidatorModel::arrayType($aArgs, ['set', 'where', 'data']);
+        ValidatorModel::notEmpty($args, ['set', 'where', 'data']);
+        ValidatorModel::arrayType($args, ['set', 'where', 'data']);
 
         DatabaseModel::update([
             'table' => 'templates',
-            'set'   => $aArgs['set'],
-            'where' => $aArgs['where'],
-            'data'  => $aArgs['data']
+            'set'   => $args['set'],
+            'where' => $args['where'],
+            'data'  => $args['data']
         ]);
 
         return true;
     }
 
-    public static function delete(array $aArgs)
+    public static function delete(array $args)
     {
-        ValidatorModel::notEmpty($aArgs, ['where', 'data']);
-        ValidatorModel::arrayType($aArgs, ['where', 'data']);
+        ValidatorModel::notEmpty($args, ['where', 'data']);
+        ValidatorModel::arrayType($args, ['where', 'data']);
 
         DatabaseModel::delete([
             'table' => 'templates',
-            'where' => $aArgs['where'],
-            'data'  => $aArgs['data']
+            'where' => $args['where'],
+            'data'  => $args['data']
         ]);
 
         return true;
diff --git a/src/core/lang/lang-en.php b/src/core/lang/lang-en.php
index 95b20331068..bb48b1bf8b6 100755
--- a/src/core/lang/lang-en.php
+++ b/src/core/lang/lang-en.php
@@ -142,6 +142,8 @@ define('_AR_DISPLAYING', 'Displaying acknowledgement receipt');
 define('_DOC_ADDED', 'Document added');
 define('_ATTACH_DISPLAYING', 'Displaying attachment');
 define('_NOTE_ADDED', 'Note added');
+define('_NOTE_UPDATED', 'Note updated');
+define('_NOTE_DELETED', 'Note deleted');
 define('_TAG_ADDED', 'Tag added');
 define('_TAG_DELETED', 'Tag deleted');
 define('_TAG_UPDATED', 'Tag updated');
diff --git a/src/core/lang/lang-fr.php b/src/core/lang/lang-fr.php
index 7c3e3756bfb..ee7f754493a 100755
--- a/src/core/lang/lang-fr.php
+++ b/src/core/lang/lang-fr.php
@@ -142,6 +142,8 @@ define('_AR_DISPLAYING', 'Visualisation de l\'accusé de réception');
 define('_DOC_ADDED', 'Document ajouté');
 define('_ATTACH_DISPLAYING', 'Visualisation de la pièce jointe');
 define('_NOTE_ADDED', 'Annotation ajoutée');
+define('_NOTE_UPDATED', 'Annotation modifiée');
+define('_NOTE_DELETED', 'Annotation supprimée');
 define('_TAG_ADDED', 'Mot-clé ajouté');
 define('_TAG_DELETED', 'Mot-clé supprimé');
 define('_TAG_UPDATED', 'Mot-clé modifié');
diff --git a/src/core/lang/lang-nl.php b/src/core/lang/lang-nl.php
index f749f7a1237..6e8e2683759 100755
--- a/src/core/lang/lang-nl.php
+++ b/src/core/lang/lang-nl.php
@@ -141,6 +141,8 @@ define('_DOC_DISPLAYING', 'Weergave van het document');
 define('_DOC_ADDED', 'Document toegevoegd');
 define('_ATTACH_DISPLAYING', 'Weergave van de bijlage');
 define('_NOTE_ADDED', 'note added _TO_TRANSLATE');
+define('_NOTE_UPDATED', 'Note updated');//TRANSLATE
+define('_NOTE_DELETED', 'Note deleted');//TRANSLATE
 define('_TAG_ADDED', 'Tag added'); //TRANSLATE
 define('_TAG_DELETED', 'Tag deleted'); //TRANSLATE
 define('_TAG_UPDATED', 'Tag updated'); //TRANSLATE
-- 
GitLab