================================================================================ PROJECT: ClassNotify SNAPSHOT_ID: 20261002-032041-73dd8d7 BUNDLE: 5/8 GIT_HEAD: 73dd8d7c5feb1cc42c8a6f218815748bfbe88bf3 WORKTREE_DIRTY: true FILES_IN_BUNDLE: 118 ================================================================================ ================================================================================ FILE BEGIN: src/Web/ClassNotify.Web/src/pages/teacher/TeacherConsole.tsx SHA256: 785d9dfbdaf96cc3205290d6bed579e885f52309f0f58565d49bce0a354d08f9 SIZE: 120292 ================================================================================ import React, { useEffect, useState, useRef } from 'react'; import { api } from '../../api/client'; import { useAuth } from '../../context/AuthContext'; import { Classroom, NotificationRecord, TeacherProfile, TeacherScreen } from '../../types'; import { teacherRealtime } from '../../realtime/TeacherRealtime'; import { CheckoutModal } from '../../components/CheckoutModal'; import { TeacherProfileSettings } from '../../components/TeacherProfileSettings'; import { Send, Volume2, CheckCircle2, Clock, AlertTriangle, User, Radio, Check, Loader2, RefreshCw, AlertCircle, Eye, Camera, ZoomIn, ZoomOut, X, XCircle, ShieldCheck, ChevronDown, ChevronRight, Sparkles, Search, Filter, KeyRound, Copy, Monitor, Layers, FileText, Trash2, BellRing, Plus, Unlink, RadioTower, Download } from 'lucide-react'; import { StatusBadge, SearchInput, Modal, DangerConfirmModal } from '../../components/ui'; export function validateAndCanonicalizeClassName(input: string): { isValid: boolean; canonical: string; error?: string } { if (!input || !input.trim()) { return { isValid: false, canonical: '', error: '请填写班级名称' }; } const raw = input.trim(); if (/[()()[\]【】{}]/.test(raw)) { return { isValid: false, canonical: '', error: '班级名称不能包含括号,请直接填写,例如:高一3班。' }; } const canonical = raw.replace(/ +/g, ''); if (canonical.length < 2 || canonical.length > 20) { return { isValid: false, canonical, error: '班级名称长度必须在 2 至 20 个字之间' }; } if (!canonical.endsWith('班')) { return { isValid: false, canonical, error: '班级名称必须以“班”结尾,例如:高一3班、91班。' }; } if (!/^[\p{Script=Han}0-9]+$/u.test(canonical)) { return { isValid: false, canonical, error: '班级名称只能包含汉字和数字,并且必须以“班”结尾,例如:高一3班、91班。' }; } return { isValid: true, canonical }; } function parseAckStatus(raw: number | string): 'Sent' | 'Delivered' | 'Acknowledged' | 'Timeout' | 'Failed' | 'Cancelled' { if (typeof raw === 'string') { switch (raw.toLowerCase()) { case 'acknowledged': case 'confirmed': return 'Acknowledged'; case 'delivered': return 'Delivered'; case 'sent': return 'Sent'; case 'cancelled': case 'canceled': return 'Cancelled'; case 'timeout': return 'Timeout'; case 'failed': return 'Failed'; default: return 'Sent'; } } switch (raw) { case 5: return 'Cancelled'; case 2: return 'Acknowledged'; case 1: return 'Delivered'; case 0: return 'Sent'; case 3: return 'Timeout'; case 4: return 'Failed'; default: return 'Sent'; } } const DEFAULT_RECENT_STUDENTS: string[] = []; const QUICK_TEMPLATES = [ { label: '到办公室', text: '请到教师办公室一趟。' }, { label: '下楼集合', text: '请立即到楼下操场集合整队。' }, { label: '家长来了', text: '校门口有家长找,请前往传达室。' }, { label: '带作业本', text: '请收齐各科作业本送至办公室。' }, { label: '课间回来', text: '预备铃已响,请迅速回教室内就坐。' }, { label: '自习纪律', text: '请保持教室内安静自习,班干部负责维护纪律。' }, ]; export const TeacherConsole: React.FC = () => { const { user } = useAuth(); const [classes, setClasses] = useState([]); const [selectedClassId, setSelectedClassId] = useState(''); const [studentName, setStudentName] = useState(''); const [customTitle, setCustomTitle] = useState(''); const [message, setMessage] = useState(''); const [messageWasManuallyEdited, setMessageWasManuallyEdited] = useState(false); const [sendError, setSendError] = useState(null); const [voice, setVoice] = useState(true); const [shake, setShake] = useState(true); const [isUrgent, setIsUrgent] = useState(false); const [duration, setDuration] = useState(60); const [highlightedMessageId, setHighlightedMessageId] = useState(null); const [sending, setSending] = useState(false); const [showAdvanced, setShowAdvanced] = useState(false); // Tab State: 'composer' (📢 发送呼叫) | 'receipts' (📋 送达回执) | 'screen' (🖥️ 班级大屏与授权) | 'profile' (👤 个人设置) const [activeTab, setActiveTab] = useState<'composer' | 'receipts' | 'screen' | 'profile'>('composer'); useEffect(() => { const urlParams = new URLSearchParams(window.location.search); const tabParam = urlParams.get('tab'); if (tabParam && ['composer', 'receipts', 'screen', 'profile'].includes(tabParam)) { setActiveTab(tabParam as any); } const handleSwitchTab = (e: any) => { if (e?.detail && ['composer', 'receipts', 'screen', 'profile'].includes(e.detail)) { setActiveTab(e.detail); } }; window.addEventListener('switch-teacher-tab', handleSwitchTab); return () => window.removeEventListener('switch-teacher-tab', handleSwitchTab); }, []); const [copiedDownloadLink, setCopiedDownloadLink] = useState(false); // Commercialization & Screen Management (Turn 103/104 Dual-Brain Consensus) const [teacherProfile, setTeacherProfile] = useState(null); const [boundScreens, setBoundScreens] = useState([]); const [checkoutModalOpen, setCheckoutModalOpen] = useState(false); const [claimModalOpen, setClaimModalOpen] = useState(false); const [claimPairingCode, setClaimPairingCode] = useState(''); const [claimClassAlias, setClaimClassAlias] = useState(''); const [claimingScreen, setClaimingScreen] = useState(false); const [claimError, setClaimError] = useState(null); const [claimSuccess, setClaimSuccess] = useState(null); const [pairingModalInfo, setPairingModalInfo] = useState<{ open: boolean; deviceId?: string; alias?: string; code?: string; ttlSeconds?: number } | null>(null); const [activatingPairingId, setActivatingPairingId] = useState(null); const [downloadVersion, setDownloadVersion] = useState(null); useEffect(() => { if (typeof api?.getDownloadManifest === 'function') { api.getDownloadManifest().then(manifest => { if (manifest && manifest.version) { setDownloadVersion(manifest.version); } }).catch(() => {}); } }, []); // Turn 103: Draft Preservation & Auto-Restore on SESSION_SUPERSEDED const [restoredDraftNotice, setRestoredDraftNotice] = useState(null); useEffect(() => { try { const savedDraftStr = localStorage.getItem('classnotify_draft_backup'); if (savedDraftStr) { const draft = JSON.parse(savedDraftStr); if (draft.content) { setMessage(draft.content); if (draft.title) setCustomTitle(draft.title); if (draft.studentName) setStudentName(draft.studentName); if (draft.targetClassId) setSelectedClassId(draft.targetClassId); setRestoredDraftNotice(`已为您自动恢复此前的通知草稿(保存于 ${new Date(draft.savedAt).toLocaleTimeString()})`); } } } catch {} }, []); const handleDiscardDraft = () => { localStorage.removeItem('classnotify_draft_backup'); setRestoredDraftNotice(null); setMessage(''); setCustomTitle(''); setStudentName(''); }; // Storage key strictly scoped to tenant, teacher user, and class for privacy (fail-closed if unauthenticated) const getRecentStudentKey = (classId: string) => { if (!user?.tenantId || !user?.userId || !classId) return null; return `classnotify:recentStudents:${user.tenantId}:${user.userId}:${classId}`; }; // Recent students persistence with tenant-user isolation const [recentStudents, setRecentStudents] = useState(DEFAULT_RECENT_STUDENTS); useEffect(() => { if (!selectedClassId) return; const key = getRecentStudentKey(selectedClassId); if (!key) { setRecentStudents([]); return; } try { const saved = localStorage.getItem(key); if (saved) { setRecentStudents(JSON.parse(saved)); } else { setRecentStudents([]); } } catch { setRecentStudents([]); } }, [selectedClassId, user?.tenantId, user?.userId]); // History & Live state with Pagination const [history, setHistory] = useState([]); const [historyLimit, setHistoryLimit] = useState(50); const [loadingMore, setLoadingMore] = useState(false); const [hasMoreHistory, setHasMoreHistory] = useState(true); const [loading, setLoading] = useState(true); const [refreshingScreens, setRefreshingScreens] = useState(false); const [loadError, setLoadError] = useState(null); // Filter state for right column receipt feed const [receiptClassFilter, setReceiptClassFilter] = useState('all'); const [receiptSearch, setReceiptSearch] = useState(''); // Visual Receipt Modal State const [visualModalData, setVisualModalData] = useState<{ notificationId: string; deviceId: string; className: string; capturedAt?: string; } | null>(null); const [visualImageUrl, setVisualImageUrl] = useState(null); const [visualLoading, setVisualLoading] = useState(false); const [visualError, setVisualError] = useState(null); const [zoomLevel, setZoomLevel] = useState(1); const [fetchingScreenshotId, setFetchingScreenshotId] = useState(null); // Cancellation Modal State const [cancelModalItem, setCancelModalItem] = useState(null); const [cancelling, setCancelling] = useState(false); // Send Success Toast State (2.5s auto fade + click jump to receipt) const [sendToast, setSendToast] = useState<{ id: number; messageId: string; message: string; className: string; classId: string; isFadingOut: boolean; } | null>(null); const sendToastTimerRef = useRef<{ fadeTimer?: any; removeTimer?: any }>({}); useEffect(() => { return () => { if (sendToastTimerRef.current.fadeTimer) clearTimeout(sendToastTimerRef.current.fadeTimer); if (sendToastTimerRef.current.removeTimer) clearTimeout(sendToastTimerRef.current.removeTimer); }; }, []); // Delete History Record Modal State const [deleteModalItem, setDeleteModalItem] = useState(null); const [deletingRecord, setDeletingRecord] = useState(false); // Classroom device health & online status (live透传) const [classroomDevices, setClassroomDevices] = useState>({}); const classesRef = useRef(classes); useEffect(() => { classesRef.current = classes; }, [classes]); const loadClassesAndHistory = async () => { setLoading(true); setLoadError(null); try { const cls = await api.getTeacherClasses(); setClasses(cls); if (cls.length > 0 && !selectedClassId) { setSelectedClassId(cls[0].id); } try { const prof = await api.getTeacherProfile(); setTeacherProfile(prof); } catch (e) { console.warn('Teacher profile unavailable', e); } try { const scrs = await api.getTeacherScreens(); setBoundScreens(scrs); } catch (e) { console.warn('Teacher screens unavailable', e); } try { const devs = await api.getTeacherClassroomDevices(); const devMap: Record = {}; devs.forEach((d) => { devMap[d.classroomId] = d; }); setClassroomDevices(devMap); } catch (err) { console.warn('Classroom devices summary unavailable', err); } const hist = await api.getTeacherHistory(undefined, historyLimit); setHistory( hist.map((item) => ({ ...item, status: parseAckStatus(item.status), })) ); if (hist.length < historyLimit) { setHasMoreHistory(false); } } catch (err: any) { setLoadError(err?.message || '加载班级或历史记录失败'); } finally { setLoading(false); } }; const handleManualRefreshScreens = async () => { setRefreshingScreens(true); const start = Date.now(); try { await loadClassesAndHistory(); } finally { const elapsed = Date.now() - start; const minSpinMs = 600; if (elapsed < minSpinMs) { setTimeout(() => setRefreshingScreens(false), minSpinMs - elapsed); } else { setRefreshingScreens(false); } } }; const formatExpirationDate = (dateStr?: string) => { if (!dateStr) return ''; try { const d = new Date(dateStr); const y = d.getFullYear(); const m = String(d.getMonth() + 1).padStart(2, '0'); const day = String(d.getDate()).padStart(2, '0'); const hh = String(d.getHours()).padStart(2, '0'); const mm = String(d.getMinutes()).padStart(2, '0'); return `${y}-${m}-${day} ${hh}:${mm}`; } catch { return dateStr; } }; const [downloadingClient, setDownloadingClient] = useState(false); const handleDownloadClient = async () => { try { setDownloadingClient(true); const res = await api.getWindowsInstallerTicket(); if (res && res.downloadUrl) { window.location.href = res.downloadUrl; } } catch (err: any) { setSendError(err?.message || '获取大屏客户端下载凭据失败,请重试'); } finally { setDownloadingClient(false); } }; const handleCopyDownloadLink = () => { const entryUrl = `${window.location.origin}/teacher?tab=screens`; navigator.clipboard.writeText(entryUrl); setCopiedDownloadLink(true); setTimeout(() => setCopiedDownloadLink(false), 2500); }; // Commercialization Screen Handlers (Turn 103/104 Dual-Brain Consensus) const handleOpenClaimModal = () => { setClaimPairingCode(''); setClaimClassAlias(''); setClaimError(null); setClaimSuccess(null); setClaimModalOpen(true); }; const handleClaimSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!claimPairingCode.trim()) return; const classCheck = validateAndCanonicalizeClassName(claimClassAlias); if (!classCheck.isValid) { setClaimError(classCheck.error || '班级名称不合法'); return; } setClaimingScreen(true); setClaimError(null); setClaimSuccess(null); try { await api.claimTeacherScreen(claimPairingCode.trim(), classCheck.canonical); const isExpired = teacherProfile?.subscriptionState === 'Expired'; if (isExpired) { setClaimSuccess('已成功绑定大屏。当前教师服务已到期,开通正式版后即可发送通知。'); } else { setClaimSuccess('大屏绑定成功!已加入到您的班级大屏列表。'); } await loadClassesAndHistory(); setTimeout(() => { setClaimModalOpen(false); setClaimSuccess(null); }, 1500); } catch (err: any) { if (err?.response?.data?.code === 'SCREEN_QUOTA_EXCEEDED' || err?.message?.includes('4 台')) { setClaimError('已达到 4 台大屏上限,请先解除不再使用的大屏。'); } else { setClaimError(err?.message || '大屏绑定失败,请核对配对码是否正确或未过期'); } } finally { setClaimingScreen(false); } }; const handleUnbindScreen = async (screen: TeacherScreen) => { if (!confirm(`确定要从您的账号解除对【${screen.classAlias}】大屏的绑定吗?\n注意:这仅解除您本人的控制权,不会影响其他老师。`)) return; try { await api.unbindTeacherScreen(screen.deviceId); } catch (err: any) { console.warn('Unbind response notice:', err); } await loadClassesAndHistory(); }; const handleActivatePairingMode = async (screen: TeacherScreen) => { setActivatingPairingId(screen.deviceId); try { const res = await api.activateScreenPairingMode(screen.deviceId); setPairingModalInfo({ open: true, deviceId: screen.deviceId, alias: screen.classAlias, code: res.pairingCode, ttlSeconds: res.ttlSeconds || 600 }); } catch (err: any) { alert(err?.message || '开启配对模式失败'); } finally { setActivatingPairingId(null); } }; // Recovery Key Rotation State & Handlers const [rotateModalOpen, setRotateModalOpen] = useState(false); const [currentPasswordInput, setCurrentPasswordInput] = useState(''); const [rotatingKey, setRotatingKey] = useState(false); const [rotateError, setRotateError] = useState(null); const [newlyRotatedKey, setNewlyRotatedKey] = useState(null); const [keyCopied, setKeyCopied] = useState(false); const handleRotateRecoveryKey = async (e: React.FormEvent) => { e.preventDefault(); if (!currentPasswordInput.trim()) return; setRotatingKey(true); setRotateError(null); try { const res = await api.rotateRecoveryKey(currentPasswordInput); setNewlyRotatedKey(res.recoveryKey); setCurrentPasswordInput(''); } catch (err: any) { setRotateError(err?.message || '轮换恢复密钥失败,请核对当前密码'); } finally { setRotatingKey(false); } }; const handleCopyNewKey = () => { if (!newlyRotatedKey) return; navigator.clipboard.writeText(newlyRotatedKey); setKeyCopied(true); setTimeout(() => setKeyCopied(false), 2000); }; const handleDownloadNewKey = () => { if (!newlyRotatedKey) return; const blob = new Blob([ `ClassNotify 安全恢复密钥 (Recovery Key)\n===================================\n生成时间: ${new Date().toLocaleString()}\n账号: ${user?.name || user?.userId}\n恢复密钥: ${newlyRotatedKey}\n\n重要提示:\n1. 此密钥是您在忘记登录密码时的最高自救凭据。\n2. 原有恢复密钥已彻底作废。\n3. 请妥善保存在安全的离线位置,切勿向他人泄露。` ], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `ClassNotify-RecoveryKey-${user?.userId || 'account'}.txt`; a.click(); URL.revokeObjectURL(url); }; const handleLoadMoreHistory = async () => { const nextLimit = historyLimit + 50; setLoadingMore(true); try { const hist = await api.getTeacherHistory(undefined, nextLimit); setHistory( hist.map((item) => ({ ...item, status: parseAckStatus(item.status), })) ); setHistoryLimit(nextLimit); if (hist.length < nextLimit) { setHasMoreHistory(false); } } catch (err: any) { console.error('加载更多历史记录失败:', err); } finally { setLoadingMore(false); } }; useEffect(() => { loadClassesAndHistory(); }, []); // Auto poll every 5s when no classrooms exist so when screen activates with trial voucher it lights up automatically useEffect(() => { if (classes.length === 0) { const timer = setInterval(() => { loadClassesAndHistory(); }, 5000); return () => clearInterval(timer); } }, [classes.length]); // Turn 110: Periodic background refresh for teacher screens, profile, and classroom devices (every 45s) useEffect(() => { const timer = setInterval(() => { api.getTeacherScreens() .then(scrs => { if (scrs) setBoundScreens(scrs); }) .catch(() => {}); api.getTeacherProfile() .then(prof => { if (prof) setTeacherProfile(prof); }) .catch(() => {}); api.getTeacherClassroomDevices() .then(devs => { if (devs) { const devMap: Record = {}; devs.forEach((d) => { devMap[d.classroomId] = d; }); setClassroomDevices(devMap); } }) .catch(() => {}); }, 45000); return () => clearInterval(timer); }, []); useEffect(() => { const unsubscribeAck = teacherRealtime.onAckReceiptReceived((receipt) => { setHistory((prev) => prev.map((item) => { if (item.id === receipt.messageId) { const mappedStatus = parseAckStatus(receipt.status); return { ...item, status: mappedStatus, confirmedAt: receipt.timestamp || item.confirmedAt || new Date().toISOString(), }; } return item; }) ); }); const unsubscribeBroadcast = teacherRealtime.onNewNotificationBroadcast((n) => { setHistory((prev) => { if (prev.some((item) => item.id === n.id)) return prev; const targetClass = classesRef.current.find((c) => c.id === n.classId); const newItem: NotificationRecord = { id: n.id, tenantId: n.tenantId, classId: n.classId, className: targetClass?.displayName || n.classId, senderName: '教师', message: n.message, priority: n.type === 2 ? 'Urgent' : 'Normal', createdAt: n.createdAt, status: 'Sent', }; return [newItem, ...prev]; }); }); const unsubscribeCancel = typeof teacherRealtime.onNotificationCancelled === 'function' ? teacherRealtime.onNotificationCancelled((cancelledNotificationId) => { setHistory((prev) => prev.map((item) => { if (item.id === cancelledNotificationId) { return { ...item, status: 'Cancelled', isCancelled: true, cancelledAt: new Date().toISOString(), }; } return item; }) ); }) : () => {}; const unsubscribeVisualReceipt = typeof (teacherRealtime as any).onVisualReceiptUploaded === 'function' ? (teacherRealtime as any).onVisualReceiptUploaded((evt: any) => { setHistory((prev) => prev.map((item) => { if (item.id === evt.notificationId) { const existingReceipts = item.receipts || []; const updatedReceipts = existingReceipts.map((r) => r.deviceId === evt.deviceId ? { ...r, visualReceiptState: 'Available' as const, visualReceiptCapturedAt: evt.capturedAt, visualReceiptExpiresAt: evt.expiresAt } : r ); if (!updatedReceipts.some((r) => r.deviceId === evt.deviceId)) { updatedReceipts.push({ deviceId: evt.deviceId, status: 'Displayed', visualReceiptState: 'Available' as const, visualReceiptCapturedAt: evt.capturedAt, visualReceiptExpiresAt: evt.expiresAt, }); } return { ...item, receipts: updatedReceipts, }; } return item; }) ); }) : () => {}; const unsubscribeDevice = typeof teacherRealtime.onDeviceStatusChanged === 'function' ? teacherRealtime.onDeviceStatusChanged((evt) => { if (evt.classId) { setClassroomDevices((prev) => ({ ...prev, [evt.classId]: { ...(prev[evt.classId] || { deviceId: evt.deviceId, classroomId: evt.classId, classroomName: evt.className, }), isOnline: evt.state === 'Online' || evt.state === 1 || evt.state === '1', lastHeartbeat: evt.lastHeartbeat, clientVersion: evt.agentVersion || prev[evt.classId]?.clientVersion, }, })); // Turn 73: If classes were empty (onboarding view), immediately reload classes to illuminate the class and switch to composer if (classesRef.current.length === 0) { loadClassesAndHistory(); } } }) : () => {}; return () => { if (typeof unsubscribeAck === 'function') unsubscribeAck(); if (typeof unsubscribeBroadcast === 'function') unsubscribeBroadcast(); if (typeof unsubscribeCancel === 'function') unsubscribeCancel(); if (typeof unsubscribeVisualReceipt === 'function') unsubscribeVisualReceipt(); if (typeof unsubscribeDevice === 'function') unsubscribeDevice(); }; }, []); // Quick template selection with smart name composition and manual edit protection const handleApplyTemplate = (tpl: typeof QUICK_TEMPLATES[0]) => { if (messageWasManuallyEdited && message.trim().length > 0) { if (!window.confirm('当前输入框已有手写内容,确定使用模版覆盖吗?')) { return; } } const trimmedStudent = studentName.trim(); if (trimmedStudent) { setMessage(`${trimmedStudent},${tpl.text}`); } else { setMessage(tpl.text); } setMessageWasManuallyEdited(false); }; const handleSelectRecentStudent = (name: string) => { setStudentName(name); // If message is untouched or empty, generate default phrase if (!messageWasManuallyEdited || !message.trim()) { setMessage(`${name},请到教师办公室一趟。`); setMessageWasManuallyEdited(false); } else { // If teacher already edited text, DO NOT overwrite! // If message doesn't start with student name, prepend cleanly if (!message.includes(name)) { setMessage(`${name},${message}`); } } }; const handleSend = async (e: React.FormEvent) => { e.preventDefault(); if (!selectedClassId || !message.trim()) return; setSending(true); setSendError(null); try { const targetClass = classes.find((c) => c.id === selectedClassId); const title = customTitle.trim() || (studentName.trim() ? `🔔 老师呼叫: ${studentName.trim()}` : `📢 ${targetClass?.displayName || '班级'}通知`); const res = await api.sendNotification({ classId: selectedClassId, studentName: studentName.trim() || undefined, title, message: message.trim(), type: isUrgent ? 2 : 0, voice, shake, durationSeconds: duration, }); // Update recent students list using tenant-isolated key const trimmedName = studentName.trim(); if (trimmedName && selectedClassId) { setRecentStudents((prev) => { const updated = [trimmedName, ...prev.filter(n => n !== trimmedName)].slice(0, 8); try { const key = getRecentStudentKey(selectedClassId); if (key) { localStorage.setItem(key, JSON.stringify(updated)); } } catch {} return updated; }); } const sentMsg = message.trim(); setMessage(''); setStudentName(''); setCustomTitle(''); setMessageWasManuallyEdited(false); setSendError(null); if (res?.messageId) { setHistory((prev) => { if (prev.some((item) => item.id === res.messageId)) return prev; const newRecord: NotificationRecord = { id: res.messageId, tenantId: '', classId: selectedClassId, className: targetClass?.displayName || selectedClassId, senderName: '教师', message: sentMsg, priority: isUrgent ? 'Urgent' : 'Normal', createdAt: new Date().toISOString(), status: 'Sent', }; return [newRecord, ...prev]; }); } // Trigger Send Success Toast (2.5s auto fade + click jump to receipt with exact messageId highlight) const targetClassName = targetClass?.displayName || selectedClassId; if (sendToastTimerRef.current.fadeTimer) { clearTimeout(sendToastTimerRef.current.fadeTimer); sendToastTimerRef.current.fadeTimer = null; } if (sendToastTimerRef.current.removeTimer) { clearTimeout(sendToastTimerRef.current.removeTimer); sendToastTimerRef.current.removeTimer = null; } const toastId = Date.now(); const newMsgId = res?.messageId || ''; setSendToast({ id: toastId, messageId: newMsgId, message: `呼叫已成功下发至【${targetClassName}】大屏!`, className: targetClassName, classId: selectedClassId, isFadingOut: false, }); sendToastTimerRef.current.fadeTimer = setTimeout(() => { setSendToast((prev) => (prev && prev.id === toastId ? { ...prev, isFadingOut: true } : prev)); }, 2200); sendToastTimerRef.current.removeTimer = setTimeout(() => { setSendToast((prev) => (prev && prev.id === toastId ? null : prev)); }, 2500); } catch (err: any) { if ((err.response?.status === 401 || err.status === 401) && (err.response?.data?.code === 'SESSION_SUPERSEDED' || err.code === 'SESSION_SUPERSEDED')) { const draft = { title: customTitle, studentName: studentName, content: message, targetClassId: selectedClassId, savedAt: new Date().toISOString() }; localStorage.setItem('classnotify_draft_backup', JSON.stringify(draft)); localStorage.removeItem('classnotify_token'); alert('您的账号已在其他设备或窗口登录,草稿内容已自动保存在本地!'); window.location.href = '/login'; return; } setSendError(err?.message || '呼叫发送失败,请检查网络或稍后重试'); } finally { setSending(false); } }; const handleToastClick = () => { if (!sendToast) return; const targetClassId = sendToast.classId; const targetMsgId = sendToast.messageId; if (sendToastTimerRef.current.fadeTimer) { clearTimeout(sendToastTimerRef.current.fadeTimer); sendToastTimerRef.current.fadeTimer = null; } if (sendToastTimerRef.current.removeTimer) { clearTimeout(sendToastTimerRef.current.removeTimer); sendToastTimerRef.current.removeTimer = null; } setSendToast(null); if (targetClassId) { setReceiptClassFilter(targetClassId); } setActiveTab('receipts'); if (targetMsgId) { setHighlightedMessageId(targetMsgId); setTimeout(() => { const el = document.querySelector(`[data-message-id="${targetMsgId}"]`); if (el) { el.scrollIntoView({ behavior: 'smooth', block: 'center' }); } }, 100); setTimeout(() => { setHighlightedMessageId((curr) => (curr === targetMsgId ? null : curr)); }, 3500); } }; const handleDeleteNotification = async () => { if (!deleteModalItem) return; setDeletingRecord(true); try { await api.deleteNotification(deleteModalItem.id); setHistory((prev) => prev.filter((item) => item.id !== deleteModalItem.id)); setDeleteModalItem(null); } catch (err: any) { alert(err?.message || '删除回执记录失败'); } finally { setDeletingRecord(false); } }; const handleCancelNotification = async () => { if (!cancelModalItem) return; setCancelling(true); try { await api.cancelNotification(cancelModalItem.id); setHistory((prev) => prev.map((item) => item.id === cancelModalItem.id ? { ...item, status: 'Cancelled', isCancelled: true, cancelledAt: new Date().toISOString() } : item ) ); setCancelModalItem(null); } catch (err: any) { alert(err.message || '提前关闭通知失败'); } finally { setCancelling(false); } }; const openVisualReceiptModal = async (notifId: string, deviceId: string, className: string, capturedAt?: string) => { setVisualModalData({ notificationId: notifId, deviceId, className, capturedAt }); setVisualLoading(true); setVisualError(null); setVisualImageUrl(null); setZoomLevel(1); try { const blob = await api.getVisualReceiptBlob(notifId, deviceId); const url = URL.createObjectURL(blob); setVisualImageUrl(url); } catch (err: any) { setVisualError(err?.message || '获取视觉核验图像失败'); } finally { setVisualLoading(false); } }; const closeVisualReceiptModal = () => { if (visualImageUrl) URL.revokeObjectURL(visualImageUrl); setVisualImageUrl(null); setVisualModalData(null); setVisualError(null); setZoomLevel(1); }; const handleFetchScreenshotOnDemand = async (record: NotificationRecord) => { setFetchingScreenshotId(record.id); try { // 1. Try to find existing deviceId in receipts let deviceId = record.receipts?.find((r) => r.deviceId)?.deviceId; // 2. If no deviceId found, refresh history from server to get latest receipts if (!deviceId) { const hist = await api.getTeacherHistory(undefined, historyLimit); setHistory(hist.map((item) => ({ ...item, status: parseAckStatus(item.status) }))); const updatedRecord = hist.find((h) => h.id === record.id); deviceId = updatedRecord?.receipts?.find((r) => r.deviceId)?.deviceId; } if (!deviceId) { alert('尚未检测到教室大屏设备在线或绑定,请确认教室大屏端正在运行'); return; } // 3. Attempt to fetch visual receipt await openVisualReceiptModal(record.id, deviceId, record.className); } catch (err: any) { alert(err?.message || '大屏端正在拍摄与上传通知截图,请在 1-2 秒后再次点击'); } finally { setFetchingScreenshotId(null); } }; // Filter receipts const filteredHistory = history.filter((item) => { if (receiptClassFilter !== 'all' && item.classId !== receiptClassFilter) { return false; } if (receiptSearch.trim()) { const q = receiptSearch.toLowerCase(); const matchMsg = item.message.toLowerCase().includes(q); const matchClass = item.className.toLowerCase().includes(q); if (!matchMsg && !matchClass) return false; } return true; }); // Recent classes (top 4) and others const recentClasses = classes.slice(0, 4); const otherClasses = classes.slice(4); const isPersonalTeacher = user?.tenantType === 'Personal' || user?.role === 'TenantOwner'; const renderComposer = () => (

快速发送呼叫

3秒极速触达
{/* 1. Target Classroom */}
{/* Quick Class Chips */}
{recentClasses.map((cls) => { const isSelected = selectedClassId === cls.id; return ( ); })} {classes.length < (teacherProfile?.screenLimit ?? 4) && ( )}
{/* Dropdown for other classes */} {otherClasses.length > 0 && (
)} {/* Live Classroom Screen Status */} {selectedClassId && (
{classroomDevices[selectedClassId]?.isOnline ? ( <> ) : ( )} {classroomDevices[selectedClassId]?.isOnline ? ( {classes.find((c) => c.id === selectedClassId)?.displayName || '班级'}大屏在线 ) : ( {classes.find((c) => c.id === selectedClassId)?.displayName || '班级'}大屏离线 · 通知将排队等待恢复 )}
)}
{/* 2. Target Student (Frequent Chips + Input) */}
{recentStudents.length > 0 && ( 点选常用学生快速填入 )}
{recentStudents.length > 0 && (
{recentStudents.map((st) => ( ))}
)} setStudentName(e.target.value)} placeholder="例如:张三、李四(若全班广播可留空)" maxLength={20} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white placeholder-slate-600 focus:outline-none focus:border-blue-500 transition-colors" />
{/* 3. Notification Message Content */}
{message.length}/200