const CommentModel = require('../models/CommentModel') const UserModel = require('../models/UserModel') const RATED_FILTER = { $ne: null, $gt: 0 } const findExistingUserRating = (creatorId, targetUserId) => { return CommentModel.findOne({ creator: creatorId, user: targetUserId, rating: RATED_FILTER, }) } const hasCreatorRatedUser = async (creatorId, targetUserId) => { const existing = await findExistingUserRating(creatorId, targetUserId) return !!existing } const resolveRatingForComment = async ({ creatorId, targetUserId, rate }) => { const existingRating = await findExistingUserRating(creatorId, targetUserId) if (existingRating) { if (rate && rate >= 1 && rate <= 5) { return { ratingValue: null, isNewRating: false, alreadyRated: true, } } return { ratingValue: null, isNewRating: false } } if (!rate || rate < 1 || rate > 5) { return { ratingValue: null, isNewRating: false, requiresRating: false } } return { ratingValue: rate, isNewRating: true } } /** rate = مجموع ستاره‌های دریافتی | user_score = میانگین ۱ تا ۵ */ const getUserLevel = (user, totalStars) => { if (totalStars <= 500) return 'تازه وارد' if (totalStars <= 2000) return 'استاندارد' if (totalStars <= 10000) return 'حرفه‌ای' if (user.expertise === 'مدل') return 'سپورمدل' if (['زیبایی', 'عکاس', 'آرایشگر'].includes(user.expertise)) { return 'استاد' } return 'استاد' } const recalculateUserRating = async (targetUserId) => { const user = await UserModel.findById(targetUserId) if (!user) return const ratedComments = await CommentModel.find({ user: targetUserId, rating: RATED_FILTER, }).sort({ createdAt: 1 }) const uniqueRatingsByCreator = new Map() for (const comment of ratedComments) { const creatorKey = comment.creator.toString() if (!uniqueRatingsByCreator.has(creatorKey)) { uniqueRatingsByCreator.set(creatorKey, comment.rating) } } const ratings = Array.from(uniqueRatingsByCreator.values()) const totalStars = ratings.reduce((acc, rating) => acc + rating, 0) const ratedCount = ratings.length user.rate = String(totalStars) user.user_score = ratedCount > 0 ? (totalStars / ratedCount).toFixed(1) : '0' user.user_level = getUserLevel(user, totalStars) await user.save() } module.exports = { RATED_FILTER, findExistingUserRating, hasCreatorRatedUser, resolveRatingForComment, recalculateUserRating, getUserLevel, }