From e6c04ef7c9dbb6b43b9d679f722d9bff4dd8a108 Mon Sep 17 00:00:00 2001 From: Collina Systems Date: Sat, 4 Jul 2026 22:56:32 -0600 Subject: [PATCH] =?UTF-8?q?feat(config):=20GET/PATCH=20/api/config=20(admi?= =?UTF-8?q?n)=20=E2=80=94=20ventana,=20switch=20tarea,=20meta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Valida ventana HH:MM con inicio getConfig(fastify.db)); + + // ──────────────── PATCH /config ──────────────── + fastify.patch( + '/config', + { + schema: { + body: { + type: 'object', + minProperties: 1, + properties: { + ventana_horaria: { + type: 'object', + required: ['inicio', 'fin'], + properties: { + inicio: { type: 'string' }, + fin: { type: 'string' }, + }, + }, + tarea_activa: { type: 'boolean' }, + meta_horas_default: { type: 'integer', minimum: 1 }, + }, + }, + }, + }, + async (req, reply) => { + const b = req.body; + if (b.ventana_horaria) { + const { inicio, fin } = b.ventana_horaria; + if (!HHMM.test(inicio) || !HHMM.test(fin) || inicio >= fin) { + return reply.code(400).send({ + error: 'Ventana inválida: usa HH:MM con inicio < fin', + code: 'VENTANA_INVALIDA', + }); + } + } + + const cambios = []; + if (b.ventana_horaria !== undefined) + cambios.push(['ventana_horaria', { inicio: b.ventana_horaria.inicio, fin: b.ventana_horaria.fin }]); + if (b.tarea_activa !== undefined) cambios.push(['tarea_activa', b.tarea_activa]); + if (b.meta_horas_default !== undefined) cambios.push(['meta_horas_default', b.meta_horas_default]); + + const client = await fastify.db.getClient(); + try { + await client.query('BEGIN'); + for (const [clave, valor] of cambios) { + const { + rows: [prev], + } = await client.query('SELECT valor FROM config WHERE clave = $1 FOR UPDATE', [clave]); + await client.query( + `INSERT INTO config (clave, valor, updated_at) VALUES ($1, $2, NOW()) + ON CONFLICT (clave) DO UPDATE SET valor = EXCLUDED.valor, updated_at = NOW()`, + [clave, JSON.stringify(valor)] + ); + await registrarBitacora(client, { + actor: req.supervisora.usuario, + accion: 'editar_config', + entidad: 'config', + antes: { clave, valor: prev?.valor ?? null }, + despues: { clave, valor }, + }); + } + await client.query('COMMIT'); + req.log.info({ claves: cambios.map((c) => c[0]) }, 'Config actualizada'); + return getConfig(fastify.db); + } catch (err) { + await client.query('ROLLBACK'); + throw err; + } finally { + client.release(); + } + } + ); +}