feat: 完善 AI 对话、每日作息与课件目录体验

新增持久化对话、追问卡片和轮次导航;支持每日子时间表、切换保留课程与自动课间;完善课件逐层目录、学期周次同步及两端自适应。同步迁移、文档和回归截图。

验证:后端 262/262、AI 55 项、Web 81/81、桌面 71/71、授权 23 项;构建、类型、Lint 与文档检查通过。
This commit is contained in:
LoveChengke committed 2026-11-08 09:07:10 +08:00
1 parent cdb64c5499
commit 9351203deb
59 files changed
+1277 -149

No files matched your search

@@ -62,7 +62,16 @@ const emit = defineEmits<{
placeholder="选择时间表"
@change="emit('change-layout', $event)"
>
<el-option v-for="item in props.layouts" :key="item.id" :value="item.id" :label="item.name" />
<el-option
v-for="item in props.layouts"
:key="item.id"
:value="item.id"
:label="
item.parentId
? (props.layouts.find((p) => p.id === item.parentId)?.name || '') + ' / ' + item.name
: item.name
"
/>
</el-select>
<button class="text-command" type="button" @click="emit('edit-layout')">
<ArchiveIcon name="clock" />
@@ -30,6 +30,7 @@ const layout = defineModel<TimeLayoutDetailDto | undefined>('layout', { default:
const emit = defineEmits<{
'select-layout': [id: string];
create: [];
'create-child': [parentId: string];
clone: [];
save: [];
refresh: [];
@@ -67,7 +68,13 @@ let reorderFrom = '';
let reorderTo = '';
let draftSequence = 0;
const visibleLayouts = computed(() => props.layouts.filter((item) => item.name.includes(search.value)));
const visibleLayouts = computed(() =>
props.layouts
.filter((item) => !item.parentId)
.flatMap((parent) => [parent, ...props.layouts.filter((child) => child.parentId === parent.id)])
.filter((item) => item.name.includes(search.value))
.map((item) => ({ ...item, name: item.parentId ? ' ↳ ' + item.name : item.name })),
);
const points = computed(() => layout.value?.points ?? []);
const selected = computed<TimePointDto | undefined>(() =>
points.value.find((point) => point.id === selectedId.value),
@@ -346,6 +353,14 @@ onUnmounted(() => {
</aside>
<main class="layout-main">
<button
v-if="layout && !layout.parentId"
class="command"
:disabled="!canCreate"
@click="emit('create-child', layout.id)"
>
新建子时间表
</button>
<header class="layout-toolbar">
<button class="command" :disabled="!canEdit || !layout" @click="addPoint('LESSON')">
<ArchiveIcon name="lesson" />
@@ -1,6 +1,8 @@
import { sha256 } from '@noble/hashes/sha2.js';
import type { AiAttachment } from '@classhelper/shared';
let attachmentSequence = 0;
export async function hashAttachment(file: File, signal?: AbortSignal): Promise<AiAttachment> {
const hash = sha256.create();
const reader = file.stream().getReader();
@@ -16,7 +18,7 @@ export async function hashAttachment(file: File, signal?: AbortSignal): Promise<
reader.releaseLock();
}
return {
id: crypto.randomUUID(),
id: `attachment-${Date.now().toString(36)}-${++attachmentSequence}-${Math.random().toString(36).slice(2)}`,
name: file.name,
size: file.size,
sha256: [...hash.digest()].map((value) => value.toString(16).padStart(2, '0')).join(''),
+257 -38
View File
@@ -22,6 +22,7 @@ import AssistantData from '@/components/AssistantData.vue';
import UrgentClassWarning from '@/components/UrgentClassWarning.vue';
import { observeTask } from '@/composables/assistantStream';
interface ChatMessage {
taskId?: string;
role: 'user' | 'assistant';
content: string;
result?: AiConversationResult;
@@ -29,6 +30,85 @@ interface ChatMessage {
state?: 'working' | 'done' | 'stopped';
}
const auth = useAuthStore();
let viewEpoch = 0;
const replacePlan = ref(false);
const conversationId = ref('');
const conversations = ref<{ id: string; title: string }[]>([]);
async function loadConversations() {
conversations.value = await api.get('/ai/conversations');
}
async function openConversation(id: string) {
if ((busy.value || executing.value) && !observing) return;
viewEpoch++;
controller?.abort();
busy.value = false;
executing.value = false;
conversationId.value = id;
attachments.value = [];
files.clear();
replacePlan.value = false;
const turns = await api.get<AiTaskDto[]>(`/ai/conversations/${id}`);
messages.value = turns.flatMap((t) => [
{ role: 'user' as const, content: t.text },
{
role: 'assistant' as const,
taskId: t.id,
activity: t.events.filter((e) => e.type === 'status').map((e) => e.message),
content: t.result?.message || t.error || '',
result: t.result,
state: 'done' as const,
},
]);
const last = turns.at(-1);
error.value = last?.error || '';
classId.value = last?.classId || '';
taskId.value = last?.id || '';
active.value = last?.result;
lastRequest = last ? { text: last.text, conversationId: id } : undefined;
clearCredentials();
if (last && ['planning', 'executing'].includes(last.state)) await resumeTask(last.id, true);
}
async function olderConversations() {
const older = await api.get<{ id: string; title: string }[]>('/ai/conversations', {
before: conversations.value.at(-1)?.id,
});
conversations.value.push(...older);
}
async function olderTurns() {
const first = messages.value.find((m) => m.taskId);
if (!first?.taskId) return;
const before = await api.get<AiTaskDto>(`/ai/tasks/${first.taskId}`);
if (!before.turnNumber) return;
const older = await api.get<AiTaskDto[]>(`/ai/conversations/${conversationId.value}`, {
before: before.turnNumber,
});
messages.value.unshift(
...older.flatMap((t) => [
{ role: 'user' as const, content: t.text, taskId: t.id },
{ role: 'assistant' as const, content: t.result?.message || '', result: t.result, taskId: t.id },
]),
);
}
const currentTurn = ref(0);
function onConversationScroll() {
const box = conversation.value;
if (!box) return;
followScroll.value = box.scrollHeight - box.scrollTop - box.clientHeight < 100;
const top = box.getBoundingClientRect().top;
const sections = [...box.querySelectorAll('.assistant-message.user')];
let active = 0;
sections.forEach((node, index) => {
if (node.getBoundingClientRect().top <= top + 100) active = index;
});
currentTurn.value = Math.max(0, active);
}
function jumpTurn(index: number) {
currentTurn.value = index;
conversation.value
?.querySelectorAll('.assistant-message.user')
[index]?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
const text = ref(''),
classId = ref(''),
classes = ref<ClassDto[]>([]),
@@ -147,19 +227,22 @@ async function retryTask(): Promise<void> {
}
async function send(retrying = false): Promise<void> {
if ((!retrying && !text.value.trim()) || busy.value || executing.value || hashing.value) return;
const epoch = viewEpoch;
const supersedesTaskId = replacePlan.value && pending.value ? taskId.value : undefined;
busy.value = true;
error.value = '';
controller = new AbortController();
let message: ChatMessage | undefined;
const uploadFiles = attachments.value.map((attachment) => ({ attachment, file: files.get(attachment.id) }));
try {
if (active.value?.planId && pending.value) await aiApi.discard(active.value.planId);
clearCredentials();
active.value = undefined;
const content = retrying ? lastRequest!.text : text.value.trim(),
history = messages.value.slice(-18).map(({ role, content }) => ({ role, content }));
if (!retrying) {
lastRequest = {
supersedesTaskId,
conversationId: conversationId.value || undefined,
text: content,
classId: classId.value || undefined,
messages: history,
@@ -173,7 +256,11 @@ async function send(retrying = false): Promise<void> {
followScroll.value = true;
await scroll();
if (!retrying || !taskId.value) {
if (!conversationId.value)
conversationId.value = (await api.post<{ id: string }>('/ai/conversations', {})).id;
lastRequest!.conversationId = conversationId.value;
taskId.value = (await aiApi.createTask(lastRequest!)).id;
message.taskId = taskId.value;
message.activity!.push(
attachments.value.length ? '正在上传附件,完成后将转入后台' : '任务已提交到后台',
);
@@ -190,7 +277,7 @@ async function send(retrying = false): Promise<void> {
await observeTask(
taskId.value,
(event) => {
if (disposed || controller?.signal.aborted) return;
if (disposed || epoch !== viewEpoch || controller?.signal.aborted) return;
if (event.type === 'status' && message!.activity?.at(-1) !== event.message)
message!.activity = [...(message!.activity ?? []), event.message].slice(-60);
if (event.type === 'message') message!.content = event.text;
@@ -199,7 +286,7 @@ async function send(retrying = false): Promise<void> {
controller.signal,
),
);
if (disposed) return;
if (disposed || epoch !== viewEpoch) return;
active.value = result;
message.content = result.message;
message.result = result;
@@ -210,6 +297,7 @@ async function send(retrying = false): Promise<void> {
}
for (const step of result.steps) credentials[step.id] = {};
} catch (e) {
if (epoch !== viewEpoch) return;
if (controller.signal.aborted) {
if (message) message.content = '已停止生成,任务已保留,可继续重试。';
} else if (!disposed && !axios.isCancel(e)) {
@@ -218,10 +306,14 @@ async function send(retrying = false): Promise<void> {
if (typeof e === 'object' && e && 'code' in e && e.code === 'AI_NOT_CONFIGURED') disabled.value = true;
}
} finally {
if (epoch !== viewEpoch) return;
observing = false;
if (message) message.state = controller.signal.aborted || error.value ? 'stopped' : 'done';
busy.value = false;
if (!disposed) taskHistory.value = await aiApi.tasks().catch(() => taskHistory.value);
if (!disposed) {
taskHistory.value = await aiApi.tasks().catch(() => taskHistory.value);
await loadConversations();
}
await scroll();
}
}
@@ -232,19 +324,17 @@ function composerKey(event: KeyboardEvent): void {
}
}
async function newConversation(): Promise<void> {
if (busy.value || executing.value || hashing.value) return;
if (pending.value && active.value?.planId) {
try {
await ElMessageBox.confirm('开始新对话将取消当前待确认计划。', '新对话', {
confirmButtonText: '开始新对话',
cancelButtonText: '保留当前对话',
});
} catch {
return;
}
await aiApi.discard(active.value.planId);
}
if (hashing.value || ((busy.value || executing.value) && !observing)) return;
viewEpoch++;
controller?.abort();
busy.value = false;
executing.value = false;
observing = false;
conversationId.value = (await api.post<{ id: string }>('/ai/conversations', {})).id;
await loadConversations();
clearCredentials();
replacePlan.value = false;
classId.value = '';
active.value = undefined;
messages.value = [];
attachments.value = [];
@@ -386,9 +476,10 @@ async function stopGeneration(): Promise<void> {
if (taskId.value) await aiApi.stopTask(taskId.value);
controller?.abort();
}
async function resumeTask(id: string): Promise<void> {
async function resumeTask(id: string, preserveHistory = false): Promise<void> {
if (busy.value || executing.value) return;
error.value = '';
const epoch = viewEpoch;
const saved = await aiApi.task(id);
taskId.value = id;
lastRequest = { text: saved.text };
@@ -399,7 +490,8 @@ async function resumeTask(id: string): Promise<void> {
state: 'done',
result: saved.result,
});
messages.value = [{ role: 'user', content: saved.text }, message];
if (preserveHistory) messages.value[messages.value.length - 1] = message;
else messages.value = [{ role: 'user', content: saved.text }, message];
active.value = saved.result;
clearCredentials();
if (saved.error) error.value = saved.error;
@@ -416,6 +508,7 @@ async function resumeTask(id: string): Promise<void> {
await observeTask(
id,
(event) => {
if (epoch !== viewEpoch) return;
if (event.type === 'status' && message.activity!.at(-1) !== event.message)
message.activity!.push(event.message);
if (event.type === 'message') message.content = event.text;
@@ -424,13 +517,16 @@ async function resumeTask(id: string): Promise<void> {
controller.signal,
),
);
if (epoch !== viewEpoch) return;
active.value = result;
message.result = result;
message.content = saved.state === 'executing' ? '任务已完成。' : result.message;
clearCredentials();
} catch (e) {
if (epoch !== viewEpoch) return;
if (!disposed && !controller.signal.aborted) error.value = failure(e);
} finally {
if (epoch !== viewEpoch) return;
message.state = error.value ? 'stopped' : 'done';
busy.value = false;
executing.value = false;
@@ -446,11 +542,8 @@ onMounted(async () => {
aiApi.capabilities(),
classApi.list().catch(() => []),
]);
taskHistory.value = await aiApi.tasks();
const latest =
taskHistory.value.find((item) => ['planning', 'executing'].includes(item.state)) ??
taskHistory.value[0];
if (latest) await resumeTask(latest.id);
await loadConversations();
if (conversations.value[0]) await openConversation(conversations.value[0].id);
} catch (e) {
error.value = failure(e);
}
@@ -481,21 +574,24 @@ onBeforeUnmount(() => {
</div>
</div>
<div class="agent-header-actions">
<el-button v-if="conversations.length >= 30" @click="olderConversations">更多对话</el-button>
<el-select
v-if="taskHistory.length"
:model-value="taskId"
placeholder="最近任务"
:disabled="busy || executing"
@change="resumeTask"
v-if="conversations.length"
:model-value="conversationId"
placeholder="对话历史"
:disabled="(busy || executing) && !observing"
@change="openConversation"
>
<el-option
v-for="item in taskHistory"
v-for="item in conversations"
:key="item.id"
:value="item.id"
:label="item.text.slice(0, 24)"
:label="item.title || '新对话'"
/>
</el-select>
<el-button :disabled="busy || executing || hashing" @click="newConversation">新对话</el-button>
<el-button :disabled="hashing || ((busy || executing) && !observing)" @click="newConversation">
新对话
</el-button>
<el-select
v-model="classId"
clearable
@@ -508,17 +604,37 @@ onBeforeUnmount(() => {
<el-button v-if="auth.can('ai:manage')" @click="$router.push('/ai-settings')">模型设置</el-button>
</div>
</header>
<el-checkbox v-if="pending" v-model="replacePlan">本轮明确替换当前待确认计划(历史记录保留)</el-checkbox>
<select
class="mobile-turn-select"
aria-label="跳转对话轮次"
:value="currentTurn"
@change="jumpTurn(Number(($event.target as HTMLSelectElement).value))"
>
<option v-for="(turn, index) in messages.filter((m) => m.role === 'user')" :key="index" :value="index">
第 {{ index + 1 }} 轮:{{ turn.content.slice(0, 16) }}
</option>
</select>
<nav class="turn-navigation" aria-label="对话轮次">
<button
v-for="(turn, index) in messages.filter((m) => m.role === 'user')"
:key="index"
:title="turn.content"
:aria-current="index === currentTurn ? 'step' : undefined"
:aria-label="`跳转第 ${index + 1} 轮:${turn.content}`"
@click="jumpTurn(index)"
>
<span>{{ index + 1 }}</span>
</button>
</nav>
<div
ref="conversation"
class="assistant-conversation"
aria-live="polite"
:aria-busy="busy || executing"
@scroll="
followScroll =
!conversation ||
conversation.scrollHeight - conversation.scrollTop - conversation.clientHeight < 100
"
@scroll="onConversationScroll"
>
<el-button v-if="messages.length >= 60" @click="olderTurns">加载更早轮次</el-button>
<div v-if="!messages.length" class="assistant-welcome">
<span class="agent-welcome-mark" aria-hidden="true">✦</span>
<h2>有什么可以帮你?</h2>
@@ -559,6 +675,38 @@ onBeforeUnmount(() => {
<li v-for="(activity, n) in message.activity" :key="n">{{ activity }}</li>
</ol>
</details>
<el-card
v-for="question in message.result?.questions || []"
:key="question.id"
class="assistant-question"
>
<strong>{{ question.text }}</strong>
<div class="question-options">
<el-button
v-for="option in question.options || []"
:key="option"
:disabled="busy"
@click="
text = question.text + ':' + option;
send();
"
>
{{ option }}
</el-button>
</div>
<small>也可以在下方输入框自由回答。</small>
</el-card>
<el-button
v-if="message.result?.planId && message.taskId"
:disabled="busy || executing"
@click="
active = message.result;
taskId = message.taskId!;
clearCredentials();
"
>
查看此轮计划
</el-button>
<p v-if="message.content">{{ message.content }}</p>
<span v-else-if="message.state === 'working'" class="agent-placeholder">
正在准备回复
@@ -716,9 +864,79 @@ onBeforeUnmount(() => {
</template>
<style scoped>
.mobile-turn-select {
display: none;
}
.turn-navigation button {
opacity: 0.45;
}
.turn-navigation button[aria-current='step'] {
opacity: 1;
}
@media (max-width: 600px) {
.mobile-turn-select {
display: block;
width: 100%;
margin: 8px 0;
max-width: 100%;
padding: 6px;
background: var(--el-bg-color);
color: var(--el-text-color-primary);
border: 1px solid var(--el-border-color);
}
.turn-navigation {
display: none !important;
}
}
.turn-navigation {
position: absolute;
right: 12px;
top: 100px;
display: flex;
flex-direction: column;
gap: 8px;
max-height: 60%;
overflow: auto;
z-index: 2;
}
.turn-navigation button {
width: 28px;
min-height: 24px;
border: 0;
background: transparent;
border-top: 3px solid var(--el-color-primary);
cursor: pointer;
}
.turn-navigation span {
font-size: 10px;
}
.question-options {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 12px 0;
}
.assistant-page {
position: relative;
}
.assistant-conversation {
padding-right: 44px;
}
@media (max-width: 600px) {
.turn-navigation {
right: 4px;
top: 150px;
max-height: 25%;
}
.assistant-conversation {
padding-right: 32px;
}
}
.assistant-page {
max-width: none;
padding: 0;
padding: 16px 24px;
display: flex;
flex-direction: column;
height: 100%;
@@ -738,7 +956,7 @@ onBeforeUnmount(() => {
text-align: center;
}
.assistant-welcome h2 {
font-size: 2em;
font-size: clamp(22px, 1.5em, 36px);
font-weight: 600;
}
.assistant-examples,
@@ -944,6 +1162,7 @@ details > summary {
@media (max-width: 720px) {
.assistant-page {
height: 100%;
padding: 16px;
}
.agent-header {
flex-wrap: wrap;
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { CoursewareFolders } from '@classhelper/ui';
import { countDates } from '@classhelper/ui';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { SOCKET_EVENTS } from '@classhelper/shared';
@@ -60,7 +61,11 @@ const canWrite = computed(() => auth.can('courseware:write'));
const folders = ref<CoursewareFolderDto[]>([]),
folderPath = ref(''),
folderFilter = ref('');
const grouping = ref<'date' | 'folder'>('date');
const grouping = ref<'date' | 'folder'>('folder');
const folderOwner = ref('');
watch(folderFilter, (value) => {
folderPath.value = value;
});
const teacher = ref('');
const teachers = computed(() => [...new Set(items.value.map((item) => item.teacher.name))]);
async function newFolder() {
@@ -69,7 +74,7 @@ async function newFolder() {
'输入文件夹名称,可用 / 创建多层分类,如 地理/必修一',
'新建文件夹',
);
const path = String(value ?? '').trim();
const path = [folderFilter.value, String(value ?? '').trim()].filter(Boolean).join('/');
if (!path) return;
await api.post('/courseware/folders', { path });
await refresh();
@@ -88,9 +93,10 @@ const dateSource = computed(() =>
(!query.value || `${item.name} ${item.teacher.name}`.includes(query.value)) &&
(!category.value || item.category === category.value) &&
(grouping.value !== 'folder' ||
!folderFilter.value ||
item.folderPath === folderFilter.value ||
item.folderPath?.startsWith(folderFilter.value + '/')) &&
((item.folderPath || '') === folderFilter.value &&
(folderOwner.value
? item.teacher.id === folderOwner.value
: new Set(items.value.map((i) => i.teacher.id)).size <= 1))) &&
(!teacher.value || item.teacher.name === teacher.value),
),
);
@@ -298,6 +304,13 @@ onMounted(() => void refresh());
</el-select>
<ch-date-picker v-model="date" :marks="dateMarks" value-format="YYYY-MM-DD" placeholder="归档日期" />
</div>
<CoursewareFolders
v-if="grouping === 'folder'"
v-model:path="folderFilter"
v-model:owner="folderOwner"
:items="items"
:folders="folders"
/>
<el-table :data="filtered" empty-text="暂无课件">
<el-table-column prop="name" label="文件名称" min-width="220" show-overflow-tooltip />
<el-table-column label="分类 / 归档位置" min-width="230">
+67 -22
View File
@@ -175,13 +175,19 @@ watch(
},
{ flush: 'sync' },
);
async function newLayout() {
async function newLayout(parentId?: string) {
if (!canCreateTime.value || saving.value) return;
const { value } = await ElMessageBox.prompt('输入时间表名称', '新时间表');
const result = await api.post<TimeLayoutDetailDto>('/time-layouts', {
name: value,
classId: classId.value || null,
points: [],
parentId,
points: parentId
? layouts.value
.find((l) => l.id === parentId)
?.points.filter((p) => !p.isAutoBreak)
.map((p) => ({ ...p, id: undefined })) || []
: [],
});
selectedLayout.value = result.id;
await load();
@@ -192,7 +198,9 @@ async function persistLayout(item: TimeLayoutDetailDto) {
throw new Error('时间点的结束时间必须晚于开始时间');
const result = await api.put<TimeLayoutDetailDto>(`/time-layouts/${item.id}`, {
...item,
points: item.points.map((p) => ({ ...p, id: p.id.startsWith('draft-') ? undefined : p.id || undefined })),
points: item.points
.filter((p) => !p.isAutoBreak)
.map((p) => ({ ...p, id: p.id.startsWith('draft-') ? undefined : p.id || undefined })),
});
layouts.value = layouts.value.map((p) => (p.id === result.id ? result : p));
layoutBaseline.value[result.id] = JSON.stringify(result);
@@ -606,15 +614,20 @@ function changeLayout(value: string) {
if (!plan.value) return;
const old = layouts.value.find((l) => l.id === plan.value!.timeLayoutId);
const next = layouts.value.find((l) => l.id === value);
// 时间点通过时间与类型匹配,不能把原外键带进另一张时间表。
plan.value.entries = plan.value.entries.flatMap((e) => {
const oldPoint = old?.points.find((p) => p.id === e.timeLayoutItemId);
const target = next?.points.find(
(p) =>
p.timeType === 'LESSON' && p.startTime === oldPoint?.startTime && p.endTime === oldPoint?.endTime,
);
return target ? [{ ...e, id: '', timeLayoutItemId: target.id }] : [];
const oldLessons = old?.points.filter((p) => p.timeType === 'LESSON') || [];
const nextLessons = next?.points.filter((p) => p.timeType === 'LESSON') || [];
const mapped = plan.value.entries.map((e) => {
const source = oldLessons.find((p) => p.id === e.timeLayoutItemId);
const target =
nextLessons.find((p) => source?.slotKey && p.slotKey === source.slotKey) ||
nextLessons[oldLessons.findIndex((p) => p.id === source?.id)];
return target ? { ...e, id: '', timeLayoutItemId: target.id } : undefined;
});
if (mapped.some((e) => !e)) {
ElMessage.warning('目标时间表节数不足,请先增加课时;原课程已保留。');
return;
}
plan.value.entries = mapped.filter((e): e is NonNullable<typeof e> => Boolean(e));
plan.value.timeLayoutId = value;
selectedLayout.value = value;
}
@@ -753,20 +766,46 @@ type GridRow = {
function pointKey(p: Pick<TimePointDto, 'startTime' | 'endTime' | 'timeType'>) {
return `${p.startTime}|${p.endTime}|${p.timeType}`;
}
const focusedDay = ref<number | null>(null);
function dayPoints(day: number) {
return layouts.value.find((l) => l.id === dayPlan(day)?.timeLayoutId)?.points || [];
}
function visualKey(p: TimePointDto, points: TimePointDto[]) {
return (
p.slotKey ||
(p.timeType === 'LESSON'
? `lesson-${points.filter((x) => x.timeType === 'LESSON').findIndex((x) => x.id === p.id) + 1}`
: pointKey(p))
);
}
const gridRows = computed(() => {
const rows = new Map<string, GridRow>();
for (const day of weekDays.value) {
const l = layouts.value.find((l) => l.id === dayPlan(day.day)?.timeLayoutId);
for (const p of l?.points || []) rows.set(pointKey(p), { ...p, key: pointKey(p) });
}
for (const day of weekDays.value)
for (const p of dayPoints(day.day)) {
const key = visualKey(p, dayPoints(day.day));
if (!rows.has(key)) rows.set(key, { ...p, key });
}
return [...rows.values()].sort(
(a, b) => a.startTime.localeCompare(b.startTime) || a.endTime.localeCompare(b.endTime),
);
});
function gridPoint(day: number, row: GridRow) {
return layouts.value
.find((l) => l.id === dayPlan(day)?.timeLayoutId)
?.points.find((p) => pointKey(p) === row.key);
const points = dayPoints(day);
return points.find((p) => visualKey(p, points) === row.key);
}
function rowTimes(row: GridRow) {
const byTime = new Map<string, string[]>();
for (const day of weekDays.value) {
if (focusedDay.value !== null && day.day !== focusedDay.value) continue;
const p = gridPoint(day.day, row);
if (!p) continue;
const key = `${p.startTime}–${p.endTime}`;
byTime.set(key, [...(byTime.get(key) || []), day.label]);
}
return [...byTime].map(([time, days]) => ({
time,
label: focusedDay.value === null && byTime.size > 1 ? days.join('、') : '',
}));
}
function gridEntry(day: number, row: GridRow) {
const point = gridPoint(day, row);
@@ -780,6 +819,7 @@ function selectCell(day: number, row?: GridRow) {
if (!p) return;
selectedPlan.value = p.id;
selectedDay.value = day;
focusedDay.value = day;
if (row) activePoint.value = gridPoint(day, row)?.id || '';
}
function isSelectedCell(day: number, row: GridRow) {
@@ -1107,7 +1147,7 @@ function selectPlanItem(id: string) {
</template>
</div>
<div v-if="viewMode === 'week'" class="week-view">
<div v-if="viewMode === 'week'" class="week-view" @keydown.esc="focusedDay = null">
<div class="week-scroll">
<table class="schedule-grid" aria-label="周课表">
<colgroup>
@@ -1116,7 +1156,9 @@ function selectPlanItem(id: string) {
</colgroup>
<thead>
<tr>
<th scope="col" class="time-heading">时间</th>
<th scope="col" class="time-heading">
<button class="text-command" @click="focusedDay = null">时间(清除选择)</button>
</th>
<th
v-for="day in weekDays"
:key="day.day"
@@ -1157,8 +1199,10 @@ function selectPlanItem(id: string) {
:class="{ 'non-lesson-row': row.timeType !== 'LESSON' }"
>
<th scope="row" class="time-cell">
<span>{{ row.startTime }}</span>
<small v-if="row.timeType !== 'DIVIDER'">{{ row.endTime }}</small>
<template v-for="time in rowTimes(row)" :key="time.time">
<span>{{ time.time }}</span>
<small v-if="time.label">{{ time.label }}</small>
</template>
</th>
<td
v-for="day in weekDays"
@@ -1449,6 +1493,7 @@ function selectPlanItem(id: string) {
:plan-count="layoutPlanCount"
@select-layout="selectedLayout = $event"
@create="newLayout"
@create-child="newLayout($event)"
@clone="cloneLayout"
@save="saveLayout"
@refresh="refresh"
+39 -2
View File
@@ -13,10 +13,12 @@
* `classId` 留空 = 全校默认;某个班有自己的配置时优先用它。
*/
import { useAuthStore } from '@/stores/auth';
import { computed, onMounted, ref } from 'vue';
import { computed, onMounted, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
getMaxTermWeeks,
buildAutoTermWeeks,
shiftDayKey,
validateTermWeeks,
isDayKey,
type ClassDto,
@@ -97,7 +99,7 @@ async function autoGenerate(): Promise<void> {
...(scope.value ? {} : { maxTermWeeks: maxTermWeeks.value }),
classId: scope.value || null,
termStartDate: termStartDate.value,
maxWeek: term.value?.maxWeek ?? getMaxTermWeeks(),
maxWeek: scope.value ? term.value?.maxWeek : maxTermWeeks.value,
});
term.value = result;
weeks.value = result.weeks.map((item) => ({ ...item }));
@@ -107,7 +109,42 @@ async function autoGenerate(): Promise<void> {
}
}
watch(maxTermWeeks, (maximum, previous) => {
if (
scope.value ||
!term.value ||
(maximum === getMaxTermWeeks(term.value.maxTermWeeks) && previous === maximum)
)
return;
const last = weeks.value.at(-1);
if (!last) {
if (isDayKey(termStartDate.value)) weeks.value = buildAutoTermWeeks(termStartDate.value, maximum);
return;
}
if (maximum > (last.weekNumber ?? 0) && isDayKey(last.endDate)) {
for (
let n = last.weekNumber + 1, start = shiftDayKey(last.endDate, 1);
n <= maximum;
n++, start = shiftDayKey(start, 7)
) {
weeks.value.push({ weekNumber: n, startDate: start, endDate: shiftDayKey(start, 6), note: '' });
}
}
});
async function save(): Promise<void> {
const removed = weeks.value.filter((w) => w.weekNumber > maxTermWeeks.value);
if (!scope.value && removed.length) {
try {
await ElMessageBox.confirm(
`将移除第 ${removed.map((w) => w.weekNumber).join('、')} 周日期区间,确认保存?`,
'缩短学期',
);
} catch {
return;
}
weeks.value = weeks.value.filter((w) => w.weekNumber <= maxTermWeeks.value);
}
if (saving.value) return;
const errors = validateTermWeeks(weeks.value);
if (!isDayKey(termStartDate.value)) errors.unshift('请填写有效的学期开始日期');