Newer
Older
import { DatePipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core';
import { AlertController, LoadingController, MenuController, ModalController } from '@ionic/angular';
import { TranslateService } from '@ngx-translate/core';
import { of } from 'rxjs';
import { catchError, finalize, tap } from 'rxjs/operators';
import { VisaWorkflowComponent } from '../document/visa-workflow/visa-workflow.component';
import { AuthService } from '../service/auth.service';
import { NotificationService } from '../service/notification.service';
import { SignaturesContentService } from '../service/signatures.service';
import { SignaturePositionComponent } from './signature-position/signature-position.component';
@Component({
templateUrl: 'indexation.component.html',
styleUrls: ['indexation.component.scss'],
})
export class IndexationComponent implements OnInit {
loading: boolean = false;
fromDocument: number = null;
@ViewChild('appVisaWorkflow', { static: false }) appVisaWorkflow: VisaWorkflowComponent;
@ViewChild('rightContent', { static: true }) rightContent: TemplateRef<any>;
constructor(
private translate: TranslateService,
private menu: MenuController,
public signaturesService: SignaturesContentService,
public viewContainerRef: ViewContainerRef,
public notificationService: NotificationService,
public loadingController: LoadingController,
public alertController: AlertController,
public datePipe: DatePipe,
public modalController: ModalController

Alex ORLUC
committed
ngOnInit(): void { }
ionViewWillEnter() {
this.menu.enable(true, 'left-menu');
this.menu.enable(true, 'right-menu');
this.signaturesService.initTemplate(this.rightContent, this.viewContainerRef, 'rightContent');
if (window.history.state.documentId !== undefined) {
this.fromDocument = window.history.state.documentId;
this.getDocumentData(this.fromDocument);
}
}
getDocumentData(resId: number) {
return new Promise((resolve) => {
this.http.get(`../rest/documents/${resId}`).pipe(
tap((data: any) => {
let ref = '';
let arrRef = data.document.reference.split('/');
arrRef = arrRef.slice(3, arrRef.length);
if (arrRef.length > 0) {
ref = arrRef.join('/');
}
this.filesToUpload.push({
title: data.document.title,
mainDocument: true,
content: '',
linkId: data.document.linkId,
metadata: data.document.metadata,
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
});
this.getDocumentContent(resId);
this.appVisaWorkflow.loadWorkflow(data.document.workflow.map((item: any) => {
item.userSignatureModes.unshift('visa');
return {
...item,
'processDate': null,
'current': false,
'role': item.mode === 'visa' ? 'visa' : item.signatureMode,
'modes': item.userSignatureModes
};
}));
for (let index = 0; index < data.document.attachments.length; index++) {
this.getAttachment(data.document.attachments[index].id);
}
resolve(true);
}),
catchError((err: any) => {
this.notificationService.handleErrors(err);
return of(false);
})
).subscribe();
});
}
getDocumentContent(resId: number) {
return new Promise((resolve) => {
this.http.get(`../rest/documents/${resId}/content`).pipe(
tap((data: any) => {
this.filesToUpload[0].content = data.encodedDocument;
resolve(true);
}),
catchError((err: any) => {
this.notificationService.handleErrors(err);
return of(false);
})
).subscribe();
});
}
getAttachment(attachId: number) {
return new Promise((resolve) => {
this.http.get(`../rest/attachments/${attachId}`).pipe(
tap((data: any) => {
this.filesToUpload.push({
title: data.attachment.title,
mainDocument: false,
content: data.attachment.encodedDocument
});
resolve(true);
}),
catchError((err: any) => {
this.notificationService.handleErrors(err);
return of(false);
})
).subscribe();
});
}
ionViewWillLeave() {
this.signaturesService.detachTemplate('rightContent');
}
async promptSaveDoc() {
const alert = await this.alertController.create({

Alex ORLUC
committed
cssClass: 'alert-info-no-msg',
header: this.translate.instant('lang.areYouSure'),
inputs: [
{
name: 'note',
id: 'note',
type: 'textarea',
placeholder: this.translate.instant('lang.addNote')
},
],
buttons: [
{
text: this.translate.instant('lang.cancel'),
role: 'cancel',
cssClass: 'secondary',
handler: () => { }
},
{
text: this.translate.instant('lang.validate'),
handler: (data: any) => {
this.loadingController.create({
message: this.translate.instant('lang.processing'),
spinner: 'dots'
}).then(async (load: HTMLIonLoadingElement) => {
load.present();
const objTosend = this.formatData(data.note);
for (let index = 0; index < objTosend.length; index++) {
await this.saveDocument(objTosend[index], index);
}
load.dismiss();
if (this.errors.length === 0) {
this.notificationService.success('lang.documentsImported');
this.router.navigate(['/home']);
}
});
}
}
]
});
await alert.present();
}
saveDocument(data: any, index: number) {
return new Promise((resolve) => {
this.http.post('../rest/documents', data).pipe(
tap(() => {
}),
finalize(() => resolve(true)),
catchError((err: any) => {
this.errors.push(data.title);
this.notificationService.handleErrors(err);
return of(false);
})
).subscribe();
});
}
formatData(note: string) {

Alex ORLUC
committed
const today: Date = new Date();
let noteObj: any = null;

Alex ORLUC
committed
let linkId: string = null;
if (note !== '') {
noteObj = {
value: note,
creator: `${this.authService.user.firstname} ${this.authService.user.lastname}`,
creationDate: this.datePipe.transform(today, 'dd-MM-y')

Alex ORLUC
committed
const formattedObj: any[] = [];
const signedFiles = this.filesToUpload.filter((item: any) => item.mainDocument);
const attachFiles = this.filesToUpload.filter((item: any) => !item.mainDocument);

Alex ORLUC
committed
if (signedFiles.length > 1) {
linkId = this.datePipe.transform(today, 'ddMMYhmmss') + '_' + Math.random().toString(36).substr(2, 9);
}
signedFiles.forEach((file: any) => {
const metadata = {};
if (this.fromDocument !== null) {
file.metadata.forEach((element: any) => {
metadata[element.label] = element.value;
});
}

Florian Azizian
committed
let formattedReference = '';
if (file.reference !== '') {
formattedReference = this.datePipe.transform(today, 'y/MM/dd') + '/' + file.reference;
}
formattedObj.push({
title: file.title,

Florian Azizian
committed
reference: formattedReference,
linkId: this.fromDocument !== null ? file.linkId : linkId,
sender: `${this.authService.user.firstname} ${this.authService.user.lastname}`,
attachments: attachFiles.map((item: any) => {
return {
title: item.title,
encodedDocument: item.content
};
}),
workflow: this.appVisaWorkflow.getCurrentWorkflow().map((item: any, index: number) => {
return {
userId: item.userId,
mode: this.authService.getWorkflowMode(item.role),
signatureMode: this.authService.getSignatureMode(item.role),
signaturePositions: file.signPos !== undefined ? file.signPos.filter((userItem: any) => userItem.sequence === index).map((item: any) => {
return {
page: item.page,
positionX: item.position.positionX,
positionY: item.position.positionY,
};
}) : []
metadata: metadata
});
});
return formattedObj;
}
dndUploadFile(event: any) {
const fileInput = {
target: {
files: [
event[0]
]
}
};
this.uploadTrigger(fileInput);
}
uploadTrigger(fileInput: any) {
if (fileInput.target.files && fileInput.target.files[0] && this.isExtensionAllowed(fileInput.target.files)) {
for (let index = 0; index < fileInput.target.files.length; index++) {

Florian Azizian
committed
let filename = fileInput.target.files[index].name;

Florian Azizian
committed
title: filename.substr(0, filename.lastIndexOf('.')),
reference: filename.substr(0, filename.lastIndexOf('.')),
mainDocument: true,
content: ''
};
const reader = new FileReader();
reader.readAsArrayBuffer(fileInput.target.files[index]);
reader.onload = (value: any) => {
file.mainDocument = this.filesToUpload.length === 0;

Alex ORLUC
committed
file.reference = this.filesToUpload.length === 0 ? file.reference : '',
file.content = this.getBase64Document(value.target.result);
if (this.filesToUpload.length === 1) {
setTimeout(() => {
this.menu.open('right-menu');
}, 500);
}
};
}
} else {
this.loading = false;
}
}
isExtensionAllowed(files: any[]) {
for (let index = 0; index < files.length; index++) {
if (files[index].name.toLowerCase().split('.').pop() !== 'pdf') {
this.notificationService.error('lang.onlyPdfAuthorized');
return false;
}
}
return true;
}
getBase64Document(buffer: ArrayBuffer) {
const TYPED_ARRAY = new Uint8Array(buffer);
const STRING_CHAR = TYPED_ARRAY.reduce((data, byte) => {
return data + String.fromCharCode(byte);
}, '');
return btoa(STRING_CHAR);
}
deleteFile(index: number) {
this.filesToUpload.splice(index, 1);
}
async signPos(index: number) {
if (this.appVisaWorkflow.getCurrentWorkflow().length > 0) {
const modal = await this.modalController.create({
component: SignaturePositionComponent,
cssClass: 'custom-alert-fullscreen',
componentProps: {
'workflow': this.appVisaWorkflow.getCurrentWorkflow().map((item: any) => {
return {
userDisplay: item.userDisplay,
mode: this.authService.getWorkflowMode(item.role),
};
}),
'signPos': this.filesToUpload[index].signPos,
'pdfTitle': this.filesToUpload[index].title,
'pdfContent': 'data:application/pdf;base64,' + this.filesToUpload[index].content,
}
});
await modal.present();
const { data } = await modal.onWillDismiss();
console.log(data);
if (data !== undefined) {
this.filesToUpload[index].signPos = data;
}
} else {
this.notificationService.error('lang.mustSetWorkflowBeforeSignPositions');
if (this.filesToUpload.filter((item: any) => item.title === '').length > 0) {
this.notificationService.error('lang.subjectMandatory');
return false;
} else if (this.filesToUpload.filter((item: any) => item.mainDocument).length === 0) {
this.notificationService.error('lang.mainDocumentMandatory');
return false;
} else if (this.appVisaWorkflow.getCurrentWorkflow().length === 0) {
this.notificationService.error('lang.workflowUserstMandatory');
this.menu.open('right-menu');
return false;
} else {
return true;
}
}