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:
@@ -1,5 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { browserClient } from '@/lib/supabase';
|
||||
import { imgUrl } from '@/lib/materialImg';
|
||||
import { toast } from '@/lib/toast';
|
||||
import UnidadesManager from './UnidadesManager';
|
||||
@@ -25,8 +24,6 @@ type Props = {
|
||||
compact?: boolean;
|
||||
};
|
||||
|
||||
const BUCKET = 'materiales-fotos';
|
||||
|
||||
export default function MaterialForm({ mode, material, categorias, compact }: Props) {
|
||||
const dialogRef = useRef<HTMLDialogElement | null>(null);
|
||||
const firstFieldRef = useRef<HTMLInputElement | null>(null);
|
||||
@@ -99,18 +96,16 @@ export default function MaterialForm({ mode, material, categorias, compact }: Pr
|
||||
if (error) errorRef.current?.focus();
|
||||
}, [error]);
|
||||
|
||||
async function uploadFotoFor(id: number): Promise<string | null> {
|
||||
if (!file) return null;
|
||||
const ext = (file.name.split('.').pop() ?? 'jpg').toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||
const path = `${id}/${Date.now()}.${ext || 'jpg'}`;
|
||||
const { error: upErr } = await browserClient()
|
||||
.storage.from(BUCKET)
|
||||
.upload(path, file, { upsert: true, contentType: file.type || undefined });
|
||||
if (upErr) {
|
||||
toast({ kind: 'error', title: 'La foto no se subió', description: 'El material se guardó sin foto.' });
|
||||
async function uploadFotoFor(materialId: number, f: File): Promise<string | null> {
|
||||
const fd = new FormData();
|
||||
fd.append('file', f);
|
||||
const res = await fetch(`/api/upload/material-foto/${materialId}`, { method: 'POST', body: fd });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
toast({ kind: 'error', title: 'La foto no se subió', description: json?.error ?? 'El material se guardó sin foto.' });
|
||||
return null;
|
||||
}
|
||||
return path;
|
||||
return json.path as string;
|
||||
}
|
||||
|
||||
const submit = async (e: React.FormEvent) => {
|
||||
@@ -151,26 +146,14 @@ export default function MaterialForm({ mode, material, categorias, compact }: Pr
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(json?.error ?? 'No se pudo crear');
|
||||
|
||||
// 2) subir foto (si hay) y PATCH imagen_path
|
||||
// 2) subir foto (si hay) — el endpoint ya persiste imagen_path
|
||||
if (file && json.id) {
|
||||
const path = await uploadFotoFor(json.id);
|
||||
if (path) {
|
||||
const p = await fetch(`/api/admin/materiales/${json.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ imagen_path: path }),
|
||||
});
|
||||
if (!p.ok) {
|
||||
toast({ kind: 'error', title: 'Foto subida pero no vinculada', description: 'Recarga y vuelve a intentar.' });
|
||||
}
|
||||
}
|
||||
await uploadFotoFor(json.id, file);
|
||||
}
|
||||
} else {
|
||||
// edit — sube nueva foto primero (si hay) y luego PATCH con el path incluido
|
||||
let newImagenPath: string | null | undefined = undefined;
|
||||
// edit — sube nueva foto primero (si hay); el endpoint persiste imagen_path
|
||||
if (file && material) {
|
||||
const path = await uploadFotoFor(material.id);
|
||||
if (path) newImagenPath = path;
|
||||
await uploadFotoFor(material.id, file);
|
||||
}
|
||||
const patch: Record<string, unknown> = {
|
||||
nombre: nombreT,
|
||||
@@ -181,7 +164,7 @@ export default function MaterialForm({ mode, material, categorias, compact }: Pr
|
||||
trackeado_por_unidad: trackeado,
|
||||
};
|
||||
if (!trackeado) patch.cantidad_total = cantidad;
|
||||
if (newImagenPath !== undefined) patch.imagen_path = newImagenPath;
|
||||
// ponytail: si el user quitó la foto (imagenPath=null y sin file), no lo PATCHeamos aquí — ese flow ya está fuera de scope de este fix
|
||||
const res = await fetch(`/api/admin/materiales/${material!.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useState } from 'react';
|
||||
import { toastAfterReload } from '@/lib/toast';
|
||||
|
||||
type Props = {
|
||||
baneoId: number;
|
||||
nombre: string;
|
||||
};
|
||||
|
||||
export default function DesbanearButton({ baneoId, nombre }: Props) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const submit = async () => {
|
||||
if (loading) return;
|
||||
if (!window.confirm(`¿Desbanear a ${nombre}? Recuperará acceso inmediato.`)) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(`/api/admin/baneos/${baneoId}/desbanear`, { method: 'POST' });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(json?.error ?? 'No se pudo desbanear');
|
||||
toastAfterReload({
|
||||
title: 'Usuario desbaneado',
|
||||
description: nombre,
|
||||
kind: 'success',
|
||||
});
|
||||
location.reload();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Error inesperado');
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
style={{ minHeight: '36px', paddingBlock: '0.25rem' }}
|
||||
onClick={submit}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? 'Desbaneando…' : 'Desbanear'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -55,6 +55,7 @@ export default function CartProvider({
|
||||
maestros?: MaestroOpt[];
|
||||
}) {
|
||||
const [cart, setCart] = useState<Map<number, CartItem>>(new Map());
|
||||
const cartHydrated = useRef(false);
|
||||
const dialogRef = useRef<HTMLDialogElement | null>(null);
|
||||
const firstFieldRef = useRef<HTMLSelectElement | null>(null);
|
||||
const [maestroId, setMaestroId] = useState<string>('');
|
||||
@@ -130,6 +131,43 @@ export default function CartProvider({
|
||||
dialogRef.current?.close();
|
||||
};
|
||||
|
||||
// Hidrata carrito desde localStorage al montar
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
try {
|
||||
const raw = window.localStorage.getItem('labre:cart:v1');
|
||||
if (raw) {
|
||||
const arr = JSON.parse(raw);
|
||||
if (Array.isArray(arr)) {
|
||||
const next = new Map<number, CartItem>();
|
||||
for (const i of arr) {
|
||||
if (i && typeof i.material_id === 'number' && typeof i.nombre === 'string') {
|
||||
next.set(i.material_id, {
|
||||
material_id: i.material_id,
|
||||
nombre: i.nombre,
|
||||
cantidad: clamp(Number(i.cantidad) || 1, Number(i.cantidad_disponible) || 1),
|
||||
cantidad_disponible: Number(i.cantidad_disponible) || 1,
|
||||
descripcion: typeof i.descripcion === 'string' ? i.descripcion : '',
|
||||
});
|
||||
}
|
||||
}
|
||||
if (next.size > 0) setCart(next);
|
||||
}
|
||||
}
|
||||
} catch { /* localStorage bloqueado o JSON inválido */ }
|
||||
cartHydrated.current = true;
|
||||
}, []);
|
||||
|
||||
// Persiste carrito a localStorage cuando cambia (después de la hidratación inicial)
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
if (!cartHydrated.current) return;
|
||||
try {
|
||||
if (cart.size === 0) window.localStorage.removeItem('labre:cart:v1');
|
||||
else window.localStorage.setItem('labre:cart:v1', JSON.stringify(Array.from(cart.values())));
|
||||
} catch { /* localStorage bloqueado */ }
|
||||
}, [cart]);
|
||||
|
||||
// Cerrar al click en backdrop
|
||||
useEffect(() => {
|
||||
const dlg = dialogRef.current;
|
||||
@@ -385,13 +423,23 @@ export default function CartProvider({
|
||||
<a href="/perfil" className="btn btn-primary">Completar perfil</a>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-2 justify-end pt-2">
|
||||
<button type="button" className="btn btn-ghost" onClick={closeCheckout} disabled={loading}>
|
||||
Cancelar
|
||||
</button>
|
||||
<button type="submit" className="btn btn-primary" disabled={loading || ok || items.length === 0}>
|
||||
{loading ? 'Enviando…' : 'Enviar solicitud'}
|
||||
<div className="flex gap-2 justify-between items-center pt-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost"
|
||||
onClick={() => { if (window.confirm('¿Vaciar todo el carrito?')) setCart(new Map()); }}
|
||||
disabled={loading || items.length === 0}
|
||||
>
|
||||
Vaciar
|
||||
</button>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" className="btn btn-ghost" onClick={closeCheckout} disabled={loading}>
|
||||
Cancelar
|
||||
</button>
|
||||
<button type="submit" className="btn btn-primary" disabled={loading || ok || items.length === 0}>
|
||||
{loading ? 'Enviando…' : 'Enviar solicitud'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { browserClient } from '@/lib/supabase';
|
||||
import { avatarInfo } from '@/lib/avatar';
|
||||
import { toast, toastAfterReload } from '@/lib/toast';
|
||||
import Avatar from './Avatar';
|
||||
@@ -22,7 +21,6 @@ type Props = {
|
||||
mode?: 'edit' | 'onboarding';
|
||||
};
|
||||
|
||||
const BUCKET = 'avatares';
|
||||
const SEM_OPTS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
|
||||
|
||||
export default function PerfilForm({
|
||||
@@ -69,18 +67,16 @@ export default function PerfilForm({
|
||||
? { ...info, src: previewUrl }
|
||||
: info;
|
||||
|
||||
async function uploadAvatar(): Promise<string | null> {
|
||||
if (!file) return null;
|
||||
const ext = (file.name.split('.').pop() ?? 'jpg').toLowerCase().replace(/[^a-z0-9]/g, '') || 'jpg';
|
||||
const path = `${userId}/${Date.now()}.${ext}`;
|
||||
const { error: upErr } = await browserClient()
|
||||
.storage.from(BUCKET)
|
||||
.upload(path, file, { upsert: true, contentType: file.type || undefined });
|
||||
if (upErr) {
|
||||
toast({ kind: 'error', title: 'La foto no se subió', description: upErr.message });
|
||||
return null;
|
||||
async function uploadAvatar(f: File): Promise<boolean> {
|
||||
const fd = new FormData();
|
||||
fd.append('file', f);
|
||||
const res = await fetch('/api/upload/avatar', { method: 'POST', body: fd });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
toast({ kind: 'error', title: 'La foto no se subió', description: json?.error ?? 'Intenta de nuevo.' });
|
||||
return false;
|
||||
}
|
||||
return path;
|
||||
return true;
|
||||
}
|
||||
|
||||
const submit = async (e: React.FormEvent) => {
|
||||
@@ -89,9 +85,10 @@ export default function PerfilForm({
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
let nuevoPath: string | null | undefined = undefined;
|
||||
// La foto se sube por su propio endpoint (que ya persiste foto_path).
|
||||
// El PATCH /api/profile solo maneja matricula/semestre/tutor.
|
||||
if (file) {
|
||||
nuevoPath = await uploadAvatar();
|
||||
await uploadAvatar(file);
|
||||
}
|
||||
const body: Record<string, string | number | null> = {
|
||||
matricula: matricula.trim() || null,
|
||||
@@ -100,7 +97,6 @@ export default function PerfilForm({
|
||||
body.semestre = semestre || null;
|
||||
body.tutor_id = tutorId ? Number(tutorId) : null;
|
||||
}
|
||||
if (nuevoPath !== undefined) body.foto_path = nuevoPath;
|
||||
|
||||
const res = await fetch('/api/profile', {
|
||||
method: 'PATCH',
|
||||
|
||||
Reference in New Issue
Block a user