Rediseño: vale de préstamo multi-ítem, fiel al formulario de papel
El vale físico del LSC permite pedir varios materiales en un solo trámite; el sistema modelaba 1 solicitud = 1 material. Migra prestamos.prestamos -> solicitudes (cabecera) + solicitud_items (renglones), vía RENAME + backfill (preserva ids/historial real). - RPC prestamos.crear_solicitud: transaccional, lockea materiales por fila, arregla la race condition del insert directo anterior. El alumno ya no inserta directo (RLS lo bloquea). - sync_stock/log_estado reescritos para iterar renglones por vale. - maestro_responsable (por vale) y profiles.semestre (perfil, nullable, sin UI todavía — onboarding queda para después). - Alumno: carrito (SolicitudCart/AgregarMaterial) reemplaza el modal de solicitud único por material. - Admin: 3 vistas de solicitudes, reportes y CSV export listan renglones por vale; api/admin/prestamos -> api/admin/solicitudes. De paso corrige un bug preexistente en detalles.ts (audit_log nunca se ordenaba por la columna correcta). Verificado: build limpio, ciclo RPC+triggers probado en una transacción revertida en prod (sin residuo), 9 vistas SSR smoke-testeadas contra el schema real. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,358 @@
|
||||
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));
|
||||
|
||||
export default function CartProvider({ materiales }: { materiales: Material[] }) {
|
||||
const [cart, setCart] = useState<Map<number, CartItem>>(new Map());
|
||||
const dialogRef = useRef<HTMLDialogElement | null>(null);
|
||||
const firstFieldRef = useRef<HTMLInputElement | null>(null);
|
||||
const [maestroResponsable, setMaestroResponsable] = useState('');
|
||||
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();
|
||||
};
|
||||
|
||||
// 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) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch('/api/solicitudes', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
maestro_responsable: maestroResponsable,
|
||||
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);
|
||||
toastAfterReload({
|
||||
kind: 'success',
|
||||
title: 'Solicitud enviada',
|
||||
description: `${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'}>
|
||||
<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>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className="label" htmlFor="maestro-responsable">Maestro responsable</label>
|
||||
<input
|
||||
ref={firstFieldRef}
|
||||
id="maestro-responsable"
|
||||
className="input"
|
||||
type="text"
|
||||
required
|
||||
maxLength={200}
|
||||
value={maestroResponsable}
|
||||
onChange={(e) => setMaestroResponsable(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="label" htmlFor="notas-cart">Motivo del préstamo</label>
|
||||
<textarea
|
||||
id="notas-cart"
|
||||
className="input"
|
||||
rows={3}
|
||||
maxLength={500}
|
||||
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)
|
||||
</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>
|
||||
)}
|
||||
|
||||
<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'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
</CartContext.Provider>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user