From cb3a7062ec1adf86397c478e64d0803b7e710ae3 Mon Sep 17 00:00:00 2001
From: Alex ORLUC <alex.orluc@maarch.org>
Date: Mon, 23 Mar 2020 14:50:39 +0100
Subject: [PATCH] FEAT #13581 TIME 3 add save tmp file button in onlyoffice +
 fix multi pj create (disable tab when editing)

---
 .../controllers/ConvertPdfController.php      |  2 +-
 .../attachment-create.component.html          | 10 +--
 .../attachment-create.component.ts            | 82 +++++++++++++------
 .../app/viewer/document-viewer.component.html |  5 ++
 .../app/viewer/document-viewer.component.ts   | 54 +++++++++++-
 5 files changed, 120 insertions(+), 33 deletions(-)

diff --git a/src/app/convert/controllers/ConvertPdfController.php b/src/app/convert/controllers/ConvertPdfController.php
index f9d30f40440..86c33dc0a1a 100755
--- a/src/app/convert/controllers/ConvertPdfController.php
+++ b/src/app/convert/controllers/ConvertPdfController.php
@@ -326,7 +326,7 @@ class ConvertPdfController
         return $response->withJson($encodedFiles);
     }
 
-    public function getConvertedFileWithEncodedFile(Request $request, Response $response)
+    public function getConvertedFileFromEncodedFile(Request $request, Response $response)
     {
         $body = $request->getParsedBody();
 
diff --git a/src/frontend/app/attachments/attachment-create/attachment-create.component.html b/src/frontend/app/attachments/attachment-create/attachment-create.component.html
index 4875ab79ac4..93c59177739 100644
--- a/src/frontend/app/attachments/attachment-create/attachment-create.component.html
+++ b/src/frontend/app/attachments/attachment-create/attachment-create.component.html
@@ -13,7 +13,7 @@
         <div *ngIf="loading" class="loading">
             <mat-spinner style="margin:auto;"></mat-spinner>
         </div>
-        <mat-tab-group #pjList style="width: 100%;" [(selectedIndex)]="indexTab" *ngIf="!loading">
+        <mat-tab-group #pjList style="width: 100%;" [(selectedIndex)]="indexTab" (selectedIndexChange)="test($event)" *ngIf="!loading">
             <mat-tab *ngFor="let attachment of attachments; let i=index" [disabled]="isDocLoading()">
                 <ng-template mat-tab-label>
                     <span [class.complete]="isPjValid(i)">PJ n°{{i+1}}&nbsp;<i *ngIf="isPjValid(i)"
@@ -118,7 +118,7 @@
             </mat-tab>
             <mat-tab disabled class="addPJ">
                 <ng-template mat-tab-label>
-                    <span><button mat-icon-button [disabled]="sendMassMode" [title]="lang.newAttachment"
+                    <span><button mat-icon-button [disabled]="sendMassMode || isDocLoading()" [title]="lang.newAttachment"
                             (click)="$event.stopPropagation();newPj()">
                             <mat-icon class="fa fa-plus"></mat-icon>
                         </button></span>
@@ -128,10 +128,10 @@
     </mat-dialog-content>
     <div mat-dialog-actions class="actions">
         <button mat-raised-button color="primary" *ngIf="creationMode && !loading" (click)="onSubmit()"
-            [disabled]="isDocLoading()">{{lang.validate}}</button>
+            [disabled]="canValidatePj()">{{lang.validate}}</button>
         <button mat-raised-button color="primary" *ngIf="sendMassMode && !loading" (click)="onSubmit('mailing')"
-            [disabled]="isDocLoading()">{{lang.mailing}}</button>
-        <button mat-raised-button mat-button *ngIf="creationMode && !loading" [disabled]="isDocLoading()"
+            [disabled]="canValidatePj()">{{lang.mailing}}</button>
+        <button mat-raised-button mat-button *ngIf="creationMode && !loading" [disabled]="canValidatePj()"
             [mat-dialog-close]="">{{lang.cancel}}</button>
     </div>
 </div>
\ No newline at end of file
diff --git a/src/frontend/app/attachments/attachment-create/attachment-create.component.ts b/src/frontend/app/attachments/attachment-create/attachment-create.component.ts
index 6f5cf737309..4259e1780e6 100644
--- a/src/frontend/app/attachments/attachment-create/attachment-create.component.ts
+++ b/src/frontend/app/attachments/attachment-create/attachment-create.component.ts
@@ -1,7 +1,7 @@
-import { Component, OnInit, Input, Inject, ViewChildren, QueryList} from '@angular/core';
+import { Component, OnInit, Input, Inject, ViewChildren, QueryList } from '@angular/core';
 import { HttpClient } from '@angular/common/http';
 import { LANG } from '../../translate.component';
-import {catchError, tap, filter, distinctUntilChanged} from 'rxjs/operators';
+import { catchError, tap, filter, distinctUntilChanged, take } from 'rxjs/operators';
 import { of } from 'rxjs';
 import { NotificationService } from '../../notification.service';
 import { MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
@@ -43,6 +43,9 @@ export class AttachmentCreateComponent implements OnInit {
 
     now: Date = new Date();
 
+    // To catch previous index to update file
+    asyncIndexTab: number = 0;
+    
     indexTab: number = 0;
 
     resourceContacts: any[] = [];
@@ -138,7 +141,7 @@ export class AttachmentCreateComponent implements OnInit {
                             this.toggleSendMass();
                         }
                     } else {
-                        if (!this.functions.empty(data.senders) &&  data.senders.length > 1) {
+                        if (!this.functions.empty(data.senders) && data.senders.length > 1) {
                             this.toggleSendMass();
                         }
                     }
@@ -321,12 +324,15 @@ export class AttachmentCreateComponent implements OnInit {
     isValid() {
         let state = true;
         this.attachFormGroup.forEach(formgroup => {
-            if (formgroup.status === 'INVALID') {
-                state = false;
-            }
             Object.keys(formgroup.controls).forEach(key => {
                 formgroup.controls[key].markAsTouched();
             });
+            console.log(formgroup.controls);
+
+            if (formgroup.status === 'INVALID') {
+                state = false;
+            }
+
         });
         return state;
     }
@@ -340,6 +346,16 @@ export class AttachmentCreateComponent implements OnInit {
     }
 
     isDocLoading() {
+        let state = false;
+        this.appDocumentViewer.toArray().forEach((app, index: number) => {
+            if (app.isEditingTemplate()) {
+                state = true;
+            }
+        });
+        return state;
+    }
+
+    canValidatePj() {
         let state = false;
         this.appDocumentViewer.toArray().forEach((app, index: number) => {
             if (app.isEditingTemplate() && app.editor.async) {
@@ -369,27 +385,40 @@ export class AttachmentCreateComponent implements OnInit {
     }
 
     newPj() {
+        this.attachments.push({
+            title: new FormControl({ value: '', disabled: false }, [Validators.required]),
+            recipient: new FormControl({ value: !this.functions.empty(this.resourceContacts[this.attachments.length]) ? [{ id: this.resourceContacts[this.attachments.length].id, type: this.resourceContacts[this.attachments.length].type }] : null, disabled: false }),
+            type: new FormControl({ value: 'response_project', disabled: false }, [Validators.required]),
+            validationDate: new FormControl({ value: null, disabled: false }),
+            encodedFile: new FormControl({ value: '', disabled: false }, [Validators.required]),
+            format: new FormControl({ value: '', disabled: false }, [Validators.required])
+        });
+        this.attachFormGroup.push(new FormGroup(this.attachments[this.attachments.length - 1]));
+        this.indexTab = this.attachments.length - 1;
+        setTimeout(() => {
+            this.getAttachType('response_project', this.indexTab);
+        }, 800);
+    }
+
+    updateFile(index: number) {
+        if (this.functions.empty(this.attachments[this.asyncIndexTab].encodedFile.value)) {
+            console.log('ca passe!');
+            
+            this.appDocumentViewer.toArray()[this.asyncIndexTab].getFile().pipe(
+                take(1),
+                tap((data) => {
+                    console.log(data);
+                    
+                    this.attachments[this.asyncIndexTab].encodedFile.setValue(data.content);
+                    this.attachments[this.asyncIndexTab].format.setValue(data.format);
+                    this.asyncIndexTab = index;
+                }),
+            ).subscribe();
+        } else {
+            this.asyncIndexTab = index;
+        }
+
 
-        this.appDocumentViewer.toArray()[this.indexTab].getFile().pipe(
-            tap((data) => {
-                this.attachments[this.indexTab].encodedFile.setValue(data.content);
-                this.attachments[this.indexTab].format.setValue(data.format);
-                this.attachments.push({
-                    title: new FormControl({ value: '', disabled: false }, [Validators.required]),
-                    recipient: new FormControl({ value: !this.functions.empty(this.resourceContacts[this.attachments.length]) ? [{ id: this.resourceContacts[this.attachments.length].id, type: this.resourceContacts[this.attachments.length].type }] : null, disabled: false }),
-                    type: new FormControl({ value: 'response_project', disabled: false }, [Validators.required]),
-                    validationDate: new FormControl({ value: null, disabled: false }),
-                    encodedFile: new FormControl({ value: '', disabled: false }, [Validators.required]),
-                    format: new FormControl({ value: '', disabled: false }, [Validators.required])
-                });
-
-                this.attachFormGroup.push(new FormGroup(this.attachments[this.attachments.length - 1]));
-                this.indexTab = this.attachments.length - 1;
-                setTimeout(() => {
-                    this.getAttachType('response_project', this.indexTab);
-                }, 800);
-            }),
-        ).subscribe();
 
     }
 
@@ -400,6 +429,7 @@ export class AttachmentCreateComponent implements OnInit {
             filter((data: string) => data === 'ok'),
             tap(() => {
                 this.indexTab = 0;
+                this.asyncIndexTab = this.indexTab;
                 this.attachments.splice(i, 1);
                 this.attachFormGroup.splice(i, 1);
             }),
diff --git a/src/frontend/app/viewer/document-viewer.component.html b/src/frontend/app/viewer/document-viewer.component.html
index cf3c48eb823..246c82e5249 100644
--- a/src/frontend/app/viewer/document-viewer.component.html
+++ b/src/frontend/app/viewer/document-viewer.component.html
@@ -118,6 +118,11 @@
     (click)="saveMainDocument()">
     <mat-icon style="height:auto;font-size:20px;" class="fas fa-check"></mat-icon>
 </button>
+<button mat-fab *ngIf="isDocModified && mode === 'attachment'" color="accent"
+    [title]="lang.saveModifications" style="position: absolute;z-index: 3;bottom: 40px;right: 60px;"
+    (click)="saveTmpDocument()">
+    <mat-icon style="height:auto;font-size:20px;" class="fas fa-check"></mat-icon>
+</button>
 <button mat-raised-button 
     *ngIf="!isDocModified && mode === 'mainDocument' && resId !== null && !functions.empty(file.subinfos) && file.subinfos.signedDocVersions && (privilegeService.hasCurrentUserPrivilege('sign_document') || this.headerService.user.id == file.creatorId)" 
     color="warn"
diff --git a/src/frontend/app/viewer/document-viewer.component.ts b/src/frontend/app/viewer/document-viewer.component.ts
index f470bfb6231..35b38bf8c2d 100755
--- a/src/frontend/app/viewer/document-viewer.component.ts
+++ b/src/frontend/app/viewer/document-viewer.component.ts
@@ -152,7 +152,7 @@ export class DocumentViewerComponent implements OnInit {
             })
         ).subscribe();
 
-        if (this.base64 !== null) {
+        if (!this.functions.empty(this.base64)) {
             this.loadFileFromBase64();
         } else if (this.tmpFilename != '' && this.tmpFilename !== undefined) {
             this.http.get('../../rest/convertedFile/' + this.tmpFilename).pipe(
@@ -952,6 +952,58 @@ export class DocumentViewerComponent implements OnInit {
         });
     }
 
+    loadTmpDocument(base64Content: string, format: string) {
+        return new Promise((resolve, reject) => {
+            this.http.post(`../../rest/convertedFile/encodedFile`, { format: format, encodedFile : base64Content}).pipe(
+                tap((data: any) => {
+                    console.log(data);
+                    this.file = {
+                        name: 'maarch',
+                        format: format,
+                        type: 'application/pdf',
+                        contentMode: 'base64',
+                        content: base64Content,
+                        src: this.base64ToArrayBuffer(data.encodedResource)
+                    };
+                }),
+                //exhaustMap((data) => this.http.post(`../../rest/convertedFile/encodedFile`, data.content)),
+                catchError((err: any) => {
+                    this.notify.handleSoftErrors(err);
+                    resolve(false);
+                    return of(false);
+                })
+            ).subscribe();
+        });
+    }
+
+    saveTmpDocument() {
+        return new Promise((resolve, reject) => {
+            this.getFile().pipe(
+                tap((data: any) => {
+                    this.file = {
+                        name: 'maarch',
+                        format: data.format,
+                        type: 'application/pdf',
+                        contentMode: 'base64',
+                        content: data.content,
+                        src: null
+                    };
+                }),
+                exhaustMap((data) => this.http.post(`../../rest/convertedFile/encodedFile`, { format: data.format, encodedFile : data.content})),
+                tap((data: any) => {
+                    this.file.src = this.base64ToArrayBuffer(data.encodedResource);
+                    this.closeEditor();
+                    resolve(true);
+                }),
+                catchError((err: any) => {
+                    this.notify.handleSoftErrors(err);
+                    resolve(false);
+                    return of(false);
+                })
+            ).subscribe();
+        });
+    }
+
     openResourceVersion(version: number, type: string) {
 
         const title = type !== 'PDF' ? this.lang[type + '_version'] : `${this.lang.version} ${version}`;
-- 
GitLab