From 812e9166397961d7712f7c6d1e004a3b3e116a6e Mon Sep 17 00:00:00 2001
From: Alex Orluc <alex.orluc@maarch.org>
Date: Wed, 21 Mar 2018 19:28:08 +0100
Subject: [PATCH] FEAT #152 add confirmation modal is role is used

---
 .../entities-administration.component.html    |  12 +-
 .../entities-administration.component.ts      | 105 +++++++++++++-----
 .../js/angular/app/app.module.ts              |   7 +-
 .../js/angular/app/confirmModal.component.ts  |  22 ++++
 .../js/angular/lang/lang-en.ts                |   3 +
 .../js/angular/lang/lang-fr.ts                |   3 +
 6 files changed, 116 insertions(+), 36 deletions(-)
 create mode 100644 apps/maarch_entreprise/js/angular/app/confirmModal.component.ts

diff --git a/apps/maarch_entreprise/Views/entities-administration.component.html b/apps/maarch_entreprise/Views/entities-administration.component.html
index ce288156312..213d4d318dc 100644
--- a/apps/maarch_entreprise/Views/entities-administration.component.html
+++ b/apps/maarch_entreprise/Views/entities-administration.component.html
@@ -10,7 +10,7 @@
     </mat-toolbar>
     <mat-sidenav-container class="admin-sidenav-container" [style.marginTop.px]="mobileQuery.matches ? 56 : 0">
         <mat-sidenav #snav [mode]="mobileQuery.matches ? 'over' : 'side'" [fixedInViewport]="mobileQuery.matches" fixedTopGap="56"
-            [opened]="mobileQuery.matches ? false : true">
+            [opened]="mobileQuery.matches ? false : true" style="width:300px;">
             <menu-nav></menu-nav>
             <mat-divider></mat-divider>
             <mat-nav-list>
@@ -24,13 +24,13 @@
             </mat-nav-list>
             <mat-divider></mat-divider>
             <mat-nav-list>
-                <h3 mat-subheader>Role(s) supplémentaire(s)</h3>
+                <h3 mat-subheader>{{lang.additionalRoles}}</h3>
                 <ng-container *ngFor="let role of listTemplateRoles">
                     <a mat-list-item disableRipple="true" *ngIf="role.id != 'dest' && role.id != 'cc'">
                         <mat-icon color="primary" mat-list-icon style="margin-bottom: 20px;">
-                            <mat-slide-toggle [(ngModel)]="role.available" [checked]="role.available" color="primary" [ngStyle]="{'opacity': role.available ? '' : '0.5'}" (change)="toggleRole(role)" [disabled]="role.id == 'dest'"></mat-slide-toggle>
+                            <mat-slide-toggle [checked]="role.available" color="primary" (click)="toggleRole(role);false"></mat-slide-toggle>
                         </mat-icon>
-                        <p mat-line>
+                        <p mat-line [ngStyle]="{'opacity': role.available ? '' : '0.5'}" (click)="toggleRole(role);false">
                             {{role.label}}
                         </p>
                     </a>
@@ -216,8 +216,8 @@
                                         </mat-option>
                                     </mat-autocomplete>
                                 </mat-form-field>
-                                <mat-list>
-                                    <span *ngFor="let role of currentEntity.roles; let i = index">
+                                <mat-list *ngIf="currentEntity.entity_id">
+                                    <span *ngFor="let role of listTemplateRoles; let i = index">
                                         <h3 *ngIf="role.available" mat-subheader style="font-weight:bold;" color="primary">{{role.label}}</h3>
                                         <span *ngIf="role.available" dnd-sortable-container [dropZones]="['boxers-zone']" [sortableData]="currentEntity.listTemplate[role.id]">
                                             <div style="min-height:30px;">
diff --git a/apps/maarch_entreprise/js/angular/app/administration/entities-administration.component.ts b/apps/maarch_entreprise/js/angular/app/administration/entities-administration.component.ts
index 06b49dc8c71..07af6a7bd36 100644
--- a/apps/maarch_entreprise/js/angular/app/administration/entities-administration.component.ts
+++ b/apps/maarch_entreprise/js/angular/app/administration/entities-administration.component.ts
@@ -2,6 +2,7 @@ import { ChangeDetectorRef, Component, OnInit, ViewChild, Inject } from '@angula
 import { MediaMatcher } from '@angular/cdk/layout';
 import { HttpClient } from '@angular/common/http';
 import { LANG } from '../translate.component';
+import { ConfirmModalComponent } from '../confirmModal.component';
 import { NotificationService } from '../notification.service';
 import { MatSidenav, MatPaginator, MatTableDataSource, MatSort, MatDialog, MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
 
@@ -19,25 +20,25 @@ declare var angularGlobals: any;
 })
 export class EntitiesAdministrationComponent extends AutoCompletePlugin implements OnInit {
 
-    private _mobileQueryListener    : () => void;
-    mobileQuery                     : MediaQueryList;
-    dialogRef                       : MatDialogRef<any>;
+    private _mobileQueryListener: () => void;
+    mobileQuery: MediaQueryList;
+    dialogRef: MatDialogRef<any>;
 
-    coreUrl                         : string;
-    lang                            : any       = LANG;
-    loading                         : boolean   = false;
+    coreUrl: string;
+    lang: any = LANG;
+    loading: boolean = false;
 
-    entities                        : any[]     = [];
-    listTemplateRoles               : any[]     = [];
-    entityTypeList                  : any[]     = [];
-    currentEntity                   : any       = {};
-    isDraggable                     : boolean   = true;
-    creationMode                    : boolean   = false;
-    idCircuitVisa                   : number;
-    config                          : any       = {};
+    entities: any[] = [];
+    listTemplateRoles: any[] = [];
+    entityTypeList: any[] = [];
+    currentEntity: any = {};
+    isDraggable: boolean = true;
+    creationMode: boolean = false;
+    idCircuitVisa: number;
+    config: any = {};
 
-    dataSource          = new MatTableDataSource(this.currentEntity.users);
-    displayedColumns    = ['firstname', 'lastname'];
+    dataSource = new MatTableDataSource(this.currentEntity.users);
+    displayedColumns = ['firstname', 'lastname'];
 
 
     @ViewChild('snav2') sidenav: MatSidenav;
@@ -192,7 +193,7 @@ export class EntitiesAdministrationComponent extends AutoCompletePlugin implemen
         var inListModel = false;
         var newElemListModel: any = {};
 
-        this.currentEntity.roles.forEach((role: any) => {
+        this.listTemplateRoles.forEach((role: any) => {
             if (role.available == true) {
                 if (this.currentEntity.listTemplate[role.id]) {
                     this.currentEntity.listTemplate[role.id].forEach((listModel: any) => {
@@ -476,7 +477,7 @@ export class EntitiesAdministrationComponent extends AutoCompletePlugin implemen
             this.currentEntity.listTemplate.dest = [template];
         }
 
-        this.currentEntity.roles.forEach((role: any) => {
+        this.listTemplateRoles.forEach((role: any) => {
             if (role.available == true) {
                 if (this.currentEntity.listTemplate[role.id]) {
                     this.currentEntity.listTemplate[role.id].forEach((listModel: any) => {
@@ -494,6 +495,12 @@ export class EntitiesAdministrationComponent extends AutoCompletePlugin implemen
             this.http.put(this.coreUrl + "rest/listTemplates/" + this.currentEntity.listTemplate.id, newDiffList)
                 .subscribe((data: any) => {
                     this.currentEntity.listTemplate.id = data.id;
+                    this.http.get(this.coreUrl + "rest/listTemplates/types/entity_id/roles")
+                        .subscribe((data: any) => {
+                            this.listTemplateRoles = data['roles'];
+                        }, (err) => {
+                            this.notify.error(err.error.errors);
+                        });
                     this.notify.success(this.lang.entityUpdated);
                 }, (err) => {
                     this.notify.error(err.error.errors);
@@ -502,6 +509,12 @@ export class EntitiesAdministrationComponent extends AutoCompletePlugin implemen
             this.http.post(this.coreUrl + "rest/listTemplates", newDiffList)
                 .subscribe((data: any) => {
                     this.currentEntity.listTemplate.id = data.id;
+                    this.http.get(this.coreUrl + "rest/listTemplates/types/entity_id/roles")
+                        .subscribe((data: any) => {
+                            this.listTemplateRoles = data['roles'];
+                        }, (err) => {
+                            this.notify.error(err.error.errors);
+                        });
                     this.notify.success(this.lang.entityUpdated);
                 }, (err) => {
                     this.notify.error(err.error.errors);
@@ -549,7 +562,7 @@ export class EntitiesAdministrationComponent extends AutoCompletePlugin implemen
             "description": this.currentEntity.entity_id,
             "items": Array()
         };
-        this.currentEntity.roles.forEach((role: any) => {
+        this.listTemplateRoles.forEach((role: any) => {
             if (role.available == true) {
                 if (this.currentEntity.listTemplate[role.id]) {
                     this.currentEntity.listTemplate[role.id].forEach((listModel: any) => {
@@ -566,6 +579,12 @@ export class EntitiesAdministrationComponent extends AutoCompletePlugin implemen
         this.http.put(this.coreUrl + "rest/listTemplates/" + this.currentEntity.listTemplate.id, newDiffList)
             .subscribe((data: any) => {
                 this.currentEntity.listTemplate.id = data.id;
+                this.http.get(this.coreUrl + "rest/listTemplates/types/entity_id/roles")
+                    .subscribe((data: any) => {
+                        this.listTemplateRoles = data['roles'];
+                    }, (err) => {
+                        this.notify.error(err.error.errors);
+                    });
                 this.notify.success(this.lang.entityUpdated);
             }, (err) => {
                 this.notify.error(err.error.errors);
@@ -616,16 +635,46 @@ export class EntitiesAdministrationComponent extends AutoCompletePlugin implemen
         }
     }
 
-    toggleRole(role:any) {
-        this.http.put(this.coreUrl + "rest/listTemplates/types/entity_id/roles", {"roles" : this.listTemplateRoles})
-            .subscribe(() => {
-                if (this.currentEntity.listTemplate) {
-                    this.currentEntity.listTemplate[role.id] = [];
+    toggleRole(role: any) {
+        console.log(role);
+        if (role.usedIn.length > 0) {
+            this.config = { data: { msg: this.lang.confirmAction, warn: this.lang.roleUsedInTemplateInfo + " : <b>" + role.usedIn.join(',') + '</b><br/>'+this.lang.roleUsedInTemplateInfo2 } };
+            let dialogRef = this.dialog.open(ConfirmModalComponent, this.config);
+            dialogRef.afterClosed().subscribe(result => {
+                if (result === "ok") {
+                    role.available = !role.available;
+                    this.http.put(this.coreUrl + "rest/listTemplates/types/entity_id/roles", { "roles": this.listTemplateRoles })
+                        .subscribe(() => {
+                            role.usedIn = [];
+                            if (this.currentEntity.listTemplate) {
+                                this.currentEntity.listTemplate[role.id] = [];
+                            }
+                            this.notify.success(this.lang.entityUpdated);
+                        }, (err) => {
+                            this.notify.error(err.error.errors);
+                        });
                 }
-                this.notify.success(this.lang.entityUpdated);
-            }, (err) => {
-                this.notify.error(err.error.errors);
             });
+        } else {
+            role.available = !role.available;
+            this.http.put(this.coreUrl + "rest/listTemplates/types/entity_id/roles", { "roles": this.listTemplateRoles })
+                .subscribe(() => {
+                    if (this.currentEntity.listTemplate) {
+                        this.currentEntity.listTemplate[role.id] = [];
+                        this.http.get(this.coreUrl + "rest/listTemplates/types/entity_id/roles")
+                            .subscribe((data: any) => {
+                                this.listTemplateRoles = data['roles'];
+                            }, (err) => {
+                                this.notify.error(err.error.errors);
+                            });
+                    }
+                    this.notify.success(this.lang.entityUpdated);
+                }, (err) => {
+                    this.notify.error(err.error.errors);
+                });
+        }
+
+
     }
 }
 @Component({
@@ -637,4 +686,4 @@ export class EntitiesAdministrationRedirectModalComponent extends AutoCompletePl
     constructor(public http: HttpClient, @Inject(MAT_DIALOG_DATA) public data: any, public dialogRef: MatDialogRef<EntitiesAdministrationRedirectModalComponent>) {
         super(http, ['entities']);
     }
-}
\ No newline at end of file
+}
diff --git a/apps/maarch_entreprise/js/angular/app/app.module.ts b/apps/maarch_entreprise/js/angular/app/app.module.ts
index 83de424bcf0..c4eaac18c78 100755
--- a/apps/maarch_entreprise/js/angular/app/app.module.ts
+++ b/apps/maarch_entreprise/js/angular/app/app.module.ts
@@ -6,6 +6,7 @@ import { HttpClientModule }                     from '@angular/common/http';
 import { AppMaterialModule }                    from './app-material.module';
 
 import { CustomSnackbarComponent }              from './notification.service';
+import { ConfirmModalComponent }                from './confirmModal.component';
 
 import { AppComponent }                         from './app.component';
 import { AppRoutingModule }                     from './app-routing.module';
@@ -31,10 +32,12 @@ import { SaveNumericPackageComponent }  from './save-numeric-package.component';
         SaveNumericPackageComponent,
         SignatureBookComponent,
         SafeUrlPipe,
-        CustomSnackbarComponent
+        CustomSnackbarComponent,
+        ConfirmModalComponent
     ],
     entryComponents: [
-        CustomSnackbarComponent
+        CustomSnackbarComponent,
+        ConfirmModalComponent
     ],
     bootstrap: [AppComponent]
 })
diff --git a/apps/maarch_entreprise/js/angular/app/confirmModal.component.ts b/apps/maarch_entreprise/js/angular/app/confirmModal.component.ts
new file mode 100644
index 00000000000..5e90535ba7a
--- /dev/null
+++ b/apps/maarch_entreprise/js/angular/app/confirmModal.component.ts
@@ -0,0 +1,22 @@
+import {Component, Inject} from '@angular/core';
+import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
+import { LANG } from './translate.component';
+
+
+@Component({
+    selector: 'dialog-result-example-dialog',
+    template: `<p mat-dialog-title>Confirmation</p>
+                <div class="alert alert-warning" role="alert" *ngIf="data.warn" [innerHTML]="data.warn">
+                </div>
+               <p mat-dialog-content class="text-center">{{data.msg}}</p>
+               <mat-dialog-actions>
+                  <button mat-button color="default" (click)="dialogRef.close('cancel')">{{lang.cancel}}</button>
+                  <span style="flex: 1 1 auto;"></span>
+                  <button mat-button color="primary" (click)="dialogRef.close('ok')">{{lang.validate}}</button>
+              </mat-dialog-actions>
+            `,
+})
+export class ConfirmModalComponent {
+    lang: any = LANG;
+    constructor(@Inject(MAT_DIALOG_DATA) public data: any, public dialogRef: MatDialogRef<ConfirmModalComponent>) { }
+}
\ No newline at end of file
diff --git a/apps/maarch_entreprise/js/angular/lang/lang-en.ts b/apps/maarch_entreprise/js/angular/lang/lang-en.ts
index ba4eb67b2e6..80b8f1cbac6 100755
--- a/apps/maarch_entreprise/js/angular/lang/lang-en.ts
+++ b/apps/maarch_entreprise/js/angular/lang/lang-en.ts
@@ -19,6 +19,7 @@ export const LANG_EN = {
     "active"                            : "Active",
     "activeCron"                        : "Active cron",
     "add"                               : "Add",
+    "additionalRoles"                   : "Additional(s) Role(s)",
     "address"                           : "Address",
     "addStatus"                         : "Add a status",
     "addUser"                           : "Add a user",
@@ -257,6 +258,8 @@ export const LANG_EN = {
     "resultPage"                        : "Result page",
     "resultPageUpdated"                 : "Page de résultat modifié",
     "role"                              : "Role",
+    "roleUsedInTemplateInfo"            : "This role is used in entities",
+    "roleUsedInTemplateInfo2"           : "Users linked to this role will be removed in diffusion list.",
     "saturday"                          : "Saturday",
     "save"                              : "Save",
     "september"                         : "September",
diff --git a/apps/maarch_entreprise/js/angular/lang/lang-fr.ts b/apps/maarch_entreprise/js/angular/lang/lang-fr.ts
index 25679a8c39a..8c095478c49 100755
--- a/apps/maarch_entreprise/js/angular/lang/lang-fr.ts
+++ b/apps/maarch_entreprise/js/angular/lang/lang-fr.ts
@@ -22,6 +22,7 @@ export const LANG_FR = {
     "active"                            : "Actif",
     "activeCron"                        : "Tâche(s) active(s)",
     "add"                               : "Ajouter",
+    "additionalRoles"                   : "Role(s) supplémentaire(s)",
     "address"                           : "Adresse",
     "addStatus"                         : "Ajouter un statut",
     "addUser"                           : "Ajouter un utilisateur",
@@ -275,6 +276,8 @@ export const LANG_FR = {
     "resultPage"                        : "Page de résultat",
     "resultPageUpdated"                 : "Page de résultat modifié",
     "role"                              : "Rôle",
+    "roleUsedInTemplateInfo"            : "Le rôle est utilisé dans les services suivants",
+    "roleUsedInTemplateInfo2"           : "Les utilisateurs associés à ce rôle seront supprimés de la liste de diffusion.",
     "saturday"                          : "Samedi",
     "save"                              : "Enregistrer",
     "september"                         : "Septembre",
-- 
GitLab