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

79 lines
1.9 KiB
TypeScript
Raw Normal View History

2025-02-06 16:32:52 +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-02-06 16:32:52 +08:00
EnrollmentStatus,
2025-01-06 08:45:23 +08:00
} from '@nice/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>) {
2025-02-06 16:32:52 +08:00
const { studentId, postId } = params;
const result = await db.$transaction(async (tx) => {
2025-01-03 09:24:46 +08:00
// 检查是否已经报名
const existing = await tx.enrollment.findUnique({
where: {
2025-02-06 16:32:52 +08:00
studentId_postId: {
2025-01-03 09:24:46 +08:00
studentId: studentId,
2025-02-06 16:32:52 +08:00
postId: postId,
2025-01-03 09:24:46 +08:00
},
},
});
if (existing) {
2025-02-06 16:32:52 +08:00
throw new ConflictException('Already enrolled in this post');
2025-01-03 09:24:46 +08:00
}
// 创建报名记录
const enrollment = await tx.enrollment.create({
data: {
studentId: studentId,
2025-02-06 16:32:52 +08:00
postId: postId,
2025-01-03 09:24:46 +08:00
status: EnrollmentStatus.ACTIVE,
},
});
2024-12-31 15:57:32 +08:00
2025-01-03 09:24:46 +08:00
return enrollment;
});
2025-02-06 16:32:52 +08:00
2025-01-03 09:24:46 +08:00
EventBus.emit('dataChanged', {
type: ObjectType.ENROLLMENT,
operation: CrudOperation.CREATED,
data: result,
});
2025-02-06 16:32:52 +08:00
return result;
2025-01-03 09:24:46 +08:00
}
async unenroll(params: z.infer<typeof UnenrollSchema>) {
2025-02-06 16:32:52 +08:00
const { studentId, postId } = params;
2025-01-03 09:24:46 +08:00
const result = await db.enrollment.update({
where: {
2025-02-06 16:32:52 +08:00
studentId_postId: {
2025-01-03 09:24:46 +08:00
studentId,
2025-02-06 16:32:52 +08:00
postId,
2025-01-03 09:24:46 +08:00
},
},
data: {
2025-02-06 16:32:52 +08:00
status: EnrollmentStatus.CANCELLED,
},
2025-01-03 09:24:46 +08:00
});
2025-02-06 16:32:52 +08:00
2025-01-03 09:24:46 +08:00
EventBus.emit('dataChanged', {
type: ObjectType.ENROLLMENT,
operation: CrudOperation.UPDATED,
data: result,
});
2025-02-06 16:32:52 +08:00
return result;
2025-01-03 09:24:46 +08:00
}
2024-12-31 15:57:32 +08:00
}