origin/apps/server/src/models/enrollment/enrollment.service.ts

75 lines
1.9 KiB
TypeScript
Raw Normal View History

2025-01-03 09:24:46 +08:00
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
2024-12-31 15:57:32 +08:00
import { BaseService } from '../base/base.service';
import {
UserProfile,
db,
ObjectType,
Prisma,
2025-01-03 09:24:46 +08:00
EnrollmentStatus
2024-12-31 15:57:32 +08:00
} from '@nicestack/common';
2025-01-03 09:24:46 +08:00
import { z } from 'zod';
import { EnrollSchema, UnenrollSchema } from './enroll.schema';
import EventBus, { CrudOperation } from '@server/utils/event-bus';
2024-12-31 15:57:32 +08:00
@Injectable()
export class EnrollmentService extends BaseService<Prisma.EnrollmentDelegate> {
constructor() {
super(db, ObjectType.COURSE);
}
2025-01-03 09:24:46 +08:00
async enroll(params: z.infer<typeof EnrollSchema>) {
const { studentId, courseId } = params
const result = await db.$transaction(async tx => {
// 检查是否已经报名
const existing = await tx.enrollment.findUnique({
where: {
studentId_courseId: {
studentId: studentId,
courseId: courseId,
},
},
});
if (existing) {
throw new ConflictException('Already enrolled in this course');
}
// 创建报名记录
const enrollment = await tx.enrollment.create({
data: {
studentId: studentId,
courseId: courseId,
status: EnrollmentStatus.ACTIVE,
},
});
2024-12-31 15:57:32 +08:00
2025-01-03 09:24:46 +08:00
return enrollment;
});
EventBus.emit('dataChanged', {
type: ObjectType.ENROLLMENT,
operation: CrudOperation.CREATED,
data: result,
});
return result
}
async unenroll(params: z.infer<typeof UnenrollSchema>) {
const { studentId, courseId } = params
const result = await db.enrollment.update({
where: {
studentId_courseId: {
studentId,
courseId,
},
},
data: {
status: EnrollmentStatus.CANCELLED
}
});
EventBus.emit('dataChanged', {
type: ObjectType.ENROLLMENT,
operation: CrudOperation.UPDATED,
data: result,
});
return result
}
2024-12-31 15:57:32 +08:00
}