diff --git a/backend/routes/polls.js b/backend/routes/polls.js index 23088b3..89c9df0 100644 --- a/backend/routes/polls.js +++ b/backend/routes/polls.js @@ -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: '投票成功' }); }); diff --git a/public/js/pages/polls.js b/public/js/pages/polls.js index af766be..63f02c8 100644 --- a/public/js/pages/polls.js +++ b/public/js/pages/polls.js @@ -23,20 +23,22 @@ const PollsPage = { renderPoll(p) { const opts = p.options || []; const max = Math.max(1, ...Object.values(p.votes || {})); + const showResult = Auth.isOwner() || !p.voted; return `
${U.esc(p.description)}
`:''} + ${p.voted && !showResult ? `