feat(cerebro): Parte 1 — cimiento multi-tenant (cliente → N estaciones)

Roadmap §6, Parte 1/6. Aditivo y no destructivo (mismo patrón que `origen`):
- schema: tablas cliente, cliente_telefono (UNIQUE numero) + station.cliente_id (FK, nullable)
- registry: Cliente/Telefono, Station.cliente_id, reg.clientes()/stations(cliente_id=),
  normaliza_telefono() + 3 validaciones (cliente existe, formato MX, teléfono ≤1 cliente)
- seed: ensure_clientes + cliente_id en ensure_stations; clientes antes que stations
- mis 3 estaciones → cliente "demo"

Aislamiento por JOIN a station (tablas calientes intactas). app/main.py sin cambios.

Verificado en caliente (PG16): schema idempotente x2; station 3/3 → demo;
cliente_telefono con números demo; /panel /live /resumen diff IDÉNTICO (A/B con vs
sin el delta); seed idempotente; motor multi-tenant (cliente B in-memory → seed lo
persiste); validaciones atrapan los 3 errores.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jorem JuárezandClaude Opus 4.8 committed 2026-06-10 17:36:59 -06:00
1 parent 0f2f9350f7
commit 4d9c9e4c85
4 files changed
+179 -10

No files matched your search

+90 -4
View File
@@ -11,6 +11,7 @@ No tiene lógica de negocio (nada de generar ventas ni resúmenes). Solo registr
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
import re
import yaml
CONFIG_PATH = Path(__file__).resolve().parent.parent / "config" / "stations.yaml"
@@ -38,9 +39,35 @@ class Turno:
despachador_default: str
# --- multi-tenant: cliente (dueño) -> N estaciones (Roadmap §6) ---
# Teléfono MX en E.164: 52 + 10 dígitos, con o sin el '1' de móvil tras el 52.
_PHONE_RE = re.compile(r"^52(1)?\d{10}$")
def normaliza_telefono(raw: str) -> str:
"""Deja SOLO dígitos (quita '+', espacios, guiones). No valida aquí: el formato
se valida en _validate sobre el resultado. Pública porque la plomería del
cerebro (Parte 5) normaliza el número entrante igual antes de mapearlo a cliente."""
return re.sub(r"\D", "", raw or "")
@dataclass(frozen=True)
class Telefono:
numero: str # E.164 MX normalizado (solo dígitos)
rol: str # 'dueño' | 'gerente' | ...
@dataclass(frozen=True)
class Cliente:
id: str # 'demo' (estable, clave en DB)
nombre: str
telefonos: tuple = () # (Telefono, ...)
@dataclass(frozen=True)
class Station:
id: str
cliente_id: str # dueño (FK -> cliente); del campo `cliente` del YAML
nombre: str
zona: str
perfil_horario: str
@@ -86,10 +113,16 @@ class Registry:
capacidad_tanque: dict
simulacion: Simulacion = None
_stations: list = field(default_factory=list)
_clientes: list = field(default_factory=list)
# --- API de iteración: el resto del backend usa SOLO esto ---
def stations(self, solo_activas: bool = True) -> list[Station]:
return [s for s in self._stations if s.activa or not solo_activas]
def stations(self, solo_activas: bool = True, cliente_id: str | None = None) -> list[Station]:
"""Estaciones del registro. `cliente_id` (multi-tenant) las acota a un dueño;
sin él, devuelve todas (la vista-dios del operador / el motor generativo)."""
out = [s for s in self._stations if s.activa or not solo_activas]
if cliente_id is not None:
out = [s for s in out if s.cliente_id == cliente_id]
return out
def station(self, sid: str) -> Station:
for s in self._stations:
@@ -97,6 +130,16 @@ class Registry:
return s
raise KeyError(f"Estación no encontrada en el registro: {sid!r}")
# --- clientes (multi-tenant): registro de dueños ---
def clientes(self) -> list[Cliente]:
return list(self._clientes)
def cliente(self, cid: str) -> Cliente:
for c in self._clientes:
if c.id == cid:
return c
raise KeyError(f"Cliente no encontrado en el registro: {cid!r}")
def fuel(self, nombre: str) -> Fuel:
return self.combustibles[nombre]
@@ -163,6 +206,26 @@ def _validate(reg: Registry) -> None:
if not (0 <= s.bomba_fuera_servicio <= s.bombas):
errores.append(f"{s.id}: bomba_fuera_servicio fuera de rango.")
# --- multi-tenant: clientes, teléfonos y pertenencia estación -> cliente ---
cliente_ids = [c.id for c in reg._clientes]
if len(cliente_ids) != len(set(cliente_ids)):
errores.append("Hay ids de cliente duplicados.")
visto_tel: dict = {} # numero -> cliente_id (teléfono pertenece a <=1 cliente)
for c in reg._clientes:
if not c.nombre:
errores.append(f"cliente {c.id!r}: nombre vacío.")
for t in c.telefonos:
if not _PHONE_RE.match(t.numero):
errores.append(f"cliente {c.id!r}: teléfono {t.numero!r} no es formato MX (52 + 10 dígitos).")
if t.numero in visto_tel and visto_tel[t.numero] != c.id:
errores.append(f"teléfono {t.numero!r} pertenece a dos clientes "
f"({visto_tel[t.numero]} y {c.id}).")
visto_tel[t.numero] = c.id
cliente_ids_set = set(cliente_ids)
for s in reg._stations:
if s.cliente_id not in cliente_ids_set:
errores.append(f"{s.id}: cliente {s.cliente_id!r} no existe en `clientes`.")
_validate_simulacion(reg, errores)
if errores:
@@ -257,9 +320,25 @@ def load_registry(path: Path | str = CONFIG_PATH) -> Registry:
combustibles = {n: Fuel(nombre=n, **v) for n, v in raw["combustibles"].items()}
turnos = [Turno(**t) for t in raw["turnos"]]
stations = [Station(**s) for s in raw["stations"]]
simulacion = Simulacion(**raw["simulacion"]) if "simulacion" in raw else None
# clientes (multi-tenant). Cada teléfono se normaliza a dígitos en carga.
clientes = []
for cid, cv in (raw.get("clientes") or {}).items():
tels = tuple(
Telefono(numero=normaliza_telefono(t["numero"]), rol=t.get("rol", ""))
for t in (cv.get("telefonos") or [])
)
clientes.append(Cliente(id=cid, nombre=cv["nombre"], telefonos=tels))
# El YAML trae `cliente` (id del dueño) en cada estación; lo mapeamos a
# Station.cliente_id, consistente con la columna/FK de la DB.
stations = []
for s in raw["stations"]:
s = dict(s)
s["cliente_id"] = s.pop("cliente", None)
stations.append(Station(**s))
reg = Registry(
meta=raw["meta"],
combustibles=combustibles,
@@ -271,6 +350,7 @@ def load_registry(path: Path | str = CONFIG_PATH) -> Registry:
capacidad_tanque=raw["capacidad_tanque"],
simulacion=simulacion,
_stations=stations,
_clientes=clientes,
)
_validate(reg)
return reg
@@ -282,9 +362,15 @@ if __name__ == "__main__":
print(f"Combustibles (venta / costo derivado / margen):")
for n, f in reg.combustibles.items():
print(f" {n:8} ${f.precio_venta_base:>7.3f} ${f.costo_compra_base:>7.3f} ${f.margen_litro:.2f}/L")
print(f"\nClientes (dueños): {len(reg.clientes())}")
for c in reg.clientes():
tels = ", ".join(f"{t.numero} ({t.rol})" for t in c.telefonos)
ests = ", ".join(s.id for s in reg.stations(cliente_id=c.id))
print(f" [{c.id}] {c.nombre} — tel: {tels} — estaciones: {ests}")
print(f"\nEstaciones activas: {len(reg.stations())}")
for s in reg.stations():
print(f" [{s.id}] {s.nombre} — {s.zona} · {s.bombas} bombas · perfil {s.perfil_horario}")
print(f" [{s.id}] {s.nombre} (cliente: {s.cliente_id}) — {s.zona} · {s.bombas} bombas · perfil {s.perfil_horario}")
sim = reg.simulacion
print(f"\nSimulación (knobs del motor):")
+24
View File
@@ -21,6 +21,26 @@ meta:
moneda: "MXN"
version_registro: 1
# ============================================================================
# REGISTRO CENTRAL DE CLIENTES (dueños) — multi-tenant (Roadmap §6)
# ----------------------------------------------------------------------------
# Jerarquía: cliente (dueño) -> N estaciones. Cada estación declara su dueño con
# el campo `cliente:` (abajo, en `stations`). El cerebro identifica al cliente por
# su TELÉFONO (cliente_telefono); por eso un teléfono pertenece a UN solo cliente.
#
# >>> Agregar un cliente = una entrada aquí. Asignar estación = un campo. <<<
#
# Teléfonos en formato MX (E.164: 52 + 10 dígitos, con o sin el '1' de móvil tras
# el 52). Los de abajo son PLACEHOLDERS de demo; el número real del dueño entra en
# la Parte 5 (plomería Quetzalcóatl).
# ============================================================================
clientes:
demo:
nombre: "Demo (Collina)"
telefonos:
- { numero: "5212221112233", rol: "dueño" } # 521 + 10 (forma móvil legacy)
- { numero: "522223334455", rol: "gerente" } # 52 + 10 (E.164 moderno)
# Catálogo de combustibles. El costo de compra se deriva: venta - margen.
# (El precio de venta diario lo fija el motor con variación ±1.2%; aquí va el base.)
combustibles:
@@ -172,6 +192,7 @@ simulacion:
# ----------------------------------------------------------------------------
stations:
- id: "cholula" # identificador estable (no cambia nunca; clave en DB)
cliente: "demo" # dueño (FK -> clientes); ver REGISTRO CENTRAL DE CLIENTES
nombre: "Cholula"
zona: "San Andrés Cholula, Puebla"
perfil_horario: "universitario"
@@ -183,6 +204,7 @@ stations:
activa: true
- id: "atlixcayotl"
cliente: "demo"
nombre: "Atlixcáyotl"
zona: "Vía Atlixcáyotl / Angelópolis, Puebla"
perfil_horario: "corporativo"
@@ -194,6 +216,7 @@ stations:
activa: true
- id: "zavaleta"
cliente: "demo"
nombre: "Zavaleta"
zona: "Av. Zavaleta, Puebla"
perfil_horario: "comercial"
@@ -206,6 +229,7 @@ stations:
# --- Plantilla para crecer (descomenta y ajusta para la estación piloto #N) ---
# - id: "nueva_estacion"
# cliente: "demo" # dueño (debe existir en `clientes` arriba)
# nombre: "Nombre Comercial"
# zona: "Dirección / colonia"
# perfil_horario: "comercial" # corporativo | universitario | comercial
+30
View File
@@ -38,6 +38,36 @@ CREATE TABLE IF NOT EXISTS station (
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- ------------------------------------------------------- multi-tenant (clientes)
-- Jerarquía: cliente (dueño) -> N estaciones. ADITIVO: el resto del esquema no
-- cambia. station.cliente_id es la FK que une cada estación a su dueño; las tablas
-- CALIENTES (sale/tank_reading/shift_cut) NO se tocan -> el aislamiento por cliente
-- se hace por JOIN a station: WHERE station_id IN (SELECT id FROM station WHERE
-- cliente_id=%s). Igual que la columna `origen`: todo IF NOT EXISTS, para servir lo
-- mismo a una DB fresca y a una ya existente.
CREATE TABLE IF NOT EXISTS cliente (
id TEXT PRIMARY KEY, -- 'demo' (estable, del registro YAML)
nombre TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Varios teléfonos por cliente (dueño + gerentes). El número es la llave por la que
-- el cerebro identifica al cliente; UNIQUE(numero) garantiza A NIVEL DB que un
-- teléfono pertenece a <=1 cliente (el registro además lo valida en carga).
CREATE TABLE IF NOT EXISTS cliente_telefono (
id BIGSERIAL PRIMARY KEY,
cliente_id TEXT NOT NULL REFERENCES cliente(id) ON DELETE CASCADE,
numero TEXT NOT NULL UNIQUE, -- E.164 MX normalizado (solo dígitos)
rol TEXT, -- 'dueño' | 'gerente' | ...
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_cliente_telefono_cliente ON cliente_telefono (cliente_id);
-- Une cada estación a su cliente. NULLABLE (aditivo: filas viejas quedan NULL y el
-- seed las puebla desde el registro). El FK solo valida los valores no nulos.
ALTER TABLE station ADD COLUMN IF NOT EXISTS cliente_id TEXT REFERENCES cliente(id);
CREATE INDEX IF NOT EXISTS ix_station_cliente ON station (cliente_id);
-- precio de venta del día por combustible y estación (fijo dentro del día)
CREATE TABLE IF NOT EXISTS daily_price (
station_id TEXT NOT NULL REFERENCES station(id) ON DELETE CASCADE,
+35 -6
View File
@@ -52,10 +52,36 @@ def ensure_fuel(conn: psycopg.Connection, reg) -> None:
)
def ensure_clientes(conn: psycopg.Connection, reg) -> None:
"""Upsert de clientes (dueños) + sus teléfonos desde el registro. DEBE correr
ANTES de ensure_stations: station.cliente_id es FK -> cliente. Idempotente
(UPSERT). UNIQUE(numero): ON CONFLICT reasigna rol/cliente si cambió en el YAML.
Como ensure_stations, refleja el registro vigente pero NO borra lo que ya no
esté en el YAML (no destructivo)."""
for c in reg.clientes():
conn.execute(
"""
INSERT INTO cliente (id, nombre) VALUES (%s, %s)
ON CONFLICT (id) DO UPDATE SET nombre = EXCLUDED.nombre
""",
(c.id, c.nombre),
)
for tel in c.telefonos:
conn.execute(
"""
INSERT INTO cliente_telefono (cliente_id, numero, rol) VALUES (%s, %s, %s)
ON CONFLICT (numero) DO UPDATE
SET cliente_id = EXCLUDED.cliente_id, rol = EXCLUDED.rol
""",
(c.id, tel.numero, tel.rol),
)
def ensure_stations(conn: psycopg.Connection, reg) -> None:
"""Upsert de TODAS las estaciones del registro (activas o no) para que la FK
exista. La mezcla de combustible y otros atributos flexibles van en config
(JSONB), de modo que el esquema no cambie si la config crece."""
(JSONB), de modo que el esquema no cambie si la config crece. cliente_id (FK ->
cliente) viene del registro: por eso ensure_clientes corre antes."""
for s in reg.stations(solo_activas=False):
config = {
"mezcla_combustible": s.mezcla_combustible,
@@ -63,11 +89,12 @@ def ensure_stations(conn: psycopg.Connection, reg) -> None:
}
conn.execute(
"""
INSERT INTO station (id, nombre, zona, perfil_horario, perfil_semana,
INSERT INTO station (id, cliente_id, nombre, zona, perfil_horario, perfil_semana,
bombas, ventas_dia_aprox, bomba_fuera_serv, activa, config)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (id) DO UPDATE
SET nombre = EXCLUDED.nombre,
SET cliente_id = EXCLUDED.cliente_id,
nombre = EXCLUDED.nombre,
zona = EXCLUDED.zona,
perfil_horario = EXCLUDED.perfil_horario,
perfil_semana = EXCLUDED.perfil_semana,
@@ -77,7 +104,7 @@ def ensure_stations(conn: psycopg.Connection, reg) -> None:
activa = EXCLUDED.activa,
config = EXCLUDED.config
""",
(s.id, s.nombre, s.zona, s.perfil_horario, s.perfil_semana,
(s.id, s.cliente_id, s.nombre, s.zona, s.perfil_horario, s.perfil_semana,
s.bombas, s.ventas_dia_aprox, s.bomba_fuera_servicio, s.activa,
Jsonb(config)),
)
@@ -119,8 +146,10 @@ def ensure_daily_price(conn: psycopg.Connection, reg, fecha: dt.date) -> None:
def seed_all(conn: psycopg.Connection, reg, fecha: dt.date) -> None:
"""Siembra catálogos + estaciones + precio del día en una transacción."""
"""Siembra catálogos + clientes + estaciones + precio del día en una transacción.
Orden: clientes ANTES que estaciones (la FK station.cliente_id lo requiere)."""
ensure_fuel(conn, reg)
ensure_clientes(conn, reg)
ensure_stations(conn, reg)
ensure_daily_price(conn, reg, fecha)
conn.commit()