0247b979ca
Segunda iteración del rediseño (sesión separada con skill impeccable). Toca prácticamente toda la UI: layout base, tokens (global.css), todas las páginas de alumno y admin, componentes de solicitudes, inventario, catálogo, filtros, toaster y modales. Docs y sistema: - DESIGN.md y PRODUCT.md actualizados con la nueva iteración. - .impeccable/design.json refleja tokens vigentes. - .impeccable/review/ contiene screenshots de la revisión visual. Dependencias: - Añade @fontsource-variable/jetbrains-mono (fuente monoespaciada). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
181 lines
5.9 KiB
TypeScript
181 lines
5.9 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import { toast, toastAfterReload } from '@/lib/toast';
|
|
|
|
type Props = {
|
|
material: {
|
|
id: number;
|
|
nombre: string;
|
|
cantidad_disponible: number;
|
|
};
|
|
};
|
|
|
|
export default function SolicitarModal({ material }: Props) {
|
|
const dialogRef = useRef<HTMLDialogElement | null>(null);
|
|
const firstFieldRef = useRef<HTMLInputElement | null>(null);
|
|
const [cantidad, setCantidad] = useState<number>(1);
|
|
const [notas, setNotas] = useState<string>('');
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [ok, setOk] = useState(false);
|
|
|
|
const titleId = `solicitar-title-${material.id}`;
|
|
|
|
const open = () => {
|
|
setError(null);
|
|
setOk(false);
|
|
setCantidad(1);
|
|
setNotas('');
|
|
dialogRef.current?.showModal();
|
|
queueMicrotask(() => firstFieldRef.current?.focus());
|
|
};
|
|
|
|
const close = () => {
|
|
if (loading) return;
|
|
dialogRef.current?.close();
|
|
};
|
|
|
|
// Cerrar al click en backdrop
|
|
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);
|
|
});
|
|
|
|
const submit = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
if (loading) return;
|
|
setLoading(true);
|
|
setError(null);
|
|
try {
|
|
const res = await fetch('/api/prestamos', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ material_id: material.id, cantidad, notas }),
|
|
});
|
|
const json = await res.json().catch(() => ({}));
|
|
if (!res.ok) {
|
|
throw new Error(json?.error ?? 'No se pudo enviar la solicitud');
|
|
}
|
|
setOk(true);
|
|
toastAfterReload({
|
|
kind: 'success',
|
|
title: 'Solicitud enviada',
|
|
description: `${material.nombre} · pendiente de aprobación`,
|
|
});
|
|
setTimeout(() => {
|
|
dialogRef.current?.close();
|
|
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);
|
|
}
|
|
};
|
|
|
|
const disabled = material.cantidad_disponible === 0;
|
|
|
|
return (
|
|
<>
|
|
<button
|
|
type="button"
|
|
className="btn btn-primary w-full"
|
|
onClick={open}
|
|
disabled={disabled}
|
|
>
|
|
{disabled ? 'Sin stock' : 'Solicitar'}
|
|
</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">
|
|
<div className="flex items-start justify-between gap-3">
|
|
<h2 id={titleId} className="text-lg font-semibold">
|
|
Solicitar: {material.nombre}
|
|
</h2>
|
|
<button
|
|
type="button"
|
|
onClick={close}
|
|
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>
|
|
|
|
<p className="text-sm opacity-70">
|
|
Disponibles: <span style={{ fontVariantNumeric: 'tabular-nums' }}>{material.cantidad_disponible}</span>
|
|
</p>
|
|
|
|
<div>
|
|
<label className="label" htmlFor={`cant-${material.id}`}>Cantidad</label>
|
|
<input
|
|
ref={firstFieldRef}
|
|
id={`cant-${material.id}`}
|
|
className="input"
|
|
type="number"
|
|
min={1}
|
|
max={material.cantidad_disponible}
|
|
value={cantidad}
|
|
required
|
|
inputMode="numeric"
|
|
onChange={(e) => setCantidad(Math.max(1, Math.min(material.cantidad_disponible, Number(e.target.value) || 1)))}
|
|
style={{ fontVariantNumeric: 'tabular-nums' }}
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="label" htmlFor={`notas-${material.id}`}>Motivo del préstamo</label>
|
|
<textarea
|
|
id={`notas-${material.id}`}
|
|
className="input"
|
|
rows={3}
|
|
maxLength={500}
|
|
value={notas}
|
|
required
|
|
onChange={(e) => setNotas(e.target.value)}
|
|
placeholder="¿Para qué clase o proyecto lo necesitas?"
|
|
style={{ minHeight: '96px' }}
|
|
aria-describedby={`notas-hint-${material.id}`}
|
|
/>
|
|
<p id={`notas-hint-${material.id}`} className="text-xs opacity-60 mt-1">
|
|
Ejemplo: Clase de Electrónica Analógica · Prof. Gómez · práctica 3.
|
|
</p>
|
|
</div>
|
|
|
|
{error && (
|
|
<p role="alert" className="text-sm" style={{ color: 'var(--color-danger-text)' }}>
|
|
{error} · Ajusta la cantidad o intenta de nuevo.
|
|
</p>
|
|
)}
|
|
{ok && (
|
|
<p role="status" className="text-sm" style={{ color: 'var(--color-positive)' }}>
|
|
Solicitud enviada. Actualizando…
|
|
</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-primary" disabled={loading || ok}>
|
|
{loading ? 'Enviando…' : 'Enviar solicitud'}
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</dialog>
|
|
</>
|
|
);
|
|
}
|