Especificación Técnica: rel_empresa_aplicacion¶
Esquema: core.identidad
Base de Datos: core
Servicio: svc-identidad
Propósito: Relación N:M entre empresas y aplicaciones activadas en el núcleo.
1. Justificación y Mejoras de Arquitectura¶
- Controla qué empresas tienen habilitada cada aplicación.
- Unique (empresa_id, aplicacion_id) impide activaciones duplicadas.
- RLS por empresa actual al ser una configuración por empresa.
2. Definiciones de Implementación¶
Table core.identidad.rel_empresa_aplicacion {
id uuid [pk, default: `gen_random_uuid()`]
empresa_id bigint [not null, ref: > mae_empresas.id]
aplicacion_id uuid [not null, ref: > cat_aplicaciones.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 {
(empresa_id, aplicacion_id) [unique, name: 'uq_rel_empresa_aplicacion']
}
// RLS por empresa actual
}
CREATE TABLE IF NOT EXISTS core.identidad.rel_empresa_aplicacion (
id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
empresa_id BIGINT NOT NULL,
aplicacion_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_empresa_aplicacion UNIQUE (empresa_id, aplicacion_id),
CONSTRAINT fk_rel_empresa_aplicacion_empresa FOREIGN KEY (empresa_id) REFERENCES core.identidad.mae_empresas (id),
CONSTRAINT fk_rel_empresa_aplicacion_aplicacion FOREIGN KEY (aplicacion_id) REFERENCES core.identidad.cat_aplicaciones (id)
);
-- Row-Level Security
ALTER TABLE core.identidad.rel_empresa_aplicacion ENABLE ROW LEVEL SECURITY;
CREATE POLICY aislamiento_empresa ON core.identidad.rel_empresa_aplicacion
FOR ALL
USING (empresa_id = NULLIF(current_setting('app.current_empresa_id', true), '')::BIGINT);
-- Comentarios
COMMENT ON COLUMN core.identidad.rel_empresa_aplicacion.empresa_id IS 'Empresa';
COMMENT ON COLUMN core.identidad.rel_empresa_aplicacion.aplicacion_id IS 'Aplicación';
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 RelEmpresaAplicacion(Base):
__tablename__ = 'rel_empresa_aplicacion'
__table_args__ = (
UniqueConstraint('empresa_id', 'aplicacion_id', name='uq_rel_empresa_aplicacion'),
{"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,
ForeignKey("mae_empresas.id"),
comment='Empresa',
)
aplicacion_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
nullable=False,
ForeignKey("cat_aplicaciones.id"),
comment='Aplicación',
)
# 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_0016
create table core.identidad.rel_empresa_aplicacion
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision: str = 'core_id_0016'
down_revision: str | None = 'core_id_0015'
branch_labels: str | None = None
depends_on: str | None = None
def upgrade() -> None:
op.create_table(
'rel_empresa_aplicacion',
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("aplicacion_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('empresa_id', 'aplicacion_id', name='uq_rel_empresa_aplicacion'),
sa.ForeignKeyConstraint(['empresa_id'], ['core.identidad.mae_empresas.id'], name='fk_rel_empresa_aplicacion_empresa'),
sa.ForeignKeyConstraint(['aplicacion_id'], ['core.identidad.cat_aplicaciones.id'], name='fk_rel_empresa_aplicacion_aplicacion'),
schema='core.identidad',
)
op.execute(
"""
ALTER TABLE core.identidad.rel_empresa_aplicacion ENABLE ROW LEVEL SECURITY;
CREATE POLICY aislamiento_empresa
ON core.identidad.rel_empresa_aplicacion
FOR ALL
USING (empresa_id = NULLIF(current_setting('app.current_empresa_id', true), '')::BIGINT);
"""
)
def downgrade() -> None:
op.drop_table('rel_empresa_aplicacion', schema='core.identidad')