diff --git a/src/Server/ClassNotify.Server/Controllers/TeacherConsoleController.cs b/src/Server/ClassNotify.Server/Controllers/TeacherConsoleController.cs index 82353ea..3cf1cec 100644 --- a/src/Server/ClassNotify.Server/Controllers/TeacherConsoleController.cs +++ b/src/Server/ClassNotify.Server/Controllers/TeacherConsoleController.cs @@ -3,6 +3,7 @@ using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Services; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; @@ -10,19 +11,40 @@ namespace ClassNotify.Server.Controllers; public record TeacherProfileDto( string TeacherId, + string? Username, + string? FullName, + string? SpaceName, string? Mobile, string SubscriptionState, DateTimeOffset? TrialEndsAt, DateTimeOffset? VipExpiresAt, int ActiveScreenCount, - int ScreenLimit + int ScreenLimit, + DateTimeOffset CreatedAt +); + +public record UpdateTeacherProfileRequest( + string? FullName, + string? SpaceName +); + +public record TeacherChangePasswordRequest( + string CurrentPassword, + string NewPassword, + string ConfirmPassword +); + +public record RotateRecoveryKeyRequest( + string CurrentPassword ); public record ScreenDto( Guid DeviceId, string ClassAlias, bool IsOnline, - DateTimeOffset BoundAt + DateTimeOffset BoundAt, + string? ClientVersion = "v2.2.0", + string? HardwareDeviceId = null ); public record ClaimScreenRequest( @@ -39,6 +61,9 @@ public class TeacherConsoleController : ControllerBase private readonly IPairingService _pairingService; private readonly IConfiguration _config; private readonly IDeviceNotificationService _deviceNotificationService; + private readonly ISecurityService _securityService; + private readonly IPasswordHasher _passwordHasher; + private readonly IInstallerTicketService _ticketService; private readonly ILogger _logger; public TeacherConsoleController( @@ -46,12 +71,18 @@ public class TeacherConsoleController : ControllerBase IPairingService pairingService, IConfiguration config, IDeviceNotificationService deviceNotificationService, + ISecurityService securityService, + IPasswordHasher passwordHasher, + IInstallerTicketService ticketService, ILogger logger) { _db = db; _pairingService = pairingService; _config = config; _deviceNotificationService = deviceNotificationService; + _securityService = securityService; + _passwordHasher = passwordHasher; + _ticketService = ticketService; _logger = logger; } @@ -63,13 +94,14 @@ public class TeacherConsoleController : ControllerBase } [HttpGet("me")] + [HttpGet("profile")] public async Task> GetProfileAsync() { var teacherId = GetTeacherId(); if (string.IsNullOrEmpty(teacherId)) return Unauthorized(new { code = "TEACHER_NOT_FOUND", message = "教师账户不存在或未授权" }); - var teacher = await _db.Users.FindAsync(teacherId); + var teacher = await _db.Users.Include(u => u.Tenant).FirstOrDefaultAsync(u => u.Id == teacherId); if (teacher == null) return Unauthorized(new { code = "TEACHER_NOT_FOUND", message = "教师账户不存在" }); @@ -78,19 +110,162 @@ public class TeacherConsoleController : ControllerBase var screenLimit = _config.GetValue("Product:PersonalScreenLimit", 4); var now = DateTimeOffset.UtcNow; - var subState = teacher.IsVipActive(now) ? "VIP" : (teacher.IsTrialActive(now) ? "Trial" : "Expired"); + // 关键自愈逻辑:若教师尚未绑定任何大屏,且非正式 VIP,试用期尚未开启,TrialEndsAt 自动修正为 null,绝不提前扣除天数 + if (activeScreenCount == 0 && teacher.VipExpiresAt == null && teacher.TrialEndsAt != null) + { + teacher.TrialEndsAt = null; + await _db.SaveChangesAsync(); + } + + var isVip = teacher.IsVipActive(now); + string subState; + if (isVip) + { + subState = "VIP"; + } + else if (teacher.TrialEndsAt == null || teacher.TrialEndsAt.Value > now) + { + subState = "Trial"; + } + else + { + subState = "Expired"; + } return Ok(new TeacherProfileDto( TeacherId: teacher.Id, + Username: teacher.Username, + FullName: teacher.FullName, + SpaceName: teacher.Tenant?.Name ?? "教师工作台", Mobile: teacher.Mobile, SubscriptionState: subState, TrialEndsAt: teacher.TrialEndsAt, VipExpiresAt: teacher.VipExpiresAt, ActiveScreenCount: activeScreenCount, - ScreenLimit: screenLimit + ScreenLimit: screenLimit, + CreatedAt: teacher.CreatedAt )); } + [HttpPatch("profile")] + public async Task UpdateProfileAsync([FromBody] UpdateTeacherProfileRequest req) + { + var teacherId = GetTeacherId(); + if (string.IsNullOrEmpty(teacherId)) + return Unauthorized(new { code = "TEACHER_NOT_FOUND", message = "教师账户不存在或未授权" }); + + var teacher = await _db.Users.Include(u => u.Tenant).FirstOrDefaultAsync(u => u.Id == teacherId); + if (teacher == null) + return Unauthorized(new { code = "TEACHER_NOT_FOUND", message = "教师账户不存在" }); + + if (!string.IsNullOrWhiteSpace(req.FullName)) + { + var name = req.FullName.Trim(); + if (name.Length > 50) + return BadRequest(new { code = "INVALID_NAME", message = "教师称谓长度不能超过 50 个字符" }); + teacher.FullName = name; + } + + if (!string.IsNullOrWhiteSpace(req.SpaceName)) + { + var space = req.SpaceName.Trim(); + if (space.Length > 100) + return BadRequest(new { code = "INVALID_SPACE_NAME", message = "教学空间名称长度不能超过 100 个字符" }); + + if (teacher.Tenant != null && (teacher.Role == "TenantOwner" || teacher.Tenant.TenantType == "Personal")) + { + teacher.Tenant.Name = space; + } + } + + await _db.SaveChangesAsync(); + _logger.LogInformation("Teacher {TeacherId} profile updated: FullName={FullName}, SpaceName={SpaceName}", + teacher.Id, teacher.FullName, teacher.Tenant?.Name); + + var profileRes = await GetProfileAsync(); + return profileRes.Result ?? Ok(profileRes.Value); + } + + [HttpPost("account/change-password")] + public async Task ChangePasswordAsync([FromBody] TeacherChangePasswordRequest req) + { + var teacherId = GetTeacherId(); + if (string.IsNullOrEmpty(teacherId)) + return Unauthorized(new { code = "TEACHER_NOT_FOUND", message = "教师账户不存在或未授权" }); + + var teacher = await _db.Users.Include(u => u.Tenant).FirstOrDefaultAsync(u => u.Id == teacherId); + if (teacher == null) + return Unauthorized(new { code = "TEACHER_NOT_FOUND", message = "教师账户不存在" }); + + if (string.IsNullOrEmpty(req.CurrentPassword)) + return BadRequest(new { code = "PASSWORD_REQUIRED", message = "请输入当前登录密码" }); + + if (string.IsNullOrEmpty(req.NewPassword) || req.NewPassword.Length < 8) + return BadRequest(new { code = "PASSWORD_TOO_SHORT", message = "为了账户安全,新密码长度不能少于 8 位" }); + + if (req.NewPassword != req.ConfirmPassword) + return BadRequest(new { code = "PASSWORD_MISMATCH", message = "两次输入的新密码不一致,请核对" }); + + var verifyResult = _passwordHasher.VerifyHashedPassword(teacher, teacher.PasswordHash, req.CurrentPassword); + if (verifyResult == PasswordVerificationResult.Failed) + { + return BadRequest(new { code = "INVALID_CURRENT_PASSWORD", message = "当前密码不正确,请核对后重试" }); + } + + teacher.PasswordHash = _passwordHasher.HashPassword(teacher, req.NewPassword); + teacher.TokenVersion++; + + var remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString(); + _db.AdminAuditEvents.Add(new AdminAuditEvent + { + Id = $"aud_{Guid.NewGuid():N}"[..16], + OccurredAt = DateTimeOffset.UtcNow, + ActorUsername = teacher.Username, + ActorRole = teacher.Role, + Action = "TEACHER_CHANGE_PASSWORD", + TargetType = "User", + TargetId = teacher.Id, + Details = "教师在控制台自主修改登录密码,旧凭据立即失效", + IpAddress = remoteIp + }); + await _db.SaveChangesAsync(); + + var freshToken = _securityService.GenerateJwtToken(teacher, teacher.Tenant, isPasswordChangeOnly: false); + _logger.LogInformation("Teacher {TeacherId} ({Username}) successfully changed password.", teacher.Id, teacher.Username); + + return Ok(new + { + success = true, + message = "密码修改成功!新密码已生效", + token = freshToken + }); + } + + [HttpPost("account/rotate-recovery-key")] + public async Task RotateRecoveryKeyAsync([FromBody] RotateRecoveryKeyRequest req) + { + var teacherId = GetTeacherId(); + if (string.IsNullOrEmpty(teacherId)) + return Unauthorized(new { code = "TEACHER_NOT_FOUND", message = "教师账户不存在或未授权" }); + + if (string.IsNullOrEmpty(req.CurrentPassword)) + return BadRequest(new { code = "PASSWORD_REQUIRED", message = "请输入当前密码以验证身份" }); + + var remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString(); + var (ok, msg, newKey) = await _securityService.RotateRecoveryKeyAsync(teacherId, req.CurrentPassword, remoteIp); + if (!ok) + { + return BadRequest(new { code = "ROTATE_FAILED", message = msg }); + } + + return Ok(new + { + success = true, + message = msg, + recoveryKey = newKey + }); + } + [HttpGet("screens")] public async Task>> GetScreensAsync() { @@ -100,20 +275,24 @@ public class TeacherConsoleController : ControllerBase var bindings = await _db.TeacherDeviceBindings .Where(b => b.TeacherId == teacherId && b.IsActive) - .Join(_db.Devices, b => b.DeviceId.ToString(), d => d.Id, (b, d) => new { - b.DeviceId, - ClassAlias = b.ClassAlias ?? "未命名教室", - d.LastHeartbeatAt, - b.BoundAt - }) .ToListAsync(); - var dtos = bindings.Select(b => new ScreenDto( - b.DeviceId, - b.ClassAlias, - b.LastHeartbeatAt.HasValue && (DateTimeOffset.UtcNow - b.LastHeartbeatAt.Value).TotalSeconds <= 120, - b.BoundAt - )).ToList(); + var allDevices = await _db.Devices.ToListAsync(); + var deviceDict = allDevices.ToDictionary(d => PairingService.ToDeviceGuid(d.Id), d => d); + + var dtos = bindings.Select(b => { + deviceDict.TryGetValue(b.DeviceId, out var dev); + var ver = dev?.ClientVersion; + if (!string.IsNullOrEmpty(ver) && !ver.StartsWith('v')) ver = $"v{ver}"; + return new ScreenDto( + b.DeviceId, + b.ClassAlias ?? "未命名教室", + dev != null && dev.LastHeartbeatAt.HasValue && (DateTimeOffset.UtcNow - dev.LastHeartbeatAt.Value).TotalSeconds <= 120, + b.BoundAt, + ver ?? "v2.2.0", + dev?.Id + ); + }).ToList(); return Ok(dtos); } @@ -128,36 +307,99 @@ public class TeacherConsoleController : ControllerBase if (string.IsNullOrWhiteSpace(req.PairingCode)) return BadRequest(new { code = "INVALID_PAIRING_CODE", message = "请输入有效的8位班级配对码" }); + var (isValid, canonicalClassName, classError) = PairingService.ValidateAndCanonicalizeClassName(req.ClassAlias); + if (!isValid) + { + return BadRequest(new { code = "INVALID_CLASS_NAME", message = classError }); + } + var normalizedCode = req.PairingCode.Replace(" ", "").Replace("-", "").Trim(); - var result = await _pairingService.ClaimDeviceAsync(teacherId, normalizedCode, req.ClassAlias); + var result = await _pairingService.ClaimDeviceAsync(teacherId, normalizedCode, canonicalClassName); if (!result.Success) { return BadRequest(new { code = result.ErrorCode, message = result.ErrorMessage }); } - return Ok(new { deviceId = result.DeviceId }); + if (result.DeviceId.HasValue) + { + try + { + var activeTeacherCount = await _db.TeacherDeviceBindings + .CountAsync(b => b.DeviceId == result.DeviceId.Value && b.IsActive); + await _deviceNotificationService.NotifyScreenClaimedAsync(result.DeviceId.Value, canonicalClassName ?? "教学班级", activeTeacherCount); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to send real-time binding notification to screen {DeviceId}", result.DeviceId.Value); + } + } + + return Ok(new { deviceId = result.DeviceId, classAlias = canonicalClassName }); } - [HttpDelete("screens/{deviceId:guid}")] - public async Task UnbindScreenAsync(Guid deviceId) + [HttpDelete("screens/{deviceId}")] + public async Task UnbindScreenAsync(string deviceId) { var teacherId = GetTeacherId(); if (string.IsNullOrEmpty(teacherId)) return Unauthorized(new { code = "UNAUTHORIZED", message = "未登录" }); - var binding = await _db.TeacherDeviceBindings - .FirstOrDefaultAsync(b => b.TeacherId == teacherId && b.DeviceId == deviceId && b.IsActive); + var bindings = await _db.TeacherDeviceBindings + .Where(b => b.TeacherId == teacherId && b.IsActive) + .ToListAsync(); - if (binding == null) - return NotFound(new { code = "BINDING_NOT_FOUND", message = "绑定记录不存在或已解除" }); + TeacherDeviceBinding? targetBinding = null; - // 统一使用已冻结字段 ReleasedAt - binding.IsActive = false; - binding.ReleasedAt = DateTimeOffset.UtcNow; - await _db.SaveChangesAsync(); + if (Guid.TryParse(deviceId, out var parsedGuid)) + { + targetBinding = bindings.FirstOrDefault(b => b.DeviceId == parsedGuid); + } + + if (targetBinding == null) + { + var hashedGuid = PairingService.ToDeviceGuid(deviceId); + targetBinding = bindings.FirstOrDefault(b => b.DeviceId == hashedGuid); + } + + if (targetBinding == null) + { + var dev = await _db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId || d.Hostname == deviceId || d.ClassroomId == deviceId); + if (dev != null) + { + var devGuid = PairingService.ToDeviceGuid(dev.Id); + targetBinding = bindings.FirstOrDefault(b => b.DeviceId == devGuid); + } + } + + if (targetBinding == null) + { + targetBinding = bindings.FirstOrDefault(b => b.ClassAlias == deviceId); + } + + if (targetBinding != null) + { + targetBinding.IsActive = false; + targetBinding.ReleasedAt = DateTimeOffset.UtcNow; + await _db.SaveChangesAsync(); + _logger.LogInformation("Teacher {TeacherId} unbound screen {DeviceId}", teacherId, targetBinding.DeviceId); + } + + // Check if there are any remaining active screens for this teacher + var remainingScreens = await _db.TeacherDeviceBindings + .CountAsync(b => b.TeacherId == teacherId && b.IsActive); + + if (remainingScreens == 0) + { + var teacher = await _db.Users.FirstOrDefaultAsync(u => u.Id == teacherId); + if (teacher != null && teacher.VipExpiresAt == null && teacher.TrialEndsAt != null) + { + teacher.TrialEndsAt = null; + await _db.SaveChangesAsync(); + _logger.LogInformation("Teacher {TeacherId} has 0 screens after unbind, reset TrialEndsAt to null", teacherId); + } + } - _logger.LogInformation("Teacher {TeacherId} unbound screen {DeviceId}", teacherId, deviceId); return NoContent(); } @@ -188,4 +430,24 @@ public class TeacherConsoleController : ControllerBase return Ok(new { pairingCode, ttlSeconds = 600 }); } + + /// + /// 已登录教师申请 Windows 客户端安装包临时下载凭据(10分钟窗口) + /// 支持所有服务状态(Trial, Active, Expired),不因订阅到期卡住客户端获取 + /// + [HttpPost("download/windows-ticket")] + public ActionResult GetWindowsInstallerTicket() + { + var teacherId = GetTeacherId(); + if (string.IsNullOrEmpty(teacherId)) + return Unauthorized(new { code = "UNAUTHORIZED", message = "未登录" }); + + var ticket = _ticketService.IssueTicket(teacherId, TimeSpan.FromMinutes(10)); + return Ok(new + { + version = "2.2.0", + downloadUrl = $"/download/windows?ticket={Uri.EscapeDataString(ticket)}", + expiresInSeconds = 600 + }); + } } diff --git a/src/Shared/ClassNotify.Shared/Contracts/IDeviceHubClient.cs b/src/Shared/ClassNotify.Shared/Contracts/IDeviceHubClient.cs index e8f207f..a670d35 100644 --- a/src/Shared/ClassNotify.Shared/Contracts/IDeviceHubClient.cs +++ b/src/Shared/ClassNotify.Shared/Contracts/IDeviceHubClient.cs @@ -56,4 +56,9 @@ public interface IDeviceHubClient /// 服务端下发大屏临时进入配对模式(携带临时配对码与有效期秒数) /// Task ReceivePairingMode(string pairingCode, int ttlSeconds); + + /// + /// Turn 115: 服务端通知大屏绑定状态更新(如任课教师首次绑定或新增任课教师绑定) + /// + Task DeviceBindingUpdated(string classDisplayName, int boundTeacherCount); } diff --git a/src/Shared/ClassNotify.Shared/Ipc/IpcMessage.cs b/src/Shared/ClassNotify.Shared/Ipc/IpcMessage.cs index d2a8d77..9650570 100644 --- a/src/Shared/ClassNotify.Shared/Ipc/IpcMessage.cs +++ b/src/Shared/ClassNotify.Shared/Ipc/IpcMessage.cs @@ -25,7 +25,11 @@ public enum IpcCommandType RequestUpdateClassName = 17, UpdateClassNameResult = 18, ClassDisplayNameChanged = 19, - EnterPairingMode = 20 + EnterPairingMode = 20, + RequestPairingMode = 21, + PairingModeResult = 22, + RequestPairingSession = 25, + PairingSessionResult = 26 } /// diff --git a/src/Shared/ClassNotify.Shared/Models/ClientStateSnapshotDto.cs b/src/Shared/ClassNotify.Shared/Models/ClientStateSnapshotDto.cs index 02acd91..4986b48 100644 --- a/src/Shared/ClassNotify.Shared/Models/ClientStateSnapshotDto.cs +++ b/src/Shared/ClassNotify.Shared/Models/ClientStateSnapshotDto.cs @@ -1,3 +1,5 @@ +using ClassNotify.Shared.Enums; + namespace ClassNotify.Shared.Models; /// @@ -5,6 +7,36 @@ namespace ClassNotify.Shared.Models; /// public class ClientStateSnapshotDto { + /// + /// Turn 115 权威设备绑定生命周期状态: Unbound / Bound + /// + public DeviceBindingState BindingState { get; set; } = DeviceBindingState.Unbound; + + /// + /// Turn 116 运行限制状态维度(与 BindingState 正交,互不污染) + /// + public OperationalRestrictionState RestrictionState { get; set; } = OperationalRestrictionState.None; + + /// + /// 权威教室/班级ID + /// + public string? ClassroomId { get; set; } + + /// + /// 权威教室/班级显示名称 + /// + public string? ClassroomDisplayName { get; set; } + + /// + /// 已绑定教师总数(去实名化计数,合规保护隐私) + /// + public int BoundTeacherCount { get; set; } = 0; + + /// + /// 状态版本号,单调递增,防止异步消息乱序覆盖 + /// + public long StateRevision { get; set; } = 0; + /// /// 设备配置状态:Unactivated / Activating / Activated / CredentialError / ReprovisionRequired /// diff --git a/src/Web/ClassNotify.Web/src/pages/teacher/TeacherConsole.tsx b/src/Web/ClassNotify.Web/src/pages/teacher/TeacherConsole.tsx index 011db6b..e8458d5 100644 --- a/src/Web/ClassNotify.Web/src/pages/teacher/TeacherConsole.tsx +++ b/src/Web/ClassNotify.Web/src/pages/teacher/TeacherConsole.tsx @@ -4,6 +4,7 @@ import { useAuth } from '../../context/AuthContext'; import { Classroom, NotificationRecord, TeacherProfile, TeacherScreen } from '../../types'; import { teacherRealtime } from '../../realtime/TeacherRealtime'; import { CheckoutModal } from '../../components/CheckoutModal'; +import { TeacherProfileSettings } from '../../components/TeacherProfileSettings'; import { Send, Volume2, @@ -37,10 +38,32 @@ import { BellRing, Plus, Unlink, - RadioTower + RadioTower, + Download } from 'lucide-react'; import { StatusBadge, SearchInput, Modal, DangerConfirmModal } from '../../components/ui'; +export function validateAndCanonicalizeClassName(input: string): { isValid: boolean; canonical: string; error?: string } { + if (!input || !input.trim()) { + return { isValid: false, canonical: '', error: '请填写班级名称' }; + } + const raw = input.trim(); + if (/[()()[\]【】{}]/.test(raw)) { + return { isValid: false, canonical: '', error: '班级名称不能包含括号,请直接填写,例如:高一3班。' }; + } + const canonical = raw.replace(/ +/g, ''); + if (canonical.length < 2 || canonical.length > 20) { + return { isValid: false, canonical, error: '班级名称长度必须在 2 至 20 个字之间' }; + } + if (!canonical.endsWith('班')) { + return { isValid: false, canonical, error: '班级名称必须以“班”结尾,例如:高一3班、91班。' }; + } + if (!/^[\p{Script=Han}0-9]+$/u.test(canonical)) { + return { isValid: false, canonical, error: '班级名称只能包含汉字和数字,并且必须以“班”结尾,例如:高一3班、91班。' }; + } + return { isValid: true, canonical }; +} + function parseAckStatus(raw: number | string): 'Sent' | 'Delivered' | 'Acknowledged' | 'Timeout' | 'Failed' | 'Cancelled' { if (typeof raw === 'string') { switch (raw.toLowerCase()) { @@ -94,8 +117,23 @@ export const TeacherConsole: React.FC = () => { const [sending, setSending] = useState(false); const [showAdvanced, setShowAdvanced] = useState(false); - // Tab State: 'composer' (📢 发送呼叫) | 'receipts' (📋 送达回执) | 'screen' (🖥️ 班级大屏与授权) - const [activeTab, setActiveTab] = useState<'composer' | 'receipts' | 'screen'>('composer'); + // Tab State: 'composer' (📢 发送呼叫) | 'receipts' (📋 送达回执) | 'screen' (🖥️ 班级大屏与授权) | 'profile' (👤 个人设置) + const [activeTab, setActiveTab] = useState<'composer' | 'receipts' | 'screen' | 'profile'>('composer'); + + useEffect(() => { + const urlParams = new URLSearchParams(window.location.search); + const tabParam = urlParams.get('tab'); + if (tabParam && ['composer', 'receipts', 'screen', 'profile'].includes(tabParam)) { + setActiveTab(tabParam as any); + } + const handleSwitchTab = (e: any) => { + if (e?.detail && ['composer', 'receipts', 'screen', 'profile'].includes(e.detail)) { + setActiveTab(e.detail); + } + }; + window.addEventListener('switch-teacher-tab', handleSwitchTab); + return () => window.removeEventListener('switch-teacher-tab', handleSwitchTab); + }, []); const [copiedDownloadLink, setCopiedDownloadLink] = useState(false); @@ -111,6 +149,17 @@ export const TeacherConsole: React.FC = () => { const [claimSuccess, setClaimSuccess] = useState(null); const [pairingModalInfo, setPairingModalInfo] = useState<{ open: boolean; deviceId?: string; alias?: string; code?: string; ttlSeconds?: number } | null>(null); const [activatingPairingId, setActivatingPairingId] = useState(null); + const [downloadVersion, setDownloadVersion] = useState(null); + + useEffect(() => { + if (typeof api?.getDownloadManifest === 'function') { + api.getDownloadManifest().then(manifest => { + if (manifest && manifest.version) { + setDownloadVersion(manifest.version); + } + }).catch(() => {}); + } + }, []); // Turn 103: Draft Preservation & Auto-Restore on SESSION_SUPERSEDED const [restoredDraftNotice, setRestoredDraftNotice] = useState(null); @@ -173,6 +222,7 @@ export const TeacherConsole: React.FC = () => { const [loadingMore, setLoadingMore] = useState(false); const [hasMoreHistory, setHasMoreHistory] = useState(true); const [loading, setLoading] = useState(true); + const [refreshingScreens, setRefreshingScreens] = useState(false); const [loadError, setLoadError] = useState(null); // Filter state for right column receipt feed @@ -289,6 +339,22 @@ export const TeacherConsole: React.FC = () => { } }; + const handleManualRefreshScreens = async () => { + setRefreshingScreens(true); + const start = Date.now(); + try { + await loadClassesAndHistory(); + } finally { + const elapsed = Date.now() - start; + const minSpinMs = 600; + if (elapsed < minSpinMs) { + setTimeout(() => setRefreshingScreens(false), minSpinMs - elapsed); + } else { + setRefreshingScreens(false); + } + } + }; + const formatExpirationDate = (dateStr?: string) => { if (!dateStr) return ''; try { @@ -304,8 +370,25 @@ export const TeacherConsole: React.FC = () => { } }; + const [downloadingClient, setDownloadingClient] = useState(false); + + const handleDownloadClient = async () => { + try { + setDownloadingClient(true); + const res = await api.getWindowsInstallerTicket(); + if (res && res.downloadUrl) { + window.location.href = res.downloadUrl; + } + } catch (err: any) { + setSendError(err?.message || '获取大屏客户端下载凭据失败,请重试'); + } finally { + setDownloadingClient(false); + } + }; + const handleCopyDownloadLink = () => { - navigator.clipboard.writeText('https://classnotify.paradise.eu.org/download/windows'); + const entryUrl = `${window.location.origin}/teacher?tab=screens`; + navigator.clipboard.writeText(entryUrl); setCopiedDownloadLink(true); setTimeout(() => setCopiedDownloadLink(false), 2500); }; @@ -322,12 +405,19 @@ export const TeacherConsole: React.FC = () => { const handleClaimSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!claimPairingCode.trim()) return; + + const classCheck = validateAndCanonicalizeClassName(claimClassAlias); + if (!classCheck.isValid) { + setClaimError(classCheck.error || '班级名称不合法'); + return; + } + setClaimingScreen(true); setClaimError(null); setClaimSuccess(null); try { - await api.claimTeacherScreen(claimPairingCode.trim(), claimClassAlias.trim() || undefined); + await api.claimTeacherScreen(claimPairingCode.trim(), classCheck.canonical); const isExpired = teacherProfile?.subscriptionState === 'Expired'; if (isExpired) { setClaimSuccess('已成功绑定大屏。当前教师服务已到期,开通正式版后即可发送通知。'); @@ -355,10 +445,10 @@ export const TeacherConsole: React.FC = () => { try { await api.unbindTeacherScreen(screen.deviceId); - await loadClassesAndHistory(); } catch (err: any) { - alert(err?.message || '解除绑定失败,请稍后重试'); + console.warn('Unbind response notice:', err); } + await loadClassesAndHistory(); }; const handleActivatePairingMode = async (screen: TeacherScreen) => { @@ -1500,9 +1590,6 @@ export const TeacherConsole: React.FC = () => {

教师工作台 - - {isPersonalTeacher ? '个人独立空间' : '智慧校园'} -

秒级定向通知教室大屏 · 支持 TTS 朗读、视觉核验与实时回执 @@ -1536,7 +1623,9 @@ export const TeacherConsole: React.FC = () => { {teacherProfile.subscriptionState === 'VIP' ? `正式版有效${teacherProfile.vipExpiresAt ? ` · 至 ${teacherProfile.vipExpiresAt.slice(0, 10)}` : ''}` : teacherProfile.subscriptionState === 'Trial' - ? `免费试用中${teacherProfile.trialEndsAt ? ` · 剩 ${Math.max(0, Math.ceil((new Date(teacherProfile.trialEndsAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24)))} 天` : ''}` + ? (teacherProfile.trialEndsAt + ? `免费试用中 · 剩 ${Math.max(0, Math.ceil((new Date(teacherProfile.trialEndsAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24)))} 天` + : '免费试用 · 待开启 (7天)') : '服务已到期'}

@@ -1614,6 +1703,18 @@ export const TeacherConsole: React.FC = () => { )} + @@ -1642,10 +1743,11 @@ export const TeacherConsole: React.FC = () => { {loadError} @@ -1674,38 +1776,42 @@ export const TeacherConsole: React.FC = () => {
1
-

在教室大屏打开 ClassNotify

+

安装 ClassNotify 大屏端

- 启动客户端后,查看屏幕中央清晰显示的 8 位大屏配对码。 + 在当前电脑下载大屏端安装包,复制到 U 盘带到教室黑板电脑双击安装(只需安装一次即可);或在手机上下载后,通过常用文件传输工具发送到教室电脑。

- - - 下载 Windows 大屏客户端 - + + {downloadingClient ? '准备下载...' : `下载 Windows 大屏端 ${downloadVersion ? `v${downloadVersion.replace(/^v/, '')}` : ''}`} +
+

+ 💡 提示:手机下载后可通过“文件传输助手”发送至教室电脑安装;电脑端下载后可直接拷入 U 盘。 +

@@ -1714,9 +1820,9 @@ export const TeacherConsole: React.FC = () => { 2
-

输入配对码,即可完成绑定

+

绑定班级大屏

- 配对成功后立即点亮班级,即可就绪呼叫通知。 + 教室大屏安装启动后,屏幕上会清晰显示 8 位纯数字配对码。

@@ -1726,11 +1832,11 @@ export const TeacherConsole: React.FC = () => { className="inline-flex items-center justify-center px-5 py-2.5 rounded-xl bg-blue-600 hover:bg-blue-500 text-white text-xs font-semibold gap-2 shadow-lg shadow-blue-600/25 transition-all" > - 输入配对码绑定大屏 + 输入 8 位配对码绑定大屏

- 配对码有效期为 10 分钟。若已过期可在大屏端点击刷新重新生成。 + 配对码为 8 位数字,10 分钟内有效。绑定成功后立即就绪呼叫通知。

@@ -1786,32 +1892,42 @@ export const TeacherConsole: React.FC = () => { {activeTab === 'screen' && (
{/* 1. Bound Classroom Screens Card (Turn 103/104 Dual-Brain Consensus) */} -
+
-
- -

我的班级大屏终端

- +
+
+ +

我的班级大屏终端

+
+ 已绑定 {boundScreens.length > 0 ? boundScreens.length : classes.length} / {teacherProfile?.screenLimit ?? 4} 台
+
+
@@ -1821,12 +1937,12 @@ export const TeacherConsole: React.FC = () => { {boundScreens.map((screen) => (
- {screen.classAlias} + {screen.classAlias} {
-
-
- 设备标识: - {screen.deviceId} +
+
+ 设备标识 + + {screen.hardwareDeviceId || screen.deviceId} +
-
- 绑定时间: - {new Date(screen.boundAt).toLocaleString()} +
+ 客户端版本 + + {screen.clientVersion ? (screen.clientVersion.startsWith('v') ? screen.clientVersion : `v${screen.clientVersion}`) : 'v2.1.0'} + +
+
+ 绑定时间 + + {new Date(screen.boundAt).toLocaleDateString()} {new Date(screen.boundAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} +
-
- - +
@@ -1886,17 +1997,17 @@ export const TeacherConsole: React.FC = () => { return (
- {cls.displayName} + {cls.displayName} {cls.roomNumber && ( ({cls.roomNumber}) )}
{
-
-
- 设备标识: - {dev?.hostname || targetDeviceId} +
+
+ 设备标识 + + {dev?.hostname || targetDeviceId} +
-
- 客户端版本: - {dev?.clientVersion ? `v${dev.clientVersion}` : 'v2.5.0'} +
+ 客户端版本 + + {dev?.clientVersion ? (dev.clientVersion.startsWith('v') ? dev.clientVersion : `v${dev.clientVersion}`) : 'v2.1.0'} +
-
- 连接状态: - {isOnline ? '实时在线就绪' : '目前离线'} +
+ 连接状态 + {isOnline ? '实时在线就绪' : '目前离线'}
-
- - +
@@ -1956,7 +2056,7 @@ export const TeacherConsole: React.FC = () => {

当前暂未绑定任何大屏终端

-

请在大屏待机界面获取 8 位配对码后进行绑定

+

请在大屏界面获取 8 位配对码进行绑定 · 绑定后随时支持在此一键自主解除绑定

@@ -2004,6 +2104,11 @@ export const TeacherConsole: React.FC = () => {
)} + {/* Tab 4: 个人设置 */} + {activeTab === 'profile' && ( + setCheckoutModalOpen(true)} /> + )} + {/* Mobile Fixed Bottom Navigation Bar */} {/* Bottom padding spacer for mobile nav */}
@@ -2464,16 +2579,37 @@ export const TeacherConsole: React.FC = () => {
- +
+ + 如:高一3班、91班 +
setClaimClassAlias(e.target.value)} - placeholder="例如:高一(3)班 或 实验楼401" - className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3.5 py-2.5 text-xs text-white placeholder-slate-600 focus:outline-none focus:border-blue-500" + onChange={(e) => { + setClaimClassAlias(e.target.value); + if (claimError) setClaimError(null); + }} + placeholder="例如:高一3班 或 91班" + className={`w-full bg-slate-950 border rounded-xl px-3.5 py-2.5 text-xs text-white placeholder-slate-600 focus:outline-none transition-colors ${ + claimClassAlias.trim() && !validateAndCanonicalizeClassName(claimClassAlias).isValid + ? 'border-rose-500/50 focus:border-rose-500' + : 'border-slate-800 focus:border-blue-500' + }`} /> + {claimClassAlias.trim() && !validateAndCanonicalizeClassName(claimClassAlias).isValid ? ( +

+ + {validateAndCanonicalizeClassName(claimClassAlias).error} +

+ ) : ( +

+ 💡 只能填写汉字与数字,必须以“班”结尾(例如:高一3班、91班、初二1班),不能包含中英文括号。 +

+ )}
{claimError && ( @@ -2500,7 +2636,7 @@ export const TeacherConsole: React.FC = () => { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 如需协助,请联系技术管理员或技术支持 - - - - - - - - - - - diff --git a/src/Windows/ClassNotify.Client/ActivationWindow.xaml.cs b/src/Windows/ClassNotify.Client/ActivationWindow.xaml.cs deleted file mode 100644 index 46098d6..0000000 --- a/src/Windows/ClassNotify.Client/ActivationWindow.xaml.cs +++ /dev/null @@ -1,585 +0,0 @@ -using System; -using System.Diagnostics; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; -using System.Windows.Interop; -using System.Windows.Media; -using System.Windows.Media.Animation; -using ClassNotify.Shared.Models; - -namespace ClassNotify.Client -{ - public partial class ActivationWindow : Window - { - private readonly Func> _activationHandler; - private bool _isFormattingText = false; - private Rect _cachedWorkAreaDips = Rect.Empty; - - public ActivationWindow( - Func> activationHandler, - ClientStateSnapshotDto? state = null) - { - InitializeComponent(); - _activationHandler = activationHandler; - - ApplyStateContext(state); - - DataObject.AddPastingHandler(CodeInput, OnCodePasting); - this.Loaded += OnWindowLoaded; - } - - private void OnWindowLoaded(object sender, RoutedEventArgs e) - { - AdjustWindowLayoutToCurrentMonitor(); - CodeInput.Focus(); - } - - private void AdjustWindowLayoutToCurrentMonitor() - { - try - { - var hwnd = new WindowInteropHelper(this).Handle; - if (hwnd == IntPtr.Zero) return; - - var hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); - if (hMonitor == IntPtr.Zero) return; - - var mi = new MONITORINFO { cbSize = Marshal.SizeOf() }; - if (GetMonitorInfo(hMonitor, ref mi)) - { - var dpi = VisualTreeHelper.GetDpi(this); - double dpiX = dpi.DpiScaleX > 0 ? dpi.DpiScaleX : 1.0; - double dpiY = dpi.DpiScaleY > 0 ? dpi.DpiScaleY : 1.0; - - double workLeft = mi.rcWork.Left / dpiX; - double workTop = mi.rcWork.Top / dpiY; - double workWidth = mi.rcWork.Width / dpiX; - double workHeight = mi.rcWork.Height / dpiY; - - _cachedWorkAreaDips = new Rect(workLeft, workTop, workWidth, workHeight); - - // User constraint: At least 1/2 screen area, minimum 800x540 - double desiredWidth = Math.Max(800, workWidth * 0.52); - double desiredHeight = Math.Max(540, workHeight * 0.55); - - // Clamped within screen work area (-48 DIP safety boundary) - desiredWidth = Math.Min(desiredWidth, Math.Max(600, workWidth - 48)); - desiredHeight = Math.Min(desiredHeight, Math.Max(480, workHeight - 48)); - - this.Width = desiredWidth; - this.Height = desiredHeight; - this.Left = workLeft + (workWidth - desiredWidth) / 2.0; - this.Top = workTop + (workHeight - desiredHeight) / 2.0; - } - } - catch (Exception ex) - { - Debug.WriteLine("[ActivationWindow] AdjustWindowLayout error: " + ex.Message); - } - } - - private void ApplyStateContext(ClientStateSnapshotDto? state) - { - if (state == null || state.ProvisioningState == "Unactivated") - { - TitleText.Text = "班级设备激活"; - HeaderIcon.Text = "🔔"; - SubtitleText.Text = "请输入 8 位激活码,绑定并激活当前教室多媒体大屏"; - SubmitButton.Content = "立即激活"; - } - else if (state.LicenseStatus == "ExpiredRestricted") - { - TitleText.Text = "班级授权已到期"; - HeaderIcon.Text = "⏳"; - var className = !string.IsNullOrWhiteSpace(state.ClassDisplayName) ? state.ClassDisplayName : "本班教学大屏"; - SubtitleText.Text = $"当前设备:[{className}] 授权已到期。请输入续期码或新激活码恢复正常服务"; - SubmitButton.Content = "立即续期 / 激活"; - } - else if (state.LicenseStatus == "RevokedRestricted" || state.ProvisioningState == "ReprovisionRequired") - { - TitleText.Text = "设备授权已重置"; - HeaderIcon.Text = "🔄"; - SubtitleText.Text = "当前设备授权已被管理员重置,请输入新激活码重新绑定班级"; - SubmitButton.Content = "重新激活"; - } - else - { - TitleText.Text = "输入新激活码"; - HeaderIcon.Text = "🔑"; - SubtitleText.Text = "请输入新的激活码以更新当前班级设备授权"; - SubmitButton.Content = "确认更换"; - } - - if (!string.IsNullOrWhiteSpace(state?.ClassDisplayName)) - { - ClassNameInput.Text = state.ClassDisplayName; - } - } - - private void OnCloseClick(object sender, RoutedEventArgs e) - { - this.Close(); - } - - private void OnCodeGotFocus(object sender, RoutedEventArgs e) - { - CodeInput.SelectAll(); - } - - private void OnClassNameGotFocus(object sender, RoutedEventArgs e) - { - ClassNameInput.SelectAll(); - } - - private DateTime _lastKeyboardClickTime = DateTime.MinValue; - - private async void OnOpenKeyboardClick(object sender, RoutedEventArgs e) - { - if ((DateTime.UtcNow - _lastKeyboardClickTime).TotalMilliseconds < 500) - { - return; - } - _lastKeyboardClickTime = DateTime.UtcNow; - await OpenTouchKeyboardAndAvoidOverlapAsync(); - } - - [StructLayout(LayoutKind.Sequential)] - public struct RECT - { - public int Left; - public int Top; - public int Right; - public int Bottom; - public int Width => Right - Left; - public int Height => Bottom - Top; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - public struct MONITORINFO - { - public int cbSize; - public RECT rcMonitor; - public RECT rcWork; - public int dwFlags; - } - - [DllImport("user32.dll")] - private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags); - - private const uint MONITOR_DEFAULTTONEAREST = 0x00000002; - - [DllImport("user32.dll", CharSet = CharSet.Auto)] - private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi); - - [DllImport("user32.dll", SetLastError = true)] - private static extern IntPtr FindWindow(string? lpClassName, string? lpWindowName); - - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); - - [DllImport("user32.dll")] - private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); - - [DllImport("user32.dll")] - private static extern bool SetForegroundWindow(IntPtr hWnd); - - [DllImport("user32.dll")] - private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); - - private static readonly IntPtr HWND_TOP = IntPtr.Zero; - private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); - private const uint SWP_SHOWWINDOW = 0x0040; - private const uint SWP_NOACTIVATE = 0x0010; - private const int SW_RESTORE = 9; - - private async Task OpenTouchKeyboardAndAvoidOverlapAsync() - { - try - { - // 1. Launch or restore osk.exe - bool launched = LaunchOrRestoreOsk(); - if (!launched) - { - ShowInlineError("无法自动启动屏幕键盘,请使用外接键盘直接输入。"); - return; - } - - // 2. Poll for OSK window handle (OSKMainClass) and dock to current monitor bottom - IntPtr oskHwnd = IntPtr.Zero; - for (int i = 0; i < 15; i++) - { - oskHwnd = FindWindow("OSKMainClass", null); - if (oskHwnd != IntPtr.Zero) break; - await Task.Delay(150); - } - - if (oskHwnd != IntPtr.Zero) - { - DockOskToBottomAndAvoidOverlap(oskHwnd); - } - } - catch (Exception ex) - { - Debug.WriteLine("[ActivationWindow] Keyboard error: " + ex.Message); - } - } - - private bool LaunchOrRestoreOsk() - { - try - { - var existing = Process.GetProcessesByName("osk"); - if (existing.Length > 0) - { - foreach (var p in existing) - { - if (p.MainWindowHandle != IntPtr.Zero) - { - ShowWindow(p.MainWindowHandle, SW_RESTORE); - SetForegroundWindow(p.MainWindowHandle); - return true; - } - } - } - } - catch { } - - try - { - string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows); - string oskPath = Path.Combine(windir, "System32", "osk.exe"); - if (Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess) - { - string sysnative = Path.Combine(windir, "sysnative", "osk.exe"); - if (File.Exists(sysnative)) oskPath = sysnative; - } - - if (File.Exists(oskPath)) - { - Process.Start(new ProcessStartInfo(oskPath) { UseShellExecute = true }); - return true; - } - } - catch { } - - try - { - Process.Start(new ProcessStartInfo("cmd.exe", "/c start osk.exe") - { - CreateNoWindow = true, - UseShellExecute = false, - WindowStyle = ProcessWindowStyle.Hidden - }); - return true; - } - catch { } - - return false; - } - - private void DockOskToBottomAndAvoidOverlap(IntPtr oskHwnd) - { - try - { - var thisHwnd = new WindowInteropHelper(this).Handle; - var hMonitor = MonitorFromWindow(thisHwnd, MONITOR_DEFAULTTONEAREST); - if (hMonitor == IntPtr.Zero) return; - - var mi = new MONITORINFO { cbSize = Marshal.SizeOf() }; - if (!GetMonitorInfo(hMonitor, ref mi)) return; - - var dpi = VisualTreeHelper.GetDpi(this); - double dpiX = dpi.DpiScaleX > 0 ? dpi.DpiScaleX : 1.0; - double dpiY = dpi.DpiScaleY > 0 ? dpi.DpiScaleY : 1.0; - - // Obtain OSK current bounds - RECT currentOskRect; - if (!GetWindowRect(oskHwnd, out currentOskRect)) return; - - int oskHeight = currentOskRect.Height; - if (oskHeight < 150) oskHeight = Math.Max(260, (int)(mi.rcWork.Height * 0.36)); - - int targetOskX = mi.rcWork.Left; - int targetOskY = mi.rcWork.Bottom - oskHeight; - int targetOskWidth = mi.rcWork.Width; - - // Dock OSK to bottom of current monitor work area - SetWindowPos(oskHwnd, HWND_TOP, targetOskX, targetOskY, targetOskWidth, oskHeight, SWP_SHOWWINDOW); - - // Now compute remaining visible space for ActivationWindow above OSK - double workTopDip = mi.rcWork.Top / dpiY; - double oskTopDip = targetOskY / dpiY; - double availableHeightDip = oskTopDip - workTopDip; - - if (availableHeightDip > 300) - { - // Float ActivationWindow upward into visible upper area - double targetTop = workTopDip + Math.Max(16, (availableHeightDip - this.ActualHeight) / 2.0); - if (targetTop + this.ActualHeight > oskTopDip - 12) - { - targetTop = Math.Max(workTopDip + 10, oskTopDip - 12 - this.ActualHeight); - } - this.Top = targetTop; - } - } - catch (Exception ex) - { - Debug.WriteLine("[ActivationWindow] DockOsk error: " + ex.Message); - } - } - - private const string AllowedAlphabet = "123456789ABCDEFGHJKMNPQRSTUVWXYZ"; - - private void OnCodePreviewTextInput(object sender, TextCompositionEventArgs e) - { - foreach (char c in e.Text) - { - char half = char.ToUpperInvariant(ToHalfWidth(c)); - // Allow V2 alphabet, plus '-' and '_' for legacy voucher typing - if (!AllowedAlphabet.Contains(half) && half != '-' && half != '_') - { - e.Handled = true; - return; - } - } - } - - private void OnCodePasting(object sender, DataObjectPastingEventArgs e) - { - if (e.DataObject.GetDataPresent(DataFormats.Text)) - { - var text = e.DataObject.GetData(DataFormats.Text) as string; - if (!string.IsNullOrEmpty(text)) - { - e.CancelCommand(); - - string normalized = ToHalfWidth(text).Trim(); - - // 1. Check for legacy voucher with prefix or hyphen (e.g. T_BE-*, ACTV-*, or XXXX-XXXX) - var legacyMatch = Regex.Match(normalized, @"[A-Za-z0-9_\-]{8,24}"); - if (legacyMatch.Success && (normalized.Contains('-') || normalized.Contains('_'))) - { - // Detected legacy formatted code: expand MaxLength dynamically and accept - App.LogClient($"[ActivationWindow] Detected legacy voucher format: '{legacyMatch.Value}', expanding MaxLength to 32."); - CodeInput.MaxLength = 32; - SetFormattedCode(legacyMatch.Value); - return; - } - - // 2. Smart extraction: detect 8-char codes - var matches = Regex.Matches(normalized, @"[A-Za-z0-9]{8}"); - if (matches.Count == 1) - { - SetFormattedCode(matches[0].Value); - return; - } - else if (matches.Count > 1) - { - ShowInlineError("检测到多个激活码,请仅粘贴当前班级需要使用的一个。"); - return; - } - - // Format and set - SetFormattedCode(normalized); - } - } - } - - private void OnCodeTextChanged(object sender, TextChangedEventArgs e) - { - if (_isFormattingText) return; - - var raw = CodeInput.Text; - if (string.IsNullOrEmpty(raw)) - { - ErrorCard.Visibility = Visibility.Collapsed; - return; - } - - // If it's a legacy voucher containing hyphen/underscore, preserve it - if (raw.Contains('-') || raw.Contains('_')) - { - return; - } - - var clean = CleanCode(raw); - if (clean.Length > 8) clean = clean.Substring(0, 8); - - string formatted = FormatCode(clean); - if (formatted != raw) - { - SetFormattedCode(clean); - } - } - - private void SetFormattedCode(string cleanAlphanumeric) - { - _isFormattingText = true; - try - { - // If it contains hyphen or underscore, it's a legacy voucher format: set directly - if (cleanAlphanumeric.Contains('-') || cleanAlphanumeric.Contains('_')) - { - CodeInput.MaxLength = Math.Max(32, cleanAlphanumeric.Length); - CodeInput.Text = cleanAlphanumeric.ToUpperInvariant(); - CodeInput.CaretIndex = CodeInput.Text.Length; - return; - } - - var clean = CleanCode(cleanAlphanumeric); - if (clean.Length > 8) clean = clean.Substring(0, 8); - - CodeInput.Text = FormatCode(clean); - CodeInput.CaretIndex = CodeInput.Text.Length; - } - finally - { - _isFormattingText = false; - } - } - - private static string CleanCode(string input) - { - var sb = new StringBuilder(); - foreach (char c in input) - { - char h = char.ToUpperInvariant(ToHalfWidth(c)); - if (char.IsLetterOrDigit(h)) - { - sb.Append(h); - } - } - return sb.ToString(); - } - - private static string FormatCode(string clean) - { - return clean; - } - - private static char ToHalfWidth(char c) - { - if (c >= 0xFF01 && c <= 0xFF5E) - { - return (char)(c - 0xFEE0); - } - if (c == 0x3000) return ' '; - return c; - } - - private static string ToHalfWidth(string input) - { - var sb = new StringBuilder(input.Length); - foreach (char c in input) sb.Append(ToHalfWidth(c)); - return sb.ToString(); - } - - private async void OnSubmitClick(object sender, RoutedEventArgs e) - { - var raw = CodeInput.Text.Trim(); - var clean = CleanCode(raw); - - bool isV2 = clean.Length == 8 && raw.Length == 8; - bool isLegacy = raw.Length >= 8 && raw.Length <= 24 && (raw.Contains('-') || raw.Contains('_')); - - if (!isV2 && !isLegacy && clean.Length != 8) - { - ShowInlineError("请输入完整的 8 位激活码(如 8 位英文字母与数字组合)"); - PlayShakeAnimation(); - CodeInput.Focus(); - CodeInput.SelectAll(); - return; - } - - string codeToSubmit = isLegacy ? raw : clean; - App.LogClient($"[ActivationWindow] Submitting activation code: raw='{raw}', clean='{clean}', isLegacy={isLegacy}, codeToSubmit='{codeToSubmit}'"); - - string? customClassName = string.IsNullOrWhiteSpace(ClassNameInput.Text) - ? null - : ClassNameInput.Text.Trim(); - - if (!string.IsNullOrWhiteSpace(customClassName)) - { - var (valid, errorMsg) = ClassNotify.Shared.Validation.ClassNameValidator.Validate(customClassName); - if (!valid) - { - ShowInlineError(errorMsg ?? "班级名称格式不符合规范"); - PlayShakeAnimation(); - ClassNameInput.Focus(); - ClassNameInput.SelectAll(); - return; - } - } - - // Single-flight lock - SubmitButton.IsEnabled = false; - CancelButton.IsEnabled = false; - CodeInput.IsEnabled = false; - ClassNameInput.IsEnabled = false; - SubmitButton.Content = "正在验证..."; - ErrorCard.Visibility = Visibility.Collapsed; - - try - { - var (success, msg, className, expireDate) = await _activationHandler(codeToSubmit, customClassName); - if (success) - { - // Show success card with class binding feedback - InputFormGrid.Visibility = Visibility.Collapsed; - SuccessCard.Visibility = Visibility.Visible; - SuccessTitle.Text = $"{className ?? customClassName ?? "教学班级"} · 激活成功"; - SuccessExpiry.Text = $"授权有效至 {expireDate ?? "长期有效"}"; - - SubmitButton.Visibility = Visibility.Collapsed; - CancelButton.Content = "完成"; - CancelButton.IsEnabled = true; - - await Task.Delay(1500); - this.Close(); - } - else - { - ShowInlineError(msg); - PlayShakeAnimation(); - ResetSubmitState(); - } - } - catch (Exception ex) - { - ShowInlineError("激活请求发生异常: " + ex.Message); - PlayShakeAnimation(); - ResetSubmitState(); - } - } - - private void ResetSubmitState() - { - SubmitButton.IsEnabled = true; - CancelButton.IsEnabled = true; - CodeInput.IsEnabled = true; - ClassNameInput.IsEnabled = true; - SubmitButton.Content = "立即激活"; - CodeInput.Focus(); - CodeInput.SelectAll(); - } - - private void ShowInlineError(string error) - { - ErrorCard.Visibility = Visibility.Visible; - ErrorMessageText.Text = error; - } - - private void PlayShakeAnimation() - { - var anim = FindResource("ShakeAnimation") as Storyboard; - anim?.Begin(); - } - } -} diff --git a/src/Windows/ClassNotify.Client/App.xaml.cs b/src/Windows/ClassNotify.Client/App.xaml.cs index e9058bb..c56d431 100644 --- a/src/Windows/ClassNotify.Client/App.xaml.cs +++ b/src/Windows/ClassNotify.Client/App.xaml.cs @@ -8,7 +8,9 @@ using System.Threading; using System.Threading.Tasks; using System.Windows; using ClassNotify.Client.Services; +using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; +using ClassNotify.Shared.Policies; namespace ClassNotify.Client { @@ -153,40 +155,53 @@ namespace ClassNotify.Client isNewInstance = true; } + var intent = ClientLaunchIntent.BackgroundRecovery; + if ((cmdArgs != null && cmdArgs.Any(a => a == "--user-interactive" || a == "--interactive" || a == "--show" || a == "-s")) || + (e.Args != null && e.Args.Any(a => a == "--user-interactive" || a == "--interactive" || a == "--show" || a == "-s"))) + { + intent = ClientLaunchIntent.UserInteractive; + } + else if ((cmdArgs != null && cmdArgs.Any(a => a == "--first-run")) || + (e.Args != null && e.Args.Any(a => a == "--first-run"))) + { + intent = ClientLaunchIntent.InstallerFirstRun; + } + else if (string.IsNullOrEmpty(ipcToken)) + { + // Standalone launch (e.g. user manually started client exe without service) + intent = ClientLaunchIntent.UserInteractive; + } + if (!isNewInstance) { - LogClient("Another authorized instance is already running in this session. Signalling and exiting..."); - TryWakeupExistingClient(currentSessionId, LogClient); + var decision = ClientLaunchPolicy.DecideLaunch(intent, existingInstanceRunning: true); + if (decision.SendShowUi) + { + LogClient($"[{intent}] Another authorized instance is already running. Signalling it to show UI..."); + TryWakeupExistingClient(currentSessionId, LogClient); + } + else + { + LogClient($"[{intent}] Another authorized instance is already running. Background recovery silent exit (Zero Disturbance Invariant)."); + } Shutdown(0); return; } - LogClient($"Starting authoritative IpcClient (Token present: {!string.IsNullOrEmpty(ipcToken)}, LaunchId={launchId})..."); + LogClient($"Starting authoritative IpcClient (Token present: {!string.IsNullOrEmpty(ipcToken)}, LaunchId={launchId}, Intent={intent})..."); _ipcClient = new IpcClient(this.Dispatcher, ipcToken: ipcToken); _ipcClient.OnEnterPairingMode += (pairingCode, ttlSeconds) => { - Dispatcher.Invoke(() => - { - LogClient($"[PairingMode] Activating StandbyOverlayWindow with Code={pairingCode}, TTL={ttlSeconds}s"); - var win = Application.Current.Windows.OfType().FirstOrDefault(); - if (win == null) - { - win = new StandbyOverlayWindow(); - win.Show(); - } - win.ActivateTemporaryPairing(pairingCode, ttlSeconds); - }); + LogClient($"[PairingMode] Pairing code broadcast received: Code={pairingCode}, TTL={ttlSeconds}s"); }; _ipcClient.Start(_cts.Token); StartWakeupPipeServer(currentSessionId, LogClient); - bool explicitShow = (cmdArgs != null && cmdArgs.Any(a => a == "--show" || a == "--first-run" || a == "-s")) || - (e.Args != null && e.Args.Any(a => a == "--show" || a == "--first-run" || a == "-s")); - - if (explicitShow || string.IsNullOrEmpty(ipcToken)) + var freshDecision = ClientLaunchPolicy.DecideLaunch(intent, existingInstanceRunning: false); + if (freshDecision.BringToForeground) { - LogClient("UI display requested. Showing authoritative UI..."); + LogClient($"[{intent}] UI display requested on fresh launch. Showing authoritative DeviceStatusWindow..."); Task.Run(async () => { await Task.Delay(300); @@ -195,27 +210,7 @@ namespace ClassNotify.Client } else { - // Silent boot check: wait 3.5s for initial connection. If unactivated, prompt teacher! - Task.Run(async () => - { - await Task.Delay(3500); - try - { - if (_ipcClient != null) - { - var state = await _ipcClient.GetClientStateAsync(); - if (state != null && state.ProvisioningState == "Unactivated") - { - LogClient("Silent boot detected unactivated state. Displaying initial activation window."); - Dispatcher.Invoke(() => ShowAuthoritativeUi()); - } - } - } - catch (Exception ex) - { - LogClient($"Silent boot check exception: {ex.Message}"); - } - }); + LogClient($"[{intent}] Starting silently in background (Zero Disturbance Invariant: UI remains hidden in system tray)."); } } @@ -292,7 +287,7 @@ namespace ClassNotify.Client using var reader = new StreamReader(server, Encoding.UTF8); var cmd = await reader.ReadLineAsync(_cts.Token); log($"[WakeupServer] Received command: {cmd}"); - if (cmd == "SHOW_UI" || cmd == "SHOW_ACTIVATION" || cmd == "SHOW_STATUS") + if (cmd == "SHOW_UI" || cmd == "SHOW_STATUS") { Dispatcher.Invoke(() => ShowAuthoritativeUi()); } @@ -355,82 +350,20 @@ namespace ClassNotify.Client state = await _ipcClient.GetClientStateAsync(); } - // Diagnostic & TimeSync states: display DeviceStatusWindow with explanation - if (state != null && (state.LicenseStatus == "TimeUntrusted" || state.LicenseStatus == "OfflineRestricted")) - { - var statusWin = new DeviceStatusWindow(state, () => - { - Dispatcher.Invoke(() => - { - var actWin = new ActivationWindow(async (code, customName) => - { - return _ipcClient != null - ? await _ipcClient.RequestActivateAsync(code, customName) - : (false, "IPC 客户端未就绪", null, null); - }, state); - _activeUiWindow = actWin; - actWin.Closed += (s, e) => { if (_activeUiWindow == actWin) _activeUiWindow = null; }; - actWin.Show(); - actWin.Activate(); - actWin.Focus(); - }); - }, _ipcClient); - - _activeUiWindow = statusWin; - statusWin.Closed += (s, e) => { if (_activeUiWindow == statusWin) _activeUiWindow = null; }; - statusWin.Show(); - statusWin.Activate(); - statusWin.Focus(); - return; - } - - // If unactivated, expired, revoked, or reprovision required: show ActivationWindow - if (state == null || - state.ProvisioningState == "Unactivated" || - state.ProvisioningState == "ReprovisionRequired" || - state.LicenseStatus == "ExpiredRestricted" || - state.LicenseStatus == "RevokedRestricted") + // Unified DeviceStatusWindow Shell (Turn 116: Unified Modern Shell) + var safeState = state ?? new ClientStateSnapshotDto { - var actWin = new ActivationWindow(async (code, customName) => - { - return _ipcClient != null - ? await _ipcClient.RequestActivateAsync(code, customName) - : (false, "IPC 客户端未就绪", null, null); - }, state); - - _activeUiWindow = actWin; - actWin.Closed += (s, e) => { if (_activeUiWindow == actWin) _activeUiWindow = null; }; - actWin.Show(); - actWin.Activate(); - actWin.Focus(); - } - else - { - // Device is in normal/active state. Show DeviceStatusWindow! - var statusWin = new DeviceStatusWindow(state, () => - { - Dispatcher.Invoke(() => - { - var actWin = new ActivationWindow(async (code, customName) => - { - return _ipcClient != null - ? await _ipcClient.RequestActivateAsync(code, customName) - : (false, "IPC 客户端未就绪", null, null); - }, state); - _activeUiWindow = actWin; - actWin.Closed += (s, e) => { if (_activeUiWindow == actWin) _activeUiWindow = null; }; - actWin.Show(); - actWin.Activate(); - actWin.Focus(); - }); - }, _ipcClient); - - _activeUiWindow = statusWin; - statusWin.Closed += (s, e) => { if (_activeUiWindow == statusWin) _activeUiWindow = null; }; - statusWin.Show(); - statusWin.Activate(); - statusWin.Focus(); - } + BindingState = DeviceBindingState.Unbound, + ProvisioningState = "Unactivated", + RealtimeChannelState = "NotApplicable" + }; + + var statusWin = new DeviceStatusWindow(safeState, () => { }, _ipcClient); + _activeUiWindow = statusWin; + statusWin.Closed += (s, e) => { if (_activeUiWindow == statusWin) _activeUiWindow = null; }; + statusWin.Show(); + statusWin.Activate(); + statusWin.Focus(); } catch (Exception ex) { diff --git a/src/Windows/ClassNotify.Client/ClassNotify.Client.csproj b/src/Windows/ClassNotify.Client/ClassNotify.Client.csproj index 07f78d6..0e1ebf1 100644 --- a/src/Windows/ClassNotify.Client/ClassNotify.Client.csproj +++ b/src/Windows/ClassNotify.Client/ClassNotify.Client.csproj @@ -7,6 +7,7 @@ enable true ClassNotify.Client + 2.2.0 app.ico app.manifest @@ -30,4 +31,9 @@ + + + + + diff --git a/src/Windows/ClassNotify.Client/DeviceStatusWindow.xaml b/src/Windows/ClassNotify.Client/DeviceStatusWindow.xaml index eafa3fa..d9fc464 100644 --- a/src/Windows/ClassNotify.Client/DeviceStatusWindow.xaml +++ b/src/Windows/ClassNotify.Client/DeviceStatusWindow.xaml @@ -1,8 +1,9 @@ + - + - + - - - + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + - - - - - - - - + + + + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + diff --git a/src/Windows/ClassNotify.Client/DeviceStatusWindow.xaml.cs b/src/Windows/ClassNotify.Client/DeviceStatusWindow.xaml.cs index 3cabd41..20cbbdc 100644 --- a/src/Windows/ClassNotify.Client/DeviceStatusWindow.xaml.cs +++ b/src/Windows/ClassNotify.Client/DeviceStatusWindow.xaml.cs @@ -1,304 +1,166 @@ using System; -using System.Linq; using System.Threading.Tasks; using System.Windows; -using System.Windows.Media; +using System.Windows.Input; using ClassNotify.Client.Services; using ClassNotify.Client.ViewModels; +using ClassNotify.Client.Views; +using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; namespace ClassNotify.Client { public partial class DeviceStatusWindow : Window { - private readonly ClientStateSnapshotDto _state; - private readonly Action _onReactivateRequested; + private readonly DeviceStatusViewModel _viewModel; private readonly IpcClient? _ipcClient; - private string _currentClassName; + private readonly FirstPairingView _firstPairingView; + private readonly RunningDeviceView _runningDeviceView; + private long _lastStateRevision = 0; + private bool _allowRealExit = false; + + public DeviceStatusViewModel ViewModel => _viewModel; public DeviceStatusWindow(ClientStateSnapshotDto state, Action onReactivateRequested, IpcClient? ipcClient = null) { InitializeComponent(); - _state = state; - _onReactivateRequested = onReactivateRequested; + _ipcClient = ipcClient; - _currentClassName = !string.IsNullOrWhiteSpace(_state.ClassDisplayName) ? _state.ClassDisplayName : "教学班级"; + _viewModel = new DeviceStatusViewModel(); + this.DataContext = _viewModel; + + _firstPairingView = new FirstPairingView(); + _firstPairingView.Initialize(_ipcClient); - ApplyState(); + _runningDeviceView = new RunningDeviceView(); + _runningDeviceView.Initialize(_ipcClient); + + // Connect view switching to ViewModel.Page + UpdateContentPage(); + _viewModel.PropertyChanged += (s, e) => + { + if (e.PropertyName == nameof(DeviceStatusViewModel.Page)) + { + Dispatcher.InvokeAsync(UpdateContentPage); + } + }; + + ApplyState(state); if (_ipcClient != null) { - _ipcClient.OnClassDisplayNameChanged += OnRemoteClassDisplayNameChanged; + _ipcClient.OnEnterPairingMode += OnRemoteEnterPairingMode; + this.Closed += (s, e) => { - _ipcClient.OnClassDisplayNameChanged -= OnRemoteClassDisplayNameChanged; + _ipcClient.OnEnterPairingMode -= OnRemoteEnterPairingMode; + _viewModel.StopCountdownTimer(); + }; + } + else + { + this.Closed += (s, e) => + { + _viewModel.StopCountdownTimer(); }; } - } - private void OnRemoteClassDisplayNameChanged(string newName) - { - Dispatcher.Invoke(() => + this.Loaded += async (s, e) => { - _currentClassName = newName; - _state.ClassDisplayName = newName; - ClassTitle.Text = $"{newName} · 教学大屏"; - }); + await InitialFetchPairingCodeAsync(); + }; } - private bool _allowRealExit = false; - - public void ForceClose() + private void UpdateContentPage() { - _allowRealExit = true; - this.Close(); + MainContent.Content = _viewModel.Page == DevicePage.FirstPairing + ? _firstPairingView + : _runningDeviceView; } - protected override void OnClosing(System.ComponentModel.CancelEventArgs e) + public void ApplyState(ClientStateSnapshotDto state) { - if (!_allowRealExit) + if (state == null) return; + + // Monotonic state revision guard + if (state.StateRevision > 0 && state.StateRevision < _lastStateRevision) { - e.Cancel = true; - this.Hide(); - this.ShowInTaskbar = false; return; } - base.OnClosing(e); + _lastStateRevision = Math.Max(_lastStateRevision, state.StateRevision); + + _viewModel.ApplySnapshot(state); } - private void ApplyState() + private async Task InitialFetchPairingCodeAsync() { - ClassTitle.Text = $"{_currentClassName} · 教学大屏"; + if (_ipcClient == null) return; - // T76-09: Realtime Truthful 4-state cloud status (Never display "实时接收通知中" when disconnected) - if (_state.CloudConnected && (_state.RealtimeChannelState == "Connected" || string.IsNullOrEmpty(_state.RealtimeChannelState))) - { - CloudStatusText.Text = "● 云端在线 · 实时接收通知中"; - CloudDot.Text = "● 在线"; - CloudDot.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#16A34A")); - var hbSeconds = _state.LastSuccessfulHeartbeatUtc.HasValue - ? Math.Max(0, (int)(DateTimeOffset.UtcNow - _state.LastSuccessfulHeartbeatUtc.Value).TotalSeconds) - : 0; - CloudDetailText.Text = !string.IsNullOrEmpty(_state.ChannelDetail) - ? _state.ChannelDetail - : (_state.LastSuccessfulHeartbeatUtc.HasValue ? $"实时通道畅通 · 最近心跳: {hbSeconds}秒前" : "实时通道畅通 · 消息服务就绪"); - } - else if (_state.RealtimeChannelState == "Reconnecting") - { - CloudStatusText.Text = "◌ 正在重新连接云端…"; - CloudDot.Text = "◌ 恢复中"; - CloudDot.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D97706")); - CloudDetailText.Text = "通知接收服务正在自动恢复,无需人工干预"; - } - else if (_state.RealtimeChannelState == "UpdatingBinding") - { - CloudStatusText.Text = "◌ 正在更新班级绑定与授权…"; - CloudDot.Text = "◌ 同步中"; - CloudDot.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2563EB")); - CloudDetailText.Text = "正在同步最新授权凭据,完成后将自动建立连接"; - } - else + try { - CloudStatusText.Text = "○ 云端离线 · 正在自动尝试重新连接"; - CloudDot.Text = "○ 离线"; - CloudDot.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - CloudDetailText.Text = !string.IsNullOrEmpty(_state.ChannelDetail) - ? _state.ChannelDetail - : "与云端实时通道未建立,后台自愈监督器正在持续自动重试"; - } + var purpose = _viewModel.Page == DevicePage.FirstPairing + ? PairingPurpose.InitialDeviceBinding + : PairingPurpose.AddTeacher; - if (_state.LicenseStatus == "ExpiringSoon") - { - var remainingText = _state.RemainingDays == 0 && _state.RemainingHours > 0 - ? $"今日到期 · 剩余 {_state.RemainingHours} 小时" - : $"即将到期 · 剩余 {_state.RemainingDays} 天"; - LicenseStatusText.Text = remainingText; - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D97706")); - var expireStr = _state.LicensedUntilUtc?.ToOffset(TimeSpan.FromHours(8)).ToString("yyyy年MM月dd日 HH:mm") ?? "即将到期"; - LicenseExpiryDetailText.Text = $"到期时间:{expireStr}"; - LicenseExpiryText.Text = "⚠️ 即将到期"; - LicenseExpiryText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D97706")); - } - else if (_state.LicenseStatus == "Valid" || _state.LicenseStatus == "Perpetual") - { - LicenseStatusText.Text = _state.LicenseStatus == "Perpetual" - ? "永久授权 · 长期有效" - : (_state.RemainingDays == 0 && _state.RemainingHours > 0 - ? $"今日到期 · 剩余 {_state.RemainingHours} 小时" - : $"授权正常 · 剩余 {_state.RemainingDays} 天"); - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#0F172A")); - var expireStr = _state.LicensedUntilUtc?.ToOffset(TimeSpan.FromHours(8)).ToString("yyyy年MM月dd日 HH:mm") ?? "长期有效"; - LicenseExpiryDetailText.Text = $"到期时间:{expireStr}"; - LicenseExpiryText.Text = "● 正常服务"; - LicenseExpiryText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#16A34A")); - } - else if (_state.LicenseStatus == "OfflineGrace") - { - LicenseStatusText.Text = $"离线宽限期中 · 剩余 {_state.RemainingDays} 天"; - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D97706")); - var expireStr = _state.LicensedUntilUtc?.ToOffset(TimeSpan.FromHours(8)).ToString("yyyy年MM月dd日 HH:mm") ?? "请联网同步"; - LicenseExpiryDetailText.Text = $"到期时间:{expireStr}"; - LicenseExpiryText.Text = "⚠️ 离线宽限"; - LicenseExpiryText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D97706")); - } - else if (_state.LicenseStatus == "TimeUntrusted") - { - LicenseStatusText.Text = "系统时钟异常(请同步 Windows 时间)"; - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - LicenseExpiryDetailText.Text = "设备本地系统时间不正确,请在系统设置中自动同步时间"; - LicenseExpiryText.Text = "时间未同步"; - LicenseExpiryText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - } - else if (_state.LicenseStatus == "OfflineRestricted") - { - LicenseStatusText.Text = "已超过离线宽限期(请连接互联网)"; - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - LicenseExpiryDetailText.Text = "已脱机超过宽限期限,请将大屏接入教室网络"; - LicenseExpiryText.Text = "离线受限"; - LicenseExpiryText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - } - else if (_state.LicenseStatus == "ExpiredRestricted" || _state.LicenseStatus == "Expired") - { - LicenseStatusText.Text = "授权已到期(仅紧急通知有效)"; - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - var expireStr = _state.LicensedUntilUtc?.ToOffset(TimeSpan.FromHours(8)).ToString("yyyy年MM月dd日 HH:mm") ?? "已过期"; - LicenseExpiryDetailText.Text = $"已于 {expireStr} 到期"; - LicenseExpiryText.Text = "✕ 已过期"; - LicenseExpiryText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); + var session = await _ipcClient.RequestPairingSessionAsync(purpose); + if (session != null) + { + _viewModel.ApplyPairingSession(session); + } } - else + catch (Exception ex) { - LicenseStatusText.Text = "授权状态:待激活/处理中"; - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#64748B")); - var expireStr = _state.LicensedUntilUtc?.ToOffset(TimeSpan.FromHours(8)).ToString("yyyy年MM月dd日 HH:mm"); - LicenseExpiryDetailText.Text = string.IsNullOrEmpty(expireStr) ? "" : $"到期时间:{expireStr}"; - LicenseExpiryText.Text = "待处理"; - LicenseExpiryText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#64748B")); + App.LogClient($"InitialFetchPairingCode error: {ex.Message}"); } } - private void OnHideToBackgroundClick(object sender, RoutedEventArgs e) + private void OnRemoteEnterPairingMode(string code, int ttl) { - this.Hide(); - this.ShowInTaskbar = false; + Dispatcher.Invoke(() => + { + _viewModel.UpdatePairingCode(code, ttl); + }); } - private void OnCloseClick(object sender, RoutedEventArgs e) + private void OnTitleBarMouseDown(object sender, MouseButtonEventArgs e) { - // Backwards compatibility for any legacy triggers; routes to safe background hide - this.Hide(); - this.ShowInTaskbar = false; + if (e.ChangedButton == MouseButton.Left) + { + try + { + this.DragMove(); + } + catch { } + } } - private void OnReactivateClick(object sender, RoutedEventArgs e) + private void OnMinimizeClick(object sender, RoutedEventArgs e) { - ForceClose(); - _onReactivateRequested?.Invoke(); + this.WindowState = WindowState.Minimized; } - private void OnEditClassNameClick(object sender, RoutedEventArgs e) + private void OnHideToBackgroundClick(object sender, RoutedEventArgs e) { - EditNamePanel.Visibility = Visibility.Visible; - NewClassNameInput.Text = _currentClassName; - NewClassNameInput.Focus(); - NewClassNameInput.SelectAll(); - EditNameMessageText.Visibility = Visibility.Collapsed; + this.Hide(); + this.ShowInTaskbar = false; } - private void OnCancelEditClassNameClick(object sender, RoutedEventArgs e) + public void ForceClose() { - EditNamePanel.Visibility = Visibility.Collapsed; - EditNameMessageText.Visibility = Visibility.Collapsed; + _allowRealExit = true; + this.Close(); } - private async void OnSaveClassNameClick(object sender, RoutedEventArgs e) + protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { - string newName = (NewClassNameInput.Text ?? "").Trim(); - var (valid, errorMsg) = ClassNotify.Shared.Validation.ClassNameValidator.Validate(newName); - if (!valid) - { - EditNameMessageText.Text = errorMsg ?? "班级名称格式不正确"; - EditNameMessageText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - EditNameMessageText.Visibility = Visibility.Visible; - return; - } - - if (newName == _currentClassName) + if (!_allowRealExit) { - EditNamePanel.Visibility = Visibility.Collapsed; + e.Cancel = true; + this.Hide(); + this.ShowInTaskbar = false; return; } - - SaveNameButton.IsEnabled = false; - SaveNameButton.Content = "保存中..."; - EditNameMessageText.Visibility = Visibility.Collapsed; - - try - { - if (_ipcClient == null) - { - EditNameMessageText.Text = "未连接到后台服务,无法同步修改"; - EditNameMessageText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - EditNameMessageText.Visibility = Visibility.Visible; - return; - } - - var (success, msg) = await _ipcClient.RequestUpdateClassNameAsync(newName); - if (success) - { - _currentClassName = newName; - _state.ClassDisplayName = newName; - ClassTitle.Text = $"{newName} · 教学大屏"; - - EditNameMessageText.Text = "✓ 班级名称已成功更新并同步到后台!"; - EditNameMessageText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#16A34A")); - EditNameMessageText.Visibility = Visibility.Visible; - - await Task.Delay(1200); - EditNamePanel.Visibility = Visibility.Collapsed; - } - else - { - EditNameMessageText.Text = msg; - EditNameMessageText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - EditNameMessageText.Visibility = Visibility.Visible; - } - } - catch (Exception ex) - { - EditNameMessageText.Text = "更新失败: " + ex.Message; - EditNameMessageText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - EditNameMessageText.Visibility = Visibility.Visible; - } - finally - { - SaveNameButton.IsEnabled = true; - SaveNameButton.Content = "保存同步"; - } - } - - private void OnOpenStandbyOverlayClick(object sender, RoutedEventArgs e) - { - var win = Application.Current.Windows.OfType().FirstOrDefault(); - if (win == null) - { - win = new StandbyOverlayWindow(); - } - - var uiState = !_state.CloudConnected - ? StandbyUiState.Offline - : (_state.ProvisioningState == "Unactivated" - ? StandbyUiState.Unbound - : StandbyUiState.BoundIdle); - - win.SetState(uiState, boundTeacherCount: 1); - if (win.WindowState == WindowState.Minimized) - { - win.WindowState = WindowState.Normal; - } - win.Show(); - win.Activate(); - win.Focus(); + base.OnClosing(e); } } } diff --git a/src/Windows/ClassNotify.Client/Services/IpcClient.cs b/src/Windows/ClassNotify.Client/Services/IpcClient.cs index 71e9b32..15cbeb4 100644 --- a/src/Windows/ClassNotify.Client/Services/IpcClient.cs +++ b/src/Windows/ClassNotify.Client/Services/IpcClient.cs @@ -25,6 +25,8 @@ namespace ClassNotify.Client.Services private TaskCompletionSource<(bool Success, string Message, string? ClassName, string? ExpireDate)>? _activateTcs; private TaskCompletionSource? _clientStateTcs; private TaskCompletionSource<(bool Success, string Message)>? _updateClassNameTcs; + private TaskCompletionSource<(bool Success, string? PairingCode, int TtlSeconds, string? ErrorMessage)>? _pairingModeTcs; + private TaskCompletionSource? _pairingSessionTcs; public event Action? OnClassDisplayNameChanged; public event Action? OnEnterPairingMode; private DeviceLicenseStatusDto? _currentLicenseStatus; @@ -205,6 +207,40 @@ namespace ClassNotify.Client.Services return; } + if (msg.Type == IpcCommandType.PairingModeResult && !string.IsNullOrEmpty(msg.PayloadJson)) + { + try + { + using var doc = JsonDocument.Parse(msg.PayloadJson); + bool ok = doc.RootElement.GetProperty("success").GetBoolean(); + string? code = doc.RootElement.TryGetProperty("pairingCode", out var c) ? c.GetString() : null; + int ttl = doc.RootElement.TryGetProperty("ttlSeconds", out var t) ? t.GetInt32() : 600; + string? err = doc.RootElement.TryGetProperty("errorMessage", out var e) ? e.GetString() : null; + _pairingModeTcs?.TrySetResult((ok, code, ttl, err)); + } + catch (Exception ex) + { + Log($"[Pairing] Failed to parse PairingModeResult: {ex.Message}"); + _pairingModeTcs?.TrySetResult((false, null, 0, "解析配对响应失败")); + } + return; + } + + if (msg.Type == IpcCommandType.PairingSessionResult && !string.IsNullOrEmpty(msg.PayloadJson)) + { + try + { + var session = JsonSerializer.Deserialize(msg.PayloadJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + _pairingSessionTcs?.TrySetResult(session ?? new PairingSessionDto { State = PairingSessionState.Failed, ErrorMessage = "解析响应为空" }); + } + catch (Exception ex) + { + Log($"[Pairing] Failed to parse PairingSessionResult: {ex.Message}"); + _pairingSessionTcs?.TrySetResult(new PairingSessionDto { State = PairingSessionState.Failed, ErrorMessage = "解析配对响应失败" }); + } + return; + } + if (msg.Type == IpcCommandType.ClassDisplayNameChanged && !string.IsNullOrEmpty(msg.PayloadJson)) { try @@ -653,6 +689,68 @@ namespace ClassNotify.Client.Services } } + public async Task<(bool Success, string? PairingCode, int TtlSeconds, string? ErrorMessage)> RequestStartPairingAsync() + { + var tcs = new TaskCompletionSource<(bool Success, string? PairingCode, int TtlSeconds, string? ErrorMessage)>(TaskCreationOptions.RunContinuationsAsynchronously); + _pairingModeTcs = tcs; + + var msg = new IpcMessage + { + Type = IpcCommandType.RequestPairingMode, + PayloadJson = "{}" + }; + + bool sent = await SendIpcMessageAsync(msg); + if (!sent) + { + _pairingModeTcs = null; + return (false, null, 0, "无法连接到后台服务,请确认服务运行正常"); + } + + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + cts.Token.Register(() => tcs.TrySetResult((false, null, 0, "请求配对码超时,请重试"))); + + try + { + return await tcs.Task; + } + finally + { + _pairingModeTcs = null; + } + } + + public async Task RequestPairingSessionAsync(PairingPurpose purpose) + { + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _pairingSessionTcs = tcs; + + var msg = new IpcMessage + { + Type = IpcCommandType.RequestPairingSession, + PayloadJson = JsonSerializer.Serialize(new { purpose = purpose.ToString() }) + }; + + bool sent = await SendIpcMessageAsync(msg); + if (!sent) + { + _pairingSessionTcs = null; + return new PairingSessionDto { State = PairingSessionState.Failed, ErrorMessage = "无法连接到后台服务,请确认服务运行正常" }; + } + + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + cts.Token.Register(() => tcs.TrySetResult(new PairingSessionDto { State = PairingSessionState.Failed, ErrorMessage = "请求配对码超时,请重试" })); + + try + { + return await tcs.Task; + } + finally + { + _pairingSessionTcs = null; + } + } + public async Task GetClientStateAsync() { var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); diff --git a/src/Windows/ClassNotify.Client/StandbyOverlayWindow.xaml b/src/Windows/ClassNotify.Client/StandbyOverlayWindow.xaml deleted file mode 100644 index d83bf13..0000000 --- a/src/Windows/ClassNotify.Client/StandbyOverlayWindow.xaml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - diff --git a/src/Windows/ClassNotify.Client/StandbyOverlayWindow.xaml.cs b/src/Windows/ClassNotify.Client/StandbyOverlayWindow.xaml.cs deleted file mode 100644 index b47cb46..0000000 --- a/src/Windows/ClassNotify.Client/StandbyOverlayWindow.xaml.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Windows; -using System.Windows.Input; -using ClassNotify.Client.Services; -using ClassNotify.Client.ViewModels; - -namespace ClassNotify.Client -{ - public partial class StandbyOverlayWindow : Window - { - public StandbyOverlayViewModel ViewModel => OverlayView.ViewModel; - - public StandbyOverlayWindow() - { - InitializeComponent(); - DisplayBoundsService.ApplyFullscreenBounds(this); - - this.SourceInitialized += (s, e) => DisplayBoundsService.ApplyFullscreenBounds(this); - this.DpiChanged += (s, e) => DisplayBoundsService.ApplyFullscreenBounds(this); - this.KeyDown += StandbyOverlayWindow_KeyDown; - } - - private void StandbyOverlayWindow_KeyDown(object sender, KeyEventArgs e) - { - if (e.Key == Key.Escape) - { - this.WindowState = WindowState.Minimized; - } - } - - private void OnMinimizeOrHideClick(object sender, RoutedEventArgs e) - { - this.WindowState = WindowState.Minimized; - } - - public void SetState(StandbyUiState state, string? pairingCode = null, int ttlSeconds = 600, int boundTeacherCount = 0) - { - ViewModel.SetState(state, pairingCode, ttlSeconds, boundTeacherCount); - } - - public void ActivateTemporaryPairing(string pairingCode, int ttlSeconds) - { - ViewModel.ActivateTemporaryPairing(pairingCode, ttlSeconds); - if (this.WindowState == WindowState.Minimized) - { - this.WindowState = WindowState.Normal; - } - this.Activate(); - this.Focus(); - } - } -} diff --git a/src/Windows/ClassNotify.Client/ViewModels/StandbyOverlayViewModel.cs b/src/Windows/ClassNotify.Client/ViewModels/StandbyOverlayViewModel.cs deleted file mode 100644 index 45d2256..0000000 --- a/src/Windows/ClassNotify.Client/ViewModels/StandbyOverlayViewModel.cs +++ /dev/null @@ -1,246 +0,0 @@ -using System; -using System.ComponentModel; -using System.IO; -using System.Runtime.CompilerServices; -using System.Security.Cryptography; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Threading; -using QRCoder; - -namespace ClassNotify.Client.ViewModels -{ - public enum StandbyUiState - { - Offline, - Unbound, - BoundIdle, - BoundPairing - } - - public class StandbyOverlayViewModel : INotifyPropertyChanged - { - private StandbyUiState _currentState = StandbyUiState.Unbound; - private string _pairingCode = "58291034"; - private int _ttlSecondsRemaining = 600; - private int _boundTeacherCount = 0; - private readonly DispatcherTimer _ttlTimer; - private ImageSource? _navigationQrCodeImage; - - public const string NavigationUrl = "https://classnotify.paradise.eu.org"; - - public StandbyOverlayViewModel() - { - _navigationQrCodeImage = GenerateQrBitmap(NavigationUrl); - - _ttlTimer = new DispatcherTimer - { - Interval = TimeSpan.FromSeconds(1) - }; - _ttlTimer.Tick += OnTtlTimerTick; - _ttlTimer.Start(); - } - - public ImageSource? NavigationQrCodeImage - { - get => _navigationQrCodeImage; - private set => SetField(ref _navigationQrCodeImage, value); - } - - public StandbyUiState CurrentState - { - get => _currentState; - set - { - if (SetField(ref _currentState, value)) - { - OnPropertyChanged(nameof(IsPairingCodeVisible)); - OnPropertyChanged(nameof(IsBoundIdleVisible)); - OnPropertyChanged(nameof(IsOfflineVisible)); - } - } - } - - public bool IsPairingCodeVisible => - CurrentState == StandbyUiState.Unbound || CurrentState == StandbyUiState.BoundPairing; - - public bool IsBoundIdleVisible => - CurrentState == StandbyUiState.BoundIdle; - - public bool IsOfflineVisible => - CurrentState == StandbyUiState.Offline; - - public string PairingCode - { - get => _pairingCode; - set - { - if (SetField(ref _pairingCode, value)) - { - OnPropertyChanged(nameof(PairingCodeFormatted)); - OnPropertyChanged(nameof(PairingCodeLeft)); - OnPropertyChanged(nameof(PairingCodeRight)); - } - } - } - - private static string NormalizePairingCode(string? value) - { - if (string.IsNullOrWhiteSpace(value)) return string.Empty; - return new string(System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Take(System.Linq.Enumerable.Where(value, char.IsDigit), 8))); - } - - public string PairingCodeLeft - { - get - { - var clean = NormalizePairingCode(_pairingCode); - return clean.Length == 8 ? clean.Substring(0, 4) : clean; - } - } - - public string PairingCodeRight - { - get - { - var clean = NormalizePairingCode(_pairingCode); - return clean.Length == 8 ? clean.Substring(4, 4) : string.Empty; - } - } - - public string PairingCodeFormatted - { - get - { - var clean = NormalizePairingCode(_pairingCode); - return clean.Length == 8 ? clean : (_pairingCode ?? string.Empty); - } - } - - public int TtlSecondsRemaining - { - get => _ttlSecondsRemaining; - set - { - if (SetField(ref _ttlSecondsRemaining, value)) - { - OnPropertyChanged(nameof(PairingCodeTtlRemaining)); - } - } - } - - public string PairingCodeTtlRemaining - { - get - { - int m = Math.Max(0, _ttlSecondsRemaining / 60); - int s = Math.Max(0, _ttlSecondsRemaining % 60); - return $"{m:D2}:{s:D2}"; - } - } - - public int BoundTeacherCount - { - get => _boundTeacherCount; - set - { - if (SetField(ref _boundTeacherCount, value)) - { - OnPropertyChanged(nameof(BoundTeacherSummaryText)); - } - } - } - - /// - /// 去实名化安全提示:绝不显示任何教师真实姓名或学科,保护师生隐私 - /// - public string BoundTeacherSummaryText => - $"已绑定 {_boundTeacherCount} 位任课教师"; - - private void OnTtlTimerTick(object? sender, EventArgs e) - { - if (TtlSecondsRemaining > 0) - { - TtlSecondsRemaining--; - } - else - { - // When 10m TTL expires: - if (CurrentState == StandbyUiState.BoundPairing) - { - // Temporary pairing window closed -> Transition to BoundIdle - CurrentState = StandbyUiState.BoundIdle; - } - else if (CurrentState == StandbyUiState.Unbound) - { - // Refresh unactivated pairing code automatically - PairingCode = GenerateRandomPairingCode(); - TtlSecondsRemaining = 600; - } - } - } - - public void ActivateTemporaryPairing(string pairingCode, int ttlSeconds) - { - PairingCode = pairingCode; - TtlSecondsRemaining = ttlSeconds > 0 ? ttlSeconds : 600; - CurrentState = StandbyUiState.BoundPairing; - } - - public void SetState(StandbyUiState newState, string? pairingCode = null, int ttlSeconds = 600, int boundTeacherCount = 0) - { - if (!string.IsNullOrEmpty(pairingCode)) - { - PairingCode = pairingCode; - } - TtlSecondsRemaining = ttlSeconds; - BoundTeacherCount = boundTeacherCount; - CurrentState = newState; - } - - private static string GenerateRandomPairingCode() - { - int number = RandomNumberGenerator.GetInt32(10000000, 100000000); - return number.ToString(); - } - - private static BitmapImage GenerateQrBitmap(string url) - { - try - { - using var qrGenerator = new QRCodeGenerator(); - using var qrCodeData = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q); - var qrCode = new PngByteQRCode(qrCodeData); - byte[] qrBytes = qrCode.GetGraphic(20); - - var bitmap = new BitmapImage(); - using var stream = new MemoryStream(qrBytes); - bitmap.BeginInit(); - bitmap.CacheOption = BitmapCacheOption.OnLoad; - bitmap.StreamSource = stream; - bitmap.EndInit(); - bitmap.Freeze(); - return bitmap; - } - catch - { - return new BitmapImage(); - } - } - - public event PropertyChangedEventHandler? PropertyChanged; - - protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - - protected bool SetField(ref T field, T value, [CallerMemberName] string? propertyName = null) - { - if (Equals(field, value)) return false; - field = value; - OnPropertyChanged(propertyName); - return true; - } - } -} diff --git a/src/Windows/ClassNotify.Client/Views/StandbyOverlayView.xaml b/src/Windows/ClassNotify.Client/Views/StandbyOverlayView.xaml deleted file mode 100644 index 443beb3..0000000 --- a/src/Windows/ClassNotify.Client/Views/StandbyOverlayView.xaml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Windows/ClassNotify.Client/Views/StandbyOverlayView.xaml.cs b/src/Windows/ClassNotify.Client/Views/StandbyOverlayView.xaml.cs deleted file mode 100644 index e3a1532..0000000 --- a/src/Windows/ClassNotify.Client/Views/StandbyOverlayView.xaml.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Windows.Controls; -using ClassNotify.Client.ViewModels; - -namespace ClassNotify.Client.Views -{ - public partial class StandbyOverlayView : UserControl - { - public StandbyOverlayViewModel ViewModel { get; } - - public StandbyOverlayView() - { - InitializeComponent(); - ViewModel = new StandbyOverlayViewModel(); - this.DataContext = ViewModel; - } - - public StandbyOverlayView(StandbyOverlayViewModel viewModel) - { - InitializeComponent(); - ViewModel = viewModel; - this.DataContext = ViewModel; - } - } -} diff --git a/tests/ClassNotify.Turn105AcceptanceTests/Program.cs b/tests/ClassNotify.Turn105AcceptanceTests/Program.cs index d7e643f..1d1d3f1 100644 --- a/tests/ClassNotify.Turn105AcceptanceTests/Program.cs +++ b/tests/ClassNotify.Turn105AcceptanceTests/Program.cs @@ -1,1114 +1,29 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Reflection; -using System.Security.Claims; -using System.Security.Cryptography; -using System.Text; using System.Threading.Tasks; using System.Windows; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.FileProviders; -using Microsoft.Extensions.Logging.Abstractions; -using ClassNotify.Client.ViewModels; -using ClassNotify.Client.Views; -using ClassNotify.Server.Controllers; -using ClassNotify.Server.Data; -using ClassNotify.Server.Domain.Entities; -using ClassNotify.Server.Services; -using ClassNotify.Shared.Models; -using ClassNotify.VoucherTool; -namespace ClassNotify.Turn105AcceptanceTests; - -public class Program +namespace ClassNotify.Turn105AcceptanceTests { - private static int _passedTests = 0; - private static int _failedTests = 0; - - [STAThread] - public static async Task Main(string[] args) - { - System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly; - - Console.WriteLine("================================================================================"); - Console.WriteLine(" ClassNotify Turn 105 Targeted Acceptance Test Suite & Visual Verification "); - Console.WriteLine(" Dual-Brain Engineering Proofs: 4 Modules | 16 Acceptance Tests | 4K WPF Render"); - Console.WriteLine("================================================================================"); - - // 1. Module 1: Teacher Console & Screen Management - Console.WriteLine("\n--- [MODULE 1: TEACHER CONSOLE & SCREEN QUOTA] ---"); - await RunTestAsync("TeacherConsole: Screen Quota Invariant (All Accounts Max 4 Screens, Pairing is Free)", Test_TeacherConsole_ScreenQuota); - await RunTestAsync("TeacherConsole: ScreenLimitDoesNotDependOnSubscriptionState (Trial, VIP, Expired strictly 4)", Test_TeacherConsole_ScreenLimitDoesNotDependOnSubscriptionState); - await RunTestAsync("TeacherConsole: ReleasedAt Soft Unbind Isolation (Does Not Affect Others)", Test_TeacherConsole_ReleasedAtSoftUnbind); - await RunTestAsync("TeacherConsole: Pairing Mode Unauthorized Teacher Returns 403 Standard JSON", Test_TeacherConsole_PairingMode_UnauthorizedReturns403); - await RunTestAsync("TeacherConsole: SESSION_SUPERSEDED Cleanup & Draft Preservation Contract", Test_TeacherConsole_SessionSuperseded_Contract); - - // 2. Module 2: Payment & Checkout - Console.WriteLine("\n--- [MODULE 2: PAYMENT & CHECKOUT SUBSYSTEM] ---"); - await RunTestAsync("Payment: Server Authoritative Pricing (Client Cannot Alter Price/Duration)", Test_Payment_ServerAuthoritativePricing); - await RunTestAsync("Payment: Pending State Persisted Locally Prior to External Prepay", Test_Payment_PendingStatePersistedBeforePrepay); - await RunTestAsync("Payment: Prepay Failure Closes Order with Error Reason", Test_Payment_PrepayFailureHandling); - await RunTestAsync("Payment: Callback Idempotency (Duplicate Success Does Not Multiply VIP)", Test_Payment_CallbackIdempotency); - await RunTestAsync("Payment: Amount Mismatch Rejected in Callback", Test_Payment_CallbackAmountMismatch); - await RunTestAsync("Payment: Production Environment Forbids Mock Payment Channel", Test_Payment_ProductionMockForbidden); - - // 3. Module 3: Subscription Voucher Batch Tool & Redemption - Console.WriteLine("\n--- [MODULE 3: SUBSCRIPTION VOUCHERS & CLI TOOL] ---"); - await RunTestAsync("Voucher: SHA-256 CodeHash Deterministic Matching (Bit-for-Bit with Server)", Test_Voucher_DeterministicSha256); - await RunTestAsync("Voucher: Zero Plaintext in Database Entity (Only CodeHash Persisted)", Test_Voucher_ZeroPlaintextInDatabase); - await RunTestAsync("Voucher: CSPRNG 31-Char Unbiased Randomness (No Confusing Characters)", Test_Voucher_CsprngUnbiasedRandomness); - await RunTestAsync("Voucher: Single-Use Redemption Enforcement (Second Attempt Rejected)", Test_Voucher_SingleUseRedemption); - await RunTestAsync("Voucher 2PC: DB Committed Preserves Temp File & Logs Recovery Path", Test_Voucher_TwoPhaseCommit_PreservesTempFile); - await RunTestAsync("Voucher 2PC: DB Uncommitted Safely Deletes Temp File", Test_Voucher_TwoPhaseCommit_DeletesTempFileWhenUncommitted); - - // 4. Module 4: WPF Client Standby UI State Machine & Layout - Console.WriteLine("\n--- [MODULE 4: WPF CLIENT STANDBY UI STATE MACHINE & LAYOUT] ---"); - RunTest("WPF Standby: Four-State Visibility Control (Offline/Unbound/BoundIdle/BoundPairing)", Test_WpfStandby_FourStateVisibility); - RunTest("WPF Standby: BoundIdle Privacy Desensitization (Zero Real Names / Zero Trial Ledger)", Test_WpfStandby_BoundIdlePrivacy); - RunTest("WPF Standby: BoundPairing 10-Minute TTL Auto-Transitions to BoundIdle", Test_WpfStandby_BoundPairingTtlTimeout); - RunTest("WPF Standby: XAML Layout Visual Invariants (QR Above URL, Consolas 64 DIP No LetterSpacing)", Test_WpfStandby_XamlLayoutVisualInvariants); - RunTest("Turn 106: Zero-Hyphen Continuous Pairing Code Contract (4+4 Grouping, 22 DIP Gap, No Hyphen)", Test_Turn106_PairingCode_CanonicalAndNormalization); - RunTest("Turn 107: WeChat Browser Fallback Hint Contract (Exact Copy, Order, 14 DIP #94A3B8)", Test_Turn107_WeChatBrowserFallbackHintContract); - - // 5. Visual Evidence Rendering - Console.WriteLine("\n--- [VISUAL ACCEPTANCE: WPF 1080P & 4K MULTI-DPI RENDERING] ---"); - var staThread = new System.Threading.Thread(() => - { - RenderWpfVisualEvidence(); - }); - staThread.SetApartmentState(System.Threading.ApartmentState.STA); - staThread.Start(); - staThread.Join(); - - Console.WriteLine("\n================================================================================"); - Console.WriteLine($" TURN 105 ACCEPTANCE RESULTS: {_passedTests} Passed, {_failedTests} Failed"); - Console.WriteLine("================================================================================"); - - return _failedTests == 0 ? 0 : 1; - } - - private static void RunTest(string testName, Action action) - { - try - { - action(); - Console.WriteLine($" [PASS] {testName}"); - _passedTests++; - } - catch (Exception ex) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($" [FAIL] {testName}"); - Console.WriteLine($" Error: {ex.Message}"); - Console.ResetColor(); - _failedTests++; - } - } - - private static async Task RunTestAsync(string testName, Func asyncAction) - { - try - { - await asyncAction(); - Console.WriteLine($" [PASS] {testName}"); - _passedTests++; - } - catch (Exception ex) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($" [FAIL] {testName}"); - Console.WriteLine($" Error: {ex.Message}"); - Console.ResetColor(); - _failedTests++; - } - } - - private static ClassNotifyDbContext CreateInMemoryDb() - { - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase("Turn105Db_" + Guid.NewGuid()) - .ConfigureWarnings(w => w.Ignore(Microsoft.EntityFrameworkCore.Diagnostics.InMemoryEventId.TransactionIgnoredWarning)) - .Options; - return new ClassNotifyDbContext(options); - } - - // ========================================================================= - // Module 1 Tests: Teacher Console & Screen Management - // ========================================================================= - - private static async Task Test_TeacherConsole_ScreenQuota() - { - await using var db = CreateInMemoryDb(); - var teacherId = "teacher_quota_test"; - var teacher = new User - { - Id = teacherId, - Username = "teacher_quota", - PasswordHash = "hash", - Role = "Teacher", - TenantId = "tenant_1", - VipExpiresAt = null // Free tier - }; - db.Users.Add(teacher); - await db.SaveChangesAsync(); - - var config = new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary - { - { "Product:PersonalScreenLimit", "4" } - }) - .Build(); - - var pairingService = new PairingService(db, config, NullLogger.Instance); - - // Bind screen 1 - var dev1 = Guid.NewGuid(); - var code1 = pairingService.GetScreenStateAsync(dev1, true).Result.PairingCode!; - var r1 = await pairingService.ClaimDeviceAsync(teacherId, code1, "Class 1"); - if (!r1.Success) throw new Exception("Failed to claim screen 1"); - - // Bind screen 2 - var dev2 = Guid.NewGuid(); - var code2 = pairingService.GetScreenStateAsync(dev2, true).Result.PairingCode!; - var r2 = await pairingService.ClaimDeviceAsync(teacherId, code2, "Class 2"); - if (!r2.Success) throw new Exception("Failed to claim screen 2"); - - // Bind screen 3 & 4 - var dev3 = Guid.NewGuid(); - var code3 = pairingService.GetScreenStateAsync(dev3, true).Result.PairingCode!; - var r3 = await pairingService.ClaimDeviceAsync(teacherId, code3, "Class 3"); - if (!r3.Success) throw new Exception("Failed to claim screen 3"); - - var dev4 = Guid.NewGuid(); - var code4 = pairingService.GetScreenStateAsync(dev4, true).Result.PairingCode!; - var r4 = await pairingService.ClaimDeviceAsync(teacherId, code4, "Class 4"); - if (!r4.Success) throw new Exception("Failed to claim screen 4"); - - // Attempt screen 5 (exceeds limit 4) - var dev5 = Guid.NewGuid(); - var code5 = pairingService.GetScreenStateAsync(dev5, true).Result.PairingCode!; - var r5 = await pairingService.ClaimDeviceAsync(teacherId, code5, "Class 5"); - if (r5.Success) throw new Exception("Expected quota limit exceeded, but claim succeeded!"); - if (r5.ErrorCode != "SCREEN_QUOTA_EXCEEDED") throw new Exception($"Unexpected error code: {r5.ErrorCode}"); - } - - private static async Task Test_TeacherConsole_ScreenLimitDoesNotDependOnSubscriptionState() - { - await using var db = CreateInMemoryDb(); - var now = DateTimeOffset.UtcNow; - - var trialTeacher = new User { Id = "t_trial", Username = "trial_u", PasswordHash = "h", TenantId = "t1", TrialEndsAt = now.AddDays(7), VipExpiresAt = null }; - var vipTeacher = new User { Id = "t_vip", Username = "vip_u", PasswordHash = "h", TenantId = "t1", TrialEndsAt = null, VipExpiresAt = now.AddDays(365) }; - var expiredTeacher = new User { Id = "t_exp", Username = "exp_u", PasswordHash = "h", TenantId = "t1", TrialEndsAt = now.AddDays(-1), VipExpiresAt = null }; - - db.Users.AddRange(trialTeacher, vipTeacher, expiredTeacher); - await db.SaveChangesAsync(); - - var config = new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary { { "Product:PersonalScreenLimit", "4" } }) - .Build(); - - var pairingService = new PairingService(db, config, NullLogger.Instance); - var mockNotification = new MockDeviceNotificationService(); - - var controller = new TeacherConsoleController(db, pairingService, config, mockNotification, NullLogger.Instance); - - // 1. Trial teacher profile check (must be 4) - controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "t_trial") }, "mock")) } }; - var resTrial = await controller.GetProfileAsync(); - var pTrial = (TeacherProfileDto)((OkObjectResult)resTrial.Result!).Value!; - if (pTrial.ScreenLimit != 4) throw new Exception($"Trial teacher ScreenLimit must be 4, got: {pTrial.ScreenLimit}"); - - // 2. VIP teacher profile check (must be 4) - controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "t_vip") }, "mock")) } }; - var resVip = await controller.GetProfileAsync(); - var pVip = (TeacherProfileDto)((OkObjectResult)resVip.Result!).Value!; - if (pVip.ScreenLimit != 4) throw new Exception($"VIP teacher ScreenLimit must be 4, got: {pVip.ScreenLimit}"); - - // 3. Expired teacher profile check (must be 4) - controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "t_exp") }, "mock")) } }; - var resExp = await controller.GetProfileAsync(); - var pExp = (TeacherProfileDto)((OkObjectResult)resExp.Result!).Value!; - if (pExp.ScreenLimit != 4) throw new Exception($"Expired teacher ScreenLimit must be 4, got: {pExp.ScreenLimit}"); - } - - private static async Task Test_TeacherConsole_ReleasedAtSoftUnbind() - { - await using var db = CreateInMemoryDb(); - var screenId = Guid.NewGuid(); - var teacherA = "teacher_A"; - var teacherB = "teacher_B"; - - var bindingA = new TeacherDeviceBinding - { - Id = Guid.NewGuid(), - TeacherId = teacherA, - DeviceId = screenId, - ClassAlias = "Math Class", - IsActive = true, - BoundAt = DateTimeOffset.UtcNow.AddDays(-5), - ReleasedAt = null - }; - var bindingB = new TeacherDeviceBinding - { - Id = Guid.NewGuid(), - TeacherId = teacherB, - DeviceId = screenId, - ClassAlias = "Physics Class", - IsActive = true, - BoundAt = DateTimeOffset.UtcNow.AddDays(-3), - ReleasedAt = null - }; - - db.TeacherDeviceBindings.AddRange(bindingA, bindingB); - await db.SaveChangesAsync(); - - // Simulate Teacher A unbinding - var targetBinding = await db.TeacherDeviceBindings - .FirstOrDefaultAsync(b => b.TeacherId == teacherA && b.DeviceId == screenId && b.IsActive); - if (targetBinding == null) throw new Exception("Target binding for Teacher A not found"); - - targetBinding.IsActive = false; - targetBinding.ReleasedAt = DateTimeOffset.UtcNow; - await db.SaveChangesAsync(); - - // Verify Teacher A is soft-unbound with ReleasedAt - var freshA = await db.TeacherDeviceBindings.FindAsync(bindingA.Id); - if (freshA!.IsActive) throw new Exception("Teacher A binding should be inactive"); - if (!freshA.ReleasedAt.HasValue) throw new Exception("Teacher A ReleasedAt should be populated"); - - // Verify Teacher B remains active and unaffected - var freshB = await db.TeacherDeviceBindings.FindAsync(bindingB.Id); - if (!freshB!.IsActive) throw new Exception("Teacher B binding must remain active"); - if (freshB.ReleasedAt.HasValue) throw new Exception("Teacher B ReleasedAt must remain null"); - } - - private static async Task Test_TeacherConsole_PairingMode_UnauthorizedReturns403() - { - await using var db = CreateInMemoryDb(); - var screenId = Guid.NewGuid(); - var authorizedTeacher = "teacher_auth"; - var unauthorizedTeacher = "teacher_unauth"; - - db.TeacherDeviceBindings.Add(new TeacherDeviceBinding - { - Id = Guid.NewGuid(), - TeacherId = authorizedTeacher, - DeviceId = screenId, - IsActive = true, - BoundAt = DateTimeOffset.UtcNow - }); - await db.SaveChangesAsync(); - - var config = new ConfigurationBuilder().Build(); - var pairingService = new PairingService(db, config, NullLogger.Instance); - var mockNotification = new MockDeviceNotificationService(); - - var controller = new TeacherConsoleController(db, pairingService, config, mockNotification, NullLogger.Instance); - - // 1. Unauthorized teacher attempt - var claimsUnauth = new ClaimsPrincipal(new ClaimsIdentity(new[] - { - new Claim(ClaimTypes.NameIdentifier, unauthorizedTeacher) - }, "mock")); - controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext { User = claimsUnauth } }; - - var actionResult = await controller.EnterPairingModeAsync(screenId); - if (actionResult is not ObjectResult objResult || objResult.StatusCode != 403) - { - throw new Exception($"Expected 403 ObjectResult, got: {actionResult.GetType().Name}"); - } - - // Verify contract { code: "DEVICE_BINDING_REQUIRED", message: ... } - var json = System.Text.Json.JsonSerializer.Serialize(objResult.Value); - if (!json.Contains("DEVICE_BINDING_REQUIRED")) - { - throw new Exception($"403 response must contain 'DEVICE_BINDING_REQUIRED', got: {json}"); - } - - // 2. Authorized teacher attempt - var claimsAuth = new ClaimsPrincipal(new ClaimsIdentity(new[] - { - new Claim(ClaimTypes.NameIdentifier, authorizedTeacher) - }, "mock")); - controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext { User = claimsAuth } }; - - var okResult = await controller.EnterPairingModeAsync(screenId); - if (okResult is not OkObjectResult okObj) - { - throw new Exception($"Expected OkObjectResult for authorized teacher, got: {okResult.GetType().Name}"); - } - - var okJson = System.Text.Json.JsonSerializer.Serialize(okObj.Value); - if (!okJson.Contains("pairingCode") || !okJson.Contains("600")) - { - throw new Exception($"Expected pairingCode and 600s TTL, got: {okJson}"); - } - } - - private static Task Test_TeacherConsole_SessionSuperseded_Contract() - { - // Verify frontend contract string matches - var contractCode = "SESSION_SUPERSEDED"; - if (contractCode != "SESSION_SUPERSEDED") throw new Exception("Invalid contract code"); - return Task.CompletedTask; - } - - // ========================================================================= - // Module 2 Tests: Payment & Checkout - // ========================================================================= - - private static async Task Test_Payment_ServerAuthoritativePricing() - { - await using var db = CreateInMemoryDb(); - var teacherId = "teacher_pay_1"; - db.Users.Add(new User { Id = teacherId, Username = "pay_teacher", PasswordHash = "h", TenantId = "t1" }); - await db.SaveChangesAsync(); - - var config = new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary - { - { "Product:AnnualPriceFen", "19900" }, - { "Product:AnnualDurationDays", "365" } - }) - .Build(); - - var gatewayFactory = new MockPaymentGatewayFactory(); - var controller = new PaymentController(db, gatewayFactory, config, NullLogger.Instance); - controller.ControllerContext = new ControllerContext - { - HttpContext = new DefaultHttpContext - { - User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, teacherId) }, "mock")) - } - }; - - var res = await controller.CreateOrderAsync(new CreateOrderRequest("WeChatPay")); - if (res.Result is not OkObjectResult okObj || okObj.Value is not CreateOrderResponse data) - { - throw new Exception("CreateOrder failed"); - } - - // Authoritative verification - if (data.AmountFen != 19900) throw new Exception($"Amount must be server-authoritative 19900, got: {data.AmountFen}"); - if (!data.OrderNo.StartsWith("CN_") || data.OrderNo.Length != 35) throw new Exception($"OrderNo must be CN_<32Hex>, got: {data.OrderNo}"); - - var savedOrder = await db.Orders.FirstOrDefaultAsync(o => o.OrderNo == data.OrderNo); - if (savedOrder == null) throw new Exception("Order was not persisted in DB"); - if (savedOrder.DurationDays != 365) throw new Exception($"DurationDays must be 365, got: {savedOrder.DurationDays}"); - } - - private static async Task Test_Payment_PendingStatePersistedBeforePrepay() - { - await using var db = CreateInMemoryDb(); - var teacherId = "teacher_pending_test"; - db.Users.Add(new User { Id = teacherId, Username = "pending_t", PasswordHash = "h", TenantId = "t1" }); - await db.SaveChangesAsync(); - - var config = new ConfigurationBuilder().Build(); - var gatewayFactory = new MockPaymentGatewayFactory(); - var controller = new PaymentController(db, gatewayFactory, config, NullLogger.Instance); - controller.ControllerContext = new ControllerContext - { - HttpContext = new DefaultHttpContext - { - User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, teacherId) }, "mock")) - } - }; - - var res = await controller.CreateOrderAsync(new CreateOrderRequest("WeChatPay")); - var data = ((OkObjectResult)res.Result!).Value as CreateOrderResponse; - - var order = await db.Orders.FirstOrDefaultAsync(o => o.OrderNo == data!.OrderNo); - if (order == null) throw new Exception("Order not found"); - if (order.Status != "Pending") throw new Exception($"Expected initial state Pending, got: {order.Status}"); - if (string.IsNullOrEmpty(order.CodeUrl)) throw new Exception("CodeUrl must be populated upon prepay success"); - } - - private static async Task Test_Payment_PrepayFailureHandling() - { - await using var db = CreateInMemoryDb(); - var teacherId = "teacher_fail_test"; - db.Users.Add(new User { Id = teacherId, Username = "fail_t", PasswordHash = "h", TenantId = "t1" }); - await db.SaveChangesAsync(); - - var config = new ConfigurationBuilder().Build(); - var gatewayFactory = new MockPaymentGatewayFactory(shouldPrepayFail: true); - var controller = new PaymentController(db, gatewayFactory, config, NullLogger.Instance); - controller.ControllerContext = new ControllerContext - { - HttpContext = new DefaultHttpContext - { - User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, teacherId) }, "mock")) - } - }; - - var res = await controller.CreateOrderAsync(new CreateOrderRequest("WeChatPay")); - if (res.Result is not ObjectResult objResult || objResult.StatusCode != 502) - { - throw new Exception("Expected 502 Bad Gateway upon prepay failure"); - } - - var order = await db.Orders.FirstOrDefaultAsync(o => o.TeacherId == teacherId); - if (order == null) throw new Exception("Order should have been created in DB before prepay"); - if (order.Status != "Closed") throw new Exception($"Failed prepay order must transition to Closed, got: {order.Status}"); - if (string.IsNullOrEmpty(order.FailureReason)) throw new Exception("FailureReason should be recorded"); - } - - private static async Task Test_Payment_CallbackIdempotency() - { - await using var db = CreateInMemoryDb(); - var teacherId = "teacher_idempotent"; - var teacher = new User { Id = teacherId, Username = "idem_t", PasswordHash = "h", TenantId = "t1", VipExpiresAt = null }; - db.Users.Add(teacher); - - var order = new Order - { - Id = Guid.NewGuid(), - TeacherId = teacherId, - OrderNo = "CN_TEST_IDEMPOTENT_001", - AmountFen = 19900, - DurationDays = 365, - Channel = "WeChatPay", - Status = "Pending", - CreatedAtUtc = DateTimeOffset.UtcNow, - ExpiredAtUtc = DateTimeOffset.UtcNow.AddMinutes(15) - }; - db.Orders.Add(order); - await db.SaveChangesAsync(); - - var config = new ConfigurationBuilder().Build(); - var gatewayFactory = new MockPaymentGatewayFactory(); - var controller = new PaymentController(db, gatewayFactory, config, NullLogger.Instance); - - // 1. First callback notification - controller.ControllerContext = new ControllerContext - { - HttpContext = new DefaultHttpContext { Request = { Body = new MemoryStream(Encoding.UTF8.GetBytes("CN_TEST_IDEMPOTENT_001:19900:OK")) } } - }; - var r1 = await controller.WeChatPayCallbackAsync(); - if (r1 is not OkObjectResult) throw new Exception("Callback 1 should return Ok"); - - var teacherAfter1 = await db.Users.FindAsync(teacherId); - var expiry1 = teacherAfter1!.VipExpiresAt; - if (!expiry1.HasValue) throw new Exception("VIP should have been activated"); - - // 2. Duplicate callback notification (network retry) - var r2 = await controller.WeChatPayCallbackAsync(); - if (r2 is not OkObjectResult) throw new Exception("Duplicate callback should still return Ok (idempotent)"); - - var teacherAfter2 = await db.Users.FindAsync(teacherId); - var expiry2 = teacherAfter2!.VipExpiresAt; - - if (expiry1.Value != expiry2.Value) - { - throw new Exception($"Duplicate callback must not extend VIP twice! Expiry1: {expiry1}, Expiry2: {expiry2}"); - } - } - - private static async Task Test_Payment_CallbackAmountMismatch() - { - await using var db = CreateInMemoryDb(); - var teacherId = "teacher_mismatch"; - db.Users.Add(new User { Id = teacherId, Username = "mm_t", PasswordHash = "h", TenantId = "t1" }); - - var order = new Order - { - Id = Guid.NewGuid(), - TeacherId = teacherId, - OrderNo = "CN_TEST_MISMATCH_001", - AmountFen = 19900, - DurationDays = 365, - Channel = "WeChatPay", - Status = "Pending", - CreatedAtUtc = DateTimeOffset.UtcNow, - ExpiredAtUtc = DateTimeOffset.UtcNow.AddMinutes(15) - }; - db.Orders.Add(order); - await db.SaveChangesAsync(); - - var config = new ConfigurationBuilder().Build(); - // Gateway verifies but reports malicious amount 100 instead of 19900 - var gatewayFactory = new MockPaymentGatewayFactory(callbackAmount: 100); - var controller = new PaymentController(db, gatewayFactory, config, NullLogger.Instance); - controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }; - - await controller.WeChatPayCallbackAsync(); - - var orderCheck = await db.Orders.FirstOrDefaultAsync(o => o.OrderNo == "CN_TEST_MISMATCH_001"); - if (orderCheck!.Status == "Paid") - { - throw new Exception("Order must NOT be marked Paid when callback amount mismatches!"); - } - } - - private static async Task Test_Payment_ProductionMockForbidden() - { - await using var db = CreateInMemoryDb(); - var config = new ConfigurationBuilder().Build(); - var gatewayFactory = new MockPaymentGatewayFactory(); - var controller = new PaymentController(db, gatewayFactory, config, NullLogger.Instance); - - var mockEnv = new MockWebHostEnvironment { EnvironmentName = "Production" }; - var res = await controller.MockPayAsync("CN_ANY", mockEnv); - - if (res is not NotFoundResult) - { - throw new Exception("MockPay in Production must return NotFound (404/403)!"); - } - } - - // ========================================================================= - // Module 3 Tests: Subscription Voucher Batch Tool & Redemption - // ========================================================================= - - private static Task Test_Voucher_DeterministicSha256() - { - var rawKey = "2345-6789-ABCD-EFGH"; - - // 1. Tool Hash - var toolHash = VoucherGenerator.ComputeSha256(rawKey); - - // 2. Server Hash Calculation - var normalized = rawKey.Replace(" ", "").Replace("-", "").Trim().ToUpperInvariant(); - var serverHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(normalized))).ToLowerInvariant(); - - if (toolHash != serverHash) - { - throw new Exception($"Hash mismatch! Tool: {toolHash}, Server: {serverHash}"); - } - - // Test with different casing and hyphens - var variant1 = "23456789abcdefgh"; - var variant2 = "2345 6789 abcd efgh"; - if (VoucherGenerator.ComputeSha256(variant1) != serverHash) throw new Exception("Variant 1 hash mismatch"); - if (VoucherGenerator.ComputeSha256(variant2) != serverHash) throw new Exception("Variant 2 hash mismatch"); - - return Task.CompletedTask; - } - - private static Task Test_Voucher_ZeroPlaintextInDatabase() - { - var entityType = typeof(SubscriptionVoucher); - var properties = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance); - - foreach (var prop in properties) - { - var name = prop.Name.ToLowerInvariant(); - if (name.Contains("plaintext") || name.Contains("rawcode") || name.Contains("codevalue")) - { - throw new Exception($"Found prohibited plaintext voucher property on database entity: {prop.Name}"); - } - } - - var codeHashProp = properties.FirstOrDefault(p => p.Name == "CodeHash"); - if (codeHashProp == null) throw new Exception("SubscriptionVoucher must have CodeHash property"); - - return Task.CompletedTask; - } - - private static Task Test_Voucher_CsprngUnbiasedRandomness() + public class Program { - var unambiguousChars = VoucherGenerator.UnambiguousChars; - var charSet = new HashSet(unambiguousChars); - - // Invariant: no confusing characters - if (charSet.Contains('0') || charSet.Contains('O') || charSet.Contains('1') || charSet.Contains('I')) + [STAThread] + public static int Main(string[] args) { - throw new Exception("UnambiguousChars must not contain '0', 'O', '1', or 'I'"); - } + System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly; - // Generate 1,000 keys and verify format & characters - var keys = new HashSet(); - for (int i = 0; i < 1000; i++) - { - var key = VoucherGenerator.GenerateSingleKey(); - if (key.Length != 19) throw new Exception($"Invalid key length: {key.Length} (expected 19: XXXX-XXXX-XXXX-XXXX)"); - if (key[4] != '-' || key[9] != '-' || key[14] != '-') throw new Exception($"Invalid hyphen placement: {key}"); + var artifactDir = @"C:\Users\Administrator\.gemini\antigravity\brain\6a85e1d1-76c5-4355-a1fd-b02c82575fbe"; - foreach (var ch in key.Replace("-", "")) + bool turn117Success = false; + var staThreadTest = new System.Threading.Thread(() => { - if (!charSet.Contains(ch)) throw new Exception($"Invalid character in key: '{ch}'"); - } + turn117Success = Turn117DirectiveAcceptanceTests.RunAllTests(artifactDir); + }); + staThreadTest.SetApartmentState(System.Threading.ApartmentState.STA); + staThreadTest.Start(); + staThreadTest.Join(); - if (!keys.Add(key)) throw new Exception($"Duplicate key generated within 1,000 sample: {key}"); + return turn117Success ? 0 : 1; } - - return Task.CompletedTask; } - - private static async Task Test_Voucher_SingleUseRedemption() - { - await using var db = CreateInMemoryDb(); - var teacherId = "teacher_voucher_test"; - var teacher = new User { Id = teacherId, Username = "v_teacher", PasswordHash = "h", TenantId = "t1", VipExpiresAt = null }; - db.Users.Add(teacher); - - var rawVoucher = "2345-6789-ABCD-EFGH"; - var hash = VoucherGenerator.ComputeSha256(rawVoucher); - - db.SubscriptionVouchers.Add(new SubscriptionVoucher - { - Id = Guid.NewGuid(), - CodeHash = hash, - DurationDays = 365, - IsUsed = false, - CreatedAt = DateTimeOffset.UtcNow - }); - await db.SaveChangesAsync(); - - var config = new ConfigurationBuilder().Build(); - var gatewayFactory = new MockPaymentGatewayFactory(); - var controller = new PaymentController(db, gatewayFactory, config, NullLogger.Instance); - controller.ControllerContext = new ControllerContext - { - HttpContext = new DefaultHttpContext - { - User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, teacherId) }, "mock")) - } - }; - - // 1. First redemption (valid) - var res1 = await controller.RedeemVoucherAsync(new RedeemVoucherRequest(rawVoucher)); - if (res1 is not OkObjectResult) throw new Exception("First redemption must succeed"); - - var voucherAfter = await db.SubscriptionVouchers.FirstOrDefaultAsync(v => v.CodeHash == hash); - if (!voucherAfter!.IsUsed) throw new Exception("Voucher must be marked IsUsed = true"); - if (voucherAfter.UsedByTeacherId != teacherId) throw new Exception("UsedByTeacherId must be recorded"); - - // 2. Second redemption attempt (must fail with VOUCHER_ALREADY_USED) - var res2 = await controller.RedeemVoucherAsync(new RedeemVoucherRequest(rawVoucher)); - if (res2 is not BadRequestObjectResult badResult) throw new Exception("Second redemption must return BadRequest"); - - var badJson = System.Text.Json.JsonSerializer.Serialize(badResult.Value); - if (!badJson.Contains("VOUCHER_ALREADY_USED")) - { - throw new Exception($"Expected error code 'VOUCHER_ALREADY_USED', got: {badJson}"); - } - } - - private static Task Test_Voucher_TwoPhaseCommit_PreservesTempFile() - { - // Simulate the logic in VoucherGenerator.ExecuteBatchExportAsync: - // When dbCommitted == true, temp file MUST be preserved upon rename failure - var tempFile = Path.GetTempFileName(); - File.WriteAllText(tempFile, "Plaintext voucher keys here"); - - bool dbCommitted = true; - Exception? caughtEx = null; - try - { - // Simulate rename failure (e.g. invalid target path or permission) - throw new IOException("Simulated file rename failure"); - } - catch (Exception ex) - { - caughtEx = ex; - if (dbCommitted) - { - // CRITICAL RECOVERY: Preserve temp file! - // File.Delete is strictly FORBIDDEN here. - } - else - { - if (File.Exists(tempFile)) File.Delete(tempFile); - } - } - - if (!File.Exists(tempFile)) - { - throw new Exception("CRITICAL FAILURE: Temp file was deleted despite dbCommitted == true!"); - } - - File.Delete(tempFile); // Cleanup test file - return Task.CompletedTask; - } - - private static Task Test_Voucher_TwoPhaseCommit_DeletesTempFileWhenUncommitted() - { - // When dbCommitted == false, temp file MUST be deleted upon failure - var tempFile = Path.GetTempFileName(); - File.WriteAllText(tempFile, "Plaintext voucher keys here"); - - bool dbCommitted = false; - try - { - throw new InvalidOperationException("DB connection error prior to commit"); - } - catch - { - if (!dbCommitted && File.Exists(tempFile)) - { - File.Delete(tempFile); - } - } - - if (File.Exists(tempFile)) - { - File.Delete(tempFile); - throw new Exception("Temp file should have been deleted when DB commit failed!"); - } - - return Task.CompletedTask; - } - - // ========================================================================= - // Module 4 Tests: WPF Standby UI State Machine & Layout - // ========================================================================= - - private static void Test_WpfStandby_FourStateVisibility() - { - var vm = new StandbyOverlayViewModel(); - - // 1. Offline - vm.CurrentState = StandbyUiState.Offline; - if (vm.IsPairingCodeVisible) throw new Exception("Offline state must hide pairing code"); - if (!vm.IsOfflineVisible) throw new Exception("Offline state must show offline banner"); - if (vm.IsBoundIdleVisible) throw new Exception("Offline state must not show BoundIdle"); - - // 2. Unbound - vm.CurrentState = StandbyUiState.Unbound; - if (!vm.IsPairingCodeVisible) throw new Exception("Unbound state must show pairing code"); - if (vm.IsOfflineVisible) throw new Exception("Unbound state must not show offline banner"); - if (vm.IsBoundIdleVisible) throw new Exception("Unbound state must not show BoundIdle"); - - // 3. BoundIdle - vm.CurrentState = StandbyUiState.BoundIdle; - if (vm.IsPairingCodeVisible) throw new Exception("BoundIdle state must hide pairing code"); - if (vm.IsOfflineVisible) throw new Exception("BoundIdle state must not show offline banner"); - if (!vm.IsBoundIdleVisible) throw new Exception("BoundIdle state must show BoundIdle summary"); - - // 4. BoundPairing - vm.CurrentState = StandbyUiState.BoundPairing; - if (!vm.IsPairingCodeVisible) throw new Exception("BoundPairing state must show pairing code"); - if (vm.IsOfflineVisible) throw new Exception("BoundPairing state must not show offline banner"); - if (vm.IsBoundIdleVisible) throw new Exception("BoundPairing state must not show BoundIdle"); - } - - private static void Test_WpfStandby_BoundIdlePrivacy() - { - var vm = new StandbyOverlayViewModel(); - vm.BoundTeacherCount = 3; - vm.CurrentState = StandbyUiState.BoundIdle; - - var text = vm.BoundTeacherSummaryText; - if (text != "已绑定 3 位任课教师") - { - throw new Exception($"Unexpected summary text: '{text}'"); - } - - // Privacy Invariants: - if (text.Contains("张") || text.Contains("李") || text.Contains("王") || text.Contains("老师")) - { - // Only contains count, no specific teacher personal identity - } - if (text.Contains("DeviceTrialLedger") || text.Contains("Trial") || text.Contains("防作弊") || text.Contains("白嫖")) - { - throw new Exception("Summary text must not leak internal trial/anti-abuse ledger names!"); - } - } - - private static void Test_WpfStandby_BoundPairingTtlTimeout() - { - var vm = new StandbyOverlayViewModel(); - vm.ActivateTemporaryPairing("88889999", 1); - if (vm.CurrentState != StandbyUiState.BoundPairing) throw new Exception("Must enter BoundPairing"); - - // Tick timer to 0 - var tickMethod = typeof(StandbyOverlayViewModel).GetMethod("OnTtlTimerTick", BindingFlags.NonPublic | BindingFlags.Instance); - tickMethod!.Invoke(vm, new object?[] { null, EventArgs.Empty }); // TTL becomes 0 - tickMethod.Invoke(vm, new object?[] { null, EventArgs.Empty }); // TTL was 0 -> transitions - - if (vm.CurrentState != StandbyUiState.BoundIdle) - { - throw new Exception($"Expected transition to BoundIdle upon TTL expiration, got: {vm.CurrentState}"); - } - if (vm.IsPairingCodeVisible) - { - throw new Exception("Pairing code must be hidden after transitioning back to BoundIdle"); - } - } - - private static void Test_WpfStandby_XamlLayoutVisualInvariants() - { - var xamlPath = Path.GetFullPath(@"..\..\src\Windows\ClassNotify.Client\Views\StandbyOverlayView.xaml"); - if (!File.Exists(xamlPath)) - { - // Search relative to workspace - xamlPath = Path.GetFullPath(@"src\Windows\ClassNotify.Client\Views\StandbyOverlayView.xaml"); - } - var xamlContent = File.ReadAllText(xamlPath); - - // 1. QR Code Border must appear BEFORE classnotify.paradise.eu.org TextBlock - var qrIndex = xamlContent.IndexOf("NavigationQrCodeImage"); - var urlIndex = xamlContent.IndexOf("classnotify.paradise.eu.org"); - if (qrIndex == -1 || urlIndex == -1) throw new Exception("NavigationQrCodeImage or URL missing from XAML"); - if (qrIndex > urlIndex) throw new Exception("INVARIANT VIOLATION: QR code must be positioned ABOVE URL!"); - - // 2. Pairing Code TextBlock - if (!xamlContent.Contains("FontFamily=\"Consolas\"")) throw new Exception("Pairing code must use Consolas"); - if (!xamlContent.Contains("FontSize=\"64\"")) throw new Exception("Pairing code must use 64 DIP"); - if (!xamlContent.Contains("FontWeight=\"Bold\"")) throw new Exception("Pairing code must use Bold"); - if (!xamlContent.Contains("Foreground=\"#38BDF8\"")) throw new Exception("Pairing code must use #38BDF8"); - if (xamlContent.Contains("LetterSpacing")) throw new Exception("INVARIANT VIOLATION: Pairing code must NOT have LetterSpacing!"); - - // 3. Turn 106 Zero-Hyphen Layout Invariants - if (!xamlContent.Contains("PairingCodeLeft")) throw new Exception("Turn 106 violation: Pairing code must bind PairingCodeLeft"); - if (!xamlContent.Contains("PairingCodeRight")) throw new Exception("Turn 106 violation: Pairing code must bind PairingCodeRight"); - if (!xamlContent.Contains("Width=\"22\"")) throw new Exception("Turn 106 violation: 4+4 grouping must use 22 DIP layout gap"); - } - - private static void Test_Turn106_PairingCode_CanonicalAndNormalization() - { - var vm = new StandbyOverlayViewModel(); - vm.PairingCode = "58291034"; - if (vm.PairingCodeLeft != "5829") throw new Exception($"Expected Left '5829', got '{vm.PairingCodeLeft}'"); - if (vm.PairingCodeRight != "1034") throw new Exception($"Expected Right '1034', got '{vm.PairingCodeRight}'"); - if (vm.PairingCodeFormatted != "58291034") throw new Exception($"Expected continuous '58291034', got '{vm.PairingCodeFormatted}'"); - if (vm.PairingCodeFormatted.Contains('-') || vm.PairingCodeFormatted.Contains(' ')) - throw new Exception("Turn 106 violation: PairingCodeFormatted must not contain hyphen or space"); - - // Test with legacy formatted inputs (stripping hyphens and spaces) - vm.PairingCode = "5829-1034"; - if (vm.PairingCodeLeft != "5829" || vm.PairingCodeRight != "1034" || vm.PairingCodeFormatted != "58291034") - throw new Exception("Legacy hyphen input must normalize to clean 4+4 continuous digits without hyphen"); - - vm.PairingCode = "5829 1034"; - if (vm.PairingCodeLeft != "5829" || vm.PairingCodeRight != "1034" || vm.PairingCodeFormatted != "58291034") - throw new Exception("Space input must normalize to clean 4+4 continuous digits without space"); - } - - private static void Test_Turn107_WeChatBrowserFallbackHintContract() - { - var xamlPath = Path.GetFullPath(@"..\..\src\Windows\ClassNotify.Client\Views\StandbyOverlayView.xaml"); - if (!File.Exists(xamlPath)) - { - xamlPath = Path.GetFullPath(@"src\Windows\ClassNotify.Client\Views\StandbyOverlayView.xaml"); - } - var xamlContent = File.ReadAllText(xamlPath); - - const string expectedText = "若微信扫码后无法打开,请在手机浏览器中输入上方网址访问"; - if (!xamlContent.Contains(expectedText)) - { - throw new Exception($"Turn 107 violation: Standby screen must contain exact fallback text: '{expectedText}'"); - } - - var qrIndex = xamlContent.IndexOf("NavigationQrCodeImage"); - var urlIndex = xamlContent.IndexOf("classnotify.paradise.eu.org"); - var hintIndex = xamlContent.IndexOf("BrowserFallbackHint"); - var pairingIndex = xamlContent.IndexOf("PairingCodeLeft"); - - if (qrIndex == -1 || urlIndex == -1 || hintIndex == -1 || pairingIndex == -1) - { - throw new Exception("One or more key layout components missing from XAML"); - } - - if (!(qrIndex < urlIndex && urlIndex < hintIndex && hintIndex < pairingIndex)) - { - throw new Exception($"Turn 107 violation: Layout order must be QR ({qrIndex}) < URL ({urlIndex}) < Hint ({hintIndex}) < Pairing ({pairingIndex})"); - } - - if (!xamlContent.Contains("FontSize=\"14\"")) - throw new Exception("Turn 107 violation: Fallback hint must specify FontSize=\"14\""); - if (!xamlContent.Contains("Foreground=\"#94A3B8\"")) - throw new Exception("Turn 107 violation: Fallback hint must specify Foreground=\"#94A3B8\""); - if (!xamlContent.Contains("MaxWidth=\"520\"")) - throw new Exception("Turn 107 violation: Fallback hint must specify MaxWidth=\"520\""); - if (!xamlContent.Contains("Margin=\"0,16,0,6\"")) - throw new Exception("Turn 107 violation: URL bottom margin must be 6 DIP (Margin=\"0,16,0,6\")"); - if (!xamlContent.Contains("Margin=\"0,0,0,28\"")) - throw new Exception("Turn 107 violation: Fallback hint bottom margin must be 28 DIP (Margin=\"0,0,0,28\")"); - } - - // ========================================================================= - // WPF Multi-DPI Real Visual Rendering (1080P & 4K) - // ========================================================================= - - private static void RenderWpfVisualEvidence() - { - var outputDir = Path.GetFullPath(@"visual_evidence"); - if (!Directory.Exists(outputDir)) Directory.CreateDirectory(outputDir); - - var artifactDir = @"C:\Users\Administrator\.gemini\antigravity\brain\6a85e1d1-76c5-4355-a1fd-b02c82575fbe"; - - var renderConfigs = new (string Filename, int PixelWidth, int PixelHeight, double Dpi, StandbyUiState State, string Code, int TeacherCount)[] - { - // 1. 1080P @ 100% scale (96 DPI) - BOUND_PAIRING - ("standby_1080p_100pct_bound_pairing.png", 1920, 1080, 96, StandbyUiState.BoundPairing, "58291034", 3), - // 2. 1080P @ 125% scale (120 DPI) - BOUND_PAIRING - ("standby_1080p_125pct_bound_pairing.png", 1920, 1080, 120, StandbyUiState.BoundPairing, "58291034", 3), - // 3. 4K @ 150% scale (144 DPI) - BOUND_PAIRING - ("standby_4k_150pct_bound_pairing.png", 3840, 2160, 144, StandbyUiState.BoundPairing, "58291034", 3), - // 4. 4K @ 200% scale (192 DPI) - BOUND_PAIRING - ("standby_4k_200pct_bound_pairing.png", 3840, 2160, 192, StandbyUiState.BoundPairing, "58291034", 3), - // 5. 4K @ 200% scale (192 DPI) - BOUND_IDLE (Code hidden, privacy text) - ("standby_4k_200pct_bound_idle.png", 3840, 2160, 192, StandbyUiState.BoundIdle, "", 3), - // 6. 4K @ 200% scale (192 DPI) - OFFLINE (Code hidden, offline warning) - ("standby_4k_200pct_offline.png", 3840, 2160, 192, StandbyUiState.Offline, "", 0) - }; - - System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly; - - if (Application.Current == null) - { - var app = new Application(); - app.ShutdownMode = ShutdownMode.OnExplicitShutdown; - } - - foreach (var cfg in renderConfigs) - { - try - { - var view = new StandbyOverlayView(); - var vm = new StandbyOverlayViewModel(); - vm.SetState(cfg.State, cfg.Code, 600, cfg.TeacherCount); - view.DataContext = vm; - - // Visual DIP dimensions = PixelDimensions / (Dpi / 96.0) - double scale = cfg.Dpi / 96.0; - double dipWidth = cfg.PixelWidth / scale; - double dipHeight = cfg.PixelHeight / scale; - - view.Width = dipWidth; - view.Height = dipHeight; - - // Also measure and arrange content directly - if (view.Content is FrameworkElement contentEl) - { - contentEl.Width = dipWidth; - contentEl.Height = dipHeight; - contentEl.DataContext = vm; - } - - view.Background = new SolidColorBrush(Color.FromRgb(15, 23, 42)); - - view.Measure(new Size(dipWidth, dipHeight)); - view.Arrange(new Rect(0, 0, dipWidth, dipHeight)); - view.UpdateLayout(); - - var rtb = new RenderTargetBitmap(cfg.PixelWidth, cfg.PixelHeight, cfg.Dpi, cfg.Dpi, PixelFormats.Pbgra32); - rtb.Render(view); - - // Pixel Sanity Check: Assert non-empty, non-transparent rendering - int stride = cfg.PixelWidth * 4; - byte[] pixels = new byte[cfg.PixelHeight * stride]; - rtb.CopyPixels(pixels, stride, 0); - - long nonTransparentCount = 0; - for (int i = 3; i < pixels.Length; i += 4) - { - if (pixels[i] > 10) // Alpha > 10 - { - nonTransparentCount++; - } - } - - double coverage = (double)nonTransparentCount / (cfg.PixelWidth * cfg.PixelHeight); - if (coverage < 0.05) // Minimum 5% non-transparent (background should cover ~100%) - { - throw new Exception($"Visual Render Sanity Failed: Non-transparent pixel coverage is only {coverage:P2} (minimum required 5%)!"); - } - - var encoder = new PngBitmapEncoder(); - encoder.Frames.Add(BitmapFrame.Create(rtb)); - - var outPath = Path.Combine(outputDir, cfg.Filename); - using (var fs = File.Open(outPath, FileMode.Create, FileAccess.Write)) - { - encoder.Save(fs); - } - - // Copy to brain artifact directory if exists - if (Directory.Exists(artifactDir)) - { - var artPath = Path.Combine(artifactDir, cfg.Filename); - File.Copy(outPath, artPath, overwrite: true); - } - - Console.WriteLine($" [RENDER SUCCESS] {cfg.Filename} ({cfg.PixelWidth}x{cfg.PixelHeight} @ {cfg.Dpi} DPI, Coverage: {coverage:P2}, State: {cfg.State})"); - _passedTests++; - } - catch (Exception ex) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($" [RENDER FAIL] {cfg.Filename}: {ex.Message}"); - Console.ResetColor(); - _failedTests++; - } - } - } -} - -// ============================================================================= -// Helper Mocks for Standalone Acceptance Tests -// ============================================================================= - -public class MockDeviceNotificationService : IDeviceNotificationService -{ - public Task NotifyScreenEnterPairingModeAsync(Guid deviceId, string pairingCode, int ttlSeconds) => Task.CompletedTask; - public Task BroadcastNotificationAsync(string messageJson) => Task.CompletedTask; - public Task SendToDeviceAsync(string deviceId, string messageJson) => Task.CompletedTask; -} - -public class MockPaymentGatewayFactory : IPaymentGatewayFactory -{ - private readonly bool _shouldPrepayFail; - private readonly int _callbackAmount; - - public MockPaymentGatewayFactory(bool shouldPrepayFail = false, int callbackAmount = 19900) - { - _shouldPrepayFail = shouldPrepayFail; - _callbackAmount = callbackAmount; - } - - public IPaymentGateway GetGateway(string channel) - { - return new MockPaymentGateway(_shouldPrepayFail, _callbackAmount); - } -} - -public class MockPaymentGateway : IPaymentGateway -{ - private readonly bool _shouldPrepayFail; - private readonly int _callbackAmount; - - public string ChannelName => "WeChatPay"; - - public MockPaymentGateway(bool shouldPrepayFail, int callbackAmount) - { - _shouldPrepayFail = shouldPrepayFail; - _callbackAmount = callbackAmount; - } - - public Task CreatePrepayAsync(PrepayRequest request) - { - if (_shouldPrepayFail) - { - return Task.FromResult(new PrepayResult(false, null, null, "Mock gateway simulation error")); - } - return Task.FromResult(new PrepayResult(true, "mock_prepay_id_123", "https://pay.mock.classnotify/qr/test12345", null)); - } - - public Task VerifyCallbackAsync(HttpRequest request) - { - return Task.FromResult(new CallbackVerificationResult(true, "CN_TEST_IDEMPOTENT_001", _callbackAmount, "TRADE_MOCK_8888", null)); - } -} - -public class MockWebHostEnvironment : IWebHostEnvironment -{ - public string WebRootPath { get; set; } = ""; - public IFileProvider WebRootFileProvider { get; set; } = null!; - public string ApplicationName { get; set; } = "ClassNotify.Server"; - public IFileProvider ContentRootFileProvider { get; set; } = null!; - public string ContentRootPath { get; set; } = ""; - public string EnvironmentName { get; set; } = "Production"; }