From fb7f421b4e08bf5728f119453f84a669b9f3bcef Mon Sep 17 00:00:00 2001
From: Guillaume Heurtier <guillaume.heurtier@maarch.org>
Date: Tue, 15 Sep 2020 14:13:53 +0200
Subject: [PATCH] FEAT #13274 TIME 9:30 added summary sheet as email attachment

---
 apps/maarch_entreprise/xml/entreprise.xml     |   4 +
 .../controllers/SummarySheetController.php    |   5 +
 .../app/process/process.component.html        |   4 +-
 .../sent-resource-list.component.ts           |  14 +-
 .../sent-resource-page.component.html         |   4 +-
 .../sent-resource-page.component.ts           | 140 +++++++++++++++++-
 6 files changed, 157 insertions(+), 14 deletions(-)

diff --git a/apps/maarch_entreprise/xml/entreprise.xml b/apps/maarch_entreprise/xml/entreprise.xml
index 15fb0cb2dca..e636b27a329 100755
--- a/apps/maarch_entreprise/xml/entreprise.xml
+++ b/apps/maarch_entreprise/xml/entreprise.xml
@@ -33,6 +33,10 @@
             <id>outgoing_mail</id>
             <label>_OUTGOING_MAIL</label>
         </type>
+        <type show="true" with_chrono="true" icon="" sign="false">
+            <id>summary_sheet</id>
+            <label>_SUMMARY_SHEET</label>
+        </type>
     </attachment_types>
     <contact_check>
         <check_days_before>5</check_days_before>  <!-- 0 if you want to disabled -->
diff --git a/src/app/resource/controllers/SummarySheetController.php b/src/app/resource/controllers/SummarySheetController.php
index 3834a035784..df85beb1666 100755
--- a/src/app/resource/controllers/SummarySheetController.php
+++ b/src/app/resource/controllers/SummarySheetController.php
@@ -165,6 +165,11 @@ class SummarySheetController
         $finfo    = new \finfo(FILEINFO_MIME_TYPE);
         $mimeType = $finfo->buffer($fileContent);
 
+        $queryParams = $request->getQueryParams();
+        if (!empty($queryParams['mode']) && $queryParams['mode'] == 'base64') {
+            return $response->withJson(['encodedDocument' => base64_encode($fileContent), 'mimeType' => $mimeType]);
+        }
+
         $response->write($fileContent);
         $response = $response->withAddedHeader('Content-Disposition', "inline; filename=maarch.pdf");
 
diff --git a/src/frontend/app/process/process.component.html b/src/frontend/app/process/process.component.html
index b962b1e79e8..a22cf5443e9 100644
--- a/src/frontend/app/process/process.component.html
+++ b/src/frontend/app/process/process.component.html
@@ -86,7 +86,7 @@
                     [resId]="currentResourceInformations.resId" [expanded]="true">
                 </app-diffusions-list>
                 <app-sent-resource-list *ngIf="currentTool === 'emails' && !loading" #appSentResource
-                    [resId]="currentResourceInformations.resId"
+                    [resId]="currentResourceInformations.resId" [currentUserId]="currentUserId" [currentGroupId]="currentGroupId" [currentBasketId]="currentBasketId"
                     (reloadBadgeSentResource)="refreshBadge($event,'emails')">
                 </app-sent-resource-list>
                 <app-visa-workflow *ngIf="currentTool === 'visaCircuit' && !loading" #appVisaWorkflow
@@ -330,4 +330,4 @@
         class="panel-right" style="overflow-x:hidden;" [class.docView]="!filtersListService.filterMode"
         [ngStyle]="{'width': appService.getViewMode() ? '80%' : '30%'}" autoFocus="false">
     </mat-sidenav>
-</mat-sidenav-container>
\ No newline at end of file
+</mat-sidenav-container>
diff --git a/src/frontend/app/sentResource/sent-resource-list.component.ts b/src/frontend/app/sentResource/sent-resource-list.component.ts
index 63cfa8e0c36..69a3dc65bcf 100644
--- a/src/frontend/app/sentResource/sent-resource-list.component.ts
+++ b/src/frontend/app/sentResource/sent-resource-list.component.ts
@@ -2,7 +2,7 @@ import {Component, OnInit, ViewChild, EventEmitter, Input, Output} from '@angula
 import { HttpClient } from '@angular/common/http';
 import { TranslateService } from '@ngx-translate/core';
 import { NotificationService } from '../../service/notification/notification.service';
-import { of } from 'rxjs';
+import { of } from 'rxjs/internal/observable/of';
 import { MatDialog } from '@angular/material/dialog';
 import { MatSort } from '@angular/material/sort';
 import { MatTableDataSource } from '@angular/material/table';
@@ -14,12 +14,11 @@ import { SentNumericPackagePageComponent } from './sent-numeric-package-page/sen
 
 @Component({
     selector: 'app-sent-resource-list',
-    templateUrl: "sent-resource-list.component.html",
+    templateUrl: 'sent-resource-list.component.html',
     styleUrls: ['sent-resource-list.component.scss'],
 })
 export class SentResourceListComponent implements OnInit {
 
-    
     loading: boolean = true;
 
     dataSource: any;
@@ -34,6 +33,9 @@ export class SentResourceListComponent implements OnInit {
 
 
     @Input('resId') resId: number = null;
+    @Input() currentUserId: number = null;
+    @Input() currentGroupId: number = null;
+    @Input() currentBasketId: number = null;
 
     @Output() reloadBadgeSentResource = new EventEmitter<string>();
 
@@ -267,7 +269,11 @@ export class SentResourceListComponent implements OnInit {
         }
 
         if (row.canManage || row.id === null) {
-            const dialogRef = this.dialog.open(SentResourcePageComponent, { panelClass: 'maarch-modal', width:'60vw', disableClose: true, data: { title: title, resId: this.resId, emailId: row.id, emailType: row.type } });
+            const dialogRef = this.dialog.open(SentResourcePageComponent, {
+                panelClass: 'maarch-modal', width: '60vw', disableClose: true, data: {
+                    title: title, resId: this.resId, emailId: row.id, emailType: row.type, currentUserId: this.currentUserId, currentGroupId: this.currentGroupId, currentBasketId: this.currentBasketId
+                }
+            });
 
             dialogRef.afterClosed().pipe(
                 filter((data: any) => data.state === 'success' || data === 'success'),
diff --git a/src/frontend/app/sentResource/sent-resource-page/sent-resource-page.component.html b/src/frontend/app/sentResource/sent-resource-page/sent-resource-page.component.html
index d6f7c84f8fd..72b1362a4b8 100644
--- a/src/frontend/app/sentResource/sent-resource-page/sent-resource-page.component.html
+++ b/src/frontend/app/sentResource/sent-resource-page/sent-resource-page.component.html
@@ -102,9 +102,9 @@
             <input matInput [placeholder]="this.translate.instant('lang.object')" [readonly]="!canManageMail()" [(ngModel)]="emailsubject"
                 maxlength="255">
             <button mat-icon-button matSuffix *ngFor="let keyVal of emailAttachTool | keyvalue"
-                [disabled]="!canManageMail() || (emailAttachTool[keyVal.key].list.length === 0)"
+                [disabled]="!canManageMail() || (emailAttachTool[keyVal.key].list.length === 0 && keyVal.key !== 'summarySheet')"
                 [title]="emailAttachTool[keyVal.key].title"
-                (click)="$event.stopPropagation();currentEmailAttachTool=keyVal.key;"
+                (click)="$event.stopPropagation();currentEmailAttachTool=keyVal.key;openSummarySheetModal(keyVal.key)"
                 [matMenuTriggerFor]="emailAttachListMenu">
                 <mat-icon class="{{emailAttachTool[keyVal.key].icon}}"
                     [class.activeButton]="(keyVal.key === 'document' && emailAttach.document.isLinked) || (keyVal.key !== 'document' && emailAttach[keyVal.key].length > 0)"
diff --git a/src/frontend/app/sentResource/sent-resource-page/sent-resource-page.component.ts b/src/frontend/app/sentResource/sent-resource-page/sent-resource-page.component.ts
index a60a79a0221..45bb1f4a2f8 100644
--- a/src/frontend/app/sentResource/sent-resource-page/sent-resource-page.component.ts
+++ b/src/frontend/app/sentResource/sent-resource-page/sent-resource-page.component.ts
@@ -16,6 +16,7 @@ import { PrivilegeService } from '../../../service/privileges.service';
 import { HeaderService } from '../../../service/header.service';
 import { Observable } from 'rxjs/internal/Observable';
 import { of } from 'rxjs/internal/observable/of';
+import { SummarySheetComponent } from '../../list/summarySheet/summary-sheet.component';
 
 declare var $: any;
 declare var tinymce: any;
@@ -28,7 +29,6 @@ declare var tinymce: any;
 })
 export class SentResourcePageComponent implements OnInit {
 
-    
     loading: boolean = true;
 
     readonly separatorKeysCodes: number[] = [COMMA, SEMICOLON, FF_SEMICOLON, 190];
@@ -78,9 +78,17 @@ export class SentResourcePageComponent implements OnInit {
             title: this.translate.instant('lang.attachAttachment'),
             list: []
         },
+        summarySheet: {
+            icon: 'fa fa-link',
+            title: this.translate.instant('lang.attachSummarySheet'),
+            list: []
+        },
     };
     emailAttach: any = {};
 
+    encodedSummarySheet: any = null;
+    summarySheetUnits: any = [];
+
     canManage: boolean = false;
     pdfMode: boolean = false;
     htmlMode: boolean = true;
@@ -368,12 +376,14 @@ export class SentResourcePageComponent implements OnInit {
                             });
                         } else if (element === 'isLinked' && data.document.isLinked === true) {
                             this.emailAttach.document.isLinked = true;
-                            this.emailAttach.document.format = data.document.original || data.document.original === undefined ? this.emailAttachTool.document.list[0].format : 'pdf',
-                                this.emailAttach.document.original = data.document.original;
+                            this.emailAttach.document.format = data.document.original || data.document.original === undefined ? this.emailAttachTool.document.list[0].format : 'pdf';
+                            this.emailAttach.document.original = data.document.original;
                             this.emailAttach.document.size = this.emailAttach.document.original ? this.emailAttachTool.document.list[0].size : this.emailAttachTool.document.list[0].convertedDocument.size;
                         }
                     });
 
+                    console.log(this.emailAttach);
+
                     resolve(true);
                 }),
                 catchError((err) => {
@@ -594,8 +604,13 @@ export class SentResourcePageComponent implements OnInit {
         this.filteredEmails = of([]);
     }
 
-    onSubmit() {
+    async onSubmit() {
         this.emailStatus = 'WAITING';
+
+        if (this.summarySheetUnits !== null) {
+            await this.createSummarySheet();
+        }
+
         if (this.data.emailId === null) {
             if (!this.isAllEmailRightFormat()) {
                 this.notify.error(this.translate.instant('lang.badEmailsFormat'));
@@ -716,8 +731,8 @@ export class SentResourcePageComponent implements OnInit {
         if (type === 'document') {
             if (this.emailAttach.document.isLinked === false) {
                 this.emailAttach.document.isLinked = true;
-                this.emailAttach.document.format = mode !== 'pdf' ? item.format : 'pdf',
-                    this.emailAttach.document.original = mode !== 'pdf';
+                this.emailAttach.document.format = mode !== 'pdf' ? item.format : 'pdf';
+                this.emailAttach.document.original = mode !== 'pdf';
                 this.emailAttach.document.size = mode === 'pdf' ? item.convertedDocument.size : item.size;
             }
         } else {
@@ -872,4 +887,117 @@ export class SentResourcePageComponent implements OnInit {
             });
         }
     }
+
+    openSummarySheetModal(keyVal: any): void {
+        if (keyVal !== 'summarySheet') {
+            return;
+        }
+        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;
+        const title = this.translate.instant('lang.summarySheet') + ' ' + today;
+
+        const dialogRef = this.dialog.open(SummarySheetComponent, {
+            panelClass: 'maarch-full-height-modal',
+            width: '800px',
+            data: {
+                paramMode: true
+            }
+        });
+        dialogRef.afterClosed().pipe(
+            tap((data: any) => {
+                this.summarySheetUnits = data;
+                this.emailAttach['summarySheet'].push({
+                    label: title,
+                    format: 'pdf',
+                    title: title
+                });
+            }),
+            catchError((err: any) => {
+                this.notify.handleSoftErrors(err);
+                return of(false);
+            })
+        ).subscribe();
+    }
+
+    async createSummarySheet() {
+        return new Promise(resolve => {
+            this.http.post('../rest/resourcesList/users/' + this.data.currentUserId + '/groups/' + this.data.currentGroupId + '/baskets/' + this.data.currentBasketId + '/summarySheets?mode=base64', {
+                units:     this.summarySheetUnits,
+                resources: [this.data.resId]
+            })
+                .pipe(
+                    tap(async (sheetData: any) => {
+                        await this.saveSummarySheet(sheetData.encodedDocument);
+
+                        this.loading = false;
+                        resolve(true);
+                    }),
+                    catchError((err) => {
+                        this.notify.handleErrors(err);
+                        resolve(false);
+                        return of(false);
+                    })
+                ).subscribe();
+        });
+    }
+
+    async saveSummarySheet(encodedDocument: any) {
+        return new Promise(resolve => {
+            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;
+            const title = this.translate.instant('lang.summarySheet') + ' ' + today;
+            this.http.post('../rest/attachments', {resIdMaster: this.data.resId, encodedFile: encodedDocument, type: 'summary_sheet', format: 'PDF', title: title})
+            .pipe(
+                tap((dataAttachment: any) => {
+                    this.emailAttach['summarySheet'] = undefined;
+
+                    this.emailAttach['attachments'].push({
+                        id:       dataAttachment.id,
+                        label:    title,
+                        format:   'pdf',
+                        title:    title,
+                        original: true
+                    });
+                    this.loading = false;
+                    resolve(true);
+                }),
+                catchError((err) => {
+                    this.notify.handleErrors(err);
+                    resolve(false);
+                    return of(false);
+                })
+            )
+            .subscribe();
+        });
+    }
 }
-- 
GitLab