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",
|
||||
"le-coffre-resources": "file:../lecoffre-ressources",
|
||||
"next": "^14.2.3",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"prettier": "^2.8.7",
|
||||
"react": "18.2.0",
|
||||
"react-dom": "18.2.0",
|
||||
|
@ -9,7 +9,7 @@ export default class DocumentTypeService {
|
||||
|
||||
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 processData: any = {
|
||||
@ -18,7 +18,7 @@ export default class DocumentTypeService {
|
||||
isDeleted: 'false',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
...documentData,
|
||||
...documentTypeData,
|
||||
};
|
||||
|
||||
const privateFields: string[] = Object.keys(processData);
|
||||
|
@ -2,6 +2,7 @@ import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import MessageBus from 'src/sdk/MessageBus';
|
||||
import User from 'src/sdk/User';
|
||||
import { FileData } from '../../../../front/Api/Entities/types';
|
||||
|
||||
export default class FileService {
|
||||
|
||||
@ -9,7 +10,7 @@ export default class FileService {
|
||||
|
||||
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 processData: any = {
|
||||
@ -81,7 +82,7 @@ export default class FileService {
|
||||
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) => {
|
||||
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
||||
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>
|
||||
{documentFiles.length > 0 && (
|
||||
<div className={classes["documents"]}>
|
||||
{documentFiles.map((documentFile) => (
|
||||
{documentFiles.map((documentFile, index) => (
|
||||
<DocumentFileElement
|
||||
key={documentFile.id}
|
||||
key={documentFile.uid || `${documentFile.id}-${index}`}
|
||||
isLoading={documentFile.isLoading}
|
||||
file={documentFile.file}
|
||||
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 DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import { FileBlob, FileData } from "@Front/Api/Entities/types";
|
||||
import WatermarkService from "@Front/Services/WatermarkService";
|
||||
|
||||
type IProps = {
|
||||
document: any;
|
||||
@ -30,50 +32,101 @@ export default function DepositDocumentComponent(props: IProps) {
|
||||
}, [document.files]);
|
||||
|
||||
const addFile = useCallback(
|
||||
(file: 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);
|
||||
async (file: File) => {
|
||||
try {
|
||||
// Add watermark to the file before processing
|
||||
const watermarkedFile = await WatermarkService.getInstance().addWatermark(file);
|
||||
|
||||
const fileBlob: any = {
|
||||
type: file.type,
|
||||
data: uint8Array
|
||||
};
|
||||
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 fileData: any = {
|
||||
file_blob: fileBlob,
|
||||
file_name: file.name
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
const fileBlob: FileBlob = {
|
||||
type: watermarkedFile.type,
|
||||
data: uint8Array
|
||||
};
|
||||
|
||||
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
|
||||
const fileUid: string = processCreated.processData.uid;
|
||||
const fileData: FileData = {
|
||||
file_blob: fileBlob,
|
||||
file_name: watermarkedFile.name
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
|
||||
if (process) {
|
||||
const document: any = process.processData;
|
||||
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
|
||||
const fileUid: string = processCreated.processData.uid;
|
||||
|
||||
let files: any[] = document.files;
|
||||
if (!files) {
|
||||
files = [];
|
||||
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());
|
||||
}
|
||||
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 }));
|
||||
}
|
||||
};
|
||||
reader.readAsArrayBuffer(watermarkedFile);
|
||||
})
|
||||
.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 }));
|
||||
} 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],
|
||||
);
|
||||
@ -82,9 +135,9 @@ export default function DepositDocumentComponent(props: IProps) {
|
||||
(fileUid: string) => {
|
||||
return new Promise<void>(
|
||||
(resolve: () => void) => {
|
||||
FileService.getFileByUid(fileUid).then((process: any) => {
|
||||
if (process) {
|
||||
FileService.updateFile(process, { isDeleted: 'true' }).then(() => {
|
||||
FileService.getFileByUid(fileUid).then((res: any) => {
|
||||
if (res) {
|
||||
FileService.updateFile(res.processId, { isDeleted: 'true' }).then(() => {
|
||||
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
|
||||
if (process) {
|
||||
const document: any = process.processData;
|
||||
|
@ -7,6 +7,7 @@ import { DocumentNotary } from "le-coffre-resources/dist/Notary";
|
||||
import Image from "next/image";
|
||||
import { NextRouter, useRouter } from "next/router";
|
||||
import React from "react";
|
||||
import { FileBlob } from "@Front/Api/Entities/types";
|
||||
|
||||
import BasePage from "../../Base";
|
||||
import classes from "./classes.module.scss";
|
||||
@ -25,7 +26,7 @@ type IState = {
|
||||
isValidateModalVisible: boolean;
|
||||
refuseText: string;
|
||||
selectedFileIndex: number;
|
||||
selectedFile: any;
|
||||
selectedFile: { uid: string; file_name: string; file_blob: FileBlob } | null;
|
||||
documentNotary: DocumentNotary | null;
|
||||
fileBlob: Blob | null;
|
||||
isLoading: boolean;
|
||||
@ -132,7 +133,7 @@ class ViewDocumentsNotaryClass extends BasePage<IPropsClass, IState> {
|
||||
{
|
||||
documentNotary,
|
||||
selectedFileIndex: 0,
|
||||
selectedFile: documentNotary.files![0]!,
|
||||
selectedFile: documentNotary.files![0] as any,
|
||||
isLoading: false,
|
||||
},
|
||||
() => {
|
||||
|
@ -141,7 +141,7 @@ export default function ClientDashboard(props: IProps) {
|
||||
let documents: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
// 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) {
|
||||
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"] });
|
||||
|
||||
const documentData: any = {
|
||||
const documentTypeData: any = {
|
||||
...values,
|
||||
office: {
|
||||
uid: officeId,
|
||||
@ -48,7 +48,7 @@ export default function DocumentTypesCreate(props: IProps) {
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
LoaderService.getInstance().show();
|
||||
DocumentTypeService.createDocumentType(documentData, validatorId).then((processCreated: any) => {
|
||||
DocumentTypeService.createDocumentType(documentTypeData, validatorId).then((processCreated: any) => {
|
||||
ToasterService.getInstance().success({
|
||||
title: "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 AutocompleteMultiSelectField from "@Front/Components/DesignSystem/Form/AutocompleteMultiSelectField";
|
||||
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 Modal from "@Front/Components/DesignSystem/Modal";
|
||||
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 classes from "./classes.module.scss";
|
||||
|
||||
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 = {
|
||||
isCreateDocumentModalVisible: boolean;
|
||||
@ -75,18 +75,38 @@ export default function ParameterDocuments(props: IProps) {
|
||||
const addDocument = useCallback(async () => {
|
||||
if (addOrEditDocument === "add") {
|
||||
try {
|
||||
const documentType = await DocumentTypes.getInstance().post({
|
||||
LoaderService.getInstance().show();
|
||||
|
||||
const documentTypeData: any = {
|
||||
name: documentName,
|
||||
private_description: visibleDescription,
|
||||
office: {
|
||||
uid: props.folder.office!.uid!,
|
||||
},
|
||||
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!;
|
||||
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
|
||||
@ -100,28 +120,44 @@ export default function ParameterDocuments(props: IProps) {
|
||||
props.onDocumentsUpdated([newDocumentType]);
|
||||
}
|
||||
|
||||
LoaderService.getInstance().hide();
|
||||
handleClose();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
LoaderService.getInstance().show();
|
||||
|
||||
const oldDocumentsType = props.folder.deed?.document_types!;
|
||||
await Deeds.getInstance().put(props.folder.deed?.uid!, {
|
||||
document_types: [
|
||||
...oldDocumentsType,
|
||||
...selectedDocuments.map((document) => DocumentType.hydrate<DocumentType>({ uid: document.id as string })),
|
||||
],
|
||||
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 })),
|
||||
...selectedDocuments.map((document: any) => ({ uid: document.id as string }))
|
||||
]
|
||||
}).then(() => resolve());
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Get the full document details for the selected documents
|
||||
const documentsById = await Promise.all(
|
||||
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 {
|
||||
label: fullDoc.name!,
|
||||
value: fullDoc.uid!,
|
||||
description: fullDoc.private_description!,
|
||||
label: documentType.name!,
|
||||
value: documentType.uid!,
|
||||
description: documentType.private_description!,
|
||||
} as IFormOption;
|
||||
})
|
||||
);
|
||||
@ -130,6 +166,7 @@ export default function ParameterDocuments(props: IProps) {
|
||||
props.onDocumentsUpdated(documentsById);
|
||||
}
|
||||
|
||||
LoaderService.getInstance().hide();
|
||||
handleClose();
|
||||
} catch (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 DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
import { DocumentData } from "../FolderInformation/ClientView/DocumentTables/types";
|
||||
|
||||
export default function AskDocuments() {
|
||||
const router = useRouter();
|
||||
@ -62,17 +63,21 @@ export default function AskDocuments() {
|
||||
LoaderService.getInstance().show();
|
||||
const documentAsked: [] = values["document_types"] as [];
|
||||
for (let i = 0; i < documentAsked.length; i++) {
|
||||
const documentTypeUid = documentAsked[i];
|
||||
if (!documentTypeUid) continue;
|
||||
|
||||
const documentData: any = {
|
||||
folder: {
|
||||
uid: folderUid,
|
||||
uid: folderUid as string,
|
||||
},
|
||||
depositor: {
|
||||
uid: customerUid,
|
||||
uid: customerUid as string,
|
||||
},
|
||||
document_type: {
|
||||
uid: documentAsked[i]
|
||||
uid: documentTypeUid
|
||||
},
|
||||
document_status: EDocumentStatus.ASKED
|
||||
document_status: EDocumentStatus.ASKED,
|
||||
file_uid: null,
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
|
@ -1,8 +1,12 @@
|
||||
import Modal from "@Front/Components/DesignSystem/Modal";
|
||||
import React from "react";
|
||||
import { FileBlob } from "@Front/Api/Entities/types";
|
||||
|
||||
type IProps = {
|
||||
file: any;
|
||||
file: {
|
||||
uid: string;
|
||||
file_blob: FileBlob;
|
||||
};
|
||||
url: string;
|
||||
isOpen: boolean;
|
||||
onClose?: () => void;
|
||||
|
@ -1,4 +1,3 @@
|
||||
import FilesNotary from "@Front/Api/LeCoffreApi/Notary/FilesNotary/Files";
|
||||
import CircleProgress from "@Front/Components/DesignSystem/CircleProgress";
|
||||
import IconButton from "@Front/Components/DesignSystem/IconButton";
|
||||
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 Module from "@Front/Config/Module";
|
||||
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 { Document } from "le-coffre-resources/dist/Customer";
|
||||
import { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document";
|
||||
import DocumentNotary, { EDocumentNotaryStatus } from "le-coffre-resources/dist/Notary/DocumentNotary";
|
||||
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 FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||
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 = {
|
||||
customerUid: string;
|
||||
@ -44,7 +45,7 @@ const tradDocumentsNotaryStatus: Record<EDocumentNotaryStatus, string> = {
|
||||
|
||||
export default function DocumentTables(props: IProps) {
|
||||
const { folderUid, customerUid } = props;
|
||||
const [documents, setDocuments] = useState<Document[]>([]);
|
||||
const [documents, setDocuments] = useState<any[]>([]);
|
||||
const [documentsNotary, setDocumentsNotary] = useState<DocumentNotary[]>([]);
|
||||
const [focusedDocumentUid, setFocusedDocumentUid] = useState<string | null>(null);
|
||||
|
||||
@ -63,6 +64,12 @@ export default function DocumentTables(props: IProps) {
|
||||
// FilterBy folder.uid & depositor.uid
|
||||
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) {
|
||||
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));
|
||||
}, []);
|
||||
|
||||
const onDownloadFileNotary = useCallback((doc: DocumentNotary) => {
|
||||
const onDownloadFileNotary = useCallback((doc: any) => {
|
||||
const file = doc.files?.[0];
|
||||
if (!file || !file?.uid) return;
|
||||
if (!file) return;
|
||||
|
||||
return FilesNotary.getInstance()
|
||||
.download(file.uid)
|
||||
.then((blob) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = file.file_name ?? "file";
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch((e) => console.warn(e));
|
||||
return new Promise<void>((resolve: () => void) => {
|
||||
const blob = new Blob([file.file_blob.data], { type: file.file_blob.type });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = file.file_name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
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(
|
||||
() =>
|
||||
documents
|
||||
@ -181,21 +255,25 @@ export default function DocumentTables(props: IProps) {
|
||||
if (document.document_status !== EDocumentStatus.ASKED) return null;
|
||||
return {
|
||||
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: {
|
||||
sx: { width: 107 },
|
||||
content: (
|
||||
<Tag
|
||||
color={ETagColor.INFO}
|
||||
variant={ETagVariant.SEMI_BOLD}
|
||||
label={tradDocumentStatus[document.document_status].toUpperCase()}
|
||||
label={tradDocumentStatus[document.document_status as EDocumentStatus].toUpperCase()}
|
||||
/>
|
||||
),
|
||||
},
|
||||
date: {
|
||||
sx: { width: 107 },
|
||||
sx: { width: 120 },
|
||||
content: document.created_at ? new Date(document.created_at).toLocaleDateString() : "_",
|
||||
},
|
||||
file: {
|
||||
sx: { width: 120 },
|
||||
content: "_",
|
||||
},
|
||||
actions: {
|
||||
sx: { width: 76 },
|
||||
content: (
|
||||
@ -217,21 +295,25 @@ export default function DocumentTables(props: IProps) {
|
||||
if (document.document_status !== EDocumentStatus.DEPOSITED) return null;
|
||||
return {
|
||||
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: {
|
||||
sx: { width: 107 },
|
||||
content: (
|
||||
<Tag
|
||||
color={ETagColor.WARNING}
|
||||
variant={ETagVariant.SEMI_BOLD}
|
||||
label={tradDocumentStatus[document.document_status].toUpperCase()}
|
||||
label={tradDocumentStatus[document.document_status as EDocumentStatus].toUpperCase()}
|
||||
/>
|
||||
),
|
||||
},
|
||||
date: {
|
||||
sx: { width: 107 },
|
||||
sx: { width: 120 },
|
||||
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
||||
},
|
||||
file: {
|
||||
sx: { width: 120 },
|
||||
content: document.files?.[0]?.file_name ?? "_",
|
||||
},
|
||||
actions: {
|
||||
sx: { width: 76 },
|
||||
content: (
|
||||
@ -253,27 +335,31 @@ export default function DocumentTables(props: IProps) {
|
||||
);
|
||||
|
||||
const validatedDocuments: IRowProps[] = useMemo(
|
||||
() =>
|
||||
documents
|
||||
() => {
|
||||
const validated = documents
|
||||
.map((document) => {
|
||||
if (document.document_status !== EDocumentStatus.VALIDATED) return null;
|
||||
return {
|
||||
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: {
|
||||
sx: { width: 107 },
|
||||
content: (
|
||||
<Tag
|
||||
color={ETagColor.SUCCESS}
|
||||
variant={ETagVariant.SEMI_BOLD}
|
||||
label={tradDocumentStatus[document.document_status].toUpperCase()}
|
||||
label={tradDocumentStatus[document.document_status as EDocumentStatus].toUpperCase()}
|
||||
/>
|
||||
),
|
||||
},
|
||||
date: {
|
||||
sx: { width: 107 },
|
||||
sx: { width: 120 },
|
||||
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
||||
},
|
||||
file: {
|
||||
sx: { width: 120 },
|
||||
content: document.files?.[0]?.file_name ?? "_",
|
||||
},
|
||||
actions: {
|
||||
sx: { width: 76 },
|
||||
content: (
|
||||
@ -286,13 +372,17 @@ export default function DocumentTables(props: IProps) {
|
||||
<IconButton icon={<EyeIcon />} />
|
||||
</Link>
|
||||
<IconButton onClick={() => onDownload(document)} icon={<ArrowDownTrayIcon />} />
|
||||
<IconButton onClick={() => onDownloadCertificate(document)} icon={<DocumentTextIcon />} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
};
|
||||
})
|
||||
.filter((document) => document !== null) as IRowProps[],
|
||||
[documents, folderUid, onDownload],
|
||||
.filter((document) => document !== null) as IRowProps[];
|
||||
|
||||
return validated;
|
||||
},
|
||||
[documents, folderUid, onDownload, onDownloadCertificate],
|
||||
);
|
||||
|
||||
const refusedDocuments: IRowProps[] = useMemo(
|
||||
@ -302,14 +392,14 @@ export default function DocumentTables(props: IProps) {
|
||||
if (document.document_status !== EDocumentStatus.REFUSED) return null;
|
||||
return {
|
||||
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: {
|
||||
sx: { width: 107 },
|
||||
content: (
|
||||
<Tag
|
||||
color={ETagColor.ERROR}
|
||||
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 {
|
||||
key: document.uid,
|
||||
document_type: {
|
||||
sx: { width: 400 },
|
||||
sx: { width: 300 },
|
||||
content: formatName(document.files?.[0]?.file_name?.split(".")?.[0] ?? "") || "_",
|
||||
},
|
||||
document_status: {
|
||||
@ -339,9 +429,13 @@ export default function DocumentTables(props: IProps) {
|
||||
content: getTagForSentDocument(document.document_status as EDocumentNotaryStatus),
|
||||
},
|
||||
date: {
|
||||
sx: { width: 107 },
|
||||
sx: { width: 120 },
|
||||
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
||||
},
|
||||
file: {
|
||||
sx: { width: 120 },
|
||||
content: document.files?.[0]?.file_name ?? "_",
|
||||
},
|
||||
actions: {
|
||||
sx: { width: 76 },
|
||||
content: (
|
||||
@ -428,6 +522,10 @@ function getHeader(dateColumnTitle: string, isMobile: boolean): IHead[] {
|
||||
key: "date",
|
||||
title: dateColumnTitle,
|
||||
},
|
||||
{
|
||||
key: "file",
|
||||
title: "Fichier",
|
||||
},
|
||||
{
|
||||
key: "actions",
|
||||
title: "Action",
|
||||
|
@ -19,6 +19,7 @@ import MessageBox from "@Front/Components/Elements/MessageBox";
|
||||
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||
import { FileBlob } from "@Front/Api/Entities/types";
|
||||
|
||||
type IProps = {};
|
||||
type IPropsClass = {
|
||||
@ -32,7 +33,7 @@ type IState = {
|
||||
isValidateModalVisible: boolean;
|
||||
refuseText: string;
|
||||
selectedFileIndex: number;
|
||||
selectedFile: any; // File | null; TODO: review
|
||||
selectedFile: { uid: string; file_name: string; file_blob: FileBlob } | null;
|
||||
validatedPercentage: number;
|
||||
document: Document | null;
|
||||
fileBlob: Blob | null;
|
||||
@ -237,6 +238,8 @@ class ViewDocumentsClass extends BasePage<IPropsClass, IState> {
|
||||
|
||||
private async getFilePreview(): Promise<void> {
|
||||
try {
|
||||
if (!this.state.selectedFile) return;
|
||||
|
||||
const fileBlob: Blob = new Blob([this.state.selectedFile.file_blob.data], { type: this.state.selectedFile.file_blob.type });
|
||||
this.setState({
|
||||
fileBlob,
|
||||
@ -247,7 +250,7 @@ class ViewDocumentsClass extends BasePage<IPropsClass, IState> {
|
||||
}
|
||||
|
||||
private downloadFile() {
|
||||
if (!this.state.fileBlob) return;
|
||||
if (!this.state.fileBlob || !this.state.selectedFile) return;
|
||||
|
||||
const url = URL.createObjectURL(this.state.fileBlob);
|
||||
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 MapUtils from './MapUtils';
|
||||
import { FileBlob } from '../front/Api/Entities/types';
|
||||
|
||||
export default class MessageBus {
|
||||
private static instance: MessageBus;
|
||||
@ -113,61 +114,71 @@ export default class MessageBus {
|
||||
|
||||
const publicDataDecoded: { [key: string]: any } = {};
|
||||
|
||||
for (let stateId = 0; stateId < process.states.length - 1; stateId++) {
|
||||
const state = process.states[stateId];
|
||||
if (!state) {
|
||||
continue;
|
||||
}
|
||||
// We only care about the public data as they are in the last commited state
|
||||
const processTip = process.states[process.states.length - 1].commited_in;
|
||||
const lastCommitedState = process.states.findLast((state: any) => state.commited_in !== processTip);
|
||||
|
||||
const publicDataEncoded = state.public_data;
|
||||
if (!publicDataEncoded) {
|
||||
continue;
|
||||
}
|
||||
if (!lastCommitedState) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const key of Object.keys(publicDataEncoded)) {
|
||||
publicDataDecoded[key] = await this.getPublicData(publicDataEncoded[key]);
|
||||
}
|
||||
const publicDataEncoded = lastCommitedState.public_data;
|
||||
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')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// We take the file in it's latest commited state
|
||||
let file: any;
|
||||
|
||||
for (let stateId = 0; stateId < process.states.length - 1; stateId++) {
|
||||
const lastState = process.states[stateId];
|
||||
if (!lastState) {
|
||||
// Which is the last state that updated file_blob?
|
||||
const lastUpdatedFileState = process.states.findLast((state: any) => state.pcd_commitment['file_blob']);
|
||||
|
||||
if (!lastUpdatedFileState) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const processData = await this.getData(processId, lastUpdatedFileState.state_id);
|
||||
const isEmpty = Object.keys(processData).length === 0;
|
||||
if (isEmpty) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const lastStateId = lastState.state_id;
|
||||
if (!lastStateId) {
|
||||
const publicDataEncoded = lastUpdatedFileState.public_data;
|
||||
if (!publicDataEncoded) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const processData = await this.getData(processId, lastStateId);
|
||||
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);
|
||||
const publicDataDecoded: { [key: string]: any } = {};
|
||||
for (const key of Object.keys(publicDataEncoded)) {
|
||||
publicDataDecoded[key] = await this.getPublicData(publicDataEncoded[key]);
|
||||
}
|
||||
|
||||
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);
|
||||
@ -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> {
|
||||
return new Promise<boolean>((resolve: (isValid: boolean) => void, reject: (error: string) => void) => {
|
||||
const messageId = `VALIDATE_TOKEN_${uuidv4()}`;
|
||||
@ -647,7 +736,7 @@ export default class MessageBus {
|
||||
console.error('[MessageBus] sendMessage: iframe not found');
|
||||
return;
|
||||
}
|
||||
console.log('[MessageBus] sendMessage:', message);
|
||||
// console.log('[MessageBus] sendMessage:', message);
|
||||
iframe.contentWindow?.postMessage(message, targetOrigin);
|
||||
}
|
||||
|
||||
@ -684,7 +773,7 @@ export default class MessageBus {
|
||||
}
|
||||
|
||||
const message = event.data;
|
||||
console.log('[MessageBus] handleMessage:', message);
|
||||
// console.log('[MessageBus] handleMessage:', message);
|
||||
|
||||
switch (message.type) {
|
||||
case 'LISTENING':
|
||||
@ -746,6 +835,14 @@ export default class MessageBus {
|
||||
this.doHandleMessage(message.messageId, 'STATE_VALIDATED', message, (message: any) => message.validatedProcess);
|
||||
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':
|
||||
console.error('Error:', message);
|
||||
this.errors[message.messageId] = message.error;
|
||||
|
Loading…
x
Reference in New Issue
Block a user