From 7435a33fe0416cec5635556a8d014ed7e14d737a Mon Sep 17 00:00:00 2001 From: Anthony Janin Date: Wed, 25 Jun 2025 20:46:37 +0200 Subject: [PATCH] Fix ask-document page --- .vscode/settings.json | 4 +- .../{ProfileService.ts => CustomerService.ts} | 22 +- .../Api/LeCoffreApi/sdk/DeedTypeService.ts | 122 ++++ .../Api/LeCoffreApi/sdk/DocumentService.ts | 95 ++++ .../Api/LeCoffreApi/sdk/FolderService.ts | 42 +- .../DefaultDeedTypeDashboard/index.tsx | 36 +- .../DefaultDocumentTypesDashboard/index.tsx | 44 +- .../DefaultNotaryDashboard/index.tsx | 7 +- .../ReceivedDocuments/index.tsx | 3 - .../DeedTypes/DeedTypesCreate/index.tsx | 50 +- .../DeedTypes/DeedTypesInformations/index.tsx | 121 ++-- .../DocumentTypesCreate/index.tsx | 66 +-- .../DocumentTypesInformations/index.tsx | 24 +- .../Folder/AddClientToFolder/index.tsx | 121 ++-- .../AskDocuments/ParameterDocuments/index.tsx | 37 +- .../Layouts/Folder/AskDocuments/index.tsx | 14 + .../Layouts/Folder/CreateFolder/index.tsx | 57 +- .../FolderInformation/ClientView/index.tsx | 15 +- .../elements/AnchoringModal/index.tsx | 2 +- .../Folder/FolderInformation/index.tsx | 9 +- .../Layouts/Folder/UpdateClient/index.tsx | 2 +- src/front/Components/Layouts/Folder/index.tsx | 20 +- src/pages/_app.tsx | 28 +- src/sdk/MessageBus.ts | 532 ++++-------------- 24 files changed, 611 insertions(+), 862 deletions(-) rename src/common/Api/LeCoffreApi/sdk/{ProfileService.ts => CustomerService.ts} (80%) create mode 100644 src/common/Api/LeCoffreApi/sdk/DeedTypeService.ts create mode 100644 src/common/Api/LeCoffreApi/sdk/DocumentService.ts diff --git a/.vscode/settings.json b/.vscode/settings.json index 2fec080c..2e8ae06f 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,7 +1,7 @@ { "editor.defaultFormatter": "esbenp.prettier-vscode", "[typescript]": { - "editor.defaultFormatter": "esbenp.prettier-vscode" + "editor.defaultFormatter": "vscode.typescript-language-features" }, "[json]": { "editor.defaultFormatter": "esbenp.prettier-vscode" @@ -32,6 +32,6 @@ "rust-client.disableRustup": true, "rust-client.autoStartRls": false, "[typescriptreact]": { - "editor.defaultFormatter": "esbenp.prettier-vscode" + "editor.defaultFormatter": "vscode.typescript-language-features" } } \ No newline at end of file diff --git a/src/common/Api/LeCoffreApi/sdk/ProfileService.ts b/src/common/Api/LeCoffreApi/sdk/CustomerService.ts similarity index 80% rename from src/common/Api/LeCoffreApi/sdk/ProfileService.ts rename to src/common/Api/LeCoffreApi/sdk/CustomerService.ts index 813f0613..963822b8 100644 --- a/src/common/Api/LeCoffreApi/sdk/ProfileService.ts +++ b/src/common/Api/LeCoffreApi/sdk/CustomerService.ts @@ -4,22 +4,22 @@ import { v4 as uuidv4 } from 'uuid'; import MessageBus from 'src/sdk/MessageBus'; import User from 'src/sdk/User'; -export default class ProfileService { +export default class CustomerService { private static readonly messageBus: MessageBus = MessageBus.getInstance(); private constructor() { } - public static createProfile(profileData: any, validatorId: string): Promise { + public static createCustomer(customerData: any, validatorId: string): Promise { const ownerId = User.getInstance().getPairingId()!; const processData: any = { uid: uuidv4(), - utype: 'profile', + utype: 'customer', isDeleted: 'false', created_at: new Date().toISOString(), updated_at: new Date().toISOString(), - ...profileData, + ...customerData, }; const privateFields: string[] = Object.keys(processData); @@ -37,7 +37,7 @@ export default class ProfileService { validation_rules: [ { quorum: 0.5, - fields: [...privateFields, 'roles'], + fields: [...privateFields, 'roles', 'uid', 'utype'], min_sig_member: 1, }, ], @@ -66,7 +66,7 @@ export default class ProfileService { } }; - return new Promise((resolve: (profileCreated: any) => void, reject: (error: string) => void) => { + return new Promise((resolve: (processCreated: any) => void, reject: (error: string) => void) => { this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => { this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => { this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => { @@ -77,13 +77,13 @@ export default class ProfileService { }); } - public static getProfiles(): Promise { - return this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['utype'] && publicValues['utype'] === 'profile'); + public static getCustomers(): Promise { + return this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['utype'] && publicValues['utype'] === 'customer'); } - public static getProfileByUid(uid: string): Promise { - return new Promise((resolve: (profile: any) => void, reject: (error: string) => void) => { - this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['uid'] === uid && publicValues['utype'] && publicValues['utype'] === 'profile').then((profiles: any[]) => { + public static getCustomerByUid(uid: string): Promise { + return new Promise((resolve: (process: any) => void, reject: (error: string) => void) => { + this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['uid'] === uid && publicValues['utype'] && publicValues['utype'] === 'customer').then((profiles: any[]) => { if (profiles.length === 0) { resolve(null); } else { diff --git a/src/common/Api/LeCoffreApi/sdk/DeedTypeService.ts b/src/common/Api/LeCoffreApi/sdk/DeedTypeService.ts new file mode 100644 index 00000000..23f9970a --- /dev/null +++ b/src/common/Api/LeCoffreApi/sdk/DeedTypeService.ts @@ -0,0 +1,122 @@ + +import { v4 as uuidv4 } from 'uuid'; + +import MessageBus from 'src/sdk/MessageBus'; +import User from 'src/sdk/User'; +import DocumentService from './DocumentService'; + +export default class DeedTypeService { + + private static readonly messageBus: MessageBus = MessageBus.getInstance(); + + private constructor() { } + + public static createDeedType(deedTypeData: any, validatorId: string): Promise { + const ownerId = User.getInstance().getPairingId()!; + + const processData: any = { + uid: uuidv4(), + utype: 'deedType', + isDeleted: 'false', + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + ...deedTypeData, + }; + + const privateFields: string[] = Object.keys(processData); + privateFields.splice(privateFields.indexOf('uid'), 1); + privateFields.splice(privateFields.indexOf('utype'), 1); + + const roles: any = { + demiurge: { + members: [...[ownerId], validatorId], + validation_rules: [], + storages: [] + }, + owner: { + members: [ownerId], + validation_rules: [ + { + quorum: 0.5, + fields: [...privateFields, 'roles', 'uid', 'utype'], + min_sig_member: 1, + }, + ], + storages: [] + }, + validator: { + members: [validatorId], + validation_rules: [ + { + quorum: 0.5, + fields: ['idCertified', 'roles'], + min_sig_member: 1, + }, + { + quorum: 0.0, + fields: [...privateFields], + min_sig_member: 0, + }, + ], + storages: [] + }, + apophis: { + members: [ownerId], + validation_rules: [], + storages: [] + } + }; + + return new Promise((resolve: (processCreated: any) => void, reject: (error: string) => void) => { + this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => { + this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => { + this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => { + resolve(processCreated); + }).catch(reject); + }).catch(reject); + }).catch(reject); + }); + } + + public static getDeedTypes(): Promise { + return this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['utype'] && publicValues['utype'] === 'deedType'); + } + + public static getDeedTypeByUid(uid: string, includeDocumentTypes: boolean = true): Promise { + return new Promise((resolve: (process: any) => void, reject: (error: string) => void) => { + this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['uid'] === uid && publicValues['utype'] && publicValues['utype'] === 'deedType').then(async (processes: any[]) => { + if (processes.length === 0) { + resolve(null); + } else { + const process: any = processes[0]; + + if (includeDocumentTypes && process.processData.document_types && process.processData.document_types.length > 0) { + process.processData.document_types = await new Promise(async (resolve: (document_types: any[]) => void) => { + const document_types: any[] = []; + for (const document_type of process.processData.document_types) { + const p: any = await DocumentService.getDocumentByUid(document_type.uid); + document_types.push(p.processData); + } + resolve(document_types); + }); + } + + resolve(process); + } + }).catch(reject); + }); + } + + public static updateDeedType(process: any, newData: any): Promise { + return new Promise((resolve: () => void, reject: (error: string) => void) => { + this.messageBus.updateProcess(process.processId, newData, [], null).then((processUpdated: any) => { + const newStateId: string = processUpdated.diffs[0]?.state_id; + this.messageBus.notifyUpdate(process.processId, newStateId).then(() => { + this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => { + resolve(); + }).catch(reject); + }).catch(reject); + }).catch(reject); + }); + } +} diff --git a/src/common/Api/LeCoffreApi/sdk/DocumentService.ts b/src/common/Api/LeCoffreApi/sdk/DocumentService.ts new file mode 100644 index 00000000..77104d67 --- /dev/null +++ b/src/common/Api/LeCoffreApi/sdk/DocumentService.ts @@ -0,0 +1,95 @@ + +import { v4 as uuidv4 } from 'uuid'; + +import MessageBus from 'src/sdk/MessageBus'; +import User from 'src/sdk/User'; + +export default class DocumentService { + + private static readonly messageBus: MessageBus = MessageBus.getInstance(); + + private constructor() { } + + public static createDocument(documentData: any, validatorId: string): Promise { + const ownerId = User.getInstance().getPairingId()!; + + const processData: any = { + uid: uuidv4(), + utype: 'document', + isDeleted: 'false', + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + ...documentData, + }; + + const privateFields: string[] = Object.keys(processData); + privateFields.splice(privateFields.indexOf('uid'), 1); + privateFields.splice(privateFields.indexOf('utype'), 1); + + const roles: any = { + demiurge: { + members: [...[ownerId], validatorId], + validation_rules: [], + storages: [] + }, + owner: { + members: [ownerId], + validation_rules: [ + { + quorum: 0.5, + fields: [...privateFields, 'roles', 'uid', 'utype'], + min_sig_member: 1, + }, + ], + storages: [] + }, + validator: { + members: [validatorId], + validation_rules: [ + { + quorum: 0.5, + fields: ['idCertified', 'roles'], + min_sig_member: 1, + }, + { + quorum: 0.0, + fields: [...privateFields], + min_sig_member: 0, + }, + ], + storages: [] + }, + apophis: { + members: [ownerId], + validation_rules: [], + storages: [] + } + }; + + return new Promise((resolve: (processCreated: any) => void, reject: (error: string) => void) => { + this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => { + this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => { + this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => { + resolve(processCreated); + }).catch(reject); + }).catch(reject); + }).catch(reject); + }); + } + + public static getDocuments(): Promise { + return this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['utype'] && publicValues['utype'] === 'document'); + } + + public static getDocumentByUid(uid: string): Promise { + return new Promise((resolve: (process: any) => void, reject: (error: string) => void) => { + this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['uid'] === uid && publicValues['utype'] && publicValues['utype'] === 'document').then((processes: any[]) => { + if (processes.length === 0) { + resolve(null); + } else { + resolve(processes[0]); + } + }).catch(reject); + }); + } +} diff --git a/src/common/Api/LeCoffreApi/sdk/FolderService.ts b/src/common/Api/LeCoffreApi/sdk/FolderService.ts index 951760a1..6e8f39eb 100644 --- a/src/common/Api/LeCoffreApi/sdk/FolderService.ts +++ b/src/common/Api/LeCoffreApi/sdk/FolderService.ts @@ -4,7 +4,8 @@ import { v4 as uuidv4 } from 'uuid'; import MessageBus from 'src/sdk/MessageBus'; import User from 'src/sdk/User'; -import ProfileService from './ProfileService'; +import CustomerService from './CustomerService'; +import DeedTypeService from './DeedTypeService'; export default class FolderService { @@ -40,7 +41,7 @@ export default class FolderService { validation_rules: [ { quorum: 0.5, - fields: [...privateFields, 'roles'], + fields: [...privateFields, 'roles', 'uid', 'utype'], min_sig_member: 1, }, ], @@ -75,7 +76,7 @@ export default class FolderService { } }; - return new Promise((resolve: (folderCreated: any) => void, reject: (error: string) => void) => { + return new Promise((resolve: (processCreated: any) => void, reject: (error: string) => void) => { this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => { this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => { this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => { @@ -90,36 +91,43 @@ export default class FolderService { return this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['utype'] && publicValues['utype'] === 'folder'); } - public static getFolderByUid(uid: string): Promise { - return new Promise((resolve: (folder: any) => void, reject: (error: string) => void) => { - this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['uid'] === uid && publicValues['utype'] && publicValues['utype'] === 'folder').then(async (folders: any[]) => { - if (folders.length === 0) { + public static getFolderByUid(uid: string, includeCustomers: boolean = true, includeDeedType: boolean = true): Promise { + return new Promise((resolve: (process: any) => void, reject: (error: string) => void) => { + this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['uid'] === uid && publicValues['utype'] && publicValues['utype'] === 'folder').then(async (processes: any[]) => { + if (processes.length === 0) { resolve(null); } else { - const folder: any = folders[0]; + const process: any = processes[0]; - if (folder.processData.customers && folder.processData.customers.length > 0) { - folder.processData.customers = await new Promise(async (resolve: (profiles: any[]) => void, reject: (error: string) => void) => { + if (includeCustomers && process.processData.customers && process.processData.customers.length > 0) { + process.processData.customers = await new Promise(async (resolve: (customers: any[]) => void) => { const customers: any[] = []; - for (const uid of folder.processData.customers) { - customers.push(await ProfileService.getProfileByUid(uid)); + for (const uid of process.processData.customers) { + const p: any = await CustomerService.getCustomerByUid(uid); + customers.push(p.processData); } resolve(customers); }); } - resolve(folder); + if (includeDeedType && process.processData.deed && process.processData.deed.deed_type) { + const p: any = await DeedTypeService.getDeedTypeByUid(process.processData.deed.deed_type.uid); + process.processData.deed.deed_type = p.processData; + process.processData.deed.document_types = p.processData.document_types.filter((item: any, index: number) => p.processData.document_types.findIndex((t: any) => t.uid === item.uid) === index); + } + + resolve(process); } }).catch(reject); }); } - public static updateFolder(folder: any, newData: any): Promise { + public static updateFolder(process: any, newData: any): Promise { return new Promise((resolve: () => void, reject: (error: string) => void) => { - this.messageBus.updateProcess(folder.processId, folder.lastStateId, newData, [], null).then((processUpdated: any) => { + this.messageBus.updateProcess(process.processId, newData, [], null).then((processUpdated: any) => { const newStateId: string = processUpdated.diffs[0]?.state_id; - this.messageBus.notifyUpdate(folder.processId, newStateId).then(() => { - this.messageBus.validateState(folder.processId, newStateId).then((_stateValidated) => { + this.messageBus.notifyUpdate(process.processId, newStateId).then(() => { + this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => { resolve(); }).catch(reject); }).catch(reject); diff --git a/src/front/Components/LayoutTemplates/DefaultDeedTypeDashboard/index.tsx b/src/front/Components/LayoutTemplates/DefaultDeedTypeDashboard/index.tsx index 508bd1a0..877408b1 100644 --- a/src/front/Components/LayoutTemplates/DefaultDeedTypeDashboard/index.tsx +++ b/src/front/Components/LayoutTemplates/DefaultDeedTypeDashboard/index.tsx @@ -5,9 +5,8 @@ import Module from "@Front/Config/Module"; import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block"; import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList"; import { DeedType } from "le-coffre-resources/dist/Notary"; -import DeedTypes, { IGetDeedTypesParams } from "@Front/Api/LeCoffreApi/Notary/DeedTypes/DeedTypes"; -import MessageBus from "src/sdk/MessageBus"; +import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService"; type IProps = IPropsDashboardWithList; @@ -15,30 +14,19 @@ export default function DefaultDeedTypeDashboard(props: IProps) { const [deedTypes, setDeedTypes] = React.useState(null); const router = useRouter(); const { deedTypeUid } = router.query; + useEffect(() => { - // TODO: review - MessageBus.getInstance().isReady().then(() => { - setTimeout(() => { - MessageBus.getInstance().getDeepTypes().then((deedTypes: any) => { - setDeedTypes(deedTypes.map((deedType: any) => deedType.processData)); - }); - }, 1000); + DeedTypeService.getDeedTypes().then((processes: any) => { + let deedTypes = processes.map((process: any) => process.processData); + + // FilterBy archived_at = null or not defined + deedTypes = deedTypes.filter((deedType: any) => !deedType.archived_at); + + // OrderBy name asc + deedTypes.sort((a: any, b: any) => a.name.localeCompare(b.name)); + + setDeedTypes(deedTypes); }); - - /* - const query: IGetDeedTypesParams = { - where: { - archived_at: null, - }, - orderBy: { - name: "asc", - }, - }; - - DeedTypes.getInstance() - .get(query) - .then((deedTypes) => setDeedTypes(deedTypes)); - */ }, []); const onSelectedBlock = (block: IBlock) => { diff --git a/src/front/Components/LayoutTemplates/DefaultDocumentTypesDashboard/index.tsx b/src/front/Components/LayoutTemplates/DefaultDocumentTypesDashboard/index.tsx index 09c516b8..1eb6528a 100644 --- a/src/front/Components/LayoutTemplates/DefaultDocumentTypesDashboard/index.tsx +++ b/src/front/Components/LayoutTemplates/DefaultDocumentTypesDashboard/index.tsx @@ -1,14 +1,12 @@ import React, { useEffect } from "react"; - import { useRouter } from "next/router"; import Module from "@Front/Config/Module"; import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block"; import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList"; import JwtService from "@Front/Services/JwtService/JwtService"; -import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes"; import { DocumentType } from "le-coffre-resources/dist/Notary"; -import MessageBus from "src/sdk/MessageBus"; +import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService"; type IProps = IPropsDashboardWithList; @@ -17,31 +15,25 @@ export default function DefaultDocumentTypeDashboard(props: IProps) { const router = useRouter(); const { documentTypeUid } = router.query; useEffect(() => { - // TODO: review - const officeId = 'demo_notary_office_id'; //JwtService.getInstance().decodeJwt()?.office_Id; - - MessageBus.getInstance().isReady().then(() => { - setTimeout(() => { - MessageBus.getInstance().getDocuments().then((documents: any) => { - setDocumentTypes(documents.map((document: any) => document.processData)); - }); - }, 1000); - }); - - /* const jwt = JwtService.getInstance().decodeJwt(); if (!jwt) return; - DocumentTypes.getInstance() - .get({ - where: { - office_uid: jwt.office_Id, - }, - orderBy: { - name: "asc", - }, - }) - .then((documentTypes) => setDocumentTypes(documentTypes)); - */ + + // TODO: review + const officeId = 'demo_notary_office_id'; // jwt.office_Id; + + DocumentService.getDocuments().then((processes: any[]) => { + if (processes.length > 0) { + let documents: any[] = processes.map((process: any) => process.processData); + + // FilterBy office.uid + documents = documents.filter((document: any) => document.office.uid === officeId); + + // OrderBy name asc + documents = documents.sort((a: any, b: any) => a.name.localeCompare(b.name)); + + setDocumentTypes(documents); + } + }); }, []); const onSelectedBlock = (block: IBlock) => { diff --git a/src/front/Components/LayoutTemplates/DefaultNotaryDashboard/index.tsx b/src/front/Components/LayoutTemplates/DefaultNotaryDashboard/index.tsx index 27287c72..31ca4d88 100644 --- a/src/front/Components/LayoutTemplates/DefaultNotaryDashboard/index.tsx +++ b/src/front/Components/LayoutTemplates/DefaultNotaryDashboard/index.tsx @@ -115,9 +115,10 @@ export default function DefaultNotaryDashboard(props: IProps) { .then((folders) => setFolders(folders)); */ - FolderService.getFolders().then((folders) => { - if (folders.length > 0) { - setFolders(folders.map((folder: any) => folder.processData).filter((folder: any) => folder.isArchived && folder.isArchived === (isArchived ? 'true' : 'false'))); + FolderService.getFolders().then((processes: any[]) => { + if (processes.length > 0) { + const folders: any[] = processes.map((process: any) => process.processData); + setFolders(folders.filter((folder: any) => folder.isArchived && folder.isArchived === (isArchived ? 'true' : 'false'))); } }); }, [isArchived]); diff --git a/src/front/Components/Layouts/ClientDashboard/ReceivedDocuments/index.tsx b/src/front/Components/Layouts/ClientDashboard/ReceivedDocuments/index.tsx index 08eaf07c..001ea71a 100644 --- a/src/front/Components/Layouts/ClientDashboard/ReceivedDocuments/index.tsx +++ b/src/front/Components/Layouts/ClientDashboard/ReceivedDocuments/index.tsx @@ -160,9 +160,6 @@ function buildRows( folderUid: string | string[], onDownloadFileNotary: (doc: DocumentNotary) => void, ): IRowProps[] { - console.log(documentsNotary); - console.log(folderUid); - return documentsNotary.map((documentNotary) => ({ key: documentNotary.uid ?? "", name: formatName(documentNotary.files?.[0]?.file_name?.split(".")?.[0] ?? "") || "_", diff --git a/src/front/Components/Layouts/DeedTypes/DeedTypesCreate/index.tsx b/src/front/Components/Layouts/DeedTypes/DeedTypesCreate/index.tsx index 91d7a43f..ffee55fc 100644 --- a/src/front/Components/Layouts/DeedTypes/DeedTypesCreate/index.tsx +++ b/src/front/Components/Layouts/DeedTypes/DeedTypesCreate/index.tsx @@ -1,4 +1,3 @@ -import DeedTypes from "@Front/Api/LeCoffreApi/Notary/DeedTypes/DeedTypes"; import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; import Form from "@Front/Components/DesignSystem/Form"; import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField"; @@ -15,9 +14,7 @@ import { useCallback, useState } from "react"; import classes from "./classes.module.scss"; import { validateOrReject, ValidationError } from "class-validator"; -import { v4 as uuidv4 } from "uuid"; - -import MessageBus from "src/sdk/MessageBus"; +import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService"; type IProps = {}; export default function DeedTypesCreate(props: IProps) { @@ -46,37 +43,22 @@ export default function DeedTypesCreate(props: IProps) { return; } - MessageBus.getInstance().isReady().then(() => { - MessageBus.getInstance().createDeedType({ ...deedType, uid: uuidv4(), utype_dt: 'deedType', isDeleted: 'false' }, [], []).then((processCreated: any) => { - MessageBus.getInstance().notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => { - MessageBus.getInstance().validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => { - router.push( - Module.getInstance() - .get() - .modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", processCreated.processData.uid), - ); - }); - }); - }); + const deedTypeData: any = { + name: values["name"], + description: values["description"], + office: { + uid: officeId, + } + }; + const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0'; + + DeedTypeService.createDeedType(deedTypeData, validatorId).then((processCreated: any) => { + router.push( + Module.getInstance() + .get() + .modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", processCreated.processData.uid), + ); }); - - /* - const deedTypeCreated = await DeedTypes.getInstance().post( - DeedType.hydrate({ - name: values["name"], - description: values["description"], - office: Office.hydrate({ - uid: officeId, - }), - }), - ); - - router.push( - Module.getInstance() - .get() - .modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", deedTypeCreated.uid!), - ); - */ } catch (validationErrors: Array | any) { setValidationError(validationErrors as ValidationError[]); return; diff --git a/src/front/Components/Layouts/DeedTypes/DeedTypesInformations/index.tsx b/src/front/Components/Layouts/DeedTypes/DeedTypesInformations/index.tsx index df54056a..d07a4d32 100644 --- a/src/front/Components/Layouts/DeedTypes/DeedTypesInformations/index.tsx +++ b/src/front/Components/Layouts/DeedTypes/DeedTypesInformations/index.tsx @@ -1,7 +1,6 @@ import ChevronIcon from "@Assets/Icons/chevron.svg"; import PenICon from "@Assets/Icons/pen.svg"; import DeedTypes from "@Front/Api/LeCoffreApi/Notary/DeedTypes/DeedTypes"; -import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes"; import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption"; import Form from "@Front/Components/DesignSystem/Form"; @@ -20,8 +19,8 @@ import { useCallback, useEffect, useState } from "react"; import classes from "./classes.module.scss"; -import MessageBus from "src/sdk/MessageBus"; -import MapUtils from "src/sdk/MapUtils"; +import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService"; +import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService"; type IProps = {}; export default function DeedTypesInformations(props: IProps) { @@ -66,63 +65,32 @@ export default function DeedTypesInformations(props: IProps) { async function getDeedType() { if (!deedTypeUid) return; - // TODO: review - MessageBus.getInstance().isReady().then(() => { - MessageBus.getInstance().getDeepTypes().then((deedTypes: any) => { - const deedType: any = deedTypes.find((deedType: any) => deedType.processData.uid === deedTypeUid); - if (deedType) { - setDeedTypeSelected(deedType.processData); + DeedTypeService.getDeedTypeByUid(deedTypeUid as string).then((process: any) => { + if (process) { + const deedType: any = process.processData; + setDeedTypeSelected(deedType); - const documentsOptions: any[] = deedType.processData.document_types - ?.map((documentType: any) => MapUtils.toJson(documentType)) - .map((documentType: any) => { - return { - label: documentType[0].name, - id: documentType[0].uid ?? "", - }; - }) - .sort((a: any, b: any) => a.label.localeCompare(b.label)); - - setSelectedDocuments(documentsOptions); - } - }); + if (!deedType.document_types) return; + const documentsOptions: IOption[] = deedType.document_types + ?.map((documentType: any) => { + return { + label: documentType.name, + id: documentType.uid ?? "", + }; + }) + .sort((a: any, b: any) => a.label.localeCompare(b.label)); + setSelectedDocuments(documentsOptions); + } }); - - /* - const deedType = await DeedTypes.getInstance().getByUid(deedTypeUid as string, { - q: { - document_types: true, - }, - }); - setDeedTypeSelected(deedType); - - if (!deedType.document_types) return; - const documentsOptions: IOption[] = deedType.document_types - ?.map((documentType) => { - return { - label: documentType.name, - id: documentType.uid ?? "", - }; - }) - .sort((a, b) => a.label.localeCompare(b.label)); - setSelectedDocuments(documentsOptions); - */ } async function getDocuments() { - // TODO: review - MessageBus.getInstance().isReady().then(() => { - setTimeout(() => { - MessageBus.getInstance().getDocuments().then((documents: any) => { - setAvailableDocuments(documents.map((document: any) => document.processData)); - }); - }, 1000); + DocumentService.getDocuments().then((processes: any[]) => { + if (processes.length) { + const documents: any[] = processes.map((process: any) => process.processData); + setAvailableDocuments(documents); + } }); - - /* - const documents = await DocumentTypes.getInstance().get({}); - setAvailableDocuments(documents); - */ } getDocuments(); @@ -136,40 +104,23 @@ export default function DeedTypesInformations(props: IProps) { [openSaveModal], ); - const saveDocumentTypes = useCallback(async () => { - /* - await DeedTypes.getInstance().put(deedTypeUid as string, { - uid: deedTypeUid as string, - document_types: selectedDocuments.map((document) => DocumentType.hydrate({ uid: document.id as string })), - }); - */ + const saveDocumentTypes = useCallback(() => { + DeedTypeService.getDeedTypeByUid(deedTypeUid as string, false).then((process: any) => { + if (process) { + const deedType: any = process.processData; - // TODO: review - MessageBus.getInstance().isReady().then(() => { - MessageBus.getInstance().getDeepTypes().then((deedTypes: any) => { - const deedType: any = deedTypes.find((deedType: any) => deedType.processData.uid === deedTypeUid); - if (deedType) { - let document_types: any[] = deedType.processData.document_types; - if (!document_types) { - document_types = []; - } - document_types.push(selectedDocuments.map((document) => { - return { - uid: document.id, - name: document.label, - } - })); - MessageBus.getInstance().updateProcess(deedType.processId, deedType.lastStateId, { document_types: document_types }, [], null).then((processUpdated: any) => { - const newStateId: string = processUpdated.diffs[0]?.state_id; - MessageBus.getInstance().notifyUpdate(deedType.processId, newStateId).then(() => { - MessageBus.getInstance().validateState(deedType.processId, newStateId).then((_stateValidated) => { - closeSaveModal(); - }); - }); - }); + let document_types: any[] = deedType.document_types; + if (!document_types) { + document_types = []; } - }); + selectedDocuments.map((selectedDocument: any) => ({ uid: selectedDocument.id as string })) + .forEach((selectedDocument: any) => document_types.push(selectedDocument)); + DeedTypeService.updateDeedType(process, { document_types: document_types }).then(() => { + closeSaveModal(); + }); + + } }); }, [closeSaveModal, deedTypeUid, selectedDocuments]); diff --git a/src/front/Components/Layouts/DocumentTypes/DocumentTypesCreate/index.tsx b/src/front/Components/Layouts/DocumentTypes/DocumentTypesCreate/index.tsx index fa2d2163..8f3328e8 100644 --- a/src/front/Components/Layouts/DocumentTypes/DocumentTypesCreate/index.tsx +++ b/src/front/Components/Layouts/DocumentTypes/DocumentTypesCreate/index.tsx @@ -1,4 +1,3 @@ -import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes"; import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; import Form from "@Front/Components/DesignSystem/Form"; import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField"; @@ -14,9 +13,7 @@ import { useCallback, useState } from "react"; import classes from "./classes.module.scss"; -import { v4 as uuidv4 } from "uuid"; - -import MessageBus from "src/sdk/MessageBus"; +import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService"; type IProps = {}; export default function DocumentTypesCreate(props: IProps) { @@ -26,56 +23,35 @@ export default function DocumentTypesCreate(props: IProps) { const onSubmitHandler = useCallback( async (e: React.FormEvent | null, values: { [key: string]: string }) => { try { - // TODO: review - const officeId = 'demo_notary_office_id'; //JwtService.getInstance().decodeJwt()?.office_Id; + const jwt = JwtService.getInstance().decodeJwt(); + if (!jwt) return; - const documentToCreate = DocumentType.hydrate({ + // TODO: review + const officeId = 'demo_notary_office_id'; // jwt.office_Id; + + const documentFormModel = DocumentType.hydrate({ ...values, office: Office.hydrate({ uid: officeId, }) }); - await validateOrReject(documentToCreate, { groups: ["createDocumentType"] }); + await validateOrReject(documentFormModel, { groups: ["createDocumentType"] }); - MessageBus.getInstance().isReady().then(() => { - const documentData: any = { - ...values, - uid: uuidv4(), - utype_d: 'document', - isDeleted: 'false' - }; - MessageBus.getInstance().createDocument(documentData, [], []).then((processCreated: any) => { - MessageBus.getInstance().notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => { - MessageBus.getInstance().validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => { - router.push( - Module.getInstance() - .get() - .modules.pages.DocumentTypes.pages.DocumentTypesInformations.props.path.replace("[uid]", processCreated.processData.uid), - ); - }); - }); - }); - }); - - /* - const jwt = JwtService.getInstance().decodeJwt(); - if (!jwt) return; - const office = Office.hydrate({ - uid: jwt.office_Id, - }); - const documentToCreate = DocumentType.hydrate({ + const documentData: any = { ...values, - office: office, - }); - await validateOrReject(documentToCreate, { groups: ["createDocumentType"] }); - const documentTypeCreated = await DocumentTypes.getInstance().post(documentToCreate); + office: { + uid: officeId, + } + }; + const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0'; - router.push( - Module.getInstance() - .get() - .modules.pages.DocumentTypes.pages.DocumentTypesInformations.props.path.replace("[uid]", documentTypeCreated.uid!), - ); - */ + DocumentService.createDocument(documentData, validatorId).then((processCreated: any) => { + router.push( + Module.getInstance() + .get() + .modules.pages.DocumentTypes.pages.DocumentTypesInformations.props.path.replace("[uid]", processCreated.processData.uid), + ); + }); } catch (e) { if (e instanceof Array) { setValidationError(e); diff --git a/src/front/Components/Layouts/DocumentTypes/DocumentTypesInformations/index.tsx b/src/front/Components/Layouts/DocumentTypes/DocumentTypesInformations/index.tsx index 0fa39150..89a87e2c 100644 --- a/src/front/Components/Layouts/DocumentTypes/DocumentTypesInformations/index.tsx +++ b/src/front/Components/Layouts/DocumentTypes/DocumentTypesInformations/index.tsx @@ -1,6 +1,5 @@ import ChevronIcon from "@Assets/Icons/chevron.svg"; import PenICon from "@Assets/Icons/pen.svg"; -import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes"; import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography"; import DefaultDocumentTypesDashboard from "@Front/Components/LayoutTemplates/DefaultDocumentTypesDashboard"; import Module from "@Front/Config/Module"; @@ -13,7 +12,7 @@ import { useEffect, useState } from "react"; import classes from "./classes.module.scss"; import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; -import MessageBus from "src/sdk/MessageBus"; +import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService"; export default function DocumentTypesInformations() { const router = useRouter(); @@ -25,23 +24,12 @@ export default function DocumentTypesInformations() { async function getDocument() { if (!documentTypeUid) return; - // TODO: review - MessageBus.getInstance().isReady().then(() => { - MessageBus.getInstance().getDocuments().then((documents: any) => { - const document: any = documents.find((document: any) => document.processData.uid === documentTypeUid as string); - if (document) { - setDocumentSelected(document.processData); - } - }); + DocumentService.getDocumentByUid(documentTypeUid as string).then((process: any) => { + if (process) { + const document: any = process.processData; + setDocumentSelected(document); + } }); - - /* - const document = await DocumentTypes.getInstance().getByUid(documentTypeUid as string, { - _count: true, - }); - if (!document) return; - setDocumentSelected(document); - */ } getDocument(); diff --git a/src/front/Components/Layouts/Folder/AddClientToFolder/index.tsx b/src/front/Components/Layouts/Folder/AddClientToFolder/index.tsx index 94b6fe9b..607245a9 100644 --- a/src/front/Components/Layouts/Folder/AddClientToFolder/index.tsx +++ b/src/front/Components/Layouts/Folder/AddClientToFolder/index.tsx @@ -1,5 +1,3 @@ -import Customers from "@Front/Api/LeCoffreApi/Notary/Customers/Customers"; -import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders"; import AutocompleteMultiSelect from "@Front/Components/DesignSystem/AutocompleteMultiSelect"; import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button"; import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption"; @@ -11,7 +9,7 @@ import BackArrow from "@Front/Components/Elements/BackArrow"; import Module from "@Front/Config/Module"; import { ValidationError } from "class-validator"; import { ECivility } from "le-coffre-resources/dist/Customer/Contact"; -import { Contact, Customer, OfficeFolder } from "le-coffre-resources/dist/Notary"; +import { Contact, Customer } from "le-coffre-resources/dist/Notary"; import Link from "next/link"; import { useRouter } from "next/router"; import backgroundImage from "@Assets/images/background_refonte.svg"; @@ -19,7 +17,7 @@ import classes from "./classes.module.scss"; import { useCallback, useEffect, useState } from "react"; import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage"; -import ProfileService from "src/common/Api/LeCoffreApi/sdk/ProfileService"; +import CustomerService from "src/common/Api/LeCoffreApi/sdk/CustomerService"; import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService"; enum ESelectedOption { @@ -66,8 +64,8 @@ export default function AddClientToFolder(props: IProps) { values["cell_phone_number"] = "+33" + values["cell_phone_number"].substring(1); } } - const contactToCreate = Contact.hydrate(values); - await contactToCreate.validateOrReject?.({ groups: ["createCustomer"], forbidUnknownValues: false }); + const contactFormModel = Contact.hydrate(values); + await contactFormModel.validateOrReject?.({ groups: ["createCustomer"], forbidUnknownValues: false }); } catch (validationErrors) { setValidationError(validationErrors as ValidationError[]); return; @@ -75,73 +73,64 @@ export default function AddClientToFolder(props: IProps) { try { // TODO: review - const profile: any = { + const customerData: any = { contact: values }; - const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0'; - ProfileService.createProfile(profile, validatorId).then((profileCreated: any) => { - FolderService.getFolderByUid(folderUid as string).then((folder: any) => { - if (folder) { - const customers: any[] = folder.processData.customers; - customers.push(profileCreated.processData.uid); + CustomerService.createCustomer(customerData, validatorId).then((processCreated: any) => { + FolderService.getFolderByUid(folderUid as string, false, false).then((process: any) => { + if (process) { + let customers: any[] = process.processData.customers; + if (!customers) { + customers = []; + } + customers.push(processCreated.processData.uid); - FolderService.updateFolder(folder, { customers }).then(() => { + FolderService.updateFolder(process, { customers: customers }).then(() => { router.push(`/folders/${folderUid}`); }); } }); }); - - /* - const customer: Customer = await Customers.getInstance().post({ - contact: values, - }); - if (!customer.uid) return; - customersToLink?.push({ uid: customer.uid } as Partial); - */ } catch (backError) { if (!Array.isArray(backError)) return; setValidationError(backError as ValidationError[]); return; } - } + } else { + FolderService.getFolderByUid(folderUid as string, false, false).then((process: any) => { + if (process) { + const customers: any[] = customersToLink.map((customer: any) => customer.uid); - /* - if (customersToLink) { - const body = OfficeFolder.hydrate({ - customers: customersToLink.map((customer) => { - return Customer.hydrate(customer); - }), + FolderService.updateFolder(process, { customers: customers }).then(() => { + router.push(`/folders/${folderUid}`); + }); + } }); - await Folders.getInstance().put(folderUid as string, body); - router.push(`/folders/${folderUid}`); } - */ }, [existingCustomers, folderUid, router, selectedCustomers, selectedOption], ); const getFolderPreSelectedCustomers = useCallback( async (folderUid: string): Promise => { - const query = { - q: { - customers: { - include: { - contact: true, - }, - }, - }, - }; let preExistingCustomers: IOption[] = []; try { - const folder = await Folders.getInstance().getByUid(folderUid, query); - preExistingCustomers = folder.customers!.map((customer) => { - return { - label: customer.contact?.first_name + " " + customer.contact?.last_name, - id: customer.uid ?? "", - }; + preExistingCustomers = await new Promise(resolve => { + FolderService.getFolderByUid(folderUid as string).then((process: any) => { + if (process) { + const folder: any = process.processData; + const preExistingCustomers: IOption[] = folder.customers + .map((customer: any) => { + return { + label: customer.contact?.first_name + " " + customer.contact?.last_name, + id: customer.uid ?? "", + }; + }); + resolve(preExistingCustomers); + } + }); }); } catch (error) { router.push(Module.getInstance().get().modules.pages["404"].props.path); @@ -153,27 +142,27 @@ export default function AddClientToFolder(props: IProps) { ); const loadCustomers = useCallback(async () => { - /* TODO: review - const query = {}; - const availableCustomers = await Customers.getInstance().get(query); - let preExistingCustomers: IOption[] | undefined = await getFolderPreSelectedCustomers(folderUid as string); - const existingCustomers = preExistingCustomers ?? []; + CustomerService.getCustomers().then(async (processes: any[]) => { + const availableCustomers: any[] = processes.map((process: any) => process.processData); - existingCustomers.forEach((customer) => { - const index = availableCustomers.findIndex((availableCustomer) => availableCustomer.uid === customer.id); - if (index !== -1) availableCustomers.splice(index, 1); + const preExistingCustomers: IOption[] | undefined = await getFolderPreSelectedCustomers(folderUid as string); + + const existingCustomers = preExistingCustomers ?? []; + existingCustomers.forEach((customer) => { + const index = availableCustomers.findIndex((availableCustomer) => availableCustomer.uid === customer.id); + if (index !== -1) availableCustomers.splice(index, 1); + }); + + let selectedOption = ESelectedOption.EXISTING_CUSTOMER; + if (availableCustomers.length === 0) { + selectedOption = ESelectedOption.NEW_CUSTOMER; + } + + setAvailableCustomers(availableCustomers); + setExistingCustomers(existingCustomers); + setIsLoaded(true); + setSelectedOption(selectedOption); }); - - let selectedOption = ESelectedOption.EXISTING_CUSTOMER; - if (availableCustomers.length === 0) { - selectedOption = ESelectedOption.NEW_CUSTOMER; - } - - setAvailableCustomers(availableCustomers); - setExistingCustomers(existingCustomers); - */ - setIsLoaded(true); - //setSelectedOption(selectedOption); }, [folderUid, getFolderPreSelectedCustomers]); const getSelectedOptions = useCallback((): IOption[] => { diff --git a/src/front/Components/Layouts/Folder/AskDocuments/ParameterDocuments/index.tsx b/src/front/Components/Layouts/Folder/AskDocuments/ParameterDocuments/index.tsx index 10e6109e..6fe966de 100644 --- a/src/front/Components/Layouts/Folder/AskDocuments/ParameterDocuments/index.tsx +++ b/src/front/Components/Layouts/Folder/AskDocuments/ParameterDocuments/index.tsx @@ -12,6 +12,8 @@ import { ChangeEvent, useCallback, useEffect, useState } from "react"; import classes from "./classes.module.scss"; +import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService"; + type IProps = { isCreateDocumentModalVisible: boolean; closeModal: () => void; @@ -29,20 +31,25 @@ export default function ParameterDocuments(props: IProps) { const [formattedOptions, setFormattedOptions] = useState([]); const getAvailableDocuments = useCallback(async () => { - const documents = await DocumentTypes.getInstance().get({}); + DocumentService.getDocuments().then((processes: any[]) => { + if (processes.length > 0) { + const documents: any[] = processes.map((process: any) => process.processData); - const formattedOptions: IOption[] = documents - .filter((document) => { - return !props.folder.deed?.document_types?.some((documentType) => documentType.uid === document.uid); - }) - .map((document) => { - return { - label: document.name, - id: document.uid ?? "", - }; - }); - formattedOptions.sort((a, b) => (a.label > b.label ? 1 : -1)); - setFormattedOptions(formattedOptions); + const formattedOptions: IOption[] = documents + .filter((document) => { + return !props.folder.deed?.document_types?.some((documentType) => documentType.uid === document.uid); + }) + .map((document) => { + return { + label: document.name, + id: document.uid ?? "", + }; + }); + + formattedOptions.sort((a, b) => (a.label > b.label ? 1 : -1)); + setFormattedOptions(formattedOptions); + } + }); }, [props.folder.deed?.document_types]); const onVisibleDescriptionChange = (event: ChangeEvent) => { @@ -92,7 +99,7 @@ export default function ParameterDocuments(props: IProps) { if (props.onDocumentsUpdated) { props.onDocumentsUpdated([newDocumentType]); } - + handleClose(); } catch (e) { console.error(e); @@ -122,7 +129,7 @@ export default function ParameterDocuments(props: IProps) { if (props.onDocumentsUpdated) { props.onDocumentsUpdated(documentsById); } - + handleClose(); } catch (e) { console.error(e); diff --git a/src/front/Components/Layouts/Folder/AskDocuments/index.tsx b/src/front/Components/Layouts/Folder/AskDocuments/index.tsx index 2e5c66c1..700444ad 100644 --- a/src/front/Components/Layouts/Folder/AskDocuments/index.tsx +++ b/src/front/Components/Layouts/Folder/AskDocuments/index.tsx @@ -15,6 +15,7 @@ import classes from "./classes.module.scss"; import ParameterDocuments from "./ParameterDocuments"; import { IOption } from "@Front/Components/DesignSystem/Form/SelectFieldOld"; import backgroundImage from "@Assets/images/background_refonte.svg"; +import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService"; export default function AskDocuments() { const router = useRouter(); @@ -123,6 +124,7 @@ export default function AskDocuments() { const loadData = useCallback(async () => { try { + /* const folder = await Folders.getInstance().getByUid(folderUid as string, { q: { deed: { @@ -139,9 +141,21 @@ export default function AskDocuments() { }, }, }); + */ + + FolderService.getFolderByUid(folderUid as string).then(async (process: any) => { + if (process) { + const folder: any = process.processData; + setFolder(folder); + setDocumentTypes(await getAvailableDocuments(folder)); + } + }); + + /* if (!folder) return; setFolder(folder); setDocumentTypes(await getAvailableDocuments(folder)); + */ } catch (e) { console.error(e); } diff --git a/src/front/Components/Layouts/Folder/CreateFolder/index.tsx b/src/front/Components/Layouts/Folder/CreateFolder/index.tsx index 5d2955ac..d095a776 100644 --- a/src/front/Components/Layouts/Folder/CreateFolder/index.tsx +++ b/src/front/Components/Layouts/Folder/CreateFolder/index.tsx @@ -1,7 +1,4 @@ import backgroundImage from "@Assets/images/background_refonte.svg"; -import DeedTypes from "@Front/Api/LeCoffreApi/Notary/DeedTypes/DeedTypes"; -import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders"; -import Users from "@Front/Api/LeCoffreApi/Notary/Users/Users"; import Button from "@Front/Components/DesignSystem/Button"; import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption"; import Form from "@Front/Components/DesignSystem/Form"; @@ -22,8 +19,8 @@ import { useRouter } from "next/router"; import React, { useCallback, useEffect, useState } from "react"; import classes from "./classes.module.scss"; -import MessageBus from "src/sdk/MessageBus"; import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService"; +import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService"; export default function CreateFolder(): JSX.Element { /** @@ -51,6 +48,7 @@ export default function CreateFolder(): JSX.Element { }, ) => { // TODO: review + console.log(JwtService.getInstance().decodeJwt()); const officeId = 'demo_notary_office_id'; //JwtService.getInstance().decodeJwt()?.office_Id; const officeFolderModel = OfficeFolder.hydrate({ @@ -73,32 +71,30 @@ export default function CreateFolder(): JSX.Element { await officeFolderModel.validateOrReject?.({ groups: ["createFolder"], forbidUnknownValues: true }); } catch (validationErrors) { setValidationError(validationErrors as ValidationError[]); - //return; + return; } try { - /* - const newOfficeFolder = await Folders.getInstance().post(officeFolderForm); - if (!newOfficeFolder) { - return; - } - router.push(`/folders/${newOfficeFolder.uid}`); - */ - const folderData: any = { - folder_number: officeFolderModel.folder_number, - name: officeFolderModel.name, - deed: officeFolderModel.deed, - description: officeFolderModel.description, + folder_number: values["folder_number"], + name: values["name"], + deed: { + deed_type: { + uid: values["deed"], + } + }, + description: values["description"], + office: { + uid: officeId + }, customers: [], documents: [], notes: [], - office: officeFolderModel.office, - stakeholders: officeFolderModel.stakeholders + stakeholders: folderAccessType === "whole_office" ? availableCollaborators : selectedCollaborators }; - FolderService.createFolder(folderData, [], []).then((folderCreated: any) => { - const folderUid: string = folderCreated.processData.uid; + FolderService.createFolder(folderData, [], []).then((processCreated: any) => { + const folderUid: string = processCreated.processData.uid; router.push(`/folders/${folderUid}`); }); } catch (backError) { @@ -124,17 +120,16 @@ export default function CreateFolder(): JSX.Element { * UseEffect */ useEffect(() => { - MessageBus.getInstance().isReady().then(() => { - MessageBus.getInstance().getDeepTypes().then((deedTypes: any) => { - console.log(deedTypes.map((deedType: any) => deedType.processData)); - setAvailableDeedTypes(deedTypes.map((deedType: any) => deedType.processData)); - }); + DeedTypeService.getDeedTypes().then((processes: any[]) => { + if (processes.length > 0) { + let deedTypes: any[] = processes.map((process: any) => process.processData); + + // FilterBy archived_at = null or not defined + deedTypes = deedTypes.filter((deedType: any) => !deedType.archived_at); + + setAvailableDeedTypes(deedTypes); + } }); - /* - DeedTypes.getInstance() - .get({ where: { archived_at: null } }) - .then((deedTypes) => setAvailableDeedTypes(deedTypes)); - */ /* TODO: review // no need to pass query 'where' param here, default query for notaries include only users which are in the same office as the caller diff --git a/src/front/Components/Layouts/Folder/FolderInformation/ClientView/index.tsx b/src/front/Components/Layouts/Folder/FolderInformation/ClientView/index.tsx index 6396cf0e..d599b1b0 100644 --- a/src/front/Components/Layouts/Folder/FolderInformation/ClientView/index.tsx +++ b/src/front/Components/Layouts/Folder/FolderInformation/ClientView/index.tsx @@ -28,9 +28,8 @@ export default function ClientView(props: IProps) { const customers: ICustomer[] = useMemo( () => { - // TODO: review - return folder?.customers?.map((customer: any) => customer.processData) - .map((customer: any) => ({ + return folder?.customers + ?.map((customer: any) => ({ id: customer.uid ?? '', ...customer, })) @@ -46,15 +45,6 @@ export default function ClientView(props: IProps) { const [customer, setCustomer] = useState<(typeof customers)[number]>(customers[0]!); - useEffect(() => { - // TODO: review - setTimeout(() => { - if (customers.length > 0 && customers[0]) { - setCustomer(customers[0]); - } - }, 50); - }, [customers]); - const tabs = useMemo( () => customers.map((customer) => ({ @@ -74,7 +64,6 @@ export default function ClientView(props: IProps) { const documentsNotary = await DocumentsNotary.getInstance().get({ where: { customer: { uid: customerUid }, folder: { uid: folder.uid } }, }); - console.log(documentsNotary); if (documentsNotary.length > 0) { documentsNotary.forEach(async (doc) => { diff --git a/src/front/Components/Layouts/Folder/FolderInformation/elements/AnchoringModal/index.tsx b/src/front/Components/Layouts/Folder/FolderInformation/elements/AnchoringModal/index.tsx index fda27e3a..f15c7d8f 100644 --- a/src/front/Components/Layouts/Folder/FolderInformation/elements/AnchoringModal/index.tsx +++ b/src/front/Components/Layouts/Folder/FolderInformation/elements/AnchoringModal/index.tsx @@ -27,7 +27,7 @@ export default function AnchoringModal(props: IProps) { MessageBus.getInstance().getFolders().then((folders: any) => { const folder = folders.find((folder: any) => folder.processData.uid === folderUid); if (folder) { - MessageBus.getInstance().updateProcess(folder.processId, folder.lastStateId, { isArchived: 'true' }, [], null).then((processUpdated: any) => { + MessageBus.getInstance().updateProcess(folder.processId, { isArchived: 'true' }, [], null).then((processUpdated: any) => { const newStateId: string = processUpdated.diffs[0]?.state_id; MessageBus.getInstance().notifyUpdate(folder.processId, newStateId).then(() => { MessageBus.getInstance().validateState(folder.processId, newStateId).then((_updatedProcess) => { diff --git a/src/front/Components/Layouts/Folder/FolderInformation/index.tsx b/src/front/Components/Layouts/Folder/FolderInformation/index.tsx index 122ae85f..44eb3574 100644 --- a/src/front/Components/Layouts/Folder/FolderInformation/index.tsx +++ b/src/front/Components/Layouts/Folder/FolderInformation/index.tsx @@ -107,10 +107,11 @@ export default function FolderInformation(props: IProps) { // TODO: review return new Promise((resolve: (value: any) => void) => { - FolderService.getFolderByUid(folderUid).then((folder: any) => { - if (folder) { - setFolder(folder.processData); - resolve(folder.processData); + FolderService.getFolderByUid(folderUid).then((process: any) => { + if (process) { + const folder: any = process.processData; + setFolder(folder); + resolve(folder); } }); }); diff --git a/src/front/Components/Layouts/Folder/UpdateClient/index.tsx b/src/front/Components/Layouts/Folder/UpdateClient/index.tsx index 2a7b4877..b6e2670b 100644 --- a/src/front/Components/Layouts/Folder/UpdateClient/index.tsx +++ b/src/front/Components/Layouts/Folder/UpdateClient/index.tsx @@ -99,7 +99,7 @@ export default function UpdateClient() { if (customer) { customer.contact = contact; // Update the contact - MessageBus.getInstance().updateProcess(folder.processId, folder.lastStateId, { customers: customers }, [], null).then((processUpdated: any) => { + MessageBus.getInstance().updateProcess(folder.processId, { customers: customers }, [], null).then((processUpdated: any) => { const newStateId: string = processUpdated.diffs[0]?.state_id; MessageBus.getInstance().notifyUpdate(folder.processId, newStateId).then(() => { MessageBus.getInstance().validateState(folder.processId, newStateId).then((_stateValidated) => { diff --git a/src/front/Components/Layouts/Folder/index.tsx b/src/front/Components/Layouts/Folder/index.tsx index 2d2a55bb..de83f825 100644 --- a/src/front/Components/Layouts/Folder/index.tsx +++ b/src/front/Components/Layouts/Folder/index.tsx @@ -25,14 +25,18 @@ export default function Folder() { useEffect(() => { // TODO: review - FolderService.getFolders().then((folders: any) => { - const foldersLive = folders.filter((folder: any) => folder.processData.isArchived === 'false'); - if (foldersLive.length !== 0) { - router.push( - Module.getInstance() - .get() - .modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", foldersLive[foldersLive.length - 1].processData.uid) - ); + FolderService.getFolders().then((processes: any[]) => { + if (processes.length > 0) { + const folders: any[] = processes.map((process: any) => process.processData); + + const foldersLive = folders.filter((folder: any) => folder.isArchived === 'false'); + if (foldersLive.length !== 0) { + router.push( + Module.getInstance() + .get() + .modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", foldersLive[foldersLive.length - 1].uid) + ); + } } }); diff --git a/src/pages/_app.tsx b/src/pages/_app.tsx index 0dfb97b5..5270afc4 100644 --- a/src/pages/_app.tsx +++ b/src/pages/_app.tsx @@ -5,7 +5,6 @@ import type { NextPage } from "next"; import type { AppType, AppProps } from "next/app"; import { useEffect, useState, type ReactElement, type ReactNode } from "react"; import getConfig from "next/config"; -import { useRouter } from "next/router"; import { GoogleTagManager } from "@next/third-parties/google"; import { hotjar } from "react-hotjar"; @@ -75,7 +74,6 @@ const MyApp = (({ instance.HOTJAR_VERSION = hotjarVersion; instance._4NK_URL = _4nkUrl; - const router = useRouter(); const [isConnected, setIsConnected] = useState(false); const [isReady, setIsReady] = useState(false); @@ -84,26 +82,18 @@ const MyApp = (({ useEffect(() => { const isAuthenticated = User.getInstance().isAuthenticated(); setIsConnected(isAuthenticated); - if (isAuthenticated) { - MessageBus.getInstance().isReady().then(() => { - setTimeout(() => { - setIsReady(true); - }, 50); - }); - } - }, []); - useEffect(() => { - const isAuthenticated = User.getInstance().isAuthenticated(); - setIsConnected(isAuthenticated); if (isAuthenticated) { - MessageBus.getInstance().isReady().then(() => { - setTimeout(() => { - setIsReady(true); - }, 50); - }); + MessageBus.getInstance().initMessageListener(); + MessageBus.getInstance().isReady().then(() => setIsReady(true)); + + return () => { + MessageBus.getInstance().destroyMessageListener(); + }; } - }, [router]); + + return () => { }; + }, []); useEffect(() => { if (!hotjarSiteId || !hotjarVersion) { diff --git a/src/sdk/MessageBus.ts b/src/sdk/MessageBus.ts index 33a88d99..3c39c120 100644 --- a/src/sdk/MessageBus.ts +++ b/src/sdk/MessageBus.ts @@ -9,7 +9,6 @@ import MapUtils from './MapUtils'; export default class MessageBus { private static instance: MessageBus; - private messageListeners: Map void> = new Map(); private errors: { [key: string]: string } = {}; private isListening: boolean = false; @@ -20,20 +19,21 @@ export default class MessageBus { return MessageBus.instance; } + public initMessageListener(): void { + window.addEventListener('message', this.handleMessage.bind(this)); + } + + public destroyMessageListener(): void { + window.removeEventListener('message', this.handleMessage.bind(this)); + } + public isReady(): Promise { if (this.isListening) { return Promise.resolve(); } return new Promise((resolve: () => void) => { - const correlationId = `IS_READY_${uuidv4()}`; - this.initMessageListener(correlationId); - - const unsubscribe = EventBus.getInstance().on('IS_READY', (responseId: string) => { - if (responseId !== correlationId) { - return; - } + const unsubscribe = EventBus.getInstance().on('IS_READY', () => { unsubscribe(); - this.destroyMessageListener(correlationId); resolve(); }); }); @@ -41,30 +41,28 @@ export default class MessageBus { public requestLink(): Promise { return new Promise((resolve: () => void, reject: (error: string) => void) => { - const correlationId = `REQUEST_LINK_${uuidv4()}`; - this.initMessageListener(correlationId); + const messageId = `REQUEST_LINK_${uuidv4()}`; const unsubscribe = EventBus.getInstance().on('LINK_ACCEPTED', (responseId: string, message: { accessToken: string, refreshToken: string }) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); User.getInstance().setTokens(message.accessToken, message.refreshToken); resolve(); }); const unsubscribeError = EventBus.getInstance().on('ERROR_LINK_ACCEPTED', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); this.sendMessage({ - type: 'REQUEST_LINK' + type: 'REQUEST_LINK', + messageId }); }); } @@ -72,24 +70,21 @@ export default class MessageBus { public getPairingId(): Promise { return new Promise((resolve: (pairingId: string) => void, reject: (error: string) => void) => { this.checkToken().then(() => { - const correlationId = uuidv4(); - this.initMessageListener(correlationId); + const messageId = `GET_PAIRING_ID_${uuidv4()}`; const unsubscribe = EventBus.getInstance().on('GET_PAIRING_ID', (responseId: string, pairingId: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); resolve(pairingId); }); const unsubscribeError = EventBus.getInstance().on('ERROR_GET_PAIRING_ID', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); @@ -99,6 +94,7 @@ export default class MessageBus { this.sendMessage({ type: 'GET_PAIRING_ID', accessToken, + messageId }); }).catch(console.error); }); @@ -107,24 +103,21 @@ export default class MessageBus { public createFile(fileData: any, stakeholdersId: string[], customersId: string[]): Promise { return new Promise((resolve: (processCreated: any) => void, reject: (error: string) => void) => { this.checkToken().then(() => { - const correlationId = `CREATE_FILE_${uuidv4()}`; - this.initMessageListener(correlationId); + const messageId = `CREATE_FILE_${uuidv4()}`; const unsubscribe = EventBus.getInstance().on('PROCESS_CREATED', (responseId: string, processCreated: any) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); resolve(processCreated); }); const unsubscribeError = EventBus.getInstance().on('ERROR_PROCESS_CREATED', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); @@ -183,13 +176,13 @@ export default class MessageBus { storages: [] } }, - accessToken + accessToken, + messageId }); }).catch(console.error); }); } - public getFiles(): Promise { return new Promise((resolve: (files: any[]) => void, reject: (error: string) => void) => { this.getProcesses().then(async (processes: any) => { @@ -254,304 +247,6 @@ export default class MessageBus { }); } - public createDocument(documentData: any, stakeholdersId: string[], customersId: string[]): Promise { - return new Promise((resolve: (processCreated: any) => void, reject: (error: string) => void) => { - this.checkToken().then(() => { - const correlationId = `CREATE_DOCUMENT_${uuidv4()}`; - this.initMessageListener(correlationId); - - const unsubscribe = EventBus.getInstance().on('PROCESS_CREATED', (responseId: string, processCreated: any) => { - if (responseId !== correlationId) { - return; - } - unsubscribe(); - this.destroyMessageListener(correlationId); - resolve(processCreated); - }); - - const unsubscribeError = EventBus.getInstance().on('ERROR_PROCESS_CREATED', (responseId: string, error: string) => { - if (responseId !== correlationId) { - return; - } - unsubscribeError(); - this.destroyMessageListener(correlationId); - reject(error); - }); - - const user = User.getInstance(); - const accessToken = user.getAccessToken()!; - - const ownerId = user.getPairingId()!; - const documentDataFields: string[] = Object.keys(documentData); - - this.sendMessage({ - type: 'CREATE_PROCESS', - processData: documentData, - privateFields: documentDataFields, - roles: { - demiurge: { - members: [ownerId], - validation_rules: [], - storages: [] - }, - owner: { - members: [ownerId], - validation_rules: [ - { - quorum: 0.5, - fields: [...documentDataFields, 'roles'], - min_sig_member: 1, - }, - ], - storages: [] - }, - stakeholders: { - members: stakeholdersId, - validation_rules: [ - { - quorum: 0.5, - fields: ['documents', 'motes'], - min_sig_member: 1, - }, - ], - storages: [] - }, - customers: { - members: customersId, - validation_rules: [ - { - quorum: 0.0, - fields: documentDataFields, - min_sig_member: 0.0, - }, - ], - storages: [] - }, - apophis: { - members: [ownerId], - validation_rules: [], - storages: [] - } - }, - accessToken - }); - }).catch(console.error); - }); - } - - public getDocuments(): Promise { - return new Promise((resolve: (documents: any[]) => void, reject: (error: string) => void) => { - this.getProcesses().then(async (processes: any) => { - const documents: any[] = []; - - for (const processId of Object.keys(processes)) { - const process = processes[processId]; - if (!process.states) { - continue; - } - - const isDocument: boolean = process.states - .map((state: any) => state.keys) - .filter((keys: any) => keys['uid'] && keys['utype_d']).length > 0; - - if (!isDocument) { - continue; - } - - let document: any; - - for (let stateId = 0; stateId < process.states.length - 1; stateId++) { - const lastState = process.states[stateId]; - if (!lastState) { - continue; - } - - const lastStateId = lastState.state_id; - if (!lastStateId) { - continue; - } - - try { - const processData = await this.getData(processId, lastStateId); - const isEmpty = Object.keys(processData).length === 0; - if (isEmpty) { - continue; - } - - if (!document) { - document = { - processId, - lastStateId, - processData, - }; - } else { - for (const key of Object.keys(processData)) { - document.processData[key] = processData[key]; - } - document.lastStateId = lastStateId; - } - } catch (error) { - console.error(error); - } - } - - documents.push(document); - } - - resolve(documents); - }).catch(reject); - }); - } - - public createDeedType(deedTypeData: any, stakeholdersId: string[], customersId: string[]): Promise { - return new Promise((resolve: (processCreated: any) => void, reject: (error: string) => void) => { - this.checkToken().then(() => { - const correlationId = `CREATE_DEED_TYPE_${uuidv4()}`; - this.initMessageListener(correlationId); - - const unsubscribe = EventBus.getInstance().on('PROCESS_CREATED', (responseId: string, processCreated: any) => { - if (responseId !== correlationId) { - return; - } - unsubscribe(); - this.destroyMessageListener(correlationId); - resolve(processCreated); - }); - - const unsubscribeError = EventBus.getInstance().on('ERROR_PROCESS_CREATED', (responseId: string, error: string) => { - if (responseId !== correlationId) { - return; - } - unsubscribeError(); - this.destroyMessageListener(correlationId); - reject(error); - }); - - const user = User.getInstance(); - const accessToken = user.getAccessToken()!; - - const ownerId = user.getPairingId()!; - const deedTypeDataFields: string[] = Object.keys(deedTypeData); - - this.sendMessage({ - type: 'CREATE_PROCESS', - processData: deedTypeData, - privateFields: deedTypeDataFields, - roles: { - demiurge: { - members: [ownerId], - validation_rules: [], - storages: [] - }, - owner: { - members: [ownerId], - validation_rules: [ - { - quorum: 0.5, - fields: [...deedTypeDataFields, 'roles'], - min_sig_member: 1, - }, - ], - storages: [] - }, - stakeholders: { - members: stakeholdersId, - validation_rules: [ - { - quorum: 0.5, - fields: ['documents', 'motes'], - min_sig_member: 1, - }, - ], - storages: [] - }, - customers: { - members: customersId, - validation_rules: [ - { - quorum: 0.0, - fields: deedTypeDataFields, - min_sig_member: 0.0, - }, - ], - storages: [] - }, - apophis: { - members: [ownerId], - validation_rules: [], - storages: [] - } - }, - accessToken - }); - }).catch(console.error); - }); - } - - public getDeepTypes(): Promise { - return new Promise((resolve: (deepTypes: any[]) => void, reject: (error: string) => void) => { - this.getProcesses().then(async (processes: any) => { - const deepTypes: any[] = []; - - for (const processId of Object.keys(processes)) { - const process = processes[processId]; - if (!process.states) { - continue; - } - - const isDeedType: boolean = process.states - .map((state: any) => state.keys) - .filter((keys: any) => keys['uid'] && keys['utype_dt']).length > 0; - - if (!isDeedType) { - continue; - } - - let deedType: any; - - for (let stateId = 0; stateId < process.states.length - 1; stateId++) { - const lastState = process.states[stateId]; - if (!lastState) { - continue; - } - - const lastStateId = lastState.state_id; - if (!lastStateId) { - continue; - } - - try { - const processData = await this.getData(processId, lastStateId); - const isEmpty = Object.keys(processData).length === 0; - if (isEmpty) { - continue; - } - - if (!deedType) { - deedType = { - processId, - lastStateId, - processData, - }; - } else { - for (const key of Object.keys(processData)) { - deedType.processData[key] = processData[key]; - } - deedType.lastStateId = lastStateId; - } - } catch (error) { - console.error(error); - } - } - - deepTypes.push(deedType); - } - - resolve(deepTypes); - }).catch(reject); - }); - } - public getProcessesDecoded(filterPublicValues: (publicValues: { [key: string]: any }) => boolean): Promise { return new Promise((resolve: (processesDecoded: any[]) => void, reject: (error: string) => void) => { this.getProcesses().then(async (processes: any) => { @@ -603,7 +298,6 @@ export default class MessageBus { if (!processData) { continue; } - processData = MapUtils.toJson(processData); const isEmpty = Object.keys(processData).length === 0; if (isEmpty) { @@ -613,6 +307,7 @@ export default class MessageBus { for (const key of Object.keys(publicDataDecoded)) { processData[key] = publicDataDecoded[key]; } + processData = MapUtils.toJson(processData); if (!processDecoded) { processDecoded = { @@ -642,24 +337,21 @@ export default class MessageBus { public createProcess(processData: any, privateFields: string[], roles: {}): Promise { return new Promise((resolve: (processCreated: any) => void, reject: (error: string) => void) => { this.checkToken().then(() => { - const correlationId = `CREATE_PROCESS_${uuidv4()}`; - this.initMessageListener(correlationId); + const messageId = `CREATE_PROCESS_${uuidv4()}`; const unsubscribe = EventBus.getInstance().on('PROCESS_CREATED', (responseId: string, processCreated: any) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); resolve(processCreated); }); const unsubscribeError = EventBus.getInstance().on('ERROR_PROCESS_CREATED', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); @@ -671,33 +363,31 @@ export default class MessageBus { processData: processData, privateFields: privateFields, roles: roles, - accessToken + accessToken, + messageId }); }).catch(console.error); }); } - public updateProcess(processId: string, lastStateId: string, newData: any, privateFields: string[], roles: {} | null): Promise { + public updateProcess(processId: string, newData: any, privateFields: string[], roles: {} | null): Promise { return new Promise((resolve: (processUpdated: any) => void, reject: (error: string) => void) => { this.checkToken().then(() => { - const correlationId = uuidv4(); - this.initMessageListener(correlationId); + const messageId = uuidv4(); const unsubscribe = EventBus.getInstance().on('PROCESS_UPDATED', (responseId: string, processUpdated: any) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); resolve(processUpdated); }); const unsubscribeError = EventBus.getInstance().on('ERROR_PROCESS_UPDATED', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); @@ -707,11 +397,11 @@ export default class MessageBus { this.sendMessage({ type: 'UPDATE_PROCESS', processId, - lastStateId, newData, privateFields, roles, - accessToken + accessToken, + messageId }); }).catch(console.error); }); @@ -720,15 +410,13 @@ export default class MessageBus { public getProcesses(): Promise { return new Promise((resolve: (processes: any) => void, reject: (error: string) => void) => { this.checkToken().then(() => { - const correlationId = `GET_PROCESSES_${uuidv4()}`; - this.initMessageListener(correlationId); + const messageId = `GET_PROCESSES_${uuidv4()}`; const unsubscribe = EventBus.getInstance().on('PROCESSES_RETRIEVED', (responseId: string, processes: any) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); // Filter processes by my processes setTimeout(() => { @@ -746,11 +434,10 @@ export default class MessageBus { }); const unsubscribeError = EventBus.getInstance().on('ERROR_PROCESSES_RETRIEVED', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); @@ -759,7 +446,8 @@ export default class MessageBus { this.sendMessage({ type: 'GET_PROCESSES', - accessToken + accessToken, + messageId }); }).catch(console.error); }); @@ -768,24 +456,21 @@ export default class MessageBus { public getMyProcesses(): Promise { return new Promise((resolve: (processes: any) => void, reject: (error: string) => void) => { this.checkToken().then(() => { - const correlationId = `GET_MY_PROCESSES_${uuidv4()}`; - this.initMessageListener(correlationId); + const messageId = `GET_MY_PROCESSES_${uuidv4()}`; const unsubscribe = EventBus.getInstance().on('GET_MY_PROCESSES', (responseId: string, processes: any) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); resolve(processes); }); const unsubscribeError = EventBus.getInstance().on('ERROR_GET_MY_PROCESSES', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); @@ -794,7 +479,8 @@ export default class MessageBus { this.sendMessage({ type: 'GET_MY_PROCESSES', - accessToken + accessToken, + messageId }); }).catch(console.error); }); @@ -803,24 +489,21 @@ export default class MessageBus { public notifyUpdate(processId: string, stateId: string): Promise { return new Promise((resolve: () => void, reject: (error: string) => void) => { this.checkToken().then(() => { - const correlationId = uuidv4(); - this.initMessageListener(correlationId); + const messageId = uuidv4(); const unsubscribe = EventBus.getInstance().on('UPDATE_NOTIFIED', (responseId: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); resolve(); }); const unsubscribeError = EventBus.getInstance().on('ERROR_UPDATE_NOTIFIED', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); @@ -831,7 +514,8 @@ export default class MessageBus { type: 'NOTIFY_UPDATE', processId, stateId, - accessToken + accessToken, + messageId }); }).catch(console.error); }); @@ -840,24 +524,21 @@ export default class MessageBus { public validateState(processId: string, stateId: string): Promise { return new Promise((resolve: (stateValidated: any) => void, reject: (error: string) => void) => { this.checkToken().then(() => { - const correlationId = uuidv4(); - this.initMessageListener(correlationId); + const messageId = `VALIDATE_STATE_${uuidv4()}`; const unsubscribe = EventBus.getInstance().on('STATE_VALIDATED', (responseId: string, stateValidated: any) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); resolve(stateValidated); }); const unsubscribeError = EventBus.getInstance().on('ERROR_STATE_VALIDATED', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); @@ -868,7 +549,8 @@ export default class MessageBus { type: 'VALIDATE_STATE', processId, stateId, - accessToken + accessToken, + messageId }); }).catch(console.error); }); @@ -877,24 +559,21 @@ export default class MessageBus { public getData(processId: string, stateId: string): Promise { return new Promise((resolve: (data: any) => void, reject: (error: string) => void) => { this.checkToken().then(() => { - const correlationId = `DATA_RETRIEVED_${uuidv4()}`; - this.initMessageListener(correlationId); + const messageId = `DATA_RETRIEVED_${uuidv4()}`; const unsubscribe = EventBus.getInstance().on('DATA_RETRIEVED', (responseId: string, data: any) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); resolve(data); }); const unsubscribeError = EventBus.getInstance().on('ERROR_DATA_RETRIEVED', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); @@ -905,7 +584,8 @@ export default class MessageBus { type: 'RETRIEVE_DATA', processId, stateId, - accessToken + accessToken, + messageId }); }).catch(console.error); }); @@ -914,24 +594,21 @@ export default class MessageBus { public getPublicData(encodedData: number[]): Promise { return new Promise((resolve: (data: any) => void, reject: (error: string) => void) => { this.checkToken().then(() => { - const correlationId = uuidv4(); - this.initMessageListener(correlationId); + const messageId = `PUBLIC_DATA_DECODED_${uuidv4()}` const unsubscribe = EventBus.getInstance().on('PUBLIC_DATA_DECODED', (responseId: string, data: any) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); resolve(data); }); const unsubscribeError = EventBus.getInstance().on('ERROR_PUBLIC_DATA_DECODED', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); @@ -941,7 +618,8 @@ export default class MessageBus { this.sendMessage({ type: 'DECODE_PUBLIC_DATA', encodedData, - accessToken + accessToken, + messageId }); }).catch(console.error); }); @@ -949,24 +627,21 @@ export default class MessageBus { private validateToken(): Promise { return new Promise((resolve: (isValid: boolean) => void, reject: (error: string) => void) => { - const correlationId = `VALIDATE_TOKEN_${uuidv4()}`; - this.initMessageListener(correlationId); + const messageId = `VALIDATE_TOKEN_${uuidv4()}`; const unsubscribe = EventBus.getInstance().on('TOKEN_VALIDATED', (responseId: string, isValid: boolean) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); resolve(isValid); }); const unsubscribeError = EventBus.getInstance().on('ERROR_TOKEN_VALIDATED', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); @@ -977,32 +652,30 @@ export default class MessageBus { this.sendMessage({ type: 'VALIDATE_TOKEN', accessToken, - refreshToken + refreshToken, + messageId }); }); } private renewToken(): Promise { return new Promise((resolve: () => void, reject: (error: string) => void) => { - const correlationId = `RENEW_TOKEN_${uuidv4()}`; - this.initMessageListener(correlationId); + const messageId = `RENEW_TOKEN_${uuidv4()}`; const unsubscribe = EventBus.getInstance().on('TOKEN_RENEWED', (responseId: string, message: { accessToken: string, refreshToken: string }) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribe(); - this.destroyMessageListener(correlationId); User.getInstance().setTokens(message.accessToken, message.refreshToken); resolve(); }); const unsubscribeError = EventBus.getInstance().on('ERROR_TOKEN_RENEWED', (responseId: string, error: string) => { - if (responseId !== correlationId) { + if (responseId !== messageId) { return; } unsubscribeError(); - this.destroyMessageListener(correlationId); reject(error); }); @@ -1011,7 +684,8 @@ export default class MessageBus { this.sendMessage({ type: 'RENEW_TOKEN', - refreshToken + refreshToken, + messageId }); }); } @@ -1045,21 +719,7 @@ export default class MessageBus { iframe.contentWindow?.postMessage(message, targetOrigin); } - private initMessageListener(correlationId: string): void { - const listener = this.handleMessage.bind(this, correlationId); - this.messageListeners.set(correlationId, listener); - window.addEventListener('message', listener); - } - - private destroyMessageListener(correlationId: string): void { - const listener = this.messageListeners.get(correlationId); - if (listener) { - window.removeEventListener('message', listener); - this.messageListeners.delete(correlationId); - } - } - - private handleMessage(correlationId: string, event: MessageEvent): void { + private handleMessage(event: MessageEvent): void { if (!event.data || event.data.type === 'PassClientScriptReady') { return; } @@ -1097,78 +757,78 @@ export default class MessageBus { switch (message.type) { case 'LISTENING': this.isListening = true; - EventBus.getInstance().emit('IS_READY', correlationId); + EventBus.getInstance().emit('IS_READY'); break; case 'LINK_ACCEPTED': - this.doHandleMessage(correlationId, 'LINK_ACCEPTED', message, (message: any) => ({ + this.doHandleMessage(message.messageId, 'LINK_ACCEPTED', message, (message: any) => ({ accessToken: message.accessToken, refreshToken: message.refreshToken })); break; case 'VALIDATE_TOKEN': - this.doHandleMessage(correlationId, 'TOKEN_VALIDATED', message, (message: any) => message.isValid); + this.doHandleMessage(message.messageId, 'TOKEN_VALIDATED', message, (message: any) => message.isValid); break; case 'RENEW_TOKEN': - this.doHandleMessage(correlationId, 'TOKEN_RENEWED', message, (message: any) => ({ + this.doHandleMessage(message.messageId, 'TOKEN_RENEWED', message, (message: any) => ({ accessToken: message.accessToken, refreshToken: message.refreshToken })); break; case 'GET_PAIRING_ID': - this.doHandleMessage(correlationId, 'GET_PAIRING_ID', message, (message: any) => message.userPairingId); + this.doHandleMessage(message.messageId, 'GET_PAIRING_ID', message, (message: any) => message.userPairingId); break; case 'PROCESS_CREATED': // CREATE_PROCESS - this.doHandleMessage(correlationId, 'PROCESS_CREATED', message, (message: any) => message.processCreated); + this.doHandleMessage(message.messageId, 'PROCESS_CREATED', message, (message: any) => message.processCreated); break; case 'PROCESS_UPDATED': // UPDATE_PROCESS - this.doHandleMessage(correlationId, 'PROCESS_UPDATED', message, (message: any) => message.updatedProcess); + this.doHandleMessage(message.messageId, 'PROCESS_UPDATED', message, (message: any) => message.updatedProcess); break; case 'PROCESSES_RETRIEVED': // GET_PROCESSES - this.doHandleMessage(correlationId, 'PROCESSES_RETRIEVED', message, (message: any) => message.processes); + this.doHandleMessage(message.messageId, 'PROCESSES_RETRIEVED', message, (message: any) => message.processes); break; case 'GET_MY_PROCESSES': // GET_MY_PROCESSES - this.doHandleMessage(correlationId, 'GET_MY_PROCESSES', message, (message: any) => message.myProcesses); + this.doHandleMessage(message.messageId, 'GET_MY_PROCESSES', message, (message: any) => message.myProcesses); break; case 'DATA_RETRIEVED': // RETRIEVE_DATA - this.doHandleMessage(correlationId, 'DATA_RETRIEVED', message, (message: any) => message.data); + this.doHandleMessage(message.messageId, 'DATA_RETRIEVED', message, (message: any) => message.data); break; case 'PUBLIC_DATA_DECODED': // DECODE_PUBLIC_DATA - this.doHandleMessage(correlationId, 'PUBLIC_DATA_DECODED', message, (message: any) => message.decodedData); + this.doHandleMessage(message.messageId, 'PUBLIC_DATA_DECODED', message, (message: any) => message.decodedData); break; case 'UPDATE_NOTIFIED': // NOTIFY_UPDATE - this.doHandleMessage(correlationId, 'UPDATE_NOTIFIED', message, () => { }); + this.doHandleMessage(message.messageId, 'UPDATE_NOTIFIED', message, () => { }); break; case 'STATE_VALIDATED': // VALIDATE_STATE - this.doHandleMessage(correlationId, 'STATE_VALIDATED', message, (message: any) => message.validatedProcess); + this.doHandleMessage(message.messageId, 'STATE_VALIDATED', message, (message: any) => message.validatedProcess); break; case 'ERROR': console.error('Error:', message); - this.errors[correlationId] = message.error; + this.errors[message.messageId] = message.error; break; } } - private doHandleMessage(correlationId: string, messageType: string, message: any, callback: (message: any) => any) { - if (this.errors[correlationId]) { - const error = this.errors[correlationId]; - delete this.errors[correlationId]; - EventBus.getInstance().emit(`ERROR_${messageType}`, correlationId, error); + private doHandleMessage(messageId: string, messageType: string, message: any, callback: (message: any) => any) { + if (this.errors[messageId]) { + const error = this.errors[messageId]; + delete this.errors[messageId]; + EventBus.getInstance().emit(`ERROR_${messageType}`, messageId, error); return; } EventBus.getInstance().emit('MESSAGE_RECEIVED', message); - EventBus.getInstance().emit(messageType, correlationId, callback(message)); + EventBus.getInstance().emit(messageType, messageId, callback(message)); } }