Files
botino/public/lib/api.js
Lucas Tettamanti 47de1efe86 Login + ABM de operadores + audit log con UI
Backend:
- 3 migrations: system_users (citext email único, password_hash, active),
  system_sessions (UUID + expires_at + revoked_at), ALTER audit_log con
  actor_user_id/actor_email/actor_ip/action_path/summary y entity_id NULL.
- src/modules/auth/: usersRepo, sessionsRepo, passwords (bcrypt cost 10),
  auth (login/logout), bootstrap (crea admin desde ADMIN_EMAIL/PASSWORD si
  la tabla está vacía). 4 tests passwords (hash distinto cada vez, verify
  rechaza, longitud mínima 8).
- middleware/requireAuth: lee cookie bot_session, busca sesión activa,
  popula req.user. Whitelist: /styles, /components, /lib, /login, /, /home
  y SPA paths (HTML carga sin auth, el JS gatea con /api/auth/me).
- middleware/auditWriter: registra cada POST/PUT/DELETE 2xx en audit_log
  con req.user, IP, body redactado (passwords/tokens/secrets). Handlers
  pueden enriquecer summary via res.locals.audit.
- routes: /api/auth/{login,logout,me} (cookie httpOnly + DB session),
  /api/system-users (ABM con guards: cant_delete_self, cant_deactivate_self,
  email único, password ≥ 8), /api/audit-log + /api/audit-log/actors.
- src/app.js: orden estricto — webhooks (sin auth) → auth routes (sin auth)
  → /login HTML → static → SPA HTML → requireAuth + auditWriter → API admin.

Bootstrap del primer admin se ejecuta en index.js antes de listen. Usa
ADMIN_EMAIL/ADMIN_PASSWORD/ADMIN_NAME del .env. Si no están seteados y la
tabla está vacía, warn y exit (nadie puede loguearse).

Frontend:
- /login.html + /login.js: form simple, POST a /api/auth/login con
  credentials:include, redirect a ?next=... o /home. Si ya hay sesión
  activa, va directo a /home.
- public/app.js gate: chequea /api/auth/me antes de initRouter; sin sesión
  redirige a /login?next=<path>. window.__USER__ disponible para shell.
- ops-shell: nav agrega "Operadores" + "Actividad". Header derecha muestra
  email del user + botón Salir (POST /api/auth/logout + redirect /login).
- system-users-crud: CRUD lista/form (estilo settings). Crear/editar/
  cambiar password/eliminar. UI muestra badge "Vos" + bloquea eliminarse
  ni desactivarse a uno mismo.
- audit-log: tabla read-only con filtros (actor, entity_type, since,
  search), paginación 50, badges por acción, modal de detalles con
  changes JSON. /api/audit-log/actors pobla el dropdown de operadores.

Smoke E2E: login OK + cookie set, /me 200; logout → /me 401; settings POST
genera fila en audit_log con actor_email + action_path; ABM crea/borra
operadores con guards; intentar borrarse devuelve 400 cant_delete_self.

161/161 tests verde (pre-existentes 157 + 4 passwords nuevos).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 19:02:37 -03:00

365 lines
12 KiB
JavaScript

import { toast } from "./toast.js";
/**
* fetch wrapper que dispara toast en error de red o respuesta no-OK.
* Devuelve la respuesta parseada como JSON. Si la respuesta tiene
* `{ ok: false, error }`, también dispara toast.
*/
export async function safeFetch(url, opts = {}, { silent = false, label = null } = {}) {
let res;
try {
res = await fetch(url, { credentials: "include", ...opts });
} catch (err) {
if (!silent) toast({ kind: "error", text: `${label || "Red"}: ${err?.message || "sin conexión"}` });
throw err;
}
if (!res.ok) {
let body = null;
try { body = await res.json(); } catch (_) {}
const msg = body?.error || body?.message || `${res.status} ${res.statusText}`;
if (!silent) toast({ kind: "error", text: `${label || "Error"}: ${msg}` });
const err = new Error(msg);
err.status = res.status;
err.body = body;
throw err;
}
try {
return await res.json();
} catch (_) {
return {};
}
}
export const api = {
async conversations({ q = "", status = "", state = "" } = {}) {
const u = new URL("/conversations", location.origin);
if (q) u.searchParams.set("q", q);
if (status) u.searchParams.set("status", status);
if (state) u.searchParams.set("state", state);
return fetch(u).then(r => r.json());
},
async deleteConversation(chat_id) {
if (!chat_id) throw new Error("chat_id_required");
return fetch(`/conversations/${encodeURIComponent(chat_id)}`, { method: "DELETE" }).then(r => r.json());
},
async users({ q = "", limit = 200 } = {}) {
const u = new URL("/users", location.origin);
if (q) u.searchParams.set("q", String(q));
u.searchParams.set("limit", String(limit));
return fetch(u).then(r => r.json());
},
async deleteUser(chat_id, { deleteWoo = false } = {}) {
if (!chat_id) throw new Error("chat_id_required");
const u = new URL(`/users/${encodeURIComponent(chat_id)}`, location.origin);
if (deleteWoo) u.searchParams.set("deleteWoo", "1");
return fetch(u, { method: "DELETE" }).then(r => r.json());
},
async messages({ chat_id, limit = 200 } = {}) {
const u = new URL("/messages", location.origin);
if (chat_id) u.searchParams.set("chat_id", chat_id);
u.searchParams.set("limit", String(limit));
return fetch(u).then(r => r.json());
},
async runs({ chat_id, limit = 1 } = {}) {
const u = new URL("/runs", location.origin);
if (chat_id) u.searchParams.set("chat_id", chat_id);
u.searchParams.set("limit", String(limit));
return fetch(u).then(r => r.json());
},
async runById(run_id) {
if (!run_id) return null;
return fetch(`/runs/${encodeURIComponent(run_id)}`).then(r => r.json());
},
async simEvolution(payload) {
return safeFetch("/webhook/evolution", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
}, { label: "Sim Evolution" });
},
async retryLast(chat_id) {
if (!chat_id) throw new Error("chat_id_required");
return safeFetch(`/conversations/${encodeURIComponent(chat_id)}/retry-last`, { method: "POST" }, { label: "Retry" });
},
// Products CRUD
async products({ q = "", limit = 2000, offset = 0 } = {}) {
const u = new URL("/products", location.origin);
if (q) u.searchParams.set("q", q);
u.searchParams.set("limit", String(limit));
u.searchParams.set("offset", String(offset));
return fetch(u).then(r => r.json());
},
async productById(id) {
if (!id) return null;
return fetch(`/products/${encodeURIComponent(id)}`).then(r => r.json());
},
async syncProducts() {
return fetch("/products/sync", { method: "POST" }).then(r => r.json());
},
async updateProductUnit(wooProductId, { sell_unit }) {
return fetch(`/products/${encodeURIComponent(wooProductId)}/unit`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sell_unit }),
}).then(r => r.json());
},
async updateProduct(wooProductId, { sell_unit, categories }) {
return fetch(`/products/${encodeURIComponent(wooProductId)}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sell_unit, categories }),
}).then(r => r.json());
},
async updateProductsUnit(wooProductIds, { sell_unit }) {
return fetch(`/products/bulk/unit`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ woo_product_ids: wooProductIds, sell_unit }),
}).then(r => r.json());
},
// Aliases CRUD
async aliases({ q = "", woo_product_id = null, limit = 200 } = {}) {
const u = new URL("/aliases", location.origin);
if (q) u.searchParams.set("q", q);
if (woo_product_id) u.searchParams.set("woo_product_id", String(woo_product_id));
u.searchParams.set("limit", String(limit));
return fetch(u).then(r => r.json());
},
async createAlias(data) {
return fetch("/aliases", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}).then(r => r.json());
},
async updateAlias(alias, data) {
return fetch(`/aliases/${encodeURIComponent(alias)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}).then(r => r.json());
},
async deleteAlias(alias) {
return fetch(`/aliases/${encodeURIComponent(alias)}`, { method: "DELETE" }).then(r => r.json());
},
// Recommendations CRUD
async recommendations({ q = "", limit = 200 } = {}) {
const u = new URL("/recommendations", location.origin);
if (q) u.searchParams.set("q", q);
u.searchParams.set("limit", String(limit));
return fetch(u).then(r => r.json());
},
async getRecommendation(id) {
if (!id) return null;
return fetch(`/recommendations/${encodeURIComponent(id)}`).then(r => r.json());
},
async createRecommendation(data) {
return fetch("/recommendations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}).then(r => r.json());
},
async updateRecommendation(id, data) {
return fetch(`/recommendations/${encodeURIComponent(id)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}).then(r => r.json());
},
async deleteRecommendation(id) {
return fetch(`/recommendations/${encodeURIComponent(id)}`, { method: "DELETE" }).then(r => r.json());
},
// Quantities (cantidades por producto/evento/persona)
async listQuantities() {
return fetch("/quantities").then(r => r.json());
},
async getProductQuantities(wooProductId) {
if (!wooProductId) return { rules: [] };
return fetch(`/quantities/${encodeURIComponent(wooProductId)}`).then(r => r.json());
},
async saveProductQuantities(wooProductId, rules) {
return fetch(`/quantities/${encodeURIComponent(wooProductId)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ rules }),
}).then(r => r.json());
},
// Sync de emergencia desde WooCommerce
async syncFromWoo() {
return fetch("/products/sync-from-woo", { method: "POST" }).then(r => r.json());
},
// --- Orders & Stats ---
async listOrders({ page = 1, limit = 50 } = {}) {
const u = new URL("/api/orders", location.origin);
u.searchParams.set("page", String(page));
u.searchParams.set("limit", String(limit));
return fetch(u).then(r => r.json());
},
async getOrderStats() {
return fetch("/api/stats/orders").then(r => r.json());
},
// Alias para compatibilidad
async listRecentOrders({ limit = 20 } = {}) {
return this.listOrders({ page: 1, limit });
},
// --- Prompts CRUD ---
async prompts() {
return fetch("/prompts").then(r => r.json());
},
async getPrompt(key) {
return fetch(`/prompts/${encodeURIComponent(key)}`).then(r => r.json());
},
async savePrompt(key, { content, model, created_by }) {
return fetch(`/prompts/${encodeURIComponent(key)}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content, model, created_by }),
}).then(r => r.json());
},
async rollbackPrompt(key, version) {
return fetch(`/prompts/${encodeURIComponent(key)}/rollback/${version}`, {
method: "POST"
}).then(r => r.json());
},
async resetPrompt(key) {
return fetch(`/prompts/${encodeURIComponent(key)}/reset`, {
method: "POST"
}).then(r => r.json());
},
async testPrompt(key, { content, test_message, store_config }) {
return fetch(`/prompts/${encodeURIComponent(key)}/test`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content, test_message, store_config }),
}).then(r => r.json());
},
// --- Human Takeovers ---
async takeovers({ limit = 50 } = {}) {
const u = new URL("/takeovers", location.origin);
u.searchParams.set("limit", String(limit));
return fetch(u).then(r => r.json());
},
async getTakeover(id) {
return fetch(`/takeovers/${id}`).then(r => r.json());
},
async respondTakeover(id, { response, add_alias, cart_items }) {
return fetch(`/takeovers/${id}/respond`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ response, add_alias, cart_items }),
}).then(r => r.json());
},
async cancelTakeover(id) {
return fetch(`/takeovers/${id}/cancel`, {
method: "POST"
}).then(r => r.json());
},
// --- Settings ---
async getSettings() {
return fetch("/settings").then(r => r.json());
},
async saveSettings(settings) {
const res = await fetch("/settings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(settings),
});
const data = await res.json();
if (!res.ok || data.ok === false) {
throw new Error(data.message || data.error || "Error guardando configuración");
}
return data;
},
// --- Auth ---
async me() {
const res = await fetch("/api/auth/me", { credentials: "include" });
if (!res.ok) return null;
const data = await res.json();
return data?.user || null;
},
async logout() {
return fetch("/api/auth/logout", { method: "POST", credentials: "include" }).then(r => r.json());
},
// --- System users (operadores) ---
async listSystemUsers() {
return safeFetch("/api/system-users", {}, { label: "Operadores" });
},
async createSystemUser({ email, name, password, active = true }) {
return safeFetch("/api/system-users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, name, password, active }),
}, { label: "Crear operador" });
},
async updateSystemUser(id, payload) {
return safeFetch(`/api/system-users/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
}, { label: "Editar operador" });
},
async deleteSystemUser(id) {
return safeFetch(`/api/system-users/${id}`, { method: "DELETE" }, { label: "Eliminar operador" });
},
// --- Audit log ---
async auditLog({ limit = 50, before, since, actor_id, entity_type, q } = {}) {
const qs = new URLSearchParams();
qs.set("limit", String(limit));
if (before) qs.set("before", before);
if (since) qs.set("since", since);
if (actor_id) qs.set("actor_id", String(actor_id));
if (entity_type) qs.set("entity_type", entity_type);
if (q) qs.set("q", q);
return safeFetch(`/api/audit-log?${qs.toString()}`, {}, { silent: true });
},
async auditActors() {
return safeFetch("/api/audit-log/actors", {}, { silent: true });
},
};