Saltar a contenido

Especificación Técnica: mae_locales_cliente

Esquema: clientes
Base de Datos: crm
Tabla Legacy Origen: i339t_locales_cliente (co_local, tx_direccion, tx_lat, tx_lng)
Propósito: Sucursales, almacenes y puntos de entrega físicos geolocalizados del cliente para visitas de promotores, geocercas móviles y despacho logístico de mercadería.


1. Justificación y Mejoras de Arquitectura

  • Desacoplamiento de Puntos de Entrega (1:N): Permite múltiples locales o sucursales por cliente comercial, cada uno con geolocalización de alta precisión y radio de geocerca en metros para validación de check-in móvil.
  • Aislamiento Multi-Tenant (RLS): Integra empresa_id BIGINT NOT NULL con políticas RLS obligatorias.
  • Integridad Referencial Compuesta: Clave única compuesta (empresa_id, id), constraint de unicidad de código local por cliente (empresa_id, cliente_id, codigo_local) y FK compuesta hacia clientes.mae_clientes.
  • Trazabilidad y Auditoría: Auditoría integral (created_at, updated_at, deleted_at, created_by, updated_by) con auditoría integral.

2. Definiciones de Implementación

Table clientes.mae_locales_cliente {
    id                      uuid              [pk, default: `gen_random_uuid()`, note: 'Identificador único UUID']
    empresa_id                  bigint        [not null, note: 'Identificador BIGINT de la empresa en core.identidad (RLS)']
    cliente_id              uuid              [not null, note: 'Cliente comercial propietario del local']
    codigo_local            varchar(30)       [not null, note: 'Código único de sucursal dentro del cliente']
    nombre_local            varchar(150)      [not null, note: 'Nombre comercial de la sucursal o punto de venta']
    tipo_domicilio_id       uuid              [not null, note: 'Tipo de domicilio o local (FK cat_tipos_domicilio)']
    is_local_matriz         boolean           [not null, default: `false`, note: 'Indica si es la sede principal o casa matriz']
    direccion_texto         text              [not null, note: 'Dirección física completa']
    referencia_ubicacion    varchar(255)      [note: 'Puntos de referencia de llegada']
    ciudad_id               uuid              [note: 'Correlación con core.identidad.mae_ciudades (sin FK cross-DB)']
    latitud                 double precision  [not null, note: 'Coordenada GPS Latitud']
    longitud                double precision  [not null, note: 'Coordenada GPS Longitud']
    radio_geocerca_metros   int               [not null, default: `100`, note: 'Radio de tolerancia en metros para check-in móvil']
    telefono_local          varchar(50)       [note: 'Teléfono de contacto de la sucursal']
    horario_atencion        varchar(150)      [note: 'Horario hábil de atención y recepción']

    // 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, id) [unique, name: 'uq_mae_locales_cliente_empresa_id']
        (empresa_id, cliente_id, codigo_local) [unique, name: 'uq_mae_locales_cliente_empresa_codigo']
        (empresa_id, is_activo) [name: 'ix_mae_locales_cliente_empresa_activo']
        (empresa_id, cliente_id) [name: 'ix_mae_locales_cliente_empresa_cliente']
        (empresa_id, latitud, longitud) [name: 'ix_mae_locales_cliente_empresa_gps']
        (empresa_id, ciudad_id) [name: 'ix_mae_locales_cliente_empresa_ciudad']
    }
}

Ref: clientes.mae_locales_cliente.(empresa_id, cliente_id) > clientes.mae_clientes.(empresa_id, id) [delete: cascade]
Ref: clientes.mae_locales_cliente.(empresa_id, tipo_domicilio_id) > clientes.cat_tipos_domicilio.(empresa_id, id)
CREATE TABLE IF NOT EXISTS clientes.mae_locales_cliente (
    id UUID NOT NULL DEFAULT gen_random_uuid(),
    empresa_id BIGINT NOT NULL,
    cliente_id UUID NOT NULL,
    codigo_local VARCHAR(30) NOT NULL,
    nombre_local VARCHAR(150) NOT NULL,
    tipo_domicilio_id UUID NOT NULL,
    is_local_matriz BOOLEAN NOT NULL DEFAULT false,
    direccion_texto TEXT NOT NULL,
    referencia_ubicacion VARCHAR(255),
    ciudad_id UUID,
    latitud DOUBLE PRECISION NOT NULL,
    longitud DOUBLE PRECISION NOT NULL,
    radio_geocerca_metros INT NOT NULL DEFAULT 100,
    telefono_local VARCHAR(50),
    horario_atencion VARCHAR(150),

    -- 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 pk_mae_locales_cliente
        PRIMARY KEY (id),

    CONSTRAINT uq_mae_locales_cliente_empresa_id
        UNIQUE (empresa_id, id),

    CONSTRAINT uq_mae_locales_cliente_empresa_codigo
        UNIQUE (empresa_id, cliente_id, codigo_local),

    CONSTRAINT fk_mae_locales_cliente_mae_clientes
        FOREIGN KEY (empresa_id, cliente_id)
        REFERENCES clientes.mae_clientes (empresa_id, id)
        ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS ix_mae_locales_cliente_empresa_activo
    ON clientes.mae_locales_cliente (empresa_id, is_activo);

CREATE INDEX IF NOT EXISTS ix_mae_locales_cliente_empresa_cliente
    ON clientes.mae_locales_cliente (empresa_id, cliente_id);

CREATE INDEX IF NOT EXISTS ix_mae_locales_cliente_empresa_gps
    ON clientes.mae_locales_cliente (empresa_id, latitud, longitud);

CREATE INDEX IF NOT EXISTS ix_mae_locales_cliente_empresa_ciudad
    ON clientes.mae_locales_cliente (empresa_id, ciudad_id);

COMMENT ON TABLE clientes.mae_locales_cliente IS
    'Locales y Puntos de Entrega del Cliente: Sucursales, almacenes y puntos geolocalizados para visitas y despacho logístico.';

COMMENT ON COLUMN clientes.mae_locales_cliente.id IS
    'Identificador único UUID';

COMMENT ON COLUMN clientes.mae_locales_cliente.empresa_id IS
    'Identificador UUID de la empresa en core.identidad (RLS)';

COMMENT ON COLUMN clientes.mae_locales_cliente.cliente_id IS
    'Cliente comercial propietario del local';

COMMENT ON COLUMN clientes.mae_locales_cliente.codigo_local IS
    'Código único de sucursal dentro del cliente';

COMMENT ON COLUMN clientes.mae_locales_cliente.nombre_local IS
    'Nombre comercial de la sucursal o punto de venta';

COMMENT ON COLUMN clientes.mae_locales_cliente.tipo_domicilio_id IS
    'Tipo de domicilio o local (FK cat_tipos_domicilio)';

COMMENT ON COLUMN clientes.mae_locales_cliente.is_local_matriz IS
    'Indica si es la sede principal o casa matriz';

COMMENT ON COLUMN clientes.mae_locales_cliente.direccion_texto IS
    'Dirección física completa';

COMMENT ON COLUMN clientes.mae_locales_cliente.referencia_ubicacion IS
    'Puntos de referencia de llegada';

COMMENT ON COLUMN clientes.mae_locales_cliente.ciudad_id IS
    'Correlación con core.identidad.mae_ciudades (sin FK cross-DB)';

COMMENT ON COLUMN clientes.mae_locales_cliente.latitud IS
    'Coordenada GPS Latitud';

COMMENT ON COLUMN clientes.mae_locales_cliente.longitud IS
    'Coordenada GPS Longitud';

COMMENT ON COLUMN clientes.mae_locales_cliente.radio_geocerca_metros IS
    'Radio de tolerancia en metros para check-in móvil';

COMMENT ON COLUMN clientes.mae_locales_cliente.telefono_local IS
    'Teléfono de contacto de la sucursal';

COMMENT ON COLUMN clientes.mae_locales_cliente.horario_atencion IS
    'Horario hábil de atención y recepción';

COMMENT ON COLUMN clientes.mae_locales_cliente.is_activo IS
    'Estado lógico del registro';

COMMENT ON COLUMN clientes.mae_locales_cliente.created_at IS
    'Fecha de creación';

COMMENT ON COLUMN clientes.mae_locales_cliente.updated_at IS
    'Fecha de última actualización';

COMMENT ON COLUMN clientes.mae_locales_cliente.deleted_at IS
    'Fecha de eliminación lógica';

COMMENT ON COLUMN clientes.mae_locales_cliente.created_by IS
    'Usuario creador';

COMMENT ON COLUMN clientes.mae_locales_cliente.updated_by IS
    'Usuario modificador';

ALTER TABLE clientes.mae_locales_cliente
    ENABLE ROW LEVEL SECURITY;

CREATE POLICY rls_mae_locales_cliente_empresa
    ON clientes.mae_locales_cliente
    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
    );
import uuid
from datetime import datetime
from typing import Optional

from sqlalchemy import (
    BigInteger,
    Boolean,
    Double,
    ForeignKeyConstraint,
    Index,
    Integer,
    String,
    Text,
    UniqueConstraint,
    text,
)
from sqlalchemy.dialects.postgresql import TIMESTAMPTZ, UUID
from sqlalchemy.orm import Mapped, mapped_column

from app.db.base import Base


class MaeLocalesCliente(Base):
    """
    Locales y Puntos de Entrega del Cliente.

    Sucursales, almacenes y puntos de entrega físicos geolocalizados del cliente
    para visitas de promotores y despacho de mercadería.

    Legacy:
        i339t_locales_cliente
    """

    __tablename__ = "mae_locales_cliente"

    __table_args__ = (
        UniqueConstraint(
            "empresa_id",
            "id",
            name="uq_mae_locales_cliente_empresa_id",
        ),
        UniqueConstraint(
            "empresa_id",
            "cliente_id",
            "codigo_local",
            name="uq_mae_locales_cliente_empresa_codigo",
        ),
        ForeignKeyConstraint(
            ["empresa_id", "cliente_id"],
            ["clientes.mae_clientes.empresa_id", "clientes.mae_clientes.id"],
            ondelete="CASCADE",
            name="fk_mae_locales_cliente_mae_clientes",
        ),
        Index(
            "ix_mae_locales_cliente_empresa_activo",
            "empresa_id",
            "is_activo",
        ),
        Index(
            "ix_mae_locales_cliente_empresa_cliente",
            "empresa_id",
            "cliente_id",
        ),
        Index(
            "ix_mae_locales_cliente_empresa_gps",
            "empresa_id",
            "latitud",
            "longitud",
        ),
        Index(
            "ix_mae_locales_cliente_empresa_ciudad",
            "empresa_id",
            "ciudad_id",
        ),
        {
            "schema": "clientes",
            "comment": "Locales y Puntos de Entrega del Cliente",
        },
    )

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        primary_key=True,
        server_default=text("gen_random_uuid()"),
        comment="Identificador único UUID",
    )

    empresa_id: Mapped[int] = mapped_column(
        BigInteger,
        nullable=False,
        comment="Identificador UUID de la empresa en core.identidad (RLS)",
    )

    cliente_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        nullable=False,
        comment="Cliente comercial propietario del local",
    )

    codigo_local: Mapped[str] = mapped_column(
        String(30),
        nullable=False,
        comment="Código único de sucursal dentro del cliente",
    )

    nombre_local: Mapped[str] = mapped_column(
        String(150),
        nullable=False,
        comment="Nombre comercial de la sucursal o punto de venta",
    )

    tipo_domicilio_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        nullable=False,
        comment="Tipo de domicilio o local (FK cat_tipos_domicilio)",
    )

    is_local_matriz: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default=text("false"),
        comment="Indica si es la sede principal o casa matriz",
    )

    direccion_texto: Mapped[str] = mapped_column(
        Text,
        nullable=False,
        comment="Dirección física completa",
    )

    referencia_ubicacion: Mapped[Optional[str]] = mapped_column(
        String(255),
        nullable=True,
        comment="Puntos de referencia de llegada",
    )

    ciudad_id: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        nullable=True,
        comment="Correlación con core.identidad.mae_ciudades (sin FK cross-DB)",
    )

    latitud: Mapped[float] = mapped_column(
        Double,
        nullable=False,
        comment="Coordenada GPS Latitud",
    )

    longitud: Mapped[float] = mapped_column(
        Double,
        nullable=False,
        comment="Coordenada GPS Longitud",
    )

    radio_geocerca_metros: Mapped[int] = mapped_column(
        Integer,
        nullable=False,
        server_default=text("100"),
        comment="Radio de tolerancia en metros para check-in móvil",
    )

    telefono_local: Mapped[Optional[str]] = mapped_column(
        String(50),
        nullable=True,
        comment="Teléfono de contacto de la sucursal",
    )

    horario_atencion: Mapped[Optional[str]] = mapped_column(
        String(150),
        nullable=True,
        comment="Horario hábil de atención y recepción",
    )

    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(
        TIMESTAMPTZ,
        nullable=False,
        server_default=text("now()"),
        comment="Fecha de creación",
    )

    updated_at: Mapped[datetime] = mapped_column(
        TIMESTAMPTZ,
        nullable=False,
        server_default=text("now()"),
        comment="Fecha de última actualización",
    )

    deleted_at: Mapped[Optional[datetime]] = mapped_column(
        TIMESTAMPTZ,
        nullable=True,
        comment="Fecha de eliminación lógica",
    )

    created_by: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        nullable=True,
        comment="Usuario creador",
    )

    updated_by: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        nullable=True,
        comment="Usuario modificador",
    )
"""create mae_locales_cliente

Revision ID: mae_0009
Revises: mae_0008
Create Date: 2026-09-09
"""

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 = "mae_0009"
down_revision: Union[str, Sequence[str], None] = "mae_0008"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:

    op.create_table(
        "mae_locales_cliente",

        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 UUID de la empresa en core.identidad (RLS)",
        ),

        sa.Column(
            "cliente_id",
            postgresql.UUID(as_uuid=True),
            nullable=False,
            comment="Cliente comercial propietario del local",
        ),

        sa.Column(
            "codigo_local",
            sa.String(length=30),
            nullable=False,
            comment="Código único de sucursal dentro del cliente",
        ),

        sa.Column(
            "nombre_local",
            sa.String(length=150),
            nullable=False,
            comment="Nombre comercial de la sucursal o punto de venta",
        ),

        sa.Column(
            "tipo_domicilio_id",
            postgresql.UUID(as_uuid=True),
            nullable=False,
            comment="Tipo de domicilio o local (FK cat_tipos_domicilio)",
        ),

        sa.Column(
            "is_local_matriz",
            sa.Boolean(),
            nullable=False,
            server_default=sa.text("false"),
            comment="Indica si es la sede principal o casa matriz",
        ),

        sa.Column(
            "direccion_texto",
            sa.Text(),
            nullable=False,
            comment="Dirección física completa",
        ),

        sa.Column(
            "referencia_ubicacion",
            sa.String(length=255),
            nullable=True,
            comment="Puntos de referencia de llegada",
        ),

        sa.Column(
            "ciudad_id",
            postgresql.UUID(as_uuid=True),
            nullable=True,
            comment="Correlación con core.identidad.mae_ciudades (sin FK cross-DB)",
        ),

        sa.Column(
            "latitud",
            sa.Float(precision=53),
            nullable=False,
            comment="Coordenada GPS Latitud",
        ),

        sa.Column(
            "longitud",
            sa.Float(precision=53),
            nullable=False,
            comment="Coordenada GPS Longitud",
        ),

        sa.Column(
            "radio_geocerca_metros",
            sa.Integer(),
            nullable=False,
            server_default=sa.text("100"),
            comment="Radio de tolerancia en metros para check-in móvil",
        ),

        sa.Column(
            "telefono_local",
            sa.String(length=50),
            nullable=True,
            comment="Teléfono de contacto de la sucursal",
        ),

        sa.Column(
            "horario_atencion",
            sa.String(length=150),
            nullable=True,
            comment="Horario hábil de atención y recepció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_mae_locales_cliente",
        ),

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

        sa.UniqueConstraint(
            "empresa_id",
            "cliente_id",
            "codigo_local",
            name="uq_mae_locales_cliente_empresa_codigo",
        ),

        sa.ForeignKeyConstraint(
            ["empresa_id", "cliente_id"],
            ["clientes.mae_clientes.empresa_id", "clientes.mae_clientes.id"],
            ondelete="CASCADE",
            name="fk_mae_locales_cliente_mae_clientes",
        ),

        comment="Locales y Puntos de Entrega del Cliente",
        schema="clientes",
    )

    op.create_index(
        "ix_mae_locales_cliente_empresa_activo",
        "mae_locales_cliente",
        ["empresa_id", "is_activo"],
        unique=False,
        schema="clientes",
    )

    op.create_index(
        "ix_mae_locales_cliente_empresa_cliente",
        "mae_locales_cliente",
        ["empresa_id", "cliente_id"],
        unique=False,
        schema="clientes",
    )

    op.create_index(
        "ix_mae_locales_cliente_empresa_gps",
        "mae_locales_cliente",
        ["empresa_id", "latitud", "longitud"],
        unique=False,
        schema="clientes",
    )

    op.create_index(
        "ix_mae_locales_cliente_empresa_ciudad",
        "mae_locales_cliente",
        ["empresa_id", "ciudad_id"],
        unique=False,
        schema="clientes",
    )

    op.execute(
        """
        ALTER TABLE clientes.mae_locales_cliente
        ENABLE ROW LEVEL SECURITY;
        """
    )

    op.execute(
        """
        CREATE POLICY rls_mae_locales_cliente_empresa
        ON clientes.mae_locales_cliente
        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_mae_locales_cliente_empresa
        ON clientes.mae_locales_cliente;
        """
    )

    op.execute(
        """
        ALTER TABLE clientes.mae_locales_cliente
        DISABLE ROW LEVEL SECURITY;
        """
    )

    op.drop_index(
        "ix_mae_locales_cliente_empresa_ciudad",
        table_name="mae_locales_cliente",
        schema="clientes",
    )

    op.drop_index(
        "ix_mae_locales_cliente_empresa_gps",
        table_name="mae_locales_cliente",
        schema="clientes",
    )

    op.drop_index(
        "ix_mae_locales_cliente_empresa_cliente",
        table_name="mae_locales_cliente",
        schema="clientes",
    )

    op.drop_index(
        "ix_mae_locales_cliente_empresa_activo",
        table_name="mae_locales_cliente",
        schema="clientes",
    )

    op.drop_table(
        "mae_locales_cliente",
        schema="clientes",
    )