diff --git a/backend/src/index.js b/backend/src/index.js index 45ca4b7..a539ac1 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -13,6 +13,7 @@ import ajustesRoutes from './routes/ajustes.js'; import becarioAuthRoutes from './routes/becario-auth.js'; import becarioPortalRoutes from './routes/becario-portal.js'; import entradaRoutes from './routes/entrada.js'; +import checadasRoutes from './routes/checadas.js'; const fastify = Fastify({ // node vive detrás del nginx del propio container (y de Traefik en prod): @@ -91,6 +92,7 @@ await fastify.register(ajustesRoutes, { prefix: '/api' }); await fastify.register(becarioAuthRoutes, { prefix: '/api' }); await fastify.register(becarioPortalRoutes, { prefix: '/api' }); await fastify.register(entradaRoutes, { prefix: '/e' }); +await fastify.register(checadasRoutes, { prefix: '/api' }); try { const address = await fastify.listen({ port: config.apiPort, host: config.apiHost }); diff --git a/backend/src/routes/checadas.js b/backend/src/routes/checadas.js new file mode 100644 index 0000000..9121d8d --- /dev/null +++ b/backend/src/routes/checadas.js @@ -0,0 +1,167 @@ +import { requireBecarioActivo } from '../services/sessions.js'; +import { calcularHoras } from '../services/horas.js'; +import { tareaActiva } from '../services/config.js'; + +// Checada (§3, §6). Exige sesión de becario ACTIVO + token fresco del NFC. +// El backend decide entrada/salida por toggle (§10.6); el `tipo` del body es +// la expectativa del cliente y se valida (409 si no coincide). Idempotente +// ante recarga con token ya usado. + +export default async function checadasRoutes(fastify) { + fastify.addHook('onRequest', requireBecarioActivo); + + // ──────────────── GET /checadas/contexto ──────────────── + // Contexto para pintar la pantalla de checada: si la tarea está activa + // (pide concepto), qué registro toca (entrada/salida) y el acumulado actual. + fastify.get('/checadas/contexto', async (req) => { + const [tarea, abierta, acumulado] = await Promise.all([ + tareaActiva(fastify.db), + fastify.db.query( + "SELECT id FROM jornadas WHERE becario_id = $1 AND estado = 'abierta' LIMIT 1", + [req.becario.id] + ), + calcularHoras(fastify.db, req.becario.id), + ]); + return { + tarea_activa: tarea, + tipo_sugerido: abierta.rows.length ? 'salida' : 'entrada', + acumulado, + }; + }); + + // ──────────────── POST /checadas ──────────────── + fastify.post( + '/checadas', + { + schema: { + body: { + type: 'object', + required: ['t'], + properties: { + t: { type: 'string', minLength: 1 }, + tipo: { type: 'string', enum: ['entrada', 'salida'] }, + concepto: { type: 'string' }, + }, + }, + }, + }, + async (req, reply) => { + const becarioId = req.becario.id; + const conceptoRaw = (req.body.concepto || '').trim(); + const client = await fastify.db.getClient(); + try { + await client.query('BEGIN'); + + const { + rows: [tok], + } = await client.query('SELECT * FROM tokens_checada WHERE token = $1 FOR UPDATE', [ + req.body.t, + ]); + + if (!tok) { + await client.query('ROLLBACK'); + return reply.code(400).send({ error: 'Token inválido', code: 'TOKEN_INVALIDO' }); + } + + // Idempotencia: token ya usado → no re-registra (§3.5). Si lo usó este + // mismo becario, devuelve su resultado; si otro, lo rechaza. + if (tok.usado_ts) { + await client.query('ROLLBACK'); + if (tok.becario_id !== becarioId) { + return reply + .code(409) + .send({ error: 'Token ya utilizado', code: 'TOKEN_YA_USADO' }); + } + const prev = await fastify.db.query('SELECT tipo FROM checadas WHERE id = $1', [ + tok.checada_id, + ]); + const acumulado = await calcularHoras(fastify.db, becarioId); + return { tipo: prev.rows[0]?.tipo ?? null, duplicada: true, acumulado }; + } + + if (new Date(tok.expira_ts) < new Date()) { + await client.query('ROLLBACK'); + return reply.code(410).send({ error: 'Token vencido', code: 'TOKEN_VENCIDO' }); + } + + // Toggle: el backend determina el tipo real (§10.6). + const { + rows: [abierta], + } = await client.query( + "SELECT id FROM jornadas WHERE becario_id = $1 AND estado = 'abierta' FOR UPDATE", + [becarioId] + ); + const tipo = abierta ? 'salida' : 'entrada'; + + // El tipo del cliente es expectativa; si no coincide, 409 con el correcto. + if (req.body.tipo && req.body.tipo !== tipo) { + await client.query('ROLLBACK'); + return reply.code(409).send({ + error: `El registro que corresponde ahora es '${tipo}'`, + code: 'CONFLICTO_TIPO', + esperado: tipo, + }); + } + + // Concepto obligatorio solo si el switch de tarea está activo (§5). + const tarea = await tareaActiva(client); + if (tarea && !conceptoRaw) { + await client.query('ROLLBACK'); + return reply + .code(400) + .send({ error: 'El concepto de la tarea es obligatorio', code: 'CONCEPTO_REQUERIDO' }); + } + + // Checada cruda (inmutable) con IP + user-agent + concepto en meta (§3.4). + const meta = { + ip: req.ip, + user_agent: req.headers['user-agent'] || null, + concepto: tarea ? conceptoRaw : conceptoRaw || null, + }; + const { + rows: [checada], + } = await client.query( + `INSERT INTO checadas (becario_id, tipo, origen, meta) + VALUES ($1, $2, $3, $4) RETURNING id, ts`, + [becarioId, tipo, tok.origen, JSON.stringify(meta)] + ); + + // Materializa/cierra la jornada (§6). + if (tipo === 'entrada') { + await client.query( + `INSERT INTO jornadas (becario_id, entrada_ts, checada_entrada_id, estado) + VALUES ($1, $2, $3, 'abierta')`, + [becarioId, checada.ts, checada.id] + ); + } else { + await client.query( + `UPDATE jornadas SET salida_ts = $2, checada_salida_id = $3, estado = 'cerrada' + WHERE id = $1`, + [abierta.id, checada.ts, checada.id] + ); + } + + // Consume el token (un solo uso). + await client.query( + 'UPDATE tokens_checada SET usado_ts = NOW(), becario_id = $2, checada_id = $3 WHERE token = $1', + [req.body.t, becarioId, checada.id] + ); + + await client.query('COMMIT'); + const acumulado = await calcularHoras(fastify.db, becarioId); + req.log.info({ becarioId, tipo, checadaId: checada.id }, 'Checada registrada'); + return { tipo, ts: checada.ts, duplicada: false, acumulado }; + } catch (err) { + await client.query('ROLLBACK'); + if (err.code === '23505') { + return reply + .code(409) + .send({ error: 'Ya tienes una jornada abierta', code: 'JORNADA_ABIERTA_DUPLICADA' }); + } + throw err; + } finally { + client.release(); + } + } + ); +}