From 01068bb24e1d95a4cd8ad8d4f6ce32757fdde736 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=89=E7=A7=8B?= <497055328@qq.com> Date: Wed, 14 Oct 2026 16:18:48 +0800 Subject: [PATCH] =?UTF-8?q?feat(training):=20=E6=8E=A5=E5=85=A5=E7=9C=9F?= =?UTF-8?q?=E5=AE=9E=E5=9F=B9=E8=AE=AD=E6=8E=A5=E5=8F=A3=E4=B8=8E=E5=AD=A6?= =?UTF-8?q?=E4=B9=A0=E7=AD=94=E9=A2=98=E6=81=A2=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- suixinkan/App/NetworkServices.swift | 4 + suixinkan/Core/Networking/APIClient.swift | 13 +- suixinkan/Core/Networking/APIRequest.swift | 1 + .../Home/Services/HomeRouteHandler.swift | 3 +- .../ViewModels/AllFunctionsViewModel.swift | 2 +- .../Home/ViewModels/HomeViewModel.swift | 6 +- .../Training/Models/TrainingAPIModels.swift | 720 ++++++++++++++++++ .../Training/Services/TrainingAPI.swift | 178 +++++ .../Services/TrainingDataService.swift | 128 ++++ .../TrainingPendingSubmissionStore.swift | 90 +++ .../TrainingRemoteExamViewModel.swift | 472 ++++++++++++ .../TrainingRemoteListViewModels.swift | 248 ++++++ .../TrainingRemoteReadingViewModel.swift | 444 +++++++++++ .../UI/Profile/ProfileViewController.swift | 1 + .../TrainingCenterViewController.swift | 75 +- .../TrainingCourseViewController.swift | 494 ++++++++++-- .../Training/TrainingExamViewController.swift | 194 +++-- .../TrainingResultViewController.swift | 137 +++- suixinkan/UI/Training/TrainingUI.swift | 31 + suixinkanTests/APIClientTests.swift | 107 +++ suixinkanTests/HomeViewModelTests.swift | 22 +- suixinkanTests/TrainingAPITests.swift | 261 +++++++ suixinkanTests/TrainingDataTestSupport.swift | 271 +++++++ suixinkanTests/TrainingFeatureTests.swift | 20 +- suixinkanTests/TrainingRemoteExamTests.swift | 604 +++++++++++++++ suixinkanTests/TrainingRemoteListTests.swift | 112 +++ .../TrainingRemoteReadingTests.swift | 491 ++++++++++++ suixinkanTests/TrainingUIRenderingTests.swift | 54 +- 28 files changed, 4945 insertions(+), 238 deletions(-) create mode 100644 suixinkan/Features/Training/Models/TrainingAPIModels.swift create mode 100644 suixinkan/Features/Training/Services/TrainingAPI.swift create mode 100644 suixinkan/Features/Training/Services/TrainingDataService.swift create mode 100644 suixinkan/Features/Training/Services/TrainingPendingSubmissionStore.swift create mode 100644 suixinkan/Features/Training/ViewModels/TrainingRemoteExamViewModel.swift create mode 100644 suixinkan/Features/Training/ViewModels/TrainingRemoteListViewModels.swift create mode 100644 suixinkan/Features/Training/ViewModels/TrainingRemoteReadingViewModel.swift create mode 100644 suixinkanTests/TrainingAPITests.swift create mode 100644 suixinkanTests/TrainingDataTestSupport.swift create mode 100644 suixinkanTests/TrainingRemoteExamTests.swift create mode 100644 suixinkanTests/TrainingRemoteListTests.swift create mode 100644 suixinkanTests/TrainingRemoteReadingTests.swift diff --git a/suixinkan/App/NetworkServices.swift b/suixinkan/App/NetworkServices.swift index bf0b929..599cdd8 100644 --- a/suixinkan/App/NetworkServices.swift +++ b/suixinkan/App/NetworkServices.swift @@ -18,6 +18,8 @@ final class NetworkServices { let homeAPI: HomeAPI let paymentAPI: PaymentAPI let offlineCollectionAPI: OfflineCollectionAPI + /// 正式培训资源 API,页面使用身份作用域工厂创建会话。 + let trainingAPI: TrainingAPI let taskAPI: TaskAPI let inviteAPI: InviteAPI let walletAPI: WalletAPI @@ -45,6 +47,7 @@ final class NetworkServices { homeAPI = HomeAPI(client: client) paymentAPI = PaymentAPI(client: client) offlineCollectionAPI = OfflineCollectionAPI(client: client) + trainingAPI = TrainingAPI(client: client) taskAPI = TaskAPI(client: client) inviteAPI = InviteAPI(client: client) walletAPI = WalletAPI(client: client) @@ -77,6 +80,7 @@ final class NetworkServices { homeAPI = HomeAPI(client: apiClient) paymentAPI = PaymentAPI(client: apiClient) offlineCollectionAPI = OfflineCollectionAPI(client: apiClient) + trainingAPI = TrainingAPI(client: apiClient) taskAPI = TaskAPI(client: apiClient) inviteAPI = InviteAPI(client: apiClient) walletAPI = WalletAPI(client: apiClient) diff --git a/suixinkan/Core/Networking/APIClient.swift b/suixinkan/Core/Networking/APIClient.swift index f1feca4..63aa342 100644 --- a/suixinkan/Core/Networking/APIClient.swift +++ b/suixinkan/Core/Networking/APIClient.swift @@ -234,6 +234,10 @@ final class APIClient { if !apiRequest.queryItems.isEmpty { components.queryItems = apiRequest.queryItems + // URLComponents 将 + 视为合法查询字符;PHP 表单式查询解析会把它当作空格。 + // 在已有百分号编码之后只替换字面 +,保留 %2B、空格和其他字符的原编码。 + components.percentEncodedQuery = components.percentEncodedQuery? + .replacingOccurrences(of: "+", with: "%2B") } guard let url = components.url else { @@ -301,7 +305,7 @@ final class APIClient { return payload } - /// 区分身份注销受限与凭证失效;150015 附带原请求 Token,便于忽略切换身份后的旧错误。 + /// 区分注销受限与凭证失效;已绑定会话时,旧 Token 的迟到错误不使新会话退出。 private func notifySessionErrorIfNeeded(for error: APIError, request: URLRequest) { if case .serverCode(150015, _) = error { guard let token = request.value(forHTTPHeaderField: "token"), !token.isEmpty else { return } @@ -313,6 +317,13 @@ final class APIClient { return } guard APIError.isAuthenticationExpired(error) else { return } + if let authTokenProvider { + let requestToken = request.value(forHTTPHeaderField: "token")? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let currentToken = authTokenProvider()? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + guard requestToken == currentToken else { return } + } notificationCenter.post(name: NotificationName.sessionDidExpire, object: nil) } diff --git a/suixinkan/Core/Networking/APIRequest.swift b/suixinkan/Core/Networking/APIRequest.swift index eec0166..9ece79c 100644 --- a/suixinkan/Core/Networking/APIRequest.swift +++ b/suixinkan/Core/Networking/APIRequest.swift @@ -9,6 +9,7 @@ import Foundation enum HTTPMethod: String { case get = "GET" case post = "POST" + case patch = "PATCH" case put = "PUT" case delete = "DELETE" } diff --git a/suixinkan/Features/Home/Services/HomeRouteHandler.swift b/suixinkan/Features/Home/Services/HomeRouteHandler.swift index 228bc64..4c6060e 100644 --- a/suixinkan/Features/Home/Services/HomeRouteHandler.swift +++ b/suixinkan/Features/Home/Services/HomeRouteHandler.swift @@ -21,7 +21,7 @@ enum HomeRouteHandler { return } - if uri != "pilot_controller", uri != "wallet", AppStore.shared.session.currentScenicId <= 0 { + if uri != "pilot_controller", uri != "wallet", uri != "/training", AppStore.shared.session.currentScenicId <= 0 { showToast("请先选择景区", from: viewController) return } @@ -40,6 +40,7 @@ enum HomeRouteHandler { case "message_center": viewController.navigationController?.pushViewController(MessageCenterViewController(), animated: true) case "/training": + guard AppStore.shared.session.accountType == .storeUser else { return } viewController.navigationController?.pushViewController(TrainingCenterViewController(), animated: true) case "space_settings": viewController.navigationController?.pushViewController(ProfileSpaceSettingsViewController(), animated: true) diff --git a/suixinkan/Features/Home/ViewModels/AllFunctionsViewModel.swift b/suixinkan/Features/Home/ViewModels/AllFunctionsViewModel.swift index c64ded5..6ccc71a 100644 --- a/suixinkan/Features/Home/ViewModels/AllFunctionsViewModel.swift +++ b/suixinkan/Features/Home/ViewModels/AllFunctionsViewModel.swift @@ -28,7 +28,7 @@ final class AllFunctionsViewModel { /// 加载全部功能并按常用配置拆分。 func loadFunctions() { let permissions = appStore.permissions.permissionItems() - let allMenus = HomeMenuCatalog.visibleMenus(from: permissions) + let allMenus = HomeMenuCatalog.visibleMenus(from: permissions).filter { $0.uri != "/training" || appStore.session.accountType == .storeUser } let accountScope = appStore.session.accountCachePrefix let roleCode = appStore.session.roleCode let savedURIs = commonMenuStore.savedCommonURIs(accountScope: accountScope, roleCode: roleCode) diff --git a/suixinkan/Features/Home/ViewModels/HomeViewModel.swift b/suixinkan/Features/Home/ViewModels/HomeViewModel.swift index 65f153b..de9ba5a 100644 --- a/suixinkan/Features/Home/ViewModels/HomeViewModel.swift +++ b/suixinkan/Features/Home/ViewModels/HomeViewModel.swift @@ -300,8 +300,10 @@ final class HomeViewModel { roleCode: roleCode ) - // 所有角色均可进入个人培训;培训名单仍由服务端授权。 - if let entry = HomeMenuCatalog.item(for: "/training"), + // 首期培训仅服务店铺账号;名单与操作资格由培训接口校验。 + if appStore.session.accountType != .storeUser { resolvedMenus.removeAll { $0.uri == "/training" } } + if appStore.session.accountType == .storeUser, + let entry = HomeMenuCatalog.item(for: "/training"), !resolvedMenus.contains(where: { $0.uri == entry.uri }) { resolvedMenus.append(entry) } diff --git a/suixinkan/Features/Training/Models/TrainingAPIModels.swift b/suixinkan/Features/Training/Models/TrainingAPIModels.swift new file mode 100644 index 0000000..bebf7aa --- /dev/null +++ b/suixinkan/Features/Training/Models/TrainingAPIModels.swift @@ -0,0 +1,720 @@ +import Foundation + +/// 培训契约日期解析;独立于全局网络解码器,兼容 RFC3339 的小数秒。 +enum TrainingAPIDateCodec { + /// 解析带时区的 RFC3339 日期,拒绝无时区字符串。 + static func decode(_ value: String) -> Date? { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + if let date = formatter.date(from: value) { return date } + formatter.formatOptions = [.withInternetDateTime] + return formatter.date(from: value) + } + + /// 按 RFC3339 编码日期,供测试和持久化使用。 + static func encode(_ date: Date) -> String { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return formatter.string(from: date) + } +} + +/// 必填 RFC3339 日期,业务属性直接读写 Date。 +@propertyWrapper +struct TrainingAPIDate: Codable, Equatable, Sendable { + var wrappedValue: Date + /// 从业务日期创建包装,保留 DTO 的普通成员初始化方式。 + init(wrappedValue: Date) { self.wrappedValue = wrappedValue } + /// 从契约字符串解码,格式错误不转换为虚假时间。 + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let raw = try container.decode(String.self) + guard let value = TrainingAPIDateCodec.decode(raw) else { + throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid RFC3339 training date") + } + wrappedValue = value + } + /// 编码为带时区字符串。 + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(TrainingAPIDateCodec.encode(wrappedValue)) + } +} + +/// 可空 RFC3339 日期;无有效期边界保持 nil,不使用本机时间代替。 +@propertyWrapper +struct TrainingAPIOptionalDate: Codable, Equatable, Sendable { + var wrappedValue: Date? + /// 从可空业务日期创建包装。 + init(wrappedValue: Date?) { self.wrappedValue = wrappedValue } + /// 解码 null 或 RFC3339 字符串。 + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if container.decodeNil() { wrappedValue = nil; return } + let raw = try container.decode(String.self) + guard let value = TrainingAPIDateCodec.decode(raw) else { + throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid RFC3339 training date") + } + wrappedValue = value + } + /// 编码可空日期。 + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + if let value = wrappedValue { try container.encode(TrainingAPIDateCodec.encode(value)) } + else { try container.encodeNil() } + } +} + +extension KeyedDecodingContainer { + /// 可选日期允许省略字段;分页的 server_time 并非每个资源都会返回。 + func decode(_ type: TrainingAPIOptionalDate.Type, forKey key: Key) throws -> TrainingAPIOptionalDate { + try decodeIfPresent(type, forKey: key) ?? TrainingAPIOptionalDate(wrappedValue: nil) + } +} + +extension TrainingLearnerStatus: Codable { + /// 将正式接口 pending 映射到页面已有的待考试状态。 + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + switch try container.decode(String.self) { + case "pending": self = .pendingExam + case "completed": self = .completed + default: throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unknown training learner status") + } + } + /// 输出正式接口状态,不使用本地 enum 的 pendingExam 字符串。 + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(apiValue) + } + /// 查询参数使用的正式状态值。 + var apiValue: String { self == .completed ? "completed" : "pending" } +} + +/// 游标分页;小节、附件、任务和成绩复用相同分页边界。 +struct TrainingCursorPage: Codable, Equatable, Sendable { + let items: [Item] + let nextCursor: String? + let hasMore: Bool + @TrainingAPIOptionalDate var serverTime: Date? + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case items + case nextCursor = "next_cursor" + case hasMore = "has_more" + case serverTime = "server_time" + } +} + +/// 概览最近成绩,只有首屏所需字段。 +struct TrainingLatestAttempt: Codable, Equatable, Sendable { + let id: String + let scoreHundredths: Int + @TrainingAPIDate var submittedAt: Date + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case id = "attempt_id" + case scoreHundredths = "score_hundredths" + case submittedAt = "submitted_at" + } +} + +/// 当前学员全部分配任务的概览统计。 +struct TrainingSummary: Codable, Equatable, Sendable { + let pendingCount: Int + let completedCount: Int + let latestAttempt: TrainingLatestAttempt? + @TrainingAPIDate var serverTime: Date + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case pendingCount = "pending_count" + case completedCount = "completed_count" + case latestAttempt = "latest_attempt" + case serverTime = "server_time" + } +} + +/// 任务列表中的本人阅读与操作资格,不包含草稿或成绩数组。 +struct TrainingLearningFlags: Codable, Equatable, Sendable { + let progressPercent: Int + let readingCompleted: Bool + let hasDraft: Bool + let canViewCourse: Bool + let canStudy: Bool + let canStartExam: Bool + let blockReason: String? + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case progressPercent = "progress_percent" + case readingCompleted = "reading_completed" + case hasDraft = "has_draft" + case canViewCourse = "can_view_course" + case canStudy = "can_study" + case canStartExam = "can_start_exam" + case blockReason = "block_reason" + } +} + +/// 任务摘要与快照引用;课程正文和试卷独立按需读取。 +struct TrainingTaskSummary: Codable, Equatable, Sendable { + let id: String + let title: String + let publisherName: String? + let mode: TrainingMode + let taskStatus: TrainingTaskStatus + let learnerStatus: TrainingLearnerStatus + @TrainingAPIOptionalDate var startAt: Date? + @TrainingAPIOptionalDate var endAt: Date? + let courseSnapshotID: String + let courseTitle: String + let paperSnapshotID: String? + let sectionCount: Int + let questionCount: Int + let passScore: Int? + let learning: TrainingLearningFlags + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case id = "task_id" + case title + case publisherName = "publisher_name" + case mode + case taskStatus = "task_status" + case learnerStatus = "learner_status" + case startAt = "start_at" + case endAt = "end_at" + case courseSnapshotID = "course_snapshot_id" + case courseTitle = "course_title" + case paperSnapshotID = "paper_snapshot_id" + case sectionCount = "section_count" + case questionCount = "question_count" + case passScore = "pass_score" + case learning + } +} + +/// 平铺任务详情,客户端以 summary 复用列表摘要。 +struct TrainingTaskDetail: Codable, Equatable, Sendable { + let summary: TrainingTaskSummary + let requiredReadingSeconds: Int + let readingRule: String + let scoring: String? + let serverTime: Date + + /// 使用已解码摘要和规则创建详情,便于纯逻辑测试。 + init(summary: TrainingTaskSummary, requiredReadingSeconds: Int, readingRule: String, scoring: String?, serverTime: Date) { + self.summary = summary + self.requiredReadingSeconds = requiredReadingSeconds + self.readingRule = readingRule + self.scoring = scoring + self.serverTime = serverTime + } + /// 从与摘要同一层的详情字段解码,避免要求不存在的 summary 对象。 + init(from decoder: Decoder) throws { + summary = try TrainingTaskSummary(from: decoder) + let container = try decoder.container(keyedBy: CodingKeys.self) + requiredReadingSeconds = try container.decode(Int.self, forKey: .requiredReadingSeconds) + readingRule = try container.decode(String.self, forKey: .readingRule) + scoring = try container.decodeIfPresent(String.self, forKey: .scoring) + serverTime = try container.decode(TrainingAPIDate.self, forKey: .serverTime).wrappedValue + } + /// 保持服务端平铺字段布局。 + func encode(to encoder: Encoder) throws { + try summary.encode(to: encoder) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(requiredReadingSeconds, forKey: .requiredReadingSeconds) + try container.encode(readingRule, forKey: .readingRule) + try container.encodeIfPresent(scoring, forKey: .scoring) + try container.encode(TrainingAPIDate(wrappedValue: serverTime), forKey: .serverTime) + } + /// 详情额外字段的契约映射。 + enum CodingKeys: String, CodingKey { + case requiredReadingSeconds = "required_reading_seconds" + case readingRule = "reading_rule" + case scoring + case serverTime = "server_time" + } +} + +/// 课程快照元信息,不含小节正文。 +struct TrainingCourseInfo: Codable, Equatable, Sendable { + let id: String + let title: String + let introduction: String + let sectionCount: Int + let attachmentCount: Int + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case id = "course_snapshot_id" + case title + case introduction + case sectionCount = "section_count" + case attachmentCount = "attachment_count" + } +} + +/// 冻结的小节目录项,序号从一开始。 +struct TrainingSectionInfo: Codable, Equatable, Sendable { + let id: String + let order: Int + let title: String + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case id = "section_id" + case order + case title + } +} + +/// 单节正式正文;HTML 按后端发布快照读取。 +struct TrainingSectionContent: Codable, Equatable, Sendable { + let id: String + let order: Int + let title: String + let contentHTML: String + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case id = "section_id" + case order + case title + case contentHTML = "content_html" + } +} + +/// 附件元信息,私有附件访问前单独申请授权链接。 +struct TrainingAttachmentInfo: Codable, Equatable, Sendable { + let id: String + let name: String + let mimeType: String + let sizeBytes: Int + let fileID: String + let downloadURL: URL? + @TrainingAPIOptionalDate var expiresAt: Date? + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case id = "attachment_id" + case name + case mimeType = "mime_type" + case sizeBytes = "size_bytes" + case fileID = "file_id" + case downloadURL = "download_url" + case expiresAt = "expires_at" + } +} + +/// 经当前任务授权的短期附件访问链接。 +struct TrainingAttachmentLink: Codable, Equatable, Sendable { + let id: String + let name: String + let url: URL + @TrainingAPIDate var expiresAt: Date + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case id = "attachment_id" + case name + case url + case expiresAt = "expires_at" + } +} + +/// 服务端权威进度与当前资格;不含课程、草稿答案或历史成绩。 +struct TrainingProgressSnapshot: Codable, Equatable, Sendable { + let taskID: String + let readingSeconds: Int + let requiredReadingSeconds: Int + let completedSectionCount: Int + let sectionCount: Int + let progressPercent: Int + let readingCompleted: Bool + let learnerStatus: TrainingLearnerStatus + @TrainingAPIOptionalDate var completedAt: Date? + let hasDraft: Bool + let canViewCourse: Bool + let canStudy: Bool + let canStartExam: Bool + let canRetry: Bool + let blockReason: String? + @TrainingAPIDate var serverTime: Date + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case taskID = "task_id" + case readingSeconds = "reading_seconds" + case requiredReadingSeconds = "required_reading_seconds" + case completedSectionCount = "completed_section_count" + case sectionCount = "section_count" + case progressPercent = "progress_percent" + case readingCompleted = "reading_completed" + case learnerStatus = "learner_status" + case completedAt = "completed_at" + case hasDraft = "has_draft" + case canViewCourse = "can_view_course" + case canStudy = "can_study" + case canStartExam = "can_start_exam" + case canRetry = "can_retry" + case blockReason = "block_reason" + case serverTime = "server_time" + } +} + +/// 阅读会话、上报规则及创建时已保存进度。 +struct TrainingStudySession: Codable, Equatable, Sendable { + let sessionID: String + @TrainingAPIDate var expiresAt: Date + let heartbeatIntervalSeconds: Int + let maxHeartbeatGapSeconds: Int + let progress: TrainingProgressSnapshot + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case sessionID = "session_id" + case expiresAt = "expires_at" + case heartbeatIntervalSeconds = "heartbeat_interval_seconds" + case maxHeartbeatGapSeconds = "max_heartbeat_gap_seconds" + case progress + } +} + +/// 幂等阅读上报确认;累计秒数只用于当前会话。 +struct TrainingHeartbeatConfirmation: Codable, Equatable, Sendable { + let sessionID: String + let acceptedSequence: Int + let acceptedActiveSecondsTotal: Int + let sessionClosed: Bool + let progress: TrainingProgressSnapshot + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case sessionID = "session_id" + case acceptedSequence = "accepted_sequence" + case acceptedActiveSecondsTotal = "accepted_active_seconds_total" + case sessionClosed = "session_closed" + case progress + } +} + +/// 冻结试卷规则与题数,不携带全卷或正确答案。 +struct TrainingPaperInfo: Codable, Equatable, Sendable { + let id: String + let scoring: String + let questionCount: Int + let maxOptionsPerQuestion: Int + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case id = "paper_snapshot_id" + case scoring + case questionCount = "question_count" + case maxOptionsPerQuestion = "max_options_per_question" + } +} + +/// 考前选项,不透明 ID 按原值提交。 +struct TrainingQuestionOption: Codable, Equatable, Sendable { + let id: String + let text: String + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case id = "option_id" + case text + } +} + +/// 一题考前快照,不包含答案和解析。 +struct TrainingQuestionItem: Codable, Equatable, Sendable { + let id: String + let order: Int + let type: TrainingQuestionType + let stem: String + let options: [TrainingQuestionOption] + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case id = "question_id" + case order + case type + case stem + case options + } +} + +/// 按冻结题位随机访问的试题页。 +struct TrainingQuestionPage: Codable, Equatable, Sendable { + let paperSnapshotID: String + let total: Int + let offset: Int + let nextOffset: Int? + let hasMore: Bool + let items: [TrainingQuestionItem] + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case paperSnapshotID = "paper_snapshot_id" + case total + case offset + case nextOffset = "next_offset" + case hasMore = "has_more" + case items + } +} + +/// 固定题位范围内已保存的本人选择。 +struct TrainingDraftAnswerItem: Codable, Equatable, Sendable { + let questionID: String + let order: Int + let selectedOptionIDs: [String] + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case questionID = "question_id" + case order + case selectedOptionIDs = "selected_option_ids" + } +} + +/// 草稿版本、恢复位置、全部已答题号及当前题位答案页。 +struct TrainingDraftPage: Codable, Equatable, Sendable { + let taskID: String + let paperSnapshotID: String + let draftRevision: Int + @TrainingAPIOptionalDate var savedAt: Date? + let lastQuestionOrder: Int + let answeredCount: Int + let answeredQuestionOrders: [Int] + let total: Int + let offset: Int + let nextOffset: Int? + let hasMore: Bool + let items: [TrainingDraftAnswerItem] + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case taskID = "task_id" + case paperSnapshotID = "paper_snapshot_id" + case draftRevision = "draft_revision" + case savedAt = "saved_at" + case lastQuestionOrder = "last_question_order" + case answeredCount = "answered_count" + case answeredQuestionOrders = "answered_question_orders" + case total + case offset + case nextOffset = "next_offset" + case hasMore = "has_more" + case items + } +} + +/// 增量保存中一题的完整选择集合,空数组取消该题作答。 +struct TrainingDraftChange: Codable, Equatable, Sendable { + let questionID: String + let selectedOptionIDs: [String] + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case questionID = "question_id" + case selectedOptionIDs = "selected_option_ids" + } +} + +/// 带乐观版本与幂等键的增量草稿请求。 +struct TrainingDraftSaveRequest: Codable, Equatable, Sendable { + let requestID: String + let paperSnapshotID: String + let baseRevision: Int + let lastQuestionOrder: Int? + let changes: [TrainingDraftChange] + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case requestID = "request_id" + case paperSnapshotID = "paper_snapshot_id" + case baseRevision = "base_revision" + case lastQuestionOrder = "last_question_order" + case changes + } +} + +/// 用户明确重考时请求重置;重试沿用同一 requestID。 +struct TrainingDraftResetRequest: Codable, Equatable, Sendable { + let requestID: String + let paperSnapshotID: String + let baseRevision: Int + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case requestID = "request_id" + case paperSnapshotID = "paper_snapshot_id" + case baseRevision = "base_revision" + } +} + +/// 保存或重置后草稿实况;重置重试不能据此盲清本地答案。 +struct TrainingDraftConfirmation: Codable, Equatable, Sendable { + let draftRevision: Int + @TrainingAPIDate var savedAt: Date + let answeredCount: Int + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case draftRevision = "draft_revision" + case savedAt = "saved_at" + case answeredCount = "answered_count" + } +} + +/// 消费服务端已保存草稿版本的幂等交卷请求,不重新上传答案。 +struct TrainingSubmissionRequest: Codable, Equatable, Sendable { + let submissionID: String + let paperSnapshotID: String + let draftRevision: Int + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case submissionID = "submission_id" + case paperSnapshotID = "paper_snapshot_id" + case draftRevision = "draft_revision" + } +} + +/// 冻结成绩摘要;解析独立读取,资格由最新任务状态决定。 +struct TrainingAttemptSummary: Codable, Equatable, Sendable { + let id: String + let taskID: String + let taskTitle: String + let courseSnapshotID: String + let courseTitle: String + let paperSnapshotID: String + @TrainingAPIDate var submittedAt: Date + let scoreHundredths: Int + let correctCount: Int + let questionCount: Int + let passScore: Int + let passed: Bool + let reviewAvailable: Bool + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case id = "attempt_id" + case taskID = "task_id" + case taskTitle = "task_title" + case courseSnapshotID = "course_snapshot_id" + case courseTitle = "course_title" + case paperSnapshotID = "paper_snapshot_id" + case submittedAt = "submitted_at" + case scoreHundredths = "score_hundredths" + case correctCount = "correct_count" + case questionCount = "question_count" + case passScore = "pass_score" + case passed + case reviewAvailable = "review_available" + } +} + +extension TrainingAttemptSummary { + /// 百分之一分整数转为最多两位小数的展示分数,不改变通过判断。 + var scoreText: String { + let whole = scoreHundredths / 100 + let fraction = scoreHundredths % 100 + if fraction == 0 { return String(whole) } + let digits = String(format: "%02d", fraction) + return "\(whole).\(fraction.isMultiple(of: 10) ? String(digits.prefix(1)) : digits)" + } +} + +/// 成绩页面使用的最新本人任务操作资格。 +struct TrainingTaskState: Codable, Equatable, Sendable { + let learnerStatus: TrainingLearnerStatus + @TrainingAPIOptionalDate var completedAt: Date? + let canRetry: Bool + let blockReason: String? + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case learnerStatus = "learner_status" + case completedAt = "completed_at" + case canRetry = "can_retry" + case blockReason = "block_reason" + } +} + +/// 单次历史成绩与最新重考资格,不含解析。 +struct TrainingAttemptDetail: Codable, Equatable, Sendable { + let attempt: TrainingAttemptSummary + let taskState: TrainingTaskState + @TrainingAPIDate var serverTime: Date + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case attempt + case taskState = "task_state" + case serverTime = "server_time" + } +} + +/// 原子交卷结果,直接显示成绩摘要并更新草稿版本。 +struct TrainingSubmissionResult: Codable, Equatable, Sendable { + let attempt: TrainingAttemptSummary + let taskState: TrainingTaskState + let draftRevision: Int + @TrainingAPIDate var serverTime: Date + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case attempt + case taskState = "task_state" + case draftRevision = "draft_revision" + case serverTime = "server_time" + } +} + +/// 本次考试冻结的题目、本人答案和考后解析。 +struct TrainingReviewItem: Codable, Equatable, Sendable { + let id: String + let order: Int + let type: TrainingQuestionType + let stem: String + let options: [TrainingQuestionOption] + let selectedOptionIDs: [String] + let correctOptionIDs: [String] + let isCorrect: Bool + let explanation: String + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case id = "question_id" + case order + case type + case stem + case options + case selectedOptionIDs = "selected_option_ids" + case correctOptionIDs = "correct_option_ids" + case isCorrect = "is_correct" + case explanation + } +} + +/// 成绩解析游标页,每次只读取最多十题。 +struct TrainingReviewPage: Codable, Equatable, Sendable { + let attemptID: String + let items: [TrainingReviewItem] + let nextCursor: String? + let hasMore: Bool + + /// 正式接口字段映射。 + enum CodingKeys: String, CodingKey { + case attemptID = "attempt_id" + case items + case nextCursor = "next_cursor" + case hasMore = "has_more" + } +} diff --git a/suixinkan/Features/Training/Services/TrainingAPI.swift b/suixinkan/Features/Training/Services/TrainingAPI.swift new file mode 100644 index 0000000..30e54f5 --- /dev/null +++ b/suixinkan/Features/Training/Services/TrainingAPI.swift @@ -0,0 +1,178 @@ +import Foundation + +/// 正式培训 API,显式在主 Actor 协调网络及登录上下文,不加载无关子资源。 +@MainActor +final class TrainingAPI: TrainingDataServing { + private let client: APIClient + private let tokenOverride: String? + private let eligible: Bool + private let validateContext: (@MainActor () -> Bool)? + private let prefix = "/api/app/training" + + /// 注入网络客户端;正式页面通过工厂固定本次身份,测试可单独注入校验。 + init(client: APIClient, tokenOverride: String? = nil, eligible: Bool = true, validateContext: (@MainActor () -> Bool)? = nil) { + self.client = client + self.tokenOverride = tokenOverride + self.eligible = eligible + self.validateContext = validateContext + } + + /// 为一次页面会话建立固定凭证及身份校验的数据源。 + func scoped(token: String, eligible: Bool, validateContext: @escaping @MainActor () -> Bool) -> TrainingAPI { + TrainingAPI(client: client, tokenOverride: token, eligible: eligible, validateContext: validateContext) + } + + /// GET /summary:读取本人统计。 + func summary() async throws -> TrainingSummary { try await read("/summary") } + + /// GET /tasks:状态和关键词只影响本次摘要页。 + func tasks(status: TrainingLearnerStatus?, keyword: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage { + var query = cursorQuery(cursor, limit: limit, maximum: 50) + if let status { query.append(item("learner_status", status.apiValue)) } + if !keyword.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { query.append(item("keyword", keyword)) } + return try await read("/tasks", query: query) + } + + /// GET /tasks/{id}:平铺任务规则,不读取正文或试卷。 + func task(id: String) async throws -> TrainingTaskDetail { try await read("/tasks/" + component(id)) } + + /// GET /courses/{id}:快照访问带本人 task_id。 + func course(id: String, taskID: String) async throws -> TrainingCourseInfo { + try await read("/courses/" + component(id), query: taskQuery(taskID)) + } + + /// GET /courses/{id}/sections:只读取目录页。 + func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage { + try await read("/courses/" + component(courseID) + "/sections", query: taskQuery(taskID) + cursorQuery(cursor, limit: limit, maximum: 50)) + } + + /// GET /courses/{id}/sections/{id}:只读取一个小节。 + func section(courseID: String, sectionID: String, taskID: String) async throws -> TrainingSectionContent { + try await read("/courses/" + component(courseID) + "/sections/" + component(sectionID), query: taskQuery(taskID)) + } + + /// GET /courses/{id}/attachments:只读取附件元信息页。 + func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage { + try await read("/courses/" + component(courseID) + "/attachments", query: taskQuery(taskID) + cursorQuery(cursor, limit: limit, maximum: 50)) + } + + /// GET /courses/{id}/attachments/{id}:获取短时授权访问地址。 + func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink { + try await read("/courses/" + component(courseID) + "/attachments/" + component(attachmentID), query: taskQuery(taskID)) + } + + /// GET /tasks/{id}/progress:读取已保存进度及资格。 + func progress(taskID: String) async throws -> TrainingProgressSnapshot { try await read("/tasks/" + component(taskID) + "/progress") } + + /// POST /tasks/{id}/study-sessions:幂等创建阅读会话。 + func startReading(taskID: String, requestID: String) async throws -> TrainingStudySession { + try await write(.post, "/tasks/" + component(taskID) + "/study-sessions", body: ReadingStartBody(requestID: requestID)) + } + + /// POST /study-sessions/{id}/heartbeat:确认当前会话读时,不自动生成新序号。 + func heartbeat(sessionID: String, sequence: Int, activeSecondsTotal: Int, final: Bool) async throws -> TrainingHeartbeatConfirmation { + try await write(.post, "/study-sessions/" + component(sessionID) + "/heartbeat", body: HeartbeatBody(sequence: sequence, activeSecondsTotal: activeSecondsTotal, final: final)) + } + + /// GET /papers/{id}:读取冻结计分规则。 + func paper(id: String, taskID: String) async throws -> TrainingPaperInfo { + try await read("/papers/" + component(id), query: taskQuery(taskID)) + } + + /// GET /papers/{id}/questions:按固定题位读取考前题目页。 + func questions(paperID: String, taskID: String, offset: Int, limit: Int) async throws -> TrainingQuestionPage { + try await read("/papers/" + component(paperID) + "/questions", query: taskQuery(taskID) + offsetQuery(offset, limit: limit, maximum: 20)) + } + + /// GET /tasks/{id}/draft:允许 limit=0 获取恢复位置和答题卡。 + func draft(taskID: String, offset: Int, limit: Int) async throws -> TrainingDraftPage { + try await read("/tasks/" + component(taskID) + "/draft", query: offsetQuery(offset, limit: limit, maximum: 100, minimum: 0)) + } + + /// PATCH /tasks/{id}/draft:只传变化题目的完整选择集合。 + func saveDraft(taskID: String, request: TrainingDraftSaveRequest) async throws -> TrainingDraftConfirmation { + try await write(.patch, "/tasks/" + component(taskID) + "/draft", body: request) + } + + /// POST /tasks/{id}/draft/reset:返回当前草稿实况,调用者按版本同步。 + func resetDraft(taskID: String, request: TrainingDraftResetRequest) async throws -> TrainingDraftConfirmation { + try await write(.post, "/tasks/" + component(taskID) + "/draft/reset", body: request) + } + + /// POST /tasks/{id}/submissions:消费已确认的草稿版本,不回传全部答案。 + func submit(taskID: String, request: TrainingSubmissionRequest) async throws -> TrainingSubmissionResult { + try await write(.post, "/tasks/" + component(taskID) + "/submissions", body: request) + } + + /// GET /attempts:任务筛选和提交恢复复用成绩分页接口。 + func attempts(taskID: String?, submissionID: String?, cursor: String?, limit: Int) async throws -> TrainingCursorPage { + var query = cursorQuery(cursor, limit: limit, maximum: 50) + if let taskID { query.append(item("task_id", taskID)) } + if let submissionID { query.append(item("submission_id", submissionID)) } + return try await read("/attempts", query: query) + } + + /// GET /attempts/{id}:单次成绩和最新重考资格。 + func attempt(id: String) async throws -> TrainingAttemptDetail { try await read("/attempts/" + component(id)) } + + /// GET /attempts/{id}/reviews:单页最多十条,不自动下载全部解析。 + func reviews(attemptID: String, cursor: String?, limit: Int) async throws -> TrainingReviewPage { + try await read("/attempts/" + component(attemptID) + "/reviews", query: cursorQuery(cursor, limit: limit, maximum: 10)) + } + + private func read(_ path: String, query: [URLQueryItem] = []) async throws -> Response { + try await perform(APIRequest(method: .get, path: prefix + path, queryItems: query, logsPayload: false)) + } + + private func write(_ method: HTTPMethod, _ path: String, body: Body) async throws -> Response { + try await perform(APIRequest(method: method, path: prefix + path, body: body, logsPayload: false)) + } + + private func perform(_ request: APIRequest) async throws -> Response { + try checkContext() + do { + let response = try await client.send(request, tokenOverride: tokenOverride) + try checkContext() + return response + } catch { + try checkContext() + throw TrainingRemoteError.map(error) + } + } + + private func checkContext() throws { + guard eligible else { throw TrainingRemoteError.accountInvalid("请切换到店铺账号后进入培训中心") } + guard validateContext?() != false else { throw TrainingRemoteError.identityChanged } + } + + nonisolated private func item(_ name: String, _ value: String) -> URLQueryItem { URLQueryItem(name: name, value: value) } + nonisolated private func taskQuery(_ id: String) -> [URLQueryItem] { [item("task_id", id)] } + nonisolated private func cursorQuery(_ cursor: String?, limit: Int, maximum: Int) -> [URLQueryItem] { + var query = [item("limit", String(min(max(limit, 1), maximum)))] + if let cursor, !cursor.isEmpty { query.append(item("cursor", cursor)) } + return query + } + nonisolated private func offsetQuery(_ offset: Int, limit: Int, maximum: Int, minimum: Int = 1) -> [URLQueryItem] { + [item("offset", String(max(offset, 0))), item("limit", String(min(max(limit, minimum), maximum)))] + } + nonisolated private func component(_ id: String) -> String { + id.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~"))) ?? id + } + + /// 阅读会话创建请求,幂等键由业务状态持久保留。 + private struct ReadingStartBody: Encodable { + let requestID: String + enum CodingKeys: String, CodingKey { case requestID = "request_id" } + } + + /// 会话心跳请求;累计读时为本会话范围。 + private struct HeartbeatBody: Encodable { + let sequence: Int + let activeSecondsTotal: Int + let final: Bool + enum CodingKeys: String, CodingKey { + case sequence, final + case activeSecondsTotal = "active_seconds_total" + } + } +} diff --git a/suixinkan/Features/Training/Services/TrainingDataService.swift b/suixinkan/Features/Training/Services/TrainingDataService.swift new file mode 100644 index 0000000..2a12456 --- /dev/null +++ b/suixinkan/Features/Training/Services/TrainingDataService.swift @@ -0,0 +1,128 @@ +import Foundation + +/// 正式培训数据源;各资源独立读取,不为页面拼接全量任务聚合。 +protocol TrainingDataServing: Sendable { + /// 获取当前学员全局统计。 + func summary() async throws -> TrainingSummary + /// 按状态和关键词读取任务摘要页。 + func tasks(status: TrainingLearnerStatus?, keyword: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage + /// 获取任务规则和快照引用。 + func task(id: String) async throws -> TrainingTaskDetail + /// 获取课程元信息,附当前授权任务。 + func course(id: String, taskID: String) async throws -> TrainingCourseInfo + /// 获取小节目录页。 + func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage + /// 读取一个小节的正式正文。 + func section(courseID: String, sectionID: String, taskID: String) async throws -> TrainingSectionContent + /// 读取附件元信息页。 + func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage + /// 获取短期附件授权链接。 + func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink + /// 刷新服务端已保存进度与操作资格。 + func progress(taskID: String) async throws -> TrainingProgressSnapshot + /// 按幂等键建立阅读会话。 + func startReading(taskID: String, requestID: String) async throws -> TrainingStudySession + /// 按会话序号确认有效读时;重试保持相同请求内容。 + func heartbeat(sessionID: String, sequence: Int, activeSecondsTotal: Int, final: Bool) async throws -> TrainingHeartbeatConfirmation + /// 读取考试规则,不获取全部试题。 + func paper(id: String, taskID: String) async throws -> TrainingPaperInfo + /// 按固定题位读取试题页。 + func questions(paperID: String, taskID: String, offset: Int, limit: Int) async throws -> TrainingQuestionPage + /// 获取草稿元信息及当前题位答案;limit=0 只读取元信息。 + func draft(taskID: String, offset: Int, limit: Int) async throws -> TrainingDraftPage + /// 串行增量保存本人选择。 + func saveDraft(taskID: String, request: TrainingDraftSaveRequest) async throws -> TrainingDraftConfirmation + /// 用户确认重考后重置草稿;响应是当前实况而非恒定空草稿。 + func resetDraft(taskID: String, request: TrainingDraftResetRequest) async throws -> TrainingDraftConfirmation + /// 消费已保存草稿版本并幂等交卷。 + func submit(taskID: String, request: TrainingSubmissionRequest) async throws -> TrainingSubmissionResult + /// 分页读取成绩;taskID+submissionID 可恢复一次交卷结果。 + func attempts(taskID: String?, submissionID: String?, cursor: String?, limit: Int) async throws -> TrainingCursorPage + /// 读取一条成绩和最新重考资格。 + func attempt(id: String) async throws -> TrainingAttemptDetail + /// 用户展开时读取解析页。 + func reviews(attemptID: String, cursor: String?, limit: Int) async throws -> TrainingReviewPage +} + +/// 培训稳定业务码及身份切换;保留服务器文案,恢复逻辑只依据枚举或 code。 +enum TrainingRemoteError: Error, LocalizedError, Equatable, Sendable { + case accountInvalid(String), forbidden(String), notWritable(String), readingRequired(String) + case sessionExpired(String), sessionConflict(String), draftRevisionConflict(String), idempotencyConflict(String) + case answerInvalid(String), answerIncomplete(String), examNotAllowed(String), contentMissing(String) + case attemptNotFound(String), paramInvalid(String), identityChanged + + /// 返回稳定业务码,身份切换属于本地拒绝,没有服务端 code。 + var code: Int? { + switch self { + case .accountInvalid: 150100 + case .forbidden: 150101 + case .notWritable: 150102 + case .readingRequired: 150103 + case .sessionExpired: 150104 + case .sessionConflict: 150105 + case .draftRevisionConflict: 150106 + case .idempotencyConflict: 150107 + case .answerInvalid: 150108 + case .answerIncomplete: 150109 + case .examNotAllowed: 150110 + case .contentMissing: 150111 + case .attemptNotFound: 150112 + case .paramInvalid: 150113 + case .identityChanged: nil + } + } + + /// 用于页面展示的错误文案,不参与错误分类。 + var errorDescription: String? { + switch self { + case let .accountInvalid(message), let .forbidden(message), let .notWritable(message), let .readingRequired(message), + let .sessionExpired(message), let .sessionConflict(message), let .draftRevisionConflict(message), + let .idempotencyConflict(message), let .answerInvalid(message), let .answerIncomplete(message), + let .examNotAllowed(message), let .contentMissing(message), let .attemptNotFound(message), let .paramInvalid(message): message + case .identityChanged: "学习账号或业务身份已切换,请重新进入培训中心" + } + } + + /// 转换培训业务错误;网络和真正登录失效错误仍保留原类型。 + static func map(_ error: Error) -> Error { + guard let apiError = error as? APIError, + case let .serverCode(code, message) = apiError else { return error } + switch code { + case 150100: return Self.accountInvalid(message) + case 150101: return Self.forbidden(message) + case 150102: return Self.notWritable(message) + case 150103: return Self.readingRequired(message) + case 150104: return Self.sessionExpired(message) + case 150105: return Self.sessionConflict(message) + case 150106: return Self.draftRevisionConflict(message) + case 150107: return Self.idempotencyConflict(message) + case 150108: return Self.answerInvalid(message) + case 150109: return Self.answerIncomplete(message) + case 150110: return Self.examNotAllowed(message) + case 150111: return Self.contentMissing(message) + case 150112: return Self.attemptNotFound(message) + case 150113: return Self.paramInvalid(message) + default: return error + } + } +} + +/// 生产数据源固定进入时的账号和业务上下文,拒绝切换身份后的迟到响应。 +enum TrainingRemoteServiceFactory { + /// 当前店铺身份才可接入;Token 与业务范围固定在本次页面会话。 + @MainActor static func production() -> any TrainingDataServing { + let session = AppStore.shared.session + let token = session.token + let scope = session.accountCachePrefix + let scenicID = session.currentScenicId + let storeID = session.currentStoreId + let eligible = !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + && session.accountType == .storeUser && !scope.isEmpty + return NetworkServices.shared.trainingAPI.scoped(token: token, eligible: eligible, validateContext: { + let current = AppStore.shared.session + return current.isLoggedIn && current.accountType == .storeUser + && current.accountCachePrefix == scope && current.token == token + && current.currentScenicId == scenicID && current.currentStoreId == storeID + }) + } +} diff --git a/suixinkan/Features/Training/Services/TrainingPendingSubmissionStore.swift b/suixinkan/Features/Training/Services/TrainingPendingSubmissionStore.swift new file mode 100644 index 0000000..c075292 --- /dev/null +++ b/suixinkan/Features/Training/Services/TrainingPendingSubmissionStore.swift @@ -0,0 +1,90 @@ +import Foundation + +/// 未确认交卷的原始请求及所属业务身份,供 App 重启后沿原键恢复。 +struct TrainingPendingSubmission: Codable, Equatable, Sendable { + let taskID: String + let request: TrainingSubmissionRequest + let accountScope: String + let scenicID: Int + let storeID: Int + + /// 固定本次提交的身份和请求,恢复时不读取新的草稿版本替换它。 + init(taskID: String, request: TrainingSubmissionRequest, context: TrainingContext) { + self.taskID = taskID + self.request = request + accountScope = context.accountScope + scenicID = context.scenicID + storeID = context.storeID + } + + /// 本次交卷的持久化作用域,不包含 Token。 + var context: TrainingContext { + TrainingContext(accountScope: accountScope, scenicID: scenicID, storeID: storeID) + } +} + +/// 待恢复记录损坏时停止生成新提交,避免重复成绩。 +enum TrainingPendingSubmissionError: Error, LocalizedError, Equatable, Sendable { + case invalidRecord, alreadyPending + + /// 告知用户尚不能安全恢复本次提交。 + var errorDescription: String? { + switch self { + case .invalidRecord: "上次交卷状态暂无法确认,请联系工作人员核查成绩后重试" + case .alreadyPending: "上次交卷尚未确认,请先恢复原提交结果" + } + } +} + +/// 按账号、景区、店铺和任务隔离待确认交卷,支持注入独立 UserDefaults 测试。 +final class TrainingPendingSubmissionStore { + private static let lock = NSRecursiveLock() + private let defaults: UserDefaults + + /// 使用指定的持久化域保存不含凭证的交卷请求。 + init(defaults: UserDefaults = .standard) { self.defaults = defaults } + + /// 当前店铺登录身份;与正式数据源一致,不要求景区 ID 大于零。 + @MainActor static func currentContext() -> TrainingContext? { + let session = AppStore.shared.session + guard session.isLoggedIn, session.accountType == .storeUser, !session.accountCachePrefix.isEmpty else { return nil } + return TrainingContext(accountScope: session.accountCachePrefix, scenicID: session.currentScenicId, storeID: session.currentStoreId) + } + + /// 读取当前作用域记录,损坏记录不当作首次交卷处理。 + func load(taskID: String, context: TrainingContext) throws -> TrainingPendingSubmission? { + Self.lock.lock() + defer { Self.lock.unlock() } + guard let data = defaults.data(forKey: key(taskID: taskID, context: context)) else { return nil } + guard let value = try? JSONDecoder().decode(TrainingPendingSubmission.self, from: data), + value.taskID == taskID, value.context == context, + !value.request.submissionID.isEmpty, !value.request.paperSnapshotID.isEmpty, + value.request.draftRevision > 0 else { throw TrainingPendingSubmissionError.invalidRecord } + return value + } + + /// 在发起网络提交前保存原始请求;不得用当前版本覆盖待恢复版本。 + func save(_ value: TrainingPendingSubmission) throws { + Self.lock.lock() + defer { Self.lock.unlock() } + if let existing = try load(taskID: value.taskID, context: value.context), existing != value { + throw TrainingPendingSubmissionError.alreadyPending + } + let storageKey = key(taskID: value.taskID, context: value.context) + defaults.set(try JSONEncoder().encode(value), forKey: storageKey) + } + + /// 只移除仍对应这次提交的记录,避免迟到响应删除后续待恢复请求。 + func remove(_ value: TrainingPendingSubmission) throws { + Self.lock.lock() + defer { Self.lock.unlock() } + guard try load(taskID: value.taskID, context: value.context) == value else { return } + defaults.removeObject(forKey: key(taskID: value.taskID, context: value.context)) + } + + private func key(taskID: String, context: TrainingContext) -> String { + let scope = Data(context.accountScope.utf8).map { String(format: "%02x", $0) }.joined() + let task = Data(taskID.utf8).map { String(format: "%02x", $0) }.joined() + return "training-pending-submission:v1:\(scope):scenic_\(context.scenicID):store_\(context.storeID):task_\(task)" + } +} diff --git a/suixinkan/Features/Training/ViewModels/TrainingRemoteExamViewModel.swift b/suixinkan/Features/Training/ViewModels/TrainingRemoteExamViewModel.swift new file mode 100644 index 0000000..4269fb9 --- /dev/null +++ b/suixinkan/Features/Training/ViewModels/TrainingRemoteExamViewModel.swift @@ -0,0 +1,472 @@ +import Foundation + +/// 分页考试状态;全局已答题号与当前页答案分离,交卷只消费服务端草稿版本。 +final class TrainingRemoteExamViewModel { + /// 固定的本人任务标识。 + let taskID: String + /// 已验证的轻量任务摘要。 + private(set) var task: TrainingTaskSummary? + /// 服务端当前考试资格。 + private(set) var progress: TrainingProgressSnapshot? + /// 冻结试卷规则与总题数。 + private(set) var paper: TrainingPaperInfo? + /// 当前展示题位,使用从零开始的索引。 + private(set) var currentIndex = 0 + /// 服务端确认的全部已答题号,题号从一开始。 + private(set) var answeredQuestionOrders: Set = [] + /// 最近确认的草稿版本,未加载前为零。 + private(set) var draftRevision = 0 + /// 当前操作期间阻止并发写入。 + private(set) var isBusy = false + /// 最近失败的展示文案,业务分支不依赖文案。 + private(set) var errorMessage: String? + /// 已提交或恢复的成绩,可直接进入成绩页面。 + private(set) var submittedAttempt: TrainingAttemptSummary? + /// 首次交卷返回的成绩及资格,成绩首屏可复用而无需等待额外请求。 + private(set) var submittedResult: TrainingAttemptDetail? + /// 账号不支持培训或任务无访问权限时返回培训中心,身份变化时退出到根页面。 + private(set) var shouldReturnToCenter = false + + private let pageSize: Int + private let pendingStore: TrainingPendingSubmissionStore + private let currentContext: @MainActor @Sendable () -> TrainingContext? + private var context: TrainingContext? + private var questionCache: [Int: TrainingQuestionItem] = [:] + private var answerCache: TrainingAnswers = [:] + private var loadedDraftIndices: Set = [] + private var pendingSubmission: TrainingPendingSubmission? + private var pendingMutation: DraftMutation? + private var initialResetRequested = false + private var needsDraftRefresh = false + private var recoveryStorageFailed = false + private var identityIsValid = true + + /// 未确认的草稿写入保持原请求 ID、版本和内容,不能被新的选择替换。 + private enum DraftMutation { + case save(TrainingDraftSaveRequest) + case reset(TrainingDraftResetRequest) + } + + /// 注入身份与持久化域,测试不访问全局登录态或网络。 + init(taskID: String, context: TrainingContext? = nil, pageSize: Int = 10, + pendingStore: TrainingPendingSubmissionStore = TrainingPendingSubmissionStore(), + currentContext: @escaping @MainActor @Sendable () -> TrainingContext? = { TrainingPendingSubmissionStore.currentContext() }) { + self.taskID = taskID + self.context = context + self.pageSize = min(20, max(1, pageSize)) + self.pendingStore = pendingStore + self.currentContext = currentContext + } + + /// 已知总题数,无需获取全部题目正文。 + var questionCount: Int { paper?.questionCount ?? 0 } + /// 全局已答数量,不把未下载的答案当成漏答。 + var answeredCount: Int { answeredQuestionOrders.count } + /// 当前已加载的题目。 + var currentQuestion: TrainingQuestionItem? { questionCache[currentIndex] } + /// 当前题已确认保存的选择。 + var currentSelectedIDs: Set { currentQuestion.flatMap { answerCache[$0.id] } ?? [] } + /// 第一处真正漏答的题位。 + var firstUnansweredIndex: Int? { + guard questionCount > 0 else { return nil } + return (1...questionCount).first { !answeredQuestionOrders.contains($0) }.map { $0 - 1 } + } + /// 存在未确认交卷时暂停编辑,直到恢复同一次结果。 + var hasPendingSubmission: Bool { pendingSubmission != nil } + /// 页面所属账号、景区或店铺已变化,不能继续显示原身份的数据。 + var isIdentityInvalid: Bool { !identityIsValid } + /// 草稿请求失败后只允许重试原操作。 + var hasPendingMutation: Bool { pendingMutation != nil } + /// 当前题正文和对应草稿范围均成功读取后,才可展示为可编辑答案。 + var isCurrentPageReady: Bool { currentQuestion != nil && loadedDraftIndices.contains(currentIndex) && !needsDraftRefresh } + /// 页读取或冲突后的恢复失败时,沿当前题位重试读取,保留其它页缓存。 + var canRetryCurrentPage: Bool { + !isBusy && identityIsValid && !hasPendingSubmission && !hasPendingMutation && !recoveryStorageFailed + && !shouldReturnToCenter && submittedAttempt == nil && paper != nil && !isCurrentPageReady + && progress?.canStartExam == true && progress?.learnerStatus != .completed + } + /// 只有权威资格允许且所有写入均确认后才能修改答案。 + var canEdit: Bool { + !isBusy && identityIsValid && !hasPendingSubmission && !hasPendingMutation && !needsDraftRefresh && !recoveryStorageFailed + && submittedAttempt == nil && progress?.canStartExam == true && progress?.learnerStatus != .completed + && !shouldReturnToCenter && paper != nil && isCurrentPageReady + } + + /// 返回已提交页面前再次核对身份,避免把缓存成绩显示给切换后的账号。 + func validateIdentity() async { + do { try await authorize() } + catch { report(error) } + } + + /// 恢复待确认提交优先于考试资格校验;正常加载只取恢复题位所在的一页。 + func load(service: any TrainingDataServing, resetDraft: Bool = false) async { + guard !isBusy else { return } + isBusy = true + errorMessage = nil + defer { isBusy = false } + do { + try await authorize() + guard let context else { throw TrainingRemoteError.identityChanged } + do { + pendingSubmission = try pendingStore.load(taskID: taskID, context: context) + recoveryStorageFailed = false + } catch { + recoveryStorageFailed = true + throw error + } + if pendingSubmission != nil { + _ = try await recoverSubmission(service: service) + return + } + if pendingMutation != nil { + try await performMutation(service: service) + return + } + let detail = try await service.task(id: taskID) + try await authorize() + let latestProgress = try await service.progress(taskID: taskID) + try await authorize() + task = detail.summary + progress = latestProgress + try requireExamAllowed() + guard let paperID = task?.paperSnapshotID else { throw TrainingError.invalidPaper } + let loadedPaper = try await service.paper(id: paperID, taskID: taskID) + try await authorize() + guard loadedPaper.id == paperID, (1...500).contains(loadedPaper.questionCount), + loadedPaper.scoring == TrainingTask.equalPercentageScoring else { throw TrainingError.invalidPaper } + if paper?.id != loadedPaper.id { questionCache = [:]; answerCache = [:]; loadedDraftIndices = [] } + paper = loadedPaper + let metadata = try await service.draft(taskID: taskID, offset: 0, limit: 0) + try await authorize() + try applyMetadata(metadata) + currentIndex = (1...questionCount).contains(metadata.lastQuestionOrder) ? metadata.lastQuestionOrder - 1 : 0 + if resetDraft, !initialResetRequested { + initialResetRequested = true + pendingMutation = .reset(TrainingDraftResetRequest(requestID: UUID().uuidString, paperSnapshotID: paperID, baseRevision: draftRevision)) + try await performMutation(service: service) + } else { + try await loadCurrentPage(service: service) + } + } catch { report(error) } + } + + /// 随机跳题直接获取所在页,并保存浏览位置;不遍历前面的题目页。 + func goToQuestion(_ index: Int, service: any TrainingDataServing) async { + guard canEdit, (0.. TrainingAttemptSummary? { + guard !isBusy, !hasPendingMutation, !recoveryStorageFailed else { return nil } + let wasEditable = canEdit + isBusy = true + errorMessage = nil + defer { isBusy = false } + do { + try await authorize() + if pendingSubmission != nil { return try await recoverSubmission(service: service) } + guard let context else { throw TrainingRemoteError.identityChanged } + if let persisted = try pendingStore.load(taskID: taskID, context: context) { + pendingSubmission = persisted + return try await recoverSubmission(service: service) + } + guard wasEditable, firstUnansweredIndex == nil else { + errorMessage = "还有 \(questionCount - answeredCount) 道题未作答" + return nil + } + try requireExamAllowed() + guard let paper else { throw TrainingError.invalidPaper } + let request = TrainingSubmissionRequest(submissionID: UUID().uuidString, paperSnapshotID: paper.id, draftRevision: draftRevision) + let pending = TrainingPendingSubmission(taskID: taskID, request: request, context: context) + do { try pendingStore.save(pending) } + catch TrainingPendingSubmissionError.alreadyPending { + pendingSubmission = try pendingStore.load(taskID: taskID, context: context) + return try await recoverSubmission(service: service) + } + pendingSubmission = pending + return try await sendSubmission(pending, service: service) + } catch { report(error); return nil } + } + + private func report(_ error: Error) { + errorMessage = error.localizedDescription + switch error { + case TrainingRemoteError.identityChanged: + identityIsValid = false + shouldReturnToCenter = true + task = nil + progress = nil + paper = nil + questionCache = [:] + answerCache = [:] + loadedDraftIndices = [] + answeredQuestionOrders = [] + draftRevision = 0 + currentIndex = 0 + submittedAttempt = nil + submittedResult = nil + // 保留原身份的未知请求,不能因切换账号而删除或换键重试。 + case TrainingRemoteError.forbidden, TrainingRemoteError.accountInvalid: shouldReturnToCenter = true + default: break + } + } + + private func authorize() async throws { + guard let actual = await currentContext() else { identityIsValid = false; throw TrainingRemoteError.identityChanged } + if context == nil { context = actual } + guard actual == context else { identityIsValid = false; throw TrainingRemoteError.identityChanged } + identityIsValid = true + } + + private func requireExamAllowed() throws { + guard task?.id == taskID, progress?.taskID == taskID else { throw TrainingError.invalidPaper } + guard task?.mode == .exam, task?.learnerStatus != .completed, + progress?.learnerStatus != .completed, progress?.completedAt == nil, + progress?.canStartExam == true, progress?.readingCompleted == true else { + throw TrainingRemoteError.examNotAllowed("当前任务暂不能考试,请返回课程确认学习进度和任务状态") + } + } + + private func applyMetadata(_ value: TrainingDraftPage) throws { + let orders = Set(value.answeredQuestionOrders) + guard value.taskID == taskID, value.paperSnapshotID == paper?.id, value.total == questionCount, + value.draftRevision > 0, orders.count == value.answeredCount, + orders.allSatisfy({ (1...questionCount).contains($0) }) else { throw TrainingError.invalidAnswers } + if value.draftRevision != draftRevision { answerCache = [:]; loadedDraftIndices = [] } + draftRevision = value.draftRevision + answeredQuestionOrders = orders + } + + private func loadCurrentPage(service: any TrainingDataServing) async throws { + guard let paper else { throw TrainingError.invalidPaper } + let offset = currentIndex / pageSize * pageSize + if questionCache[currentIndex] == nil { + try await fetchQuestions(offset: offset, paperID: paper.id, service: service) + // 大小预算允许后端缩短页;远处题号直接请求目标位置,避免遍历此前的页。 + if questionCache[currentIndex] == nil, currentIndex != offset { + try await fetchQuestions(offset: currentIndex, paperID: paper.id, service: service) + } + guard currentQuestion != nil else { throw TrainingError.invalidPaper } + } + if !loadedDraftIndices.contains(currentIndex) { + try await fetchDraft(offset: offset, service: service) + if !loadedDraftIndices.contains(currentIndex), currentIndex != offset { + try await fetchDraft(offset: currentIndex, service: service) + } + guard loadedDraftIndices.contains(currentIndex) else { throw TrainingError.invalidAnswers } + } + if let question = currentQuestion { + let selected = answerCache[question.id] ?? [] + guard selected.isSubset(of: Set(question.options.map(\.id))), + question.type != .single || selected.count <= 1 else { throw TrainingError.invalidAnswers } + } + needsDraftRefresh = false + } + + private func fetchQuestions(offset: Int, paperID: String, service: any TrainingDataServing) async throws { + let page = try await service.questions(paperID: paperID, taskID: taskID, offset: offset, limit: pageSize) + try await authorize() + let end = min(questionCount, offset + pageSize) + guard page.paperSnapshotID == paperID, page.total == questionCount, page.offset == offset, + !page.items.isEmpty, page.items.count <= end - offset, + Set(page.items.map(\.order)).count == page.items.count, + Set(page.items.map(\.id)).count == page.items.count else { throw TrainingError.invalidPaper } + for question in page.items { + guard (offset + 1...end).contains(question.order), !question.id.isEmpty, + (2...6).contains(question.options.count), Set(question.options.map(\.id)).count == question.options.count, + !questionCache.values.contains(where: { $0.id == question.id && $0.order != question.order }) else { + throw TrainingError.invalidPaper + } + questionCache[question.order - 1] = question + } + } + + private func fetchDraft(offset: Int, service: any TrainingDataServing) async throws { + let page = try await service.draft(taskID: taskID, offset: offset, limit: pageSize) + try await authorize() + try applyMetadata(page) + let requestedEnd = min(questionCount, offset + pageSize) + let coveredEnd = page.nextOffset ?? requestedEnd + guard page.offset == offset, coveredEnd > offset, coveredEnd <= requestedEnd, + Set(page.items.map(\.questionID)).count == page.items.count, + Set(page.items.map(\.order)).count == page.items.count else { throw TrainingError.invalidAnswers } + for index in offset..= draftRevision, (0...questionCount).contains(confirmation.answeredCount) else { + throw TrainingError.invalidAnswers + } + pendingMutation = nil + draftRevision = confirmation.draftRevision + switch mutation { + case .reset: + // 重置重试返回当前实况,不能根据成功响应把之后的新答案清空。 + currentIndex = 0 + try await refreshDraft(service: service) + case .save(let request): + for change in request.changes { + answerCache[change.questionID] = Set(change.selectedOptionIDs) + if let question = questionCache.values.first(where: { $0.id == change.questionID }) { + if change.selectedOptionIDs.isEmpty { answeredQuestionOrders.remove(question.order) } + else { answeredQuestionOrders.insert(question.order) } + } + } + if answeredCount != confirmation.answeredCount { try await refreshDraft(service: service) } + } + } catch { + if case TrainingRemoteError.draftRevisionConflict = error { + pendingMutation = nil + try? await refreshDraft(service: service) + } else if let remote = error as? TrainingRemoteError, remote.code != nil { + if case .idempotencyConflict = remote { /* 保留原请求,禁止换键覆盖。 */ } + else { + pendingMutation = nil + if let latest = try? await service.progress(taskID: taskID) { + try await authorize() + progress = latest + } else { progress = nil } + } + } + throw error + } + } + + private func recoverSubmission(service: any TrainingDataServing) async throws -> TrainingAttemptSummary? { + guard let pending = pendingSubmission else { return nil } + let page = try await service.attempts(taskID: taskID, submissionID: pending.request.submissionID, cursor: nil, limit: 1) + try await authorize() + guard page.items.count <= 1 else { throw TrainingError.invalidAnswers } + if let attempt = page.items.first { + return try finishSubmission(pending, attempt: attempt, serverTime: page.serverTime ?? attempt.submittedAt) + } + return try await sendSubmission(pending, service: service) + } + + private func sendSubmission(_ pending: TrainingPendingSubmission, service: any TrainingDataServing) async throws -> TrainingAttemptSummary? { + do { + let result = try await service.submit(taskID: taskID, request: pending.request) + try await authorize() + draftRevision = max(draftRevision, result.draftRevision) + let attempt = try finishSubmission(pending, attempt: result.attempt, serverTime: result.serverTime) + submittedResult = TrainingAttemptDetail(attempt: result.attempt, taskState: result.taskState, serverTime: result.serverTime) + return attempt + } catch { + if let remote = error as? TrainingRemoteError, remote.code != nil { + switch remote { + case .idempotencyConflict, .forbidden, .accountInvalid: + // 权限拒绝无法证明原请求未成功,保留恢复键。 + break + default: + try await authorize() + try pendingStore.remove(pending) + pendingSubmission = nil + needsDraftRefresh = true + if let latest = try? await service.progress(taskID: taskID) { + try await authorize() + progress = latest + if latest.canStartExam { try? await refreshDraft(service: service) } + } + } + } + throw error + } + } + + private func finishSubmission(_ pending: TrainingPendingSubmission, attempt: TrainingAttemptSummary, serverTime: Date) throws -> TrainingAttemptSummary { + guard attempt.taskID == taskID, attempt.paperSnapshotID == pending.request.paperSnapshotID else { throw TrainingError.invalidAnswers } + try pendingStore.remove(pending) + pendingSubmission = nil + submittedAttempt = attempt + let state = TrainingTaskState(learnerStatus: attempt.passed ? .completed : .pendingExam, + completedAt: attempt.passed ? attempt.submittedAt : nil, canRetry: false, blockReason: attempt.passed ? "completed" : nil) + submittedResult = TrainingAttemptDetail(attempt: attempt, taskState: state, serverTime: serverTime) + return attempt + } +} diff --git a/suixinkan/Features/Training/ViewModels/TrainingRemoteListViewModels.swift b/suixinkan/Features/Training/ViewModels/TrainingRemoteListViewModels.swift new file mode 100644 index 0000000..2249267 --- /dev/null +++ b/suixinkan/Features/Training/ViewModels/TrainingRemoteListViewModels.swift @@ -0,0 +1,248 @@ +import Foundation + +/// 培训列表只保存摘要和服务端游标,不聚合课程、试卷或解析。 +final class TrainingRemoteCenterViewModel { + /// 当前页面入口。 + var tab: TrainingCenterTab = .home + /// 服务端任务状态筛选。 + var filter: TrainingLearnerStatus = .pendingExam + /// 服务端同时搜索任务名和课程名。 + var keyword = "" + /// 当前任务摘要页。 + private(set) var tasks: [TrainingTaskSummary] = [] + /// 当前成绩摘要页。 + private(set) var records: [TrainingAttemptSummary] = [] + /// 不受分页和关键词影响的概览。 + private(set) var summary: TrainingSummary? + /// 首次加载或刷新状态。 + private(set) var isLoading = false + /// 翻页状态,避免重复消费同一游标。 + private(set) var isLoadingMore = false + /// 最近失败说明。 + private(set) var errorMessage: String? + /// 是否仍有下一页。 + private(set) var hasMore = false + /// 进入时的身份已失效,页面应关闭而不是展示旧作用域统计。 + private(set) var isIdentityInvalid = false + private var nextCursor: String? + private var generation = UUID() + + /// 概览中的待完成数量。 + var pendingCount: Int { summary?.pendingCount ?? 0 } + /// 概览中的已完成数量。 + var completedCount: Int { summary?.completedCount ?? 0 } + /// 最近成绩只来自概览接口,不遍历历史。 + var latestScore: String { summary?.latestAttempt.map { TrainingScore.text($0.scoreHundredths) } ?? "—" } + + /// 切换入口时保留筛选状态,清除搜索和旧游标。 + func selectTab(_ tab: TrainingCenterTab) { + self.tab = tab + keyword = "" + generation = UUID() + nextCursor = nil + hasMore = false + } + + /// 搜索文本变化立即失效游标与旧请求,网络首屏可以稍后防抖执行。 + func setKeyword(_ value: String) { + keyword = value + generation = UUID() + nextCursor = nil + hasMore = false + isLoading = false + isLoadingMore = false + } + + /// 页面并行读取概览和当前摘要页,保留顶部统计而不遍历其他资源。 + func load(service: any TrainingDataServing) async { + let requestID = UUID() + generation = requestID + isLoading = true + isLoadingMore = false + errorMessage = nil + hasMore = false + nextCursor = nil + let requestedTab = tab + let requestedFilter = filter + let query = keyword.trimmingCharacters(in: .whitespacesAndNewlines) + defer { if generation == requestID { isLoading = false } } + do { + async let overview = service.summary() + switch requestedTab { + case .home: + async let page = service.tasks(status: .pendingExam, keyword: "", cursor: nil, limit: 3) + let (loadedSummary, loadedPage) = try await (overview, page) + guard generation == requestID, !Task.isCancelled else { return } + summary = loadedSummary + tasks = loadedPage.items + records = [] + case .tasks: + let page = try await service.tasks(status: requestedFilter, keyword: query, cursor: nil, limit: 20) + let loadedSummary = try await overview + guard generation == requestID, !Task.isCancelled else { return } + summary = loadedSummary + tasks = page.items + records = [] + nextCursor = page.hasMore ? page.nextCursor : nil + hasMore = nextCursor != nil + case .records: + let page = try await service.attempts(taskID: nil, submissionID: nil, cursor: nil, limit: 20) + let loadedSummary = try await overview + guard generation == requestID, !Task.isCancelled else { return } + summary = loadedSummary + records = page.items + tasks = [] + nextCursor = page.hasMore ? page.nextCursor : nil + hasMore = nextCursor != nil + } + } catch { + guard generation == requestID, !Task.isCancelled else { return } + tasks = [] + records = [] + summary = nil + isIdentityInvalid = error as? TrainingRemoteError == .identityChanged + errorMessage = error.localizedDescription + } + } + + /// 用户主动加载下一页,不提前遍历全部任务或成绩。 + func loadMore(service: any TrainingDataServing) async { + guard !isLoading, !isLoadingMore, let cursor = nextCursor, tab != .home else { return } + isLoadingMore = true + errorMessage = nil + let requestID = generation + defer { if generation == requestID { isLoadingMore = false } } + do { + if tab == .tasks { + let page = try await service.tasks(status: filter, keyword: keyword.trimmingCharacters(in: .whitespacesAndNewlines), cursor: cursor, limit: 20) + guard generation == requestID, !Task.isCancelled else { return } + let existing = Set(tasks.map(\.id)) + tasks += page.items.filter { !existing.contains($0.id) } + nextCursor = page.hasMore && page.nextCursor != cursor ? page.nextCursor : nil + } else { + let page = try await service.attempts(taskID: nil, submissionID: nil, cursor: cursor, limit: 20) + guard generation == requestID, !Task.isCancelled else { return } + let existing = Set(records.map(\.id)) + records += page.items.filter { !existing.contains($0.id) } + nextCursor = page.hasMore && page.nextCursor != cursor ? page.nextCursor : nil + } + hasMore = nextCursor != nil + } catch { + guard generation == requestID, !Task.isCancelled else { return } + if error as? TrainingRemoteError == .identityChanged { + tasks = []; records = []; summary = nil; nextCursor = nil; hasMore = false + isIdentityInvalid = true + } + errorMessage = error.localizedDescription + } + } +} + +/// 成绩首屏只读单次摘要,解析由展开或翻页动作触发。 +final class TrainingRemoteResultViewModel { + /// 服务端成绩主键。 + let attemptID: String + /// 当前摘要与最新操作资格。 + private(set) var detail: TrainingAttemptDetail? + /// 已按需读取的解析页。 + private(set) var reviews: [TrainingReviewItem] = [] + /// 摘要加载状态。 + private(set) var isLoading = false + /// 解析分页状态。 + private(set) var isLoadingReviews = false + /// 是否已成功加载解析首屏。 + private(set) var hasLoadedReviews = false + /// 解析是否仍可继续翻页。 + private(set) var hasMoreReviews = false + /// 摘要失败信息。 + private(set) var errorMessage: String? + /// 解析失败信息,不替换已成功显示的成绩。 + private(set) var reviewErrorMessage: String? + /// 登录身份变化后清空成绩与解析,页面应退出旧身份作用域。 + private(set) var isIdentityInvalid = false + /// 非店铺账号或任务权限撤回时退出该次成绩。 + private(set) var isAccessRevoked = false + private var reviewCursor: String? + private var generation = UUID() + + /// 通过成绩 ID 定位,不读取任务的所有历史。 + init(attemptID: String, initialDetail: TrainingAttemptDetail? = nil) { + self.attemptID = attemptID + self.detail = initialDetail + } + + /// 返回页面时更新操作资格,但保留已读取的冻结解析。 + func load(service: any TrainingDataServing) async { + let requestID = UUID() + generation = requestID + isLoading = true + errorMessage = nil + defer { if generation == requestID { isLoading = false } } + do { + let loaded = try await service.attempt(id: attemptID) + guard generation == requestID, !Task.isCancelled else { return } + detail = loaded + if !loaded.attempt.reviewAvailable { + reviews = [] + hasLoadedReviews = false + hasMoreReviews = false + reviewCursor = nil + reviewErrorMessage = nil + } + } catch { + guard generation == requestID, !Task.isCancelled else { return } + detail = nil + reviews = [] + hasLoadedReviews = false + hasMoreReviews = false + isIdentityInvalid = error as? TrainingRemoteError == .identityChanged + isAccessRevoked = [150100, 150101].contains((error as? TrainingRemoteError)?.code ?? 0) + errorMessage = error.localizedDescription + } + } + + /// 初次展开只取第一页,再次展开复用已有解析。 + func loadReviews(service: any TrainingDataServing, nextPage: Bool = false) async { + guard !isLoadingReviews, detail?.attempt.reviewAvailable == true else { return } + if nextPage { guard hasMoreReviews, reviewCursor != nil else { return } } + else if hasLoadedReviews { return } + let cursor = nextPage ? reviewCursor : nil + let requestID = generation + isLoadingReviews = true + reviewErrorMessage = nil + defer { isLoadingReviews = false } + do { + let page = try await service.reviews(attemptID: attemptID, cursor: cursor, limit: 10) + guard generation == requestID, !Task.isCancelled else { return } + let existing = Set(reviews.map(\.id)) + reviews += page.items.filter { !existing.contains($0.id) } + hasLoadedReviews = true + reviewCursor = page.hasMore && page.nextCursor != cursor ? page.nextCursor : nil + hasMoreReviews = reviewCursor != nil + } catch { + guard generation == requestID, !Task.isCancelled else { return } + isAccessRevoked = [150100, 150101].contains((error as? TrainingRemoteError)?.code ?? 0) + if error as? TrainingRemoteError == .identityChanged || isAccessRevoked { + detail = nil + reviews = [] + hasLoadedReviews = false + hasMoreReviews = false + reviewCursor = nil + isIdentityInvalid = error as? TrainingRemoteError == .identityChanged + } + reviewErrorMessage = error.localizedDescription + } + } +} + +/// 服务端百分之一分的整数使用最多两位小数展示。 +enum TrainingScore { + /// 不自行判分,只格式化已确认的成绩。 + static func text(_ hundredths: Int) -> String { + let whole = hundredths / 100 + let fraction = hundredths % 100 + guard fraction != 0 else { return String(whole) } + let digits = String(format: "%02d", fraction) + return "\(whole).\(fraction.isMultiple(of: 10) ? String(digits.prefix(1)) : digits)" + } +} diff --git a/suixinkan/Features/Training/ViewModels/TrainingRemoteReadingViewModel.swift b/suixinkan/Features/Training/ViewModels/TrainingRemoteReadingViewModel.swift new file mode 100644 index 0000000..c37a09f --- /dev/null +++ b/suixinkan/Features/Training/ViewModels/TrainingRemoteReadingViewModel.swift @@ -0,0 +1,444 @@ +import Foundation + +/// 正式课程按需读取与有效前台读时;页面在操作完成后主动读取状态并刷新。 +final class TrainingRemoteReadingViewModel { + /// 当前本人任务标识。 + let taskID: String + /// 已加载的轻量任务规则与快照引用。 + private(set) var task: TrainingTaskDetail? + /// 已加载的课程元信息,不包含全部正文。 + private(set) var course: TrainingCourseInfo? + /// 用户已请求的小节目录,首次最多二十项。 + private(set) var sections: [TrainingSectionInfo] = [] + /// 当前选择的小节正式正文。 + private(set) var currentSection: TrainingSectionContent? + /// 当前小节标识,正文加载失败时供重试使用。 + private(set) var currentSectionID: String? + /// 用户已请求的附件元信息,不包含文件内容。 + private(set) var attachments: [TrainingAttachmentInfo] = [] + /// 最新后端确认的学习进度与资格。 + private(set) var progress: TrainingProgressSnapshot? + /// 首次加载或切换正文期间阻止重复内容操作。 + private(set) var isLoading = false + /// 小节目录下一页正在加载。 + private(set) var isLoadingSections = false + /// 附件目录下一页正在加载。 + private(set) var isLoadingAttachments = false + /// 附件链接正在授权。 + private(set) var isAuthorizingAttachment = false + /// 小节目录是否还有用户可主动读取的页面。 + private(set) var hasMoreSections = false + /// 附件目录是否还有用户可主动读取的页面。 + private(set) var hasMoreAttachments = false + /// 已经读取过附件第一页,避免反复取相同元信息。 + private(set) var hasLoadedAttachments = false + /// 是否正在累计本次会话的可见读时。 + private(set) var isReading = false + /// 当前会话本地累计秒数;新会话始终从零开始。 + private(set) var activeSecondsTotal = 0 + /// 最近一次阅读保存失败,可用原请求安全重试。 + private(set) var readingErrorMessage: String? + /// 会话恢复提示,与当前操作资格分开展示。 + private(set) var readingNotice: String? + /// 身份已经切换,所有迟到结果都应被丢弃。 + private(set) var isInvalidated = false + + private let service: any TrainingDataServing + private let validateIdentity: @MainActor @Sendable () -> Bool + private let now: @Sendable () -> Date + private var generation = 0 + private var sectionCursor: String? + private var attachmentCursor: String? + private var bodies: [String: TrainingSectionContent] = [:] + private var contentErrorMessage: String? + private var session: TrainingStudySession? + private var sessionRequestID: String? + private var acceptedActiveSecondsTotal = 0 + private var nextSequence = 1 + private var pendingHeartbeat: PendingHeartbeat? + private var finalRequested = false + private var wantsReading = false + private var isSessionBusy = false + private var sessionWaiters: [CheckedContinuation] = [] + private var readingClock = TrainingReadingClock() + private var lastVisibleUptime: TimeInterval = 0 + + /// 一次冻结的幂等心跳;重试时序号、累计秒数与 final 均不能变更。 + private struct PendingHeartbeat { + let sessionID: String + let sequence: Int + let activeSecondsTotal: Int + let final: Bool + } + + /// 注入正式数据源、身份校验与时钟,不让 ViewModel 依赖 UIKit 或共享登录视图。 + init( + taskID: String, + service: any TrainingDataServing, + now: @escaping @Sendable () -> Date = { Date() }, + validateIdentity: @escaping @MainActor @Sendable () -> Bool = { true } + ) { + self.taskID = taskID + self.service = service + self.now = now + self.validateIdentity = validateIdentity + } + + /// 页面展示的内容或保存错误,不用中文文案判断恢复分支。 + var errorMessage: String? { readingErrorMessage ?? contentErrorMessage } + + /// 显示未确认读时的倒计时,但只有服务器确认后才允许开始考试。 + var remainingSeconds: Int { + guard let progress else { return task?.requiredReadingSeconds ?? 0 } + let unconfirmed = max(0, activeSecondsTotal - acceptedActiveSecondsTotal) + return max(0, progress.requiredReadingSeconds - progress.readingSeconds - unconfirmed) + } + + /// 当前后端是否允许继续有效学习,完成或只读任务不建立新会话。 + var canStudy: Bool { progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated } + + /// 首次只取元信息、目录第一页、首节正文和小型进度,不预取附件或其他小节正文。 + func load() async { + guard !isLoading, !isInvalidated else { return } + let epoch = generation + isLoading = true + contentErrorMessage = nil + defer { if generation == epoch { isLoading = false } } + do { + let detail = try await service.task(id: taskID) + try await checkIdentity(epoch) + guard detail.summary.learning.canViewCourse else { + throw TrainingRemoteError.forbidden("当前任务不能查看课程") + } + let courseID = detail.summary.courseSnapshotID + async let metadata = service.course(id: courseID, taskID: taskID) + async let directory = service.sections(courseID: courseID, taskID: taskID, cursor: nil, limit: 20) + async let savedProgress = service.progress(taskID: taskID) + let (info, page, saved) = try await (metadata, directory, savedProgress) + try await checkIdentity(epoch) + guard let first = page.items.first else { throw TrainingRemoteError.contentMissing("暂无课程内容") } + let body = try await service.section(courseID: courseID, sectionID: first.id, taskID: taskID) + try await checkIdentity(epoch) + task = detail + course = info + sections = page.items + sectionCursor = page.nextCursor + hasMoreSections = page.hasMore + currentSectionID = first.id + currentSection = body + bodies[body.id] = body + progress = saved + } catch { saveContentError(error, epoch: epoch) } + } + + /// 返回已缓存课程时只刷新本人资格与进度,保留正文和目录缓存。 + func refreshProgress() async { + let epoch = generation + guard !isInvalidated else { return } + do { + let value = try await service.progress(taskID: taskID) + try await checkIdentity(epoch) + progress = value + if !value.canStudy || value.readingCompleted { pauseReading() } + contentErrorMessage = nil + } catch { saveContentError(error, epoch: epoch) } + } + + /// 切章节立即暂停;只读取选中正文,已经看过的同快照正文直接复用。 + func selectSection(id: String) async { + guard !isLoading, !isInvalidated, let course else { return } + let epoch = generation + isLoading = true + defer { if generation == epoch { isLoading = false } } + pauseReading() + await flush(final: true) + guard generation == epoch, !isInvalidated, !Task.isCancelled else { return } + contentErrorMessage = nil + currentSectionID = id + currentSection = nil + do { + let body: TrainingSectionContent + if let cached = bodies[id] { body = cached } + else { body = try await service.section(courseID: course.id, sectionID: id, taskID: taskID) } + try await checkIdentity(epoch) + currentSection = body + bodies[id] = body + } catch { saveContentError(error, epoch: epoch) } + } + + /// 仅用户点击加载更多时读取目录下一页,不为展示一个小节遍历全部目录。 + func loadMoreSections() async { + guard !isLoadingSections, hasMoreSections, let cursor = sectionCursor, let course, !isInvalidated else { return } + let epoch = generation + isLoadingSections = true + defer { if generation == epoch { isLoadingSections = false } } + do { + let page = try await service.sections(courseID: course.id, taskID: taskID, cursor: cursor, limit: 20) + try await checkIdentity(epoch) + let existing = Set(sections.map(\.id)) + sections.append(contentsOf: page.items.filter { !existing.contains($0.id) }) + sectionCursor = page.nextCursor + hasMoreSections = page.hasMore + contentErrorMessage = nil + } catch { saveContentError(error, epoch: epoch) } + } + + /// 首次打开附件目录才读取第一页;后续页也由用户主动请求。 + func loadAttachments(loadMore: Bool = false) async { + guard !isLoadingAttachments, let course, !isInvalidated else { return } + if hasLoadedAttachments && !loadMore { return } + if loadMore && (!hasMoreAttachments || attachmentCursor == nil) { return } + let epoch = generation + isLoadingAttachments = true + defer { if generation == epoch { isLoadingAttachments = false } } + do { + let page = try await service.attachments(courseID: course.id, taskID: taskID, cursor: loadMore ? attachmentCursor : nil, limit: 20) + try await checkIdentity(epoch) + let existing = Set(attachments.map(\.id)) + if !loadMore { attachments = page.items } + else { attachments.append(contentsOf: page.items.filter { !existing.contains($0.id) }) } + attachmentCursor = page.nextCursor + hasMoreAttachments = page.hasMore + hasLoadedAttachments = true + contentErrorMessage = nil + } catch { saveContentError(error, epoch: epoch) } + } + + /// 点击附件时取得可直接交给系统浏览器的有效 HTTPS 链接,不附 App Token。 + func authorizeAttachment(id: String) async -> TrainingAttachmentLink? { + guard !isAuthorizingAttachment, let course, !isInvalidated else { return nil } + let epoch = generation + isAuthorizingAttachment = true + defer { if generation == epoch { isAuthorizingAttachment = false } } + do { + let link = try await service.attachmentURL(courseID: course.id, attachmentID: id, taskID: taskID) + try await checkIdentity(epoch) + guard link.url.scheme?.lowercased() == "https", link.url.host != nil, link.expiresAt > now() else { + throw TrainingRemoteError.paramInvalid("附件访问地址无效或已过期,请重试") + } + contentErrorMessage = nil + return link + } catch { saveContentError(error, epoch: epoch); return nil } + } + + /// 正文已经在前台可见时建立或恢复会话;创建丢响应时沿用原 requestID。 + func startReading(at uptime: TimeInterval) async { + guard currentSection != nil, canStudy else { return } + let epoch = generation + wantsReading = true + lastVisibleUptime = uptime + await waitForSessionOperation(epoch: epoch) + guard generation == epoch, !isInvalidated, wantsReading, canStudy, currentSection != nil else { return } + isSessionBusy = true + defer { finishSessionOperation(epoch: epoch) } + do { + try await checkIdentity(epoch) + if pendingHeartbeat != nil || finalRequested { + try await sendHeartbeats(epoch: epoch) + } + if session == nil && canStudy { try await createSession(epoch: epoch) } + if wantsReading, session != nil, canStudy { + readingErrorMessage = nil + readingClock.resume(at: uptime) + isReading = true + } else if session != nil { try await sendHeartbeats(epoch: epoch) } + } catch { await handleReadingError(error, epoch: epoch) } + } + + /// 由前台定时器驱动,每次最多记一秒;到间隔或门槛才发送网络心跳。 + func recordVisibleTime(at uptime: TimeInterval) async { + lastVisibleUptime = uptime + guard isReading, wantsReading, canStudy, !isSessionBusy, pendingHeartbeat == nil, + readingClock.takeSecond(at: uptime) else { return } + activeSecondsTotal += 1 + let interval = max(1, session?.heartbeatIntervalSeconds ?? 5) + if activeSecondsTotal - acceptedActiveSecondsTotal >= interval || remainingSeconds == 0 { + await flush(final: remainingSeconds == 0) + } + } + + /// 页面隐藏、锁屏、正文切换或附件打开时同步停止计时,丢弃未满一秒片段。 + func pauseReading() { + wantsReading = false + finalRequested = true + isReading = false + readingClock.pause() + } + + /// 保存已累计片段;先重试冻结的旧请求,再用新序号发送最终关闭请求。 + func flush(final: Bool = false) async { + if final { pauseReading() } + let epoch = generation + await waitForSessionOperation(epoch: epoch) + guard generation == epoch, !isInvalidated, session != nil else { return } + isSessionBusy = true + defer { finishSessionOperation(epoch: epoch) } + do { + try await checkIdentity(epoch) + try await sendHeartbeats(epoch: epoch) + readingErrorMessage = nil + } catch { await handleReadingError(error, epoch: epoch) } + } + + /// 身份切换使所有异步操作失效,清理旧账号内容和未确认片段。 + func invalidate() { + generation += 1 + isInvalidated = true + pauseReading() + clearSession() + task = nil + course = nil + sections = [] + currentSection = nil + currentSectionID = nil + attachments = [] + bodies = [:] + progress = nil + contentErrorMessage = nil + readingErrorMessage = nil + readingNotice = nil + sectionCursor = nil + attachmentCursor = nil + hasMoreSections = false + hasMoreAttachments = false + hasLoadedAttachments = false + isLoading = false + isLoadingSections = false + isLoadingAttachments = false + isAuthorizingAttachment = false + isSessionBusy = false + resumeSessionWaiters() + } + + private func createSession(epoch: Int) async throws { + let requestID = sessionRequestID ?? UUID().uuidString + sessionRequestID = requestID + let value = try await service.startReading(taskID: taskID, requestID: requestID) + try await checkIdentity(epoch) + session = value + progress = value.progress + activeSecondsTotal = 0 + acceptedActiveSecondsTotal = 0 + nextSequence = 1 + finalRequested = !wantsReading || !canStudy + } + + private func sendHeartbeats(epoch: Int) async throws { + while let session { + if pendingHeartbeat == nil { + guard finalRequested || activeSecondsTotal > acceptedActiveSecondsTotal else { return } + pendingHeartbeat = PendingHeartbeat(sessionID: session.sessionID, sequence: nextSequence, + activeSecondsTotal: activeSecondsTotal, final: finalRequested) + } + guard let pending = pendingHeartbeat else { return } + let response = try await service.heartbeat(sessionID: pending.sessionID, sequence: pending.sequence, + activeSecondsTotal: pending.activeSecondsTotal, final: pending.final) + try await checkIdentity(epoch) + guard response.sessionID == pending.sessionID, response.acceptedSequence == pending.sequence, + response.acceptedActiveSecondsTotal >= acceptedActiveSecondsTotal, + response.acceptedActiveSecondsTotal <= pending.activeSecondsTotal else { + throw TrainingRemoteError.sessionConflict("学习上报确认与请求不一致") + } + progress = response.progress + acceptedActiveSecondsTotal = response.acceptedActiveSecondsTotal + nextSequence = pending.sequence + 1 + pendingHeartbeat = nil + if response.sessionClosed || pending.final { + clearSession() + return + } + if response.progress.readingCompleted || !response.progress.canStudy { pauseReading() } + if !finalRequested { return } + } + } + + private func clearSession() { + session = nil + sessionRequestID = nil + pendingHeartbeat = nil + activeSecondsTotal = 0 + acceptedActiveSecondsTotal = 0 + nextSequence = 1 + finalRequested = false + isReading = false + readingClock.pause() + } + + private func waitForSessionOperation(epoch: Int) async { + while isSessionBusy, generation == epoch, !isInvalidated { + await withCheckedContinuation { sessionWaiters.append($0) } + } + } + + private func finishSessionOperation(epoch: Int) { + guard generation == epoch else { return } + isSessionBusy = false + resumeSessionWaiters() + } + + private func resumeSessionWaiters() { + let waiters = sessionWaiters + sessionWaiters = [] + waiters.forEach { $0.resume() } + } + + private func checkIdentity(_ epoch: Int) async throws { + guard generation == epoch, !isInvalidated, !Task.isCancelled else { throw CancellationError() } + guard await validateIdentity() else { + invalidate() + throw TrainingRemoteError.identityChanged + } + } + + private func saveContentError(_ error: Error, epoch: Int) { + guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return } + let mapped = TrainingRemoteError.map(error) + let code = (mapped as? TrainingRemoteError)?.code + if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 { + invalidate() + return + } + contentErrorMessage = mapped.localizedDescription + } + + private func handleReadingError(_ error: Error, epoch: Int) async { + guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return } + let mapped = TrainingRemoteError.map(error) + let code = (mapped as? TrainingRemoteError)?.code + if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 { + invalidate() + return + } + isReading = false + readingClock.pause() + readingErrorMessage = mapped.localizedDescription + guard code == 150104 || code == 150105 || code == 150102 else { return } + do { + let saved = try await service.progress(taskID: taskID) + try await checkIdentity(epoch) + let shouldResume = wantsReading && code != 150102 + clearSession() + progress = saved + wantsReading = shouldResume + if code == 150104 || code == 150105 { + readingErrorMessage = nil + readingNotice = "学习会话已恢复,继续阅读即可" + } + if shouldResume, canStudy { + try await createSession(epoch: epoch) + if wantsReading, canStudy { + readingClock.resume(at: lastVisibleUptime) + isReading = true + readingErrorMessage = nil + readingNotice = "学习会话已恢复,继续阅读即可" + } else if session != nil { try await sendHeartbeats(epoch: epoch) } + } + } catch { + guard generation == epoch, !isInvalidated else { return } + let mapped = TrainingRemoteError.map(error) + let code = (mapped as? TrainingRemoteError)?.code + if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 { invalidate() } + else { readingErrorMessage = mapped.localizedDescription } + } + } +} diff --git a/suixinkan/UI/Profile/ProfileViewController.swift b/suixinkan/UI/Profile/ProfileViewController.swift index b22fb41..464f038 100644 --- a/suixinkan/UI/Profile/ProfileViewController.swift +++ b/suixinkan/UI/Profile/ProfileViewController.swift @@ -204,6 +204,7 @@ final class ProfileViewController: BaseViewController { } private func applyViewModel() { + trainingRow.isHidden = AppStore.shared.session.accountType != .storeUser trainingRow.configure(value: "学习课程与答题", accessory: .chevron) nicknameField.text = viewModel.displayNickname uidLabel.text = "UID:\(viewModel.displayUID)" diff --git a/suixinkan/UI/Training/TrainingCenterViewController.swift b/suixinkan/UI/Training/TrainingCenterViewController.swift index 4e5ffac..029f9db 100644 --- a/suixinkan/UI/Training/TrainingCenterViewController.swift +++ b/suixinkan/UI/Training/TrainingCenterViewController.swift @@ -5,9 +5,11 @@ import UIKit @MainActor final class TrainingCenterViewController: TrainingBaseViewController { /// 差异化列表中的任务与考试记录标识。 - private enum Item: Hashable { case task(String), attempt(taskID: String, attemptID: String) } - private let service: any TrainingServing - private let viewModel = TrainingCenterViewModel() + private enum Item: Hashable { case task(String), attempt(String) } + private var reloadTask: Task? + private var searchTask: Task? + private let service: any TrainingDataServing + private let viewModel = TrainingRemoteCenterViewModel() private let tableView = UITableView(frame: .zero, style: .plain) private let refreshControl = UIRefreshControl() private let header = UIStackView() @@ -29,9 +31,9 @@ final class TrainingCenterViewController: TrainingBaseViewController { private let moreButton = TrainingUI.button("加载更多记录", plain: true) private var dataSource: UITableViewDiffableDataSource! - /// 默认连接正式服务,开发演示仅由用户显式打开。 - init(service: any TrainingServing = TrainingServiceFactory.production(), showsHistory: Bool = false) { - self.service = service + /// 默认使用当前登录身份连接环境配置中的培训接口。 + init(service: (any TrainingDataServing)? = nil, showsHistory: Bool = false) { + self.service = service ?? TrainingRemoteServiceFactory.production() viewModel.tab = showsHistory ? .records : .home super.init(nibName: nil, bundle: nil) } @@ -41,9 +43,6 @@ final class TrainingCenterViewController: TrainingBaseViewController { override func setupNavigationBar() { TrainingUI.navigation(self, title: "培训中心") - #if DEBUG - if !service.isDemo { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "开发演示", style: .plain, target: self, action: #selector(demoTapped)) } - #endif } override func setupUI() { @@ -87,7 +86,6 @@ final class TrainingCenterViewController: TrainingBaseViewController { body.spacing = 11 body.isLayoutMarginsRelativeArrangement = true body.layoutMargins = UIEdgeInsets(top: 14, left: 13, bottom: 10, right: 13) - if service.isDemo { body.addArrangedSubview(TrainingUI.demoNotice()) } let heading = UIStackView(arrangedSubviews: [headingLabel, viewAllButton]) heading.alignment = .center heading.spacing = 8 @@ -205,9 +203,9 @@ final class TrainingCenterViewController: TrainingBaseViewController { cell.configure(task: task) cell.onAction = { [weak self] in self?.openTask(task, directAction: true) } return cell - case .attempt(let taskID, let attemptID): - guard let task = self.viewModel.tasks.first(where: { $0.id == taskID }), let attempt = task.progress.attempts.first(where: { $0.id == attemptID }), let cell = table.dequeueReusableCell(withIdentifier: TrainingRecordCell.reuseIdentifier, for: indexPath) as? TrainingRecordCell else { return nil } - cell.configure(task: task, attempt: attempt) + case .attempt(let attemptID): + guard let attempt = self.viewModel.records.first(where: { $0.id == attemptID }), let cell = table.dequeueReusableCell(withIdentifier: TrainingRecordCell.reuseIdentifier, for: indexPath) as? TrainingRecordCell else { return nil } + cell.configure(attempt: attempt) return cell } } @@ -237,7 +235,7 @@ final class TrainingCenterViewController: TrainingBaseViewController { button.configuration = configuration button.accessibilityTraits = index == viewModel.tab.rawValue ? [.button, .selected] : .button } - let items: [Item] = viewModel.tab == .records ? viewModel.records.prefix(viewModel.recordLimit).map { .attempt(taskID: $0.task.id, attemptID: $0.attempt.id) } : viewModel.visibleTasks.map { .task($0.id) } + let items: [Item] = viewModel.tab == .records ? viewModel.records.map { .attempt($0.id) } : viewModel.tasks.map { .task($0.id) } var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections([0]) snapshot.appendItems(items) @@ -247,7 +245,11 @@ final class TrainingCenterViewController: TrainingBaseViewController { stateLabel.isHidden = !items.isEmpty retryButton.isHidden = viewModel.errorMessage == nil retryButton.isEnabled = !viewModel.isLoading - moreButton.isHidden = viewModel.tab != .records || viewModel.records.count <= viewModel.recordLimit + moreButton.isHidden = !viewModel.hasMore + moreButton.isEnabled = !viewModel.isLoadingMore + var moreConfiguration = moreButton.configuration + moreConfiguration?.title = viewModel.isLoadingMore ? "正在加载…" : "加载更多" + moreButton.configuration = moreConfiguration if !viewModel.isLoading { refreshControl.endRefreshing() } sizeTableSupplementaryViews() } @@ -255,6 +257,8 @@ final class TrainingCenterViewController: TrainingBaseViewController { /// 页面出现和下拉刷新都读取最新本人任务。 func reload() async { await viewModel.load(service: service) + guard !Task.isCancelled else { return } + if viewModel.isIdentityInvalid { navigationController?.popToRootViewController(animated: false); return } await withCheckedContinuation { (continuation: CheckedContinuation) in applyState { continuation.resume() } } @@ -265,29 +269,38 @@ final class TrainingCenterViewController: TrainingBaseViewController { view.endEditing(true) viewModel.selectTab(tab) searchField.text = "" - applyState() + reloadTapped() tableView.setContentOffset(.zero, animated: false) } @objc private func reloadTapped() { - guard !viewModel.isLoading else { return } - Task { @MainActor in await reload() } + reloadTask?.cancel() + reloadTask = Task { @MainActor [weak self] in await self?.reload() } } @objc private func tabTapped(_ button: UIButton) { if let tab = TrainingCenterTab(rawValue: button.tag) { selectTab(tab) } } - @objc private func filterTapped(_ button: UIButton) { viewModel.filter = button.tag == 0 ? .pendingExam : .completed; applyState() } - @objc private func searchChanged() { viewModel.keyword = searchField.text ?? ""; applyState() } - @objc private func moreTapped() { viewModel.recordLimit += 20; applyState() } + @objc private func filterTapped(_ button: UIButton) { viewModel.filter = button.tag == 0 ? .pendingExam : .completed; reloadTapped() } + @objc private func searchChanged() { + viewModel.setKeyword(searchField.text ?? "") + reloadTask?.cancel() + searchTask?.cancel() + moreButton.isHidden = true + searchTask = Task { @MainActor [weak self] in + do { try await Task.sleep(for: .milliseconds(300)) } catch { return } + self?.reloadTapped() + } + } + @objc private func moreTapped() { + Task { @MainActor [weak self] in + guard let self else { return } + await viewModel.loadMore(service: service) + if viewModel.isIdentityInvalid { navigationController?.popToRootViewController(animated: false); return } + applyState() + } + } @objc private func viewAllTapped() { viewModel.filter = .pendingExam; selectTab(.tasks) } - #if DEBUG - @objc private func demoTapped() { - do { navigationController?.pushViewController(TrainingCenterViewController(service: try TrainingServiceFactory.demo()), animated: true) } - catch { showToast(error.localizedDescription) } - } - #endif - - private func openTask(_ task: TrainingTask, directAction: Bool) { - let controller: UIViewController = directAction && TrainingTaskPresentation(task: task).canStartExam ? TrainingExamViewController(taskID: task.id, service: service) : TrainingCourseViewController(taskID: task.id, service: service) + private func openTask(_ task: TrainingTaskSummary, directAction: Bool) { + let controller: UIViewController = directAction && task.learning.canStartExam ? TrainingExamViewController(taskID: task.id, service: service) : TrainingCourseViewController(taskID: task.id, service: service) navigationController?.pushViewController(controller, animated: true) } } @@ -298,7 +311,7 @@ extension TrainingCenterViewController: UITableViewDelegate { guard let item = dataSource.itemIdentifier(for: indexPath) else { return } switch item { case .task(let id): if let task = viewModel.tasks.first(where: { $0.id == id }) { openTask(task, directAction: false) } - case .attempt(let taskID, let attemptID): navigationController?.pushViewController(TrainingResultViewController(taskID: taskID, attemptID: attemptID, service: service), animated: true) + case .attempt(let attemptID): if let attempt = viewModel.records.first(where: { $0.id == attemptID }) { navigationController?.pushViewController(TrainingResultViewController(taskID: attempt.taskID, attemptID: attempt.id, service: service), animated: true) } } } } diff --git a/suixinkan/UI/Training/TrainingCourseViewController.swift b/suixinkan/UI/Training/TrainingCourseViewController.swift index 9f3c7c9..16cf25c 100644 --- a/suixinkan/UI/Training/TrainingCourseViewController.swift +++ b/suixinkan/UI/Training/TrainingCourseViewController.swift @@ -3,28 +3,46 @@ import SnapKit import UIKit import WebKit -/// 全部图文小节连续阅读,唯一底部按钮展示 20 秒倒计时。 +/// 正式课程按需阅读:正文分页、附件授权与服务端确认的前台读时。 @MainActor final class TrainingCourseViewController: TrainingBaseViewController { - private let service: any TrainingServing - private let viewModel: TrainingReadingViewModel + private let service: any TrainingDataServing + private let viewModel: TrainingRemoteReadingViewModel private let webView: WKWebView + private let toolbar = UIStackView() + private let sectionsButton = TrainingUI.button("章节目录", secondary: true) + private let attachmentsButton = TrainingUI.button("课程附件", secondary: true) private let bottomStack = UIStackView() private let noticeLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary) private let actionButton = TrainingUI.button("正在加载课程…") - /// 当前课程标识,用于成绩页返回已有学习页面。 - var taskID: String { viewModel.taskID } - private var readingTimer: Timer? + private var contentTask: Task? + private var readingTask: Task? + private var closingTask: Task? + private var closingGeneration = 0 + private var contentNavigation: WKNavigation? + private var appIsActive = UIApplication.shared.applicationState == .active + private var isOpeningResource = false private var contentIsReady = false private var contentLoadFailed = false private var pageIsVisible = false - private var readingClock = TrainingReadingClock() - /// 开启当前任务的连续阅读页面,禁用课程 HTML 中的 JavaScript。 - init(taskID: String, service: any TrainingServing) { + /// 当前任务标识,成绩页可复用已有课程页面。 + var taskID: String { viewModel.taskID } + + /// 使用正式数据源读取课程,课程 HTML 禁用脚本执行。 + init(taskID: String, service: any TrainingDataServing) { self.service = service - viewModel = TrainingReadingViewModel(taskID: taskID) + let session = AppStore.shared.session + let scope = session.accountCachePrefix + let scenicID = session.currentScenicId + let storeID = session.currentStoreId + let token = session.token + viewModel = TrainingRemoteReadingViewModel(taskID: taskID, service: service, validateIdentity: { + let current = AppStore.shared.session + return current.accountCachePrefix == scope && current.currentScenicId == scenicID + && current.currentStoreId == storeID && current.token == token + }) let configuration = WKWebViewConfiguration() configuration.defaultWebpagePreferences.allowsContentJavaScript = false webView = WKWebView(frame: .zero, configuration: configuration) @@ -37,10 +55,14 @@ final class TrainingCourseViewController: TrainingBaseViewController { override func setupNavigationBar() { TrainingUI.navigation(self, title: "课程学习") } override func setupUI() { - webView.navigationDelegate = self view.backgroundColor = TrainingUI.background + webView.navigationDelegate = self webView.backgroundColor = TrainingUI.background webView.isOpaque = false + toolbar.spacing = 10 + toolbar.distribution = .fillEqually + toolbar.addArrangedSubview(sectionsButton) + toolbar.addArrangedSubview(attachmentsButton) bottomStack.axis = .vertical bottomStack.spacing = 8 bottomStack.layoutMargins = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12) @@ -49,13 +71,22 @@ final class TrainingCourseViewController: TrainingBaseViewController { bottomStack.addArrangedSubview(noticeLabel) bottomStack.addArrangedSubview(actionButton) actionButton.accessibilityIdentifier = "training.reading.action" + sectionsButton.accessibilityIdentifier = "training.reading.sections" + attachmentsButton.accessibilityIdentifier = "training.reading.attachments" + view.addSubview(toolbar) view.addSubview(webView) view.addSubview(bottomStack) + applyState() } override func setupConstraints() { + toolbar.snp.makeConstraints { + $0.top.equalTo(view.safeAreaLayoutGuide).offset(8) + $0.leading.trailing.equalToSuperview().inset(13) + } webView.snp.makeConstraints { - $0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide) + $0.top.equalTo(toolbar.snp.bottom).offset(8) + $0.leading.trailing.equalTo(view.safeAreaLayoutGuide) $0.bottom.equalTo(bottomStack.snp.top) } bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) } @@ -63,14 +94,27 @@ final class TrainingCourseViewController: TrainingBaseViewController { override func bindActions() { actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside) - NotificationCenter.default.addObserver(self, selector: #selector(pauseReading), name: UIApplication.willResignActiveNotification, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(resumeReading), name: UIApplication.didBecomeActiveNotification, object: nil) + sectionsButton.addTarget(self, action: #selector(sectionsTapped), for: .touchUpInside) + attachmentsButton.addTarget(self, action: #selector(attachmentsTapped), for: .touchUpInside) + NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) + for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange, NotificationName.userDidLogout] { + NotificationCenter.default.addObserver(self, selector: #selector(identityChanged), name: name, object: nil) + } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) pageIsVisible = true - loadCourse() + if viewModel.task == nil { loadCourse() } + else { + contentTask = Task { @MainActor [weak self] in + guard let self else { return } + await viewModel.refreshProgress() + applyState() + resumeReading() + } + } } override func viewWillDisappear(_ animated: Bool) { @@ -79,142 +123,321 @@ final class TrainingCourseViewController: TrainingBaseViewController { pauseReading() } - override func onSessionDidExpire() { - pauseReading() - navigationController?.popToRootViewController(animated: true) + override func onSessionDidExpire() { identityChanged() } + + private var isContentVisible: Bool { + pageIsVisible && contentIsReady && !contentLoadFailed && !isOpeningResource && presentedViewController == nil + && navigationController?.topViewController === self && appIsActive && UIApplication.shared.applicationState == .active } private func loadCourse() { pauseReading() contentIsReady = false contentLoadFailed = false - actionButton.isEnabled = false - Task { @MainActor in - await viewModel.load(service: service) - if let task = viewModel.task { - let sections = task.course.sections.map { "

\(escape($0.title))

\($0.contentHTML)
" }.joined() - let attachments = task.course.attachments.map { attachment in - guard let url = attachment.url, url.scheme?.lowercased() == "https", url.host != nil else { - return "

附件:\(escape(attachment.name))(尚未同步)

" - } - return "

📄 \(escape(attachment.name))

" - }.joined() - let demo = service.isDemo ? "

开发演示 · 记录仅保存在本机,未同步景区后台

" : "" - let meta = task.mode == .exam ? "学习 + 考试 · \(task.course.sections.count) 节 · \(task.questions.count) 题 · \(task.passScore) 分及格" : "仅学习 · \(task.course.sections.count) 节" - webView.loadHTMLString(""" - - - - \(demo)
1 课程学习\(task.mode == .exam ? "2 在线考试" : "完成学习")

\(escape(task.title))

\(escape(task.course.title))

\(meta)

\(escape(task.course.introduction))

\(sections)
\(attachments) - """, baseURL: nil) - } + contentNavigation = nil + contentTask = Task { @MainActor [weak self] in + guard let self else { return } + await viewModel.load() + guard !Task.isCancelled else { return } + renderCurrentSection() applyState() } } + private func selectSection(_ id: String) { + isOpeningResource = false + pauseReading() + contentIsReady = false + contentLoadFailed = false + contentNavigation = nil + contentTask = Task { @MainActor [weak self] in + guard let self else { return } + await viewModel.selectSection(id: id) + guard !Task.isCancelled else { return } + renderCurrentSection() + applyState() + } + } + + private func renderCurrentSection() { + guard !viewModel.isInvalidated, let task = viewModel.task?.summary, + let course = viewModel.course, let section = viewModel.currentSection else { return } + let metadata = task.mode == .exam + ? "学习 + 考试 · \(course.sectionCount) 节 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格" + : "仅学习 · \(course.sectionCount) 节" + contentNavigation = webView.loadHTMLString(""" + + +
1 课程学习\(task.mode == .exam ? "2 在线考试" : "完成学习")
+

\(escape(task.title))

\(escape(course.title))

\(metadata)

\(escape(course.introduction))

+

第 \(section.order) / \(course.sectionCount) 节

\(escape(section.title))

\(section.contentHTML)
+ """, baseURL: nil) + } + private func escape(_ text: String) -> String { text.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<") .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """) } private func applyState() { - if let error = viewModel.errorMessage ?? (contentLoadFailed ? "课程加载失败,请重试" : nil) { - pauseReading() - noticeLabel.text = error - setActionTitle("重新加载") + guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return } + sectionsButton.isEnabled = !viewModel.isLoading && !viewModel.sections.isEmpty + attachmentsButton.isEnabled = !viewModel.isLoading && (viewModel.course?.attachmentCount ?? 0) > 0 + if let progress = viewModel.progress, progress.readingCompleted { + noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成" + if viewModel.task?.summary.mode == .exam && progress.canStartExam { setActionTitle("开始考试") } + else { setActionTitle("返回培训中心") } actionButton.isEnabled = true + readingTimer?.invalidate() + readingTimer = nil return } - guard let task = viewModel.task else { return } - if let reason = task.submissionBlockReason(now: Date()) { - pauseReading() - noticeLabel.text = reason + if contentLoadFailed || viewModel.currentSection == nil { + noticeLabel.text = viewModel.errorMessage ?? (contentLoadFailed ? "课程正文加载失败,请重试" : "正在加载课程…") + setActionTitle(contentLoadFailed || viewModel.errorMessage != nil ? "重新加载课程" : "正在加载课程…") + actionButton.isEnabled = !viewModel.isLoading && (contentLoadFailed || viewModel.errorMessage != nil) + return + } + if !viewModel.canStudy { + readingTimer?.invalidate() + readingTimer = nil + noticeLabel.text = viewModel.readingErrorMessage ?? "当前任务可回顾课程,不能继续提交学习记录" setActionTitle("返回培训中心") actionButton.isEnabled = true - } else if task.hasFinishedReading { - pauseReading() - noticeLabel.text = "课程阅读已完成" - setActionTitle(task.mode == .exam ? "开始考试" : "完成学习") + } else if let error = viewModel.errorMessage { + readingTimer?.invalidate() + readingTimer = nil + noticeLabel.text = error + setActionTitle(viewModel.readingErrorMessage != nil ? "重试保存并继续学习" : "重新加载课程") actionButton.isEnabled = true } else { - noticeLabel.text = "请阅读课程内容,倒计时结束后" + (task.mode == .exam ? "即可考试" : "完成学习") - setActionTitle("\(task.mode == .exam ? "开始考试" : "完成学习")(\(viewModel.remainingSeconds)s)") + let action = viewModel.task?.summary.mode == .exam ? "开始考试" : "完成学习" + noticeLabel.text = viewModel.readingNotice ?? (viewModel.remainingSeconds == 0 ? "正在确认学习进度…" : "请在前台阅读课程内容,倒计时结束后等待保存确认") + setActionTitle("\(action)(\(viewModel.remainingSeconds)s)") actionButton.isEnabled = false } } - private func setActionTitle(_ title: String) { var configuration = actionButton.configuration; configuration?.title = title; actionButton.configuration = configuration } + private func setActionTitle(_ title: String) { + var configuration = actionButton.configuration + configuration?.title = title + actionButton.configuration = configuration + } @objc private func pauseReading() { readingTimer?.invalidate() readingTimer = nil - readingClock.pause() + viewModel.pauseReading() + let previousClose = closingTask + closingGeneration += 1 + let epoch = closingGeneration + closingTask = Task { @MainActor [weak self] in + guard let self else { return } + await previousClose?.value + await viewModel.flush() + if closingGeneration == epoch { closingTask = nil } + applyState() + resumeReading() + } } - @objc private func resumeReading() { - guard pageIsVisible, contentIsReady, presentedViewController == nil, - navigationController?.topViewController === self, UIApplication.shared.applicationState == .active, - readingTimer == nil, viewModel.errorMessage == nil, let task = viewModel.task, - !task.hasFinishedReading, task.submissionBlockReason(now: Date()) == nil else { return } - readingClock.resume(at: ProcessInfo.processInfo.systemUptime) + @objc private func appWillResignActive() { appIsActive = false; pauseReading() } + + @objc private func appDidBecomeActive() { appIsActive = true; resumeReading() } + + private func resumeReading(retrying: Bool = false) { + guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), readingTask == nil else { return } + let pendingClose = closingTask + readingTask = Task { @MainActor [weak self] in + guard let self else { return } + await pendingClose?.value + guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), !Task.isCancelled else { + readingTask = nil + return + } + await viewModel.startReading(at: ProcessInfo.processInfo.systemUptime) + readingTask = nil + applyState() + if isContentVisible && viewModel.isReading { installReadingTimer() } + } + } + + private func installReadingTimer() { + guard readingTimer == nil else { return } let timer = Timer(timeInterval: 0.25, repeats: true) { [weak self] _ in - Task { @MainActor in await self?.recordSecond() } + Task { @MainActor in self?.readingTick() } } readingTimer = timer RunLoop.main.add(timer, forMode: .common) } - private func recordSecond() async { - guard pageIsVisible, contentIsReady, presentedViewController == nil, - navigationController?.topViewController === self, readingTimer != nil, - UIApplication.shared.applicationState == .active, !viewModel.isBusy else { return } - let uptime = ProcessInfo.processInfo.systemUptime - guard readingClock.takeSecond(at: uptime) else { return } - await viewModel.recordSecond(service: service) - applyState() + private func readingTick() { + guard isContentVisible, readingTask == nil, viewModel.isReading else { return } + readingTask = Task { @MainActor [weak self] in + guard let self else { return } + await viewModel.recordVisibleTime(at: ProcessInfo.processInfo.systemUptime) + readingTask = nil + applyState() + if isContentVisible, viewModel.canStudy, !viewModel.isReading { resumeReading() } + } + } + + @objc private func identityChanged() { + readingTimer?.invalidate() + readingTimer = nil + contentTask?.cancel() + readingTask?.cancel() + closingTask?.cancel() + contentNavigation = nil + viewModel.invalidate() + leaveUnavailableCourse() } @objc private func actionTapped() { - if viewModel.errorMessage != nil || contentLoadFailed { loadCourse(); return } - guard let task = viewModel.task else { return } - if task.submissionBlockReason(now: Date()) != nil || task.mode == .study && task.hasFinishedReading { - if let center = navigationController?.viewControllers.last(where: { $0 is TrainingCenterViewController }) { - navigationController?.popToViewController(center, animated: true) - } - } else if task.hasFinishedReading, task.mode == .exam { - navigationController?.pushViewController(TrainingExamViewController(taskID: task.id, service: service), animated: true) + if let progress = viewModel.progress, progress.readingCompleted { + pauseReading() + if viewModel.task?.summary.mode == .exam && progress.canStartExam { + navigationController?.pushViewController(TrainingExamViewController(taskID: taskID, service: service), animated: true) + } else { returnToCenter() } + } else if contentLoadFailed || viewModel.currentSection == nil { + if let sectionID = viewModel.currentSectionID { selectSection(sectionID) } + else { loadCourse() } + } else if !viewModel.canStudy { returnToCenter() } + else if viewModel.readingErrorMessage != nil { + resumeReading(retrying: true) + } else if viewModel.errorMessage != nil { + if let sectionID = viewModel.currentSectionID { selectSection(sectionID) } + else { loadCourse() } } } + + private func returnToCenter() { + if let center = navigationController?.viewControllers.last(where: { $0 is TrainingCenterViewController }) { + navigationController?.popToViewController(center, animated: true) + } else { navigationController?.popToRootViewController(animated: true) } + } + + private func leaveUnavailableCourse() { + readingTimer?.invalidate() + readingTimer = nil + contentNavigation = nil + webView.stopLoading() + webView.loadHTMLString("", baseURL: nil) + if let presentedViewController { + presentedViewController.dismiss(animated: false) { [weak self] in self?.returnToCenter() } + } else { returnToCenter() } + } + + @objc private func sectionsTapped() { + isOpeningResource = true + pauseReading() + let picker = TrainingCoursePickerViewController(title: "章节目录", rows: sectionRows(), hasMore: viewModel.hasMoreSections, + selectedID: viewModel.currentSectionID, select: { [weak self] id in self?.selectSection(id) }, + loadMore: { [weak self] in + guard let self else { return ([], false) } + await viewModel.loadMoreSections() + applyState() + if let error = viewModel.errorMessage { showToast(error) } + return (sectionRows(), viewModel.hasMoreSections) + }, close: { [weak self] in self?.finishResourcePresentation() }) + presentPicker(picker) + } + + private func sectionRows() -> [TrainingCoursePickerRow] { + viewModel.sections.map { TrainingCoursePickerRow(id: $0.id, title: "\($0.order). \($0.title)") } + } + + @objc private func attachmentsTapped() { + isOpeningResource = true + pauseReading() + contentTask = Task { @MainActor [weak self] in + guard let self else { return } + await viewModel.loadAttachments() + guard !Task.isCancelled else { return } + if viewModel.isInvalidated { applyState(); return } + if let error = viewModel.errorMessage { isOpeningResource = false; showToast(error); applyState(); return } + let picker = TrainingCoursePickerViewController(title: "课程附件", rows: attachmentRows(), hasMore: viewModel.hasMoreAttachments, + select: { [weak self] id in self?.openAttachment(id) }, loadMore: { [weak self] in + guard let self else { return ([], false) } + await viewModel.loadAttachments(loadMore: true) + applyState() + if let error = viewModel.errorMessage { showToast(error) } + return (attachmentRows(), viewModel.hasMoreAttachments) + }, close: { [weak self] in self?.finishResourcePresentation() }) + presentPicker(picker) + } + } + + private func attachmentRows() -> [TrainingCoursePickerRow] { + viewModel.attachments.map { TrainingCoursePickerRow(id: $0.id, title: $0.name) } + } + + private func presentPicker(_ picker: TrainingCoursePickerViewController) { + let navigation = UINavigationController(rootViewController: picker) + navigation.modalPresentationStyle = .pageSheet + navigation.sheetPresentationController?.detents = [.medium(), .large()] + navigation.sheetPresentationController?.prefersGrabberVisible = true + navigation.presentationController?.delegate = picker + present(navigation, animated: true) + } + + private func openAttachment(_ id: String) { + isOpeningResource = true + pauseReading() + contentTask = Task { @MainActor [weak self] in + guard let self else { return } + guard let link = await viewModel.authorizeAttachment(id: id), !Task.isCancelled else { + isOpeningResource = false + if let error = viewModel.errorMessage { showToast(error) } + applyState() + return + } + let controller = SFSafariViewController(url: link.url) + controller.delegate = self + present(controller, animated: true) + } + } + + private func finishResourcePresentation() { + isOpeningResource = false + resumeReading() + } } extension TrainingCourseViewController: WKNavigationDelegate { + /// 当前正文渲染完成且页面可见后才开始有效阅读。 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + guard let contentNavigation, navigation === contentNavigation else { return } contentIsReady = true contentLoadFailed = false applyState() resumeReading() } + /// 正文初始加载失败时停止计时,保留重试入口。 func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { + guard let contentNavigation, navigation === contentNavigation else { return } contentIsReady = false contentLoadFailed = true pauseReading() applyState() } + /// 正文导航失败时不把失败页面停留计入学习。 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { + guard let contentNavigation, navigation === contentNavigation else { return } contentIsReady = false contentLoadFailed = true pauseReading() applyState() } + /// 仅允许本机 HTML 初始加载;用户点击的 HTTPS 链接交给 Safari。 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if navigationAction.navigationType == .other, navigationAction.request.url?.absoluteString == "about:blank" { @@ -224,6 +447,7 @@ extension TrainingCourseViewController: WKNavigationDelegate { decisionHandler(.cancel) guard navigationAction.navigationType == .linkActivated, let url = navigationAction.request.url, url.scheme?.lowercased() == "https", url.host != nil else { return } + isOpeningResource = true pauseReading() let controller = SFSafariViewController(url: url) controller.delegate = self @@ -232,7 +456,109 @@ extension TrainingCourseViewController: WKNavigationDelegate { } extension TrainingCourseViewController: SFSafariViewControllerDelegate { + /// 关闭外部链接后,仅在正文重新可见时建立新的阅读片段。 func safariViewControllerDidFinish(_ controller: SFSafariViewController) { - controller.dismiss(animated: true) { [weak self] in self?.resumeReading() } + controller.dismiss(animated: true) { [weak self] in self?.finishResourcePresentation() } } } + +/// 目录或附件选择器的一行展示数据,不携带业务行为。 +private struct TrainingCoursePickerRow: Hashable { + let id: String + let title: String +} + +/// 原生可滚动资源选择器;用户按需加载更多,选中或关闭后明确通知课程页面。 +@MainActor +private final class TrainingCoursePickerViewController: UIViewController, UITableViewDelegate, UIAdaptivePresentationControllerDelegate { + /// 差异化列表中的资源项与主动分页入口。 + private enum Item: Hashable { case resource(String), more } + private var rows: [TrainingCoursePickerRow] + private var hasMore: Bool + private let selectedID: String? + private let select: (String) -> Void + private let loadMore: () async -> ([TrainingCoursePickerRow], Bool) + private let close: () -> Void + private let tableView = UITableView(frame: .zero, style: .insetGrouped) + private var dataSource: UITableViewDiffableDataSource! + private var isLoadingMore = false + + /// 使用页面提供的展示行、明确选择动作与分页动作构造选择器。 + init(title: String, rows: [TrainingCoursePickerRow], hasMore: Bool, selectedID: String? = nil, + select: @escaping (String) -> Void, loadMore: @escaping () async -> ([TrainingCoursePickerRow], Bool), close: @escaping () -> Void) { + self.rows = rows + self.hasMore = hasMore + self.selectedID = selectedID + self.select = select + self.loadMore = loadMore + self.close = close + super.init(nibName: nil, bundle: nil) + self.title = title + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = TrainingUI.background + navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak self] _ in + guard let self else { return } + dismiss(animated: true, completion: close) + }) + tableView.delegate = self + tableView.rowHeight = UITableView.automaticDimension + tableView.estimatedRowHeight = 52 + tableView.register(UITableViewCell.self, forCellReuseIdentifier: "resource") + view.addSubview(tableView) + tableView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) } + dataSource = UITableViewDiffableDataSource(tableView: tableView) { [weak self] table, indexPath, item in + guard let self else { return nil } + let cell = table.dequeueReusableCell(withIdentifier: "resource", for: indexPath) + var content = UIListContentConfiguration.cell() + switch item { + case .resource(let id): + content.text = rows.first(where: { $0.id == id })?.title + content.textProperties.numberOfLines = 0 + cell.accessoryType = id == selectedID ? .checkmark : .none + case .more: + content.text = isLoadingMore ? "正在加载…" : "加载更多" + content.textProperties.color = TrainingUI.primary + cell.accessoryType = .none + } + cell.contentConfiguration = content + return cell + } + applyRows() + } + + private func applyRows() { + var snapshot = NSDiffableDataSourceSnapshot() + snapshot.appendSections([0]) + snapshot.appendItems(rows.map { .resource($0.id) }) + if hasMore { snapshot.appendItems([.more]) } + if hasMore, dataSource.snapshot().indexOfItem(.more) != nil { snapshot.reconfigureItems([.more]) } + dataSource.apply(snapshot, animatingDifferences: true) + } + + /// 选择后等待模态页面完全关闭,再让课程加载正文或授权附件。 + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + tableView.deselectRow(at: indexPath, animated: true) + guard !isLoadingMore, let item = dataSource.itemIdentifier(for: indexPath) else { return } + switch item { + case .resource(let id): dismiss(animated: true) { [select] in select(id) } + case .more: + isLoadingMore = true + applyRows() + Task { @MainActor [weak self] in + guard let self else { return } + (rows, hasMore) = await loadMore() + isLoadingMore = false + applyRows() + } + } + } + + /// 下拉关闭选择器时恢复正文可见性,由课程页面重新核验计时条件。 + func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { close() } +} diff --git a/suixinkan/UI/Training/TrainingExamViewController.swift b/suixinkan/UI/Training/TrainingExamViewController.swift index fa93ba0..9a3e930 100644 --- a/suixinkan/UI/Training/TrainingExamViewController.swift +++ b/suixinkan/UI/Training/TrainingExamViewController.swift @@ -1,12 +1,15 @@ import SnapKit import UIKit -/// 原生单选/多选答题页,支持逐题跳转、草稿恢复与确认交卷。 +/// 按需分页的原生考试页,增量保存草稿并持久恢复未知交卷结果。 @MainActor final class TrainingExamViewController: TrainingBaseViewController { - private let service: any TrainingServing - private let viewModel: TrainingExamViewModel + private let service: any TrainingDataServing + private let viewModel: TrainingRemoteExamViewModel private let resetDraft: Bool + private var openedResult = false + private var navigationIsScheduled = false + private var hasAppeared = false private let scrollView = UIScrollView() private let contentStack = TrainingUI.card() private let positionLabel = TrainingUI.label(style: .subheadline, color: AppColor.primary) @@ -20,10 +23,10 @@ final class TrainingExamViewController: TrainingBaseViewController { private let statusLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary) private let submitButton = AppButton(title: "交卷") - /// 重考时清除旧草稿,普通进入时恢复本人已保存的答案。 - init(taskID: String, service: any TrainingServing, resetDraft: Bool = false) { + /// 用户明确重考才传 resetDraft;默认恢复已有草稿和未确认提交。 + init(taskID: String, service: any TrainingDataServing, resetDraft: Bool = false, viewModel: TrainingRemoteExamViewModel? = nil) { self.service = service - viewModel = TrainingExamViewModel(taskID: taskID) + self.viewModel = viewModel ?? TrainingRemoteExamViewModel(taskID: taskID, context: TrainingPendingSubmissionStore.currentContext()) self.resetDraft = resetDraft super.init(nibName: nil, bundle: nil) } @@ -45,7 +48,6 @@ final class TrainingExamViewController: TrainingBaseViewController { navigationStack.distribution = .fillEqually navigationStack.addArrangedSubview(previousButton) navigationStack.addArrangedSubview(nextButton) - if service.isDemo { contentStack.addArrangedSubview(TrainingUI.demoNotice()) } [positionLabel, questionLabel, hintLabel, optionStack, navigationStack].forEach(contentStack.addArrangedSubview) bottomStack.axis = .vertical bottomStack.spacing = 8 @@ -84,35 +86,49 @@ final class TrainingExamViewController: TrainingBaseViewController { loadExam() } + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + let returning = hasAppeared + hasAppeared = true + if viewModel.submittedAttempt != nil || viewModel.shouldReturnToCenter { + Task { @MainActor in await viewModel.validateIdentity(); finishOperation() } + return + } + if returning, !viewModel.isBusy { loadExam() } + } + override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) } private func loadExam() { - submitButton.isEnabled = false + disableControls() Task { @MainActor in await viewModel.load(service: service, resetDraft: resetDraft) - applyState() + finishOperation() } } private func applyState() { for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() } - guard let task = viewModel.task, let question = viewModel.currentQuestion else { + let pendingTitle = viewModel.hasPendingSubmission ? "恢复交卷结果" + : viewModel.hasPendingMutation ? "重试保存" : viewModel.canRetryCurrentPage ? "重试加载本题" : nil + guard let question = viewModel.currentQuestion else { positionLabel.text = "" - questionLabel.text = viewModel.errorMessage ?? "正在加载试卷…" + questionLabel.text = viewModel.errorMessage ?? (viewModel.hasPendingSubmission ? "正在确认上次交卷结果…" : "正在加载试卷…") hintLabel.text = "" + statusLabel.text = viewModel.hasPendingSubmission ? "上次提交尚未确认,恢复结果后再继续操作" : "" navigationStack.isHidden = true - submitButton.setTitle("重新加载", for: .normal) - submitButton.isEnabled = viewModel.errorMessage != nil + submitButton.setTitle(pendingTitle ?? "重新加载", for: .normal) + submitButton.isEnabled = !viewModel.isBusy && (viewModel.errorMessage != nil || pendingTitle != nil) navigationItem.rightBarButtonItem?.isEnabled = false return } navigationStack.isHidden = false - navigationItem.rightBarButtonItem?.isEnabled = !viewModel.isBusy - positionLabel.text = "第 \(viewModel.currentIndex + 1) / \(task.questions.count) 题 · \(question.type == .single ? "单选题" : "多选题")" + navigationItem.rightBarButtonItem?.isEnabled = viewModel.canEdit + positionLabel.text = "第 \(viewModel.currentIndex + 1) / \(viewModel.questionCount) 题 · \(question.type == .single ? "单选题" : "多选题")" questionLabel.text = question.stem hintLabel.text = question.type == .single ? "请选择一个答案" : "请选择所有正确答案,少选、多选、错选均不得分" for (index, option) in question.options.enumerated() { - let selected = viewModel.answers[question.id]?.contains(option.id) == true + let selected = viewModel.currentSelectedIDs.contains(option.id) let button = UIButton(type: .system) var configuration = UIButton.Configuration.filled() configuration.title = "\(TrainingQuestion.optionLetter(index)).\(option.text)" @@ -127,44 +143,92 @@ final class TrainingExamViewController: TrainingBaseViewController { button.contentHorizontalAlignment = .leading button.titleLabel?.numberOfLines = 0 button.titleLabel?.lineBreakMode = .byWordWrapping - button.isEnabled = !viewModel.isBusy + button.isEnabled = viewModel.canEdit button.accessibilityIdentifier = "training.option.\(option.id)" button.accessibilityTraits = selected ? [.button, .selected] : .button button.addAction(UIAction { [weak self] _ in self?.selectOption(option.id) }, for: .touchUpInside) optionStack.addArrangedSubview(button) button.snp.makeConstraints { $0.height.greaterThanOrEqualTo(56) } } - previousButton.isEnabled = !viewModel.isBusy && viewModel.currentIndex > 0 - nextButton.isEnabled = !viewModel.isBusy && viewModel.currentIndex < task.questions.count - 1 - statusLabel.text = viewModel.errorMessage ?? "已答 \(viewModel.answeredCount)/\(task.questions.count) · 答案已保存,可稍后继续" + previousButton.isEnabled = viewModel.canEdit && viewModel.currentIndex > 0 + nextButton.isEnabled = viewModel.canEdit && viewModel.currentIndex < viewModel.questionCount - 1 + statusLabel.text = viewModel.errorMessage ?? "已答 \(viewModel.answeredCount)/\(viewModel.questionCount) · 答案已保存,可稍后继续" statusLabel.textColor = viewModel.errorMessage == nil ? AppColor.textSecondary : AppColor.danger - submitButton.setTitle(viewModel.isBusy ? "正在保存…" : "交卷", for: .normal) - submitButton.isEnabled = !viewModel.isBusy + submitButton.setTitle(pendingTitle ?? (viewModel.isBusy ? "正在保存…" : "交卷"), for: .normal) + submitButton.isEnabled = !viewModel.isBusy && (pendingTitle != nil || viewModel.canEdit) + } + + private func disableControls() { + optionStack.arrangedSubviews.compactMap { $0 as? UIButton }.forEach { $0.isEnabled = false } + [previousButton, nextButton, submitButton].forEach { $0.isEnabled = false } + navigationItem.rightBarButtonItem?.isEnabled = false + } + + private func finishOperation() { + applyState() + scheduleNavigationIfNeeded() + } + + private func scheduleNavigationIfNeeded() { + guard !openedResult, !navigationIsScheduled, + viewModel.shouldReturnToCenter || viewModel.submittedAttempt != nil, + let navigationController, navigationController.topViewController === self else { return } + navigationIsScheduled = true + let complete: @MainActor @Sendable () -> Void = { [weak self, weak navigationController] in + guard let self else { return } + self.navigationIsScheduled = false + guard let navigationController, navigationController.topViewController === self else { return } + // 返回页面的原 pop 必须先结束,否则新的成绩栈会被 UIKit 恢复成旧考试栈。 + if navigationController.transitionCoordinator != nil { self.scheduleNavigationIfNeeded(); return } + if self.viewModel.shouldReturnToCenter { self.returnToCenter() } + else if let attempt = self.viewModel.submittedAttempt { self.openResult(attempt) } + } + if let coordinator = navigationController.transitionCoordinator { + let registered = coordinator.animate(alongsideTransition: nil) { _ in + DispatchQueue.main.async(execute: complete) + } + if !registered { DispatchQueue.main.async(execute: complete) } + } else { DispatchQueue.main.async(execute: complete) } + } + + private func returnToCenter() { + guard let navigationController, navigationController.topViewController === self else { return } + if viewModel.isIdentityInvalid { + navigationController.popToRootViewController(animated: false) + return + } + if let center = navigationController.viewControllers.last(where: { $0 is TrainingCenterViewController }) { + navigationController.popToViewController(center, animated: true) + } else { navigationController.popToRootViewController(animated: true) } } private func selectOption(_ id: String) { + guard viewModel.canEdit else { return } + disableControls() Task { @MainActor in - let operation = Task { await viewModel.select(optionID: id, service: service) } - await Task.yield() - applyState() - await operation.value - applyState() + await viewModel.select(optionID: id, service: service) + finishOperation() } } private func goToQuestion(_ index: Int) { - viewModel.goToQuestion(index) - applyState() - scrollView.setContentOffset(.zero, animated: false) - UIAccessibility.post(notification: .screenChanged, argument: questionLabel) + guard viewModel.canEdit else { return } + disableControls() + Task { @MainActor in + await viewModel.goToQuestion(index, service: service) + finishOperation() + scrollView.setContentOffset(.zero, animated: false) + UIAccessibility.post(notification: .screenChanged, argument: questionLabel) + } } @objc private func previousTapped() { goToQuestion(viewModel.currentIndex - 1) } @objc private func nextTapped() { goToQuestion(viewModel.currentIndex + 1) } @objc private func answerCardTapped() { - guard let task = viewModel.task, !viewModel.isBusy else { return } - let controller = TrainingAnswerCardViewController(task: task, answers: viewModel.answers, currentIndex: viewModel.currentIndex) + guard viewModel.canEdit else { return } + let controller = TrainingAnswerCardViewController(questionCount: viewModel.questionCount, + answeredOrders: viewModel.answeredQuestionOrders, currentIndex: viewModel.currentIndex) controller.onSelect = { [weak self] index in self?.goToQuestion(index) } let navigation = UINavigationController(rootViewController: controller) if let sheet = navigation.sheetPresentationController { sheet.detents = [.medium(), .large()]; sheet.prefersGrabberVisible = true } @@ -173,52 +237,74 @@ final class TrainingExamViewController: TrainingBaseViewController { @objc private func submitTapped() { guard !viewModel.isBusy else { return } - guard let task = viewModel.task else { loadExam(); return } - if let missing = viewModel.firstUnansweredIndex { - goToQuestion(missing) - showToast("还有 \(task.questions.count - viewModel.answeredCount) 道题未作答,已定位到第一道") + if viewModel.hasPendingMutation { + disableControls() + Task { @MainActor in await viewModel.retryMutation(service: service); finishOperation() } return } - let alert = UIAlertController(title: "确认交卷?", message: "已完成 \(task.questions.count) 道题,提交后将生成本次考试记录。", preferredStyle: .alert) + if viewModel.hasPendingSubmission { performSubmit(); return } + if viewModel.canRetryCurrentPage { + disableControls() + Task { @MainActor in await viewModel.retryCurrentPage(service: service); finishOperation() } + return + } + guard viewModel.currentQuestion != nil else { loadExam(); return } + guard viewModel.canEdit else { return } + if let missing = viewModel.firstUnansweredIndex { + goToQuestion(missing) + showToast("还有 \(viewModel.questionCount - viewModel.answeredCount) 道题未作答,已定位到第一道") + return + } + let alert = UIAlertController(title: "确认交卷?", message: "已完成 \(viewModel.questionCount) 道题,提交后将生成本次考试记录。", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "继续检查", style: .cancel)) alert.addAction(UIAlertAction(title: "交卷", style: .default) { [weak self] _ in self?.performSubmit() }) present(alert, animated: true) } private func performSubmit() { + disableControls() Task { @MainActor in - let operation = Task { await viewModel.submit(service: service) } - await Task.yield() - applyState() - let attempt = await operation.value - applyState() - guard let attempt, let navigationController else { return } - let result = TrainingResultViewController(taskID: viewModel.taskID, attemptID: attempt.id, service: service) - navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [result], animated: true) + _ = await viewModel.submit(service: service) + finishOperation() } } + + private func openResult(_ attempt: TrainingAttemptSummary) { + guard !openedResult, let navigationController, navigationController.topViewController === self else { return } + openedResult = true + let result = TrainingResultViewController(taskID: viewModel.taskID, attemptID: attempt.id, service: service, initialDetail: viewModel.submittedResult) + navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [result], animated: true) + } } /// 可滚动的网格答题卡,支持最多 500 道题。 @MainActor final class TrainingAnswerCardViewController: UIViewController { - private let task: TrainingTask - private let answers: TrainingAnswers + private let questionCount: Int + private let answeredOrders: Set private let currentIndex: Int private let collectionView: UICollectionView private var dataSource: UICollectionViewDiffableDataSource! /// 关闭答题卡后将用户选择的题目位置返回考试页面。 var onSelect: ((Int) -> Void)? - /// 根据本次草稿展示已答和当前题,不显示正确答案。 - init(task: TrainingTask, answers: TrainingAnswers, currentIndex: Int) { - self.task = task - self.answers = answers + /// 使用总题数和已答题号展示答题卡,无需下载题目或全部答案。 + init(questionCount: Int, answeredOrders: Set, currentIndex: Int) { + self.questionCount = min(500, max(0, questionCount)) + self.answeredOrders = answeredOrders self.currentIndex = currentIndex collectionView = UICollectionView(frame: .zero, collectionViewLayout: Self.makeLayout()) super.init(nibName: nil, bundle: nil) } + /// 保留演示渲染测试的初始化入口,将本地试卷转换成轻量题号状态。 + convenience init(task: TrainingTask, answers: TrainingAnswers, currentIndex: Int) { + let orders = Set(task.questions.enumerated().compactMap { index, question in + (answers[question.id] ?? []).isEmpty ? nil : index + 1 + }) + self.init(questionCount: task.questions.count, answeredOrders: orders, currentIndex: currentIndex) + } + /// 保持原有五列、52 点行高与 12 点间距,随可用宽度自动计算列宽。 private static func makeLayout() -> UICollectionViewCompositionalLayout { UICollectionViewCompositionalLayout { _, environment in @@ -254,7 +340,7 @@ final class TrainingAnswerCardViewController: UIViewController { dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { [weak self] collection, indexPath, index in guard let self else { return nil } let cell = collection.dequeueReusableCell(withReuseIdentifier: "question", for: indexPath) - let answered = !(self.answers[self.task.questions[index].id] ?? []).isEmpty + let answered = self.answeredOrders.contains(index + 1) var content = UIListContentConfiguration.cell() content.text = "\(index + 1)" content.textProperties.alignment = .center @@ -272,7 +358,7 @@ final class TrainingAnswerCardViewController: UIViewController { } var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections([0]) - snapshot.appendItems(Array(task.questions.indices)) + snapshot.appendItems(Array(0.. Bool private var loadFailed = false private var showsDetails = false + private var usesInitialDetail: Bool + private var resultLoadTask: Task? private let scrollView = UIScrollView() private let contentStack = UIStackView() private let footer = UIView() private let actionButton = TrainingUI.button("完成,返回培训中心") /// 使用记录 ID 读取最新本人任务,禁止通过后从旧失败记录继续重考。 - init(taskID: String, attemptID: String, service: any TrainingServing) { + init(taskID: String, attemptID: String, service: any TrainingDataServing, initialDetail: TrainingAttemptDetail? = nil) { self.taskID = taskID self.attemptID = attemptID self.service = service + let session = AppStore.shared.session + let scope = session.accountCachePrefix + let token = session.token + let scenicID = session.currentScenicId + let storeID = session.currentStoreId + validateIdentity = { + let current = AppStore.shared.session + return current.accountCachePrefix == scope && current.token == token + && current.currentScenicId == scenicID && current.currentStoreId == storeID + } + viewModel = TrainingRemoteResultViewModel(attemptID: attemptID, initialDetail: initialDetail) + usesInitialDetail = initialDetail != nil super.init(nibName: nil, bundle: nil) } @@ -60,27 +74,40 @@ final class TrainingResultViewController: TrainingBaseViewController { } override func bindActions() { actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside) } - override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); loadResult() } + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + if leaveInaccessibleTaskIfNeeded() { return } + if usesInitialDetail, let detail = viewModel.detail { + usesInitialDetail = false + render(detail: detail) + } else { loadResult() } + } override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) } private func loadResult() { Task { @MainActor in await reload() } } - /// 页面出现时重新读取记录,失败可重试,不展示上个任务成绩。 + /// 页面出现时只刷新该次成绩,解析在用户展开后加载。 func reload() async { + if let resultLoadTask { await resultLoadTask.value; return } + let task = Task { @MainActor [weak self] in + await self?.performReload() + } + resultLoadTask = task + await task.value + resultLoadTask = nil + } + + private func performReload() async { actionButton.isEnabled = false - do { - let task = try await service.task(id: taskID) - guard let attempt = task.progress.attempts.first(where: { $0.id == attemptID }) else { throw TrainingError.notFound } - loadedTask = task - loadedAttempt = attempt + await viewModel.load(service: service) + if leaveInaccessibleTaskIfNeeded() { return } + if let detail = viewModel.detail { loadFailed = false - render(task: task, attempt: attempt) - } catch { - loadedTask = nil - loadedAttempt = nil + render(detail: detail) + } else { loadFailed = true clearContent() - contentStack.addArrangedSubview(TrainingUI.text(error.localizedDescription, color: TrainingUI.muted)) + contentStack.addArrangedSubview(TrainingUI.text(viewModel.errorMessage ?? "成绩加载失败", color: TrainingUI.muted)) setActionTitle("重新加载") } actionButton.isEnabled = true @@ -90,11 +117,22 @@ final class TrainingResultViewController: TrainingBaseViewController { for child in contentStack.arrangedSubviews { contentStack.removeArrangedSubview(child); child.removeFromSuperview() } } + private func leaveInaccessibleTaskIfNeeded() -> Bool { + let identityChanged = !validateIdentity() || viewModel.isIdentityInvalid + guard identityChanged || viewModel.isAccessRevoked else { return false } + clearContent() + if !identityChanged, + let center = navigationController?.viewControllers.first(where: { $0 is TrainingCenterViewController }) { + navigationController?.popToViewController(center, animated: true) + } else { navigationController?.popToRootViewController(animated: false) } + return true + } + private func setActionTitle(_ title: String) { var configuration = actionButton.configuration; configuration?.title = title; actionButton.configuration = configuration } - private func render(task: TrainingTask, attempt: TrainingAttempt) { + private func render(detail: TrainingAttemptDetail) { + let attempt = detail.attempt clearContent() - if attempt.isDemo { contentStack.addArrangedSubview(TrainingUI.demoNotice()) } let summary = UIStackView() summary.axis = .vertical summary.spacing = 11 @@ -118,9 +156,9 @@ final class TrainingResultViewController: TrainingBaseViewController { score.spacing = 6 score.snp.makeConstraints { $0.height.greaterThanOrEqualTo(69) } summary.addArrangedSubview(score) - let detail = TrainingUI.text("\(task.passScore) 分及格 · \(TrainingUI.date(attempt.submittedAt))", size: 12.5, color: TrainingUI.muted) - detail.textAlignment = .center - summary.addArrangedSubview(detail) + let dateLabel = TrainingUI.text("\(attempt.passScore) 分及格 · \(TrainingUI.date(attempt.submittedAt))", size: 12.5, color: TrainingUI.muted) + dateLabel.textAlignment = .center + summary.addArrangedSubview(dateLabel) contentStack.addArrangedSubview(summary) let counts = TrainingUI.card() let row = UIStackView(arrangedSubviews: [TrainingUI.text("答对 \(attempt.correctCount) 题"), TrainingUI.text("答错 \(attempt.questionCount - attempt.correctCount) 题")]) @@ -131,44 +169,74 @@ final class TrainingResultViewController: TrainingBaseViewController { let details = TrainingUI.button(showsDetails ? "收起答案解析" : "查看答案解析", secondary: true) details.accessibilityIdentifier = "training.result.details" details.addTarget(self, action: #selector(toggleDetails), for: .touchUpInside) + details.isEnabled = attempt.reviewAvailable && !viewModel.isLoadingReviews contentStack.addArrangedSubview(details) let learning = TrainingUI.button("返回学习", plain: true) learning.accessibilityIdentifier = "training.result.learning" learning.addTarget(self, action: #selector(returnToLearning), for: .touchUpInside) contentStack.addArrangedSubview(learning) - if showsDetails { - for (index, review) in attempt.reviews.enumerated() { + if showsDetails && attempt.reviewAvailable { + for review in viewModel.reviews { let card = TrainingUI.card() - let top = UIStackView(arrangedSubviews: [TrainingUI.text("第 \(index + 1) 题", size: 12.5, color: TrainingUI.muted), TrainingUI.text(review.isCorrect ? "回答正确" : "回答错误", size: 12, color: review.isCorrect ? TrainingUI.success : .systemRed)]) + let top = UIStackView(arrangedSubviews: [TrainingUI.text("第 \(review.order) 题", size: 12.5, color: TrainingUI.muted), TrainingUI.text(review.isCorrect ? "回答正确" : "回答错误", size: 12, color: review.isCorrect ? TrainingUI.success : .systemRed)]) top.distribution = .equalSpacing card.addArrangedSubview(top) - card.addArrangedSubview(TrainingUI.text(review.question.stem, size: 15.5, weight: .semibold)) - for (optionIndex, option) in review.question.options.enumerated() { + card.addArrangedSubview(TrainingUI.text(review.stem, size: 15.5, weight: .semibold)) + for (optionIndex, option) in review.options.enumerated() { card.addArrangedSubview(TrainingUI.text("\(TrainingQuestion.optionLetter(optionIndex)). \(option.text)", size: 13.5, color: UIColor(red: 92/255, green: 108/255, blue: 132/255, alpha: 1))) } func letters(_ ids: Set) -> String { - let values = review.question.options.enumerated().compactMap { ids.contains($0.element.id) ? TrainingQuestion.optionLetter($0.offset) : nil } + let values = review.options.enumerated().compactMap { ids.contains($0.element.id) ? TrainingQuestion.optionLetter($0.offset) : nil } return values.isEmpty ? "未作答" : values.joined(separator: "、") } - card.addArrangedSubview(TrainingUI.text("你的答案:\(letters(review.selectedIDs)) · 正确答案:\(letters(review.correctIDs))", size: 12.5, color: TrainingUI.muted)) + card.addArrangedSubview(TrainingUI.text("你的答案:\(letters(Set(review.selectedOptionIDs))) · 正确答案:\(letters(Set(review.correctOptionIDs)))", size: 12.5, color: TrainingUI.muted)) card.addArrangedSubview(TrainingUI.notice(review.explanation.isEmpty ? "暂无解析" : review.explanation)) contentStack.addArrangedSubview(card) } } - let canRetry = !attempt.passed && task.submissionBlockReason(now: Date()) == nil + if showsDetails && attempt.reviewAvailable { + if let error = viewModel.reviewErrorMessage { contentStack.addArrangedSubview(TrainingUI.notice(error)) } + if viewModel.isLoadingReviews { contentStack.addArrangedSubview(TrainingUI.text("正在加载解析…", color: TrainingUI.muted)) } + if viewModel.hasMoreReviews || viewModel.reviewErrorMessage != nil { + let more = TrainingUI.button(viewModel.reviewErrorMessage != nil ? "重试加载解析" : "加载更多解析", plain: true) + more.isEnabled = !viewModel.isLoadingReviews + more.addTarget(self, action: #selector(moreReviewsTapped), for: .touchUpInside) + contentStack.addArrangedSubview(more) + } + } + let canRetry = !attempt.passed && detail.taskState.canRetry contentStack.addArrangedSubview(TrainingUI.text(canRetry ? "截止前可不限次数重考,每次成绩都会保留。" : "本次记录只读,可回顾课程内容和答案解析。", size: 12, color: TrainingUI.muted)) setActionTitle(canRetry ? "再考一次" : "完成,返回培训中心") } @objc private func toggleDetails() { - guard let task = loadedTask, let attempt = loadedAttempt else { return } + if leaveInaccessibleTaskIfNeeded() { return } + guard let detail = viewModel.detail else { return } showsDetails.toggle() - render(task: task, attempt: attempt) + render(detail: detail) + guard showsDetails else { return } + Task { @MainActor [weak self] in + guard let self else { return } + await viewModel.loadReviews(service: service) + if leaveInaccessibleTaskIfNeeded() { return } + if let current = viewModel.detail { render(detail: current) } + } + } + + @objc private func moreReviewsTapped() { + if leaveInaccessibleTaskIfNeeded() { return } + Task { @MainActor [weak self] in + guard let self else { return } + await viewModel.loadReviews(service: service, nextPage: viewModel.hasLoadedReviews) + if leaveInaccessibleTaskIfNeeded() { return } + if let current = viewModel.detail { render(detail: current) } + } } /// 无论是否通过都能返回本次课程,优先复用导航栈中的课程页面。 @objc private func returnToLearning() { - guard loadedTask != nil, let navigationController else { return } + if leaveInaccessibleTaskIfNeeded() { return } + guard viewModel.detail != nil, let navigationController else { return } if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) { navigationController.popToViewController(course, animated: true) } else { @@ -177,9 +245,10 @@ final class TrainingResultViewController: TrainingBaseViewController { } @objc private func actionTapped() { + if leaveInaccessibleTaskIfNeeded() { return } if loadFailed { loadResult(); return } - guard let task = loadedTask, let attempt = loadedAttempt, let navigationController else { return } - if !attempt.passed, task.submissionBlockReason(now: Date()) == nil { + guard let detail = viewModel.detail, let navigationController else { return } + if !detail.attempt.passed, detail.taskState.canRetry { navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [TrainingExamViewController(taskID: taskID, service: service, resetDraft: true)], animated: true) } else if let center = navigationController.viewControllers.last(where: { $0 is TrainingCenterViewController }) { navigationController.popToViewController(center, animated: true) diff --git a/suixinkan/UI/Training/TrainingUI.swift b/suixinkan/UI/Training/TrainingUI.swift index ba45048..ce35ba5 100644 --- a/suixinkan/UI/Training/TrainingUI.swift +++ b/suixinkan/UI/Training/TrainingUI.swift @@ -199,6 +199,28 @@ final class TrainingTaskCell: UITableViewCell { footer.axis = traitCollection.preferredContentSizeCategory.isAccessibilityCategory ? .vertical : .horizontal } + /// 正式任务卡只展示摘要和服务端资格,不由本地时钟推断是否可交卷。 + func configure(task: TrainingTaskSummary) { + titleLabel.text = task.title + deadlineLabel.text = task.endAt.map { "截止时间:\(TrainingUI.date($0))" } ?? "未设置截止时间" + statusLabel.text = task.learnerStatus.title + statusLabel.textColor = task.learnerStatus == .completed ? TrainingUI.success : TrainingUI.primary + let publisher = task.publisherName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + publisherLabel.text = "发布人:\(publisher.isEmpty ? "未记录" : publisher)" + metaLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.sectionCount) 节 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格" : "仅学习 · \(task.sectionCount) 节" + let completed = task.learnerStatus == .completed + hintLabel.text = completed ? "已完成本次学习任务" : task.learning.canStartExam ? "课程已学完,可以开始考试" : task.learning.canStudy ? "请阅读课程,完成学习要求" : "任务暂不可提交,可回顾课程内容" + let progress = min(100, max(0, task.learning.progressPercent)) + progressView.progress = Float(progress) / 100 + progressLabel.text = "学习进度 \(progress)%" + var configuration = actionButton.configuration + configuration?.title = completed ? "回顾学习" : task.learning.canStartExam ? (task.learning.hasDraft ? "继续答题" : "开始考试") : task.learning.canStudy ? "去学习" : "查看课程" + actionButton.configuration = configuration + actionButton.isEnabled = task.learning.canViewCourse || task.learning.canStartExam + actionButton.accessibilityIdentifier = "training.task.action.\(task.id)" + footer.axis = traitCollection.preferredContentSizeCategory.isAccessibilityCategory ? .vertical : .horizontal + } + @objc private func actionTapped() { onAction?() } } @@ -245,6 +267,15 @@ final class TrainingRecordCell: UITableViewCell { statusLabel.text = attempt.passed ? "已通过" : "未通过" statusLabel.textColor = attempt.passed ? TrainingUI.success : .systemRed } + + /// 正式历史列表使用成绩摘要,不读取任务或完整解析。 + func configure(attempt: TrainingAttemptSummary) { + titleLabel.text = attempt.taskTitle + scoreLabel.text = "\(attempt.scoreText) 分" + detailLabel.text = "\(TrainingUI.date(attempt.submittedAt)) · 答对 \(attempt.correctCount) / \(attempt.questionCount) 题" + statusLabel.text = attempt.passed ? "已通过" : "未通过" + statusLabel.textColor = attempt.passed ? TrainingUI.success : .systemRed + } } /// 培训页面在账号或景区切换时立即关闭,停止展示旧身份记录。 diff --git a/suixinkanTests/APIClientTests.swift b/suixinkanTests/APIClientTests.swift index 979ba97..9906ed7 100644 --- a/suixinkanTests/APIClientTests.swift +++ b/suixinkanTests/APIClientTests.swift @@ -40,6 +40,45 @@ final class APIClientTests: XCTestCase { XCTAssertEqual(session.requests[0].value(forHTTPHeaderField: "token"), "test-token-abc") } + func testQueryPreservesOpaqueCursorWithPlusAndDoesNotEncodePercentTwice() async throws { + let responseData = try TestJSON.envelope(data: AppConfigResponse(enableRegister: false)) + let session = MockURLSession(responses: [responseData]) + let client = APIClient(environment: .testing, session: session) + let cursor = "base64+part/with=padding 中文" + let literalPercent = "%2B already encoded text" + + let _: AppConfigResponse = try await client.send(APIRequest( + method: .get, + path: "/api/app/config", + queryItems: [ + URLQueryItem(name: "cursor", value: cursor), + URLQueryItem(name: "literal", value: literalPercent), + ] + )) + + let url = try XCTUnwrap(session.requests.first?.url) + let components = try XCTUnwrap(URLComponents(url: url, resolvingAgainstBaseURL: false)) + let encodedQuery = try XCTUnwrap(components.percentEncodedQuery) + XCTAssertFalse(encodedQuery.contains("+")) + XCTAssertTrue(encodedQuery.contains("base64%2Bpart")) + XCTAssertTrue(encodedQuery.contains("part/with%3Dpadding"), "保留原有斜线编码语义,等号仍作为值编码") + XCTAssertTrue(encodedQuery.contains("%20")) + XCTAssertTrue(encodedQuery.contains("%E4%B8%AD%E6%96%87")) + XCTAssertTrue(encodedQuery.contains("literal=%252B%20"), "请求值中的字面百分号只编码一次") + XCTAssertFalse(encodedQuery.contains("base64%252B"), "修正生成的 %2B 不能再次编码为 %252B") + + // 模拟 PHP/Laravel 常见的 form-query 解析,区别于 URLComponents 对 + 的保留行为。 + let decodedPairs = encodedQuery.split(separator: "&").map { pair -> (String, String) in + let parts = pair.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false) + let name = String(parts[0]).replacingOccurrences(of: "+", with: " ").removingPercentEncoding ?? "" + let value = String(parts[1]).replacingOccurrences(of: "+", with: " ").removingPercentEncoding ?? "" + return (name, value) + } + let decoded = Dictionary(uniqueKeysWithValues: decodedPairs) + XCTAssertEqual(decoded["cursor"], cursor, "加号、空格、斜线、等号和中文均须原样到达后端") + XCTAssertEqual(decoded["literal"], literalPercent) + } + func testSendThrowsServerCodeErrorForBusinessFailure() async throws { let responseData = try TestJSON.errorEnvelope(code: 100001, msg: "密码错误") let session = MockURLSession(responses: [responseData]) @@ -97,6 +136,49 @@ final class APIClientTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } + func testExpiredResponseFromReplacedTokenDoesNotExpireNewSession() async throws { + let center = NotificationCenter() + let expired = XCTNSNotificationExpectation(name: NotificationName.sessionDidExpire, object: nil, notificationCenter: center) + expired.isInverted = true + let token = APIClientTestTokenState("old-token") + let session = APIClientExpiredResponseSession( + response: try TestJSON.errorEnvelope(code: 100060, msg: "旧 Token 已失效"), + beforeResponse: { token.value = "new-token" } + ) + let client = APIClient(environment: .testing, session: session, notificationCenter: center) + client.bindAuthTokenProvider { token.value } + + do { + let _: AppConfigResponse = try await client.send(APIRequest(method: .get, path: "/api/app/config")) + XCTFail("旧请求仍须向调用者返回原始失败") + } catch let APIError.serverCode(code, _) { + XCTAssertEqual(code, 100060) + } + + let sentToken = await session.requestToken + XCTAssertEqual(sentToken, "old-token") + XCTAssertEqual(token.value, "new-token") + await fulfillment(of: [expired], timeout: 0.1) + } + + func testExpiredResponseForCurrentTokenStillExpiresSession() async throws { + let center = NotificationCenter() + let expired = XCTNSNotificationExpectation(name: NotificationName.sessionDidExpire, object: nil, notificationCenter: center) + let token = APIClientTestTokenState("current-token") + let session = APIClientExpiredResponseSession( + response: try TestJSON.errorEnvelope(code: 180024, msg: "Token 已失效"), + beforeResponse: { token.value = "current-token" } + ) + let client = APIClient(environment: .testing, session: session, notificationCenter: center) + client.bindAuthTokenProvider { token.value } + + _ = try? await client.send(APIRequest(method: .get, path: "/api/app/config")) + + let sentToken = await session.requestToken + XCTAssertEqual(sentToken, "current-token") + await fulfillment(of: [expired], timeout: 1) + } + func testMultipartUploadBuildsAndroidCompatibleRequest() async throws { let session = MockURLSession(responses: [try TestJSON.envelope(data: EmptyPayload())]) let client = APIClient( @@ -152,3 +234,28 @@ final class APIClientTests: XCTestCase { } } } + +/// 网络等待期间可以切换的主 Actor 凭证,避免并发测试修改捕获变量。 +@MainActor +private final class APIClientTestTokenState { + var value: String + init(_ value: String) { self.value = value } +} + +/// 在请求已发出、响应返回前切换会话,模拟真实账号切换时的迟到失败。 +private actor APIClientExpiredResponseSession: URLSessionProtocol { + private let response: Data + private let beforeResponse: @MainActor @Sendable () -> Void + private(set) var requestToken: String? + + init(response: Data, beforeResponse: @escaping @MainActor @Sendable () -> Void) { + self.response = response + self.beforeResponse = beforeResponse + } + + func data(for request: URLRequest) async throws -> (Data, URLResponse) { + requestToken = request.value(forHTTPHeaderField: "token") + await beforeResponse() + return (response, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + } +} diff --git a/suixinkanTests/HomeViewModelTests.swift b/suixinkanTests/HomeViewModelTests.swift index 9235fea..ca35a6a 100644 --- a/suixinkanTests/HomeViewModelTests.swift +++ b/suixinkanTests/HomeViewModelTests.swift @@ -83,7 +83,7 @@ final class HomeViewModelTests: XCTestCase { ]) let viewModel = HomeViewModel(appStore: appStore) viewModel.rebuildCommonMenus() - XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "/training"]) + XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet"]) } func testRebuildCommonMenusPersistsDefaultURIsOnFirstLoad() { @@ -100,7 +100,7 @@ final class HomeViewModelTests: XCTestCase { viewModel.rebuildCommonMenus() XCTAssertEqual(viewModel.commonMenus.map(\.uri), [ - "wallet", "cloud_management", "task_management", "system_settings", "/training", + "wallet", "cloud_management", "task_management", "system_settings", ]) XCTAssertEqual( menuStore.savedCommonURIs( @@ -120,7 +120,7 @@ final class HomeViewModelTests: XCTestCase { await viewModel.loadPermissions(api: api, force: true) XCTAssertTrue(viewModel.showPermissionDialog) - XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["/training"]) + XCTAssertTrue(viewModel.commonMenus.isEmpty) } func testPermissionApplyDestinationRoutesReviewingAndRejectedToStatus() async throws { @@ -200,7 +200,7 @@ final class HomeViewModelTests: XCTestCase { XCTAssertFalse(viewModel.showPermissionDialog) XCTAssertTrue(viewModel.isMinimalTopRole) - XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "cloud_management", "/training"]) + XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "cloud_management"]) XCTAssertEqual(viewModel.storeItem?.name, "测试门店") } @@ -227,10 +227,22 @@ final class HomeViewModelTests: XCTestCase { viewModel.markNeedsPermissionReload() await viewModel.reloadIfNeeded(api: api) - XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "/training"]) + XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet"]) XCTAssertEqual(session.requests.count, 1) } + /// 培训入口仅向店铺账号开放,权限菜单不能绕过账号类型限制。 + func testTrainingEntryIsStoreOnlyAndDoesNotDuplicatePermissionMenu() { + appStore.permissions.savePermissionItems([HomePermissionItem(id: "training", name: "培训", uri: "/training")]) + let viewModel = HomeViewModel(appStore: appStore) + viewModel.rebuildCommonMenus() + XCTAssertFalse(viewModel.commonMenus.contains { $0.uri == "/training" }) + appStore.session.accountType = .storeUser + appStore.permissions.savePermissionItems([HomePermissionItem(id: "training", name: "培训", uri: "/training")]) + viewModel.rebuildCommonMenus() + XCTAssertEqual(viewModel.commonMenus.filter { $0.uri == "/training" }.count, 1) + } + func testUnreadMessageStatusUsesCountEndpointAndUpdatesBadgeState() async { let api = HomeMessageCenterAPIMock() api.unreadCountResponses = [ diff --git a/suixinkanTests/TrainingAPITests.swift b/suixinkanTests/TrainingAPITests.swift new file mode 100644 index 0000000..7d06c8e --- /dev/null +++ b/suixinkanTests/TrainingAPITests.swift @@ -0,0 +1,261 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 正式培训契约测试:校验独立资源、请求体、日期、稳定错误及身份边界。 +@MainActor +final class TrainingAPITests: XCTestCase { + private let dateText = "2026-10-14T10:00:00+08:00" + + func testSummaryTaskPageAndFlatDetailDecodeServerTypes() async throws { + var detail = taskJSON + detail.merge(["required_reading_seconds": 20, "reading_rule": "course_duration", "scoring": NSNull(), "server_time": dateText]) { _, new in new } + let session = MockURLSession(responses: [ + try envelope(["pending_count": 7, "completed_count": 12, "latest_attempt": NSNull(), "server_time": dateText]), + try envelope(["items": [taskJSON], "next_cursor": NSNull(), "has_more": false, "server_time": dateText]), + try envelope(detail), + try envelope(["items": [], "next_cursor": NSNull(), "has_more": false, "server_time": dateText]), + ]) + let client = APIClient(environment: .testing, session: session) + client.bindAuthTokenProvider { "current-token" } + let api = TrainingAPI(client: client) + + let summary = try await api.summary() + let page = try await api.tasks(status: .pendingExam, keyword: "游客 服务", cursor: nil, limit: 3) + let task = try await api.task(id: "task_101") + let empty = try await api.tasks(status: nil, keyword: "", cursor: "cursor+opaque", limit: 80) + + XCTAssertEqual(summary.pendingCount, 7) + XCTAssertNil(summary.latestAttempt) + XCTAssertEqual(page.items.first?.learnerStatus, .pendingExam) + XCTAssertNil(page.items.first?.startAt) + XCTAssertNil(page.items.first?.endAt) + XCTAssertNil(page.items.first?.paperSnapshotID) + XCTAssertNil(page.items.first?.passScore) + XCTAssertEqual(task.summary.id, "task_101") + XCTAssertEqual(task.requiredReadingSeconds, 20) + XCTAssertEqual(task.readingRule, "course_duration") + XCTAssertEqual(task.serverTime, try XCTUnwrap(ISO8601DateFormatter().date(from: dateText))) + XCTAssertTrue(empty.items.isEmpty) + XCTAssertNil(empty.nextCursor) + XCTAssertEqual(try query(session.requests[1]), ["learner_status": "pending", "keyword": "游客 服务", "limit": "3"]) + XCTAssertEqual(try query(session.requests[3]), ["cursor": "cursor+opaque", "limit": "50"]) + XCTAssertEqual(session.requests[0].value(forHTTPHeaderField: "token"), "current-token") + XCTAssertEqual(session.requests[0].value(forHTTPHeaderField: "X-OS-TYPE"), "iOS") + } + + func testCourseResourcesCarryTaskAuthorizationAndDoNotAggregate() async throws { + let session = MockURLSession(responses: [ + try envelope(["course_snapshot_id": "cs_3", "title": "规范", "introduction": "简介", "section_count": 1, "attachment_count": 1]), + try envelope(["items": [["section_id": "section_1", "order": 1, "title": "正文"]], "next_cursor": NSNull(), "has_more": false]), + try envelope(["section_id": "section_1", "order": 1, "title": "正文", "content_html": "

正式内容

"]), + try envelope(["items": [["attachment_id": "file_1", "name": "规范.pdf", "mime_type": "application/pdf", "size_bytes": 4096, "file_id": "file_1", "download_url": NSNull(), "expires_at": NSNull()]], "next_cursor": NSNull(), "has_more": false]), + try envelope(["attachment_id": "file_1", "name": "规范.pdf", "url": "https://files.zhifly.cn/private?signature=one", "expires_at": dateText]), + ]) + let api = TrainingAPI(client: APIClient(environment: .testing, session: session)) + let course = try await api.course(id: "cs_3", taskID: "task_101") + let sections = try await api.sections(courseID: "cs_3", taskID: "task_101", cursor: nil, limit: 20) + let content = try await api.section(courseID: "cs_3", sectionID: "section_1", taskID: "task_101") + let attachments = try await api.attachments(courseID: "cs_3", taskID: "task_101", cursor: "attachment-cursor", limit: 20) + let link = try await api.attachmentURL(courseID: "cs_3", attachmentID: "file_1", taskID: "task_101") + + XCTAssertEqual(course.id, "cs_3") + XCTAssertEqual(sections.items.first?.id, "section_1") + XCTAssertEqual(content.contentHTML, "

正式内容

") + XCTAssertNil(attachments.items.first?.downloadURL) + XCTAssertEqual(link.url.host, "files.zhifly.cn") + XCTAssertEqual(session.requests.count, 5) + for request in session.requests { + XCTAssertEqual(request.httpMethod, "GET") + XCTAssertEqual(try query(request)["task_id"], "task_101") + } + XCTAssertEqual(session.requests[2].url?.path, "/api/app/training/courses/cs_3/sections/section_1") + XCTAssertEqual(session.requests[4].url?.path, "/api/app/training/courses/cs_3/attachments/file_1") + XCTAssertEqual(try query(session.requests[3])["cursor"], "attachment-cursor") + } + + func testReadingSessionAndHeartbeatKeepCallerIdempotencyData() async throws { + let session = MockURLSession(responses: [ + try envelope(progressJSON), + try envelope(["session_id": "session-uuid", "expires_at": dateText, "heartbeat_interval_seconds": 5, "max_heartbeat_gap_seconds": 15, "progress": progressJSON]), + try envelope(["session_id": "session-uuid", "accepted_sequence": 1, "accepted_active_seconds_total": 5, "session_closed": true, "progress": progressJSON]), + ]) + let api = TrainingAPI(client: APIClient(environment: .testing, session: session)) + let progress = try await api.progress(taskID: "task_101") + let reading = try await api.startReading(taskID: "task_101", requestID: "read-id") + let confirmation = try await api.heartbeat(sessionID: reading.sessionID, sequence: 1, activeSecondsTotal: 5, final: true) + + XCTAssertEqual(progress.readingSeconds, 12) + XCTAssertEqual(reading.heartbeatIntervalSeconds, 5) + XCTAssertEqual(confirmation.acceptedSequence, 1) + XCTAssertEqual(confirmation.acceptedActiveSecondsTotal, 5) + XCTAssertTrue(confirmation.sessionClosed) + XCTAssertEqual(try body(session.requests[1])["request_id"] as? String, "read-id") + let heartbeat = try body(session.requests[2]) + XCTAssertEqual(Set(heartbeat.keys), ["sequence", "active_seconds_total", "final"]) + XCTAssertEqual(heartbeat["active_seconds_total"] as? Int, 5) + XCTAssertEqual(heartbeat["final"] as? Bool, true) + } + + func testQuestionDraftAndPatchUseFrozenPositionsAndVersion() async throws { + let session = MockURLSession(responses: [ + try envelope(["paper_snapshot_id": "ps_3", "scoring": "equal-percentage-v1", "question_count": 30, "max_options_per_question": 6]), + try envelope(["paper_snapshot_id": "ps_3", "total": 30, "offset": 10, "next_offset": 20, "has_more": true, "items": [questionJSON]]), + try envelope(draftJSON), + try envelope(["draft_revision": 5, "saved_at": dateText, "answered_count": 2]), + try envelope(["draft_revision": 8, "saved_at": dateText, "answered_count": 3]), + ]) + let api = TrainingAPI(client: APIClient(environment: .testing, session: session)) + let paper = try await api.paper(id: "ps_3", taskID: "task_101") + let questions = try await api.questions(paperID: "ps_3", taskID: "task_101", offset: 10, limit: 10) + let draft = try await api.draft(taskID: "task_101", offset: 0, limit: 0) + let saved = try await api.saveDraft(taskID: "task_101", request: TrainingDraftSaveRequest(requestID: "save-id", paperSnapshotID: "ps_3", baseRevision: 4, lastQuestionOrder: 11, changes: [TrainingDraftChange(questionID: "101", selectedOptionIDs: ["A", "B"])])) + let reset = try await api.resetDraft(taskID: "task_101", request: TrainingDraftResetRequest(requestID: "reset-id", paperSnapshotID: "ps_3", baseRevision: 5)) + + XCTAssertEqual(paper.questionCount, 30) + XCTAssertEqual(questions.items.first?.id, "101") + XCTAssertEqual(questions.items.first?.options.map(\.id), ["A", "B"]) + XCTAssertEqual(questions.offset, 10) + XCTAssertEqual(draft.answeredQuestionOrders, [1, 11]) + XCTAssertNil(draft.savedAt) + XCTAssertEqual(try query(session.requests[2])["limit"], "0") + XCTAssertEqual(saved.draftRevision, 5) + XCTAssertEqual(reset.draftRevision, 8) + XCTAssertEqual(reset.answeredCount, 3, "重置重试可能返回已重新作答的实况,不能假定为零") + XCTAssertEqual(session.requests[3].httpMethod, "PATCH") + let patch = try body(session.requests[3]) + XCTAssertEqual(patch["request_id"] as? String, "save-id") + XCTAssertEqual(patch["base_revision"] as? Int, 4) + let changes = try XCTUnwrap(patch["changes"] as? [[String: Any]]) + XCTAssertEqual(changes.first?["selected_option_ids"] as? [String], ["A", "B"]) + XCTAssertEqual(session.requests[4].url?.path, "/api/app/training/tasks/task_101/draft/reset") + } + + func testSubmissionUsesOnlyDraftVersionAndResultRecoveryIsPrecise() async throws { + let taskState: [String: Any] = ["learner_status": "completed", "completed_at": dateText, "can_retry": false, "block_reason": "completed"] + var review = questionJSON + review.merge(["selected_option_ids": ["A"], "correct_option_ids": ["A"], "is_correct": true, "explanation": "说明服务规则"]) { _, new in new } + let session = MockURLSession(responses: [ + try envelope(["attempt": attemptJSON, "task_state": taskState, "draft_revision": 6, "server_time": dateText]), + try envelope(["items": [attemptJSON], "next_cursor": NSNull(), "has_more": false]), + try envelope(["attempt": attemptJSON, "task_state": taskState, "server_time": dateText]), + try envelope(["attempt_id": "attempt_12", "items": [review], "next_cursor": NSNull(), "has_more": false]), + ]) + let api = TrainingAPI(client: APIClient(environment: .testing, session: session)) + let result = try await api.submit(taskID: "task_101", request: TrainingSubmissionRequest(submissionID: "submit-id", paperSnapshotID: "ps_3", draftRevision: 5)) + let recovered = try await api.attempts(taskID: "task_101", submissionID: "submit-id", cursor: nil, limit: 1) + let detail = try await api.attempt(id: "attempt_12") + let reviews = try await api.reviews(attemptID: "attempt_12", cursor: nil, limit: 50) + + let submission = try body(session.requests[0]) + XCTAssertEqual(Set(submission.keys), ["submission_id", "paper_snapshot_id", "draft_revision"]) + XCTAssertNil(submission["answers"]) + XCTAssertEqual(result.attempt.id, "attempt_12") + XCTAssertEqual(result.attempt.scoreText, "87.5") + XCTAssertEqual(result.draftRevision, 6) + XCTAssertEqual(recovered.items.first?.id, result.attempt.id) + XCTAssertEqual(try query(session.requests[1]), ["task_id": "task_101", "submission_id": "submit-id", "limit": "1"]) + XCTAssertFalse(detail.taskState.canRetry) + XCTAssertEqual(reviews.items.first?.correctOptionIDs, ["A"]) + XCTAssertEqual(try query(session.requests[3])["limit"], "10") + } + + func testStableTrainingErrorsAreMappedWithoutSwallowingAuthenticationErrors() async throws { + let codes = Array(150100...150113) + let responses = try codes.map { try TestJSON.errorEnvelope(code: $0, msg: "业务错误") } + [try TestJSON.errorEnvelope(code: 100060, msg: "登录失效")] + let api = TrainingAPI(client: APIClient(environment: .testing, session: MockURLSession(responses: responses))) + for code in codes { + do { _ = try await api.summary(); XCTFail("应抛培训业务错误") } + catch let error as TrainingRemoteError { + XCTAssertEqual(error.code, code) + XCTAssertEqual(error.errorDescription, "业务错误") + } + } + do { _ = try await api.summary(); XCTFail("应保留登录失效错误") } + catch let APIError.serverCode(code, _) { XCTAssertEqual(code, 100060) } + } + + func testInvalidAccountAndChangedIdentityNeverDeliverTrainingData() async throws { + let unused = MockURLSession(responses: [try envelope([:])]) + let ineligible = TrainingAPI(client: APIClient(environment: .testing, session: unused), eligible: false) + do { _ = try await ineligible.summary(); XCTFail("应拒绝非店铺身份") } + catch let error as TrainingRemoteError { XCTAssertEqual(error.code, 150100) } + XCTAssertTrue(unused.requests.isEmpty) + + let before = TrainingAPI(client: APIClient(environment: .testing, session: unused), validateContext: { false }) + do { _ = try await before.summary(); XCTFail("请求前应校验身份") } + catch let error as TrainingRemoteError { XCTAssertEqual(error, .identityChanged) } + XCTAssertTrue(unused.requests.isEmpty) + + let identity = TrainingAPITestIdentity() + let delayed = TrainingIdentityChangingSession(response: try envelope(["pending_count": 0, "completed_count": 0, "latest_attempt": NSNull(), "server_time": dateText]), change: { identity.isCurrent = false }) + let after = TrainingAPI(client: APIClient(environment: .testing, session: delayed), tokenOverride: "frozen-token", validateContext: { identity.isCurrent }) + do { _ = try await after.summary(); XCTFail("迟到响应不得返回给新身份") } + catch let error as TrainingRemoteError { XCTAssertEqual(error, .identityChanged) } + let token = await delayed.lastToken + XCTAssertEqual(token, "frozen-token") + } + + func testRFC3339FractionalSecondsAndInvalidDatesStayLocalToTrainingDTOs() throws { + let decoder = JSONDecoder() + let json = #"{"attempt_id":"attempt_1","score_hundredths":9999,"submitted_at":"2026-10-14T10:00:00.123+08:00"}"# + let attempt = try decoder.decode(TrainingLatestAttempt.self, from: Data(json.utf8)) + XCTAssertEqual(attempt.submittedAt.timeIntervalSince1970.truncatingRemainder(dividingBy: 1), 0.123, accuracy: 0.001) + let invalid = json.replacingOccurrences(of: "2026-10-14T10:00:00.123+08:00", with: "2026-10-14 10:00:00") + XCTAssertThrowsError(try decoder.decode(TrainingLatestAttempt.self, from: Data(invalid.utf8))) + } + + private var flagsJSON: [String: Any] { + ["progress_percent": 0, "reading_completed": false, "has_draft": false, "can_view_course": true, "can_study": true, "can_start_exam": false, "block_reason": "reading_required"] + } + private var taskJSON: [String: Any] { + ["task_id": "task_101", "title": "规范培训", "publisher_name": NSNull(), "mode": "study", "task_status": "published", "learner_status": "pending", "start_at": NSNull(), "end_at": NSNull(), "course_snapshot_id": "cs_3", "course_title": "规范", "paper_snapshot_id": NSNull(), "section_count": 1, "question_count": 0, "pass_score": NSNull(), "learning": flagsJSON] + } + private var progressJSON: [String: Any] { + var fields = flagsJSON + fields.merge(["task_id": "task_101", "reading_seconds": 12, "required_reading_seconds": 20, "completed_section_count": 0, "section_count": 1, "learner_status": "pending", "completed_at": NSNull(), "can_retry": false, "server_time": dateText]) { _, new in new } + return fields + } + private var questionJSON: [String: Any] { + ["question_id": "101", "order": 11, "type": "multiple", "stem": "请选择", "options": [["option_id": "A", "text": "说明规范"], ["option_id": "B", "text": "确认费用"]]] + } + private var draftJSON: [String: Any] { + ["task_id": "task_101", "paper_snapshot_id": "ps_3", "draft_revision": 4, "saved_at": NSNull(), "last_question_order": 11, "answered_count": 2, "answered_question_orders": [1, 11], "total": 30, "offset": 0, "next_offset": NSNull(), "has_more": false, "items": []] + } + private var attemptJSON: [String: Any] { + ["attempt_id": "attempt_12", "task_id": "task_101", "task_title": "规范培训", "course_snapshot_id": "cs_3", "course_title": "规范", "paper_snapshot_id": "ps_3", "submitted_at": dateText, "score_hundredths": 8750, "correct_count": 7, "question_count": 8, "pass_score": 80, "passed": true, "review_available": true] + } + private func envelope(_ payload: [String: Any]) throws -> Data { + try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": payload]) + } + private func body(_ request: URLRequest) throws -> [String: Any] { + try XCTUnwrap(JSONSerialization.jsonObject(with: try XCTUnwrap(request.httpBody)) as? [String: Any]) + } + private func query(_ request: URLRequest) throws -> [String: String] { + let url = try XCTUnwrap(request.url) + return Dictionary(uniqueKeysWithValues: (URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []).compactMap { item in item.value.map { (item.name, $0) } }) + } +} + +/// 测试中可控的主 Actor 身份标记。 +@MainActor +private final class TrainingAPITestIdentity { + var isCurrent = true +} + +/// 在响应返回前切换身份,验证生产数据源丢弃迟到结果。 +private actor TrainingIdentityChangingSession: URLSessionProtocol { + private let response: Data + private let change: @MainActor @Sendable () -> Void + private(set) var lastToken: String? + + init(response: Data, change: @escaping @MainActor @Sendable () -> Void) { + self.response = response + self.change = change + } + func data(for request: URLRequest) async throws -> (Data, URLResponse) { + lastToken = request.value(forHTTPHeaderField: "token") + await change() + return (response, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + } +} diff --git a/suixinkanTests/TrainingDataTestSupport.swift b/suixinkanTests/TrainingDataTestSupport.swift new file mode 100644 index 0000000..39e381f --- /dev/null +++ b/suixinkanTests/TrainingDataTestSupport.swift @@ -0,0 +1,271 @@ +import Foundation +@testable import suixinkan + +/// 正式 DTO 测试样例,所有数据在内存中生成,不发出真实请求。 +enum TrainingRemoteFixtures { + static let now = Date(timeIntervalSince1970: 1_800_000_000) + /// 固定试卷的一题。 + static func question(_ order: Int) -> TrainingQuestionItem { + TrainingQuestionItem(id: "q\(order)", order: order, type: .single, stem: "培训题目 \(order)", options: [TrainingQuestionOption(id: "A", text: "正确选择"), TrainingQuestionOption(id: "B", text: "另一选择")]) + } + /// 不含正文和答案的任务摘要。 + static func task(id: String = "task_1", title: String = "一线服务规范学习", questionCount: Int = 30, readingCompleted: Bool = true) -> TrainingTaskSummary { + TrainingTaskSummary(id: id, title: title, publisherName: "培训负责人", mode: .exam, taskStatus: .published, learnerStatus: .pendingExam, startAt: nil, endAt: nil, courseSnapshotID: "course_1", courseTitle: "景区服务规范", paperSnapshotID: "paper_1", sectionCount: 2, questionCount: questionCount, passScore: 80, learning: TrainingLearningFlags(progressPercent: readingCompleted ? 100 : 0, readingCompleted: readingCompleted, hasDraft: false, canViewCourse: true, canStudy: !readingCompleted, canStartExam: readingCompleted, blockReason: readingCompleted ? nil : "reading_required")) + } + /// 轻量任务详情。 + static func detail(questionCount: Int = 30, readingCompleted: Bool = true) -> TrainingTaskDetail { + TrainingTaskDetail(summary: task(questionCount: questionCount, readingCompleted: readingCompleted), requiredReadingSeconds: 20, readingRule: "course_duration", scoring: "equal-percentage-v1", serverTime: now) + } + /// 服务端确认读时与资格。 + static func progress(seconds: Int = 20, completed: Bool = false) -> TrainingProgressSnapshot { + TrainingProgressSnapshot(taskID: "task_1", readingSeconds: seconds, requiredReadingSeconds: 20, completedSectionCount: seconds >= 20 ? 2 : 0, sectionCount: 2, progressPercent: seconds >= 20 ? 100 : 0, readingCompleted: seconds >= 20, learnerStatus: completed ? .completed : .pendingExam, completedAt: completed ? now : nil, hasDraft: false, canViewCourse: true, canStudy: seconds < 20 && !completed, canStartExam: seconds >= 20 && !completed, canRetry: !completed, blockReason: completed ? "completed" : seconds < 20 ? "reading_required" : nil, serverTime: now) + } + /// 单次已提交成绩。 + static func attempt(id: String = "attempt_1", passed: Bool = true, questionCount: Int = 30, reviewAvailable: Bool = true) -> TrainingAttemptSummary { + TrainingAttemptSummary(id: id, taskID: "task_1", taskTitle: "一线服务规范学习", courseSnapshotID: "course_1", courseTitle: "景区服务规范", paperSnapshotID: "paper_1", submittedAt: now, scoreHundredths: passed ? 10000 : 5000, correctCount: passed ? questionCount : questionCount / 2, questionCount: questionCount, passScore: 80, passed: passed, reviewAvailable: reviewAvailable) + } + /// 冻结成绩的当前操作资格。 + static func result(passed: Bool = true, reviewAvailable: Bool = true, questionCount: Int = 30) -> TrainingAttemptDetail { + TrainingAttemptDetail(attempt: attempt(passed: passed, questionCount: questionCount, reviewAvailable: reviewAvailable), taskState: TrainingTaskState(learnerStatus: passed ? .completed : .pendingExam, completedAt: passed ? now : nil, canRetry: !passed, blockReason: passed ? "completed" : nil), serverTime: now) + } + /// 一页解析。 + static func review(_ order: Int = 1) -> TrainingReviewItem { + let question = question(order) + return TrainingReviewItem(id: question.id, order: order, type: question.type, stem: question.stem, options: question.options, selectedOptionIDs: ["A"], correctOptionIDs: ["A"], isCorrect: true, explanation: "应先向游客说明服务内容与费用。") + } +} + +/// 通用培训替身,允许测试注入失败和丢响应,记录实际的轻量资源调用。 +actor TrainingDataStub: TrainingDataServing { + /// 可核对分页、上报和资源范围的调用参数。 + struct Call: Equatable, Sendable { + let name: String + var taskID: String? = nil + var cursor: String? = nil + var offset: Int? = nil + var limit: Int? = nil + } + /// 心跳的固定幂等负载。 + struct HeartbeatCall: Equatable, Sendable { + let sessionID: String + let sequence: Int + let activeSecondsTotal: Int + let final: Bool + } + /// 各方法可替换响应,未替换的方法使用独立内存状态。 + struct Configuration: Sendable { + var questionCount = 30 + var readingSeconds = 20 + var summaryHandler: (@Sendable () async throws -> TrainingSummary)? + var tasksHandler: (@Sendable (TrainingLearnerStatus?, String, String?, Int) async throws -> TrainingCursorPage)? + var taskHandler: (@Sendable (String) async throws -> TrainingTaskDetail)? + var progressHandler: (@Sendable (String) async throws -> TrainingProgressSnapshot)? + var courseHandler: (@Sendable () async throws -> TrainingCourseInfo)? + var sectionsHandler: (@Sendable (String?) async throws -> TrainingCursorPage)? + var sectionHandler: (@Sendable (String) async throws -> TrainingSectionContent)? + var attachmentsHandler: (@Sendable (String?) async throws -> TrainingCursorPage)? + var startReadingHandler: (@Sendable (String) async throws -> TrainingStudySession)? + var heartbeatHandler: (@Sendable (HeartbeatCall) async throws -> TrainingHeartbeatConfirmation)? + var questionsHandler: (@Sendable (Int, Int) async throws -> TrainingQuestionPage)? + var draftHandler: (@Sendable (Int, Int) async throws -> TrainingDraftPage)? + var saveHandler: (@Sendable (TrainingDraftSaveRequest) async throws -> TrainingDraftConfirmation)? + var resetHandler: (@Sendable (TrainingDraftResetRequest) async throws -> TrainingDraftConfirmation)? + var submitHandler: (@Sendable (TrainingSubmissionRequest) async throws -> TrainingSubmissionResult)? + var attemptsHandler: (@Sendable (String?, String?, String?) async throws -> TrainingCursorPage)? + var attemptHandler: (@Sendable (String) async throws -> TrainingAttemptDetail)? + var reviewsHandler: (@Sendable (String?) async throws -> TrainingReviewPage)? + } + private var configuration: Configuration + private(set) var calls: [Call] = [] + private(set) var savedRequests: [TrainingDraftSaveRequest] = [] + private(set) var resetRequests: [TrainingDraftResetRequest] = [] + private(set) var submissionRequests: [TrainingSubmissionRequest] = [] + private(set) var heartbeats: [HeartbeatCall] = [] + private(set) var startReadingRequests: [String] = [] + private var revision = 1 + private var answers: [String: [String]] = [:] + private var lastOrder = 0 + private var submitted: [String: TrainingSubmissionResult] = [:] + private var savedPayloads: [String: TrainingDraftSaveRequest] = [:] + private var resetPayloads: [String: TrainingDraftResetRequest] = [:] + private var submissionPayloads: [String: TrainingSubmissionRequest] = [:] + private var readingBases: [String: Int] = [:] + private var heartbeatConfirmations: [String: TrainingHeartbeatConfirmation] = [:] + private var heartbeatPayloads: [String: HeartbeatCall] = [:] + private var savedConfirmations: [String: TrainingDraftConfirmation] = [:] + private var readingSeconds: Int + + /// 每个测试独立初始化,默认不复用其他测试状态。 + init(configuration: Configuration = Configuration()) { + self.configuration = configuration + readingSeconds = configuration.readingSeconds + } + /// 在 actor 内更换响应配置。 + func configure(_ update: @Sendable (inout Configuration) -> Void) { update(&configuration) } + /// 注入一个已有草稿,供跨设备和恢复测试。 + func seedDraft(revision: Int, answers: [String: [String]], lastOrder: Int = 0) { + self.revision = revision; self.answers = answers; self.lastOrder = lastOrder + } + /// 读取概览,不派生全量任务历史。 + func summary() async throws -> TrainingSummary { + calls.append(Call(name: "summary")) + if let handler = configuration.summaryHandler { return try await handler() } + return TrainingSummary(pendingCount: 1, completedCount: 0, latestAttempt: nil, serverTime: TrainingRemoteFixtures.now) + } + /// 记录任务过滤及游标。 + func tasks(status: TrainingLearnerStatus?, keyword: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage { + calls.append(Call(name: "tasks", cursor: cursor, limit: limit)) + if let handler = configuration.tasksHandler { return try await handler(status, keyword, cursor, limit) } + return TrainingCursorPage(items: [TrainingRemoteFixtures.task(questionCount: configuration.questionCount)], nextCursor: nil, hasMore: false, serverTime: TrainingRemoteFixtures.now) + } + /// 任务详情仍不携带正文或试卷。 + func task(id: String) async throws -> TrainingTaskDetail { + calls.append(Call(name: "task", taskID: id)) + if let handler = configuration.taskHandler { return try await handler(id) } + return TrainingRemoteFixtures.detail(questionCount: configuration.questionCount, readingCompleted: readingSeconds >= 20) + } + /// 课程元信息。 + func course(id: String, taskID: String) async throws -> TrainingCourseInfo { + calls.append(Call(name: "course", taskID: taskID)) + if let handler = configuration.courseHandler { return try await handler() } + return TrainingCourseInfo(id: id, title: "景区服务规范", introduction: "正式课程简介", sectionCount: 2, attachmentCount: 0) + } + /// 小节目录,仅含标题与序号。 + func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage { + calls.append(Call(name: "sections", taskID: taskID, cursor: cursor, limit: limit)) + if let handler = configuration.sectionsHandler { return try await handler(cursor) } + return TrainingCursorPage(items: [TrainingSectionInfo(id: "s1", order: 1, title: "接待礼仪"), TrainingSectionInfo(id: "s2", order: 2, title: "问题处理")], nextCursor: nil, hasMore: false, serverTime: nil) + } + /// 仅请求指定小节正文。 + func section(courseID: String, sectionID: String, taskID: String) async throws -> TrainingSectionContent { + calls.append(Call(name: "section", taskID: taskID)) + if let handler = configuration.sectionHandler { return try await handler(sectionID) } + return TrainingSectionContent(id: sectionID, order: sectionID == "s1" ? 1 : 2, title: "接待礼仪", contentHTML: "

主动问候,并清晰说明服务内容。

") + } + /// 分页附件元数据。 + func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage { + calls.append(Call(name: "attachments", taskID: taskID, cursor: cursor, limit: limit)) + if let handler = configuration.attachmentsHandler { return try await handler(cursor) } + return TrainingCursorPage(items: [], nextCursor: nil, hasMore: false, serverTime: nil) + } + /// 返回用于 Safari 的授权 HTTPS URL。 + func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink { + calls.append(Call(name: "attachmentURL", taskID: taskID)) + return TrainingAttachmentLink(id: attachmentID, name: "培训附件", url: URL(string: "https://example.test/training.pdf")!, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600)) + } + /// 只返回权威读时。 + func progress(taskID: String) async throws -> TrainingProgressSnapshot { + calls.append(Call(name: "progress", taskID: taskID)) + if let handler = configuration.progressHandler { return try await handler(taskID) } + return TrainingRemoteFixtures.progress(seconds: readingSeconds) + } + /// 创建会话,记录幂等键。 + func startReading(taskID: String, requestID: String) async throws -> TrainingStudySession { + calls.append(Call(name: "startReading", taskID: taskID)); startReadingRequests.append(requestID) + if let handler = configuration.startReadingHandler { return try await handler(requestID) } + if readingBases[requestID] == nil { readingBases[requestID] = readingSeconds } + return TrainingStudySession(sessionID: requestID, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600), heartbeatIntervalSeconds: 5, maxHeartbeatGapSeconds: 15, progress: TrainingRemoteFixtures.progress(seconds: readingSeconds)) + } + /// 测试按序号返回确认,不接触真实学员记录。 + func heartbeat(sessionID: String, sequence: Int, activeSecondsTotal: Int, final: Bool) async throws -> TrainingHeartbeatConfirmation { + let call = HeartbeatCall(sessionID: sessionID, sequence: sequence, activeSecondsTotal: activeSecondsTotal, final: final) + heartbeats.append(call); calls.append(Call(name: "heartbeat")) + if let handler = configuration.heartbeatHandler { return try await handler(call) } + let key = "\(sessionID):\(sequence)" + if let prior = heartbeatConfirmations[key] { + guard heartbeatPayloads[key] == call else { throw TrainingRemoteError.sessionConflict("序号冲突") } + return prior + } + readingSeconds = min(20, max(readingSeconds, (readingBases[sessionID] ?? 0) + activeSecondsTotal)) + let result = TrainingHeartbeatConfirmation(sessionID: sessionID, acceptedSequence: sequence, acceptedActiveSecondsTotal: activeSecondsTotal, sessionClosed: final, progress: TrainingRemoteFixtures.progress(seconds: readingSeconds)) + heartbeatConfirmations[key] = result; heartbeatPayloads[key] = call + return result + } + /// 不含题目数组的试卷元信息。 + func paper(id: String, taskID: String) async throws -> TrainingPaperInfo { + calls.append(Call(name: "paper", taskID: taskID)) + return TrainingPaperInfo(id: id, scoring: "equal-percentage-v1", questionCount: configuration.questionCount, maxOptionsPerQuestion: 6) + } + /// 仅生成请求范围内的固定题位。 + func questions(paperID: String, taskID: String, offset: Int, limit: Int) async throws -> TrainingQuestionPage { + calls.append(Call(name: "questions", taskID: taskID, offset: offset, limit: limit)) + if let handler = configuration.questionsHandler { return try await handler(offset, limit) } + let end = min(configuration.questionCount, offset + limit) + let items = offset < end ? ((offset + 1)...end).map(TrainingRemoteFixtures.question) : [] + return TrainingQuestionPage(paperSnapshotID: paperID, total: configuration.questionCount, offset: offset, nextOffset: end < configuration.questionCount ? end : nil, hasMore: end < configuration.questionCount, items: items) + } + /// 草稿元信息覆盖全卷,答案仅提供当前范围。 + func draft(taskID: String, offset: Int, limit: Int) async throws -> TrainingDraftPage { + calls.append(Call(name: "draft", taskID: taskID, offset: offset, limit: limit)) + if let handler = configuration.draftHandler { return try await handler(offset, limit) } + let orders = answers.filter { !$0.value.isEmpty }.keys.compactMap { Int($0.dropFirst()) }.sorted() + let end = min(configuration.questionCount, offset + limit) + let items = limit > 0 ? orders.filter { $0 > offset && $0 <= end }.map { TrainingDraftAnswerItem(questionID: "q\($0)", order: $0, selectedOptionIDs: answers["q\($0)"] ?? []) } : [] + return TrainingDraftPage(taskID: taskID, paperSnapshotID: "paper_1", draftRevision: revision, savedAt: answers.isEmpty ? nil : TrainingRemoteFixtures.now, lastQuestionOrder: lastOrder, answeredCount: orders.count, answeredQuestionOrders: orders, total: configuration.questionCount, offset: offset, nextOffset: limit > 0 && end < configuration.questionCount ? end : nil, hasMore: limit > 0 && end < configuration.questionCount, items: items) + } + /// 默认实现模拟版本比较与单题替换。 + func saveDraft(taskID: String, request: TrainingDraftSaveRequest) async throws -> TrainingDraftConfirmation { + savedRequests.append(request); calls.append(Call(name: "saveDraft", taskID: taskID)) + if let handler = configuration.saveHandler { return try await handler(request) } + if let confirmation = savedConfirmations[request.requestID] { + guard savedPayloads[request.requestID] == request else { throw TrainingRemoteError.idempotencyConflict("幂等键冲突") } + return confirmation + } + guard request.baseRevision == revision else { throw TrainingRemoteError.draftRevisionConflict("版本冲突") } + for change in request.changes { answers[change.questionID] = change.selectedOptionIDs } + if let order = request.lastQuestionOrder { lastOrder = order } + if !request.changes.isEmpty { revision += 1 } + let result = TrainingDraftConfirmation(draftRevision: revision, savedAt: TrainingRemoteFixtures.now, answeredCount: answers.values.filter { !$0.isEmpty }.count) + savedConfirmations[request.requestID] = result + savedPayloads[request.requestID] = request + return result + } + /// 重置确认可由测试返回非空当前实况。 + func resetDraft(taskID: String, request: TrainingDraftResetRequest) async throws -> TrainingDraftConfirmation { + resetRequests.append(request); calls.append(Call(name: "resetDraft", taskID: taskID)) + if let handler = configuration.resetHandler { return try await handler(request) } + if let prior = resetPayloads[request.requestID] { + guard prior == request else { throw TrainingRemoteError.idempotencyConflict("幂等键冲突") } + return TrainingDraftConfirmation(draftRevision: revision, savedAt: TrainingRemoteFixtures.now, answeredCount: answers.values.filter { !$0.isEmpty }.count) + } + guard request.baseRevision == revision else { throw TrainingRemoteError.draftRevisionConflict("版本冲突") } + resetPayloads[request.requestID] = request + answers = [:]; revision += 1; lastOrder = 0 + return TrainingDraftConfirmation(draftRevision: revision, savedAt: TrainingRemoteFixtures.now, answeredCount: 0) + } + /// 默认交卷只消费已经保存的版本。 + func submit(taskID: String, request: TrainingSubmissionRequest) async throws -> TrainingSubmissionResult { + submissionRequests.append(request); calls.append(Call(name: "submit", taskID: taskID)) + if let handler = configuration.submitHandler { return try await handler(request) } + if let result = submitted[request.submissionID] { + guard submissionPayloads[request.submissionID] == request else { throw TrainingRemoteError.idempotencyConflict("幂等键冲突") } + return result + } + guard request.draftRevision == revision else { throw TrainingRemoteError.draftRevisionConflict("版本冲突") } + guard answers.values.filter({ !$0.isEmpty }).count == configuration.questionCount else { throw TrainingRemoteError.answerIncomplete("存在未答题") } + let detail = TrainingRemoteFixtures.result(questionCount: configuration.questionCount) + revision += 1; answers = [:] + let result = TrainingSubmissionResult(attempt: detail.attempt, taskState: detail.taskState, draftRevision: revision, serverTime: TrainingRemoteFixtures.now) + submitted[request.submissionID] = result + submissionPayloads[request.submissionID] = request + return result + } + /// 记录列表或提交恢复只返回摘要。 + func attempts(taskID: String?, submissionID: String?, cursor: String?, limit: Int) async throws -> TrainingCursorPage { + calls.append(Call(name: "attempts", taskID: taskID, cursor: cursor, limit: limit)) + if let handler = configuration.attemptsHandler { return try await handler(taskID, submissionID, cursor) } + return TrainingCursorPage(items: submissionID.flatMap { submitted[$0]?.attempt }.map { [$0] } ?? [], nextCursor: nil, hasMore: false, serverTime: nil) + } + /// 成绩首屏没有解析数组。 + func attempt(id: String) async throws -> TrainingAttemptDetail { + calls.append(Call(name: "attempt")) + if let handler = configuration.attemptHandler { return try await handler(id) } + return TrainingRemoteFixtures.result(questionCount: configuration.questionCount) + } + /// 展开解析时才记录调用。 + func reviews(attemptID: String, cursor: String?, limit: Int) async throws -> TrainingReviewPage { + calls.append(Call(name: "reviews", cursor: cursor, limit: limit)) + if let handler = configuration.reviewsHandler { return try await handler(cursor) } + return TrainingReviewPage(attemptID: attemptID, items: [TrainingRemoteFixtures.review()], nextCursor: nil, hasMore: false) + } +} diff --git a/suixinkanTests/TrainingFeatureTests.swift b/suixinkanTests/TrainingFeatureTests.swift index 50a30a9..bd67f6b 100644 --- a/suixinkanTests/TrainingFeatureTests.swift +++ b/suixinkanTests/TrainingFeatureTests.swift @@ -368,20 +368,22 @@ struct TrainingFeatureTests { #expect(model.errorMessage != nil) } - @Test("首页所有角色都有培训入口,服务端下发时不重复") - func trainingEntryForEveryRole() { + @Test("培训入口按店铺账号开放,权限下发不重复且不能绕过账号限制") + func trainingEntryFollowsAccountScope() { let suite = "TrainingMenuTests-\(UUID().uuidString)" guard let defaults = UserDefaults(suiteName: suite) else { Issue.record("无法创建独立存储"); return } defer { defaults.removePersistentDomain(forName: suite) } let appStore = AppStore(defaults: defaults) appStore.session.userId = "1001" - appStore.session.accountType = .scenicUser - for role in AppRoleCode.allCases { - appStore.session.roleCode = role.rawValue - appStore.permissions.savePermissionItems([HomePermissionItem(id: "training", name: "培训", uri: "/training")]) - let model = HomeViewModel(appStore: appStore, commonMenuStore: HomeCommonMenuStore(defaults: defaults)) - model.rebuildCommonMenus() - #expect(model.commonMenus.filter { $0.uri == "/training" }.count == 1) + for accountType in [AppAccountType.scenicUser, .storeUser] { + appStore.session.accountType = accountType + for role in AppRoleCode.allCases { + appStore.session.roleCode = role.rawValue + appStore.permissions.savePermissionItems([HomePermissionItem(id: "training", name: "培训", uri: "/training")]) + let model = HomeViewModel(appStore: appStore, commonMenuStore: HomeCommonMenuStore(defaults: defaults)) + model.rebuildCommonMenus() + #expect(model.commonMenus.filter { $0.uri == "/training" }.count == (accountType == .storeUser ? 1 : 0)) + } } #expect(HomeMenuCatalog.item(for: "/training")?.title == "培训中心") } diff --git a/suixinkanTests/TrainingRemoteExamTests.swift b/suixinkanTests/TrainingRemoteExamTests.swift new file mode 100644 index 0000000..94d6b7d --- /dev/null +++ b/suixinkanTests/TrainingRemoteExamTests.swift @@ -0,0 +1,604 @@ +import Foundation +import Testing +import UIKit +@testable import suixinkan + +/// 注入一次失败,验证重试仍保持同一请求内容。 +private actor TrainingExamFailureCounter { + private var value = 0 + /// 返回本次调用序号。 + func next() -> Int { value += 1; return value } +} + +/// 为当前页失败和恢复测试建立稀疏草稿响应。 +private enum TrainingExamDraftFixtures { + /// 仅返回请求题位范围内的答案,元信息仍覆盖完整试卷。 + static func page(total: Int, revision: Int, answers: [Int: [String]], offset: Int, limit: Int) -> TrainingDraftPage { + let orders = answers.filter { !$0.value.isEmpty }.keys.sorted() + let end = min(total, offset + limit) + let items = limit > 0 ? orders.filter { $0 > offset && $0 <= end }.map { + TrainingDraftAnswerItem(questionID: "q\($0)", order: $0, selectedOptionIDs: answers[$0] ?? []) + } : [] + return TrainingDraftPage(taskID: "task_1", paperSnapshotID: "paper_1", draftRevision: revision, + savedAt: TrainingRemoteFixtures.now, lastQuestionOrder: 1, answeredCount: orders.count, + answeredQuestionOrders: orders, total: total, offset: offset, + nextOffset: limit > 0 && end < total ? end : nil, hasMore: limit > 0 && end < total, items: items) + } +} + +/// 可在请求之间切换的业务身份,不依赖 AppStore 单例。 +@MainActor +private final class TrainingExamTestIdentity { + var context: TrainingContext? + /// 固定测试开始时的账号范围。 + init(_ context: TrainingContext) { self.context = context } +} + +/// 正式分页答题、版本保存及未知交卷恢复测试;全部使用内存网络替身。 +@Suite("培训中心正式答题与交卷恢复") +@MainActor +struct TrainingRemoteExamTests { + private let context = TrainingContext(accountScope: "exam_user", scenicID: 10, storeID: 3) + + private func makeDefaults() throws -> (name: String, defaults: UserDefaults) { + let name = "TrainingRemoteExamTests-\(UUID().uuidString)" + return (name, try #require(UserDefaults(suiteName: name))) + } + + private func makeModel(defaults: UserDefaults, identity: TrainingExamTestIdentity? = nil) -> TrainingRemoteExamViewModel { + let scope = identity?.context ?? context + return TrainingRemoteExamViewModel(taskID: "task_1", context: scope, + pendingStore: TrainingPendingSubmissionStore(defaults: defaults), currentContext: { if let identity { return identity.context }; return scope }) + } + + @Test("500题恢复和随机跳题只下载所在页,已答状态来自全局题号") + func lazyPagesAndGlobalAnswers() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + var configuration = TrainingDataStub.Configuration() + configuration.questionCount = 500 + let source = TrainingDataStub(configuration: configuration) + await source.seedDraft(revision: 6, answers: ["q401": ["A"], "q500": ["B"]], lastOrder: 401) + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + #expect(model.currentIndex == 400) + #expect(model.currentQuestion?.id == "q401") + #expect(model.currentSelectedIDs == ["A"]) + #expect(model.answeredCount == 2) + #expect(model.firstUnansweredIndex == 0) + await model.goToQuestion(499, service: source) + #expect(model.currentSelectedIDs == ["B"]) + await model.goToQuestion(400, service: source) + await model.goToQuestion(500, service: source) + #expect(model.currentIndex == 400) + let calls = await source.calls + #expect(calls.filter { $0.name == "questions" }.map(\.offset) == [400, 490]) + #expect(calls.filter { $0.name == "questions" }.allSatisfy { $0.limit == 10 }) + #expect(calls.filter { $0.name == "draft" }.map(\.limit) == [0, 10, 10]) + #expect(model.answeredQuestionOrders == [401, 500]) + } + + @Test("响应按字节预算缩页时,随机目标直接补取而不扫描全卷") + func shortPageRandomAccess() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + var configuration = TrainingDataStub.Configuration() + configuration.questionsHandler = { offset, _ in + let end = min(30, offset + 3) + return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 30, offset: offset, + nextOffset: end < 30 ? end : nil, hasMore: end < 30, + items: ((offset + 1)...end).map(TrainingRemoteFixtures.question)) + } + configuration.draftHandler = { offset, limit in + let end = limit == 0 ? offset : min(30, offset + 3) + let items: [TrainingDraftAnswerItem] = limit > 0 && offset < 19 && end >= 19 + ? [TrainingDraftAnswerItem(questionID: "q19", order: 19, selectedOptionIDs: ["B"])] : [] + return TrainingDraftPage(taskID: "task_1", paperSnapshotID: "paper_1", draftRevision: 1, + savedAt: TrainingRemoteFixtures.now, lastQuestionOrder: 1, answeredCount: 1, + answeredQuestionOrders: [19], total: 30, offset: offset, + nextOffset: limit > 0 && end < 30 ? end : nil, hasMore: limit > 0 && end < 30, items: items) + } + configuration.saveHandler = { request in + TrainingDraftConfirmation(draftRevision: request.baseRevision, savedAt: TrainingRemoteFixtures.now, answeredCount: 1) + } + let source = TrainingDataStub(configuration: configuration) + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + await model.goToQuestion(18, service: source) + #expect(model.currentQuestion?.id == "q19") + #expect(model.currentSelectedIDs == ["B"]) + #expect(model.firstUnansweredIndex == 0) + let calls = await source.calls + #expect(calls.filter { $0.name == "questions" }.map(\.offset) == [0, 10, 18]) + #expect(calls.filter { $0.name == "draft" && $0.limit != 0 }.map(\.offset) == [0, 10, 18]) + } + + @Test("全部已答即使只缓存一页也可交卷,不全量读取或回传草稿") + func submitSavedRevisionWithoutReadingWholeDraft() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + var configuration = TrainingDataStub.Configuration() + configuration.questionCount = 500 + let source = TrainingDataStub(configuration: configuration) + await source.seedDraft(revision: 15, answers: Dictionary(uniqueKeysWithValues: (1...500).map { ("q\($0)", ["A"]) })) + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + #expect(model.answeredCount == 500) + #expect(model.firstUnansweredIndex == nil) + #expect(await model.submit(service: source)?.id == "attempt_1") + let requests = await source.submissionRequests + #expect(requests.count == 1) + #expect(requests.first?.draftRevision == 15) + #expect(requests.first?.paperSnapshotID == "paper_1") + let calls = await source.calls + #expect(calls.filter { $0.name == "draft" }.map(\.limit) == [0, 10]) + #expect(calls.filter { $0.name == "questions" }.count == 1) + #expect(!model.hasPendingSubmission) + #expect(model.submittedResult?.attempt.id == "attempt_1") + } + + @Test("选择仅保存一题变化且使用最新确认版本") + func incrementalSaveAndRevision() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + let source = TrainingDataStub() + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + await model.select(optionID: "A", service: source) + #expect(model.draftRevision == 2) + #expect(model.answeredQuestionOrders == [1]) + await model.select(optionID: "B", service: source) + let requests = await source.savedRequests + #expect(requests.map(\.baseRevision) == [1, 2]) + #expect(requests.allSatisfy { $0.changes.count == 1 && $0.changes.first?.questionID == "q1" }) + #expect(requests.last?.changes.first?.selectedOptionIDs == ["B"]) + #expect(requests[0].requestID != requests[1].requestID) + #expect(model.currentSelectedIDs == ["B"]) + #expect(model.answeredCount == 1) + } + + @Test("多选切换提交规范化集合,取消一项不丢失其它选择") + func multipleChoiceIncrementalToggle() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + var configuration = TrainingDataStub.Configuration() + configuration.questionsHandler = { offset, limit in + let end = min(30, offset + limit) + let questions = ((offset + 1)...end).map { order -> TrainingQuestionItem in + let original = TrainingRemoteFixtures.question(order) + return TrainingQuestionItem(id: original.id, order: order, type: order == 1 ? .multiple : .single, + stem: original.stem, options: original.options) + } + return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 30, offset: offset, + nextOffset: end < 30 ? end : nil, hasMore: end < 30, items: questions) + } + let source = TrainingDataStub(configuration: configuration) + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + await model.select(optionID: "A", service: source) + await model.select(optionID: "B", service: source) + await model.select(optionID: "A", service: source) + #expect(model.currentSelectedIDs == ["B"]) + #expect((await source.savedRequests).map { $0.changes.first?.selectedOptionIDs } == [["A"], ["A", "B"], ["B"]]) + #expect(model.answeredCount == 1) + } + + @Test("保存超时暂停编辑,重试同ID同版本同内容") + func saveFailureRetainsOriginalRequest() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + let counter = TrainingExamFailureCounter() + var configuration = TrainingDataStub.Configuration() + configuration.saveHandler = { request in + if await counter.next() == 1 { throw URLError(.timedOut) } + return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1, savedAt: TrainingRemoteFixtures.now, answeredCount: 1) + } + let source = TrainingDataStub(configuration: configuration) + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + await model.select(optionID: "A", service: source) + #expect(model.hasPendingMutation) + #expect(!model.canEdit) + #expect(model.currentSelectedIDs.isEmpty) + await model.select(optionID: "B", service: source) + #expect(await source.savedRequests.count == 1) + await model.retryMutation(service: source) + let requests = await source.savedRequests + #expect(requests.count == 2) + #expect(requests[0] == requests[1]) + #expect(model.currentSelectedIDs == ["A"]) + #expect(!model.hasPendingMutation) + } + + @Test("版本冲突读取最新元信息与当前页,不覆盖其它设备的新答案") + func conflictRefreshesCurrentPage() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + let source = TrainingDataStub() + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + await source.seedDraft(revision: 8, answers: ["q1": ["B"], "q10": ["A"]]) + await model.select(optionID: "A", service: source) + #expect(model.draftRevision == 8) + #expect(model.currentSelectedIDs == ["B"]) + #expect(model.answeredCount == 2) + #expect(model.errorMessage != nil) + #expect(!model.hasPendingMutation) + #expect(await source.savedRequests.count == 1) + let calls = await source.calls + #expect(calls.filter { $0.name == "draft" }.map(\.limit) == [0, 10, 0, 10]) + } + + @Test("重置超时沿原键恢复,成功响应含新答案时不盲清") + func resetRetryUsesCurrentDraftState() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + let counter = TrainingExamFailureCounter() + var configuration = TrainingDataStub.Configuration() + configuration.resetHandler = { _ in + if await counter.next() == 1 { throw URLError(.networkConnectionLost) } + return TrainingDraftConfirmation(draftRevision: 5, savedAt: TrainingRemoteFixtures.now, answeredCount: 1) + } + let source = TrainingDataStub(configuration: configuration) + await source.seedDraft(revision: 3, answers: ["q1": ["A"]]) + let model = makeModel(defaults: domain.defaults) + await model.load(service: source, resetDraft: true) + #expect(model.hasPendingMutation) + await source.seedDraft(revision: 5, answers: ["q1": ["B"]]) + await model.retryMutation(service: source) + let requests = await source.resetRequests + #expect(requests.count == 2) + #expect(requests[0] == requests[1]) + #expect(model.draftRevision == 5) + #expect(model.currentSelectedIDs == ["B"]) + #expect(model.answeredQuestionOrders == [1]) + #expect(!model.hasPendingMutation) + } + + @Test("未知交卷跨页面重建恢复;查询0条重试原请求,通过后也可找回原成绩") + func durableUnknownSubmissionRecovery() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + var configuration = TrainingDataStub.Configuration() + configuration.questionCount = 3 + configuration.submitHandler = { _ in throw URLError(.timedOut) } + let source = TrainingDataStub(configuration: configuration) + await source.seedDraft(revision: 7, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]]) + let first = makeModel(defaults: domain.defaults) + await first.load(service: source) + #expect(await first.submit(service: source) == nil) + #expect(first.hasPendingSubmission) + #expect(!first.canEdit) + let stored = try TrainingPendingSubmissionStore(defaults: domain.defaults).load(taskID: "task_1", context: context) + let saved = try #require(stored) + + let second = makeModel(defaults: domain.defaults) + await second.load(service: source) + #expect(second.hasPendingSubmission) + let requests = await source.submissionRequests + #expect(requests.count == 2) + #expect(requests[0] == requests[1]) + #expect(requests[1] == saved.request) + + await source.configure { + $0.progressHandler = { _ in TrainingRemoteFixtures.progress(completed: true) } + $0.attemptsHandler = { _, _, _ in + TrainingCursorPage(items: [TrainingRemoteFixtures.attempt()], nextCursor: nil, hasMore: false, serverTime: nil) + } + } + let restored = makeModel(defaults: domain.defaults) + await restored.load(service: source) + #expect(restored.submittedAttempt?.id == "attempt_1") + #expect(restored.submittedResult?.taskState.canRetry == false) + #expect(!restored.hasPendingSubmission) + #expect(await source.submissionRequests.count == 2) + #expect(try TrainingPendingSubmissionStore(defaults: domain.defaults).load(taskID: "task_1", context: context) == nil) + } + + @Test("账号景区店铺隔离待确认请求,身份切换不消费旧账号记录") + func pendingScopeAndIdentityIsolation() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + let store = TrainingPendingSubmissionStore(defaults: domain.defaults) + let pending = TrainingPendingSubmission(taskID: "task_1", request: TrainingSubmissionRequest(submissionID: "original", paperSnapshotID: "paper_1", draftRevision: 4), context: context) + try store.save(pending) + for different in [TrainingContext(accountScope: "other", scenicID: 10, storeID: 3), + TrainingContext(accountScope: context.accountScope, scenicID: 11, storeID: 3), + TrainingContext(accountScope: context.accountScope, scenicID: 10, storeID: 4)] { + #expect(try store.load(taskID: "task_1", context: different) == nil) + } + let identity = TrainingExamTestIdentity(TrainingContext(accountScope: "other", scenicID: 10, storeID: 3)) + let source = TrainingDataStub() + await source.seedDraft(revision: 2, answers: ["q1": ["B"]]) + let model = makeModel(defaults: domain.defaults, identity: identity) + await model.load(service: source) + #expect(model.currentQuestion?.id == "q1") + #expect(model.currentSelectedIDs == ["B"]) + #expect(!model.hasPendingSubmission) + #expect(!(await source.calls).contains { $0.name == "attempts" || $0.name == "submit" }) + #expect(try store.load(taskID: "task_1", context: context) == pending) + identity.context = context + await model.validateIdentity() + #expect(model.isIdentityInvalid) + #expect(model.shouldReturnToCenter) + #expect(model.currentQuestion == nil) + #expect(model.currentSelectedIDs.isEmpty) + #expect(model.task == nil && model.progress == nil && model.paper == nil) + #expect(model.answeredQuestionOrders.isEmpty) + #expect(!model.canEdit) + #expect(try store.load(taskID: "task_1", context: context) == pending) + + var failedConfiguration = TrainingDataStub.Configuration() + failedConfiguration.submitHandler = { _ in throw URLError(.timedOut) } + let failed = TrainingDataStub(configuration: failedConfiguration) + identity.context = context + let original = makeModel(defaults: domain.defaults, identity: identity) + await original.load(service: failed) + #expect(original.hasPendingSubmission) + identity.context = TrainingContext(accountScope: "other", scenicID: 10, storeID: 3) + _ = await original.submit(service: failed) + #expect(original.isIdentityInvalid) + #expect(original.shouldReturnToCenter) + #expect(original.currentQuestion == nil) + #expect(await failed.submissionRequests.count == 1) + #expect(try store.load(taskID: "task_1", context: context) == pending) + } + + @Test("同任务页面不能覆盖待确认记录,交卷前优先恢复已有持久化键") + func existingPendingRequestCannotBeOverwritten() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + var configuration = TrainingDataStub.Configuration() + configuration.questionCount = 3 + configuration.submitHandler = { _ in throw URLError(.timedOut) } + let source = TrainingDataStub(configuration: configuration) + await source.seedDraft(revision: 9, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]]) + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + let store = TrainingPendingSubmissionStore(defaults: domain.defaults) + let pending = TrainingPendingSubmission(taskID: "task_1", + request: TrainingSubmissionRequest(submissionID: "original", paperSnapshotID: "paper_1", draftRevision: 9), context: context) + try store.save(pending) + let replacement = TrainingPendingSubmission(taskID: "task_1", + request: TrainingSubmissionRequest(submissionID: "replacement", paperSnapshotID: "paper_1", draftRevision: 9), context: context) + #expect(throws: TrainingPendingSubmissionError.alreadyPending) { try store.save(replacement) } + #expect(await model.submit(service: source) == nil) + #expect(await source.submissionRequests == [pending.request]) + #expect(try store.load(taskID: "task_1", context: context) == pending) + } + + @Test("服务端已完成资格阻止读取试卷和新的交卷") + func completedGatePreventsNewSubmission() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + var configuration = TrainingDataStub.Configuration() + configuration.progressHandler = { _ in TrainingRemoteFixtures.progress(completed: true) } + let source = TrainingDataStub(configuration: configuration) + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + #expect(!model.canEdit) + #expect(await model.submit(service: source) == nil) + #expect(!(await source.calls).contains { $0.name == "paper" || $0.name == "questions" || $0.name == "submit" }) + } + + @Test("明确漏答业务拒绝释放待确认请求,并恢复最新漏答题号") + func definiteRejectionReleasesPendingSubmission() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + var configuration = TrainingDataStub.Configuration() + configuration.questionCount = 3 + let source = TrainingDataStub(configuration: configuration) + await source.seedDraft(revision: 4, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]]) + await source.configure { + $0.submitHandler = { request in + await source.seedDraft(revision: request.draftRevision, answers: ["q1": ["A"], "q2": ["A"]]) + throw TrainingRemoteError.answerIncomplete("第3题尚未作答") + } + } + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + #expect(await model.submit(service: source) == nil) + #expect(!model.hasPendingSubmission) + #expect(model.answeredCount == 2) + #expect(model.firstUnansweredIndex == 2) + #expect(try TrainingPendingSubmissionStore(defaults: domain.defaults).load(taskID: "task_1", context: context) == nil) + } + + @Test("题目成功而草稿页失败时禁止编辑,多选恢复后保留原B再加入A") + func failedDraftPageCannotOverwriteUnloadedAnswers() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + let counter = TrainingExamFailureCounter() + var configuration = TrainingDataStub.Configuration() + configuration.questionCount = 20 + configuration.questionsHandler = { offset, limit in + let end = min(20, offset + limit) + let items = ((offset + 1)...end).map { order -> TrainingQuestionItem in + let original = TrainingRemoteFixtures.question(order) + return TrainingQuestionItem(id: original.id, order: order, type: order == 11 ? .multiple : .single, + stem: original.stem, options: original.options) + } + return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 20, offset: offset, + nextOffset: end < 20 ? end : nil, hasMore: end < 20, items: items) + } + configuration.draftHandler = { offset, limit in + if offset == 10, limit > 0, await counter.next() == 1 { throw URLError(.timedOut) } + return TrainingExamDraftFixtures.page(total: 20, revision: 3, answers: [1: ["A"], 11: ["B"]], offset: offset, limit: limit) + } + let source = TrainingDataStub(configuration: configuration) + await source.seedDraft(revision: 3, answers: ["q1": ["A"], "q11": ["B"]]) + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + await model.goToQuestion(10, service: source) + #expect(model.currentQuestion?.id == "q11") + #expect(!model.isCurrentPageReady) + #expect(!model.canEdit) + #expect(model.canRetryCurrentPage) + await model.select(optionID: "A", service: source) + #expect(await source.savedRequests.isEmpty) + await model.retryCurrentPage(service: source) + #expect(model.currentSelectedIDs == ["B"]) + #expect(model.canEdit) + await model.select(optionID: "A", service: source) + #expect((await source.savedRequests).last?.changes.first?.selectedOptionIDs == ["A", "B"]) + await model.goToQuestion(0, service: source) + #expect(model.currentSelectedIDs == ["A"]) + #expect((await source.calls).filter { $0.name == "draft" && $0.offset == 0 }.count == 2) + } + + @Test("冲突后元信息刷新断网仍有当前页重试入口,不会永久锁页") + func conflictRefreshFailureCanRetryCurrentPage() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + let source = TrainingDataStub() + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + await source.seedDraft(revision: 8, answers: ["q1": ["B"]]) + let counter = TrainingExamFailureCounter() + await source.configure { + $0.draftHandler = { offset, limit in + if await counter.next() == 1 { throw URLError(.networkConnectionLost) } + return TrainingExamDraftFixtures.page(total: 30, revision: 8, answers: [1: ["B"]], offset: offset, limit: limit) + } + } + await model.select(optionID: "A", service: source) + #expect(!model.canEdit) + #expect(model.canRetryCurrentPage) + #expect(!model.hasPendingMutation) + await model.retryCurrentPage(service: source) + #expect(model.currentSelectedIDs == ["B"]) + #expect(model.draftRevision == 8) + #expect(model.canEdit) + #expect(await source.savedRequests.count == 1) + } + + @Test("交卷成功时考试页被覆盖,返回后仍直接进入已有成绩") + func coveredExamPresentsCompletedResultWhenVisibleAgain() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + var configuration = TrainingDataStub.Configuration() + configuration.questionCount = 3 + let source = TrainingDataStub(configuration: configuration) + await source.seedDraft(revision: 2, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]]) + let model = makeModel(defaults: domain.defaults) + let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model) + let navigation = UINavigationController(rootViewController: controller) + let window = try makeWindow(navigation) + defer { window.isHidden = true } + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + while !model.canEdit, ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } + #expect(model.canEdit) + try await settleTransitions(in: navigation) + let covering = UIViewController() + navigation.pushViewController(covering, animated: false) + try await settleTransitions(in: navigation) + #expect(await model.submit(service: source)?.id == "attempt_1") + #expect(navigation.topViewController === covering) + navigation.popViewController(animated: true) + let resultDeadline = ContinuousClock.now.advanced(by: .seconds(3)) + while !(navigation.topViewController is TrainingResultViewController), ContinuousClock.now < resultDeadline { + try await Task.sleep(for: .milliseconds(10)) + } + try await settleTransitions(in: navigation) + #expect(navigation.topViewController is TrainingResultViewController) + #expect(!(await source.calls).contains { $0.name == "attempt" }) + } + + @Test("身份切换后返回考试页清理旧数据并退出根页面,保留未知交卷键") + func changedIdentityReturnsToRootWithoutConsumingSubmission() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + var configuration = TrainingDataStub.Configuration() + configuration.questionCount = 3 + configuration.submitHandler = { _ in throw URLError(.timedOut) } + let source = TrainingDataStub(configuration: configuration) + await source.seedDraft(revision: 2, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]]) + let identity = TrainingExamTestIdentity(context) + let model = makeModel(defaults: domain.defaults, identity: identity) + let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model) + let root = UIViewController() + let center = TrainingCenterViewController(service: source) + let navigation = UINavigationController() + navigation.setViewControllers([root, center, controller], animated: false) + let window = try makeWindow(navigation) + defer { window.isHidden = true } + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + while !model.canEdit, ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } + #expect(model.canEdit) + try await settleTransitions(in: navigation) + let covering = UIViewController() + navigation.pushViewController(covering, animated: false) + try await settleTransitions(in: navigation) + #expect(await model.submit(service: source) == nil) + let store = TrainingPendingSubmissionStore(defaults: domain.defaults) + let stored = try store.load(taskID: "task_1", context: context) + let pending = try #require(stored) + identity.context = TrainingContext(accountScope: "other", scenicID: 10, storeID: 3) + navigation.popViewController(animated: true) + let exitDeadline = ContinuousClock.now.advanced(by: .seconds(3)) + while navigation.topViewController !== root, ContinuousClock.now < exitDeadline { + try await Task.sleep(for: .milliseconds(10)) + } + try await settleTransitions(in: navigation) + #expect(navigation.topViewController === root) + #expect(model.isIdentityInvalid && model.shouldReturnToCenter) + #expect(model.currentQuestion == nil && model.submittedAttempt == nil) + #expect(try store.load(taskID: "task_1", context: context) == pending) + #expect(await source.submissionRequests.count == 1) + } + + private func makeWindow(_ navigation: UINavigationController) throws -> UIWindow { + let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + let window = UIWindow(windowScene: scene) + window.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + window.rootViewController = navigation + navigation.beginAppearanceTransition(true, animated: false) + window.isHidden = false + navigation.endAppearanceTransition() + navigation.view.layoutIfNeeded() + return window + } + + private func settleTransitions(in navigation: UINavigationController) async throws { + // 非动画栈替换也可能在当前 main loop 中尚未结束。 + try await Task.sleep(for: .milliseconds(20)) + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + while navigation.transitionCoordinator != nil, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(10)) + } + #expect(navigation.transitionCoordinator == nil) + } + + @Test("再次加载重考页刷新资格但不重复清稿") + func returningExamDoesNotRepeatInitialReset() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + let source = TrainingDataStub() + await source.seedDraft(revision: 3, answers: ["q1": ["A"]]) + let model = makeModel(defaults: domain.defaults) + await model.load(service: source, resetDraft: true) + await model.select(optionID: "B", service: source) + await model.load(service: source, resetDraft: true) + #expect(await source.resetRequests.count == 1) + #expect(model.currentSelectedIDs == ["B"]) + } + + @Test("未知交卷恢复遇权限拒绝请求退出考试,但保留原持久化提交键") + func forbiddenRecoveryRetainsOriginalSubmission() async throws { + let domain = try makeDefaults() + defer { domain.defaults.removePersistentDomain(forName: domain.name) } + var configuration = TrainingDataStub.Configuration() + configuration.submitHandler = { _ in throw TrainingRemoteError.forbidden("任务暂不可访问") } + let source = TrainingDataStub(configuration: configuration) + let store = TrainingPendingSubmissionStore(defaults: domain.defaults) + let pending = TrainingPendingSubmission(taskID: "task_1", + request: TrainingSubmissionRequest(submissionID: "original", paperSnapshotID: "paper_1", draftRevision: 3), context: context) + try store.save(pending) + let model = makeModel(defaults: domain.defaults) + await model.load(service: source) + #expect(model.shouldReturnToCenter) + #expect(model.hasPendingSubmission) + #expect(try store.load(taskID: "task_1", context: context) == pending) + #expect(await source.submissionRequests == [pending.request]) + } +} diff --git a/suixinkanTests/TrainingRemoteListTests.swift b/suixinkanTests/TrainingRemoteListTests.swift new file mode 100644 index 0000000..1985e1e --- /dev/null +++ b/suixinkanTests/TrainingRemoteListTests.swift @@ -0,0 +1,112 @@ +import Foundation +import Testing +@testable import suixinkan + +/// 任务和成绩的分页、请求边界与缓存复用回归。 +@Suite("正式培训摘要与解析") +struct TrainingRemoteListTests { + @Test("首页只请求概览与三条任务摘要") + func homeUsesSmallResources() async { + let source = TrainingDataStub() + let model = TrainingRemoteCenterViewModel() + await model.load(service: source) + let calls = await source.calls + #expect(Set(calls.map(\.name)) == Set(["summary", "tasks"])) + #expect(calls.first { $0.name == "tasks" }?.limit == 3) + #expect(model.tasks.count == 1) + #expect(model.latestScore == "—") + } + + @Test("任务筛选传给服务端,用户翻页才消费游标") + func serverFilteringAndPagination() async { + let source = TrainingDataStub() + await source.configure { + $0.tasksHandler = { status, keyword, cursor, _ in + #expect(status == .completed) + #expect(keyword == "服务") + return TrainingCursorPage(items: [TrainingRemoteFixtures.task(id: cursor == nil ? "first" : "second")], nextCursor: cursor == nil ? "next" : nil, hasMore: cursor == nil, serverTime: nil) + } + } + let model = TrainingRemoteCenterViewModel() + model.selectTab(.tasks) + model.filter = .completed + model.keyword = " 服务 " + await model.load(service: source) + #expect(model.tasks.map(\.id) == ["first"]) + #expect(model.hasMore) + await model.loadMore(service: source) + #expect(model.tasks.map(\.id) == ["first", "second"]) + #expect(!model.hasMore) + #expect(await source.calls.count == 3) + } + + @Test("记录页不读取任务、试卷或课程") + func recordsAreIndependent() async { + let source = TrainingDataStub() + let model = TrainingRemoteCenterViewModel() + model.selectTab(.records) + await model.load(service: source) + #expect(Set(await source.calls.map(\.name)) == Set(["summary", "attempts"])) + } + + @Test("成绩首屏不预取解析,展开后只取一页并复用") + func reviewsAreLazyAndCached() async { + let source = TrainingDataStub() + let model = TrainingRemoteResultViewModel(attemptID: "attempt_1") + await model.load(service: source) + #expect(await source.calls.map(\.name) == ["attempt"]) + #expect(model.reviews.isEmpty) + await model.loadReviews(service: source) + await model.loadReviews(service: source) + #expect(model.reviews.count == 1) + #expect(await source.calls.filter { $0.name == "reviews" }.count == 1) + } + + @Test("解析失败保留成绩并能重试") + func reviewsFailureDoesNotHideScore() async { + let source = TrainingDataStub() + await source.configure { $0.reviewsHandler = { _ in throw APIError.networkFailed("离线") } } + let model = TrainingRemoteResultViewModel(attemptID: "attempt_1") + await model.load(service: source) + await model.loadReviews(service: source) + #expect(model.detail != nil) + #expect(model.reviewErrorMessage != nil) + await source.configure { $0.reviewsHandler = nil } + await model.loadReviews(service: source) + #expect(model.hasLoadedReviews) + } + + @Test("刷新成绩后解析不可用时移除此前缓存") + func reviewAvailabilityClearsCachedPages() async { + let source = TrainingDataStub() + let model = TrainingRemoteResultViewModel(attemptID: "attempt_1") + await model.load(service: source) + await model.loadReviews(service: source) + #expect(!model.reviews.isEmpty) + await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(reviewAvailable: false) } } + await model.load(service: source) + #expect(model.detail != nil) + #expect(model.reviews.isEmpty) + #expect(!model.hasLoadedReviews) + await model.loadReviews(service: source) + #expect(await source.calls.filter { $0.name == "reviews" }.count == 1) + } + + @Test("身份变化或权限撤回后清空已缓存成绩与解析", arguments: [TrainingRemoteError.identityChanged, .forbidden("任务权限已撤回")]) + func identityChangeClearsCachedResult(error: TrainingRemoteError) async { + let source = TrainingDataStub() + await source.configure { $0.reviewsHandler = { _ in + TrainingReviewPage(attemptID: "attempt_1", items: [TrainingRemoteFixtures.review()], nextCursor: "next", hasMore: true) + } } + let model = TrainingRemoteResultViewModel(attemptID: "attempt_1") + await model.load(service: source) + await model.loadReviews(service: source) + #expect(!model.reviews.isEmpty) + await source.configure { $0.reviewsHandler = { _ in throw error } } + await model.loadReviews(service: source, nextPage: true) + #expect(model.isIdentityInvalid == (error == .identityChanged)) + #expect(model.isAccessRevoked == (error.code == 150101)) + #expect(model.detail == nil) + #expect(model.reviews.isEmpty) + } +} diff --git a/suixinkanTests/TrainingRemoteReadingTests.swift b/suixinkanTests/TrainingRemoteReadingTests.swift new file mode 100644 index 0000000..774a6e3 --- /dev/null +++ b/suixinkanTests/TrainingRemoteReadingTests.swift @@ -0,0 +1,491 @@ +import Foundation +import Testing +@testable import suixinkan + +/// 正式课程的按需资源、前台计时和幂等恢复;只使用内存替身,不修改真实学员记录。 +@Suite("正式培训课程与读时") +@MainActor +struct TrainingRemoteReadingTests { + private func source(seconds: Int = 0) -> TrainingDataStub { + var configuration = TrainingDataStub.Configuration() + configuration.readingSeconds = seconds + return TrainingDataStub(configuration: configuration) + } + + private func model(_ source: TrainingDataStub) -> TrainingRemoteReadingViewModel { + TrainingRemoteReadingViewModel(taskID: "task_1", service: source, now: { TrainingRemoteFixtures.now }) + } + + private func bind(_ server: TrainingReadingReplyController, to source: TrainingDataStub) async { + await source.configure { + $0.progressHandler = { _ in await server.progress() } + $0.startReadingHandler = { try await server.create(requestID: $0) } + $0.heartbeatHandler = { try await server.confirm($0) } + } + } + + /// 百节课程首次只读一页目录和一节正文,明确选择过的正文才缓存。 + @Test("首次不遍历百节正文,目录主动分页,正文按选择复用") + func lazyCourseResources() async { + let source = source() + await source.configure { + $0.courseHandler = { TrainingCourseInfo(id: "course_1", title: "课程", introduction: "简介", sectionCount: 100, attachmentCount: 20) } + $0.sectionsHandler = { cursor in + let range = cursor == nil ? 1...20 : 21...40 + return TrainingCursorPage(items: range.map { TrainingSectionInfo(id: "s\($0)", order: $0, title: "小节\($0)") }, + nextCursor: cursor == nil ? "next" : "last", hasMore: true, serverTime: nil) + } + } + let model = model(source) + await model.load() + var calls = await source.calls + #expect(model.sections.count == 20) + #expect(calls.filter { $0.name == "sections" }.count == 1) + #expect(calls.first { $0.name == "sections" }?.limit == 20) + #expect(calls.filter { $0.name == "section" }.count == 1) + #expect(!calls.contains { ["attachments", "paper", "questions", "draft", "attempts"].contains($0.name) }) + await model.loadMoreSections() + #expect(model.sections.count == 40) + await model.selectSection(id: "s2") + await model.selectSection(id: "s1") + calls = await source.calls + #expect(calls.filter { $0.name == "section" }.count == 2) + #expect(calls.filter { $0.name == "sections" }.last?.cursor == "next") + } + + /// 倒计时本地刷新,五秒合并网络上报,最后一个片段关闭会话。 + @Test("每五秒上报且门槛由后端确认,完成后停止会话") + func batchedHeartbeatAndCompletion() async { + let source = source() + let model = model(source) + await model.load() + await model.startReading(at: 0) + for second in 1...4 { await model.recordVisibleTime(at: Double(second)) } + #expect(await source.heartbeats.isEmpty) + #expect(model.progress?.readingSeconds == 0) + for second in 5...20 { await model.recordVisibleTime(at: Double(second)) } + let calls = await source.heartbeats + #expect(calls.map(\.activeSecondsTotal) == [5, 10, 15, 20]) + #expect(calls.map(\.sequence) == [1, 2, 3, 4]) + #expect(calls.last?.final == true) + #expect(model.progress?.readingCompleted == true) + #expect(!model.isReading) + #expect(model.remainingSeconds == 0) + } + + /// 已保存读时不混入会话累计;不足五秒的门槛片段也即时确认。 + @Test("历史十二秒加新会话八秒,心跳总数仍从零开始") + func historyAndSessionAreSeparate() async { + let source = source(seconds: 12) + let model = model(source) + await model.load() + await model.startReading(at: 0) + for second in 1...8 { await model.recordVisibleTime(at: Double(second)) } + let calls = await source.heartbeats + #expect(calls.map(\.activeSecondsTotal) == [5, 8]) + #expect(calls.last?.final == true) + #expect(model.progress?.readingSeconds == 20) + #expect(model.progress?.readingCompleted == true) + } + + /// 后台间隔与未满秒片段均不补算,重开会话使用独立序号和累计秒数。 + @Test("暂停后长时间停留不补读时,恢复会话从零计时") + func pauseDoesNotCountBackgroundTime() async { + let source = source() + let model = model(source) + await model.load() + await model.startReading(at: 0) + for second in 1...3 { await model.recordVisibleTime(at: Double(second)) } + model.pauseReading() + await model.flush() + await model.recordVisibleTime(at: 999) + await model.startReading(at: 1000) + await model.recordVisibleTime(at: 1000.5) + await model.recordVisibleTime(at: 1001) + await model.recordVisibleTime(at: 1002) + model.pauseReading() + await model.flush() + let calls = await source.heartbeats + #expect(calls.map(\.activeSecondsTotal) == [3, 2]) + #expect(calls.map(\.sequence) == [1, 1]) + #expect(calls.allSatisfy { $0.final }) + #expect(calls[0].sessionID != calls[1].sessionID) + #expect(model.progress?.readingSeconds == 5) + } + + /// 创建已成功但响应丢失时,同一创建键恢复原会话。 + @Test("创建会话丢响应重试沿用 requestID") + func createResponseLossUsesSameRequestID() async { + let source = source() + let server = TrainingReadingReplyController(loseCreateResponse: true) + await bind(server, to: source) + let model = model(source) + await model.load() + await model.startReading(at: 0) + #expect(model.readingErrorMessage != nil) + await model.startReading(at: 10) + let requests = await source.startReadingRequests + #expect(requests.count == 2) + #expect(requests[0] == requests[1]) + #expect(model.isReading) + #expect(model.activeSecondsTotal == 0) + } + + /// 服务端已接受的普通心跳丢响应,不能改变序号或负载再次累计。 + @Test("心跳丢响应同序号同负载重试,不重复增记") + func heartbeatResponseLossIsIdempotent() async { + let source = source() + let server = TrainingReadingReplyController(loseHeartbeatResponse: true) + await bind(server, to: source) + let model = model(source) + await model.load() + await model.startReading(at: 0) + for second in 1...5 { await model.recordVisibleTime(at: Double(second)) } + #expect(model.progress?.readingSeconds == 0) + await model.flush() + let calls = await source.heartbeats + #expect(calls.count == 2) + #expect(calls[0] == calls[1]) + #expect(calls[0].final == false) + #expect(model.progress?.readingSeconds == 5) + #expect(await server.progress().readingSeconds == 5) + } + + /// 最终关闭请求同样冻结 final 和累计秒数,重试不能改成普通心跳。 + @Test("final 关闭丢响应保持原 final 负载,之后使用新会话") + func finalResponseLossKeepsPayload() async { + let source = source() + let server = TrainingReadingReplyController(loseHeartbeatResponse: true) + await bind(server, to: source) + let model = model(source) + await model.load() + await model.startReading(at: 0) + for second in 1...3 { await model.recordVisibleTime(at: Double(second)) } + model.pauseReading() + await model.flush() + #expect(model.readingErrorMessage != nil) + await model.flush(final: true) + let calls = await source.heartbeats + #expect(calls.count == 2) + #expect(calls[0] == calls[1]) + #expect(calls[0].final) + #expect(model.progress?.readingSeconds == 3) + await model.startReading(at: 100) + let requests = await source.startReadingRequests + #expect(requests.count == 2) + #expect(requests[0] != requests[1]) + #expect(model.activeSecondsTotal == 0) + } + + /// 暂停发生在网络请求中间时,先确认旧负载,再以新序号关闭。 + @Test("普通心跳请求中途暂停,确认后再发送 final") + func pauseDuringHeartbeatFinishesSequentially() async { + let source = source() + let gate = TrainingReadingHeartbeatGate() + await source.configure { $0.heartbeatHandler = { await gate.confirm($0) } } + let model = model(source) + await model.load() + await model.startReading(at: 0) + for second in 1...4 { await model.recordVisibleTime(at: Double(second)) } + let operation = Task { await model.recordVisibleTime(at: 5) } + await gate.waitUntilRequested() + model.pauseReading() + let closing = Task { await model.flush() } + #expect(await source.heartbeats.count == 1) + await gate.release() + await operation.value + await closing.value + let calls = await source.heartbeats + #expect(calls.count == 2) + #expect(calls[0].sequence == 1 && !calls[0].final) + #expect(calls[1].sequence == 2 && calls[1].final) + #expect(calls[0].activeSecondsTotal == calls[1].activeSecondsTotal) + #expect(!model.isReading) + #expect(model.progress?.readingSeconds == 5) + } + + /// 前台恢复发生在 final 请求中途,等待结束后必须真正建立新会话。 + @Test("final 请求仍在飞时恢复阅读,串行等待关闭后启动") + func resumeWaitsForFinalConfirmation() async { + let source = source() + let server = TrainingReadingReplyController() + let gate = TrainingReadingHeartbeatGate() + await bind(server, to: source) + await source.configure { $0.heartbeatHandler = { call in + _ = await gate.confirm(call) + return try await server.confirm(call) + } } + let model = model(source) + await model.load() + await model.startReading(at: 0) + for second in 1...3 { await model.recordVisibleTime(at: Double(second)) } + let closing = Task { await model.flush(final: true) } + await gate.waitUntilRequested() + let probe = TrainingReadingResumeProbe() + let resuming = Task { + probe.started = true + await model.startReading(at: 100) + probe.finished = true + } + while !probe.started { await Task.yield() } + #expect(!probe.finished) + #expect(await source.startReadingRequests.count == 1) + await gate.release() + await closing.value + await resuming.value + #expect(model.isReading) + #expect(await source.startReadingRequests.count == 2) + #expect(model.activeSecondsTotal == 0) + #expect(model.progress?.readingSeconds == 3) + await model.recordVisibleTime(at: 101) + #expect(model.activeSecondsTotal == 1) + } + + /// 任务截止后刷新只读资格,不可通过重试重新累计有效读时。 + @Test("150102刷新为只读资格,不能重新建立学习会话") + func notWritableRefreshesReadOnlyState() async { + let source = source() + let model = model(source) + await model.load() + await model.startReading(at: 0) + let saved = TrainingRemoteFixtures.progress(seconds: 7) + let readOnly = TrainingProgressSnapshot(taskID: saved.taskID, readingSeconds: saved.readingSeconds, + requiredReadingSeconds: saved.requiredReadingSeconds, + completedSectionCount: saved.completedSectionCount, sectionCount: saved.sectionCount, + progressPercent: saved.progressPercent, readingCompleted: false, + learnerStatus: .pendingExam, completedAt: nil, hasDraft: false, + canViewCourse: true, canStudy: false, canStartExam: false, + canRetry: false, blockReason: "closed", serverTime: saved.serverTime) + await source.configure { + $0.heartbeatHandler = { _ in throw TrainingRemoteError.notWritable("arbitrary closed message") } + $0.progressHandler = { _ in readOnly } + } + for second in 1...5 { await model.recordVisibleTime(at: Double(second)) } + #expect(!model.canStudy) + #expect(model.progress?.blockReason == "closed") + #expect(model.currentSection != nil) + await model.startReading(at: 100) + #expect(await source.startReadingRequests.count == 1) + #expect(!model.isReading) + } + + /// 稳定权限拒绝清空正文与进度,让页面立即退出而非保留旧内容。 + @Test("账号失效或培训权限撤回时清内容退出", arguments: [ + TrainingRemoteError.accountInvalid("account no longer eligible"), + TrainingRemoteError.forbidden("assignment revoked") + ]) + func accessDenialInvalidatesCourse(_ failure: TrainingRemoteError) async { + let source = source() + let model = model(source) + await model.load() + await model.startReading(at: 0) + await source.configure { $0.heartbeatHandler = { _ in throw failure } } + for second in 1...5 { await model.recordVisibleTime(at: Double(second)) } + #expect(model.isInvalidated) + #expect(model.currentSection == nil) + #expect(model.progress == nil) + #expect(model.sections.isEmpty) + #expect(!model.isReading) + } + + /// 只按稳定业务码恢复过期与冲突,不依据错误文案。 + @Test("会话过期或冲突先读权威进度,重建新会话序号", arguments: [ + TrainingRemoteError.sessionExpired("arbitrary expired message"), + TrainingRemoteError.sessionConflict("arbitrary conflict message") + ]) + func expiredSessionRestoresProgress(_ failure: TrainingRemoteError) async { + let source = source() + let server = TrainingReadingReplyController(nextFailure: failure) + await bind(server, to: source) + let model = model(source) + await model.load() + await model.startReading(at: 0) + for second in 1...5 { await model.recordVisibleTime(at: Double(second)) } + #expect(model.isReading) + #expect(model.activeSecondsTotal == 0) + #expect(await source.startReadingRequests.count == 2) + for second in 6...10 { await model.recordVisibleTime(at: Double(second)) } + let calls = await source.heartbeats + #expect(calls.count == 2) + #expect(calls[0].sessionID != calls[1].sessionID) + #expect(calls[1].sequence == 1) + #expect(calls[1].activeSecondsTotal == 5) + #expect(model.progress?.readingSeconds == 5) + #expect((await source.calls).filter { $0.name == "progress" }.count >= 2) + } + + /// 正文请求挂起时切身份,旧正文不能回到已经关闭的学员页面。 + @Test("身份切换丢弃迟到正文和权威进度") + func identityChangeDiscardsLateBody() async { + let source = source() + let gate = TrainingReadingBodyGate() + await source.configure { $0.sectionHandler = { _ in await gate.body() } } + let model = model(source) + let operation = Task { await model.load() } + await gate.waitUntilRequested() + model.invalidate() + await gate.release() + await operation.value + #expect(model.isInvalidated) + #expect(model.task == nil) + #expect(model.currentSection == nil) + #expect(model.progress == nil) + #expect(model.sections.isEmpty) + } + + /// 元信息不提前授权文件,用户点击附件时才申请短期可打开链接。 + @Test("附件目录按需分页,点击才获取授权地址") + func attachmentsAreLazyAndAuthorized() async { + let source = source(seconds: 20) + await source.configure { + $0.attachmentsHandler = { cursor in + let id = cursor == nil ? "file_1" : "file_2" + let item = TrainingAttachmentInfo(id: id, name: "培训.pdf", mimeType: "application/pdf", sizeBytes: 1024, + fileID: id, downloadURL: nil, expiresAt: nil) + return TrainingCursorPage(items: [item], nextCursor: cursor == nil ? "next" : nil, + hasMore: cursor == nil, serverTime: nil) + } + } + let model = model(source) + await model.load() + #expect(!(await source.calls).contains { $0.name == "attachments" }) + await model.loadAttachments() + await model.loadAttachments() + #expect((await source.calls).filter { $0.name == "attachments" }.count == 1) + #expect(!(await source.calls).contains { $0.name == "attachmentURL" }) + await model.loadAttachments(loadMore: true) + #expect(model.attachments.count == 2) + let link = await model.authorizeAttachment(id: "file_1") + #expect(link?.url.scheme == "https") + #expect(link?.expiresAt == TrainingRemoteFixtures.now.addingTimeInterval(3600)) + #expect((await source.calls).filter { $0.name == "attachmentURL" }.count == 1) + } + + /// 只读回顾仍能加载正文,但不创建会话、不增加读时。 + @Test("已读完的只读课程不新建学习会话") + func readOnlyDoesNotStartSession() async { + let source = source(seconds: 20) + let model = model(source) + await model.load() + await model.startReading(at: 0) + await model.recordVisibleTime(at: 1000) + #expect(model.currentSection != nil) + #expect(await source.startReadingRequests.isEmpty) + #expect(await source.heartbeats.isEmpty) + #expect(!model.isReading) + } +} + +/// 只模拟创建与心跳的服务器确认,支持先持久确认再丢响应和稳定业务失败。 +private actor TrainingReadingReplyController { + private var seconds = 0 + private var sessions: [String: TrainingStudySession] = [:] + private var bases: [String: Int] = [:] + private var confirmations: [String: (TrainingDataStub.HeartbeatCall, TrainingHeartbeatConfirmation)] = [:] + private var loseCreateResponse: Bool + private var loseHeartbeatResponse: Bool + private var nextFailure: TrainingRemoteError? + + /// 每个测试独立配置一次响应丢失或一次稳定业务错误。 + init(loseCreateResponse: Bool = false, loseHeartbeatResponse: Bool = false, nextFailure: TrainingRemoteError? = nil) { + self.loseCreateResponse = loseCreateResponse + self.loseHeartbeatResponse = loseHeartbeatResponse + self.nextFailure = nextFailure + } + + /// 当前权威读时由服务端状态生成。 + func progress() -> TrainingProgressSnapshot { TrainingRemoteFixtures.progress(seconds: seconds) } + + /// 同创建键返回原会话;响应丢失不撤销已经创建的会话。 + func create(requestID: String) throws -> TrainingStudySession { + if let saved = sessions[requestID] { return saved } + let session = TrainingStudySession(sessionID: requestID, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600), + heartbeatIntervalSeconds: 5, maxHeartbeatGapSeconds: 15, progress: progress()) + sessions[requestID] = session + bases[requestID] = seconds + if loseCreateResponse { loseCreateResponse = false; throw URLError(.timedOut) } + return session + } + + /// 先记服务端确认,再抛超时;重试必须保留完整的原负载。 + func confirm(_ call: TrainingDataStub.HeartbeatCall) throws -> TrainingHeartbeatConfirmation { + if let failure = nextFailure { nextFailure = nil; throw failure } + let key = "\(call.sessionID):\(call.sequence)" + if let (prior, saved) = confirmations[key] { + guard prior == call else { throw TrainingRemoteError.sessionConflict("changed retry payload") } + return saved + } + seconds = min(20, max(seconds, (bases[call.sessionID] ?? 0) + call.activeSecondsTotal)) + let result = TrainingHeartbeatConfirmation(sessionID: call.sessionID, acceptedSequence: call.sequence, + acceptedActiveSecondsTotal: call.activeSecondsTotal, + sessionClosed: call.final, progress: progress()) + confirmations[key] = (call, result) + if loseHeartbeatResponse { loseHeartbeatResponse = false; throw URLError(.timedOut) } + return result + } +} + +/// 不使用固定延时的正文响应闸门,精确控制身份切换和迟到响应的先后顺序。 +private actor TrainingReadingBodyGate { + private var response: CheckedContinuation? + private var waiters: [CheckedContinuation] = [] + + /// 等待测试明确释放正文,通知等待请求已发出的测试代码。 + func body() async -> TrainingSectionContent { + await withCheckedContinuation { + response = $0 + waiters.forEach { $0.resume() } + waiters = [] + } + } + + /// 不轮询地等待正文请求已经挂起。 + func waitUntilRequested() async { + if response != nil { return } + await withCheckedContinuation { waiters.append($0) } + } + + /// 在身份已变化后返回旧账号正文。 + func release() { + response?.resume(returning: TrainingSectionContent(id: "s1", order: 1, title: "旧正文", contentHTML: "

旧账号课程

")) + response = nil + } +} + +/// 精确挂起首个普通心跳,验证暂停不会并行发送或更改该请求。 +private actor TrainingReadingHeartbeatGate { + private var response: CheckedContinuation? + private var waiters: [CheckedContinuation] = [] + private var hasDelayed = false + + /// 首个请求等待测试释放,后续最终心跳立即确认。 + func confirm(_ call: TrainingDataStub.HeartbeatCall) async -> TrainingHeartbeatConfirmation { + if !hasDelayed { + hasDelayed = true + await withCheckedContinuation { + response = $0 + waiters.forEach { $0.resume() } + waiters = [] + } + } + return TrainingHeartbeatConfirmation(sessionID: call.sessionID, acceptedSequence: call.sequence, + acceptedActiveSecondsTotal: call.activeSecondsTotal, sessionClosed: call.final, + progress: TrainingRemoteFixtures.progress(seconds: call.activeSecondsTotal)) + } + + /// 不使用时间延迟,等待首个网络请求已经挂起。 + func waitUntilRequested() async { + if response != nil { return } + await withCheckedContinuation { waiters.append($0) } + } + + /// 让普通心跳完成,页面随后应使用新序号发送 final。 + func release() { response?.resume(); response = nil } +} + +/// 记录恢复动作是否已进入和完成,避免用固定延时验证串行等待。 +@MainActor +private final class TrainingReadingResumeProbe { + var started = false + var finished = false +} diff --git a/suixinkanTests/TrainingUIRenderingTests.swift b/suixinkanTests/TrainingUIRenderingTests.swift index 23c5a03..7763268 100644 --- a/suixinkanTests/TrainingUIRenderingTests.swift +++ b/suixinkanTests/TrainingUIRenderingTests.swift @@ -14,7 +14,7 @@ struct TrainingUIRenderingTests { defer { try? FileManager.default.removeItem(at: directory) } let source = TrainingDemoService(context: TrainingContext(accountScope: "render", scenicID: 1, storeID: 1), storage: TrainingDemoFileStorage(directory: directory)) - let controller = TrainingCenterViewController(service: source) + let controller = TrainingCenterViewController(service: TrainingDataStub()) controller.loadViewIfNeeded() await controller.reload() let navigation = UINavigationController(rootViewController: controller) @@ -23,8 +23,8 @@ struct TrainingUIRenderingTests { navigation.view.layoutIfNeeded() Attachment.record(render(navigation.view), named: "培训首页", as: .png) let labels = allViews(controller.view).compactMap { $0 as? UILabel } - #expect(labels.contains { $0.text == "一线服务规范学习(演示)" }) - #expect(labels.contains { $0.text?.contains("未同步景区后台") == true }) + #expect(labels.contains { $0.text == "一线服务规范学习" }) + #expect(!labels.contains { $0.text?.contains("未同步景区后台") == true }) let original = try await source.task(id: "demo-service") let longTask = TrainingTask(id: original.id, title: String(repeating: "游客沟通与接待服务规范培训", count: 3), @@ -58,50 +58,62 @@ struct TrainingUIRenderingTests { @Test("未通过成绩可展开解析并返回已有课程,旧失败成绩在通过后不可重考") func resultLearningAndReviewNavigation() async throws { - let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: directory) } - let source = TrainingDemoService(context: TrainingContext(accountScope: "result-render", scenicID: 1, storeID: 1), storage: TrainingDemoFileStorage(directory: directory)) - for _ in 0..<20 { _ = try await source.recordReadingSecond(taskID: "demo-service") } - let wrong: TrainingAnswers = ["q1": ["B"], "q2": ["C"], "q3": ["A"], "q4": ["D"]] - let attempt = try await source.submit(taskID: "demo-service", answers: wrong, submissionID: "failed") + let source = TrainingDataStub() + await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(passed: false) } } + let attempt = TrainingRemoteFixtures.attempt(passed: false) let center = TrainingCenterViewController(service: source) - let course = TrainingCourseViewController(taskID: "demo-service", service: source) - let result = TrainingResultViewController(taskID: "demo-service", attemptID: attempt.id, service: source) + let course = TrainingCourseViewController(taskID: "task_1", service: source) + let result = TrainingResultViewController(taskID: "task_1", attemptID: attempt.id, service: source) let navigation = UINavigationController() navigation.setViewControllers([center, course, result], animated: false) let window = try makeWindow(navigation) defer { window.isHidden = true } result.loadViewIfNeeded() await result.reload() + try await settleTransitions(in: navigation) navigation.view.layoutIfNeeded() let learning = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.learning" }) let details = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.details" }) let action = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.action" }) #expect(action.configuration?.title == "再考一次") - #expect(!allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == attempt.reviews.first?.question.stem }) + #expect(!allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == TrainingRemoteFixtures.review().stem }) Attachment.record(render(navigation.view), named: "未通过成绩默认收起解析", as: .png) details.sendActions(for: .touchUpInside) + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + while !allViews(result.view).compactMap({ $0 as? UILabel }).contains(where: { $0.text == TrainingRemoteFixtures.review().stem }), ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(10)) + } navigation.view.layoutIfNeeded() - #expect(allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == attempt.reviews.first?.question.stem }) + #expect(allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == TrainingRemoteFixtures.review().stem }) Attachment.record(render(navigation.view), named: "成绩答案解析展开", as: .png) learning.sendActions(for: .touchUpInside) + try await settleTransitions(in: navigation) #expect(navigation.topViewController === course) navigation.setViewControllers([center, result], animated: false) + try await settleTransitions(in: navigation) await result.reload() let newLearning = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.learning" }) newLearning.sendActions(for: .touchUpInside) - #expect((navigation.topViewController as? TrainingCourseViewController)?.taskID == "demo-service") - let passed = try await source.submit(taskID: "demo-service", answers: ["q1": ["A"], "q2": ["A", "B"], "q3": ["B"], "q4": ["A", "B", "C"]], submissionID: "passed") + try await settleTransitions(in: navigation) + #expect((navigation.topViewController as? TrainingCourseViewController)?.taskID == "task_1") + await source.configure { $0.attemptHandler = { _ in + TrainingAttemptDetail(attempt: TrainingRemoteFixtures.attempt(passed: false), taskState: TrainingRemoteFixtures.result(passed: true).taskState, serverTime: TrainingRemoteFixtures.now) + } } + let passed = TrainingRemoteFixtures.attempt(passed: true) navigation.setViewControllers([center, result], animated: false) + try await settleTransitions(in: navigation) await result.reload() #expect(action.configuration?.title == "完成,返回培训中心") - let passedResult = TrainingResultViewController(taskID: "demo-service", attemptID: passed.id, service: source) + await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(passed: true) } } + let passedResult = TrainingResultViewController(taskID: "task_1", attemptID: passed.id, service: source) navigation.setViewControllers([center, passedResult], animated: false) + try await settleTransitions(in: navigation) await passedResult.reload() navigation.view.layoutIfNeeded() Attachment.record(render(navigation.view), named: "通过成绩仍可返回学习", as: .png) let completion = try #require(allViews(passedResult.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.action" }) completion.sendActions(for: .touchUpInside) + try await settleTransitions(in: navigation) #expect(navigation.topViewController === center) } @@ -146,6 +158,16 @@ struct TrainingUIRenderingTests { Attachment.record(image, named: "100题答题卡", as: .png) } + /// 前一导航动画结束后再执行后续操作,避免测试同时驱动互相冲突的转场。 + private func settleTransitions(in navigation: UINavigationController) async throws { + await Task.yield() + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + while navigation.transitionCoordinator != nil, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(10)) + } + #expect(navigation.transitionCoordinator == nil) + } + /// 按实际可见状态等待差异化列表动画,超时后让测试明确失败。 private func waitForVisibleCell(at indexPath: IndexPath, in collection: UICollectionView) async throws -> UICollectionViewCell { let deadline = ContinuousClock.now.advanced(by: .seconds(3))