Files
MC_Report/backend/routes/polls.js
canglan 8c5ce78fd0 chore: add AGPLv3 copyright header to all source files
- 52 JS files (backend + public/js): header with
  Copyright (C) 2026 Sea Network Technology Studio
  Author: CangLan <admin@sea-studio.top>
  + AGPLv3 notice
- idempotent (skips if header present), all syntax-checked
2026-08-19 20:27:05 +08:00

142 lines
7.7 KiB
JavaScript

/*
* MC Report System
* Copyright (C) 2026 Sea Network Technology Studio
* Author: CangLan <admin@sea-studio.top>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
const express = require('express');
const { query, getRow } = require('../db');
const { authenticate, requireRole } = require('../middleware/auth');
const router = express.Router();
router.get('/groups', authenticate, async (req, res) => {
res.json(await query('SELECT * FROM server_groups ORDER BY group_name, server_name'));
});
router.post('/groups', authenticate, requireRole('owner'), async (req, res) => {
const { group_name, server_name, alias } = req.body;
if (!group_name || !server_name) return res.status(400).json({ error: '分组名和子服名为必填' });
if (alias) {
const dup = await getRow('SELECT id FROM server_groups WHERE alias = ?', [alias]);
if (dup) return res.status(400).json({ error: '该外部别名已被使用' });
}
await query('INSERT IGNORE INTO server_groups(group_name, server_name, alias) VALUES (?,?,?)', [group_name, server_name, alias || '']);
res.status(201).json({ message: '已添加' });
});
router.put('/groups/:id', authenticate, requireRole('owner'), async (req, res) => {
const { group_name, server_name, alias } = req.body;
if (!group_name || !server_name) return res.status(400).json({ error: '分组名和子服名为必填' });
if (alias) {
const dup = await getRow('SELECT id FROM server_groups WHERE alias = ? AND id != ?', [alias, req.params.id]);
if (dup) return res.status(400).json({ error: '该外部别名已被使用' });
}
await query('UPDATE server_groups SET group_name = ?, server_name = ?, alias = ? WHERE id = ?', [group_name, server_name, alias || '', req.params.id]);
res.json({ message: '已更新' });
});
router.delete('/groups/:id', authenticate, requireRole('owner'), async (req, res) => {
await query('DELETE FROM server_groups WHERE id = ?', [req.params.id]);
res.json({ message: '已删除' });
});
router.get('/active', authenticate, async (req, res) => {
const groups = await query('SELECT DISTINCT group_name, server_name FROM server_groups ORDER BY group_name, server_name');
const result = {};
for (const g of groups) {
const polls = await query(`SELECT id, title, description, group_name, server_name, start_time, end_time, active, created_at FROM polls
WHERE active = 1 AND group_name = ? AND server_name = ? AND (end_time IS NULL OR end_time > NOW())
ORDER BY created_at DESC LIMIT 1`, [g.group_name, g.server_name]);
if (polls.length === 0) continue;
const p = polls[0];
p.options = JSON.parse(p.options || '[]');
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] = 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;
if (!result[g.group_name]) result[g.group_name] = [];
result[g.group_name].push({ ...p, server_name: g.server_name });
}
res.json(result);
});
router.get('/:id', authenticate, requireRole('owner'), async (req, res) => {
const p = await getRow('SELECT * FROM polls WHERE id = ?', [req.params.id]);
if (!p) return res.status(404).json({ error: '不存在' });
res.json(p);
});
router.post('/', authenticate, requireRole('owner'), async (req, res) => {
const { title, description, options, group_name, server_name, start_time, end_time } = req.body;
if (!title || !options || !Array.isArray(options) || options.length < 2) return res.status(400).json({ error: '标题和至少2个选项为必填' });
if (!group_name || !server_name) return res.status(400).json({ error: '请选择分组和子服' });
const existing = await getRow(`SELECT id FROM polls WHERE active = 1 AND group_name = ? AND server_name = ? AND (end_time IS NULL OR end_time > NOW())`, [group_name, server_name]);
if (existing) return res.status(400).json({ error: '该子服已有进行中的投票' });
await query(`INSERT INTO polls(title, description, options, group_name, server_name, start_time, end_time, created_by) VALUES (?,?,?,?,?,?,?,?)`,
[title, description||'', JSON.stringify(options), group_name, server_name, start_time||null, end_time||null, req.user.id]);
res.status(201).json({ message: '创建成功' });
});
router.put('/:id', authenticate, requireRole('owner'), async (req, res) => {
const p = await getRow('SELECT * FROM polls WHERE id = ?', [req.params.id]);
if (!p) return res.status(404).json({ error: '投票不存在' });
const fields = {};
if (req.body.title) fields.title = req.body.title;
if (req.body.description !== undefined) fields.description = req.body.description;
if (req.body.active !== undefined) fields.active = req.body.active ? 1 : 0;
if (req.body.options) fields.options = JSON.stringify(req.body.options);
if (req.body.start_time !== undefined) fields.start_time = req.body.start_time || null;
if (req.body.end_time !== undefined) fields.end_time = req.body.end_time || null;
if (req.body.group_name) fields.group_name = req.body.group_name;
if (req.body.server_name) fields.server_name = req.body.server_name;
if (!Object.keys(fields).length) return res.status(400).json({ error: '无更新内容' });
const sets = Object.keys(fields).map(k => `${k} = ?`).join(', ');
await query(`UPDATE polls SET ${sets} WHERE id = ?`, [...Object.values(fields), req.params.id]);
res.json({ message: '更新成功' });
});
router.delete('/:id', authenticate, requireRole('owner'), async (req, res) => {
await query('DELETE FROM poll_votes WHERE poll_id = ?', [req.params.id]);
await query('DELETE FROM polls WHERE id = ?', [req.params.id]);
res.json({ message: '已删除' });
});
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: '投票不存在或已关闭' });
if (p.end_time && new Date(p.end_time) < new Date()) return res.status(400).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 (?,?,?)', [req.params.id, req.user.id, option_index]);
res.json({ message: '投票成功' });
});
module.exports = router;