From a427acdcf23a7a2443fc7557f94450c8f301d99f Mon Sep 17 00:00:00 2001 From: Collina Systems Date: Sat, 4 Jul 2026 19:08:51 -0600 Subject: [PATCH] feat(ajustes): crear (minutos +/- con motivo) y listar por becario MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .env.example | 6 ++- backend/src/index.js | 2 + backend/src/routes/ajustes.js | 93 +++++++++++++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 2 deletions(-) create mode 100644 backend/src/routes/ajustes.js diff --git a/.env.example b/.env.example index a6a8bef..c40785e 100644 --- a/.env.example +++ b/.env.example @@ -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:// +ALLOWED_ORIGINS=http://localhost,http://127.0.0.1 diff --git a/backend/src/index.js b/backend/src/index.js index 79688ec..31a1380 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -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 }); diff --git a/backend/src/routes/ajustes.js b/backend/src/routes/ajustes.js new file mode 100644 index 0000000..c386e53 --- /dev/null +++ b/backend/src/routes/ajustes.js @@ -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' } }, +};