dea268d975
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
450 lines
17 KiB
TypeScript
450 lines
17 KiB
TypeScript
import { createContext, useContext, useEffect, useMemo, useRef, useState } from 'react';
|
|
import { toast, toastAfterReload } from '@/lib/toast';
|
|
import AgregarMaterial from './AgregarMaterial';
|
|
|
|
type Material = {
|
|
id: number;
|
|
nombre: string;
|
|
descripcion: string | null;
|
|
cantidad_disponible: number;
|
|
cantidad_total: number;
|
|
numero_inventario: string | null;
|
|
categoria: { id: number; nombre: string } | null;
|
|
};
|
|
|
|
type CartItem = {
|
|
material_id: number;
|
|
nombre: string;
|
|
cantidad: number;
|
|
cantidad_disponible: number;
|
|
descripcion: string;
|
|
};
|
|
|
|
type CartContextValue = {
|
|
items: CartItem[];
|
|
addItem: (material: { id: number; nombre: string; cantidad_disponible: number }) => void;
|
|
updateCantidad: (material_id: number, n: number) => void;
|
|
updateDescripcion: (material_id: number, texto: string) => void;
|
|
removeItem: (material_id: number) => void;
|
|
has: (material_id: number) => boolean;
|
|
};
|
|
|
|
const CartContext = createContext<CartContextValue | null>(null);
|
|
|
|
export function useCart() {
|
|
const ctx = useContext(CartContext);
|
|
if (!ctx) throw new Error('useCart debe usarse dentro de CartProvider');
|
|
return ctx;
|
|
}
|
|
|
|
const clamp = (n: number, max: number) => Math.max(1, Math.min(max, n));
|
|
|
|
type MaestroOpt = { id: number; nombre: string };
|
|
|
|
export default function CartProvider({
|
|
materiales,
|
|
tutorNombre = null,
|
|
perfilCompleto = true,
|
|
esDocente = false,
|
|
maestros = [],
|
|
}: {
|
|
materiales: Material[];
|
|
tutorNombre?: string | null;
|
|
perfilCompleto?: boolean;
|
|
esDocente?: boolean;
|
|
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>('');
|
|
const [notas, setNotas] = useState('');
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [ok, setOk] = useState(false);
|
|
|
|
const items = useMemo(() => Array.from(cart.values()), [cart]);
|
|
|
|
const addItem: CartContextValue['addItem'] = (material) => {
|
|
setCart((prev) => {
|
|
const next = new Map(prev);
|
|
const existing = next.get(material.id);
|
|
if (existing) {
|
|
next.set(material.id, { ...existing, cantidad: clamp(existing.cantidad + 1, material.cantidad_disponible) });
|
|
} else {
|
|
next.set(material.id, {
|
|
material_id: material.id,
|
|
nombre: material.nombre,
|
|
cantidad: 1,
|
|
cantidad_disponible: material.cantidad_disponible,
|
|
descripcion: '',
|
|
});
|
|
}
|
|
return next;
|
|
});
|
|
};
|
|
|
|
const updateCantidad: CartContextValue['updateCantidad'] = (material_id, n) => {
|
|
setCart((prev) => {
|
|
const existing = prev.get(material_id);
|
|
if (!existing) return prev;
|
|
const next = new Map(prev);
|
|
next.set(material_id, { ...existing, cantidad: clamp(n, existing.cantidad_disponible) });
|
|
return next;
|
|
});
|
|
};
|
|
|
|
const updateDescripcion: CartContextValue['updateDescripcion'] = (material_id, texto) => {
|
|
setCart((prev) => {
|
|
const existing = prev.get(material_id);
|
|
if (!existing) return prev;
|
|
const next = new Map(prev);
|
|
next.set(material_id, { ...existing, descripcion: texto });
|
|
return next;
|
|
});
|
|
};
|
|
|
|
const removeItem: CartContextValue['removeItem'] = (material_id) => {
|
|
setCart((prev) => {
|
|
const next = new Map(prev);
|
|
next.delete(material_id);
|
|
return next;
|
|
});
|
|
};
|
|
|
|
const has: CartContextValue['has'] = (material_id) => cart.has(material_id);
|
|
|
|
const value: CartContextValue = { items, addItem, updateCantidad, updateDescripcion, removeItem, has };
|
|
|
|
const titleId = 'checkout-title';
|
|
|
|
const openCheckout = () => {
|
|
setError(null);
|
|
setOk(false);
|
|
dialogRef.current?.showModal();
|
|
queueMicrotask(() => firstFieldRef.current?.focus());
|
|
};
|
|
|
|
const closeCheckout = () => {
|
|
if (loading) return;
|
|
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;
|
|
if (!dlg) return;
|
|
const onClick = (e: MouseEvent) => {
|
|
if (e.target === dlg) closeCheckout();
|
|
};
|
|
dlg.addEventListener('click', onClick);
|
|
return () => dlg.removeEventListener('click', onClick);
|
|
});
|
|
|
|
const submit = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
if (loading || items.length === 0 || !perfilCompleto) return;
|
|
setLoading(true);
|
|
setError(null);
|
|
try {
|
|
const maestroIdNum = maestroId ? Number(maestroId) : null;
|
|
const res = await fetch('/api/solicitudes', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
maestro_id: esDocente ? null : maestroIdNum,
|
|
notas: notas || undefined,
|
|
items: items.map((i) => ({
|
|
material_id: i.material_id,
|
|
cantidad: i.cantidad,
|
|
descripcion: i.descripcion || undefined,
|
|
})),
|
|
}),
|
|
});
|
|
const json = await res.json().catch(() => ({}));
|
|
if (!res.ok) {
|
|
throw new Error(json?.error ?? 'No se pudo enviar la solicitud');
|
|
}
|
|
setOk(true);
|
|
const usedFallback = !esDocente && !maestroIdNum && !!tutorNombre;
|
|
toastAfterReload({
|
|
kind: 'success',
|
|
title: 'Solicitud enviada',
|
|
description: usedFallback
|
|
? `${items.length} material${items.length === 1 ? '' : 'es'} · maestro: ${tutorNombre} (tu tutor)`
|
|
: `${items.length} material${items.length === 1 ? '' : 'es'} · pendiente de aprobación`,
|
|
});
|
|
setTimeout(() => {
|
|
dialogRef.current?.close();
|
|
setCart(new Map());
|
|
location.reload();
|
|
}, 800);
|
|
} catch (err) {
|
|
const msg = err instanceof Error ? err.message : 'Error inesperado';
|
|
setError(msg);
|
|
toast({ kind: 'error', title: 'No se pudo enviar', description: msg });
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<CartContext.Provider value={value}>
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
|
{materiales.map((m) => (
|
|
<article
|
|
key={m.id}
|
|
className="card flex flex-col gap-3"
|
|
data-cat={m.categoria?.id ?? 'sin'}
|
|
data-nombre={m.nombre}
|
|
data-numero-inventario={m.numero_inventario ?? ''}
|
|
>
|
|
<div className="flex items-start justify-between gap-2">
|
|
<h3 className="font-semibold leading-snug">{m.nombre}</h3>
|
|
{m.categoria && (
|
|
<span
|
|
className="text-xs px-2 py-0.5 rounded-[2px] whitespace-nowrap uppercase tracking-wide"
|
|
style={{
|
|
background: 'color-mix(in oklab, var(--color-primary) 25%, white)',
|
|
color: 'var(--color-ink)',
|
|
border: '1.5px solid var(--color-primary)',
|
|
}}
|
|
>
|
|
{m.categoria.nombre}
|
|
</span>
|
|
)}
|
|
</div>
|
|
|
|
{m.descripcion && <p className="text-sm opacity-75 line-clamp-2">{m.descripcion}</p>}
|
|
|
|
<dl className="text-xs opacity-70 grid grid-cols-2 gap-1">
|
|
<dt className="opacity-60">Inventario</dt>
|
|
<dd className="text-right font-mono">{m.numero_inventario ?? '—'}</dd>
|
|
<dt className="opacity-60">Disponibles</dt>
|
|
<dd className="text-right" style={{ fontVariantNumeric: 'tabular-nums' }}>
|
|
{m.cantidad_disponible} / {m.cantidad_total}
|
|
</dd>
|
|
</dl>
|
|
|
|
<div className="mt-auto">
|
|
<AgregarMaterial material={{ id: m.id, nombre: m.nombre, cantidad_disponible: m.cantidad_disponible }} />
|
|
</div>
|
|
</article>
|
|
))}
|
|
</div>
|
|
|
|
{items.length > 0 && (
|
|
<button
|
|
type="button"
|
|
className="btn btn-primary fixed bottom-24 right-4 md:bottom-6 md:right-6 z-40"
|
|
style={{ boxShadow: 'var(--shadow-hard)' }}
|
|
onClick={openCheckout}
|
|
>
|
|
Ver solicitud ({items.length})
|
|
</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,32rem)]"
|
|
>
|
|
<form onSubmit={submit} className="p-5 sm:p-6 flex flex-col gap-4">
|
|
<div className="flex items-start justify-between gap-3">
|
|
<h2 id={titleId} className="text-lg font-semibold">
|
|
Tu solicitud
|
|
</h2>
|
|
<button
|
|
type="button"
|
|
onClick={closeCheckout}
|
|
aria-label="Cerrar"
|
|
className="rounded-lg p-1.5 hover:bg-black/5 transition-colors"
|
|
>
|
|
<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>
|
|
|
|
{items.length === 0 ? (
|
|
<p className="text-sm opacity-70">Tu solicitud está vacía. Cierra esta ventana y agrega material del catálogo.</p>
|
|
) : (
|
|
<ul className="flex flex-col gap-3 max-h-64 overflow-y-auto -mx-1 px-1">
|
|
{items.map((item) => (
|
|
<li
|
|
key={item.material_id}
|
|
className="flex items-start gap-2 pb-3"
|
|
style={{ borderBottom: '1.5px solid color-mix(in oklab, var(--color-ink) 15%, transparent)' }}
|
|
>
|
|
<div className="flex-1 min-w-0">
|
|
<p className="font-medium text-sm truncate">{item.nombre}</p>
|
|
<div className="flex items-center gap-2 mt-1.5">
|
|
<label className="sr-only" htmlFor={`cant-cart-${item.material_id}`}>
|
|
Cantidad de {item.nombre}
|
|
</label>
|
|
<input
|
|
id={`cant-cart-${item.material_id}`}
|
|
className="input"
|
|
type="number"
|
|
min={1}
|
|
max={item.cantidad_disponible}
|
|
value={item.cantidad}
|
|
inputMode="numeric"
|
|
onChange={(e) => updateCantidad(item.material_id, Number(e.target.value) || 1)}
|
|
style={{ width: '4.5rem', minHeight: '36px', paddingBlock: '0.25rem', fontVariantNumeric: 'tabular-nums' }}
|
|
/>
|
|
<span className="text-xs opacity-60">de {item.cantidad_disponible}</span>
|
|
</div>
|
|
<label className="sr-only" htmlFor={`desc-cart-${item.material_id}`}>
|
|
Nota para {item.nombre}
|
|
</label>
|
|
<input
|
|
id={`desc-cart-${item.material_id}`}
|
|
className="input mt-2"
|
|
type="text"
|
|
maxLength={200}
|
|
value={item.descripcion}
|
|
onChange={(e) => updateDescripcion(item.material_id, e.target.value)}
|
|
placeholder="Nota opcional: color, con webcam…"
|
|
style={{ minHeight: '36px', paddingBlock: '0.25rem' }}
|
|
/>
|
|
</div>
|
|
<button
|
|
type="button"
|
|
onClick={() => removeItem(item.material_id)}
|
|
aria-label={`Quitar ${item.nombre}`}
|
|
className="rounded-lg p-1.5 hover:bg-black/5 transition-colors shrink-0"
|
|
>
|
|
<svg width="16" height="16" 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>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
|
|
{!esDocente && (
|
|
<div>
|
|
<label className="label" htmlFor="maestro-select">Maestro responsable</label>
|
|
<select
|
|
ref={firstFieldRef}
|
|
id="maestro-select"
|
|
className="input"
|
|
value={maestroId}
|
|
onChange={(e) => setMaestroId(e.target.value)}
|
|
aria-describedby="maestro-hint"
|
|
>
|
|
<option value="">
|
|
{tutorNombre ? `— Usar mi tutor (${tutorNombre}) —` : '— Elige un maestro —'}
|
|
</option>
|
|
{maestros.map((m) => (
|
|
<option key={m.id} value={String(m.id)}>{m.nombre}</option>
|
|
))}
|
|
</select>
|
|
<p id="maestro-hint" className="text-xs opacity-70 mt-1">
|
|
{tutorNombre
|
|
? <>Si no eliges nadie se usará tu tutor: <strong>{tutorNombre}</strong>.</>
|
|
: 'Debes elegir un maestro; no tienes tutor guardado.'}
|
|
</p>
|
|
</div>
|
|
)}
|
|
|
|
<div>
|
|
<label className="label" htmlFor="notas-cart">Motivo del préstamo</label>
|
|
<textarea
|
|
id="notas-cart"
|
|
className="input"
|
|
rows={3}
|
|
maxLength={250}
|
|
value={notas}
|
|
onChange={(e) => setNotas(e.target.value)}
|
|
placeholder="¿Para qué clase o proyecto lo necesitas?"
|
|
style={{ minHeight: '96px' }}
|
|
aria-describedby="notas-cart-hint"
|
|
/>
|
|
<p id="notas-cart-hint" className="text-xs opacity-60 mt-1">
|
|
Ejemplo: Clase de Electrónica Analógica · Prof. Gómez · práctica 3. (Opcional, máx. 250 caracteres)
|
|
</p>
|
|
</div>
|
|
|
|
{error && (
|
|
<p role="alert" className="text-sm" style={{ color: 'var(--color-danger-text)' }}>
|
|
{error} · Ajusta la solicitud e intenta de nuevo.
|
|
</p>
|
|
)}
|
|
{ok && (
|
|
<p role="status" className="text-sm" style={{ color: 'var(--color-positive)' }}>
|
|
Solicitud enviada. Actualizando…
|
|
</p>
|
|
)}
|
|
|
|
{!perfilCompleto ? (
|
|
<div className="card p-3">
|
|
<p className="text-sm mb-3">Necesitas completar tu perfil (matrícula + tutor) para crear vales.</p>
|
|
<a href="/perfil" className="btn btn-primary">Completar perfil</a>
|
|
</div>
|
|
) : (
|
|
<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>
|
|
</dialog>
|
|
</CartContext.Provider>
|
|
);
|
|
}
|