diff --git a/src/modules/product/Repository/comment.ts b/src/modules/product/Repository/comment.ts index 2e6e4a9..2bc9257 100644 --- a/src/modules/product/Repository/comment.ts +++ b/src/modules/product/Repository/comment.ts @@ -1,6 +1,7 @@ import { Types } from "mongoose"; import { BaseRepository } from "../../../common/base/repository"; +import { Question_CommentStatus } from "../../../common/enums/question_comment.enum"; import { ProductsCommentsQueries } from "../../../common/types/query.type"; import { IComment } from "../models/Abstraction/IComment"; import { CommentModel } from "../models/comment.model"; @@ -100,6 +101,31 @@ class CommentRepository extends BaseRepository { async getCommentsForReport() { return await this.model.find({ status: "pending" }).countDocuments(); } + + async getProductStats(productId: number) { + const result = await this.model.aggregate([ + { + $match: { product: productId, status: Question_CommentStatus.Accepted }, + }, + { + $group: { + _id: "$product", + commentsCount: { $sum: 1 }, + averageRate: { $avg: "$rate" }, + }, + }, + { + $project: { + _id: 0, + product: "$_id", + commentsCount: 1, + averageRate: { $round: ["$averageRate", 1] }, + }, + }, + ]); + + return result[0] || { product: productId, commentsCount: 0, averageRate: 0 }; + } } function createCommentRepo(): CommentRepository { diff --git a/src/modules/product/providers/product.service.ts b/src/modules/product/providers/product.service.ts index 053d168..27677da 100644 --- a/src/modules/product/providers/product.service.ts +++ b/src/modules/product/providers/product.service.ts @@ -979,8 +979,9 @@ class ProductService { throw new BadRequestError(CommonMessage.NotEnoughVariant); } const product = ProductDTO.transformProduct(docs[0]); + const stats = await this.commentRepo.getProductStats(productId); const categoryPath = await this.categoryRepo.getCategoryPath(product.category._id.toString()); - return { product, categoryPath }; + return { product, categoryPath, stats }; } //**************************************************************