Especificación Técnica: rel_usuario_menu_accion¶
Esquema: core.identidad
Base de Datos: core
Servicio: svc-identidad
Propósito: Relación N:M de acciones habilitadas por usuario sobre menús específicos.
1. Justificación y Mejoras de Arquitectura¶
- Granularidad máxima: usuario + menú + acción(es) habilitadas.
- Unique (usuario_id, accion_id, empresa_id) evita duplicados.
- RLS por empresa actual.
2. Definiciones de Implementación¶
Table core.identidad.rel_usuario_menu_accion {
id uuid [pk, default: `gen_random_uuid()`]
empresa_id bigint [not null]
usuario_id uuid [not null, ref: > mae_usuarios.id]
menu_id uuid [not null, ref: > cfg_menu.id]
accion_id uuid [not null, ref: > cfg_menu_acciones.id]
// Auditoría General
is_activo boolean [not null, default: `true`, note: 'Estado lógico del registro']
created_at timestamptz [not null, default: `now()`, note: 'Fecha de creación']
updated_at timestamptz [not null, default: `now()`, note: 'Fecha de última actualización']
deleted_at timestamptz [note: 'Fecha de eliminación lógica']
created_by uuid [note: 'Usuario creador']
updated_by uuid [note: 'Usuario modificador']
Indexes {
(usuario_id, accion_id, empresa_id) [unique, name: 'uq_rel_usuario_menu_accion']
}
// RLS por empresa actual
}
CREATE TABLE IF NOT EXISTS core.identidad.rel_usuario_menu_accion (
id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
empresa_id BIGINT NOT NULL,
usuario_id UUID NOT NULL,
menu_id UUID NOT NULL,
accion_id UUID NOT NULL,
-- Auditoría General
is_activo BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ,
created_by UUID,
updated_by UUID,
CONSTRAINT uq_rel_usuario_menu_accion UNIQUE (usuario_id, accion_id, empresa_id),
CONSTRAINT fk_rel_usuario_menu_accion_usuario FOREIGN KEY (usuario_id) REFERENCES core.identidad.mae_usuarios (id),
CONSTRAINT fk_rel_usuario_menu_accion_menu FOREIGN KEY (menu_id) REFERENCES core.identidad.cfg_menu (id),
CONSTRAINT fk_rel_usuario_menu_accion_accion FOREIGN KEY (accion_id) REFERENCES core.identidad.cfg_menu_acciones (id)
);
-- Row-Level Security
ALTER TABLE core.identidad.rel_usuario_menu_accion ENABLE ROW LEVEL SECURITY;
CREATE POLICY aislamiento_empresa ON core.identidad.rel_usuario_menu_accion
FOR ALL
USING (empresa_id = NULLIF(current_setting('app.current_empresa_id', true), '')::BIGINT);
-- Comentarios
COMMENT ON COLUMN core.identidad.rel_usuario_menu_accion.empresa_id IS 'Empresa';
COMMENT ON COLUMN core.identidad.rel_usuario_menu_accion.usuario_id IS 'Usuario';
COMMENT ON COLUMN core.identidad.rel_usuario_menu_accion.menu_id IS 'Menú';
COMMENT ON COLUMN core.identidad.rel_usuario_menu_accion.accion_id IS 'Acción habilitada';
from datetime import datetime, date
from typing import Optional
import uuid
from sqlalchemy import (
BigInteger,
Boolean,
CheckConstraint,
Date,
DateTime,
ForeignKey,
Identity,
Index,
Integer,
SmallInteger,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class RelUsuarioMenuAccion(Base):
__tablename__ = 'rel_usuario_menu_accion'
__table_args__ = (
UniqueConstraint('usuario_id', 'accion_id', 'empresa_id', name='uq_rel_usuario_menu_accion'),
{"schema": 'core.identidad'},
)
id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
primary_key=True,
server_default=text("gen_random_uuid()"),
)
empresa_id: Mapped[int] = mapped_column(
BigInteger,
nullable=False,
comment='Empresa',
)
usuario_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
nullable=False,
ForeignKey("mae_usuarios.id"),
comment='Usuario',
)
menu_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
nullable=False,
ForeignKey("cfg_menu.id"),
comment='Menú',
)
accion_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
nullable=False,
ForeignKey("cfg_menu_acciones.id"),
comment='Acción habilitada',
)
# Auditoría General
is_activo: Mapped[bool] = mapped_column(
Boolean,
nullable=False,
server_default=text("true"),
comment='Estado lógico del registro',
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
nullable=False,
server_default=text("now()"),
comment='Fecha de creación',
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
nullable=False,
server_default=text("now()"),
comment='Fecha de última actualización',
)
deleted_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True),
comment='Fecha de eliminación lógica',
)
created_by: Mapped[uuid.UUID | None] = mapped_column(
UUID(as_uuid=True),
comment='Usuario creador',
)
updated_by: Mapped[uuid.UUID | None] = mapped_column(
UUID(as_uuid=True),
comment='Usuario modificador',
)
"""revision: core_id_0022
create table core.identidad.rel_usuario_menu_accion
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision: str = 'core_id_0022'
down_revision: str | None = 'core_id_0021'
branch_labels: str | None = None
depends_on: str | None = None
def upgrade() -> None:
op.create_table(
'rel_usuario_menu_accion',
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
sa.Column("empresa_id", sa.BigInteger(), nullable=False),
sa.Column("usuario_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("menu_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("accion_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("is_activo", sa.Boolean(), nullable=False, server_default=sa.text("true")),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
sa.Column("deleted_at", sa.DateTime(timezone=True)),
sa.Column("created_by", postgresql.UUID(as_uuid=True)),
sa.Column("updated_by", postgresql.UUID(as_uuid=True)),
sa.UniqueConstraint('usuario_id', 'accion_id', 'empresa_id', name='uq_rel_usuario_menu_accion'),
sa.ForeignKeyConstraint(['usuario_id'], ['core.identidad.mae_usuarios.id'], name='fk_rel_usuario_menu_accion_usuario'),
sa.ForeignKeyConstraint(['menu_id'], ['core.identidad.cfg_menu.id'], name='fk_rel_usuario_menu_accion_menu'),
sa.ForeignKeyConstraint(['accion_id'], ['core.identidad.cfg_menu_acciones.id'], name='fk_rel_usuario_menu_accion_accion'),
schema='core.identidad',
)
op.execute(
"""
ALTER TABLE core.identidad.rel_usuario_menu_accion ENABLE ROW LEVEL SECURITY;
CREATE POLICY aislamiento_empresa
ON core.identidad.rel_usuario_menu_accion
FOR ALL
USING (empresa_id = NULLIF(current_setting('app.current_empresa_id', true), '')::BIGINT);
"""
)
def downgrade() -> None:
op.drop_table('rel_usuario_menu_accion', schema='core.identidad')