92 lines
2.6 KiB
JavaScript
92 lines
2.6 KiB
JavaScript
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: true }
|
|
}
|
|
|
|
return { ratingValue: rate, isNewRating: true }
|
|
}
|
|
|
|
const getUserLevel = (user, totalRating) => {
|
|
if (user.expertise === 'مدل') {
|
|
if (totalRating <= 50) return 'تازه وارد'
|
|
if (totalRating <= 100) return 'استاندارد'
|
|
if (totalRating <= 300) return 'حرفهای'
|
|
return 'استاد'
|
|
}
|
|
|
|
if (['زیبایی', 'عکاس'].includes(user.expertise)) {
|
|
if (totalRating <= 50) return 'تازه وارد'
|
|
if (totalRating <= 100) return 'استاندارد'
|
|
if (totalRating <= 300) return 'حرفهای'
|
|
return 'استاد'
|
|
}
|
|
|
|
return user.user_level
|
|
}
|
|
|
|
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 totalRating = ratings.reduce((acc, rating) => acc + rating, 0)
|
|
const ratedCount = ratings.length
|
|
|
|
user.user_score = totalRating
|
|
user.user_level = getUserLevel(user, totalRating)
|
|
user.rate = ratedCount > 0 ? (totalRating / ratedCount).toFixed(1) : '0'
|
|
await user.save()
|
|
}
|
|
|
|
module.exports = {
|
|
RATED_FILTER,
|
|
findExistingUserRating,
|
|
hasCreatorRatedUser,
|
|
resolveRatingForComment,
|
|
recalculateUserRating
|
|
}
|