From fa472fce86a8bead63525e5ab0afe16ad31db728 Mon Sep 17 00:00:00 2001 From: Collina Systems Date: Sat, 4 Jul 2026 18:26:59 -0600 Subject: [PATCH] =?UTF-8?q?feat(becarios):=20CRUD=20con=20baja=20l=C3=B3gi?= =?UTF-8?q?ca=20y=20avance=20de=20horas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GET lista/detalle con horas ya calculadas por el backend - POST crear, PATCH editar (nombre/matrícula/institución/meta_horas) - POST /:id/baja: estado='baja', nunca DELETE físico (conserva historial) - cada mutación escribe en bitacora (antes/después) dentro de la transacción --- backend/src/index.js | 2 + backend/src/routes/becarios.js | 207 +++++++++++++++++++++++++++++++++ 2 files changed, 209 insertions(+) create mode 100644 backend/src/routes/becarios.js diff --git a/backend/src/index.js b/backend/src/index.js index 34ce450..c35eba5 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -6,6 +6,7 @@ import { config } from './config.js'; import { db } from './db/client.js'; import { runMigrations, seedSupervisora } from './db/migrate.js'; import authRoutes from './routes/auth.js'; +import becariosRoutes from './routes/becarios.js'; const fastify = Fastify({ // node vive detrás del nginx del propio container (y de Traefik en prod): @@ -77,6 +78,7 @@ await seedSupervisora(db, fastify.log); fastify.decorate('db', db); await fastify.register(authRoutes, { prefix: '/api' }); +await fastify.register(becariosRoutes, { prefix: '/api' }); try { const address = await fastify.listen({ port: config.apiPort, host: config.apiHost }); diff --git a/backend/src/routes/becarios.js b/backend/src/routes/becarios.js new file mode 100644 index 0000000..e3ca23d --- /dev/null +++ b/backend/src/routes/becarios.js @@ -0,0 +1,207 @@ +import { requireSupervisora } from '../services/sessions.js'; +import { registrarBitacora } from '../services/bitacora.js'; +import { calcularHoras, calcularHorasIndex } from '../services/horas.js'; + +const COLS = 'id, nombre, matricula, institucion, meta_horas, estado, created_at'; + +export default async function becariosRoutes(fastify) { + // Todo endpoint de este plugin exige sesión de supervisora (§10.1). + fastify.addHook('preHandler', requireSupervisora); + + // ──────────────── GET /becarios ──────────────── + // Lista con el avance (horas) ya calculado por el backend. + fastify.get('/becarios', async () => { + const [{ rows }, horas] = await Promise.all([ + fastify.db.query(`SELECT ${COLS} FROM becarios ORDER BY estado, nombre`), + calcularHorasIndex(fastify.db), + ]); + return rows.map((b) => ({ ...b, horas: horas[b.id] ?? null })); + }); + + // ──────────────── GET /becarios/:id ──────────────── + fastify.get( + '/becarios/:id', + { schema: { params: idParam } }, + async (req, reply) => { + const { rows } = await fastify.db.query(`SELECT ${COLS} FROM becarios WHERE id = $1`, [ + req.params.id, + ]); + if (rows.length === 0) return notFound(reply); + const horas = await calcularHoras(fastify.db, req.params.id); + return { ...rows[0], horas }; + } + ); + + // ──────────────── POST /becarios ──────────────── + fastify.post( + '/becarios', + { + schema: { + body: { + type: 'object', + required: ['nombre'], + properties: { + nombre: { type: 'string', minLength: 1 }, + matricula: { type: 'string' }, + institucion: { type: 'string' }, + meta_horas: { type: 'integer', minimum: 1 }, + }, + }, + }, + }, + async (req, reply) => { + const { nombre, matricula = null, institucion = null, meta_horas = 480 } = req.body; + const client = await fastify.db.getClient(); + try { + await client.query('BEGIN'); + const { + rows: [becario], + } = await client.query( + `INSERT INTO becarios (nombre, matricula, institucion, meta_horas) + VALUES ($1, $2, $3, $4) RETURNING ${COLS}`, + [nombre, matricula, institucion, meta_horas] + ); + await registrarBitacora(client, { + actor: req.supervisora.usuario, + accion: 'crear', + entidad: 'becario', + entidadId: becario.id, + despues: becario, + }); + await client.query('COMMIT'); + req.log.info({ becarioId: becario.id }, 'Becario creado'); + return reply.code(201).send(becario); + } catch (err) { + await client.query('ROLLBACK'); + throw err; + } finally { + client.release(); + } + } + ); + + // ──────────────── PATCH /becarios/:id ──────────────── + fastify.patch( + '/becarios/:id', + { + schema: { + params: idParam, + body: { + type: 'object', + minProperties: 1, + properties: { + nombre: { type: 'string', minLength: 1 }, + matricula: { type: 'string' }, + institucion: { type: 'string' }, + meta_horas: { type: 'integer', minimum: 1 }, + }, + }, + }, + }, + async (req, reply) => { + const campos = ['nombre', 'matricula', 'institucion', 'meta_horas']; + const client = await fastify.db.getClient(); + try { + await client.query('BEGIN'); + const { + rows: [antes], + } = await client.query(`SELECT ${COLS} FROM becarios WHERE id = $1 FOR UPDATE`, [ + req.params.id, + ]); + if (!antes) { + await client.query('ROLLBACK'); + return notFound(reply); + } + const sets = []; + const values = [req.params.id]; + let i = 2; + for (const campo of campos) { + if (req.body[campo] !== undefined) { + sets.push(`${campo} = $${i++}`); + values.push(req.body[campo]); + } + } + const { + rows: [despues], + } = await client.query( + `UPDATE becarios SET ${sets.join(', ')} WHERE id = $1 RETURNING ${COLS}`, + values + ); + await registrarBitacora(client, { + actor: req.supervisora.usuario, + accion: 'editar', + entidad: 'becario', + entidadId: despues.id, + antes, + despues, + }); + await client.query('COMMIT'); + req.log.info({ becarioId: despues.id }, 'Becario editado'); + return despues; + } catch (err) { + await client.query('ROLLBACK'); + throw err; + } finally { + client.release(); + } + } + ); + + // ──────────────── POST /becarios/:id/baja ──────────────── + // Baja lógica (estado='baja'), nunca DELETE físico (§10, conserva historial). + fastify.post( + '/becarios/:id/baja', + { schema: { params: idParam } }, + async (req, reply) => { + const client = await fastify.db.getClient(); + try { + await client.query('BEGIN'); + const { + rows: [antes], + } = await client.query(`SELECT ${COLS} FROM becarios WHERE id = $1 FOR UPDATE`, [ + req.params.id, + ]); + if (!antes) { + await client.query('ROLLBACK'); + return notFound(reply); + } + if (antes.estado === 'baja') { + await client.query('ROLLBACK'); + return reply.code(409).send({ error: 'El becario ya está de baja', code: 'YA_DE_BAJA' }); + } + const { + rows: [despues], + } = await client.query( + `UPDATE becarios SET estado = 'baja' WHERE id = $1 RETURNING ${COLS}`, + [req.params.id] + ); + await registrarBitacora(client, { + actor: req.supervisora.usuario, + accion: 'baja', + entidad: 'becario', + entidadId: despues.id, + antes, + despues, + }); + await client.query('COMMIT'); + req.log.info({ becarioId: despues.id }, 'Becario dado de baja'); + return despues; + } catch (err) { + await client.query('ROLLBACK'); + throw err; + } finally { + client.release(); + } + } + ); +} + +const idParam = { + type: 'object', + required: ['id'], + properties: { id: { type: 'string', format: 'uuid' } }, +}; + +function notFound(reply) { + return reply.code(404).send({ error: 'Becario no encontrado', code: 'BECARIO_NO_ENCONTRADO' }); +}