feat: 班级小助手 阶段1-3(monorepo + 后端 REST/Socket.IO + Web 管理端)

This commit is contained in:
LoveChengke committed 2026-09-11 21:57:38 +08:00
commit 84ab49de10
102 files changed
+14751

No files matched your search

@@ -0,0 +1,94 @@
import { Router } from 'express';
import { sendCreated, sendOk } from '../../lib/http.js';
import { idParamSchema } from '../../lib/schemas.js';
import { authenticate, getAuthUser, requireRole } from '../../middleware/auth.js';
import { validate, validatedParams, validatedQuery } from '../../middleware/validate.js';
import { defineModule } from '../module.types.js';
import {
createStudentSchema,
listStudentsQuerySchema,
resetPasswordSchema,
updateStudentSchema,
type CreateStudentInput,
type ResetPasswordInput,
type UpdateStudentInput,
} from './students.schemas.js';
import * as studentService from './students.service.js';
const router = Router();
router.use(authenticate());
/** GET /api/students?classId=&keyword= - 学生名单(教师/管理员) */
router.get(
'/',
requireRole('ADMIN', 'TEACHER'),
validate({ query: listStudentsQuerySchema }),
async (req, res) => {
const user = getAuthUser(req);
const query = validatedQuery<{ classId?: string; keyword?: string }>(req);
sendOk(res, await studentService.listStudents(user, query), '获取学生列表成功');
},
);
/** POST /api/students - 新建学生账号 */
router.post(
'/',
requireRole('ADMIN', 'TEACHER'),
validate({ body: createStudentSchema }),
async (req, res) => {
const user = getAuthUser(req);
sendCreated(
res,
await studentService.createStudent(user, req.body as CreateStudentInput),
'学生账号创建成功',
);
},
);
/** PATCH /api/students/:id - 修改学生信息 / 调班 */
router.patch(
'/:id',
requireRole('ADMIN', 'TEACHER'),
validate({ params: idParamSchema, body: updateStudentSchema }),
async (req, res) => {
const user = getAuthUser(req);
const { id } = validatedParams<{ id: string }>(req);
sendOk(
res,
await studentService.updateStudent(user, id, req.body as UpdateStudentInput),
'学生信息更新成功',
);
},
);
/** POST /api/students/:id/reset-password - 重置密码 */
router.post(
'/:id/reset-password',
requireRole('ADMIN', 'TEACHER'),
validate({ params: idParamSchema, body: resetPasswordSchema }),
async (req, res) => {
const user = getAuthUser(req);
const { id } = validatedParams<{ id: string }>(req);
await studentService.resetPassword(user, id, req.body as ResetPasswordInput);
sendOk(res, { id }, '密码已重置');
},
);
/** DELETE /api/students/:id - 删除学生账号 */
router.delete(
'/:id',
requireRole('ADMIN', 'TEACHER'),
validate({ params: idParamSchema }),
async (req, res) => {
const user = getAuthUser(req);
const { id } = validatedParams<{ id: string }>(req);
await studentService.deleteStudent(user, id);
sendOk(res, { id }, '学生账号已删除');
},
);
export const studentsModule = defineModule({
name: 'students',
basePath: '/students',
router,
});
@@ -0,0 +1,28 @@
import { z } from 'zod';
import { keywordSchema } from '../../lib/schemas.js';
export const listStudentsQuerySchema = z.object({
classId: z.string().min(1).optional(),
keyword: keywordSchema,
});
export const createStudentSchema = z.object({
username: z.string().trim().min(3, '用户名至少 3 位').max(32),
name: z.string().trim().min(1, '请输入姓名').max(32),
password: z.string().min(6, '密码至少 6 位').max(128).optional(),
classId: z.string().min(1).nullish(),
});
export const updateStudentSchema = z.object({
username: z.string().trim().min(3).max(32).optional(),
name: z.string().trim().min(1).max(32).optional(),
classId: z.string().min(1).nullish(),
});
export const resetPasswordSchema = z.object({
newPassword: z.string().min(6, '新密码至少 6 位').max(128).optional(),
});
export type CreateStudentInput = z.infer<typeof createStudentSchema>;
export type UpdateStudentInput = z.infer<typeof updateStudentSchema>;
export type ResetPasswordInput = z.infer<typeof resetPasswordSchema>;
@@ -0,0 +1,149 @@
import type { StudentDto } from '@classhelper/shared';
import { env } from '../../config/env.js';
import { assertClassWritable, classScopeWhere, isAdmin, resolveClassScope } from '../../lib/access.js';
import { prisma } from '../../lib/db.js';
import { ApiError } from '../../lib/http.js';
import type { TokenPayload } from '../../lib/jwt.js';
import { toStudentDto } from '../../lib/mappers.js';
import { hashPassword } from '../../lib/password.js';
import type { CreateStudentInput, ResetPasswordInput, UpdateStudentInput } from './students.schemas.js';
export interface ListStudentOptions {
classId?: string;
keyword?: string;
}
/** 学生名单(按班级权限过滤) */
export async function listStudents(user: TokenPayload, options: ListStudentOptions): Promise<StudentDto[]> {
const scope = await resolveClassScope(user, options.classId);
const students = await prisma.user.findMany({
where: {
role: 'STUDENT',
...classScopeWhere(scope),
...(options.keyword
? {
OR: [{ name: { contains: options.keyword } }, { username: { contains: options.keyword } }],
}
: {}),
},
include: { class: { select: { name: true, grade: true } } },
orderBy: [{ classId: 'asc' }, { username: 'asc' }],
take: 500,
});
return students.map(toStudentDto);
}
/** 新建学生账号(可选直接分班) */
export async function createStudent(user: TokenPayload, input: CreateStudentInput): Promise<StudentDto> {
if (input.classId) await assertClassWritable(user, input.classId);
const passwordHash = await hashPassword(input.password ?? env.defaultStudentPassword);
const created = await prisma.user.create({
data: {
username: input.username,
name: input.name,
role: 'STUDENT',
classId: input.classId ?? null,
passwordHash,
},
});
if (input.classId) {
await prisma.enrollment.upsert({
where: { userId_classId: { userId: created.id, classId: input.classId } },
create: { userId: created.id, classId: input.classId },
update: {},
});
}
const student = await prisma.user.findUniqueOrThrow({
where: { id: created.id },
include: { class: { select: { name: true, grade: true } } },
});
return toStudentDto(student);
}
/** 修改学生信息 / 调班 */
export async function updateStudent(
user: TokenPayload,
studentId: string,
input: UpdateStudentInput,
): Promise<StudentDto> {
const student = await prisma.user.findUnique({ where: { id: studentId } });
if (!student || student.role !== 'STUDENT') throw ApiError.notFound('学生不存在');
if (student.classId) {
await assertClassWritable(user, student.classId);
} else if (!isAdmin(user)) {
throw ApiError.forbidden('该学生尚未分班,仅管理员可以直接修改');
}
const nextClassId = input.classId === undefined ? student.classId : (input.classId ?? null);
if (nextClassId && nextClassId !== student.classId) {
await assertClassWritable(user, nextClassId);
}
const updated = await prisma.user.update({
where: { id: studentId },
data: {
...(input.name ? { name: input.name } : {}),
...(input.username ? { username: input.username } : {}),
classId: nextClassId,
},
});
// 同步 Enrollment:换班时清理旧记录
if (nextClassId) {
await prisma.enrollment.deleteMany({ where: { userId: studentId, classId: { not: nextClassId } } });
await prisma.enrollment.upsert({
where: { userId_classId: { userId: studentId, classId: nextClassId } },
create: { userId: studentId, classId: nextClassId },
update: {},
});
} else {
await prisma.enrollment.deleteMany({ where: { userId: studentId } });
}
const result = await prisma.user.findUniqueOrThrow({
where: { id: updated.id },
include: { class: { select: { name: true, grade: true } } },
});
return toStudentDto(result);
}
/** 删除学生账号(级联删除其作业状态、成绩、已读记录) */
export async function deleteStudent(user: TokenPayload, studentId: string): Promise<void> {
const student = await prisma.user.findUnique({ where: { id: studentId } });
if (!student || student.role !== 'STUDENT') throw ApiError.notFound('学生不存在');
if (student.classId) {
await assertClassWritable(user, student.classId);
} else if (!isAdmin(user)) {
throw ApiError.forbidden('该学生尚未分班,仅管理员可以删除');
}
await prisma.user.delete({ where: { id: studentId } });
}
/** 重置学生密码(未指定时使用默认初始密码) */
export async function resetPassword(
user: TokenPayload,
studentId: string,
input: ResetPasswordInput,
): Promise<void> {
const student = await prisma.user.findUnique({ where: { id: studentId } });
if (!student || student.role !== 'STUDENT') throw ApiError.notFound('学生不存在');
if (student.classId) {
await assertClassWritable(user, student.classId);
} else if (!isAdmin(user)) {
throw ApiError.forbidden('该学生尚未分班,仅管理员可以重置密码');
}
await prisma.user.update({
where: { id: studentId },
data: { passwordHash: await hashPassword(input.newPassword ?? env.defaultStudentPassword) },
});
}