fix: no revote, blind result after voting, admin 1.5 vote weight
This commit is contained in:
@@ -13,13 +13,17 @@ router.get('/active', authenticate, async (req, res) => {
|
||||
const polls = await query('SELECT id, title, description, active, created_at FROM polls WHERE active = 1 ORDER BY created_at DESC');
|
||||
for (const p of polls) {
|
||||
p.options = JSON.parse(p.options || '[]');
|
||||
const rows = await query('SELECT option_index, COUNT(*) as count FROM poll_votes WHERE poll_id = ? GROUP BY option_index', [p.id]);
|
||||
const rows = await query(`SELECT pv.option_index,
|
||||
SUM(CASE WHEN u.role IN ('owner','admin') THEN 1.5 ELSE 1 END) as total
|
||||
FROM poll_votes pv JOIN users u ON pv.user_id = u.id
|
||||
WHERE pv.poll_id = ? GROUP BY pv.option_index`, [p.id]);
|
||||
p.votes = {};
|
||||
let total = 0;
|
||||
for (const r of rows) { p.votes[r.option_index] = r.count; total += r.count; }
|
||||
p.total = total;
|
||||
for (const r of rows) { p.votes[r.option_index] = Math.round(r.total * 10) / 10; total += r.total; }
|
||||
p.total = Math.round(total * 10) / 10;
|
||||
const myVote = await getRow('SELECT option_index FROM poll_votes WHERE poll_id = ? AND user_id = ?', [p.id, req.user.id]);
|
||||
p.my_vote = myVote ? myVote.option_index : null;
|
||||
p.voted = !!myVote;
|
||||
}
|
||||
res.json(polls);
|
||||
});
|
||||
@@ -54,11 +58,13 @@ router.delete('/:id', authenticate, requireRole('owner'), async (req, res) => {
|
||||
router.post('/:id/vote', authenticate, async (req, res) => {
|
||||
const p = await getRow('SELECT * FROM polls WHERE id = ? AND active = 1', [req.params.id]);
|
||||
if (!p) return res.status(404).json({ error: '投票不存在或已关闭' });
|
||||
const voted = await getRow('SELECT id FROM poll_votes WHERE poll_id = ? AND user_id = ?', [p.id, req.user.id]);
|
||||
if (voted) return res.status(400).json({ error: '您已投过票' });
|
||||
const { option_index } = req.body;
|
||||
if (option_index === undefined || option_index === null) return res.status(400).json({ error: '请选择选项' });
|
||||
const opts = JSON.parse(p.options || '[]');
|
||||
if (option_index < 0 || option_index >= opts.length) return res.status(400).json({ error: '无效选项' });
|
||||
await query('INSERT INTO poll_votes(poll_id, user_id, option_index) VALUES (?,?,?) ON DUPLICATE KEY UPDATE option_index = VALUES(option_index)', [req.params.id, req.user.id, option_index]);
|
||||
await query('INSERT INTO poll_votes(poll_id, user_id, option_index) VALUES (?,?,?)', [req.params.id, req.user.id, option_index]);
|
||||
res.json({ message: '投票成功' });
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user