staff_data/apps/server/src/models/post/utils.ts

126 lines
2.7 KiB
TypeScript
Raw Normal View History

2025-02-06 16:32:52 +08:00
import {
db,
EnrollmentStatus,
Post,
PostType,
UserProfile,
VisitType,
} from '@nice/common';
2024-12-30 09:22:38 +08:00
2025-02-06 16:32:52 +08:00
export async function setPostRelation(params: {
data: Post;
staff?: UserProfile;
}) {
const { data, staff } = params;
const limitedComments = await db.post.findMany({
where: {
parentId: data.id,
type: PostType.POST_COMMENT,
},
include: {
author: true,
},
take: 5,
});
const commentsCount = await db.post.count({
where: {
parentId: data.id,
type: PostType.POST_COMMENT,
},
});
const readed =
(await db.visit.count({
where: {
postId: data.id,
type: VisitType.READED,
visitorId: staff?.id,
},
})) > 0;
const readedCount = await db.visit.count({
where: {
postId: data.id,
type: VisitType.READED,
},
});
Object.assign(data, {
readed,
readedCount,
limitedComments,
commentsCount,
// trouble
});
}
export async function updateParentLectureStats(parentId: string) {
const ParentStats = await db.post.aggregate({
where: {
ancestors: {
some: {
ancestorId: parentId,
descendant: {
type: PostType.LECTURE,
deletedAt: null,
},
2024-12-30 08:26:40 +08:00
},
2025-02-06 16:32:52 +08:00
},
},
_count: { _all: true },
_sum: {
duration: true,
},
});
await db.post.update({
where: { id: parentId },
data: {
//totalLectures: courseStats._count._all,
//totalDuration: courseStats._sum.duration || 0,
},
});
}
2024-12-31 15:57:32 +08:00
2025-02-06 16:32:52 +08:00
// 更新课程评价统计
export async function updateCourseReviewStats(courseId: string) {
const reviews = await db.visit.findMany({
where: {
postId: courseId,
type: PostType.COURSE_REVIEW,
deletedAt: null,
},
select: { views: true },
});
const numberOfReviews = reviews.length;
const averageRating =
numberOfReviews > 0
? reviews.reduce((sum, review) => sum + review.views, 0) / numberOfReviews
: 0;
2024-12-30 08:26:40 +08:00
2025-02-06 16:32:52 +08:00
return db.post.update({
where: { id: courseId },
data: {
// numberOfReviews,
//averageRating,
},
});
}
// 更新课程注册统计
export async function updateCourseEnrollmentStats(courseId: string) {
const completedEnrollments = await db.enrollment.count({
where: {
postId: courseId,
status: EnrollmentStatus.COMPLETED,
},
});
const totalEnrollments = await db.enrollment.count({
where: { postId: courseId },
});
const completionRate =
totalEnrollments > 0 ? (completedEnrollments / totalEnrollments) * 100 : 0;
return db.post.update({
where: { id: courseId },
data: {
// numberOfStudents: totalEnrollments,
// completionRate,
},
});
}