Files
labre-web/src/components/admin/usuarios/BanearForm.tsx
T
LakG ac3e7061ac Rediseño visual UABC + Mulish + auditoría de BD (P0/P1)
Rediseño visual:
- Nueva identidad UABC/editorial (DESIGN.md), tipografía Mulish, tokens
  verde/dorado/negro sobre bone-white, patrón de puntos verde en canvas,
  radios 8/12/30/9999, sin sombras, hairline 1px, tarjetas con leve
  transparencia + blur suave + borde verde muy sutil.
- 45 archivos .astro/.tsx alineados al nuevo sistema (Track A/B/C/D/E).
- Limpieza post-critique: eliminado triple CTA en home alumno, .card
  anidados en admin, aria-live decorativo, 26 aliases legacy en global.css,
  border-l verde en nav (patrón AI-slop), classList.remove obsoletos.

Auditoría de llamadas a BD (para 20-50 usuarios concurrentes):
- P0-1: middleware con cache in-memory de profile (30s) + is_banned (30s)
  por uid; exclusión de assets estáticos (/_astro/*, /audio/*, favicon).
  Invalidación en signout, PATCH /profile, baneos.
- P0-2: eliminado count pendientes duplicado en AppLayout; badge se
  hidrata client-side (BadgeSolicitudes con fetch inicial).
- P0-3: migración 0008 REPLICA IDENTITY FULL en solicitudes + delta
  preciso en BadgeSolicitudes (con fallback a refetch).
- P1: admin/index dedupe (4 queries → 2 con recientes.filter), catalogo
  reusa profile del middleware (3 queries → 1), inventario paralelo,
  estadisticas con cache 60s en RAM (stats-cache.ts), migración 0009
  con 3 índices (fecha, vencidos parcial, audit compuesto).

Fixes P0 de UI post-critique:
- estadisticas.astro: ReferenceError DIAS restaurado.
- solicitudes (3 vistas): error rendering sanitizado (no expone mensaje
  Postgres crudo al admin).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014xaxs8cGcQe9NwbMqA1gvn
2026-09-21 09:42:12 -07:00

203 lines
6.4 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
import { toastAfterReload } from '@/lib/toast';
type Props = {
profile: { id: string; nombre?: string | null; email: string };
adminSelf: boolean;
};
export default function BanearForm({ profile, adminSelf }: Props) {
const dialogRef = useRef<HTMLDialogElement | null>(null);
const firstFieldRef = useRef<HTMLTextAreaElement | null>(null);
const errorRef = useRef<HTMLParagraphElement | null>(null);
const [razon, setRazon] = useState('');
const [expiresAt, setExpiresAt] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const titleId = `banear-${profile.id}`;
const label = profile.nombre?.trim() || profile.email;
const open = () => {
if (adminSelf) return;
setError(null);
setRazon('');
setExpiresAt('');
dialogRef.current?.showModal();
queueMicrotask(() => firstFieldRef.current?.focus());
};
const close = () => {
if (loading) return;
dialogRef.current?.close();
};
useEffect(() => {
const dlg = dialogRef.current;
if (!dlg) return;
const onClick = (e: MouseEvent) => {
if (e.target === dlg) close();
};
dlg.addEventListener('click', onClick);
return () => dlg.removeEventListener('click', onClick);
});
useEffect(() => {
if (error) errorRef.current?.focus();
}, [error]);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
if (loading) return;
const trimmed = razon.trim();
if (trimmed.length < 5) {
setError('La razón debe tener al menos 5 caracteres');
return;
}
setLoading(true);
setError(null);
try {
const payload: { profile_id: string; razon: string; expires_at?: string } = {
profile_id: profile.id,
razon: trimmed,
};
if (expiresAt) {
payload.expires_at = new Date(expiresAt + 'T23:59:59').toISOString();
}
const res = await fetch('/api/admin/baneos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(json?.error ?? 'No se pudo banear');
toastAfterReload({
title: 'Usuario baneado',
description: label,
kind: 'success',
});
dialogRef.current?.close();
location.reload();
} catch (err) {
setError(err instanceof Error ? err.message : 'Error inesperado');
} finally {
setLoading(false);
}
};
return (
<>
<button
type="button"
className="btn btn-danger text-xs px-3"
style={{
minHeight: '36px',
paddingBlock: '0.25rem',
opacity: adminSelf ? 0.5 : 1,
cursor: adminSelf ? 'not-allowed' : undefined,
}}
onClick={open}
disabled={adminSelf}
title={adminSelf ? 'No puedes banearte a ti mismo' : undefined}
aria-label={adminSelf ? 'No puedes banearte a ti mismo' : `Banear a ${label}`}
>
Banear
</button>
<dialog
ref={dialogRef}
aria-labelledby={titleId}
className="card bg-bone-white rounded-[12px] p-0 border border-hairline-gray backdrop:bg-negro-institucional/40 w-[min(92vw,28rem)]"
style={{ boxShadow: 'none' }}
>
<form onSubmit={submit} className="p-6 flex flex-col gap-4" autoComplete="off">
<div className="flex items-start justify-between gap-3">
<h2 id={titleId} className="text-xl text-graphite font-normal">
Banear a {label}
</h2>
<button
type="button"
onClick={close}
aria-label="Cerrar"
className="rounded-[8px] p-1.5 hover:bg-linen text-graphite transition-colors leading-none"
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
<path d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<p className="text-sm text-graphite/70">
El usuario no podrá acceder al sistema hasta ser desbaneado.
</p>
<div>
<label className="label" htmlFor={`${titleId}-razon`}>
Razón del baneo
</label>
<textarea
ref={firstFieldRef}
id={`${titleId}-razon`}
className="input"
rows={4}
value={razon}
onChange={(e) => setRazon(e.target.value)}
required
minLength={5}
maxLength={500}
aria-invalid={error ? true : undefined}
aria-describedby={error ? `${titleId}-err` : undefined}
placeholder="Explica el motivo — el usuario lo verá en su pantalla de bloqueo."
/>
<p className="text-xs text-graphite/60 mt-1">
{razon.length}/500
</p>
</div>
<div>
<label className="label" htmlFor={`${titleId}-expires`}>
Fecha de expiración (opcional)
</label>
<input
id={`${titleId}-expires`}
type="date"
className="input"
value={expiresAt}
min={new Date().toISOString().split('T')[0]}
onChange={(e) => setExpiresAt(e.target.value)}
/>
<p className="text-xs text-graphite/60 mt-1">
Opcional. Si se omite, el baneo será indefinido hasta desbanear manualmente.
</p>
</div>
{error && (
<p
ref={errorRef}
id={`${titleId}-err`}
role="alert"
tabIndex={-1}
className="text-sm text-negro-institucional"
>
{error}
</p>
)}
<div className="flex gap-2 justify-end pt-2">
<button type="button" className="btn btn-ghost" onClick={close} disabled={loading}>
Cancelar
</button>
<button
type="submit"
className="btn btn-danger"
disabled={loading}
>
{loading ? 'Baneando…' : 'Banear'}
</button>
</div>
</form>
</dialog>
</>
);
}