From c0ea8215dd8c8d7d64d8cb8afb29a03ccd8f3bed Mon Sep 17 00:00:00 2001
From: Alex ORLUC <alex.orluc@maarch.org>
Date: Wed, 12 Jul 2017 18:27:15 +0200
Subject: [PATCH] FEAT #5731 fix parameters V2 with validator + new select /
 create / delete / update + new notif method

---
 .../app/parameter-administration.component.js | 65 +++++------------
 .../app/parameter-administration.component.ts | 60 +++++-----------
 .../parameters-administration.component.js    | 25 ++-----
 .../parameters-administration.component.ts    | 39 ++++-------
 core/Controllers/ParametersController.php     | 52 ++++++++------
 core/Models/ParametersModel.php               | 19 +++--
 core/Models/ParametersModelAbstract.php       | 70 ++++++++++---------
 core/Models/TextFormatModelAbstract.php       | 20 ++++++
 8 files changed, 157 insertions(+), 193 deletions(-)

diff --git a/apps/maarch_entreprise/js/angular/app/parameter-administration.component.js b/apps/maarch_entreprise/js/angular/app/parameter-administration.component.js
index d8cd4361619..ee34a248860 100644
--- a/apps/maarch_entreprise/js/angular/app/parameter-administration.component.js
+++ b/apps/maarch_entreprise/js/angular/app/parameter-administration.component.js
@@ -40,9 +40,6 @@ var ParameterAdministrationComponent = (function () {
                     _this.type = 'string';
                     _this.pageTitle = _this.lang.newParameter;
                     _this.loading = false;
-                    setTimeout(function () {
-                        //$j("select").chosen({width:"100%",disable_search_threshold: 10, search_contains: true}); 
-                    }, 0);
                 }, function () {
                     location.href = "index.php";
                 });
@@ -56,9 +53,6 @@ var ParameterAdministrationComponent = (function () {
                     _this.lang = data.lang;
                     _this.type = data.type;
                     _this.loading = false;
-                    setTimeout(function () {
-                        //$j("select").chosen({width:"100%",disable_search_threshold: 10, search_contains: true});   
-                    }, 0);
                 }, function () {
                     location.href = "index.php";
                 });
@@ -74,6 +68,7 @@ var ParameterAdministrationComponent = (function () {
         }
     };
     ParameterAdministrationComponent.prototype.onSubmit = function () {
+        var _this = this;
         if (this.type == 'date') {
             this.parameter.param_value_date = $j("#paramValue").val();
             this.parameter.param_value_int = null;
@@ -87,50 +82,26 @@ var ParameterAdministrationComponent = (function () {
             this.parameter.param_value_date = null;
             this.parameter.param_value_int = null;
         }
-        /*if(this.mode == 'create'){
+        if (this.creationMode == true) {
             this.http.post(this.coreUrl + 'rest/parameters', this.parameter)
-            .map(res => res.json())
-            .subscribe((data) => {
-                if(data.errors) {
-                    this.resultInfo = data.errors;
-                    $j('#resultInfo').removeClass().addClass('alert alert-danger alert-dismissible');
-                    $j("#resultInfo").fadeTo(3000, 500).slideUp(500, function(){
-                        $j("#resultInfo").slideUp(500);
-                    });
-                    this.parameter.param_value_date=null;
-                    this.parameter.param_value_int=null;
-                    this.parameter.param_value_string=null;
-                } else {
-                    this.resultInfo = this.lang.paramCreatedSuccess;
-                    $j('#resultInfo').removeClass().addClass('alert alert-success alert-dismissible');
-                    $j("#resultInfo").fadeTo(3000, 500).slideUp(500, function(){
-                        $j("#resultInfo").slideUp(500);
-                    });
-                    this.router.navigate(['administration/parameters']);
-                }
-                
+                .map(function (res) { return res.json(); })
+                .subscribe(function (data) {
+                _this.router.navigate(['administration/parameters']);
+                successNotification(data.success);
+            }, function (err) {
+                errorNotification(JSON.parse(err._body).errors);
             });
-        } else if(this.mode == "update"){
-
-            this.http.put(this.coreUrl+'rest/parameters/'+this.paramId,this.parameter)
-            .map(res => res.json())
-            .subscribe((data) => {
-                if(data.errors){
-                    this.resultInfo = data.errors;
-                    $j('#resultInfo').removeClass().addClass('alert alert-danger alert-dismissible');
-                    $j("#resultInfo").fadeTo(3000, 500).slideUp(500, function(){
-                        $j("#resultInfo").slideUp(500);
-                    });
-                } else {
-                    this.resultInfo = this.lang.paramUpdatedSuccess;
-                    $j('#resultInfo').removeClass().addClass('alert alert-success alert-dismissible');
-                    $j("#resultInfo").fadeTo(3000, 500).slideUp(500, function(){
-                        $j("#resultInfo").slideUp(500);
-                    });
-                    this.router.navigate(['administration/parameters']);
-                }
+        }
+        else if (this.creationMode == false) {
+            this.http.put(this.coreUrl + 'rest/parameters/' + this.parameter.id, this.parameter)
+                .map(function (res) { return res.json(); })
+                .subscribe(function (data) {
+                _this.router.navigate(['administration/parameters']);
+                successNotification(data.success);
+            }, function (err) {
+                errorNotification(JSON.parse(err._body).errors);
             });
-        }*/
+        }
     };
     return ParameterAdministrationComponent;
 }());
diff --git a/apps/maarch_entreprise/js/angular/app/parameter-administration.component.ts b/apps/maarch_entreprise/js/angular/app/parameter-administration.component.ts
index bb163c2fac1..13378033d08 100644
--- a/apps/maarch_entreprise/js/angular/app/parameter-administration.component.ts
+++ b/apps/maarch_entreprise/js/angular/app/parameter-administration.component.ts
@@ -4,8 +4,11 @@ import 'rxjs/add/operator/map';
 import { Router, ActivatedRoute } from '@angular/router';
 
 declare function $j(selector: any) : any;
+declare function successNotification(message: string) : void;
+declare function errorNotification(message: string) : void;
 
 declare var angularGlobals : any;
+
 @Component({
     templateUrl : angularGlobals['parameter-administrationView'],
     styleUrls   : ['../../node_modules/bootstrap/dist/css/bootstrap.min.css']
@@ -43,9 +46,7 @@ export class ParameterAdministrationComponent implements OnInit {
                         this.pageTitle = this.lang.newParameter;
 
                         this.loading = false;
-                        setTimeout(() => {
-                            //$j("select").chosen({width:"100%",disable_search_threshold: 10, search_contains: true}); 
-                        }, 0);
+
                 }, () => {
                     location.href = "index.php";
                 });
@@ -59,9 +60,6 @@ export class ParameterAdministrationComponent implements OnInit {
                         this.type = data.type;
 
                         this.loading = false;
-                        setTimeout(() => {
-                            //$j("select").chosen({width:"100%",disable_search_threshold: 10, search_contains: true});   
-                        }, 0);
 
                     }, () => {
                         location.href = "index.php";
@@ -81,7 +79,6 @@ export class ParameterAdministrationComponent implements OnInit {
         }
     }
 
-    
     onSubmit() {
         if(this.type=='date'){
             this.parameter.param_value_date = $j("#paramValue").val();
@@ -97,49 +94,26 @@ export class ParameterAdministrationComponent implements OnInit {
             this.parameter.param_value_int=null;
         }
 
-        /*if(this.mode == 'create'){
+        if(this.creationMode == true){
             this.http.post(this.coreUrl + 'rest/parameters', this.parameter)
             .map(res => res.json())
-            .subscribe((data) => {
-                if(data.errors) {
-                    this.resultInfo = data.errors;
-                    $j('#resultInfo').removeClass().addClass('alert alert-danger alert-dismissible');
-                    $j("#resultInfo").fadeTo(3000, 500).slideUp(500, function(){
-                        $j("#resultInfo").slideUp(500);
-                    });
-                    this.parameter.param_value_date=null;
-                    this.parameter.param_value_int=null;
-                    this.parameter.param_value_string=null;
-                } else {
-                    this.resultInfo = this.lang.paramCreatedSuccess;
-                    $j('#resultInfo').removeClass().addClass('alert alert-success alert-dismissible');
-                    $j("#resultInfo").fadeTo(3000, 500).slideUp(500, function(){
-                        $j("#resultInfo").slideUp(500);
-                    });
-                    this.router.navigate(['administration/parameters']);
-                }
+            .subscribe((data) => {                
+                this.router.navigate(['administration/parameters']);
+                successNotification(data.success);
                 
+            },(err) => {
+                errorNotification(JSON.parse(err._body).errors);
             });
-        } else if(this.mode == "update"){
+        } else if(this.creationMode == false){
 
-            this.http.put(this.coreUrl+'rest/parameters/'+this.paramId,this.parameter)
+            this.http.put(this.coreUrl+'rest/parameters/'+this.parameter.id,this.parameter)
             .map(res => res.json())             
             .subscribe((data) => {
-                if(data.errors){
-                    this.resultInfo = data.errors;
-                    $j('#resultInfo').removeClass().addClass('alert alert-danger alert-dismissible');
-                    $j("#resultInfo").fadeTo(3000, 500).slideUp(500, function(){
-                        $j("#resultInfo").slideUp(500);
-                    });
-                } else {
-                    this.resultInfo = this.lang.paramUpdatedSuccess;
-                    $j('#resultInfo').removeClass().addClass('alert alert-success alert-dismissible');
-                    $j("#resultInfo").fadeTo(3000, 500).slideUp(500, function(){
-                        $j("#resultInfo").slideUp(500);
-                    });
-                    this.router.navigate(['administration/parameters']);                    
-                }
+                this.router.navigate(['administration/parameters']);
+                successNotification(data.success);                         
+            },(err) => {
+                errorNotification(JSON.parse(err._body).errors);
             });
-        }*/
+        }
     }
 }
diff --git a/apps/maarch_entreprise/js/angular/app/parameters-administration.component.js b/apps/maarch_entreprise/js/angular/app/parameters-administration.component.js
index e4cc0d6f436..858cb307247 100644
--- a/apps/maarch_entreprise/js/angular/app/parameters-administration.component.js
+++ b/apps/maarch_entreprise/js/angular/app/parameters-administration.component.js
@@ -89,26 +89,15 @@ var ParametersAdministrationComponent = (function () {
             this.http.delete(this.coreUrl + 'rest/parameters/' + paramId)
                 .map(function (res) { return res.json(); })
                 .subscribe(function (data) {
-                if (data.errors) {
-                    _this.resultInfo = data.errors;
-                    $j('#resultInfo').removeClass().addClass('alert alert-danger alert-dismissible');
-                    $j("#resultInfo").fadeTo(3000, 500).slideUp(500, function () {
-                        $j("#resultInfo").slideUp(500);
-                    });
-                }
-                else {
-                    for (var i = 0; i < _this.parametersList.length; i++) {
-                        if (_this.parametersList[i].id == paramId) {
-                            _this.parametersList.splice(i, 1);
-                        }
+                for (var i = 0; i < _this.parametersList.length; i++) {
+                    if (_this.parametersList[i].id == paramId) {
+                        _this.parametersList.splice(i, 1);
                     }
-                    _this.table.row($j("#" + paramId)).remove().draw();
-                    _this.resultInfo = "Paramètre supprimé avec succès";
-                    $j('#resultInfo').removeClass().addClass('alert alert-success alert-dismissible');
-                    $j("#resultInfo").fadeTo(3000, 500).slideUp(500, function () {
-                        $j("#resultInfo").slideUp(500);
-                    });
                 }
+                _this.table.row($j("#" + paramId)).remove().draw();
+                successNotification(data.success);
+            }, function (err) {
+                errorNotification(JSON.parse(err._body).errors);
             });
         }
     };
diff --git a/apps/maarch_entreprise/js/angular/app/parameters-administration.component.ts b/apps/maarch_entreprise/js/angular/app/parameters-administration.component.ts
index 228963cfeca..eb1df9f1ddc 100644
--- a/apps/maarch_entreprise/js/angular/app/parameters-administration.component.ts
+++ b/apps/maarch_entreprise/js/angular/app/parameters-administration.component.ts
@@ -3,6 +3,8 @@ import { Http } from '@angular/http';
 import 'rxjs/add/operator/map';
 
 declare function $j(selector: any) : any;
+declare function successNotification(message: string) : void;
+declare function errorNotification(message: string) : void;
 
 declare var angularGlobals : any;
 
@@ -97,31 +99,20 @@ export class ParametersAdministrationComponent implements OnInit {
 
     deleteParameter(paramId : string){
         var resp =confirm(this.lang.deleteConfirm+' '+paramId+'?');
-        if(resp){
-                this.http.delete(this.coreUrl + 'rest/parameters/'+paramId)
-                    .map(res => res.json())
-                    .subscribe((data) => {
-                        if(data.errors){
-                            this.resultInfo = data.errors;
-                                $j('#resultInfo').removeClass().addClass('alert alert-danger alert-dismissible');
-                                $j("#resultInfo").fadeTo(3000, 500).slideUp(500, function(){
-                                    $j("#resultInfo").slideUp(500);
-                                });
-                        } else{
-                            for(var i = 0; i<this.parametersList.length;i++){
-                                if(this.parametersList[i].id==paramId){
-                                    this.parametersList.splice(i,1);
-                                }
-                            }
-                            this.table.row($j("#"+paramId)).remove().draw();
-                            this.resultInfo = "Paramètre supprimé avec succès";
-                        
-                            $j('#resultInfo').removeClass().addClass('alert alert-success alert-dismissible');
-                                $j("#resultInfo").fadeTo(3000, 500).slideUp(500, function(){
-                                    $j("#resultInfo").slideUp(500);
-                                });
+        if (resp) {
+            this.http.delete(this.coreUrl + 'rest/parameters/'+paramId)
+                .map(res => res.json())
+                .subscribe((data) => {
+                    for(var i = 0; i<this.parametersList.length;i++){
+                        if(this.parametersList[i].id==paramId){
+                            this.parametersList.splice(i,1);
                         }
-                    });
+                    }
+                    this.table.row($j("#"+paramId)).remove().draw();
+                    successNotification(data.success);               
+                },(err) => {
+                    errorNotification(JSON.parse(err._body).errors);
+                });
         }
     }
  
diff --git a/core/Controllers/ParametersController.php b/core/Controllers/ParametersController.php
index 56a7e49ffd9..d7e5c16bb2e 100644
--- a/core/Controllers/ParametersController.php
+++ b/core/Controllers/ParametersController.php
@@ -1,15 +1,11 @@
 <?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 Parameters Controller
-* @author dev@maarch.org
+* @brief   ParametersController
+* @author  dev <dev@maarch.org>
 * @ingroup core
 */
 
@@ -73,6 +69,7 @@ class ParametersController
 
         if (!empty($errors)) {
             return $response
+                ->withStatus(500)
                 ->withJson(['errors' => $errors]);
         }
         
@@ -81,16 +78,18 @@ class ParametersController
         $return = ParametersModel::create($datas);
 
         if ($return) {
-            $obj = ParametersModel::getById([
-                'id' => $datas['id']
-            ]);
+            $obj = ParametersModel::getById(['id' => $datas['id']]);
         } else {
             return $response
                 ->withStatus(500)
                 ->withJson(['errors' => _NOT_CREATE]);
         }
 
-        return $response->withJson($obj);
+        return $response->withJson(
+            [
+            'success'   =>  _PARAMETER. ' <b>' . $obj['id'] .'</b> ' ._ADDED,
+            ]
+        );
     }
 
     public function update(RequestInterface $request, ResponseInterface $response, $aArgs)
@@ -99,6 +98,7 @@ class ParametersController
 
         if (!empty($errors)) {
             return $response
+                ->withStatus(500)
                 ->withJson(['errors' => $errors]);
         }
 
@@ -106,22 +106,28 @@ class ParametersController
         $return = ParametersModel::update($aArgs);
 
         if ($return) {
-            $obj = ParametersModel::getById([
-                'id' => $aArgs['id']
-            ]);
+            $obj = ParametersModel::getById(['id' => $aArgs['id']]);
         } else {
             return $response
                 ->withStatus(500)
                 ->withJson(['errors' => _NOT_UPDATE]);
         }
 
-        return $response->withJson($obj);
+        return $response->withJson(
+            [
+            'success'   =>  _PARAMETER. ' <b>' . $aArgs['id'] .'</b> ' ._UPDATED,
+            ]
+        );
     }
 
     public function delete(RequestInterface $request, ResponseInterface $response, $aArgs)
     {
         $obj = ParametersModel::delete(['id' => $aArgs['id']]);
-        return $response->withJson($obj);
+        return $response->withJson(
+            [
+            'success'   =>  _PARAMETER. ' <b>' . $aArgs['id'] .'</b> ' ._DELETED,
+            ]
+        );
     }
 
     protected function control($request, $mode)
@@ -129,10 +135,12 @@ class ParametersController
         $errors = [];
 
         if ($mode == 'update') {
-            $obj = ParametersModel::getById([
+            $obj = ParametersModel::getById(
+                [
                 'id' => $request->getParam('id'),
                 'param_value_int' => $request->getParam('param_value_int')
-            ]);
+                ]
+            );
             if (empty($obj)) {
                 array_push($errors, _ID . ' '. _NOT_EXISTS);
             }
@@ -152,9 +160,7 @@ class ParametersController
             if (!Validator::regex('/^[0-9]*$/')->validate($request->getParam('param_value_int')) && $request->getParam('param_value_int')!=null) {
                 array_push($errors, _INVALID_INTEGER);
             }
-            $obj = ParametersModel::getById([
-                'id' => $request->getParam('id')
-            ]);
+            $obj = ParametersModel::getById(['id' => $request->getParam('id')]);
             if (!empty($obj)) {
                 array_push($errors, _ID . ' ' . $obj[0]['id'] . ' ' . _ALREADY_EXISTS);
             }
@@ -164,9 +170,9 @@ class ParametersController
                 array_push($errors, _INVALID_PARAM_DATE);
             }
         }
-        if (!Validator::notEmpty()->validate($request->getParam('param_value_int'))&&
-        !Validator::notEmpty()->validate($request->getParam('param_value_string'))&&
-        !Validator::notEmpty()->validate($request->getParam('param_value_date'))
+        if (!Validator::notEmpty()->validate($request->getParam('param_value_int'))
+            && !Validator::notEmpty()->validate($request->getParam('param_value_string'))
+            && !Validator::notEmpty()->validate($request->getParam('param_value_date'))
         ) {
             array_push($errors, _PARAM_VALUE_IS_EMPTY);
         }
diff --git a/core/Models/ParametersModel.php b/core/Models/ParametersModel.php
index 098bd2ea0cd..119c4f0e3e3 100644
--- a/core/Models/ParametersModel.php
+++ b/core/Models/ParametersModel.php
@@ -1,12 +1,19 @@
 <?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.
 
-    namespace Core\Models;
+* @brief   ParametersModel
+* @author  dev <dev@maarch.org>
+* @ingroup core
+*/
 
-    use Core\Models\ParametersModelAbstract;
+namespace Core\Models;
 
-    class ParametersModel extends ParametersModelAbstract
-    {
+use Core\Models\ParametersModelAbstract;
 
-    }
+class ParametersModel extends ParametersModelAbstract
+{
 
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/core/Models/ParametersModelAbstract.php b/core/Models/ParametersModelAbstract.php
index 33171485089..a7d7d3af068 100644
--- a/core/Models/ParametersModelAbstract.php
+++ b/core/Models/ParametersModelAbstract.php
@@ -11,15 +11,13 @@
 
 namespace Core\Models;
 
-require_once 'core/class/class_functions.php';
-
-class ParametersModelAbstract extends \Apps_Table_Service
+class ParametersModelAbstract
 {
     public static function getList()
     {
         $func = new \functions();
 
-        $aReturn = static::select(
+        $aReturn = DatabaseModel::select(
             ['select'    => empty($aArgs['select']) ? ['*'] : $aArgs['select'],
             'table'     => ['parameters']]
         );
@@ -42,45 +40,51 @@ class ParametersModelAbstract extends \Apps_Table_Service
 
     public static function getById(array $aArgs = [])
     {
-        $func = new \functions();
-        static::checkRequired($aArgs, ['id']);
-        static::checkString($aArgs, ['id']);
+        ValidatorModel::notEmpty($aArgs, ['id']);
+        ValidatorModel::stringType($aArgs, ['id']);
 
-        $aReturn = static::select([
+        $aReturn = DatabaseModel::select(
+            [
             'select'    => empty($aArgs['select']) ? ['*'] : $aArgs['select'],
             'table'     =>['parameters'],
             'where'     => ['id = ?'],
             'data'      => [$aArgs['id']]
-        ]);
-        if ($aReturn[0]['param_value_date']!=null) {
-            $aReturn[0]['param_value_date']=$func->format_date($aReturn[0]['param_value_date']);
+            ]
+        );
+        if ($aReturn[0]['param_value_date'] != null) {
+            $aReturn[0]['param_value_date'] = TextFormatModel::format_date($aReturn[0]['param_value_date']);
         }
         
         return $aReturn[0];
-
     }
 
     public static function create(array $aArgs = [])
     {
-        static::checkRequired($aArgs, ['id']);
-        static::checkString($aArgs, ['id']);
-
-        $aReturn = static::insertInto($aArgs, 'parameters');
+        ValidatorModel::notEmpty($aArgs, ['id']);
+        ValidatorModel::stringType($aArgs, ['id']);
+
+        $aReturn = DatabaseModel::insert(
+            [
+            'table'         => 'parameters',
+            'columnsValues' => $aArgs
+            ]
+        );
 
         return $aReturn;
     }
 
     public static function update(array $aArgs = [])
     {
-        static::checkRequired($aArgs, ['id']);
-        static::checkString($aArgs, ['id']);
-
-        $where['id'] = $aArgs['id'];
+        ValidatorModel::notEmpty($aArgs, ['id']);
+        ValidatorModel::stringType($aArgs, ['id']);
 
-        $aReturn = static::updateTable(
-            $aArgs,
-            'parameters',
-            $where
+        $aReturn = DatabaseModel::update(
+            [
+            'table'     => 'parameters',
+            'set'       => $aArgs,
+            'where'     => ['id = ?'],
+            'data'      => [$aArgs['id']]
+            ]
         );
 
         return $aReturn;
@@ -88,14 +92,16 @@ class ParametersModelAbstract extends \Apps_Table_Service
 
     public static function delete(array $aArgs = [])
     {
-        static::checkRequired($aArgs, ['id']);
-        static::checkString($aArgs, ['id']);
-
-        $aReturn = static::deleteFrom([
-                'table' => 'parameters',
-                'where' => ['id = ?'],
-                'data'  => [$aArgs['id']]
-            ]);
+        ValidatorModel::notEmpty($aArgs, ['id']);
+        ValidatorModel::stringType($aArgs, ['id']);
+
+        $aReturn = DatabaseModel::delete(
+            [
+            'table' => 'parameters',
+            'where' => ['id = ?'],
+            'data'  => [$aArgs['id']]
+            ]
+        );
 
         return $aReturn;
     }
diff --git a/core/Models/TextFormatModelAbstract.php b/core/Models/TextFormatModelAbstract.php
index 26aa2cf8a1c..d1c313e4b53 100644
--- a/core/Models/TextFormatModelAbstract.php
+++ b/core/Models/TextFormatModelAbstract.php
@@ -31,4 +31,24 @@ class TextFormatModelAbstract
 
         return utf8_encode($string);
     }
+
+    public function format_date($date)
+    {
+        $last_date = '';
+        if($date <> "")
+        {
+            if(strpos($date," "))
+            {
+                $date_ex = explode(" ",$date);
+                $the_date = explode("-",$date_ex[0]);
+                $last_date = $the_date[2]."-".$the_date[1]."-".$the_date[0];
+            }
+            else
+            {
+                $the_date = explode("-",$date);
+                $last_date = $the_date[2]."-".$the_date[1]."-".$the_date[0];
+            }
+        }
+        return $last_date;
+    }
 }
-- 
GitLab