feat(server): 统一课表解析并完善权限范围与年度升级
This commit is contained in:
1 parent
66ef878a71
commit
4dc824c283
54 files changed
+2401
-625
No files matched your search
@@ -0,0 +1,241 @@
|
||||
import { importProfile } from './profile-import.service.js';
|
||||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { prisma } from '../../lib/db.js';
|
||||
import { assertCanManageSchedule, assertClassAccess } from '../../lib/access.js';
|
||||
import { sendOk, sendCreated, ApiError } from '../../lib/http.js';
|
||||
import { idParamSchema } from '../../lib/schemas.js';
|
||||
import { authenticate, getAuthUser, requirePermission } from '../../middleware/auth.js';
|
||||
import { validate, validatedQuery } from '../../middleware/validate.js';
|
||||
import { defineModule } from '../module.types.js';
|
||||
import * as schemas from './class-plans.schemas.js';
|
||||
import * as service from './class-plans.service.js';
|
||||
|
||||
const layouts = Router();
|
||||
layouts.use(authenticate());
|
||||
layouts.get('/', validate({ query: schemas.scopeQuery }), async (req, res) =>
|
||||
sendOk(res, await service.listLayouts(getAuthUser(req), validatedQuery<{ classId?: string }>(req).classId)),
|
||||
);
|
||||
layouts.post(
|
||||
'/',
|
||||
requirePermission('timetable:manage'),
|
||||
validate({ body: schemas.layoutSchema }),
|
||||
async (req, res) => sendCreated(res, await service.saveLayout(req.body)),
|
||||
);
|
||||
layouts.put(
|
||||
'/:id',
|
||||
requirePermission('timetable:manage'),
|
||||
validate({ params: idParamSchema, body: schemas.layoutSchema }),
|
||||
async (req, res) => sendOk(res, await service.saveLayout(req.body, String(req.params.id))),
|
||||
);
|
||||
layouts.post(
|
||||
'/:id/clone',
|
||||
requirePermission('timetable:manage'),
|
||||
validate({ params: idParamSchema, body: schemas.cloneSchema }),
|
||||
async (req, res) => {
|
||||
const current = (await service.listLayouts(getAuthUser(req))).find((p) => p.id === req.params.id);
|
||||
if (!current) throw ApiError.notFound('时间表不存在');
|
||||
sendCreated(
|
||||
res,
|
||||
await service.saveLayout({
|
||||
...current,
|
||||
name: req.body.name || `${current.name} 副本`,
|
||||
points: current.points.map((p) => ({ ...p, id: undefined, timeType: p.timeType as 'LESSON' })),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
layouts.post(
|
||||
'/:id/import',
|
||||
requirePermission('timetable:manage'),
|
||||
validate({ params: idParamSchema, body: schemas.importLayoutSchema }),
|
||||
async (req, res) => {
|
||||
const all = await service.listLayouts(getAuthUser(req));
|
||||
const target = all.find((p) => p.id === req.params.id),
|
||||
source = all.find((p) => p.id === req.body.sourceId);
|
||||
if (!target || !source) throw ApiError.notFound('时间表不存在');
|
||||
sendOk(
|
||||
res,
|
||||
await service.saveLayout(
|
||||
{
|
||||
...target,
|
||||
points: source.points.map((p) => ({ ...p, id: undefined, timeType: p.timeType as 'LESSON' })),
|
||||
},
|
||||
target.id,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
layouts.delete(
|
||||
'/:id',
|
||||
requirePermission('timetable:manage'),
|
||||
validate({ params: idParamSchema }),
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id);
|
||||
if (await prisma.classPlan.count({ where: { timeLayoutId: id } }))
|
||||
throw ApiError.conflict('仍有课表使用该时间表');
|
||||
await prisma.timeLayout.delete({ where: { id } });
|
||||
await service.notifyScheduleChanged();
|
||||
sendOk(res, { id });
|
||||
},
|
||||
);
|
||||
|
||||
const plans = Router();
|
||||
plans.use(authenticate());
|
||||
plans.post(
|
||||
'/import/profile',
|
||||
requirePermission('schedule:write'),
|
||||
validate({
|
||||
body: z.object({
|
||||
classId: z.string().min(1),
|
||||
payload: z.unknown(),
|
||||
mode: z.enum(['merge', 'replace']).default('merge'),
|
||||
}),
|
||||
}),
|
||||
async (req, res) =>
|
||||
sendCreated(
|
||||
res,
|
||||
await importProfile(getAuthUser(req), req.body.classId, req.body.payload, req.body.mode),
|
||||
),
|
||||
);
|
||||
plans.get('/', validate({ query: schemas.scopeQuery }), async (req, res) => {
|
||||
const q = validatedQuery<{ classId?: string; week?: number }>(req);
|
||||
sendOk(res, await service.listPlans(getAuthUser(req), q.classId, q.week));
|
||||
});
|
||||
plans.post(
|
||||
'/',
|
||||
requirePermission('schedule:write'),
|
||||
validate({ body: schemas.planSchema }),
|
||||
async (req, res) => sendCreated(res, await service.savePlan(getAuthUser(req), req.body)),
|
||||
);
|
||||
plans.put(
|
||||
'/:id',
|
||||
requirePermission('schedule:write'),
|
||||
validate({ params: idParamSchema, body: schemas.planSchema }),
|
||||
async (req, res) => sendOk(res, await service.savePlan(getAuthUser(req), req.body, String(req.params.id))),
|
||||
);
|
||||
plans.patch(
|
||||
'/:id/enabled',
|
||||
requirePermission('schedule:write'),
|
||||
validate({ params: idParamSchema, body: z.object({ enabled: z.boolean() }) }),
|
||||
async (req, res) => {
|
||||
const p = await service.requirePlan(getAuthUser(req), String(req.params.id));
|
||||
sendOk(
|
||||
res,
|
||||
await prisma.classPlan.update({ where: { id: p.id }, data: { isEnabled: req.body.enabled } }),
|
||||
);
|
||||
await service.notifyScheduleChanged(p.classId);
|
||||
},
|
||||
);
|
||||
plans.put(
|
||||
'/:id/entries',
|
||||
requirePermission('schedule:write'),
|
||||
validate({ params: idParamSchema, body: schemas.entriesSchema }),
|
||||
async (req, res) =>
|
||||
sendOk(res, await service.saveEntries(getAuthUser(req), String(req.params.id), req.body)),
|
||||
);
|
||||
plans.post(
|
||||
'/:id/clone',
|
||||
requirePermission('schedule:write'),
|
||||
validate({ params: idParamSchema, body: schemas.cloneSchema }),
|
||||
async (req, res) =>
|
||||
sendCreated(res, await service.clonePlan(getAuthUser(req), String(req.params.id), req.body.name)),
|
||||
);
|
||||
plans.get('/:id/export', validate({ params: idParamSchema }), async (req, res) => {
|
||||
const p = await service.requirePlan(getAuthUser(req), String(req.params.id), false);
|
||||
sendOk(res, { format: 'classhelper-class-plan', plan: p, timeLayout: p.layout });
|
||||
});
|
||||
plans.post(
|
||||
'/import',
|
||||
requirePermission('schedule:write'),
|
||||
validate({ body: z.object({ plan: schemas.planSchema, entries: schemas.entriesSchema.shape.entries }) }),
|
||||
async (req, res) => {
|
||||
const p = await service.savePlan(getAuthUser(req), req.body.plan);
|
||||
sendCreated(res, await service.saveEntries(getAuthUser(req), p.id, { entries: req.body.entries }));
|
||||
},
|
||||
);
|
||||
plans.delete(
|
||||
'/:id',
|
||||
requirePermission('schedule:write'),
|
||||
validate({ params: idParamSchema }),
|
||||
async (req, res) => {
|
||||
const p = await service.requirePlan(getAuthUser(req), String(req.params.id));
|
||||
await prisma.classPlan.delete({ where: { id: p.id } });
|
||||
await service.notifyScheduleChanged(p.classId);
|
||||
sendOk(res, { id: p.id });
|
||||
},
|
||||
);
|
||||
|
||||
const groups = Router();
|
||||
groups.use(authenticate());
|
||||
groups.get('/selection', validate({ query: z.object({ classId: z.string().min(1) }) }), async (req, res) => {
|
||||
const { classId } = validatedQuery<{ classId: string }>(req);
|
||||
await assertClassAccess(getAuthUser(req), classId);
|
||||
const value = await prisma.appSetting.findUnique({ where: { key: `schedule.group.${classId}` } });
|
||||
sendOk(res, value ? JSON.parse(value.value) : {});
|
||||
});
|
||||
groups.get('/', validate({ query: z.object({ classId: z.string().min(1) }) }), async (req, res) => {
|
||||
const { classId } = validatedQuery<{ classId: string }>(req);
|
||||
await assertClassAccess(getAuthUser(req), classId);
|
||||
sendOk(res, await prisma.classPlanGroup.findMany({ where: { classId } }));
|
||||
});
|
||||
groups.post(
|
||||
'/',
|
||||
requirePermission('schedule:write'),
|
||||
validate({ body: schemas.groupSchema }),
|
||||
async (req, res) => sendCreated(res, await service.saveGroup(getAuthUser(req), req.body)),
|
||||
);
|
||||
groups.put(
|
||||
'/:id',
|
||||
requirePermission('schedule:write'),
|
||||
validate({ params: idParamSchema, body: schemas.groupSchema }),
|
||||
async (req, res) => sendOk(res, await service.saveGroup(getAuthUser(req), req.body, String(req.params.id))),
|
||||
);
|
||||
groups.delete(
|
||||
'/:id',
|
||||
requirePermission('schedule:write'),
|
||||
validate({ params: idParamSchema }),
|
||||
async (req, res) => {
|
||||
const p = await prisma.classPlanGroup.findUnique({ where: { id: String(req.params.id) } });
|
||||
if (!p) throw ApiError.notFound('群组不存在');
|
||||
await assertCanManageSchedule(getAuthUser(req), p.classId);
|
||||
await prisma.classPlanGroup.delete({ where: { id: p.id } });
|
||||
await service.notifyScheduleChanged(p.classId);
|
||||
sendOk(res, { id: p.id });
|
||||
},
|
||||
);
|
||||
groups.post(
|
||||
'/select',
|
||||
requirePermission('schedule:write'),
|
||||
validate({ body: schemas.groupSelectionSchema }),
|
||||
async (req, res) => {
|
||||
const { classId, ...value } = schemas.groupSelectionSchema.parse(req.body);
|
||||
await assertCanManageSchedule(getAuthUser(req), classId);
|
||||
for (const id of [value.selected, value.temporary].filter(Boolean))
|
||||
if (!(await prisma.classPlanGroup.findFirst({ where: { id, classId } })))
|
||||
throw ApiError.badRequest('群组不属于本班');
|
||||
if (value.temporary && !value.expireTime) throw ApiError.badRequest('临时群组必须指定过期时间');
|
||||
await prisma.appSetting.upsert({
|
||||
where: { key: `schedule.group.${classId}` },
|
||||
create: { key: `schedule.group.${classId}`, value: JSON.stringify(value) },
|
||||
update: { value: JSON.stringify(value) },
|
||||
});
|
||||
await service.notifyScheduleChanged(classId);
|
||||
sendOk(res, value);
|
||||
},
|
||||
);
|
||||
export const timeLayoutsModule = defineModule({
|
||||
name: 'time-layouts',
|
||||
basePath: '/time-layouts',
|
||||
router: layouts,
|
||||
});
|
||||
export const classPlansModule = defineModule({
|
||||
name: 'class-plans',
|
||||
basePath: '/class-plans',
|
||||
router: plans,
|
||||
});
|
||||
export const classPlanGroupsModule = defineModule({
|
||||
name: 'class-plan-groups',
|
||||
basePath: '/class-plan-groups',
|
||||
router: groups,
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { z } from 'zod';
|
||||
import { isDayKey, TIME_POINT_TYPES } from '@classhelper/shared';
|
||||
import { timeSchema } from '../../lib/schemas.js';
|
||||
export const scopeQuery = z.object({
|
||||
classId: z.string().min(1).optional(),
|
||||
week: z.coerce.number().int().min(1).max(60).optional(),
|
||||
});
|
||||
export const pointSchema = z
|
||||
.object({
|
||||
id: z.string().min(1).optional(),
|
||||
name: z.string().max(64).default(''),
|
||||
startTime: timeSchema,
|
||||
endTime: timeSchema,
|
||||
timeType: z.enum(TIME_POINT_TYPES).default('LESSON'),
|
||||
isHideDefault: z.boolean().default(false),
|
||||
defaultClassId: z.string().nullish(),
|
||||
breakName: z.string().max(64).default(''),
|
||||
actionSet: z.string().max(10000).default('{}'),
|
||||
})
|
||||
.refine((p) => p.timeType === 'DIVIDER' || p.startTime < p.endTime, '结束时间必须晚于开始时间');
|
||||
export const layoutSchema = z.object({
|
||||
name: z.string().trim().min(1).max(64),
|
||||
classId: z.string().nullish(),
|
||||
points: z.array(pointSchema).max(100),
|
||||
});
|
||||
export const planSchema = z
|
||||
.object({
|
||||
classId: z.string().min(1),
|
||||
name: z.string().trim().min(1).max(64),
|
||||
timeLayoutId: z.string().min(1),
|
||||
associatedGroup: z.string().nullish(),
|
||||
weekday: z.number().int().min(0).max(7).default(0),
|
||||
weekCountDiv: z.number().int().min(0).max(9).default(0),
|
||||
weekCountDivTotal: z.number().int().min(1).max(9).default(2),
|
||||
weekStart: z.number().int().min(1).max(60).default(1),
|
||||
weekEnd: z.number().int().min(1).max(60).default(60),
|
||||
isEnabled: z.boolean().default(true),
|
||||
})
|
||||
.refine((p) => p.weekCountDiv <= p.weekCountDivTotal && p.weekStart <= p.weekEnd, '启用周次规则不合法');
|
||||
export const entriesSchema = z.object({
|
||||
entries: z
|
||||
.array(
|
||||
z.object({
|
||||
timeLayoutItemId: z.string().min(1),
|
||||
courseId: z.string().nullish(),
|
||||
isEnabled: z.boolean().default(true),
|
||||
isChangedClass: z.boolean().default(false),
|
||||
location: z.string().max(100).nullish(),
|
||||
}),
|
||||
)
|
||||
.max(100),
|
||||
});
|
||||
export const groupSchema = z.object({
|
||||
classId: z.string().min(1),
|
||||
name: z.string().trim().min(1).max(64),
|
||||
isGlobal: z.boolean().default(false),
|
||||
isDefault: z.boolean().default(false),
|
||||
});
|
||||
export const datedPlanSchema = z.object({
|
||||
classId: z.string().min(1),
|
||||
classPlanId: z.string().min(1),
|
||||
date: z.string().refine(isDayKey, '日期无效'),
|
||||
});
|
||||
export const swapSchema = datedPlanSchema.extend({ first: z.string().min(1), second: z.string().min(1) });
|
||||
export const cloneSchema = z.object({ name: z.string().trim().min(1).max(64).optional() });
|
||||
export const importLayoutSchema = z.object({ sourceId: z.string().min(1) });
|
||||
export const groupSelectionSchema = z.object({
|
||||
classId: z.string().min(1),
|
||||
selected: z.string().min(1).optional(),
|
||||
temporary: z.string().min(1).optional(),
|
||||
expireTime: z.iso.datetime({ offset: true }).optional(),
|
||||
});
|
||||
@@ -0,0 +1,228 @@
|
||||
import { SOCKET_EVENTS } from '@classhelper/shared';
|
||||
import { prisma } from '../../lib/db.js';
|
||||
import { assertCanManageSchedule, assertClassAccess, getAccessibleClassIds } from '../../lib/access.js';
|
||||
import { getMaxTermWeeks } from '../../lib/term.js';
|
||||
import { ApiError } from '../../lib/http.js';
|
||||
import type { TokenPayload } from '../../lib/jwt.js';
|
||||
import { emitToClass } from '../../realtime/bus.js';
|
||||
import { planInclude } from '../../lib/class-plan.js';
|
||||
import type { z } from 'zod';
|
||||
import type {
|
||||
planSchema,
|
||||
layoutSchema,
|
||||
entriesSchema,
|
||||
groupSchema,
|
||||
datedPlanSchema,
|
||||
} from './class-plans.schemas.js';
|
||||
|
||||
export async function notifyScheduleChanged(classId?: string | null) {
|
||||
const ids = classId
|
||||
? [classId]
|
||||
: (await prisma.class.findMany({ where: { archivedYearId: null }, select: { id: true } })).map(
|
||||
(c) => c.id,
|
||||
);
|
||||
for (const id of ids) emitToClass(id, SOCKET_EVENTS.scheduleUpdated, { classId: id, action: 'updated' });
|
||||
}
|
||||
export async function listLayouts(user: TokenPayload, classId?: string) {
|
||||
if (classId) await assertClassAccess(user, classId);
|
||||
const ids = classId ? [classId] : await getAccessibleClassIds(user);
|
||||
return prisma.timeLayout.findMany({
|
||||
where: { OR: [{ classId: null }, { classId: { in: ids } }] },
|
||||
include: { points: { orderBy: { position: 'asc' } } },
|
||||
});
|
||||
}
|
||||
export async function saveLayout(input: z.infer<typeof layoutSchema>, id?: string) {
|
||||
if (id && !(await prisma.timeLayout.findUnique({ where: { id } }))) throw ApiError.notFound('时间表不存在');
|
||||
const pointIds = input.points.flatMap((p) => (p.id ? [p.id] : []));
|
||||
if (new Set(pointIds).size !== pointIds.length) throw ApiError.badRequest('时间点不能重复');
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const layout = id
|
||||
? await tx.timeLayout.update({ where: { id }, data: { name: input.name } })
|
||||
: await tx.timeLayout.create({
|
||||
data: { name: input.name, classId: input.classId ?? null, source: 'manual' },
|
||||
});
|
||||
const owned = await tx.timeLayoutItem.findMany({
|
||||
where: { timeLayoutId: layout.id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (pointIds.some((p) => !owned.some((o) => o.id === p)))
|
||||
throw ApiError.badRequest('时间点不属于这份时间表');
|
||||
await tx.timeLayoutItem.deleteMany({ where: { timeLayoutId: layout.id, id: { notIn: pointIds } } });
|
||||
for (const [position, point] of input.points.entries()) {
|
||||
const { id: pointId, ...data } = point;
|
||||
if (pointId) await tx.timeLayoutItem.update({ where: { id: pointId }, data: { ...data, position } });
|
||||
else await tx.timeLayoutItem.create({ data: { ...data, position, timeLayoutId: layout.id } });
|
||||
}
|
||||
return tx.timeLayout.findUniqueOrThrow({
|
||||
where: { id: layout.id },
|
||||
include: { points: { orderBy: { position: 'asc' } } },
|
||||
});
|
||||
});
|
||||
await notifyScheduleChanged();
|
||||
return result;
|
||||
}
|
||||
export async function listPlans(user: TokenPayload, classId?: string, week?: number) {
|
||||
if (classId) await assertClassAccess(user, classId);
|
||||
return prisma.classPlan.findMany({
|
||||
where: {
|
||||
classId: { in: classId ? [classId] : await getAccessibleClassIds(user) },
|
||||
...(week ? { weekStart: { lte: week }, weekEnd: { gte: week } } : {}),
|
||||
},
|
||||
include: planInclude,
|
||||
orderBy: [{ weekday: 'asc' }, { name: 'asc' }],
|
||||
});
|
||||
}
|
||||
export async function requirePlan(user: TokenPayload, id: string, write = true) {
|
||||
const p = await prisma.classPlan.findUnique({ where: { id }, include: planInclude });
|
||||
if (!p) throw ApiError.notFound('课表不存在');
|
||||
await (write ? assertCanManageSchedule : assertClassAccess)(user, p.classId);
|
||||
return p;
|
||||
}
|
||||
export async function savePlan(user: TokenPayload, input: z.infer<typeof planSchema>, id?: string) {
|
||||
await assertCanManageSchedule(user, input.classId);
|
||||
const maxWeek = await getMaxTermWeeks();
|
||||
if (input.weekStart > maxWeek) throw ApiError.badRequest('起始周超过全校上限');
|
||||
input = { ...input, weekEnd: Math.min(input.weekEnd, maxWeek) };
|
||||
if (id && (await requirePlan(user, id)).classId !== input.classId)
|
||||
throw ApiError.badRequest('不能移动课表到另一班');
|
||||
const layout = await prisma.timeLayout.findUnique({ where: { id: input.timeLayoutId } });
|
||||
if (!layout || (layout.classId && layout.classId !== input.classId))
|
||||
throw ApiError.badRequest('时间表不属于本班或全校');
|
||||
if (input.associatedGroup) {
|
||||
const group = await prisma.classPlanGroup.findUnique({ where: { id: input.associatedGroup } });
|
||||
if (group?.classId !== input.classId) throw ApiError.badRequest('课表群组不属于本班');
|
||||
}
|
||||
const result = id
|
||||
? await prisma.classPlan.update({ where: { id }, data: input })
|
||||
: await prisma.classPlan.create({ data: input });
|
||||
await notifyScheduleChanged(input.classId);
|
||||
return result;
|
||||
}
|
||||
export async function saveEntries(user: TokenPayload, id: string, input: z.infer<typeof entriesSchema>) {
|
||||
const plan = await requirePlan(user, id);
|
||||
const ids = input.entries.map((e) => e.timeLayoutItemId);
|
||||
if (
|
||||
new Set(ids).size !== ids.length ||
|
||||
ids.some((id) => !plan.layout.points.some((p) => p.id === id && p.timeType === 'LESSON'))
|
||||
)
|
||||
throw ApiError.badRequest('时间点必须唯一且为本时间表的上课时间点');
|
||||
const courseIds = [...new Set(input.entries.flatMap((e) => (e.courseId ? [e.courseId] : [])))];
|
||||
const count = await prisma.course.count({ where: { id: { in: courseIds }, classId: plan.classId } });
|
||||
if (count !== courseIds.length) throw ApiError.badRequest('不能使用其他班级的课程');
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.classPlanEntry.deleteMany({ where: { classPlanId: id } });
|
||||
for (const e of input.entries) await tx.classPlanEntry.create({ data: { ...e, classPlanId: id } });
|
||||
});
|
||||
await notifyScheduleChanged(plan.classId);
|
||||
return requirePlan(user, id);
|
||||
}
|
||||
export async function clonePlan(user: TokenPayload, id: string, name?: string, overlayDate?: string) {
|
||||
const p = await requirePlan(user, id);
|
||||
const {
|
||||
id: _id,
|
||||
entries,
|
||||
layout: _layout,
|
||||
group: _group,
|
||||
createdAt: _created,
|
||||
updatedAt: _updated,
|
||||
scheduled: _scheduled,
|
||||
...data
|
||||
} = { ...p, scheduled: undefined };
|
||||
const cloned = await prisma.classPlan.create({
|
||||
data: {
|
||||
...data,
|
||||
name: name || `${p.name} 副本`,
|
||||
isEnabled: Boolean(overlayDate),
|
||||
isOverlay: Boolean(overlayDate),
|
||||
overlaySourceId: overlayDate ? id : null,
|
||||
overlayDate: overlayDate ?? null,
|
||||
entries: {
|
||||
create: entries.map((e) => ({
|
||||
timeLayoutItemId: e.timeLayoutItemId,
|
||||
courseId: e.courseId,
|
||||
location: e.location,
|
||||
isEnabled: e.isEnabled,
|
||||
isChangedClass: e.isChangedClass,
|
||||
})),
|
||||
},
|
||||
},
|
||||
});
|
||||
await notifyScheduleChanged(p.classId);
|
||||
return cloned;
|
||||
}
|
||||
export async function saveGroup(user: TokenPayload, input: z.infer<typeof groupSchema>, id?: string) {
|
||||
await assertCanManageSchedule(user, input.classId);
|
||||
if (id) {
|
||||
const current = await prisma.classPlanGroup.findUnique({ where: { id } });
|
||||
if (current?.classId !== input.classId) throw ApiError.forbidden('无权修改该群组');
|
||||
}
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
if (input.isDefault)
|
||||
await tx.classPlanGroup.updateMany({ where: { classId: input.classId }, data: { isDefault: false } });
|
||||
return id
|
||||
? tx.classPlanGroup.update({ where: { id }, data: input })
|
||||
: tx.classPlanGroup.create({ data: input });
|
||||
});
|
||||
await notifyScheduleChanged(input.classId);
|
||||
return result;
|
||||
}
|
||||
export async function schedulePlan(user: TokenPayload, input: z.infer<typeof datedPlanSchema>) {
|
||||
const p = await requirePlan(user, input.classPlanId);
|
||||
if (p.classId !== input.classId) throw ApiError.badRequest('课表不属于本班');
|
||||
const result = await prisma.scheduledClassPlan.upsert({
|
||||
where: { classId_date: { classId: input.classId, date: input.date } },
|
||||
create: { classId: input.classId, classPlanId: input.classPlanId, date: input.date },
|
||||
update: { classPlanId: input.classPlanId },
|
||||
});
|
||||
await notifyScheduleChanged(input.classId);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 临时层、换课及预定在同一事务发布,客户端不会先收到尚未换完的中间课表。 */
|
||||
export async function createOverlay(
|
||||
user: TokenPayload,
|
||||
id: string,
|
||||
date: string,
|
||||
swap?: { first: string; second: string },
|
||||
) {
|
||||
const source = await requirePlan(user, id);
|
||||
const a = source.entries.find((e) => e.timeLayoutItemId === swap?.first),
|
||||
b = source.entries.find((e) => e.timeLayoutItemId === swap?.second);
|
||||
if (swap && (!a || !b || a.id === b.id)) throw ApiError.badRequest('请选择两节不同的课');
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const p = await tx.classPlan.create({
|
||||
data: {
|
||||
classId: source.classId,
|
||||
name: `${source.name} 临时层`,
|
||||
timeLayoutId: source.timeLayoutId,
|
||||
weekday: source.weekday,
|
||||
weekCountDiv: source.weekCountDiv,
|
||||
weekCountDivTotal: source.weekCountDivTotal,
|
||||
weekStart: source.weekStart,
|
||||
weekEnd: source.weekEnd,
|
||||
associatedGroup: source.associatedGroup,
|
||||
isOverlay: true,
|
||||
isEnabled: true,
|
||||
overlaySourceId: source.id,
|
||||
overlayDate: date,
|
||||
entries: {
|
||||
create: source.entries.map((e) => ({
|
||||
timeLayoutItemId: e.timeLayoutItemId,
|
||||
courseId:
|
||||
swap && e.id === a?.id ? b!.courseId : swap && e.id === b?.id ? a!.courseId : e.courseId,
|
||||
isEnabled: e.isEnabled,
|
||||
isChangedClass: Boolean(swap && (e.id === a?.id || e.id === b?.id)),
|
||||
location: e.location,
|
||||
})),
|
||||
},
|
||||
},
|
||||
});
|
||||
return tx.scheduledClassPlan.upsert({
|
||||
where: { classId_date: { classId: source.classId, date } },
|
||||
create: { classId: source.classId, date, classPlanId: p.id },
|
||||
update: { classPlanId: p.id },
|
||||
});
|
||||
});
|
||||
await notifyScheduleChanged(source.classId);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import { isDayKey, dayKeyLocal } from '@classhelper/shared';
|
||||
import { prisma } from '../../lib/db.js';
|
||||
import { assertCanManageSchedule } from '../../lib/access.js';
|
||||
import { ApiError } from '../../lib/http.js';
|
||||
import type { TokenPayload } from '../../lib/jwt.js';
|
||||
import { notifyScheduleChanged } from './class-plans.service.js';
|
||||
const record = z.record(z.string(), z.unknown());
|
||||
function object(value: unknown): Record<string, unknown> {
|
||||
const parsed = record.safeParse(value);
|
||||
return parsed.success ? parsed.data : {};
|
||||
}
|
||||
function time(value: unknown) {
|
||||
const match = String(value ?? '').match(/(?:^|T)(\d{1,2}):(\d{2})/);
|
||||
if (!match) throw ApiError.badRequest('时间点缺少合法起止时间');
|
||||
const result = `${match[1]!.padStart(2, '0')}:${match[2]}`;
|
||||
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(result)) throw ApiError.badRequest('时间不合法');
|
||||
return result;
|
||||
}
|
||||
/** 直接保留上游三元组/四种时间点/显式课程位置,绝不经过单双周的有损中间格式。 */
|
||||
export async function importProfile(user: TokenPayload, classId: string, payload: unknown, mode = 'merge') {
|
||||
await assertCanManageSchedule(user, classId);
|
||||
let parsed = payload;
|
||||
if (typeof payload === 'string') {
|
||||
try {
|
||||
parsed = JSON.parse(payload);
|
||||
} catch {
|
||||
throw ApiError.badRequest('JSON 格式不正确');
|
||||
}
|
||||
}
|
||||
const root = object(parsed),
|
||||
layouts = object(root.TimeLayouts),
|
||||
plans = object(root.ClassPlans),
|
||||
subjects = object(root.Subjects),
|
||||
groups = object(root.ClassPlanGroups);
|
||||
if (!Object.keys(layouts).length || !Object.keys(plans).length)
|
||||
throw ApiError.badRequest('需要包含 TimeLayouts 与 ClassPlans 的 ClassIsland JSON');
|
||||
if (Object.keys(plans).length > 500 || Object.keys(layouts).length > 100)
|
||||
throw ApiError.badRequest('导入课表过多');
|
||||
const cls = await prisma.class.findUniqueOrThrow({ where: { id: classId } });
|
||||
const warnings: string[] = [];
|
||||
const stable = (kind: string, id: string) =>
|
||||
`profile-${kind}-${createHash('sha256')
|
||||
.update(classId + '|' + id)
|
||||
.digest('hex')
|
||||
.slice(0, 32)}`;
|
||||
const result = await prisma.$transaction(
|
||||
async (tx) => {
|
||||
const courses = new Map<string, string>();
|
||||
const createdCourses: string[] = [];
|
||||
for (const [id, value] of Object.entries(subjects)) {
|
||||
const subject = object(value),
|
||||
name = String(subject.Name || '')
|
||||
.trim()
|
||||
.slice(0, 64);
|
||||
if (!name) continue;
|
||||
let course = await tx.course.findUnique({ where: { classId_name: { classId, name } } });
|
||||
if (!course) {
|
||||
if (!cls.teacherId) throw ApiError.badRequest('请先为新班指定班主任或建立科目任课关系');
|
||||
course = await tx.course.create({
|
||||
data: {
|
||||
classId,
|
||||
name,
|
||||
teacherId: cls.teacherId,
|
||||
initial: String(subject.Initial || Array.from(name)[0] || '').slice(0, 8),
|
||||
isOutDoor: subject.IsOutDoor === true,
|
||||
},
|
||||
});
|
||||
createdCourses.push(name);
|
||||
} else if (subject.Initial !== undefined || subject.IsOutDoor !== undefined)
|
||||
course = await tx.course.update({
|
||||
where: { id: course.id },
|
||||
data: {
|
||||
...(subject.Initial !== undefined
|
||||
? { initial: String(subject.Initial || Array.from(name)[0] || '').slice(0, 8) }
|
||||
: {}),
|
||||
...(subject.IsOutDoor !== undefined ? { isOutDoor: subject.IsOutDoor === true } : {}),
|
||||
},
|
||||
});
|
||||
courses.set(id, course.id);
|
||||
}
|
||||
const groupIds = new Map<string, string>();
|
||||
for (const [id, value] of Object.entries(groups)) {
|
||||
const g = object(value);
|
||||
const data = {
|
||||
classId,
|
||||
name: String(g.Name || '导入群组').slice(0, 64),
|
||||
isGlobal: g.IsGlobal === true,
|
||||
isDefault: id === root.SelectedClassPlanGroupId,
|
||||
};
|
||||
const created = await tx.classPlanGroup.upsert({
|
||||
where: { id: stable('group', id) },
|
||||
create: { id: stable('group', id), ...data },
|
||||
update: data,
|
||||
});
|
||||
groupIds.set(id, created.id);
|
||||
}
|
||||
if (mode === 'replace') {
|
||||
await tx.scheduledClassPlan.deleteMany({ where: { classId } });
|
||||
await tx.classPlan.deleteMany({ where: { classId } });
|
||||
}
|
||||
const layoutIds = new Map<string, { id: string; lessons: string[] }>();
|
||||
for (const [id, value] of Object.entries(layouts)) {
|
||||
const l = object(value),
|
||||
points = Array.isArray(l.Layouts) ? l.Layouts : [];
|
||||
if (points.length > 100) throw ApiError.badRequest('每份时间表最多100个时间点');
|
||||
const data = {
|
||||
classId,
|
||||
name: String(l.Name || '导入时间表').slice(0, 64),
|
||||
source: 'classisland',
|
||||
isOverlay: l.IsOverlay === true,
|
||||
};
|
||||
const created = await tx.timeLayout.upsert({
|
||||
where: { id: stable('layout', id) },
|
||||
create: { id: stable('layout', id), ...data },
|
||||
update: data,
|
||||
});
|
||||
const lessons: string[] = [],
|
||||
pointIds: string[] = [];
|
||||
for (const [position, value] of points.entries()) {
|
||||
const p = object(value),
|
||||
timeType = (['LESSON', 'BREAK', 'DIVIDER', 'ACTION'] as const)[Number(p.TimeType || 0)];
|
||||
if (!timeType) throw ApiError.badRequest('未知时间点类型');
|
||||
const startTime = time(p.StartTime),
|
||||
endTime = time(p.EndTime);
|
||||
if (timeType !== 'DIVIDER' && startTime >= endTime)
|
||||
throw ApiError.badRequest('时间点结束必须晚于开始');
|
||||
const pointData = {
|
||||
timeLayoutId: created.id,
|
||||
position,
|
||||
name: String(p.Name || '').slice(0, 64),
|
||||
startTime,
|
||||
endTime,
|
||||
timeType,
|
||||
isHideDefault: p.IsHideDefault === true,
|
||||
defaultClassId: courses.get(String(p.DefaultClassId)) || null,
|
||||
breakName: String(p.BreakNameText || p.BreakName || '').slice(0, 64),
|
||||
actionSet: JSON.stringify(p.ActionSet || {}),
|
||||
};
|
||||
const point = await tx.timeLayoutItem.upsert({
|
||||
where: { id: stable('point', id + '|' + position) },
|
||||
create: { id: stable('point', id + '|' + position), ...pointData },
|
||||
update: pointData,
|
||||
});
|
||||
pointIds.push(point.id);
|
||||
if (timeType === 'LESSON') lessons.push(point.id);
|
||||
}
|
||||
await tx.timeLayoutItem.deleteMany({ where: { timeLayoutId: created.id, id: { notIn: pointIds } } });
|
||||
layoutIds.set(id, { id: created.id, lessons });
|
||||
}
|
||||
for (const [id, value] of Object.entries(layouts)) {
|
||||
const source = layoutIds.get(String(object(value).OverlaySourceId)),
|
||||
target = layoutIds.get(id);
|
||||
if (source && target)
|
||||
await tx.timeLayout.update({ where: { id: target.id }, data: { overlaySourceId: source.id } });
|
||||
}
|
||||
const planIds = new Map<string, string>();
|
||||
let created = 0,
|
||||
updated = 0;
|
||||
for (const [id, value] of Object.entries(plans)) {
|
||||
const p = object(value),
|
||||
rule = object(p.TimeRule),
|
||||
layout = layoutIds.get(String(p.TimeLayoutId));
|
||||
if (!layout) {
|
||||
warnings.push(`课表 ${p.Name} 的时间表不存在,已跳过`);
|
||||
continue;
|
||||
}
|
||||
const weekday = Number(rule.WeekDay || 0),
|
||||
weekCountDiv = Number(rule.WeekCountDiv || 0),
|
||||
weekCountDivTotal = Number(rule.WeekCountDivTotal || 2);
|
||||
if (
|
||||
!Number.isInteger(weekday) ||
|
||||
weekday < 0 ||
|
||||
weekday > 7 ||
|
||||
!Number.isInteger(weekCountDiv) ||
|
||||
weekCountDiv < 0 ||
|
||||
weekCountDiv > 9 ||
|
||||
!Number.isInteger(weekCountDivTotal) ||
|
||||
weekCountDivTotal < 1 ||
|
||||
weekCountDivTotal > 9 ||
|
||||
weekCountDiv > weekCountDivTotal
|
||||
)
|
||||
throw ApiError.badRequest('导入启用规则不合法(支持1–9周轮换)');
|
||||
const previous = await tx.classPlan.findUnique({ where: { id: stable('plan', id) } });
|
||||
const data = {
|
||||
classId,
|
||||
name: String(p.Name || '导入课表').slice(0, 64),
|
||||
timeLayoutId: layout.id,
|
||||
associatedGroup: groupIds.get(String(p.AssociatedGroup)) || null,
|
||||
weekday,
|
||||
weekCountDiv,
|
||||
weekCountDivTotal,
|
||||
isEnabled: p.IsEnabled !== false,
|
||||
isOverlay: p.IsOverlay === true,
|
||||
};
|
||||
const plan = await tx.classPlan.upsert({
|
||||
where: { id: stable('plan', id) },
|
||||
create: { id: stable('plan', id), ...data },
|
||||
update: data,
|
||||
});
|
||||
planIds.set(id, plan.id);
|
||||
if (previous) updated += layout.lessons.length;
|
||||
else created += layout.lessons.length;
|
||||
await tx.classPlanEntry.deleteMany({ where: { classPlanId: plan.id } });
|
||||
const entries = Array.isArray(p.Classes) ? p.Classes : [];
|
||||
for (const [index, pointId] of layout.lessons.entries()) {
|
||||
const entry = object(entries[index]);
|
||||
await tx.classPlanEntry.create({
|
||||
data: {
|
||||
classPlanId: plan.id,
|
||||
timeLayoutItemId: pointId,
|
||||
courseId: entry.IsEmpty === true ? null : courses.get(String(entry.SubjectId)) || null,
|
||||
isEnabled: entry.IsEnabled !== false,
|
||||
isChangedClass: entry.IsChangedClass === true,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const [id, value] of Object.entries(plans)) {
|
||||
const p = object(value),
|
||||
planId = planIds.get(id),
|
||||
sourceId = planIds.get(String(p.OverlaySourceId));
|
||||
if (planId && sourceId)
|
||||
await tx.classPlan.update({ where: { id: planId }, data: { overlaySourceId: sourceId } });
|
||||
}
|
||||
for (const [dateKey, value] of Object.entries(object(root.OrderedSchedules))) {
|
||||
const date = isDayKey(dateKey) ? dateKey : dayKeyLocal(new Date(dateKey)),
|
||||
planId = planIds.get(String(object(value).ClassPlanId));
|
||||
if (date && isDayKey(date) && planId)
|
||||
await tx.scheduledClassPlan.upsert({
|
||||
where: { classId_date: { classId, date } },
|
||||
create: { classId, date, classPlanId: planId },
|
||||
update: { classPlanId: planId },
|
||||
});
|
||||
}
|
||||
const dateOf = (value: unknown) => {
|
||||
const parsed = new Date(String(value || ''));
|
||||
return Number.isNaN(parsed.getTime()) ? dayKeyLocal(new Date()) : dayKeyLocal(parsed);
|
||||
};
|
||||
const overlayId = planIds.get(String(root.OverlayClassPlanId));
|
||||
if (root.IsOverlayClassPlanEnabled === true && overlayId)
|
||||
await tx.classPlan.update({
|
||||
where: { id: overlayId },
|
||||
data: { isOverlay: true, isEnabled: true, overlayDate: dateOf(root.TempClassPlanSetupTime) },
|
||||
});
|
||||
const temporaryPlan = planIds.get(String(root.TempClassPlanId)),
|
||||
selected = groupIds.get(String(root.SelectedClassPlanGroupId)),
|
||||
temporary =
|
||||
root.IsTempClassPlanGroupEnabled === true
|
||||
? groupIds.get(String(root.TempClassPlanGroupId))
|
||||
: undefined;
|
||||
if (temporaryPlan || selected || temporary) {
|
||||
const key = `schedule.group.${classId}`,
|
||||
value = JSON.stringify({
|
||||
selected,
|
||||
temporary,
|
||||
expireTime: root.TempClassPlanGroupExpireTime,
|
||||
temporaryPlan,
|
||||
temporaryPlanDate: temporaryPlan ? dateOf(root.TempClassPlanSetupTime) : undefined,
|
||||
});
|
||||
await tx.appSetting.upsert({ where: { key }, create: { key, value }, update: { value } });
|
||||
}
|
||||
return {
|
||||
imported: created + updated,
|
||||
created,
|
||||
updated,
|
||||
createdCourses,
|
||||
weekStart: 1,
|
||||
weekEnd: cls.termWeeks,
|
||||
};
|
||||
},
|
||||
{ timeout: 30000 },
|
||||
);
|
||||
await notifyScheduleChanged(classId);
|
||||
return { ...result, warnings };
|
||||
}
|
||||
Reference in new issue
Block a user