================================================================================ ClassNotify P2.2 SuperAdmin Control Plane & Multi-Tenant Reconstruction Bundle Timestamp: 2026-09-23T16:08:29.086Z Total Files: 14 ================================================================================ ================================================================================ FILE: src/Server/ClassNotify.Server/Controllers/AdminController.cs ================================================================================ using System.Security.Claims; using ClassNotify.Server.Hubs; using ClassNotify.Server.Services; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; namespace ClassNotify.Server.Controllers; [ApiController] [Route("api/[controller]")] [Authorize(Roles = "SuperAdmin")] public class AdminController : ControllerBase { private readonly ISecurityService _securityService; private readonly IHubContext _deviceHub; private readonly IHubContext _teacherHub; private readonly ILogger _logger; public AdminController( ISecurityService securityService, IHubContext deviceHub, IHubContext teacherHub, ILogger logger) { _securityService = securityService; _deviceHub = deviceHub; _teacherHub = teacherHub; _logger = logger; } private string GetActorUsername() => User.FindFirst(ClaimTypes.Name)?.Value ?? "admin"; private string GetActorRole() => User.FindFirst(ClaimTypes.Role)?.Value ?? "SuperAdmin"; private string? GetClientIp() => HttpContext.Connection.RemoteIpAddress?.ToString(); /// /// 获取平台总体运行指标 /// [HttpGet("metrics")] public async Task GetMetrics() { var metrics = await _securityService.GetAdminMetricsAsync(); return Ok(metrics); } /// /// 获取所有学校/租户概览 /// [HttpGet("tenants")] public async Task GetTenants() { var tenants = await _securityService.GetTenantsOverviewAsync(); return Ok(tenants); } /// /// 创建新学校/租户 /// [HttpPost("tenants")] public async Task CreateTenant([FromBody] CreateTenantRequest req) { if (string.IsNullOrWhiteSpace(req.Id) || string.IsNullOrWhiteSpace(req.Name)) { return BadRequest(new { success = false, message = "学校代码与名称不能为空" }); } try { var tenant = await _securityService.CreateTenantAsync(req.Id.Trim(), req.Name.Trim()); await _securityService.LogAdminAuditAsync( GetActorUsername(), GetActorRole(), "CREATE_TENANT", "Tenant", tenant.Id, $"创建学校: {tenant.Name} ({tenant.Id})", GetClientIp()); return Ok(tenant); } catch (InvalidOperationException ex) { return Conflict(new { success = false, message = ex.Message }); } } /// /// 更新学校信息或停用/启用学校 /// [HttpPatch("tenants/{tenantId}")] public async Task UpdateTenant(string tenantId, [FromBody] UpdateTenantRequest req) { if (string.IsNullOrWhiteSpace(req.Name)) { return BadRequest(new { success = false, message = "学校名称不能为空" }); } var updated = await _securityService.UpdateTenantAsync(tenantId, req.Name.Trim(), req.IsActive); if (updated == null) { return NotFound(new { success = false, message = "未找到指定学校" }); } await _securityService.LogAdminAuditAsync( GetActorUsername(), GetActorRole(), "UPDATE_TENANT", "Tenant", tenantId, $"更新学校: {req.Name}, 启用状态: {req.IsActive}", GetClientIp()); return Ok(updated); } /// /// 获取平台用户列表 (支持按租户和角色筛选) /// [HttpGet("users")] public async Task GetUsers([FromQuery] string? tenantId, [FromQuery] string? role) { var users = await _securityService.GetAllUsersAdminAsync(tenantId, role); return Ok(users); } /// /// 创建新用户 (严格执行角色白名单校验: 仅限 SchoolAdmin 或 Teacher) /// [HttpPost("users")] public async Task CreateUser([FromBody] CreateUserAdminRequest req) { if (string.IsNullOrWhiteSpace(req.Username) || string.IsNullOrWhiteSpace(req.Password)) { return BadRequest(new { success = false, message = "用户名与密码不能为空" }); } if (string.IsNullOrWhiteSpace(req.TenantId)) { return BadRequest(new { success = false, message = "必须指定归属学校" }); } if (req.Role != "SchoolAdmin" && req.Role != "Teacher") { return BadRequest(new { success = false, message = "只允许创建校区管理员 (SchoolAdmin) 或教师账号 (Teacher)" }); } try { var user = await _securityService.CreateUserAdminAsync(req); await _securityService.LogAdminAuditAsync( GetActorUsername(), GetActorRole(), "CREATE_USER", "User", user.Username, $"创建用户: {user.FullName} ({user.Role}),学校: {user.TenantName}", GetClientIp()); return Ok(user); } catch (InvalidOperationException ex) { return Conflict(new { success = false, message = ex.Message }); } } /// /// 管理员重置指定用户密码 /// [HttpPost("users/{userId}/reset-password")] public async Task ResetPassword(string userId, [FromBody] ResetPasswordRequest req) { if (string.IsNullOrWhiteSpace(req.NewPassword)) { return BadRequest(new { success = false, message = "新密码不能为空" }); } var ok = await _securityService.ResetPasswordAsync(userId, req.NewPassword); if (!ok) { return NotFound(new { success = false, message = "用户不存在" }); } await _securityService.LogAdminAuditAsync( GetActorUsername(), GetActorRole(), "RESET_PASSWORD", "User", userId, "管理员重置用户登录密码", GetClientIp()); return Ok(new { success = true, message = "密码已成功重置" }); } /// /// 锁定或解锁用户账号 /// [HttpPost("users/{userId}/lock")] public async Task SetUserLock(string userId, [FromBody] LockUserRequest req) { var ok = await _securityService.SetUserLockAsync(userId, req.IsLocked); if (!ok) { return NotFound(new { success = false, message = "用户不存在" }); } var action = req.IsLocked ? "LOCK_USER" : "UNLOCK_USER"; var detail = req.IsLocked ? "锁定账号 (禁止登录)" : "解锁账号 (恢复登录)"; await _securityService.LogAdminAuditAsync(GetActorUsername(), GetActorRole(), action, "User", userId, detail, GetClientIp()); return Ok(new { success = true, isLocked = req.IsLocked, message = detail }); } /// /// 删除指定用户 /// [HttpDelete("users/{userId}")] public async Task DeleteUser(string userId) { var ok = await _securityService.DeleteUserAsync(userId); if (!ok) { return NotFound(new { success = false, message = "用户不存在或无法删除" }); } await _securityService.LogAdminAuditAsync( GetActorUsername(), GetActorRole(), "DELETE_USER", "User", userId, "删除用户", GetClientIp()); return Ok(new { success = true, message = "用户已删除" }); } /// /// 获取全网所有设备及其在线状态、心跳、版本 /// [HttpGet("devices")] public async Task GetDevices() { var devices = await _securityService.GetAllDevicesAsync(); return Ok(devices); } /// /// 更新设备信息 (主机名/重命名、绑定班级) /// [HttpPatch("devices/{deviceId}")] public async Task UpdateDevice(string deviceId, [FromBody] UpdateDeviceRequest req) { var ok = await _securityService.UpdateDeviceAsync(deviceId, req.Hostname, req.ClassroomId); if (!ok) { return NotFound(new { success = false, message = "设备不存在" }); } await _securityService.LogAdminAuditAsync( GetActorUsername(), GetActorRole(), "UPDATE_DEVICE", "Device", deviceId, $"更新设备元数据: 主机名={req.Hostname}, 绑定班级={req.ClassroomId}", GetClientIp()); return Ok(new { success = true, message = "设备信息已更新" }); } /// /// 清退并注销指定设备 /// [HttpPost("devices/{deviceId}/decommission")] public async Task DecommissionDevice(string deviceId) { var ok = await _securityService.DecommissionDeviceAsync(deviceId); if (!ok) { return NotFound(new { success = false, message = "设备不存在" }); } await _securityService.LogAdminAuditAsync( GetActorUsername(), GetActorRole(), "DECOMMISSION_DEVICE", "Device", deviceId, "注销并清退设备", GetClientIp()); return Ok(new { success = true, message = "设备已注销并清退" }); } /// /// 向指定设备下发远程维护指令 (SelfCheck, RestartClient, Reconnect, RefreshConfig) /// [HttpPost("devices/{deviceId}/command")] public async Task SendDeviceCommand(string deviceId, [FromBody] RemoteCommandRequestDto req) { if (string.IsNullOrWhiteSpace(deviceId) || string.IsNullOrWhiteSpace(req.Command)) { return BadRequest(new { success = false, message = "设备编号与指令内容不可为空" }); } try { var adminUser = GetActorUsername(); var cmdType = req.Command; if (cmdType.Equals("ping", StringComparison.OrdinalIgnoreCase)) cmdType = DeviceCommandTypes.SelfCheck; else if (cmdType.Equals("restart_client", StringComparison.OrdinalIgnoreCase)) cmdType = DeviceCommandTypes.RestartClient; else if (cmdType.Equals("refresh_config", StringComparison.OrdinalIgnoreCase)) cmdType = DeviceCommandTypes.RefreshConfig; else if (cmdType.Equals("reconnect", StringComparison.OrdinalIgnoreCase)) cmdType = DeviceCommandTypes.Reconnect; if (!DeviceCommandTypes.IsSupported(cmdType)) { return BadRequest(new { success = false, message = $"不支持的指令类型: '{req.Command}'。允许指令: {string.Join(", ", DeviceCommandTypes.AllSupported)}" }); } var cmdDto = await _securityService.CreateDeviceCommandAsync(null, deviceId, cmdType, req.Parameters, adminUser); var connId = _securityService.GetDeviceConnectionId(deviceId); if (!string.IsNullOrEmpty(connId)) { await _deviceHub.Clients.Client(connId).ReceiveRemoteCommand(cmdDto); await _securityService.MarkCommandDispatchedAsync(cmdDto.CommandId); cmdDto.Status = DeviceCommandStatuses.Dispatched; _logger.LogInformation("Admin dispatched remote command {CommandId} ('{Command}') to device {DeviceId} ({ConnId})", cmdDto.CommandId, cmdDto.CommandType, deviceId, connId); } else { _logger.LogInformation("Device {DeviceId} is offline. Remote command {CommandId} queued as Pending (expires at {ExpiresAt})", deviceId, cmdDto.CommandId, cmdDto.ExpiresAt); } await _securityService.LogAdminAuditAsync( adminUser, GetActorRole(), "REMOTE_COMMAND", "Device", deviceId, $"指令: {cmdDto.CommandType}, 状态: {cmdDto.Status}", GetClientIp()); return Ok(new { success = true, commandId = cmdDto.CommandId, deviceId, command = cmdDto.CommandType, status = cmdDto.Status, expiresAt = cmdDto.ExpiresAt, message = string.IsNullOrEmpty(connId) ? $"设备当前离线,指令 [{cmdDto.CommandType}] 已入队,将在设备上线时自动补发 (有效期至 {cmdDto.ExpiresAt:u})" : $"远程指令 [{cmdDto.CommandType}] 已通过 SignalR 实时下发至设备" }); } catch (ArgumentException ex) { return BadRequest(new { success = false, message = ex.Message }); } catch (InvalidOperationException ex) { return NotFound(new { success = false, message = ex.Message }); } } /// /// 获取全网激活码列表 /// [HttpGet("activation-codes")] public async Task GetActivationCodes() { var codes = await _securityService.GetActivationCodesAsync(null); return Ok(codes); } /// /// 超级管理员直接生成指定学校指定班级的激活码 /// [HttpPost("activation-codes")] public async Task GenerateActivationCode([FromQuery] string tenantId, [FromQuery] string classId) { if (string.IsNullOrWhiteSpace(tenantId) || string.IsNullOrWhiteSpace(classId)) { return BadRequest(new { success = false, message = "租户与班级不可为空" }); } var code = await _securityService.GenerateActivationCodeAsync(tenantId, classId); await _securityService.LogAdminAuditAsync( GetActorUsername(), GetActorRole(), "GENERATE_ACTIVATION_CODE", "ActivationCode", code, $"为学校 {tenantId} 班级 {classId} 生成激活码", GetClientIp()); return Ok(new { success = true, code, tenantId, classId, message = "激活码生成成功" }); } /// /// 作废或删除激活码 /// [HttpDelete("activation-codes/{code}")] public async Task DeleteActivationCode(string code) { var ok = await _securityService.DeleteActivationCodeAsync(code); if (!ok) { return NotFound(new { success = false, message = "激活码不存在" }); } await _securityService.LogAdminAuditAsync( GetActorUsername(), GetActorRole(), "DELETE_ACTIVATION_CODE", "ActivationCode", code, "作废/删除激活码", GetClientIp()); return Ok(new { success = true, message = "激活码已成功作废" }); } /// /// 获取全平台最新通知历史记录与 ACK /// [HttpGet("notifications")] public async Task GetNotifications([FromQuery] int limit = 50) { var list = await _securityService.GetNotificationsAsync(null, null, limit); return Ok(list); } /// /// 超级管理员跨租户/全网紧急广播下发 /// [HttpPost("broadcasts")] public async Task EmergencyBroadcast([FromBody] EmergencyBroadcastRequest req) { if (string.IsNullOrWhiteSpace(req.Message)) { return BadRequest(new { success = false, message = "广播内容不能为空" }); } var actor = GetActorUsername(); var targetTenants = new List(); if (string.IsNullOrWhiteSpace(req.TenantId) || req.TenantId == "*") { targetTenants = await _securityService.GetTenantsOverviewAsync(); } else { var all = await _securityService.GetTenantsOverviewAsync(); var found = all.FirstOrDefault(t => t.Id == req.TenantId); if (found != null) targetTenants.Add(found); else return NotFound(new { success = false, message = $"未找到指定学校: {req.TenantId}" }); } int dispatchedCount = 0; var duration = req.DurationSeconds > 0 ? req.DurationSeconds : 30; foreach (var tenant in targetTenants) { var classrooms = await _securityService.GetClassroomsAsync(tenant.Id); foreach (var cls in classrooms) { var notif = new NotificationDto { Id = $"msg_emerg_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}_{Guid.NewGuid().ToString("N")[..4]}", TenantId = tenant.Id, ClassId = cls.Id, Title = string.IsNullOrWhiteSpace(req.Title) ? "⚠️ 全校紧急通知" : req.Title, Message = req.Message, Type = NotificationType.Urgent, CreatedAt = DateTimeOffset.UtcNow, ExpiresAt = DateTimeOffset.UtcNow.AddSeconds(duration + 120), DurationSeconds = duration, Voice = req.Voice, Shake = req.Shake }; await _securityService.RecordNotificationAsync(notif, null, "系统超级管理员 (应急广播)"); // Dispatch to SignalR classroom group await _deviceHub.Clients.Group($"t:{tenant.Id}:c:{cls.Id}").ReceiveNotification(notif); // Dispatch to Teacher Hub await _teacherHub.Clients.Group($"t:{tenant.Id}:teachers").OnNewNotificationBroadcast(notif); dispatchedCount++; } } await _securityService.LogAdminAuditAsync( actor, GetActorRole(), "EMERGENCY_BROADCAST", "System", req.TenantId ?? "ALL", $"下发紧急广播: {req.Title} - {req.Message} (覆盖 {dispatchedCount} 个班级)", GetClientIp()); return Ok(new { success = true, dispatchedCount, targetSchools = targetTenants.Count, message = $"紧急广播已成功下发至 {targetTenants.Count} 所学校共 {dispatchedCount} 个班级教室大屏" }); } /// /// 获取平台真实系统健康状态 (数据库连通性、延迟、内存、运行时间、连接数) /// [HttpGet("system/health")] public async Task GetSystemHealth() { var health = await _securityService.GetSystemHealthAsync(); return Ok(health); } /// /// 获取超级管理员关键操作审计日志 /// [HttpGet("audit-logs")] public async Task GetAuditLogs([FromQuery] int limit = 100) { var logs = await _securityService.GetAdminAuditLogsAsync(limit); return Ok(logs); } } ================================================================================ FILE: src/Server/ClassNotify.Server/Services/ISecurityService.cs ================================================================================ using ClassNotify.Server.Domain.Entities; using ClassNotify.Shared.Models; namespace ClassNotify.Server.Services; public sealed record DeviceConnectionRegistrationResult( string CurrentConnectionId, string? ReplacedConnectionId); public interface ISecurityService { // Auth & Identity Task LoginTeacherAsync(TeacherLoginDto dto, string? remoteIp = null); Task ActivateDeviceAsync(DeviceActivationRequestDto dto); Task ValidateDeviceAsync(string deviceId, string deviceToken); // Tenant & Classrooms Task GetClassroomAsync(string tenantId, string classId); Task> GetClassroomsAsync(string tenantId); Task CreateClassroomAsync(string tenantId, CreateClassroomDto dto); Task GetTenantAsync(string tenantId); Task> GetTenantsOverviewAsync(); // Users Task> GetUsersAsync(string tenantId); Task CreateUserAsync(string tenantId, CreateTeacherDto dto); // Devices & Metrics Task GetAdminMetricsAsync(); Task> GetAllDevicesAsync(); Task> GetTenantDevicesAsync(string tenantId); Task RegisterDeviceConnectionAsync(string connectionId, string deviceId, string tenantId, string classroomId, string? hostname, string? remoteIp, string? clientVersion); Task UnregisterDeviceConnectionAsync(string connectionId); bool IsCurrentDeviceConnection(string deviceId, string connectionId); Task UpdateDeviceHeartbeatAsync(string connectionId); string? GetDeviceConnectionId(string deviceId); // Activation Codes Task GenerateActivationCodeAsync(string tenantId, string classId); Task> GetActivationCodesAsync(string? tenantId); // Notifications & ACKs (PostgreSQL & NotificationReceipt per-device isolation) Task RecordNotificationAsync(NotificationDto notification, string? senderUserId, string senderName); Task RecordAckAsync(string messageId, string authenticatedDeviceId, AckReceiptDto ack); Task ValidateNotificationTargetAsync(string messageId, string tenantId, string classroomId); Task> GetNotificationsAsync(string? tenantId, string? classId, int limit = 50); Task> GetPendingNotificationsForDeviceAsync(string deviceId); // Device Commands (P1 Batch 10) Task CreateDeviceCommandAsync(string? callerTenantId, string deviceId, string commandType, string? parameters, string createdBy); Task MarkCommandDispatchedAsync(string commandId); Task RecordCommandResultAsync(DeviceCommandResultDto result, string callerDeviceId, string? callerTenantId); Task GetDeviceCommandAsync(string commandId, string? callerTenantId = null); Task> GetPendingCommandsForDeviceAsync(string deviceId); Task> GetDeviceCommandHistoryAsync(string? tenantId, string? deviceId, string? status, int limit = 50); // SuperAdmin Control Plane Extensions Task CreateTenantAsync(string id, string name); Task UpdateTenantAsync(string id, string name, bool isActive); Task> GetAllUsersAdminAsync(string? tenantId, string? role); Task CreateUserAdminAsync(CreateUserAdminRequest req); Task ResetPasswordAsync(string userId, string newPassword); Task SetUserLockAsync(string userId, bool isLocked); Task DeleteUserAsync(string userId); Task UpdateDeviceAsync(string deviceId, string? hostname, string? classroomId); Task DecommissionDeviceAsync(string deviceId); Task DeleteActivationCodeAsync(string code); Task GetSystemHealthAsync(); Task LogAdminAuditAsync(string actorUsername, string actorRole, string action, string targetType, string targetId, string? details, string? ip); Task> GetAdminAuditLogsAsync(int limit = 100); } ================================================================================ FILE: src/Server/ClassNotify.Server/Services/SecurityService.cs ================================================================================ using System.Collections.Concurrent; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; namespace ClassNotify.Server.Services; public class LiveConnectionInfo { public string ConnectionId { get; set; } = string.Empty; public string DeviceId { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string? Hostname { get; set; } public string? RemoteIp { get; set; } public string? ClientVersion { get; set; } public DateTimeOffset LastHeartbeat { get; set; } = DateTimeOffset.UtcNow; public LiveConnectionInfo(string connectionId, string deviceId, string tenantId, string classroomId, string? hostname, string? remoteIp, string? clientVersion, DateTimeOffset lastHeartbeat) { ConnectionId = connectionId; DeviceId = deviceId; TenantId = tenantId; ClassroomId = classroomId; Hostname = hostname; RemoteIp = remoteIp; ClientVersion = clientVersion; LastHeartbeat = lastHeartbeat; } } public class SecurityService : ISecurityService { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; private readonly IDataProtector _protector; private readonly IPasswordHasher _passwordHasher; private readonly JwtOptions _jwtOptions; // In-memory real-time SignalR live connection registries (NOT in PostgreSQL) private readonly ConcurrentDictionary _liveConnections = new(); private readonly ConcurrentDictionary _deviceToConnection = new(); private readonly ConcurrentDictionary _connectionTenantMap = new(); // Heartbeat DB update throttle map (at most once every 30s per device) private readonly ConcurrentDictionary _lastHeartbeatDbUpdate = new(); public SecurityService( IServiceScopeFactory scopeFactory, IDataProtectionProvider dataProtectionProvider, IPasswordHasher passwordHasher, IOptions jwtOptions, ILogger logger) { _scopeFactory = scopeFactory; _logger = logger; _protector = dataProtectionProvider.CreateProtector("ClassNotify.DeviceTokens.v1"); _passwordHasher = passwordHasher; _jwtOptions = jwtOptions.Value; } #region Auth & Identity public async Task LoginTeacherAsync(TeacherLoginDto dto, string? remoteIp = null) { if (string.IsNullOrWhiteSpace(dto.Username) || string.IsNullOrWhiteSpace(dto.Password)) { return new TeacherLoginResultDto { Success = false, ErrorMessage = "用户名与密码不可为空" }; } var normalizedUser = dto.Username.Trim(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.FirstOrDefaultAsync(u => u.Username == normalizedUser); if (user == null) { _logger.LogWarning("Authentication failed: User '{Username}' not found. Remote IP: {RemoteIp} at {Timestamp}", normalizedUser, remoteIp ?? "unknown", DateTimeOffset.UtcNow); return new TeacherLoginResultDto { Success = false, ErrorMessage = "用户名或密码错误" }; } bool passwordValid = false; bool needsRehash = false; // 1. Try modern ASP.NET Core PasswordHasher var verifyResult = _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, dto.Password); if (verifyResult == PasswordVerificationResult.Success) { passwordValid = true; } else if (verifyResult == PasswordVerificationResult.SuccessRehashNeeded) { passwordValid = true; needsRehash = true; } else { // 2. Fallback to legacy SHA256 with fixed salt for backward compatibility if (VerifyLegacyPassword(dto.Password, user.PasswordHash)) { passwordValid = true; needsRehash = true; _logger.LogInformation("Legacy password verified for user '{Username}'. Will upgrade to PasswordHasher.", normalizedUser); } } if (!passwordValid) { _logger.LogWarning("Authentication failed: Invalid credentials for user '{Username}'. Remote IP: {RemoteIp} at {Timestamp}", normalizedUser, remoteIp ?? "unknown", DateTimeOffset.UtcNow); return new TeacherLoginResultDto { Success = false, ErrorMessage = "用户名或密码错误" }; } // 3. Automatic on-the-fly hash upgrade if legacy or rehash needed if (needsRehash) { user.PasswordHash = _passwordHasher.HashPassword(user, dto.Password); await db.SaveChangesAsync(); _logger.LogInformation("Password hash successfully upgraded to ASP.NET Core PasswordHasher for user '{Username}'.", normalizedUser); } _logger.LogInformation("User '{Username}' ({UserId}) successfully authenticated from IP {RemoteIp}.", normalizedUser, user.Id, remoteIp ?? "unknown"); var token = GenerateJwtToken(user); return new TeacherLoginResultDto { Success = true, Token = token, UserId = user.Id, FullName = user.FullName, TenantId = user.TenantId, Role = user.Role }; } public async Task ActivateDeviceAsync(DeviceActivationRequestDto dto) { if (string.IsNullOrWhiteSpace(dto.ActivationCode)) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "激活码不可为空" }; } if (string.IsNullOrWhiteSpace(dto.InstallationId) || !dto.InstallationId.StartsWith("inst_") || dto.InstallationId.Length > 50) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "安装实例标识符 (InstallationId) 无效或格式不正确" }; } var normalizedCode = dto.ActivationCode.Trim().ToUpperInvariant(); var normalizedInstId = dto.InstallationId.Trim(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); using var tx = await db.Database.BeginTransactionAsync(); try { var code = await db.ActivationCodes.FirstOrDefaultAsync(c => c.Code == normalizedCode); if (code == null) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "激活码无效" }; } if (code.IsUsed) { // P0-09 / P1-02 Idempotency Rule: If same installationId, return original device credentials if (!string.IsNullOrEmpty(code.InstallationId) && string.Equals(code.InstallationId, normalizedInstId, StringComparison.OrdinalIgnoreCase)) { var existingDev = await db.Devices.FirstOrDefaultAsync(d => (!string.IsNullOrEmpty(code.UsedByDeviceId) && d.Id == code.UsedByDeviceId) || d.InstallationId == normalizedInstId); var existingCred = await db.DeviceCredentials.FirstOrDefaultAsync(c => (!string.IsNullOrEmpty(code.UsedByDeviceId) && c.DeviceId == code.UsedByDeviceId) || c.InstallationId == normalizedInstId); var existingCls = await db.Classrooms.FirstOrDefaultAsync(c => c.TenantId == code.TenantId && c.Id == code.ClassroomId); if (existingDev != null && existingCred != null && existingCls != null) { string recoveredToken; try { recoveredToken = _protector.Unprotect(existingCred.EncryptedRecoverableToken); } catch (Exception ex) { _logger.LogError(ex, "Failed to unprotect recoverable token for InstallationId {InstallationId}", normalizedInstId); return new DeviceActivationResultDto { Success = false, ErrorMessage = "解密设备凭据失败,请联系管理员" }; } _logger.LogInformation("Idempotent activation retry for InstallationId {InstallationId}, returning recovered token for Device {DeviceId}", normalizedInstId, existingDev.Id); return new DeviceActivationResultDto { Success = true, DeviceId = existingDev.Id, DeviceToken = recoveredToken, TenantId = existingCls.TenantId, ClassId = existingCls.Id, ClassDisplayName = existingCls.DisplayName }; } } // Different installationId or unable to match installationId -> 409 Conflict return new DeviceActivationResultDto { Success = false, ErrorMessage = "该激活码已被其他设备安装实例使用" }; } if (code.ExpiresAt < DateTimeOffset.UtcNow) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "激活码已过期" }; } var cls = await db.Classrooms.FirstOrDefaultAsync(c => c.TenantId == code.TenantId && c.Id == code.ClassroomId); if (cls == null) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "绑定的班级不存在" }; } var deviceId = $"dev_{Guid.NewGuid():N}"[..12]; var rawToken = $"dtoken_{Guid.NewGuid():N}"; var tokenHash = HashToken(rawToken); var device = new Device { Id = deviceId, TenantId = code.TenantId, ClassroomId = code.ClassroomId, DeviceTokenHash = tokenHash, InstallationId = normalizedInstId, Hostname = dto.Hostname, IsActive = true, CreatedAt = DateTimeOffset.UtcNow }; var credRecord = new DeviceCredentialRecord { DeviceId = deviceId, InstallationId = normalizedInstId, DeviceTokenHash = tokenHash, EncryptedRecoverableToken = _protector.Protect(rawToken), CreatedAt = DateTimeOffset.UtcNow }; db.Devices.Add(device); db.DeviceCredentials.Add(credRecord); code.IsUsed = true; code.UsedAt = DateTimeOffset.UtcNow; code.UsedByDeviceId = deviceId; code.InstallationId = normalizedInstId; await db.SaveChangesAsync(); await tx.CommitAsync(); _logger.LogInformation("Device {DeviceId} activated successfully for {TenantId} / {ClassId} ({DisplayName}) [InstallationId: {InstallationId}]", deviceId, cls.TenantId, cls.Id, cls.DisplayName, normalizedInstId); return new DeviceActivationResultDto { Success = true, DeviceId = deviceId, DeviceToken = rawToken, TenantId = cls.TenantId, ClassId = cls.Id, ClassDisplayName = cls.DisplayName }; } catch (Exception ex) { await tx.RollbackAsync(); _logger.LogError(ex, "Exception during device activation transaction for code {Code}", normalizedCode); throw; } } public async Task ValidateDeviceAsync(string deviceId, string deviceToken) { if (string.IsNullOrEmpty(deviceId) || string.IsNullOrEmpty(deviceToken)) { return null; } var tokenHash = HashToken(deviceToken); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return await db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == deviceId && d.DeviceTokenHash == tokenHash && d.IsActive); } #endregion #region Tenants & Classrooms public async Task GetTenantAsync(string tenantId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return await db.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == tenantId && t.IsActive); } public async Task> GetTenantsOverviewAsync() { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var tenants = await db.Tenants.AsNoTracking().Where(t => t.Id != "global").ToListAsync(); var classrooms = await db.Classrooms.AsNoTracking().ToListAsync(); var devices = await db.Devices.AsNoTracking().ToListAsync(); var liveSnapshots = _liveConnections.Values.ToList(); return tenants.Select(t => { var classCount = classrooms.Count(c => c.TenantId == t.Id); var deviceCount = devices.Count(d => d.TenantId == t.Id); var onlineCount = liveSnapshots.Count(c => c.TenantId == t.Id); return new TenantAdminDto { Id = t.Id, Name = t.Name, ClassroomCount = classCount, DeviceCount = deviceCount, OnlineCount = onlineCount, IsActive = t.IsActive, CreatedAt = t.CreatedAt }; }).ToList(); } public async Task GetClassroomAsync(string tenantId, string classId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return await db.Classrooms.AsNoTracking().FirstOrDefaultAsync(c => c.TenantId == tenantId && c.Id == classId); } public async Task> GetClassroomsAsync(string tenantId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return await db.Classrooms.AsNoTracking().Where(c => c.TenantId == tenantId).ToListAsync(); } public async Task CreateClassroomAsync(string tenantId, CreateClassroomDto dto) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); if (await db.Classrooms.AnyAsync(c => c.TenantId == tenantId && c.Id == dto.Id)) { return false; } db.Classrooms.Add(new Classroom { Id = dto.Id, TenantId = tenantId, DisplayName = dto.DisplayName, Grade = dto.Grade, RoomNumber = dto.RoomNumber, CreatedAt = DateTimeOffset.UtcNow }); await db.SaveChangesAsync(); return true; } #endregion #region Users public async Task> GetUsersAsync(string tenantId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return await db.Users.AsNoTracking().Where(u => u.TenantId == tenantId).ToListAsync(); } public async Task CreateUserAsync(string tenantId, CreateTeacherDto dto) { if (string.IsNullOrWhiteSpace(dto.Password) || dto.Password.Length < 8) { _logger.LogWarning("CreateUser rejected: Password must be at least 8 characters long."); return false; } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); if (await db.Users.AnyAsync(u => u.Username == dto.Username.Trim())) { return false; } var user = new User { Id = $"usr_{Guid.NewGuid():N}"[..12], TenantId = tenantId, Username = dto.Username.Trim(), FullName = dto.FullName, Role = dto.Role, CreatedAt = DateTimeOffset.UtcNow }; // Strictly use modern PasswordHasher for new user creation user.PasswordHash = _passwordHasher.HashPassword(user, dto.Password); db.Users.Add(user); await db.SaveChangesAsync(); return true; } #endregion #region Devices & Live SignalR Connections public async Task GetAdminMetricsAsync() { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var totalTenants = await db.Tenants.CountAsync(t => t.Id != "global"); var totalClassrooms = await db.Classrooms.CountAsync(); var totalDevices = await db.Devices.CountAsync(); var onlineDevices = _liveConnections.Count; var startOfToday = DateTimeOffset.UtcNow.Date; var todayNotifications = await db.Notifications.CountAsync(n => n.CreatedAt >= startOfToday); return new AdminMetricsDto { TotalTenants = totalTenants, TotalClassrooms = totalClassrooms, TotalDevices = totalDevices, OnlineDevices = onlineDevices, TodayNotifications = todayNotifications, AbnormalDevices = 0 }; } public async Task> GetAllDevicesAsync() { return await BuildDeviceAdminDtosAsync(null); } public async Task> GetTenantDevicesAsync(string tenantId) { return await BuildDeviceAdminDtosAsync(tenantId); } private async Task> BuildDeviceAdminDtosAsync(string? tenantId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.Devices.AsNoTracking(); if (!string.IsNullOrEmpty(tenantId) && tenantId != "global") { query = query.Where(d => d.TenantId == tenantId); } var devices = await query.ToListAsync(); var tenants = await db.Tenants.AsNoTracking().ToDictionaryAsync(t => t.Id, t => t.Name); var classrooms = await db.Classrooms.AsNoTracking().ToDictionaryAsync(c => $"{c.TenantId}_{c.Id}", c => c.DisplayName); var liveSnapshot = _liveConnections.ToDictionary(k => k.Key, v => v.Value); return devices.Select(d => { var isOnline = _deviceToConnection.TryGetValue(d.Id, out var connId) && liveSnapshot.ContainsKey(connId); liveSnapshot.TryGetValue(connId ?? string.Empty, out var connInfo); tenants.TryGetValue(d.TenantId, out var tName); classrooms.TryGetValue($"{d.TenantId}_{d.ClassroomId}", out var cName); return new DeviceAdminDto { DeviceId = d.Id, TenantId = d.TenantId, TenantName = tName ?? d.TenantId, ClassroomId = d.ClassroomId, ClassroomName = cName ?? d.ClassroomId, Hostname = d.Hostname, IsOnline = isOnline, LastHeartbeat = isOnline ? connInfo?.LastHeartbeat : d.LastHeartbeatAt, ClientVersion = isOnline ? connInfo?.ClientVersion : null, RemoteIp = isOnline ? connInfo?.RemoteIp : null, ServiceRunning = isOnline, ClientRunning = isOnline }; }).ToList(); } public Task RegisterDeviceConnectionAsync( string connectionId, string deviceId, string tenantId, string classroomId, string? hostname, string? remoteIp, string? clientVersion) { string? replacedConnectionId = null; if (_deviceToConnection.TryGetValue(deviceId, out var existingConnId)) { replacedConnectionId = existingConnId; _liveConnections.TryRemove(existingConnId, out _); _connectionTenantMap.TryRemove(existingConnId, out _); _logger.LogInformation("Replacing previous ConnectionId {OldConnId} with {NewConnId} for Device {DeviceId}", existingConnId, connectionId, deviceId); } _deviceToConnection[deviceId] = connectionId; var liveInfo = new LiveConnectionInfo(connectionId, deviceId, tenantId, classroomId, hostname, remoteIp, clientVersion, DateTimeOffset.UtcNow); _liveConnections[connectionId] = liveInfo; _connectionTenantMap[connectionId] = (tenantId, classroomId, deviceId); _logger.LogInformation("Device {DeviceId} connected via SignalR. ConnectionId={ConnId}, IP={RemoteIp}", deviceId, connectionId, remoteIp); return Task.FromResult(new DeviceConnectionRegistrationResult(connectionId, replacedConnectionId)); } public Task UnregisterDeviceConnectionAsync(string connectionId) { if (_connectionTenantMap.TryRemove(connectionId, out var info)) { _liveConnections.TryRemove(connectionId, out _); if (_deviceToConnection.TryGetValue(info.DeviceId, out var currentConnId) && currentConnId == connectionId) { _deviceToConnection.TryRemove(info.DeviceId, out _); _logger.LogInformation("Unregistered active device connection {ConnId} for Device {DeviceId}", connectionId, info.DeviceId); return Task.FromResult(true); } else { _logger.LogWarning("Ignored stale disconnect for {ConnId} (Device {DeviceId} active connection is {CurrentConnId})", connectionId, info.DeviceId, currentConnId); return Task.FromResult(false); } } return Task.FromResult(false); } public bool IsCurrentDeviceConnection(string deviceId, string connectionId) { return _deviceToConnection.TryGetValue(deviceId, out var currentConnId) && currentConnId == connectionId; } public Task UpdateDeviceHeartbeatAsync(string connectionId) { if (_liveConnections.TryGetValue(connectionId, out var info)) { info.LastHeartbeat = DateTimeOffset.UtcNow; // Throttled DB heartbeat update (every 30s) var now = DateTimeOffset.UtcNow; var lastUpdate = _lastHeartbeatDbUpdate.GetOrAdd(info.DeviceId, DateTimeOffset.MinValue); if (now - lastUpdate >= TimeSpan.FromSeconds(30)) { _lastHeartbeatDbUpdate[info.DeviceId] = now; _ = Task.Run(async () => { try { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var dev = await db.Devices.FindAsync(info.DeviceId); if (dev != null) { dev.LastHeartbeatAt = now; await db.SaveChangesAsync(); } } catch { } }); } } return Task.CompletedTask; } public string? GetDeviceConnectionId(string deviceId) { return _deviceToConnection.TryGetValue(deviceId, out var connId) ? connId : null; } #endregion #region Activation Codes public async Task GenerateActivationCodeAsync(string tenantId, string classId) { var code = $"{tenantId[..Math.Min(4, tenantId.Length)].ToUpperInvariant()}-{Guid.NewGuid():N}"[..12].ToUpperInvariant(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); db.ActivationCodes.Add(new ActivationCode { Code = code, TenantId = tenantId, ClassroomId = classId, ExpiresAt = DateTimeOffset.UtcNow.AddDays(7), IsUsed = false }); await db.SaveChangesAsync(); return code; } public async Task> GetActivationCodesAsync(string? tenantId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.ActivationCodes.AsNoTracking(); if (!string.IsNullOrEmpty(tenantId) && tenantId != "global") { query = query.Where(c => c.TenantId == tenantId); } var codes = await query.OrderByDescending(c => c.ExpiresAt).ToListAsync(); var tenants = await db.Tenants.AsNoTracking().ToDictionaryAsync(t => t.Id, t => t.Name); var classrooms = await db.Classrooms.AsNoTracking().ToDictionaryAsync(c => $"{c.TenantId}_{c.Id}", c => c.DisplayName); return codes.Select(c => { tenants.TryGetValue(c.TenantId, out var tName); classrooms.TryGetValue($"{c.TenantId}_{c.ClassroomId}", out var cName); return new ActivationCodeDto { Code = c.Code, TenantId = c.TenantId, TenantName = tName ?? c.TenantId, ClassroomId = c.ClassroomId, ClassroomName = cName ?? c.ClassroomId, ExpiresAt = c.ExpiresAt, IsUsed = c.IsUsed, UsedAt = c.UsedAt, UsedByDeviceId = c.UsedByDeviceId }; }).ToList(); } #endregion #region Notifications & NotificationReceipts (PostgreSQL) public async Task RecordNotificationAsync(NotificationDto notification, string? senderUserId, string senderName) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var notifEntity = new Notification { Id = notification.Id, TenantId = notification.TenantId, ClassroomId = notification.ClassId, SenderUserId = senderUserId, SenderName = senderName, Message = notification.Message, Title = notification.Title, Priority = notification.Type.ToString(), CreatedAt = notification.CreatedAt, ExpiresAt = notification.ExpiresAt, Voice = notification.Voice, Shake = notification.Shake, DurationSeconds = notification.DurationSeconds }; db.Notifications.Add(notifEntity); // Find active devices for this classroom and create initial Receipt with Status = "Sent" var targetDevices = await db.Devices.AsNoTracking() .Where(d => d.TenantId == notification.TenantId && d.ClassroomId == notification.ClassId && d.IsActive) .ToListAsync(); foreach (var dev in targetDevices) { db.NotificationReceipts.Add(new NotificationReceipt { Id = $"rcpt_{Guid.NewGuid():N}", NotificationId = notification.Id, DeviceId = dev.Id, Status = "Sent", UpdatedAt = DateTimeOffset.UtcNow }); } await db.SaveChangesAsync(); } public async Task RecordAckAsync(string messageId, string authenticatedDeviceId, AckReceiptDto ack) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var receipt = await db.NotificationReceipts .FirstOrDefaultAsync(r => r.NotificationId == messageId && r.DeviceId == authenticatedDeviceId); if (receipt == null) { // If receipt didn't exist (e.g. device activated after notification or direct delivery), create it receipt = new NotificationReceipt { Id = $"rcpt_{Guid.NewGuid():N}", NotificationId = messageId, DeviceId = authenticatedDeviceId, Status = "Sent", UpdatedAt = DateTimeOffset.UtcNow }; db.NotificationReceipts.Add(receipt); } // State Machine Protection: // Rank: Sent (0) -> DeviceReceived (1) -> Displayed (2) -> Acknowledged (3) // Terminal states: Timeout, Failed. // Rule: Never regress from Acknowledged to any lower rank or failure. if (receipt.Status == "Acknowledged") { _logger.LogInformation("Receipt {ReceiptId} (Dev {DevId}) is already Acknowledged. Ignoring subsequent {Status}.", receipt.Id, authenticatedDeviceId, ack.Status); return; } switch (ack.Status) { case AckStatus.Delivered: // Client WPF displayed window on screen receipt.DeviceReceivedAt ??= ack.Timestamp; receipt.DisplayedAt ??= ack.Timestamp; if (receipt.Status != "Displayed" && receipt.Status != "Acknowledged") { receipt.Status = "Displayed"; } break; case AckStatus.Acknowledged: receipt.DeviceReceivedAt ??= ack.Timestamp; receipt.DisplayedAt ??= ack.Timestamp; receipt.AcknowledgedAt = ack.Timestamp; receipt.Status = "Acknowledged"; break; case AckStatus.Timeout: if (receipt.Status != "Acknowledged") { receipt.Status = "Timeout"; } break; case AckStatus.Failed: if (receipt.Status != "Acknowledged") { receipt.Status = "Failed"; receipt.FailedAt = ack.Timestamp; receipt.FailureReason = ack.Remark; } break; case AckStatus.Sent: default: break; } receipt.UpdatedAt = DateTimeOffset.UtcNow; await db.SaveChangesAsync(); } public async Task ValidateNotificationTargetAsync(string messageId, string tenantId, string classroomId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return await db.Notifications.AsNoTracking() .AnyAsync(n => n.Id == messageId && n.TenantId == tenantId && n.ClassroomId == classroomId); } public async Task> GetNotificationsAsync(string? tenantId, string? classId, int limit = 50) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.Notifications.AsNoTracking().Include(n => n.Receipts).AsQueryable(); if (!string.IsNullOrEmpty(tenantId) && tenantId != "global") { query = query.Where(n => n.TenantId == tenantId); } if (!string.IsNullOrEmpty(classId)) { query = query.Where(n => n.ClassroomId == classId); } var notifications = await query.OrderByDescending(n => n.CreatedAt).Take(limit).ToListAsync(); var classrooms = await db.Classrooms.AsNoTracking().ToDictionaryAsync(c => $"{c.TenantId}_{c.Id}", c => c.DisplayName); return notifications.Select(n => { classrooms.TryGetValue($"{n.TenantId}_{n.ClassroomId}", out var cName); // Compute aggregate status across all device receipts string status = "Sent"; DateTimeOffset? confirmedAt = null; if (n.Receipts.Any(r => r.Status == "Acknowledged")) { status = "Acknowledged"; confirmedAt = n.Receipts.FirstOrDefault(r => r.Status == "Acknowledged")?.AcknowledgedAt; } else if (n.Receipts.Any(r => r.Status == "Displayed" || r.Status == "DeviceReceived")) { status = "Delivered"; } else if (n.Receipts.Any(r => r.Status == "Failed")) { status = "Failed"; } else if (n.Receipts.Any(r => r.Status == "Timeout")) { status = "Timeout"; } else if ((n.Receipts.Any() && n.Receipts.All(r => r.Status == "Expired")) || (n.ExpiresAt.HasValue && n.ExpiresAt.Value <= DateTimeOffset.UtcNow)) { status = "Expired"; } return new NotificationRecordDto { Id = n.Id, TenantId = n.TenantId, ClassId = n.ClassroomId, ClassName = cName ?? n.ClassroomId, SenderName = n.SenderName, Message = n.Message, Priority = n.Priority, CreatedAt = n.CreatedAt, Status = status, ConfirmedAt = confirmedAt, ExpiresAt = n.ExpiresAt }; }).ToList(); } public async Task> GetPendingNotificationsForDeviceAsync(string deviceId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var now = DateTimeOffset.UtcNow; // Query pending receipts for this authenticated device var pendingReceipts = await db.NotificationReceipts .Include(r => r.Notification) .Where(r => r.DeviceId == deviceId && r.Status == "Sent") .ToListAsync(); var validDtos = new List(); bool hasStateChanges = false; foreach (var receipt in pendingReceipts) { if (receipt.Notification == null) continue; // Check if notification has expired (or is legacy Batch 8 record where ExpiresAt is NULL) if (!receipt.Notification.ExpiresAt.HasValue || receipt.Notification.ExpiresAt.Value <= now) { receipt.Status = "Expired"; receipt.UpdatedAt = now; hasStateChanges = true; _logger.LogInformation("Receipt {ReceiptId} for Device {DeviceId} (Msg {MsgId}) marked Expired (ExpiresAt: {ExpiresAt}).", receipt.Id, deviceId, receipt.NotificationId, receipt.Notification.ExpiresAt); } else { var n = receipt.Notification; validDtos.Add(new NotificationDto { Id = n.Id, TenantId = n.TenantId, ClassId = n.ClassroomId, Title = n.Title, Message = n.Message, Type = Enum.TryParse(n.Priority, out var p) ? p : ClassNotify.Shared.Enums.NotificationType.Call, Voice = n.Voice, Shake = n.Shake, DurationSeconds = n.DurationSeconds, CreatedAt = n.CreatedAt, ExpiresAt = n.ExpiresAt }); } } if (hasStateChanges) { await db.SaveChangesAsync(); } return validDtos.OrderBy(d => d.CreatedAt).ToList(); } #endregion #region Device Commands (P1 Batch 10) public async Task CreateDeviceCommandAsync(string? callerTenantId, string deviceId, string commandType, string? parameters, string createdBy) { if (string.IsNullOrWhiteSpace(deviceId)) { throw new ArgumentException("DeviceId cannot be empty", nameof(deviceId)); } // Whitelist check if (!DeviceCommandTypes.IsSupported(commandType)) { throw new ArgumentException($"Unsupported command type '{commandType}'. Whitelist: {string.Join(", ", DeviceCommandTypes.AllSupported)}"); } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var device = await db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId); if (device == null) { throw new InvalidOperationException($"Target device '{deviceId}' not found"); } // Multi-tenant isolation: non-superadmin caller must match device tenant if (!string.IsNullOrEmpty(callerTenantId) && !string.Equals(callerTenantId, device.TenantId, StringComparison.OrdinalIgnoreCase)) { throw new UnauthorizedAccessException($"Device '{deviceId}' does not belong to tenant '{callerTenantId}'"); } var ttl = DeviceCommandTypes.GetDefaultTtl(commandType); var now = DateTimeOffset.UtcNow; var commandId = $"cmd_{Guid.NewGuid():N}"; var entity = new DeviceCommand { Id = commandId, TenantId = device.TenantId, DeviceId = device.Id, CommandType = commandType, Parameters = parameters, CreatedBy = createdBy, CreatedAt = now, ExpiresAt = now.Add(ttl), Status = DeviceCommandStatuses.Pending }; db.DeviceCommands.Add(entity); await db.SaveChangesAsync(); _logger.LogInformation("Created remote command {CommandId} ({CommandType}) for Device {DeviceId} (Tenant {TenantId}, TTL {TtlMinutes}m) by {CreatedBy}", commandId, commandType, device.Id, device.TenantId, ttl.TotalMinutes, createdBy); return new DeviceCommandDto { CommandId = entity.Id, TenantId = entity.TenantId, DeviceId = entity.DeviceId, CommandType = entity.CommandType, Parameters = entity.Parameters, CreatedBy = entity.CreatedBy, CreatedAt = entity.CreatedAt, ExpiresAt = entity.ExpiresAt, Status = entity.Status }; } public async Task MarkCommandDispatchedAsync(string commandId) { if (string.IsNullOrWhiteSpace(commandId)) return false; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var cmd = await db.DeviceCommands.FirstOrDefaultAsync(c => c.Id == commandId); if (cmd == null) return false; if (cmd.Status == DeviceCommandStatuses.Pending) { cmd.Status = DeviceCommandStatuses.Dispatched; await db.SaveChangesAsync(); return true; } return false; } public async Task RecordCommandResultAsync(DeviceCommandResultDto result, string callerDeviceId, string? callerTenantId) { if (result == null || string.IsNullOrWhiteSpace(result.CommandId)) { _logger.LogWarning("RecordCommandResultAsync called with empty CommandId"); return null; } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var cmd = await db.DeviceCommands.FirstOrDefaultAsync(c => c.Id == result.CommandId); if (cmd == null) { _logger.LogWarning("Remote command {CommandId} not found when recording execution result", result.CommandId); return null; } // Security assertion: device and tenant isolation if (!string.Equals(cmd.DeviceId, callerDeviceId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Rejecting command result: DeviceId mismatch. Target: {TargetDevice}, Caller: {CallerDevice} (Command {CommandId})", cmd.DeviceId, callerDeviceId, result.CommandId); return null; } if (!string.IsNullOrEmpty(callerTenantId) && !string.Equals(cmd.TenantId, callerTenantId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Rejecting command result: TenantId mismatch. Target: {TargetTenant}, Caller: {CallerTenant} (Command {CommandId})", cmd.TenantId, callerTenantId, result.CommandId); return null; } // Idempotency: if already reached terminal state, do not overwrite final outcome if (DeviceCommandStatuses.IsTerminal(cmd.Status)) { _logger.LogInformation("Command {CommandId} already completed with terminal status '{Status}'. Ignoring duplicate result report.", cmd.Id, cmd.Status); return new DeviceCommandResultDto { CommandId = cmd.Id, DeviceId = cmd.DeviceId, Status = cmd.Status, ResultCode = cmd.ResultCode ?? 0, ResultMessage = cmd.ResultMessage, ExecutionDurationMs = cmd.DurationMs ?? 0, Timestamp = cmd.CompletedAt ?? DateTimeOffset.UtcNow }; } var now = DateTimeOffset.UtcNow; cmd.Status = result.Status; cmd.ResultCode = result.ResultCode; cmd.DurationMs = result.ExecutionDurationMs; cmd.ResultMessage = result.ResultMessage != null && result.ResultMessage.Length > 1000 ? result.ResultMessage[..1000] : result.ResultMessage; cmd.StartedAt ??= result.Timestamp; cmd.CompletedAt = now; await db.SaveChangesAsync(); _logger.LogInformation("Recorded execution result for Command {CommandId} (Device {DeviceId}): Status={Status}, ResultCode={ResultCode}, Duration={Duration}ms", cmd.Id, cmd.DeviceId, cmd.Status, cmd.ResultCode, cmd.DurationMs); return new DeviceCommandResultDto { CommandId = cmd.Id, DeviceId = cmd.DeviceId, Status = cmd.Status, ResultCode = cmd.ResultCode ?? 0, ResultMessage = cmd.ResultMessage, ExecutionDurationMs = cmd.DurationMs ?? result.ExecutionDurationMs, Timestamp = cmd.CompletedAt ?? now }; } public async Task GetDeviceCommandAsync(string commandId, string? callerTenantId = null) { if (string.IsNullOrWhiteSpace(commandId)) return null; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var cmd = await db.DeviceCommands.FirstOrDefaultAsync(c => c.Id == commandId); if (cmd == null) return null; if (!string.IsNullOrEmpty(callerTenantId) && !string.Equals(cmd.TenantId, callerTenantId, StringComparison.OrdinalIgnoreCase)) { return null; } // Active TTL evaluation: if Pending/Dispatched and past ExpiresAt, transition via Normalizer if (DeviceCommandNormalizer.NormalizeExpiredOrTimedOut(cmd, DateTimeOffset.UtcNow)) { await db.SaveChangesAsync(); } return new DeviceCommandDto { CommandId = cmd.Id, TenantId = cmd.TenantId, DeviceId = cmd.DeviceId, CommandType = cmd.CommandType, Parameters = cmd.Parameters, CreatedBy = cmd.CreatedBy, CreatedAt = cmd.CreatedAt, ExpiresAt = cmd.ExpiresAt, Status = cmd.Status, StartedAt = cmd.StartedAt, CompletedAt = cmd.CompletedAt, DurationMs = cmd.DurationMs, ResultCode = cmd.ResultCode, ResultMessage = cmd.ResultMessage }; } public async Task> GetPendingCommandsForDeviceAsync(string deviceId) { if (string.IsNullOrWhiteSpace(deviceId)) return new List(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var list = await db.DeviceCommands .Where(c => c.DeviceId == deviceId && (c.Status == DeviceCommandStatuses.Pending || c.Status == DeviceCommandStatuses.Dispatched)) .OrderBy(c => c.CreatedAt) .ToListAsync(); var now = DateTimeOffset.UtcNow; var valid = new List(); bool hasExpiredUpdates = false; foreach (var cmd in list) { if (DeviceCommandNormalizer.NormalizeExpiredOrTimedOut(cmd, now)) { hasExpiredUpdates = true; _logger.LogInformation("Command {CommandId} for Device {DeviceId} marked {Status} (ExpiresAt: {ExpiresAt}).", cmd.Id, deviceId, cmd.Status, cmd.ExpiresAt); } else { valid.Add(new DeviceCommandDto { CommandId = cmd.Id, TenantId = cmd.TenantId, DeviceId = cmd.DeviceId, CommandType = cmd.CommandType, Parameters = cmd.Parameters, CreatedBy = cmd.CreatedBy, CreatedAt = cmd.CreatedAt, ExpiresAt = cmd.ExpiresAt, Status = cmd.Status, StartedAt = cmd.StartedAt, CompletedAt = cmd.CompletedAt, DurationMs = cmd.DurationMs, ResultCode = cmd.ResultCode, ResultMessage = cmd.ResultMessage }); } } if (hasExpiredUpdates) { await db.SaveChangesAsync(); } return valid; } public async Task> GetDeviceCommandHistoryAsync(string? tenantId, string? deviceId, string? status, int limit = 50) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.DeviceCommands.AsQueryable(); if (!string.IsNullOrEmpty(tenantId)) { query = query.Where(c => c.TenantId == tenantId); } if (!string.IsNullOrEmpty(deviceId)) { query = query.Where(c => c.DeviceId == deviceId); } if (!string.IsNullOrEmpty(status)) { query = query.Where(c => c.Status == status); } var commands = await query .OrderByDescending(c => c.CreatedAt) .Take(Math.Min(limit, 200)) .ToListAsync(); var now = DateTimeOffset.UtcNow; bool hasExpiredUpdates = false; var result = new List(); foreach (var cmd in commands) { if (DeviceCommandNormalizer.NormalizeExpiredOrTimedOut(cmd, now)) { hasExpiredUpdates = true; } result.Add(new DeviceCommandDto { CommandId = cmd.Id, TenantId = cmd.TenantId, DeviceId = cmd.DeviceId, CommandType = cmd.CommandType, Parameters = cmd.Parameters, CreatedBy = cmd.CreatedBy, CreatedAt = cmd.CreatedAt, ExpiresAt = cmd.ExpiresAt, Status = cmd.Status, StartedAt = cmd.StartedAt, CompletedAt = cmd.CompletedAt, DurationMs = cmd.DurationMs, ResultCode = cmd.ResultCode, ResultMessage = cmd.ResultMessage }); } if (hasExpiredUpdates) { await db.SaveChangesAsync(); } return result; } #endregion #region Helpers public string GenerateJwtToken(User user) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.UTF8.GetBytes(_jwtOptions.SigningKey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(ClaimTypes.Name, user.FullName), new Claim(ClaimTypes.Role, user.Role), new Claim("tenant_id", user.TenantId) }), Issuer = _jwtOptions.Issuer, Audience = _jwtOptions.Audience, Expires = DateTime.UtcNow.AddDays(_jwtOptions.LifetimeDays > 0 ? _jwtOptions.LifetimeDays : 14), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } /// /// Legacy SHA256 password verifier for migration of existing accounts. /// STRICTLY PROHIBITED FOR GENERATING NEW PASSWORDS. /// public static bool VerifyLegacyPassword(string plaintextPassword, string legacyHash) { if (string.IsNullOrEmpty(plaintextPassword) || string.IsNullOrEmpty(legacyHash)) { return false; } using var sha = SHA256.Create(); var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(plaintextPassword + "_classnotify_salt")); var computed = Convert.ToBase64String(bytes); return CryptographicOperations.FixedTimeEquals( Encoding.UTF8.GetBytes(computed), Encoding.UTF8.GetBytes(legacyHash)); } private static string HashToken(string token) { using var sha = SHA256.Create(); var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(token)); return Convert.ToBase64String(bytes); } #region SuperAdmin Control Plane Implementations public async Task CreateTenantAsync(string id, string name) { if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(name)) throw new ArgumentException("学校ID与名称不可为空"); var cleanId = id.Trim().ToLowerInvariant(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); if (await db.Tenants.AnyAsync(t => t.Id == cleanId)) throw new InvalidOperationException($"租户ID '{cleanId}' 已存在"); var tenant = new Tenant { Id = cleanId, Name = name.Trim(), IsActive = true, CreatedAt = DateTimeOffset.UtcNow }; db.Tenants.Add(tenant); await db.SaveChangesAsync(); return new TenantAdminDto { Id = tenant.Id, Name = tenant.Name, ClassroomCount = 0, DeviceCount = 0, OnlineCount = 0, IsActive = tenant.IsActive, CreatedAt = tenant.CreatedAt }; } public async Task UpdateTenantAsync(string id, string name, bool isActive) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var tenant = await db.Tenants.FirstOrDefaultAsync(t => t.Id == id); if (tenant == null) return null; if (!string.IsNullOrWhiteSpace(name)) tenant.Name = name.Trim(); tenant.IsActive = isActive; await db.SaveChangesAsync(); var classroomCount = await db.Classrooms.CountAsync(c => c.TenantId == id); var deviceCount = await db.Devices.CountAsync(d => d.TenantId == id); var onlineCount = _liveConnections.Values.Count(c => c.TenantId == id); return new TenantAdminDto { Id = tenant.Id, Name = tenant.Name, ClassroomCount = classroomCount, DeviceCount = deviceCount, OnlineCount = onlineCount, IsActive = tenant.IsActive, CreatedAt = tenant.CreatedAt }; } public async Task> GetAllUsersAdminAsync(string? tenantId, string? role) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.Users.Include(u => u.Tenant).AsQueryable(); if (!string.IsNullOrWhiteSpace(tenantId)) query = query.Where(u => u.TenantId == tenantId); if (!string.IsNullOrWhiteSpace(role)) query = query.Where(u => u.Role == role); var list = await query.OrderByDescending(u => u.CreatedAt).ToListAsync(); return list.Select(u => new UserAdminDto { Id = u.Id, TenantId = u.TenantId, TenantName = u.Tenant?.Name ?? u.TenantId, Username = u.Username, FullName = u.FullName, Role = u.Role, IsLocked = u.IsLocked, CreatedAt = u.CreatedAt, LastLoginAt = u.LastLoginAt }).ToList(); } public async Task CreateUserAdminAsync(CreateUserAdminRequest req) { if (string.IsNullOrWhiteSpace(req.TenantId) || string.IsNullOrWhiteSpace(req.Username) || string.IsNullOrWhiteSpace(req.Password) || string.IsNullOrWhiteSpace(req.FullName)) throw new ArgumentException("所有必填字段均不可为空"); var targetRole = req.Role?.Trim(); if (targetRole != "SchoolAdmin" && targetRole != "Teacher") throw new ArgumentException("角色必须为 'SchoolAdmin' 或 'Teacher'"); var cleanUser = req.Username.Trim(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); if (await db.Users.AnyAsync(u => u.Username == cleanUser)) throw new InvalidOperationException($"用户名 '{cleanUser}' 已被占用"); var tenant = await db.Tenants.FirstOrDefaultAsync(t => t.Id == req.TenantId); if (tenant == null) throw new InvalidOperationException($"租户 '{req.TenantId}' 不存在"); var user = new User { Id = $"usr_{Guid.NewGuid():N}".Substring(0, 12), TenantId = req.TenantId, Username = cleanUser, FullName = req.FullName.Trim(), Role = targetRole, IsLocked = false, CreatedAt = DateTimeOffset.UtcNow }; user.PasswordHash = _passwordHasher.HashPassword(user, req.Password); db.Users.Add(user); await db.SaveChangesAsync(); return new UserAdminDto { Id = user.Id, TenantId = user.TenantId, TenantName = tenant.Name, Username = user.Username, FullName = user.FullName, Role = user.Role, IsLocked = user.IsLocked, CreatedAt = user.CreatedAt }; } public async Task ResetPasswordAsync(string userId, string newPassword) { if (string.IsNullOrWhiteSpace(newPassword)) throw new ArgumentException("新密码不可为空"); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.FirstOrDefaultAsync(u => u.Id == userId); if (user == null) return false; user.PasswordHash = _passwordHasher.HashPassword(user, newPassword); await db.SaveChangesAsync(); return true; } public async Task SetUserLockAsync(string userId, bool isLocked) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.FirstOrDefaultAsync(u => u.Id == userId); if (user == null) return false; user.IsLocked = isLocked; await db.SaveChangesAsync(); return true; } public async Task DeleteUserAsync(string userId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.FirstOrDefaultAsync(u => u.Id == userId); if (user == null) return false; if (user.Role == "SuperAdmin") throw new InvalidOperationException("无法删除超级管理员"); db.Users.Remove(user); await db.SaveChangesAsync(); return true; } public async Task UpdateDeviceAsync(string deviceId, string? hostname, string? classroomId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var device = await db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId); if (device == null) return false; if (!string.IsNullOrWhiteSpace(hostname)) device.Hostname = hostname.Trim(); if (!string.IsNullOrWhiteSpace(classroomId)) device.ClassroomId = classroomId.Trim(); await db.SaveChangesAsync(); return true; } public async Task DecommissionDeviceAsync(string deviceId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var device = await db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId); if (device == null) return false; device.IsActive = false; device.LastHeartbeatAt = null; await db.SaveChangesAsync(); if (_deviceToConnection.TryRemove(deviceId, out var connId)) { _liveConnections.TryRemove(connId, out _); _connectionTenantMap.TryRemove(connId, out _); } return true; } public async Task DeleteActivationCodeAsync(string code) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var act = await db.ActivationCodes.FirstOrDefaultAsync(a => a.Code == code); if (act == null) return false; db.ActivationCodes.Remove(act); await db.SaveChangesAsync(); return true; } public async Task GetSystemHealthAsync() { bool dbOk = false; double latencyMs = 0; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); try { var sw = System.Diagnostics.Stopwatch.StartNew(); dbOk = await db.Database.CanConnectAsync(); sw.Stop(); latencyMs = sw.Elapsed.TotalMilliseconds; } catch {} var process = System.Diagnostics.Process.GetCurrentProcess(); var uptime = DateTime.UtcNow - process.StartTime.ToUniversalTime(); return new SystemHealthDto { Status = dbOk ? "Healthy" : "Degraded", DatabaseConnected = dbOk, DatabaseLatencyMs = Math.Round(latencyMs, 2), ActiveSignalRConnections = _liveConnections.Count, OnlineDevices = _liveConnections.Count, ServerTime = DateTimeOffset.UtcNow.ToString("o"), Uptime = $"{(int)uptime.TotalHours}h {uptime.Minutes}m {uptime.Seconds}s", MemoryUsedBytes = process.WorkingSet64 }; } public async Task LogAdminAuditAsync(string actorUsername, string actorRole, string action, string targetType, string targetId, string? details, string? ip) { try { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var evt = new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}".Substring(0, 16), OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actorUsername, ActorRole = actorRole, Action = action, TargetType = targetType, TargetId = targetId, Details = details, IpAddress = ip }; db.AdminAuditEvents.Add(evt); await db.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError(ex, "Failed to write AdminAuditEvent for action {Action}", action); } } public async Task> GetAdminAuditLogsAsync(int limit = 100) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var list = await db.AdminAuditEvents .OrderByDescending(a => a.OccurredAt) .Take(limit) .ToListAsync(); return list.Select(a => new AdminAuditLogDto { Id = a.Id, OccurredAt = a.OccurredAt, ActorUsername = a.ActorUsername, ActorRole = a.ActorRole, Action = a.Action, TargetType = a.TargetType, TargetId = a.TargetId, Details = a.Details, IpAddress = a.IpAddress }).ToList(); } #endregion #endregion } ================================================================================ FILE: src/Shared/ClassNotify.Shared/Models/AdminDtos.cs ================================================================================ namespace ClassNotify.Shared.Models; /// /// 全局平台统计指标 (超级管理员大盘) /// public class AdminMetricsDto { public int TotalTenants { get; set; } public int TotalClassrooms { get; set; } public int TotalDevices { get; set; } public int OnlineDevices { get; set; } public int OfflineDevices => Math.Max(0, TotalDevices - OnlineDevices); public int TodayNotifications { get; set; } public int AbnormalDevices { get; set; } } /// /// 设备明细与实时状态 DTO /// public class DeviceAdminDto { public string DeviceId { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string TenantName { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string ClassroomName { get; set; } = string.Empty; public string? Hostname { get; set; } public bool IsOnline { get; set; } public DateTimeOffset? LastHeartbeat { get; set; } public string? ClientVersion { get; set; } public string? RemoteIp { get; set; } public bool ServiceRunning { get; set; } = true; public bool ClientRunning { get; set; } = true; } /// /// 学校/租户大盘 DTO /// public class TenantAdminDto { public string Id { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; public int ClassroomCount { get; set; } public int DeviceCount { get; set; } public int OnlineCount { get; set; } public bool IsActive { get; set; } = true; public DateTimeOffset CreatedAt { get; set; } } /// /// 激活码详情 DTO /// public class ActivationCodeDto { public string Code { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string TenantName { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string ClassroomName { get; set; } = string.Empty; public DateTimeOffset ExpiresAt { get; set; } public bool IsUsed { get; set; } public DateTimeOffset? UsedAt { get; set; } public string? UsedByDeviceId { get; set; } } /// /// 远程指令下发请求 /// public class RemoteCommandRequestDto { public string Command { get; set; } = string.Empty; // "ping", "restart_client", "refresh_config" public string? Parameters { get; set; } } /// /// 创建班级请求 /// public class CreateClassroomDto { public string Id { get; set; } = string.Empty; public string DisplayName { get; set; } = string.Empty; public string? Grade { get; set; } public string? RoomNumber { get; set; } } /// /// 创建教师账号请求 /// public class CreateTeacherDto { public string Username { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; public string FullName { get; set; } = string.Empty; public string Role { get; set; } = "Teacher"; // Teacher, SchoolAdmin } /// /// 消息历史记录与回执 /// public class NotificationRecordDto { public string Id { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string ClassId { get; set; } = string.Empty; public string ClassName { get; set; } = string.Empty; public string SenderName { get; set; } = string.Empty; public string Message { get; set; } = string.Empty; public string Priority { get; set; } = "Normal"; public DateTimeOffset CreatedAt { get; set; } public string Status { get; set; } = "Sent"; // Sent, Delivered, Acknowledged, Timeout, Failed public DateTimeOffset? ConfirmedAt { get; set; } public DateTimeOffset? ExpiresAt { get; set; } } public class UserAdminDto { public string Id { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string TenantName { get; set; } = string.Empty; public string Username { get; set; } = string.Empty; public string FullName { get; set; } = string.Empty; public string Role { get; set; } = string.Empty; public bool IsLocked { get; set; } public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset? LastLoginAt { get; set; } } public class CreateUserAdminRequest { public string TenantId { get; set; } = string.Empty; public string Username { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; public string FullName { get; set; } = string.Empty; public string Role { get; set; } = "SchoolAdmin"; // SchoolAdmin, Teacher } public class ResetPasswordRequest { public string NewPassword { get; set; } = string.Empty; } public class LockUserRequest { public bool IsLocked { get; set; } = true; } public class CreateTenantRequest { public string Id { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; } public class UpdateTenantRequest { public string Name { get; set; } = string.Empty; public bool IsActive { get; set; } = true; } public class UpdateDeviceRequest { public string? Hostname { get; set; } public string? ClassroomId { get; set; } } public class EmergencyBroadcastRequest { public string? TenantId { get; set; } // null or empty = all schools public string Title { get; set; } = "⚠️ 全校紧急通知"; public string Message { get; set; } = string.Empty; public bool Voice { get; set; } = true; public bool Shake { get; set; } = true; public int DurationSeconds { get; set; } = 30; } public class SystemHealthDto { public string Status { get; set; } = "Healthy"; public bool DatabaseConnected { get; set; } = true; public double DatabaseLatencyMs { get; set; } public int ActiveSignalRConnections { get; set; } public int OnlineDevices { get; set; } public string ServerTime { get; set; } = string.Empty; public string Uptime { get; set; } = string.Empty; public long MemoryUsedBytes { get; set; } } public class AdminAuditLogDto { public string Id { get; set; } = string.Empty; public DateTimeOffset OccurredAt { get; set; } public string ActorUsername { get; set; } = string.Empty; public string ActorRole { get; set; } = string.Empty; public string Action { get; set; } = string.Empty; public string TargetType { get; set; } = string.Empty; public string TargetId { get; set; } = string.Empty; public string? Details { get; set; } public string? IpAddress { get; set; } } ================================================================================ FILE: src/Web/ClassNotify.Web/src/types/index.ts ================================================================================ export type UserRole = 'SuperAdmin' | 'SchoolAdmin' | 'Teacher'; export interface CurrentUser { userId: string; name: string; role: UserRole; tenantId: string; } export interface LoginResult { success: boolean; token?: string; tenantId?: string; userId?: string; fullName?: string; role?: UserRole; errorMessage?: string; } export interface AdminMetrics { totalTenants: number; totalClassrooms: number; totalDevices: number; onlineDevices: number; offlineDevices: number; todayNotifications: number; abnormalDevices: number; } export interface TenantAdmin { id: string; name: string; classroomCount: number; deviceCount: number; onlineCount: number; isActive: boolean; createdAt: string; } export interface DeviceAdmin { deviceId: string; tenantId: string; tenantName: string; classroomId: string; classroomName: string; hostname?: string; isOnline: boolean; lastHeartbeat?: string; clientVersion?: string; remoteIp?: string; serviceRunning: boolean; clientRunning: boolean; healthStatus?: string; } export interface ActivationCode { code: string; tenantId: string; tenantName: string; classroomId: string; classroomName: string; expiresAt: string; isUsed: boolean; usedAt?: string; usedByDeviceId?: string; } export interface Classroom { id: string; tenantId: string; displayName: string; grade?: string; roomNumber?: string; } export interface TeacherUser { id: string; username: string; fullName: string; role: string; } export interface NotificationRecord { id: string; tenantId: string; classId: string; className: string; senderName: string; message: string; priority: string; createdAt: string; status: 'Sent' | 'Delivered' | 'Acknowledged' | 'Timeout' | 'Failed'; confirmedAt?: string; } export interface SendNotificationPayload { classId: string; studentName?: string; title: string; message: string; type: number; // 0=Call, 1=Broadcast, 2=Urgent voice: boolean; shake: boolean; durationSeconds: number; } export interface UserAdmin { id: string; tenantId: string; tenantName: string; username: string; fullName: string; role: string; isLocked: boolean; createdAt: string; lastLoginAt?: string; } export interface CreateUserAdminRequest { tenantId: string; username: string; password: string; fullName: string; role: string; } export interface CreateTenantRequest { id: string; name: string; } export interface UpdateTenantRequest { name: string; isActive: boolean; } export interface UpdateDeviceRequest { hostname?: string; classroomId?: string; } export interface EmergencyBroadcastRequest { tenantId?: string; title: string; message: string; voice: boolean; shake: boolean; durationSeconds: number; } export interface SystemHealth { status: string; databaseConnected: boolean; databaseLatencyMs: number; activeSignalRConnections: number; onlineDevices: number; serverTime: string; uptime: string; memoryUsedBytes: number; } export interface AdminAuditLog { id: string; occurredAt: string; actorUsername: string; actorRole: string; action: string; targetType: string; targetId: string; details?: string; ipAddress?: string; } ================================================================================ FILE: src/Web/ClassNotify.Web/src/api/client.ts ================================================================================ import { AdminMetrics, TenantAdmin, DeviceAdmin, ActivationCode, Classroom, TeacherUser, NotificationRecord, SendNotificationPayload, LoginResult, CurrentUser, UserAdmin, CreateUserAdminRequest, CreateTenantRequest, UpdateTenantRequest, UpdateDeviceRequest, EmergencyBroadcastRequest, SystemHealth, AdminAuditLog } 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'), 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; dispatchedCount: number; targetSchools: number; message: string }>('/admin/broadcasts', { method: 'POST', body: JSON.stringify(dto), }), // 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), }), 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), } ), getTeacherHistory: (classId?: string, limit = 50): Promise => request( `/notification/history?${classId ? `classId=${encodeURIComponent(classId)}&` : ''}limit=${limit}` ), }; ================================================================================ FILE: src/Web/ClassNotify.Web/src/pages/admin/TenantManagement.tsx ================================================================================ import React, { useEffect, useState } from 'react'; import { api } from '../../api/client'; import { TenantAdmin, CreateTenantRequest, UpdateTenantRequest } from '../../types'; import { Building2, Plus, Search, RefreshCw, CheckCircle2, XCircle, Edit3, GraduationCap, AlertCircle } from 'lucide-react'; export const TenantManagement: React.FC = () => { const [tenants, setTenants] = useState([]); const [loading, setLoading] = useState(true); const [search, setSearch] = useState(''); const [message, setMessage] = useState<{ text: string; success: boolean } | null>(null); // Create Modal const [showCreateModal, setShowCreateModal] = useState(false); const [createForm, setCreateForm] = useState({ id: '', name: '' }); const [createLoading, setCreateLoading] = useState(false); // Edit Modal const [editingTenant, setEditingTenant] = useState(null); const [editForm, setEditForm] = useState({ name: '', isActive: true }); const [editLoading, setEditLoading] = useState(false); const loadTenants = async () => { try { const data = await api.getTenants(); setTenants(data); } catch (err: any) { console.error('Failed to load tenants', err); } finally { setLoading(false); } }; useEffect(() => { loadTenants(); }, []); const handleCreate = async (e: React.FormEvent) => { e.preventDefault(); if (!createForm.id.trim() || !createForm.name.trim()) return; setCreateLoading(true); try { await api.createTenant({ id: createForm.id.trim(), name: createForm.name.trim(), }); setMessage({ text: `学校 [${createForm.name}] 创建成功!`, success: true }); setShowCreateModal(false); setCreateForm({ id: '', name: '' }); loadTenants(); } catch (err: any) { setMessage({ text: err.message || '创建学校失败', success: false }); } finally { setCreateLoading(false); } }; const openEdit = (tenant: TenantAdmin) => { setEditingTenant(tenant); setEditForm({ name: tenant.name, isActive: tenant.isActive }); }; const handleEdit = async (e: React.FormEvent) => { e.preventDefault(); if (!editingTenant || !editForm.name.trim()) return; setEditLoading(true); try { await api.updateTenant(editingTenant.id, { name: editForm.name.trim(), isActive: editForm.isActive, }); setMessage({ text: `学校 [${editForm.name}] 配置已更新`, success: true }); setEditingTenant(null); loadTenants(); } catch (err: any) { setMessage({ text: err.message || '更新学校配置失败', success: false }); } finally { setEditLoading(false); } }; const filteredTenants = tenants.filter( (t) => t.name.toLowerCase().includes(search.toLowerCase()) || t.id.toLowerCase().includes(search.toLowerCase()) ); return (
{/* Header */}

学校租户生命周期管理

统筹多校区租户实体,支持新校区入驻配置、基础信息变更与服务启停冻结

{/* Alert Banner */} {message && (
{message.success ? ( ) : ( )} {message.text}
)} {/* Filter Bar */}
setSearch(e.target.value)} placeholder="按学校标识代码 (ID) 或名称搜索..." className="bg-transparent border-none text-sm text-white placeholder-slate-500 focus:outline-none w-full" /> {search && ( )}
{/* Tenants Table */}
{filteredTenants.length === 0 ? ( ) : ( filteredTenants.map((t) => ( )) )}
学校名称 / 标识码 班级总数 终端大屏 (在线/总计) 服务状态 接入时间 管理操作
{loading ? '正在读取租户列表...' : '暂无匹配的学校租户'}
{t.name}
{t.id}
{t.classroomCount} 个班级
{t.onlineCount} 在线 / {t.deviceCount} 总屏
{t.isActive ? (
正常运营
) : (
已停用冻结
)}
{new Date(t.createdAt).toLocaleDateString()}
{/* Create Modal */} {showCreateModal && (

接入新学校租户

setCreateForm({ ...createForm, id: e.target.value })} 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" />

只能包含小写字母、数字和下划线,作为多租户隔离主键不可篡改

setCreateForm({ ...createForm, name: e.target.value })} 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" />
)} {/* Edit Modal */} {editingTenant && (

编辑学校配置: {editingTenant.id}

setEditForm({ ...editForm, name: e.target.value })} 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/UserManagement.tsx ================================================================================ import React, { useEffect, useState } from 'react'; import { api } from '../../api/client'; import { UserAdmin, TenantAdmin, CreateUserAdminRequest } from '../../types'; import { Users, Plus, Search, RefreshCw, KeyRound, Lock, Unlock, Trash2, Building2, ShieldAlert, CheckCircle2, AlertCircle, GraduationCap } from 'lucide-react'; export const UserManagement: React.FC = () => { const [users, setUsers] = useState([]); const [tenants, setTenants] = useState([]); const [loading, setLoading] = useState(true); const [search, setSearch] = useState(''); const [selectedTenant, setSelectedTenant] = useState(''); const [selectedRole, setSelectedRole] = useState(''); const [message, setMessage] = useState<{ text: string; success: boolean } | null>(null); // Create User Modal const [showCreateModal, setShowCreateModal] = useState(false); const [createForm, setCreateForm] = useState({ tenantId: '', username: '', password: '', fullName: '', role: 'Teacher', }); const [createLoading, setCreateLoading] = useState(false); // Reset Password Modal const [resettingUser, setResettingUser] = useState(null); const [newPassword, setNewPassword] = useState(''); const [resetLoading, setResetLoading] = useState(false); // Action Loading tracking const [actionLoading, setActionLoading] = useState(null); const loadData = async () => { try { const [uData, tData] = await Promise.all([ api.getUsers(selectedTenant || undefined, selectedRole || undefined), api.getTenants(), ]); setUsers(uData); setTenants(tData); } catch (err: any) { console.error('Failed to load user management data', err); } finally { setLoading(false); } }; useEffect(() => { loadData(); }, [selectedTenant, selectedRole]); const handleCreate = async (e: React.FormEvent) => { e.preventDefault(); if (!createForm.tenantId || !createForm.username || !createForm.password || !createForm.fullName) { setMessage({ text: '请填写所有必填字段', success: false }); return; } setCreateLoading(true); try { await api.createUser(createForm); setMessage({ text: `用户 [${createForm.username}] 创建成功!`, success: true }); setShowCreateModal(false); setCreateForm({ tenantId: tenants[0]?.id || '', username: '', password: '', fullName: '', role: 'Teacher', }); loadData(); } catch (err: any) { setMessage({ text: err.message || '创建用户失败', success: false }); } finally { setCreateLoading(false); } }; const handleResetPassword = async (e: React.FormEvent) => { e.preventDefault(); if (!resettingUser || !newPassword.trim()) return; setResetLoading(true); try { await api.resetPassword(resettingUser.id, newPassword.trim()); setMessage({ text: `用户 [${resettingUser.username}] 的密码已重置成功`, success: true }); setResettingUser(null); setNewPassword(''); } catch (err: any) { setMessage({ text: err.message || '重置密码失败', success: false }); } finally { setResetLoading(false); } }; const handleToggleLock = async (user: UserAdmin) => { const nextState = !user.isLocked; const confirmPrompt = nextState ? `确定要锁定账号 [${user.username}] 吗?锁定后该用户将无法登录系统。` : `确定要解锁账号 [${user.username}] 吗?`; if (!window.confirm(confirmPrompt)) return; setActionLoading(`lock_${user.id}`); try { await api.setUserLock(user.id, nextState); setMessage({ text: `用户 [${user.username}] 已成功${nextState ? '锁定' : '解锁'}`, success: true, }); loadData(); } catch (err: any) { setMessage({ text: err.message || '操作失败', success: false }); } finally { setActionLoading(null); } }; const handleDeleteUser = async (user: UserAdmin) => { if (user.role === 'SuperAdmin') { alert('超级管理员账号不可删除'); return; } if (!window.confirm(`警告:确定要永久删除用户 [${user.username} (${user.fullName})] 吗?此操作不可逆!`)) { return; } setActionLoading(`delete_${user.id}`); try { await api.deleteUser(user.id); setMessage({ text: `用户 [${user.username}] 已被删除`, success: true }); loadData(); } catch (err: any) { setMessage({ text: err.message || '删除用户失败', success: false }); } finally { setActionLoading(null); } }; const filteredUsers = users.filter((u) => { const matchesSearch = u.username.toLowerCase().includes(search.toLowerCase()) || u.fullName.toLowerCase().includes(search.toLowerCase()) || u.tenantName.toLowerCase().includes(search.toLowerCase()); return matchesSearch; }); return (
{/* Header */}

多租户统一用户中枢

全网教职工与校级管理员统一管控,支持跨校账号开户、密码强行重置、异常封禁与权限审计

{/* Alert Banner */} {message && (
{message.success ? ( ) : ( )} {message.text}
)} {/* Filter Toolbar */}
{/* Search */}
setSearch(e.target.value)} placeholder="搜索用户名、姓名或学校..." className="bg-transparent border-none text-xs text-white placeholder-slate-500 focus:outline-none w-full" />
{/* Tenant Filter */}
{/* Role Filter */}
{/* Users Table */}
{filteredUsers.length === 0 ? ( ) : ( filteredUsers.map((u) => ( )) )}
用户姓名 / 登录名 归属学校 角色身份 账号状态 最近登录 生命周期操作
{loading ? '正在同步用户中枢...' : '暂无匹配的用户'}
{u.fullName}
{u.username}
{u.tenantName}
{u.tenantId}
{u.role === 'SuperAdmin' ? ( 超级管理员 ) : u.role === 'SchoolAdmin' ? ( 校区管理员 ) : ( 授课老师 )} {u.isLocked ? ( 已锁定封禁 ) : ( 正常 )} {u.lastLoginAt ? new Date(u.lastLoginAt).toLocaleString() : '尚未登录'}
{/* Reset Password */} {/* Lock / Unlock */} {u.role !== 'SuperAdmin' && ( )} {/* Delete User */} {u.role !== 'SuperAdmin' && ( )}
{/* Create User Modal */} {showCreateModal && (

开通新用户账号

平台超级管理员只可通过系统底层配置文件委任,禁止通过控制台赋予。

setCreateForm({ ...createForm, username: e.target.value })} 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" />
setCreateForm({ ...createForm, fullName: e.target.value })} 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" />
setCreateForm({ ...createForm, password: e.target.value })} 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" />
)} {/* Reset Password Modal */} {resettingUser && (

重置用户密码: {resettingUser.username}

为归属于 [{resettingUser.tenantName}] 的 [{resettingUser.fullName}] 强行设置新密码。

setNewPassword(e.target.value)} 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 ================================================================================ import React, { useEffect, useState } from 'react'; import { api } from '../../api/client'; import { TenantAdmin, EmergencyBroadcastRequest } from '../../types'; import { Radio, AlertTriangle, Send, Volume2, Vibrate, Clock, Building2, CheckCircle2, ShieldAlert, Flame, CloudRain, Users, Megaphone } from 'lucide-react'; export const EmergencyBroadcast: React.FC = () => { const [tenants, setTenants] = useState([]); const [loading, setLoading] = useState(true); const [submitting, setSubmitting] = useState(false); const [result, setResult] = useState<{ dispatchedCount: number; targetSchools: number; message: string; success: boolean; } | null>(null); const [form, setForm] = useState({ tenantId: '', title: '⚠️ 全校紧急预警通报', message: '', voice: true, shake: true, durationSeconds: 30, }); 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, }, ]; useEffect(() => { const fetchTenants = async () => { try { const data = await api.getTenants(); setTenants(data); } catch (err) { console.error('Failed to load tenants', err); } finally { setLoading(false); } }; fetchTenants(); }, []); 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 handleBroadcast = async (e: React.FormEvent) => { e.preventDefault(); if (!form.message.trim()) { alert('请输入广播通知正文'); return; } const targetDesc = form.tenantId ? `指定学校 [${tenants.find((t) => t.id === form.tenantId)?.name || form.tenantId}]` : '全网所有学校与所有教室大屏 (全域群发)'; const confirmed = window.confirm( `⚠️ 极高优先级应急调度确认:\n\n目标受众: ${targetDesc}\n标题: ${form.title}\n时长: ${form.durationSeconds} 秒\n语音播报: ${form.voice ? '是' : '否'}\n强震颤: ${form.shake ? '是' : '否'}\n\n此指令将穿透静音模式并以最高置顶层级在所有终端大屏弹出!确定立即下发吗?` ); if (!confirmed) return; setSubmitting(true); setResult(null); try { const res = await api.sendEmergencyBroadcast({ ...form, tenantId: form.tenantId || undefined, }); setResult({ dispatchedCount: res.dispatchedCount, targetSchools: res.targetSchools, message: res.message, success: true, }); setForm((prev) => ({ ...prev, message: '' })); } catch (err: any) { setResult({ dispatchedCount: 0, targetSchools: 0, message: err.message || '应急广播下发失败', success: false, }); } finally { setSubmitting(false); } }; return (
{/* Header */}

全域紧急应急广播

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

{/* Result Banner */} {result && (
{result.success ? ( ) : ( )} {result.message}
)} {/* 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 */}