taskController.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import pool from '../config/db.js';
  2. // @desc 获取用户的所有任务
  3. // @route GET /api/tasks
  4. // @access Private
  5. const getTasks = async (req, res) => {
  6. try {
  7. const userId = req.user.id;
  8. const sortBy = req.query.sortBy || 'expected_completion_date';
  9. const order = req.query.order || 'ASC';
  10. let orderClause = '';
  11. switch (sortBy) {
  12. case 'completed':
  13. orderClause = 'completed ASC, expected_completion_date ASC';
  14. break;
  15. case 'created_date':
  16. orderClause = `created_date ${order}`;
  17. break;
  18. case 'expected_completion_date':
  19. orderClause = `expected_completion_date ${order}`;
  20. break;
  21. case 'importance':
  22. orderClause = `importance ${order}`;
  23. break;
  24. default:
  25. orderClause = 'expected_completion_date ASC';
  26. }
  27. const [tasks] = await pool.query(
  28. `SELECT * FROM tasks WHERE user_id = ? ORDER BY ${orderClause}`,
  29. [userId]
  30. );
  31. res.json(tasks);
  32. } catch (error) {
  33. console.error(error);
  34. res.status(500).json({ message: '服务器错误' });
  35. }
  36. };
  37. // @desc 创建新任务
  38. // @route POST /api/tasks
  39. // @access Private
  40. const createTask = async (req, res) => {
  41. try {
  42. const { name, expected_completion_date, importance, notes } = req.body;
  43. const userId = req.user.id;
  44. const created_date = new Date().toISOString().split('T')[0]; // 当前日期
  45. const [result] = await pool.query(
  46. 'INSERT INTO tasks (user_id, name, created_date, expected_completion_date, importance, notes, completed) VALUES (?, ?, ?, ?, ?, ?, false)',
  47. [userId, name, created_date, expected_completion_date, importance, notes]
  48. );
  49. if (result.insertId) {
  50. const [newTask] = await pool.query('SELECT * FROM tasks WHERE id = ?', [result.insertId]);
  51. res.status(201).json(newTask[0]);
  52. } else {
  53. res.status(400).json({ message: '无效的任务数据' });
  54. }
  55. } catch (error) {
  56. console.error(error);
  57. res.status(500).json({ message: '服务器错误' });
  58. }
  59. };
  60. // @desc 获取单个任务
  61. // @route GET /api/tasks/:id
  62. // @access Private
  63. const getTaskById = async (req, res) => {
  64. try {
  65. const taskId = req.params.id;
  66. const userId = req.user.id;
  67. const [tasks] = await pool.query('SELECT * FROM tasks WHERE id = ? AND user_id = ?', [
  68. taskId,
  69. userId,
  70. ]);
  71. if (tasks.length === 0) {
  72. return res.status(404).json({ message: '任务未找到' });
  73. }
  74. res.json(tasks[0]);
  75. } catch (error) {
  76. console.error(error);
  77. res.status(500).json({ message: '服务器错误' });
  78. }
  79. };
  80. // @desc 更新任务
  81. // @route PUT /api/tasks/:id
  82. // @access Private
  83. const updateTask = async (req, res) => {
  84. try {
  85. const taskId = req.params.id;
  86. const userId = req.user.id;
  87. const { name, expected_completion_date, importance, notes, completed } = req.body;
  88. // 检查任务是否存在
  89. const [existingTasks] = await pool.query('SELECT * FROM tasks WHERE id = ? AND user_id = ?', [
  90. taskId,
  91. userId,
  92. ]);
  93. if (existingTasks.length === 0) {
  94. return res.status(404).json({ message: '任务未找到' });
  95. }
  96. // 设置完成日期
  97. let completion_date = null;
  98. if (completed && !existingTasks[0].completed) {
  99. completion_date = new Date().toISOString().split('T')[0]; // 当前日期
  100. } else if (completed) {
  101. completion_date = existingTasks[0].completion_date;
  102. }
  103. // 更新任务
  104. await pool.query(
  105. 'UPDATE tasks SET name = ?, expected_completion_date = ?, importance = ?, notes = ?, completed = ?, completion_date = ? WHERE id = ? AND user_id = ?',
  106. [name, expected_completion_date, importance, notes, completed, completion_date, taskId, userId]
  107. );
  108. // 获取更新后的任务
  109. const [updatedTasks] = await pool.query('SELECT * FROM tasks WHERE id = ?', [taskId]);
  110. res.json(updatedTasks[0]);
  111. } catch (error) {
  112. console.error(error);
  113. res.status(500).json({ message: '服务器错误' });
  114. }
  115. };
  116. // @desc 删除任务
  117. // @route DELETE /api/tasks/:id
  118. // @access Private
  119. const deleteTask = async (req, res) => {
  120. try {
  121. const taskId = req.params.id;
  122. const userId = req.user.id;
  123. // 检查任务是否存在
  124. const [existingTasks] = await pool.query('SELECT * FROM tasks WHERE id = ? AND user_id = ?', [
  125. taskId,
  126. userId,
  127. ]);
  128. if (existingTasks.length === 0) {
  129. return res.status(404).json({ message: '任务未找到' });
  130. }
  131. // 删除任务
  132. await pool.query('DELETE FROM tasks WHERE id = ? AND user_id = ?', [taskId, userId]);
  133. res.json({ message: '任务已删除' });
  134. } catch (error) {
  135. console.error(error);
  136. res.status(500).json({ message: '服务器错误' });
  137. }
  138. };
  139. // @desc 获取最近7天的任务统计
  140. // @route GET /api/tasks/stats/weekly
  141. // @access Private
  142. const getWeeklyStats = async (req, res) => {
  143. try {
  144. const userId = req.user.id;
  145. // 获取最近7天的日期
  146. const dates = [];
  147. for (let i = 6; i >= 0; i--) {
  148. const date = new Date();
  149. date.setDate(date.getDate() - i);
  150. dates.push(date.toISOString().split('T')[0]);
  151. }
  152. // 获取每天创建的任务数量
  153. const createdTasks = await Promise.all(
  154. dates.map(async (date) => {
  155. const [rows] = await pool.query(
  156. 'SELECT COUNT(*) as count FROM tasks WHERE user_id = ? AND created_date = ?',
  157. [userId, date]
  158. );
  159. return { date, count: rows[0].count };
  160. })
  161. );
  162. // 获取每天完成的任务数量
  163. const completedTasks = await Promise.all(
  164. dates.map(async (date) => {
  165. const [rows] = await pool.query(
  166. 'SELECT COUNT(*) as count FROM tasks WHERE user_id = ? AND completion_date = ?',
  167. [userId, date]
  168. );
  169. return { date, count: rows[0].count };
  170. })
  171. );
  172. res.json({
  173. dates,
  174. createdTasks: createdTasks.map(item => item.count),
  175. completedTasks: completedTasks.map(item => item.count)
  176. });
  177. } catch (error) {
  178. console.error(error);
  179. res.status(500).json({ message: '服务器错误' });
  180. }
  181. };
  182. // @desc 获取任务重要程度统计
  183. // @route GET /api/tasks/stats/importance
  184. // @access Private
  185. const getImportanceStats = async (req, res) => {
  186. try {
  187. const userId = req.user.id;
  188. // 获取不同重要程度的任务数量
  189. const [rows] = await pool.query(
  190. 'SELECT importance, COUNT(*) as count FROM tasks WHERE user_id = ? GROUP BY importance ORDER BY importance',
  191. [userId]
  192. );
  193. res.json(rows);
  194. } catch (error) {
  195. console.error(error);
  196. res.status(500).json({ message: '服务器错误' });
  197. }
  198. };
  199. export {
  200. getTasks,
  201. createTask,
  202. getTaskById,
  203. updateTask,
  204. deleteTask,
  205. getWeeklyStats,
  206. getImportanceStats
  207. };