feat: 完善 AI 对话、每日作息与课件目录体验
新增持久化对话、追问卡片和轮次导航;支持每日子时间表、切换保留课程与自动课间;完善课件逐层目录、学期周次同步及两端自适应。同步迁移、文档和回归截图。 验证:后端 262/262、AI 55 项、Web 81/81、桌面 71/71、授权 23 项;构建、类型、Lint 与文档检查通过。
This commit is contained in:
1 parent
cdb64c5499
commit
9351203deb
59 files changed
+1277
-149
No files matched your search
@@ -27,6 +27,29 @@ import { setTimeout as delay } from 'node:timers/promises';
|
||||
|
||||
const router = Router();
|
||||
router.use(authenticate());
|
||||
router.post('/conversations', requirePermission('ai:use'), async (req, res) => {
|
||||
sendOk(res, await tasks.createConversation(getAuthUser(req)));
|
||||
});
|
||||
router.get('/conversations', requirePermission('ai:use'), async (req, res) => {
|
||||
sendOk(
|
||||
res,
|
||||
await tasks.conversations(
|
||||
getAuthUser(req),
|
||||
typeof req.query.before === 'string' ? req.query.before : undefined,
|
||||
),
|
||||
);
|
||||
});
|
||||
router.get(
|
||||
'/conversations/:id',
|
||||
requirePermission('ai:use'),
|
||||
validate({ params: planIdSchema }),
|
||||
async (req, res) => {
|
||||
const before = Number(req.query.before);
|
||||
if (req.query.before !== undefined && (!Number.isInteger(before) || before < 1))
|
||||
throw ApiError.badRequest('轮次游标无效');
|
||||
sendOk(res, await tasks.conversationTurns(getAuthUser(req), String(req.params.id), before || undefined));
|
||||
},
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/tasks/:id/events',
|
||||
@@ -63,7 +86,7 @@ router.get(
|
||||
sent.add(JSON.stringify(event));
|
||||
}
|
||||
}
|
||||
if (['ready', 'succeeded'].includes(current.state) && current.result) {
|
||||
if (['ready', 'succeeded', 'waiting_input'].includes(current.state) && current.result) {
|
||||
send({ type: 'result', result: current.result });
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,8 @@ export const discoverModelsSchema = updateAiSettingsSchema.pick({ baseUrl: true,
|
||||
|
||||
/** `POST /api/ai/interpret`:一句中文原话 */
|
||||
export const aiInterpretSchema = z.object({
|
||||
supersedesTaskId: z.string().min(1).max(100).optional(),
|
||||
conversationId: z.string().min(1).max(100).optional(),
|
||||
text: z.string().trim().min(1, '请说明要做的事').max(8000),
|
||||
messages: z
|
||||
.array(z.object({ role: z.enum(['user', 'assistant']), content: z.string().max(8000) }).strict())
|
||||
|
||||
@@ -27,6 +27,16 @@ const operationSchema = z
|
||||
})
|
||||
.strict();
|
||||
const replySchema = z.object({
|
||||
questions: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string().min(1).max(100),
|
||||
text: z.string().min(1).max(1000),
|
||||
options: z.array(z.string().max(200)).max(10).optional(),
|
||||
}),
|
||||
)
|
||||
.max(3)
|
||||
.optional(),
|
||||
message: z.string().max(4000).optional(),
|
||||
queries: z.array(operationSchema).max(8).default([]),
|
||||
operations: z.array(operationSchema).max(16).default([]),
|
||||
@@ -176,6 +186,20 @@ export async function interpretConversation(
|
||||
});
|
||||
else reply = replySchema.parse({ message: '离线示例未识别此任务,请配置模型或补充具体操作。' });
|
||||
}
|
||||
if (reply.questions?.length)
|
||||
return {
|
||||
planId: null,
|
||||
steps: [],
|
||||
results: modelResults,
|
||||
message: reply.message || reply.questions.map((q) => q.text).join(';'),
|
||||
questions: reply.questions,
|
||||
action: 'unknown',
|
||||
params: {},
|
||||
preview: { summary: '请补充必要信息', warnings: [] },
|
||||
confidence: 0,
|
||||
needConfirm: false,
|
||||
rawReply: null,
|
||||
};
|
||||
const results: AiConversationResult['results'] = [...modelResults];
|
||||
for (const query of reply.queries)
|
||||
results.push({
|
||||
@@ -215,7 +239,7 @@ export async function interpretConversation(
|
||||
settings.provider !== 'openai' ||
|
||||
!(error instanceof ApiError) ||
|
||||
![400, 422].includes(error.status) ||
|
||||
(run.corrections ?? 0) >= 2
|
||||
(run.corrections ?? 0) >= 1
|
||||
)
|
||||
throw error;
|
||||
run.emit?.({ type: 'status', message: '参数需要调整,正在自动核对并修正预览' });
|
||||
|
||||
@@ -29,12 +29,26 @@ const operationSchema = z
|
||||
.strict();
|
||||
const replySchema = z
|
||||
.object({
|
||||
questions: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string().min(1).max(100),
|
||||
text: z.string().min(1).max(1000),
|
||||
options: z.array(z.string().max(200)).max(10).optional(),
|
||||
}),
|
||||
)
|
||||
.max(3)
|
||||
.optional(),
|
||||
message: z.string().max(4000).optional(),
|
||||
queries: z.array(operationSchema).max(8).default([]),
|
||||
operations: z.array(operationSchema).max(16).default([]),
|
||||
})
|
||||
.refine(
|
||||
(value) => !!value.message?.trim() || value.queries.length > 0 || value.operations.length > 0,
|
||||
(value) =>
|
||||
!!value.message?.trim() ||
|
||||
!!value.questions?.length ||
|
||||
value.queries.length > 0 ||
|
||||
value.operations.length > 0,
|
||||
'回复不能是空对象',
|
||||
);
|
||||
|
||||
@@ -95,6 +109,7 @@ export async function planWithModel(
|
||||
content: [
|
||||
'你是 ClassHelper 助手。只输出严格 JSON:{message,queries:[{action,target?,query?}],operations:[{action,target?,params?,attachmentId?}]}。',
|
||||
'例如普通回复:{"message":"你好,需要处理什么?","queries":[],"operations":[]};查询:{"message":"正在查询班级","queries":[{"action":"classes.list"}],"operations":[]}。禁止 Markdown 围栏,message 只写简短进度或给用户的回复。',
|
||||
'缺少用户才能提供的必要信息时,返回 questions:[{id,text,options?}],operations 和 queries 必须为空,等待用户回答。',
|
||||
'queries 只能查询,operations 是待确认写操作,不能声称已执行。先查询真实 id 和现状,再规划修改;不猜测班级、账号、学生、课程和时间点 id。信息不足时追问。',
|
||||
'仅可选择工具目录中的 action。工具 schema.target 列出路径参数,schema.params 是 params 的 JSON Schema。查询条件放 query。所有数据和动作遵循操作者的实时权限。',
|
||||
'数据库备份/恢复/清空/切换/SQL、服务器配置/启停/升级和密钥维护禁止执行。密码字段留空,由用户在专门表单输入。',
|
||||
@@ -112,7 +127,8 @@ export async function planWithModel(
|
||||
];
|
||||
const results: AiConversationResult['results'] = [];
|
||||
const apiKey = decryptSecret(await getSetting(SETTING_KEYS.aiApiKey));
|
||||
let corrections = 0;
|
||||
let corrections = run.corrections ?? 0;
|
||||
const seenQueries = new Set<string>();
|
||||
for (let round = 0; round < 12; round++) {
|
||||
signal.throwIfAborted();
|
||||
await run.authorize?.();
|
||||
@@ -185,13 +201,14 @@ export async function planWithModel(
|
||||
reply = parseModelReply(completion.content);
|
||||
} catch {
|
||||
signal.throwIfAborted();
|
||||
if (++corrections >= 3)
|
||||
run.corrections = ++corrections;
|
||||
if (corrections > 1)
|
||||
throw new ApiError(
|
||||
502,
|
||||
'AI_TASK_INCOMPLETE',
|
||||
'任务已保留,但模型暂未给出可执行方案。自动校正已尝试三次,可点击继续重试;尚未执行任何更改。',
|
||||
'任务已保留,但模型暂未给出可执行方案。自动校正已尝试一次,可点击继续重试;尚未执行任何更改。',
|
||||
);
|
||||
run.emit?.({ type: 'status', message: `正在自动校正回复(${corrections}/3)` });
|
||||
run.emit?.({ type: 'status', message: `正在自动校正回复(${corrections}/1)` });
|
||||
messages.push({
|
||||
role: 'user',
|
||||
content:
|
||||
@@ -199,9 +216,21 @@ export async function planWithModel(
|
||||
});
|
||||
continue;
|
||||
}
|
||||
corrections = 0;
|
||||
if (reply.questions?.length) return { reply: { ...reply, operations: [], queries: [] }, results };
|
||||
if (!reply.queries.length) return { reply, results };
|
||||
for (const query of reply.queries) {
|
||||
const signature = JSON.stringify(query);
|
||||
if (seenQueries.has(signature))
|
||||
return {
|
||||
reply: {
|
||||
message: '已有查询结果仍不足以确定你的意图,请补充需要处理的对象或期望结果。',
|
||||
questions: [{ id: 'clarify-task', text: '请补充你要处理的对象和具体要求。' }],
|
||||
queries: [],
|
||||
operations: [],
|
||||
},
|
||||
results,
|
||||
};
|
||||
seenQueries.add(signature);
|
||||
signal.throwIfAborted();
|
||||
run.emit?.({
|
||||
type: 'status',
|
||||
|
||||
@@ -16,7 +16,7 @@ import { coursewareRoot } from '../courseware/courseware.service.js';
|
||||
import { interpretConversation } from './conversation.js';
|
||||
import { sanitizePrompt } from './model-planner.js';
|
||||
import { runRead } from './actions.js';
|
||||
import { confirmPlan, getPlan, preparePlan } from './plans.js';
|
||||
import { confirmPlan, getPlan, preparePlan, discardPlan } from './plans.js';
|
||||
import type { AiInterpretInput } from './ai.schemas.js';
|
||||
|
||||
const active = new Map<string, AbortController>();
|
||||
@@ -71,7 +71,7 @@ export async function createTask(user: TokenPayload, input: AiInterpretInput) {
|
||||
const expired = await prisma.aiTask.findMany({
|
||||
where: {
|
||||
userId: user.sub,
|
||||
state: { in: ['preparing', 'ready', 'failed', 'stopped', 'succeeded'] },
|
||||
state: { in: ['preparing', 'ready', 'failed', 'stopped', 'succeeded', 'waiting_input'] },
|
||||
updatedAt: { lt: new Date(Date.now() - 24 * 60 * 60 * 1000) },
|
||||
},
|
||||
take: 20,
|
||||
@@ -82,16 +82,87 @@ export async function createTask(user: TokenPayload, input: AiInterpretInput) {
|
||||
3
|
||||
)
|
||||
throw ApiError.conflict('请等待现有后台任务完成');
|
||||
const conversation = input.conversationId
|
||||
? await ownedConversation(user, input.conversationId)
|
||||
: await createConversation(user);
|
||||
if (input.supersedesTaskId) {
|
||||
const old = await owned(user, input.supersedesTaskId);
|
||||
if (old.conversationId !== conversation.id || old.state !== 'ready')
|
||||
throw ApiError.conflict('只能替换本对话中明确选中的待确认计划');
|
||||
}
|
||||
const previous = await prisma.aiTask.findMany({
|
||||
where: { userId: user.sub, conversationId: conversation.id },
|
||||
orderBy: { turnNumber: 'asc' },
|
||||
});
|
||||
if (previous.some((t) => ['planning', 'executing'].includes(t.state)))
|
||||
throw ApiError.conflict('当前对话仍在处理,请等待完成');
|
||||
const history: { role: 'user' | 'assistant'; content: string }[] = [];
|
||||
for (const old of previous) {
|
||||
const checked = await task(user, old.id);
|
||||
history.push({ role: 'user', content: checked.text });
|
||||
if (checked.result)
|
||||
history.push({
|
||||
role: 'assistant',
|
||||
content:
|
||||
checked.result.message +
|
||||
'\n' +
|
||||
JSON.stringify(
|
||||
checked.result.steps.map((s) => ({ action: s.action, status: s.status, summary: s.summary })),
|
||||
),
|
||||
});
|
||||
}
|
||||
const context =
|
||||
history.length > 18
|
||||
? [
|
||||
{
|
||||
role: 'user' as const,
|
||||
content:
|
||||
'此前用户需求摘要:' +
|
||||
history
|
||||
.slice(0, -18)
|
||||
.filter((m) => m.role === 'user')
|
||||
.map((m) => m.content.slice(0, 300))
|
||||
.join(';')
|
||||
.slice(-7000),
|
||||
},
|
||||
...history.slice(-18),
|
||||
]
|
||||
: history;
|
||||
const last = previous.at(-1);
|
||||
const inherited =
|
||||
last?.state === 'waiting_input' && !input.attachments?.length
|
||||
? decode<AiInterpretInput>(last.input).attachments
|
||||
: undefined;
|
||||
const safe = {
|
||||
...input,
|
||||
attachments: input.attachments?.length ? input.attachments : inherited,
|
||||
text: sanitizePrompt(input.text),
|
||||
messages: input.messages?.map((item) => ({ ...item, content: sanitizePrompt(item.content) })),
|
||||
conversationId: conversation.id,
|
||||
messages: context.map((item) => ({ ...item, content: sanitizePrompt(item.content).slice(0, 8000) })),
|
||||
};
|
||||
Object.assign(safe, { accessStamp: await accessStamp(user) });
|
||||
const row = await prisma.aiTask.create({
|
||||
data: { userId: user.sub, input: encryptSecret(JSON.stringify(safe)) },
|
||||
data: {
|
||||
userId: user.sub,
|
||||
conversationId: conversation.id,
|
||||
turnNumber: (previous.at(-1)?.turnNumber ?? 0) + 1,
|
||||
input: encryptSecret(JSON.stringify(safe)),
|
||||
},
|
||||
});
|
||||
return { id: row.id };
|
||||
if (last && inherited?.length) {
|
||||
for (const attachment of inherited) {
|
||||
const source = attachmentPath(last.id, attachment.id),
|
||||
target = attachmentPath(row.id, attachment.id);
|
||||
if (!fs.existsSync(source)) throw ApiError.badRequest('原附件暂存已过期,请重新上传后继续');
|
||||
await fsp.mkdir(path.dirname(target), { recursive: true });
|
||||
await fsp.copyFile(source, target);
|
||||
}
|
||||
}
|
||||
await prisma.aiConversation.update({
|
||||
where: { id: conversation.id },
|
||||
data: { title: conversation.title || sanitizePrompt(input.text).slice(0, 80), updatedAt: new Date() },
|
||||
});
|
||||
return { id: row.id, conversationId: conversation.id };
|
||||
}
|
||||
export async function stageAttachment(
|
||||
user: TokenPayload,
|
||||
@@ -174,6 +245,9 @@ export async function task(user: TokenPayload, id: string): Promise<AiTaskDto> {
|
||||
}
|
||||
return {
|
||||
id,
|
||||
classId: decode<AiInterpretInput>(row.input).classId,
|
||||
conversationId: row.conversationId,
|
||||
turnNumber: row.turnNumber,
|
||||
state: row.state,
|
||||
text: decode<AiInterpretInput>(row.input).text,
|
||||
result,
|
||||
@@ -283,12 +357,29 @@ export async function startTask(user: TokenPayload, id: string) {
|
||||
await prisma.aiTask.update({
|
||||
where: { id },
|
||||
data: {
|
||||
state: result.steps.length ? 'ready' : 'succeeded',
|
||||
state: result.questions?.length ? 'waiting_input' : result.steps.length ? 'ready' : 'succeeded',
|
||||
result: encryptSecret(JSON.stringify(result)),
|
||||
},
|
||||
});
|
||||
if (input.supersedesTaskId && result.steps.length) {
|
||||
const old = await owned(user, input.supersedesTaskId);
|
||||
if (old.conversationId !== row.conversationId || old.state !== 'ready')
|
||||
throw ApiError.conflict('原计划已变化,替换未完成,请分别核对计划');
|
||||
if (active.has(old.id)) throw ApiError.conflict('原计划正在执行,不能替换');
|
||||
const claimed = await prisma.aiTask.updateMany({
|
||||
where: { id: old.id, state: 'ready' },
|
||||
data: { state: 'superseded' },
|
||||
});
|
||||
if (!claimed.count) throw ApiError.conflict('原计划已变化,替换未完成');
|
||||
const oldResult = decode<AiConversationResult>(old.result);
|
||||
if (oldResult.planId) await discardPlan(user, oldResult.planId);
|
||||
await prisma.aiTask.updateMany({
|
||||
where: { id: old.id, state: 'ready' },
|
||||
data: { state: 'superseded' },
|
||||
});
|
||||
}
|
||||
emit({ type: 'status', message: result.steps.length ? '变更预览已准备,等待确认' : '处理完成' });
|
||||
if (!result.steps.length) await cleanup(id, input);
|
||||
if (!result.steps.length && !result.questions?.length) await cleanup(id, input);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -364,3 +455,53 @@ export async function stopTask(user: TokenPayload, id: string) {
|
||||
data: { state: 'stopped', error: '任务已按你的要求停止。' },
|
||||
});
|
||||
}
|
||||
|
||||
export async function createConversation(user: TokenPayload) {
|
||||
await assertPermission(user, 'ai:use');
|
||||
return prisma.aiConversation.create({ data: { userId: user.sub } });
|
||||
}
|
||||
async function ownedConversation(user: TokenPayload, id: string) {
|
||||
await assertPermission(user, 'ai:use');
|
||||
const row = await prisma.aiConversation.findFirst({ where: { id, userId: user.sub } });
|
||||
if (!row) throw ApiError.forbidden('无法访问此对话');
|
||||
return row;
|
||||
}
|
||||
export async function conversations(user: TokenPayload, before?: string) {
|
||||
await assertPermission(user, 'ai:use');
|
||||
const legacy = await prisma.aiTask.findMany({
|
||||
where: { userId: user.sub, conversationId: null },
|
||||
take: 100,
|
||||
});
|
||||
for (const old of legacy)
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const c = await tx.aiConversation.upsert({
|
||||
where: { id: old.id },
|
||||
create: {
|
||||
id: old.id,
|
||||
userId: user.sub,
|
||||
title: sanitizePrompt(decode<AiInterpretInput>(old.input).text).slice(0, 80),
|
||||
createdAt: old.createdAt,
|
||||
},
|
||||
update: {},
|
||||
});
|
||||
await tx.aiTask.updateMany({
|
||||
where: { id: old.id, conversationId: null },
|
||||
data: { conversationId: c.id },
|
||||
});
|
||||
});
|
||||
return prisma.aiConversation.findMany({
|
||||
where: { userId: user.sub },
|
||||
orderBy: [{ updatedAt: 'desc' }, { id: 'desc' }],
|
||||
take: 30,
|
||||
...(before ? { cursor: { id: before }, skip: 1 } : {}),
|
||||
});
|
||||
}
|
||||
export async function conversationTurns(user: TokenPayload, id: string, before?: number) {
|
||||
await ownedConversation(user, id);
|
||||
const rows = await prisma.aiTask.findMany({
|
||||
where: { conversationId: id, userId: user.sub, ...(before ? { turnNumber: { lt: before } } : {}) },
|
||||
orderBy: { turnNumber: 'desc' },
|
||||
take: 30,
|
||||
});
|
||||
return Promise.all(rows.reverse().map((row) => task(user, row.id)));
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Prisma } from '../../generated/prisma/client.js';
|
||||
export async function fillLayoutBreaks(tx: Prisma.TransactionClient, id: string) {
|
||||
await tx.timeLayoutItem.deleteMany({ where: { timeLayoutId: id, isAutoBreak: true } });
|
||||
const points = await tx.timeLayoutItem.findMany({
|
||||
where: { timeLayoutId: id },
|
||||
orderBy: [{ startTime: 'asc' }, { position: 'asc' }],
|
||||
});
|
||||
const lessons = points.filter((p) => p.timeType === 'LESSON');
|
||||
for (let i = 0; i < lessons.length; i++)
|
||||
if (!lessons[i]!.slotKey)
|
||||
await tx.timeLayoutItem.update({ where: { id: lessons[i]!.id }, data: { slotKey: `lesson-${i + 1}` } });
|
||||
for (let i = 1; i < lessons.length; i++) {
|
||||
const left = lessons[i - 1]!,
|
||||
right = lessons[i]!;
|
||||
let cursor = left.endTime;
|
||||
for (const occupied of points
|
||||
.filter((p) => p.timeType !== 'DIVIDER' && p.startTime < right.startTime && p.endTime > left.endTime)
|
||||
.sort((a, b) => a.startTime.localeCompare(b.startTime))) {
|
||||
const end = occupied.startTime < right.startTime ? occupied.startTime : right.startTime;
|
||||
if (cursor < end) await add(cursor, end, i);
|
||||
if (occupied.endTime > cursor) cursor = occupied.endTime;
|
||||
}
|
||||
if (cursor < right.startTime) await add(cursor, right.startTime, i);
|
||||
}
|
||||
async function add(startTime: string, endTime: string, index: number) {
|
||||
await tx.timeLayoutItem.create({
|
||||
data: {
|
||||
timeLayoutId: id,
|
||||
position: index * 2 - 1,
|
||||
startTime,
|
||||
endTime,
|
||||
timeType: 'BREAK',
|
||||
breakName: '课间休息',
|
||||
isAutoBreak: true,
|
||||
slotKey: `break-${index}-${startTime}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
const ordered = await tx.timeLayoutItem.findMany({
|
||||
where: { timeLayoutId: id },
|
||||
orderBy: [{ startTime: 'asc' }, { position: 'asc' }],
|
||||
});
|
||||
for (const [position, p] of ordered.entries())
|
||||
await tx.timeLayoutItem.update({ where: { id: p.id }, data: { position } });
|
||||
}
|
||||
@@ -8,6 +8,8 @@ export const scopeQuery = z.object({
|
||||
export const pointSchema = z
|
||||
.object({
|
||||
id: z.string().min(1).optional(),
|
||||
slotKey: z.string().max(100).default(''),
|
||||
isAutoBreak: z.boolean().default(false),
|
||||
name: z.string().max(64).default(''),
|
||||
startTime: timeSchema,
|
||||
endTime: timeSchema,
|
||||
@@ -19,6 +21,7 @@ export const pointSchema = z
|
||||
})
|
||||
.refine((p) => p.timeType === 'DIVIDER' || p.startTime < p.endTime, '结束时间必须晚于开始时间');
|
||||
export const layoutSchema = z.object({
|
||||
parentId: z.string().min(1).nullish(),
|
||||
name: z.string().trim().min(1).max(64),
|
||||
classId: z.string().nullish(),
|
||||
points: z.array(pointSchema).max(100),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { fillLayoutBreaks } from './auto-breaks.js';
|
||||
import { assertAdmin, assertHeadOnly, assertPermissionOrClassDevice } from '../../lib/authz/index.js';
|
||||
import { SOCKET_EVENTS } from '@classhelper/shared';
|
||||
import { prisma } from '../../lib/db.js';
|
||||
@@ -43,11 +44,18 @@ export async function saveLayout(user: TokenPayload, input: z.infer<typeof layou
|
||||
await assertLayoutWrite(user, layoutClassId, id);
|
||||
if (existing && input.classId !== undefined && input.classId !== existing.classId)
|
||||
throw ApiError.forbidden('不能移动时间表到其他班级');
|
||||
if (input.parentId) {
|
||||
const parent = await prisma.timeLayout.findUnique({ where: { id: input.parentId } });
|
||||
if (!parent || parent.id === id || parent.classId !== layoutClassId || parent.parentId)
|
||||
throw ApiError.badRequest('父时间表无效或范围不一致');
|
||||
}
|
||||
// 默认课程属于具体班级:全校时间表不保留默认课程,非上课时间点也不保留。
|
||||
const points = input.points.map((point) => ({
|
||||
...point,
|
||||
defaultClassId: point.timeType === 'LESSON' && layoutClassId ? (point.defaultClassId ?? null) : null,
|
||||
}));
|
||||
const points = input.points
|
||||
.filter((p) => !p.isAutoBreak)
|
||||
.map((point) => ({
|
||||
...point,
|
||||
defaultClassId: point.timeType === 'LESSON' && layoutClassId ? (point.defaultClassId ?? null) : null,
|
||||
}));
|
||||
const defaultIds = [...new Set(points.flatMap((p) => (p.defaultClassId ? [p.defaultClassId] : [])))];
|
||||
if (defaultIds.length && layoutClassId) {
|
||||
const count = await prisma.course.count({
|
||||
@@ -59,9 +67,17 @@ export async function saveLayout(user: TokenPayload, input: z.infer<typeof layou
|
||||
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.update({
|
||||
where: { id },
|
||||
data: { name: input.name, ...(input.parentId !== undefined ? { parentId: input.parentId } : {}) },
|
||||
})
|
||||
: await tx.timeLayout.create({
|
||||
data: { name: input.name, classId: input.classId ?? null, source: 'manual' },
|
||||
data: {
|
||||
name: input.name,
|
||||
classId: input.classId ?? null,
|
||||
parentId: input.parentId,
|
||||
source: 'manual',
|
||||
},
|
||||
});
|
||||
const owned = await tx.timeLayoutItem.findMany({
|
||||
where: { timeLayoutId: layout.id },
|
||||
@@ -75,6 +91,7 @@ export async function saveLayout(user: TokenPayload, input: z.infer<typeof layou
|
||||
if (pointId) await tx.timeLayoutItem.update({ where: { id: pointId }, data: { ...data, position } });
|
||||
else await tx.timeLayoutItem.create({ data: { ...data, position, timeLayoutId: layout.id } });
|
||||
}
|
||||
await fillLayoutBreaks(tx, layout.id);
|
||||
return tx.timeLayout.findUniqueOrThrow({
|
||||
where: { id: layout.id },
|
||||
include: { points: { orderBy: { position: 'asc' } } },
|
||||
@@ -152,16 +169,54 @@ export async function savePlan(user: TokenPayload, input: z.infer<typeof planSch
|
||||
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 } });
|
||||
const layout = await prisma.timeLayout.findUnique({
|
||||
where: { id: input.timeLayoutId },
|
||||
include: { points: { orderBy: { position: 'asc' } } },
|
||||
});
|
||||
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 });
|
||||
const previous = id ? await requirePlan(user, id) : null;
|
||||
const changes =
|
||||
previous && previous.timeLayoutId !== layout.id
|
||||
? previous.entries.map((entry) => {
|
||||
const oldLessons = previous.layout.points.filter((p) => p.timeType === 'LESSON');
|
||||
const source = oldLessons.find((p) => p.id === entry.timeLayoutItemId);
|
||||
const lessons = layout.points.filter((p) => p.timeType === 'LESSON');
|
||||
const target =
|
||||
lessons.find((p) => source?.slotKey && p.slotKey === source.slotKey) ||
|
||||
lessons[oldLessons.findIndex((p) => p.id === source?.id)];
|
||||
if (!target) throw ApiError.conflict('目标时间表课时不足,原课表已保留,请先处理差异');
|
||||
return { id: entry.id, target: target.id };
|
||||
})
|
||||
: [];
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const row = id
|
||||
? await tx.classPlan.update({ where: { id }, data: input })
|
||||
: await tx.classPlan.create({ data: input });
|
||||
// 先删除再重建,避免槽位交换命中日课表/时间点的组合唯一键。
|
||||
if (changes.length && previous) {
|
||||
await tx.classPlanEntry.deleteMany({ where: { classPlanId: previous.id } });
|
||||
for (const entry of previous.entries) {
|
||||
const target = changes.find((c) => c.id === entry.id)!;
|
||||
await tx.classPlanEntry.create({
|
||||
data: {
|
||||
id: entry.id,
|
||||
classPlanId: previous.id,
|
||||
timeLayoutItemId: target.target,
|
||||
courseId: entry.courseId,
|
||||
isEnabled: entry.isEnabled,
|
||||
isChangedClass: entry.isChangedClass,
|
||||
location: entry.location,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return row;
|
||||
});
|
||||
await notifyScheduleChanged(input.classId);
|
||||
return result;
|
||||
}
|
||||
@@ -317,6 +372,7 @@ export async function deleteLayout(user: TokenPayload, id: string) {
|
||||
const layout = await prisma.timeLayout.findUnique({ where: { id } });
|
||||
if (!layout) throw ApiError.notFound('时间表不存在');
|
||||
await assertLayoutWrite(user, layout.classId, id);
|
||||
if (await prisma.timeLayout.count({ where: { parentId: id } })) throw ApiError.conflict('仍有子时间表');
|
||||
if (await prisma.classPlan.count({ where: { timeLayoutId: id } }))
|
||||
throw ApiError.conflict('仍有课表使用该时间表');
|
||||
await prisma.timeLayout.delete({ where: { id } });
|
||||
|
||||
@@ -47,9 +47,12 @@ export async function exportProfile(user: TokenPayload, classId: string) {
|
||||
l.id,
|
||||
{
|
||||
Name: l.name,
|
||||
ParentTimeLayoutId: l.parentId,
|
||||
IsOverlay: l.isOverlay,
|
||||
OverlaySourceId: l.overlaySourceId,
|
||||
Layouts: l.points.map((p) => ({
|
||||
SlotKey: p.slotKey,
|
||||
IsAutoBreak: p.isAutoBreak,
|
||||
Name: p.name,
|
||||
StartTime: p.startTime,
|
||||
EndTime: p.endTime,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { fillLayoutBreaks } from './auto-breaks.js';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import { isDayKey, dayKeyLocal } from '@classhelper/shared';
|
||||
@@ -102,6 +103,17 @@ export async function importProfile(user: TokenPayload, classId: string, payload
|
||||
await tx.scheduledClassPlan.deleteMany({ where: { classId } });
|
||||
await tx.classPlan.deleteMany({ where: { classId } });
|
||||
}
|
||||
for (const [id, value] of Object.entries(layouts)) {
|
||||
const parent = object(value).ParentTimeLayoutId;
|
||||
if (
|
||||
parent != null &&
|
||||
(typeof parent !== 'string' ||
|
||||
!layouts[parent] ||
|
||||
parent === id ||
|
||||
object(layouts[parent]).ParentTimeLayoutId)
|
||||
)
|
||||
throw ApiError.badRequest('父时间表不存在或存在循环、嵌套关系');
|
||||
}
|
||||
const layoutIds = new Map<string, { id: string; lessons: string[] }>();
|
||||
for (const [id, value] of Object.entries(layouts)) {
|
||||
const l = object(value),
|
||||
@@ -129,6 +141,8 @@ export async function importProfile(user: TokenPayload, classId: string, payload
|
||||
if (timeType !== 'DIVIDER' && startTime >= endTime)
|
||||
throw ApiError.badRequest('时间点结束必须晚于开始');
|
||||
const pointData = {
|
||||
slotKey: typeof p.SlotKey === 'string' ? p.SlotKey.slice(0, 100) : '',
|
||||
isAutoBreak: p.IsAutoBreak === true,
|
||||
timeLayoutId: created.id,
|
||||
position,
|
||||
name: String(p.Name || '').slice(0, 64),
|
||||
@@ -151,6 +165,14 @@ export async function importProfile(user: TokenPayload, classId: string, payload
|
||||
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 target = layoutIds.get(id),
|
||||
parent = layoutIds.get(String(object(value).ParentTimeLayoutId));
|
||||
if (target) {
|
||||
await tx.timeLayout.update({ where: { id: target.id }, data: { parentId: parent?.id ?? null } });
|
||||
await fillLayoutBreaks(tx, target.id);
|
||||
}
|
||||
}
|
||||
for (const [id, value] of Object.entries(layouts)) {
|
||||
const source = layoutIds.get(String(object(value).OverlaySourceId)),
|
||||
target = layoutIds.get(id);
|
||||
|
||||
@@ -205,6 +205,14 @@ export async function listFolders(user: TokenPayload) {
|
||||
}
|
||||
export async function createFolder(user: TokenPayload, folderPath: string) {
|
||||
await assertPermission(user, 'courseware:write');
|
||||
for (let i = 1; i < folderPath.split('/').length; i++) {
|
||||
const parent = folderPath.split('/').slice(0, i).join('/');
|
||||
await prisma.coursewareFolder.upsert({
|
||||
where: { ownerId_path: { ownerId: user.sub, path: parent } },
|
||||
create: { ownerId: user.sub, path: parent },
|
||||
update: {},
|
||||
});
|
||||
}
|
||||
const row = await prisma.coursewareFolder.upsert({
|
||||
where: { ownerId_path: { ownerId: user.sub, path: folderPath } },
|
||||
create: { ownerId: user.sub, path: folderPath },
|
||||
|
||||
@@ -20,8 +20,7 @@ import type { ClassPlanYamlImportInput } from './imports.schemas.js';
|
||||
* 这里把它**归一化成 ClassIsland 兼容的 `{ TimeLayouts, ClassPlans, Subjects }` 载荷**,
|
||||
* 再交给 `importProfile()` 写入:
|
||||
* - merge / replace、稳定 id、事务回滚、权限与 `notifyScheduleChanged` 全部复用现有一份实现;
|
||||
* - 全部 schedules 里出现过的不同 (start_time, end_time) 合并成一张时间表,
|
||||
* LESSON 时间点按时间排序,同一天没列出的时间点写成空课(IsEmpty);
|
||||
* - 作息存在差异时按日期与周相位生成独立子时间表,保留当天显式空课;
|
||||
* - 单双周映射:all → WeekCountDiv=0,odd → 1/2,even → 2/2;
|
||||
* - enable_day 1=周一 … 7=周日,ClassIsland 的 WeekDay 同样 1=周一 … 7=周日,直接对应。
|
||||
*
|
||||
@@ -605,45 +604,44 @@ export function buildClassIslandProfile(
|
||||
...(subject.initial ? { Initial: subject.initial } : {}),
|
||||
};
|
||||
}
|
||||
const layouts: Record<string, unknown> = {
|
||||
'yaml-layout': {
|
||||
Name: LAYOUT_NAME,
|
||||
Layouts: parsed.layout.map((point) => ({
|
||||
StartTime: point.startTime,
|
||||
EndTime: point.endTime,
|
||||
TimeType: 0,
|
||||
Name: '',
|
||||
})),
|
||||
},
|
||||
};
|
||||
const signatures = new Set(
|
||||
parsed.schedules.map((s) => JSON.stringify(s.lessons.map((l) => [l.startTime, l.endTime]))),
|
||||
);
|
||||
const split = signatures.size > 1;
|
||||
const layouts: Record<string, unknown> = {};
|
||||
const plans: Record<string, unknown> = {};
|
||||
if (split) layouts['yaml-layout'] = { Name: LAYOUT_NAME, Layouts: [] };
|
||||
for (const schedule of parsed.schedules) {
|
||||
const lessonByTime = new Map(
|
||||
schedule.lessons
|
||||
.filter((lesson) => lesson.subject)
|
||||
.map((lesson) => [`${lesson.startTime}-${lesson.endTime}`, lesson]),
|
||||
);
|
||||
const classes = parsed.layout.map((point) => {
|
||||
const lesson = lessonByTime.get(`${point.startTime}-${point.endTime}`);
|
||||
if (!lesson) return { IsEmpty: true, IsEnabled: true };
|
||||
return {
|
||||
SubjectId: `yaml-subject-${lesson.subject}`,
|
||||
IsEnabled: true,
|
||||
Location: lesson.location || '',
|
||||
};
|
||||
});
|
||||
plans[`yaml-plan-${schedule.weekday}-${schedule.parity.toLowerCase()}`] = {
|
||||
const key = `yaml-plan-${schedule.weekday}-${schedule.parity.toLowerCase()}`;
|
||||
const layoutId = split
|
||||
? `yaml-layout-${schedule.weekday}-${schedule.parity.toLowerCase()}`
|
||||
: 'yaml-layout';
|
||||
const lessons = [...schedule.lessons].sort((a, b) => a.startTime.localeCompare(b.startTime));
|
||||
layouts[layoutId] = {
|
||||
Name: split
|
||||
? `${WEEKDAY_LABELS[schedule.weekday - 1]}${schedule.parity === 'ALL' ? '' : schedule.parity === 'ODD' ? '(单周)' : '(双周)'}`
|
||||
: LAYOUT_NAME,
|
||||
ParentTimeLayoutId: split ? 'yaml-layout' : null,
|
||||
Layouts: lessons.map((l, i) => ({
|
||||
StartTime: l.startTime,
|
||||
EndTime: l.endTime,
|
||||
TimeType: 0,
|
||||
Name: `第 ${i + 1} 节`,
|
||||
SlotKey: `lesson-${i + 1}`,
|
||||
})),
|
||||
};
|
||||
plans[key] = {
|
||||
Name: schedule.name,
|
||||
TimeLayoutId: 'yaml-layout',
|
||||
TimeRule: {
|
||||
WeekDay: schedule.weekday,
|
||||
WeekCountDiv: parityDiv(schedule.parity),
|
||||
WeekCountDivTotal: 2,
|
||||
},
|
||||
TimeLayoutId: layoutId,
|
||||
TimeRule: { WeekDay: schedule.weekday, WeekCountDiv: parityDiv(schedule.parity), WeekCountDivTotal: 2 },
|
||||
WeekStart: 1,
|
||||
WeekEnd: weekEnd,
|
||||
IsEnabled: true,
|
||||
Classes: classes,
|
||||
Classes: lessons.map((l) =>
|
||||
l.subject
|
||||
? { SubjectId: `yaml-subject-${l.subject}`, IsEnabled: true, Location: l.location || '' }
|
||||
: { IsEmpty: true, IsEnabled: true },
|
||||
),
|
||||
};
|
||||
}
|
||||
return { TimeLayouts: layouts, ClassPlans: plans, Subjects: subjects };
|
||||
@@ -667,7 +665,12 @@ export async function previewYamlClassPlan(
|
||||
entries: parsed.entries,
|
||||
subjects: parsed.subjectNames,
|
||||
missingSubjects: parsed.subjectNames.filter((name) => !existing.has(name)),
|
||||
layoutNames: parsed.layout.length > 0 ? [LAYOUT_NAME] : [],
|
||||
layoutNames:
|
||||
parsed.layout.length > 0
|
||||
? Object.values(
|
||||
buildClassIslandProfile(parsed, 1).TimeLayouts as Record<string, { Name: string }>,
|
||||
).map((l) => l.Name)
|
||||
: [],
|
||||
planCount: parsed.planCount,
|
||||
errors: parsed.errors,
|
||||
warnings: parsed.warnings,
|
||||
|
||||
@@ -368,6 +368,8 @@ export async function importTimeLayout(
|
||||
const previousPoint = candidates.find((old) => old.endTime === p.endTime) || candidates[0];
|
||||
if (previousPoint) claimed.add(previousPoint.id);
|
||||
return {
|
||||
slotKey: previousPoint?.slotKey || '',
|
||||
isAutoBreak: false,
|
||||
id: previousPoint?.id,
|
||||
position,
|
||||
name: p.name,
|
||||
|
||||
@@ -25,6 +25,7 @@ export const updateTermWeeksSchema = z.object({
|
||||
});
|
||||
|
||||
export const autoTermWeeksSchema = z.object({
|
||||
maxTermWeeks: z.coerce.number().int().min(1).max(60).optional(),
|
||||
classId: z.string().min(1).nullish(),
|
||||
termStartDate: termStartDateSchema.optional(),
|
||||
maxWeek: z.coerce.number().int().min(1).max(60).optional(),
|
||||
|
||||
@@ -13,7 +13,7 @@ import { ApiError } from '../../lib/http.js';
|
||||
import type { TokenPayload } from '../../lib/jwt.js';
|
||||
import { logger } from '../../lib/logger.js';
|
||||
import { getMaxTermWeeks, loadTermContext, resolveCurrentWeek } from '../../lib/term.js';
|
||||
import { SETTING_KEYS, setSetting } from '../../lib/settings.js';
|
||||
import { SETTING_KEYS } from '../../lib/settings.js';
|
||||
import { emitToClass } from '../../realtime/bus.js';
|
||||
import { SOCKET_EVENTS } from '@classhelper/shared';
|
||||
import type { AutoTermWeeksInput, UpdateTermWeeksInput } from './term.schemas.js';
|
||||
@@ -111,6 +111,24 @@ export async function updateTermWeeks(
|
||||
}
|
||||
|
||||
await prisma.$transaction([
|
||||
...(!scope && input.termStartDate
|
||||
? [
|
||||
prisma.appSetting.upsert({
|
||||
where: { key: SETTING_KEYS.termStartDate },
|
||||
create: { key: SETTING_KEYS.termStartDate, value: input.termStartDate },
|
||||
update: { value: input.termStartDate },
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(input.maxTermWeeks !== undefined
|
||||
? [
|
||||
prisma.appSetting.upsert({
|
||||
where: { key: SETTING_KEYS.termMaxWeeks },
|
||||
create: { key: SETTING_KEYS.termMaxWeeks, value: String(maximum) },
|
||||
update: { value: String(maximum) },
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
prisma.termWeek.deleteMany({ where: { classId: scope } }),
|
||||
...(input.weeks.length > 0
|
||||
? [
|
||||
@@ -130,15 +148,7 @@ export async function updateTermWeeks(
|
||||
: []),
|
||||
]);
|
||||
|
||||
// 全校默认没有"班级记录"可以挂开学日期,写进全局设置(`term.startDate`)。
|
||||
// 需求:「服务端可设置学期开始日期,以保证当前周次正确,管理员也可以随时纠正」——
|
||||
// 原先这一级只能来自 `.env`,改一次要动文件 + 重启。
|
||||
if (input.termStartDate && !scope) {
|
||||
await setSetting(SETTING_KEYS.termStartDate, input.termStartDate);
|
||||
}
|
||||
|
||||
logger.info(`学期周次已更新:范围=${scope || '全校默认'} 周数=${input.weeks.length} 由 ${user.name} 执行`);
|
||||
if (input.maxTermWeeks !== undefined) await setSetting(SETTING_KEYS.termMaxWeeks, String(maximum));
|
||||
logger.info(`学期周次已更新:范围=${scope || '全校默认'} 周数=${input.weeks.length}`);
|
||||
await publishTermChange(scope);
|
||||
return readTermWeeks(scope);
|
||||
}
|
||||
@@ -155,12 +165,17 @@ export async function autoTermWeeks(user: TokenPayload, input: AutoTermWeeksInpu
|
||||
else assertAdmin(user);
|
||||
const context = await loadTermContext(scope || null);
|
||||
const termStartDate = input.termStartDate || context.termStartDate || env.termStartDate;
|
||||
const maxWeek = input.maxWeek ?? context.maxWeek;
|
||||
const maxWeek = scope ? context.maxWeek : (input.maxTermWeeks ?? input.maxWeek ?? context.maxWeek);
|
||||
|
||||
const weeks = buildAutoTermWeeks(termStartDate, maxWeek);
|
||||
if (weeks.length === 0) throw ApiError.badRequest('请先填写学期开始日期(第 1 教学周的周一)');
|
||||
|
||||
return updateTermWeeks(user, { classId: scope || null, termStartDate, weeks });
|
||||
return updateTermWeeks(user, {
|
||||
classId: scope || null,
|
||||
termStartDate,
|
||||
weeks,
|
||||
...(scope ? {} : { maxTermWeeks: input.maxTermWeeks }),
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 调休建议(联网,可选) */
|
||||
|
||||
Reference in new issue
Block a user