update project

This commit is contained in:
2025-11-04 18:20:19 +03:00
parent 0d1dcf21c1
commit 71f3f353ab
5 changed files with 386 additions and 43 deletions

View File

@@ -463,6 +463,49 @@ router.patch('/profile', verifyToken, async (req, res) => {
return res.status(result.status).json(result.body);
}
if (action === 'updateProfile') {
await waitForDatabaseConnection();
const { firstName, lastName, position, phone } = payload;
if (!firstName && !lastName && !position && !phone) {
return res.status(400).json({ error: 'At least one field must be provided' });
}
const user = await User.findById(req.userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
if (firstName) user.firstName = firstName;
if (lastName) user.lastName = lastName;
if (position !== undefined) user.position = position;
if (phone !== undefined) user.phone = phone;
user.updatedAt = new Date();
await user.save();
const company = user.companyId ? await Company.findById(user.companyId) : null;
return res.json({
message: 'Profile updated successfully',
user: {
id: user._id.toString(),
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
position: user.position,
phone: user.phone,
companyId: user.companyId?.toString()
},
company: company ? {
id: company._id.toString(),
name: company.fullName,
inn: company.inn
} : null
});
}
res.json({ message: 'Profile endpoint' });
} catch (error) {
console.error('Profile update error:', error);

View File

@@ -84,13 +84,30 @@ router.get('/my/stats', verifyToken, async (req, res) => {
: Promise.resolve(0),
]);
// Подсчитываем просмотры профиля из запросов к профилю компании
const profileViews = company?.metrics?.profileViews || 0;
// Получаем статистику за последнюю неделю для изменений
const weekAgo = new Date();
weekAgo.setDate(weekAgo.getDate() - 7);
const sentRequestsLastWeek = await Request.countDocuments({
senderCompanyId: companyIdString,
createdAt: { $gte: weekAgo }
});
const receivedRequestsLastWeek = await Request.countDocuments({
recipientCompanyId: companyIdString,
createdAt: { $gte: weekAgo }
});
const stats = {
profileViews: company?.metrics?.profileViews || 0,
profileViewsChange: 0,
profileViews: profileViews,
profileViewsChange: 0, // Можно добавить отслеживание просмотров, если нужно
sentRequests,
sentRequestsChange: 0,
sentRequestsChange: sentRequestsLastWeek,
receivedRequests,
receivedRequestsChange: 0,
receivedRequestsChange: receivedRequestsLastWeek,
newMessages: unreadMessages,
rating: Number.isFinite(company?.rating) ? Number(company.rating) : 0,
};
@@ -231,6 +248,24 @@ router.get('/:id', async (req, res) => {
});
}
// Отслеживаем просмотр профиля (если это не владелец компании)
const userId = req.userId;
if (userId) {
const User = require('../models/User');
const user = await User.findById(userId);
if (user && user.companyId && user.companyId.toString() !== company._id.toString()) {
// Инкрементируем просмотры профиля
if (!company.metrics) {
company.metrics = {};
}
if (!company.metrics.profileViews) {
company.metrics.profileViews = 0;
}
company.metrics.profileViews = (company.metrics.profileViews || 0) + 1;
await company.save();
}
}
res.json({
...company.toObject(),
id: company._id

View File

@@ -2,6 +2,7 @@ const express = require('express');
const router = express.Router();
const { verifyToken } = require('../middleware/auth');
const Review = require('../models/Review');
const Company = require('../models/Company');
// Функция для логирования с проверкой DEV переменной
const log = (message, data = '') => {
@@ -14,6 +15,35 @@ const log = (message, data = '') => {
}
};
// Функция для пересчета рейтинга компании
const updateCompanyRating = async (companyId) => {
try {
const reviews = await Review.find({ companyId });
if (reviews.length === 0) {
await Company.findByIdAndUpdate(companyId, {
rating: 0,
reviews: 0,
updatedAt: new Date()
});
return;
}
const totalRating = reviews.reduce((sum, review) => sum + review.rating, 0);
const averageRating = totalRating / reviews.length;
await Company.findByIdAndUpdate(companyId, {
rating: averageRating,
reviews: reviews.length,
updatedAt: new Date()
});
log('[Reviews] Updated company rating:', companyId, 'New rating:', averageRating);
} catch (error) {
console.error('[Reviews] Error updating company rating:', error.message);
}
};
// GET /reviews/company/:companyId - получить отзывы компании
router.get('/company/:companyId', verifyToken, async (req, res) => {
try {
@@ -42,30 +72,54 @@ router.post('/', verifyToken, async (req, res) => {
if (!companyId || !rating || !comment) {
return res.status(400).json({
error: 'companyId, rating, and comment are required',
error: 'Заполните все обязательные поля: компания, рейтинг и комментарий',
});
}
if (rating < 1 || rating > 5) {
return res.status(400).json({
error: 'Rating must be between 1 and 5',
error: 'Рейтинг должен быть от 1 до 5',
});
}
if (comment.trim().length < 10 || comment.trim().length > 1000) {
const trimmedComment = comment.trim();
if (trimmedComment.length < 10) {
return res.status(400).json({
error: 'Comment must be between 10 and 1000 characters',
error: 'Отзыв должен содержать минимум 10 символов',
});
}
if (trimmedComment.length > 1000) {
return res.status(400).json({
error: 'Отзыв не должен превышать 1000 символов',
});
}
// Получить данные пользователя из БД для актуальной информации
const User = require('../models/User');
const Company = require('../models/Company');
const user = await User.findById(req.userId);
const userCompany = user && user.companyId ? await Company.findById(user.companyId) : null;
if (!user) {
return res.status(404).json({
error: 'Пользователь не найден',
});
}
// Создать новый отзыв
const newReview = new Review({
companyId,
authorCompanyId: req.companyId,
authorName: req.user.firstName + ' ' + req.user.lastName,
authorCompany: req.user.companyName || 'Company',
authorCompanyId: user.companyId || req.companyId,
authorName: user.firstName && user.lastName
? `${user.firstName} ${user.lastName}`
: req.user?.firstName && req.user?.lastName
? `${req.user.firstName} ${req.user.lastName}`
: 'Аноним',
authorCompany: userCompany?.fullName || userCompany?.shortName || req.user?.companyName || 'Компания',
rating: parseInt(rating),
comment: comment.trim(),
comment: trimmedComment,
verified: true,
createdAt: new Date(),
updatedAt: new Date()
@@ -75,11 +129,14 @@ router.post('/', verifyToken, async (req, res) => {
log('[Reviews] New review created:', savedReview._id);
// Пересчитываем рейтинг компании
await updateCompanyRating(companyId);
res.status(201).json(savedReview);
} catch (error) {
console.error('[Reviews] Error creating review:', error.message);
res.status(500).json({
error: 'Internal server error',
error: 'Ошибка при сохранении отзыва',
message: error.message,
});
}