Anthony Janin 87976783a3
All checks were successful
Build and Push to Registry / build-and-push (push) Successful in 3m59s
Fix some issues
2025-08-05 14:56:53 +02:00

329 lines
12 KiB
TypeScript

import { v4 as uuidv4 } from 'uuid';
import User from 'src/sdk/User';
import AbstractService from './AbstractService';
import CustomerService from './CustomerService';
import CollaboratorService from './CollaboratorService';
import DeedTypeService from './DeedTypeService';
import DocumentTypeService from './DocumentTypeService';
import DocumentService from './DocumentService';
import FileService from './FileService';
import NoteService from './NoteService';
export default class FolderService extends AbstractService {
private constructor() {
super();
}
public static createFolder(folderData: any, stakeholdersId: string[], customersId: string[]): Promise<any> {
const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = {
uid: uuidv4(),
utype: 'folder',
isDeleted: 'false',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...folderData
};
const privateFields: string[] = Object.keys(processData);
privateFields.splice(privateFields.indexOf('uid'), 1);
privateFields.splice(privateFields.indexOf('utype'), 1);
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
const roles: any = {
demiurge: {
members: [ownerId],
validation_rules: [],
storages: []
},
owner: {
members: [ownerId],
validation_rules: [
{
quorum: 0.5,
fields: [...privateFields, 'roles', 'uid', 'utype'],
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: privateFields,
min_sig_member: 0.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) => {
this.getFolderByUid(processCreated.processData.uid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static getFolders(callback: (processes: any[]) => void, waitForAll: boolean = false): void {
// Check if we have valid cache
const items: any[] = this.getItems('_folders_');
if (items.length > 0 && !waitForAll) {
setTimeout(() => callback([...items]), 0);
}
this.messageBus.getProcessesDecoded((publicValues: any) =>
publicValues['uid'] &&
publicValues['utype'] &&
publicValues['utype'] === 'folder' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false' &&
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
).then(async (processes: any[]) => {
if (processes.length === 0) {
if (waitForAll) {
callback([...items]);
}
return;
}
const updatedItems: any[] = [...items];
for (let processIndex = 0; processIndex < processes.length; processIndex++) {
let process = processes[processIndex];
if (!waitForAll) {
process = await this.completeFolder(process, (processInProgress: any) => {
const currentItems: any[] = [...updatedItems];
const existingIndex: number = currentItems.findIndex(item => item.processData?.uid === processInProgress.processData?.uid);
if (existingIndex >= 0) {
currentItems[existingIndex] = processInProgress;
} else {
currentItems.push(processInProgress);
}
callback(currentItems);
});
} else {
process = await this.completeFolder(process);
}
// Update cache
this.setItem('_folders_', process);
const existingIndex: number = updatedItems.findIndex(item => item.processData?.uid === process.processData?.uid);
if (existingIndex >= 0) {
updatedItems[existingIndex] = process;
} else {
updatedItems.push(process);
}
if (!waitForAll) {
callback([...updatedItems]);
}
}
if (waitForAll) {
callback([...updatedItems]);
}
});
}
public static getFoldersBy(whereClause: { [path: string]: any }): Promise<any[]> {
return new Promise<any[]>((resolve: (folders: any[]) => void) => {
this.getFolders((processes: any[]) => {
if (processes.length === 0) {
resolve([]);
} else {
resolve(processes.filter((process: any) => {
const folder: any = process.processData;
for (const path in whereClause) {
const paths: string[] = path.split('.');
let value: any = folder;
for (let i = 0; i < paths.length; i++) {
const currentPath = paths[i];
if (!currentPath || value === undefined || value === null) {
break;
}
value = value[currentPath];
}
if (value !== whereClause[path]) {
return false;
}
}
return true;
}));
}
}, true);
});
}
public static getFolderByUid(uid: string): Promise<any> {
// Check if we have valid cache
const item: any = this.getItem('_folders_', uid);
if (item) {
return Promise.resolve(item);
}
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' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false'
).then(async (processes: any[]) => {
if (processes.length === 0) {
resolve(null);
} else {
let process: any = processes[0];
process = await this.completeFolder(process);
// Update cache
this.setItem('_folders_', process);
resolve(process);
}
}).catch(reject);
});
}
public static updateFolder(process: any, newData: any): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
const folderUid: string = process.processData.uid;
this.removeItem('_folders_', folderUid);
this.getFolderByUid(folderUid).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
public static refreshFolderByUid(uid: string): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
this.getFolderByUid(uid).then((process: any) => {
this.updateFolder(process, {}).then(resolve).catch(reject);
}).catch(reject);
});
}
private static async completeFolder(process: any, progressCallback?: (processInProgress: any) => void): Promise<any> {
const progressiveProcess: any = JSON.parse(JSON.stringify(process));
if (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 customer of process.processData.customers) {
customers.push((await CustomerService.getCustomerByUid(customer.uid)).processData);
}
resolve(customers);
});
if (process.processData.customers && process.processData.customers.length > 0) {
const documents: any[] = (await DocumentService.getDocuments()).map((process: any) => process.processData);
for (const customer of process.processData.customers) {
customer.documents = documents.filter((document: any) => (document.depositor && document.depositor.uid === customer.uid) || (document.customer && document.customer.uid === customer.uid));
for (const document of customer.documents) {
if (document.document_type) {
document.document_type = (await DocumentTypeService.getDocumentTypeByUid(document.document_type.uid)).processData;
}
if (document.files && document.files.length > 0) {
const files: any[] = [];
for (const file of document.files) {
files.push({ uid: file.uid, file_name: (await FileService.getFileByUid(file.uid)).processData.file_name });
}
document.files = files;
}
}
}
}
if (progressCallback) {
progressiveProcess.processData.customers = process.processData.customers;
progressCallback(JSON.parse(JSON.stringify(progressiveProcess)));
}
}
if (process.processData.stakeholders && process.processData.stakeholders.length > 0) {
process.processData.stakeholders = await new Promise<any[]>(async (resolve: (stakeholders: any[]) => void) => {
const stakeholders: any[] = [];
for (const stakeholder of process.processData.stakeholders) {
stakeholders.push((await CollaboratorService.getCollaboratorByUid(stakeholder.uid)).processData);
}
resolve(stakeholders);
});
if (progressCallback) {
progressiveProcess.processData.stakeholders = process.processData.stakeholders;
progressCallback(JSON.parse(JSON.stringify(progressiveProcess)));
}
}
if (process.processData.deed && process.processData.deed.deed_type) {
const deed_type: any = (await DeedTypeService.getDeedTypeByUid(process.processData.deed.deed_type.uid)).processData;
process.processData.deed.deed_type = deed_type;
if (deed_type.document_types && deed_type.document_types.length > 0) {
// Remove duplicates
process.processData.deed.document_types = deed_type.document_types.filter((item: any, index: number) => deed_type.document_types.findIndex((t: any) => t.uid === item.uid) === index);
}
if (progressCallback) {
progressiveProcess.processData.deed = process.processData.deed;
progressCallback(JSON.parse(JSON.stringify(progressiveProcess)));
}
}
const notes: any[] = (await NoteService.getNotes()).map((process: any) => process.processData);
if (notes.length > 0) {
process.processData.notes = notes.filter((note: any) => note.folder.uid === process.processData.uid);
if (progressCallback) {
progressiveProcess.processData.notes = process.processData.notes;
progressCallback(JSON.parse(JSON.stringify(progressiveProcess)));
}
}
return process;
}
}