using System.Security.Claims; using System.Text.Json; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Hubs; using ClassNotify.Server.Infrastructure.Correlation; 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; using Microsoft.EntityFrameworkCore; 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; private readonly ClassNotifyDbContext _dbContext; private readonly ICorrelationContext _correlationContext; public AdminController( ISecurityService securityService, IHubContext deviceHub, IHubContext teacherHub, ILogger logger, ClassNotifyDbContext dbContext, ICorrelationContext correlationContext) { _securityService = securityService; _deviceHub = deviceHub; _teacherHub = teacherHub; _logger = logger; _dbContext = dbContext; _correlationContext = correlationContext; } 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(), GetActorUsername(), GetActorRole(), 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, GetActorUsername(), GetActorRole(), GetClientIp()); if (updated == null) { return NotFound(new { success = false, message = "未找到指定学校" }); } return Ok(updated); } /// /// 获取平台用户列表 (支持按租户、角色与搜索关键字筛选) /// [HttpGet("users")] public async Task GetUsers([FromQuery] string? tenantId, [FromQuery] string? role, [FromQuery] string? q) { var users = await _securityService.GetAllUsersAdminAsync(tenantId, role, q); 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 (req.Password.Length < 8) { return BadRequest(new { success = false, message = "用户密码长度不得小于 8 个字符" }); } 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, GetActorUsername(), GetActorRole(), 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 (req == null || string.IsNullOrWhiteSpace(req.NewPassword)) { return BadRequest(new { success = false, message = "新密码不可为空" }); } try { var ok = await _securityService.ResetPasswordAsync(userId, req.NewPassword, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) return NotFound(new { success = false, message = "用户不存在" }); return Ok(new { success = true, message = "用户密码已成功重置,已有登录凭据已强制失效" }); } catch (ArgumentException ex) { return BadRequest(new { success = false, message = ex.Message }); } } /// /// 管理员为指定用户签发一次性重置工单 (用户自设新密码,管理员不接触新密码明文) /// [HttpPost("users/{userId}/issue-reset-ticket")] public async Task IssueResetTicket(string userId) { var adminUserId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "admin"; var result = await _securityService.IssueAdminResetTicketAsync(adminUserId, GetActorUsername(), userId, GetClientIp()); if (!result.Success) { return NotFound(result); } return Ok(result); } /// /// 锁定或解锁用户账号 /// [HttpPost("users/{userId}/lock")] public async Task SetUserLock(string userId, [FromBody] LockUserRequest req) { var ok = await _securityService.SetUserLockAsync(userId, req.IsLocked, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) { return NotFound(new { success = false, message = "用户不存在" }); } var detail = req.IsLocked ? "锁定账号 (禁止登录)" : "解锁账号 (恢复登录)"; return Ok(new { success = true, isLocked = req.IsLocked, message = detail }); } /// /// 更新指定用户信息 (姓名、角色、归属学校/空间) /// [HttpPatch("users/{userId}")] public async Task UpdateUser(string userId, [FromBody] UpdateUserAdminRequest req) { try { var user = await _securityService.UpdateUserAdminAsync(userId, req, GetActorUsername(), GetActorRole(), GetClientIp()); if (user == null) { return NotFound(new { success = false, message = "用户不存在" }); } return Ok(new { success = true, user, message = "用户信息已成功更新" }); } catch (ArgumentException ex) { return BadRequest(new { success = false, message = ex.Message }); } } /// /// 删除指定用户 (严格防护超级管理员及当前登录账号) /// [HttpDelete("users/{userId}")] public async Task DeleteUser(string userId) { var currentUserId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (!string.IsNullOrEmpty(currentUserId) && currentUserId == userId) { return BadRequest(new { success = false, message = "严禁删除当前正在登录的超级管理员自身账号" }); } try { var ok = await _securityService.DeleteUserAsync(userId, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) { return NotFound(new { success = false, message = "用户不存在或已被删除" }); } return Ok(new { success = true, message = "用户已永久删除" }); } catch (InvalidOperationException ex) { if (ex.Message.Contains("唯一所有者") || ex.Message.Contains("唯一校区管理员")) { return Conflict(new { success = false, message = ex.Message }); } return BadRequest(new { success = false, message = ex.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) { try { var ok = await _securityService.UpdateDeviceAsync(deviceId, req.Hostname, req.ClassroomId, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) { return NotFound(new { success = false, message = "设备不存在" }); } return Ok(new { success = true, message = "设备信息已更新" }); } catch (InvalidOperationException ex) { return BadRequest(new { success = false, message = ex.Message }); } } /// /// 清退并注销指定设备 /// [HttpPost("devices/{deviceId}/decommission")] public async Task DecommissionDevice(string deviceId) { var ok = await _securityService.DecommissionDeviceAsync(deviceId, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) { return NotFound(new { success = false, message = "设备不存在" }); } 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, GetActorRole(), GetClientIp()); 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); await _securityService.LogAdminAuditAsync( adminUser, GetActorRole(), "REMOTE_COMMAND_DISPATCHED", "Device", deviceId, $"指令已实时通过 SignalR 下发: {cmdDto.CommandType} (CommandId: {cmdDto.CommandId})", GetClientIp()); } 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_QUEUED", "Device", deviceId, $"设备离线,指令已入队待补发: {cmdDto.CommandType} (CommandId: {cmdDto.CommandId})", 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 }); } } /// /// 触发指定终端设备执行全面自检 (7 项诊断) 并开启端到端追踪 /// [HttpPost("devices/{deviceId}/self-check")] public async Task TriggerDeviceSelfCheck(string deviceId) { if (string.IsNullOrWhiteSpace(deviceId)) { return BadRequest(new { success = false, message = "设备编号不可为空" }); } var dev = await _dbContext.Devices.FirstOrDefaultAsync(d => d.Id == deviceId); if (dev == null) { return NotFound(new { success = false, message = $"未找到设备 {deviceId}" }); } var adminUser = GetActorUsername(); var correlationId = _correlationContext.CorrelationId; if (string.IsNullOrEmpty(correlationId)) { correlationId = $"sc_corr_{Guid.NewGuid():N}"[..20]; } var selfCheckId = $"sc_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..24]; var requestedAt = DateTimeOffset.UtcNow; var run = new DeviceSelfCheckRun { Id = selfCheckId, TenantId = dev.TenantId, DeviceId = dev.Id, CorrelationId = correlationId, Status = "Pending", RequestedAtUtc = requestedAt, RequestedByUserId = adminUser }; _dbContext.DeviceSelfChecks.Add(run); await _dbContext.SaveChangesAsync(); var selfCheckReq = new DeviceSelfCheckRequestDto { SelfCheckId = selfCheckId, CorrelationId = correlationId, RequestedAtUtc = requestedAt, TimeoutSeconds = 15 }; var payload = JsonSerializer.Serialize(selfCheckReq); var cmdDto = await _securityService.CreateDeviceCommandAsync( dev.TenantId, dev.Id, DeviceCommandTypes.SelfCheck, payload, adminUser, GetActorRole(), GetClientIp()); var connId = _securityService.GetDeviceConnectionId(deviceId); bool isOnline = !string.IsNullOrEmpty(connId); if (isOnline) { await _deviceHub.Clients.Client(connId!).ReceiveRemoteCommand(cmdDto); await _securityService.MarkCommandDispatchedAsync(cmdDto.CommandId); cmdDto.Status = DeviceCommandStatuses.Dispatched; _logger.LogInformation("Dispatched SelfCheck command {CommandId} (SelfCheckId: {SelfCheckId}) to Device {DeviceId} ({ConnId})", cmdDto.CommandId, selfCheckId, deviceId, connId); } else { _logger.LogInformation("Device {DeviceId} is offline. SelfCheck command {CommandId} (SelfCheckId: {SelfCheckId}) queued as Pending", deviceId, cmdDto.CommandId, selfCheckId); } await _securityService.LogAdminAuditAsync( adminUser, GetActorRole(), "DEVICE_SELF_CHECK_TRIGGERED", "Device", deviceId, $"发起设备自检: SelfCheckId={selfCheckId}, CorrelationId={correlationId}, Online={isOnline}", GetClientIp()); return Ok(new { success = true, selfCheckId, correlationId, commandId = cmdDto.CommandId, isOnline, message = isOnline ? "自检指令已下发,正在等待终端上报诊断报告" : "设备当前离线,自检指令已入队,待上线后触发" }); } /// /// 获取指定终端设备最近的自检诊断记录 /// [HttpGet("devices/{deviceId}/self-checks")] public async Task GetDeviceSelfChecks(string deviceId) { var runs = await _dbContext.DeviceSelfChecks .Where(r => r.DeviceId == deviceId) .OrderByDescending(r => r.RequestedAtUtc) .Take(20) .ToListAsync(); return Ok(runs); } /// /// 获取单次自检详细诊断结果 /// [HttpGet("devices/self-checks/{selfCheckId}")] public async Task GetDeviceSelfCheckById(string selfCheckId) { var run = await _dbContext.DeviceSelfChecks.FirstOrDefaultAsync(r => r.Id == selfCheckId); if (run == null) { return NotFound(new { success = false, message = "未找到自检记录" }); } return Ok(run); } /// /// 获取指定学校的所有班级列表 (供管理端激活码生成等下拉选择) /// [HttpGet("classes")] public async Task GetClasses([FromQuery] string tenantId) { if (string.IsNullOrWhiteSpace(tenantId)) { return BadRequest(new { success = false, message = "租户代码不可为空" }); } var classes = await _securityService.GetClassroomsAsync(tenantId.Trim()); return Ok(classes); } /// /// 获取全网激活码列表 /// [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 = null, [FromQuery] string? classId = null, [FromQuery] int? durationDays = null, [FromQuery] string? tier = null, [FromQuery] string? notes = null, [FromQuery] int? count = null, [FromBody] GenerateActivationCodeRequestDto? body = null) { var finalTenantId = !string.IsNullOrWhiteSpace(body?.TenantId) ? body.TenantId.Trim() : tenantId?.Trim(); var finalClassId = !string.IsNullOrWhiteSpace(body?.ClassId) ? body.ClassId.Trim() : classId?.Trim(); var finalTier = !string.IsNullOrWhiteSpace(body?.Tier) ? body.Tier.Trim() : (!string.IsNullOrWhiteSpace(tier) ? tier.Trim() : "Trial"); var finalNotes = !string.IsNullOrWhiteSpace(body?.Notes) ? body.Notes.Trim() : notes?.Trim(); int finalCount = body?.Count ?? count ?? 1; int? finalDurationDays = body?.DurationDays ?? durationDays ?? 7; if (string.IsNullOrWhiteSpace(finalTenantId) || string.IsNullOrWhiteSpace(finalClassId)) { return BadRequest(new { success = false, message = "租户与班级不可为空" }); } if (string.Equals(finalTier, "Perpetual", StringComparison.OrdinalIgnoreCase)) { finalDurationDays = null; } else { if (!finalDurationDays.HasValue || finalDurationDays.Value < 1 || finalDurationDays.Value > 3650) { return BadRequest(new { success = false, message = "授权时长必须在 1 至 3650 天之间" }); } } try { var codes = await _securityService.GenerateActivationCodesAsync( finalTenantId, finalClassId, finalCount, finalDurationDays, finalTier, finalNotes, GetActorUsername(), GetActorRole(), GetClientIp()); return Ok(new { success = true, code = codes.FirstOrDefault() ?? string.Empty, codes, count = codes.Count, tenantId = finalTenantId, classId = finalClassId, durationDays = finalDurationDays, tier = finalTier, notes = finalNotes, message = codes.Count > 1 ? $"成功批量生成 {codes.Count} 个激活码" : "激活码生成成功" }); } catch (InvalidOperationException ex) { return BadRequest(new { success = false, message = ex.Message }); } catch (Exception ex) { return BadRequest(new { success = false, message = ex.Message }); } } /// /// 批量更新激活码备注/标记 /// [HttpPut("activation-codes/notes")] public async Task BatchTagActivationCodes([FromBody] BatchTagActivationCodesRequestDto dto) { if (dto.Codes == null || dto.Codes.Count == 0) { return BadRequest(new { success = false, message = "未选择任何激活码" }); } var ok = await _securityService.UpdateActivationCodeNotesAsync( dto.Codes, dto.Notes, GetActorUsername(), GetActorRole(), GetClientIp()); return Ok(new { success = ok, message = ok ? "激活码备注更新成功" : "未找到匹配的激活码" }); } /// /// 超级管理员修改设备班级名称 /// [HttpPut("devices/{deviceId}/class-name")] public async Task UpdateDeviceClassName( string deviceId, [FromBody] UpdateClassNameRequestDto dto, [FromServices] IHubContext deviceHubContext) { if (dto == null || string.IsNullOrWhiteSpace(dto.ClassName)) { return BadRequest(new { success = false, message = "班级名称不可为空" }); } var (success, message, newName) = await _securityService.UpdateDeviceClassNameAsync( deviceId, dto.ClassName, GetActorUsername(), GetActorRole()); if (!success) { return BadRequest(new { success = false, message }); } try { await deviceHubContext.Clients.Group($"dev_{deviceId}").ClassDisplayNameChanged(newName ?? dto.ClassName); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to broadcast ClassDisplayNameChanged to device"); } return Ok(new { success = true, message, className = newName }); } /// /// 管理员为指定设备直接续费/延期 (Remote One-Click Renewal) /// [HttpPost("devices/{deviceId}/license")] public async Task ManageDeviceLicense( string deviceId, [FromBody] RenewDeviceLicenseRequestDto dto, [FromServices] IHubContext deviceHubContext) { var (success, message, newStatus) = await _securityService.RenewDeviceLicenseAsync( deviceId, dto.ActivationCode, dto.ExtendDays, dto.Tier, GetActorUsername(), dto.Reason, dto.ValidThroughDate); if (!success) { return BadRequest(new { success = false, message }); } // Push real-time updated license status via SignalR to all if (newStatus != null) { await deviceHubContext.Clients.All.ReceiveLicenseStatus(newStatus); } return Ok(new { success = true, message, license = newStatus }); } /// /// 管理员批量为多个设备续费/延期 (Remote Batch Renewal) /// [HttpPost("devices/licenses/batch-renew")] public async Task BatchManageDeviceLicenses( [FromBody] BatchRenewDevicesLicenseRequestDto dto, [FromServices] IHubContext deviceHubContext) { var (success, message, renewedList) = await _securityService.BatchRenewDevicesLicenseAsync( dto.DeviceIds, dto.ExtendDays, dto.Tier, GetActorUsername(), dto.Reason, dto.ValidThroughDate, dto.ClientRequestId, dto.LicenseKind, dto.ValidThroughLocalDate, null); if (!success) { return BadRequest(new { success = false, message }); } foreach (var item in renewedList) { if (item.Status != null) { await deviceHubContext.Clients.All.ReceiveLicenseStatus(item.Status); } } return Ok(new { success = true, message, renewedCount = renewedList.Count }); } /// /// 获取全平台商业授权变更流水与审计账本 /// [HttpGet("licenses")] public async Task GetLicenseRecords([FromQuery] int limit = 100) { var records = await _securityService.GetLicenseRecordsAsync(null, limit); return Ok(records); } /// /// 作废或删除激活码 /// [HttpDelete("activation-codes/{code}")] public async Task DeleteActivationCode(string code) { var ok = await _securityService.DeleteActivationCodeAsync(code, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) { return NotFound(new { success = false, message = "激活码不存在" }); } 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 = "广播内容不能为空" }); } if (req.Message.Length > 2000) { return BadRequest(new { success = false, message = "广播内容长度不能超过 2000 字符" }); } if (!string.IsNullOrWhiteSpace(req.Title) && req.Title.Length > 100) { return BadRequest(new { success = false, message = "广播标题长度不能超过 100 字符" }); } if (req.DurationSeconds < 5 || req.DurationSeconds > 600) { return BadRequest(new { success = false, message = "广播显示时长必须在 5 至 600 秒之间" }); } var actor = GetActorUsername(); var targetTenants = new List(); if (string.IsNullOrWhiteSpace(req.TenantId) || req.TenantId == "*") { var all = await _securityService.GetTenantsOverviewAsync(); targetTenants = all.Where(t => t.IsActive).ToList(); } else { var all = await _securityService.GetTenantsOverviewAsync(); var found = all.FirstOrDefault(t => t.Id == req.TenantId); if (found != null) { if (!found.IsActive) { return BadRequest(new { success = false, message = $"目标学校 '{found.Name}' 当前已被停用,无法接收应急广播" }); } targetTenants.Add(found); } else return NotFound(new { success = false, message = $"未找到指定学校: {req.TenantId}" }); } // P0-FailClosed Audit: Persist BROADCAST_REQUESTED audit BEFORE triggering any SignalR broadcast. // If audit write fails (e.g. DB error or trigger block), an exception is thrown and NO broadcast is ever dispatched. await _securityService.LogAdminAuditAsync( actor, GetActorRole(), "EMERGENCY_BROADCAST_REQUESTED", "System", req.TenantId ?? "ALL", $"请求下发紧急广播: {req.Title} (计划覆盖 {targetTenants.Count} 所学校)", GetClientIp()); var broadcastId = $"bcast_{Guid.NewGuid():N}"; int dispatchedCount = 0; var duration = req.DurationSeconds; 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]}", BroadcastId = broadcastId, 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_COMPLETED", "System", req.TenantId ?? "ALL", $"紧急广播下发完成: {req.Title} - {req.Message} (覆盖 {dispatchedCount} 个班级, BroadcastId: {broadcastId})", GetClientIp()); return Ok(new { success = true, broadcastId, dispatchedCount, targetSchools = targetTenants.Count, message = $"紧急广播已成功下发至 {targetTenants.Count} 所学校共 {dispatchedCount} 个班级,正在等待设备回执" }); } /// /// 获取紧急广播真实设备回执聚合状态 /// [HttpGet("broadcasts/{broadcastId}/receipt-summary")] public async Task GetBroadcastReceiptSummary(string broadcastId, CancellationToken ct) { var summary = await _securityService.GetBroadcastReceiptSummaryAsync(broadcastId, ct); if (summary == null) { return NotFound(new { success = false, message = "未找到该广播记录" }); } return Ok(summary); } /// /// 获取平台真实系统健康状态 (数据库连通性、延迟、内存、运行时间、连接数) /// [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); } #region Turn 75: Trial Anti-Freeload & Direct Usability Polish Endpoints /// /// 获取设备首次试用防刷台账列表 (T75-04, T75-05, T75-06) /// 仅限 SuperAdmin 角色,指纹已脱敏,绝不暴露明文激活码 /// [HttpGet("trial-ledgers")] public async Task GetTrialLedgers( [FromQuery] string? tenantId = null, [FromQuery] string? q = null, [FromQuery] bool onlyBlocked = false, [FromQuery] string? overrideState = null, [FromQuery] int limit = 100) { var ledgers = await _securityService.GetTrialLedgersAsync(tenantId, q, onlyBlocked, overrideState, limit); return Ok(ledgers); } /// /// 超管人工特批一次性试用放行 (T75-07, T75-08, T75-11) /// 必须填写经审计的原因,默认 72 小时内单次有效 /// [HttpPost("trial-ledgers/{id}/override")] public async Task GrantTrialOverride(string id, [FromBody] GrantTrialOverrideRequestDto request) { if (request == null || string.IsNullOrWhiteSpace(request.Reason)) { return BadRequest(new { success = false, message = "特批原因不能为空,必须详细记录特批缘由以供安全审计" }); } var (success, message, ledger) = await _securityService.GrantTrialOverrideAsync( id, request.Reason, request.ValidHours, GetActorUsername(), GetClientIp()); if (!success) { if (message.Contains("已存在有效特批放行额度")) { return Conflict(new { success = false, message }); } return BadRequest(new { success = false, message }); } return Ok(new { success = true, message, ledger }); } /// /// 撤销未消费的特批放行资格 (T75-10, T75-11) /// [HttpPost("trial-ledgers/{id}/revoke-override")] public async Task RevokeTrialOverride(string id, [FromBody] RevokeTrialOverrideRequestDto? request) { var (success, message) = await _securityService.RevokeTrialOverrideAsync( id, request?.Reason, GetActorUsername(), GetClientIp()); if (!success) { return BadRequest(new { success = false, message }); } return Ok(new { success = true, message }); } /// /// 获取商业授权服务端权威聚合大盘统计指标 (T75-02, T75-03) /// 排除测试数据污染与负数记录,服务端原子计算 /// [HttpGet("licenses/summary")] [HttpGet("license-records/summary")] public async Task GetLicenseRecordsSummary([FromQuery] string? tenantId = null) { var summary = await _securityService.GetLicenseRecordsSummaryAsync(tenantId); return Ok(summary); } /// /// 修改大屏设备运维备注 (T75-16) /// 区分 Classroom.DisplayName (班级名称) 与 Device.DisplayLabel (大屏备注) /// [HttpPatch("devices/{deviceId}/display-label")] public async Task UpdateDeviceDisplayLabel(string deviceId, [FromBody] UpdateDeviceDisplayLabelRequest request) { var ok = await _securityService.UpdateDeviceDisplayLabelAsync( deviceId, request?.DisplayLabel, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) { return NotFound(new { success = false, message = "设备不存在或更新失败" }); } return Ok(new { success = true, displayLabel = request?.DisplayLabel, message = "大屏备注更新成功" }); } #endregion }