Fix ask-document page

This commit is contained in:
Anthony Janin 2025-06-25 20:46:37 +02:00
parent 65f67993ba
commit 7435a33fe0
24 changed files with 611 additions and 862 deletions

View File

@ -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"
}
}

View File

@ -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<any> {
public static createCustomer(customerData: any, validatorId: string): Promise<any> {
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<any>((resolve: (profileCreated: any) => void, reject: (error: string) => void) => {
return new Promise<any>((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<any[]> {
return this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['utype'] && publicValues['utype'] === 'profile');
public static getCustomers(): Promise<any[]> {
return this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['utype'] && publicValues['utype'] === 'customer');
}
public static getProfileByUid(uid: string): Promise<any> {
return new Promise<any>((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<any> {
return new Promise<any>((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 {

View File

@ -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<any> {
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<any>((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<any[]> {
return this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['utype'] && publicValues['utype'] === 'deedType');
}
public static getDeedTypeByUid(uid: string, includeDocumentTypes: boolean = true): Promise<any> {
return new Promise<any>((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<any[]>(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<void> {
return new Promise<void>((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);
});
}
}

View File

@ -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<any> {
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<any>((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<any[]> {
return this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['utype'] && publicValues['utype'] === 'document');
}
public static getDocumentByUid(uid: string): Promise<any> {
return new Promise<any>((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);
});
}
}

View File

@ -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<any>((resolve: (folderCreated: any) => void, reject: (error: string) => void) => {
return new Promise<any>((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<any> {
return new Promise<any>((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<any> {
return new Promise<any>((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<any[]>(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<any[]>(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<void> {
public static updateFolder(process: any, newData: any): Promise<void> {
return new Promise<void>((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);

View File

@ -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<DeedType[] | null>(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);
/*
const query: IGetDeedTypesParams = {
where: {
archived_at: null,
},
orderBy: {
name: "asc",
},
};
// FilterBy archived_at = null or not defined
deedTypes = deedTypes.filter((deedType: any) => !deedType.archived_at);
DeedTypes.getInstance()
.get(query)
.then((deedTypes) => setDeedTypes(deedTypes));
*/
// OrderBy name asc
deedTypes.sort((a: any, b: any) => a.name.localeCompare(b.name));
setDeedTypes(deedTypes);
});
}, []);
const onSelectedBlock = (block: IBlock) => {

View File

@ -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) => {

View File

@ -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]);

View File

@ -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] ?? "") || "_",

View File

@ -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) => {
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<DeedType>({
name: values["name"],
description: values["description"],
office: Office.hydrate<Office>({
uid: officeId,
}),
}),
);
router.push(
Module.getInstance()
.get()
.modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", deedTypeCreated.uid!),
);
*/
} catch (validationErrors: Array<ValidationError> | any) {
setValidationError(validationErrors as ValidationError[]);
return;

View File

@ -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);
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);
}
});
});
/*
const deedType = await DeedTypes.getInstance().getByUid(deedTypeUid as string, {
q: {
document_types: true,
},
});
DeedTypeService.getDeedTypeByUid(deedTypeUid as string).then((process: any) => {
if (process) {
const deedType: any = process.processData;
setDeedTypeSelected(deedType);
if (!deedType.document_types) return;
const documentsOptions: IOption[] = deedType.document_types
?.map((documentType) => {
?.map((documentType: any) => {
return {
label: documentType.name,
id: documentType.uid ?? "",
};
})
.sort((a, b) => a.label.localeCompare(b.label));
.sort((a: any, b: any) => 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);
});
/*
const documents = await DocumentTypes.getInstance().get({});
DocumentService.getDocuments().then((processes: any[]) => {
if (processes.length) {
const documents: any[] = processes.map((process: any) => process.processData);
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<DocumentType>({ 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;
let document_types: any[] = deedType.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) => {
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]);

View File

@ -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<HTMLFormElement> | 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<DocumentType>({
// TODO: review
const officeId = 'demo_notary_office_id'; // jwt.office_Id;
const documentFormModel = DocumentType.hydrate<DocumentType>({
...values,
office: Office.hydrate<Office>({
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'
office: {
uid: officeId,
}
};
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) => {
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
DocumentService.createDocument(documentData, validatorId).then((processCreated: 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<Office>({
uid: jwt.office_Id,
});
const documentToCreate = DocumentType.hydrate<DocumentType>({
...values,
office: office,
});
await validateOrReject(documentToCreate, { groups: ["createDocumentType"] });
const documentTypeCreated = await DocumentTypes.getInstance().post(documentToCreate);
router.push(
Module.getInstance()
.get()
.modules.pages.DocumentTypes.pages.DocumentTypesInformations.props.path.replace("[uid]", documentTypeCreated.uid!),
);
*/
} catch (e) {
if (e instanceof Array) {
setValidationError(e);

View File

@ -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();

View File

@ -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<Customer>(values);
await contactToCreate.validateOrReject?.({ groups: ["createCustomer"], forbidUnknownValues: false });
const contactFormModel = Contact.hydrate<Customer>(values);
await contactFormModel.validateOrReject?.({ groups: ["createCustomer"], forbidUnknownValues: false });
} catch (validationErrors) {
setValidationError(validationErrors as ValidationError[]);
return;
@ -75,74 +73,65 @@ 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<Customer>);
*/
} 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<OfficeFolder>({
customers: customersToLink.map((customer) => {
return Customer.hydrate<Customer>(customer);
}),
});
await Folders.getInstance().put(folderUid as string, body);
FolderService.updateFolder(process, { customers: customers }).then(() => {
router.push(`/folders/${folderUid}`);
});
}
});
}
*/
},
[existingCustomers, folderUid, router, selectedCustomers, selectedOption],
);
const getFolderPreSelectedCustomers = useCallback(
async (folderUid: string): Promise<IOption[] | undefined> => {
const query = {
q: {
customers: {
include: {
contact: true,
},
},
},
};
let preExistingCustomers: IOption[] = [];
try {
const folder = await Folders.getInstance().getByUid(folderUid, query);
preExistingCustomers = folder.customers!.map((customer) => {
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);
return;
@ -153,12 +142,12 @@ 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);
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);
@ -171,9 +160,9 @@ export default function AddClientToFolder(props: IProps) {
setAvailableCustomers(availableCustomers);
setExistingCustomers(existingCustomers);
*/
setIsLoaded(true);
//setSelectedOption(selectedOption);
setSelectedOption(selectedOption);
});
}, [folderUid, getFolderPreSelectedCustomers]);
const getSelectedOptions = useCallback((): IOption[] => {

View File

@ -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,7 +31,9 @@ export default function ParameterDocuments(props: IProps) {
const [formattedOptions, setFormattedOptions] = useState<IOption[]>([]);
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) => {
@ -41,8 +45,11 @@ export default function ParameterDocuments(props: IProps) {
id: document.uid ?? "",
};
});
formattedOptions.sort((a, b) => (a.label > b.label ? 1 : -1));
setFormattedOptions(formattedOptions);
}
});
}, [props.folder.deed?.document_types]);
const onVisibleDescriptionChange = (event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {

View File

@ -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);
}

View File

@ -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<OfficeFolder>({
@ -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

View File

@ -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) => {

View File

@ -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) => {

View File

@ -107,10 +107,11 @@ export default function FolderInformation(props: IProps) {
// TODO: review
return new Promise<any>((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);
}
});
});

View File

@ -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) => {

View File

@ -25,15 +25,19 @@ export default function Folder() {
useEffect(() => {
// TODO: review
FolderService.getFolders().then((folders: any) => {
const foldersLive = folders.filter((folder: any) => folder.processData.isArchived === 'false');
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].processData.uid)
.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", foldersLive[foldersLive.length - 1].uid)
);
}
}
});
/*

View File

@ -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) {

View File

@ -9,7 +9,6 @@ import MapUtils from './MapUtils';
export default class MessageBus {
private static instance: MessageBus;
private messageListeners: Map<string, (event: MessageEvent) => 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<void> {
if (this.isListening) {
return Promise.resolve();
}
return new Promise<void>((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<void> {
return new Promise<void>((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<string> {
return new Promise<string>((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<any> {
return new Promise<any>((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<any> {
return new Promise<any>((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<any> {
return new Promise<any>((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<any> {
return new Promise<any>((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<any> {
return new Promise<any>((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<any> {
return new Promise<any>((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<any[]> {
return new Promise<any[]>((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<any> {
return new Promise<any>((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<any> {
public updateProcess(processId: string, newData: any, privateFields: string[], roles: {} | null): Promise<any> {
return new Promise<any>((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<any> {
return new Promise<any>((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<any> {
return new Promise<any>((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<void> {
return new Promise<void>((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<any> {
return new Promise<any>((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<any> {
return new Promise<any>((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<any> {
return new Promise<any>((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<boolean> {
return new Promise<boolean>((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<void> {
return new Promise<void>((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));
}
}