chore(release): 1.3.3 发布并退役旧联动

This commit is contained in:
LoveChengke committed 2026-10-17 03:06:46 +08:00
1 parent b7cdc7c9ea
commit c0ebf88138
184 files changed
+5450 -11705

No files matched your search

@@ -102,14 +102,6 @@ onMounted(async () => {
bootText.value = '正在恢复登录状态...';
const session = await auth.restore();
// 通知显示位置:先用本地配置兜底(断网也要按上次的选择决定本机弹不弹),
// 登录态就绪后再向服务器对齐一次(服务端才是单一事实来源)
const storedConfig = await window.desktop?.getConfig?.();
if (storedConfig?.notificationChannel) {
appStore.applyLocalNotificationChannel(storedConfig.notificationChannel);
}
void appStore.loadNotificationChannel(auth.classId);
// 连通性探测与健康轮询放到后台,不阻塞进入界面(离线时也能立刻看到缓存数据)
void appStore.init(session.serverUrl);
@@ -2,7 +2,6 @@ import {
API_PATHS,
type ClassDetailDto,
type ClassDto,
type ClassIslandNotificationChannel,
type CourseDto,
type ExamDto,
type ExamRankingDto,
@@ -47,36 +46,6 @@ export const classApi = {
detail: (id: string): Promise<ClassDetailDto> => api.get(`${API_PATHS.classes}/${id}`),
};
/**
* 通知显示位置(both / client / classisland)。
*
* 由**这台教室机器自己**决定"提醒弹在 ClassHelper 还是 ClassIsland":
* 本地存一份用于本机的弹窗/上岛判断,同时写回班级记录,服务端据此决定要不要推 ClassIsland。
*/
export const classChannelApi = {
get: (classId: string): Promise<{ notificationChannel: ClassIslandNotificationChannel }> =>
api.get(`${API_PATHS.classes}/${classId}/notification-channel`),
set: (
classId: string,
notificationChannel: ClassIslandNotificationChannel,
): Promise<{ notificationChannel: ClassIslandNotificationChannel }> =>
api.patch(`${API_PATHS.classes}/${classId}/notification-channel`, { notificationChannel }),
};
/** 本班 ClassIsland 联动状态(教室客户端「设置 → ClassIsland 联动」展示) */
export const classIslandStatusApi = {
get: (
classId: string,
): Promise<{
connected: boolean;
deviceName: string | null;
deviceCount: number;
lastSeenAt: string | null;
pluginVersion: string | null;
classIslandVersion: string | null;
}> => api.get(`${API_PATHS.classes}/${classId}/classisland-status`),
};
export const scheduleApi = {
list: (params: { classId?: string; week?: number }): Promise<ScheduleDto[]> =>
api.get(API_PATHS.schedules, params),
@@ -151,13 +120,11 @@ export const gradeApi = {
/**
* ClassHelper 班级端设置:「是否允许按学号查询本班学生成绩明细」。
* 与通知显示位置同一套模式 —— 由教室机器自己决定,教师/管理员在 Web 端也能改。
* 教师/管理员在 Web 端控制,教室机器只读取当前状态。
*/
export const classGradeQueryApi = {
get: (classId: string): Promise<{ studentGradeQueryEnabled: boolean }> =>
api.get(`${API_PATHS.classes}/${classId}/student-grade-query`),
set: (classId: string, enabled: boolean): Promise<{ studentGradeQueryEnabled: boolean }> =>
api.patch(`${API_PATHS.classes}/${classId}/student-grade-query`, { enabled }),
};
export const dashboardApi = {
+55 -12
View File
@@ -1,3 +1,5 @@
import { getCacheScope, scopedKey } from './scope.js';
/**
* IndexedDB 缓存层(无第三方依赖)。
*
@@ -37,7 +39,8 @@ let databasePromise: Promise<IDBDatabase> | null = null;
function openDatabase(): Promise<IDBDatabase> {
if (databasePromise) return databasePromise;
databasePromise = new Promise<IDBDatabase>((resolve, reject) => {
let failed = false;
const opening = new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onupgradeneeded = () => {
@@ -49,12 +52,36 @@ function openDatabase(): Promise<IDBDatabase> {
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error ?? new Error('IndexedDB 打开失败'));
request.onblocked = () => reject(new Error('IndexedDB 被其它窗口占用'));
request.onsuccess = () => {
const db = request.result;
if (failed) {
db.close();
return;
}
const reset = (): void => {
if (databasePromise === opening) databasePromise = null;
};
db.onversionchange = () => {
db.close();
reset();
};
db.onclose = reset;
resolve(db);
};
request.onerror = () => {
failed = true;
reject(request.error ?? new Error('IndexedDB 打开失败'));
};
request.onblocked = () => {
failed = true;
reject(new Error('IndexedDB 被其它窗口占用'));
};
});
return databasePromise;
databasePromise = opening;
void opening.catch(() => {
if (databasePromise === opening) databasePromise = null;
});
return opening;
}
function runRequest<T>(
@@ -67,7 +94,8 @@ function runRequest<T>(
new Promise<T>((resolve, reject) => {
const transaction = db.transaction(store, mode);
const request = action(transaction.objectStore(store));
request.onsuccess = () => resolve(request.result as T);
transaction.oncomplete = () => resolve(request.result as T);
transaction.onabort = () => reject(transaction.error ?? new Error('IndexedDB 事务已中止'));
request.onerror = () => reject(request.error ?? new Error('IndexedDB 操作失败'));
}),
);
@@ -89,14 +117,28 @@ function toPlain<T>(value: T): T {
}
}
export async function cacheSet<T>(store: CacheStore, key: string, value: T): Promise<void> {
const record: CacheRecord<T> = { key, value: toPlain(value), updatedAt: Date.now() };
export async function cacheSet<T>(
store: CacheStore,
key: string,
value: T,
scope = getCacheScope(),
): Promise<void> {
const record: CacheRecord<T> = {
key: store === 'profile' ? key : scopedKey(key, scope),
value: toPlain(value),
updatedAt: Date.now(),
};
await runRequest<IDBValidKey>(store, 'readwrite', (objectStore) => objectStore.put(record));
}
export function cacheGet<T>(store: CacheStore, key: string): Promise<CacheRecord<T> | null> {
export function cacheGet<T>(
store: CacheStore,
key: string,
scope = getCacheScope(),
): Promise<CacheRecord<T> | null> {
const resolvedKey = store === 'profile' ? key : scopedKey(key, scope);
return runRequest<CacheRecord<T> | undefined>(store, 'readonly', (objectStore) =>
objectStore.get(key),
objectStore.get(resolvedKey),
).then((record) => record ?? null);
}
@@ -105,7 +147,8 @@ export function cacheList<T>(store: CacheStore): Promise<Array<CacheRecord<T>>>
}
export async function cacheRemove(store: CacheStore, key: string): Promise<void> {
await runRequest<undefined>(store, 'readwrite', (objectStore) => objectStore.delete(key));
const resolvedKey = store === 'profile' ? key : scopedKey(key);
await runRequest<undefined>(store, 'readwrite', (objectStore) => objectStore.delete(resolvedKey));
}
export async function cacheClearStore(store: CacheStore): Promise<void> {
+9 -2
View File
@@ -1,4 +1,5 @@
import { cacheGet, cacheSet, type CacheStore } from './db.js';
import { getCacheScope } from './scope.js';
export interface CachedFetchResult<T> {
data: T;
@@ -23,13 +24,19 @@ export async function fetchWithCache<T>(
loader: () => Promise<T>,
fallback: T,
): Promise<CachedFetchResult<T>> {
const scope = getCacheScope();
try {
const data = await loader();
await cacheSet(store, key, data);
if (scope !== getCacheScope())
return { data: fallback, fromCache: false, updatedAt: null, error: '会话已切换' };
// 网络成功但本地磁盘不可用时,仍返回刚获取的数据。
await cacheSet(store, key, data, scope).catch(() => undefined);
return { data, fromCache: false, updatedAt: Date.now(), error: null };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
const cached = await cacheGet<T>(store, key).catch(() => null);
const cached = await cacheGet<T>(store, key, scope).catch(() => null);
if (scope !== getCacheScope())
return { data: fallback, fromCache: false, updatedAt: null, error: '会话已切换' };
if (cached) {
return { data: cached.value, fromCache: true, updatedAt: cached.updatedAt, error: message };
}
+22
View File
@@ -0,0 +1,22 @@
let activeScope = 'anonymous';
const listeners = new Set<() => void>();
/** 同一台机器可切换服务端与班级,两者都必须纳入缓存命名空间。 */
export function setCacheScope(server: string, identity: string): void {
const next = `${encodeURIComponent(server.replace(/\/+$/, ''))}@${encodeURIComponent(identity)}`;
if (next === activeScope) return;
activeScope = next;
for (const listener of listeners) listener();
}
export function getCacheScope(): string {
return activeScope;
}
export function scopedKey(key: string, scope = activeScope): string {
return `${scope}::${key}`;
}
export function onCacheScopeChanged(listener: () => void): void {
listeners.add(listener);
}
export function profileCacheKey(server: string, username: string): string {
return `${encodeURIComponent(server.replace(/\/+$/, ''))}@${encodeURIComponent(username)}::profile`;
}
+31 -6
View File
@@ -1,5 +1,27 @@
import { cacheGet, cacheRemove, cacheSet, cacheStats } from './db.js';
import { fetchWithCache } from './index.js';
import { setCacheScope } from './scope.js';
export async function cacheIsolationSelfTest(): Promise<SmokeCheckResult> {
const key = `scope-check-${Date.now()}`;
try {
setCacheScope('http://scope-a.invalid', 'class-a');
await cacheSet('grades', key, ['班级甲']);
setCacheScope('http://scope-a.invalid', 'class-b');
if (await cacheGet('grades', key)) return { ok: false, detail: '跨班级读到了缓存' };
setCacheScope('http://scope-b.invalid', 'class-a');
if (await cacheGet('grades', key)) return { ok: false, detail: '跨服务端读到了缓存' };
setCacheScope('http://scope-a.invalid', 'class-a');
const own = await cacheGet<string[]>('grades', key);
await cacheRemove('grades', key);
return { ok: own?.value[0] === '班级甲', detail: '换班和换服务端均隔离,原班缓存仍可读取' };
} finally {
setCacheScope('', 'anonymous');
}
}
/** 联网自检与造数、清理始终使用同一服务端。 */
let smokeServerUrl = 'http://127.0.0.1:4000';
export interface SmokeCheckResult {
ok: boolean;
@@ -208,7 +230,7 @@ async function seedSmokeContent(
need: { homework: boolean; notification: boolean },
): Promise<SmokeCheckResult> {
if (!classId) return { ok: false, detail: '缺少班级,无法自建数据' };
const serverUrl = 'http://127.0.0.1:4000';
const serverUrl = smokeServerUrl;
const stamp = `自检 ${new Date().toLocaleTimeString('zh-CN')}`;
try {
@@ -275,7 +297,7 @@ async function cleanupTemporaryContent(): Promise<string> {
if (!temporaryContent) return '';
const { token, homeworks, notifications } = temporaryContent;
temporaryContent = null;
const serverUrl = 'http://127.0.0.1:4000';
const serverUrl = smokeServerUrl;
const removals = [
...homeworks.map((id) => `/api/homeworks/${id}`),
...notifications.map((id) => `/api/notifications/${id}`),
@@ -298,6 +320,7 @@ async function cleanupTemporaryContent(): Promise<string> {
export async function onlineScenario(credentials?: {
code: string;
password: string;
serverUrl?: string;
}): Promise<SmokeCheckResult> {
const [{ useAuthStore }, { useAppStore }, { useRealtimeStore }, api, cache] = await Promise.all([
import('../stores/auth.js'),
@@ -311,7 +334,8 @@ export async function onlineScenario(credentials?: {
const appStore = useAppStore();
const realtime = useRealtimeStore();
const serverUrl = 'http://127.0.0.1:4000';
const serverUrl = credentials?.serverUrl ?? smokeServerUrl;
smokeServerUrl = serverUrl;
const detail: string[] = [];
try {
@@ -441,7 +465,7 @@ export async function islandRealtimeScenario(): Promise<{
import('../island/bridge.js'),
]);
const auth = useAuthStore();
const serverUrl = 'http://127.0.0.1:4000';
const serverUrl = smokeServerUrl;
const classId = auth.classId ?? null;
if (!classId) return { ok: false, detail: '当前学生没有班级,无法投递通知' };
@@ -499,7 +523,7 @@ export async function islandRealtimeCleanup(
teacherToken: string,
): Promise<SmokeCheckResult> {
try {
const response = await fetch(`http://127.0.0.1:4000/api/notifications/${notificationId}`, {
const response = await fetch(`${smokeServerUrl}/api/notifications/${notificationId}`, {
method: 'DELETE',
headers: { authorization: `Bearer ${teacherToken}` },
});
@@ -544,7 +568,7 @@ export async function scheduleTimelineSelfTest(): Promise<SmokeCheckResult> {
import('../router/index.js'),
]);
const auth = useAuthStore();
const serverUrl = 'http://127.0.0.1:4000';
const serverUrl = smokeServerUrl;
const classId = auth.classId ?? null;
if (!classId) return { ok: false, detail: '当前学生没有班级,无法构造课表' };
@@ -1172,6 +1196,7 @@ export async function aboutPageSelfTest(): Promise<SmokeCheckResult> {
export function registerSmokeHooks(): void {
window.__classhelperSmoke__ = {
cacheSelfTest,
cacheIsolationSelfTest,
offlineScenario,
layoutNavigationSelfTest,
onlineScenario,
@@ -102,7 +102,7 @@ function finish(): void {
}
function onKeydown(event: KeyboardEvent): void {
if (event.key === 'Escape') finish();
if (onboarding.visible && event.key === 'Escape') finish();
}
if (typeof window !== 'undefined') {
window.addEventListener('keydown', onKeydown);
@@ -154,9 +154,7 @@ onUnmounted(() => {
</div>
<div class="onboarding-actions">
<el-button v-if="!isFirst" data-action="prev" @click="goPrev">上一步</el-button>
<el-button v-if="!isLast" type="primary" data-action="next" @click="goNext">
下一步
</el-button>
<el-button v-if="!isLast" type="primary" data-action="next" @click="goNext">下一步</el-button>
<el-button v-else type="primary" data-action="finish" @click="finish">开始使用</el-button>
</div>
</div>
@@ -250,7 +248,7 @@ onUnmounted(() => {
margin: 0 0 8px;
font-size: 13px;
line-height: 1.8;
color: var(--ch-text-regular, #606266);
color: var(--ch-text-secondary);
}
.onboarding-foot {
@@ -0,0 +1,12 @@
import { ElMessageBox } from 'element-plus';
/** 取消是正常交互;真实异常继续交给调用方处理。 */
export async function confirmAction(...args: Parameters<typeof ElMessageBox.confirm>): Promise<boolean> {
try {
await ElMessageBox.confirm(...args);
return true;
} catch (reason) {
if (reason === 'cancel' || reason === 'close') return false;
throw reason;
}
}
@@ -1,3 +1,4 @@
import { watch, type WatchStopHandle } from 'vue';
import {
SOCKET_EVENTS,
resolveClassStatus,
@@ -8,6 +9,7 @@ import {
} from '@classhelper/shared';
import { notificationApi, scheduleApi } from '../api/index.js';
import { fetchWithCache } from '../cache/index.js';
import { getCacheScope } from '../cache/scope.js';
import { clearOfflineSince, readOfflineSince, useAppStore } from '../stores/app.js';
import { useAuthStore } from '../stores/auth.js';
import { useNotificationStore } from '../stores/notifications.js';
@@ -30,6 +32,9 @@ let currentPeriod: ClassPeriod | null = null;
let inClass = false;
let tickTimer: ReturnType<typeof setInterval> | null = null;
let refreshTimer: ReturnType<typeof setInterval> | null = null;
let stopWeekWatch: WatchStopHandle | null = null;
let scheduleRequest = 0;
let scheduleWeek = 1;
/** 供通知投递时读取:当前是否上课 + 本节课结束时间 */
export function getIslandClassContext(): { inClass: boolean; currentPeriodEnd: string | null } {
@@ -45,21 +50,28 @@ export async function refreshIslandSchedules(): Promise<void> {
const appStore = useAppStore();
const auth = useAuthStore();
if (!auth.token) return;
const scope = getCacheScope();
const classId = auth.classId ?? undefined;
await appStore.refreshTerm(classId);
if (scope !== getCacheScope() || !auth.token) return;
const request = ++scheduleRequest;
const week = appStore.currentWeek;
const result = await fetchWithCache<ScheduleDto[]>(
'schedules',
`week:${week}`,
() => scheduleApi.list({ classId: auth.classId ?? undefined, week }),
() => scheduleApi.list({ classId, week }),
[],
);
if (scope !== getCacheScope() || request !== scheduleRequest) return;
if (result.error && !result.updatedAt) return;
schedules = result.data;
scheduleWeek = week;
recomputeClassState(true);
}
function recomputeClassState(force = false): void {
const appStore = useAppStore();
const status = resolveClassStatus(schedules, new Date(), appStore.currentWeek);
const status = resolveClassStatus(schedules, new Date(), scheduleWeek);
const nextInClass = status.inClass;
currentPeriod = status.current;
@@ -313,6 +325,12 @@ function onScheduleUpdated(): void {
export function startIslandBridge(): void {
if (tickTimer) return;
stopWeekWatch = watch(
() => useAppStore().currentWeek,
() => {
void refreshIslandSchedules();
},
);
void refreshIslandSchedules().catch(() => undefined);
@@ -338,6 +356,9 @@ export function stopIslandBridge(): void {
if (refreshTimer) clearInterval(refreshTimer);
tickTimer = null;
refreshTimer = null;
scheduleRequest += 1;
stopWeekWatch?.();
stopWeekWatch = null;
useRealtimeStore().off(SOCKET_EVENTS.scheduleUpdated, onScheduleUpdated);
schedules = [];
@@ -1,7 +1,8 @@
<script setup lang="ts">
import { confirmAction } from '../composables/confirm.js';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, type MenuInstance } from 'element-plus';
import { ElMessage, type MenuInstance } from 'element-plus';
import { SOCKET_EVENTS, type NotificationDto } from '@classhelper/shared';
import { startIslandBridge, stopIslandBridge } from '../island/bridge.js';
import { useThemeReveal } from '../composables/motion.js';
@@ -354,7 +355,7 @@ const connectionText = computed(() => {
});
async function handleLogout(): Promise<void> {
await ElMessageBox.confirm('确认退出当前账号?离线缓存会保留。', '退出登录', { type: 'warning' });
if (!(await confirmAction('确认退出当前账号?离线缓存会保留。', '退出登录', { type: 'warning' }))) return;
realtime.disconnect();
await auth.logout();
ElMessage.success('已退出登录');
@@ -370,6 +371,10 @@ async function handleLogout(): Promise<void> {
function onNotification(payload: unknown): void {
void notifications.pushRealtime(payload as NotificationDto);
}
function onNotificationDeleted(payload: unknown): void {
void notifications.removeRealtime((payload as { id: string }).id);
window.desktop?.islandRemoveNotification((payload as { id: string }).id);
}
/** 服务器从不可达恢复为可达:自动同步一次(联网后自动同步) */
function onRecovered(): void {
@@ -378,9 +383,10 @@ function onRecovered(): void {
}
onMounted(async () => {
realtime.on(SOCKET_EVENTS.notificationNew, onNotification);
realtime.on(SOCKET_EVENTS.notificationDeleted, onNotificationDeleted);
await notifications.load().catch(() => undefined);
await notifications.refreshUnreadCount();
realtime.on(SOCKET_EVENTS.notificationNew, onNotification);
appStore.onServerRecovered(onRecovered);
// 灵动岛桥接跟着"已登录布局"的生命周期走:这样退出登录会随布局卸载而停止,
// 重新登录(或换班登录)时又会重新启动,不会拿旧课表算上课状态。
@@ -389,6 +395,7 @@ onMounted(async () => {
onUnmounted(() => {
realtime.off(SOCKET_EVENTS.notificationNew, onNotification);
realtime.off(SOCKET_EVENTS.notificationDeleted, onNotificationDeleted);
appStore.offServerRecovered(onRecovered);
stopIslandBridge();
});
@@ -410,7 +417,10 @@ onUnmounted(() => {
data-test="sidebar-toggle"
@click="ui.toggleSidebar()"
>
<el-icon :size="16"><Expand v-if="ui.sidebarCollapsed" /><Fold v-else /></el-icon>
<el-icon :size="16">
<Expand v-if="ui.sidebarCollapsed" />
<Fold v-else />
</el-icon>
</button>
<!-- 品牌区在折叠时**不是 v-if 删掉**,而是靠 CSS 收宽度 + 淡出:
v-if 会在动画中途把节点直接摘掉,看上去是"啪"地一跳;收放要连续就得让它们一直在。 -->
@@ -422,11 +432,7 @@ onUnmounted(() => {
把"跟着菜单滚出视口"的底片裁掉,不让它盖到品牌区/页脚上。
两层都 pointer-events:none —— 底片盖在菜单项上,否则会把点击吃掉。 -->
<div class="nav-indicator-clip" :style="clipStyle" aria-hidden="true">
<div
class="nav-indicator"
:class="{ 'is-following': indicatorFollowing }"
:style="indicatorStyle"
/>
<div class="nav-indicator" :class="{ 'is-following': indicatorFollowing }" :style="indicatorStyle" />
</div>
<el-menu
ref="menuRef"
@@ -495,7 +501,10 @@ onUnmounted(() => {
:aria-label="ui.theme === 'dark' ? '切换到浅色模式' : '切换到深色模式'"
@click="handleThemeToggle"
>
<el-icon><Sunny v-if="ui.theme === 'dark'" /><Moon v-else /></el-icon>
<el-icon>
<Sunny v-if="ui.theme === 'dark'" />
<Moon v-else />
</el-icon>
</el-button>
</el-tooltip>
<el-dropdown trigger="click">
@@ -1,15 +1,12 @@
import { computed, ref } from 'vue';
import { defineStore } from 'pinia';
import {
DEFAULT_CLASSISLAND_NOTIFICATION_CHANNEL,
STORAGE_KEYS,
formatDate,
type ClassIslandNotificationChannel,
} from '@classhelper/shared';
import { STORAGE_KEYS, formatDate } from '@classhelper/shared';
import { pingHealth, setApiBaseUrl, setReachabilityReporter } from '../api/http.js';
import { classChannelApi } from '../api/index.js';
import { cacheClearAll, cacheStats, type CacheStoreStat } from '../cache/db.js';
import { DEFAULT_SERVER, normalizeServerUrl } from '../config.js';
import { dashboardApi } from '../api/index.js';
import { fetchWithCache } from '../cache/index.js';
import { getCacheScope, onCacheScopeChanged } from '../cache/scope.js';
type RecoveryHandler = () => void;
@@ -70,13 +67,26 @@ export const useAppStore = defineStore('app', () => {
const currentWeek = ref(1);
const maxWeek = ref(20);
const initialized = ref(false);
/**
* 通知显示位置:这台教室机器把提醒弹在哪个端。
*
* 单一事实来源是**班级记录**(服务端),本地这份只是缓存:断网时也要能按上次的选择
* 决定本机弹不弹,所以启动时先读本地配置、登录后再向服务器对齐一次。
*/
const notificationChannel = ref<ClassIslandNotificationChannel>(DEFAULT_CLASSISLAND_NOTIFICATION_CHANNEL);
let termRequest = 0;
onCacheScopeChanged(() => {
currentWeek.value = 1;
maxWeek.value = 20;
termRequest += 1;
clearOfflineSince();
});
/** 当前教学周的单一写入入口,课表页与灵动岛共用。 */
async function refreshTerm(classId?: string): Promise<void> {
const request = ++termRequest;
const scope = getCacheScope();
const result = await fetchWithCache('classes', 'term', () => dashboardApi.term(classId), {
currentWeek: 1,
maxWeek: 20,
});
if (request !== termRequest || scope !== getCacheScope() || (result.error && !result.updatedAt)) return;
currentWeek.value = result.data.currentWeek;
maxWeek.value = result.data.maxWeek;
}
const offline = computed(() => !serverReachable.value);
const lastSyncText = computed(() => (lastSyncAt.value ? formatDate(lastSyncAt.value, true) : '尚未同步'));
@@ -178,53 +188,6 @@ export const useAppStore = defineStore('app', () => {
void refreshCacheStats();
}
/* ------------------------------------------------------------ 通知显示位置 */
/** 启动时用本地配置兜底(此时可能还没登录/断网) */
function applyLocalNotificationChannel(value: ClassIslandNotificationChannel): void {
notificationChannel.value = value;
}
/**
* 向服务器对齐显示位置。
* 登录后调用:以服务端为准(多台机器/老师改过之后,本地缓存可能已经过期)。
*/
async function loadNotificationChannel(classId: string | null): Promise<void> {
if (!classId) return;
try {
const result = await classChannelApi.get(classId);
notificationChannel.value = result.notificationChannel;
await window.desktop?.saveConfig({ notificationChannel: result.notificationChannel });
} catch {
// 离线/无权限:保留本地值,不影响展示
}
}
/**
* 改显示位置:先落本地(立刻生效),再写回班级记录。
* 服务端写失败时返回 false,由设置页提示"已保存在本机,联网后请重试"。
*/
async function setNotificationChannel(
classId: string | null,
value: ClassIslandNotificationChannel,
): Promise<boolean> {
notificationChannel.value = value;
await window.desktop?.saveConfig({ notificationChannel: value });
if (!classId) return false;
try {
const result = await classChannelApi.set(classId, value);
notificationChannel.value = result.notificationChannel;
return true;
} catch {
return false;
}
}
/** 本次提醒是否要在本机弹(弹窗 + 灵动岛);"只在 ClassIsland 上弹"时为 false */
function shouldPopupLocally(): boolean {
return notificationChannel.value !== 'classisland';
}
return {
serverUrl,
serverReachable,
@@ -236,17 +199,13 @@ export const useAppStore = defineStore('app', () => {
currentWeek,
maxWeek,
initialized,
notificationChannel,
init,
ping,
applyServerUrl,
applyLocalNotificationChannel,
loadNotificationChannel,
setNotificationChannel,
shouldPopupLocally,
refreshCacheStats,
clearCache,
markSynced,
refreshTerm,
onServerRecovered,
offServerRecovered,
stopHealthPolling,
@@ -5,8 +5,9 @@ import { authApi } from '../api/index.js';
import { setApiBaseUrl, setTokenProvider } from '../api/http.js';
import { cacheGet, cacheSet } from '../cache/db.js';
import { normalizeServerUrl } from '../config.js';
const PROFILE_KEY = 'me';
import { profileCacheKey, setCacheScope } from '../cache/scope.js';
let profileKey = '';
let sessionServer = '';
/**
* 登录态。
@@ -58,10 +59,13 @@ export const useAuthStore = defineStore('auth', () => {
loading.value = true;
try {
const payload: LoginResponse = await authApi.classLogin({ code, password });
profileKey = profileCacheKey(normalized, code);
sessionServer = normalized;
setCacheScope(normalized, payload.user.classId ?? payload.user.id);
applyToken(payload.token);
user.value = payload.user;
offlineSession.value = false;
await cacheSet('profile', PROFILE_KEY, user.value);
await cacheSet('profile', profileKey, user.value).catch(() => undefined);
await persistSession(normalized, code, payload.token);
} finally {
loading.value = false;
@@ -90,8 +94,11 @@ export const useAuthStore = defineStore('auth', () => {
}
}
const cachedProfile = await cacheGet<SessionUser>('profile', PROFILE_KEY).catch(() => null);
profileKey = profileCacheKey(serverUrl, username);
sessionServer = serverUrl;
const cachedProfile = await cacheGet<SessionUser>('profile', profileKey).catch(() => null);
if (cachedProfile) user.value = cachedProfile.value;
setCacheScope(serverUrl, user.value?.classId ?? user.value?.id ?? `unresolved:${username}`);
// 服务器刷新放到后台,绝不阻塞启动:离线时也能立刻进入界面看缓存数据
if (token.value) void refreshProfile();
@@ -102,11 +109,14 @@ export const useAuthStore = defineStore('auth', () => {
/** 后台刷新个人资料;服务器不可达时保持缓存资料与离线会话标记 */
async function refreshProfile(): Promise<void> {
if (!token.value) return;
const requestedToken = token.value;
try {
const profile = await authApi.me();
if (token.value !== requestedToken) return;
user.value = profile;
setCacheScope(sessionServer, profile.classId ?? profile.id);
offlineSession.value = false;
await cacheSet('profile', PROFILE_KEY, profile);
await cacheSet('profile', profileKey, profile).catch(() => undefined);
} catch {
offlineSession.value = Boolean(user.value);
}
@@ -120,6 +130,7 @@ export const useAuthStore = defineStore('auth', () => {
}
applyToken(null);
user.value = null;
setCacheScope('', 'anonymous');
offlineSession.value = false;
if (window.desktop) await window.desktop.saveConfig({ token: null });
}
@@ -5,6 +5,7 @@ import { notificationApi } from '../api/index.js';
import { cacheSet } from '../cache/db.js';
import { fetchWithCache } from '../cache/index.js';
import { useAppStore } from './app.js';
import { getCacheScope, onCacheScopeChanged } from '../cache/scope.js';
/**
* 通知状态:列表 + 未读数。
@@ -18,6 +19,23 @@ export const useNotificationStore = defineStore('notifications', () => {
const fromCache = ref(false);
const updatedAt = ref<number | null>(null);
const error = ref<string | null>(null);
let requestId = 0;
let revision = 0;
const changes = new Map<string, { revision: number; value: NotificationDto | null }>();
onCacheScopeChanged(() => {
requestId += 1;
revision = 0;
changes.clear();
items.value = [];
unreadCount.value = 0;
loading.value = false;
fromCache.value = false;
updatedAt.value = null;
error.value = null;
});
function changed(id: string, value: NotificationDto | null): void {
changes.set(id, { revision: ++revision, value });
}
const unreadItems = computed(() => items.value.filter((item) => !item.read));
@@ -34,6 +52,9 @@ export const useNotificationStore = defineStore('notifications', () => {
}
async function load(): Promise<void> {
const request = ++requestId;
const scope = getCacheScope();
const startedAt = revision;
loading.value = true;
try {
const result = await fetchWithCache<NotificationDto[]>(
@@ -42,14 +63,23 @@ export const useNotificationStore = defineStore('notifications', () => {
() => notificationApi.list(),
[],
);
items.value = result.data;
if (request !== requestId || scope !== getCacheScope()) return;
const merged = new Map(result.data.map((item) => [item.id, item]));
for (const [id, change] of changes) {
if (change.revision <= startedAt) continue;
if (change.value) merged.set(id, change.value);
else merged.delete(id);
}
items.value = [...merged.values()].sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
changes.clear();
fromCache.value = result.fromCache;
updatedAt.value = result.updatedAt;
error.value = result.error;
recount();
await persist();
if (!result.fromCache) useAppStore().markSynced();
} finally {
loading.value = false;
if (request === requestId) loading.value = false;
}
}
@@ -57,6 +87,14 @@ export const useNotificationStore = defineStore('notifications', () => {
async function pushRealtime(payload: NotificationDto): Promise<void> {
if (items.value.some((item) => item.id === payload.id)) return;
items.value = [{ ...payload, read: false }, ...items.value];
changed(payload.id, items.value[0]!);
recount();
await persist();
}
async function removeRealtime(id: string): Promise<void> {
items.value = items.value.filter((item) => item.id !== id);
changed(id, null);
recount();
await persist();
}
@@ -67,6 +105,7 @@ export const useNotificationStore = defineStore('notifications', () => {
if (target) {
target.read = true;
target.readAt = new Date().toISOString();
changed(id, { ...target });
}
recount();
await persist();
@@ -76,6 +115,7 @@ export const useNotificationStore = defineStore('notifications', () => {
const result = await notificationApi.markAllRead();
const now = new Date().toISOString();
items.value = items.value.map((item) => ({ ...item, read: true, readAt: item.readAt ?? now }));
for (const item of items.value) changed(item.id, item);
recount();
await persist();
return result.marked;
@@ -100,6 +140,7 @@ export const useNotificationStore = defineStore('notifications', () => {
error,
load,
pushRealtime,
removeRealtime,
markRead,
markAllRead,
refreshUnreadCount,
@@ -12,7 +12,6 @@ import {
} from '@classhelper/shared';
import { socketUrlOf } from '../config.js';
import { pushCallToIsland, pushHomeworkToIsland, pushNotificationToIsland } from '../island/bridge.js';
import { useAppStore } from './app.js';
type RealtimeEventName = keyof ServerToClientEvents;
type EventHandler = (payload: unknown) => void;
@@ -23,18 +22,6 @@ type EventHandler = (payload: unknown) => void;
* 还会把数据写回 IndexedDB,保证断网时看到的是最后同步到的内容。
*/
export const useRealtimeStore = defineStore('realtime', () => {
const app = useAppStore();
/**
* 本机要不要弹这次提醒。
*
* 教室在设置页选了「只在 ClassIsland 上弹」时,客户端仍然把通知收进通知中心(列表里有记录、
* 未读红点照常),但**不再弹窗、也不上岛** —— 否则老师会看到两个地方同时炸出来。
*/
function popupLocally(): boolean {
return app.shouldPopupLocally();
}
const connected = ref(false);
const connecting = ref(false);
const lastEventName = ref<string | null>(null);
@@ -76,18 +63,20 @@ export const useRealtimeStore = defineStore('realtime', () => {
dispatch('__connect_error__', error.message);
});
instance.on(SOCKET_EVENTS.notificationDeleted, (payload) => {
mark(SOCKET_EVENTS.notificationDeleted);
dispatch(SOCKET_EVENTS.notificationDeleted, payload);
});
instance.on(SOCKET_EVENTS.notificationNew, (payload: NotificationDto) => {
mark(SOCKET_EVENTS.notificationNew);
if (popupLocally()) {
ElMessage({
message: `【${PRIORITY_LABELS[payload.priority] ?? payload.priority}】${payload.title}`,
type: payload.priority === 'URGENT' ? 'error' : 'info',
duration: 5000,
showClose: true,
});
// 投递到桌面灵动岛:紧急通知立即展开;上课期间的非紧急通知会暂存,下课后自动弹出
pushNotificationToIsland(payload);
}
ElMessage({
message: `【${PRIORITY_LABELS[payload.priority] ?? payload.priority}】${payload.title}`,
type: payload.priority === 'URGENT' ? 'error' : 'info',
duration: 5000,
showClose: true,
});
// 投递到桌面灵动岛:紧急通知立即展开;上课期间的非紧急通知会暂存,下课后自动弹出
pushNotificationToIsland(payload);
dispatch(SOCKET_EVENTS.notificationNew, payload);
});
@@ -101,16 +90,14 @@ export const useRealtimeStore = defineStore('realtime', () => {
instance.on(SOCKET_EVENTS.callNew, (payload: NotificationDto) => {
mark(SOCKET_EVENTS.callNew);
if (popupLocally()) {
ElMessage({
message: payload.title,
type: 'warning',
duration: 8000,
showClose: true,
});
// 叫人:无论是否上课都立即展开(老师正在等这位同学)
pushCallToIsland(payload);
}
ElMessage({
message: payload.title,
type: 'warning',
duration: 8000,
showClose: true,
});
// 叫人:无论是否上课都立即展开(老师正在等这位同学)
pushCallToIsland(payload);
dispatch(SOCKET_EVENTS.callNew, payload);
});
@@ -384,7 +384,7 @@ onUnmounted(() => {
</el-table-column>
<el-table-column label="等级" width="80">
<template #default="{ row }">
{{ gradeLevel(gradePercent(row.score, row.totalScore)) }}
{{ row.level || gradeLevel(gradePercent(row.score, row.totalScore)) }}
</template>
</el-table-column>
<el-table-column label="发布时间" width="170">
@@ -70,8 +70,6 @@ async function submit(): Promise<void> {
try {
await auth.login(form.serverUrl, form.code.trim(), form.password);
await appStore.init(form.serverUrl);
// 登录后对齐"通知显示位置":这台机器上次选的是弹 ClassHelper 还是弹 ClassIsland
await appStore.loadNotificationChannel(auth.classId);
if (auth.token) realtime.connect(appStore.serverUrl, auth.token);
ElMessage.success(`已进入 ${auth.displayName}`);
await router.replace('/schedule');
@@ -12,7 +12,7 @@ import {
type ScheduleDto,
type ScheduleWeekView,
} from '@classhelper/shared';
import { dashboardApi, scheduleApi } from '../api/index.js';
import { scheduleApi } from '../api/index.js';
import { fetchWithCache } from '../cache/index.js';
import { useAppStore } from '../stores/app.js';
import { useAuthStore } from '../stores/auth.js';
@@ -172,14 +172,9 @@ function remainText(minutes: number): string {
async function loadTerm(): Promise<void> {
// 带 classId:周次上限取本班"教学周数"(班主任可调,默认 20 周)
const result = await fetchWithCache('classes', 'term', () => dashboardApi.term(auth.classId ?? undefined), {
currentWeek: 1,
maxWeek: 20,
});
appStore.currentWeek = result.data.currentWeek;
appStore.maxWeek = result.data.maxWeek;
weekOptions.value = buildWeekOptions(result.data.maxWeek);
if (!week.value || week.value === 1) week.value = result.data.currentWeek;
await appStore.refreshTerm(auth.classId ?? undefined);
weekOptions.value = buildWeekOptions(appStore.maxWeek);
if (!week.value || week.value === 1) week.value = appStore.currentWeek;
}
async function loadSchedules(): Promise<void> {
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { confirmAction } from '../../composables/confirm.js';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '../../stores/auth.js';
import { useRealtimeStore } from '../../stores/realtime.js';
@@ -13,7 +14,7 @@ const auth = useAuthStore();
const realtime = useRealtimeStore();
async function logout(): Promise<void> {
await ElMessageBox.confirm('确认退出当前账号?', '退出登录', { type: 'warning' });
if (!(await confirmAction('确认退出当前账号?', '退出登录', { type: 'warning' }))) return;
realtime.disconnect();
await auth.logout();
ElMessage.success('已退出登录');
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { confirmAction } from '../../composables/confirm.js';
import { computed, onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus';
import { formatDate, relativeTime, type UpdateInfo } from '@classhelper/shared';
import type { ClientAgentStatus, DesktopAppInfo } from '../../../types/desktop.js';
import { useAppStore } from '../../stores/app.js';
@@ -198,9 +199,12 @@ const cacheRows = computed(() =>
);
async function clearCache(): Promise<void> {
await ElMessageBox.confirm('清空后离线时将无法查看历史数据,确认继续?', '清空离线缓存', {
type: 'warning',
});
if (
!(await confirmAction('清空后离线时将无法查看历史数据,确认继续?', '清空离线缓存', {
type: 'warning',
}))
)
return;
await appStore.clearCache();
ElMessage.success('离线缓存已清空');
}
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { confirmAction } from '../../composables/confirm.js';
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus';
import {
HOMEWORK_PHRASE_DEFAULTS,
HOMEWORK_PHRASE_MAX_COUNT,
@@ -93,9 +94,12 @@ async function manualSync(): Promise<void> {
}
async function clearCache(): Promise<void> {
await ElMessageBox.confirm('清空后离线时将无法查看历史数据,确认继续?', '清空离线缓存', {
type: 'warning',
});
if (
!(await confirmAction('清空后离线时将无法查看历史数据,确认继续?', '清空离线缓存', {
type: 'warning',
}))
)
return;
await appStore.clearCache();
ElMessage.success('离线缓存已清空');
}
@@ -151,7 +155,7 @@ async function removePhrase(value: string): Promise<void> {
}
async function resetPhrases(): Promise<void> {
await ElMessageBox.confirm('恢复为默认快捷短语?', '恢复默认', { type: 'warning' });
if (!(await confirmAction('恢复为默认快捷短语?', '恢复默认', { type: 'warning' }))) return;
phrases.value = [...HOMEWORK_PHRASE_DEFAULTS];
await savePhrases();
ElMessage.success('已恢复默认');
@@ -192,7 +196,7 @@ const updateTargetText = computed(() => {
const pendingUpdateText = computed(() => {
const pending = agent.value?.pendingUpdateVersion ?? '';
if (!pending) return '无';
return `${pending}(已下载,空闲时自动安装)`;
return `${pending}(已下载,等待按服务端指定的时机安装)`;
});
const lastErrorText = computed(() => agent.value?.lastError?.trim() || '无');
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { confirmAction } from '../../composables/confirm.js';
import { computed, onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus';
import {
DEFAULT_ISLAND_APPEARANCE,
ISLAND_APPEARANCE_RANGES as RANGES,
@@ -65,7 +66,7 @@ async function saveIslandAppearance(): Promise<void> {
}
async function resetIslandAppearance(): Promise<void> {
await ElMessageBox.confirm('恢复灵动岛的默认外观?', '恢复默认', { type: 'warning' });
if (!(await confirmAction('恢复灵动岛的默认外观?', '恢复默认', { type: 'warning' }))) return;
applyIslandAppearance({ ...DEFAULT_ISLAND_APPEARANCE });
await saveIslandAppearance();
}
@@ -1,42 +1,8 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import {
CLASSISLAND_NOTIFICATION_CHANNEL_HINTS,
CLASSISLAND_NOTIFICATION_CHANNEL_LABELS,
CLASSISLAND_NOTIFICATION_CHANNELS,
formatDate,
type ClassIslandNotificationChannel,
} from '@classhelper/shared';
import { classGradeQueryApi, classIslandStatusApi } from '../../api/index.js';
import { useAppStore } from '../../stores/app.js';
import { onMounted, ref } from 'vue';
import { classGradeQueryApi } from '../../api/index.js';
import { useAuthStore } from '../../stores/auth.js';
/**
* 提醒设置:这台教室机器把提醒弹在哪个端(客户端 / ClassIsland / 两端都弹)。
* 值同时落本地配置与班级记录(服务端据此决定是否推送 ClassIsland)。
*/
const appStore = useAppStore();
const auth = useAuthStore();
const channelSaving = ref(false);
/**
* 本班有没有接入 ClassIsland 设备。
*
* 只用来禁用「只在 ClassIsland 上弹」——没有设备时选它等于把提醒静默丢掉;
* 注意**不能**顺手把「两端都弹」也禁掉:那样教室一旦选过"只在客户端",没设备时就再也切不回来了。
*/
const classIslandConnected = ref(false);
/** 本班 ClassIsland 设备的展示信息(设备名 / 最后上报),来自 /classes/:id/classisland-status */
const classIslandStatus = ref<{
connected: boolean;
deviceName: string | null;
deviceCount: number;
lastSeenAt: string | null;
pluginVersion: string | null;
classIslandVersion: string | null;
} | null>(null);
/* ------------------------------------------------------------ 班级端成绩查询状态(只读)
*
* 「是否允许班级端查看成绩」是**服务端口径**:管理员在 Web 端「班级管理」里开关,
@@ -56,43 +22,7 @@ async function loadGradeQuery(): Promise<void> {
}
}
const classIslandStatusText = computed(() => {
const status = classIslandStatus.value;
if (!status || !status.connected) return '未接入';
const seen = status.lastSeenAt ? `最后上报 ${formatDate(status.lastSeenAt, true)}` : '尚未上报过';
return `已接入 · ${status.deviceName ?? 'ClassIsland 设备'} · ${seen}`;
});
const channelOptions = computed(() =>
CLASSISLAND_NOTIFICATION_CHANNELS.map((value) => ({
value,
label: CLASSISLAND_NOTIFICATION_CHANNEL_LABELS[value],
disabled: value === 'classisland' && !classIslandConnected.value,
})),
);
async function applyChannel(value: ClassIslandNotificationChannel): Promise<void> {
channelSaving.value = true;
try {
const saved = await appStore.setNotificationChannel(auth.classId, value);
if (saved) ElMessage.success('提醒显示位置已更新');
else ElMessage.warning('已保存在本机,但同步到服务器失败(离线或权限不足),联网后请再点一次');
} finally {
channelSaving.value = false;
}
}
onMounted(async () => {
await appStore.loadNotificationChannel(auth.classId);
// 本班 ClassIsland 联动状态:没接设备就别让选「只在 ClassIsland 上弹」
if (auth.classId) {
const status = await classIslandStatusApi.get(auth.classId).catch(() => null);
classIslandStatus.value = status;
classIslandConnected.value = status?.connected === true;
}
// 班级端成绩查询开关(存在班级上,与 Web 端共享同一个值)
await loadGradeQuery();
});
onMounted(loadGradeQuery);
</script>
<template>
@@ -100,44 +30,14 @@ onMounted(async () => {
<div class="page-header">
<div>
<h2 class="page-title">提醒</h2>
<p class="page-subtitle">老师发通知 / 叫人时,提醒弹在哪个端</p>
<p class="page-subtitle">通知提醒与成绩查询状态</p>
</div>
</div>
<el-card shadow="never">
<template #header><span>ClassIsland 联动</span></template>
<el-descriptions :column="1" border size="small" class="mb-12">
<el-descriptions-item label="联动状态">{{ classIslandStatusText }}</el-descriptions-item>
<el-descriptions-item label="插件 / ClassIsland">
{{ classIslandStatus?.pluginVersion ?? '—' }} /
{{ classIslandStatus?.classIslandVersion ?? '—' }}
</el-descriptions-item>
</el-descriptions>
<template #header>通知提醒</template>
<p class="text-muted">
<strong>通知模式</strong>
:老师在 ClassHelper 上发布通知 / 叫人时,提醒弹在灵动岛还是 ClassIsland,
由这台教室机器决定。选择会同步到班级,服务端据此决定是否推送到教室的 ClassIsland。
</p>
<el-radio-group
:model-value="appStore.notificationChannel"
:disabled="channelSaving"
class="channel-group"
@change="
(value: string | number | boolean | undefined) =>
applyChannel(value as ClassIslandNotificationChannel)
"
>
<el-radio v-for="item in channelOptions" :key="item.value" :value="item.value" :disabled="item.disabled">
{{ item.label }}
</el-radio>
</el-radio-group>
<p class="text-muted channel-hint">
{{ CLASSISLAND_NOTIFICATION_CHANNEL_HINTS[appStore.notificationChannel] }}
<template v-if="!classIslandConnected">
<br />
提示:本班还没有接入 ClassIsland 设备(在 Web 端「ClassHelper 联动」里接入后才能选"只在
ClassIsland 上弹")。
</template>
通知与叫人通过 ClassHelper 客户端和灵动岛提醒。普通通知在上课期间暂存,下课后补弹;紧急通知立即提醒。
</p>
</el-card>
@@ -150,9 +50,7 @@ onMounted(async () => {
打开后,可以在「成绩」页看到本班成绩与排名。学生本身没有账号、不能登录,
查成绩就是由这台教室机器代做。关闭后本机查成绩会被服务端拒绝,教师端不受影响。
</p>
<p class="text-muted">
本开关由管理员在服务端「班级管理」和「客户端设备」里统一设置,教室机器不提供本地开关。
</p>
<p class="text-muted">本开关由管理员在服务端「班级管理」里统一设置,教室机器不提供本地开关。</p>
<el-tag :type="gradeQueryEnabled ? 'success' : 'info'" effect="plain">
{{ gradeQueryEnabled ? '当前:已允许查看成绩与排名' : '当前:已由管理员关闭' }}
</el-tag>