Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mejora - API - Refactorización de Update Model #260

Closed
wants to merge 23 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions eda/eda_api/lib/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import errorMiddleware from './middleware/error.middleware';
import Router from './router';

const path = require('path');
/* SDA CUSTOM*/ // Show current node_modules folder
/* SDA CUSTOM*/ console.log("NODE MODULES PATH",require.resolve('lodash'));
const database = require('../config/database.config');
const mongoose = require('mongoose');
const compression = require('compression');
Expand Down
281 changes: 89 additions & 192 deletions eda/eda_api/lib/module/updateModel/service/cleanModel.ts
Original file line number Diff line number Diff line change
@@ -1,195 +1,92 @@
/**
* Este módulo se encarga de limpiar y consolidar los permisos del modelo de datos.
* Maneja la deduplicación de roles, fusión de permisos y sincronización con MongoDB.
*/

import _ from "lodash";
import Group, { IGroup } from '../../admin/groups/model/group.model'
import DataSourceSchema from '../../datasource/model/datasource.model'
import Group, { IGroup } from '../../admin/groups/model/group.model';
import DataSourceSchema from '../../datasource/model/datasource.model';

export class CleanModel {

public async cleanModel(main_model : any) : Promise<any> {

let roles = _.cloneDeep(main_model.ds.metadata.model_granted_roles);

let model = {
"users": [],
"usersName": [],
"none": "",
"table": "",
"column": "",
"global": "",
"permission": "",
"type": "",
"value":[]
}

let modelAc = {
"users": [],
"usersName": [],
"none": "",
"table": "",
"column": "",
"global": "",
"permission": "",
"type": "",
"value":[]
}

let groupModel = {
"groups": [],
"groupsName": [],
"none": "",
"table": "",
"column": "",
"global": "",
"permission": "",
"type": "",
"value":[]
}

let model_granted_roles = [] ;

for (let i=0;i<roles.length;i++) {

if (i==0) {
model = roles[i];
model_granted_roles.push(model)

} else {
let match = model_granted_roles.find(r => r.table == roles[i].table
&& r.column == roles[i].column
&& r.type == roles[i].type
&& r.global == roles[i].global
&& r.none == roles[i].none
&& r.permission == roles[i].permission
&& r?.dynamic == roles[i]?.dynamic
);
if( _.isEmpty(match) == false ){
if(roles[i].value && match.value ){
roles[i].value.forEach((e,i)=> {
if( e != match.value[i]){
match = false;
}
});
}
}


if (_.isEmpty(match) == false && roles[i].type == "users") {
if (!match.users.includes(roles[i].users[0])) {match.users.push(roles[i].users[0]) } ;
if (!match.usersName.includes(roles[i].usersName[0])) {match.usersName.push(roles[i].usersName[0]) } ;
modelAc = match;

} else if (_.isEmpty(match) == false && roles[i].type == "groups") {
if (!match.groups.includes(roles[i].groups[0])) {match.groups.push(roles[i].groups[0]) } ;
if (!match.groupsName.includes(roles[i].groupsName[0])) {match.groupsName.push(roles[i].groupsName[0]) } ;
groupModel = match;
}
else {
if (_.isEmpty(modelAc.table) == false) {model_granted_roles.push(modelAc) };
if (_.isEmpty(groupModel.table) == false ) {model_granted_roles.push(groupModel)};
if (roles[i].type == "groups") {
groupModel = roles[i];
if (_.isEmpty(groupModel.table) == false) {model_granted_roles.push(groupModel)} ;
} else {
model = roles[i];
if (_.isEmpty(model.table) == false) {model_granted_roles.push(model)} ;
}
}
}
}


//recuperamos los model_granted_roles de mongo, donde se han añadido permisos para SCRM_*
const finder = await DataSourceSchema.find({_id: "111111111111111111111111" }) ;
let mgs = [];
const mgsmap = _.cloneDeep(finder.map(e => mgs = e.ds.metadata.model_granted_roles));

function objetosIgualesGrupos(objetoA: any, objetoB: any): boolean {
if (objetoA.groups != undefined && objetoB.groups != undefined
) return (
objetoA.groups.join(',') === objetoB.groups.join(',') &&
objetoA.groupsName.join(',') === objetoB.groupsName.join(',') &&
objetoA.none === objetoB.none &&
objetoA.table === objetoB.table &&
objetoA.column === objetoB.column &&
objetoA.global === objetoB.global &&
objetoA.permission === objetoB.permission &&
objetoA.type === objetoB.type
);
}


function objetosIgualesUsuarios(objetoA: any, objetoB: any): boolean {
if (objetoA.users != undefined && objetoB.users != undefined && objetoA?.dynamic && objetoB?.dynamic && objetoA?.value && objetoB?.value ){
return (
objetoA.users.join(',') === objetoB.users.join(',') &&
objetoA.usersName.join(',') === objetoB.usersName.join(',') &&
objetoA.none === objetoB.none &&
objetoA.table === objetoB.table &&
objetoA.column === objetoB.column &&
objetoA.global === objetoB.global &&
objetoA.permission === objetoB.permission &&
objetoA.type === objetoB.type &&
objetoA?.dynamic === objetoB?.dynamic &&
objetoA?.value[0] === objetoB?.value[0]
);
}else if (objetoA.users != undefined && objetoB.users != undefined && objetoA?.value && objetoB?.value ){
return (
objetoA.users.join(',') === objetoB.users.join(',') &&
objetoA.usersName.join(',') === objetoB.usersName.join(',') &&
objetoA.none === objetoB.none &&
objetoA.table === objetoB.table &&
objetoA.column === objetoB.column &&
objetoA.global === objetoB.global &&
objetoA.permission === objetoB.permission &&
objetoA.type === objetoB.type &&
objetoA?.value[0] === objetoB?.value[0]
);
}else if (objetoA.users != undefined && objetoB.users != undefined ){
return (
objetoA.users.join(',') === objetoB.users.join(',') &&
objetoA.usersName.join(',') === objetoB.usersName.join(',') &&
objetoA.none === objetoB.none &&
objetoA.table === objetoB.table &&
objetoA.column === objetoB.column &&
objetoA.global === objetoB.global &&
objetoA.permission === objetoB.permission &&
objetoA.type === objetoB.type
);
}
}


// Filtrar objetos únicos grupos
const objetosUnicosGrupos = model_granted_roles.filter((objeto, index, self) =>
self.findIndex(other => objetosIgualesGrupos(objeto, other)) === index
);



// Filtrar objetos únicos usuarios
const objetosUnicosUsuarios = model_granted_roles.filter((objeto, index, self) =>
self.findIndex(other => objetosIgualesUsuarios(objeto, other)) === index
);

model_granted_roles = objetosUnicosGrupos.concat(objetosUnicosUsuarios);

model_granted_roles.forEach( r=> {
r.source = 'update_model';
}
);

// Recuperando los permisos provenientes de SinergiaCRM
// la propiedad source --> "EDA" indica que el permiso proviene de la applicacion y no de la base de datos
if(mgsmap.length!==0) {
const userRoles = mgsmap[0].filter( (r:any) => {
return r?.source === 'SDA' && !r.groupsName.find( e => e.startsWith('SCRM_'))
});

// Agregando los permisos agregados previamente en la aplicacion.
const all_roles = [ ...model_granted_roles, ...userRoles];
main_model.ds.metadata.model_granted_roles = all_roles;
}

return main_model;
}
}

/**
* Limpia y consolida los permisos del modelo
* @param main_model Modelo de datos a procesar
* @returns Modelo procesado con permisos consolidados
*/
public async cleanModel(main_model: any): Promise<any> {
// Clonar roles para no modificar original
const roles = _.cloneDeep(main_model.ds.metadata.model_granted_roles);
const model_granted_roles: any[] = [];
const mapRoles = new Map();

/**
* Añade o actualiza un rol en el mapa de roles
* @param role Rol a procesar
* @param key Clave única del rol
*/
const addOrUpdateRole = (role: any, key: string) => {
const existingRole = mapRoles.get(key);
if (existingRole) {
// Fusionar usuarios o grupos según tipo
if (role.type === "users") {
existingRole.users = Array.from(new Set([...existingRole.users, ...role.users]));
existingRole.usersName = Array.from(new Set([...existingRole.usersName, ...role.usersName]));
} else if (role.type === "groups") {
existingRole.groups = Array.from(new Set([...existingRole.groups, ...role.groups]));
existingRole.groupsName = Array.from(new Set([...existingRole.groupsName, ...role.groupsName]));
}
} else {
// Crear nuevo rol si no existe
mapRoles.set(key, _.cloneDeep(role));
}
};

// Procesar cada rol y generar clave única
roles.forEach((role: any) => {
const key = `${role.table}-${role.column}-${role.type}-${role.global}-${role.none}-${role.permission}-${role.dynamic}-${role.value?.join(',')}`;
addOrUpdateRole(role, key);
});

// Convertir mapa a array
mapRoles.forEach((value) => model_granted_roles.push(value));

// Obtener permisos existentes de MongoDB
const finder = await DataSourceSchema.find({ _id: "111111111111111111111111" });
const mgsmap = finder
.map((e) => e.ds.metadata.model_granted_roles)
.reduce((acc, val) => acc.concat(val), []);

/**
* Filtra roles duplicados usando una clave compuesta
* @param roles Array de roles a filtrar
* @param comparator Función de comparación
* @returns Array de roles únicos
*/
const filterUniqueRoles = (roles: any[], comparator: (a: any, b: any) => boolean) => {
const seen = new Map();
return roles.filter((role) => {
const key = `${role.table}-${role.column}-${role.type}-${role.global}-${role.none}-${role.permission}-${role.users?.join(',')}-${role.groups?.join(',')}`;
if (seen.has(key)) return false;
seen.set(key, role);
return true;
});
};

// Obtener roles únicos y marcar origen
const uniqueRoles = filterUniqueRoles(model_granted_roles, _.isEqual);
uniqueRoles.forEach((role) => (role.source = "update_model"));

// Combinar roles según existencia de permisos en MongoDB
if (mgsmap.length) {
// Filtrar roles de usuario SDA no-SCRM
const userRoles = mgsmap.filter(
(r: any) => r?.source === "SDA" && !r.groupsName.some((name: string) => name.startsWith("SCRM_"))
);
main_model.ds.metadata.model_granted_roles = [...uniqueRoles, ...userRoles];
} else {
main_model.ds.metadata.model_granted_roles = uniqueRoles;
}

return main_model;
}
}
Loading