feat(becarios): CRUD con baja lógica y avance de horas
- 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
This commit is contained in:
1 parent
bb0ad96431
commit
fa472fce86
2 files changed
+209
No files matched your search
@@ -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 });
|
||||
|
||||
@@ -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' });
|
||||
}
|
||||
Reference in new issue
Block a user