Saltar a contenido

0009 - cat_prioridades_requerimiento

"""create cat_prioridades_requerimiento

Revision ID: 0009
Revises: 0008
Create Date: 2026-09-11
"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql


# revision identifiers, used by Alembic.
revision: str = "0009"
down_revision: Union[str, Sequence[str], None] = "0008"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:

    op.create_table(
        "cat_prioridades_requerimiento",

        sa.Column(
            "id",
            postgresql.UUID(as_uuid=True),
            nullable=False,
            server_default=sa.text("gen_random_uuid()"),
            comment="Identificador único UUID",
        ),

        sa.Column(
            "empresa_id",
            sa.BigInteger(),
            nullable=False,
            comment="Identificador BIGINT de la empresa en core.identidad (RLS)",
        ),

        sa.Column("codigo", sa.String(length=20), nullable=False, comment="Código"),
        sa.Column("nombre", sa.String(length=50), nullable=False, comment="Nombre"),
        sa.Column("descripcion", sa.String(length=255), nullable=True, comment="Descripción"),

        # Auditoría General
        sa.Column(
            "is_activo",
            sa.Boolean(),
            nullable=False,
            server_default=sa.text("true"),
            comment="Estado lógico del registro",
        ),

        sa.Column(
            "created_at",
            sa.TIMESTAMP(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
            comment="Fecha de creación",
        ),

        sa.Column(
            "updated_at",
            sa.TIMESTAMP(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
            comment="Fecha de última actualización",
        ),

        sa.Column(
            "deleted_at",
            sa.TIMESTAMP(timezone=True),
            nullable=True,
            comment="Fecha de eliminación lógica",
        ),

        sa.Column(
            "created_by",
            postgresql.UUID(as_uuid=True),
            nullable=True,
            comment="Usuario creador",
        ),

        sa.Column(
            "updated_by",
            postgresql.UUID(as_uuid=True),
            nullable=True,
            comment="Usuario modificador",
        ),

        sa.PrimaryKeyConstraint(
            "id",
            name="pk_cat_prioridades_requerimiento",
        ),

        sa.UniqueConstraint(
            "empresa_id",
            "id",
            name="uq_cat_prioridades_req_empresa_id",
        ),

        sa.UniqueConstraint(
            "empresa_id",
            "codigo",
            name="uq_cat_prioridades_req_empresa_codigo",
        ),

        comment="Catálogo de niveles de prioridad para requerimientos comerciales de visitas (ALTA, MEDIA, BAJA, URGENTE).",
        schema="fuerza_ventas",
    )

    op.create_index(
        "ix_cat_prioridades_req_empresa_activo",
        "cat_prioridades_requerimiento",
        ["empresa_id", "is_activo"],
        unique=False,
        schema="fuerza_ventas",
    )

    op.execute(
        """
        ALTER TABLE fuerza_ventas.cat_prioridades_requerimiento
        ENABLE ROW LEVEL SECURITY;
        """
    )

    op.execute(
        """
        CREATE POLICY rls_cat_prioridades_requerimiento_empresa
        ON fuerza_ventas.cat_prioridades_requerimiento
        FOR ALL
        USING (
            empresa_id = current_setting(
                'app.current_empresa_id',
                true
            )::BIGINT
        )
        WITH CHECK (
            empresa_id = current_setting(
                'app.current_empresa_id',
                true
            )::BIGINT
        );
        """
    )


def downgrade() -> None:

    op.execute(
        """
        DROP POLICY IF EXISTS rls_cat_prioridades_requerimiento_empresa
        ON fuerza_ventas.cat_prioridades_requerimiento;
        """
    )

    op.execute(
        """
        ALTER TABLE fuerza_ventas.cat_prioridades_requerimiento
        DISABLE ROW LEVEL SECURITY;
        """
    )

    op.drop_index(
        "ix_cat_prioridades_req_empresa_activo",
        table_name="cat_prioridades_requerimiento",
        schema="fuerza_ventas",
    )

    op.drop_table(
        "cat_prioridades_requerimiento",
        schema="fuerza_ventas",
    )