From fa00d684a9c111cbcea5fe8b6db362d5ab733f64 Mon Sep 17 00:00:00 2001
From: Alex ORLUC <alex.orluc@maarch.org>
Date: Tue, 21 Apr 2020 17:14:27 +0200
Subject: [PATCH] FEAT #13126 TIME 2 add linked resources attachments

---
 .../printed-folder-modal.component.html       |   6 +-
 .../printed-folder-modal.component.scss       |   6 +-
 .../printed-folder-modal.component.ts         | 188 ++++++++++++------
 src/frontend/lang/lang-en.ts                  |   1 +
 src/frontend/lang/lang-fr.ts                  |   1 +
 src/frontend/lang/lang-nl.ts                  |   1 +
 6 files changed, 143 insertions(+), 60 deletions(-)

diff --git a/src/frontend/app/printedFolder/printed-folder-modal.component.html b/src/frontend/app/printedFolder/printed-folder-modal.component.html
index 40a3c899195..7ae910e2e6a 100644
--- a/src/frontend/app/printedFolder/printed-folder-modal.component.html
+++ b/src/frontend/app/printedFolder/printed-folder-modal.component.html
@@ -6,7 +6,7 @@
         <button [title]="lang.close" mat-icon-button (click)="dialogRef.close();">
             <mat-icon class="fa fa-times"></mat-icon>
         </button></h1>
-    <mat-dialog-content>
+    <mat-dialog-content style="padding-bottom:10px;">
         <div class="loading" *ngIf="loading; else loadingTemplate">
             <mat-spinner style="margin:auto;"></mat-spinner>
         </div>
@@ -55,6 +55,10 @@
                                     *ngFor="let element of printedFolderElement[keyVal.key]"
                                     [disabled]="!element.canConvert" [value]="element.id">
                                     <div class="printedFolderElement-item {{keyVal.key}}">
+                                        <div color="primary" style="flex:1;font-size: 80%;padding-right: 10px;"
+                                            *ngIf="!functions.empty(element.chronoMaster)">
+                                            {{element.chronoMaster}}
+                                        </div>
                                         <div color="primary" style="flex:1;font-size: 80%;padding-right: 10px;"
                                             *ngIf="!functions.empty(element.chrono)">
                                             {{element.chrono}}
diff --git a/src/frontend/app/printedFolder/printed-folder-modal.component.scss b/src/frontend/app/printedFolder/printed-folder-modal.component.scss
index 43612314734..d606206f9c0 100644
--- a/src/frontend/app/printedFolder/printed-folder-modal.component.scss
+++ b/src/frontend/app/printedFolder/printed-folder-modal.component.scss
@@ -20,7 +20,7 @@
     display: flex;
     height: 100%;
     width: 100%;
-    position: absolute;
+    padding: 10px;
     top: 0px;
     left: 0px;
 }
@@ -58,6 +58,10 @@
     grid-template-columns: 1fr 2fr 1fr 1fr 1fr;
 }
 
+.linkedResources {
+    grid-template-columns: 1fr 1fr 2fr 1fr 1fr 1fr;
+}
+
 .printedFolderContainer {
     display: grid;
     grid-template-columns: 1fr;
diff --git a/src/frontend/app/printedFolder/printed-folder-modal.component.ts b/src/frontend/app/printedFolder/printed-folder-modal.component.ts
index 4dd0fcb8e3e..12683492e03 100644
--- a/src/frontend/app/printedFolder/printed-folder-modal.component.ts
+++ b/src/frontend/app/printedFolder/printed-folder-modal.component.ts
@@ -1,14 +1,14 @@
-import { Component, Inject } from '@angular/core';
+import { Component, Inject, OnInit } from '@angular/core';
 import { MAT_DIALOG_DATA, MatDialogRef, MatDialog } from '@angular/material/dialog';
 import { LANG } from '../translate.component';
 import { HttpClient } from '@angular/common/http';
 import { NotificationService } from '../notification.service';
 import { map, tap, catchError, finalize } from 'rxjs/operators';
-import { of } from 'rxjs';
 import { FunctionsService } from '../../service/functions.service';
 import { FormControl } from '@angular/forms';
 import { SortPipe } from '../../plugins/sorting.pipe';
 import { SummarySheetComponent } from '../list/summarySheet/summary-sheet.component';
+import { of } from 'rxjs/internal/observable/of';
 
 
 @Component({
@@ -16,7 +16,7 @@ import { SummarySheetComponent } from '../list/summarySheet/summary-sheet.compon
     styleUrls: ['printed-folder-modal.component.scss'],
     providers: [SortPipe]
 })
-export class PrintedFolderModalComponent {
+export class PrintedFolderModalComponent implements OnInit {
     loading: boolean = true;
 
     lang: any = LANG;
@@ -34,7 +34,8 @@ export class PrintedFolderModalComponent {
         attachments: [],
         notes: [],
         emails: [],
-        acknowledgementReceipts: []
+        acknowledgementReceipts: [],
+        linkedResources : [],
     };
 
     selectedPrintedFolderElement: any = {};
@@ -59,6 +60,7 @@ export class PrintedFolderModalComponent {
         await this.getEmails();
         await this.getAcknowledgementReceips();
         await this.getNotes();
+        await this.getLinkedResources();
 
         this.loading = false;
     }
@@ -66,7 +68,7 @@ export class PrintedFolderModalComponent {
     getMainDocInfo() {
         return new Promise((resolve) => {
             this.http.get(`../rest/resources/${this.data.resId}/fileInformation`).pipe(
-                map((data: any) => {   
+                map((data: any) => {
                     data = {
                         ...data.information,
                         id: this.data.resId,
@@ -74,8 +76,8 @@ export class PrintedFolderModalComponent {
                     return data;
                 }),
                 tap((data) => {
-                   this.mainDocumentInformation = data;
-                   resolve(true);
+                    this.mainDocumentInformation = data;
+                    resolve(true);
                 }),
                 catchError((err: any) => {
                     this.notify.handleSoftErrors(err);
@@ -88,25 +90,75 @@ export class PrintedFolderModalComponent {
 
     getAttachments() {
         return new Promise((resolve) => {
-            this.http.get("../rest/resources/" + this.data.resId + "/attachments").pipe(
+            this.http.get('../rest/resources/' + this.data.resId + '/attachments').pipe(
                 map((data: any) => {
                     data.attachments = data.attachments.map((attachment: any) => {
                         return {
-                           id: attachment.resId,
-                           label: attachment.title,
-                           chrono: !this.functions.empty(attachment.chrono) ? attachment.chrono : this.lang.undefined,
-                           type: attachment.typeLabel,
-                           creationDate: attachment.creationDate,
-                           canConvert : attachment.canConvert,
-                           status: attachment.status
-                        }
+                            id: attachment.resId,
+                            label: attachment.title,
+                            chrono: !this.functions.empty(attachment.chrono) ? attachment.chrono : this.lang.undefined,
+                            type: attachment.typeLabel,
+                            creationDate: attachment.creationDate,
+                            canConvert: attachment.canConvert,
+                            status: attachment.status
+                        };
+                    });
+                    return data.attachments;
+                }),
+                tap((data) => {
+
+                    this.printedFolderElement.attachments = this.sortPipe.transform(data, 'chrono');
+                    resolve(true);
+                }),
+                catchError((err: any) => {
+                    this.notify.handleSoftErrors(err);
+                    resolve(false);
+                    return of(false);
+                })
+            ).subscribe();
+        });
+    }
+
+    getLinkedResources() {
+        return new Promise((resolve) => {
+            this.http.get(`../rest/resources/${this.data.resId}/linkedResources`).pipe(
+                tap(async (data: any) => {
+                    for (let index = 0; index < data.linkedResources.length; index++) {
+                        await this.getLinkedAttachments(data.linkedResources[index]);
+                    }
+                    resolve(true);
+                }),
+                catchError((err: any) => {
+                    this.notify.handleSoftErrors(err);
+                    resolve(false);
+                    return of(false);
+                })
+            ).subscribe();
+        });
+    }
+
+    getLinkedAttachments(resourceMaster: any) {
+        return new Promise((resolve) => {
+            this.http.get(`../rest/resources/${resourceMaster.resId}/attachments`).pipe(
+                map((data: any) => {
+                    data.attachments = data.attachments.map((attachment: any) => {
+                        return {
+                            id: attachment.resId,
+                            label: attachment.title,
+                            resIdMaster : resourceMaster.resId,
+                            chronoMaster: resourceMaster.chrono,
+                            chrono: !this.functions.empty(attachment.chrono) ? attachment.chrono : this.lang.undefined,
+                            type: attachment.typeLabel,
+                            creationDate: attachment.creationDate,
+                            canConvert: attachment.canConvert,
+                            status: attachment.status
+                        };
                     });
                     return data.attachments;
                 }),
                 tap((data) => {
-                    
-                   this.printedFolderElement.attachments = this.sortPipe.transform(data, 'chrono');
-                   resolve(true);
+                    this.printedFolderElement.linkedResources = this.printedFolderElement.linkedResources.concat(this.sortPipe.transform(data, 'chronoMaster'));
+                    resolve(true);
                 }),
                 catchError((err: any) => {
                     this.notify.handleSoftErrors(err);
@@ -127,8 +179,8 @@ export class PrintedFolderModalComponent {
                             recipients: item.recipients,
                             creationDate: item.creation_date,
                             label: !this.functions.empty(item.object) ? item.object : `<i>${this.lang.emptySubject}<i>`,
-                            canConvert : true
-                        }
+                            canConvert: true
+                        };
                     });
                     return data.emails;
                 }),
@@ -156,8 +208,8 @@ export class PrintedFolderModalComponent {
                             creator: `${item.firstname} ${item.lastname}`,
                             creationDate: item.creation_date,
                             label: item.value,
-                            canConvert : true
-                        }
+                            canConvert: true
+                        };
                     });
                     return data.notes;
                 }),
@@ -188,7 +240,7 @@ export class PrintedFolderModalComponent {
                         }
                         let name;
                         if (!this.functions.empty(item.contact.firstname) && !this.functions.empty(item.contact.lastname)) {
-                            name = `${item.contact.firstname} ${item.contact.lastname}`
+                            name = `${item.contact.firstname} ${item.contact.lastname}`;
                         } else {
                             name = this.lang.contactDeleted;
                         }
@@ -199,8 +251,8 @@ export class PrintedFolderModalComponent {
                             recipients: item.format === 'html' ? email : name,
                             creationDate: item.creationDate,
                             label: item.format === 'html' ? this.lang.ARelectronic : this.lang.ARPaper,
-                            canConvert : true
-                        }
+                            canConvert: true
+                        };
                     });
                     return data;
                 }),
@@ -230,30 +282,30 @@ export class PrintedFolderModalComponent {
     onSubmit() {
         this.isLoadingResults = true;
 
-        this.http.post(`../rest/resources/folderPrint`, this.formatPrintedFolder(), { responseType: "blob" }).pipe(
+        this.http.post(`../rest/resources/folderPrint`, this.formatPrintedFolder(), { responseType: 'blob' }).pipe(
             tap((data: any) => {
-                let downloadLink = document.createElement('a');
-                    downloadLink.href = window.URL.createObjectURL(data);
-                    let today: any;
-                    let dd: any;
-                    let mm: any;
-                    let yyyy: any;
-    
-                    today = new Date();
-                    dd = today.getDate();
-                    mm = today.getMonth() + 1;
-                    yyyy = today.getFullYear();
-    
-                    if (dd < 10) {
-                        dd = '0' + dd;
-                    }
-                    if (mm < 10) {
-                        mm = '0' + mm;
-                    }
-                    today = dd + '-' + mm + '-' + yyyy;
-                    downloadLink.setAttribute('download', "export_maarch_" + today + ".pdf");
-                    document.body.appendChild(downloadLink);
-                    downloadLink.click();
+                const downloadLink = document.createElement('a');
+                downloadLink.href = window.URL.createObjectURL(data);
+                let today: any;
+                let dd: any;
+                let mm: any;
+                let yyyy: any;
+
+                today = new Date();
+                dd = today.getDate();
+                mm = today.getMonth() + 1;
+                yyyy = today.getFullYear();
+
+                if (dd < 10) {
+                    dd = '0' + dd;
+                }
+                if (mm < 10) {
+                    mm = '0' + mm;
+                }
+                today = dd + '-' + mm + '-' + yyyy;
+                downloadLink.setAttribute('download', 'export_maarch_' + today + '.pdf');
+                document.body.appendChild(downloadLink);
+                downloadLink.click();
             }),
             finalize(() => this.isLoadingResults = false),
             catchError((err: any) => {
@@ -264,19 +316,39 @@ export class PrintedFolderModalComponent {
     }
 
     formatPrintedFolder() {
-        let printedFolder: any = {
-            withSeparator : this.withSeparator,
-            summarySheet : this.summarySheet,
-            resources : []
+        const printedFolder: any = {
+            withSeparator: this.withSeparator,
+            summarySheet: this.summarySheet,
+            resources: []
         };
-        let resource = {
-            resId : this.data.resId,
-            document : this.mainDocument,
+        const resource = {
+            resId: this.data.resId,
+            document: this.mainDocument,
         };
         Object.keys(this.printedFolderElement).forEach(element => {
             resource[element] = this.selectedPrintedFolderElement[element].value.length === this.printedFolderElement[element].length ? 'ALL' : this.selectedPrintedFolderElement[element].value;
         });
 
+        // for Linked ressource (complex array)
+        if (!this.functions.empty(resource['linkedResources'])) {
+            resource['linkedResources'] = [];
+            this.selectedPrintedFolderElement['linkedResources'].value.forEach((item: any) => {
+                const resIdMaster = this.printedFolderElement.linkedResources.filter((res: any) => res.id === item)[0].resIdMaster;
+                if (resource['linkedResources'].filter((res: any) => res.resId === resIdMaster).length > 0) {
+                    resource['linkedResources'].filter((res: any) => res.resId === resIdMaster)[0].attachments.push(item);
+                } else {
+                    resource['linkedResources'].push(
+                        {
+                            resId : resIdMaster,
+                            attachments : [
+                                item
+                            ]
+                        }
+                    );
+                }
+            });
+        }
+
         printedFolder.resources.push(resource);
 
 
@@ -289,7 +361,7 @@ export class PrintedFolderModalComponent {
             panelClass: 'maarch-full-height-modal',
             width: '800px',
             data: {
-                paramMode : true
+                paramMode: true
             }
         });
         dialogRef.afterClosed().pipe(
@@ -300,7 +372,7 @@ export class PrintedFolderModalComponent {
                 this.notify.handleSoftErrors(err);
                 return of(false);
             })
-        ).subscribe(); 
+        ).subscribe();
     }
 
     isEmptySelection() {
diff --git a/src/frontend/lang/lang-en.ts b/src/frontend/lang/lang-en.ts
index 27eb96e580f..3841a5f0673 100755
--- a/src/frontend/lang/lang-en.ts
+++ b/src/frontend/lang/lang-en.ts
@@ -1673,4 +1673,5 @@ export const LANG_EN = {
     "accountLocked": "Too many connections attemps. Retry in",
     "modelUsedByResources": "This model is used by resources, you can't delete it.",
     "mustChangePassword": "Please, you must change your password.",
+    "linkedResources": "Attachments (linked mails)",
 };
diff --git a/src/frontend/lang/lang-fr.ts b/src/frontend/lang/lang-fr.ts
index d3a07e6ec3b..a241748ab0d 100755
--- a/src/frontend/lang/lang-fr.ts
+++ b/src/frontend/lang/lang-fr.ts
@@ -1673,4 +1673,5 @@ export const LANG_FR = {
     "accountLocked": "Nombre de tentatives de connexion dépassée. Réessayez dans",
     "modelUsedByResources": "Le modèle est utilisé par des courriers, vous ne pouvez pas le supprimer.",
     "mustChangePassword": "Vous êtes invité à changer votre mot de passe.",
+    "linkedResources": "Pièces jointes (courriers liés)",
 };
diff --git a/src/frontend/lang/lang-nl.ts b/src/frontend/lang/lang-nl.ts
index 4c4b2945bdc..13c9289d479 100755
--- a/src/frontend/lang/lang-nl.ts
+++ b/src/frontend/lang/lang-nl.ts
@@ -1657,4 +1657,5 @@ export const LANG_NL = {
     "accountLocked": "Too many connections attemps. Retry in", //_TO_TRANSLATE
     "modelUsedByResources": "This model is used by resources, you can't delete it.", //_TO_TRANSLATE
     "mustChangePassword": "Please, you must change your password.", //_TO_TRANSLATE
+    "linkedResources": "Attachments (linked mails)", //_TO_TRANSLATE
 };
-- 
GitLab