From 12a5d0a928f7765cdef97b8e9f0e343f76fc671a Mon Sep 17 00:00:00 2001 From: Professional Date: Sat, 24 May 2025 02:02:16 +0700 Subject: [PATCH] =?UTF-8?q?=D0=BE=D1=82=D0=BE=D0=B1=D1=80=D0=B0=D0=B6?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=80=D0=B5=D0=B0=D0=BB=D1=8C=D0=BD?= =?UTF-8?q?=D0=BE=D0=B9=20=D1=81=D1=82=D0=B0=D1=82=D0=B8=D1=81=D1=82=D0=B8?= =?UTF-8?q?=D0=BA=D0=B8=20=D0=BD=D0=B0=20=D0=B3=D0=BB=D0=B0=D0=B2=D0=BD?= =?UTF-8?q?=D0=BE=D0=BC=20=D1=8D=D0=BA=D1=80=D0=B0=D0=BD=D0=B5=20=D0=B0?= =?UTF-8?q?=D0=B2=D1=82=D0=BE=D1=80=D0=B8=D0=B7=D0=BE=D0=B2=D0=B0=D0=BD?= =?UTF-8?q?=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D1=82=D0=B5=D0=BB=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/controllers/userController.js | 64 +++++++++++++++++++++++++-- backend/routes/userRoutes.js | 6 ++- src/services/api.js | 5 +++ src/views/HomeView.vue | 43 ++++++++++++++++-- 4 files changed, 110 insertions(+), 8 deletions(-) diff --git a/backend/controllers/userController.js b/backend/controllers/userController.js index 7e955c9..b10e5b1 100644 --- a/backend/controllers/userController.js +++ b/backend/controllers/userController.js @@ -393,11 +393,69 @@ const getUserById = async (req, res, next) => { } }; +// @desc Получить статистику пользователя для главной страницы +// @route GET /api/users/stats +// @access Private +const getUserStats = async (req, res, next) => { + try { + const currentUserId = req.user._id; + + // 1. Получаем количество лайков (кто лайкнул текущего пользователя) + const likesCount = await User.countDocuments({ + liked: currentUserId + }); + + // 2. Получаем количество совпадений (matches) + const matchesCount = await User.findById(currentUserId) + .select('matches') + .then(user => user?.matches?.length || 0); + + // 3. Получаем количество непрочитанных сообщений + const Conversation = require('../models/Conversation'); + const Message = require('../models/Message'); + + // Находим все диалоги пользователя + const userConversations = await Conversation.find({ + participants: currentUserId + }).select('_id'); + + const conversationIds = userConversations.map(conv => conv._id); + + // Считаем непрочитанные сообщения в этих диалогах + const unreadMessagesCount = await Message.countDocuments({ + conversationId: { $in: conversationIds }, + sender: { $ne: currentUserId }, // Сообщения от других пользователей + readBy: { $ne: currentUserId } // Которые текущий пользователь не читал + }); + + // 4. Для просмотров профиля пока возвращаем заглушку, + // так как у нас нет модели для отслеживания просмотров + // В будущем можно добавить отдельную коллекцию ProfileViews + const profileViewsCount = 0; // TODO: Реализовать отслеживание просмотров + + const stats = { + profileViews: profileViewsCount, + likes: likesCount, + matches: matchesCount, + unreadMessages: unreadMessagesCount + }; + + console.log(`[USER_CTRL] Статистика пользователя ${currentUserId}:`, stats); + + res.status(200).json(stats); + + } catch (error) { + console.error('[USER_CTRL] Ошибка при получении статистики пользователя:', error.message); + next(error); + } +}; + module.exports = { updateUserProfile, getUsersForSwiping, uploadUserProfilePhoto, - setMainPhoto, // <--- Добавлено - deletePhoto, // <--- Добавлено - getUserById, // <--- Добавлено + setMainPhoto, + deletePhoto, + getUserById, + getUserStats, // <--- Добавляем новую функцию }; \ No newline at end of file diff --git a/backend/routes/userRoutes.js b/backend/routes/userRoutes.js index c23051c..9dc29d7 100644 --- a/backend/routes/userRoutes.js +++ b/backend/routes/userRoutes.js @@ -1,6 +1,6 @@ const express = require('express'); const router = express.Router(); -const { updateUserProfile, getUsersForSwiping, uploadUserProfilePhoto, setMainPhoto, deletePhoto, getUserById } = require('../controllers/userController'); +const { updateUserProfile, getUsersForSwiping, uploadUserProfilePhoto, setMainPhoto, deletePhoto, getUserById, getUserStats } = require('../controllers/userController'); const { protect } = require('../middleware/authMiddleware'); // Нам нужен protect для защиты маршрута const multer = require('multer'); // 1. Импортируем multer const path = require('path'); // Может понадобиться для фильтрации файлов @@ -36,6 +36,10 @@ const upload = multer({ router.put('/profile', protect, updateUserProfile); router.get('/suggestions', protect, getUsersForSwiping); // <--- НОВЫЙ МАРШРУТ +// Маршрут для получения статистики пользователя +// GET /api/users/stats +router.get('/stats', protect, getUserStats); // <--- НОВЫЙ МАРШРУТ + // Маршрут для загрузки фотографии профиля // POST /api/users/profile/photo router.post('/profile/photo', protect, upload.single('profilePhoto'), uploadUserProfilePhoto); diff --git a/src/services/api.js b/src/services/api.js index 99fa792..9a7dcaa 100644 --- a/src/services/api.js +++ b/src/services/api.js @@ -111,5 +111,10 @@ export default { // Новый метод для получения профиля пользователя по ID getUserById(userId) { return apiClient.get(`/users/${userId}`); + }, + + // Новый метод для получения статистики пользователя + getUserStats() { + return apiClient.get('/users/stats'); } }; \ No newline at end of file diff --git a/src/views/HomeView.vue b/src/views/HomeView.vue index 6324436..1be8ef4 100644 --- a/src/views/HomeView.vue +++ b/src/views/HomeView.vue @@ -104,7 +104,7 @@
-

25

+

{{ stats.profileViews }}

Просмотров профиля

@@ -114,7 +114,7 @@
-

8

+

{{ stats.likes }}

Лайков

@@ -124,7 +124,7 @@
-

3

+

{{ stats.unreadMessages }}

Новых сообщения

@@ -181,10 +181,40 @@