��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<User> _passwordHasher; + private readonly IInstallerTicketService _ticketService; private readonly ILogger<TeacherConsoleController> _logger; public TeacherConsoleController( @@ -46,12 +71,18 @@ public class TeacherConsoleController : ControllerBase IPairingService pairingService, IConfiguration config, IDeviceNotificationService deviceNotificationService, + ISecurityService securityService, + IPasswordHasher<User> passwordHasher, + IInstallerTicketService ticketService, ILogger<TeacherConsoleController> 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<ActionResult<TeacherProfileDto>> GetProfileAsync() { var teacherId = GetTeacherId(); if (string.IsNullOrEmpty(teacherId)) return Unauthorized(new { code = "TEACHER_NOT_FOUND", message = "Ye^&�7b NX[(Wb*g�cCg" }); - 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 = "Ye^&�7b NX[(W" }); @@ -78,19 +110,162 @@ public class TeacherConsoleController : ControllerBase var screenLimit = _config.GetValue<int>("Product:PersonalScreenLimit", 4); var now = DateTimeOffset.UtcNow; - var subState = teacher.IsVipActive(now) ? "VIP" : (teacher.IsTrialActive(now) ? "Trial" : "Expired"); + // sQ.��a;�����Ye^\*g�~�[�NUO'YO\ �N^�ck_ VIP �Ջ(ug\*g_/T �TrialEndsAt ꁨR�Ock:N null ��~ N�cMRcbd�)Ype + 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 ?? "Ye^�]\O�S", 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<IActionResult> UpdateProfileAsync([FromBody] UpdateTeacherProfileRequest req) + { + var teacherId = GetTeacherId(); + if (string.IsNullOrEmpty(teacherId)) + return Unauthorized(new { code = "TEACHER_NOT_FOUND", message = "Ye^&�7b NX[(Wb*g�cCg" }); + + 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 = "Ye^&�7b NX[(W" }); + + if (!string.IsNullOrWhiteSpace(req.FullName)) + { + var name = req.FullName.Trim(); + if (name.Length > 50) + return BadRequest(new { code = "INVALID_NAME", message = "Ye^�y���^ N����Ǐ 50 *NW[&{" }); + 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 = "Yef[zz�� T�y��^ N����Ǐ 100 *NW[&{" }); + + 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<IActionResult> ChangePasswordAsync([FromBody] TeacherChangePasswordRequest req) + { + var teacherId = GetTeacherId(); + if (string.IsNullOrEmpty(teacherId)) + return Unauthorized(new { code = "TEACHER_NOT_FOUND", message = "Ye^&�7b NX[(Wb*g�cCg" }); + + 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 = "Ye^&�7b NX[(W" }); + + if (string.IsNullOrEmpty(req.CurrentPassword)) + return BadRequest(new { code = "PASSWORD_REQUIRED", message = "����eQS_MR{vU_�[x" }); + + if (string.IsNullOrEmpty(req.NewPassword) || req.NewPassword.Length < 8) + return BadRequest(new { code = "PASSWORD_TOO_SHORT", message = ":N�N&�7b�[hQ ��e�[x��^ N��\�N 8 MO" }); + + if (req.NewPassword != req.ConfirmPassword) + return BadRequest(new { code = "PASSWORD_MISMATCH", message = "$N!k��eQ�v�e�[x NN� ���8h�[" }); + + var verifyResult = _passwordHasher.VerifyHashedPassword(teacher, teacher.PasswordHash, req.CurrentPassword); + if (verifyResult == PasswordVerificationResult.Failed) + { + return BadRequest(new { code = "INVALID_CURRENT_PASSWORD", message = "S_MR�[x Ncknx ���8h�[T͑Ջ" }); + } + + 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 = "Ye^(W�c6R�S�;N�O9e{vU_�[x ��e�Qnc�zsS1YHe", + 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 = "�[x�O9eb�R��e�[x�]uHe", + token = freshToken + }); + } + + [HttpPost("account/rotate-recovery-key")] + public async Task<IActionResult> RotateRecoveryKeyAsync([FromBody] RotateRecoveryKeyRequest req) + { + var teacherId = GetTeacherId(); + if (string.IsNullOrEmpty(teacherId)) + return Unauthorized(new { code = "TEACHER_NOT_FOUND", message = "Ye^&�7b NX[(Wb*g�cCg" }); + + if (string.IsNullOrEmpty(req.CurrentPassword)) + return BadRequest(new { code = "PASSWORD_REQUIRED", message = "����eQS_MR�[x�N�������N" }); + + 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<ActionResult<List<ScreenDto>>> 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 ?? "*g}T TYe�[", - 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 ?? "*g}T TYe�[", + 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 = "����eQ gHe�v8MO�s�~M��[x" }); + 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 ?? "Yef[�s�~", 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<ActionResult> UnbindScreenAsync(Guid deviceId) + [HttpDelete("screens/{deviceId}")] + public async Task<ActionResult> UnbindScreenAsync(string deviceId) { var teacherId = GetTeacherId(); if (string.IsNullOrEmpty(teacherId)) return Unauthorized(new { code = "UNAUTHORIZED", message = "*g{vU_" }); - 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 = "�~�[��U_ NX[(Wb�]�d�" }); + TeacherDeviceBinding? targetBinding = null; - // �~NO(u�]�Q�~W[�k 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 }); } + + /// <summary> + /// �]{vU_Ye^3u�� Windows �[7b�z�[ňS4N�e N}��Qnc�10R���z�S � + /// /ec@b g g�R�r`�Trial, Active, Expired � � N�V���0RgaSOO�[7b�z���S + /// </summary> + [HttpPost("download/windows-ticket")] + public ActionResult GetWindowsInstallerTicket() + { + var teacherId = GetTeacherId(); + if (string.IsNullOrEmpty(teacherId)) + return Unauthorized(new { code = "UNAUTHORIZED", message = "*g{vU_" }); + + 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 /// g�R�z N�S'YO\4N�eۏeQM��[!j_�:d&^4N�eM��[xN gHeg�ype � /// </summary> Task ReceivePairingMode(string pairingCode, int ttlSeconds); + + /// <summary> + /// Turn 115: g�R�z��w'YO\�~�[�r`�f�e��Y�N��Ye^��!k�~�[b�e�X�N��Ye^�~�[ � + /// </summary> + 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 } /// <summary> 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; /// <summary> @@ -5,6 +7,36 @@ namespace ClassNotify.Shared.Models; /// </summary> public class ClientStateSnapshotDto { + /// <summary> + /// Turn 115 CgZ��Y�~�[u}ThTg�r`: Unbound / Bound + /// </summary> + public DeviceBindingState BindingState { get; set; } = DeviceBindingState.Unbound; + + /// <summary> + /// Turn 116 ЏL�P�6R�r`�~�^�N BindingState ck�N ��N Nal�g � + /// </summary> + public OperationalRestrictionState RestrictionState { get; set; } = OperationalRestrictionState.None; + + /// <summary> + /// CgZYe�[/�s�~ID + /// </summary> + public string? ClassroomId { get; set; } + + /// <summary> + /// CgZYe�[/�s�~>f:y T�y + /// </summary> + public string? ClassroomDisplayName { get; set; } + + /// <summary> + /// �]�~�[Ye^;`pe��S�[ TS��pe �Tĉ�O�b���y � + /// </summary> + public int BoundTeacherCount { get; set; } = 0; + + /// <summary> + /// �r`Hr,g�S �US���X �2�bk_ek�mo`qN�^���v + /// </summary> + public long StateRevision { get; set; } = 0; + /// <summary> /// ��YM�n�r`�Unactivated / Activating / Activated / CredentialError / ReprovisionRequired /// </summary> 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: '��kX�Q�s�~ T�y' }; + } + const raw = input.trim(); + if (/[()� �[\]00{}]/.test(raw)) { + return { isValid: false, canonical: '', error: '�s�~ T�y N��S+T�b�S ����v�ckX�Q ��O�Y�ؚN3�s0' }; + } + const canonical = raw.replace(/ +/g, ''); + if (canonical.length < 2 || canonical.length > 20) { + return { isValid: false, canonical, error: '�s�~ T�y��^�_{�(W 2 � 20 *NW[KN��' }; + } + if (!canonical.endsWith('�s')) { + return { isValid: false, canonical, error: '�s�~ T�y�_{��N �s �~>\ ��O�Y�ؚN3�s091�s0' }; + } + if (!/^[\p{Script=Han}0-9]+$/u.test(canonical)) { + return { isValid: false, canonical, error: '�s�~ T�y�S��S+TIlW[�TpeW[ �v^N�_{��N �s �~>\ ��O�Y�ؚN3�s091�s0' }; + } + 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' (=��� �S�|T�S) | 'receipts' (=��� ����Vgb) | 'screen' (=إ�� �s�~'YO\N�cCg) - const [activeTab, setActiveTab] = useState<'composer' | 'receipts' | 'screen'>('composer'); + // Tab State: 'composer' (=��� �S�|T�S) | 'receipts' (=��� ����Vgb) | 'screen' (=إ�� �s�~'YO\N�cCg) | 'profile' (=�d� *N�N��n) + 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<string | null>(null); const [pairingModalInfo, setPairingModalInfo] = useState<{ open: boolean; deviceId?: string; alias?: string; code?: string; ttlSeconds?: number } | null>(null); const [activatingPairingId, setActivatingPairingId] = useState<string | null>(null); + const [downloadVersion, setDownloadVersion] = useState<string | null>(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<string | null>(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<string | null>(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 || '���S'YO\�[7b�z N}��Qnc1Y%� ���͑Ջ'); + } 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 || '�s�~ T�y NT�l'); + 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('�]b�R�~�['YO\0S_MRYe^ g�R�]0Rg �_�ck_HrTsS�S�S���w0'); @@ -355,10 +445,10 @@ export const TeacherConsole: React.FC = () => { try { await api.unbindTeacherScreen(screen.deviceId); - await loadClassesAndHistory(); } catch (err: any) { - alert(err?.message || '�d��~�[1Y%� ��� zT͑Ջ'); + console.warn('Unbind response notice:', err); } + await loadClassesAndHistory(); }; const handleActivatePairingMode = async (screen: TeacherScreen) => { @@ -1500,9 +1590,6 @@ export const TeacherConsole: React.FC = () => { <div> <h1 className="text-xl sm:text-2xl font-bold tracking-tight text-white flex items-center gap-2.5"> Ye^�]\O�S - <span className="text-xs px-2.5 py-0.5 rounded-full bg-blue-500/10 text-blue-400 border border-blue-500/20 font-medium"> - {isPersonalTeacher ? '*N�N�r�zzz��' : 'zfga!h�V'} - </span> </h1> <p className="text-xs sm:text-sm text-slate-400 mt-1.5 leading-normal"> �y�~�[T��wYe�['YO\ � /ec TTS g��0Ɖɉ8h��N�[�e�Vgb @@ -1536,7 +1623,9 @@ export const TeacherConsole: React.FC = () => { {teacherProfile.subscriptionState === 'VIP' ? `ck_Hr gHe${teacherProfile.vipExpiresAt ? ` � � ${teacherProfile.vipExpiresAt.slice(0, 10)}` : ''}` : teacherProfile.subscriptionState === 'Trial' - ? `MQ9�Ջ(u-N${teacherProfile.trialEndsAt ? ` � iR ${Math.max(0, Math.ceil((new Date(teacherProfile.trialEndsAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24)))} )Y` : ''}` + ? (teacherProfile.trialEndsAt + ? `MQ9�Ջ(u-N � iR ${Math.max(0, Math.ceil((new Date(teacherProfile.trialEndsAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24)))} )Y` + : 'MQ9�Ջ(u � �__/T (7)Y)') : ' g�R�]0Rg'} </span> </div> @@ -1614,6 +1703,18 @@ export const TeacherConsole: React.FC = () => { </span> )} </button> + <button + type="button" + onClick={() => setActiveTab('profile')} + className={`pb-2.5 text-sm font-medium transition-all flex items-center gap-2 relative ${ + activeTab === 'profile' + ? 'text-white font-semibold after:absolute after:bottom-0 after:left-0 after:right-0 after:h-0.5 after:bg-blue-500 after:rounded-full' + : 'text-slate-400 hover:text-slate-200' + }`} + > + <User className="w-4 h-4" /> + <span>*N�ND��e</span> + </button> </div> </div> @@ -1642,10 +1743,11 @@ export const TeacherConsole: React.FC = () => { <span>{loadError}</span> </div> <button - onClick={loadClassesAndHistory} - className="flex items-center gap-1 px-3 py-1 rounded-lg bg-rose-600 hover:bg-rose-500 text-white font-medium transition-colors" + onClick={handleManualRefreshScreens} + disabled={refreshingScreens} + className="flex items-center gap-1 px-3 py-1 rounded-lg bg-rose-600 hover:bg-rose-500 disabled:opacity-50 text-white font-medium transition-colors" > - <RefreshCw className="w-3.5 h-3.5" /> + <RefreshCw className={`w-3.5 h-3.5 ${refreshingScreens ? 'animate-spin' : ''}`} /> ͑Ջ </button> </div> @@ -1674,38 +1776,42 @@ export const TeacherConsole: React.FC = () => { <div className="flex items-start gap-3"> <span className="w-6 h-6 rounded-full bg-blue-500/20 text-blue-400 font-bold flex items-center justify-center shrink-0 text-xs mt-0.5">1</span> <div className="space-y-1.5 flex-1"> - <p className="font-semibold text-white text-sm">(WYe�['YO\Sb_ ClassNotify</p> + <p className="font-semibold text-white text-sm">�[ň ClassNotify 'YO\�z</p> <p className="text-slate-400 text-xs leading-relaxed"> - /T�R�[7b�zT ��g wO\U^-N.Ynpf>f:y�v <strong>8 MO'YO\M��[x</strong>0 + (WS_MR5u� N}�'YO\�z�[ňS � Y6R0R U �v&^0RYe�[ўg5u��S�Q�[ň��S��[ňN!ksS�S ��b(WKb:g N N}�T ��Ǐ8^(u�e�N O���]wQ�S�0RYe�[5u�0 </p> <div className="flex flex-wrap items-center gap-2 pt-1.5"> - <a - href="https://classnotify.paradise.eu.org/download/windows" - target="_blank" - rel="noopener noreferrer" - className="inline-flex items-center px-3 py-1.5 rounded-lg bg-blue-600 hover:bg-blue-500 text-white text-xs font-medium gap-1.5 transition-colors shadow-sm" + <button + type="button" + onClick={handleDownloadClient} + disabled={downloadingClient} + className="inline-flex items-center px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-500 text-white text-xs font-semibold gap-1.5 transition-colors shadow-sm disabled:opacity-60" > - <Monitor className="w-3.5 h-3.5" /> - <span> N}� Windows 'YO\�[7b�z</span> - </a> + <Monitor className="w-4 h-4" /> + <span>{downloadingClient ? '�QY N}�...' : ` N}� Windows 'YO\�z ${downloadVersion ? `v${downloadVersion.replace(/^v/, '')}` : ''}`}</span> + </button> <button type="button" onClick={handleCopyDownloadLink} - className="inline-flex items-center px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs border border-slate-700 gap-1.5 transition-colors" + className="inline-flex items-center px-3 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs border border-slate-700 gap-1.5 transition-colors" + title=" Y6R�[7b�z N}�eQ�S���c (�S�~Ye�[5u�Sb_{vU_sS�S N}�)" > {copiedDownloadLink ? ( <> <Check className="w-3.5 h-3.5 text-emerald-400" /> - <span className="text-emerald-400">�] Y6R N}����c</span> + <span className="text-emerald-400">�] Y6ReQ�S���c</span> </> ) : ( <> <Copy className="w-3.5 h-3.5" /> - <span> Y6R N}����c</span> + <span> Y6ReQ�S���c</span> </> )} </button> </div> + <p className="text-[11px] text-slate-500 pt-0.5"> + =ء� �c:y�Kb:g N}�T�S�Ǐ �e�N O���RKb �S��Ye�[5u��[ň�5u��z N}�T�S�v�c�beQ U �v0 + </p> </div> </div> @@ -1714,9 +1820,9 @@ export const TeacherConsole: React.FC = () => { <span className="w-6 h-6 rounded-full bg-blue-500/20 text-blue-400 font-bold flex items-center justify-center shrink-0 text-xs mt-0.5">2</span> <div className="space-y-2.5 flex-1"> <div> - <p className="font-semibold text-white text-sm">��eQM��[x �sS�S�[b�~�[</p> + <p className="font-semibold text-white text-sm">�~�[�s�~'YO\</p> <p className="text-slate-400 text-xs mt-0.5"> - M��[b�RT�zsS�p�N�s�~ �sS�S1\�~|T�S��w0 + Ye�['YO\�[ň/T�RT �O\U^ NOnpf>f:y 8 MO�~peW[M��[x0 </p> </div> <div className="pt-1"> @@ -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" > <Plus className="w-4 h-4" /> - <span>��eQM��[x�~�['YO\</span> + <span>��eQ 8 MOM��[x�~�['YO\</span> </button> </div> <p className="text-[11px] text-slate-500"> - M��[x gHeg:N 10 R��0��]Ǐg�S(W'YO\�z�p�Q7R�e͑�eub0 + M��[x:N 8 MOpeW[ �10 R���Q gHe0�~�[b�RT�zsS1\�~|T�S��w0 </p> </div> </div> @@ -1786,32 +1892,42 @@ export const TeacherConsole: React.FC = () => { {activeTab === 'screen' && ( <div className="max-w-5xl mx-auto space-y-6"> {/* 1. Bound Classroom Screens Card (Turn 103/104 Dual-Brain Consensus) */} - <div className="bg-slate-900 border border-slate-800 rounded-2xl p-5 shadow-sm space-y-4"> + <div className="bg-slate-900 border border-slate-800 rounded-2xl p-4 sm:p-5 shadow-sm space-y-4"> <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-3 border-b border-slate-800/70"> - <div className="flex items-center gap-2"> - <Monitor className="w-4 h-4 text-blue-400" /> - <h2 className="text-sm font-semibold text-white">b�v�s�~'YO\�~�z</h2> - <span className="text-[11px] px-2 py-0.5 rounded-full bg-slate-800 text-slate-300 font-mono"> + <div className="flex items-center justify-between sm:justify-start gap-2"> + <div className="flex items-center gap-2"> + <Monitor className="w-4 h-4 text-blue-400" /> + <h2 className="text-sm font-semibold text-white">b�v�s�~'YO\�~�z</h2> + </div> + <span className="text-[11px] px-2.5 py-0.5 rounded-full bg-slate-800 text-slate-300 font-mono"> �]�~�[ {boundScreens.length > 0 ? boundScreens.length : classes.length} / {teacherProfile?.screenLimit ?? 4} �S </span> </div> + <div className="flex items-center gap-2"> <button type="button" - onClick={loadClassesAndHistory} - className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition-colors" - title="7R�e�~�z�r`" + onClick={handleDownloadClient} + disabled={downloadingClient} + className="px-3 py-1.5 rounded-xl bg-slate-800 hover:bg-slate-750 text-slate-200 hover:text-white border border-slate-700/80 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 shadow-sm disabled:opacity-60" + title=" N}� Windows 'YO\�[7b�zo��N" > - <RefreshCw className="w-3.5 h-3.5" /> + <Download className={`w-3.5 h-3.5 text-blue-400 ${downloadingClient ? 'animate-bounce' : ''}`} /> + <span>{downloadingClient ? '�QY N}�...' : ' N}�'YO\o��N'}</span> </button> + <button type="button" onClick={handleOpenClaimModal} disabled={teacherProfile ? (boundScreens.length >= teacherProfile.screenLimit) : false} - className="px-3 py-1.5 rounded-xl bg-blue-600 hover:bg-blue-500 disabled:opacity-50 disabled:cursor-not-allowed text-white text-xs font-medium transition-colors flex items-center gap-1.5 shadow-sm" + className="px-3.5 py-1.5 rounded-xl bg-blue-600 hover:bg-blue-500 disabled:opacity-50 disabled:cursor-not-allowed text-white text-xs font-semibold transition-colors flex items-center justify-center gap-1.5 shadow-md shadow-blue-600/20" > <Plus className="w-3.5 h-3.5" /> - <span>��eQM��[x�~�['YO\</span> + <span> + {teacherProfile && boundScreens.length >= teacherProfile.screenLimit + ? `�]�� ${teacherProfile.screenLimit} �S NP�` + : '�~�[�e�s�~'YO\'} + </span> </button> </div> </div> @@ -1821,12 +1937,12 @@ export const TeacherConsole: React.FC = () => { {boundScreens.map((screen) => ( <div key={screen.deviceId} - className="bg-slate-950/70 border border-slate-800 rounded-xl p-4 space-y-3" + className="bg-slate-950/70 border border-slate-800 rounded-xl p-4 space-y-3 shadow-sm" > <div className="flex items-center justify-between"> - <span className="font-semibold text-white text-sm">{screen.classAlias}</span> + <span className="font-bold text-white text-base">{screen.classAlias}</span> <span - className={`px-2 py-0.5 rounded-full text-[11px] font-medium flex items-center gap-1.5 ${ + className={`px-2.5 py-0.5 rounded-full text-[11px] font-medium flex items-center gap-1.5 ${ screen.isOnline ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-slate-800 text-slate-400 border border-slate-700' @@ -1837,40 +1953,35 @@ export const TeacherConsole: React.FC = () => { </span> </div> - <div className="text-xs text-slate-400 space-y-1 pt-1 border-t border-slate-850"> - <div> - <span className="text-slate-500">��YhƋ�</span> - <span className="font-mono text-slate-300 ml-1">{screen.deviceId}</span> + <div className="space-y-1.5 text-xs text-slate-400 pt-2.5 border-t border-slate-800/80"> + <div className="flex items-center justify-between gap-2"> + <span className="text-slate-500 shrink-0">��YhƋ</span> + <span className="font-mono text-slate-300 truncate max-w-[200px]" title={screen.hardwareDeviceId || screen.deviceId}> + {screen.hardwareDeviceId || screen.deviceId} + </span> </div> - <div> - <span className="text-slate-500">�~�[�e���</span> - <span className="text-slate-300 ml-1">{new Date(screen.boundAt).toLocaleString()}</span> + <div className="flex items-center justify-between gap-2"> + <span className="text-slate-500 shrink-0">�[7b�zHr,g</span> + <span className="font-mono text-slate-300"> + {screen.clientVersion ? (screen.clientVersion.startsWith('v') ? screen.clientVersion : `v${screen.clientVersion}`) : 'v2.1.0'} + </span> + </div> + <div className="flex items-center justify-between gap-2"> + <span className="text-slate-500 shrink-0">�~�[�e��</span> + <span className="text-slate-300"> + {new Date(screen.boundAt).toLocaleDateString()} {new Date(screen.boundAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} + </span> </div> </div> - <div className="flex items-center justify-between pt-2 border-t border-slate-850"> - <button - type="button" - onClick={() => handleActivatePairingMode(screen)} - disabled={activatingPairingId === screen.deviceId} - className="px-2.5 py-1 rounded-lg bg-sky-500/10 hover:bg-sky-500/20 text-sky-400 hover:text-sky-300 text-xs font-medium border border-sky-500/20 transition-colors flex items-center gap-1" - title="4N�e_/T'YO\�_:gM��[x�10R���z�S �" - > - {activatingPairingId === screen.deviceId ? ( - <Loader2 className="w-3 h-3 animate-spin" /> - ) : ( - <RadioTower className="w-3 h-3" /> - )} - <span>_/TM��[�z�S (10R)</span> - </button> - + <div className="flex justify-end pt-3 border-t border-slate-800/80"> <button type="button" onClick={() => handleUnbindScreen(screen)} - className="px-2.5 py-1 rounded-lg bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 hover:text-rose-300 text-xs font-medium border border-rose-500/20 transition-colors flex items-center gap-1" + className="py-1.5 px-3 rounded-xl bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 hover:text-rose-300 text-xs font-medium border border-rose-500/20 transition-colors flex items-center justify-center gap-1.5 shadow-sm" title="�NS_MR&��S�d�dk'YO\�v�~�[� Nq_�TvQ�N�N��Ye^ �" > - <Unlink className="w-3 h-3" /> + <Unlink className="w-3.5 h-3.5" /> <span>�d��~�[</span> </button> </div> @@ -1886,17 +1997,17 @@ export const TeacherConsole: React.FC = () => { return ( <div key={cls.id} - className="bg-slate-950/70 border border-slate-800 rounded-xl p-4 space-y-3" + className="bg-slate-950/70 border border-slate-800 rounded-xl p-4 space-y-3 shadow-sm" > <div className="flex items-center justify-between"> <div className="flex items-center gap-2"> - <span className="font-semibold text-white text-sm">{cls.displayName}</span> + <span className="font-bold text-white text-base">{cls.displayName}</span> {cls.roomNumber && ( <span className="text-xs text-slate-400">({cls.roomNumber})</span> )} </div> <span - className={`px-2 py-0.5 rounded-full text-[11px] font-medium flex items-center gap-1.5 ${ + className={`px-2.5 py-0.5 rounded-full text-[11px] font-medium flex items-center gap-1.5 ${ isOnline ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-slate-800 text-slate-400 border border-slate-700' @@ -1907,44 +2018,33 @@ export const TeacherConsole: React.FC = () => { </span> </div> - <div className="grid grid-cols-2 gap-2 text-xs text-slate-400 pt-1 border-t border-slate-850"> - <div> - <span className="text-slate-500">��YhƋ�</span> - <span className="font-mono text-slate-300 ml-1">{dev?.hostname || targetDeviceId}</span> + <div className="space-y-1.5 text-xs text-slate-400 pt-2.5 border-t border-slate-800/80"> + <div className="flex items-center justify-between gap-2"> + <span className="text-slate-500 shrink-0">��YhƋ</span> + <span className="font-mono text-slate-300 truncate max-w-[200px]" title={dev?.hostname || targetDeviceId}> + {dev?.hostname || targetDeviceId} + </span> </div> - <div> - <span className="text-slate-500">�[7b�zHr,g�</span> - <span className="font-mono text-slate-300 ml-1">{dev?.clientVersion ? `v${dev.clientVersion}` : 'v2.5.0'}</span> + <div className="flex items-center justify-between gap-2"> + <span className="text-slate-500 shrink-0">�[7b�zHr,g</span> + <span className="font-mono text-slate-300"> + {dev?.clientVersion ? (dev.clientVersion.startsWith('v') ? dev.clientVersion : `v${dev.clientVersion}`) : 'v2.1.0'} + </span> </div> - <div className="col-span-2"> - <span className="text-slate-500">ޏ�c�r`�</span> - <span className="text-slate-300 ml-1">{isOnline ? '�[�e(W�~1\�~' : '�vMR�y�~'}</span> + <div className="flex items-center justify-between gap-2"> + <span className="text-slate-500 shrink-0">ޏ�c�r`</span> + <span className="text-slate-300">{isOnline ? '�[�e(W�~1\�~' : '�vMR�y�~'}</span> </div> </div> - <div className="flex items-center justify-between pt-2 border-t border-slate-850"> - <button - type="button" - onClick={() => handleActivatePairingMode({ deviceId: targetDeviceId, classAlias: cls.displayName, isOnline: !!isOnline, boundAt: new Date().toISOString() })} - disabled={activatingPairingId === targetDeviceId} - className="px-2.5 py-1 rounded-lg bg-sky-500/10 hover:bg-sky-500/20 text-sky-400 hover:text-sky-300 text-xs font-medium border border-sky-500/20 transition-colors flex items-center gap-1" - title="4N�e_/T'YO\�_:gM��[x�10R���z�S �" - > - {activatingPairingId === targetDeviceId ? ( - <Loader2 className="w-3 h-3 animate-spin" /> - ) : ( - <RadioTower className="w-3 h-3" /> - )} - <span>_/TM��[�z�S (10R)</span> - </button> - + <div className="flex justify-end pt-3 border-t border-slate-800/80"> <button type="button" onClick={() => handleUnbindScreen({ deviceId: targetDeviceId, classAlias: cls.displayName, isOnline: !!isOnline, boundAt: new Date().toISOString() })} - className="px-2.5 py-1 rounded-lg bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 hover:text-rose-300 text-xs font-medium border border-rose-500/20 transition-colors flex items-center gap-1" + className="py-1.5 px-3 rounded-xl bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 hover:text-rose-300 text-xs font-medium border border-rose-500/20 transition-colors flex items-center justify-center gap-1.5 shadow-sm" title="�NS_MR&��S�d�dk'YO\�v�~�[� Nq_�TvQ�N�N��Ye^ �" > - <Unlink className="w-3 h-3" /> + <Unlink className="w-3.5 h-3.5" /> <span>�d��~�[</span> </button> </div> @@ -1956,7 +2056,7 @@ export const TeacherConsole: React.FC = () => { <div className="text-center py-10 text-slate-400 text-xs space-y-3"> <Monitor className="w-10 h-10 text-slate-600 mx-auto" /> <p className="text-slate-300 font-medium">S_MR�f*g�~�[�NUO'YO\�~�z</p> - <p className="text-slate-500 text-[11px]">��(W'YO\�_:gLub����S 8 MOM��[xTۏL��~�[</p> + <p className="text-slate-500 text-[11px]">��(W'YO\Lub����S 8 MOM��[xۏL��~�[ � �~�[T���e/ec(WdkN.��;N�d��~�[</p> <div className="pt-1"> <button type="button" @@ -1964,7 +2064,7 @@ export const TeacherConsole: React.FC = () => { className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-500 text-white font-medium inline-flex items-center gap-1.5 text-xs transition-colors shadow-md shadow-blue-600/20" > <Plus className="w-3.5 h-3.5" /> - <span>�zsS��eQM��[x�~�[</span> + <span>�~�[�e�s�~'YO\</span> </button> </div> </div> @@ -2004,6 +2104,11 @@ export const TeacherConsole: React.FC = () => { </div> )} + {/* Tab 4: *N�N��n */} + {activeTab === 'profile' && ( + <TeacherProfileSettings onOpenCheckout={() => setCheckoutModalOpen(true)} /> + )} + {/* Mobile Fixed Bottom Navigation Bar */} <nav className="fixed bottom-0 left-0 right-0 z-40 bg-slate-900/95 backdrop-blur-md border-t border-slate-800 md:hidden flex items-center justify-around py-2 px-3 shadow-2xl" @@ -2042,6 +2147,16 @@ export const TeacherConsole: React.FC = () => { <Monitor className="w-5 h-5" /> <span className="text-[11px]">b�v�s�~</span> </button> + <button + type="button" + onClick={() => setActiveTab('profile')} + className={`flex flex-col items-center gap-1 py-1 px-3 rounded-xl transition-all ${ + activeTab === 'profile' ? 'text-blue-400 font-semibold' : 'text-slate-400 hover:text-slate-200' + }`} + > + <User className="w-5 h-5" /> + <span className="text-[11px]">*N�ND��e</span> + </button> </nav> {/* Bottom padding spacer for mobile nav */} <div className="h-16 md:hidden"></div> @@ -2464,16 +2579,37 @@ export const TeacherConsole: React.FC = () => { </div> <div> - <label className="block text-xs font-medium text-slate-300 mb-1.5"> - �s�~+R T / Ye�[Y�l��S � � - </label> + <div className="flex justify-between items-center mb-1.5"> + <label className="block text-xs font-medium text-slate-300"> + �s�~ T�y��_kX � + </label> + <span className="text-[11px] text-slate-400 font-mono">�Y�ؚN3�s091�s</span> + </div> <input type="text" + required value={claimClassAlias} - onChange={(e) => setClaimClassAlias(e.target.value)} - placeholder="�O�Y�ؚN(3)�s b �[��|i401" - 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="�O�Y�ؚN3�s b 91�s" + 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 ? ( + <p className="text-[11px] text-rose-400 mt-1.5 flex items-center gap-1"> + <AlertCircle className="w-3.5 h-3.5 shrink-0" /> + <span>{validateAndCanonicalizeClassName(claimClassAlias).error}</span> + </p> + ) : ( + <p className="text-[10px] text-slate-400 mt-1"> + =ء� �S��kX�QIlW[NpeW[ ��_{��N �s �~>\��O�Y�ؚN3�s091�s0R�N1�s � �<strong> N��S+T-N�e�b�S</strong>0 + </p> + )} </div> {claimError && ( @@ -2500,7 +2636,7 @@ export const TeacherConsole: React.FC = () => { </button> <button type="submit" - disabled={claimingScreen || claimPairingCode.replace(/[^0-9]/g, '').length !== 8} + disabled={claimingScreen || claimPairingCode.replace(/[^0-9]/g, '').length !== 8 || !validateAndCanonicalizeClassName(claimClassAlias).isValid} className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-500 text-white text-xs font-semibold shadow-md shadow-blue-600/20 transition-all flex items-center gap-1.5 disabled:opacity-50" > {claimingScreen ? ( diff --git a/src/Windows/ClassNotify.Client/ActivationWindow.xaml b/src/Windows/ClassNotify.Client/ActivationWindow.xaml deleted file mode 100644 index 22b18b8..0000000 --- a/src/Windows/ClassNotify.Client/ActivationWindow.xaml +++ /dev/null @@ -1,262 +0,0 @@ -<Window x:Class="ClassNotify.Client.ActivationWindow" - xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" - xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" - Title="ClassNotify �s�~��Y�o;m" - Width="840" Height="600" - WindowStartupLocation="CenterScreen" - WindowStyle="None" - AllowsTransparency="True" - Background="Transparent" - Topmost="True" - ShowInTaskbar="True" - TextOptions.TextFormattingMode="Display" - TextOptions.TextRenderingMode="ClearType" - UseLayoutRounding="True" - SnapsToDevicePixels="True" - FontFamily="Microsoft YaHei UI, Microsoft YaHei, Segoe UI"> - - <Window.Resources> - <!-- Horizontal Shake Animation for Error Feedback --> - <Storyboard x:Key="ShakeAnimation"> - <DoubleAnimationUsingKeyFrames Storyboard.TargetName="CardTranslate" - Storyboard.TargetProperty="X"> - <EasingDoubleKeyFrame KeyTime="0:0:0.04" Value="-8"/> - <EasingDoubleKeyFrame KeyTime="0:0:0.08" Value="8"/> - <EasingDoubleKeyFrame KeyTime="0:0:0.12" Value="-6"/> - <EasingDoubleKeyFrame KeyTime="0:0:0.16" Value="6"/> - <EasingDoubleKeyFrame KeyTime="0:0:0.20" Value="-4"/> - <EasingDoubleKeyFrame KeyTime="0:0:0.24" Value="4"/> - <EasingDoubleKeyFrame KeyTime="0:0:0.28" Value="0"/> - </DoubleAnimationUsingKeyFrames> - </Storyboard> - </Window.Resources> - - <Border x:Name="RootCard" - Background="#FFFFFF" - BorderBrush="#CBD5E1" - BorderThickness="1.5" - CornerRadius="18" - Margin="16" - RenderOptions.ClearTypeHint="Enabled" - TextOptions.TextFormattingMode="Display" - TextOptions.TextRenderingMode="ClearType" - UseLayoutRounding="True" - SnapsToDevicePixels="True"> - <Border.RenderTransform> - <TranslateTransform x:Name="CardTranslate" X="0" Y="0"/> - </Border.RenderTransform> - <Border.Effect> - <DropShadowEffect BlurRadius="28" Color="#000000" Opacity="0.18" ShadowDepth="8" Direction="270" /> - </Border.Effect> - - <Grid Margin="36,28,36,28"> - <Grid.RowDefinitions> - <RowDefinition Height="Auto"/> <!-- Header --> - <RowDefinition Height="*"/> <!-- Content (Input or Success) --> - <RowDefinition Height="Auto"/> <!-- Footer / Actions --> - </Grid.RowDefinitions> - - <!-- Close Button Top Right --> - <Button HorizontalAlignment="Right" VerticalAlignment="Top" - Click="OnCloseClick" - Background="Transparent" BorderThickness="0" - Foreground="#475569" FontSize="20" FontWeight="Bold" - Cursor="Hand" Margin="0,-8,-8,0" Padding="10,6"> - ' - </Button> - - <!-- Header Section --> - <StackPanel Grid.Row="0" Margin="0,0,0,16"> - <StackPanel Orientation="Horizontal" Margin="0,0,0,8"> - <Border Background="#EFF6FF" CornerRadius="10" Padding="8" Margin="0,0,12,0"> - <TextBlock x:Name="HeaderIcon" Text="=��" FontSize="26" VerticalAlignment="Center" /> - </Border> - <TextBlock x:Name="TitleText" Text="�s�~��Y�o;m" FontSize="26" FontWeight="Bold" Foreground="#0F172A" VerticalAlignment="Center" /> - </StackPanel> - <TextBlock x:Name="SubtitleText" - Text="����eQ 8 MO�o;mx ��~�[v^�o;mS_MRYe�[Y�ZSO'YO\" - FontSize="15" FontWeight="Normal" Foreground="#334155" TextWrapping="Wrap" LineHeight="22" /> - </StackPanel> - - <!-- Main Input Form --> - <Grid x:Name="InputFormGrid" Grid.Row="1" VerticalAlignment="Center" Margin="0,4,0,12"> - <Grid.RowDefinitions> - <RowDefinition Height="Auto"/> <!-- Activation Code Label & Input --> - <RowDefinition Height="Auto"/> <!-- Custom Class Name Label & Input --> - <RowDefinition Height="Auto"/> <!-- Error Card --> - </Grid.RowDefinitions> - - <!-- Part 1: Activation Code Input Area --> - <StackPanel Grid.Row="0" Margin="0,0,0,14"> - <TextBlock Text="��Y�o;mx" FontSize="14" FontWeight="SemiBold" Foreground="#1E293B" Margin="2,0,0,6"/> - <Grid> - <Grid.ColumnDefinitions> - <ColumnDefinition Width="*"/> - <ColumnDefinition Width="Auto"/> - </Grid.ColumnDefinitions> - - <Border Grid.Column="0" Background="#F8FAFC" BorderBrush="#CBD5E1" BorderThickness="1.5" CornerRadius="12"> - <TextBox x:Name="CodeInput" - Height="60" - FontSize="28" - FontFamily="Consolas, Segoe UI, sans-serif" - FontWeight="Bold" - TextAlignment="Center" - VerticalContentAlignment="Center" - Background="Transparent" - BorderThickness="0" - Foreground="#0F172A" - CaretBrush="#2563EB" - MaxLength="8" - InputMethod.IsInputMethodEnabled="False" - PreviewTextInput="OnCodePreviewTextInput" - TextChanged="OnCodeTextChanged" - GotFocus="OnCodeGotFocus"> - <TextBox.InputScope> - <InputScope> - <InputScope.Names> - <InputScopeName NameValue="AlphanumericHalfWidth" /> - </InputScope.Names> - </InputScope> - </TextBox.InputScope> - </TextBox> - </Border> - - <!-- Touch Screen Soft Keyboard Trigger Button --> - <Button Grid.Column="1" - Click="OnOpenKeyboardClick" - Margin="10,0,0,0" - Height="60" - Padding="18,0" - Background="#F1F5F9" - BorderBrush="#CBD5E1" - BorderThickness="1.5" - Cursor="Hand" - ToolTip="��QO\U^o�.��v��eQ"> - <Button.Resources> - <Style TargetType="Border"> - <Setter Property="CornerRadius" Value="12" /> - </Style> - </Button.Resources> - <StackPanel Orientation="Horizontal" VerticalAlignment="Center"> - <TextBlock Text="(#" FontSize="18" Margin="0,0,6,0" VerticalAlignment="Center"/> - <TextBlock Text="��Q.��v" FontSize="15" FontWeight="Bold" Foreground="#0F172A" VerticalAlignment="Center"/> - </StackPanel> - </Button> - </Grid> - <TextBlock Text=" - </StackPanel> - - <!-- Part 2: Custom Class Name Input Area --> - <StackPanel Grid.Row="1" Margin="0,0,0,10"> - <TextBlock Text="�s�~>f:y T�y�/ecꁚ[IN �T�~�S(W�{tT�S���e�O9e �" FontSize="14" FontWeight="SemiBold" Foreground="#1E293B" Margin="2,0,0,6"/> - <Border Background="#F8FAFC" BorderBrush="#CBD5E1" BorderThickness="1.5" CornerRadius="12"> - <TextBox x:Name="ClassNameInput" - Height="52" - FontSize="17" - FontWeight="SemiBold" - Padding="16,0" - VerticalContentAlignment="Center" - Background="Transparent" - BorderThickness="0" - Foreground="#0F172A" - CaretBrush="#2563EB" - MaxLength="30" - GotFocus="OnClassNameGotFocus" - ToolTip="��eQ,g�s�~w�[ T�y ��Y81�s0820810�s�d� �s Y N�S+TIlW[ �" /> - </Border> - <TextBlock Text="* - </StackPanel> - - <!-- Part 3: Inline Error Banner (Red Accent Card) --> - <Border x:Name="ErrorCard" - Grid.Row="2" - Background="#FEF2F2" - BorderBrush="#FCA5A5" - BorderThickness="1.5" - CornerRadius="10" - Padding="14,10" - Margin="0,6,0,0" - Visibility="Collapsed"> - <StackPanel Orientation="Horizontal"> - <TextBlock Text="�&�" FontSize="16" Margin="0,0,10,0" VerticalAlignment="Center" /> - <TextBlock x:Name="ErrorMessageText" - Text="�o;mx�eHe ���8h�[T͑Ջ" - FontSize="14" Foreground="#991B1B" FontWeight="SemiBold" - TextWrapping="Wrap" VerticalAlignment="Center" /> - </StackPanel> - </Border> - </Grid> - - <!-- Success Card View (Shown on Successful Activation) --> - <Border x:Name="SuccessCard" - Grid.Row="1" - Background="#F0FDF4" - BorderBrush="#86EFAC" - BorderThickness="1.5" - CornerRadius="16" - Padding="28" - VerticalAlignment="Center" - Visibility="Collapsed"> - <StackPanel HorizontalAlignment="Center"> - <TextBlock Text="'" FontSize="44" HorizontalAlignment="Center" Margin="0,0,0,10" /> - <TextBlock x:Name="SuccessTitle" Text="kQt^�~(1)�s � �o;mb�R" FontSize="22" FontWeight="Bold" Foreground="#15803D" HorizontalAlignment="Center" Margin="0,0,0,6" /> - <TextBlock x:Name="SuccessExpiry" Text="�cCg gHe� 2027t^9g27�e" FontSize="15" FontWeight="SemiBold" Foreground="#166534" HorizontalAlignment="Center" Margin="0,0,0,10" /> - <TextBlock Text="ClassNotify �s�~'YO\�z�]_�YT�SЏL� ���w�|�~ck8^1\�~" FontSize="13" Foreground="#15803D" HorizontalAlignment="Center" /> - </StackPanel> - </Border> - - <!-- Footer / Action Buttons --> - <Grid Grid.Row="2" Margin="0,14,0,0"> - <Grid.ColumnDefinitions> - <ColumnDefinition Width="*"/> - <ColumnDefinition Width="Auto"/> - </Grid.ColumnDefinitions> - - <TextBlock VerticalAlignment="Center" FontSize="13" FontWeight="Medium" Foreground="#475569"> - �Y�OS�R ���T��|�b/g�{tXTb�b/g/ec - </TextBlock> - - <StackPanel Grid.Column="1" Orientation="Horizontal"> - <Button x:Name="CancelButton" - Content=" zT�o;m" - Click="OnCloseClick" - Background="#F8FAFC" - Foreground="#334155" - BorderBrush="#94A3B8" - BorderThickness="1" - Padding="22,10" - Margin="0,0,12,0" - Cursor="Hand" - FontWeight="Medium" - FontSize="15"> - <Button.Resources> - <Style TargetType="Border"> - <Setter Property="CornerRadius" Value="10" /> - </Style> - </Button.Resources> - </Button> - - <Button x:Name="SubmitButton" - Content="�zsS�o;m" - Click="OnSubmitClick" - Background="#2563EB" - Foreground="#FFFFFF" - BorderThickness="0" - Padding="28,10" - Cursor="Hand" - FontWeight="Bold" - FontSize="16"> - <Button.Resources> - <Style TargetType="Border"> - <Setter Property="CornerRadius" Value="10" /> - </Style> - </Button.Resources> - </Button> - </StackPanel> - </Grid> - </Grid> - </Border> -</Window> 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<string, string?, Task<(bool Success, string Message, string? ClassName, string? ExpireDate)>> _activationHandler; - private bool _isFormattingText = false; - private Rect _cachedWorkAreaDips = Rect.Empty; - - public ActivationWindow( - Func<string, string?, Task<(bool Success, string Message, string? ClassName, string? ExpireDate)>> 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<MONITORINFO>() }; - 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 = "�s�~��Y�o;m"; - HeaderIcon.Text = "=��"; - SubtitleText.Text = "����eQ 8 MO�o;mx ��~�[v^�o;mS_MRYe�[Y�ZSO'YO\"; - SubmitButton.Content = "�zsS�o;m"; - } - else if (state.LicenseStatus == "ExpiredRestricted") - { - TitleText.Text = "�s�~�cCg�]0Rg"; - HeaderIcon.Text = "�#"; - var className = !string.IsNullOrWhiteSpace(state.ClassDisplayName) ? state.ClassDisplayName : ",g�sYef['YO\"; - SubtitleText.Text = $"S_MR��Y�[{className}] �cCg�]0Rg0����eQ�~gxb�e�o;mxb` Yck8^ g�R"; - SubmitButton.Content = "�zsS�~g / �o;m"; - } - else if (state.LicenseStatus == "RevokedRestricted" || state.ProvisioningState == "ReprovisionRequired") - { - TitleText.Text = "��Y�cCg�]͑n"; - HeaderIcon.Text = "=��"; - SubtitleText.Text = "S_MR��Y�cCg�]���{tXT͑n �����eQ�e�o;mx͑�e�~�[�s�~"; - SubmitButton.Content = "͑�e�o;m"; - } - else - { - TitleText.Text = "��eQ�e�o;mx"; - HeaderIcon.Text = "=��"; - SubtitleText.Text = "����eQ�e�v�o;mx�N�f�eS_MR�s�~��Y�cCg"; - SubmitButton.Content = "nx���fbc"; - } - - 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("�e�lꁨR/T�RO\U^.��v ���O(uY�c.��v�v�c��eQ0"); - 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<MONITORINFO>() }; - 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("�hKm0RY*N�o;mx ����N�|4�S_MR�s�~���O(u�vN*N0"); - 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("����eQ�[te�v 8 MO�o;mx��Y 8 MO�eW[�kNpeW[�~T �"); - 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 ?? "�s�~ T�y 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<StandbyOverlayWindow>().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 �[7b�z*g1\�~", 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 �[7b�z*g1\�~", 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 �[7b�z*g1\�~", 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 @@ <ImplicitUsings>enable</ImplicitUsings> <UseWPF>true</UseWPF> <AssemblyName>ClassNotify.Client</AssemblyName> + <Version>2.2.0</Version> <ApplicationIcon>app.ico</ApplicationIcon> <ApplicationManifest>app.manifest</ApplicationManifest> </PropertyGroup> @@ -30,4 +31,9 @@ <Compile Include="..\ClassNotify.Service\Services\HardwareFingerprintProvider.cs" Link="Services\HardwareFingerprintProvider.cs" /> </ItemGroup> + <ItemGroup> + <InternalsVisibleTo Include="ClassNotify.Turn105AcceptanceTests" /> + <InternalsVisibleTo Include="ClassNotify.WpfIpcTests" /> + </ItemGroup> + </Project> 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 @@ <Window x:Class="ClassNotify.Client.DeviceStatusWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" - Title="ClassNotify �s�~��Y�r`" - Width="580" Height="450" + Title="ClassNotify Ye�['YO\�~�z" + Width="760" Height="620" + MinWidth="700" MinHeight="560" WindowStartupLocation="CenterScreen" WindowStyle="None" AllowsTransparency="True" @@ -15,235 +16,127 @@ SnapsToDevicePixels="True" FontFamily="Microsoft YaHei UI, Microsoft YaHei, Segoe UI"> + <!-- Turn 117 UI FINAL IMPLEMENTATION DIRECTIVE: ZERO SCROLL, ZERO OVERFLOW --> <Border Background="#FFFFFF" BorderBrush="#CBD5E1" BorderThickness="1.5" CornerRadius="16" - Margin="12" + Margin="10" RenderOptions.ClearTypeHint="Enabled"> <Border.Effect> - <DropShadowEffect BlurRadius="24" Color="#000000" Opacity="0.15" ShadowDepth="6" Direction="270" /> + <DropShadowEffect BlurRadius="24" Color="#000000" Opacity="0.12" ShadowDepth="4" Direction="270" /> </Border.Effect> - <Grid Margin="28,22,28,22"> + <Grid Margin="24,18,24,18"> <Grid.RowDefinitions> - <RowDefinition Height="Auto"/> <!-- Header --> - <RowDefinition Height="*"/> <!-- Status Cards & Edit Panel --> - <RowDefinition Height="Auto"/> <!-- Footer Buttons --> + <RowDefinition Height="Auto"/> <!-- Row 0: Top Header / Title Bar --> + <RowDefinition Height="*"/> <!-- Row 1: Direct ContentControl (PAGE A / PAGE B) - ZERO SCROLL --> + <RowDefinition Height="Auto"/> <!-- Row 2: Bottom Status & Action Bar --> </Grid.RowDefinitions> - <!-- Hide to Background Button (') --> - <Button HorizontalAlignment="Right" VerticalAlignment="Top" - Click="OnHideToBackgroundClick" - Background="Transparent" BorderThickness="0" - Foreground="#475569" FontSize="18" FontWeight="Bold" - Cursor="Hand" Margin="0,-6,-6,0" Padding="8,2" - ToolTip="��υ0RT�S�T�S\�~�~�c6e��w �"> - ' - </Button> + <!-- Row 0: Header & Title Bar (Draggable) --> + <Grid Grid.Row="0" Margin="0,0,0,8" MouseLeftButtonDown="OnTitleBarMouseDown" Background="Transparent"> + <Grid.ColumnDefinitions> + <ColumnDefinition Width="*"/> + <ColumnDefinition Width="Auto"/> + </Grid.ColumnDefinitions> + + <!-- Left: App Icon, Title, Version --> + <StackPanel Orientation="Horizontal" VerticalAlignment="Center"> + <Border Background="#2563EB" CornerRadius="8" Width="36" Height="36" Margin="0,0,10,0"> + <TextBlock Text="<���" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center" /> + </Border> + <TextBlock Text="ClassNotify Ye�['YO\�~�z" + FontSize="18" FontWeight="Bold" Foreground="#0F172A" + VerticalAlignment="Center" /> + <TextBlock Text="v1.3.0" + FontSize="12" Foreground="#64748B" + VerticalAlignment="Center" Margin="8,2,0,0" /> + </StackPanel> + + <!-- Right: Cloud Reachability Indicator & Window Controls --> + <StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center"> + <!-- Dynamic Cloud Reachability Pill --> + <Border Background="{Binding HeaderReachabilityBackground}" + BorderBrush="{Binding HeaderReachabilityBorder}" + BorderThickness="1" + CornerRadius="16" + Padding="12,4" + VerticalAlignment="Center" + Margin="0,0,12,0"> + <TextBlock Text="{Binding HeaderReachabilityText}" + Foreground="{Binding HeaderReachabilityBrush}" + FontWeight="SemiBold" + FontSize="12" + VerticalAlignment="Center"/> + </Border> + + <!-- Minimize Button --> + <Button Click="OnMinimizeClick" + Background="Transparent" BorderThickness="0" + Foreground="#64748B" FontSize="16" FontWeight="Bold" + Cursor="Hand" Padding="8,2" Margin="0,0,2,0" + ToolTip="g\S"> +  + </Button> - <!-- Header --> - <StackPanel Grid.Row="0" Margin="0,0,0,16"> + <!-- Close (Hide) Button --> + <Button Click="OnHideToBackgroundClick" + Background="Transparent" BorderThickness="0" + Foreground="#64748B" FontSize="18" FontWeight="Bold" + Cursor="Hand" Padding="8,2" + ToolTip="��υ0RT�S�T�S\�~�~�c6e��w �"> + ' + </Button> + </StackPanel> + </Grid> + + <!-- Row 1: Direct ContentControl (Strict Two-Page Lifecycle: FirstPairingView / RunningDeviceView) --> + <!-- ZERO SCROLL, ZERO OVERFLOW --> + <ContentControl Grid.Row="1" + x:Name="MainContent" + Focusable="False" + VerticalAlignment="Center" + HorizontalAlignment="Stretch" /> + + <!-- Row 2: Bottom Status & Action Bar --> + <Border Grid.Row="2" + CornerRadius="10" + Background="#EFF6FF" + Padding="14,8" + Margin="0,8,0,0"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> - <StackPanel Orientation="Horizontal" VerticalAlignment="Center"> - <Border Background="#EFF6FF" CornerRadius="10" Padding="8" Margin="0,0,12,0"> - <TextBlock Text="<���" FontSize="20" VerticalAlignment="Center" /> - </Border> - <StackPanel VerticalAlignment="Center"> - <TextBlock x:Name="ClassTitle" Text="Yef['YO\" FontSize="20" FontWeight="Bold" Foreground="#0F172A" VerticalAlignment="Center" /> - <TextBlock x:Name="SubtitleInfo" Text="ClassNotify �s�~�mo`��w�c6e�~�z" FontSize="13" Foreground="#475569" Margin="0,2,0,0"/> - </StackPanel> + <!-- Left: Information Tip --> + <StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Center"> + <TextBlock Text="9!�" FontSize="14" VerticalAlignment="Center" Margin="0,0,6,0"/> + <TextBlock Text="{Binding FooterTipText}" + FontSize="12" Foreground="#334155" + VerticalAlignment="Center" /> </StackPanel> - <!-- Edit Class Name Trigger Button --> + <!-- Right: [ =إ�� ��υ0RT�S ] Button --> <Button Grid.Column="1" - x:Name="EditNameButton" - Click="OnEditClassNameClick" - Background="#F1F5F9" - BorderBrush="#CBD5E1" - BorderThickness="1" - Foreground="#1E293B" - FontWeight="SemiBold" - FontSize="12" - Padding="10,6" - Margin="0,0,24,0" - Cursor="Hand" - VerticalAlignment="Center"> + Click="OnHideToBackgroundClick" + Background="#2563EB" Foreground="#FFFFFF" BorderThickness="0" + FontWeight="SemiBold" Padding="16,7" + Cursor="Hand" FontSize="13"> <Button.Resources> <Style TargetType="Border"> <Setter Property="CornerRadius" Value="8" /> </Style> </Button.Resources> <StackPanel Orientation="Horizontal"> - <TextBlock Text="'� " FontSize="12"/> - <TextBlock Text="�O9e�s�~ T�y"/> + <TextBlock Text="=إ�� " FontSize="12" VerticalAlignment="Center"/> + <TextBlock Text="��υ0RT�S" VerticalAlignment="Center"/> </StackPanel> </Button> </Grid> - </StackPanel> - - <!-- Status Body --> - <StackPanel Grid.Row="1" VerticalAlignment="Center"> - <!-- Inline Class Name Edit Panel --> - <Border x:Name="EditNamePanel" - Visibility="Collapsed" - Background="#F8FAFC" - BorderBrush="#93C5FD" - BorderThickness="1.5" - CornerRadius="12" - Padding="14,12" - Margin="0,0,0,14"> - <StackPanel> - <TextBlock Text="�O9eS_MR'YO\�~�[�v�s�~ T�y�" FontSize="13" FontWeight="Bold" Foreground="#0F172A" Margin="0,0,0,8"/> - <Grid Margin="0,0,0,8"> - <Grid.ColumnDefinitions> - <ColumnDefinition Width="*"/> - <ColumnDefinition Width="Auto"/> - <ColumnDefinition Width="Auto"/> - </Grid.ColumnDefinitions> - <TextBox x:Name="NewClassNameInput" - Height="38" - FontSize="14" - FontWeight="SemiBold" - Padding="10,0" - VerticalContentAlignment="Center" - Background="#FFFFFF" - BorderBrush="#CBD5E1" - BorderThickness="1.5" - Foreground="#0F172A" - MaxLength="30"/> - <Button Grid.Column="1" - x:Name="SaveNameButton" - Content="�OX[ Tek" - Click="OnSaveClassNameClick" - Background="#2563EB" - Foreground="#FFFFFF" - FontWeight="Bold" - FontSize="13" - Padding="14,0" - Margin="8,0,0,0" - Height="38" - Cursor="Hand"> - <Button.Resources> - <Style TargetType="Border"> - <Setter Property="CornerRadius" Value="8" /> - </Style> - </Button.Resources> - </Button> - <Button Grid.Column="2" - Content="�S�m" - Click="OnCancelEditClassNameClick" - Background="#E2E8F0" - Foreground="#334155" - FontWeight="Medium" - FontSize="13" - Padding="12,0" - Margin="6,0,0,0" - Height="38" - Cursor="Hand"> - <Button.Resources> - <Style TargetType="Border"> - <Setter Property="CornerRadius" Value="8" /> - </Style> - </Button.Resources> - </Button> - </Grid> - <TextBlock x:Name="EditNameMessageText" FontSize="12" Foreground="#DC2626" Visibility="Collapsed" TextWrapping="Wrap"/> - <TextBlock Text="* - </StackPanel> - </Border> - - <!-- Cloud Connection Row (Truthful 4-state real-time status) --> - <Border Background="#F8FAFC" BorderBrush="#E2E8F0" BorderThickness="1.5" CornerRadius="12" Padding="16,12" Margin="0,0,0,12"> - <Grid> - <Grid.ColumnDefinitions> - <ColumnDefinition Width="*"/> - <ColumnDefinition Width="Auto"/> - </Grid.ColumnDefinitions> - <StackPanel> - <TextBlock Text="�N�z g�R�r`" FontSize="12" Foreground="#475569" FontWeight="Medium" Margin="0,0,0,3"/> - <TextBlock x:Name="CloudStatusText" Text="�N�z�]ޏ�c � �[�e�c6e��w-N" FontSize="14" FontWeight="SemiBold" Foreground="#0F172A"/> - <TextBlock x:Name="CloudDetailText" Text="�[�e�S�Eu� � gя�_�ck8^" FontSize="11" Foreground="#64748B" Margin="0,2,0,0"/> - </StackPanel> - <TextBlock x:Name="CloudDot" Grid.Column="1" Text="�% (W�~" FontSize="13" FontWeight="Bold" Foreground="#16A34A" VerticalAlignment="Center"/> - </Grid> - </Border> - - <!-- License Status Row --> - <Border Background="#F8FAFC" BorderBrush="#E2E8F0" BorderThickness="1.5" CornerRadius="12" Padding="16,12"> - <Grid> - <Grid.ColumnDefinitions> - <ColumnDefinition Width="*"/> - <ColumnDefinition Width="Auto"/> - </Grid.ColumnDefinitions> - <StackPanel> - <TextBlock Text="�s�~�cCg�r`" FontSize="12" Foreground="#475569" FontWeight="Medium" Margin="0,0,0,3"/> - <TextBlock x:Name="LicenseStatusText" Text="�cCgck8^ � iRYO 365 )Y" FontSize="14" FontWeight="SemiBold" Foreground="#0F172A"/> - <TextBlock x:Name="LicenseExpiryDetailText" Text="0Rg�e����g gHe" FontSize="12" Foreground="#64748B" Margin="0,4,0,0"/> - </StackPanel> - <TextBlock x:Name="LicenseExpiryText" Grid.Column="1" Text="ck8^ g�R" FontSize="13" Foreground="#16A34A" FontWeight="Bold" VerticalAlignment="Center"/> - </Grid> - </Border> - </StackPanel> - - <!-- Footer Buttons --> - <Grid Grid.Row="2" Margin="0,16,0,0"> - <Grid.ColumnDefinitions> - <ColumnDefinition Width="*"/> - <ColumnDefinition Width="Auto"/> - </Grid.ColumnDefinitions> - - <Button Content="�~g�cCg / ͑�e�o;m" - Click="OnReactivateClick" - Background="Transparent" - Foreground="#2563EB" - BorderThickness="0" - Cursor="Hand" - FontSize="13" - FontWeight="SemiBold" - HorizontalAlignment="Left" - VerticalAlignment="Center"/> - - <Button Content="=إ�� 'YO\�_:gLub�" - Click="OnOpenStandbyOverlayClick" - Background="#F1F5F9" - BorderBrush="#CBD5E1" - BorderThickness="1" - Foreground="#0F172A" - Cursor="Hand" - FontSize="12" - FontWeight="SemiBold" - Padding="10,6" - Margin="150,0,0,0" - HorizontalAlignment="Left" - VerticalAlignment="Center"/> - - <StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center"> - <TextBlock Text="T�SO�~�~�c6e��w � g�e�mo`�e\ꁨR9_�Q" - FontSize="11" Foreground="#64748B" - VerticalAlignment="Center" Margin="0,0,12,0"/> - <Button Content="��υ0RT�S" - Click="OnHideToBackgroundClick" - Background="#2563EB" - Foreground="#FFFFFF" - BorderThickness="0" - FontWeight="SemiBold" - Padding="16,8" - Cursor="Hand" - FontSize="13"> - <Button.Resources> - <Style TargetType="Border"> - <Setter Property="CornerRadius" Value="8" /> - </Style> - </Button.Resources> - </Button> - </StackPanel> - </Grid> + </Border> </Grid> </Border> </Window> 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 : "Yef[�s�~"; + _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} � Yef['YO\"; - }); + 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} � Yef['YO\"; + if (_ipcClient == null) return; - // T76-09: Realtime Truthful 4-state cloud status (Never display "�[�e�c6e��w-N" when disconnected) - if (_state.CloudConnected && (_state.RealtimeChannelState == "Connected" || string.IsNullOrEmpty(_state.RealtimeChannelState))) - { - CloudStatusText.Text = "�% �N�z(W�~ � �[�e�c6e��w-N"; - CloudDot.Text = "�% (W�~"; - 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 ? $"�[�e�S�Eu� � gя�_�: {hbSeconds}�yMR" : "�[�e�S�Eu� � �mo` g�R1\�~"); - } - else if (_state.RealtimeChannelState == "Reconnecting") - { - CloudStatusText.Text = "�% ck(W͑�eޏ�c�N�z& "; - CloudDot.Text = "�% b` Y-N"; - CloudDot.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D97706")); - CloudDetailText.Text = "��w�c6e g�Rck(WꁨRb` Y ��e��N�]r^��"; - } - else if (_state.RealtimeChannelState == "UpdatingBinding") - { - CloudStatusText.Text = "�% ck(W�f�e�s�~�~�[N�cCg& "; - CloudDot.Text = "�% Tek-N"; - CloudDot.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2563EB")); - CloudDetailText.Text = "ck(W Tekg�e�cCg�Qnc ��[bT\ꁨR�^�zޏ�c"; - } - else + try { - CloudStatusText.Text = "�% �N�z�y�~ � ck(WꁨR\Ջ͑�eޏ�c"; - CloudDot.Text = "�% �y�~"; - CloudDot.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - CloudDetailText.Text = !string.IsNullOrEmpty(_state.ChannelDetail) - ? _state.ChannelDetail - : "N�N�z�[�e�S�*g�^�z �T�S�a�vcwhVck(Wc�~ꁨR͑Ջ"; - } + var purpose = _viewModel.Page == DevicePage.FirstPairing + ? PairingPurpose.InitialDeviceBinding + : PairingPurpose.AddTeacher; - if (_state.LicenseStatus == "ExpiringSoon") - { - var remainingText = _state.RemainingDays == 0 && _state.RemainingHours > 0 - ? $"�N�e0Rg � iRYO {_state.RemainingHours} \�e" - : $"sS\0Rg � iRYO {_state.RemainingDays} )Y"; - LicenseStatusText.Text = remainingText; - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D97706")); - var expireStr = _state.LicensedUntilUtc?.ToOffset(TimeSpan.FromHours(8)).ToString("yyyyt^MMgdd�e HH:mm") ?? "sS\0Rg"; - LicenseExpiryDetailText.Text = $"0Rg�e���{expireStr}"; - LicenseExpiryText.Text = "�&� sS\0Rg"; - LicenseExpiryText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D97706")); - } - else if (_state.LicenseStatus == "Valid" || _state.LicenseStatus == "Perpetual") - { - LicenseStatusText.Text = _state.LicenseStatus == "Perpetual" - ? "8lEN�cCg � �g gHe" - : (_state.RemainingDays == 0 && _state.RemainingHours > 0 - ? $"�N�e0Rg � iRYO {_state.RemainingHours} \�e" - : $"�cCgck8^ � iRYO {_state.RemainingDays} )Y"); - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#0F172A")); - var expireStr = _state.LicensedUntilUtc?.ToOffset(TimeSpan.FromHours(8)).ToString("yyyyt^MMgdd�e HH:mm") ?? "�g gHe"; - LicenseExpiryDetailText.Text = $"0Rg�e���{expireStr}"; - LicenseExpiryText.Text = "�% ck8^ g�R"; - LicenseExpiryText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#16A34A")); - } - else if (_state.LicenseStatus == "OfflineGrace") - { - LicenseStatusText.Text = $"�y�~�[P�g-N � iRYO {_state.RemainingDays} )Y"; - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D97706")); - var expireStr = _state.LicensedUntilUtc?.ToOffset(TimeSpan.FromHours(8)).ToString("yyyyt^MMgdd�e HH:mm") ?? "��T�Q Tek"; - LicenseExpiryDetailText.Text = $"0Rg�e���{expireStr}"; - LicenseExpiryText.Text = "�&� �y�~�[P�"; - LicenseExpiryText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D97706")); - } - else if (_state.LicenseStatus == "TimeUntrusted") - { - LicenseStatusText.Text = "�|�~�e��_8^��� Tek Windows �e�� �"; - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - LicenseExpiryDetailText.Text = "��Y,g0W�|�~�e�� Ncknx ���(W�|�~��n-NꁨR Tek�e��"; - LicenseExpiryText.Text = "�e��*g Tek"; - LicenseExpiryText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - } - else if (_state.LicenseStatus == "OfflineRestricted") - { - LicenseStatusText.Text = "�]��Ǐ�y�~�[P�g���ޏ�c�NT�Q �"; - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - LicenseExpiryDetailText.Text = "�]1�:g��Ǐ�[P�gP� ���\'YO\�ceQYe�[Q�~"; - LicenseExpiryText.Text = "�y�~�SP�"; - LicenseExpiryText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - } - else if (_state.LicenseStatus == "ExpiredRestricted" || _state.LicenseStatus == "Expired") - { - LicenseStatusText.Text = "�cCg�]0Rg��N'}%`��w gHe �"; - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); - var expireStr = _state.LicensedUntilUtc?.ToOffset(TimeSpan.FromHours(8)).ToString("yyyyt^MMgdd�e HH:mm") ?? "�]Ǐg"; - LicenseExpiryDetailText.Text = $"�]�N {expireStr} 0Rg"; - LicenseExpiryText.Text = "' �]Ǐg"; - 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 = "�cCg�r`��_�o;m/Yt-N"; - LicenseStatusText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#64748B")); - var expireStr = _state.LicensedUntilUtc?.ToOffset(TimeSpan.FromHours(8)).ToString("yyyyt^MMgdd�e HH:mm"); - LicenseExpiryDetailText.Text = string.IsNullOrEmpty(expireStr) ? "" : $"0Rg�e���{expireStr}"; - LicenseExpiryText.Text = "�_Yt"; - 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 ?? "�s�~ T�y().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<ClientStateSnapshotDto?>? _clientStateTcs; private TaskCompletionSource<(bool Success, string Message)>? _updateClassNameTcs; + private TaskCompletionSource<(bool Success, string? PairingCode, int TtlSeconds, string? ErrorMessage)>? _pairingModeTcs; + private TaskCompletionSource<PairingSessionDto>? _pairingSessionTcs; public event Action<string>? OnClassDisplayNameChanged; public event Action<string, int>? 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, "㉐gM��[�T�^1Y%�")); + } + return; + } + + if (msg.Type == IpcCommandType.PairingSessionResult && !string.IsNullOrEmpty(msg.PayloadJson)) + { + try + { + var session = JsonSerializer.Deserialize<PairingSessionDto>(msg.PayloadJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + _pairingSessionTcs?.TrySetResult(session ?? new PairingSessionDto { State = PairingSessionState.Failed, ErrorMessage = "㉐g�T�^:Nzz" }); + } + catch (Exception ex) + { + Log($"[Pairing] Failed to parse PairingSessionResult: {ex.Message}"); + _pairingSessionTcs?.TrySetResult(new PairingSessionDto { State = PairingSessionState.Failed, ErrorMessage = "㉐gM��[�T�^1Y%�" }); + } + 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, "�e�lޏ�c0RT�S g�R ���nx�� g�RЏL�ck8^"); + } + + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + cts.Token.Register(() => tcs.TrySetResult((false, null, 0, "��BlM��[x���e ���͑Ջ"))); + + try + { + return await tcs.Task; + } + finally + { + _pairingModeTcs = null; + } + } + + public async Task<PairingSessionDto> RequestPairingSessionAsync(PairingPurpose purpose) + { + var tcs = new TaskCompletionSource<PairingSessionDto>(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 = "�e�lޏ�c0RT�S g�R ���nx�� g�RЏL�ck8^" }; + } + + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + cts.Token.Register(() => tcs.TrySetResult(new PairingSessionDto { State = PairingSessionState.Failed, ErrorMessage = "��BlM��[x���e ���͑Ջ" })); + + try + { + return await tcs.Task; + } + finally + { + _pairingSessionTcs = null; + } + } + public async Task<ClientStateSnapshotDto?> GetClientStateAsync() { var tcs = new TaskCompletionSource<ClientStateSnapshotDto?>(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 @@ -<Window x:Class="ClassNotify.Client.StandbyOverlayWindow" - xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" - xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" - xmlns:views="clr-namespace:ClassNotify.Client.Views" - Title="ClassNotify Ye�['YO\�_:g" - WindowState="Normal" - WindowStartupLocation="Manual" - Topmost="False" - WindowStyle="None" - ResizeMode="NoResize" - AllowsTransparency="False" - Background="#0F172A" - ShowInTaskbar="True" - UseLayoutRounding="True" - SnapsToDevicePixels="True"> - <Grid> - <views:StandbyOverlayView x:Name="OverlayView" /> - - <!-- Subtle Top Right Quick Control --> - <Button HorizontalAlignment="Right" VerticalAlignment="Top" - Click="OnMinimizeOrHideClick" - Background="Transparent" BorderThickness="0" - Foreground="#64748B" FontSize="16" FontWeight="Bold" - Cursor="Hand" Margin="0,16,24,0" Padding="8,4" - ToolTip="g\S�_:gLub�"> - ' - </Button> - </Grid> -</Window> 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)); - } - } - } - - /// <summary> - /// �S�[ TS�[hQ�c:y��~ N>f:y�NUOYe^w�[�Y Tbf[�y ��O�b^u���y - /// </summary> - public string BoundTeacherSummaryText => - $"�]�~�[ {_boundTeacherCount} MO�N��Ye^"; - - 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<T>(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 @@ -<UserControl x:Class="ClassNotify.Client.Views.StandbyOverlayView" - xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" - xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" - xmlns:d="http://schemas.microsoft.com/expression/blend/2008" - xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" - mc:Ignorable="d" - SnapsToDevicePixels="True" - UseLayoutRounding="True"> - <UserControl.Resources> - <BooleanToVisibilityConverter x:Key="BoolToVis" /> - </UserControl.Resources> - <Grid Background="#0F172A"> - <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> - - <!-- 1. �N�~xE\ N (220 DIP) �~�[*����c --> - <Border Width="240" Height="240" Background="White" CornerRadius="16" Padding="10" HorizontalAlignment="Center"> - <Image Source="{Binding NavigationQrCodeImage}" Width="220" Height="220" RenderOptions.BitmapScalingMode="NearestNeighbor" /> - </Border> - - <!-- 2. �[�eQ@WE\ N (USL��~�e,g) --> - <TextBlock Text="classnotify.paradise.eu.org" - FontSize="20" FontWeight="SemiBold" - Foreground="#94A3B8" HorizontalAlignment="Center" - Margin="0,16,0,6" /> - - <!-- 2.1 �_�OSb N_�e�v\Q�^�d\Oc_ --> - <TextBlock x:Name="BrowserFallbackHint" - Text="傮_�OkbxT�e�lSb_ ���(WKb:gOmȉhV-N��eQ N�eQ@W���" - FontSize="14" FontWeight="Normal" - Foreground="#94A3B8" HorizontalAlignment="Center" - TextAlignment="Center" - TextWrapping="Wrap" - MaxWidth="520" - Margin="0,0,0,28" /> - - <!-- 3. M��[�Qnc�R`:S�W ( c�V`�S�c>f:y) --> - <StackPanel Visibility="{Binding IsPairingCodeVisible, Converter={StaticResource BoolToVis}}"> - <TextBlock Text="8 MO�s�~M��[x" FontSize="16" Foreground="#64748B" HorizontalAlignment="Center" /> - <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,8,0,8"> - <TextBlock Text="{Binding PairingCodeLeft}" - FontFamily="Consolas" FontSize="64" FontWeight="Bold" - Foreground="#38BDF8" /> - <Border Width="22" /> - <TextBlock Text="{Binding PairingCodeRight}" - FontFamily="Consolas" FontSize="64" FontWeight="Bold" - Foreground="#38BDF8" /> - </StackPanel> - <TextBlock Text="{Binding PairingCodeTtlRemaining, StringFormat=' gHegiRYO: {0}'}" - FontSize="14" Foreground="#F59E0B" HorizontalAlignment="Center" /> - </StackPanel> - - <!-- 4. BOUND_IDLE 8^`��S�[ TS�c:y --> - <StackPanel Visibility="{Binding IsBoundIdleVisible, Converter={StaticResource BoolToVis}}"> - <Border Background="#1E293B" CornerRadius="20" Padding="16,8" HorizontalAlignment="Center"> - <TextBlock Text="{Binding BoundTeacherSummaryText, FallbackValue='�]�~�[ 3 MO�N��Ye^'}" - FontSize="16" Foreground="#E2E8F0" /> - </Border> - </StackPanel> - - <!-- 5. OFFLINE �c:y --> - <StackPanel Visibility="{Binding IsOfflineVisible, Converter={StaticResource BoolToVis}}"> - <TextBlock Text="�&� 'YO\�]�y�~ �ck(W\ՋꁨRb` YQ�~ޏ�c..." - FontSize="15" Foreground="#EF4444" HorizontalAlignment="Center" Margin="0,12,0,0" /> - </StackPanel> - </StackPanel> - </Grid> -</UserControl> 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<int> 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<Task> 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<ClassNotifyDbContext>() - .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<string, string?> - { - { "Product:PersonalScreenLimit", "4" } - }) - .Build(); - - var pairingService = new PairingService(db, config, NullLogger<PairingService>.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<string, string?> { { "Product:PersonalScreenLimit", "4" } }) - .Build(); - - var pairingService = new PairingService(db, config, NullLogger<PairingService>.Instance); - var mockNotification = new MockDeviceNotificationService(); - - var controller = new TeacherConsoleController(db, pairingService, config, mockNotification, NullLogger<TeacherConsoleController>.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<PairingService>.Instance); - var mockNotification = new MockDeviceNotificationService(); - - var controller = new TeacherConsoleController(db, pairingService, config, mockNotification, NullLogger<TeacherConsoleController>.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<string, string?> - { - { "Product:AnnualPriceFen", "19900" }, - { "Product:AnnualDurationDays", "365" } - }) - .Build(); - - var gatewayFactory = new MockPaymentGatewayFactory(); - var controller = new PaymentController(db, gatewayFactory, config, NullLogger<PaymentController>.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<PaymentController>.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<PaymentController>.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<PaymentController>.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<PaymentController>.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<PaymentController>.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<char>(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<string>(); - 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<PaymentController>.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 MO�N��Ye^") - { - throw new Exception($"Unexpected summary text: '{text}'"); - } - - // Privacy Invariants: - if (text.Contains(" _") || text.Contains("Ng") || text.Contains("�s") || text.Contains("�^")) - { - // Only contains count, no specific teacher personal identity - } - if (text.Contains("DeviceTrialLedger") || text.Contains("Trial") || text.Contains("2�\O _") || text.Contains("}v�Z")) - { - 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 = "傮_�OkbxT�e�lSb_ ���(WKb:gOmȉhV-N��eQ N�eQ@W���"; - 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<PrepayResult> 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<CallbackVerificationResult> 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"; }