feat(admin): Registro de transacciones — log de auditoría de todo el sistema
NUEVA INFRAESTRUCTURA * SQL 010: tabla audit_log (id, fecha, user_email, user_name, modulo, accion, entity_type, entity_id, entity_label, detalles JSON, ip_addr) con índices por fecha/user/modulo/accion/entity. * src/AuditLog.php: helper estático con dos métodos: - log() lee actor de $_SESSION (uso normal post-auth) - logAs() recibe email/name explícito (para login/logout y CLI) Falla silenciosamente si la DB no responde — no rompe la operación principal por un fallo de logging. HOOKS EN MUTACIONES * Auth.php: registra 'login' al completar OAuth y 'logout' antes de destruir la sesión. * escrituras/api.php: registra create/update/delete con id+nombre. * tramites/api.php: registra 8 mutaciones — create/update/delete del trámite, set_status (con nuevo estatus en detalles), add_obs, add_hours/update_hours/delete_hours (con abogado y horas en detalles), todos referenciados por codigo (ADM-001, etc.). * admin/api.php: registra create_user/update_user/delete_user, con diff de cambios en update_user. * GETs (list_*) no se loguean — serían ruido. LECTOR * admin/api.php nuevo endpoint GET ?action=list_log que devuelve entradas con filtros from/to/user/modulo/accion/search (LIKE) + catálogos para dropdowns. Límite 500 por query. UI EN PANEL DE CONTROL * admin.html ahora tiene tabs: "Usuarios" (existente) y "Registro de transacciones" (nuevo). * Tab Registro: toolbar de filtros (rango fechas, usuario, módulo, acción, búsqueda libre, atajos Hoy/Semana/Mes/Todo) + tabla con Fecha·Hora · Usuario · Módulo (pill coloreado) · Acción · Entidad con label y tipo · Detalles JSON resumido.
This commit is contained in:
@@ -137,6 +137,38 @@ tr.is-me td { background:#FFFBEB; font-weight:500; }
|
||||
.toast.error { border-left-color:#ef5350; }
|
||||
|
||||
.empty { text-align:center; padding:40px; color:var(--gray-400); }
|
||||
|
||||
/* TABS */
|
||||
.tabs-wrap { max-width:1180px; margin:18px auto 0; padding:0 24px; display:flex; gap:4px; border-bottom:1px solid var(--gray-200); }
|
||||
.tab { padding:10px 18px; cursor:pointer; font-size:13px; font-weight:500; color:var(--gray-700);
|
||||
border-bottom:3px solid transparent; transition:all .15s; }
|
||||
.tab:hover { color:var(--navy); }
|
||||
.tab.active { color:var(--navy); border-bottom-color:var(--gold); font-weight:600; }
|
||||
.panel { display:none; }
|
||||
.panel.active { display:block; }
|
||||
|
||||
/* AUDIT LOG */
|
||||
.log-toolbar { max-width:1180px; margin:18px auto 12px; padding:0 24px; display:flex; gap:10px; flex-wrap:wrap; align-items:flex-end; }
|
||||
.log-tbl { max-width:1180px; margin:0 auto 32px; padding:0 24px; }
|
||||
.log-tbl table th, .log-tbl table td { white-space:normal; }
|
||||
.log-fecha { font-family:ui-monospace,monospace; font-size:11.5px; color:var(--gray-700); white-space:nowrap; }
|
||||
.log-user { font-weight:500; color:var(--gray-900); }
|
||||
.log-user-email { font-size:10.5px; color:var(--gray-400); display:block; }
|
||||
.log-mod { display:inline-block; padding:2px 9px; border-radius:12px; font-size:10.5px; font-weight:700;
|
||||
text-transform:uppercase; letter-spacing:.05em; color:#fff; }
|
||||
.mod-auth { background:#6c5b95; } .mod-escrituras { background:#1B3A6B; }
|
||||
.mod-tramites { background:#9E7C2E; } .mod-admin { background:#722f37; }
|
||||
.mod-default { background:#9B9A96; }
|
||||
.log-accion { font-family:ui-monospace,monospace; font-size:11.5px; color:var(--navy); font-weight:600; }
|
||||
.log-entity { font-size:12px; color:var(--gray-700); }
|
||||
.log-entity small { color:var(--gray-400); font-size:10.5px; }
|
||||
.log-detalles { font-size:11px; color:var(--gray-400); max-width:320px; word-break:break-word;
|
||||
font-family:ui-monospace,monospace; }
|
||||
.log-row-limit { padding:14px; text-align:center; font-size:11.5px; color:var(--gray-400);
|
||||
background:var(--off); border-top:1px solid var(--gray-100); }
|
||||
.tb-quick-log { font-size:11px; padding:6px 10px; background:var(--off); border:1px solid var(--gray-200);
|
||||
border-radius:6px; color:var(--gray-700); transition:all .15s; }
|
||||
.tb-quick-log:hover { background:var(--navy); color:#fff; border-color:var(--navy); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -167,6 +199,13 @@ tr.is-me td { background:#FFFBEB; font-weight:500; }
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="tabs-wrap">
|
||||
<div class="tab active" data-tab="users" onclick="switchTab('users')">Usuarios</div>
|
||||
<div class="tab" data-tab="log" onclick="switchTab('log')">Registro de transacciones</div>
|
||||
</div>
|
||||
|
||||
<div class="panel active" id="panel-users">
|
||||
|
||||
<div class="intro">
|
||||
<h1>Usuarios y permisos</h1>
|
||||
<p>Administra la lista unificada de usuarios del sistema. El campo <b>Nombre completo</b> es lo que aparece en el dropdown "Abogado Solicitante" (solo si el rol es <b>Socio</b> o <b>Abogado</b>). Los emails que empiezan con <code>placeholder-</code> son los nombres sembrados al inicio para que los dropdowns no salieran vacíos; reemplázalos con los emails reales conforme los abogados se logueen.</p>
|
||||
@@ -209,6 +248,72 @@ tr.is-me td { background:#FFFBEB; font-weight:500; }
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div><!-- /panel-users -->
|
||||
|
||||
<div class="panel" id="panel-log">
|
||||
<div class="intro">
|
||||
<h1>Registro de transacciones</h1>
|
||||
<p>Cada login, logout, creación, edición y eliminación queda registrada con el usuario que la ejecutó. Útil para auditoría y para entender quién hizo qué.</p>
|
||||
</div>
|
||||
|
||||
<div class="log-toolbar">
|
||||
<div class="tb-group">
|
||||
<label>Desde</label>
|
||||
<input type="date" id="log-from">
|
||||
</div>
|
||||
<div class="tb-group">
|
||||
<label>Hasta</label>
|
||||
<input type="date" id="log-to">
|
||||
</div>
|
||||
<div class="tb-group">
|
||||
<label>Usuario</label>
|
||||
<select id="log-user"><option value="">— Todos —</option></select>
|
||||
</div>
|
||||
<div class="tb-group">
|
||||
<label>Módulo</label>
|
||||
<select id="log-modulo"><option value="">— Todos —</option></select>
|
||||
</div>
|
||||
<div class="tb-group">
|
||||
<label>Acción</label>
|
||||
<select id="log-accion"><option value="">— Todas —</option></select>
|
||||
</div>
|
||||
<div class="tb-group" style="flex:1;min-width:160px;">
|
||||
<label>Búsqueda libre</label>
|
||||
<input type="search" id="log-search" placeholder="texto en nombre, entidad o detalles…">
|
||||
</div>
|
||||
<div class="tb-group">
|
||||
<label> </label>
|
||||
<div style="display:flex;gap:5px;">
|
||||
<button class="tb-quick-log" onclick="setLogQuick('today')">Hoy</button>
|
||||
<button class="tb-quick-log" onclick="setLogQuick('week')">Semana</button>
|
||||
<button class="tb-quick-log" onclick="setLogQuick('month')">Mes</button>
|
||||
<button class="tb-quick-log" onclick="setLogQuick('all')">Todo</button>
|
||||
<button class="btn-primary" onclick="loadLog()" style="padding:7px 14px;">Aplicar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="log-tbl">
|
||||
<div class="tbl-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fecha · Hora</th>
|
||||
<th>Usuario</th>
|
||||
<th>Módulo</th>
|
||||
<th>Acción</th>
|
||||
<th>Entidad</th>
|
||||
<th>Detalles</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="log-tbody"></tbody>
|
||||
</table>
|
||||
<div id="log-empty" class="empty" style="display:none;">Sin transacciones en el período seleccionado.</div>
|
||||
<div id="log-rowinfo" class="log-row-limit" style="display:none;"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div><!-- /panel-log -->
|
||||
|
||||
<div class="modal-overlay" id="modal">
|
||||
<div class="modal">
|
||||
<header class="modal-head">
|
||||
@@ -481,6 +586,113 @@ document.addEventListener('keydown', e => {
|
||||
$(id).addEventListener('change', render);
|
||||
});
|
||||
|
||||
// ── TABS ─────────────────────────────────────────────────────
|
||||
function switchTab(name){
|
||||
document.querySelectorAll('.tab').forEach(t => t.classList.toggle('active', t.dataset.tab === name));
|
||||
document.querySelectorAll('.panel').forEach(p => p.classList.toggle('active', p.id === 'panel-' + name));
|
||||
if (name === 'log' && !logLoaded) { defaultLogDates(); loadLog(); logLoaded = true; }
|
||||
}
|
||||
|
||||
// ── AUDIT LOG ────────────────────────────────────────────────
|
||||
let logLoaded = false;
|
||||
const MOD_LABEL = { auth:'Auth', escrituras:'Escrituras', tramites:'Trámites', admin:'Admin', horas:'Horas', calendario:'Calendario' };
|
||||
const ACCION_LABEL = {
|
||||
login:'Login', logout:'Logout',
|
||||
create:'Crear', update:'Editar', delete:'Eliminar',
|
||||
create_user:'Crear usuario', update_user:'Editar usuario', delete_user:'Eliminar usuario',
|
||||
set_status:'Cambiar estatus', add_obs:'Agregar observación',
|
||||
add_hours:'Agregar horas', update_hours:'Editar horas', delete_hours:'Eliminar horas',
|
||||
};
|
||||
|
||||
function defaultLogDates(){
|
||||
const now = new Date();
|
||||
const first = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
const ymd = d => d.toISOString().slice(0,10);
|
||||
$('log-from').value = ymd(first);
|
||||
$('log-to').value = ymd(now);
|
||||
}
|
||||
function setLogQuick(period){
|
||||
const now = new Date();
|
||||
let from, to = now;
|
||||
if (period === 'today') from = now;
|
||||
if (period === 'week') { const d = now.getDay() || 7; from = new Date(now); from.setDate(now.getDate()-d+1); }
|
||||
if (period === 'month') from = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
if (period === 'all') { $('log-from').value = ''; $('log-to').value = ''; loadLog(); return; }
|
||||
const ymd = d => d.toISOString().slice(0,10);
|
||||
$('log-from').value = ymd(from);
|
||||
$('log-to').value = ymd(to);
|
||||
loadLog();
|
||||
}
|
||||
function fmtLogDate(dt){
|
||||
if(!dt) return '—';
|
||||
const d=new Date(dt); if(isNaN(d)) return dt;
|
||||
return d.toLocaleDateString('es-PA',{day:'2-digit',month:'2-digit',year:'numeric'})
|
||||
+' · '+d.toLocaleTimeString('es-PA',{hour:'2-digit',minute:'2-digit',second:'2-digit'});
|
||||
}
|
||||
async function loadLog(){
|
||||
const params = new URLSearchParams();
|
||||
['from','to','user','modulo','accion','search'].forEach(k => {
|
||||
const v = $('log-'+k).value;
|
||||
if (v) params.set(k, v);
|
||||
});
|
||||
try {
|
||||
const d = await apiCall('GET', 'list_log', null, params.toString());
|
||||
if (!d) return;
|
||||
// Poblar dropdowns con catálogos vistos
|
||||
populateLogDropdowns(d);
|
||||
renderLog(d.entries||[]);
|
||||
} catch(e){ toast('Error: '+e.message, 'error'); }
|
||||
}
|
||||
function populateLogDropdowns(d){
|
||||
// Usuarios (preserva selección)
|
||||
const uSel = $('log-user'); const uPrev = uSel.value;
|
||||
uSel.innerHTML = '<option value="">— Todos —</option>' +
|
||||
(d.usuarios||[]).map(u => `<option value="${esc(u.user_email)}">${esc(u.user_name || u.user_email)}</option>`).join('');
|
||||
uSel.value = uPrev;
|
||||
// Módulos
|
||||
const mSel = $('log-modulo'); const mPrev = mSel.value;
|
||||
mSel.innerHTML = '<option value="">— Todos —</option>' +
|
||||
(d.modulos||[]).map(m => `<option value="${esc(m)}">${esc(MOD_LABEL[m] || m)}</option>`).join('');
|
||||
mSel.value = mPrev;
|
||||
// Acciones
|
||||
const aSel = $('log-accion'); const aPrev = aSel.value;
|
||||
aSel.innerHTML = '<option value="">— Todas —</option>' +
|
||||
(d.acciones||[]).map(a => `<option value="${esc(a)}">${esc(ACCION_LABEL[a] || a)}</option>`).join('');
|
||||
aSel.value = aPrev;
|
||||
}
|
||||
function renderLog(entries){
|
||||
const tbody = $('log-tbody');
|
||||
const empty = $('log-empty');
|
||||
const info = $('log-rowinfo');
|
||||
if (!entries.length) { tbody.innerHTML=''; empty.style.display='block'; info.style.display='none'; return; }
|
||||
empty.style.display = 'none';
|
||||
tbody.innerHTML = entries.map(e => {
|
||||
const modClass = MOD_LABEL[e.modulo] ? 'mod-' + e.modulo : 'mod-default';
|
||||
const detallesShort = e.detalles ? esc(e.detalles).substring(0, 280) : '';
|
||||
const entityCol = e.entity_label
|
||||
? `<b>${esc(e.entity_label)}</b>${e.entity_type?` <small>${esc(e.entity_type)}</small>`:''}`
|
||||
: (e.entity_type ? `<small>${esc(e.entity_type)}</small>` : '—');
|
||||
return `<tr>
|
||||
<td class="log-fecha">${esc(fmtLogDate(e.fecha))}</td>
|
||||
<td><span class="log-user">${esc(e.user_name || '—')}</span><span class="log-user-email">${esc(e.user_email || '')}</span></td>
|
||||
<td><span class="log-mod ${modClass}">${esc(MOD_LABEL[e.modulo] || e.modulo)}</span></td>
|
||||
<td class="log-accion">${esc(ACCION_LABEL[e.accion] || e.accion)}</td>
|
||||
<td class="log-entity">${entityCol}</td>
|
||||
<td class="log-detalles">${detallesShort}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
info.style.display = 'block';
|
||||
info.textContent = `Mostrando ${entries.length} transacciones` + (entries.length >= 500 ? ' (límite del servidor — ajusta los filtros para ver más).' : '.');
|
||||
}
|
||||
|
||||
['log-from','log-to','log-user','log-modulo','log-accion'].forEach(id => {
|
||||
$(id).addEventListener('change', loadLog);
|
||||
});
|
||||
$('log-search').addEventListener('input', () => {
|
||||
clearTimeout(window._logSearchTimer);
|
||||
window._logSearchTimer = setTimeout(loadLog, 350);
|
||||
});
|
||||
|
||||
loadUsers();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
Reference in New Issue
Block a user