================================================================================ CLASSNOTIFY P2.4 WEB FRONTEND IMMUTABLE AUDIT SOURCE BUNDLE Release ID: 20260924-P24-REMEDIATED-C3F740EF Generated At: 2026-09-24T12:40:31.328Z Target: Tokyo Oracle Linux Production Deployment (158.179.179.29) Public Audit URL: https://audit.paradise.eu.org/web-frontend-source.txt ================================================================================ REMEDIATION HIGHLIGHTS: 1. TeacherManagement.tsx: Strict minLength=8 password enforcement; RBAC-guarded Reset/Lock action buttons. 2. EmergencyBroadcast.tsx: Single-click submission guard; Real-time receipt summary aggregation polling. ================================================================================ /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/api/client.ts SIZE: 9490 chars SHA256: FC9C311F9464D089A3C27A0B1E49D519BDF91DD652808AB47ED0B54941CA5B52 ===================================================================== */ import { AdminMetrics, TenantAdmin, DeviceAdmin, ActivationCode, Classroom, TeacherUser, NotificationRecord, SendNotificationPayload, LoginResult, CurrentUser, UserAdmin, CreateUserAdminRequest, CreateTenantRequest, UpdateTenantRequest, UpdateDeviceRequest, EmergencyBroadcastRequest, SystemHealth, AdminAuditLog, BroadcastReceiptSummary } from '../types'; import { sessionManager } from '../realtime/SessionManager'; const API_BASE = '/api'; export function getToken(): string | null { return localStorage.getItem('classnotify_token'); } export function setToken(token: string) { localStorage.setItem('classnotify_token', token); } export function clearToken() { localStorage.removeItem('classnotify_token'); localStorage.removeItem('classnotify_user'); } async function request(endpoint: string, options: RequestInit = {}): Promise { const token = getToken(); const headers: Record = { 'Content-Type': 'application/json', ...(options.headers as Record), }; if (token) { headers['Authorization'] = `Bearer ${token}`; } const res = await fetch(`${API_BASE}${endpoint}`, { ...options, headers, }); if (res.status === 401) { clearToken(); sessionManager.notifySessionExpired('未授权或登录已过期,请重新登录'); throw new Error('未授权或登录已过期,请重新登录'); } if (!res.ok) { let errorMsg = `请求失败 (${res.status})`; try { const err = await res.json(); errorMsg = err.message || err.errorMessage || errorMsg; } catch { // ignore json parse error } throw new Error(errorMsg); } return res.json() as Promise; } export const api = { // Auth login: (username: string, password: string): Promise => request('/auth/login', { method: 'POST', body: JSON.stringify({ username, password }), }), getMe: (): Promise => request('/auth/me'), // SuperAdmin getAdminMetrics: (): Promise => request('/admin/metrics'), getTenants: (): Promise => request('/admin/tenants'), getAllDevices: (): Promise => request('/admin/devices'), sendDeviceCommand: (deviceId: string, command: string, parameters?: string) => request<{ success: boolean; message: string }>(`/admin/devices/${deviceId}/command`, { method: 'POST', body: JSON.stringify({ command, parameters }), }), getAdminActivationCodes: (): Promise => request('/admin/activation-codes'), getAdminClasses: (tenantId: string): Promise => request(`/admin/classes?tenantId=${encodeURIComponent(tenantId)}`), generateAdminCode: (tenantId: string, classId: string) => request<{ success: boolean; code: string; message: string }>( `/admin/activation-codes?tenantId=${encodeURIComponent(tenantId)}&classId=${encodeURIComponent(classId)}`, { method: 'POST' } ), getAdminNotifications: (limit = 50): Promise => request(`/admin/notifications?limit=${limit}`), // Tenant Management createTenant: (dto: CreateTenantRequest): Promise => request('/admin/tenants', { method: 'POST', body: JSON.stringify(dto), }), updateTenant: (tenantId: string, dto: UpdateTenantRequest): Promise => request(`/admin/tenants/${encodeURIComponent(tenantId)}`, { method: 'PATCH', body: JSON.stringify(dto), }), // User Management getUsers: (tenantId?: string, role?: string): Promise => { const params = new URLSearchParams(); if (tenantId) params.append('tenantId', tenantId); if (role) params.append('role', role); const qs = params.toString(); return request(`/admin/users${qs ? `?${qs}` : ''}`); }, createUser: (dto: CreateUserAdminRequest): Promise => request('/admin/users', { method: 'POST', body: JSON.stringify(dto), }), resetPassword: (userId: string, newPassword: string) => request<{ success: boolean; message: string }>(`/admin/users/${encodeURIComponent(userId)}/reset-password`, { method: 'POST', body: JSON.stringify({ newPassword }), }), setUserLock: (userId: string, isLocked: boolean) => request<{ success: boolean; isLocked: boolean; message: string }>(`/admin/users/${encodeURIComponent(userId)}/lock`, { method: 'POST', body: JSON.stringify({ isLocked }), }), deleteUser: (userId: string) => request<{ success: boolean; message: string }>(`/admin/users/${encodeURIComponent(userId)}`, { method: 'DELETE', }), // Device Extensions updateDevice: (deviceId: string, dto: UpdateDeviceRequest) => request<{ success: boolean; message: string }>(`/admin/devices/${encodeURIComponent(deviceId)}`, { method: 'PATCH', body: JSON.stringify(dto), }), decommissionDevice: (deviceId: string) => request<{ success: boolean; message: string }>(`/admin/devices/${encodeURIComponent(deviceId)}/decommission`, { method: 'POST', }), // Activation Code Management deleteActivationCode: (code: string) => request<{ success: boolean; message: string }>(`/admin/activation-codes/${encodeURIComponent(code)}`, { method: 'DELETE', }), // Emergency Broadcast sendEmergencyBroadcast: (dto: EmergencyBroadcastRequest) => request<{ success: boolean; broadcastId: string; dispatchedCount: number; targetSchools: number; message: string }>('/admin/broadcasts', { method: 'POST', body: JSON.stringify(dto), }), getBroadcastReceiptSummary: (broadcastId: string): Promise => request(`/admin/broadcasts/${encodeURIComponent(broadcastId)}/receipt-summary`), // System Health & Audit getSystemHealth: (): Promise => request('/admin/system/health'), getAuditLogs: (limit = 100): Promise => request(`/admin/audit-logs?limit=${limit}`), // School Admin getSchoolOverview: (): Promise<{ tenantId: string; tenantName: string; classCount: number; deviceCount: number; onlineCount: number; teacherCount: number; }> => request('/school-admin/overview'), getSchoolClasses: (): Promise => request('/school-admin/classes'), createSchoolClass: (dto: { id: string; displayName: string; grade?: string; roomNumber?: string }) => request<{ success: boolean; message: string }>('/school-admin/classes', { method: 'POST', body: JSON.stringify(dto), }), getSchoolTeachers: (): Promise => request('/school-admin/teachers'), createSchoolTeacher: (dto: { username: string; password: string; fullName: string; role: string }) => request<{ success: boolean; message: string }>('/school-admin/teachers', { method: 'POST', body: JSON.stringify(dto), }), resetSchoolTeacherPassword: (userId: string, newPassword: string) => request<{ success: boolean; message: string }>(`/school-admin/teachers/${encodeURIComponent(userId)}/reset-password`, { method: 'POST', body: JSON.stringify({ newPassword }), }), setSchoolTeacherLock: (userId: string, isLocked: boolean) => request<{ success: boolean; message: string }>(`/school-admin/teachers/${encodeURIComponent(userId)}/lock`, { method: 'POST', body: JSON.stringify({ isLocked }), }), getSchoolDevices: (): Promise => request('/school-admin/devices'), getSchoolCodes: (): Promise => request('/school-admin/activation-codes'), generateSchoolCode: (classId: string) => request<{ success: boolean; code: string; message: string }>( `/school-admin/activation-codes?classId=${encodeURIComponent(classId)}`, { method: 'POST' } ), // Teacher getTeacherClasses: (): Promise => request('/notification/classes'), sendNotification: (payload: SendNotificationPayload) => request<{ success: boolean; messageId: string; className: string; message: string }>( '/notification/send', { method: 'POST', body: JSON.stringify(payload), } ), cancelNotification: (notificationId: string) => request<{ success: boolean; message: string }>( `/notifications/${encodeURIComponent(notificationId)}/cancel`, { method: 'POST' } ), getTeacherHistory: (classId?: string, limit = 50): Promise => request( `/notification/history?${classId ? `classId=${encodeURIComponent(classId)}&` : ''}limit=${limit}` ), getVisualReceiptBlob: async (notificationId: string, deviceId: string): Promise => { const token = getToken(); const res = await fetch(`${API_BASE}/notifications/${encodeURIComponent(notificationId)}/receipts/${encodeURIComponent(deviceId)}/visual-receipt`, { headers: token ? { Authorization: `Bearer ${token}` } : {}, }); if (res.status === 410) { throw new Error('视觉回执已按24小时保存策略自动销毁'); } if (res.status === 404) { throw new Error('未找到该通知的视觉回执'); } if (!res.ok) { throw new Error(`获取视觉回执失败 (${res.status})`); } return res.blob(); }, }; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/App.tsx SIZE: 4068 chars SHA256: 16CDE291A22BB1C6C9E5BBE5CDB5F6B3ACBA873A4B42BC7704C700452258D291 ===================================================================== */ import React from 'react'; import { BrowserRouter, Routes, Route, Navigate, Outlet } from 'react-router-dom'; import { AuthProvider, useAuth } from './context/AuthContext'; import { Navbar } from './components/Navbar'; import { RoleRoute } from './components/RoleRoute'; import { Login } from './pages/Login'; // SuperAdmin import { AdminDashboard } from './pages/admin/AdminDashboard'; import { DeviceManagement } from './pages/admin/DeviceManagement'; import { AdminActivationCodes } from './pages/admin/ActivationCodes'; import { HistoryAudit } from './pages/admin/HistoryAudit'; import { TenantManagement } from './pages/admin/TenantManagement'; import { UserManagement } from './pages/admin/UserManagement'; import { EmergencyBroadcast } from './pages/admin/EmergencyBroadcast'; // SchoolAdmin import { SchoolDashboard } from './pages/school/SchoolDashboard'; import { ClassManagement } from './pages/school/ClassManagement'; import { TeacherManagement } from './pages/school/TeacherManagement'; import { SchoolActivationCodes } from './pages/school/SchoolActivationCodes'; // Teacher import { TeacherConsole } from './pages/teacher/TeacherConsole'; // Role Guard Component export const ProtectedLayout: React.FC = () => { const { user, isLoading } = useAuth(); if (isLoading) { return (
正在验证用户身份...
); } if (!user) { return ; } return (
); }; export const RootRedirect: React.FC = () => { const { user, isLoading } = useAuth(); if (isLoading) { return (
正在初始化...
); } if (!user) return ; if (user.role === 'SuperAdmin') return ; if (user.role === 'SchoolAdmin') return ; return ; }; export const AppRoutes: React.FC = () => { return ( } /> } /> {/* Authenticated Layout */} }> {/* SuperAdmin Routes */} }> } /> } /> } /> } /> } /> } /> } /> {/* SchoolAdmin Routes */} }> } /> } /> } /> } /> {/* Teacher Routes */} }> } /> {/* Fallback */} } /> ); }; export const App: React.FC = () => { return ( ); }; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/components/Navbar.tsx SIZE: 16705 chars SHA256: 1C22FBFD452578D7593D56E8E87121B3D6A5A720F3F31CCBDA2CC79167790842 ===================================================================== */ import React, { useState, useEffect } from 'react'; import { Link, useLocation } from 'react-router-dom'; import { useAuth } from '../context/AuthContext'; import { Bell, Monitor, KeyRound, History, School, Users, Layers, LogOut, ShieldCheck, GraduationCap, Building2, Radio, Menu, X } from 'lucide-react'; import { RealtimeStatusBadge } from './RealtimeStatusBadge'; export const Navbar: React.FC = () => { const { user, logout } = useAuth(); const location = useLocation(); const [mobileMenuOpen, setMobileMenuOpen] = useState(false); // Close mobile menu on route change useEffect(() => { setMobileMenuOpen(false); }, [location.pathname]); if (!user) return null; const isActive = (path: string) => location.pathname === path; return (
{/* Brand & Role */}
ClassNotify {user.role === 'SuperAdmin' && ( <> 超级运维后台 )} {user.role === 'SchoolAdmin' && ( <> 学校管理后台 )} {user.role === 'Teacher' && ( <> 教师工作台 )} {/* Cloud Realtime Connection Badge */}
{/* Navigation Links */} {/* User profile & Logout */}
{user.name} {user.tenantId === 'global' ? '全平台' : user.tenantId}
{/* Mobile menu toggle button */}
{/* Mobile Navigation Drawer */} {mobileMenuOpen && (
{user.role === 'SuperAdmin' && ( <>
总览大盘
设备激活码生成与管理 重点
学校租户
用户中枢
设备集控
全校应急广播
审计历史
)} {user.role === 'SchoolAdmin' && ( <> 学校概览 班级管理 教师账号 本校激活码 )} {user.role === 'Teacher' && ( 呼叫与回执 )}
)}
); }; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/components/RealtimeStatusBadge.tsx SIZE: 1590 chars SHA256: 0673D53A29C1CE75D141AF25D6B2EE082A33BFA3D54AFBC64DFE6419AE2A7659 ===================================================================== */ import React, { useEffect, useState } from 'react'; import { teacherRealtime, RealtimeState } from '../realtime/TeacherRealtime'; export const RealtimeStatusBadge: React.FC = () => { const [state, setState] = useState(teacherRealtime.getState()); useEffect(() => { return teacherRealtime.onStateChange(setState); }, []); if (state === 'Connected') { return ( 云端已连接 ); } if (state === 'Reconnecting') { return ( 正在重连 ); } if (state === 'Connecting') { return ( 正在连接... ); } return ( 连接断开 ); }; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/components/RoleRoute.tsx SIZE: 941 chars SHA256: 140F05FFBFC62F181514254F980DBCB96070D807EA959A7C2FCB185B510AF9F5 ===================================================================== */ import React from 'react'; import { Navigate, Outlet } from 'react-router-dom'; import { useAuth } from '../context/AuthContext'; import { UserRole } from '../types'; interface RoleRouteProps { allowedRoles: UserRole[]; children?: React.ReactNode; } export const RoleRoute: React.FC = ({ allowedRoles, children }) => { const { user, isLoading } = useAuth(); if (isLoading) { return (
正在验证用户权限...
); } if (!user) { return ; } if (!allowedRoles.includes(user.role)) { if (user.role === 'SuperAdmin') return ; if (user.role === 'SchoolAdmin') return ; return ; } return children ? <>{children} : ; }; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/context/AuthContext.tsx SIZE: 3365 chars SHA256: 2FABC71795C1598B27643EADA77A0D55B02C7FCBF73BBB202DDAC7A462A79A92 ===================================================================== */ import React, { createContext, useContext, useState, useEffect } from 'react'; import { CurrentUser, UserRole } from '../types'; import { api, setToken, clearToken, getToken } from '../api/client'; import { teacherRealtime } from '../realtime/TeacherRealtime'; import { sessionManager } from '../realtime/SessionManager'; interface AuthContextType { user: CurrentUser | null; token: string | null; login: (username: string, password: string) => Promise; logout: () => void; isLoading: boolean; } const AuthContext = createContext(undefined); export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [user, setUser] = useState(() => { try { const cached = localStorage.getItem('classnotify_user'); return cached ? JSON.parse(cached) : null; } catch { return null; } }); const [token, setTokenState] = useState(getToken()); const [isLoading, setIsLoading] = useState(true); // Subscribe to 401 session expiration useEffect(() => { const unsubscribe = sessionManager.subscribe(() => { teacherRealtime.stop(); clearToken(); setTokenState(null); setUser(null); }); return () => unsubscribe(); }, []); useEffect(() => { const initAuth = async () => { const savedToken = getToken(); if (savedToken) { try { const me = await api.getMe(); setUser(me); localStorage.setItem('classnotify_user', JSON.stringify(me)); sessionManager.reset(); // Start SignalR for authenticated users teacherRealtime.start(); } catch (err: any) { // If 401, sessionManager already handled it. // If network error / 502 / timeout, keep existing cached session and do NOT clear token! if (err?.message?.includes('未授权') || err?.message?.includes('401')) { clearToken(); setTokenState(null); setUser(null); } } } else { clearToken(); setUser(null); setTokenState(null); } setIsLoading(false); }; initAuth(); }, []); const login = async (username: string, password: string): Promise => { const res = await api.login(username, password); if (!res.success || !res.token || !res.role) { throw new Error(res.errorMessage || '登录失败'); } setToken(res.token); setTokenState(res.token); const currentUser: CurrentUser = { userId: res.userId || '', name: res.fullName || username, role: res.role, tenantId: res.tenantId || '', }; setUser(currentUser); localStorage.setItem('classnotify_user', JSON.stringify(currentUser)); sessionManager.reset(); // Start SignalR on login teacherRealtime.start(); return res.role; }; const logout = () => { teacherRealtime.stop(); clearToken(); setTokenState(null); setUser(null); sessionManager.reset(); }; return ( {children} ); }; export const useAuth = () => { const ctx = useContext(AuthContext); if (!ctx) throw new Error('useAuth must be used within an AuthProvider'); return ctx; }; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/index.css SIZE: 503 chars SHA256: 99F80F1313DE3E940567C017B03E34D2E5A8EE9552517F1C9C81546315389284 ===================================================================== */ @tailwind base; @tailwind components; @tailwind utilities; @layer base { body { @apply bg-slate-950 text-slate-100 min-h-screen selection:bg-indigo-500 selection:text-white; } } /* Glassmorphic card styling */ .glass-panel { @apply bg-slate-900/70 backdrop-blur-xl border border-slate-800/80 rounded-2xl shadow-xl; } .glass-card { @apply bg-slate-800/40 backdrop-blur-md border border-slate-700/50 rounded-xl transition-all duration-200 hover:border-slate-600/70 hover:bg-slate-800/60; } /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/main.tsx SIZE: 240 chars SHA256: 79FAF095F462C11B5DC445DAC9043C06809247D25C47F6693FCCD656D1A1D35A ===================================================================== */ import React from 'react'; import ReactDOM from 'react-dom/client'; import { App } from './App'; import './index.css'; ReactDOM.createRoot(document.getElementById('root')!).render( ); /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/pages/admin/ActivationCodes.tsx SIZE: 20779 chars SHA256: 27AA34EB24006DE68B972889BB6CB919AA2ED22C9CB0B882FF02A9DB8207EB5D ===================================================================== */ import React, { useEffect, useState } from 'react'; import { useSearchParams, Link } from 'react-router-dom'; import { api } from '../../api/client'; import { ActivationCode, TenantAdmin, Classroom } from '../../types'; import { KeyRound, Plus, Copy, Check, Clock, CheckCircle2, Trash2, RefreshCw, Search, Building2, Layers, Sparkles, AlertCircle } from 'lucide-react'; export const AdminActivationCodes: React.FC = () => { const [searchParams] = useSearchParams(); const [codes, setCodes] = useState([]); const [tenants, setTenants] = useState([]); const [loading, setLoading] = useState(true); const [copiedCode, setCopiedCode] = useState(null); const [search, setSearch] = useState(''); const [selectedFilterTenant, setSelectedFilterTenant] = useState(''); // Modal state const [showModal, setShowModal] = useState(false); const [selectedTenant, setSelectedTenant] = useState(''); const [classes, setClasses] = useState([]); const [loadingClasses, setLoadingClasses] = useState(false); const [selectedClassId, setSelectedClassId] = useState(''); const [isCustomClass, setIsCustomClass] = useState(false); const [customClassId, setCustomClassId] = useState(''); const [generating, setGenerating] = useState(false); const [generatedResult, setGeneratedResult] = useState<{ code: string; schoolName: string; className: string } | null>(null); const loadData = async () => { try { const [c, t] = await Promise.all([api.getAdminActivationCodes(), api.getTenants()]); setCodes(c); setTenants(t); if (t.length > 0 && !selectedTenant) { setSelectedTenant(t[0].id); } } catch (err) { console.error('Failed to load activation codes', err); } finally { setLoading(false); } }; useEffect(() => { loadData(); }, []); // Handle URL search params useEffect(() => { const urlTenant = searchParams.get('tenantId'); const autoOpen = searchParams.get('openGenerate') === 'true'; if (urlTenant) { setSelectedFilterTenant(urlTenant); setSelectedTenant(urlTenant); if (autoOpen) setShowModal(true); } }, [searchParams]); // Load classrooms when selectedTenant changes useEffect(() => { if (!selectedTenant) return; setLoadingClasses(true); api.getAdminClasses(selectedTenant) .then((cls) => { setClasses(cls); if (cls.length > 0) { setSelectedClassId(cls[0].id); setIsCustomClass(false); } else { setSelectedClassId(''); setIsCustomClass(true); } }) .catch((err) => { console.warn('Could not load classes for tenant:', selectedTenant, err); setClasses([]); setIsCustomClass(true); }) .finally(() => setLoadingClasses(false)); }, [selectedTenant]); const copyToClipboard = (code: string) => { navigator.clipboard.writeText(code); setCopiedCode(code); setTimeout(() => setCopiedCode(null), 2000); }; const handleGenerate = async (e: React.FormEvent) => { e.preventDefault(); const finalClassId = isCustomClass ? customClassId.trim() : selectedClassId.trim(); if (!selectedTenant || !finalClassId) { alert('请选择学校及目标班级'); return; } setGenerating(true); try { const res = await api.generateAdminCode(selectedTenant, finalClassId); const schoolObj = tenants.find((t) => t.id === selectedTenant); const classObj = classes.find((c) => c.id === finalClassId); setGeneratedResult({ code: res.code, schoolName: schoolObj?.name || selectedTenant, className: classObj?.displayName || finalClassId, }); setShowModal(false); setCustomClassId(''); loadData(); } catch (err: any) { alert(err.message || '生成激活码失败'); } finally { setGenerating(false); } }; const handleDelete = async (code: string) => { if (!window.confirm(`确定要废弃/删除激活码 [${code}] 吗?废弃后将无法用于设备初始化绑定。`)) { return; } try { await api.deleteActivationCode(code); loadData(); } catch (err: any) { alert(err.message || '删除激活码失败'); } }; const filteredCodes = codes.filter((c) => { const matchesTenant = !selectedFilterTenant || c.tenantId === selectedFilterTenant; const matchesSearch = c.code.toLowerCase().includes(search.toLowerCase()) || c.classroomName.toLowerCase().includes(search.toLowerCase()) || c.tenantName.toLowerCase().includes(search.toLowerCase()); return matchesTenant && matchesSearch; }); return (
{/* Top Banner & Action */}

全网设备激活码大盘

生成与管理各学校教室电脑安装所需的 8 位一次性硬件绑定激活码,支持过期清理与强制废除

{/* Generated Success Callout */} {generatedResult && (
激活码生成成功!
归属:{generatedResult.schoolName} / {generatedResult.className}(有效期 7 天,一次性硬件绑定)
{generatedResult.code}
)} {/* Filter Toolbar */}
setSearch(e.target.value)} placeholder="搜索激活码、班级或学校..." className="bg-transparent border-none text-xs text-white placeholder-slate-500 focus:outline-none w-full" />
共 {filteredCodes.length} 个激活码
{/* Codes Table */}
{filteredCodes.length === 0 ? ( ) : ( filteredCodes.map((c) => ( {/* Code */} {/* School / Class */} {/* Status */} {/* Device info */} {/* Expiry */} {/* Actions */} )) )}
激活码 绑定学校 / 班级 使用状态 激活设备 有效期限 操作
{loading ? '正在读取激活码...' : '暂无匹配的激活码'}
点击右上角“生成新激活码”即可为任意学校教室开通绑定码
{c.code}
{c.classroomName}
{c.tenantName}
{c.isUsed ? ( 已激活绑定 ) : ( 等待激活 )} {c.usedByDeviceId ? ( {c.usedByDeviceId} ) : ( - )} {new Date(c.expiresAt).toLocaleDateString()} {new Date(c.expiresAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
{/* Generate Code Modal */} {showModal && (

生成班级设备激活码

{/* Select School */}
{/* Select Classroom */}
{loadingClasses ? (
正在读取该校班级列表...
) : isCustomClass ? ( setCustomClassId(e.target.value)} placeholder="输入班级编号,如 cls_801" className="w-full px-3 py-2.5 rounded-xl bg-slate-950 border border-slate-700 text-white text-sm focus:ring-2 focus:ring-amber-500 focus:outline-none" required /> ) : classes.length > 0 ? ( ) : (
该校暂无预设班级,请手动输入班级代码:
setCustomClassId(e.target.value)} placeholder="如 cls_801 或 cls_new" className="w-full px-3 py-2.5 rounded-xl bg-slate-950 border border-slate-700 text-white text-sm focus:ring-2 focus:ring-amber-500 focus:outline-none" required />
)}
💡 使用说明:
1. 激活码生成后有效期为 7 天;
2. 在教室电脑上运行 ClassNotify 安装程序,输入此激活码即可完成班级与屏幕绑定。
)}
); }; export const ActivationCodes = AdminActivationCodes; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/pages/admin/AdminDashboard.tsx SIZE: 16461 chars SHA256: 68B372020850C0BC17EC83BB413E33EC2A5473617593BE0EA23248B6C5E96051 ===================================================================== */ import React, { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; import { api } from '../../api/client'; import { AdminMetrics, TenantAdmin, NotificationRecord, SystemHealth, AdminAuditLog } from '../../types'; import { Building2, Monitor, Bell, Activity, CheckCircle2, Clock, Radio, Users, KeyRound, Database, Cpu, ShieldCheck, AlertTriangle, ArrowRight } from 'lucide-react'; export const AdminDashboard: React.FC = () => { const [metrics, setMetrics] = useState(null); const [tenants, setTenants] = useState([]); const [recentNotifs, setRecentNotifs] = useState([]); const [health, setHealth] = useState(null); const [auditLogs, setAuditLogs] = useState([]); const [loading, setLoading] = useState(true); const loadData = async () => { try { const [m, t, n, h, a] = await Promise.all([ api.getAdminMetrics(), api.getTenants(), api.getAdminNotifications(6), api.getSystemHealth().catch(() => null), api.getAuditLogs(6).catch(() => []), ]); setMetrics(m); setTenants(t); setRecentNotifs(n); if (h) setHealth(h); if (a) setAuditLogs(a); } catch (err) { console.error('Failed to load admin dashboard data', err); } finally { setLoading(false); } }; useEffect(() => { loadData(); const timer = setInterval(loadData, 10000); // 10s auto-refresh return () => clearInterval(timer); }, []); return (
{/* Top Header & System Health Live Pill */}

全域云控超管总览

实时管控多校区实体、网格化终端生命周期、底层微内核与紧急调度通道

生成设备激活码 {/* Real Live Health Status */}
{health?.databaseConnected ? (
PostgreSQL 正常 ({health.databaseLatencyMs.toFixed(1)}ms)
) : (
数据库异常断开
)} |
在线屏: {health?.onlineDevices ?? metrics?.onlineDevices ?? 0}
|
运行: {health?.uptime || '99.98%'}
{/* Metric Cards */}
{/* Total Tenants */}
入驻学校 / 租户
{loading ? '-' : metrics?.totalTenants ?? 0} 所校区
{/* Total Devices */}
总设备数量
{loading ? '-' : metrics?.totalDevices ?? 0} 台教室终端
{/* Online Devices */}
在线设备 (实时连通)
{loading ? '-' : metrics?.onlineDevices ?? 0} / 离线 {loading ? '-' : metrics?.offlineDevices ?? 0}
{/* Today Notifications */}
今日呼叫通知
{loading ? '-' : metrics?.todayNotifications ?? 0} 次下发
{/* Quick Access Control Plane Panels */}

核心管控中枢入口

学校租户
入驻、变更与冻结
用户中枢
跨校开户、改密与封禁
设备集控
心跳、远程指令与清退
激活码大盘 快速生成
生成、绑定与废除
应急广播
全域群发与强置顶
{/* Grid: Tenants Summary & Recent Audit Logs */}
{/* Tenants List */}

各校区终端在线统计

管理学校 →
{tenants.map((t) => { const rate = t.deviceCount > 0 ? Math.round((t.onlineCount / t.deviceCount) * 100) : 0; return ( ); })}
学校名称 班级数 设备数 在线状态 在线率
{t.name} ({t.id}) {t.classroomCount} {t.deviceCount} {t.onlineCount} / {t.deviceCount} 在线 = 80 ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : rate > 0 ? 'bg-amber-500/10 text-amber-400 border border-amber-500/30' : 'bg-slate-800 text-slate-400' }`} > {rate}%
{/* Admin Audit Trail Feed */}

管理员关键操作审计

不可篡改
{auditLogs.length === 0 ? (
暂无审计记录
) : ( auditLogs.map((log) => (
{log.action} {new Date(log.occurredAt).toLocaleTimeString()}
{log.details || log.targetId}
操作者: {log.actorUsername} {log.targetType}
)) )}
); }; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/pages/admin/DeviceManagement.tsx SIZE: 16822 chars SHA256: 9CF45E48FBC2D0A534ECE8660C3293B4E43540618C721EB7D238A5DC4A921DA2 ===================================================================== */ import React, { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; import { api } from '../../api/client'; import { DeviceAdmin } from '../../types'; import { Monitor, RefreshCw, RotateCcw, Activity, CheckCircle2, AlertCircle, Search, Edit3, Trash2, Clock, KeyRound } from 'lucide-react'; export const DeviceManagement: React.FC = () => { const [devices, setDevices] = useState([]); const [loading, setLoading] = useState(true); const [search, setSearch] = useState(''); const [commandResult, setCommandResult] = useState<{ deviceId: string; message: string; success: boolean; } | null>(null); const [actionLoading, setActionLoading] = useState(null); // Edit Device State const [editingDevice, setEditingDevice] = useState(null); const [editHostname, setEditHostname] = useState(''); const [editClassroomId, setEditClassroomId] = useState(''); const [editLoading, setEditLoading] = useState(false); const loadDevices = async () => { try { const data = await api.getAllDevices(); setDevices(data); } catch (err) { console.error('Failed to load devices', err); } finally { setLoading(false); } }; useEffect(() => { loadDevices(); const interval = setInterval(loadDevices, 5000); // Live poll return () => clearInterval(interval); }, []); const handleCommand = async (deviceId: string, cmd: string, params?: string) => { setActionLoading(`${deviceId}_${cmd}`); setCommandResult(null); try { const res = await api.sendDeviceCommand(deviceId, cmd, params); setCommandResult({ deviceId, message: res.message, success: true, }); loadDevices(); } catch (err: any) { setCommandResult({ deviceId, message: err.message || '远程指令下发失败', success: false, }); } finally { setActionLoading(null); } }; const openEdit = (d: DeviceAdmin) => { setEditingDevice(d); setEditHostname(d.hostname || ''); setEditClassroomId(d.classroomId || ''); }; const handleSaveEdit = async (e: React.FormEvent) => { e.preventDefault(); if (!editingDevice) return; setEditLoading(true); try { await api.updateDevice(editingDevice.deviceId, { hostname: editHostname.trim() || undefined, classroomId: editClassroomId.trim() || undefined, }); setCommandResult({ deviceId: editingDevice.deviceId, message: '设备信息更新成功', success: true, }); setEditingDevice(null); loadDevices(); } catch (err: any) { setCommandResult({ deviceId: editingDevice.deviceId, message: err.message || '更新设备失败', success: false, }); } finally { setEditLoading(false); } }; const handleDecommission = async (d: DeviceAdmin) => { if (!window.confirm(`高危操作确认:确定要注销并清退设备 [${d.deviceId} (${d.hostname || d.classroomName})] 吗?\n清退后该设备将无法接入,需重新生成激活码绑定!`)) { return; } setActionLoading(`decommission_${d.deviceId}`); try { await api.decommissionDevice(d.deviceId); setCommandResult({ deviceId: d.deviceId, message: '设备已成功清退并注销', success: true, }); loadDevices(); } catch (err: any) { setCommandResult({ deviceId: d.deviceId, message: err.message || '清退设备失败', success: false, }); } finally { setActionLoading(null); } }; const formatHeartbeat = (timeStr?: string) => { if (!timeStr) return '从无心跳'; const diff = Math.floor((Date.now() - new Date(timeStr).getTime()) / 1000); if (diff < 10) return '刚刚 (几秒前)'; if (diff < 60) return `${diff} 秒前`; if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前`; return `${Math.floor(diff / 3600)} 小时前`; }; const filteredDevices = devices.filter( (d) => d.tenantName.toLowerCase().includes(search.toLowerCase()) || d.classroomName.toLowerCase().includes(search.toLowerCase()) || d.deviceId.toLowerCase().includes(search.toLowerCase()) || (d.hostname && d.hostname.toLowerCase().includes(search.toLowerCase())) ); return (
{/* Header */}

全网设备集控中心

实时监控教室终端健康心跳与服务状态,支持在线秒级下发或离线指令入队补发、元数据变更与清退

生成新设备激活码
{/* Command Result Banner */} {commandResult && (
{commandResult.success ? ( ) : ( )} [设备 {commandResult.deviceId}] {commandResult.message}
)} {/* Search Filter */}
setSearch(e.target.value)} placeholder="按学校、班级、设备编号或计算机名过滤..." className="bg-transparent border-none text-sm text-white placeholder-slate-500 focus:outline-none w-full" /> {search && ( )}
{/* Devices Table */}
{filteredDevices.length === 0 ? ( ) : ( filteredDevices.map((d) => ( {/* School / Class */} {/* Device ID / Hostname */} {/* Status */} {/* Last Heartbeat */} {/* Version */} {/* Operations */} )) )}
学校 / 班级 设备编号 / 主机名 运行状态 心跳与 IP 版本 运维指令与管理
{loading ? '正在同步设备状态...' : '暂无匹配的设备'}
{d.classroomName}
{d.tenantName}
{d.deviceId}
{d.hostname || 'Classroom-PC'}
{d.isOnline ? (
在线 (实时连通)
) : (
离线 (支持离线入队)
)}
{formatHeartbeat(d.lastHeartbeat)}
{d.remoteIp || '127.0.0.1'}
v{d.clientVersion || '2.1.0'}
{/* Ping / SelfCheck (Offline queuing supported!) */} {/* Restart Client */} {/* Refresh Config */} {/* Edit metadata */} {/* Decommission */}
{/* Edit Modal */} {editingDevice && (

调整设备元数据

设备唯一识别码: {editingDevice.deviceId}

setEditHostname(e.target.value)} placeholder="例如: LAB-BUILDING-201-PC" className="w-full px-3 py-2 rounded-xl bg-slate-800 border border-slate-700 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500" />
setEditClassroomId(e.target.value)} placeholder="例如: cls_801" className="w-full px-3 py-2 rounded-xl bg-slate-800 border border-slate-700 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500" />
)}
); }; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/pages/admin/EmergencyBroadcast.tsx SIZE: 24823 chars SHA256: 922E86B403FD4B2A7D8FD47090FAC7BF08877B4C7CFFC18E15BD4F28245B223E ===================================================================== */ import React, { useEffect, useState } from 'react'; import { api } from '../../api/client'; import { TenantAdmin, EmergencyBroadcastRequest, NotificationRecord, BroadcastReceiptSummary } from '../../types'; import { Radio, AlertTriangle, Send, Volume2, Vibrate, Clock, Building2, CheckCircle2, ShieldAlert, Flame, CloudRain, Users, Megaphone, Loader2, X, History, Tv } from 'lucide-react'; export const EmergencyBroadcast: React.FC = () => { const [tenants, setTenants] = useState([]); const [loadingTenants, setLoadingTenants] = useState(true); const [recentBroadcasts, setRecentBroadcasts] = useState([]); const [loadingHistory, setLoadingHistory] = useState(false); const [form, setForm] = useState({ tenantId: '', title: '⚠️ 全校紧急预警通报', message: '', voice: true, shake: true, durationSeconds: 30, }); // Modal & Submit State const [showConfirmModal, setShowConfirmModal] = useState(false); const [submitting, setSubmitting] = useState(false); const [activeBroadcastId, setActiveBroadcastId] = useState(null); const [receiptSummary, setReceiptSummary] = useState(null); const [result, setResult] = useState<{ dispatchedCount: number; targetSchools: number; message: string; success: boolean; timestamp: string; } | null>(null); const templates = [ { title: '⚠️ 消防紧急疏散演练', content: '全体师生请注意:现在进行全校紧急消防演练,请任课老师组织学生按预定疏散路线迅速、有序撤离至操场,不要慌乱!', duration: 60, shake: true, voice: true, icon: Flame, }, { title: '⛈️ 恶劣雷雨大风避险通报', content: '气象台发布雷电暴雨黄色预警,请各班立即紧闭门窗,切断教室非必要电器电源,严禁学生前往走廊与室外活动!', duration: 45, shake: true, voice: true, icon: CloudRain, }, { title: '📢 临时紧急集合通知', content: '请全体班主任与班长立即到行政楼二楼报告厅参加紧急安全调度会议,其余同学保持教室内安静自习。', duration: 30, shake: false, voice: true, icon: Users, }, { title: '🔔 全校临时作息调整', content: '因突发教学安排,今天下午放学时间调整为 16:30,请任课老师提醒学生整理个人物品按时离校。', duration: 30, shake: false, voice: true, icon: Megaphone, }, ]; const fetchTenants = async () => { try { const data = await api.getTenants(); setTenants(data); } catch (err) { console.error('Failed to load tenants', err); } finally { setLoadingTenants(false); } }; const fetchRecentBroadcasts = async () => { setLoadingHistory(true); try { const data = await api.getAdminNotifications(15); // Filter urgent broadcasts or show recent ones setRecentBroadcasts(data); } catch (err) { console.error('Failed to load recent broadcasts', err); } finally { setLoadingHistory(false); } }; useEffect(() => { fetchTenants(); fetchRecentBroadcasts(); }, []); const handleApplyTemplate = (tpl: typeof templates[0]) => { setForm((prev) => ({ ...prev, title: tpl.title, message: tpl.content, durationSeconds: tpl.duration, shake: tpl.shake, voice: tpl.voice, })); }; const handlePreBroadcast = (e: React.FormEvent) => { e.preventDefault(); if (!form.message.trim()) { alert('请输入广播通知正文'); return; } setShowConfirmModal(true); }; useEffect(() => { if (!activeBroadcastId) return; let stopped = false; let timer: number | undefined; const startTime = Date.now(); const poll = async () => { try { const summary = await api.getBroadcastReceiptSummary(activeBroadcastId); if (stopped) return; setReceiptSummary(summary); if (!summary.completed && Date.now() - startTime < 60000) { timer = window.setTimeout(poll, 2000); } } catch { if (!stopped && Date.now() - startTime < 60000) { timer = window.setTimeout(poll, 3000); } } }; poll(); return () => { stopped = true; if (timer) clearTimeout(timer); }; }, [activeBroadcastId]); const handleExecuteBroadcast = async () => { setSubmitting(true); try { const res = await api.sendEmergencyBroadcast({ ...form, tenantId: form.tenantId || undefined, }); if (res.broadcastId) { setActiveBroadcastId(res.broadcastId); } setResult({ dispatchedCount: res.dispatchedCount, targetSchools: res.targetSchools, message: res.message, success: true, timestamp: new Date().toLocaleTimeString(), }); setShowConfirmModal(false); setForm((prev) => ({ ...prev, message: '' })); fetchRecentBroadcasts(); } catch (err: any) { setResult({ dispatchedCount: 0, targetSchools: 0, message: err.message || '应急广播下发失败', success: false, timestamp: new Date().toLocaleTimeString(), }); setShowConfirmModal(false); } finally { setSubmitting(false); } }; // Target summary calculation const selectedTenant = tenants.find((t) => t.id === form.tenantId); const totalClassesTargeted = selectedTenant ? selectedTenant.classroomCount : tenants.reduce((acc, t) => acc + (t.classroomCount || 0), 0); const totalDevicesTargeted = selectedTenant ? selectedTenant.deviceCount : tenants.reduce((acc, t) => acc + (t.deviceCount || 0), 0); return (
{/* Header */}

全域紧急应急广播

超级管理员最高优先调度通道,覆盖全网多校区所有教室大屏终端,支持强置顶、TTS 语音播报与视效抖动

{/* Result Breakdown Panel */} {result && (
{result.success ? ( ) : ( )}

{result.success ? '全域紧急广播指令已成功下发' : '广播下发遇到异常'}

{result.message}

{result.success && (
目标学校: {result.targetSchools} 所 投递教室班级: {result.dispatchedCount} 间 下发时间: {result.timestamp}
)} {/* Real-time Receipt Aggregation */} {receiptSummary && (
目标终端设备 {receiptSummary.targetDevices}
已在屏幕显示 {receiptSummary.displayed}
排队 / 离线等待 {receiptSummary.pending}
已取消 {receiptSummary.cancelled}
失败 / 超时 {receiptSummary.failed}
)}
)} {/* Quick Templates */}

应急广播预设模板 (点击快速填装)

{templates.map((tpl, i) => { const Icon = tpl.icon; return ( ); })}
{/* Form Panel */}
{/* Target Scope */}
setForm({ ...form, title: e.target.value })} className="w-full px-3.5 py-2.5 rounded-xl bg-slate-900/80 border border-slate-700 text-sm text-white focus:outline-none focus:border-indigo-500" placeholder="例如: ⚠️ 全校紧急避险预警" />
{/* Broadcast Message */}