feat(shared,server,web,client,plugin)!: 角色与权限重构 + 学期周次 + 课表方向反转(1.2.0)
学生、任课关系、周次口径三处长期靠约定维持的事情,改为由数据模型保证。 学生不是账号 - 拆出独立 Student 表,没有 passwordHash / role / 任何登录字段 - 「学生不能登录」由表结构保证,不再靠「登录前判 role 再 403」的代码分支 - 三张个人数据表外键 userId → studentId;删掉 Enrollment 与 ClassTeacher - 学生一律称「学号」、教师一律称「工号」,「学生账号」这个概念消失 任课关系唯一来源 = Course(班级 + 科目 + 教师) - 班主任 = Class.teacherId,科任 = Course.teacherId,同一人两处指向同一账号、不重复建号 - 作业与成绩按科目再收一道:挂科目只由该科任课老师改,没挂科目归班主任 / 管理员 - 新增「任课教师分配」与「班级教师批量导入」(带「使用工号匹配」开关) 成绩与名单 - 成绩等级:百分制 / 等级制 A·B·C·D / 自定义,支持单个与批量改等级 - 按学号查成绩明细(教师端 + 班级端 + 设备令牌),受按班开关控制 - 调班 / 转出(单个与批量)+ 可查历史;学号不变、历史作业成绩留原归属 - 毕业归档页(按年度记录毕业班级 / 毕业生 / 转出学生 / 该届通知与作业) - 学年升级(未毕业不归档、数据沿用);班级称呼改为「2026级1班」 ClassHelper 班级端在线状态 - Web 端显示 班级 / 设备名 / 设备号 / 在线离线 / 最后在线 / 最后心跳 - lastHeartbeatAt 驱动 60 秒在线窗口,与只表示「带状态上报」的 lastSeenAt 分开 学期周次 - 新增 TermWeek(classId 空串 = 全校默认),管理员可用日期范围选择器逐周配置 - 一键按开学日期生成整学期;联网拉取调休建议(只给建议、不改数据,无外网失败属正常) - 改周次后随课表下发给教室的 ClassHelper 班级端 课表方向反转 - 主方向改为「服务端 → 教室」自动下发;教室不再自动回传 - 取教室课表改为手动动作(点击前弹警告),插件按待办标记在下一次心跳补报 改名 - 班级小助手 → ClassHelper:界面、窗口标题、托盘、灵动岛、EXE、安装包、 安装目录、systemd 描述、插件清单与设置页、官网、文档站、README BREAKING CHANGE: 产品名与 EXE 名变更(班级小助手.exe → ClassHelper.exe), 安装目录随之改变,不支持覆盖安装,需先卸载旧版。 服务端首次启动会自动应用 6 个数据库迁移(学生行按 id 原样搬迁,历史数据不丢), 升级前请先备份。
This commit is contained in:
1 parent
17f55864bf
commit
9d5ac7adf9
172 files changed
+8761
-1896
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { Router } from 'express';
|
||||
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';
|
||||
@@ -7,41 +7,114 @@ import { defineModule } from '../module.types.js';
|
||||
import {
|
||||
createStudentSchema,
|
||||
listStudentsQuerySchema,
|
||||
listTransfersQuerySchema,
|
||||
transferOutStudentsSchema,
|
||||
transferStudentsSchema,
|
||||
updateStudentSchema,
|
||||
type CreateStudentInput,
|
||||
type ListStudentsQuery,
|
||||
type ListTransfersQuery,
|
||||
type TransferOutStudentsInput,
|
||||
type TransferStudentsInput,
|
||||
type UpdateStudentInput,
|
||||
} from './students.schemas.js';
|
||||
import * as studentService from './students.service.js';
|
||||
|
||||
const router = Router();
|
||||
router.use(authenticate());
|
||||
|
||||
/**
|
||||
* GET /api/students?classId=&keyword= - 学生名单
|
||||
* 学生名单。
|
||||
*
|
||||
* 注意是**仅管理员**(不是教师/管理员):学生名单自带用户名,而学生初始密码是统一的默认值,
|
||||
* 因此名单属于管理员专属数据;教师查看本班学生请用 `GET /api/classes/:id/students`
|
||||
* (那条按班级权限校验,班级设备也能读)。
|
||||
* - 学生**没有账号**:这里是"名单记录"的增删改,没有任何密码/角色字段;
|
||||
* - 读:教师/管理员按自己可访问的班级过滤(服务层 `resolveClassScope`);
|
||||
* 教室机器读本班名单请用 `GET /api/classes/:id/students`;
|
||||
* - 写:管理员或**本班班主任**(服务层逐班判权限),调班与转出仅管理员。
|
||||
*/
|
||||
router.get('/', requireRole('ADMIN'), 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), '获取学生列表成功');
|
||||
});
|
||||
router.get(
|
||||
'/',
|
||||
requireRole('ADMIN', 'TEACHER'),
|
||||
validate({ query: listStudentsQuerySchema }),
|
||||
async (req, res) => {
|
||||
const user = getAuthUser(req);
|
||||
const query = validatedQuery<ListStudentsQuery>(req);
|
||||
sendOk(res, await studentService.listStudents(user, query), '获取学生列表成功');
|
||||
},
|
||||
);
|
||||
|
||||
/** POST /api/students - 新建学生账号 */
|
||||
router.post('/', requireRole('ADMIN'), validate({ body: createStudentSchema }), async (req, res) => {
|
||||
const user = getAuthUser(req);
|
||||
sendCreated(
|
||||
res,
|
||||
await studentService.createStudent(user, req.body as CreateStudentInput),
|
||||
'学生账号创建成功',
|
||||
);
|
||||
});
|
||||
/** GET /api/students/transfers - 调班 / 转出历史(管理员看全部,也可按学生或班级过滤) */
|
||||
router.get(
|
||||
'/transfers',
|
||||
requireRole('ADMIN', 'TEACHER'),
|
||||
validate({ query: listTransfersQuerySchema }),
|
||||
async (req, res) => {
|
||||
const user = getAuthUser(req);
|
||||
const query = validatedQuery<ListTransfersQuery>(req);
|
||||
sendOk(res, await studentService.listTransfers(user, query), '获取调班历史成功');
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /api/students/transfer - 调班(单个与批量同一接口)
|
||||
*
|
||||
* 只改学生当前班级:**学号不变、不创建账号**,原班级/新班级/操作人/时间记入历史;
|
||||
* 历史作业与成绩保留原归属。
|
||||
*/
|
||||
router.post(
|
||||
'/transfer',
|
||||
requireRole('ADMIN'),
|
||||
validate({ body: transferStudentsSchema }),
|
||||
async (req, res) => {
|
||||
const user = getAuthUser(req);
|
||||
const result = await studentService.transferStudents(user, req.body as TransferStudentsInput);
|
||||
sendOk(res, result, `已调动 ${result.moved} 名学生`);
|
||||
},
|
||||
);
|
||||
|
||||
/** POST /api/students/transfer-out - 学生转出(学籍离开本校,不是调班) */
|
||||
router.post(
|
||||
'/transfer-out',
|
||||
requireRole('ADMIN'),
|
||||
validate({ body: transferOutStudentsSchema }),
|
||||
async (req, res) => {
|
||||
const user = getAuthUser(req);
|
||||
const result = await studentService.transferOutStudents(user, req.body as TransferOutStudentsInput);
|
||||
sendOk(res, result, `已办理 ${result.transferred} 名学生转出`);
|
||||
},
|
||||
);
|
||||
|
||||
/** GET /api/students/:id/transfers - 单个学生的调班 / 转出历史 */
|
||||
router.get(
|
||||
'/:id/transfers',
|
||||
requireRole('ADMIN', 'TEACHER'),
|
||||
validate({ params: idParamSchema }),
|
||||
async (req, res) => {
|
||||
const user = getAuthUser(req);
|
||||
const { id } = validatedParams<{ id: string }>(req);
|
||||
const result = await studentService.listTransfers(user, { studentId: id, pageSize: 200 });
|
||||
sendOk(res, result, '获取该生调班历史成功');
|
||||
},
|
||||
);
|
||||
|
||||
/** 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'),
|
||||
requireRole('ADMIN', 'TEACHER'),
|
||||
validate({ params: idParamSchema, body: updateStudentSchema }),
|
||||
async (req, res) => {
|
||||
const user = getAuthUser(req);
|
||||
@@ -54,13 +127,18 @@ router.patch(
|
||||
},
|
||||
);
|
||||
|
||||
/** DELETE /api/students - 删除学生名单记录 */
|
||||
router.delete('/:id', requireRole('ADMIN'), validate({ params: idParamSchema }), async (req, res) => {
|
||||
const user = getAuthUser(req);
|
||||
const { id } = validatedParams<{ id: string }>(req);
|
||||
await studentService.deleteStudent(user, id);
|
||||
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',
|
||||
|
||||
@@ -1,24 +1,80 @@
|
||||
import { z } from 'zod';
|
||||
import { keywordSchema } from '../../lib/schemas.js';
|
||||
import {
|
||||
enrollmentYearSchema,
|
||||
guardianPhoneSchema,
|
||||
keywordSchema,
|
||||
studentGenderSchema,
|
||||
studentNameSchema,
|
||||
studentNoSchema,
|
||||
studentStatusSchema,
|
||||
} from '../../lib/schemas.js';
|
||||
|
||||
export const listStudentsQuerySchema = z.object({
|
||||
classId: z.string().min(1).optional(),
|
||||
keyword: keywordSchema,
|
||||
/** 只看某个状态(默认不筛选;`active` = 只看在读) */
|
||||
status: studentStatusSchema,
|
||||
/** 是否包含已归档(毕业/转出)的学生,默认 false */
|
||||
includeArchived: z
|
||||
.union([z.boolean(), z.string()])
|
||||
.optional()
|
||||
.transform((value) => value === true || value === 'true' || value === '1'),
|
||||
});
|
||||
|
||||
// 学生只有"名单"没有"账号":不设密码、不能登录(2026-10-01 起学生个人账号已全部清理,
|
||||
// 学生端统一用班级码 + 班级密码),因此这里没有也不该有任何密码字段。
|
||||
// 学生只有「名单」没有「账号」:没有密码字段、没有角色字段,也不能登录。
|
||||
// 学号是学生的唯一标识与查询键,`studentNoSchema` 负责归一化与格式校验。
|
||||
export const createStudentSchema = z.object({
|
||||
username: z.string().trim().min(3, '用户名至少 3 位').max(32),
|
||||
name: z.string().trim().min(1, '请输入姓名').max(32),
|
||||
studentNo: studentNoSchema,
|
||||
name: studentNameSchema,
|
||||
classId: z.string().min(1).nullish(),
|
||||
gender: studentGenderSchema,
|
||||
guardianPhone: guardianPhoneSchema,
|
||||
status: studentStatusSchema,
|
||||
});
|
||||
|
||||
export const updateStudentSchema = z.object({
|
||||
username: z.string().trim().min(3).max(32).optional(),
|
||||
name: z.string().trim().min(1).max(32).optional(),
|
||||
studentNo: studentNoSchema.optional(),
|
||||
name: studentNameSchema.optional(),
|
||||
classId: z.string().min(1).nullish(),
|
||||
gender: studentGenderSchema,
|
||||
guardianPhone: guardianPhoneSchema,
|
||||
status: studentStatusSchema,
|
||||
});
|
||||
|
||||
/**
|
||||
* 调班:单个与批量共用。
|
||||
* 传一个 id 就是单个调班;`toClassId = null` 表示移出班级(回到「未分班」)。
|
||||
* **学号不变**,历史作业与成绩保留原归属。
|
||||
*/
|
||||
export const transferStudentsSchema = z.object({
|
||||
studentIds: z.array(z.string().min(1)).min(1, '请至少选择一名学生').max(500),
|
||||
toClassId: z.string().min(1).nullable(),
|
||||
note: z.string().trim().max(200).optional(),
|
||||
});
|
||||
|
||||
/** 转出(学籍离开本校,不是调班):班级归属保留作历史 */
|
||||
export const transferOutStudentsSchema = z.object({
|
||||
studentIds: z.array(z.string().min(1)).min(1, '请至少选择一名学生').max(500),
|
||||
note: z.string().trim().max(200).optional(),
|
||||
});
|
||||
|
||||
/** 调班历史查询 */
|
||||
export const listTransfersQuerySchema = z.object({
|
||||
studentId: z.string().min(1).optional(),
|
||||
classId: z.string().min(1).optional(),
|
||||
page: z.coerce.number().int().min(1).optional(),
|
||||
pageSize: z.coerce.number().int().min(1).max(200).optional(),
|
||||
});
|
||||
|
||||
/** 学生名单导入时的班级归属(按班级名解析,重名报错) */
|
||||
export const studentClassHintSchema = z.object({
|
||||
className: z.string().trim().max(64).optional(),
|
||||
enrollmentYear: enrollmentYearSchema.optional(),
|
||||
});
|
||||
|
||||
export type CreateStudentInput = z.infer<typeof createStudentSchema>;
|
||||
export type UpdateStudentInput = z.infer<typeof updateStudentSchema>;
|
||||
export type TransferStudentsInput = z.infer<typeof transferStudentsSchema>;
|
||||
export type TransferOutStudentsInput = z.infer<typeof transferOutStudentsSchema>;
|
||||
export type ListStudentsQuery = z.infer<typeof listStudentsQuerySchema>;
|
||||
export type ListTransfersQuery = z.infer<typeof listTransfersQuerySchema>;
|
||||
@@ -1,126 +1,349 @@
|
||||
import type { StudentDto } from '@classhelper/shared';
|
||||
import { assertCanManageRoster, classScopeWhere, isAdmin, resolveClassScope } from '../../lib/access.js';
|
||||
import type { PaginatedResult, StudentDto, StudentTransferDto } from '@classhelper/shared';
|
||||
import { normalizeStudentNo } from '@classhelper/shared';
|
||||
import {
|
||||
assertCanManageRoster,
|
||||
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 type { CreateStudentInput, UpdateStudentInput } from './students.schemas.js';
|
||||
import { toStudentDto, toStudentTransferDto } from '../../lib/mappers.js';
|
||||
import { SOCKET_EVENTS } from '@classhelper/shared';
|
||||
import { emitToClass } from '../../realtime/bus.js';
|
||||
import type {
|
||||
CreateStudentInput,
|
||||
ListStudentsQuery,
|
||||
ListTransfersQuery,
|
||||
TransferOutStudentsInput,
|
||||
TransferStudentsInput,
|
||||
UpdateStudentInput,
|
||||
} from './students.schemas.js';
|
||||
|
||||
export interface ListStudentOptions {
|
||||
classId?: string;
|
||||
keyword?: string;
|
||||
}
|
||||
/**
|
||||
* 学生是**班级名单里的记录**,不是账号:
|
||||
* 没有密码、不能登录、没有个人入口。`studentNo`(学号)是唯一标识与查询键。
|
||||
*
|
||||
* 本模块负责名单的增删改与**调班 / 转出**;学生的个人数据(作业完成、通知已读、成绩)
|
||||
* 挂在 `studentId` 上,因此调班只改 `Student.classId` ——
|
||||
* 历史作业与成绩保留原归属,后续数据按新班级生成。
|
||||
*/
|
||||
|
||||
const withClass = { class: { select: { name: true, grade: true } } } as const;
|
||||
|
||||
/** 学生名单(按班级权限过滤) */
|
||||
export async function listStudents(user: TokenPayload, options: ListStudentOptions): Promise<StudentDto[]> {
|
||||
export async function listStudents(
|
||||
user: TokenPayload,
|
||||
options: ListStudentsQuery,
|
||||
): Promise<StudentDto[]> {
|
||||
const scope = await resolveClassScope(user, options.classId);
|
||||
|
||||
const students = await prisma.user.findMany({
|
||||
const students = await prisma.student.findMany({
|
||||
where: {
|
||||
role: 'STUDENT',
|
||||
...classScopeWhere(scope),
|
||||
...(options.status ? { status: options.status } : {}),
|
||||
// 默认不显示已归档(毕业 / 转出)的学生:他们属于归档页,不该混在在读名单里
|
||||
...(options.includeArchived ? {} : { archivedYearId: null }),
|
||||
...(options.keyword
|
||||
? {
|
||||
OR: [{ name: { contains: options.keyword } }, { username: { contains: options.keyword } }],
|
||||
}
|
||||
? { OR: [{ name: { contains: options.keyword } }, { studentNo: { contains: options.keyword } }] }
|
||||
: {}),
|
||||
},
|
||||
include: { class: { select: { name: true, grade: true } } },
|
||||
orderBy: [{ classId: 'asc' }, { username: 'asc' }],
|
||||
take: 500,
|
||||
include: withClass,
|
||||
orderBy: [{ classId: 'asc' }, { studentNo: 'asc' }],
|
||||
take: 1000,
|
||||
});
|
||||
|
||||
return students.map(toStudentDto);
|
||||
}
|
||||
|
||||
/** 新建学生(名单实体,可选直接分班)。学生不设密码:登录一律走班级账号,见 createStudentSchema 的说明 */
|
||||
export async function createStudent(user: TokenPayload, input: CreateStudentInput): Promise<StudentDto> {
|
||||
if (input.classId) assertCanManageRoster(user);
|
||||
|
||||
const created = await prisma.user.create({
|
||||
data: {
|
||||
username: input.username,
|
||||
name: input.name,
|
||||
role: 'STUDENT',
|
||||
classId: input.classId ?? null,
|
||||
// User.passwordHash 是必填列,学生用空串占位(登录的 STUDENT 403 判定在密码校验之前,永远不会用到它)
|
||||
passwordHash: '',
|
||||
},
|
||||
/** 按学号取学生(学生没账号,因此没有"按 id 取自己"的入口) */
|
||||
export async function findStudentByNo(studentNo: string, classId?: string): Promise<StudentDto | null> {
|
||||
const record = await prisma.student.findFirst({
|
||||
where: { studentNo: normalizeStudentNo(studentNo), ...(classId ? { classId } : {}) },
|
||||
include: withClass,
|
||||
});
|
||||
|
||||
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);
|
||||
return record ? toStudentDto(record) : null;
|
||||
}
|
||||
|
||||
/** 修改学生信息 / 调班 */
|
||||
/** 新建学生(名单记录,可选直接分班)。学生不设密码、没有账号属性 */
|
||||
export async function createStudent(user: TokenPayload, input: CreateStudentInput): Promise<StudentDto> {
|
||||
await assertCanManageRoster(user, input.classId ?? undefined);
|
||||
await assertStudentNoFree(input.studentNo);
|
||||
if (input.classId) await assertClassExists(input.classId);
|
||||
|
||||
const created = await prisma.student.create({
|
||||
data: {
|
||||
studentNo: input.studentNo,
|
||||
name: input.name,
|
||||
classId: input.classId ?? null,
|
||||
gender: input.gender ?? '',
|
||||
guardianPhone: input.guardianPhone ?? '',
|
||||
status: input.status ?? 'active',
|
||||
},
|
||||
include: withClass,
|
||||
});
|
||||
|
||||
if (created.classId) {
|
||||
emitToClass(created.classId, SOCKET_EVENTS.classUpdated, {
|
||||
classId: created.classId,
|
||||
action: 'updated',
|
||||
});
|
||||
}
|
||||
return toStudentDto(created);
|
||||
}
|
||||
|
||||
/** 修改学生信息(含调班;走本接口的单个调班同样会记入调班历史) */
|
||||
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('学生不存在');
|
||||
const student = await prisma.student.findUnique({ where: { id: studentId } });
|
||||
if (!student) throw ApiError.notFound('学生不存在');
|
||||
|
||||
if (student.classId) {
|
||||
assertCanManageRoster(user);
|
||||
} else if (!isAdmin(user)) {
|
||||
throw ApiError.forbidden('该学生尚未分班,仅管理员可以直接修改');
|
||||
await assertCanManageRoster(user, student.classId ?? undefined);
|
||||
if (input.studentNo && input.studentNo !== student.studentNo) {
|
||||
await assertStudentNoFree(input.studentNo, studentId);
|
||||
}
|
||||
|
||||
const nextClassId = input.classId === undefined ? student.classId : (input.classId ?? null);
|
||||
if (nextClassId && nextClassId !== student.classId) {
|
||||
assertCanManageRoster(user);
|
||||
}
|
||||
const classChanged = nextClassId !== student.classId;
|
||||
if (classChanged) await assertCanManageRoster(user, nextClassId ?? undefined);
|
||||
|
||||
const updated = await prisma.user.update({
|
||||
const updated = await prisma.student.update({
|
||||
where: { id: studentId },
|
||||
data: {
|
||||
...(input.studentNo ? { studentNo: input.studentNo } : {}),
|
||||
...(input.name ? { name: input.name } : {}),
|
||||
...(input.username ? { username: input.username } : {}),
|
||||
...(input.gender !== undefined ? { gender: input.gender } : {}),
|
||||
...(input.guardianPhone !== undefined ? { guardianPhone: input.guardianPhone } : {}),
|
||||
...(input.status !== undefined ? { status: input.status } : {}),
|
||||
classId: nextClassId,
|
||||
},
|
||||
include: withClass,
|
||||
});
|
||||
|
||||
// 同步 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 } });
|
||||
// 换班要留痕(单个调班与批量调班都写同一种历史)
|
||||
if (classChanged) {
|
||||
await recordTransfer(user, [updated], student.classId, nextClassId, 'single', '');
|
||||
}
|
||||
|
||||
const result = await prisma.user.findUniqueOrThrow({
|
||||
where: { id: updated.id },
|
||||
include: { class: { select: { name: true, grade: true } } },
|
||||
});
|
||||
return toStudentDto(result);
|
||||
return toStudentDto(updated);
|
||||
}
|
||||
|
||||
/** 删除学生账号(级联删除其作业状态、成绩、已读记录) */
|
||||
/** 删除学生记录(级联删除其作业状态、成绩、已读记录与调班历史) */
|
||||
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('学生不存在');
|
||||
const student = await prisma.student.findUnique({ where: { id: studentId } });
|
||||
if (!student) throw ApiError.notFound('学生不存在');
|
||||
await assertCanManageRoster(user, student.classId ?? undefined);
|
||||
|
||||
if (student.classId) {
|
||||
assertCanManageRoster(user);
|
||||
} else if (!isAdmin(user)) {
|
||||
throw ApiError.forbidden('该学生尚未分班,仅管理员可以删除');
|
||||
await prisma.student.delete({ where: { id: studentId } });
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 调班 / 转出 */
|
||||
|
||||
/**
|
||||
* 调班:单个与批量共用(传一个 id 就是单个)。
|
||||
*
|
||||
* 规则(需求「管理员调班」):
|
||||
* - 只改学生**当前班级**,学号不变、不创建任何账号;
|
||||
* - 原班级、新班级、操作人、时间写入 `StudentClassTransfer`,历史可查;
|
||||
* - 历史作业与成绩保留原归属(它们挂在各自的 `classId` 上,不随学生走)。
|
||||
*/
|
||||
export async function transferStudents(
|
||||
user: TokenPayload,
|
||||
input: TransferStudentsInput,
|
||||
): Promise<{ moved: number; transfers: StudentTransferDto[] }> {
|
||||
if (!isAdmin(user)) throw ApiError.forbidden('只有管理员可以调班');
|
||||
|
||||
const students = await prisma.student.findMany({ where: { id: { in: input.studentIds } } });
|
||||
if (students.length !== input.studentIds.length) {
|
||||
throw ApiError.badRequest('部分学生不存在,请刷新后重试');
|
||||
}
|
||||
if (input.toClassId) await assertClassExists(input.toClassId);
|
||||
|
||||
const movable = students.filter((item) => item.classId !== input.toClassId);
|
||||
if (movable.length === 0) {
|
||||
throw ApiError.badRequest('所选学生已经全部在这个班级里');
|
||||
}
|
||||
|
||||
await prisma.user.delete({ where: { id: studentId } });
|
||||
await prisma.$transaction(
|
||||
movable.map((item) =>
|
||||
prisma.student.update({ where: { id: item.id }, data: { classId: input.toClassId } }),
|
||||
),
|
||||
);
|
||||
|
||||
const mode = movable.length > 1 ? 'batch' : 'single';
|
||||
// 注意传的是**调班前**的 movable(classId 还是原班级):历史里的"原班级"要按每条自己的来
|
||||
const transfers = await recordTransfer(user, movable, null, input.toClassId, mode, input.note ?? '');
|
||||
|
||||
notifyClassChange(movable.map((item) => item.classId), input.toClassId);
|
||||
return { moved: movable.length, transfers };
|
||||
}
|
||||
|
||||
/**
|
||||
* 学生转出:学籍离开本校(**不是调班**)。
|
||||
*
|
||||
* 班级归属保留作历史(成绩/作业/已读都还在),状态置为 `transferred`,
|
||||
* 并写一条 `mode = 'transfer-out'` 的历史,归档页据此统计"当年转出的学生"。
|
||||
*/
|
||||
export async function transferOutStudents(
|
||||
user: TokenPayload,
|
||||
input: TransferOutStudentsInput,
|
||||
): Promise<{ transferred: number; transfers: StudentTransferDto[] }> {
|
||||
if (!isAdmin(user)) throw ApiError.forbidden('只有管理员可以办理学生转出');
|
||||
|
||||
const students = await prisma.student.findMany({ where: { id: { in: input.studentIds } } });
|
||||
if (students.length !== input.studentIds.length) {
|
||||
throw ApiError.badRequest('部分学生不存在,请刷新后重试');
|
||||
}
|
||||
const pending = students.filter((item) => item.status !== 'transferred');
|
||||
if (pending.length === 0) throw ApiError.badRequest('所选学生都已经转出');
|
||||
|
||||
const now = new Date();
|
||||
await prisma.$transaction(
|
||||
pending.map((item) =>
|
||||
prisma.student.update({
|
||||
where: { id: item.id },
|
||||
data: { status: 'transferred', transferredAt: now, transferNote: input.note ?? '' },
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// 班级名快照:转出时把学生"离开的那个班"记下来,之后班级改名也不影响历史
|
||||
const classNames = await loadClassNames(pending.map((item) => item.classId));
|
||||
await prisma.studentClassTransfer.createMany({
|
||||
data: pending.map((item) => ({
|
||||
studentId: item.id,
|
||||
studentNo: item.studentNo,
|
||||
studentName: item.name,
|
||||
fromClassId: item.classId,
|
||||
fromClassName: item.classId ? (classNames.get(item.classId) ?? '') : '',
|
||||
toClassId: null,
|
||||
toClassName: '转出本校',
|
||||
operatorId: user.sub,
|
||||
operatorName: user.name,
|
||||
mode: 'transfer-out',
|
||||
note: input.note ?? '',
|
||||
})),
|
||||
});
|
||||
|
||||
notifyClassChange(pending.map((item) => item.classId), null);
|
||||
|
||||
const created = await prisma.studentClassTransfer.findMany({
|
||||
where: { studentId: { in: pending.map((item) => item.id) }, mode: 'transfer-out' },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: pending.length,
|
||||
});
|
||||
return { transferred: pending.length, transfers: created.map(toStudentTransferDto) };
|
||||
}
|
||||
|
||||
/** 调班 / 转出历史(单个学生或某个班级,管理员看全部) */
|
||||
export async function listTransfers(
|
||||
user: TokenPayload,
|
||||
options: ListTransfersQuery,
|
||||
): Promise<PaginatedResult<StudentTransferDto>> {
|
||||
if (!isAdmin(user) && !options.classId && !options.studentId) {
|
||||
throw ApiError.forbidden('查看全部调班历史需要管理员权限');
|
||||
}
|
||||
|
||||
const where = {
|
||||
...(options.studentId ? { studentId: options.studentId } : {}),
|
||||
...(options.classId
|
||||
? { OR: [{ fromClassId: options.classId }, { toClassId: options.classId }] }
|
||||
: {}),
|
||||
};
|
||||
|
||||
const page = options.page ?? 1;
|
||||
const pageSize = options.pageSize ?? 50;
|
||||
const [items, total] = await Promise.all([
|
||||
prisma.studentClassTransfer.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
prisma.studentClassTransfer.count({ where }),
|
||||
]);
|
||||
|
||||
return { items: items.map(toStudentTransferDto), total, page, pageSize };
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 内部工具 */
|
||||
|
||||
/**
|
||||
* 写入调班历史。
|
||||
*
|
||||
* - `fromOverride` 非空时,所有条目都用它作为"原班级"(单个调班场景);
|
||||
* - 为空时逐条取**该学生自己的 classId** 作为"原班级"(批量调班场景,
|
||||
* 各人的来源班可能不同)。
|
||||
*/
|
||||
async function recordTransfer(
|
||||
user: TokenPayload,
|
||||
students: { id: string; studentNo: string; name: string; classId: string | null }[],
|
||||
fromOverride: string | null,
|
||||
toClassId: string | null,
|
||||
mode: 'single' | 'batch',
|
||||
note: string,
|
||||
): Promise<StudentTransferDto[]> {
|
||||
const fromIds = students.map((item) => fromOverride ?? item.classId);
|
||||
const classNames = await loadClassNames([...fromIds, toClassId]);
|
||||
|
||||
await prisma.studentClassTransfer.createMany({
|
||||
data: students.map((item, index) => {
|
||||
const fromClassId = fromIds[index] ?? null;
|
||||
return {
|
||||
studentId: item.id,
|
||||
studentNo: item.studentNo,
|
||||
studentName: item.name,
|
||||
fromClassId,
|
||||
fromClassName: fromClassId ? (classNames.get(fromClassId) ?? '') : '',
|
||||
toClassId,
|
||||
toClassName: toClassId ? (classNames.get(toClassId) ?? '') : '未分班',
|
||||
operatorId: user.sub,
|
||||
operatorName: user.name,
|
||||
mode,
|
||||
note,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
const created = await prisma.studentClassTransfer.findMany({
|
||||
where: { studentId: { in: students.map((item) => item.id) } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: students.length,
|
||||
});
|
||||
return created.map(toStudentTransferDto);
|
||||
}
|
||||
|
||||
async function loadClassNames(classIds: (string | null)[]): Promise<Map<string, string>> {
|
||||
const ids = [...new Set(classIds.filter((id): id is string => Boolean(id)))];
|
||||
if (ids.length === 0) return new Map();
|
||||
const classes = await prisma.class.findMany({ where: { id: { in: ids } }, select: { id: true, name: true } });
|
||||
return new Map(classes.map((item) => [item.id, item.name]));
|
||||
}
|
||||
|
||||
/** 调班后让相关班级的前端刷新名单(旧班与新班都要收到) */
|
||||
function notifyClassChange(fromClassIds: (string | null)[], toClassId: string | null): void {
|
||||
const targets = new Set([...fromClassIds, toClassId].filter((id): id is string => Boolean(id)));
|
||||
for (const classId of targets) {
|
||||
emitToClass(classId, SOCKET_EVENTS.classUpdated, { classId, action: 'updated' });
|
||||
}
|
||||
}
|
||||
|
||||
async function assertClassExists(classId: string): Promise<void> {
|
||||
const record = await prisma.class.findUnique({ where: { id: classId }, select: { id: true } });
|
||||
if (!record) throw ApiError.badRequest('班级不存在');
|
||||
}
|
||||
|
||||
/** 学号唯一:`Student.studentNo` 上已有唯一约束,这里给出一句人话的 409 */
|
||||
async function assertStudentNoFree(studentNo: string, exceptId?: string): Promise<void> {
|
||||
const existing = await prisma.student.findUnique({
|
||||
where: { studentNo },
|
||||
select: { id: true, name: true, classId: true },
|
||||
});
|
||||
if (existing && existing.id !== exceptId) {
|
||||
throw ApiError.conflict(`学号 ${studentNo} 已被学生「${existing.name}」占用`);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user