From 846ae0bc78d3b685d134d6a21496f6a3f4dc23a9 Mon Sep 17 00:00:00 2001
From: "florian.azizian" <florian.azizian@maarch.org>
Date: Tue, 14 Jan 2020 18:08:23 +0100
Subject: [PATCH] FEAT #10633 TIME 2:20 Front - redirect initiator entity
 action

---
 rest/index.php                                |  1 +
 .../controllers/ActionMethodController.php    | 47 ++++++-------
 .../PreProcessActionController.php            |  9 +--
 src/frontend/app/actions/actions.service.ts   | 23 +++++++
 ...ect-initiator-entity-action.component.html | 42 ++++++++++++
 ...ect-initiator-entity-action.component.scss | 37 ++++++++++
 ...irect-initiator-entity-action.component.ts | 68 +++++++++++++++++++
 src/frontend/app/app.module.ts                |  3 +
 src/frontend/lang/lang-en.ts                  |  2 +
 src/frontend/lang/lang-fr.ts                  |  2 +
 src/frontend/lang/lang-nl.ts                  |  2 +
 11 files changed, 207 insertions(+), 29 deletions(-)
 create mode 100644 src/frontend/app/actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component.html
 create mode 100644 src/frontend/app/actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component.scss
 create mode 100644 src/frontend/app/actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component.ts

diff --git a/rest/index.php b/rest/index.php
index 153200ca0fc..b9367690b7e 100755
--- a/rest/index.php
+++ b/rest/index.php
@@ -378,6 +378,7 @@ $app->post('/acknowledgementReceipt', \AcknowledgementReceipt\controllers\Acknow
 $app->post('/resourcesList/users/{userId}/groups/{groupId}/baskets/{basketId}/checkAcknowledgementReceipt', \Action\controllers\PreProcessActionController::class . ':checkAcknowledgementReceipt');
 $app->post('/resourcesList/users/{userId}/groups/{groupId}/baskets/{basketId}/checkExternalSignatoryBook', \Action\controllers\PreProcessActionController::class . ':checkExternalSignatoryBook');
 $app->post('/resourcesList/users/{userId}/groups/{groupId}/baskets/{basketId}/checkExternalNoteBook', \Action\controllers\PreProcessActionController::class . ':checkExternalNoteBook');
+$app->post('/resourcesList/users/{userId}/groups/{groupId}/baskets/{basketId}/checkInitiatorEntity', \Action\controllers\PreProcessActionController::class . ':checkInitiatorEntity');
 $app->get('/resourcesList/users/{userId}/groups/{groupId}/baskets/{basketId}/actions/{actionId}/getRedirect', \Action\controllers\PreProcessActionController::class . ':getRedirectInformations');
 $app->post('/resourcesList/users/{userId}/groups/{groupId}/baskets/{basketId}/actions/{actionId}/checkShippings', \Action\controllers\PreProcessActionController::class . ':checkShippings');
 $app->post('/resourcesList/users/{userId}/groups/{groupId}/baskets/{basketId}/actions/{actionId}/checkSignatureBook', \Action\controllers\PreProcessActionController::class . ':checkSignatureBook');
diff --git a/src/app/action/controllers/ActionMethodController.php b/src/app/action/controllers/ActionMethodController.php
index 5c2b164a28d..cf7d5480230 100644
--- a/src/app/action/controllers/ActionMethodController.php
+++ b/src/app/action/controllers/ActionMethodController.php
@@ -289,38 +289,35 @@ class ActionMethodController
         if (!empty($resource)) {
             $entityInfo = EntityModel::getByEntityId(['entityId' => $resource['initiator'], 'select' => ['id']]);
             if (!empty($entityInfo)) {
-                $destUser = ListTemplateModel::getWithItems(['data' => ['entity_id = ?', 'item_mode = ?', 'type = ?'], 'data' => [$entityInfo['id'], 'dest', 'diffusionList']]);
+                $destUser = ListTemplateModel::getWithItems(['where' => ['entity_id = ?', 'item_mode = ?', 'type = ?'], 'data' => [$entityInfo['id'], 'dest', 'diffusionList']]);
                 if (!empty($destUser)) {
-                    $listInstances = ListInstanceModel::get(['select' => ['*'], 'where' => ['res_id = ?', 'difflist_type = ?', 'item_mode = ?'], 'data' => [$args['resId'], 'entity_id', 'dest']]);
-                    if (!empty($listInstances)) {
-                        ListInstanceModel::create([
-                            'res_id'              => $listInstances[0]['res_id'],
-                            'sequence'            => $listInstances[0]['sequence'],
-                            'item_id'             => $listInstances[0]['item_id'],
-                            'item_type'           => $listInstances[0]['item_type'],
-                            'item_mode'           => 'cc',
-                            'added_by_user'       => $listInstances[0]['added_by_user'],
-                            'viewed'              => $listInstances[0]['viewed'],
-                            'difflist_type'       => $listInstances[0]['difflist_type'],
-                            'process_date'        => $listInstances[0]['process_date'],
-                            'process_comment'     => $listInstances[0]['process_comment'],
-                            'requested_signature' => $listInstances[0]['requested_signature']
-                        ]);
-                    }
-                    $userInfo = UserModel::getById(['select' => ['user_id'], 'id' => $destUser[0]['item_id']]);
                     ListInstanceModel::update([
                         'set' => [
-                            'item_id' => $userInfo['user_id']
+                            'item_mode' => 'cc'
                         ],
-                        'where' => ['listinstance_id = ?'],
-                        'data' => [$listInstances[0]['listinstance_id']]
+                        'where' => ['item_mode = ?', 'res_id = ?'],
+                        'data' => ['dest', $args['resId']]
                     ]);
-                    ResModel::update([
-                        'set'   => ['destination' => $resource['initiator']],
-                        'where' => ['res_id = ?'],
-                        'data'  => [$args['resId']]
+                    $userInfo = UserModel::getById(['select' => ['user_id'], 'id' => $destUser[0]['item_id']]);
+                    ListInstanceModel::create([
+                        'res_id'              => $args['resId'],
+                        'sequence'            => 0,
+                        'item_id'             => $userInfo['user_id'],
+                        'item_type'           => 'user_id',
+                        'item_mode'           => 'dest',
+                        'added_by_user'       => $GLOBALS['userId'],
+                        'viewed'              => 0,
+                        'difflist_type'       => 'entity_id'
                     ]);
+                    $destUser = $userInfo['user_id'];
+                } else {
+                    $destUser = '';
                 }
+                ResModel::update([
+                    'set'   => ['destination' => $resource['initiator'], 'dest_user' => $destUser],
+                    'where' => ['res_id = ?'],
+                    'data'  => [$args['resId']]
+                ]);
             }
         }
 
diff --git a/src/app/action/controllers/PreProcessActionController.php b/src/app/action/controllers/PreProcessActionController.php
index 3afe3f0be7e..786b974d514 100755
--- a/src/app/action/controllers/PreProcessActionController.php
+++ b/src/app/action/controllers/PreProcessActionController.php
@@ -818,18 +818,19 @@ class PreProcessActionController
         $withoutEntity = [];
 
         $resources = ResModel::get([
-            'select' => ['initiator', 'res_id'],
+            'select' => ['initiator', 'res_id', 'alt_identifier'],
             'where'  => ['res_id in (?)'],
             'data'   => [$data['resources']]
         ]);
 
-        $resourcesInfo = array_column($resources, 'initiator', 'res_id');
+        $resourcesInfoInitiator = array_column($resources, 'initiator', 'res_id');
+        $resourcesInfoChrono = array_column($resources, 'alt_identifier', 'res_id');
 
         foreach ($data['resources'] as $valueResId) {
-            if (!empty($resourcesInfo[$valueResId])) {
+            if (!empty($resourcesInfoInitiator[$valueResId])) {
                 $withEntity[] = $valueResId;
             } else {
-                $withoutEntity[] = $valueResId;
+                $withoutEntity[] = $resourcesInfoChrono[$valueResId] ?? _UNDEFINED;
             }
         }
 
diff --git a/src/frontend/app/actions/actions.service.ts b/src/frontend/app/actions/actions.service.ts
index c7d6bfb0ab5..af87e163072 100644
--- a/src/frontend/app/actions/actions.service.ts
+++ b/src/frontend/app/actions/actions.service.ts
@@ -19,6 +19,7 @@ import { SendExternalSignatoryBookActionComponent } from './send-external-signat
 import { SendExternalNoteBookActionComponent } from './send-external-note-book-action/send-external-note-book-action.component';
 import { RedirectActionComponent } from './redirect-action/redirect-action.component';
 import { SendShippingActionComponent } from './send-shipping-action/send-shipping-action.component';
+import { redirectInitiatorEntityActionComponent } from './redirect-initiator-entity-action/redirect-initiator-entity-action.component';
 import { Router } from '@angular/router';
 
 @Injectable()
@@ -298,6 +299,28 @@ export class ActionsService {
         ).subscribe();
     }
 
+    redirectInitiatorEntityAction(options: any = null) {
+        const dialogRef = this.dialog.open(redirectInitiatorEntityActionComponent, {
+            disableClose: true,
+            width: '500px',
+            data: this.setDatasActionToSend()
+        });
+        dialogRef.afterClosed().pipe(
+            tap((data: any) => {
+                this.unlockResourceAfterActionModal(data);
+            }),
+            filter((data: string) => data === 'success'),
+            tap((result: any) => {
+                this.endAction(result);
+            }),
+            finalize(() => this.loading = false),
+            catchError((err: any) => {
+                this.notify.handleErrors(err);
+                return of(false);
+            })
+        ).subscribe();
+    }
+
     updateAcknowledgementSendDateAction(options: any = null) {
         const dialogRef = this.dialog.open(UpdateAcknowledgementSendDateActionComponent, {
             disableClose: true,
diff --git a/src/frontend/app/actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component.html b/src/frontend/app/actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component.html
new file mode 100644
index 00000000000..fcb3f31dd70
--- /dev/null
+++ b/src/frontend/app/actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component.html
@@ -0,0 +1,42 @@
+<h1 mat-dialog-title>{{data.action.label}}</h1>
+<div mat-dialog-content *ngIf="!loadingInit">
+    <div *ngIf="loading" class="loading" style="display:flex;height:100%;">
+        <mat-spinner style="margin:auto;"></mat-spinner>
+    </div>
+    <div class="row">
+        <div class="col-md-12">
+            {{lang.makeActionOn}} 
+                <b *ngIf="data.resIds.length == 1" color="primary" class="highlight">{{data.resource.chrono}}</b>
+                <b *ngIf="data.resIds.length > 1" color="primary" class="highlight">{{data.resIds.length}}
+                    {{lang.elements}}</b> ?
+                <div *ngIf="resourcesInfo.withoutEntity.length > 0">
+                    <div class="alert-message alert-message-info acknowledgementList" role="alert">
+                        <p>
+                            {{lang.hasNoEntity}} :
+                        </p>
+                        <ul>
+                            <li *ngFor="let info of resourcesInfo.withoutEntity">
+                                {{info}}
+                            </li>
+                        </ul>
+                    </div>
+                </div>
+                <div *ngIf="resourcesInfo.withEntity.length > 0">
+                    <div class="alert-message alert-message-success" role="alert">
+                        <p>
+                            {{lang.destUserSetToDefault}}
+                        </p>
+                    </div>
+                </div>
+        </div>
+        <div class="col-md-12">
+            <app-note-editor #noteEditor [resIds]="data.resIds"></app-note-editor>
+        </div>
+    </div>
+</div>
+<div mat-dialog-actions class="actions">
+    <button mat-raised-button mat-button color="primary"
+        [disabled]="loading || resourcesInfo.withEntity.length == 0"
+        (click)="onSubmit()">{{lang.validate}}</button>
+    <button mat-raised-button mat-button [disabled]="loading" [mat-dialog-close]="">{{lang.cancel}}</button>
+</div>
diff --git a/src/frontend/app/actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component.scss b/src/frontend/app/actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component.scss
new file mode 100644
index 00000000000..45d114a19c4
--- /dev/null
+++ b/src/frontend/app/actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component.scss
@@ -0,0 +1,37 @@
+.highlight {
+    font-size: 110%;
+}
+
+.loading {
+    display: flex;
+    position: absolute;
+    top: 0;
+    left: 0;
+    width: 100%;
+    height: 100%;
+    background: #ffffffb3;
+    z-index: 1;
+    overflow: hidden;
+}
+
+.acknowledgementList {
+    ul {
+        font-size: 12px;
+        max-height: 100px;
+        overflow: auto;
+        padding-left: 25px;
+        padding-right: 5px;
+        padding-bottom: 10px;
+        margin-top: 10px;
+    }
+
+    p {
+        //font-size: 18px;
+        margin: 0;
+        text-decoration: underline;
+    }
+
+    b {
+        font-size: 120%;
+    }
+}
\ No newline at end of file
diff --git a/src/frontend/app/actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component.ts b/src/frontend/app/actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component.ts
new file mode 100644
index 00000000000..e8616047c72
--- /dev/null
+++ b/src/frontend/app/actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component.ts
@@ -0,0 +1,68 @@
+import { Component, OnInit, Inject, ViewChild } from '@angular/core';
+import { LANG } from '../../translate.component';
+import { NotificationService } from '../../notification.service';
+import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
+import { HttpClient } from '@angular/common/http';
+import { NoteEditorComponent } from '../../notes/note-editor.component';
+import { tap, finalize, catchError } from 'rxjs/operators';
+import { of } from 'rxjs';
+
+@Component({
+    templateUrl: "redirect-initiator-entity-action.component.html",
+    styleUrls: ['redirect-initiator-entity-action.component.scss'],
+    providers: [NotificationService],
+})
+export class redirectInitiatorEntityActionComponent implements OnInit {
+
+    lang: any = LANG;
+    loading: boolean = false;
+    loadingInit: boolean = false;
+    resourcesInfo: any = {
+        withEntity: [],
+        withoutEntity: []
+    };
+
+    @ViewChild('noteEditor', { static: false }) noteEditor: NoteEditorComponent;
+    loadingExport: boolean;
+
+    constructor(public http: HttpClient, private notify: NotificationService, public dialogRef: MatDialogRef<redirectInitiatorEntityActionComponent>, @Inject(MAT_DIALOG_DATA) public data: any) { }
+
+    ngOnInit(): void {
+        this.loadingInit = true;
+
+        this.http.post('../../rest/resourcesList/users/' + this.data.userId + '/groups/' + this.data.groupId + '/baskets/' + this.data.basketId + '/checkInitiatorEntity', { resources: this.data.resIds })
+            .subscribe((data: any) => {
+                this.resourcesInfo = data;
+                this.loadingInit = false;
+            }, (err) => {
+                this.notify.error(err.error.errors);
+                this.loadingInit = false;
+            });
+    }
+
+    onSubmit() {
+        this.loading = true;
+        this.executeAction();
+    }
+
+    executeAction() {
+        // let realResSelected: string[];
+        // console.log(this.resourcesInfo.withEntity);
+        // realResSelected = this.resourcesInfo.withEntity.map((e: any) => { return e.res_id; });
+        // console.log(realResSelected);
+        this.http.put(this.data.processActionRoute, { resources: this.resourcesInfo.withEntity, note: this.noteEditor.getNoteContent() }).pipe(
+            tap((data: any) => {
+                if (data && data.errors != null) {
+                    this.notify.error(data.errors);
+                }
+                this.dialogRef.close('success');
+            }),
+            finalize(() => this.loading = false),
+            catchError((err: any) => {
+                this.notify.handleErrors(err);
+                return of(false);
+            })
+        ).subscribe();
+    }
+
+}
diff --git a/src/frontend/app/app.module.ts b/src/frontend/app/app.module.ts
index a8bd7c93cae..09d63b71a22 100755
--- a/src/frontend/app/app.module.ts
+++ b/src/frontend/app/app.module.ts
@@ -52,6 +52,7 @@ import { ProcessActionComponent }               from './actions/process-action/p
 import { ViewDocActionComponent }               from './actions/view-doc-action/view-doc-action.component';
 import { RedirectActionComponent }               from './actions/redirect-action/redirect-action.component';
 import { SendShippingActionComponent }               from './actions/send-shipping-action/send-shipping-action.component';
+import { redirectInitiatorEntityActionComponent } from './actions/redirect-initiator-entity-action/redirect-initiator-entity-action.component';
 
 import { FiltersListComponent }                 from './list/filters/filters-list.component';
 import { FiltersToolComponent }                 from './list/filters/filters-tool.component';
@@ -139,6 +140,7 @@ import { AddAvisModelModalComponent } from './avis/addAvisModel/add-avis-model-m
         ViewDocActionComponent,
         RedirectActionComponent,
         SendShippingActionComponent,
+        redirectInitiatorEntityActionComponent,
         ActionsListComponent,
         PrintSeparatorComponent,
         FolderPinnedComponent,
@@ -188,6 +190,7 @@ import { AddAvisModelModalComponent } from './avis/addAvisModel/add-avis-model-m
         ProcessActionComponent,
         RedirectActionComponent,
         SendShippingActionComponent,
+        redirectInitiatorEntityActionComponent,
         ViewDocActionComponent,
         FolderUpdateComponent,
         AddPrivateIndexingModelModalComponent,
diff --git a/src/frontend/lang/lang-en.ts b/src/frontend/lang/lang-en.ts
index 8a0a7f08d9b..36202cb428c 100755
--- a/src/frontend/lang/lang-en.ts
+++ b/src/frontend/lang/lang-en.ts
@@ -1404,4 +1404,6 @@ export const LANG_EN = {
     "avisSent" : "Opinion given",
     "openFullscreen" : "Enable fullscreen",
     "closeFullscreen" : "Disable fullscreen",
+    "hasNoEntity": "Those mails do not have initiator entity",
+    "destUserSetToDefault": "Assignee will be the assignee of the initiator entity template list",
 };
diff --git a/src/frontend/lang/lang-fr.ts b/src/frontend/lang/lang-fr.ts
index 64ab655a6e0..9bfb9a83c3b 100755
--- a/src/frontend/lang/lang-fr.ts
+++ b/src/frontend/lang/lang-fr.ts
@@ -1444,4 +1444,6 @@ export const LANG_FR = {
     "avisSent" : "Avis donné",
     "openFullscreen" : "Activer le mode plein écran",
     "closeFullscreen" : "Désactiver le mode plein écran",
+    "hasNoEntity": "Les courriers suivants n'ont pas d'entité initiatrice",
+    "destUserSetToDefault": "Le destinataire sera celui de la liste de diffusion de l'entité initiatrice",
 };
diff --git a/src/frontend/lang/lang-nl.ts b/src/frontend/lang/lang-nl.ts
index 7670fd7cfd9..da0aec0f1ed 100755
--- a/src/frontend/lang/lang-nl.ts
+++ b/src/frontend/lang/lang-nl.ts
@@ -1429,4 +1429,6 @@ export const LANG_NL = {
     "avisSent" : "Opinion given", //_TO_TRANSLATE
     "openFullscreen" : "Enable fullscreen", //_TO_TRANSLATE
     "closeFullscreen" : "Disable fullscreen", //_TO_TRANSLATE
+    "hasNoEntity": "Those mails do not have initiator entity", //_TO_TRANSLATE
+    "destUserSetToDefault": "Assignee will be the assignee of the initiator entity template list", //_TO_TRANSLATE
 };
-- 
GitLab