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>
This commit is contained in:
Lucas Tettamanti
2026-05-02 19:02:37 -03:00
parent 4a64256ef4
commit 47de1efe86
27 changed files with 1628 additions and 32 deletions

View File

@@ -0,0 +1,202 @@
import { api } from "../lib/api.js";
import { modal } from "../lib/modal.js";
class AuditLog extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.items = [];
this.actors = [];
this.loading = false;
this.filters = { actor_id: "", entity_type: "", since: "", q: "" };
this.limit = 50;
this.shadowRoot.innerHTML = `
<style>
:host { display:block; height:100%; padding:16px 24px 24px; overflow:auto; }
* { box-sizing:border-box; font-family: var(--font-sans); }
.container { max-width:1400px; margin:0 auto; }
.toolbar { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:12px 4px 16px; position:sticky; top:0; background:var(--bg); border-bottom:1px solid var(--border); margin-bottom:16px; flex-wrap:wrap; z-index:5; }
.toolbar-title { margin:0; font-size:18px; font-weight:600; }
.filters { display:flex; gap:8px; align-items:center; flex-wrap:wrap; }
.filters input, .filters select { padding:7px 10px; font-size:13px; border:1px solid var(--border-hi); border-radius:var(--r-md); background:var(--panel); color:var(--text); }
.filters input:focus, .filters select:focus { outline:none; border-color:var(--accent); }
button { cursor:pointer; background:var(--accent); color:var(--text-on-acc, #fff); border:none; border-radius:var(--r-md); padding:7px 12px; font-size:12px; font-weight:500; }
button:hover { background:var(--accent-hover); }
button.secondary { background:var(--panel); color:var(--text); border:1px solid var(--border-hi); }
button.secondary:hover { border-color:var(--accent); color:var(--accent-hover); }
.panel { background:var(--panel); border:1px solid var(--border); border-radius:10px; overflow:hidden; }
table { width:100%; border-collapse:collapse; font-size:13px; }
thead th { text-align:left; padding:10px 12px; background:var(--panel-2); border-bottom:1px solid var(--border); color:var(--text-muted); font-weight:600; font-size:11px; text-transform:uppercase; letter-spacing:.4px; }
tbody td { padding:10px 12px; border-bottom:1px solid var(--border); vertical-align:top; }
tbody tr:last-child td { border-bottom:none; }
tbody tr:hover { background:var(--panel-2); }
td.ts { font-family: var(--font-mono); color:var(--text-muted); white-space:nowrap; font-size:12px; }
td.actor { color:var(--text); }
td.actor.system { color:var(--text-muted); font-style:italic; }
td.path { font-family: var(--font-mono); font-size:12px; color:var(--accent-hover); white-space:nowrap; }
td.summary { color:var(--text); }
td.entity { color:var(--text-muted); font-size:12px; }
td.actions { text-align:right; }
td.actions button { padding:4px 8px; font-size:11px; background:transparent; color:var(--text-muted); border:1px solid var(--border-hi); }
td.actions button:hover { color:var(--accent); border-color:var(--accent); background:var(--accent-soft); }
.empty { padding:32px; text-align:center; color:var(--text-muted); font-size:13px; }
.footer { display:flex; justify-content:space-between; align-items:center; padding:12px; background:var(--panel-2); border-top:1px solid var(--border); font-size:12px; color:var(--text-muted); }
.badge-action { display:inline-block; font-size:11px; padding:2px 8px; border-radius:6px; font-weight:500; }
.badge-action.create { background:var(--ok-soft); color:var(--ok); }
.badge-action.update { background:var(--accent-soft); color:var(--accent-hover); }
.badge-action.delete { background:var(--err-soft); color:var(--err); }
.badge-action.login { background:var(--accent-soft); color:var(--accent-hover); }
.badge-action.login_failed { background:var(--err-soft); color:var(--err); }
.badge-action.logout { background:var(--panel-3); color:var(--text-muted); }
</style>
<div class="container">
<div class="toolbar">
<h2 class="toolbar-title">Actividad</h2>
<div class="filters">
<select id="fActor"><option value="">Todos los actores</option></select>
<select id="fEntity">
<option value="">Toda entidad</option>
<option value="auth">auth</option>
<option value="settings">settings</option>
<option value="system_user">system_user</option>
<option value="product">product</option>
<option value="conversations">conversations</option>
<option value="takeovers">takeovers</option>
</select>
<input id="fSince" type="datetime-local" />
<input id="fSearch" type="text" placeholder="Buscar en summary..." />
<button id="btnApply" type="button">Aplicar</button>
<button id="btnRefresh" class="secondary" type="button">↻</button>
</div>
</div>
<div class="panel">
<table>
<thead>
<tr>
<th style="width:160px;">Fecha</th>
<th style="width:180px;">Operador</th>
<th style="width:100px;">Acción</th>
<th style="width:200px;">Ruta</th>
<th>Resumen</th>
<th style="width:80px;"></th>
</tr>
</thead>
<tbody id="rows"></tbody>
</table>
<div class="footer" id="footer">—</div>
</div>
</div>
`;
}
connectedCallback() {
this.shadowRoot.getElementById("btnApply").addEventListener("click", () => this.applyFilters());
this.shadowRoot.getElementById("btnRefresh").addEventListener("click", () => this.load());
this.shadowRoot.getElementById("fSearch").addEventListener("keydown", (e) => {
if (e.key === "Enter") this.applyFilters();
});
this.loadActors();
this.load();
}
applyFilters() {
this.filters.actor_id = this.shadowRoot.getElementById("fActor").value || "";
this.filters.entity_type = this.shadowRoot.getElementById("fEntity").value || "";
this.filters.since = this.shadowRoot.getElementById("fSince").value || "";
this.filters.q = this.shadowRoot.getElementById("fSearch").value.trim();
this.load();
}
async loadActors() {
try {
const data = await api.auditActors();
this.actors = data.items || [];
const sel = this.shadowRoot.getElementById("fActor");
const current = sel.value;
sel.innerHTML = `<option value="">Todos los actores</option>` +
this.actors.map((a) => `<option value="${a.id}">${this.escapeHtml(a.email)}</option>`).join("");
sel.value = current;
} catch {}
}
async load() {
this.loading = true;
this.renderRows();
try {
const params = { limit: this.limit };
if (this.filters.actor_id) params.actor_id = this.filters.actor_id;
if (this.filters.entity_type) params.entity_type = this.filters.entity_type;
if (this.filters.since) params.since = new Date(this.filters.since).toISOString();
if (this.filters.q) params.q = this.filters.q;
const data = await api.auditLog(params);
this.items = data.items || [];
this.loading = false;
this.renderRows();
} catch (e) {
this.loading = false;
this.items = [];
this.renderRows();
}
}
renderRows() {
const rows = this.shadowRoot.getElementById("rows");
const footer = this.shadowRoot.getElementById("footer");
if (this.loading) {
rows.innerHTML = `<tr><td colspan="6" class="empty">Cargando...</td></tr>`;
footer.textContent = "—";
return;
}
if (!this.items.length) {
rows.innerHTML = `<tr><td colspan="6" class="empty">Sin actividad para los filtros aplicados.</td></tr>`;
footer.textContent = "0 eventos";
return;
}
rows.innerHTML = this.items.map((r) => {
const ts = new Date(r.created_at);
const tsStr = ts.toLocaleString("es-AR", { day: "2-digit", month: "2-digit", year: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });
const actor = r.actor_email || r.actor || "system";
const actorClass = r.actor_user_id ? "" : "system";
const actionClass = String(r.action || "").replace(/[^a-z_]/g, "");
return `
<tr data-id="${r.id}">
<td class="ts">${this.escapeHtml(tsStr)}</td>
<td class="actor ${actorClass}">${this.escapeHtml(actor)}</td>
<td><span class="badge-action ${actionClass}">${this.escapeHtml(r.action || "—")}</span></td>
<td class="path">${this.escapeHtml(r.action_path || "")}</td>
<td class="summary">${this.escapeHtml(r.summary || `${r.entity_type || ""}${r.entity_id ? "#"+r.entity_id : ""}`)}</td>
<td class="actions"><button data-action="details" data-id="${r.id}">Detalles</button></td>
</tr>
`;
}).join("");
rows.querySelectorAll('button[data-action="details"]').forEach((btn) => {
btn.addEventListener("click", () => this.showDetails(btn.dataset.id));
});
footer.textContent = `${this.items.length} evento${this.items.length === 1 ? "" : "s"}${this.items.length >= this.limit ? " (mostrando últimos)" : ""}`;
}
showDetails(id) {
const r = this.items.find((x) => String(x.id) === String(id));
if (!r) return;
const lines = [];
lines.push(`Fecha: ${new Date(r.created_at).toLocaleString("es-AR")}`);
lines.push(`Operador: ${r.actor_email || r.actor || "system"}`);
if (r.actor_ip) lines.push(`IP: ${r.actor_ip}`);
lines.push(`Acción: ${r.action}`);
lines.push(`Entidad: ${r.entity_type || "-"}${r.entity_id ? "#"+r.entity_id : ""}`);
if (r.action_path) lines.push(`Ruta: ${r.action_path}`);
if (r.summary) lines.push(`Resumen: ${r.summary}`);
if (r.changes) lines.push("\nCambios:\n" + JSON.stringify(r.changes, null, 2));
modal.info(lines.join("\n"));
}
escapeHtml(s) {
return String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
}
customElements.define("audit-log", AuditLog);

View File

@@ -56,6 +56,11 @@ class OpsShell extends HTMLElement {
@keyframes pulse { 0%,100% { opacity:1; } 50% { opacity:.4; } }
/* Notification bell */
.user-menu { display:flex; align-items:center; gap:8px; padding:4px 4px 4px 10px; border-radius: var(--r-sm); border:1px solid var(--border); }
.user-email { font: var(--fw-medium) 12px/1.2 var(--font-sans); color: var(--text); max-width:160px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.logout-btn { background: transparent; border: 1px solid transparent; color: var(--text-muted); padding: 4px 8px; border-radius: var(--r-sm); cursor:pointer; font:var(--fw-medium) 11px/1 var(--font-sans); }
.logout-btn:hover { color: var(--err); border-color: var(--err-soft); background: var(--err-soft); }
.notification-bell { position:relative; cursor:pointer; padding: 8px; border-radius: var(--r-sm); transition: background .15s; }
.notification-bell:hover { background: var(--panel-2); }
.notification-bell svg { width:18px; height:18px; fill: var(--text-muted); transition:fill .15s; display:block; }
@@ -98,6 +103,8 @@ class OpsShell extends HTMLElement {
<a class="nav-btn" href="/cantidades" data-view="quantities">Cantidades</a>
<a class="nav-btn" href="/pedidos" data-view="orders">Pedidos</a>
<a class="nav-btn" href="/configuracion" data-view="settings">Config</a>
<a class="nav-btn" href="/operadores" data-view="operadores">Operadores</a>
<a class="nav-btn" href="/actividad" data-view="actividad">Actividad</a>
</nav>
<div class="spacer"></div>
<div class="notification-bell" id="notificationBell" title="Takeovers pendientes">
@@ -105,6 +112,10 @@ class OpsShell extends HTMLElement {
<span class="badge" id="takeoverBadge" style="display:none;">0</span>
</div>
<div class="status disconnected" id="sseStatus"><span class="dot"></span><span class="label">Conectando…</span></div>
<div class="user-menu" id="userMenu" title="Sesión">
<span class="user-email" id="userEmail">—</span>
<button class="logout-btn" id="logoutBtn" type="button">Salir</button>
</div>
</header>
<div id="viewHome" class="view active">
@@ -174,6 +185,18 @@ class OpsShell extends HTMLElement {
<settings-crud></settings-crud>
</div>
</div>
<div id="viewOperadores" class="view">
<div class="layout-crud">
<system-users-crud></system-users-crud>
</div>
</div>
<div id="viewActividad" class="view">
<div class="layout-crud">
<audit-log></audit-log>
</div>
</div>
</div>
`;
}
@@ -187,6 +210,18 @@ class OpsShell extends HTMLElement {
if (label) label.textContent = s.ok ? "En vivo" : "Reconectando…";
});
// User session badge + logout.
const user = window.__USER__ || null;
const emailEl = this.shadowRoot.getElementById("userEmail");
if (emailEl) emailEl.textContent = user?.email || "—";
this.shadowRoot.getElementById("logoutBtn")?.addEventListener("click", async () => {
try {
await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
} finally {
window.location.replace("/login");
}
});
// Listen for view switch requests from other components
this._unsubSwitch = on("ui:switchView", ({ view }) => {
if (view) this.setView(view, {}, { updateUrl: true });

View File

@@ -0,0 +1,259 @@
import { api } from "../lib/api.js";
import { modal } from "../lib/modal.js";
import { toast } from "../lib/toast.js";
class SystemUsersCrud extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.users = [];
this.selected = null; // user seleccionado (objeto)
this.editing = null; // copia editable de selected
this.creating = false; // si true, editing es un user nuevo
this.loading = false;
this.saving = false;
this.shadowRoot.innerHTML = `
<style>
:host { display:block; height:100%; padding:16px 24px 24px; overflow:auto; }
* { box-sizing:border-box; font-family: var(--font-sans); }
.container { max-width:1200px; margin:0 auto; }
.toolbar { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:12px 4px 16px; position:sticky; top:0; background:var(--bg); border-bottom:1px solid var(--border); margin-bottom:16px; }
.toolbar-title { margin:0; font-size:18px; font-weight:600; }
.toolbar button { padding:8px 14px; font-size:13px; }
.grid { display:grid; grid-template-columns: minmax(280px,360px) minmax(0,1fr); gap:16px; align-items:start; }
@media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }
.panel { background:var(--panel); border:1px solid var(--border); border-radius:10px; padding:16px; }
.panel h3 { margin:0 0 12px; font-size:14px; font-weight:600; color:var(--text-muted); text-transform:uppercase; letter-spacing:.4px; }
.list { display:flex; flex-direction:column; gap:6px; max-height:60vh; overflow-y:auto; }
.empty { padding:24px; color:var(--text-muted); text-align:center; font-size:13px; }
.item { padding:10px 12px; border:1px solid var(--border); border-radius:var(--r-md); cursor:pointer; transition:all .15s; background:var(--panel-2); }
.item:hover { border-color:var(--border-hi); }
.item.active { border-color:var(--accent); background:var(--accent-soft); }
.item.inactive { opacity:.55; }
.item-email { font-size:13px; font-weight:500; color:var(--text); }
.item-name { font-size:11px; color:var(--text-muted); margin-top:2px; }
.badge { display:inline-block; font-size:10px; padding:1px 6px; border-radius:6px; margin-left:6px; }
.badge.you { background:var(--accent-soft); color:var(--accent-hover); }
.badge.off { background:var(--panel-3); color:var(--text-muted); }
.form .field { margin-bottom:14px; }
.form label { display:block; font-size:11px; color:var(--text-muted); margin-bottom:6px; text-transform:uppercase; letter-spacing:.4px; }
.form input, .form select { width:100%; padding:9px 12px; font-size:13px; border:1px solid var(--border-hi); border-radius:var(--r-md); background:var(--panel-2); color:var(--text); }
.form input:focus, .form select:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px var(--accent-soft); }
.form-hint { font-size:11px; color:var(--text-muted); margin-top:4px; }
.form-actions { display:flex; gap:8px; flex-wrap:wrap; margin-top:16px; }
button { cursor:pointer; background:var(--accent); color:var(--text-on-acc, #fff); border:none; border-radius:var(--r-md); padding:9px 16px; font-size:13px; font-weight:500; }
button:hover { background:var(--accent-hover); }
button:disabled { opacity:.5; cursor:not-allowed; }
button.secondary { background:var(--panel); color:var(--text); border:1px solid var(--border-hi); }
button.secondary:hover { border-color:var(--accent); color:var(--accent-hover); }
button.danger { background:var(--err); color:#fff; border:none; }
button.danger:hover { filter:brightness(0.95); }
.placeholder { padding:24px; color:var(--text-muted); text-align:center; font-size:13px; }
</style>
<div class="container">
<div class="toolbar">
<h2 class="toolbar-title">Operadores</h2>
<div><button id="btnNew" type="button">+ Nuevo operador</button></div>
</div>
<div class="grid">
<div class="panel">
<h3>Lista</h3>
<div class="list" id="list"></div>
</div>
<div class="panel">
<h3 id="formTitle">Detalle</h3>
<div id="formSlot"></div>
</div>
</div>
</div>
`;
}
connectedCallback() {
this.shadowRoot.getElementById("btnNew").addEventListener("click", () => this.startCreate());
this.load();
}
meId() {
const u = window.__USER__;
return u ? Number(u.id) : null;
}
async load() {
this.loading = true;
this.renderList();
try {
const data = await api.listSystemUsers();
this.users = data.items || [];
this.loading = false;
// Si hay seleccionado, refrescar referencia.
if (this.selected) {
this.selected = this.users.find((u) => Number(u.id) === Number(this.selected.id)) || null;
}
this.renderList();
this.renderForm();
} catch (e) {
this.loading = false;
this.renderList();
}
}
startCreate() {
this.creating = true;
this.selected = null;
this.editing = { email: "", name: "", password: "", active: true };
this.renderList();
this.renderForm();
}
selectUser(user) {
this.creating = false;
this.selected = user;
this.editing = { ...user, password: "" };
this.renderList();
this.renderForm();
}
renderList() {
const list = this.shadowRoot.getElementById("list");
if (this.loading) { list.innerHTML = `<div class="empty">Cargando...</div>`; return; }
if (!this.users.length) { list.innerHTML = `<div class="empty">No hay operadores</div>`; return; }
const meId = this.meId();
list.innerHTML = this.users.map((u) => {
const isMe = Number(u.id) === meId;
const active = !this.creating && this.selected?.id === u.id ? "active" : "";
const inactive = !u.active ? "inactive" : "";
return `
<div class="item ${active} ${inactive}" data-id="${u.id}">
<div class="item-email">${this.escapeHtml(u.email)}${isMe ? '<span class="badge you">Vos</span>' : ""}${!u.active ? '<span class="badge off">Inactivo</span>' : ""}</div>
<div class="item-name">${this.escapeHtml(u.name)}</div>
</div>
`;
}).join("");
list.querySelectorAll(".item[data-id]").forEach((el) => {
el.addEventListener("click", () => {
const u = this.users.find((x) => String(x.id) === el.dataset.id);
if (u) this.selectUser(u);
});
});
}
renderForm() {
const title = this.shadowRoot.getElementById("formTitle");
const slot = this.shadowRoot.getElementById("formSlot");
if (!this.editing) {
title.textContent = "Detalle";
slot.innerHTML = `<div class="placeholder">Seleccioná un operador o creá uno nuevo.</div>`;
return;
}
const isCreate = this.creating;
const meId = this.meId();
const isSelf = !isCreate && Number(this.selected?.id) === meId;
title.textContent = isCreate ? "Nuevo operador" : `Editar — ${this.selected?.email || ""}`;
slot.innerHTML = `
<div class="form">
<div class="field">
<label>Email</label>
<input id="fEmail" type="email" value="${this.escapeHtml(this.editing.email || "")}" ${isCreate ? "" : "disabled"} placeholder="ej. juan@local" autocomplete="off" />
${!isCreate ? '<div class="form-hint">El email no se puede cambiar (volvete a crear el operador si hace falta).</div>' : ""}
</div>
<div class="field">
<label>Nombre</label>
<input id="fName" type="text" value="${this.escapeHtml(this.editing.name || "")}" placeholder="Juan Pérez" />
</div>
<div class="field">
<label>${isCreate ? "Contraseña" : "Cambiar contraseña (opcional)"}</label>
<input id="fPassword" type="password" value="" placeholder="${isCreate ? "Mínimo 8 caracteres" : "Dejar vacío para no cambiar"}" autocomplete="new-password" />
${isCreate ? '<div class="form-hint">Mínimo 8 caracteres.</div>' : ""}
</div>
${isCreate ? "" : `
<div class="field">
<label>Estado</label>
<select id="fActive" ${isSelf ? "disabled" : ""}>
<option value="true" ${this.editing.active ? "selected" : ""}>Activo</option>
<option value="false" ${!this.editing.active ? "selected" : ""}>Inactivo</option>
</select>
${isSelf ? '<div class="form-hint">No podés desactivarte a vos mismo.</div>' : ""}
</div>
`}
<div class="form-actions">
<button id="btnSave" type="button">${this.saving ? "Guardando..." : isCreate ? "Crear" : "Guardar cambios"}</button>
<button id="btnCancel" type="button" class="secondary">Cancelar</button>
${isCreate || isSelf ? "" : '<button id="btnDelete" type="button" class="danger" style="margin-left:auto;">Eliminar</button>'}
</div>
</div>
`;
this.shadowRoot.getElementById("btnCancel").addEventListener("click", () => {
this.creating = false;
this.editing = this.selected ? { ...this.selected, password: "" } : null;
this.renderForm();
});
this.shadowRoot.getElementById("btnSave").addEventListener("click", () => this.save());
this.shadowRoot.getElementById("btnDelete")?.addEventListener("click", () => this.remove());
}
async save() {
const f = this.shadowRoot;
const email = f.getElementById("fEmail").value.trim();
const name = f.getElementById("fName").value.trim();
const password = f.getElementById("fPassword").value;
const activeEl = f.getElementById("fActive");
const active = activeEl ? activeEl.value === "true" : true;
if (this.creating) {
if (!email) return toast({ kind: "error", text: "Email requerido" });
if (!name) return toast({ kind: "error", text: "Nombre requerido" });
if (!password || password.length < 8) return toast({ kind: "error", text: "Contraseña mínimo 8 caracteres" });
} else {
if (!name) return toast({ kind: "error", text: "Nombre requerido" });
if (password && password.length < 8) return toast({ kind: "error", text: "Contraseña mínimo 8 caracteres" });
}
this.saving = true;
this.renderForm();
try {
if (this.creating) {
await api.createSystemUser({ email, name, password, active });
toast({ kind: "ok", text: "Operador creado" });
} else {
const payload = { name, active };
if (password) payload.password = password;
await api.updateSystemUser(this.selected.id, payload);
toast({ kind: "ok", text: "Cambios guardados" });
}
this.creating = false;
await this.load();
} catch (e) {
// safeFetch ya muestra toast
} finally {
this.saving = false;
this.renderForm();
}
}
async remove() {
if (!this.selected) return;
const ok = await modal.confirm(`¿Eliminar al operador ${this.selected.email}? Pierde acceso al sistema.`, { confirmText: "Eliminar", cancelText: "Cancelar" });
if (!ok) return;
try {
await api.deleteSystemUser(this.selected.id);
toast({ kind: "ok", text: "Operador eliminado" });
this.selected = null;
this.editing = null;
await this.load();
} catch (e) {}
}
escapeHtml(s) {
return String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
}
customElements.define("system-users-crud", SystemUsersCrud);