feat(solicitudes): cola admin — autorizar (materializa/cierra) y rechazar
Autorizar olvido_entrada crea checada(s) manual(es) + jornada (cerrada si hay salida → suma; abierta si no). Autorizar autocierre fija la salida y cierra la jornada en 'revision'. Rechazar deja la jornada como está. Toda resolución a bitacora; valida rango (23514→400) y jornada abierta (23505).
This commit is contained in:
1 parent
e6c04ef7c9
commit
9a5bd439ac
2 files changed
+250
No files matched your search
@@ -15,6 +15,7 @@ import becarioPortalRoutes from './routes/becario-portal.js';
|
||||
import entradaRoutes from './routes/entrada.js';
|
||||
import checadasRoutes from './routes/checadas.js';
|
||||
import configRoutes from './routes/config.js';
|
||||
import solicitudesRoutes from './routes/solicitudes.js';
|
||||
|
||||
const fastify = Fastify({
|
||||
// node vive detrás del nginx del propio container (y de Traefik en prod):
|
||||
@@ -95,6 +96,7 @@ await fastify.register(becarioPortalRoutes, { prefix: '/api' });
|
||||
await fastify.register(entradaRoutes, { prefix: '/e' });
|
||||
await fastify.register(checadasRoutes, { prefix: '/api' });
|
||||
await fastify.register(configRoutes, { prefix: '/api' });
|
||||
await fastify.register(solicitudesRoutes, { prefix: '/api' });
|
||||
|
||||
try {
|
||||
const address = await fastify.listen({ port: config.apiPort, host: config.apiHost });
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import { requireSupervisora } from '../services/sessions.js';
|
||||
import { registrarBitacora } from '../services/bitacora.js';
|
||||
|
||||
// Cola de solicitudes de los becarios (§7). La supervisora autoriza, corrige o
|
||||
// rechaza. Autorizar es el único camino de escritura efectiva (§10.1):
|
||||
// olvido_entrada → materializa la jornada (checada manual + jornada)
|
||||
// autorizar_autocierre → fija la salida real y cierra la jornada en 'revision'
|
||||
// Toda resolución escribe en bitacora.
|
||||
|
||||
const idParam = {
|
||||
type: 'object',
|
||||
required: ['id'],
|
||||
properties: { id: { type: 'string', format: 'uuid' } },
|
||||
};
|
||||
|
||||
export default async function solicitudesRoutes(fastify) {
|
||||
fastify.addHook('onRequest', requireSupervisora);
|
||||
|
||||
// ──────────────── GET /solicitudes?estado= ────────────────
|
||||
fastify.get(
|
||||
'/solicitudes',
|
||||
{
|
||||
schema: {
|
||||
querystring: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
estado: { type: 'string', enum: ['pendiente', 'autorizada', 'rechazada'] },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
async (req) => {
|
||||
const params = [];
|
||||
let where = '';
|
||||
if (req.query.estado) {
|
||||
params.push(req.query.estado);
|
||||
where = 'WHERE s.estado = $1';
|
||||
}
|
||||
const { rows } = await fastify.db.query(
|
||||
`SELECT s.id, s.becario_id, b.nombre AS becario_nombre, b.telefono AS becario_telefono,
|
||||
s.tipo, s.propuesta, s.estado, s.jornada_id,
|
||||
s.resuelta_por, s.resuelta_ts, s.created_at
|
||||
FROM solicitudes s
|
||||
JOIN becarios b ON b.id = s.becario_id
|
||||
${where}
|
||||
ORDER BY s.created_at DESC`,
|
||||
params
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
);
|
||||
|
||||
// ──────────────── POST /solicitudes/:id/autorizar ────────────────
|
||||
fastify.post(
|
||||
'/solicitudes/:id/autorizar',
|
||||
{
|
||||
schema: {
|
||||
params: idParam,
|
||||
body: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
entrada_ts: { type: 'string', format: 'date-time' },
|
||||
salida_ts: { type: 'string', format: 'date-time' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
async (req, reply) => {
|
||||
const client = await fastify.db.getClient();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const {
|
||||
rows: [sol],
|
||||
} = await client.query('SELECT * FROM solicitudes WHERE id = $1 FOR UPDATE', [
|
||||
req.params.id,
|
||||
]);
|
||||
if (!sol) {
|
||||
await client.query('ROLLBACK');
|
||||
return notFound(reply);
|
||||
}
|
||||
if (sol.estado !== 'pendiente') {
|
||||
await client.query('ROLLBACK');
|
||||
return reply
|
||||
.code(409)
|
||||
.send({ error: `La solicitud ya está '${sol.estado}'`, code: 'YA_RESUELTA' });
|
||||
}
|
||||
|
||||
let jornadaId = null;
|
||||
const despues = {};
|
||||
|
||||
if (sol.tipo === 'olvido_entrada') {
|
||||
// Materializa la jornada: checada de entrada (manual, inmutable) +
|
||||
// opcionalmente salida para que quede cerrada y sume (§7).
|
||||
const entradaTs = req.body?.entrada_ts ?? sol.propuesta?.entrada_ts;
|
||||
if (!entradaTs) {
|
||||
await client.query('ROLLBACK');
|
||||
return reply
|
||||
.code(400)
|
||||
.send({ error: 'Falta entrada_ts', code: 'ENTRADA_REQUERIDA' });
|
||||
}
|
||||
const salidaTs = req.body?.salida_ts ?? null;
|
||||
const {
|
||||
rows: [ce],
|
||||
} = await client.query(
|
||||
`INSERT INTO checadas (becario_id, tipo, ts, origen, meta)
|
||||
VALUES ($1, 'entrada', $2, 'manual', $3) RETURNING id`,
|
||||
[sol.becario_id, entradaTs, JSON.stringify({ solicitud_id: sol.id, motivo: 'olvido_entrada' })]
|
||||
);
|
||||
let cs = null;
|
||||
if (salidaTs) {
|
||||
const r = await client.query(
|
||||
`INSERT INTO checadas (becario_id, tipo, ts, origen, meta)
|
||||
VALUES ($1, 'salida', $2, 'manual', $3) RETURNING id`,
|
||||
[sol.becario_id, salidaTs, JSON.stringify({ solicitud_id: sol.id, motivo: 'olvido_entrada' })]
|
||||
);
|
||||
cs = r.rows[0].id;
|
||||
}
|
||||
const {
|
||||
rows: [jornada],
|
||||
} = await client.query(
|
||||
`INSERT INTO jornadas
|
||||
(becario_id, entrada_ts, salida_ts, checada_entrada_id, checada_salida_id, estado, editada)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, TRUE) RETURNING id`,
|
||||
[sol.becario_id, entradaTs, salidaTs, ce.id, cs, salidaTs ? 'cerrada' : 'abierta']
|
||||
);
|
||||
jornadaId = jornada.id;
|
||||
despues.entrada_ts = entradaTs;
|
||||
despues.salida_ts = salidaTs;
|
||||
despues.jornada_estado = salidaTs ? 'cerrada' : 'abierta';
|
||||
} else {
|
||||
// autorizar_autocierre: fija la salida real y cierra la jornada en revision.
|
||||
const salidaTs = req.body?.salida_ts;
|
||||
if (!salidaTs) {
|
||||
await client.query('ROLLBACK');
|
||||
return reply
|
||||
.code(400)
|
||||
.send({ error: 'Falta salida_ts para cerrar la jornada', code: 'SALIDA_REQUERIDA' });
|
||||
}
|
||||
const {
|
||||
rows: [jornada],
|
||||
} = await client.query(
|
||||
`UPDATE jornadas SET salida_ts = $2, estado = 'cerrada', editada = TRUE
|
||||
WHERE id = $1 AND estado = 'revision' RETURNING id`,
|
||||
[sol.jornada_id, salidaTs]
|
||||
);
|
||||
if (!jornada) {
|
||||
await client.query('ROLLBACK');
|
||||
return reply
|
||||
.code(409)
|
||||
.send({ error: 'La jornada asociada no está en revisión', code: 'JORNADA_NO_REVISION' });
|
||||
}
|
||||
jornadaId = jornada.id;
|
||||
despues.salida_ts = salidaTs;
|
||||
despues.jornada_estado = 'cerrada';
|
||||
}
|
||||
|
||||
const {
|
||||
rows: [resuelta],
|
||||
} = await client.query(
|
||||
`UPDATE solicitudes
|
||||
SET estado = 'autorizada', jornada_id = $2, resuelta_por = $3, resuelta_ts = NOW()
|
||||
WHERE id = $1 RETURNING id, tipo, estado, jornada_id, resuelta_ts`,
|
||||
[sol.id, jornadaId, req.supervisora.usuario]
|
||||
);
|
||||
await registrarBitacora(client, {
|
||||
actor: req.supervisora.usuario,
|
||||
accion: 'autorizar_solicitud',
|
||||
entidad: 'solicitud',
|
||||
entidadId: sol.id,
|
||||
antes: { tipo: sol.tipo, propuesta: sol.propuesta },
|
||||
despues,
|
||||
});
|
||||
await client.query('COMMIT');
|
||||
req.log.info({ solicitudId: sol.id, jornadaId }, 'Solicitud autorizada');
|
||||
return resuelta;
|
||||
} catch (err) {
|
||||
await client.query('ROLLBACK');
|
||||
if (err.code === '23514') {
|
||||
return reply
|
||||
.code(400)
|
||||
.send({ error: 'La salida no puede ser anterior a la entrada', code: 'RANGO_INVALIDO' });
|
||||
}
|
||||
if (err.code === '23505') {
|
||||
return reply
|
||||
.code(409)
|
||||
.send({ error: 'El becario ya tiene una jornada abierta', code: 'JORNADA_ABIERTA_DUPLICADA' });
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// ──────────────── POST /solicitudes/:id/rechazar ────────────────
|
||||
fastify.post(
|
||||
'/solicitudes/:id/rechazar',
|
||||
{ schema: { params: idParam } },
|
||||
async (req, reply) => {
|
||||
const client = await fastify.db.getClient();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const {
|
||||
rows: [sol],
|
||||
} = await client.query('SELECT * FROM solicitudes WHERE id = $1 FOR UPDATE', [
|
||||
req.params.id,
|
||||
]);
|
||||
if (!sol) {
|
||||
await client.query('ROLLBACK');
|
||||
return notFound(reply);
|
||||
}
|
||||
if (sol.estado !== 'pendiente') {
|
||||
await client.query('ROLLBACK');
|
||||
return reply
|
||||
.code(409)
|
||||
.send({ error: `La solicitud ya está '${sol.estado}'`, code: 'YA_RESUELTA' });
|
||||
}
|
||||
const {
|
||||
rows: [resuelta],
|
||||
} = await client.query(
|
||||
`UPDATE solicitudes SET estado = 'rechazada', resuelta_por = $2, resuelta_ts = NOW()
|
||||
WHERE id = $1 RETURNING id, tipo, estado, resuelta_ts`,
|
||||
[sol.id, req.supervisora.usuario]
|
||||
);
|
||||
await registrarBitacora(client, {
|
||||
actor: req.supervisora.usuario,
|
||||
accion: 'rechazar_solicitud',
|
||||
entidad: 'solicitud',
|
||||
entidadId: sol.id,
|
||||
antes: { tipo: sol.tipo, propuesta: sol.propuesta },
|
||||
despues: { estado: 'rechazada' },
|
||||
});
|
||||
await client.query('COMMIT');
|
||||
req.log.info({ solicitudId: sol.id }, 'Solicitud rechazada');
|
||||
return resuelta;
|
||||
} catch (err) {
|
||||
await client.query('ROLLBACK');
|
||||
throw err;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function notFound(reply) {
|
||||
return reply.code(404).send({ error: 'Solicitud no encontrada', code: 'SOLICITUD_NO_ENCONTRADA' });
|
||||
}
|
||||
Reference in new issue
Block a user