diff --git a/src/entities/bot/bot.controller.js b/src/entities/bot/bot.controller.js index 81775ec..2b56e62 100644 --- a/src/entities/bot/bot.controller.js +++ b/src/entities/bot/bot.controller.js @@ -1,23 +1,6 @@ -const botService = require('./bot.service'); +const botService = require("./bot.service"); class BotController { - /** - * Get tasks for a specific date by chat_id - * Route: GET /bot/tasks/:chat_id?date=YYYY-MM-DD - * If date is not provided, returns tasks for today - */ - getTasksForDateByChatId(req, res) { - const chat_id = req.params.chat_id; - const date = req.query.date || null; // Optional date parameter - - botService.getTasksForDateByChatId(chat_id, date).then((result) => { - res.status(result.status).json(result.data); - }); - } - - /** - * @deprecated Use getTasksForDateByChatId instead. This method is kept for backward compatibility. - */ getTasksForTodayByChatId(req, res) { const chat_id = req.params.chat_id; botService.getTasksForTodayByChatId(chat_id).then((result) => { diff --git a/src/entities/bot/bot.routes.js b/src/entities/bot/bot.routes.js index 0ab3aa8..1328960 100644 --- a/src/entities/bot/bot.routes.js +++ b/src/entities/bot/bot.routes.js @@ -2,13 +2,7 @@ const express = require('express'); const router = express.Router(); const botController = require('./bot.controller'); -// Получить задачи на конкретную дату по chat_id -// Route: GET /bot/tasks/:chat_id?date=YYYY-MM-DD -// If date is not provided, returns tasks for today -//TODO:: authenticate придумать для бота -router.get('/tasks/:chat_id', (req, res) => botController.getTasksForDateByChatId(req, res)); - -// Deprecated: старый роут для обратной совместимости +// Получить задачи на сегодня по chat_id //TODO:: authenticate придумать для бота router.get('/today/:chat_id', (req, res) => botController.getTasksForTodayByChatId(req, res)); diff --git a/src/entities/bot/bot.service.js b/src/entities/bot/bot.service.js index 6cf5103..6d46a66 100644 --- a/src/entities/bot/bot.service.js +++ b/src/entities/bot/bot.service.js @@ -1,68 +1,22 @@ const userService = require('../user/user.service'); const taskService = require('../task/task.service'); -const templateModel = require('../template.task/models/template.task.model'); -const { getDateStringInTZ } = require('../../utils/date'); - /** * Bot service class with business logic for bot operations */ class BotService { - /** - * Get tasks for a specific date by chat_id (optimized with subtasks) - * Returns format compatible with old API: { tasks, templates, dateString, dayOfWeek } - * @param {string} chat_id - Telegram chat ID - * @param {string} date - Optional date in YYYY-MM-DD format. If not provided, uses today in user's timezone - * @returns {Promise<{status: number, data: any}>} - */ - async getTasksForDateByChatId(chat_id, date = null) { + async getTasksForTodayByChatId(chat_id) { try { const user = await userService.getUserByChatId(chat_id); if (!user) { return { status: 404, data: { error: 'Пользователь не найден' } }; } - - const timezone = user.timezone || 'Europe/Moscow'; - - // If date is not provided, use today in user's timezone - const taskDate = date || getDateStringInTZ(timezone); - const dateString = taskDate; - - // Get tasks with subtasks (optimized - 2 queries) - const tasksResult = await taskService.getTasksForDateWithSubTasks(user.id, taskDate); - if (tasksResult.status !== 200) { - return tasksResult; - } - - // Calculate day of week for templates - // Parse the date to get day of week - const dateObj = new Date(taskDate + 'T12:00:00'); // Use noon to avoid timezone issues - const jsDay = dateObj.getDay(); - const dayOfWeek = jsDay === 0 ? 7 : jsDay; // Convert Sunday (0) to 7 - - // Get templates for this day of week - const [templates] = await templateModel.getTemplatesForDay(user.id, dayOfWeek); - - return { - status: 200, - data: { - tasks: tasksResult.data, - templates: templates || [], - dateString, - dayOfWeek, - }, - }; + const result = await taskService.getTasksForToday(user.id, user.timezone); + return { status: result.status, data: result.data }; } catch (err) { - console.error('❌ Ошибка при получении задач на дату:', err); + console.error("❌ Ошибка при получении задач на сегодня:", err); return { status: 500, data: { error: err.message } }; } } - - /** - * @deprecated Use getTasksForDateByChatId instead. This method is kept for backward compatibility. - */ - async getTasksForTodayByChatId(chat_id) { - return this.getTasksForDateByChatId(chat_id); - } } // Create a singleton instance diff --git a/src/entities/task/task.service.js b/src/entities/task/task.service.js index d86f560..0e2d1f6 100644 --- a/src/entities/task/task.service.js +++ b/src/entities/task/task.service.js @@ -422,53 +422,6 @@ class TaskService { return { status: 500, data: { error: err.message } }; } } - - /** - * Optimized version: Get tasks for a specific date with subtasks using only 2 SQL queries - * @param {number} userId - User ID - * @param {string} taskDate - Date in YYYY-MM-DD format - * @returns {Promise<{status: number, data: any}>} - */ - async getTasksForDateWithSubTasks(userId, taskDate) { - try { - // Get all tasks for the date and all subtasks for the user in parallel (2 queries total) - const [[tasks], [subtasks]] = await Promise.all([ - taskModel.getTasksForDate(userId, taskDate), - subtaskModel.getAllSubtasksByUserId(userId), - ]); - - if (!tasks.length) { - return { status: 404, data: { error: 'Задачи не найдены' } }; - } - - // Filter subtasks to only include those for tasks on this date - const taskIds = new Set(tasks.map((task) => task.id)); - const relevantSubtasks = (subtasks || []).filter((subtask) => - taskIds.has(subtask.parent_task_id) - ); - - // Group subtasks by parent_task_id for O(1) lookup - const subtasksByTaskId = new Map(); - for (const subtask of relevantSubtasks) { - const taskId = subtask.parent_task_id; - if (!subtasksByTaskId.has(taskId)) { - subtasksByTaskId.set(taskId, []); - } - subtasksByTaskId.get(taskId).push(subtask); - } - - // Combine tasks with their subtasks - const fullTasks = tasks.map((task) => ({ - ...task, - subtasks: subtasksByTaskId.get(task.id) || [], - })); - - return { status: 200, data: fullTasks }; - } catch (err) { - console.error('❌ Ошибка при получении задач на дату с подзадачами:', err); - return { status: 500, data: { error: err.message } }; - } - } } // Create a singleton instance