Compare commits
10 Commits
747328324a
...
0267892cdc
Author | SHA1 | Date | |
---|---|---|---|
![]() |
0267892cdc | ||
![]() |
0d443be163 | ||
![]() |
6f66a797da | ||
![]() |
28aa5e6c45 | ||
![]() |
1838f615fe | ||
![]() |
d5bc41660c | ||
![]() |
1fc9f1e73c | ||
![]() |
f46dae8954 | ||
![]() |
b00fb2a55a | ||
d3e13bd801 |
@ -32,6 +32,7 @@
|
|||||||
"jwt-decode": "^3.1.2",
|
"jwt-decode": "^3.1.2",
|
||||||
"le-coffre-resources": "file:../lecoffre-ressources",
|
"le-coffre-resources": "file:../lecoffre-ressources",
|
||||||
"next": "^14.2.3",
|
"next": "^14.2.3",
|
||||||
|
"pdf-lib": "^1.17.1",
|
||||||
"prettier": "^2.8.7",
|
"prettier": "^2.8.7",
|
||||||
"react": "18.2.0",
|
"react": "18.2.0",
|
||||||
"react-dom": "18.2.0",
|
"react-dom": "18.2.0",
|
||||||
|
@ -9,7 +9,7 @@ export default class DocumentTypeService {
|
|||||||
|
|
||||||
private constructor() { }
|
private constructor() { }
|
||||||
|
|
||||||
public static createDocumentType(documentData: any, validatorId: string): Promise<any> {
|
public static createDocumentType(documentTypeData: any, validatorId: string): Promise<any> {
|
||||||
const ownerId = User.getInstance().getPairingId()!;
|
const ownerId = User.getInstance().getPairingId()!;
|
||||||
|
|
||||||
const processData: any = {
|
const processData: any = {
|
||||||
@ -18,7 +18,7 @@ export default class DocumentTypeService {
|
|||||||
isDeleted: 'false',
|
isDeleted: 'false',
|
||||||
created_at: new Date().toISOString(),
|
created_at: new Date().toISOString(),
|
||||||
updated_at: new Date().toISOString(),
|
updated_at: new Date().toISOString(),
|
||||||
...documentData,
|
...documentTypeData,
|
||||||
};
|
};
|
||||||
|
|
||||||
const privateFields: string[] = Object.keys(processData);
|
const privateFields: string[] = Object.keys(processData);
|
||||||
|
@ -2,6 +2,7 @@ import { v4 as uuidv4 } from 'uuid';
|
|||||||
|
|
||||||
import MessageBus from 'src/sdk/MessageBus';
|
import MessageBus from 'src/sdk/MessageBus';
|
||||||
import User from 'src/sdk/User';
|
import User from 'src/sdk/User';
|
||||||
|
import { FileData } from '../../../../front/Api/Entities/types';
|
||||||
|
|
||||||
export default class FileService {
|
export default class FileService {
|
||||||
|
|
||||||
@ -9,7 +10,7 @@ export default class FileService {
|
|||||||
|
|
||||||
private constructor() { }
|
private constructor() { }
|
||||||
|
|
||||||
public static createFile(fileData: any, validatorId: string): Promise<any> {
|
public static createFile(fileData: FileData, validatorId: string): Promise<any> {
|
||||||
const ownerId = User.getInstance().getPairingId()!;
|
const ownerId = User.getInstance().getPairingId()!;
|
||||||
|
|
||||||
const processData: any = {
|
const processData: any = {
|
||||||
@ -81,7 +82,7 @@ export default class FileService {
|
|||||||
return this.messageBus.getFileByUid(uid);
|
return this.messageBus.getFileByUid(uid);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static updateFile(process: any, newData: any): Promise<void> {
|
public static updateFile(process: any, newData: Partial<FileData> & { isDeleted?: string }): Promise<void> {
|
||||||
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
|
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
|
||||||
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
||||||
const newStateId: string = processUpdated.diffs[0]?.state_id;
|
const newStateId: string = processUpdated.diffs[0]?.state_id;
|
||||||
|
2
src/front/Api/Entities/index.ts
Normal file
2
src/front/Api/Entities/index.ts
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
export * from './types';
|
||||||
|
export * from './rule';
|
21
src/front/Api/Entities/types.ts
Normal file
21
src/front/Api/Entities/types.ts
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
/**
|
||||||
|
* FileBlob interface representing a file's binary data and metadata
|
||||||
|
* Used for file transmission and storage in the application
|
||||||
|
*/
|
||||||
|
export interface FileBlob {
|
||||||
|
/** MIME type of the file (e.g., "application/pdf", "image/jpeg") */
|
||||||
|
type: string;
|
||||||
|
/** Binary data of the file as Uint8Array */
|
||||||
|
data: Uint8Array;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FileData interface representing a complete file object with blob and metadata
|
||||||
|
* Used when creating or updating files in the system
|
||||||
|
*/
|
||||||
|
export interface FileData {
|
||||||
|
/** The file blob containing type and binary data */
|
||||||
|
file_blob: FileBlob;
|
||||||
|
/** The name of the file */
|
||||||
|
file_name: string;
|
||||||
|
}
|
@ -213,9 +213,9 @@ export default function DragAndDrop(props: IProps) {
|
|||||||
</div>
|
</div>
|
||||||
{documentFiles.length > 0 && (
|
{documentFiles.length > 0 && (
|
||||||
<div className={classes["documents"]}>
|
<div className={classes["documents"]}>
|
||||||
{documentFiles.map((documentFile) => (
|
{documentFiles.map((documentFile, index) => (
|
||||||
<DocumentFileElement
|
<DocumentFileElement
|
||||||
key={documentFile.id}
|
key={documentFile.uid || `${documentFile.id}-${index}`}
|
||||||
isLoading={documentFile.isLoading}
|
isLoading={documentFile.isLoading}
|
||||||
file={documentFile.file}
|
file={documentFile.file}
|
||||||
onRemove={() => handleRemove(documentFile)}
|
onRemove={() => handleRemove(documentFile)}
|
||||||
|
@ -9,6 +9,8 @@ import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm";
|
|||||||
|
|
||||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||||
|
import { FileBlob, FileData } from "@Front/Api/Entities/types";
|
||||||
|
import WatermarkService from "@Front/Services/WatermarkService";
|
||||||
|
|
||||||
type IProps = {
|
type IProps = {
|
||||||
document: any;
|
document: any;
|
||||||
@ -30,50 +32,101 @@ export default function DepositDocumentComponent(props: IProps) {
|
|||||||
}, [document.files]);
|
}, [document.files]);
|
||||||
|
|
||||||
const addFile = useCallback(
|
const addFile = useCallback(
|
||||||
(file: File) => {
|
async (file: File) => {
|
||||||
return new Promise<void>(
|
try {
|
||||||
(resolve: () => void) => {
|
// Add watermark to the file before processing
|
||||||
const reader = new FileReader();
|
const watermarkedFile = await WatermarkService.getInstance().addWatermark(file);
|
||||||
reader.onload = (event) => {
|
|
||||||
if (event.target?.result) {
|
return new Promise<void>(
|
||||||
const arrayBuffer = event.target.result as ArrayBuffer;
|
(resolve: () => void) => {
|
||||||
const uint8Array = new Uint8Array(arrayBuffer);
|
const reader = new FileReader();
|
||||||
|
reader.onload = (event) => {
|
||||||
|
if (event.target?.result) {
|
||||||
|
const arrayBuffer = event.target.result as ArrayBuffer;
|
||||||
|
const uint8Array = new Uint8Array(arrayBuffer);
|
||||||
|
|
||||||
const fileBlob: any = {
|
const fileBlob: FileBlob = {
|
||||||
type: file.type,
|
type: watermarkedFile.type,
|
||||||
data: uint8Array
|
data: uint8Array
|
||||||
};
|
};
|
||||||
|
|
||||||
const fileData: any = {
|
const fileData: FileData = {
|
||||||
file_blob: fileBlob,
|
file_blob: fileBlob,
|
||||||
file_name: file.name
|
file_name: watermarkedFile.name
|
||||||
};
|
};
|
||||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||||
|
|
||||||
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
|
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
|
||||||
const fileUid: string = processCreated.processData.uid;
|
const fileUid: string = processCreated.processData.uid;
|
||||||
|
|
||||||
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
|
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
|
||||||
if (process) {
|
if (process) {
|
||||||
const document: any = process.processData;
|
const document: any = process.processData;
|
||||||
|
|
||||||
let files: any[] = document.files;
|
let files: any[] = document.files;
|
||||||
if (!files) {
|
if (!files) {
|
||||||
files = [];
|
files = [];
|
||||||
|
}
|
||||||
|
files.push({ uid: fileUid });
|
||||||
|
|
||||||
|
DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.DEPOSITED }).then(() => resolve());
|
||||||
}
|
}
|
||||||
files.push({ uid: fileUid });
|
});
|
||||||
|
|
||||||
DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.DEPOSITED }).then(() => resolve());
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
});
|
}
|
||||||
}
|
};
|
||||||
};
|
reader.readAsArrayBuffer(watermarkedFile);
|
||||||
reader.readAsArrayBuffer(file);
|
})
|
||||||
})
|
.then(onChange)
|
||||||
.then(onChange)
|
.then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier uploadé avec succès!" }))
|
||||||
.then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier uploadé avec succès!" }))
|
.catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message }));
|
||||||
.catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message }));
|
} catch (error) {
|
||||||
|
console.error('Error processing file with watermark:', error);
|
||||||
|
// If watermarking fails, proceed with original file
|
||||||
|
return new Promise<void>(
|
||||||
|
(resolve: () => void) => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = (event) => {
|
||||||
|
if (event.target?.result) {
|
||||||
|
const arrayBuffer = event.target.result as ArrayBuffer;
|
||||||
|
const uint8Array = new Uint8Array(arrayBuffer);
|
||||||
|
|
||||||
|
const fileBlob: FileBlob = {
|
||||||
|
type: file.type,
|
||||||
|
data: uint8Array
|
||||||
|
};
|
||||||
|
|
||||||
|
const fileData: FileData = {
|
||||||
|
file_blob: fileBlob,
|
||||||
|
file_name: file.name
|
||||||
|
};
|
||||||
|
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||||
|
|
||||||
|
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
|
||||||
|
const fileUid: string = processCreated.processData.uid;
|
||||||
|
|
||||||
|
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
|
||||||
|
if (process) {
|
||||||
|
const document: any = process.processData;
|
||||||
|
|
||||||
|
let files: any[] = document.files;
|
||||||
|
if (!files) {
|
||||||
|
files = [];
|
||||||
|
}
|
||||||
|
files.push({ uid: fileUid });
|
||||||
|
|
||||||
|
DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.DEPOSITED }).then(() => resolve());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.readAsArrayBuffer(file);
|
||||||
|
})
|
||||||
|
.then(onChange)
|
||||||
|
.then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier uploadé avec succès!" }))
|
||||||
|
.catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message }));
|
||||||
|
}
|
||||||
},
|
},
|
||||||
[document.uid, onChange],
|
[document.uid, onChange],
|
||||||
);
|
);
|
||||||
@ -82,9 +135,9 @@ export default function DepositDocumentComponent(props: IProps) {
|
|||||||
(fileUid: string) => {
|
(fileUid: string) => {
|
||||||
return new Promise<void>(
|
return new Promise<void>(
|
||||||
(resolve: () => void) => {
|
(resolve: () => void) => {
|
||||||
FileService.getFileByUid(fileUid).then((process: any) => {
|
FileService.getFileByUid(fileUid).then((res: any) => {
|
||||||
if (process) {
|
if (res) {
|
||||||
FileService.updateFile(process, { isDeleted: 'true' }).then(() => {
|
FileService.updateFile(res.processId, { isDeleted: 'true' }).then(() => {
|
||||||
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
|
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
|
||||||
if (process) {
|
if (process) {
|
||||||
const document: any = process.processData;
|
const document: any = process.processData;
|
||||||
|
@ -7,6 +7,7 @@ import { DocumentNotary } from "le-coffre-resources/dist/Notary";
|
|||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import { NextRouter, useRouter } from "next/router";
|
import { NextRouter, useRouter } from "next/router";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
|
import { FileBlob } from "@Front/Api/Entities/types";
|
||||||
|
|
||||||
import BasePage from "../../Base";
|
import BasePage from "../../Base";
|
||||||
import classes from "./classes.module.scss";
|
import classes from "./classes.module.scss";
|
||||||
@ -25,7 +26,7 @@ type IState = {
|
|||||||
isValidateModalVisible: boolean;
|
isValidateModalVisible: boolean;
|
||||||
refuseText: string;
|
refuseText: string;
|
||||||
selectedFileIndex: number;
|
selectedFileIndex: number;
|
||||||
selectedFile: any;
|
selectedFile: { uid: string; file_name: string; file_blob: FileBlob } | null;
|
||||||
documentNotary: DocumentNotary | null;
|
documentNotary: DocumentNotary | null;
|
||||||
fileBlob: Blob | null;
|
fileBlob: Blob | null;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
@ -132,7 +133,7 @@ class ViewDocumentsNotaryClass extends BasePage<IPropsClass, IState> {
|
|||||||
{
|
{
|
||||||
documentNotary,
|
documentNotary,
|
||||||
selectedFileIndex: 0,
|
selectedFileIndex: 0,
|
||||||
selectedFile: documentNotary.files![0]!,
|
selectedFile: documentNotary.files![0] as any,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
},
|
},
|
||||||
() => {
|
() => {
|
||||||
|
@ -141,7 +141,7 @@ export default function ClientDashboard(props: IProps) {
|
|||||||
let documents: any[] = processes.map((process: any) => process.processData);
|
let documents: any[] = processes.map((process: any) => process.processData);
|
||||||
|
|
||||||
// FilterBy folder_uid
|
// FilterBy folder_uid
|
||||||
documents = documents.filter((document: any) => document.folder.uid === folderUid);
|
documents = documents.filter((document: any) => document.folder.uid === folderUid && document.depositor);
|
||||||
|
|
||||||
for (const document of documents) {
|
for (const document of documents) {
|
||||||
document.document_type = (await DocumentTypeService.getDocumentTypeByUid(document.document_type.uid)).processData;
|
document.document_type = (await DocumentTypeService.getDocumentTypeByUid(document.document_type.uid)).processData;
|
||||||
|
@ -39,7 +39,7 @@ export default function DocumentTypesCreate(props: IProps) {
|
|||||||
});
|
});
|
||||||
await validateOrReject(documentFormModel, { groups: ["createDocumentType"] });
|
await validateOrReject(documentFormModel, { groups: ["createDocumentType"] });
|
||||||
|
|
||||||
const documentData: any = {
|
const documentTypeData: any = {
|
||||||
...values,
|
...values,
|
||||||
office: {
|
office: {
|
||||||
uid: officeId,
|
uid: officeId,
|
||||||
@ -48,7 +48,7 @@ export default function DocumentTypesCreate(props: IProps) {
|
|||||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||||
|
|
||||||
LoaderService.getInstance().show();
|
LoaderService.getInstance().show();
|
||||||
DocumentTypeService.createDocumentType(documentData, validatorId).then((processCreated: any) => {
|
DocumentTypeService.createDocumentType(documentTypeData, validatorId).then((processCreated: any) => {
|
||||||
ToasterService.getInstance().success({
|
ToasterService.getInstance().success({
|
||||||
title: "Succès !",
|
title: "Succès !",
|
||||||
description: "Type de document créé avec succès"
|
description: "Type de document créé avec succès"
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
import Deeds from "@Front/Api/LeCoffreApi/Notary/Deeds/Deeds";
|
|
||||||
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
|
|
||||||
import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption";
|
import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption";
|
||||||
import AutocompleteMultiSelectField from "@Front/Components/DesignSystem/Form/AutocompleteMultiSelectField";
|
import AutocompleteMultiSelectField from "@Front/Components/DesignSystem/Form/AutocompleteMultiSelectField";
|
||||||
import { IOption as IFormOption } from "@Front/Components/DesignSystem/Form/SelectFieldOld";
|
import { IOption as IFormOption } from "@Front/Components/DesignSystem/Form/SelectFieldOld";
|
||||||
@ -7,12 +5,14 @@ import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
|
|||||||
import TextField from "@Front/Components/DesignSystem/Form/TextField";
|
import TextField from "@Front/Components/DesignSystem/Form/TextField";
|
||||||
import Modal from "@Front/Components/DesignSystem/Modal";
|
import Modal from "@Front/Components/DesignSystem/Modal";
|
||||||
import RadioBox from "@Front/Components/DesignSystem/RadioBox";
|
import RadioBox from "@Front/Components/DesignSystem/RadioBox";
|
||||||
import { DocumentType, OfficeFolder } from "le-coffre-resources/dist/Notary";
|
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
|
||||||
import { ChangeEvent, useCallback, useEffect, useState } from "react";
|
import { ChangeEvent, useCallback, useEffect, useState } from "react";
|
||||||
|
|
||||||
import classes from "./classes.module.scss";
|
import classes from "./classes.module.scss";
|
||||||
|
|
||||||
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
|
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
|
||||||
|
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
|
||||||
|
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||||
|
|
||||||
type IProps = {
|
type IProps = {
|
||||||
isCreateDocumentModalVisible: boolean;
|
isCreateDocumentModalVisible: boolean;
|
||||||
@ -75,18 +75,38 @@ export default function ParameterDocuments(props: IProps) {
|
|||||||
const addDocument = useCallback(async () => {
|
const addDocument = useCallback(async () => {
|
||||||
if (addOrEditDocument === "add") {
|
if (addOrEditDocument === "add") {
|
||||||
try {
|
try {
|
||||||
const documentType = await DocumentTypes.getInstance().post({
|
LoaderService.getInstance().show();
|
||||||
|
|
||||||
|
const documentTypeData: any = {
|
||||||
name: documentName,
|
name: documentName,
|
||||||
private_description: visibleDescription,
|
private_description: visibleDescription,
|
||||||
office: {
|
office: {
|
||||||
uid: props.folder.office!.uid!,
|
uid: props.folder.office!.uid!,
|
||||||
},
|
},
|
||||||
public_description: visibleDescription,
|
public_description: visibleDescription,
|
||||||
|
};
|
||||||
|
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||||
|
|
||||||
|
const documentType: any = await new Promise<any>((resolve: (documentType: any) => void) => {
|
||||||
|
DocumentTypeService.createDocumentType(documentTypeData, validatorId).then((processCreated: any) => {
|
||||||
|
const documentType: any = processCreated.processData;
|
||||||
|
resolve(documentType);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const oldDocumentsType = props.folder.deed?.document_types!;
|
const oldDocumentsType = props.folder.deed?.document_types!;
|
||||||
await Deeds.getInstance().put(props.folder.deed?.uid!, {
|
|
||||||
document_types: [...oldDocumentsType, documentType],
|
await new Promise<void>((resolve: () => void) => {
|
||||||
|
DeedTypeService.getDeedTypeByUid(props.folder.deed?.deed_type?.uid!).then((process: any) => {
|
||||||
|
if (process) {
|
||||||
|
DeedTypeService.updateDeedType(process, {
|
||||||
|
document_types: [
|
||||||
|
...oldDocumentsType.map((document: any) => ({ uid: document.uid })),
|
||||||
|
{ uid: documentType.uid }
|
||||||
|
]
|
||||||
|
}).then(() => resolve());
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create a new document type in the format expected by the parent component
|
// Create a new document type in the format expected by the parent component
|
||||||
@ -100,28 +120,44 @@ export default function ParameterDocuments(props: IProps) {
|
|||||||
props.onDocumentsUpdated([newDocumentType]);
|
props.onDocumentsUpdated([newDocumentType]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
LoaderService.getInstance().hide();
|
||||||
handleClose();
|
handleClose();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
|
LoaderService.getInstance().show();
|
||||||
|
|
||||||
const oldDocumentsType = props.folder.deed?.document_types!;
|
const oldDocumentsType = props.folder.deed?.document_types!;
|
||||||
await Deeds.getInstance().put(props.folder.deed?.uid!, {
|
await new Promise<void>((resolve: () => void) => {
|
||||||
document_types: [
|
DeedTypeService.getDeedTypeByUid(props.folder.deed?.deed_type?.uid!).then((process: any) => {
|
||||||
...oldDocumentsType,
|
if (process) {
|
||||||
...selectedDocuments.map((document) => DocumentType.hydrate<DocumentType>({ uid: document.id as string })),
|
DeedTypeService.updateDeedType(process, {
|
||||||
],
|
document_types: [
|
||||||
|
...oldDocumentsType.map((document: any) => ({ uid: document.uid })),
|
||||||
|
...selectedDocuments.map((document: any) => ({ uid: document.id as string }))
|
||||||
|
]
|
||||||
|
}).then(() => resolve());
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Get the full document details for the selected documents
|
// Get the full document details for the selected documents
|
||||||
const documentsById = await Promise.all(
|
const documentsById = await Promise.all(
|
||||||
selectedDocuments.map(async (doc) => {
|
selectedDocuments.map(async (doc) => {
|
||||||
const fullDoc = await DocumentTypes.getInstance().getByUid(doc.id as string);
|
const documentType: any = await new Promise<any>((resolve: (documentType: any) => void) => {
|
||||||
|
DocumentTypeService.getDocumentTypeByUid(doc.id as string).then((process: any) => {
|
||||||
|
if (process) {
|
||||||
|
const documentType: any = process.processData;
|
||||||
|
resolve(documentType);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
return {
|
return {
|
||||||
label: fullDoc.name!,
|
label: documentType.name!,
|
||||||
value: fullDoc.uid!,
|
value: documentType.uid!,
|
||||||
description: fullDoc.private_description!,
|
description: documentType.private_description!,
|
||||||
} as IFormOption;
|
} as IFormOption;
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
@ -130,6 +166,7 @@ export default function ParameterDocuments(props: IProps) {
|
|||||||
props.onDocumentsUpdated(documentsById);
|
props.onDocumentsUpdated(documentsById);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
LoaderService.getInstance().hide();
|
||||||
handleClose();
|
handleClose();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
|
@ -18,6 +18,7 @@ import backgroundImage from "@Assets/images/background_refonte.svg";
|
|||||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||||
|
import { DocumentData } from "../FolderInformation/ClientView/DocumentTables/types";
|
||||||
|
|
||||||
export default function AskDocuments() {
|
export default function AskDocuments() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@ -62,17 +63,21 @@ export default function AskDocuments() {
|
|||||||
LoaderService.getInstance().show();
|
LoaderService.getInstance().show();
|
||||||
const documentAsked: [] = values["document_types"] as [];
|
const documentAsked: [] = values["document_types"] as [];
|
||||||
for (let i = 0; i < documentAsked.length; i++) {
|
for (let i = 0; i < documentAsked.length; i++) {
|
||||||
|
const documentTypeUid = documentAsked[i];
|
||||||
|
if (!documentTypeUid) continue;
|
||||||
|
|
||||||
const documentData: any = {
|
const documentData: any = {
|
||||||
folder: {
|
folder: {
|
||||||
uid: folderUid,
|
uid: folderUid as string,
|
||||||
},
|
},
|
||||||
depositor: {
|
depositor: {
|
||||||
uid: customerUid,
|
uid: customerUid as string,
|
||||||
},
|
},
|
||||||
document_type: {
|
document_type: {
|
||||||
uid: documentAsked[i]
|
uid: documentTypeUid
|
||||||
},
|
},
|
||||||
document_status: EDocumentStatus.ASKED
|
document_status: EDocumentStatus.ASKED,
|
||||||
|
file_uid: null,
|
||||||
};
|
};
|
||||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||||
|
|
||||||
|
@ -1,8 +1,12 @@
|
|||||||
import Modal from "@Front/Components/DesignSystem/Modal";
|
import Modal from "@Front/Components/DesignSystem/Modal";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
|
import { FileBlob } from "@Front/Api/Entities/types";
|
||||||
|
|
||||||
type IProps = {
|
type IProps = {
|
||||||
file: any;
|
file: {
|
||||||
|
uid: string;
|
||||||
|
file_blob: FileBlob;
|
||||||
|
};
|
||||||
url: string;
|
url: string;
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
onClose?: () => void;
|
onClose?: () => void;
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
import FilesNotary from "@Front/Api/LeCoffreApi/Notary/FilesNotary/Files";
|
|
||||||
import CircleProgress from "@Front/Components/DesignSystem/CircleProgress";
|
import CircleProgress from "@Front/Components/DesignSystem/CircleProgress";
|
||||||
import IconButton from "@Front/Components/DesignSystem/IconButton";
|
import IconButton from "@Front/Components/DesignSystem/IconButton";
|
||||||
import Table from "@Front/Components/DesignSystem/Table";
|
import Table from "@Front/Components/DesignSystem/Table";
|
||||||
@ -7,9 +6,8 @@ import Tag, { ETagColor, ETagVariant } from "@Front/Components/DesignSystem/Tag"
|
|||||||
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
|
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
|
||||||
import Module from "@Front/Config/Module";
|
import Module from "@Front/Config/Module";
|
||||||
import useOpenable from "@Front/Hooks/useOpenable";
|
import useOpenable from "@Front/Hooks/useOpenable";
|
||||||
import { ArrowDownTrayIcon, EyeIcon, TrashIcon } from "@heroicons/react/24/outline";
|
import { ArrowDownTrayIcon, EyeIcon, TrashIcon, DocumentTextIcon } from "@heroicons/react/24/outline";
|
||||||
import { useMediaQuery } from "@mui/material";
|
import { useMediaQuery } from "@mui/material";
|
||||||
import { Document } from "le-coffre-resources/dist/Customer";
|
|
||||||
import { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document";
|
import { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document";
|
||||||
import DocumentNotary, { EDocumentNotaryStatus } from "le-coffre-resources/dist/Notary/DocumentNotary";
|
import DocumentNotary, { EDocumentNotaryStatus } from "le-coffre-resources/dist/Notary/DocumentNotary";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
@ -24,6 +22,9 @@ import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
|||||||
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
|
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
|
||||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||||
|
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||||
|
import PdfService, { CertificateData, Metadata } from "@Front/Services/PdfService";
|
||||||
|
import MessageBus from "src/sdk/MessageBus";
|
||||||
|
|
||||||
type IProps = {
|
type IProps = {
|
||||||
customerUid: string;
|
customerUid: string;
|
||||||
@ -44,7 +45,7 @@ const tradDocumentsNotaryStatus: Record<EDocumentNotaryStatus, string> = {
|
|||||||
|
|
||||||
export default function DocumentTables(props: IProps) {
|
export default function DocumentTables(props: IProps) {
|
||||||
const { folderUid, customerUid } = props;
|
const { folderUid, customerUid } = props;
|
||||||
const [documents, setDocuments] = useState<Document[]>([]);
|
const [documents, setDocuments] = useState<any[]>([]);
|
||||||
const [documentsNotary, setDocumentsNotary] = useState<DocumentNotary[]>([]);
|
const [documentsNotary, setDocumentsNotary] = useState<DocumentNotary[]>([]);
|
||||||
const [focusedDocumentUid, setFocusedDocumentUid] = useState<string | null>(null);
|
const [focusedDocumentUid, setFocusedDocumentUid] = useState<string | null>(null);
|
||||||
|
|
||||||
@ -63,6 +64,12 @@ export default function DocumentTables(props: IProps) {
|
|||||||
// FilterBy folder.uid & depositor.uid
|
// FilterBy folder.uid & depositor.uid
|
||||||
documents = documents.filter((document: any) => document.folder.uid === folderUid && document.depositor && document.depositor.uid === customerUid);
|
documents = documents.filter((document: any) => document.folder.uid === folderUid && document.depositor && document.depositor.uid === customerUid);
|
||||||
|
|
||||||
|
console.log('[DocumentTables] fetchDocuments: all documents for this folder/customer:', documents.map(doc => ({
|
||||||
|
uid: doc.uid,
|
||||||
|
status: doc.document_status,
|
||||||
|
type: doc.document_type?.name
|
||||||
|
})));
|
||||||
|
|
||||||
for (const document of documents) {
|
for (const document of documents) {
|
||||||
document.document_type = (await DocumentTypeService.getDocumentTypeByUid(document.document_type.uid)).processData;
|
document.document_type = (await DocumentTypeService.getDocumentTypeByUid(document.document_type.uid)).processData;
|
||||||
|
|
||||||
@ -157,23 +164,90 @@ export default function DocumentTables(props: IProps) {
|
|||||||
}).catch((e) => console.warn(e));
|
}).catch((e) => console.warn(e));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const onDownloadFileNotary = useCallback((doc: DocumentNotary) => {
|
const onDownloadFileNotary = useCallback((doc: any) => {
|
||||||
const file = doc.files?.[0];
|
const file = doc.files?.[0];
|
||||||
if (!file || !file?.uid) return;
|
if (!file) return;
|
||||||
|
|
||||||
return FilesNotary.getInstance()
|
return new Promise<void>((resolve: () => void) => {
|
||||||
.download(file.uid)
|
const blob = new Blob([file.file_blob.data], { type: file.file_blob.type });
|
||||||
.then((blob) => {
|
const url = URL.createObjectURL(blob);
|
||||||
const url = URL.createObjectURL(blob);
|
const a = document.createElement('a');
|
||||||
const a = document.createElement("a");
|
a.href = url;
|
||||||
a.href = url;
|
a.download = file.file_name;
|
||||||
a.download = file.file_name ?? "file";
|
document.body.appendChild(a);
|
||||||
a.click();
|
a.click();
|
||||||
URL.revokeObjectURL(url);
|
document.body.removeChild(a);
|
||||||
})
|
URL.revokeObjectURL(url);
|
||||||
.catch((e) => console.warn(e));
|
|
||||||
|
resolve();
|
||||||
|
}).catch((e) => console.warn(e));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const onDownloadCertificate = useCallback(async (doc: any) => {
|
||||||
|
try {
|
||||||
|
console.log('[DocumentTables] onDownloadCertificate: doc', doc);
|
||||||
|
const certificateData: CertificateData = {
|
||||||
|
customer: {
|
||||||
|
firstName: doc.depositor.first_name || doc.depositor.firstName || "N/A",
|
||||||
|
lastName: doc.depositor.last_name || doc.depositor.lastName || "N/A",
|
||||||
|
postalAddress: doc.depositor.postal_address || doc.depositor.address || doc.depositor.postalAddress || "N/A",
|
||||||
|
email: doc.depositor.email || "N/A"
|
||||||
|
},
|
||||||
|
notary: {
|
||||||
|
name: "N/A"
|
||||||
|
},
|
||||||
|
folderUid: folderUid,
|
||||||
|
documentHash: "N/A",
|
||||||
|
metadata: {
|
||||||
|
fileName: "N/A",
|
||||||
|
isDeleted: false,
|
||||||
|
updatedAt: new Date(),
|
||||||
|
commitmentId: "N/A",
|
||||||
|
createdAt: new Date(),
|
||||||
|
documentUid: "N/A",
|
||||||
|
documentType: "N/A",
|
||||||
|
merkleProof: "N/A"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get the specific document that was clicked
|
||||||
|
const documentProcess = await DocumentService.getDocumentByUid(doc.uid);
|
||||||
|
if (!documentProcess) {
|
||||||
|
throw new Error('Document not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process only the files for this specific document
|
||||||
|
for (const file of documentProcess.processData.files) {
|
||||||
|
const fileProcess = await FileService.getFileByUid(file.uid);
|
||||||
|
console.log('[DocumentTables] onDownloadCertificate: fileProcess', fileProcess);
|
||||||
|
|
||||||
|
const hash = fileProcess.lastUpdatedFileState.pcd_commitment.file_blob;
|
||||||
|
certificateData.documentHash = hash;
|
||||||
|
|
||||||
|
const proof = await MessageBus.getInstance().generateMerkleProof(fileProcess.lastUpdatedFileState, 'file_blob');
|
||||||
|
console.log('[DocumentTables] onDownloadCertificate: proof', proof);
|
||||||
|
|
||||||
|
const metadata: Metadata = {
|
||||||
|
fileName: fileProcess.processData.file_name,
|
||||||
|
isDeleted: false,
|
||||||
|
updatedAt: new Date(fileProcess.processData.updated_at),
|
||||||
|
commitmentId: fileProcess.lastUpdatedFileState.commited_in,
|
||||||
|
createdAt: new Date(fileProcess.processData.created_at),
|
||||||
|
documentUid: doc.uid,
|
||||||
|
documentType: doc.document_type.name,
|
||||||
|
merkleProof: proof
|
||||||
|
};
|
||||||
|
certificateData.metadata = metadata;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('[DocumentTables] onDownloadCertificate: certificateData', certificateData);
|
||||||
|
|
||||||
|
await PdfService.getInstance().downloadCertificate(certificateData);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error downloading certificate:', error);
|
||||||
|
}
|
||||||
|
}, [folderUid, customerUid]);
|
||||||
|
|
||||||
const askedDocuments: IRowProps[] = useMemo(
|
const askedDocuments: IRowProps[] = useMemo(
|
||||||
() =>
|
() =>
|
||||||
documents
|
documents
|
||||||
@ -181,21 +255,25 @@ export default function DocumentTables(props: IProps) {
|
|||||||
if (document.document_status !== EDocumentStatus.ASKED) return null;
|
if (document.document_status !== EDocumentStatus.ASKED) return null;
|
||||||
return {
|
return {
|
||||||
key: document.uid,
|
key: document.uid,
|
||||||
document_type: { sx: { width: 400 }, content: document.document_type?.name ?? "_" },
|
document_type: { sx: { width: 300 }, content: document.document_type?.name ?? "_" },
|
||||||
document_status: {
|
document_status: {
|
||||||
sx: { width: 107 },
|
sx: { width: 107 },
|
||||||
content: (
|
content: (
|
||||||
<Tag
|
<Tag
|
||||||
color={ETagColor.INFO}
|
color={ETagColor.INFO}
|
||||||
variant={ETagVariant.SEMI_BOLD}
|
variant={ETagVariant.SEMI_BOLD}
|
||||||
label={tradDocumentStatus[document.document_status].toUpperCase()}
|
label={tradDocumentStatus[document.document_status as EDocumentStatus].toUpperCase()}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
date: {
|
date: {
|
||||||
sx: { width: 107 },
|
sx: { width: 120 },
|
||||||
content: document.created_at ? new Date(document.created_at).toLocaleDateString() : "_",
|
content: document.created_at ? new Date(document.created_at).toLocaleDateString() : "_",
|
||||||
},
|
},
|
||||||
|
file: {
|
||||||
|
sx: { width: 120 },
|
||||||
|
content: "_",
|
||||||
|
},
|
||||||
actions: {
|
actions: {
|
||||||
sx: { width: 76 },
|
sx: { width: 76 },
|
||||||
content: (
|
content: (
|
||||||
@ -217,21 +295,25 @@ export default function DocumentTables(props: IProps) {
|
|||||||
if (document.document_status !== EDocumentStatus.DEPOSITED) return null;
|
if (document.document_status !== EDocumentStatus.DEPOSITED) return null;
|
||||||
return {
|
return {
|
||||||
key: document.uid,
|
key: document.uid,
|
||||||
document_type: { sx: { width: 400 }, content: document.document_type?.name ?? "_" },
|
document_type: { sx: { width: 300 }, content: document.document_type?.name ?? "_" },
|
||||||
document_status: {
|
document_status: {
|
||||||
sx: { width: 107 },
|
sx: { width: 107 },
|
||||||
content: (
|
content: (
|
||||||
<Tag
|
<Tag
|
||||||
color={ETagColor.WARNING}
|
color={ETagColor.WARNING}
|
||||||
variant={ETagVariant.SEMI_BOLD}
|
variant={ETagVariant.SEMI_BOLD}
|
||||||
label={tradDocumentStatus[document.document_status].toUpperCase()}
|
label={tradDocumentStatus[document.document_status as EDocumentStatus].toUpperCase()}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
date: {
|
date: {
|
||||||
sx: { width: 107 },
|
sx: { width: 120 },
|
||||||
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
||||||
},
|
},
|
||||||
|
file: {
|
||||||
|
sx: { width: 120 },
|
||||||
|
content: document.files?.[0]?.file_name ?? "_",
|
||||||
|
},
|
||||||
actions: {
|
actions: {
|
||||||
sx: { width: 76 },
|
sx: { width: 76 },
|
||||||
content: (
|
content: (
|
||||||
@ -253,27 +335,31 @@ export default function DocumentTables(props: IProps) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const validatedDocuments: IRowProps[] = useMemo(
|
const validatedDocuments: IRowProps[] = useMemo(
|
||||||
() =>
|
() => {
|
||||||
documents
|
const validated = documents
|
||||||
.map((document) => {
|
.map((document) => {
|
||||||
if (document.document_status !== EDocumentStatus.VALIDATED) return null;
|
if (document.document_status !== EDocumentStatus.VALIDATED) return null;
|
||||||
return {
|
return {
|
||||||
key: document.uid,
|
key: document.uid,
|
||||||
document_type: { sx: { width: 400 }, content: document.document_type?.name ?? "_" },
|
document_type: { sx: { width: 300 }, content: document.document_type?.name ?? "_" },
|
||||||
document_status: {
|
document_status: {
|
||||||
sx: { width: 107 },
|
sx: { width: 107 },
|
||||||
content: (
|
content: (
|
||||||
<Tag
|
<Tag
|
||||||
color={ETagColor.SUCCESS}
|
color={ETagColor.SUCCESS}
|
||||||
variant={ETagVariant.SEMI_BOLD}
|
variant={ETagVariant.SEMI_BOLD}
|
||||||
label={tradDocumentStatus[document.document_status].toUpperCase()}
|
label={tradDocumentStatus[document.document_status as EDocumentStatus].toUpperCase()}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
date: {
|
date: {
|
||||||
sx: { width: 107 },
|
sx: { width: 120 },
|
||||||
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
||||||
},
|
},
|
||||||
|
file: {
|
||||||
|
sx: { width: 120 },
|
||||||
|
content: document.files?.[0]?.file_name ?? "_",
|
||||||
|
},
|
||||||
actions: {
|
actions: {
|
||||||
sx: { width: 76 },
|
sx: { width: 76 },
|
||||||
content: (
|
content: (
|
||||||
@ -286,13 +372,17 @@ export default function DocumentTables(props: IProps) {
|
|||||||
<IconButton icon={<EyeIcon />} />
|
<IconButton icon={<EyeIcon />} />
|
||||||
</Link>
|
</Link>
|
||||||
<IconButton onClick={() => onDownload(document)} icon={<ArrowDownTrayIcon />} />
|
<IconButton onClick={() => onDownload(document)} icon={<ArrowDownTrayIcon />} />
|
||||||
|
<IconButton onClick={() => onDownloadCertificate(document)} icon={<DocumentTextIcon />} />
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
.filter((document) => document !== null) as IRowProps[],
|
.filter((document) => document !== null) as IRowProps[];
|
||||||
[documents, folderUid, onDownload],
|
|
||||||
|
return validated;
|
||||||
|
},
|
||||||
|
[documents, folderUid, onDownload, onDownloadCertificate],
|
||||||
);
|
);
|
||||||
|
|
||||||
const refusedDocuments: IRowProps[] = useMemo(
|
const refusedDocuments: IRowProps[] = useMemo(
|
||||||
@ -302,14 +392,14 @@ export default function DocumentTables(props: IProps) {
|
|||||||
if (document.document_status !== EDocumentStatus.REFUSED) return null;
|
if (document.document_status !== EDocumentStatus.REFUSED) return null;
|
||||||
return {
|
return {
|
||||||
key: document.uid,
|
key: document.uid,
|
||||||
document_type: { sx: { width: 400 }, content: document.document_type?.name ?? "_" },
|
document_type: { sx: { width: 300 }, content: document.document_type?.name ?? "_" },
|
||||||
document_status: {
|
document_status: {
|
||||||
sx: { width: 107 },
|
sx: { width: 107 },
|
||||||
content: (
|
content: (
|
||||||
<Tag
|
<Tag
|
||||||
color={ETagColor.ERROR}
|
color={ETagColor.ERROR}
|
||||||
variant={ETagVariant.SEMI_BOLD}
|
variant={ETagVariant.SEMI_BOLD}
|
||||||
label={tradDocumentStatus[document.document_status].toUpperCase()}
|
label={tradDocumentStatus[document.document_status as EDocumentStatus].toUpperCase()}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@ -331,7 +421,7 @@ export default function DocumentTables(props: IProps) {
|
|||||||
return {
|
return {
|
||||||
key: document.uid,
|
key: document.uid,
|
||||||
document_type: {
|
document_type: {
|
||||||
sx: { width: 400 },
|
sx: { width: 300 },
|
||||||
content: formatName(document.files?.[0]?.file_name?.split(".")?.[0] ?? "") || "_",
|
content: formatName(document.files?.[0]?.file_name?.split(".")?.[0] ?? "") || "_",
|
||||||
},
|
},
|
||||||
document_status: {
|
document_status: {
|
||||||
@ -339,9 +429,13 @@ export default function DocumentTables(props: IProps) {
|
|||||||
content: getTagForSentDocument(document.document_status as EDocumentNotaryStatus),
|
content: getTagForSentDocument(document.document_status as EDocumentNotaryStatus),
|
||||||
},
|
},
|
||||||
date: {
|
date: {
|
||||||
sx: { width: 107 },
|
sx: { width: 120 },
|
||||||
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
||||||
},
|
},
|
||||||
|
file: {
|
||||||
|
sx: { width: 120 },
|
||||||
|
content: document.files?.[0]?.file_name ?? "_",
|
||||||
|
},
|
||||||
actions: {
|
actions: {
|
||||||
sx: { width: 76 },
|
sx: { width: 76 },
|
||||||
content: (
|
content: (
|
||||||
@ -428,6 +522,10 @@ function getHeader(dateColumnTitle: string, isMobile: boolean): IHead[] {
|
|||||||
key: "date",
|
key: "date",
|
||||||
title: dateColumnTitle,
|
title: dateColumnTitle,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: "file",
|
||||||
|
title: "Fichier",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
key: "actions",
|
key: "actions",
|
||||||
title: "Action",
|
title: "Action",
|
||||||
|
@ -19,6 +19,7 @@ import MessageBox from "@Front/Components/Elements/MessageBox";
|
|||||||
|
|
||||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||||
|
import { FileBlob } from "@Front/Api/Entities/types";
|
||||||
|
|
||||||
type IProps = {};
|
type IProps = {};
|
||||||
type IPropsClass = {
|
type IPropsClass = {
|
||||||
@ -32,7 +33,7 @@ type IState = {
|
|||||||
isValidateModalVisible: boolean;
|
isValidateModalVisible: boolean;
|
||||||
refuseText: string;
|
refuseText: string;
|
||||||
selectedFileIndex: number;
|
selectedFileIndex: number;
|
||||||
selectedFile: any; // File | null; TODO: review
|
selectedFile: { uid: string; file_name: string; file_blob: FileBlob } | null;
|
||||||
validatedPercentage: number;
|
validatedPercentage: number;
|
||||||
document: Document | null;
|
document: Document | null;
|
||||||
fileBlob: Blob | null;
|
fileBlob: Blob | null;
|
||||||
@ -237,6 +238,8 @@ class ViewDocumentsClass extends BasePage<IPropsClass, IState> {
|
|||||||
|
|
||||||
private async getFilePreview(): Promise<void> {
|
private async getFilePreview(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
|
if (!this.state.selectedFile) return;
|
||||||
|
|
||||||
const fileBlob: Blob = new Blob([this.state.selectedFile.file_blob.data], { type: this.state.selectedFile.file_blob.type });
|
const fileBlob: Blob = new Blob([this.state.selectedFile.file_blob.data], { type: this.state.selectedFile.file_blob.type });
|
||||||
this.setState({
|
this.setState({
|
||||||
fileBlob,
|
fileBlob,
|
||||||
@ -247,7 +250,7 @@ class ViewDocumentsClass extends BasePage<IPropsClass, IState> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private downloadFile() {
|
private downloadFile() {
|
||||||
if (!this.state.fileBlob) return;
|
if (!this.state.fileBlob || !this.state.selectedFile) return;
|
||||||
|
|
||||||
const url = URL.createObjectURL(this.state.fileBlob);
|
const url = URL.createObjectURL(this.state.fileBlob);
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
|
741
src/front/Services/PdfService/index.ts
Normal file
741
src/front/Services/PdfService/index.ts
Normal file
@ -0,0 +1,741 @@
|
|||||||
|
import { saveAs } from 'file-saver';
|
||||||
|
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
|
||||||
|
|
||||||
|
export interface CustomerInfo {
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
postalAddress: string;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NotaryInfo {
|
||||||
|
name: string;
|
||||||
|
// Add more notary fields as needed
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Metadata {
|
||||||
|
fileName: string,
|
||||||
|
createdAt: Date,
|
||||||
|
isDeleted: boolean,
|
||||||
|
updatedAt: Date,
|
||||||
|
commitmentId: string,
|
||||||
|
documentUid: string;
|
||||||
|
documentType: string;
|
||||||
|
merkleProof: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CertificateData {
|
||||||
|
customer: CustomerInfo;
|
||||||
|
notary: NotaryInfo;
|
||||||
|
folderUid: string;
|
||||||
|
documentHash: string;
|
||||||
|
metadata: Metadata;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class PdfService {
|
||||||
|
private static instance: PdfService;
|
||||||
|
|
||||||
|
public static getInstance(): PdfService {
|
||||||
|
if (!PdfService.instance) {
|
||||||
|
PdfService.instance = new PdfService();
|
||||||
|
}
|
||||||
|
return PdfService.instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a certificate PDF for a document
|
||||||
|
* @param certificateData - Data needed for the certificate
|
||||||
|
* @returns Promise<Blob> - The generated PDF as a blob
|
||||||
|
*/
|
||||||
|
public async generateCertificate(certificateData: CertificateData): Promise<Blob> {
|
||||||
|
try {
|
||||||
|
const pdfDoc = await PDFDocument.create();
|
||||||
|
const page = pdfDoc.addPage([595, 842]); // A4 size
|
||||||
|
const { width, height } = page.getSize();
|
||||||
|
|
||||||
|
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||||
|
const helveticaBoldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
||||||
|
const helveticaObliqueFont = await pdfDoc.embedFont(StandardFonts.HelveticaOblique);
|
||||||
|
|
||||||
|
let y = height - 40; // Start 40pt from the top
|
||||||
|
const leftMargin = 20;
|
||||||
|
const rightSectionX = 320;
|
||||||
|
const lineSpacing = 16;
|
||||||
|
|
||||||
|
// Notary Information Section (Top Left)
|
||||||
|
page.drawText('Notaire Validateur:', {
|
||||||
|
x: leftMargin,
|
||||||
|
y: y,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
y -= lineSpacing;
|
||||||
|
page.drawText(certificateData.notary.name, {
|
||||||
|
x: leftMargin,
|
||||||
|
y: y,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Customer Information Section (Top Right)
|
||||||
|
let yRight = height - 40;
|
||||||
|
page.drawText('Fournisseur de Document:', {
|
||||||
|
x: rightSectionX,
|
||||||
|
y: yRight,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yRight -= lineSpacing;
|
||||||
|
page.drawText(`${certificateData.customer.firstName} ${certificateData.customer.lastName}`, {
|
||||||
|
x: rightSectionX,
|
||||||
|
y: yRight,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yRight -= lineSpacing;
|
||||||
|
page.drawText(certificateData.customer.email, {
|
||||||
|
x: rightSectionX,
|
||||||
|
y: yRight,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yRight -= lineSpacing;
|
||||||
|
page.drawText(certificateData.customer.postalAddress, {
|
||||||
|
x: rightSectionX,
|
||||||
|
y: yRight,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Centered Title
|
||||||
|
y -= 4 * lineSpacing; // Add more space between header and title
|
||||||
|
const titleText = 'Certificat de Validation de Document';
|
||||||
|
const titleWidth = helveticaBoldFont.widthOfTextAtSize(titleText, 20);
|
||||||
|
page.drawText(titleText, {
|
||||||
|
x: (width - titleWidth) / 2,
|
||||||
|
y: y,
|
||||||
|
size: 20,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
y -= lineSpacing;
|
||||||
|
|
||||||
|
// Add a line separator
|
||||||
|
page.drawLine({
|
||||||
|
start: { x: leftMargin, y: y },
|
||||||
|
end: { x: width - leftMargin, y: y },
|
||||||
|
thickness: 0.5,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
y -= lineSpacing;
|
||||||
|
|
||||||
|
// Document Information Section
|
||||||
|
page.drawText('Informations du Document', {
|
||||||
|
x: leftMargin,
|
||||||
|
y: y,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
y -= lineSpacing;
|
||||||
|
page.drawText(`UID du Dossier: ${certificateData.folderUid}`, {
|
||||||
|
x: leftMargin,
|
||||||
|
y: y,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
y -= lineSpacing;
|
||||||
|
page.drawText(`Type de Document: ${certificateData.metadata.documentType}`, {
|
||||||
|
x: leftMargin,
|
||||||
|
y: y,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
y -= lineSpacing;
|
||||||
|
page.drawText(`Nom du fichier: ${certificateData.metadata.fileName}`, {
|
||||||
|
x: leftMargin,
|
||||||
|
y: y,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
y -= lineSpacing;
|
||||||
|
page.drawText(`Créé le: ${certificateData.metadata.createdAt.toLocaleDateString('fr-FR')}`, {
|
||||||
|
x: leftMargin,
|
||||||
|
y: y,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
y -= lineSpacing;
|
||||||
|
page.drawText(`Dernière modification: ${certificateData.metadata.updatedAt.toLocaleDateString('fr-FR')}`, {
|
||||||
|
x: leftMargin,
|
||||||
|
y: y,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
y -= lineSpacing;
|
||||||
|
|
||||||
|
// Document Hash Section
|
||||||
|
page.drawText('Intégrité du Document', {
|
||||||
|
x: leftMargin,
|
||||||
|
y: y,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
y -= lineSpacing;
|
||||||
|
|
||||||
|
// Add verification data as base64
|
||||||
|
const verificationData = {
|
||||||
|
documentHash: certificateData.documentHash,
|
||||||
|
commitmentId: certificateData.metadata.commitmentId,
|
||||||
|
merkleProof: certificateData.metadata.merkleProof || "N/A"
|
||||||
|
};
|
||||||
|
const verificationDataBase64 = btoa(JSON.stringify(verificationData));
|
||||||
|
|
||||||
|
// Calculate proper chunk size based on available width and font size
|
||||||
|
const availableWidth = width - (2 * leftMargin) - 20; // Full width minus margins and safety buffer
|
||||||
|
const fontSize = 12;
|
||||||
|
// Use a typical base64 character for width calculation
|
||||||
|
const avgCharWidth = helveticaFont.widthOfTextAtSize('A', fontSize);
|
||||||
|
const charsPerLine = Math.floor(availableWidth / avgCharWidth);
|
||||||
|
const chunkSize = Math.max(60, Math.min(100, charsPerLine)); // More conservative limits
|
||||||
|
|
||||||
|
const chunks = [];
|
||||||
|
for (let j = 0; j < verificationDataBase64.length; j += chunkSize) {
|
||||||
|
chunks.push(verificationDataBase64.slice(j, j + chunkSize));
|
||||||
|
}
|
||||||
|
chunks.forEach((chunk, index) => {
|
||||||
|
page.drawText(chunk, {
|
||||||
|
x: leftMargin,
|
||||||
|
y: y - (index * 12), // Increased line spacing
|
||||||
|
size: fontSize,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add explanatory text about certificate usage
|
||||||
|
y -= (chunks.length * 12) + 40; // Space after verification data
|
||||||
|
const explanatoryText = "Ce certificat doit être utilisé avec le document qu'il certifie pour être vérifié sur la page dédiée. Le document correspondant à ce certificat doit être téléchargé depuis LeCoffre et peut être conservé avec le certificat tant qu'il n'est pas modifié.";
|
||||||
|
const explanatoryLines = this.splitTextToFit(helveticaObliqueFont, explanatoryText, width - (2 * leftMargin), 11);
|
||||||
|
explanatoryLines.forEach((line, index) => {
|
||||||
|
page.drawText(line, {
|
||||||
|
x: leftMargin,
|
||||||
|
y: y - (index * 14), // Slightly more spacing for readability
|
||||||
|
size: 11,
|
||||||
|
font: helveticaObliqueFont,
|
||||||
|
color: rgb(0.3, 0.3, 0.3) // Slightly grayed out to distinguish from main content
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Footer
|
||||||
|
const footerText1 = `Page 1 sur 1`;
|
||||||
|
const footerText2 = `Généré le ${new Date().toLocaleString('fr-FR')}`;
|
||||||
|
const footerWidth1 = helveticaObliqueFont.widthOfTextAtSize(footerText1, 10);
|
||||||
|
const footerWidth2 = helveticaObliqueFont.widthOfTextAtSize(footerText2, 10);
|
||||||
|
page.drawText(footerText1, {
|
||||||
|
x: (width - footerWidth1) / 2,
|
||||||
|
y: 35,
|
||||||
|
size: 10,
|
||||||
|
font: helveticaObliqueFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
page.drawText(footerText2, {
|
||||||
|
x: (width - footerWidth2) / 2,
|
||||||
|
y: 25,
|
||||||
|
size: 10,
|
||||||
|
font: helveticaObliqueFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
const pdfBytes = await pdfDoc.save();
|
||||||
|
return new Blob([pdfBytes], { type: 'application/pdf' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error generating certificate:', error);
|
||||||
|
throw new Error('Failed to generate certificate');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Split text to fit within a specified width
|
||||||
|
* @param font - PDF font instance
|
||||||
|
* @param text - Text to split
|
||||||
|
* @param maxWidth - Maximum width in points
|
||||||
|
* @param fontSize - Font size
|
||||||
|
* @returns Array of text lines
|
||||||
|
*/
|
||||||
|
private splitTextToFit(font: any, text: string, maxWidth: number, fontSize: number): string[] {
|
||||||
|
const lines: string[] = [];
|
||||||
|
let currentLine = '';
|
||||||
|
|
||||||
|
// Split by characters (pdf-lib doesn't have word-level text measurement)
|
||||||
|
const chars = text.split('');
|
||||||
|
|
||||||
|
for (const char of chars) {
|
||||||
|
const testLine = currentLine + char;
|
||||||
|
const testWidth = font.widthOfTextAtSize(testLine, fontSize);
|
||||||
|
|
||||||
|
if (testWidth <= maxWidth) {
|
||||||
|
currentLine = testLine;
|
||||||
|
} else {
|
||||||
|
if (currentLine) {
|
||||||
|
lines.push(currentLine);
|
||||||
|
currentLine = char;
|
||||||
|
} else {
|
||||||
|
// If even a single character is too wide, force a break
|
||||||
|
lines.push(char);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentLine) {
|
||||||
|
lines.push(currentLine);
|
||||||
|
}
|
||||||
|
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Download a certificate PDF
|
||||||
|
* @param certificateData - Data needed for the certificate
|
||||||
|
* @param filename - Optional filename for the download
|
||||||
|
*/
|
||||||
|
public async downloadCertificate(certificateData: CertificateData, filename?: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
const pdfBlob = await this.generateCertificate(certificateData);
|
||||||
|
const defaultFilename = `certificate_${certificateData.metadata.documentUid}_${new Date().toISOString().split('T')[0]}.pdf`;
|
||||||
|
saveAs(pdfBlob, filename || defaultFilename);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error downloading certificate:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate certificate for notary documents
|
||||||
|
* @param certificateData - Data needed for the certificate
|
||||||
|
* @returns Promise<Blob> - The generated PDF as a blob
|
||||||
|
*/
|
||||||
|
public async generateNotaryCertificate(certificateData: CertificateData): Promise<Blob> {
|
||||||
|
try {
|
||||||
|
// Create a new PDF document
|
||||||
|
const pdfDoc = await PDFDocument.create();
|
||||||
|
const page = pdfDoc.addPage([595, 842]); // A4 size
|
||||||
|
const { width, height } = page.getSize();
|
||||||
|
|
||||||
|
// Embed the standard font
|
||||||
|
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||||
|
const helveticaBoldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
||||||
|
const helveticaObliqueFont = await pdfDoc.embedFont(StandardFonts.HelveticaOblique);
|
||||||
|
|
||||||
|
// Notary Information Section (Top Left)
|
||||||
|
page.drawText('Notaire Validateur:', {
|
||||||
|
x: 20,
|
||||||
|
y: height - 30,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
page.drawText(certificateData.notary.name, {
|
||||||
|
x: 20,
|
||||||
|
y: height - 37,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Customer Information Section (Top Right)
|
||||||
|
page.drawText('Fournisseur de Document:', {
|
||||||
|
x: 120,
|
||||||
|
y: height - 30,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
page.drawText(`${certificateData.customer.firstName} ${certificateData.customer.lastName}`, {
|
||||||
|
x: 120,
|
||||||
|
y: height - 37,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
page.drawText(certificateData.customer.email, {
|
||||||
|
x: 120,
|
||||||
|
y: height - 44,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
page.drawText(certificateData.customer.postalAddress, {
|
||||||
|
x: 120,
|
||||||
|
y: height - 51,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Centered Title
|
||||||
|
const titleText = 'Certificat Notarial de Validation de Document';
|
||||||
|
const titleWidth = helveticaBoldFont.widthOfTextAtSize(titleText, 20);
|
||||||
|
page.drawText(titleText, {
|
||||||
|
x: (width - titleWidth) / 2,
|
||||||
|
y: height - 80,
|
||||||
|
size: 20,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add a line separator
|
||||||
|
page.drawLine({
|
||||||
|
start: { x: 20, y: height - 90 },
|
||||||
|
end: { x: width - 20, y: height - 90 },
|
||||||
|
thickness: 0.5,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
let yPosition = height - 110;
|
||||||
|
|
||||||
|
// Document Information Section
|
||||||
|
page.drawText('Informations du Document', {
|
||||||
|
x: 20,
|
||||||
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 10;
|
||||||
|
|
||||||
|
page.drawText(`Identifiant du Document: ${certificateData.metadata.documentUid}`, {
|
||||||
|
x: 20,
|
||||||
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 7;
|
||||||
|
|
||||||
|
page.drawText(`Type de Document: ${certificateData.metadata.documentType}`, {
|
||||||
|
x: 20,
|
||||||
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 7;
|
||||||
|
|
||||||
|
page.drawText(`Numéro de dossier: ${certificateData.folderUid}`, {
|
||||||
|
x: 20,
|
||||||
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 7;
|
||||||
|
|
||||||
|
page.drawText(`Créé le: ${certificateData.metadata.createdAt.toLocaleDateString('fr-FR')}`, {
|
||||||
|
x: 20,
|
||||||
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 7;
|
||||||
|
|
||||||
|
page.drawText(`Nom du fichier: ${certificateData.metadata.fileName}`, {
|
||||||
|
x: 20,
|
||||||
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 7;
|
||||||
|
|
||||||
|
page.drawText(`ID de transaction: ${certificateData.metadata.commitmentId}`, {
|
||||||
|
x: 20,
|
||||||
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 7;
|
||||||
|
|
||||||
|
page.drawText(`Dernière modification: ${certificateData.metadata.updatedAt.toLocaleDateString('fr-FR')}`, {
|
||||||
|
x: 20,
|
||||||
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 7;
|
||||||
|
|
||||||
|
page.drawText(`Statut: ${certificateData.metadata.isDeleted ? 'Supprimé' : 'Actif'}`, {
|
||||||
|
x: 20,
|
||||||
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 15;
|
||||||
|
|
||||||
|
// Document Hash Section
|
||||||
|
page.drawText('Intégrité du Document', {
|
||||||
|
x: 20,
|
||||||
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 10;
|
||||||
|
|
||||||
|
page.drawText(`Hash SHA256 du Document:`, {
|
||||||
|
x: 20,
|
||||||
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 7;
|
||||||
|
|
||||||
|
// Split hash into multiple lines if needed
|
||||||
|
const hash = certificateData.documentHash;
|
||||||
|
const maxWidth = 170; // Available width for text
|
||||||
|
const hashLines = this.splitTextToFit(helveticaFont, hash, maxWidth, 12);
|
||||||
|
|
||||||
|
for (const line of hashLines) {
|
||||||
|
page.drawText(line, {
|
||||||
|
x: 25,
|
||||||
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 7;
|
||||||
|
}
|
||||||
|
yPosition -= 8; // Extra space after hash
|
||||||
|
|
||||||
|
yPosition -= 5;
|
||||||
|
|
||||||
|
// Footer
|
||||||
|
const footerText1 = `Page 1 sur 1`;
|
||||||
|
const footerText2 = `Certificat Notarial - Généré le ${new Date().toLocaleString('fr-FR')}`;
|
||||||
|
const footerWidth1 = helveticaObliqueFont.widthOfTextAtSize(footerText1, 10);
|
||||||
|
const footerWidth2 = helveticaObliqueFont.widthOfTextAtSize(footerText2, 10);
|
||||||
|
|
||||||
|
page.drawText(footerText1, {
|
||||||
|
x: (width - footerWidth1) / 2,
|
||||||
|
y: 30,
|
||||||
|
size: 10,
|
||||||
|
font: helveticaObliqueFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
page.drawText(footerText2, {
|
||||||
|
x: (width - footerWidth2) / 2,
|
||||||
|
y: 25,
|
||||||
|
size: 10,
|
||||||
|
font: helveticaObliqueFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add verification data as base64 in small font
|
||||||
|
const verificationData = {
|
||||||
|
documentHash: certificateData.documentHash,
|
||||||
|
commitmentId: certificateData.metadata.commitmentId,
|
||||||
|
merkleProof: certificateData.metadata.merkleProof || "N/A"
|
||||||
|
};
|
||||||
|
const verificationDataBase64 = btoa(JSON.stringify(verificationData));
|
||||||
|
|
||||||
|
// Split into chunks if too long
|
||||||
|
const chunkSize = 80;
|
||||||
|
const chunks = [];
|
||||||
|
for (let j = 0; j < verificationDataBase64.length; j += chunkSize) {
|
||||||
|
chunks.push(verificationDataBase64.slice(j, j + chunkSize));
|
||||||
|
}
|
||||||
|
|
||||||
|
chunks.forEach((chunk, index) => {
|
||||||
|
page.drawText(chunk, {
|
||||||
|
x: 20,
|
||||||
|
y: 15 - (index * 3),
|
||||||
|
size: 6,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Save the PDF
|
||||||
|
const pdfBytes = await pdfDoc.save();
|
||||||
|
return new Blob([pdfBytes], { type: 'application/pdf' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error generating notary certificate:', error);
|
||||||
|
throw new Error('Failed to generate notary certificate');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Download a notary certificate PDF
|
||||||
|
* @param certificateData - Data needed for the certificate
|
||||||
|
* @param filename - Optional filename for the download
|
||||||
|
*/
|
||||||
|
public async downloadNotaryCertificate(certificateData: CertificateData, filename?: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
const pdfBlob = await this.generateNotaryCertificate(certificateData);
|
||||||
|
const defaultFilename = `notary_certificate_${certificateData.metadata.documentUid}_${new Date().toISOString().split('T')[0]}.pdf`;
|
||||||
|
saveAs(pdfBlob, filename || defaultFilename);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error downloading notary certificate:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a PDF certificate and extract document information
|
||||||
|
* @param pdfBlob - The PDF file as a blob
|
||||||
|
* @returns Promise<{documentHash: string, documentUid: string, commitmentId: string, merkleProof?: string}> - Extracted information
|
||||||
|
*/
|
||||||
|
public async parseCertificate(pdfBlob: Blob): Promise<{documentHash: string, documentUid: string, commitmentId: string, merkleProof?: string}> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const fileReader = new FileReader();
|
||||||
|
|
||||||
|
fileReader.onload = async () => {
|
||||||
|
try {
|
||||||
|
// Convert PDF to text using browser's PDF capabilities
|
||||||
|
const arrayBuffer = fileReader.result as ArrayBuffer;
|
||||||
|
const pdfData = new Uint8Array(arrayBuffer);
|
||||||
|
console.log("PDF data:", pdfData);
|
||||||
|
|
||||||
|
// Use a simple text extraction approach
|
||||||
|
// This is a basic implementation - for production, consider using pdfjs-dist
|
||||||
|
const text = await this.extractTextFromPdf(pdfData);
|
||||||
|
|
||||||
|
// Parse the extracted text to find our certificate data
|
||||||
|
const parsedData = this.parseCertificateText(text);
|
||||||
|
|
||||||
|
if (!parsedData.documentHash) {
|
||||||
|
throw new Error('Document hash not found in certificate');
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve(parsedData);
|
||||||
|
} catch (error) {
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fileReader.onerror = () => {
|
||||||
|
reject(new Error('Failed to read PDF file'));
|
||||||
|
};
|
||||||
|
|
||||||
|
fileReader.readAsArrayBuffer(pdfBlob);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract text from PDF using browser capabilities
|
||||||
|
* @param pdfData - PDF data as Uint8Array
|
||||||
|
* @returns Promise<string> - Extracted text
|
||||||
|
*/
|
||||||
|
private async extractTextFromPdf(pdfData: Uint8Array): Promise<string> {
|
||||||
|
console.log("extractTextFromPdf");
|
||||||
|
|
||||||
|
// Convert PDF data to string to search for base64 patterns
|
||||||
|
const pdfString = new TextDecoder('utf-8').decode(pdfData);
|
||||||
|
|
||||||
|
// Look for base64 patterns in the PDF content
|
||||||
|
// This is a simple approach that should work for our embedded data
|
||||||
|
const base64Matches = pdfString.match(/([A-Za-z0-9+/]{80,}={0,2})/g);
|
||||||
|
|
||||||
|
if (base64Matches && base64Matches.length > 0) {
|
||||||
|
console.log('Found base64 patterns in PDF:', base64Matches.length);
|
||||||
|
// Return the longest base64 string (most likely our verification data)
|
||||||
|
const longestBase64 = base64Matches.reduce((a, b) => a.length > b.length ? a : b);
|
||||||
|
return longestBase64;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no base64 found, return empty string
|
||||||
|
console.log('No base64 patterns found in PDF');
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse certificate text to extract specific fields
|
||||||
|
* @param text - Extracted text from PDF (could be base64 or regular text)
|
||||||
|
* @returns Parsed certificate data
|
||||||
|
*/
|
||||||
|
private parseCertificateText(text: string): {documentHash: string, documentUid: string, commitmentId: string, merkleProof?: string} {
|
||||||
|
const result = {
|
||||||
|
documentHash: '',
|
||||||
|
documentUid: '',
|
||||||
|
commitmentId: '',
|
||||||
|
merkleProof: undefined as string | undefined
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check if the text is a base64 string (our new format)
|
||||||
|
if (text.match(/^[A-Za-z0-9+/]+={0,2}$/)) {
|
||||||
|
try {
|
||||||
|
console.log('Attempting to decode base64 data:', text.substring(0, 50) + '...');
|
||||||
|
const decodedData = atob(text);
|
||||||
|
const verificationData = JSON.parse(decodedData);
|
||||||
|
|
||||||
|
console.log('Successfully decoded verification data:', verificationData);
|
||||||
|
|
||||||
|
if (verificationData.documentHash) {
|
||||||
|
result.documentHash = verificationData.documentHash;
|
||||||
|
}
|
||||||
|
if (verificationData.commitmentId) {
|
||||||
|
result.commitmentId = verificationData.commitmentId;
|
||||||
|
}
|
||||||
|
if (verificationData.merkleProof && verificationData.merkleProof !== "N/A") {
|
||||||
|
result.merkleProof = verificationData.merkleProof;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we successfully extracted data from base64, return early
|
||||||
|
if (result.documentHash) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.log('Failed to decode base64 data:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to text parsing for older certificates
|
||||||
|
// Extract document hash (64 character hex string)
|
||||||
|
const hashMatch = text.match(/Hash SHA256 du Document:\s*([a-fA-F0-9]{64})/);
|
||||||
|
if (hashMatch && hashMatch[1]) {
|
||||||
|
result.documentHash = hashMatch[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract document UID
|
||||||
|
const uidMatch = text.match(/UID du Document:\s*([^\n\r]+)/);
|
||||||
|
if (uidMatch && uidMatch[1]) {
|
||||||
|
result.documentUid = uidMatch[1].trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract commitment ID
|
||||||
|
const commitmentMatch = text.match(/ID de transaction:\s*([^\n\r]+)/);
|
||||||
|
if (commitmentMatch && commitmentMatch[1]) {
|
||||||
|
result.commitmentId = commitmentMatch[1].trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract merkle proof
|
||||||
|
const merkleProofMatch = text.match(/Preuve Merkle \(Blockchain\):\s*([^\n\r]+)/);
|
||||||
|
if (merkleProofMatch && merkleProofMatch[1]) {
|
||||||
|
result.merkleProof = merkleProofMatch[1].trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
211
src/front/Services/WatermarkService/index.ts
Normal file
211
src/front/Services/WatermarkService/index.ts
Normal file
@ -0,0 +1,211 @@
|
|||||||
|
export default class WatermarkService {
|
||||||
|
private static instance: WatermarkService;
|
||||||
|
|
||||||
|
public static getInstance(): WatermarkService {
|
||||||
|
if (!WatermarkService.instance) {
|
||||||
|
WatermarkService.instance = new WatermarkService();
|
||||||
|
}
|
||||||
|
return WatermarkService.instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a watermark to a file based on its type
|
||||||
|
* @param file - The original file
|
||||||
|
* @returns Promise<File> - The file with watermark added
|
||||||
|
*/
|
||||||
|
public async addWatermark(file: File): Promise<File> {
|
||||||
|
const fileType = file.type;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (fileType.startsWith('image/')) {
|
||||||
|
return await this.addWatermarkToImage(file);
|
||||||
|
} else if (fileType === 'application/pdf') {
|
||||||
|
return await this.addWatermarkToPdf(file);
|
||||||
|
} else {
|
||||||
|
// For other file types, return the original file
|
||||||
|
console.log(`Watermark not supported for file type: ${fileType}`);
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error adding watermark:', error);
|
||||||
|
// Return original file if watermarking fails
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add watermark to image files
|
||||||
|
* @param file - Image file
|
||||||
|
* @returns Promise<File> - Image with watermark
|
||||||
|
*/
|
||||||
|
private async addWatermarkToImage(file: File): Promise<File> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = (event) => {
|
||||||
|
try {
|
||||||
|
const img = new Image();
|
||||||
|
img.onload = () => {
|
||||||
|
try {
|
||||||
|
// Create canvas
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
|
||||||
|
if (!ctx) {
|
||||||
|
reject(new Error('Could not get canvas context'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set canvas size to image size
|
||||||
|
canvas.width = img.width;
|
||||||
|
canvas.height = img.height;
|
||||||
|
|
||||||
|
// Draw original image
|
||||||
|
ctx.drawImage(img, 0, 0);
|
||||||
|
|
||||||
|
// Add watermark
|
||||||
|
this.addImageWatermark(ctx, img.width, img.height);
|
||||||
|
|
||||||
|
// Convert to blob
|
||||||
|
canvas.toBlob((blob) => {
|
||||||
|
if (blob) {
|
||||||
|
const watermarkedFile = new File([blob], file.name, { type: file.type });
|
||||||
|
resolve(watermarkedFile);
|
||||||
|
} else {
|
||||||
|
reject(new Error('Could not create blob from canvas'));
|
||||||
|
}
|
||||||
|
}, file.type);
|
||||||
|
} catch (error) {
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
img.onerror = reject;
|
||||||
|
img.src = event.target?.result as string;
|
||||||
|
} catch (error) {
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.onerror = reject;
|
||||||
|
reader.readAsDataURL(file);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add watermark to PDF files
|
||||||
|
* @param file - PDF file
|
||||||
|
* @returns Promise<File> - PDF with watermark
|
||||||
|
*/
|
||||||
|
private async addWatermarkToPdf(file: File): Promise<File> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = async (event) => {
|
||||||
|
try {
|
||||||
|
const arrayBuffer = event.target?.result as ArrayBuffer;
|
||||||
|
|
||||||
|
// Import pdf-lib dynamically to avoid SSR issues
|
||||||
|
const { PDFDocument, rgb } = await import('pdf-lib');
|
||||||
|
|
||||||
|
// Load the existing PDF
|
||||||
|
const pdfDoc = await PDFDocument.load(arrayBuffer);
|
||||||
|
|
||||||
|
// Get all pages
|
||||||
|
const pages = pdfDoc.getPages();
|
||||||
|
|
||||||
|
// Add watermark to each page
|
||||||
|
for (const page of pages) {
|
||||||
|
this.addPdfWatermark(page, rgb(0.8, 0.2, 0.2)); // Pale red color
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save the modified PDF
|
||||||
|
const pdfBytes = await pdfDoc.save();
|
||||||
|
const watermarkedFile = new File([pdfBytes], file.name, { type: file.type });
|
||||||
|
resolve(watermarkedFile);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error adding watermark to PDF:', error);
|
||||||
|
// If PDF watermarking fails, return original file
|
||||||
|
resolve(file);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.onerror = reject;
|
||||||
|
reader.readAsArrayBuffer(file);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add watermark to image using Canvas
|
||||||
|
* @param ctx - Canvas 2D context
|
||||||
|
* @param width - Image width
|
||||||
|
* @param height - Image height
|
||||||
|
*/
|
||||||
|
private addImageWatermark(ctx: CanvasRenderingContext2D, width: number, height: number): void {
|
||||||
|
// Save current state
|
||||||
|
ctx.save();
|
||||||
|
|
||||||
|
// Set watermark properties
|
||||||
|
ctx.fillStyle = 'rgba(128, 128, 128, 0.7)'; // Semi-transparent gray
|
||||||
|
ctx.font = '12px Arial';
|
||||||
|
ctx.textAlign = 'right';
|
||||||
|
ctx.textBaseline = 'bottom';
|
||||||
|
|
||||||
|
// Position watermark in bottom-right corner
|
||||||
|
const text = 'Processed by LeCoffre';
|
||||||
|
const x = width - 10; // 10 pixels from right edge
|
||||||
|
const y = height - 10; // 10 pixels from bottom
|
||||||
|
|
||||||
|
// Add watermark text
|
||||||
|
ctx.fillText(text, x, y);
|
||||||
|
|
||||||
|
// Restore state
|
||||||
|
ctx.restore();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add watermark to PDF using pdf-lib
|
||||||
|
* @param page - PDF page from pdf-lib
|
||||||
|
* @param color - Color for the watermark
|
||||||
|
*/
|
||||||
|
private addPdfWatermark(page: any, color: any): void {
|
||||||
|
const { width, height } = page.getSize();
|
||||||
|
|
||||||
|
// Calculate watermark position (bottom-right corner)
|
||||||
|
const text = 'Processed by LeCoffre';
|
||||||
|
const dateTime = new Date().toLocaleString('fr-FR', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit'
|
||||||
|
});
|
||||||
|
|
||||||
|
const fontSize = 10;
|
||||||
|
const lineHeight = 12; // Space between lines
|
||||||
|
|
||||||
|
// Calculate text widths (approximate - pdf-lib doesn't have a direct method for this)
|
||||||
|
// Using a conservative estimate: ~6 points per character for 10pt font
|
||||||
|
const estimatedTextWidth1 = text.length * 6;
|
||||||
|
const estimatedTextWidth2 = dateTime.length * 6;
|
||||||
|
const maxTextWidth = Math.max(estimatedTextWidth1, estimatedTextWidth2);
|
||||||
|
|
||||||
|
// Position watermark with proper margins (20 points from edges)
|
||||||
|
const x = width - maxTextWidth - 20; // 20 points from right edge
|
||||||
|
const y = 20; // 20 points from bottom
|
||||||
|
|
||||||
|
// Add watermark text with transparency (first line)
|
||||||
|
page.drawText(text, {
|
||||||
|
x: x,
|
||||||
|
y: y + lineHeight, // Second line (top)
|
||||||
|
size: fontSize,
|
||||||
|
color: color,
|
||||||
|
opacity: 0.7
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add date/time with transparency (second line)
|
||||||
|
page.drawText(dateTime, {
|
||||||
|
x: x,
|
||||||
|
y: y, // First line (bottom)
|
||||||
|
size: fontSize,
|
||||||
|
color: color,
|
||||||
|
opacity: 0.7
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -6,6 +6,7 @@ import EventBus from './EventBus';
|
|||||||
import User from './User';
|
import User from './User';
|
||||||
|
|
||||||
import MapUtils from './MapUtils';
|
import MapUtils from './MapUtils';
|
||||||
|
import { FileBlob } from '../front/Api/Entities/types';
|
||||||
|
|
||||||
export default class MessageBus {
|
export default class MessageBus {
|
||||||
private static instance: MessageBus;
|
private static instance: MessageBus;
|
||||||
@ -113,61 +114,71 @@ export default class MessageBus {
|
|||||||
|
|
||||||
const publicDataDecoded: { [key: string]: any } = {};
|
const publicDataDecoded: { [key: string]: any } = {};
|
||||||
|
|
||||||
for (let stateId = 0; stateId < process.states.length - 1; stateId++) {
|
// We only care about the public data as they are in the last commited state
|
||||||
const state = process.states[stateId];
|
const processTip = process.states[process.states.length - 1].commited_in;
|
||||||
if (!state) {
|
const lastCommitedState = process.states.findLast((state: any) => state.commited_in !== processTip);
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const publicDataEncoded = state.public_data;
|
if (!lastCommitedState) {
|
||||||
if (!publicDataEncoded) {
|
continue;
|
||||||
continue;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
for (const key of Object.keys(publicDataEncoded)) {
|
const publicDataEncoded = lastCommitedState.public_data;
|
||||||
publicDataDecoded[key] = await this.getPublicData(publicDataEncoded[key]);
|
if (!publicDataEncoded) {
|
||||||
}
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const key of Object.keys(publicDataEncoded)) {
|
||||||
|
publicDataDecoded[key] = await this.getPublicData(publicDataEncoded[key]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!(publicDataDecoded['uid'] && publicDataDecoded['uid'] === uid && publicDataDecoded['utype'] && publicDataDecoded['utype'] === 'file')) {
|
if (!(publicDataDecoded['uid'] && publicDataDecoded['uid'] === uid && publicDataDecoded['utype'] && publicDataDecoded['utype'] === 'file')) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// We take the file in it's latest commited state
|
||||||
let file: any;
|
let file: any;
|
||||||
|
|
||||||
for (let stateId = 0; stateId < process.states.length - 1; stateId++) {
|
// Which is the last state that updated file_blob?
|
||||||
const lastState = process.states[stateId];
|
const lastUpdatedFileState = process.states.findLast((state: any) => state.pcd_commitment['file_blob']);
|
||||||
if (!lastState) {
|
|
||||||
|
if (!lastUpdatedFileState) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const processData = await this.getData(processId, lastUpdatedFileState.state_id);
|
||||||
|
const isEmpty = Object.keys(processData).length === 0;
|
||||||
|
if (isEmpty) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const lastStateId = lastState.state_id;
|
const publicDataEncoded = lastUpdatedFileState.public_data;
|
||||||
if (!lastStateId) {
|
if (!publicDataEncoded) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
const publicDataDecoded: { [key: string]: any } = {};
|
||||||
try {
|
for (const key of Object.keys(publicDataEncoded)) {
|
||||||
const processData = await this.getData(processId, lastStateId);
|
publicDataDecoded[key] = await this.getPublicData(publicDataEncoded[key]);
|
||||||
const isEmpty = Object.keys(processData).length === 0;
|
|
||||||
if (isEmpty) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!file) {
|
|
||||||
file = {
|
|
||||||
processId,
|
|
||||||
lastStateId,
|
|
||||||
processData,
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
for (const key of Object.keys(processData)) {
|
|
||||||
file.processData[key] = processData[key];
|
|
||||||
}
|
|
||||||
file.lastStateId = lastStateId;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!file) {
|
||||||
|
file = {
|
||||||
|
processId,
|
||||||
|
lastUpdatedFileState,
|
||||||
|
processData,
|
||||||
|
publicDataDecoded,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
for (const key of Object.keys(processData)) {
|
||||||
|
file.processData[key] = processData[key];
|
||||||
|
}
|
||||||
|
file.lastUpdatedFileState = lastUpdatedFileState;
|
||||||
|
for (const key of Object.keys(publicDataDecoded)) {
|
||||||
|
file.publicDataDecoded[key] = publicDataDecoded[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
files.push(file);
|
files.push(file);
|
||||||
@ -557,6 +568,84 @@ export default class MessageBus {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hash a document file using SHA-256
|
||||||
|
* @param fileBlob - The file blob to hash
|
||||||
|
* @returns Promise<string> - The SHA-256 hash of the file
|
||||||
|
*/
|
||||||
|
public hashDocument(fileBlob: FileBlob, commitedIn: string): Promise<string> {
|
||||||
|
return new Promise<string>((resolve: (hash: string) => void, reject: (error: string) => void) => {
|
||||||
|
this.checkToken().then(() => {
|
||||||
|
const messageId = `HASH_VALUE_${uuidv4()}`;
|
||||||
|
|
||||||
|
const unsubscribe = EventBus.getInstance().on('VALUE_HASHED', (responseId: string, hash: string) => {
|
||||||
|
if (responseId !== messageId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unsubscribe();
|
||||||
|
resolve(hash);
|
||||||
|
});
|
||||||
|
|
||||||
|
const unsubscribeError = EventBus.getInstance().on('ERROR_VALUE_HASHED', (responseId: string, error: string) => {
|
||||||
|
if (responseId !== messageId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unsubscribeError();
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
|
||||||
|
const user = User.getInstance();
|
||||||
|
const accessToken = user.getAccessToken()!;
|
||||||
|
|
||||||
|
const label = 'file_blob';
|
||||||
|
|
||||||
|
this.sendMessage({
|
||||||
|
type: 'HASH_VALUE',
|
||||||
|
accessToken,
|
||||||
|
commitedIn,
|
||||||
|
label,
|
||||||
|
fileBlob,
|
||||||
|
messageId
|
||||||
|
});
|
||||||
|
}).catch(reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public generateMerkleProof(processState: any, attributeName: string): Promise<any> {
|
||||||
|
return new Promise<any>((resolve: (proof: any) => void, reject: (error: string) => void) => {
|
||||||
|
this.checkToken().then(() => {
|
||||||
|
const messageId = `GET_MERKLE_PROOF_${uuidv4()}`;
|
||||||
|
|
||||||
|
const unsubscribe = EventBus.getInstance().on('MERKLE_PROOF_RETRIEVED', (responseId: string, proof: any) => {
|
||||||
|
if (responseId !== messageId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unsubscribe();
|
||||||
|
resolve(proof);
|
||||||
|
});
|
||||||
|
|
||||||
|
const unsubscribeError = EventBus.getInstance().on('ERROR_MERKLE_PROOF_RETRIEVED', (responseId: string, error: string) => {
|
||||||
|
if (responseId !== messageId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unsubscribeError();
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
|
||||||
|
const user = User.getInstance();
|
||||||
|
const accessToken = user.getAccessToken()!;
|
||||||
|
|
||||||
|
this.sendMessage({
|
||||||
|
type: 'GET_MERKLE_PROOF',
|
||||||
|
accessToken,
|
||||||
|
processState,
|
||||||
|
attributeName,
|
||||||
|
messageId
|
||||||
|
});
|
||||||
|
}).catch(reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private validateToken(): Promise<boolean> {
|
private validateToken(): Promise<boolean> {
|
||||||
return new Promise<boolean>((resolve: (isValid: boolean) => void, reject: (error: string) => void) => {
|
return new Promise<boolean>((resolve: (isValid: boolean) => void, reject: (error: string) => void) => {
|
||||||
const messageId = `VALIDATE_TOKEN_${uuidv4()}`;
|
const messageId = `VALIDATE_TOKEN_${uuidv4()}`;
|
||||||
@ -647,7 +736,7 @@ export default class MessageBus {
|
|||||||
console.error('[MessageBus] sendMessage: iframe not found');
|
console.error('[MessageBus] sendMessage: iframe not found');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
console.log('[MessageBus] sendMessage:', message);
|
// console.log('[MessageBus] sendMessage:', message);
|
||||||
iframe.contentWindow?.postMessage(message, targetOrigin);
|
iframe.contentWindow?.postMessage(message, targetOrigin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -684,7 +773,7 @@ export default class MessageBus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const message = event.data;
|
const message = event.data;
|
||||||
console.log('[MessageBus] handleMessage:', message);
|
// console.log('[MessageBus] handleMessage:', message);
|
||||||
|
|
||||||
switch (message.type) {
|
switch (message.type) {
|
||||||
case 'LISTENING':
|
case 'LISTENING':
|
||||||
@ -746,6 +835,14 @@ export default class MessageBus {
|
|||||||
this.doHandleMessage(message.messageId, 'STATE_VALIDATED', message, (message: any) => message.validatedProcess);
|
this.doHandleMessage(message.messageId, 'STATE_VALIDATED', message, (message: any) => message.validatedProcess);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
case 'VALUE_HASHED': // HASH_VALUE
|
||||||
|
this.doHandleMessage(message.messageId, 'VALUE_HASHED', message, (message: any) => message.hash);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'MERKLE_PROOF_RETRIEVED': // GENERATE_MERKLE_PROOF
|
||||||
|
this.doHandleMessage(message.messageId, 'MERKLE_PROOF_RETRIEVED', message, (message: any) => message.proof);
|
||||||
|
break;
|
||||||
|
|
||||||
case 'ERROR':
|
case 'ERROR':
|
||||||
console.error('Error:', message);
|
console.error('Error:', message);
|
||||||
this.errors[message.messageId] = message.error;
|
this.errors[message.messageId] = message.error;
|
||||||
|
Loading…
x
Reference in New Issue
Block a user