Sistema de préstamos LabRe UABC — implementación inicial

Sistema web para gestión de préstamos de material del Laboratorio de
Sistemas Computacionales de la UABC.

- Backend: Supabase self-hosted, schema aislado `prestamos` con RLS,
  triggers de stock y audit log (supabase/migrations/0001_init.sql).
- Auth: Google OAuth restringido a @uabc.edu.mx, verificado en
  middleware y como segunda línea en trigger de DB.
- Frontend: Astro 7 (SSR con adapter Node) + React islands + Tailwind
  v4 con paleta UABC (primary #00723F, secondary #DD971A) bajo regla
  60/30/10.
- Interfaz alumno mobile-first: catálogo con filtro por categorías,
  solicitud de préstamos, historial personal.
- Interfaz admin desktop-first: panel con KPIs, bandeja de solicitudes
  (aprobar/rechazar/devolver), CRUD de inventario y categorías,
  reportes filtrables con export CSV nativo.
- Modales con `<dialog>` nativo, cero librerías de UI adicionales.
- Deploy: Dockerfile multi-stage node:22-alpine + docker-compose para
  publicar bajo prestamos.buglabs.dev vía Cloudflare Tunnel.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-08-14 19:37:49 -07:00
parent 6bbd6d3a6b
commit 1121ab7199
58 changed files with 6281 additions and 252 deletions
+71
View File
@@ -0,0 +1,71 @@
import type { APIRoute } from 'astro';
export const prerender = false;
const parseId = (raw: string | undefined) => {
const id = Number(raw);
return Number.isInteger(id) && id > 0 ? id : null;
};
export const PATCH: APIRoute = async ({ request, locals, params }) => {
if (locals.profile?.rol !== 'admin') {
return Response.json({ error: 'No autorizado' }, { status: 403 });
}
const id = parseId(params.id);
if (!id) return Response.json({ error: 'ID inválido' }, { status: 400 });
let body: { nombre?: unknown };
try {
body = await request.json();
} catch {
return Response.json({ error: 'JSON inválido' }, { status: 400 });
}
const nombre = typeof body.nombre === 'string' ? body.nombre.trim() : '';
if (!nombre) {
return Response.json({ error: 'El nombre es obligatorio' }, { status: 400 });
}
const { error } = await locals.supabase
.from('categorias')
.update({ nombre })
.eq('id', id);
if (error) {
if ((error as { code?: string }).code === '23505') {
return Response.json({ error: 'Ya existe una categoría con ese nombre' }, { status: 409 });
}
return Response.json({ error: 'No se pudo actualizar' }, { status: 500 });
}
return Response.json({ ok: true });
};
export const DELETE: APIRoute = async ({ locals, params }) => {
if (locals.profile?.rol !== 'admin') {
return Response.json({ error: 'No autorizado' }, { status: 403 });
}
const id = parseId(params.id);
if (!id) return Response.json({ error: 'ID inválido' }, { status: 400 });
const { count } = await locals.supabase
.from('materiales')
.select('id', { count: 'exact', head: true })
.eq('categoria_id', id);
const { error } = await locals.supabase.from('categorias').delete().eq('id', id);
if (error) {
if ((error as { code?: string }).code === '23503') {
return Response.json(
{ error: `Tiene ${count ?? 'varios'} materiales asociados — reasígnalos primero` },
{ status: 409 },
);
}
return Response.json({ error: 'No se pudo eliminar' }, { status: 500 });
}
return Response.json({ ok: true });
};
+36
View File
@@ -0,0 +1,36 @@
import type { APIRoute } from 'astro';
export const prerender = false;
export const POST: APIRoute = async ({ request, locals }) => {
if (locals.profile?.rol !== 'admin') {
return Response.json({ error: 'No autorizado' }, { status: 403 });
}
let body: { nombre?: unknown };
try {
body = await request.json();
} catch {
return Response.json({ error: 'JSON inválido' }, { status: 400 });
}
const nombre = typeof body.nombre === 'string' ? body.nombre.trim() : '';
if (!nombre) {
return Response.json({ error: 'El nombre es obligatorio' }, { status: 400 });
}
const { data, error } = await locals.supabase
.from('categorias')
.insert({ nombre })
.select('id')
.single();
if (error) {
if ((error as { code?: string }).code === '23505') {
return Response.json({ error: 'Ya existe una categoría con ese nombre' }, { status: 409 });
}
return Response.json({ error: 'No se pudo crear la categoría' }, { status: 500 });
}
return Response.json({ id: data.id }, { status: 201 });
};
+140
View File
@@ -0,0 +1,140 @@
import type { APIRoute } from 'astro';
export const prerender = false;
type Patch = {
nombre?: string | null;
categoria_id?: number | null;
descripcion?: string | null;
numero_inventario?: string | null;
estado?: string;
cantidad_total?: number;
cantidad_disponible?: number;
};
const parseId = (raw: string | undefined) => {
const id = Number(raw);
return Number.isInteger(id) && id > 0 ? id : null;
};
export const PATCH: APIRoute = async ({ request, locals, params }) => {
if (locals.profile?.rol !== 'admin') {
return Response.json({ error: 'No autorizado' }, { status: 403 });
}
const id = parseId(params.id);
if (!id) return Response.json({ error: 'ID inválido' }, { status: 400 });
let body: Record<string, unknown>;
try {
body = await request.json();
} catch {
return Response.json({ error: 'JSON inválido' }, { status: 400 });
}
const patch: Patch = {};
if ('nombre' in body) {
const nombre = typeof body.nombre === 'string' ? body.nombre.trim() : '';
if (!nombre) return Response.json({ error: 'El nombre no puede quedar vacío' }, { status: 400 });
patch.nombre = nombre;
}
if ('categoria_id' in body) {
if (body.categoria_id === null || body.categoria_id === '') {
patch.categoria_id = null;
} else {
const cid = Number(body.categoria_id);
if (!Number.isInteger(cid) || cid <= 0)
return Response.json({ error: 'Categoría inválida' }, { status: 400 });
patch.categoria_id = cid;
}
}
if ('descripcion' in body) {
patch.descripcion =
typeof body.descripcion === 'string' && body.descripcion.trim()
? body.descripcion.trim()
: null;
}
if ('numero_inventario' in body) {
patch.numero_inventario =
typeof body.numero_inventario === 'string' && body.numero_inventario.trim()
? body.numero_inventario.trim()
: null;
}
if ('estado' in body) {
const estado = typeof body.estado === 'string' ? body.estado : '';
if (!['disponible', 'mantenimiento', 'baja'].includes(estado))
return Response.json({ error: 'Estado inválido' }, { status: 400 });
patch.estado = estado;
}
if ('cantidad_total' in body) {
const nuevoTotal = Number(body.cantidad_total);
if (!Number.isInteger(nuevoTotal) || nuevoTotal < 0)
return Response.json({ error: 'Cantidad total inválida' }, { status: 400 });
const { data: actual, error: selErr } = await locals.supabase
.from('materiales')
.select('cantidad_total, cantidad_disponible')
.eq('id', id)
.maybeSingle();
if (selErr || !actual)
return Response.json({ error: 'Material no encontrado' }, { status: 404 });
const prestados = actual.cantidad_total - actual.cantidad_disponible;
if (nuevoTotal < prestados) {
return Response.json(
{ error: `No puede quedar debajo de lo prestado (${prestados})` },
{ status: 409 },
);
}
patch.cantidad_total = nuevoTotal;
patch.cantidad_disponible = actual.cantidad_disponible + (nuevoTotal - actual.cantidad_total);
}
if (Object.keys(patch).length === 0) {
return Response.json({ error: 'Nada que actualizar' }, { status: 400 });
}
const { error } = await locals.supabase.from('materiales').update(patch).eq('id', id);
if (error) {
if ((error as { code?: string }).code === '23505') {
return Response.json({ error: 'Nº de inventario ya existe' }, { status: 409 });
}
if ((error as { code?: string }).code === '23503') {
return Response.json({ error: 'Categoría inexistente' }, { status: 409 });
}
return Response.json({ error: 'No se pudo actualizar' }, { status: 500 });
}
return Response.json({ ok: true });
};
export const DELETE: APIRoute = async ({ locals, params }) => {
if (locals.profile?.rol !== 'admin') {
return Response.json({ error: 'No autorizado' }, { status: 403 });
}
const id = parseId(params.id);
if (!id) return Response.json({ error: 'ID inválido' }, { status: 400 });
const { error } = await locals.supabase.from('materiales').delete().eq('id', id);
if (error) {
if ((error as { code?: string }).code === '23503') {
return Response.json(
{ error: 'Tiene préstamos asociados — no se puede eliminar' },
{ status: 409 },
);
}
return Response.json({ error: 'No se pudo eliminar' }, { status: 500 });
}
return Response.json({ ok: true });
};
+79
View File
@@ -0,0 +1,79 @@
import type { APIRoute } from 'astro';
export const prerender = false;
export const POST: APIRoute = async ({ request, locals }) => {
if (locals.profile?.rol !== 'admin') {
return Response.json({ error: 'No autorizado' }, { status: 403 });
}
let body: {
nombre?: unknown;
categoria_id?: unknown;
descripcion?: unknown;
cantidad_total?: unknown;
numero_inventario?: unknown;
estado?: unknown;
};
try {
body = await request.json();
} catch {
return Response.json({ error: 'JSON inválido' }, { status: 400 });
}
const nombre = typeof body.nombre === 'string' ? body.nombre.trim() : '';
if (!nombre) {
return Response.json({ error: 'El nombre es obligatorio' }, { status: 400 });
}
const cantidad_total = Number(body.cantidad_total);
if (!Number.isInteger(cantidad_total) || cantidad_total < 0) {
return Response.json({ error: 'La cantidad total debe ser un entero mayor o igual a 0' }, { status: 400 });
}
const categoria_id =
body.categoria_id === null || body.categoria_id === undefined || body.categoria_id === ''
? null
: Number(body.categoria_id);
if (categoria_id !== null && (!Number.isInteger(categoria_id) || categoria_id <= 0)) {
return Response.json({ error: 'Categoría inválida' }, { status: 400 });
}
const descripcion =
typeof body.descripcion === 'string' && body.descripcion.trim() ? body.descripcion.trim() : null;
const numero_inventario =
typeof body.numero_inventario === 'string' && body.numero_inventario.trim()
? body.numero_inventario.trim()
: null;
const estadoIn = typeof body.estado === 'string' ? body.estado : 'disponible';
if (!['disponible', 'mantenimiento', 'baja'].includes(estadoIn)) {
return Response.json({ error: 'Estado inválido' }, { status: 400 });
}
const { data, error } = await locals.supabase
.from('materiales')
.insert({
nombre,
categoria_id,
descripcion,
cantidad_total,
cantidad_disponible: cantidad_total,
numero_inventario,
estado: estadoIn,
})
.select('id')
.single();
if (error) {
if ((error as { code?: string }).code === '23505') {
return Response.json({ error: 'Nº de inventario ya existe' }, { status: 409 });
}
if ((error as { code?: string }).code === '23503') {
return Response.json({ error: 'Categoría inexistente' }, { status: 409 });
}
return Response.json({ error: 'No se pudo crear el material' }, { status: 500 });
}
return Response.json({ id: data.id }, { status: 201 });
};
@@ -0,0 +1,44 @@
import type { APIRoute } from 'astro';
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
export const POST: APIRoute = async ({ params, request, locals }) => {
if (!locals.user) return json({ error: 'no autenticado' }, 401);
if (locals.profile?.rol !== 'admin') return json({ error: 'no autorizado' }, 403);
const id = Number(params.id);
if (!Number.isInteger(id) || id <= 0) return json({ error: 'id inválido' }, 400);
let body: any;
try { body = await request.json(); } catch { return json({ error: 'JSON inválido' }, 400); }
const fecha = String(body?.fecha_devolucion_estimada ?? '');
if (!ISO_DATE.test(fecha)) return json({ error: 'fecha_devolucion_estimada debe ser YYYY-MM-DD' }, 400);
const hoy = new Date().toISOString().split('T')[0];
if (fecha < hoy) return json({ error: 'la fecha no puede ser pasada' }, 400);
const notas = typeof body?.notas === 'string' && body.notas.trim() ? body.notas.trim() : null;
const update: Record<string, unknown> = {
estado: 'aprobado',
fecha_aprobacion: new Date().toISOString(),
fecha_devolucion_estimada: fecha,
aprobado_por: locals.user.id,
};
if (notas) update.notas = notas;
const { data, error } = await locals.supabase
.from('prestamos')
.update(update)
.eq('id', id)
.eq('estado', 'pendiente')
.select('id')
.maybeSingle();
if (error) return json({ error: error.message }, 500);
if (!data) return json({ error: 'la solicitud ya no está pendiente' }, 409);
return json({ ok: true });
};
@@ -0,0 +1,35 @@
import type { APIRoute } from 'astro';
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
export const GET: APIRoute = async ({ params, locals }) => {
if (!locals.user) return json({ error: 'no autenticado' }, 401);
if (locals.profile?.rol !== 'admin') return json({ error: 'no autorizado' }, 403);
const id = Number(params.id);
if (!Number.isInteger(id) || id <= 0) return json({ error: 'id inválido' }, 400);
const prestamoQ = locals.supabase
.from('prestamos')
.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)'
)
.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 })
.limit(20);
const [{ data: prestamo, error: pErr }, { data: audit_log, error: lErr }] = await Promise.all([prestamoQ, logQ]);
if (pErr) return json({ error: pErr.message }, 500);
if (!prestamo) return json({ error: 'no encontrado' }, 404);
return json({ prestamo, audit_log: lErr ? [] : (audit_log ?? []) });
};
@@ -0,0 +1,24 @@
import type { APIRoute } from 'astro';
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
export const POST: APIRoute = async ({ params, locals }) => {
if (!locals.user) return json({ error: 'no autenticado' }, 401);
if (locals.profile?.rol !== 'admin') return json({ error: 'no autorizado' }, 403);
const id = Number(params.id);
if (!Number.isInteger(id) || id <= 0) return json({ error: 'id inválido' }, 400);
const { data, error } = await locals.supabase
.from('prestamos')
.update({ estado: 'devuelto', fecha_devolucion_real: new Date().toISOString() })
.eq('id', id)
.in('estado', ['aprobado', 'activo'])
.select('id')
.maybeSingle();
if (error) return json({ error: error.message }, 500);
if (!data) return json({ error: 'el préstamo no está en curso' }, 409);
return json({ ok: true });
};
@@ -0,0 +1,30 @@
import type { APIRoute } from 'astro';
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
export const POST: APIRoute = async ({ params, request, locals }) => {
if (!locals.user) return json({ error: 'no autenticado' }, 401);
if (locals.profile?.rol !== 'admin') return json({ error: 'no autorizado' }, 403);
const id = Number(params.id);
if (!Number.isInteger(id) || id <= 0) return json({ error: 'id inválido' }, 400);
let body: any;
try { body = await request.json(); } catch { return json({ error: 'JSON inválido' }, 400); }
const motivo = typeof body?.motivo === 'string' ? body.motivo.trim() : '';
if (motivo.length < 5) return json({ error: 'el motivo debe tener al menos 5 caracteres' }, 400);
const { data, error } = await locals.supabase
.from('prestamos')
.update({ estado: 'rechazado', notas: motivo, aprobado_por: locals.user.id })
.eq('id', id)
.eq('estado', 'pendiente')
.select('id')
.maybeSingle();
if (error) return json({ error: error.message }, 500);
if (!data) return json({ error: 'la solicitud ya no está pendiente' }, 409);
return json({ ok: true });
};
+28
View File
@@ -0,0 +1,28 @@
import type { APIRoute } from 'astro';
export const prerender = false;
export const GET: APIRoute = async ({ locals, url }) => {
if (locals.profile?.rol !== 'admin') {
return new Response('Forbidden', { status: 403 });
}
const raw = (url.searchParams.get('q') ?? '').trim();
// ponytail: strip wildcards + comma so .or() parses cleanly; swap for FTS index if search feels slow
const q = raw.replace(/[%_,\\]/g, ' ').slice(0, 64);
if (!q) {
return Response.json([]);
}
const pattern = `%${q}%`;
const { data, error } = await locals.supabase
.from('profiles')
.select('id, nombre, email, matricula')
.or(`nombre.ilike.${pattern},email.ilike.${pattern},matricula.ilike.${pattern}`)
.limit(10);
if (error) return new Response(error.message, { status: 500 });
const items = (data ?? []).map((p) => {
const nombre = p.nombre ?? p.email;
const mat = p.matricula ? ` (${p.matricula})` : '';
return { id: p.id, label: `${nombre}${mat}${p.email}` };
});
return Response.json(items);
};
+90
View File
@@ -0,0 +1,90 @@
import type { APIRoute } from 'astro';
export const prerender = false;
const HEADERS = [
'Fecha solicitud',
'Alumno',
'Matrícula',
'Email',
'Material',
'Nº inventario',
'Cantidad',
'Estado',
'Fecha aprobación',
'Fecha devolución estimada',
'Fecha devolución real',
'Notas',
];
function csvCell(v: unknown): string {
const s = v == null ? '' : String(v);
return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
function isoDate(v: string | null | undefined): string {
if (!v) return '';
// Timestamps y dates ambos son ISO-parseables; toISOString().slice(0,10) devuelve YYYY-MM-DD
const d = new Date(v);
return isNaN(d.getTime()) ? '' : d.toISOString().slice(0, 10);
}
export const GET: APIRoute = async ({ locals, url }) => {
if (locals.profile?.rol !== 'admin') {
return new Response('Forbidden', { status: 403 });
}
const sp = url.searchParams;
const desde = sp.get('desde');
const hasta = sp.get('hasta');
const estado = sp.get('estado');
const materialId = sp.get('material_id');
const alumnoId = sp.get('alumno_id');
let query = locals.supabase
.from('prestamos')
.select(`
id, cantidad, 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)
`)
.order('fecha_solicitud', { ascending: false })
// ponytail: 5000 evita OOM en export ad-hoc; paginar/streamear si un solo reporte lo excede rutinariamente
.limit(5000);
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 (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 lines = [HEADERS, ...rows].map((row) => row.map(csvCell).join(','));
// BOM para que Excel abra UTF-8 sin romper acentos
const csv = '' + lines.join('\r\n') + '\r\n';
const today = new Date().toISOString().slice(0, 10);
return new Response(csv, {
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': `attachment; filename="reporte-${today}.csv"`,
'Cache-Control': 'no-store',
},
});
};
@@ -0,0 +1,27 @@
import type { APIRoute } from 'astro';
export const prerender = false;
export const GET: APIRoute = async ({ locals, url }) => {
if (locals.profile?.rol !== 'admin') {
return new Response('Forbidden', { status: 403 });
}
const raw = (url.searchParams.get('q') ?? '').trim();
// ponytail: strip PostgREST wildcards + comma so ilike/or() stay literal; FTS when catálogo crece >2k
const q = raw.replace(/[%_,\\]/g, ' ').slice(0, 64);
if (!q) {
return Response.json([]);
}
const { data, error } = await locals.supabase
.from('materiales')
.select('id, nombre, numero_inventario')
.ilike('nombre', `%${q}%`)
.order('nombre', { ascending: true })
.limit(10);
if (error) return new Response(error.message, { status: 500 });
const items = (data ?? []).map((m) => ({
id: m.id,
label: m.numero_inventario ? `${m.nombre}${m.numero_inventario}` : m.nombre,
}));
return Response.json(items);
};