Update CollaboratorService

This commit is contained in:
Sosthene 2025-09-11 14:09:01 +02:00
parent bb44128e12
commit 229a5a9585

View File

@ -4,9 +4,6 @@ import User from 'src/sdk/User';
import AbstractService from './AbstractService'; import AbstractService from './AbstractService';
import OfficeService from './OfficeService';
import RoleService from './RoleService';
import OfficeRoleService from './OfficeRoleService';
import { DEFAULT_STORAGE_URLS } from '@Front/Config/AppConstants'; import { DEFAULT_STORAGE_URLS } from '@Front/Config/AppConstants';
export default class CollaboratorService extends AbstractService { export default class CollaboratorService extends AbstractService {
@ -15,7 +12,7 @@ export default class CollaboratorService extends AbstractService {
super(); super();
} }
public static createCollaborator(collaboratorData: any, validatorId: string): Promise<any> { public static async createCollaborator(collaboratorData: any, validatorId: string): Promise<{ processId: string, processData: any }> {
const ownerId: string = User.getInstance().getPairingId()!; const ownerId: string = User.getInstance().getPairingId()!;
const processData: any = { const processData: any = {
@ -28,134 +25,85 @@ export default class CollaboratorService extends AbstractService {
}; };
const privateFields: string[] = Object.keys(processData); const privateFields: string[] = Object.keys(processData);
privateFields.splice(privateFields.indexOf('uid'), 1); const allFields: string[] = [...privateFields, 'roles'];
privateFields.splice(privateFields.indexOf('utype'), 1);
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
const roles: any = { const roles: any = {
demiurge: { demiurge: {
members: [ownerId], members: [ownerId, validatorId],
validation_rules: [], validation_rules: [],
storages: [] storages: []
}, },
owner: { owner: {
members: [ownerId], members: [ownerId, validatorId],
validation_rules: [ validation_rules: [
{ {
quorum: 1, quorum: 0.01,
fields: [...privateFields, 'roles', 'uid', 'utype', 'isDeleted'], fields: allFields,
min_sig_member: 1, min_sig_member: 0.01,
},
],
storages: [...DEFAULT_STORAGE_URLS]
},
validator: {
members: [validatorId],
validation_rules: [
{
quorum: 1,
fields: [...privateFields, 'roles', 'uid', 'utype', 'isDeleted'],
min_sig_member: 1,
}, },
], ],
storages: [...DEFAULT_STORAGE_URLS] storages: [...DEFAULT_STORAGE_URLS]
}, },
apophis: { apophis: {
members: [ownerId], members: [ownerId, validatorId],
validation_rules: [], validation_rules: [],
storages: [] storages: []
} }
}; };
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => { try {
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => { const processCreated = await this.messageBus.createProcess(processData, privateFields, roles);
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => { await this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id);
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => { await this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id);
this.getCollaboratorByUid(processCreated.processData.uid).then(resolve).catch(reject); const finalProcessData = await this.messageBus.getProcessData(processCreated.processId);
}).catch(reject); return { processId: processCreated.processId, processData: finalProcessData };
}).catch(reject); } catch (error) {
}).catch(reject); throw error;
}); }
} }
public static getCollaborators(callback: (processes: any[]) => void, waitForAll: boolean = false): void { public static getCollaborators(callback: (processes: Record<string, any>) => void): void {
// Check if we have valid cache const items: Record<string, any> = this.getItems('_collaborators_');
const items: any[] = this.getItems('_collaborators_'); if (Object.keys(items).length > 0) {
if (items.length > 0 && !waitForAll) { setTimeout(() => callback(items), 0);
setTimeout(() => callback([...items]), 0);
} }
this.messageBus.getProcessesDecoded((publicValues: any) => this.messageBus.getProcessesDecoded((processId: string, data: any) =>
publicValues['uid'] && data['utype'] &&
publicValues['utype'] && data['utype'] === 'collaborator' &&
publicValues['utype'] === 'collaborator' && data['isDeleted'] &&
publicValues['isDeleted'] && data['isDeleted'] === 'false' &&
publicValues['isDeleted'] === 'false' && !Object.keys(items).includes(processId)
!items.map((item: any) => item.processData.uid).includes(publicValues['uid']) ).then(async (processesData: Record<string, any>) => {
).then(async (processes: any[]) => { if (Object.keys(processesData).length === 0) {
if (processes.length === 0) { // If no new processes and no cached items, return empty array
if (waitForAll) { if (Object.keys(items).length === 0) {
callback([...items]); callback([]);
} }
return; return;
} }
const updatedItems: any[] = [...items]; // Single callback with all completed items
callback(items);
for (let processIndex = 0; processIndex < processes.length; processIndex++) { }).catch(error => {
let process = processes[processIndex]; console.error('Failed to fetch collaborators:', error);
// Return cached data if available, otherwise empty array
if (!waitForAll) { callback(items);
process = await this.completeCollaborator(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.completeCollaborator(process);
}
// Update cache
this.setItem('_collaborators_', 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 getCollaboratorsBy(whereClause: { [path: string]: any }): Promise<any[]> { public static getCollaboratorsBy(whereClause: { [path: string]: any }): Promise<Record<string, any>> {
return new Promise<any[]>((resolve: (collaborators: any[]) => void) => { return new Promise<Record<string, any>>((resolve: (collaborators: Record<string, any>) => void) => {
this.getCollaborators((processes: any[]) => { this.getCollaborators((processes: Record<string, any>) => {
if (processes.length === 0) { if (Object.keys(processes).length === 0) {
resolve([]); resolve({});
} else { } else {
resolve(processes.filter((process: any) => { const filteredEntries = Object.entries(processes).filter(([processId, process]) => {
const collaborator: any = process.processData;
for (const path in whereClause) { for (const path in whereClause) {
const paths: string[] = path.split('.'); const paths: string[] = path.split('.');
let value: any = collaborator; let value: any = process;
value['processId'] = processId;
for (let i = 0; i < paths.length; i++) { for (let i = 0; i < paths.length; i++) {
const currentPath = paths[i]; const currentPath = paths[i];
if (!currentPath || value === undefined || value === null) { if (!currentPath || value === undefined || value === null) {
@ -170,19 +118,28 @@ export default class CollaboratorService extends AbstractService {
} }
return true; return true;
})); });
// Convert filtered entries back to a Record
const filteredProcesses: Record<string, any> = {};
filteredEntries.forEach(([processId, process]) => {
filteredProcesses[processId] = process;
});
resolve(filteredProcesses);
} }
}, true); });
}); });
} }
public static getCollaboratorBy(whereClause: { [path: string]: any }): Promise<any | null> { public static getCollaboratorBy(whereClause: { [path: string]: any }): Promise<any | null> {
return new Promise<any | null>((resolve: (collaborator: any | null) => void) => { return new Promise<any | null>((resolve: (collaborator: any | null) => void) => {
this.getCollaborators((processes: any[]) => { this.getCollaborators((processes: Record<string, any>) => {
if (processes.length === 0) { const processArray = Object.values(processes);
if (processArray.length === 0) {
resolve(null); resolve(null);
} else { } else {
resolve(processes.find((process: any) => { resolve(processArray.find((process: any) => {
const collaborator: any = process.processData; const collaborator: any = process.processData;
for (const path in whereClause) { for (const path in whereClause) {
@ -205,120 +162,30 @@ export default class CollaboratorService extends AbstractService {
return true; return true;
})); }));
} }
}, true); });
}); });
} }
public static getCollaboratorByUid(uid: string, forceRefresh: boolean = false): Promise<any> { public static async updateCollaborator(processId: string, newData: any): Promise<void> {
// Check if we have valid cache try {
const item: any = this.getItem('_collaborators_', uid); const processUpdated = await this.messageBus.updateProcess(
if (item && !forceRefresh) { processId,
return Promise.resolve(item); { updated_at: new Date().toISOString(), ...newData },
} [],
null
);
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => { const newStateId: string = processUpdated.diffs[0]?.state_id;
this.messageBus.getProcessesDecoded((publicValues: any) => await this.messageBus.notifyUpdate(processId, newStateId);
publicValues['uid'] && await this.messageBus.validateState(processId, newStateId);
publicValues['uid'] === uid &&
publicValues['utype'] && const processData = await this.messageBus.getProcessData(processId);
publicValues['utype'] === 'collaborator' &&
publicValues['isDeleted'] &&
publicValues['isDeleted'] === 'false'
).then(async (processes: any[]) => {
if (processes.length === 0) {
resolve(null);
} else {
let process: any = processes[0];
process = await this.completeCollaborator(process);
// Update cache // Update cache
this.setItem('_collaborators_', process); this.setItem('_collaborators_', processId, processData);
} catch (error) {
resolve(process); console.error('Failed to update collaborator:', error);
} throw error; // Re-throw to allow caller to handle
}).catch(reject);
});
}
public static updateCollaborator(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 collaboratorUid: string = process.processData.uid;
this.removeItem('_collaborators_', collaboratorUid);
this.getCollaboratorByUid(collaboratorUid, true).then(resolve).catch(reject);
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
}
private static async completeCollaborator(process: any, progressCallback?: (processInProgress: any) => void): Promise<any> {
const progressiveProcess: any = JSON.parse(JSON.stringify(process));
if (process.processData.office) {
const office: any = (await OfficeService.getOfficeByUid(process.processData.office.uid)).processData;
if (office) {
process.processData.office = {
uid: office.uid,
idNot: office.idNot,
crpcen: office.crpcen,
name: office.name,
office_status: office.office_status
};
if (progressCallback) {
progressiveProcess.processData.office = process.processData.office;
progressCallback(JSON.parse(JSON.stringify(progressiveProcess)));
}
} else {
console.error('Office not found');
} }
} }
if (process.processData.role) {
const role: any = (await RoleService.getRoleByUid(process.processData.role.uid)).processData;
if (!role) {
console.error('Role not found');
} else {
process.processData.role = {
uid: role.uid,
name: role.name
};
}
if (progressCallback) {
progressiveProcess.processData.role = process.processData.role;
progressCallback(JSON.parse(JSON.stringify(progressiveProcess)));
}
}
if (process.processData.office_role) {
const officeRole: any = (await OfficeRoleService.getOfficeRoleByUid(process.processData.office_role.uid)).processData;
if (!officeRole) {
console.error('Office role not found');
} else {
process.processData.office_role = {
uid: officeRole.uid,
name: officeRole.name,
rules: officeRole.rules?.map((rule: any) => {
return {
uid: rule.uid,
name: rule.name
};
})
};
}
if (progressCallback) {
progressiveProcess.processData.office_role = process.processData.office_role;
progressCallback(JSON.parse(JSON.stringify(progressiveProcess)));
}
}
return process;
}
} }