Newer
Older
import { DatePipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core';
import { Route, Router } from '@angular/router';
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) => {
this.filesToUpload.push({
title: data.document.title,
reference: '',
mainDocument: true,
content: '',
linkId: data.document.linkId,
metadata: data.document.metadata,
70
71
72
73
74
75
76
77
78
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
});
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'),
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
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: 'Enregistrement ...',
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('Document(s) importé(s)');
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) => {
formattedObj.push({
title: file.title,
reference: this.datePipe.transform(today, 'y/MM/dd') + '/' + file.reference,
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: this.fromDocument !== null ? file.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++) {
let file = {
title: fileInput.target.files[index].name,

Alex ORLUC
committed
reference: fileInput.target.files[index].name,
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('Seul des fichiers pdf sont autorisés');
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,
'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('Veuillez paramétrer votre circuit avant de pouvoir positionner les signatures.');
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;
}
}