Initial commit
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
const express = require('express');
|
||||
const { authRequired } = require('../middleware/auth');
|
||||
const { resolveTenant } = require('../middleware/tenant');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get('/active', resolveTenant, async (req, res, next) => {
|
||||
try {
|
||||
const [[period]] = await req.tenantPool.query('SELECT * FROM survey_periods WHERE estado = "activa" ORDER BY id DESC LIMIT 1');
|
||||
if (!period) return res.json({ period: null, questions: [] });
|
||||
|
||||
const [questions] = await req.tenantPool.query(
|
||||
'SELECT sq.question_id, sq.question_code, sq.text_snapshot AS text, d.name AS dimension FROM survey_questions sq JOIN dimensions d ON d.id = sq.dimension_id WHERE sq.survey_period_id = ? ORDER BY sq.sort_order ASC',
|
||||
[period.id]
|
||||
);
|
||||
|
||||
res.json({ period, questions });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/responses', authRequired, resolveTenant, async (req, res, next) => {
|
||||
try {
|
||||
const { survey_period_id, answers } = req.body;
|
||||
if (!survey_period_id || !Array.isArray(answers)) {
|
||||
return res.status(400).json({ error: 'survey_period_id y answers requeridos' });
|
||||
}
|
||||
const [[{ total_questions }]] = await req.tenantPool.query(
|
||||
'SELECT COUNT(*) AS total_questions FROM survey_questions WHERE survey_period_id = ?',
|
||||
[survey_period_id]
|
||||
);
|
||||
const uniqueIds = new Set(answers.map((a) => a.question_id));
|
||||
if (uniqueIds.size !== total_questions) {
|
||||
return res.status(400).json({ error: 'Resultados incompletos' });
|
||||
}
|
||||
|
||||
for (const ans of answers) {
|
||||
if (![1,2,3,4,5].includes(Number(ans.value))) {
|
||||
return res.status(400).json({ error: 'Valor inválido' });
|
||||
}
|
||||
const [[qrow]] = await req.tenantPool.query(
|
||||
'SELECT question_code FROM survey_questions WHERE survey_period_id = ? AND question_id = ? LIMIT 1',
|
||||
[survey_period_id, ans.question_id]
|
||||
);
|
||||
await req.tenantPool.query(
|
||||
'INSERT INTO responses (survey_period_id, user_id, question_id, question_code, value) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value)',
|
||||
[survey_period_id, req.user.id, ans.question_id, qrow?.question_code || '', ans.value]
|
||||
);
|
||||
}
|
||||
|
||||
res.json({ ok: true });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user