v1.7: overlay carga, baneos, carrito persistente, fix upload
Lista negra: - Migración 0007: tabla baneos con historial (soporta expires_at futuro) - Helper is_banned() usado por middleware - Middleware guard: user baneado → rewrite /banned (admin exento) - Página /banned con razón/fecha/expires + botón signout - Panel /admin/usuarios con banear/desbanear (razón obligatoria, self-ban bloqueado) - Nav admin nueva entrada Usuarios + icono users Fix upload de fotos (bug definitivo): - Root cause: browserClient no autentica al Storage (cookies httpOnly no legibles desde JS) - Nuevos endpoints proxy /api/upload/material-foto/[id] y /avatar - Validan sesión con cookie httpOnly, suben con service_role (bypass RLS) - Refactor MaterialForm y PerfilForm para usar fetch multipart - Cookies httpOnly intactas (cero riesgo XSS) Overlay de carga: - Layout.astro con #page-loader (backdrop-filter blur + spinner mono) - Script inline captura clicks en <a href> y submits de <form> mismo origen - Filtros: modifier keys, target=_blank, anchor#, cross-origin, defaultPrevented - Respeta prefers-reduced-motion; pageshow limpia por bfcache Carrito persistente + vaciar: - SolicitudCart: useEffect hidrata/persiste labre:cart:v1 en localStorage - Guard cartHydrated evita pisar en montaje inicial - Botón "Vaciar" en checkout con window.confirm (solo con perfilCompleto) Filtro inventario sin auto-submit: - Removido script debounced que hacía form.submit() en cada tecla - Botón "Filtrar" existente sigue funcionando
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
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 [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('');
|
||||
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 res = await fetch('/api/admin/baneos', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ profile_id: profile.id, razon: trimmed }),
|
||||
});
|
||||
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-ghost"
|
||||
style={{
|
||||
minHeight: '36px',
|
||||
paddingBlock: '0.25rem',
|
||||
color: adminSelf ? undefined : 'var(--color-danger-text)',
|
||||
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="rounded-lg p-0 bg-white text-[color:var(--color-ink)] border-2 border-[color:var(--color-ink)] shadow-[var(--shadow-hard)] backdrop:bg-black/40 w-[min(92vw,28rem)]"
|
||||
>
|
||||
<form onSubmit={submit} className="p-5 sm:p-6 flex flex-col gap-4" autoComplete="off">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<h2 id={titleId} className="text-lg font-semibold">
|
||||
Banear a {label}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={close}
|
||||
aria-label="Cerrar"
|
||||
className="rounded-lg p-1 hover:bg-black/5 transition-colors leading-none text-xl"
|
||||
>
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="text-sm" style={{ color: 'var(--color-pencil)' }}>
|
||||
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 mt-1" style={{ color: 'var(--color-pencil)' }}>
|
||||
{razon.length}/500
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p
|
||||
ref={errorRef}
|
||||
id={`${titleId}-err`}
|
||||
role="alert"
|
||||
tabIndex={-1}
|
||||
className="text-sm"
|
||||
style={{ color: 'var(--color-danger-text)' }}
|
||||
>
|
||||
{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"
|
||||
style={{ background: 'var(--color-danger)', color: 'var(--color-ink)' }}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? 'Baneando…' : 'Banear'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user