feat(ajustes): crear (minutos +/- con motivo) y listar por becario

También: CORS lista el origen del panel. El panel es same-origin tras
nginx pero el navegador manda Origin en POST; el contenedor corre en
NODE_ENV=production, así que se declara vía ALLOWED_ORIGINS.
This commit is contained in:
Collina Systems committed 2026-07-04 19:08:51 -06:00
1 parent 2a5d3881d3
commit a427acdcf2
3 files changed
+99 -2

No files matched your search

+4 -2
View File
@@ -16,5 +16,7 @@ SUPERVISORA_USER=supervisora
SUPERVISORA_PASSWORD_INICIAL=
# Una jornada abierta más de estas horas pasa a estado "revision" (Fase C)
MAX_HORAS_JORNADA=12
# Orígenes extra permitidos por CORS (el frontend servido por nginx es same-origin)
ALLOWED_ORIGINS=
# Origen(es) del panel permitidos por CORS. El panel se sirve same-origin
# detrás de nginx, pero el navegador manda header Origin en los POST y hay que
# listarlo. Dev: http://localhost,http://127.0.0.1 · Prod: https://<dominio>
ALLOWED_ORIGINS=http://localhost,http://127.0.0.1
+2
View File
@@ -9,6 +9,7 @@ import authRoutes from './routes/auth.js';
import becariosRoutes from './routes/becarios.js';
import dispositivosRoutes from './routes/dispositivos.js';
import jornadasRoutes from './routes/jornadas.js';
import ajustesRoutes from './routes/ajustes.js';
const fastify = Fastify({
// node vive detrás del nginx del propio container (y de Traefik en prod):
@@ -83,6 +84,7 @@ await fastify.register(authRoutes, { prefix: '/api' });
await fastify.register(becariosRoutes, { prefix: '/api' });
await fastify.register(dispositivosRoutes, { prefix: '/api' });
await fastify.register(jornadasRoutes, { prefix: '/api' });
await fastify.register(ajustesRoutes, { prefix: '/api' });
try {
const address = await fastify.listen({ port: config.apiPort, host: config.apiHost });
+93
View File
@@ -0,0 +1,93 @@
import { requireSupervisora } from '../services/sessions.js';
import { registrarBitacora } from '../services/bitacora.js';
// Ajustes de minutos con motivo obligatorio (§4). Suman/restan al total
// junto con las jornadas cerradas. Solo la supervisora los crea.
export default async function ajustesRoutes(fastify) {
fastify.addHook('preHandler', requireSupervisora);
// ──────────────── GET /becarios/:id/ajustes ────────────────
fastify.get(
'/becarios/:id/ajustes',
{ schema: { params: idParam } },
async (req) => {
const { rows } = await fastify.db.query(
'SELECT id, becario_id, minutos, motivo, created_at FROM ajustes WHERE becario_id = $1 ORDER BY created_at DESC',
[req.params.id]
);
return rows;
}
);
// ──────────────── POST /becarios/:id/ajustes ────────────────
fastify.post(
'/becarios/:id/ajustes',
{
schema: {
params: idParam,
body: {
type: 'object',
required: ['minutos', 'motivo'],
properties: {
// != 0 lo refuerza el CHECK de la tabla; aquí solo el tipo
minutos: { type: 'integer' },
motivo: { type: 'string', minLength: 1 },
},
},
},
},
async (req, reply) => {
const { minutos, motivo } = req.body;
if (minutos === 0 || motivo.trim().length === 0) {
return reply.code(400).send({
error: 'minutos debe ser distinto de 0 y motivo no puede estar vacío',
code: 'AJUSTE_INVALIDO',
});
}
const client = await fastify.db.getClient();
try {
await client.query('BEGIN');
// Verifica que el becario exista (el FK también, pero da mejor error)
const { rows: b } = await client.query('SELECT 1 FROM becarios WHERE id = $1', [
req.params.id,
]);
if (b.length === 0) {
await client.query('ROLLBACK');
return reply
.code(404)
.send({ error: 'Becario no encontrado', code: 'BECARIO_NO_ENCONTRADO' });
}
const {
rows: [ajuste],
} = await client.query(
`INSERT INTO ajustes (becario_id, minutos, motivo)
VALUES ($1, $2, $3)
RETURNING id, becario_id, minutos, motivo, created_at`,
[req.params.id, minutos, motivo.trim()]
);
await registrarBitacora(client, {
actor: req.supervisora.usuario,
accion: 'crear',
entidad: 'ajuste',
entidadId: ajuste.id,
despues: ajuste,
});
await client.query('COMMIT');
req.log.info({ ajusteId: ajuste.id, minutos }, 'Ajuste creado');
return reply.code(201).send(ajuste);
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
);
}
const idParam = {
type: 'object',
required: ['id'],
properties: { id: { type: 'string', format: 'uuid' } },
};