feat(core-edu): 完整实现 core-edu 教学核心服务
包含 classes/exams/homework/grades/attendance/scheduling 域、outbox、iam-consumer、redis 配置等完整实现
This commit is contained in:
20
services/core-edu/src/attendance/attendance-status.ts
Normal file
20
services/core-edu/src/attendance/attendance-status.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* 考勤状态枚举(纯常量,用于校验)
|
||||
*
|
||||
* 状态值(ISSUE-003 仲裁 scheme A):
|
||||
* present / absent / late / leave
|
||||
*/
|
||||
export const ATTENDANCE_STATUSES = [
|
||||
"present",
|
||||
"absent",
|
||||
"late",
|
||||
"leave",
|
||||
] as const;
|
||||
|
||||
export type AttendanceStatus = (typeof ATTENDANCE_STATUSES)[number];
|
||||
|
||||
export function isValidAttendanceStatus(
|
||||
status: string,
|
||||
): status is AttendanceStatus {
|
||||
return (ATTENDANCE_STATUSES as readonly string[]).includes(status);
|
||||
}
|
||||
83
services/core-edu/src/attendance/attendance.controller.ts
Normal file
83
services/core-edu/src/attendance/attendance.controller.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { Body, Controller, Get, Param, Post, Req } from "@nestjs/common";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AttendanceService,
|
||||
type RecordAttendanceInput,
|
||||
} from "./attendance.service.js";
|
||||
import {
|
||||
Permissions,
|
||||
RequirePermission,
|
||||
} from "../middleware/permission.guard.js";
|
||||
import type { AuthenticatedRequest } from "../middleware/auth.middleware.js";
|
||||
import {
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
} from "../shared/errors/application-error.js";
|
||||
|
||||
const recordAttendanceSchema = z.object({
|
||||
scheduleId: z.string().min(1),
|
||||
studentId: z.string().min(1),
|
||||
status: z.enum(["present", "absent", "late", "leave"]),
|
||||
remark: z.string().optional(),
|
||||
schoolId: z.string().min(1),
|
||||
});
|
||||
|
||||
@Controller("v1/attendance")
|
||||
export class AttendanceController {
|
||||
constructor(private readonly attendanceService: AttendanceService) {}
|
||||
|
||||
@Post()
|
||||
@RequirePermission(Permissions.ATTENDANCE_CREATE)
|
||||
async record(
|
||||
@Body() body: unknown,
|
||||
@Req() req: AuthenticatedRequest,
|
||||
): Promise<{ success: true; data: { id: string } }> {
|
||||
const userId = req.userId;
|
||||
if (!userId) {
|
||||
throw new UnauthorizedError("Missing x-user-id header");
|
||||
}
|
||||
const parsed = recordAttendanceSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
throw new ValidationError(
|
||||
"Invalid attendance input",
|
||||
parsed.error.flatten(),
|
||||
);
|
||||
}
|
||||
const input: RecordAttendanceInput = {
|
||||
...parsed.data,
|
||||
recordedBy: userId,
|
||||
};
|
||||
const result = await this.attendanceService.recordAttendance(input, userId);
|
||||
return { success: true, data: result };
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@RequirePermission(Permissions.ATTENDANCE_READ)
|
||||
async findOne(@Param("id") id: string): Promise<{
|
||||
success: true;
|
||||
data: Awaited<ReturnType<AttendanceService["getAttendance"]>>;
|
||||
}> {
|
||||
const data = await this.attendanceService.getAttendance(id);
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Get("student/:studentId")
|
||||
@RequirePermission(Permissions.ATTENDANCE_READ)
|
||||
async listByStudent(@Param("studentId") studentId: string): Promise<{
|
||||
success: true;
|
||||
data: Awaited<ReturnType<AttendanceService["listByStudent"]>>;
|
||||
}> {
|
||||
const data = await this.attendanceService.listByStudent(studentId);
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Get("class/:classId")
|
||||
@RequirePermission(Permissions.ATTENDANCE_READ)
|
||||
async listByClass(@Param("classId") classId: string): Promise<{
|
||||
success: true;
|
||||
data: Awaited<ReturnType<AttendanceService["listByClass"]>>;
|
||||
}> {
|
||||
const data = await this.attendanceService.listByClass(classId);
|
||||
return { success: true, data };
|
||||
}
|
||||
}
|
||||
10
services/core-edu/src/attendance/attendance.module.ts
Normal file
10
services/core-edu/src/attendance/attendance.module.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { AttendanceController } from "./attendance.controller.js";
|
||||
import { AttendanceService } from "./attendance.service.js";
|
||||
|
||||
@Module({
|
||||
controllers: [AttendanceController],
|
||||
providers: [AttendanceService],
|
||||
exports: [AttendanceService],
|
||||
})
|
||||
export class AttendanceModule {}
|
||||
74
services/core-edu/src/attendance/attendance.repository.ts
Normal file
74
services/core-edu/src/attendance/attendance.repository.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import { eq, and, inArray } from "drizzle-orm";
|
||||
import { db } from "../config/database.js";
|
||||
import {
|
||||
attendance,
|
||||
type Attendance,
|
||||
type NewAttendance,
|
||||
} from "./attendance.schema.js";
|
||||
import { schedules } from "../scheduling/scheduling.schema.js";
|
||||
|
||||
export class AttendanceRepository {
|
||||
async findById(id: string): Promise<Attendance | undefined> {
|
||||
const [result] = await db
|
||||
.select()
|
||||
.from(attendance)
|
||||
.where(eq(attendance.id, id))
|
||||
.limit(1);
|
||||
return result;
|
||||
}
|
||||
|
||||
async findByScheduleAndStudent(
|
||||
scheduleId: string,
|
||||
studentId: string,
|
||||
): Promise<Attendance | undefined> {
|
||||
const [result] = await db
|
||||
.select()
|
||||
.from(attendance)
|
||||
.where(
|
||||
and(
|
||||
eq(attendance.scheduleId, scheduleId),
|
||||
eq(attendance.studentId, studentId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return result;
|
||||
}
|
||||
|
||||
async findByStudentId(studentId: string): Promise<Attendance[]> {
|
||||
return db
|
||||
.select()
|
||||
.from(attendance)
|
||||
.where(eq(attendance.studentId, studentId));
|
||||
}
|
||||
|
||||
async findByScheduleId(scheduleId: string): Promise<Attendance[]> {
|
||||
return db
|
||||
.select()
|
||||
.from(attendance)
|
||||
.where(eq(attendance.scheduleId, scheduleId));
|
||||
}
|
||||
|
||||
async findByClassId(classId: string): Promise<Attendance[]> {
|
||||
// Two-step query: find schedule IDs for class, then attendance by those IDs
|
||||
const classSchedules = await db
|
||||
.select({ id: schedules.id })
|
||||
.from(schedules)
|
||||
.where(eq(schedules.classId, classId));
|
||||
const scheduleIds = classSchedules.map((s) => s.id);
|
||||
if (scheduleIds.length === 0) return [];
|
||||
return db
|
||||
.select()
|
||||
.from(attendance)
|
||||
.where(inArray(attendance.scheduleId, scheduleIds));
|
||||
}
|
||||
|
||||
async create(record: NewAttendance, tx: typeof db = db): Promise<void> {
|
||||
await tx.insert(attendance).values(record);
|
||||
}
|
||||
|
||||
async update(id: string, data: Partial<NewAttendance>): Promise<void> {
|
||||
await db.update(attendance).set(data).where(eq(attendance.id, id));
|
||||
}
|
||||
}
|
||||
|
||||
export const attendanceRepository = new AttendanceRepository();
|
||||
40
services/core-edu/src/attendance/attendance.schema.ts
Normal file
40
services/core-edu/src/attendance/attendance.schema.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import {
|
||||
mysqlTable,
|
||||
varchar,
|
||||
text,
|
||||
timestamp,
|
||||
char,
|
||||
index,
|
||||
uniqueIndex,
|
||||
} from "drizzle-orm/mysql-core";
|
||||
|
||||
// 考勤记录表
|
||||
export const attendance = mysqlTable(
|
||||
"core_edu_attendance",
|
||||
{
|
||||
id: char("id", { length: 36 }).notNull().primaryKey(),
|
||||
scheduleId: char("schedule_id", { length: 36 }).notNull(),
|
||||
studentId: char("student_id", { length: 36 }).notNull(),
|
||||
status: varchar("status", { length: 20 }).notNull(), // present | absent | late | leave
|
||||
remark: text("remark"),
|
||||
recordedBy: char("recorded_by", { length: 36 }).notNull(),
|
||||
schoolId: char("school_id", { length: 36 }).notNull(),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
|
||||
},
|
||||
(table) => ({
|
||||
uniqSchedStudent: uniqueIndex("uniq_sched_student").on(
|
||||
table.scheduleId,
|
||||
table.studentId,
|
||||
),
|
||||
idxAttendanceStudentId: index("idx_attendance_student_id").on(
|
||||
table.studentId,
|
||||
),
|
||||
idxAttendanceScheduleId: index("idx_attendance_schedule_id").on(
|
||||
table.scheduleId,
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
export type Attendance = typeof attendance.$inferSelect;
|
||||
export type NewAttendance = typeof attendance.$inferInsert;
|
||||
116
services/core-edu/src/attendance/attendance.service.ts
Normal file
116
services/core-edu/src/attendance/attendance.service.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { db } from "../config/database.js";
|
||||
import { attendanceRepository } from "./attendance.repository.js";
|
||||
import { outboxRepository } from "../shared/outbox/outbox.repository.js";
|
||||
import { buildEvent, serializeEvent } from "../shared/outbox/event-builder.js";
|
||||
import { isValidAttendanceStatus } from "./attendance-status.js";
|
||||
import {
|
||||
NotFoundError,
|
||||
ValidationError,
|
||||
ConflictError,
|
||||
} from "../shared/errors/application-error.js";
|
||||
import type { Attendance } from "./attendance.schema.js";
|
||||
|
||||
export interface RecordAttendanceInput {
|
||||
scheduleId: string;
|
||||
studentId: string;
|
||||
status: string;
|
||||
remark?: string;
|
||||
recordedBy: string;
|
||||
schoolId: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AttendanceService {
|
||||
async recordAttendance(
|
||||
input: RecordAttendanceInput,
|
||||
userId?: string,
|
||||
): Promise<{ id: string }> {
|
||||
if (
|
||||
!input.scheduleId ||
|
||||
!input.studentId ||
|
||||
!input.recordedBy ||
|
||||
!input.schoolId
|
||||
) {
|
||||
throw new ValidationError(
|
||||
"scheduleId, studentId, recordedBy, schoolId are required",
|
||||
);
|
||||
}
|
||||
if (!isValidAttendanceStatus(input.status)) {
|
||||
throw new ValidationError(
|
||||
`Invalid attendance status: ${input.status}. Must be one of: present, absent, late, leave`,
|
||||
);
|
||||
}
|
||||
|
||||
// Idempotency: check existing record
|
||||
const existing = await attendanceRepository.findByScheduleAndStudent(
|
||||
input.scheduleId,
|
||||
input.studentId,
|
||||
);
|
||||
if (existing) {
|
||||
throw new ConflictError(
|
||||
`Attendance already recorded for student ${input.studentId} in schedule ${input.scheduleId}`,
|
||||
);
|
||||
}
|
||||
|
||||
const id = randomUUID();
|
||||
const event = buildEvent({
|
||||
aggregateId: id,
|
||||
eventType: "attendance.recorded",
|
||||
payload: {
|
||||
attendanceId: id,
|
||||
scheduleId: input.scheduleId,
|
||||
studentId: input.studentId,
|
||||
status: input.status,
|
||||
},
|
||||
userId,
|
||||
});
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
await attendanceRepository.create(
|
||||
{
|
||||
id,
|
||||
scheduleId: input.scheduleId,
|
||||
studentId: input.studentId,
|
||||
status: input.status,
|
||||
remark: input.remark,
|
||||
recordedBy: input.recordedBy,
|
||||
schoolId: input.schoolId,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
await outboxRepository.create(
|
||||
{
|
||||
id: randomUUID(),
|
||||
eventId: event.event_id,
|
||||
aggregateId: id,
|
||||
aggregateType: "attendance",
|
||||
eventType: "attendance.recorded",
|
||||
occurredAt: new Date(event.occurred_at),
|
||||
payload: serializeEvent(event),
|
||||
status: "pending",
|
||||
},
|
||||
tx,
|
||||
);
|
||||
});
|
||||
|
||||
return { id };
|
||||
}
|
||||
|
||||
async getAttendance(id: string): Promise<Attendance> {
|
||||
const record = await attendanceRepository.findById(id);
|
||||
if (!record) {
|
||||
throw new NotFoundError(`Attendance ${id} not found`);
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
async listByStudent(studentId: string): Promise<Attendance[]> {
|
||||
return attendanceRepository.findByStudentId(studentId);
|
||||
}
|
||||
|
||||
async listByClass(classId: string): Promise<Attendance[]> {
|
||||
return attendanceRepository.findByClassId(classId);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user