123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239 |
- import pool from '../config/db.js';
- // @desc 获取用户的所有任务
- // @route GET /api/tasks
- // @access Private
- const getTasks = async (req, res) => {
- try {
- const userId = req.user.id;
- const sortBy = req.query.sortBy || 'expected_completion_date';
- const order = req.query.order || 'ASC';
-
- let orderClause = '';
- switch (sortBy) {
- case 'completed':
- orderClause = 'completed ASC, expected_completion_date ASC';
- break;
- case 'created_date':
- orderClause = `created_date ${order}`;
- break;
- case 'expected_completion_date':
- orderClause = `expected_completion_date ${order}`;
- break;
- case 'importance':
- orderClause = `importance ${order}`;
- break;
- default:
- orderClause = 'expected_completion_date ASC';
- }
- const [tasks] = await pool.query(
- `SELECT * FROM tasks WHERE user_id = ? ORDER BY ${orderClause}`,
- [userId]
- );
- res.json(tasks);
- } catch (error) {
- console.error(error);
- res.status(500).json({ message: '服务器错误' });
- }
- };
- // @desc 创建新任务
- // @route POST /api/tasks
- // @access Private
- const createTask = async (req, res) => {
- try {
- const { name, expected_completion_date, importance, notes } = req.body;
- const userId = req.user.id;
- const created_date = new Date().toISOString().split('T')[0]; // 当前日期
- const [result] = await pool.query(
- 'INSERT INTO tasks (user_id, name, created_date, expected_completion_date, importance, notes, completed) VALUES (?, ?, ?, ?, ?, ?, false)',
- [userId, name, created_date, expected_completion_date, importance, notes]
- );
- if (result.insertId) {
- const [newTask] = await pool.query('SELECT * FROM tasks WHERE id = ?', [result.insertId]);
- res.status(201).json(newTask[0]);
- } else {
- res.status(400).json({ message: '无效的任务数据' });
- }
- } catch (error) {
- console.error(error);
- res.status(500).json({ message: '服务器错误' });
- }
- };
- // @desc 获取单个任务
- // @route GET /api/tasks/:id
- // @access Private
- const getTaskById = async (req, res) => {
- try {
- const taskId = req.params.id;
- const userId = req.user.id;
- const [tasks] = await pool.query('SELECT * FROM tasks WHERE id = ? AND user_id = ?', [
- taskId,
- userId,
- ]);
- if (tasks.length === 0) {
- return res.status(404).json({ message: '任务未找到' });
- }
- res.json(tasks[0]);
- } catch (error) {
- console.error(error);
- res.status(500).json({ message: '服务器错误' });
- }
- };
- // @desc 更新任务
- // @route PUT /api/tasks/:id
- // @access Private
- const updateTask = async (req, res) => {
- try {
- const taskId = req.params.id;
- const userId = req.user.id;
- const { name, expected_completion_date, importance, notes, completed } = req.body;
- // 检查任务是否存在
- const [existingTasks] = await pool.query('SELECT * FROM tasks WHERE id = ? AND user_id = ?', [
- taskId,
- userId,
- ]);
- if (existingTasks.length === 0) {
- return res.status(404).json({ message: '任务未找到' });
- }
- // 设置完成日期
- let completion_date = null;
- if (completed && !existingTasks[0].completed) {
- completion_date = new Date().toISOString().split('T')[0]; // 当前日期
- } else if (completed) {
- completion_date = existingTasks[0].completion_date;
- }
- // 更新任务
- await pool.query(
- 'UPDATE tasks SET name = ?, expected_completion_date = ?, importance = ?, notes = ?, completed = ?, completion_date = ? WHERE id = ? AND user_id = ?',
- [name, expected_completion_date, importance, notes, completed, completion_date, taskId, userId]
- );
- // 获取更新后的任务
- const [updatedTasks] = await pool.query('SELECT * FROM tasks WHERE id = ?', [taskId]);
- res.json(updatedTasks[0]);
- } catch (error) {
- console.error(error);
- res.status(500).json({ message: '服务器错误' });
- }
- };
- // @desc 删除任务
- // @route DELETE /api/tasks/:id
- // @access Private
- const deleteTask = async (req, res) => {
- try {
- const taskId = req.params.id;
- const userId = req.user.id;
- // 检查任务是否存在
- const [existingTasks] = await pool.query('SELECT * FROM tasks WHERE id = ? AND user_id = ?', [
- taskId,
- userId,
- ]);
- if (existingTasks.length === 0) {
- return res.status(404).json({ message: '任务未找到' });
- }
- // 删除任务
- await pool.query('DELETE FROM tasks WHERE id = ? AND user_id = ?', [taskId, userId]);
- res.json({ message: '任务已删除' });
- } catch (error) {
- console.error(error);
- res.status(500).json({ message: '服务器错误' });
- }
- };
- // @desc 获取最近7天的任务统计
- // @route GET /api/tasks/stats/weekly
- // @access Private
- const getWeeklyStats = async (req, res) => {
- try {
- const userId = req.user.id;
-
- // 获取最近7天的日期
- const dates = [];
- for (let i = 6; i >= 0; i--) {
- const date = new Date();
- date.setDate(date.getDate() - i);
- dates.push(date.toISOString().split('T')[0]);
- }
-
- // 获取每天创建的任务数量
- const createdTasks = await Promise.all(
- dates.map(async (date) => {
- const [rows] = await pool.query(
- 'SELECT COUNT(*) as count FROM tasks WHERE user_id = ? AND created_date = ?',
- [userId, date]
- );
- return { date, count: rows[0].count };
- })
- );
-
- // 获取每天完成的任务数量
- const completedTasks = await Promise.all(
- dates.map(async (date) => {
- const [rows] = await pool.query(
- 'SELECT COUNT(*) as count FROM tasks WHERE user_id = ? AND completion_date = ?',
- [userId, date]
- );
- return { date, count: rows[0].count };
- })
- );
-
- res.json({
- dates,
- createdTasks: createdTasks.map(item => item.count),
- completedTasks: completedTasks.map(item => item.count)
- });
- } catch (error) {
- console.error(error);
- res.status(500).json({ message: '服务器错误' });
- }
- };
- // @desc 获取任务重要程度统计
- // @route GET /api/tasks/stats/importance
- // @access Private
- const getImportanceStats = async (req, res) => {
- try {
- const userId = req.user.id;
-
- // 获取不同重要程度的任务数量
- const [rows] = await pool.query(
- 'SELECT importance, COUNT(*) as count FROM tasks WHERE user_id = ? GROUP BY importance ORDER BY importance',
- [userId]
- );
-
- res.json(rows);
- } catch (error) {
- console.error(error);
- res.status(500).json({ message: '服务器错误' });
- }
- };
- export {
- getTasks,
- createTask,
- getTaskById,
- updateTask,
- deleteTask,
- getWeeklyStats,
- getImportanceStats
- };
|