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:
@@ -7,8 +7,10 @@ const HEADERS = [
|
||||
'Alumno',
|
||||
'Matrícula',
|
||||
'Email',
|
||||
'Maestro responsable',
|
||||
'Material',
|
||||
'Nº inventario',
|
||||
'Descripción',
|
||||
'Cantidad',
|
||||
'Estado',
|
||||
'Fecha aprobación',
|
||||
@@ -40,12 +42,16 @@ export const GET: APIRoute = async ({ locals, url }) => {
|
||||
const materialId = sp.get('material_id');
|
||||
const alumnoId = sp.get('alumno_id');
|
||||
|
||||
const itemsSelect = materialId
|
||||
? 'items:solicitud_items!inner(cantidad, descripcion, material:materiales(nombre, numero_inventario))'
|
||||
: 'items:solicitud_items(cantidad, descripcion, material:materiales(nombre, numero_inventario))';
|
||||
|
||||
let query = locals.supabase
|
||||
.from('prestamos')
|
||||
.from('solicitudes')
|
||||
.select(`
|
||||
id, cantidad, fecha_solicitud, fecha_aprobacion, fecha_devolucion_estimada, fecha_devolucion_real, estado, notas,
|
||||
id, maestro_responsable, fecha_solicitud, fecha_aprobacion, fecha_devolucion_estimada, fecha_devolucion_real, estado, notas,
|
||||
alumno:profiles!alumno_id(nombre, email, matricula),
|
||||
material:materiales!material_id(nombre, numero_inventario)
|
||||
${itemsSelect}
|
||||
`)
|
||||
.order('fecha_solicitud', { ascending: false })
|
||||
// ponytail: 5000 evita OOM en export ad-hoc; paginar/streamear si un solo reporte lo excede rutinariamente
|
||||
@@ -54,26 +60,30 @@ export const GET: APIRoute = async ({ locals, url }) => {
|
||||
if (desde) query = query.gte('fecha_solicitud', desde);
|
||||
if (hasta) query = query.lte('fecha_solicitud', `${hasta}T23:59:59.999Z`);
|
||||
if (estado && estado !== 'all') query = query.eq('estado', estado);
|
||||
if (materialId) query = query.eq('material_id', materialId);
|
||||
if (materialId) query = query.eq('items.material_id', materialId);
|
||||
if (alumnoId) query = query.eq('alumno_id', alumnoId);
|
||||
|
||||
const { data, error } = await query;
|
||||
if (error) return new Response(error.message, { status: 500 });
|
||||
|
||||
const rows = (data ?? []).map((r: any) => [
|
||||
isoDate(r.fecha_solicitud),
|
||||
r.alumno?.nombre ?? '',
|
||||
r.alumno?.matricula ?? '',
|
||||
r.alumno?.email ?? '',
|
||||
r.material?.nombre ?? '',
|
||||
r.material?.numero_inventario ?? '',
|
||||
r.cantidad,
|
||||
r.estado,
|
||||
isoDate(r.fecha_aprobacion),
|
||||
isoDate(r.fecha_devolucion_estimada),
|
||||
isoDate(r.fecha_devolucion_real),
|
||||
r.notas ?? '',
|
||||
]);
|
||||
const rows = (data ?? []).flatMap((r: any) =>
|
||||
(r.items ?? []).map((item: any) => [
|
||||
isoDate(r.fecha_solicitud),
|
||||
r.alumno?.nombre ?? '',
|
||||
r.alumno?.matricula ?? '',
|
||||
r.alumno?.email ?? '',
|
||||
r.maestro_responsable ?? '',
|
||||
item.material?.nombre ?? '',
|
||||
item.material?.numero_inventario ?? '',
|
||||
item.descripcion ?? '',
|
||||
item.cantidad,
|
||||
r.estado,
|
||||
isoDate(r.fecha_aprobacion),
|
||||
isoDate(r.fecha_devolucion_estimada),
|
||||
isoDate(r.fecha_devolucion_real),
|
||||
r.notas ?? '',
|
||||
])
|
||||
);
|
||||
|
||||
const lines = [HEADERS, ...rows].map((row) => row.map(csvCell).join(','));
|
||||
// BOM para que Excel abra UTF-8 sin romper acentos
|
||||
|
||||
@@ -31,7 +31,7 @@ export const POST: APIRoute = async ({ params, request, locals }) => {
|
||||
if (notas) update.notas = notas;
|
||||
|
||||
const { data, error } = await locals.supabase
|
||||
.from('prestamos')
|
||||
.from('solicitudes')
|
||||
.update(update)
|
||||
.eq('id', id)
|
||||
.eq('estado', 'pendiente')
|
||||
|
||||
@@ -11,19 +11,18 @@ export const GET: APIRoute = async ({ params, locals }) => {
|
||||
if (!Number.isInteger(id) || id <= 0) return json({ error: 'id inválido' }, 400);
|
||||
|
||||
const prestamoQ = locals.supabase
|
||||
.from('prestamos')
|
||||
.from('solicitudes')
|
||||
.select(
|
||||
'id, cantidad, estado, fecha_solicitud, fecha_aprobacion, fecha_devolucion_estimada, fecha_devolucion_real, notas, alumno:profiles!alumno_id(id, nombre, email, matricula), material:materiales!material_id(id, nombre, numero_inventario)'
|
||||
'id, estado, fecha_solicitud, fecha_aprobacion, fecha_devolucion_estimada, fecha_devolucion_real, notas, maestro_responsable, alumno:profiles!alumno_id(id, nombre, email, matricula), items:solicitud_items(cantidad, descripcion, material:materiales(id, nombre, numero_inventario))'
|
||||
)
|
||||
.eq('id', id)
|
||||
.maybeSingle();
|
||||
|
||||
// Nombre y orden asumidos del audit_log: select('*') para no romper si el esquema difiere.
|
||||
const logQ = locals.supabase
|
||||
.from('audit_log')
|
||||
.select('*')
|
||||
.eq('prestamo_id', id)
|
||||
.order('created_at', { ascending: false })
|
||||
.eq('solicitud_id', id)
|
||||
.order('at', { ascending: false })
|
||||
.limit(20);
|
||||
|
||||
const [{ data: prestamo, error: pErr }, { data: audit_log, error: lErr }] = await Promise.all([prestamoQ, logQ]);
|
||||
|
||||
@@ -11,7 +11,7 @@ export const POST: APIRoute = async ({ params, locals }) => {
|
||||
if (!Number.isInteger(id) || id <= 0) return json({ error: 'id inválido' }, 400);
|
||||
|
||||
const { data, error } = await locals.supabase
|
||||
.from('prestamos')
|
||||
.from('solicitudes')
|
||||
.update({ estado: 'devuelto', fecha_devolucion_real: new Date().toISOString() })
|
||||
.eq('id', id)
|
||||
.in('estado', ['aprobado', 'activo'])
|
||||
|
||||
@@ -17,7 +17,7 @@ export const POST: APIRoute = async ({ params, request, locals }) => {
|
||||
if (motivo.length < 5) return json({ error: 'el motivo debe tener al menos 5 caracteres' }, 400);
|
||||
|
||||
const { data, error } = await locals.supabase
|
||||
.from('prestamos')
|
||||
.from('solicitudes')
|
||||
.update({ estado: 'rechazado', notas: motivo, aprobado_por: locals.user.id })
|
||||
.eq('id', id)
|
||||
.eq('estado', 'pendiente')
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import type { APIRoute } from 'astro';
|
||||
|
||||
export const prerender = false;
|
||||
|
||||
export const POST: APIRoute = async ({ request, locals }) => {
|
||||
const user = locals.user;
|
||||
if (!user) {
|
||||
return Response.json({ error: 'No autenticado' }, { status: 401 });
|
||||
}
|
||||
|
||||
let body: { material_id?: unknown; cantidad?: unknown; notas?: unknown };
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return Response.json({ error: 'JSON inválido' }, { status: 400 });
|
||||
}
|
||||
|
||||
const material_id = Number(body.material_id);
|
||||
const cantidad = Number(body.cantidad);
|
||||
const notas = typeof body.notas === 'string' && body.notas.trim() ? body.notas.trim() : null;
|
||||
|
||||
if (!Number.isInteger(material_id) || material_id <= 0) {
|
||||
return Response.json({ error: 'material_id requerido' }, { status: 400 });
|
||||
}
|
||||
if (!Number.isInteger(cantidad) || cantidad <= 0) {
|
||||
return Response.json({ error: 'cantidad debe ser un entero mayor que cero' }, { status: 400 });
|
||||
}
|
||||
|
||||
const supabase = locals.supabase;
|
||||
|
||||
const { data: material, error: matErr } = await supabase
|
||||
.from('materiales')
|
||||
.select('id, cantidad_disponible, estado')
|
||||
.eq('id', material_id)
|
||||
.maybeSingle();
|
||||
|
||||
if (matErr) {
|
||||
return Response.json({ error: 'No se pudo verificar el material' }, { status: 500 });
|
||||
}
|
||||
if (!material || material.estado !== 'disponible') {
|
||||
return Response.json({ error: 'Material no disponible' }, { status: 404 });
|
||||
}
|
||||
if (material.cantidad_disponible < cantidad) {
|
||||
return Response.json({ error: 'Sin stock suficiente' }, { status: 409 });
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('prestamos')
|
||||
.insert({ alumno_id: user.id, material_id, cantidad, notas })
|
||||
.select('id')
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return Response.json({ error: 'No se pudo registrar la solicitud' }, { status: 500 });
|
||||
}
|
||||
|
||||
return Response.json({ id: data.id }, { status: 201 });
|
||||
};
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { APIRoute } from 'astro';
|
||||
|
||||
export const prerender = false;
|
||||
|
||||
type ItemInput = { material_id?: unknown; cantidad?: unknown; descripcion?: unknown };
|
||||
|
||||
function statusForError(message: string): { status: number; error: string } {
|
||||
if (message.startsWith('no_autenticado')) {
|
||||
return { status: 401, error: 'No autenticado' };
|
||||
}
|
||||
if (
|
||||
message.startsWith('maestro_responsable_requerido') ||
|
||||
message.startsWith('items_requeridos') ||
|
||||
message.startsWith('item_invalido')
|
||||
) {
|
||||
return { status: 400, error: 'Solicitud inválida' };
|
||||
}
|
||||
if (message.startsWith('material_no_existe')) {
|
||||
return { status: 409, error: 'Uno de los materiales ya no existe' };
|
||||
}
|
||||
if (message.startsWith('material_no_disponible')) {
|
||||
return { status: 409, error: 'Uno de los materiales ya no está disponible' };
|
||||
}
|
||||
if (message.startsWith('stock_insuficiente')) {
|
||||
return { status: 409, error: 'Sin stock suficiente para uno de los materiales' };
|
||||
}
|
||||
return { status: 500, error: 'No se pudo registrar la solicitud' };
|
||||
}
|
||||
|
||||
export const POST: APIRoute = async ({ request, locals }) => {
|
||||
if (!locals.user) {
|
||||
return Response.json({ error: 'No autenticado' }, { status: 401 });
|
||||
}
|
||||
|
||||
let body: { maestro_responsable?: unknown; notas?: unknown; items?: unknown };
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return Response.json({ error: 'JSON inválido' }, { status: 400 });
|
||||
}
|
||||
|
||||
const maestro_responsable = typeof body.maestro_responsable === 'string' ? body.maestro_responsable.trim() : '';
|
||||
const notas = typeof body.notas === 'string' && body.notas.trim() ? body.notas.trim() : null;
|
||||
|
||||
if (!maestro_responsable) {
|
||||
return Response.json({ error: 'Maestro responsable requerido' }, { status: 400 });
|
||||
}
|
||||
if (!Array.isArray(body.items) || body.items.length === 0) {
|
||||
return Response.json({ error: 'Agrega al menos un material' }, { status: 400 });
|
||||
}
|
||||
|
||||
const items: Array<{ material_id: number; cantidad: number; descripcion: string | null }> = [];
|
||||
for (const raw of body.items as ItemInput[]) {
|
||||
const material_id = Number(raw.material_id);
|
||||
const cantidad = Number(raw.cantidad);
|
||||
if (!Number.isInteger(material_id) || material_id <= 0) {
|
||||
return Response.json({ error: 'material_id inválido en un renglón' }, { status: 400 });
|
||||
}
|
||||
if (!Number.isInteger(cantidad) || cantidad <= 0) {
|
||||
return Response.json({ error: 'cantidad inválida en un renglón' }, { status: 400 });
|
||||
}
|
||||
const descripcion = typeof raw.descripcion === 'string' && raw.descripcion.trim() ? raw.descripcion.trim() : null;
|
||||
items.push({ material_id, cantidad, descripcion });
|
||||
}
|
||||
|
||||
const { data, error } = await locals.supabase.rpc('crear_solicitud', {
|
||||
p_maestro_responsable: maestro_responsable,
|
||||
p_notas: notas,
|
||||
p_items: items,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
const { status, error: message } = statusForError(error.message ?? '');
|
||||
return Response.json({ error: message }, { status });
|
||||
}
|
||||
|
||||
return Response.json({ id: data }, { status: 201 });
|
||||
};
|
||||
Reference in New Issue
Block a user