Emp perfis #25

Merged
killer-cf merged 4 commits from emp-perfis into master 2025-11-15 00:58:00 +00:00
5 changed files with 29 additions and 322 deletions
Showing only changes of commit 5b2c682870 - Show all commits

View File

@@ -15,8 +15,8 @@ import type * as actions_smtp from "../actions/smtp.js";
import type * as actions_utils_nodeCrypto from "../actions/utils/nodeCrypto.js"; import type * as actions_utils_nodeCrypto from "../actions/utils/nodeCrypto.js";
import type * as atestadosLicencas from "../atestadosLicencas.js"; import type * as atestadosLicencas from "../atestadosLicencas.js";
import type * as ausencias from "../ausencias.js"; import type * as ausencias from "../ausencias.js";
import type * as auth from "../auth.js";
import type * as auth_utils from "../auth/utils.js"; import type * as auth_utils from "../auth/utils.js";
import type * as auth from "../auth.js";
import type * as chat from "../chat.js"; import type * as chat from "../chat.js";
import type * as configuracaoEmail from "../configuracaoEmail.js"; import type * as configuracaoEmail from "../configuracaoEmail.js";
import type * as crons from "../crons.js"; import type * as crons from "../crons.js";
@@ -28,7 +28,6 @@ import type * as ferias from "../ferias.js";
import type * as funcionarios from "../funcionarios.js"; import type * as funcionarios from "../funcionarios.js";
import type * as healthCheck from "../healthCheck.js"; import type * as healthCheck from "../healthCheck.js";
import type * as http from "../http.js"; import type * as http from "../http.js";
import type * as limparPerfisAntigos from "../limparPerfisAntigos.js";
import type * as logsAcesso from "../logsAcesso.js"; import type * as logsAcesso from "../logsAcesso.js";
import type * as logsAtividades from "../logsAtividades.js"; import type * as logsAtividades from "../logsAtividades.js";
import type * as logsLogin from "../logsLogin.js"; import type * as logsLogin from "../logsLogin.js";
@@ -54,6 +53,14 @@ import type {
FunctionReference, FunctionReference,
} from "convex/server"; } from "convex/server";
/**
* A utility for referencing Convex functions in your app's API.
*
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
declare const fullApi: ApiFromModules<{ declare const fullApi: ApiFromModules<{
"actions/email": typeof actions_email; "actions/email": typeof actions_email;
"actions/linkPreview": typeof actions_linkPreview; "actions/linkPreview": typeof actions_linkPreview;
@@ -62,8 +69,8 @@ declare const fullApi: ApiFromModules<{
"actions/utils/nodeCrypto": typeof actions_utils_nodeCrypto; "actions/utils/nodeCrypto": typeof actions_utils_nodeCrypto;
atestadosLicencas: typeof atestadosLicencas; atestadosLicencas: typeof atestadosLicencas;
ausencias: typeof ausencias; ausencias: typeof ausencias;
auth: typeof auth;
"auth/utils": typeof auth_utils; "auth/utils": typeof auth_utils;
auth: typeof auth;
chat: typeof chat; chat: typeof chat;
configuracaoEmail: typeof configuracaoEmail; configuracaoEmail: typeof configuracaoEmail;
crons: typeof crons; crons: typeof crons;
@@ -75,7 +82,6 @@ declare const fullApi: ApiFromModules<{
funcionarios: typeof funcionarios; funcionarios: typeof funcionarios;
healthCheck: typeof healthCheck; healthCheck: typeof healthCheck;
http: typeof http; http: typeof http;
limparPerfisAntigos: typeof limparPerfisAntigos;
logsAcesso: typeof logsAcesso; logsAcesso: typeof logsAcesso;
logsAtividades: typeof logsAtividades; logsAtividades: typeof logsAtividades;
logsLogin: typeof logsLogin; logsLogin: typeof logsLogin;
@@ -95,30 +101,14 @@ declare const fullApi: ApiFromModules<{
"utils/getClientIP": typeof utils_getClientIP; "utils/getClientIP": typeof utils_getClientIP;
verificarMatriculas: typeof verificarMatriculas; verificarMatriculas: typeof verificarMatriculas;
}>; }>;
declare const fullApiWithMounts: typeof fullApi;
/**
* A utility for referencing Convex functions in your app's public API.
*
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
export declare const api: FilterApi< export declare const api: FilterApi<
typeof fullApi, typeof fullApiWithMounts,
FunctionReference<any, "public"> FunctionReference<any, "public">
>; >;
/**
* A utility for referencing Convex functions in your app's internal API.
*
* Usage:
* ```js
* const myFunctionReference = internal.myModule.myFunction;
* ```
*/
export declare const internal: FilterApi< export declare const internal: FilterApi<
typeof fullApi, typeof fullApiWithMounts,
FunctionReference<any, "internal"> FunctionReference<any, "internal">
>; >;

View File

@@ -10,6 +10,7 @@
import { import {
ActionBuilder, ActionBuilder,
AnyComponents,
HttpActionBuilder, HttpActionBuilder,
MutationBuilder, MutationBuilder,
QueryBuilder, QueryBuilder,
@@ -18,9 +19,15 @@ import {
GenericQueryCtx, GenericQueryCtx,
GenericDatabaseReader, GenericDatabaseReader,
GenericDatabaseWriter, GenericDatabaseWriter,
FunctionReference,
} from "convex/server"; } from "convex/server";
import type { DataModel } from "./dataModel.js"; import type { DataModel } from "./dataModel.js";
type GenericCtx =
| GenericActionCtx<DataModel>
| GenericMutationCtx<DataModel>
| GenericQueryCtx<DataModel>;
/** /**
* Define a query in this Convex app's public API. * Define a query in this Convex app's public API.
* *
@@ -85,12 +92,11 @@ export declare const internalAction: ActionBuilder<DataModel, "internal">;
/** /**
* Define an HTTP action. * Define an HTTP action.
* *
* The wrapped function will be used to respond to HTTP requests received * This function will be used to respond to HTTP requests received by a Convex
* by a Convex deployment if the requests matches the path and method where * deployment if the requests matches the path and method where this action
* this action is routed. Be sure to route your httpAction in `convex/http.js`. * is routed. Be sure to route your action in `convex/http.js`.
* *
* @param func - The function. It receives an {@link ActionCtx} as its first argument * @param func - The function. It receives an {@link ActionCtx} as its first argument.
* and a Fetch API `Request` object as its second.
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up. * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
*/ */
export declare const httpAction: HttpActionBuilder; export declare const httpAction: HttpActionBuilder;

View File

@@ -16,6 +16,7 @@ import {
internalActionGeneric, internalActionGeneric,
internalMutationGeneric, internalMutationGeneric,
internalQueryGeneric, internalQueryGeneric,
componentsGeneric,
} from "convex/server"; } from "convex/server";
/** /**
@@ -80,14 +81,10 @@ export const action = actionGeneric;
export const internalAction = internalActionGeneric; export const internalAction = internalActionGeneric;
/** /**
* Define an HTTP action. * Define a Convex HTTP action.
* *
* The wrapped function will be used to respond to HTTP requests received * @param func - The function. It receives an {@link ActionCtx} as its first argument, and a `Request` object
* by a Convex deployment if the requests matches the path and method where * as its second.
* this action is routed. Be sure to route your httpAction in `convex/http.js`. * @returns The wrapped endpoint function. Route a URL path to this function in `convex/http.js`.
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument
* and a Fetch API `Request` object as its second.
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
*/ */
export const httpAction = httpActionGeneric; export const httpAction = httpActionGeneric;

View File

@@ -1,285 +0,0 @@
import { internalMutation, query } from "./_generated/server";
import { v } from "convex/values";
/**
* Listar todos os perfis (roles) do sistema
*/
export const listarTodosRoles = query({
args: {},
returns: v.array(
v.object({
_id: v.id("roles"),
nome: v.string(),
descricao: v.string(),
nivel: v.number(),
setor: v.optional(v.string()),
customizado: v.optional(v.boolean()),
editavel: v.optional(v.boolean()),
_creationTime: v.number(),
})
),
handler: async (ctx) => {
const roles = await ctx.db.query("roles").collect();
return roles.map((role) => ({
_id: role._id,
nome: role.nome,
descricao: role.descricao,
nivel: role.nivel,
setor: role.setor,
customizado: role.customizado,
editavel: role.editavel,
_creationTime: role._creationTime,
}));
},
});
/**
* Limpar perfis antigos/duplicados
*
* CRITÉRIOS:
* - Manter apenas: ti_master (nível 0), admin (nível 2), ti_usuario (nível 2)
* - Remover: admin antigo (nível 0), ti genérico (nível 1), outros duplicados
*/
export const limparPerfisAntigos = internalMutation({
args: {},
returns: v.object({
removidos: v.array(
v.object({
nome: v.string(),
descricao: v.string(),
nivel: v.number(),
motivo: v.string(),
})
),
mantidos: v.array(
v.object({
nome: v.string(),
descricao: v.string(),
nivel: v.number(),
})
),
}),
handler: async (ctx) => {
const roles = await ctx.db.query("roles").collect();
const removidos: Array<{
nome: string;
descricao: string;
nivel: number;
motivo: string;
}> = [];
const mantidos: Array<{
nome: string;
descricao: string;
nivel: number;
}> = [];
// Perfis que devem ser mantidos (apenas 1 de cada)
const perfisCorretos = new Map<string, boolean>();
perfisCorretos.set("ti_master", false);
perfisCorretos.set("admin", false);
perfisCorretos.set("ti_usuario", false);
for (const role of roles) {
let deveManter = false;
let motivo = "";
// TI_MASTER - Manter apenas o de nível 0
if (role.nome === "ti_master") {
if (role.nivel === 0 && !perfisCorretos.get("ti_master")) {
deveManter = true;
perfisCorretos.set("ti_master", true);
} else {
motivo =
role.nivel !== 0
? "TI_MASTER deve ser nível 0, este é nível " + role.nivel
: "TI_MASTER duplicado";
}
}
// ADMIN - Manter apenas o de nível 2
else if (role.nome === "admin") {
if (role.nivel === 2 && !perfisCorretos.get("admin")) {
deveManter = true;
perfisCorretos.set("admin", true);
} else {
motivo =
role.nivel !== 2
? "ADMIN deve ser nível 2, este é nível " + role.nivel
: "ADMIN duplicado";
}
}
// TI_USUARIO - Manter apenas o de nível 2
else if (role.nome === "ti_usuario") {
if (role.nivel === 2 && !perfisCorretos.get("ti_usuario")) {
deveManter = true;
perfisCorretos.set("ti_usuario", true);
} else {
motivo =
role.nivel !== 2
? "TI_USUARIO deve ser nível 2, este é nível " + role.nivel
: "TI_USUARIO duplicado";
}
}
// Perfis genéricos antigos (remover)
else if (role.nome === "ti") {
motivo =
"Perfil genérico 'ti' obsoleto - usar 'ti_master' ou 'ti_usuario'";
}
// Outros perfis específicos de setores (manter se forem nível >= 2)
else if (
role.nome === "rh" ||
role.nome === "financeiro" ||
role.nome === "controladoria" ||
role.nome === "licitacoes" ||
role.nome === "compras" ||
role.nome === "juridico" ||
role.nome === "comunicacao" ||
role.nome === "programas_esportivos" ||
role.nome === "secretaria_executiva" ||
role.nome === "gestao_pessoas" ||
role.nome === "usuario"
) {
if (role.nivel >= 2) {
deveManter = true;
} else {
motivo = `Perfil de setor com nível incorreto (${role.nivel}), deveria ser >= 2`;
}
}
// Perfis customizados (manter sempre)
else if (role.customizado) {
deveManter = true;
}
// Outros perfis desconhecidos
else {
motivo = "Perfil desconhecido ou obsoleto";
}
if (deveManter) {
mantidos.push({
nome: role.nome,
descricao: role.descricao,
nivel: role.nivel,
});
console.log(
`✅ MANTIDO: ${role.nome} (${role.descricao}) - Nível ${role.nivel}`
);
} else {
// Verificar se há usuários usando este perfil
const usuariosComRole = await ctx.db
.query("usuarios")
.withIndex("by_role", (q) => q.eq("roleId", role._id))
.collect();
if (usuariosComRole.length > 0) {
console.log(
`⚠️ AVISO: Não é possível remover "${role.nome}" porque ${usuariosComRole.length} usuário(s) ainda usa(m) este perfil`
);
mantidos.push({
nome: role.nome,
descricao: role.descricao,
nivel: role.nivel,
});
} else {
// Remover permissões associadas
const permissoes = await ctx.db
.query("rolePermissoes")
.withIndex("by_role", (q) => q.eq("roleId", role._id))
.collect();
for (const perm of permissoes) {
await ctx.db.delete(perm._id);
}
// Remover o role
await ctx.db.delete(role._id);
removidos.push({
nome: role.nome,
descricao: role.descricao,
nivel: role.nivel,
motivo: motivo || "Não especificado",
});
console.log(
`🗑️ REMOVIDO: ${role.nome} (${role.descricao}) - Nível ${role.nivel} - Motivo: ${motivo}`
);
}
}
}
return { removidos, mantidos };
},
});
/**
* Verificar se existem perfis com níveis incorretos
*/
export const verificarNiveisIncorretos = query({
args: {},
returns: v.array(
v.object({
nome: v.string(),
descricao: v.string(),
nivelAtual: v.number(),
nivelCorreto: v.number(),
problema: v.string(),
})
),
handler: async (ctx) => {
const roles = await ctx.db.query("roles").collect();
const problemas: Array<{
nome: string;
descricao: string;
nivelAtual: number;
nivelCorreto: number;
problema: string;
}> = [];
for (const role of roles) {
// TI_MASTER deve ser nível 0
if (role.nome === "ti_master" && role.nivel !== 0) {
problemas.push({
nome: role.nome,
descricao: role.descricao,
nivelAtual: role.nivel,
nivelCorreto: 0,
problema: "TI_MASTER deve ter acesso total (nível 0)",
});
}
// ADMIN deve ser nível 2
if (role.nome === "admin" && role.nivel !== 2) {
problemas.push({
nome: role.nome,
descricao: role.descricao,
nivelAtual: role.nivel,
nivelCorreto: 2,
problema: "ADMIN deve ser editável (nível 2)",
});
}
// TI_USUARIO deve ser nível 2
if (role.nome === "ti_usuario" && role.nivel !== 2) {
problemas.push({
nome: role.nome,
descricao: role.descricao,
nivelAtual: role.nivel,
nivelCorreto: 2,
problema: "TI_USUARIO deve ser editável (nível 2)",
});
}
// Perfil genérico "ti" não deveria existir
if (role.nome === "ti") {
problemas.push({
nome: role.nome,
descricao: role.descricao,
nivelAtual: role.nivel,
nivelCorreto: -1, // Indica que deve ser removido
problema: "Perfil genérico obsoleto - usar ti_master ou ti_usuario",
});
}
}
return problemas;
},
});