Files
botino/public/main.js
Lucas Tettamanti 7b6c62b23d Mejoras: idempotency webhook, métricas rewriter, recommend en XState, seeds
7 frentes en una pasada:

1. Idempotency en pipeline.processMessage: si el message_id ya existía
   (Evolution suele reentregar webhooks), skip todo el turn y devuelve
   { duplicate: true }. Antes el ON CONFLICT DO NOTHING evitaba el insert
   pero igual procesaba NLU + side effects.

2. Limpieza de payment residual de admin/UI:
   - ordersRepo.getMonthlyStats / getTotals: out las queries cash/card
   - home-dashboard: out el donut "Efectivo vs Tarjeta"
   - orders-crud: out columna "Pago" + sección de detalle de pago
   - conversation-inspector: out 💵💳 del resumen
   - takeovers: out payment_link en run, out payment del summary
   - public/main.js: out la invariant no_checkout_without_payment_link
   - prompts-crud: out la entry "payment" del PROMPT_LABELS
   - wooOrders.parseOrder: out lectura de payment_method/is_paid (estado
     del pago lo gestiona el comercio offline, fuera del bot)
   - ordersRepo: out is_cash/is_paid del row mapping

3. Seed migration 20260501130000_seed_piaf_settings_and_replies:
   - schedule realista para piaf (delivery/pickup días+horas)
   - delivery_zones con barrios CABA reales (Palermo, Belgrano, etc)
   - 41 reply_templates con 17 keys + variantes (todo lo de DEFAULTS)
   Permite editar respuestas sin redeploy y desbloquea {{store_hours_today}},
   {{delivery_zones_summary}} reales en los templates.

4. Address validation en shipping: nuevo checkAddressInZone() en
   storeContext.js. Cuando el usuario da dirección, se valida contra
   zonas configuradas. Si está fuera, renderiza shipping.address_out_of_zone
   con sugerencia de zonas alternativas. Sin zonas configuradas → accept-by-default.

5. Métricas rewriter: getRewriterMetrics() expuesto, contadores
   ok/fallback/timeouts + avg_ms + fallback_rate. Endpoint nuevo
   /api/metrics/rewriter.

6. Shadow XState → audit_log: el shadow mode pasa de console.log a
   insertAuditLog con entity_type='xstate_shadow'. Permite review post-mortem.

7. Recommend portado a XState: nuevo recommendActor (fromPromise) wrappea
   handleRecommend; sub-state cart.recommending invoca el actor; ingestRecommendResult
   absorbe { plan, decision } en context. RECOMMEND event funciona desde idle
   y desde cart con USE_XSTATE=1.

8. tenantId opcional en renderReply/loadReplyVariants — defaultea a
   getTenantId() del módulo shared/tenant.js. Backward-compat: callers
   pueden seguir pasando tenantId o omitirlo.

E2E tests nuevos en machine/e2e.test.js: golden flow pickup, golden flow
delivery con address-in-zone, snapshot rehydrate full flow, universal
cart-on-add desde shipping. 192/192 tests pasando (188 previos + 4 E2E).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 21:18:29 -03:00

222 lines
5.5 KiB
JavaScript

// main.js
// Express server for: Ops UI (static) + SSE stream + Local WhatsApp Simulator + simple in-memory stores
// Run: npm i express cors && node main.js
// Open: http://localhost:3000
import express from "express";
import cors from "cors";
import crypto from "crypto";
import path from "path";
import { fileURLToPath } from "url";
const app = express();
app.use(cors());
app.use(express.json({ limit: "1mb" }));
// Serve /public as static (UI + webcomponents)
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const publicDir = path.join(__dirname, "public");
app.use(express.static(publicDir));
/**
* In-memory store (MVP). Replace with Postgres later.
*/
const conversations = new Map(); // chat_id -> conversation snapshot
const runs = new Map(); // run_id -> run object
/**
* SSE clients (Server-Sent Events)
*/
const sseClients = new Set();
function sseSend(event, data) {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
for (const res of sseClients) res.write(payload);
}
function nowIso() {
return new Date().toISOString();
}
function newId(prefix = "run") {
return `${prefix}_${crypto.randomUUID()}`;
}
function upsertConversation(chat_id, patch) {
const prev = conversations.get(chat_id) || {
chat_id,
from: patch.from || chat_id,
state: "IDLE",
intent: "other",
last_activity: nowIso(),
status: "ok",
last_run_id: null,
};
const next = {
...prev,
...patch,
last_activity: nowIso(),
};
conversations.set(chat_id, next);
return next;
}
/**
* TODO: Replace this with your real pipeline later:
* - loadState from Postgres
* - call LLM (structured output)
* - product search (LIMITED) + resolve ids
* - create/update Woo order
* - save state
*/
async function processMessage({ chat_id, from, text }) {
const prevConv = conversations.get(chat_id) || null;
const run_id = newId("run");
const started_at = Date.now();
// Minimal simulated LLM output (replace later)
const plan = {
reply: `Recibido: "${text}". ¿Querés retiro o envío?`,
next_state: "BUILDING_ORDER",
intent: "create_order",
missing_fields: ["delivery_or_pickup"],
order_action: "none",
basket_resolved: { items: [] },
};
const invariants = {
ok: true,
checks: [
{ name: "required_keys_present", ok: true },
{ name: "no_order_action_without_items", ok: true },
],
};
const run = {
run_id,
ts: nowIso(),
chat_id,
from,
status: "ok", // ok|warn|error
prev_state: prevConv?.state || "IDLE",
input: { text },
llm_output: plan,
tools: [], // later: [{name, ok, ms, input_summary, output_summary}]
invariants,
final_reply: plan.reply,
order_id: null,
latency_ms: Date.now() - started_at,
};
runs.set(run_id, run);
const conv = upsertConversation(chat_id, {
from,
state: plan.next_state,
intent: plan.intent,
status: run.status,
last_run_id: run_id,
});
// Push realtime events to UI
sseSend("conversation.upsert", conv);
sseSend("run.created", run);
return run;
}
/**
* SSE endpoint (UI connects here)
*/
app.get("/stream", (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
// If compression middleware ever added, you'd need res.flushHeaders()
res.flushHeaders?.();
// hello event
res.write(`event: hello\ndata: ${JSON.stringify({ ts: nowIso() })}\n\n`);
sseClients.add(res);
req.on("close", () => {
sseClients.delete(res);
res.end();
});
});
/**
* Local WhatsApp Simulator:
* POST /sim/send { chat_id, from_phone, text }
*/
app.post("/sim/send", async (req, res) => {
const { chat_id, from_phone, text } = req.body || {};
if (!chat_id || !from_phone || !text) {
return res.status(400).json({ ok: false, error: "chat_id, from_phone, text are required" });
}
try {
const run = await processMessage({ chat_id, from: from_phone, text });
res.json({ ok: true, run_id: run.run_id, reply: run.final_reply });
} catch (err) {
res.status(500).json({ ok: false, error: "internal_error", detail: String(err?.message || err) });
}
});
/**
* List conversations
* GET /conversations?q=&status=&state=
*/
app.get("/conversations", (req, res) => {
const { q = "", status = "", state = "" } = req.query;
const items = [...conversations.values()]
.filter(c => (q ? (String(c.chat_id).includes(q) || String(c.from).includes(q)) : true))
.filter(c => (status ? c.status === status : true))
.filter(c => (state ? c.state === state : true))
.sort((a, b) => (a.last_activity < b.last_activity ? 1 : -1));
res.json({ items });
});
/**
* List runs (optionally by chat_id)
* GET /runs?chat_id=&limit=50
*/
app.get("/runs", (req, res) => {
const { chat_id, limit = "50" } = req.query;
const lim = Math.max(1, Math.min(200, parseInt(limit, 10) || 50));
let items = [...runs.values()].sort((a, b) => (a.ts < b.ts ? 1 : -1));
if (chat_id) items = items.filter(r => r.chat_id === chat_id);
res.json({ items: items.slice(0, lim) });
});
/**
* Run detail
* GET /runs/:run_id
*/
app.get("/runs/:run_id", (req, res) => {
const run = runs.get(req.params.run_id);
if (!run) return res.status(404).json({ ok: false, error: "not_found" });
res.json(run);
});
/**
* Root: serve UI
*/
app.get("/", (req, res) => {
res.sendFile(path.join(publicDir, "index.html"));
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`UI: http://localhost:${port}`);
});