chore: inicializa cash-monitor como repositorio propio
Saca el proyecto del repo git que colgaba de HOME, que NO lo trackeaba (verificado: git ls-files bajo la carpeta = 0 archivos; el repo de HOME no tenia ningun commit). Por eso no hubo que sacar nada del indice del padre ni commitear alli; solo se movio la carpeta (cash monitor -> cash-monitor, sin espacio) y se inicio repo nuevo en rama main, alineado con wk-contratos. Contenido: registro central (config/) + esquema PostgreSQL (db/), motor generativo del Roadmap §1 (engine/: db, seed, generators, runner) y API FastAPI con boton arranque/paro + feed (app/), bloque simulacion calibrado en stations.yaml, y CLAUDE.md con las reglas de trabajo. Verificacion: registry valida OK (carga + validacion del bloque simulacion); generadores unit-probados via dry-run (volumen del dia cuadra con ventas_dia_aprox, merma termica vs real, sesgos de fuga); capa HTTP smoke-test con TestClient (degrada con elegancia sin DB); SQL revisado a mano contra schema.sql. PENDIENTE: corrida end-to-end real contra PostgreSQL (seed -> catch-up -> vivo -> feed). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
commit
f88fb1c6cb
19 files changed
+2267
No files matched your search
@@ -0,0 +1,11 @@
|
||||
# Copia a .env y completa. NO subas .env a Gitea.
|
||||
DATABASE_URL=postgresql://collina:CHANGE_ME@localhost:5432/collina
|
||||
TZ=America/Mexico_City
|
||||
|
||||
# Evolution API (WhatsApp) — para fases posteriores
|
||||
EVOLUTION_API_URL=
|
||||
EVOLUTION_API_KEY=
|
||||
|
||||
# Google Sheets espejo (para fases posteriores; si el VPS empuja al Sheets)
|
||||
GOOGLE_SERVICE_ACCOUNT_JSON=
|
||||
SHEETS_SPREADSHEET_ID=
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.env
|
||||
.venv/
|
||||
venv/
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.db
|
||||
.DS_Store
|
||||
.idea/
|
||||
.vscode/
|
||||
@@ -0,0 +1,50 @@
|
||||
# CLAUDE.md — Collina Cash Monitor
|
||||
|
||||
Guía de onboarding para cualquier sesión de IA sobre este proyecto. Léela completa antes de proponer o escribir nada.
|
||||
|
||||
## REGLAS DE TRABAJO (no negociables)
|
||||
1. **Pregunta antes de construir.** No generes ni cambies código hasta que el alcance esté autorizado. Ante ambigüedad, pregunta; no asumas.
|
||||
2. **Investiga, no inventes.** Cualquier dato del mundo real (precios, márgenes, KPIs, comportamiento de gasolineras MX, turnos) se verifica con fuentes, no se inventa. Marca el nivel de respaldo de cada supuesto.
|
||||
3. **Modularidad por estación.** La unidad modular es la estación, declarada en `config/stations.yaml`. Todo el código ITERA sobre el registro; nunca hardcodea estaciones. Prueba de fuego: agregar una estación = una entrada en el YAML, sin tocar código ni esquema.
|
||||
4. **La lógica de negocio vive en el backend** (Python/FastAPI + PostgreSQL), NO en la demo de Sheets (`demo-sheets/` es desechable).
|
||||
5. **Stack fijo:** Python 3.11 / FastAPI + PostgreSQL, despliegue en VPS con Coolify, versionado en Gitea autohospedado, WhatsApp vía Evolution API.
|
||||
|
||||
## FLUJO DE DATOS (regla de oro)
|
||||
Los datos nacen en la operación → llegan a la DB de Collina (este backend) → opcionalmente se reflejan (espejo) en Google Sheets. La fuente de verdad es la DB de Collina, nunca el Sheets. El Sheets es solo superficie de demo.
|
||||
|
||||
## MEMORIA POR CAPAS (cerebro IA)
|
||||
- Caliente (detallado): mes en curso, transacción por transacción (sale, tank_reading, shift_cut).
|
||||
- Frío (comprimido): meses cerrados → monthly_summary (JSONB). El día 1 de cada mes se calcula el resumen y se libera el crudo.
|
||||
- El cerebro enruta: consulta de hoy → datos calientes; mes pasado → resumen frío + link al dashboard.
|
||||
Resumen mensual = 4 bloques, por estación + consolidado: (1) tendencia/comparación, (2) margen/rentabilidad, (3) mermas/faltantes, (4) cumplimiento por turno/despachador.
|
||||
|
||||
## DATOS REALES YA CALIBRADOS (no re-inventar)
|
||||
- Precios venta Puebla (PETROIntelligence jun-2026): Magna $23.742 · Premium $28.102 · Diésel $27.202 MXN/L.
|
||||
- Márgenes/litro (Onexpo/Profeco MX): Magna ~$1.10 · Premium ~$1.30 · Diésel ~$1.65. Costo = venta − margen.
|
||||
- Turnos (común MX): 3 de 8 h — 06–14 / 14–22 / 22–06.
|
||||
- Mezcla de pago (gasolinera de barrio MX): ~78% efectivo, 16% tarjeta, 6% transferencia.
|
||||
- Estaciones piloto (Puebla): Cholula (universitaria/turística), Atlixcáyotl (corporativa/commute), Zavaleta (comercial, bomba #4 intermitente).
|
||||
- Demo del motor: ráfaga de arranque (1 venta cada 15 s en bombas distintas, ~5 min) y luego 1–5 ventas/minuto.
|
||||
|
||||
## ESTRUCTURA Y ESTADO
|
||||
- config/ → stations.yaml (registro central) + registry.py (carga + validación)
|
||||
- db/ → schema.sql (PostgreSQL: caliente + frío; estación como FK)
|
||||
- engine/ → motor generativo (db, seed, generators, runner) [pendiente validar en caliente]
|
||||
- app/ → FastAPI (/engine/start|stop|status, /live, botón + feed)
|
||||
- demo-sheets/ → CollinaSimV2.gs (simulación de demo, DESECHABLE)
|
||||
|
||||
Pendiente crítico: corrida real contra PostgreSQL (seed → catch-up → vivo → feed). SQL revisado a mano y generadores unit-probados, pero el camino DB end-to-end no se ha ejecutado en caliente. Mayor riesgo: el `ON CONFLICT` de los upserts (columnas vs UNIQUE/PK reales) y los `FILTER`/agregados de la vista.
|
||||
|
||||
## ROADMAP
|
||||
1. ✅ Registro central + esquema DB.
|
||||
2. 🔄 Motor generativo (escribe a DB iterando el registro; botón start/stop). ⏳ Falta validar end-to-end contra Postgres.
|
||||
3. ⏳ Espejo en Sheets (decidir: Sheets lee endpoint HTTPS del VPS, o el VPS empuja con service account).
|
||||
4. ⏳ Cierre mensual (trigger día 1) → resumen por estación + consolidado.
|
||||
5. ⏳ Dashboards interactivos + link temporal.
|
||||
6. ⏳ Cerebro IA + WhatsApp (Evolution API).
|
||||
|
||||
## CULTURA (heredada de wk-contratos)
|
||||
- Commits granulares con el "porqué" y la evidencia de verificación en el cuerpo.
|
||||
- Generadores puramente funcionales: reciben datos, devuelven resultado, sin estado global ni red.
|
||||
- Diseñar el schema completo desde el inicio aunque solo se active lo necesario.
|
||||
- Distinguir SIEMPRE lo verificado en caliente de lo solo revisado a mano.
|
||||
@@ -0,0 +1,119 @@
|
||||
# Collina Systems — Backend (prototipo)
|
||||
|
||||
Plataforma de monitoreo para estaciones de servicio (gasolineras). Monitorea y
|
||||
reporta operación; **no** mueve dinero ni edita registros.
|
||||
|
||||
## Visión y flujo de datos
|
||||
Los datos **nacen en la operación → llegan a la base de datos de Collina (este
|
||||
backend) → opcionalmente se reflejan (espejo) en Google Sheets**. La fuente de
|
||||
verdad es la DB de Collina, nunca el Sheets. El Sheets es solo superficie de
|
||||
demo/visualización.
|
||||
|
||||
```
|
||||
Operación (real o simulada)
|
||||
│
|
||||
▼
|
||||
Backend Collina (FastAPI + PostgreSQL) ← fuente de verdad
|
||||
│ │
|
||||
▼ ▼
|
||||
Cerebro IA / reportes Espejo en Google Sheets (opcional, demo)
|
||||
│
|
||||
▼
|
||||
WhatsApp (Evolution API)
|
||||
```
|
||||
|
||||
## Principio rector: MODULARIDAD POR ESTACIÓN
|
||||
La unidad modular es la **estación**. Está declarada en un registro central
|
||||
(`config/stations.yaml`) y **todo el backend itera sobre ese registro**. El
|
||||
código nunca conoce estaciones por nombre.
|
||||
|
||||
> **Prueba de fuego:** agregar una estación (la #2, #5, #20) = **una entrada**
|
||||
> en `config/stations.yaml`. No se toca código ni esquema de DB.
|
||||
|
||||
En la DB, la estación es una **FK** (`station_id`) en todas las tablas de datos,
|
||||
nunca una tabla por estación. Pasar de 1 a N estaciones no cambia el esquema.
|
||||
|
||||
## Estado actual (lo construido)
|
||||
- ✅ `config/stations.yaml` — registro central (3 estaciones piloto: Cholula,
|
||||
Atlixcáyotl, Zavaleta, en Puebla) + catálogos compartidos (combustibles,
|
||||
perfiles de zona, turnos, mezcla de pago).
|
||||
- ✅ `config/registry.py` — cargador + **validación** del registro (combustibles,
|
||||
perfiles de 24 h, mezclas que sumen 1, ids únicos). Deriva costo = venta − margen.
|
||||
- ✅ `db/schema.sql` — esquema PostgreSQL. Datos calientes (sale, tank_reading,
|
||||
shift_cut) para el mes en curso; datos fríos (monthly_summary, JSONB) para
|
||||
meses cerrados. Vista `v_live_today` = concentrado en vivo.
|
||||
- ✅ **Motor generativo** (`engine/` + `app/`) — Roadmap §1. Escribe operación
|
||||
realista a la DB iterando sobre el registro, con botón arranque/paro. Los knobs
|
||||
(fugas, ritmo, temperatura) viven en el bloque `simulacion:` de
|
||||
`config/stations.yaml` y se validan en `config/registry.py`. Nada se hardcodea:
|
||||
cada parámetro trae su nivel de respaldo ([SÓLIDO]/[DÉBIL]/[DEMO]).
|
||||
|
||||
## Roadmap (lo que sigue, en orden acordado)
|
||||
1. **Motor generativo** (Python): genera operación realista y la escribe a la DB,
|
||||
iterando sobre el registro. Arranca/para con un botón. Es la "materia prima".
|
||||
- Datos reales ya calibrados: precios Puebla (PETROIntelligence jun-2026),
|
||||
márgenes MX (Magna ~$1.10/L, Premium ~$1.30/L, Diésel ~$1.65/L).
|
||||
- Comportamiento de demo: ráfaga de arranque (1 venta cada 15 s, bombas
|
||||
distintas) los primeros ~5 min; luego 1–5 ventas/minuto.
|
||||
3. **Espejo en Sheets** (pendiente decidir: Sheets lee endpoint HTTPS del VPS, o
|
||||
el VPS empuja al Sheets con service account).
|
||||
4. **Cierre mensual** (día 1 de cada mes): calcula resumen por estación +
|
||||
consolidado, lo guarda en `monthly_summary`, libera el crudo del mes.
|
||||
- Resumen = 4 bloques: (1) tendencia/comparación, (2) margen/rentabilidad,
|
||||
(3) mermas/faltantes, (4) cumplimiento por turno/despachador.
|
||||
5. **Dashboards** interactivos por resumen + link temporal.
|
||||
6. **Cerebro IA + WhatsApp** (Evolution API): enruta consultas (operación viva
|
||||
vs. histórico comprimido), responde en lenguaje natural y entrega links.
|
||||
|
||||
## Stack
|
||||
- Python 3.11+ / FastAPI
|
||||
- PostgreSQL (en producción vía Coolify)
|
||||
- Despliegue: VPS + Coolify; versionado en Gitea
|
||||
- Mensajería: Evolution API (WhatsApp)
|
||||
|
||||
## Correr el registro (sanity check)
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
python config/registry.py # imprime estaciones y costos derivados
|
||||
```
|
||||
|
||||
## Aplicar el esquema (cuando haya Postgres)
|
||||
```bash
|
||||
psql "$DATABASE_URL" -f db/schema.sql
|
||||
```
|
||||
|
||||
## Correr el motor generativo (§1)
|
||||
```bash
|
||||
python -m venv .venv && source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
|
||||
cp .env.example .env # y pon tu DATABASE_URL
|
||||
psql "$DATABASE_URL" -f db/schema.sql
|
||||
|
||||
uvicorn app.main:app --reload # abre http://127.0.0.1:8000
|
||||
```
|
||||
- **`/`** — página con botón **Arrancar/Detener** y feed en vivo (lo más reciente arriba).
|
||||
- **`POST /engine/start`** — siembra catálogos + precio del día, **reconstruye la
|
||||
operación de HOY** (00:00→ahora, volumen realista que cuadra con `ventas_dia_aprox`)
|
||||
de forma **incremental e idempotente**, y luego genera **en vivo** (ráfaga de
|
||||
1 venta/15 s en bombas distintas los ~5 min, luego 1–5 ventas/min).
|
||||
- **`POST /engine/stop`** · **`GET /engine/status`** · **`GET /live`** (lee `v_live_today`).
|
||||
|
||||
El estado vive en la DB (fuente de verdad), no en la memoria del proceso: parar y
|
||||
volver a arrancar reaprovecha lo ya escrito y solo extiende el alcance.
|
||||
|
||||
**Fugas inyectadas** (las lucrativas de detectar, todas knobs en `simulacion:`):
|
||||
drive-off (`sale.drive_off`), merma "no explicada" sesgada al turno nocturno
|
||||
(separable de la merma térmica vía `tank_reading.vol_bruto/neto`), y faltante de
|
||||
caja sesgado a un despachador (`shift_cut.diferencia`). Magnitudes [DÉBIL]:
|
||||
defaults editables, calibrar contra datos reales después.
|
||||
|
||||
> Sin tocar código ni esquema: agregar la estación #N = una entrada en
|
||||
> `config/stations.yaml`; el motor la siembra y le genera operación sola.
|
||||
|
||||
## Notas para Claude Code
|
||||
- Respeta el principio de modularidad: cualquier función nueva debe **iterar
|
||||
sobre el registro**, no hardcodear estaciones.
|
||||
- La lógica de negocio vive aquí (backend), **no** en el Apps Script de la demo.
|
||||
- El prototipo del motor y del resumen mensual ya se validaron en Python; al
|
||||
portarlos, mantener los datos reales ya calibrados (ver Roadmap §1 y §4).
|
||||
@@ -0,0 +1 @@
|
||||
"""API FastAPI del backend Collina. Por ahora expone el botón del motor (§1)."""
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
"""API del backend Collina — el "botón" del motor generativo (Roadmap §1).
|
||||
|
||||
Endpoints:
|
||||
POST /engine/start arranca (siembra + catch-up del día + loop en vivo)
|
||||
POST /engine/stop detiene el loop
|
||||
GET /engine/status estado + contadores por estación
|
||||
GET /live concentrado del día (v_live_today) + feed de ventas recientes
|
||||
GET / página con botones Start/Stop y feed en vivo (lo más nuevo arriba)
|
||||
|
||||
La lógica vive en engine/; aquí solo se expone. El feed lee la DB (fuente de
|
||||
verdad), no la memoria del proceso.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
|
||||
from engine import db
|
||||
from engine.runner import runner
|
||||
|
||||
app = FastAPI(title="Collina — Motor generativo", version="0.1")
|
||||
|
||||
|
||||
@app.post("/engine/start")
|
||||
async def engine_start():
|
||||
return await runner.start()
|
||||
|
||||
|
||||
@app.post("/engine/stop")
|
||||
async def engine_stop():
|
||||
return await runner.stop()
|
||||
|
||||
|
||||
@app.get("/engine/status")
|
||||
async def engine_status():
|
||||
return runner.status()
|
||||
|
||||
|
||||
@app.get("/live")
|
||||
async def live():
|
||||
"""Concentrado de hoy por estación + últimas ventas (más reciente arriba)."""
|
||||
try:
|
||||
with db.connect() as conn:
|
||||
concentrado = conn.execute(
|
||||
"SELECT station_id, nombre, cargas, litros, ingreso, ganancia, efectivo "
|
||||
"FROM v_live_today ORDER BY ingreso DESC NULLS LAST"
|
||||
).fetchall()
|
||||
feed = conn.execute(
|
||||
"""
|
||||
SELECT s.ts, s.station_id, st.nombre, s.bomba, s.fuel_name,
|
||||
s.litros, s.monto, s.ganancia, s.metodo_pago, s.turno,
|
||||
s.despachador, s.drive_off
|
||||
FROM sale s JOIN station st ON st.id = s.station_id
|
||||
ORDER BY s.ts DESC
|
||||
LIMIT 60
|
||||
"""
|
||||
).fetchall()
|
||||
return {
|
||||
"concentrado": [_jsonable(r) for r in concentrado],
|
||||
"feed": [_jsonable(r) for r in feed],
|
||||
}
|
||||
except db.DatabaseNotConfigured as e:
|
||||
return JSONResponse(status_code=503, content={"error": str(e)})
|
||||
except Exception as e:
|
||||
return JSONResponse(status_code=503, content={"error": f"{type(e).__name__}: {e}"})
|
||||
|
||||
|
||||
def _jsonable(row: dict) -> dict:
|
||||
out = {}
|
||||
for k, v in row.items():
|
||||
if hasattr(v, "isoformat"):
|
||||
out[k] = v.isoformat(timespec="seconds")
|
||||
elif hasattr(v, "__float__") and not isinstance(v, (int, float, bool)):
|
||||
out[k] = float(v) # Decimal -> float
|
||||
else:
|
||||
out[k] = v
|
||||
return out
|
||||
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def home():
|
||||
return _HTML
|
||||
|
||||
|
||||
_HTML = """<!doctype html>
|
||||
<html lang="es"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Collina — Motor generativo</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; }
|
||||
body { font-family: system-ui, sans-serif; margin: 0; padding: 24px; max-width: 1000px; margin: auto; }
|
||||
h1 { font-size: 20px; } .sub { color: #888; font-size: 13px; margin-top: -8px; }
|
||||
button { font-size: 15px; padding: 10px 20px; border-radius: 8px; border: 1px solid #8884; cursor: pointer; }
|
||||
#start { background:#16a34a; color:#fff; } #stop { background:#dc2626; color:#fff; }
|
||||
button[disabled] { opacity:.45; cursor:not-allowed; }
|
||||
.bar { display:flex; gap:10px; align-items:center; margin:16px 0; flex-wrap:wrap; }
|
||||
.pill { padding:4px 10px; border-radius:999px; font-size:12px; border:1px solid #8884; }
|
||||
table { width:100%; border-collapse:collapse; font-size:13px; }
|
||||
th,td { text-align:left; padding:6px 8px; border-bottom:1px solid #8882; }
|
||||
th { color:#888; font-weight:600; }
|
||||
td.num { text-align:right; font-variant-numeric: tabular-nums; }
|
||||
.grid { display:grid; grid-template-columns:1fr 1fr; gap:24px; margin-top:18px; }
|
||||
@media(max-width:780px){ .grid{ grid-template-columns:1fr; } }
|
||||
.doff { color:#dc2626; font-weight:600; }
|
||||
.new { animation: flash 1.2s ease-out; }
|
||||
@keyframes flash { from { background:#16a34a33; } to { background:transparent; } }
|
||||
</style></head>
|
||||
<body>
|
||||
<h1>⛽ Collina — Motor generativo</h1>
|
||||
<p class="sub">Produce operación realista y la escribe a PostgreSQL, iterando sobre el registro de estaciones.</p>
|
||||
<div class="bar">
|
||||
<button id="start">▶ Arrancar</button>
|
||||
<button id="stop">■ Detener</button>
|
||||
<span class="pill" id="estado">—</span>
|
||||
<span class="pill" id="db">DB —</span>
|
||||
<span class="pill" id="cnt">0 ventas</span>
|
||||
</div>
|
||||
<div id="msg" class="sub"></div>
|
||||
<div class="grid">
|
||||
<div>
|
||||
<h3>Concentrado de hoy</h3>
|
||||
<table><thead><tr><th>Estación</th><th class="num">Cargas</th><th class="num">Litros</th><th class="num">Ingreso</th><th class="num">Ganancia</th></tr></thead>
|
||||
<tbody id="conc"></tbody></table>
|
||||
</div>
|
||||
<div>
|
||||
<h3>Ventas en vivo <span class="sub">(lo más reciente, arriba)</span></h3>
|
||||
<table><thead><tr><th>Hora</th><th>Estación</th><th>Bba</th><th>Comb.</th><th class="num">Litros</th><th class="num">Monto</th><th>Pago</th></tr></thead>
|
||||
<tbody id="feed"></tbody></table>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
const $ = id => document.getElementById(id);
|
||||
let lastTop = null;
|
||||
async function post(p){ try { const r = await fetch(p,{method:'POST'}); const j = await r.json(); $('msg').textContent = j.mensaje || ''; refresh(); } catch(e){ $('msg').textContent = e; } }
|
||||
$('start').onclick = ()=>post('/engine/start');
|
||||
$('stop').onclick = ()=>post('/engine/stop');
|
||||
function money(n){ return n==null?'—':'$'+Number(n).toLocaleString('es-MX',{maximumFractionDigits:0}); }
|
||||
function num(n){ return n==null?'—':Number(n).toLocaleString('es-MX',{maximumFractionDigits:1}); }
|
||||
async function refresh(){
|
||||
try {
|
||||
const st = await (await fetch('/engine/status')).json();
|
||||
$('estado').textContent = st.running ? ('● '+st.fase) : '○ detenido';
|
||||
$('estado').style.color = st.running ? '#16a34a' : '#888';
|
||||
$('db').textContent = 'DB ' + (st.db_ok ? 'ok' : 'sin conexión');
|
||||
$('db').style.color = st.db_ok ? '#16a34a' : '#dc2626';
|
||||
$('cnt').textContent = (st.ventas_sesion||0) + ' ventas (sesión)';
|
||||
$('start').disabled = st.running; $('stop').disabled = !st.running;
|
||||
if (st.ultimo_error) $('msg').textContent = 'Error: ' + st.ultimo_error;
|
||||
|
||||
const lv = await (await fetch('/live')).json();
|
||||
if (lv.error){ $('msg').textContent = lv.error; return; }
|
||||
$('conc').innerHTML = (lv.concentrado||[]).map(r =>
|
||||
`<tr><td>${r.nombre}</td><td class="num">${r.cargas??0}</td><td class="num">${num(r.litros)}</td><td class="num">${money(r.ingreso)}</td><td class="num">${money(r.ganancia)}</td></tr>`).join('');
|
||||
const top = lv.feed && lv.feed[0] ? lv.feed[0].ts+lv.feed[0].station_id+lv.feed[0].monto : null;
|
||||
$('feed').innerHTML = (lv.feed||[]).map((r,i) => {
|
||||
const hora = (r.ts||'').slice(11,19);
|
||||
const doff = r.drive_off ? ' <span class="doff">⚠ drive-off</span>' : '';
|
||||
const cls = (i===0 && top!==lastTop) ? 'new' : '';
|
||||
return `<tr class="${cls}"><td>${hora}</td><td>${r.nombre}</td><td>${r.bomba}</td><td>${r.fuel_name}</td><td class="num">${num(r.litros)}</td><td class="num">${money(r.monto)}${doff}</td><td>${r.metodo_pago}</td></tr>`;
|
||||
}).join('');
|
||||
lastTop = top;
|
||||
} catch(e){ $('msg').textContent = e; }
|
||||
}
|
||||
refresh(); setInterval(refresh, 2000);
|
||||
</script>
|
||||
</body></html>"""
|
||||
Whitespace-only changes.
@@ -0,0 +1,266 @@
|
||||
"""
|
||||
Cargador del registro central de estaciones.
|
||||
|
||||
Responsabilidad única: leer config/stations.yaml, VALIDARLO y exponer objetos
|
||||
cómodos para que el resto del backend itere sobre las estaciones sin conocer
|
||||
ninguna por nombre. Si alguien agrega una estación mal formada, esto lo detecta
|
||||
de inmediato (no fallos silenciosos al escalar a N).
|
||||
|
||||
No tiene lógica de negocio (nada de generar ventas ni resúmenes). Solo registro.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
|
||||
CONFIG_PATH = Path(__file__).resolve().parent.parent / "config" / "stations.yaml"
|
||||
|
||||
|
||||
# --------------------------- estructuras de datos ---------------------------
|
||||
@dataclass(frozen=True)
|
||||
class Fuel:
|
||||
nombre: str
|
||||
precio_venta_base: float
|
||||
margen_litro: float
|
||||
|
||||
@property
|
||||
def costo_compra_base(self) -> float:
|
||||
# El costo de compra se DERIVA: venta - margen. (Lo que pediste para
|
||||
# poder reportar ganancia real, no solo ingreso.)
|
||||
return round(self.precio_venta_base - self.margen_litro, 3)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Turno:
|
||||
id: str
|
||||
inicio: int
|
||||
fin: int
|
||||
despachador_default: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Station:
|
||||
id: str
|
||||
nombre: str
|
||||
zona: str
|
||||
perfil_horario: str
|
||||
perfil_semana: str
|
||||
bombas: int
|
||||
ventas_dia_aprox: int
|
||||
mezcla_combustible: dict
|
||||
bomba_fuera_servicio: int
|
||||
activa: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Simulacion:
|
||||
"""Knobs del motor generativo (bloque `simulacion` del YAML).
|
||||
|
||||
No tiene lógica: solo transporta los parámetros ya validados. El motor los
|
||||
lee; nunca hardcodea estos números. Sub-bloques quedan como dict para no
|
||||
acoplar el cargador a cada knob (agregar un knob = una clave en el YAML).
|
||||
"""
|
||||
arranque: dict
|
||||
ritmo_vivo_min_por_min: float
|
||||
ritmo_vivo_max_por_min: float
|
||||
catchup: dict
|
||||
carga: dict
|
||||
precio_variacion_venta_pct: float
|
||||
precio_variacion_costo_pct: float
|
||||
tank_reading_intervalo_min: int
|
||||
reorden_pct: float
|
||||
recarga_objetivo_pct: float
|
||||
temperatura: dict
|
||||
fugas: dict
|
||||
|
||||
|
||||
@dataclass
|
||||
class Registry:
|
||||
meta: dict
|
||||
combustibles: dict # nombre -> Fuel
|
||||
perfiles_horarios: dict # nombre -> [24 floats]
|
||||
perfiles_semana: dict # nombre -> {Lun..Dom: float}
|
||||
turnos: list # [Turno]
|
||||
mezcla_pago: dict
|
||||
modos_venta: dict
|
||||
capacidad_tanque: dict
|
||||
simulacion: Simulacion = None
|
||||
_stations: 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 station(self, sid: str) -> Station:
|
||||
for s in self._stations:
|
||||
if s.id == sid:
|
||||
return s
|
||||
raise KeyError(f"Estación no encontrada en el registro: {sid!r}")
|
||||
|
||||
def fuel(self, nombre: str) -> Fuel:
|
||||
return self.combustibles[nombre]
|
||||
|
||||
def perfil_horario(self, station: Station) -> list[float]:
|
||||
return self.perfiles_horarios[station.perfil_horario]
|
||||
|
||||
def perfil_semana(self, station: Station) -> dict:
|
||||
return self.perfiles_semana[station.perfil_semana]
|
||||
|
||||
def turno_por_hora(self, hora: int) -> Turno:
|
||||
"""Turno que cubre una hora (0-23). Soporta el turno que cruza medianoche."""
|
||||
for t in self.turnos:
|
||||
if t.inicio <= t.fin: # turno normal, p.ej. 06-14
|
||||
if t.inicio <= hora < t.fin:
|
||||
return t
|
||||
else: # turno que cruza medianoche, 22-06
|
||||
if hora >= t.inicio or hora < t.fin:
|
||||
return t
|
||||
raise KeyError(f"Ninguna turno cubre la hora {hora}")
|
||||
|
||||
|
||||
# ------------------------------- validación --------------------------------
|
||||
DOW_KEYS = {"Lun", "Mar", "Mie", "Jue", "Vie", "Sab", "Dom"}
|
||||
|
||||
|
||||
def _validate(reg: Registry) -> None:
|
||||
errores = []
|
||||
|
||||
if not reg.combustibles:
|
||||
errores.append("No hay combustibles definidos.")
|
||||
for nombre, f in reg.combustibles.items():
|
||||
if f.margen_litro <= 0 or f.margen_litro >= f.precio_venta_base:
|
||||
errores.append(f"Combustible {nombre}: margen fuera de rango ({f.margen_litro}).")
|
||||
|
||||
for nombre, perfil in reg.perfiles_horarios.items():
|
||||
if len(perfil) != 24:
|
||||
errores.append(f"Perfil horario {nombre!r} debe tener 24 valores (tiene {len(perfil)}).")
|
||||
|
||||
for nombre, semana in reg.perfiles_semana.items():
|
||||
faltan = DOW_KEYS - set(semana.keys())
|
||||
if faltan:
|
||||
errores.append(f"Perfil semana {nombre!r} le faltan días: {faltan}.")
|
||||
|
||||
for grupo, mezcla in (("mezcla_pago", reg.mezcla_pago), ("modos_venta", reg.modos_venta)):
|
||||
s = sum(mezcla.values())
|
||||
if abs(s - 1.0) > 0.001:
|
||||
errores.append(f"{grupo} no suma 1.0 (suma {s:.3f}).")
|
||||
|
||||
ids = [s.id for s in reg._stations]
|
||||
if len(ids) != len(set(ids)):
|
||||
errores.append("Hay ids de estación duplicados.")
|
||||
|
||||
for s in reg._stations:
|
||||
if s.perfil_horario not in reg.perfiles_horarios:
|
||||
errores.append(f"{s.id}: perfil_horario {s.perfil_horario!r} no existe.")
|
||||
if s.perfil_semana not in reg.perfiles_semana:
|
||||
errores.append(f"{s.id}: perfil_semana {s.perfil_semana!r} no existe.")
|
||||
sm = sum(s.mezcla_combustible.values())
|
||||
if abs(sm - 1.0) > 0.001:
|
||||
errores.append(f"{s.id}: mezcla_combustible no suma 1.0 (suma {sm:.3f}).")
|
||||
for fuel_name in s.mezcla_combustible:
|
||||
if fuel_name not in reg.combustibles:
|
||||
errores.append(f"{s.id}: combustible {fuel_name!r} no está en el catálogo.")
|
||||
if not (0 <= s.bomba_fuera_servicio <= s.bombas):
|
||||
errores.append(f"{s.id}: bomba_fuera_servicio fuera de rango.")
|
||||
|
||||
_validate_simulacion(reg, errores)
|
||||
|
||||
if errores:
|
||||
raise ValueError("Registro inválido:\n - " + "\n - ".join(errores))
|
||||
|
||||
|
||||
def _validate_simulacion(reg: Registry, errores: list) -> None:
|
||||
"""Valida los knobs del motor: probabilidades en [0,1], rangos coherentes,
|
||||
y referencias cruzadas (turno/combustibles) consistentes con el registro."""
|
||||
sim = reg.simulacion
|
||||
if sim is None:
|
||||
errores.append("Falta el bloque 'simulacion' en el registro.")
|
||||
return
|
||||
|
||||
# probabilidades / porcentajes que deben estar en [0, 1]
|
||||
fugas = sim.fugas
|
||||
for k in ("drive_off_prob", "merma_evaporacion_pct", "merma_no_explicada_pct",
|
||||
"faltante_caja_pct_efectivo"):
|
||||
v = fugas.get(k)
|
||||
if v is None or not (0.0 <= v <= 1.0):
|
||||
errores.append(f"simulacion.fugas.{k} debe estar en [0,1] (es {v!r}).")
|
||||
if sim.carga.get("monto_fijo_prob") is None or not (0.0 <= sim.carga["monto_fijo_prob"] <= 1.0):
|
||||
errores.append("simulacion.carga.monto_fijo_prob debe estar en [0,1].")
|
||||
|
||||
# ritmos y rangos numéricos coherentes
|
||||
if not (0 < sim.ritmo_vivo_min_por_min <= sim.ritmo_vivo_max_por_min):
|
||||
errores.append("simulacion: ritmo_vivo_min_por_min debe ser >0 y <= max.")
|
||||
if sim.carga["tanque_lleno_litros_min"] >= sim.carga["tanque_lleno_litros_max"]:
|
||||
errores.append("simulacion.carga: tanque_lleno_litros_min debe ser < max.")
|
||||
if not sim.carga.get("montos_fijos_mxn"):
|
||||
errores.append("simulacion.carga.montos_fijos_mxn no puede estar vacío.")
|
||||
if not (0 < sim.reorden_pct < sim.recarga_objetivo_pct <= 100):
|
||||
errores.append("simulacion: se requiere 0 < reorden_pct < recarga_objetivo_pct <= 100.")
|
||||
if sim.tank_reading_intervalo_min <= 0:
|
||||
errores.append("simulacion.tank_reading_intervalo_min debe ser > 0.")
|
||||
|
||||
# temperatura: min < max y coeficiente por cada combustible del catálogo
|
||||
temp = sim.temperatura
|
||||
if temp["min_c"] >= temp["max_c"]:
|
||||
errores.append("simulacion.temperatura: min_c debe ser < max_c.")
|
||||
for fuel_name in reg.combustibles:
|
||||
if fuel_name not in temp.get("coef_termico", {}):
|
||||
errores.append(f"simulacion.temperatura.coef_termico le falta {fuel_name!r}.")
|
||||
|
||||
# referencias cruzadas: el turno y despachador sesgados deben existir
|
||||
turnos_ids = {t.id for t in reg.turnos}
|
||||
if fugas.get("merma_sesgo_turno") not in turnos_ids:
|
||||
errores.append(f"simulacion.fugas.merma_sesgo_turno {fugas.get('merma_sesgo_turno')!r} no es un turno válido.")
|
||||
despachadores = {t.despachador_default for t in reg.turnos}
|
||||
if fugas.get("faltante_sesgo_despachador") not in despachadores:
|
||||
errores.append(
|
||||
f"simulacion.fugas.faltante_sesgo_despachador {fugas.get('faltante_sesgo_despachador')!r} "
|
||||
f"no es un despachador del registro ({sorted(despachadores)})."
|
||||
)
|
||||
|
||||
|
||||
# -------------------------------- carga -------------------------------------
|
||||
def load_registry(path: Path | str = CONFIG_PATH) -> Registry:
|
||||
with open(path, "r", encoding="utf-8") as fh:
|
||||
raw = yaml.safe_load(fh)
|
||||
|
||||
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
|
||||
|
||||
reg = Registry(
|
||||
meta=raw["meta"],
|
||||
combustibles=combustibles,
|
||||
perfiles_horarios=raw["perfiles_horarios"],
|
||||
perfiles_semana=raw["perfiles_semana"],
|
||||
turnos=turnos,
|
||||
mezcla_pago=raw["mezcla_pago"],
|
||||
modos_venta=raw["modos_venta"],
|
||||
capacidad_tanque=raw["capacidad_tanque"],
|
||||
simulacion=simulacion,
|
||||
_stations=stations,
|
||||
)
|
||||
_validate(reg)
|
||||
return reg
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
reg = load_registry()
|
||||
print(f"Registro v{reg.meta['version_registro']} — {reg.meta['empresa']}")
|
||||
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"\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}")
|
||||
|
||||
sim = reg.simulacion
|
||||
print(f"\nSimulación (knobs del motor):")
|
||||
print(f" ráfaga: 1 venta / {sim.arranque['rafaga_intervalo_seg']}s "
|
||||
f"por {sim.arranque['rafaga_duracion_min']} min; luego "
|
||||
f"{sim.ritmo_vivo_min_por_min}-{sim.ritmo_vivo_max_por_min} ventas/min")
|
||||
print(f" fugas: drive-off {sim.fugas['drive_off_prob']*100:.2f}% de cargas · "
|
||||
f"merma {(sim.fugas['merma_evaporacion_pct']+sim.fugas['merma_no_explicada_pct'])*100:.2f}% "
|
||||
f"(no explicada sesgada a turno {sim.fugas['merma_sesgo_turno']}) · "
|
||||
f"faltante caja sesgado a {sim.fugas['faltante_sesgo_despachador']}")
|
||||
@@ -0,0 +1,192 @@
|
||||
# ============================================================================
|
||||
# REGISTRO CENTRAL DE ESTACIONES — Collina Systems
|
||||
# ----------------------------------------------------------------------------
|
||||
# Esta es la COLUMNA VERTEBRAL del diseño modular.
|
||||
#
|
||||
# >>> Agregar una estación nueva = una entrada en `stations`. Nada más. <<<
|
||||
#
|
||||
# Todo el backend (motor generativo, resúmenes mensuales, consolidado,
|
||||
# reconciliación de mermas, espejo en Sheets) ITERA sobre este registro.
|
||||
# El código nunca conoce nombres de estación "a mano": siempre recorre esta
|
||||
# lista. Por eso pasar de 1 a N estaciones no toca lógica.
|
||||
#
|
||||
# Valores calibrados con datos reales (Puebla / México, jun-2026):
|
||||
# - Precios de venta: PETROIntelligence Puebla 01-jun-2026
|
||||
# - Márgenes por litro: Onexpo / Profeco (Magna ~1.10, Premium ~1.30, Diésel ~1.65)
|
||||
# ============================================================================
|
||||
|
||||
meta:
|
||||
empresa: "Collina Systems"
|
||||
zona_horaria: "America/Mexico_City"
|
||||
moneda: "MXN"
|
||||
version_registro: 1
|
||||
|
||||
# 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:
|
||||
Magna: { precio_venta_base: 23.742, margen_litro: 1.10 }
|
||||
Premium: { precio_venta_base: 28.102, margen_litro: 1.30 }
|
||||
Diesel: { precio_venta_base: 27.202, margen_litro: 1.65 }
|
||||
|
||||
# Perfiles de demanda por hora (0–23). Reutilizables entre estaciones por "tipo
|
||||
# de zona", para no repetir 24 números en cada estación. Una estación referencia
|
||||
# un perfil por su clave.
|
||||
perfiles_horarios:
|
||||
corporativo: # corredor de oficinas: picos de commute (7-9, 18-20)
|
||||
[0.18,0.12,0.10,0.10,0.15,0.35,0.95,1.75,1.85,1.35,1.05,1.10,1.25,1.30,1.15,1.05,1.20,1.65,1.95,1.80,1.20,0.70,0.40,0.25]
|
||||
universitario: # zona universitaria/turística: arranca tarde, fuerte noche/finde
|
||||
[0.30,0.22,0.15,0.12,0.12,0.25,0.55,0.95,1.25,1.30,1.25,1.35,1.55,1.60,1.45,1.35,1.45,1.70,1.90,1.95,1.75,1.35,0.85,0.50]
|
||||
comercial: # zona comercial/residencial: pareja, pico vespertino
|
||||
[0.20,0.14,0.11,0.11,0.16,0.40,0.85,1.35,1.45,1.30,1.25,1.40,1.55,1.50,1.40,1.45,1.60,1.70,1.65,1.45,1.10,0.75,0.45,0.28]
|
||||
|
||||
# Factores por día de semana (Lun..Dom) por tipo de zona. Estacionalidad.
|
||||
perfiles_semana:
|
||||
corporativo: { Lun: 1.04, Mar: 1.04, Mie: 1.04, Jue: 1.04, Vie: 1.04, Sab: 0.80, Dom: 0.72 }
|
||||
universitario: { Lun: 0.94, Mar: 0.94, Mie: 0.94, Jue: 0.94, Vie: 1.18, Sab: 1.32, Dom: 1.20 }
|
||||
comercial: { Lun: 0.97, Mar: 0.97, Mie: 0.97, Jue: 0.97, Vie: 1.10, Sab: 1.22, Dom: 1.05 }
|
||||
|
||||
# Esquema de turnos (común MX: 3 turnos de 8 h). Compartido por todas.
|
||||
turnos:
|
||||
- { id: "06-14", inicio: 6, fin: 14, despachador_default: "D-01" }
|
||||
- { id: "14-22", inicio: 14, fin: 22, despachador_default: "D-02" }
|
||||
- { id: "22-06", inicio: 22, fin: 6, despachador_default: "D-03" }
|
||||
|
||||
# Mezcla de pago (gasolinera de barrio MX: efectivo dominante).
|
||||
mezcla_pago:
|
||||
Efectivo: 0.78
|
||||
Tarjeta: 0.16
|
||||
Transferencia: 0.06
|
||||
|
||||
# Modos de venta del forecourt.
|
||||
modos_venta:
|
||||
Pospago: 0.70
|
||||
Prepago: 0.20
|
||||
CRIND: 0.10
|
||||
|
||||
# Capacidad de tanque por combustible (litros). 1 tanque por combustible.
|
||||
capacidad_tanque:
|
||||
Magna: 50000
|
||||
Premium: 30000
|
||||
Diesel: 30000
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# PARÁMETROS DE SIMULACIÓN (knobs del motor generativo, Roadmap §1).
|
||||
# NINGÚN número aquí es "ley": son defaults EDITABLES. Cada uno trae su nivel
|
||||
# de respaldo (la investigación de jun-2026 cazó cifras mal etiquetadas; por eso
|
||||
# todo es configurable y nada se hardcodea en el código).
|
||||
# [SÓLIDO] = dato físico/oficial verificado con fuente.
|
||||
# [DÉBIL] = benchmark sin fuente MX dura; default conservador, calibrar luego.
|
||||
# [DEMO] = ritmo de demostración, sin pretensión de realismo estadístico.
|
||||
# Es catálogo GLOBAL (no por-estación): no rompe la prueba de fuego del registro.
|
||||
# ----------------------------------------------------------------------------
|
||||
simulacion:
|
||||
# --- Ritmo de la demo EN VIVO [DEMO] -------------------------------------
|
||||
# Al arrancar: ráfaga de 1 venta cada 15 s en bombas distintas; luego 1–5/min.
|
||||
# (El relleno de HOY 00:00→ahora NO usa esto: usa volumen realista, abajo.)
|
||||
arranque:
|
||||
rafaga_intervalo_seg: 15
|
||||
rafaga_duracion_min: 5
|
||||
ritmo_vivo_min_por_min: 1 # ventas/minuto AGREGADAS (toda la flota) tras la ráfaga
|
||||
ritmo_vivo_max_por_min: 5
|
||||
|
||||
# --- Volumen realista para el catch-up del día [del registro] ------------
|
||||
# El relleno usa ventas_dia_aprox × perfil_horario × perfil_semana para que
|
||||
# los totales del día cuadren con lo declarado por estación.
|
||||
catchup:
|
||||
jitter_pct: 0.10 # ±10% de ruido sobre el conteo esperado por hora
|
||||
|
||||
# --- Distribución de litros por carga [DÉBIL] ----------------------------
|
||||
# No hay censo público de litros/ticket. ENIGH 2024 ancla gasto por hogar
|
||||
# (~$1,023/mes), NO ticket por transacción. Se modela como MEZCLA:
|
||||
carga:
|
||||
monto_fijo_prob: 0.60 # 60% cargan por monto fijo...
|
||||
montos_fijos_mxn: [200, 300, 500, 1000]
|
||||
tanque_lleno_litros_min: 30 # ...40% "llenan tanque" (30–65 L)
|
||||
tanque_lleno_litros_max: 65
|
||||
|
||||
# --- Precio diario [parcial: variación es DEMO, márgenes del registro] ----
|
||||
precio_variacion_venta_pct: 0.012 # ±1.2% sobre precio_venta_base (nota del YAML)
|
||||
precio_variacion_costo_pct: 0.015 # el costo de reposición se mueve algo más → señal "cohetes y plumas"
|
||||
|
||||
# --- Lecturas de tanque (ATG) --------------------------------------------
|
||||
tank_reading_intervalo_min: 30
|
||||
reorden_pct: 18.0 # si el tanque baja de 18% lleno, llega una descarga
|
||||
recarga_objetivo_pct: 92.0 # la descarga lo deja ~92% lleno
|
||||
|
||||
# --- Temperatura ambiente del día [coeficientes SÓLIDOS] -----------------
|
||||
# La dilatación térmica es física verificada (gasolina 0.00126/°C, diésel
|
||||
# 0.00083/°C). Mueve el delta vol_bruto/vol_neto que la plataforma usará para
|
||||
# separar merma legítima (temperatura) del faltante anómalo.
|
||||
temperatura:
|
||||
referencia_c: 20.0 # corrección a neto (convención Gilbarco en MX)
|
||||
min_c: 14.0 # madrugada (Puebla)
|
||||
max_c: 31.0 # mediodía
|
||||
hora_pico: 15 # hora del máximo de temperatura
|
||||
coef_termico: # fracción de volumen por °C
|
||||
Magna: 0.00126
|
||||
Premium: 0.00126
|
||||
Diesel: 0.00083
|
||||
|
||||
# --- Fugas inyectadas (todas DÉBILES → configurables, NO dato duro) -------
|
||||
# Son las fugas LUCRATIVAS de detectar; el motor las inyecta con señal para
|
||||
# que la plataforma tenga algo real que vigilar. Magnitudes ilustrativas.
|
||||
fugas:
|
||||
drive_off_prob: 0.001 # [DÉBIL] ~0.1% de cargas (benchmark UK/US recortado;
|
||||
# en MX el despacho es atendido → menos exposición)
|
||||
merma_evaporacion_pct: 0.0020 # [DÉBIL] ~0.2% del volumen: merma "legítima" (evaporación/manejo)
|
||||
merma_no_explicada_pct: 0.0030 # [DÉBIL] ~0.3% del volumen: "ordeña" (lo que sí es robo)
|
||||
merma_sesgo_turno: "22-06" # se concentra en el turno nocturno → señal de reincidencia
|
||||
faltante_caja_pct_efectivo: 0.0020 # [DÉBIL] ~0.2% del efectivo cobrado por turno
|
||||
faltante_sesgo_despachador: "D-02" # reincidencia en un despachador → señal accionable
|
||||
tope_efectivo_mxn: 700 # [SÓLIDO] tope de efectivo en mano (Pemex ~700, BP ~1000)
|
||||
# (el umbral "$200" que circula NO tiene fuente: no se usa)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# LAS ESTACIONES. Cada una es un módulo autónomo.
|
||||
# Para agregar la #4, #5, #N: copia un bloque y cámbialo. El resto se genera solo.
|
||||
# ----------------------------------------------------------------------------
|
||||
stations:
|
||||
- id: "cholula" # identificador estable (no cambia nunca; clave en DB)
|
||||
nombre: "Cholula"
|
||||
zona: "San Andrés Cholula, Puebla"
|
||||
perfil_horario: "universitario"
|
||||
perfil_semana: "universitario"
|
||||
bombas: 6
|
||||
ventas_dia_aprox: 560 # transacciones/día típicas (escala el volumen)
|
||||
mezcla_combustible: { Magna: 0.58, Premium: 0.27, Diesel: 0.15 }
|
||||
bomba_fuera_servicio: 0 # 0 = ninguna; o el número de bomba intermitente
|
||||
activa: true
|
||||
|
||||
- id: "atlixcayotl"
|
||||
nombre: "Atlixcáyotl"
|
||||
zona: "Vía Atlixcáyotl / Angelópolis, Puebla"
|
||||
perfil_horario: "corporativo"
|
||||
perfil_semana: "corporativo"
|
||||
bombas: 8
|
||||
ventas_dia_aprox: 820
|
||||
mezcla_combustible: { Magna: 0.49, Premium: 0.34, Diesel: 0.17 }
|
||||
bomba_fuera_servicio: 0
|
||||
activa: true
|
||||
|
||||
- id: "zavaleta"
|
||||
nombre: "Zavaleta"
|
||||
zona: "Av. Zavaleta, Puebla"
|
||||
perfil_horario: "comercial"
|
||||
perfil_semana: "comercial"
|
||||
bombas: 6
|
||||
ventas_dia_aprox: 480
|
||||
mezcla_combustible: { Magna: 0.55, Premium: 0.30, Diesel: 0.15 }
|
||||
bomba_fuera_servicio: 4
|
||||
activa: true
|
||||
|
||||
# --- Plantilla para crecer (descomenta y ajusta para la estación piloto #N) ---
|
||||
# - id: "nueva_estacion"
|
||||
# nombre: "Nombre Comercial"
|
||||
# zona: "Dirección / colonia"
|
||||
# perfil_horario: "comercial" # corporativo | universitario | comercial
|
||||
# perfil_semana: "comercial"
|
||||
# bombas: 6
|
||||
# ventas_dia_aprox: 500
|
||||
# mezcla_combustible: { Magna: 0.55, Premium: 0.30, Diesel: 0.15 }
|
||||
# bomba_fuera_servicio: 0
|
||||
# activa: true
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
-- ============================================================================
|
||||
-- COLLINA SYSTEMS — ESQUEMA DE BASE DE DATOS (PostgreSQL)
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- Principio rector: la ESTACIÓN es una fila en `station` y una FK en todo lo
|
||||
-- demás. NUNCA una tabla por estación. Así, pasar de 1 a N estaciones no
|
||||
-- cambia el esquema: solo se insertan filas. El backend itera sobre `station`.
|
||||
--
|
||||
-- Dos horizontes de datos:
|
||||
-- CALIENTE (detallado): sale, tank_reading, shift_cut -> mes en curso.
|
||||
-- FRÍO (comprimido): monthly_summary (+ JSONB) -> meses cerrados.
|
||||
-- Al cerrar el mes, se calcula el resumen, se guarda en monthly_summary y se
|
||||
-- libera el crudo del mes (DELETE de sale/tank_reading/shift_cut de ese mes).
|
||||
-- ============================================================================
|
||||
|
||||
CREATE SCHEMA IF NOT EXISTS collina;
|
||||
SET search_path TO collina, public;
|
||||
|
||||
-- ------------------------------------------------------------------ catálogos
|
||||
CREATE TABLE IF NOT EXISTS fuel (
|
||||
name TEXT PRIMARY KEY, -- 'Magna','Premium','Diesel'
|
||||
sale_price_base NUMERIC(8,3) NOT NULL,
|
||||
margin_per_liter NUMERIC(8,3) NOT NULL,
|
||||
cost_base NUMERIC(8,3) GENERATED ALWAYS AS (sale_price_base - margin_per_liter) STORED
|
||||
);
|
||||
|
||||
-- ------------------------------------------------------------- estaciones (N)
|
||||
CREATE TABLE IF NOT EXISTS station (
|
||||
id TEXT PRIMARY KEY, -- 'cholula' (estable, del registro)
|
||||
nombre TEXT NOT NULL,
|
||||
zona TEXT,
|
||||
perfil_horario TEXT NOT NULL,
|
||||
perfil_semana TEXT NOT NULL,
|
||||
bombas SMALLINT NOT NULL,
|
||||
ventas_dia_aprox INTEGER NOT NULL,
|
||||
bomba_fuera_serv SMALLINT NOT NULL DEFAULT 0,
|
||||
activa BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
config JSONB, -- mezcla_combustible, etc. (flexible)
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- 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,
|
||||
fecha DATE NOT NULL,
|
||||
fuel_name TEXT NOT NULL REFERENCES fuel(name),
|
||||
sale_price NUMERIC(8,3) NOT NULL,
|
||||
cost_price NUMERIC(8,3) NOT NULL, -- costo de compra de ese día
|
||||
PRIMARY KEY (station_id, fecha, fuel_name)
|
||||
);
|
||||
|
||||
-- ============================================================ DATOS CALIENTES
|
||||
-- VENTAS (bitácora de cargas). Materia prima del mes en curso.
|
||||
CREATE TABLE IF NOT EXISTS sale (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
station_id TEXT NOT NULL REFERENCES station(id) ON DELETE CASCADE,
|
||||
ts TIMESTAMPTZ NOT NULL,
|
||||
bomba SMALLINT NOT NULL,
|
||||
manguera TEXT,
|
||||
fuel_name TEXT NOT NULL REFERENCES fuel(name),
|
||||
litros NUMERIC(10,2) NOT NULL,
|
||||
precio_unitario NUMERIC(8,3) NOT NULL,
|
||||
costo_unitario NUMERIC(8,3) NOT NULL, -- congela el costo del día
|
||||
monto NUMERIC(12,2) NOT NULL,
|
||||
ganancia NUMERIC(12,2) NOT NULL, -- (precio-costo)*litros
|
||||
modo_venta TEXT NOT NULL, -- Pospago/Prepago/CRIND
|
||||
metodo_pago TEXT NOT NULL, -- Efectivo/Tarjeta/Transferencia
|
||||
despachador TEXT NOT NULL, -- ID: D-01...
|
||||
turno TEXT NOT NULL, -- '06-14'...
|
||||
drive_off BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
|
||||
-- LECTURAS DE TANQUE (ATG), cada 30 min. Base de la reconciliación de mermas.
|
||||
CREATE TABLE IF NOT EXISTS tank_reading (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
station_id TEXT NOT NULL REFERENCES station(id) ON DELETE CASCADE,
|
||||
ts TIMESTAMPTZ NOT NULL,
|
||||
tanque TEXT NOT NULL, -- 'M-TK','P-TK','D-TK'
|
||||
fuel_name TEXT NOT NULL REFERENCES fuel(name),
|
||||
nivel_cm NUMERIC(8,1),
|
||||
vol_bruto_l NUMERIC(12,1) NOT NULL,
|
||||
vol_neto_l NUMERIC(12,1), -- corregido @20°C
|
||||
nivel_agua_cm NUMERIC(6,1),
|
||||
temperatura_c NUMERIC(5,1),
|
||||
ullage_l NUMERIC(12,1),
|
||||
pct_lleno NUMERIC(5,1),
|
||||
evento TEXT NOT NULL DEFAULT 'Lectura normal', -- 'Fin descarga'...
|
||||
vol_entregado_l NUMERIC(12,1)
|
||||
);
|
||||
|
||||
-- CORTES DE TURNO / CAJA. Un corte por (estación, fecha, turno, despachador).
|
||||
CREATE TABLE IF NOT EXISTS shift_cut (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
station_id TEXT NOT NULL REFERENCES station(id) ON DELETE CASCADE,
|
||||
fecha DATE NOT NULL,
|
||||
turno TEXT NOT NULL,
|
||||
despachador TEXT NOT NULL,
|
||||
litros_vendidos NUMERIC(12,2) NOT NULL,
|
||||
ingreso_esperado NUMERIC(12,2) NOT NULL,
|
||||
cobrado_efectivo NUMERIC(12,2) NOT NULL,
|
||||
cobrado_tarjeta NUMERIC(12,2) NOT NULL,
|
||||
cobrado_transfer NUMERIC(12,2) NOT NULL,
|
||||
depositado_caja NUMERIC(12,2) NOT NULL,
|
||||
diferencia NUMERIC(12,2) NOT NULL, -- sin lógica de alerta aún
|
||||
UNIQUE (station_id, fecha, turno, despachador)
|
||||
);
|
||||
|
||||
-- =============================================================== DATOS FRÍOS
|
||||
-- RESUMEN MENSUAL. Una fila POR ESTACIÓN + una fila consolidada (station_id = NULL
|
||||
-- => consolidado del grupo). Los 4 bloques viven en `data` (JSONB) para que el
|
||||
-- esquema no cambie si los insights evolucionan; los KPIs clave se "promueven"
|
||||
-- a columnas para consultar/ordenar rápido.
|
||||
CREATE TABLE IF NOT EXISTS monthly_summary (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
station_id TEXT REFERENCES station(id) ON DELETE CASCADE, -- NULL = consolidado
|
||||
periodo CHAR(7) NOT NULL, -- 'YYYY-MM'
|
||||
es_consolidado BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
-- KPIs promovidos (Bloque 1 y 2) para ranking/tendencia sin abrir el JSON
|
||||
litros BIGINT,
|
||||
ingreso BIGINT,
|
||||
costo BIGINT,
|
||||
ganancia BIGINT,
|
||||
margen_litro NUMERIC(8,3),
|
||||
-- KPIs de fuga (Bloque 3)
|
||||
merma_litros BIGINT,
|
||||
merma_pesos BIGINT,
|
||||
drive_pesos BIGINT,
|
||||
faltante_caja BIGINT,
|
||||
-- los 4 bloques completos + insights + metadatos
|
||||
data JSONB NOT NULL,
|
||||
dashboard_url TEXT, -- link temporal al dashboard
|
||||
n_tx_comprimidas INTEGER,
|
||||
cerrado_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (station_id, periodo, es_consolidado)
|
||||
);
|
||||
|
||||
-- ------------------------------------------------------------------- índices
|
||||
CREATE INDEX IF NOT EXISTS ix_sale_station_ts ON sale (station_id, ts);
|
||||
CREATE INDEX IF NOT EXISTS ix_sale_ts ON sale (ts);
|
||||
CREATE INDEX IF NOT EXISTS ix_tank_station_ts ON tank_reading (station_id, ts);
|
||||
CREATE INDEX IF NOT EXISTS ix_shift_station_fecha ON shift_cut (station_id, fecha);
|
||||
CREATE INDEX IF NOT EXISTS ix_summary_periodo ON monthly_summary (periodo);
|
||||
CREATE INDEX IF NOT EXISTS ix_summary_station ON monthly_summary (station_id, periodo);
|
||||
|
||||
-- ------------------------------------------------------ vista de concentrado
|
||||
-- "Concentrado en vivo": agrega TODAS las estaciones del mes en curso sin
|
||||
-- materializar nada. Itera implícitamente sobre cuantas estaciones existan.
|
||||
CREATE OR REPLACE VIEW v_live_today AS
|
||||
SELECT
|
||||
s.station_id,
|
||||
st.nombre,
|
||||
date_trunc('day', s.ts AT TIME ZONE 'America/Mexico_City') AS dia,
|
||||
COUNT(*) AS cargas,
|
||||
SUM(s.litros) AS litros,
|
||||
SUM(s.monto) AS ingreso,
|
||||
SUM(s.ganancia) AS ganancia,
|
||||
SUM(s.monto) FILTER (WHERE s.metodo_pago = 'Efectivo') AS efectivo
|
||||
FROM sale s
|
||||
JOIN station st ON st.id = s.station_id
|
||||
GROUP BY s.station_id, st.nombre, dia;
|
||||
@@ -0,0 +1,438 @@
|
||||
/* ============================================================================
|
||||
COLLINA — SIMULACIÓN DE OPERACIÓN (Google Sheets autónomo, acumulativo)
|
||||
----------------------------------------------------------------------------
|
||||
Tres estaciones de Puebla: Cholula, Atlixcáyotl, Zavaleta.
|
||||
La hoja GENERA operación realista y la ACUMULA hacia adelante. No depende de
|
||||
semillas ni "cuadra" con nada externo: solo genera.
|
||||
|
||||
PESTAÑAS
|
||||
• 📊 TABLERO resumen en vivo (por estación: litros, ingreso, tx,
|
||||
ticket, % efectivo, precios del día). Se recalcula del
|
||||
acumulado en cada corrida.
|
||||
• 🟢 VENTAS bitácora de cargas que CRECE: cada renglón es una venta.
|
||||
• 🛢️ TANQUES lecturas ATG (cada 30 min) por tanque. El nivel BAJA con
|
||||
las ventas y SUBE con descargas.
|
||||
• 🧾 TURNOS cortes por turno y despachador (06–14 / 14–22 / 22–06).
|
||||
• 📅 HISTÓRICO 30 cierres FIJOS; solo las fechas se recorren según hoy.
|
||||
• 🗄️ ARCHIVO al cambiar de día, las ventas del día anterior se mueven
|
||||
aquí y la bitácora viva se limpia.
|
||||
|
||||
COMPORTAMIENTO ESPECIAL
|
||||
• Al ▶️ Iniciar: BURST de arranque ~5 min, una venta cada 15 s en bombas
|
||||
distintas (trigger rápido que se autodestruye). Luego ritmo normal/min.
|
||||
• Precio por litro: se fija al primer arranque del día y se mantiene todo el
|
||||
día (varía de un día a otro).
|
||||
|
||||
INSTALAR: Extensiones ▸ Apps Script ▸ pega esto ▸ guarda ▸ recarga la hoja ▸
|
||||
menú "⛽ Collina ▸ ▶️ Iniciar simulación".
|
||||
============================================================================ */
|
||||
|
||||
var TZ = "America/Mexico_City";
|
||||
|
||||
var PRICE_BASE = { Magna: 23.742, Premium: 28.102, Diesel: 27.202 }; // Puebla 01-jun-2026
|
||||
|
||||
// Curva de demanda por hora (0–23) por zona. Define cuántas ventas por minuto.
|
||||
var HOURLY = {
|
||||
atlixcayotl:[.18,.12,.10,.10,.15,.35,.95,1.75,1.85,1.35,1.05,1.10,1.25,1.30,1.15,1.05,1.20,1.65,1.95,1.80,1.20,.70,.40,.25],
|
||||
cholula: [.30,.22,.15,.12,.12,.25,.55,.95,1.25,1.30,1.25,1.35,1.55,1.60,1.45,1.35,1.45,1.70,1.90,1.95,1.75,1.35,.85,.50],
|
||||
zavaleta: [.20,.14,.11,.11,.16,.40,.85,1.35,1.45,1.30,1.25,1.40,1.55,1.50,1.40,1.45,1.60,1.70,1.65,1.45,1.10,.75,.45,.28]
|
||||
};
|
||||
|
||||
// Ventas/min en el PICO (multiplicado por el peso horario => ventas/min reales).
|
||||
var PEAK_TPM = { cholula:0.65, atlixcayotl:0.95, zavaleta:0.55 };
|
||||
|
||||
var STATIONS = [
|
||||
{ id:"cholula", name:"Cholula", pumps:6, dead:0 },
|
||||
{ id:"atlixcayotl", name:"Atlixcáyotl", pumps:8, dead:0 },
|
||||
{ id:"zavaleta", name:"Zavaleta", pumps:6, dead:4 }
|
||||
];
|
||||
|
||||
// Tanque por combustible (3 por estación). Capacidad en litros.
|
||||
var TANKS = ["Magna","Premium","Diesel"];
|
||||
var TANK_CAP = { Magna:50000, Premium:30000, Diesel:30000 };
|
||||
// Manguera/grado por bomba (índice de bomba -> combustible)
|
||||
var PUMP_FUEL = ["Magna","Premium","Diesel","Magna","Diesel","Premium","Magna","Diesel"];
|
||||
|
||||
var PAY_METHODS = [ ["Efectivo",0.78], ["Tarjeta",0.16], ["Transferencia",0.06] ]; // gasolinera de barrio MX
|
||||
var SALE_MODES = [ ["Pospago",0.70], ["Prepago",0.20], ["CRIND",0.10] ];
|
||||
|
||||
var SHEETS = {
|
||||
tablero:"📊 TABLERO", ventas:"🟢 VENTAS", tanques:"🛢️ TANQUES",
|
||||
turnos:"🧾 TURNOS", historico:"📅 HISTÓRICO", archivo:"🗄️ ARCHIVO"
|
||||
};
|
||||
var BURST_SECONDS = 15; // una venta cada 15 s en el arranque
|
||||
var BURST_MINUTES = 5; // durante 5 minutos
|
||||
|
||||
/* ------------------------------- utilidades -------------------------------- */
|
||||
function ss(){ return SpreadsheetApp.getActiveSpreadsheet(); }
|
||||
function props(){ return PropertiesService.getDocumentProperties(); }
|
||||
function now(){ return new Date(); }
|
||||
function fmt(d,p){ return Utilities.formatDate(d, TZ, p); }
|
||||
function todayKey(){ return fmt(now(),"yyyy-MM-dd"); }
|
||||
function hourNow(){ return +fmt(now(),"H"); }
|
||||
function getSheet(name){ var s=ss().getSheetByName(name); if(!s) s=ss().insertSheet(name); return s; }
|
||||
function pick(table){ var r=Math.random(),a=0; for(var i=0;i<table.length;i++){ a+=table[i][1]; if(r<=a) return table[i][0]; } return table[table.length-1][0]; }
|
||||
function stById(id){ for(var i=0;i<STATIONS.length;i++) if(STATIONS[i].id===id) return STATIONS[i]; }
|
||||
function turnoDe(h){ return (h>=6&&h<14)?"06–14":(h>=14&&h<22)?"14–22":"22–06"; }
|
||||
function despDeTurno(h){ return (h>=6&&h<14)?"D-01":(h>=14&&h<22)?"D-02":"D-03"; } // ID rotando por turno
|
||||
|
||||
/* --------------------------- precio fijo del día --------------------------- */
|
||||
function priceForToday(){
|
||||
var key=todayKey();
|
||||
var saved=props().getProperty("price:"+key);
|
||||
if(saved) return JSON.parse(saved);
|
||||
// variación pequeña determinada al primer arranque del día (±1.2%) y fija todo el día
|
||||
var p={};
|
||||
TANKS.forEach(function(f){
|
||||
var jitter = 1 + (Math.random()*0.024 - 0.012);
|
||||
p[f]=Math.round(PRICE_BASE[f]*jitter*1000)/1000;
|
||||
});
|
||||
props().setProperty("price:"+key, JSON.stringify(p));
|
||||
return p;
|
||||
}
|
||||
|
||||
/* ----------------------------- estado de tanques --------------------------- */
|
||||
// Nivel inicial de tanques (al iniciar día). Se guarda y baja con ventas.
|
||||
function initTanks(){
|
||||
var state={};
|
||||
STATIONS.forEach(function(st){
|
||||
state[st.id]={};
|
||||
TANKS.forEach(function(f){
|
||||
var cap=TANK_CAP[f];
|
||||
state[st.id][f]={ vol: Math.round(cap*(0.55+Math.random()*0.30)), cap:cap }; // 55–85% lleno
|
||||
});
|
||||
});
|
||||
props().setProperty("tanks", JSON.stringify(state));
|
||||
return state;
|
||||
}
|
||||
function getTanks(){ var t=props().getProperty("tanks"); return t?JSON.parse(t):initTanks(); }
|
||||
function saveTanks(t){ props().setProperty("tanks", JSON.stringify(t)); }
|
||||
|
||||
/* =============================== GENERAR VENTAS ============================= */
|
||||
// Genera `count` ventas, las escribe en VENTAS, descuenta tanques y acumula
|
||||
// totales por turno. `rotatePumps` fuerza bombas distintas consecutivas (burst).
|
||||
function generateSales(count, rotatePumps){
|
||||
var sh=getSheet(SHEETS.ventas);
|
||||
ensureVentasHeader(sh);
|
||||
var price=priceForToday();
|
||||
var tanks=getTanks();
|
||||
var rows=[];
|
||||
var lpRaw=props().getProperty("lastPump");
|
||||
var lastPump=lpRaw?JSON.parse(lpRaw):{}; // persistente entre llamadas (clave para el burst)
|
||||
var h=hourNow(), t=now();
|
||||
|
||||
for(var k=0;k<count;k++){
|
||||
// elegir estación ponderada por su actividad horaria
|
||||
var st=pickStationByHour(h);
|
||||
var pumpCount=st.pumps;
|
||||
// bomba: rotación estricta si burst; si no, aleatoria evitando repetir la inmediata
|
||||
var p, prev=lastPump[st.id]||0;
|
||||
if(rotatePumps){ p=(prev % pumpCount)+1; }
|
||||
else { do { p=1+Math.floor(Math.random()*pumpCount); } while(p===prev && pumpCount>1); }
|
||||
if(st.dead===p && h>=14){ p=(p % pumpCount)+1; } // bomba muerta por la tarde
|
||||
lastPump[st.id]=p;
|
||||
|
||||
var fuel=PUMP_FUEL[(p-1)%PUMP_FUEL.length];
|
||||
var manguera=p+"-"+fuel.charAt(0); // ej. "3-D"
|
||||
var litros=Math.round((5+Math.pow(Math.random(),2)*45)*100)/100; // 5–50 L sesgo a chico
|
||||
var pu=price[fuel];
|
||||
var monto=Math.round(litros*pu*100)/100;
|
||||
var modo=pick(SALE_MODES);
|
||||
var pago=pick(PAY_METHODS);
|
||||
var driveoff = (modo==="Pospago" && Math.random()<0.004) ? "SÍ" : ""; // ~0.4% fugas
|
||||
// marca de tiempo: reparte las ventas del lote dentro del último minuto
|
||||
var ts=new Date(t.getTime() - (count-1-k)*Math.floor(60000/Math.max(count,1)));
|
||||
rows.push([ fmt(ts,"yyyy-MM-dd HH:mm:ss"), st.name, "Bomba "+p, manguera,
|
||||
fuel==="Diesel"?"Diésel":fuel, litros, pu, monto, modo, pago,
|
||||
despDeTurno(h), turnoDe(h), driveoff ]);
|
||||
// descontar del tanque (si hubo venta efectiva)
|
||||
if(!driveoff){ var tk=tanks[st.id][fuel]; tk.vol=Math.max(0, Math.round(tk.vol-litros)); }
|
||||
accTurno(st.id, turnoDe(h), despDeTurno(h), litros, monto, pago);
|
||||
}
|
||||
if(rows.length){
|
||||
sh.getRange(sh.getLastRow()+1,1,rows.length,rows[0].length).setValues(rows);
|
||||
}
|
||||
saveTanks(tanks);
|
||||
props().setProperty("lastPump", JSON.stringify(lastPump));
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
function pickStationByHour(h){
|
||||
// peso = curva horaria × actividad pico de la estación
|
||||
var weights=STATIONS.map(function(st){ return HOURLY[st.id][h]*PEAK_TPM[st.id]; });
|
||||
var sum=weights.reduce(function(a,b){return a+b;},0);
|
||||
var r=Math.random()*sum, a=0;
|
||||
for(var i=0;i<STATIONS.length;i++){ a+=weights[i]; if(r<=a) return STATIONS[i]; }
|
||||
return STATIONS[STATIONS.length-1];
|
||||
}
|
||||
|
||||
// ventas a generar en ESTE minuto: aleatorio plano entre 1 y 5 (no depende de la hora)
|
||||
function salesThisMinute(){
|
||||
return 1 + Math.floor(Math.random()*5); // 1,2,3,4 o 5
|
||||
}
|
||||
|
||||
/* ------------------------- acumulado por turno (caja) ---------------------- */
|
||||
function accTurno(stId, turno, desp, litros, monto, pago){
|
||||
var key="turno:"+todayKey()+":"+stId+":"+turno;
|
||||
var raw=props().getProperty(key);
|
||||
var a=raw?JSON.parse(raw):{desp:desp,litros:0,esperado:0,efectivo:0,tarjeta:0,transfer:0};
|
||||
a.litros+=litros; a.esperado+=monto;
|
||||
if(pago==="Efectivo") a.efectivo+=monto;
|
||||
else if(pago==="Tarjeta") a.tarjeta+=monto;
|
||||
else a.transfer+=monto;
|
||||
props().setProperty(key, JSON.stringify(a));
|
||||
}
|
||||
|
||||
/* ============================== ESCRIBIR PESTAÑAS ========================== */
|
||||
function ensureVentasHeader(sh){
|
||||
if(sh.getLastRow()>=1 && sh.getRange(1,1).getValue()==="Fecha-hora") return;
|
||||
sh.clear();
|
||||
var head=["Fecha-hora","Estación","Bomba","Manguera/grado","Combustible","Litros",
|
||||
"Precio unitario","Monto","Modo de venta","Método de pago","Despachador","Turno","Drive-off"];
|
||||
sh.getRange(1,1,1,head.length).setValues([head]).setFontWeight("bold").setFontColor("#fff").setBackground("#1a7f4b");
|
||||
sh.setFrozenRows(1);
|
||||
sh.getRange("F:F").setNumberFormat("#,##0.00");
|
||||
sh.getRange("G:G").setNumberFormat("$#,##0.000");
|
||||
sh.getRange("H:H").setNumberFormat("$#,##0.00");
|
||||
}
|
||||
|
||||
function buildTanques(){
|
||||
var sh=getSheet(SHEETS.tanques);
|
||||
if(sh.getRange(1,1).getValue()!=="Fecha-hora"){
|
||||
sh.clear();
|
||||
var head=["Fecha-hora","Estación","Tanque","Combustible","Nivel producto (cm)","Volumen bruto (L)",
|
||||
"Volumen neto @20°C (L)","Nivel agua (cm)","Temperatura (°C)","Ullage (L)","% lleno","Evento","Volumen entregado (L)"];
|
||||
sh.getRange(1,1,1,head.length).setValues([head]).setFontWeight("bold").setFontColor("#fff").setBackground("#8a5a00");
|
||||
sh.setFrozenRows(1);
|
||||
}
|
||||
// una lectura ATG por tanque cada vez que toca media hora (00 y 30)
|
||||
var m=+fmt(now(),"m");
|
||||
if(m!==0 && m!==30 && props().getProperty("forceTank")!=="1") return;
|
||||
props().deleteProperty("forceTank");
|
||||
var tanks=getTanks(), temp=18+Math.random()*6, rows=[];
|
||||
var ts=fmt(now(),"yyyy-MM-dd HH:mm:ss");
|
||||
STATIONS.forEach(function(st){
|
||||
TANKS.forEach(function(f){
|
||||
var tk=tanks[st.id][f], cap=tk.cap, vol=tk.vol;
|
||||
var evento="Lectura normal", entregado="";
|
||||
// descarga (delivery) cuando el tanque baja del 25%: se rellena a ~90%
|
||||
if(vol < cap*0.25){
|
||||
var nuevo=Math.round(cap*0.90);
|
||||
entregado=nuevo-vol; vol=nuevo; tk.vol=vol; evento="Fin descarga";
|
||||
}
|
||||
var pct=vol/cap;
|
||||
var nivel=Math.round(pct*250); // cm aprox (tanque ~2.5 m)
|
||||
var agua=Math.round((Math.random()*2.5)*10)/10; // cm de agua (bajo = sano)
|
||||
var neto=Math.round(vol*(1-(temp-20)*0.00072)); // corrección térmica simple
|
||||
var ullage=cap-vol;
|
||||
rows.push([ts, st.name, f.charAt(0)+"-TK", f==="Diesel"?"Diésel":f, nivel, vol, neto,
|
||||
agua, Math.round(temp*10)/10, ullage, Math.round(pct*1000)/10, evento, entregado]);
|
||||
});
|
||||
});
|
||||
saveTanks(tanks);
|
||||
sh.getRange(sh.getLastRow()+1,1,rows.length,rows[0].length).setValues(rows);
|
||||
sh.getRange("F:G").setNumberFormat("#,##0");
|
||||
sh.getRange("K:K").setNumberFormat("0.0\"%\"");
|
||||
}
|
||||
|
||||
function buildTurnos(){
|
||||
var sh=getSheet(SHEETS.turnos);
|
||||
sh.clear();
|
||||
var head=["Fecha","Estación","Turno","Despachador","Litros vendidos","Ingreso esperado",
|
||||
"Cobrado efectivo","Cobrado tarjeta","Cobrado transferencia","Depositado a caja fuerte","Diferencia"];
|
||||
sh.getRange(1,1,1,head.length).setValues([head]).setFontWeight("bold").setFontColor("#fff").setBackground("#0b3b32");
|
||||
sh.setFrozenRows(1);
|
||||
var key=todayKey(), rows=[];
|
||||
STATIONS.forEach(function(st){
|
||||
["06–14","14–22","22–06"].forEach(function(turno){
|
||||
var raw=props().getProperty("turno:"+key+":"+st.id+":"+turno);
|
||||
if(!raw) return;
|
||||
var a=JSON.parse(raw);
|
||||
var depositado=Math.round(a.efectivo*(0.93+Math.random()*0.06)); // deposita casi todo el efectivo
|
||||
var diferencia=Math.round(a.efectivo)-depositado; // (lógica de alerta: después)
|
||||
rows.push([key, st.name, turno, a.desp, Math.round(a.litros), Math.round(a.esperado),
|
||||
Math.round(a.efectivo), Math.round(a.tarjeta), Math.round(a.transfer), depositado, diferencia]);
|
||||
});
|
||||
});
|
||||
if(rows.length) sh.getRange(2,1,rows.length,rows[0].length).setValues(rows);
|
||||
for(var c=6;c<=11;c++) sh.getRange(1,c,1+rows.length,1).setNumberFormat("$#,##0");
|
||||
sh.getRange("E:E").setNumberFormat('#,##0" L"');
|
||||
}
|
||||
|
||||
function buildTablero(){
|
||||
var sh=getSheet(SHEETS.tablero); sh.clear();
|
||||
var price=priceForToday();
|
||||
sh.getRange("A1").setValue("COLLINA — OPERACIÓN EN VIVO").setFontSize(16).setFontWeight("bold").setFontColor("#0b3b32");
|
||||
sh.getRange("A2").setValue("Actualizado: "+fmt(now(),"EEE d 'de' MMM yyyy · HH:mm:ss")+" · "+TZ).setFontColor("#667781").setFontSize(10);
|
||||
sh.getRange("A3").setValue("Precio del día — Magna $"+price.Magna+" · Premium $"+price.Premium+" · Diésel $"+price.Diesel).setFontColor("#1a7f4b").setFontSize(10);
|
||||
|
||||
// agregamos del día leyendo la pestaña VENTAS
|
||||
var agg=aggregateToday();
|
||||
var head=["Estación","Ingreso (MXN)","Litros","Cargas","Ticket prom.","% efectivo"];
|
||||
sh.getRange(5,1,1,6).setValues([head]).setFontWeight("bold").setFontColor("#fff").setBackground("#1a7f4b");
|
||||
var rows=[], tI=0,tL=0,tN=0;
|
||||
STATIONS.forEach(function(st){
|
||||
var a=agg[st.name]||{ing:0,lit:0,n:0,ef:0};
|
||||
var ticket=a.n?a.ing/a.n:0, pef=a.ing?a.ef/a.ing:0;
|
||||
rows.push([st.name, Math.round(a.ing), Math.round(a.lit), a.n, Math.round(ticket), pef]);
|
||||
tI+=a.ing; tL+=a.lit; tN+=a.n;
|
||||
});
|
||||
rows.push(["TOTAL GRUPO", Math.round(tI), Math.round(tL), tN, "", ""]);
|
||||
sh.getRange(6,1,rows.length,6).setValues(rows);
|
||||
sh.getRange(6,2,rows.length,1).setNumberFormat("$#,##0");
|
||||
sh.getRange(6,3,rows.length,1).setNumberFormat('#,##0" L"');
|
||||
sh.getRange(6,5,rows.length-1,1).setNumberFormat("$#,##0");
|
||||
sh.getRange(6,6,rows.length-1,1).setNumberFormat("0.0%");
|
||||
sh.getRange(5+rows.length,1,1,6).setFontWeight("bold").setBackground("#e7f6ef");
|
||||
sh.setColumnWidth(1,170); for(var c=2;c<=6;c++) sh.setColumnWidth(c,140);
|
||||
sh.setFrozenRows(5);
|
||||
}
|
||||
|
||||
// suma del día desde la pestaña VENTAS (acumulado real)
|
||||
function aggregateToday(){
|
||||
var sh=getSheet(SHEETS.ventas);
|
||||
var last=sh.getLastRow(); if(last<2) return {};
|
||||
var data=sh.getRange(2,2,last-1,9).getValues(); // B..J: Estación..Método pago
|
||||
var agg={};
|
||||
for(var i=0;i<data.length;i++){
|
||||
var est=data[i][0], litros=data[i][4], monto=data[i][6], pago=data[i][8];
|
||||
if(!agg[est]) agg[est]={ing:0,lit:0,n:0,ef:0};
|
||||
agg[est].ing+=monto; agg[est].lit+=litros; agg[est].n++;
|
||||
if(pago==="Efectivo") agg[est].ef+=monto;
|
||||
}
|
||||
return agg;
|
||||
}
|
||||
|
||||
/* ------------------------------ HISTÓRICO 30 D ----------------------------- */
|
||||
// Datos FIJOS (se escriben una vez). Solo las FECHAS se recorren según hoy.
|
||||
var HIST_FIXED = null;
|
||||
function histFixed(){
|
||||
if(HIST_FIXED) return HIST_FIXED;
|
||||
// 30 valores fijos por estación (patrón realista, no se regeneran)
|
||||
var base={ cholula:298000, atlixcayotl:455000, zavaleta:259000 };
|
||||
var pat=[1.02,0.97,1.00,0.95,1.10,1.28,1.16,0.99,0.96,1.01,0.94,1.12,1.30,1.18,
|
||||
1.00,0.98,0.93,1.09,1.27,1.15,0.97,0.95,1.03,0.92,1.11,1.29,1.17,0.98,0.96,1.04];
|
||||
var arr=[];
|
||||
for(var k=0;k<30;k++){
|
||||
arr.push({
|
||||
cholula:Math.round(base.cholula*pat[k]),
|
||||
atlixcayotl:Math.round(base.atlixcayotl*pat[(k+5)%30]),
|
||||
zavaleta:Math.round(base.zavaleta*pat[(k+11)%30])
|
||||
});
|
||||
}
|
||||
HIST_FIXED=arr; return arr;
|
||||
}
|
||||
function buildHistorico(){
|
||||
var sh=getSheet(SHEETS.historico); sh.clear();
|
||||
sh.getRange("A1").setValue("HISTÓRICO — CIERRES DIARIOS (últimos 30 días)").setFontSize(14).setFontWeight("bold").setFontColor("#0b3b32");
|
||||
sh.getRange("A2").setValue("Valores fijos · las fechas se recorren según hoy ("+fmt(now(),"EEE d 'de' MMM")+")").setFontColor("#667781").setFontSize(10);
|
||||
var head=["Fecha","Cholula (MXN)","Atlixcáyotl (MXN)","Zavaleta (MXN)","Total grupo"];
|
||||
sh.getRange(4,1,1,5).setValues([head]).setFontWeight("bold").setFontColor("#fff").setBackground("#075e54");
|
||||
var fixed=histFixed(), rows=[];
|
||||
for(var k=1;k<=30;k++){
|
||||
var d=new Date(); d.setDate(d.getDate()-k);
|
||||
var f=fixed[k-1];
|
||||
rows.push([ fmt(d,"EEE d 'de' MMM"), f.cholula, f.atlixcayotl, f.zavaleta, f.cholula+f.atlixcayotl+f.zavaleta ]);
|
||||
}
|
||||
sh.getRange(5,1,rows.length,5).setValues(rows);
|
||||
sh.getRange(5,2,rows.length,4).setNumberFormat("$#,##0");
|
||||
sh.setColumnWidth(1,150); for(var c=2;c<=5;c++) sh.setColumnWidth(c,150);
|
||||
sh.setFrozenRows(4);
|
||||
}
|
||||
|
||||
/* ------------------------- archivo al cambiar de día ----------------------- */
|
||||
function archiveIfNewDay(){
|
||||
var key=todayKey();
|
||||
var last=props().getProperty("activeDay");
|
||||
if(last && last!==key){
|
||||
// mover VENTAS del día anterior a ARCHIVO
|
||||
var v=getSheet(SHEETS.ventas), a=getSheet(SHEETS.archivo);
|
||||
var lr=v.getLastRow();
|
||||
if(lr>1){
|
||||
var data=v.getRange(1,1,lr,13).getValues();
|
||||
if(a.getLastRow()<1){ a.getRange(1,1,1,13).setValues([data[0]]).setFontWeight("bold"); }
|
||||
var body=data.slice(1);
|
||||
if(body.length) a.getRange(a.getLastRow()+1,1,body.length,13).setValues(body);
|
||||
v.clear();
|
||||
}
|
||||
// limpiar acumulados de turno y tanques del día viejo (nuevos al iniciar)
|
||||
var all=props().getProperties();
|
||||
Object.keys(all).forEach(function(p){ if(p.indexOf("turno:"+last)===0) props().deleteProperty(p); });
|
||||
initTanks();
|
||||
}
|
||||
props().setProperty("activeDay", key);
|
||||
}
|
||||
|
||||
/* ================================ ORQUESTACIÓN ============================= */
|
||||
function refrescar(){
|
||||
ss().setSpreadsheetTimeZone(TZ);
|
||||
archiveIfNewDay();
|
||||
var n=salesThisMinute();
|
||||
if(n>0) generateSales(n, false);
|
||||
buildTanques();
|
||||
buildTablero();
|
||||
buildTurnos();
|
||||
// histórico solo si falta o cambió el día
|
||||
if(props().getProperty("histDate")!==todayKey()){ buildHistorico(); props().setProperty("histDate",todayKey()); }
|
||||
var t=ss().getSheetByName(SHEETS.ventas); if(t) ss().setActiveSheet(t);
|
||||
}
|
||||
|
||||
/* ---- BURST de arranque: una venta cada 15 s por ~5 min, bombas distintas --- */
|
||||
function burstTick(){
|
||||
var endAt=+props().getProperty("burstEnd")||0;
|
||||
if(Date.now()>endAt){ stopBurst(); return; }
|
||||
generateSales(1, true); // rotación estricta de bombas
|
||||
buildTablero();
|
||||
}
|
||||
function startBurst(){
|
||||
stopBurst();
|
||||
props().setProperty("burstEnd", String(Date.now()+BURST_MINUTES*60*1000));
|
||||
// trigger de alta frecuencia: Apps Script permite mínimo cada 1 min por tiempo,
|
||||
// pero podemos encadenar varios disparos de "segundos" con triggers de reloj.
|
||||
// Workaround: usamos un trigger cada minuto que internamente dispara 4 ventas
|
||||
// espaciadas (cada 15 s) con Utilities.sleep, durante la ventana del burst.
|
||||
ScriptApp.newTrigger("burstMinute").timeBased().everyMinutes(1).create();
|
||||
burstMinute(); // primer minuto inmediato
|
||||
}
|
||||
function burstMinute(){
|
||||
var endAt=+props().getProperty("burstEnd")||0;
|
||||
for(var i=0;i<4;i++){ // 4 ventas × 15 s = 1 minuto
|
||||
if(Date.now()>endAt) break;
|
||||
generateSales(1, true);
|
||||
buildTablero();
|
||||
if(i<3) Utilities.sleep(BURST_SECONDS*1000);
|
||||
}
|
||||
if(Date.now()>endAt) stopBurst();
|
||||
}
|
||||
function stopBurst(){
|
||||
ScriptApp.getProjectTriggers().forEach(function(t){
|
||||
if(t.getHandlerFunction()==="burstMinute"||t.getHandlerFunction()==="burstTick") ScriptApp.deleteTrigger(t);
|
||||
});
|
||||
props().deleteProperty("burstEnd");
|
||||
}
|
||||
|
||||
function iniciarSimulacion(){
|
||||
detenerSimulacion();
|
||||
props().deleteProperty("histDate");
|
||||
initTanks();
|
||||
props().setProperty("forceTank","1");
|
||||
refrescar();
|
||||
ScriptApp.newTrigger("refrescar").timeBased().everyMinutes(1).create();
|
||||
startBurst();
|
||||
ss().toast("Simulación iniciada: burst de "+BURST_MINUTES+" min y luego ritmo normal.","Collina",6);
|
||||
}
|
||||
function detenerSimulacion(){
|
||||
ScriptApp.getProjectTriggers().forEach(function(t){
|
||||
var f=t.getHandlerFunction();
|
||||
if(f==="refrescar"||f==="burstMinute"||f==="burstTick") ScriptApp.deleteTrigger(t);
|
||||
});
|
||||
props().deleteProperty("burstEnd");
|
||||
}
|
||||
|
||||
function onOpen(){
|
||||
SpreadsheetApp.getUi().createMenu("⛽ Collina")
|
||||
.addItem("▶️ Iniciar simulación","iniciarSimulacion")
|
||||
.addItem("🔄 Generar ahora (1 tick)","refrescar")
|
||||
.addItem("⏹️ Detener simulación","detenerSimulacion")
|
||||
.addToUi();
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# Collina — Simulación de operación en Google Sheets (instalación)
|
||||
|
||||
Hoja **autónoma** que **genera y acumula** operación realista de 3 estaciones de
|
||||
Puebla (Cholula, Atlixcáyotl, Zavaleta). No depende de tu VPS ni de semillas:
|
||||
solo genera. Toda la lógica vive dentro de la hoja (Apps Script).
|
||||
|
||||
## Instalar
|
||||
1. **sheets.new** (hoja nueva).
|
||||
2. **Extensiones ▸ Apps Script**, borra lo que haya y **pega `CollinaSimV2.gs`**. Guarda (💾).
|
||||
3. Recarga la hoja (F5). Aparece el menú **⛽ Collina**.
|
||||
4. **⛽ Collina ▸ ▶️ Iniciar simulación**. Autoriza el script (es tuyo).
|
||||
|
||||
## Pestañas
|
||||
- **📊 TABLERO** — resumen del día por estación (ingreso, litros, cargas, ticket, % efectivo) y el **precio del día**. Se recalcula del acumulado.
|
||||
- **🟢 VENTAS** — bitácora que **crece**: Fecha-hora · Estación · Bomba · Manguera/grado · Combustible · Litros · Precio unitario · Monto · Modo de venta · Método de pago · Despachador (ID) · Turno · Drive-off.
|
||||
- **🛢️ TANQUES** — lecturas ATG cada 30 min: nivel, volumen bruto, **neto @20°C**, agua, temperatura, ullage, % lleno, y **descargas** (cuando un tanque baja del 25% se rellena y se registra el volumen entregado). El nivel **baja con las ventas**.
|
||||
- **🧾 TURNOS** — cortes por turno (06–14 / 14–22 / 22–06) y despachador: litros, ingreso esperado, cobrado efectivo/tarjeta/transferencia, depositado a caja fuerte y **Diferencia** (sin lógica de alerta todavía).
|
||||
- **📅 HISTÓRICO** — 30 cierres **fijos**; solo las fechas se recorren según el día en que abres la hoja.
|
||||
- **🗄️ ARCHIVO** — al cambiar de día, las ventas del día anterior se mueven aquí y la bitácora viva se limpia.
|
||||
|
||||
## Comportamiento clave
|
||||
- **Arranque para demo**: al dar ▶️, durante ~5 min se genera **una venta cada 15 s en bombas distintas** (rotación estricta, nunca la misma bomba dos veces seguidas). Pasados los 5 min, ritmo normal cada minuto según la curva horaria de cada zona.
|
||||
- **Precio del día**: se fija al primer arranque de la fecha (varía ±1.2% sobre el precio base de Puebla) y se mantiene todo el día. Cambia al cambiar de día.
|
||||
- **Realismo de zona**: Atlixcáyotl (corporativa) explota en commute (7–9h, 18–20h); Cholula (universitaria/turística) carga tarde-noche; Zavaleta (comercial) pareja con pico vespertino y la **bomba #4 fuera de servicio** por la tarde.
|
||||
- **Pago estilo barrio MX**: ~78% efectivo, ~16% tarjeta, ~6% transferencia.
|
||||
|
||||
## Notas técnicas
|
||||
- Hora de **México** (America/Mexico_City).
|
||||
- El burst usa el truco estándar de Apps Script (un trigger por minuto que dispara 4 ventas espaciadas 15 s), porque los triggers de tiempo no bajan de 1 minuto.
|
||||
- **⏹️ Detener simulación** quita todos los triggers. **🔄 Generar ahora** produce un tick manual.
|
||||
|
||||
## Compartir
|
||||
**Compartir ▸ Cualquiera con el enlace ▸ Lector** para que el prospecto la vea.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Demo en Google Sheets (DESECHABLE)
|
||||
|
||||
`CollinaSimV2.gs` es la simulación autónoma usada SOLO para demo en vivo. No es
|
||||
parte del producto: la lógica real vive en el backend (`../`). En producción el
|
||||
Sheets será, a lo sumo, un espejo de la DB de Collina.
|
||||
|
||||
Se incluye aquí por completitud. Ver `INSTALAR-V2.md` para instalarlo.
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Motor generativo de Collina (Roadmap §1).
|
||||
|
||||
Produce operación realista (ventas, lecturas de tanque, cortes de turno) y la
|
||||
escribe a PostgreSQL ITERANDO sobre el registro de estaciones. Arranca/para con
|
||||
un botón (ver app/main.py). Es la "materia prima" del resto del backend.
|
||||
"""
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Acceso a PostgreSQL para el motor.
|
||||
|
||||
Responsabilidad única: dar conexiones psycopg listas (con search_path al esquema
|
||||
`collina`) y un par de helpers de salud. No tiene lógica de negocio ni SQL de
|
||||
dominio (eso vive en seed.py / runner.py). Lee DATABASE_URL del entorno (.env).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
# Cargar .env de la raíz del proyecto si está python-dotenv disponible.
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(Path(__file__).resolve().parent.parent / ".env")
|
||||
except Exception: # dotenv es opcional; en prod las vars vienen del entorno (Coolify)
|
||||
pass
|
||||
|
||||
# El esquema vive en `collina` (ver db/schema.sql). Toda conexión arranca ahí.
|
||||
SEARCH_PATH = "collina,public"
|
||||
|
||||
|
||||
class DatabaseNotConfigured(RuntimeError):
|
||||
"""DATABASE_URL no está definido."""
|
||||
|
||||
|
||||
def get_dsn() -> str:
|
||||
dsn = os.environ.get("DATABASE_URL")
|
||||
if not dsn:
|
||||
raise DatabaseNotConfigured(
|
||||
"DATABASE_URL no está definido. Copia .env.example a .env y complétalo."
|
||||
)
|
||||
return dsn
|
||||
|
||||
|
||||
def connect() -> psycopg.Connection:
|
||||
"""Conexión nueva con row_factory dict y search_path al esquema collina."""
|
||||
conn = psycopg.connect(get_dsn(), row_factory=dict_row)
|
||||
conn.execute(f"SET search_path TO {SEARCH_PATH}")
|
||||
return conn
|
||||
|
||||
|
||||
def ping() -> bool:
|
||||
"""True si la DB responde. No lanza: úsalo para el health check del status."""
|
||||
try:
|
||||
with connect() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
@@ -0,0 +1,222 @@
|
||||
"""Generadores PUROS de operación (sin I/O, testeables).
|
||||
|
||||
Cada función fabrica UNA fila lista para insertar, dado el registro, los knobs
|
||||
(reg.simulacion) y un RNG. No tocan la DB ni el reloj: reciben `ts`/`rng` para
|
||||
ser deterministas en pruebas. Aquí viven las fugas inyectadas (drive-off, merma
|
||||
'no explicada' sesgada a turno, faltante de caja sesgado a despachador) que
|
||||
hacen que la plataforma tenga señal lucrativa que vigilar.
|
||||
|
||||
Las magnitudes de fuga son DÉBILES (ver bloque `simulacion` del YAML): defaults
|
||||
editables, no datos duros. Los márgenes y precios vienen del REGISTRO.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import math
|
||||
import random
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- utilidades
|
||||
def _weighted_choice(rng: random.Random, items: dict):
|
||||
"""Elige una clave de {clave: peso} proporcional al peso."""
|
||||
total = sum(items.values())
|
||||
r = rng.uniform(0, total)
|
||||
acc = 0.0
|
||||
for k, w in items.items():
|
||||
acc += w
|
||||
if r <= acc:
|
||||
return k
|
||||
return next(iter(items)) # fallback por redondeo
|
||||
|
||||
|
||||
def tanque_code(fuel_name: str) -> str:
|
||||
"""'Magna' -> 'M-TK', 'Premium' -> 'P-TK', 'Diesel' -> 'D-TK'."""
|
||||
return f"{fuel_name[0].upper()}-TK"
|
||||
|
||||
|
||||
# ------------------------------------------------------------ demanda / pesos
|
||||
def factor_semana(reg, station, fecha: dt.date) -> float:
|
||||
dias = ["Lun", "Mar", "Mie", "Jue", "Vie", "Sab", "Dom"]
|
||||
return reg.perfil_semana(station)[dias[fecha.weekday()]]
|
||||
|
||||
|
||||
def peso_estacion(reg, station, ts: dt.datetime) -> float:
|
||||
"""Peso instantáneo de una estación para repartir ventas en vivo:
|
||||
volumen base × perfil horario × estacionalidad del día."""
|
||||
perfil = reg.perfil_horario(station)
|
||||
return station.ventas_dia_aprox * perfil[ts.hour] * factor_semana(reg, station, ts.date())
|
||||
|
||||
|
||||
def ventas_esperadas_en_hora(reg, station, fecha: dt.date, hora: int) -> float:
|
||||
"""Conteo esperado de ventas de una estación en una hora dada (para el
|
||||
catch-up del día). Reparte ventas_dia_aprox según el perfil horario y la
|
||||
escala por el factor del día de la semana."""
|
||||
perfil = reg.perfil_horario(station)
|
||||
frac_hora = perfil[hora] / sum(perfil)
|
||||
return station.ventas_dia_aprox * factor_semana(reg, station, fecha) * frac_hora
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- selección
|
||||
def pick_fuel(reg, station, rng: random.Random) -> str:
|
||||
return _weighted_choice(rng, station.mezcla_combustible)
|
||||
|
||||
|
||||
def pick_bomba(station, rng: random.Random) -> int:
|
||||
"""Bomba 1..N; salta la bomba fuera de servicio (si la hay)."""
|
||||
candidatas = [b for b in range(1, station.bombas + 1)
|
||||
if b != station.bomba_fuera_servicio]
|
||||
if not candidatas: # red de seguridad (no debería pasar)
|
||||
candidatas = list(range(1, station.bombas + 1))
|
||||
return rng.choice(candidatas)
|
||||
|
||||
|
||||
def pick_litros(reg, sale_price: float, rng: random.Random) -> float:
|
||||
"""Litros de la carga, como MEZCLA: monto fijo ($200/$300/...) o tanque lleno.
|
||||
El ticket real así queda por debajo de 'llenar tanque', como en la realidad."""
|
||||
carga = reg.simulacion.carga
|
||||
if rng.random() < carga["monto_fijo_prob"]:
|
||||
monto = rng.choice(carga["montos_fijos_mxn"])
|
||||
litros = monto / sale_price
|
||||
else:
|
||||
litros = rng.uniform(carga["tanque_lleno_litros_min"],
|
||||
carga["tanque_lleno_litros_max"])
|
||||
return round(litros, 2)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- ventas
|
||||
def make_sale(reg, station, ts: dt.datetime, price_map: dict, rng: random.Random) -> dict:
|
||||
"""Fabrica una venta lista para insertar en `sale`.
|
||||
|
||||
price_map: {fuel_name: (sale_price, cost_price)} del día (de seed.precio_del_dia).
|
||||
Deriva turno/despachador de la hora; inyecta drive-off con prob. configurable.
|
||||
ganancia = (precio - costo) · litros (margen del registro, congelado al día).
|
||||
"""
|
||||
fuel_name = pick_fuel(reg, station, rng)
|
||||
sale_price, cost_price = price_map[fuel_name]
|
||||
litros = pick_litros(reg, sale_price, rng)
|
||||
|
||||
monto = round(litros * sale_price, 2)
|
||||
ganancia = round((sale_price - cost_price) * litros, 2)
|
||||
|
||||
turno = reg.turno_por_hora(ts.hour)
|
||||
bomba = pick_bomba(station, rng)
|
||||
drive_off = rng.random() < reg.simulacion.fugas["drive_off_prob"]
|
||||
|
||||
return {
|
||||
"station_id": station.id,
|
||||
"ts": ts,
|
||||
"bomba": bomba,
|
||||
"manguera": f"{bomba}{rng.choice('AB')}",
|
||||
"fuel_name": fuel_name,
|
||||
"litros": litros,
|
||||
"precio_unitario": sale_price,
|
||||
"costo_unitario": cost_price,
|
||||
"monto": monto,
|
||||
"ganancia": ganancia,
|
||||
"modo_venta": _weighted_choice(rng, reg.modos_venta),
|
||||
"metodo_pago": _weighted_choice(rng, reg.mezcla_pago),
|
||||
"despachador": turno.despachador_default,
|
||||
"turno": turno.id,
|
||||
"drive_off": drive_off,
|
||||
}
|
||||
|
||||
|
||||
# ------------------------------------------------------------- temperatura
|
||||
def temperatura_en(reg, ts: dt.datetime) -> float:
|
||||
"""Temperatura ambiente sinusoidal del día (máx en hora_pico, mín 12 h después).
|
||||
Mueve el delta vol_bruto/vol_neto que la plataforma usa para separar merma
|
||||
térmica (legítima) del faltante anómalo."""
|
||||
t = reg.simulacion.temperatura
|
||||
hora = ts.hour + ts.minute / 60.0
|
||||
frac = math.cos((hora - t["hora_pico"]) / 24.0 * 2 * math.pi) # 1 en el pico, -1 opuesto
|
||||
mid = (t["min_c"] + t["max_c"]) / 2.0
|
||||
amp = (t["max_c"] - t["min_c"]) / 2.0
|
||||
return round(mid + amp * frac, 1)
|
||||
|
||||
|
||||
# ----------------------------------------------------------- lecturas tanque
|
||||
def make_tank_reading(reg, station, fuel_name: str, ts: dt.datetime,
|
||||
inv_inicial: float, litros_vendidos_dia: float,
|
||||
litros_vendidos_turno_sesgado: float, vol_entregado_dia: float,
|
||||
rng: random.Random, evento: str = "Lectura normal",
|
||||
vol_entregado_l: float | None = None) -> dict:
|
||||
"""Lectura de tanque (ATG) coherente con la operación.
|
||||
|
||||
Modelo:
|
||||
vol_teorico = inventario_inicial - ventas_dia + descargas_dia (lo que dicen los libros)
|
||||
vol_neto = vol_teorico - merma_evaporacion - merma_no_explicada (producto real @20°C)
|
||||
vol_bruto = vol_neto · (1 + coef_termico·(T - T_ref)) (medido a T actual)
|
||||
|
||||
- merma_evaporacion: % del volumen vendido → merma legítima.
|
||||
- merma_no_explicada (ORDEÑA): % de lo vendido en el turno sesgado → se
|
||||
concentra de noche, generando la señal de reincidencia que vale dinero.
|
||||
"""
|
||||
sim = reg.simulacion
|
||||
capacidad = reg.capacidad_tanque[fuel_name]
|
||||
|
||||
vol_teorico = inv_inicial - litros_vendidos_dia + vol_entregado_dia
|
||||
merma_evap = sim.fugas["merma_evaporacion_pct"] * litros_vendidos_dia
|
||||
merma_ordena = sim.fugas["merma_no_explicada_pct"] * litros_vendidos_turno_sesgado
|
||||
vol_neto = vol_teorico - merma_evap - merma_ordena
|
||||
|
||||
temp = temperatura_en(reg, ts)
|
||||
coef = sim.temperatura["coef_termico"][fuel_name]
|
||||
ref = sim.temperatura["referencia_c"]
|
||||
vol_bruto = vol_neto * (1 + coef * (temp - ref))
|
||||
|
||||
pct_lleno = max(0.0, min(100.0, vol_bruto / capacidad * 100))
|
||||
nivel_cm = round(pct_lleno / 100.0 * 250.0, 1) # tanque nominal ~250 cm de alto
|
||||
|
||||
return {
|
||||
"station_id": station.id,
|
||||
"ts": ts,
|
||||
"tanque": tanque_code(fuel_name),
|
||||
"fuel_name": fuel_name,
|
||||
"nivel_cm": nivel_cm,
|
||||
"vol_bruto_l": round(vol_bruto, 1),
|
||||
"vol_neto_l": round(vol_neto, 1),
|
||||
"nivel_agua_cm": round(rng.uniform(0.3, 1.4), 1),
|
||||
"temperatura_c": temp,
|
||||
"ullage_l": round(capacidad - vol_bruto, 1),
|
||||
"pct_lleno": round(pct_lleno, 1),
|
||||
"evento": evento,
|
||||
"vol_entregado_l": round(vol_entregado_l, 1) if vol_entregado_l is not None else None,
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------- corte caja
|
||||
def make_shift_cut(reg, station, fecha: dt.date, turno_id: str, despachador: str,
|
||||
agg: dict, rng: random.Random) -> dict:
|
||||
"""Corte de turno/caja a partir de los agregados de venta del turno.
|
||||
|
||||
agg: {litros, ingreso_esperado, cobrado_efectivo, cobrado_tarjeta, cobrado_transfer}.
|
||||
Inyecta un faltante de caja (% del efectivo) con SESGO a un despachador, para
|
||||
que la reincidencia sea detectable. El umbral de alerta NO se hardcodea aquí:
|
||||
es decisión de la plataforma (knob), no del generador.
|
||||
"""
|
||||
sim = reg.simulacion.fugas
|
||||
pct = sim["faltante_caja_pct_efectivo"]
|
||||
|
||||
# El despachador sesgado falta más y con más varianza (señal accionable).
|
||||
if despachador == sim["faltante_sesgo_despachador"]:
|
||||
factor = rng.uniform(2.0, 4.0)
|
||||
else:
|
||||
factor = rng.uniform(0.0, 1.0)
|
||||
faltante = round(agg["cobrado_efectivo"] * pct * factor, 2)
|
||||
|
||||
depositado = round(agg["cobrado_efectivo"] - faltante, 2)
|
||||
diferencia = round(depositado - agg["cobrado_efectivo"], 2) # negativo = faltante
|
||||
|
||||
return {
|
||||
"station_id": station.id,
|
||||
"fecha": fecha,
|
||||
"turno": turno_id,
|
||||
"despachador": despachador,
|
||||
"litros_vendidos": round(agg["litros"], 2),
|
||||
"ingreso_esperado": round(agg["ingreso_esperado"], 2),
|
||||
"cobrado_efectivo": round(agg["cobrado_efectivo"], 2),
|
||||
"cobrado_tarjeta": round(agg["cobrado_tarjeta"], 2),
|
||||
"cobrado_transfer": round(agg["cobrado_transfer"], 2),
|
||||
"depositado_caja": depositado,
|
||||
"diferencia": diferencia,
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
"""Orquestador del motor: el "botón" arranque/paro.
|
||||
|
||||
Diseño clave (lo que pediste): el estado vive en la DB, no en memoria. Al
|
||||
arrancar, el motor RECONSTRUYE el día desde la DB y solo rellena el hueco
|
||||
(00:00 → ahora) de forma incremental e idempotente; luego sigue EN VIVO. Si lo
|
||||
paras y vuelves a arrancar, reaprovecha lo ya escrito y solo extiende el alcance.
|
||||
|
||||
- Catch-up del día: usa VOLUMEN REALISTA (ventas_dia_aprox × perfil) para que
|
||||
los totales cuadren con lo declarado por estación.
|
||||
- En vivo: ritmo de DEMO (ráfaga 1/15s en bombas distintas → 1–5/min).
|
||||
|
||||
Todo itera sobre `reg.stations()`: agregar la estación #N al YAML = se genera
|
||||
sola, sin tocar este archivo.
|
||||
|
||||
DB: psycopg es síncrono; el loop es async. Las operaciones de DB corren en un
|
||||
hilo (asyncio.to_thread) serializadas por un lock, sobre una conexión persistente.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime as dt
|
||||
import random
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from config.registry import load_registry
|
||||
from engine import db, seed
|
||||
from engine.generators import (
|
||||
make_sale, make_shift_cut, make_tank_reading,
|
||||
peso_estacion, ventas_esperadas_en_hora,
|
||||
)
|
||||
|
||||
|
||||
# ------------------------------------------------------------- SQL de dominio
|
||||
def _insert_sale(conn, row: dict) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO sale (station_id, ts, bomba, manguera, fuel_name, litros,
|
||||
precio_unitario, costo_unitario, monto, ganancia,
|
||||
modo_venta, metodo_pago, despachador, turno, drive_off)
|
||||
VALUES (%(station_id)s, %(ts)s, %(bomba)s, %(manguera)s, %(fuel_name)s,
|
||||
%(litros)s, %(precio_unitario)s, %(costo_unitario)s, %(monto)s,
|
||||
%(ganancia)s, %(modo_venta)s, %(metodo_pago)s, %(despachador)s,
|
||||
%(turno)s, %(drive_off)s)
|
||||
""",
|
||||
row,
|
||||
)
|
||||
|
||||
|
||||
def _insert_tank_reading(conn, row: dict) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO tank_reading (station_id, ts, tanque, fuel_name, nivel_cm,
|
||||
vol_bruto_l, vol_neto_l, nivel_agua_cm,
|
||||
temperatura_c, ullage_l, pct_lleno, evento, vol_entregado_l)
|
||||
VALUES (%(station_id)s, %(ts)s, %(tanque)s, %(fuel_name)s, %(nivel_cm)s,
|
||||
%(vol_bruto_l)s, %(vol_neto_l)s, %(nivel_agua_cm)s, %(temperatura_c)s,
|
||||
%(ullage_l)s, %(pct_lleno)s, %(evento)s, %(vol_entregado_l)s)
|
||||
""",
|
||||
row,
|
||||
)
|
||||
|
||||
|
||||
def _insert_shift_cut(conn, row: dict) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO shift_cut (station_id, fecha, turno, despachador, litros_vendidos,
|
||||
ingreso_esperado, cobrado_efectivo, cobrado_tarjeta,
|
||||
cobrado_transfer, depositado_caja, diferencia)
|
||||
VALUES (%(station_id)s, %(fecha)s, %(turno)s, %(despachador)s, %(litros_vendidos)s,
|
||||
%(ingreso_esperado)s, %(cobrado_efectivo)s, %(cobrado_tarjeta)s,
|
||||
%(cobrado_transfer)s, %(depositado_caja)s, %(diferencia)s)
|
||||
ON CONFLICT (station_id, fecha, turno, despachador) DO NOTHING
|
||||
""",
|
||||
row,
|
||||
)
|
||||
|
||||
|
||||
def _scalar(conn, sql: str, params: tuple) -> float:
|
||||
row = conn.execute(sql, params).fetchone()
|
||||
val = next(iter(row.values())) if row else None
|
||||
return float(val) if val is not None else 0.0
|
||||
|
||||
|
||||
def _sold(conn, sid, fuel, t0, t1) -> float:
|
||||
return _scalar(conn, "SELECT COALESCE(SUM(litros),0) s FROM sale "
|
||||
"WHERE station_id=%s AND fuel_name=%s AND ts>=%s AND ts<%s",
|
||||
(sid, fuel, t0, t1))
|
||||
|
||||
|
||||
def _sold_turno(conn, sid, fuel, turno_id, t0, t1) -> float:
|
||||
return _scalar(conn, "SELECT COALESCE(SUM(litros),0) s FROM sale "
|
||||
"WHERE station_id=%s AND fuel_name=%s AND turno=%s AND ts>=%s AND ts<%s",
|
||||
(sid, fuel, turno_id, t0, t1))
|
||||
|
||||
|
||||
def _delivered(conn, sid, fuel, t0, t1) -> float:
|
||||
return _scalar(conn, "SELECT COALESCE(SUM(vol_entregado_l),0) s FROM tank_reading "
|
||||
"WHERE station_id=%s AND fuel_name=%s AND vol_entregado_l IS NOT NULL "
|
||||
"AND ts>=%s AND ts<%s",
|
||||
(sid, fuel, t0, t1))
|
||||
|
||||
|
||||
def _max_ts(conn, tabla, sid, t0, t1):
|
||||
row = conn.execute(f"SELECT MAX(ts) m FROM {tabla} WHERE station_id=%s AND ts>=%s AND ts<%s",
|
||||
(sid, t0, t1)).fetchone()
|
||||
return row["m"] if row else None
|
||||
|
||||
|
||||
def _shift_agg(conn, sid, t0, t1) -> dict:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(litros),0) litros,
|
||||
COALESCE(SUM(monto),0) ingreso_esperado,
|
||||
COALESCE(SUM(monto) FILTER (WHERE NOT drive_off AND metodo_pago='Efectivo'),0) cobrado_efectivo,
|
||||
COALESCE(SUM(monto) FILTER (WHERE NOT drive_off AND metodo_pago='Tarjeta'),0) cobrado_tarjeta,
|
||||
COALESCE(SUM(monto) FILTER (WHERE NOT drive_off AND metodo_pago='Transferencia'),0) cobrado_transfer
|
||||
FROM sale WHERE station_id=%s AND ts>=%s AND ts<%s
|
||||
""",
|
||||
(sid, t0, t1),
|
||||
).fetchone()
|
||||
return {k: float(v) for k, v in row.items()}
|
||||
|
||||
|
||||
def _shift_cut_exists(conn, sid, fecha, turno_id, despachador) -> bool:
|
||||
return conn.execute("SELECT 1 FROM shift_cut WHERE station_id=%s AND fecha=%s "
|
||||
"AND turno=%s AND despachador=%s",
|
||||
(sid, fecha, turno_id, despachador)).fetchone() is not None
|
||||
|
||||
|
||||
# --------------------------------------------------------------- el motor
|
||||
class EngineRunner:
|
||||
"""Singleton que arranca/para la generación. Una instancia por proceso."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.reg = load_registry()
|
||||
self.sim = self.reg.simulacion
|
||||
self.tz = ZoneInfo(self.reg.meta["zona_horaria"])
|
||||
self._task: asyncio.Task | None = None
|
||||
self._db_lock = asyncio.Lock()
|
||||
self._conn = None
|
||||
self._rng = random.Random()
|
||||
self._reset_stats()
|
||||
self._last_bomba: dict[str, int] = {}
|
||||
self._last_turno = None
|
||||
self._next_tank_ts = None
|
||||
|
||||
# --- estado / status ---
|
||||
def _reset_stats(self) -> None:
|
||||
self.stats = {
|
||||
"iniciado_at": None,
|
||||
"fase": "detenido",
|
||||
"ventas_sesion": 0,
|
||||
"por_estacion": {},
|
||||
"ultima_venta_ts": None,
|
||||
"ultimo_error": None,
|
||||
}
|
||||
|
||||
@property
|
||||
def running(self) -> bool:
|
||||
return self._task is not None and not self._task.done()
|
||||
|
||||
def now(self) -> dt.datetime:
|
||||
return dt.datetime.now(self.tz)
|
||||
|
||||
def status(self) -> dict:
|
||||
return {
|
||||
"running": self.running,
|
||||
"db_ok": db.ping(),
|
||||
"fase": self.stats["fase"],
|
||||
"iniciado_at": self.stats["iniciado_at"],
|
||||
"ventas_sesion": self.stats["ventas_sesion"],
|
||||
"por_estacion": self.stats["por_estacion"],
|
||||
"ultima_venta_ts": self.stats["ultima_venta_ts"],
|
||||
"ultimo_error": self.stats["ultimo_error"],
|
||||
"estaciones_activas": [s.id for s in self.reg.stations()],
|
||||
}
|
||||
|
||||
# --- ciclo de vida ---
|
||||
async def start(self) -> dict:
|
||||
if self.running:
|
||||
return {"ok": True, "mensaje": "El motor ya estaba corriendo.", **self.status()}
|
||||
if not db.ping():
|
||||
return {"ok": False, "mensaje": "Sin conexión a la DB. Revisa DATABASE_URL y aplica db/schema.sql.",
|
||||
**self.status()}
|
||||
|
||||
self._reset_stats()
|
||||
self.stats["iniciado_at"] = self.now().isoformat(timespec="seconds")
|
||||
self._conn = await asyncio.to_thread(db.connect)
|
||||
|
||||
# 1) Sembrar registro + precio del día. 2) Catch-up incremental de hoy.
|
||||
await self._db(self._do_seed)
|
||||
await self._db(self._do_catch_up, self.now())
|
||||
|
||||
# 3) Loop en vivo.
|
||||
self._last_turno = self.reg.turno_por_hora(self.now().hour)
|
||||
self._next_tank_ts = self._proximo_marca_tanque(self.now())
|
||||
self._task = asyncio.create_task(self._live_loop())
|
||||
return {"ok": True, "mensaje": "Motor arrancado: día reconstruido + generación en vivo.",
|
||||
**self.status()}
|
||||
|
||||
async def stop(self) -> dict:
|
||||
if self._task:
|
||||
self._task.cancel()
|
||||
try:
|
||||
await self._task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
self._task = None
|
||||
if self._conn:
|
||||
await asyncio.to_thread(self._conn.close)
|
||||
self._conn = None
|
||||
self.stats["fase"] = "detenido"
|
||||
return {"ok": True, "mensaje": "Motor detenido.", **self.status()}
|
||||
|
||||
# --- helper de DB (serializado, en hilo) ---
|
||||
async def _db(self, fn, *args):
|
||||
async with self._db_lock:
|
||||
return await asyncio.to_thread(fn, *args)
|
||||
|
||||
# ---------------------------------------------------------- seed + catch-up
|
||||
def _do_seed(self) -> None:
|
||||
seed.seed_all(self._conn, self.reg, self.now().date())
|
||||
|
||||
def _do_catch_up(self, now: dt.datetime) -> None:
|
||||
"""Rellena el hueco de HOY (incremental) directo a la DB."""
|
||||
day0 = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
for s in self.reg.stations():
|
||||
# --- ventas: del último ts registrado hoy hasta ahora ---
|
||||
last = _max_ts(self._conn, "sale", s.id, day0, now) or day0
|
||||
for row in self._gap_sales(s, last, now):
|
||||
_insert_sale(self._conn, row)
|
||||
self._contar_venta(row)
|
||||
|
||||
# las lecturas/cortes dependen de que las ventas ya estén (visibles en la tx)
|
||||
for s in self.reg.stations():
|
||||
for fuel in self.reg.combustibles:
|
||||
last_tank = _max_ts(self._conn, "tank_reading", s.id, day0, now)
|
||||
desde = last_tank or day0
|
||||
for mark in self._marcas_tanque(desde, now, incluir_desde=last_tank is None):
|
||||
self._emit_tank_reading(s, fuel, mark)
|
||||
|
||||
for s in self.reg.stations():
|
||||
for turno, t0, t1 in self._turnos_completos_hoy(now):
|
||||
if not _shift_cut_exists(self._conn, s.id, t0.date(), turno.id, turno.despachador_default):
|
||||
agg = _shift_agg(self._conn, s.id, t0, t1)
|
||||
_insert_shift_cut(self._conn, make_shift_cut(
|
||||
self.reg, s, t0.date(), turno.id, turno.despachador_default, agg, self._rng))
|
||||
|
||||
self._conn.commit()
|
||||
|
||||
def _gap_sales(self, station, last_ts: dt.datetime, now: dt.datetime) -> list[dict]:
|
||||
"""Ventas del hueco [last_ts, now) con VOLUMEN REALISTA por hora."""
|
||||
fecha = now.date()
|
||||
price_map = {f: seed.precio_del_dia(self.reg, station.id, f, fecha)
|
||||
for f in self.reg.combustibles}
|
||||
jitter = self.sim.catchup["jitter_pct"]
|
||||
out: list[dict] = []
|
||||
t = last_ts
|
||||
while t < now:
|
||||
hora_fin = min(now, (t.replace(minute=0, second=0, microsecond=0) + dt.timedelta(hours=1)))
|
||||
frac = (hora_fin - t).total_seconds() / 3600.0
|
||||
esperado = ventas_esperadas_en_hora(self.reg, station, fecha, t.hour) * frac
|
||||
n = max(0, round(esperado * (1 + self._rng.uniform(-jitter, jitter))))
|
||||
span = (hora_fin - t).total_seconds()
|
||||
for _ in range(n):
|
||||
ts = t + dt.timedelta(seconds=self._rng.uniform(0, span))
|
||||
out.append(make_sale(self.reg, station, ts, price_map, self._rng))
|
||||
t = hora_fin
|
||||
out.sort(key=lambda r: r["ts"])
|
||||
return out
|
||||
|
||||
# ------------------------------------------------------------- en vivo
|
||||
async def _live_loop(self) -> None:
|
||||
try:
|
||||
# Fase ráfaga: 1 venta / intervalo en bombas distintas.
|
||||
self.stats["fase"] = "ráfaga"
|
||||
fin_rafaga = self.now() + dt.timedelta(minutes=self.sim.arranque["rafaga_duracion_min"])
|
||||
while self.now() < fin_rafaga:
|
||||
await self._tick(distinct_pump=True)
|
||||
await asyncio.sleep(self.sim.arranque["rafaga_intervalo_seg"])
|
||||
|
||||
# Fase régimen: 1–5 ventas/min agregadas.
|
||||
self.stats["fase"] = "vivo"
|
||||
lo, hi = self.sim.ritmo_vivo_min_por_min, self.sim.ritmo_vivo_max_por_min
|
||||
while True:
|
||||
await self._tick(distinct_pump=False)
|
||||
await asyncio.sleep(self._rng.uniform(60.0 / hi, 60.0 / lo))
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e: # no tumbar el proceso por un fallo transitorio de DB
|
||||
self.stats["ultimo_error"] = f"{type(e).__name__}: {e}"
|
||||
self.stats["fase"] = "error"
|
||||
|
||||
async def _tick(self, distinct_pump: bool) -> None:
|
||||
"""Una venta en vivo + (si toca) lecturas de tanque y corte de turno."""
|
||||
await self._db(self._do_tick, distinct_pump, self.now())
|
||||
|
||||
def _do_tick(self, distinct_pump: bool, now: dt.datetime) -> None:
|
||||
station = self._elige_estacion(now)
|
||||
fecha = now.date()
|
||||
price_map = {f: seed.precio_del_dia(self.reg, station.id, f, fecha)
|
||||
for f in self.reg.combustibles}
|
||||
row = make_sale(self.reg, station, now, price_map, self._rng)
|
||||
if distinct_pump and self._last_bomba.get(station.id) == row["bomba"] and station.bombas > 2:
|
||||
row = make_sale(self.reg, station, now, price_map, self._rng) # re-tira para bomba distinta
|
||||
self._last_bomba[station.id] = row["bomba"]
|
||||
_insert_sale(self._conn, row)
|
||||
self._contar_venta(row)
|
||||
|
||||
# lecturas de tanque cada N minutos (todas las estaciones × combustibles)
|
||||
if now >= self._next_tank_ts:
|
||||
for s in self.reg.stations():
|
||||
for fuel in self.reg.combustibles:
|
||||
self._emit_tank_reading(s, fuel, self._next_tank_ts)
|
||||
self._next_tank_ts = self._next_tank_ts + dt.timedelta(minutes=self.sim.tank_reading_intervalo_min)
|
||||
|
||||
# corte de turno al cruzar un límite de turno
|
||||
self._maybe_shift_cut(now)
|
||||
|
||||
self._conn.commit()
|
||||
|
||||
def _maybe_shift_cut(self, now: dt.datetime) -> None:
|
||||
curr = self.reg.turno_por_hora(now.hour)
|
||||
prev = self._last_turno
|
||||
if prev is not None and curr.id != prev.id:
|
||||
if prev.inicio <= prev.fin:
|
||||
t0 = now.replace(hour=prev.inicio, minute=0, second=0, microsecond=0)
|
||||
else: # turno nocturno: arrancó a las 22:00 del día anterior
|
||||
t0 = (now - dt.timedelta(days=1)).replace(hour=prev.inicio, minute=0, second=0, microsecond=0)
|
||||
for s in self.reg.stations():
|
||||
if not _shift_cut_exists(self._conn, s.id, t0.date(), prev.id, prev.despachador_default):
|
||||
agg = _shift_agg(self._conn, s.id, t0, now)
|
||||
_insert_shift_cut(self._conn, make_shift_cut(
|
||||
self.reg, s, t0.date(), prev.id, prev.despachador_default, agg, self._rng))
|
||||
self._last_turno = curr
|
||||
|
||||
# ------------------------------------------------------------- helpers
|
||||
def _emit_tank_reading(self, station, fuel: str, ts: dt.datetime) -> None:
|
||||
day0 = ts.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
cap = self.reg.capacidad_tanque[fuel]
|
||||
sesgo_turno = self.sim.fugas["merma_sesgo_turno"]
|
||||
|
||||
sold = _sold(self._conn, station.id, fuel, day0, ts)
|
||||
sold_sesgo = _sold_turno(self._conn, station.id, fuel, sesgo_turno, day0, ts)
|
||||
delivered = _delivered(self._conn, station.id, fuel, day0, ts)
|
||||
inv_ini = self._inv_inicial(station.id, fuel, ts.date())
|
||||
|
||||
current = inv_ini - sold + delivered
|
||||
evento, vol_entregado_l = "Lectura normal", None
|
||||
if current / cap * 100 < self.sim.reorden_pct:
|
||||
amount = self.sim.recarga_objetivo_pct / 100 * cap - current
|
||||
if amount > 0:
|
||||
evento, vol_entregado_l, delivered = "Fin descarga", amount, delivered + amount
|
||||
|
||||
_insert_tank_reading(self._conn, make_tank_reading(
|
||||
self.reg, station, fuel, ts, inv_ini, sold, sold_sesgo, delivered,
|
||||
self._rng, evento, vol_entregado_l))
|
||||
|
||||
def _inv_inicial(self, sid: str, fuel: str, fecha: dt.date) -> float:
|
||||
cap = self.reg.capacidad_tanque[fuel]
|
||||
rng = seed._daily_rng("inv", sid, fuel, fecha.isoformat())
|
||||
return round(cap * rng.uniform(0.55, 0.90), 1)
|
||||
|
||||
def _elige_estacion(self, now: dt.datetime):
|
||||
activas = self.reg.stations()
|
||||
pesos = [peso_estacion(self.reg, s, now) for s in activas]
|
||||
return self._rng.choices(activas, weights=pesos, k=1)[0]
|
||||
|
||||
def _proximo_marca_tanque(self, now: dt.datetime) -> dt.datetime:
|
||||
paso = self.sim.tank_reading_intervalo_min
|
||||
minuto = (now.minute // paso + 1) * paso
|
||||
base = now.replace(second=0, microsecond=0)
|
||||
return base.replace(minute=0) + dt.timedelta(minutes=minuto)
|
||||
|
||||
def _marcas_tanque(self, desde: dt.datetime, hasta: dt.datetime, incluir_desde: bool):
|
||||
paso = self.sim.tank_reading_intervalo_min
|
||||
if incluir_desde:
|
||||
t = desde.replace(minute=0, second=0, microsecond=0)
|
||||
else:
|
||||
t = self._proximo_marca_tanque(desde)
|
||||
while t <= hasta:
|
||||
yield t
|
||||
t = t + dt.timedelta(minutes=paso)
|
||||
|
||||
def _turnos_completos_hoy(self, now: dt.datetime):
|
||||
"""Turnos que iniciaron y terminaron HOY antes de `now` (excluye el
|
||||
nocturno que cruza medianoche; ese corte se emite en vivo al cerrar)."""
|
||||
day0 = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
out = []
|
||||
for t in self.reg.turnos:
|
||||
if t.inicio <= t.fin:
|
||||
t0 = day0.replace(hour=t.inicio)
|
||||
t1 = day0.replace(hour=t.fin)
|
||||
if t1 <= now:
|
||||
out.append((t, t0, t1))
|
||||
return out
|
||||
|
||||
def _contar_venta(self, row: dict) -> None:
|
||||
self.stats["ventas_sesion"] += 1
|
||||
self.stats["por_estacion"][row["station_id"]] = \
|
||||
self.stats["por_estacion"].get(row["station_id"], 0) + 1
|
||||
self.stats["ultima_venta_ts"] = row["ts"].isoformat(timespec="seconds")
|
||||
|
||||
|
||||
# Singleton del proceso.
|
||||
runner = EngineRunner()
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
"""Sincroniza el registro → DB de forma idempotente.
|
||||
|
||||
Esta es la PRUEBA DE FUEGO de modularidad: recorre `reg.stations()` y `reg`
|
||||
para crear/actualizar catálogos (fuel), estaciones (station) y el precio del día
|
||||
(daily_price). Agregar la estación #N al YAML hace que aquí se siembre sola, sin
|
||||
tocar este código ni el esquema.
|
||||
|
||||
Todo es idempotente:
|
||||
- fuel / station: UPSERT (refleja el registro vigente).
|
||||
- daily_price: INSERT ... ON CONFLICT DO NOTHING (el primer precio del día
|
||||
queda fijo; reiniciar el motor el mismo día no lo mueve).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import random
|
||||
|
||||
import psycopg
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
|
||||
def _daily_rng(*parts) -> random.Random:
|
||||
"""RNG estable por (estación, combustible, fecha): mismo día → mismo precio,
|
||||
independiente de PYTHONHASHSEED. Así el seed es reproducible e idempotente."""
|
||||
key = "|".join(str(p) for p in parts)
|
||||
seed = int.from_bytes(hashlib.sha256(key.encode()).digest()[:8], "big")
|
||||
return random.Random(seed)
|
||||
|
||||
|
||||
def ensure_fuel(conn: psycopg.Connection, reg) -> None:
|
||||
"""Upsert del catálogo de combustibles desde el registro."""
|
||||
for name, fuel in reg.combustibles.items():
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO fuel (name, sale_price_base, margin_per_liter)
|
||||
VALUES (%s, %s, %s)
|
||||
ON CONFLICT (name) DO UPDATE
|
||||
SET sale_price_base = EXCLUDED.sale_price_base,
|
||||
margin_per_liter = EXCLUDED.margin_per_liter
|
||||
""",
|
||||
(name, fuel.precio_venta_base, fuel.margen_litro),
|
||||
)
|
||||
|
||||
|
||||
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."""
|
||||
for s in reg.stations(solo_activas=False):
|
||||
config = {
|
||||
"mezcla_combustible": s.mezcla_combustible,
|
||||
"zona": s.zona,
|
||||
}
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO station (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)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET nombre = EXCLUDED.nombre,
|
||||
zona = EXCLUDED.zona,
|
||||
perfil_horario = EXCLUDED.perfil_horario,
|
||||
perfil_semana = EXCLUDED.perfil_semana,
|
||||
bombas = EXCLUDED.bombas,
|
||||
ventas_dia_aprox = EXCLUDED.ventas_dia_aprox,
|
||||
bomba_fuera_serv = EXCLUDED.bomba_fuera_serv,
|
||||
activa = EXCLUDED.activa,
|
||||
config = EXCLUDED.config
|
||||
""",
|
||||
(s.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)),
|
||||
)
|
||||
|
||||
|
||||
def precio_del_dia(reg, station_id: str, fuel_name: str, fecha: dt.date) -> tuple[float, float]:
|
||||
"""Precio de venta y costo de reposición del día para (estación, combustible).
|
||||
|
||||
Determinista por día (RNG sembrado), para que sea idempotente. El costo se
|
||||
mueve un poco más que la venta (precio_variacion_costo_pct > venta_pct): así
|
||||
el margen del día varía y emerge la señal 'cohetes y plumas' que la
|
||||
plataforma podrá explotar. Márgenes y bases vienen del REGISTRO, no inventados.
|
||||
"""
|
||||
fuel = reg.fuel(fuel_name)
|
||||
sim = reg.simulacion
|
||||
rng = _daily_rng(station_id, fuel_name, fecha.isoformat())
|
||||
|
||||
venta_var = sim.precio_variacion_venta_pct
|
||||
costo_var = sim.precio_variacion_costo_pct
|
||||
sale_price = fuel.precio_venta_base * (1 + rng.uniform(-venta_var, venta_var))
|
||||
cost_price = fuel.costo_compra_base * (1 + rng.uniform(-costo_var, costo_var))
|
||||
return round(sale_price, 3), round(cost_price, 3)
|
||||
|
||||
|
||||
def ensure_daily_price(conn: psycopg.Connection, reg, fecha: dt.date) -> None:
|
||||
"""Precio del día por estación × combustible. ON CONFLICT DO NOTHING: el
|
||||
primer precio del día queda fijo (reiniciar el motor no lo altera)."""
|
||||
for s in reg.stations():
|
||||
for fuel_name in reg.combustibles:
|
||||
sale_price, cost_price = precio_del_dia(reg, s.id, fuel_name, fecha)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO daily_price (station_id, fecha, fuel_name, sale_price, cost_price)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
ON CONFLICT (station_id, fecha, fuel_name) DO NOTHING
|
||||
""",
|
||||
(s.id, fecha, fuel_name, sale_price, cost_price),
|
||||
)
|
||||
|
||||
|
||||
def seed_all(conn: psycopg.Connection, reg, fecha: dt.date) -> None:
|
||||
"""Siembra catálogos + estaciones + precio del día en una transacción."""
|
||||
ensure_fuel(conn, reg)
|
||||
ensure_stations(conn, reg)
|
||||
ensure_daily_price(conn, reg, fecha)
|
||||
conn.commit()
|
||||
@@ -0,0 +1,8 @@
|
||||
# Backend Collina — prototipo
|
||||
fastapi>=0.110
|
||||
uvicorn[standard]>=0.29
|
||||
pydantic>=2.6
|
||||
PyYAML>=6.0
|
||||
psycopg[binary]>=3.1 # driver PostgreSQL
|
||||
SQLAlchemy>=2.0 # ORM/consultas (opcional, para el motor y reportes)
|
||||
python-dotenv>=1.0
|
||||
Reference in new issue
Block a user