feat(training): 接入真实培训接口与学习答题恢复

This commit is contained in:
2026-10-14 16:18:48 +08:00
parent 8862ae5401
commit 01068bb24e
28 changed files with 4945 additions and 238 deletions
+4
View File
@@ -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)
+12 -1
View File
@@ -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)
}
@@ -9,6 +9,7 @@ import Foundation
enum HTTPMethod: String {
case get = "GET"
case post = "POST"
case patch = "PATCH"
case put = "PUT"
case delete = "DELETE"
}
@@ -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)
@@ -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)
@@ -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)
}
@@ -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<Item: Codable & Equatable & Sendable>: 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"
}
}
@@ -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<TrainingTaskSummary> {
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<TrainingSectionInfo> {
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<TrainingAttachmentInfo> {
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<TrainingAttemptSummary> {
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<Response: Decodable>(_ path: String, query: [URLQueryItem] = []) async throws -> Response {
try await perform(APIRequest<Response>(method: .get, path: prefix + path, queryItems: query, logsPayload: false))
}
private func write<Response: Decodable, Body: Encodable>(_ method: HTTPMethod, _ path: String, body: Body) async throws -> Response {
try await perform(APIRequest<Response>(method: method, path: prefix + path, body: body, logsPayload: false))
}
private func perform<Response: Decodable>(_ request: APIRequest<Response>) 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"
}
}
}
@@ -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<TrainingTaskSummary>
/// 获取任务规则和快照引用。
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<TrainingSectionInfo>
/// 读取一个小节的正式正文。
func section(courseID: String, sectionID: String, taskID: String) async throws -> TrainingSectionContent
/// 读取附件元信息页。
func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttachmentInfo>
/// 获取短期附件授权链接。
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<TrainingAttemptSummary>
/// 读取一条成绩和最新重考资格。
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
})
}
}
@@ -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)"
}
}
@@ -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<Int> = []
/// 最近确认的草稿版本,未加载前为零。
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<Int> = []
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<String> { 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..<questionCount).contains(index) else { return }
isBusy = true
errorMessage = nil
defer { isBusy = false }
do {
try await authorize()
currentIndex = index
try await loadCurrentPage(service: service)
guard let paper else { throw TrainingError.invalidPaper }
pendingMutation = .save(TrainingDraftSaveRequest(requestID: UUID().uuidString, paperSnapshotID: paper.id,
baseRevision: draftRevision, lastQuestionOrder: index + 1, changes: []))
try await performMutation(service: service)
} catch { report(error) }
}
/// 增量保存当前一题,网络结果未知时保留原 ID 和完整请求供重试。
func select(optionID: String, service: any TrainingDataServing) async {
guard canEdit, let question = currentQuestion, let paper,
question.options.contains(where: { $0.id == optionID }) else { return }
isBusy = true
errorMessage = nil
defer { isBusy = false }
do {
try await authorize()
var selected = currentSelectedIDs
if question.type == .single { selected = [optionID] }
else if selected.contains(optionID) { selected.remove(optionID) }
else { selected.insert(optionID) }
pendingMutation = .save(TrainingDraftSaveRequest(requestID: UUID().uuidString, paperSnapshotID: paper.id,
baseRevision: draftRevision, lastQuestionOrder: question.order,
changes: [TrainingDraftChange(questionID: question.id, selectedOptionIDs: selected.sorted())]))
try await performMutation(service: service)
} catch { report(error) }
}
/// 沿用失败草稿写入的原请求,不生成新的幂等键。
func retryMutation(service: any TrainingDataServing) async {
guard !isBusy, pendingMutation != nil, !hasPendingSubmission else { return }
isBusy = true
errorMessage = nil
defer { isBusy = false }
do { try await authorize(); try await performMutation(service: service) }
catch { report(error) }
}
/// 仅重读当前未就绪题位;已确认的其它页不会因一次网络失败被清空。
func retryCurrentPage(service: any TrainingDataServing) async {
guard canRetryCurrentPage else { return }
isBusy = true
errorMessage = nil
defer { isBusy = false }
do {
try await authorize()
if needsDraftRefresh { try await refreshDraft(service: service) }
else { try await loadCurrentPage(service: service) }
} catch { report(error) }
}
/// 持久保存交卷请求后提交;未知结果先查原键,再重试原版本。
func submit(service: any TrainingDataServing) async -> 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..<coveredEnd {
if let question = questionCache[index] { answerCache[question.id] = [] }
}
for answer in page.items {
guard (offset + 1...coveredEnd).contains(answer.order), !answer.questionID.isEmpty,
Set(answer.selectedOptionIDs).count == answer.selectedOptionIDs.count else { throw TrainingError.invalidAnswers }
if let question = questionCache[answer.order - 1] {
guard question.id == answer.questionID,
Set(answer.selectedOptionIDs).isSubset(of: Set(question.options.map(\.id))),
question.type != .single || answer.selectedOptionIDs.count <= 1 else { throw TrainingError.invalidAnswers }
}
answerCache[answer.questionID] = Set(answer.selectedOptionIDs)
}
loadedDraftIndices.formUnion(offset..<coveredEnd)
}
private func refreshDraft(service: any TrainingDataServing) async throws {
needsDraftRefresh = true
let metadata = try await service.draft(taskID: taskID, offset: 0, limit: 0)
try await authorize()
answerCache = [:]
loadedDraftIndices = []
try applyMetadata(metadata)
try await loadCurrentPage(service: service)
}
private func performMutation(service: any TrainingDataServing) async throws {
guard let mutation = pendingMutation else { return }
do {
let confirmation: TrainingDraftConfirmation
switch mutation {
case .save(let request): confirmation = try await service.saveDraft(taskID: taskID, request: request)
case .reset(let request): confirmation = try await service.resetDraft(taskID: taskID, request: request)
}
try await authorize()
guard confirmation.draftRevision >= 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
}
}
@@ -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)"
}
}
@@ -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<Void, Never>] = []
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 }
}
}
}
@@ -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)"
@@ -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<Void, Never>?
private var searchTask: Task<Void, Never>?
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<Int, Item>!
/// 默认连接正式服务,开发演示仅由用户显式打开。
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<Int, Item>()
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<Void, Never>) 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) }
}
}
}
@@ -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<Void, Never>?
private var readingTask: Task<Void, Never>?
private var closingTask: Task<Void, Never>?
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 { "<section><h2>\(escape($0.title))</h2>\($0.contentHTML)</section>" }.joined()
let attachments = task.course.attachments.map { attachment in
guard let url = attachment.url, url.scheme?.lowercased() == "https", url.host != nil else {
return "<p>附件:\(escape(attachment.name))(尚未同步)</p>"
}
return "<p><a href=\"\(escape(url.absoluteString))\">📄 \(escape(attachment.name))</a></p>"
}.joined()
let demo = service.isDemo ? "<p class='demo'>开发演示 · 记录仅保存在本机,未同步景区后台</p>" : ""
let meta = task.mode == .exam ? "学习 + 考试 · \(task.course.sections.count) 节 · \(task.questions.count) 题 · \(task.passScore) 分及格" : "仅学习 · \(task.course.sections.count) 节"
webView.loadHTMLString("""
<!doctype html><html lang="zh-CN"><head><meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
<style>
*{box-sizing:border-box}body{font:15px -apple-system,BlinkMacSystemFont,sans-serif;color:#34435b;background:#f5f8fc;margin:0;padding:14px 13px;line-height:1.95;overflow-wrap:anywhere}
h1{font-size:17px;font-weight:600;line-height:1.6;color:#172033;margin:14px 0 6px}h2{font-size:15.5px;font-weight:600;color:#172033;margin:0 0 10px}img{max-width:100%;height:auto}table{max-width:100%;display:block;overflow:auto}section{margin:0 0 24px}section:last-child{margin-bottom:0}a{color:#2379ff}
.demo{color:#946116;background:#fff5e5;font-size:11px;padding:8px 10px;border-radius:6px;line-height:1.6;margin:0 0 12px}
.step{display:flex;gap:20px;background:#edf1f7;padding:9px 12px;border-radius:8px;font-size:13px;color:#8994a6}.step b{font-weight:500;color:#2379ff}
.muted{font-size:12.5px;color:#8491a6;line-height:1.65;margin:6px 0}.reading{background:white;border:1px solid #e3ebf5;border-radius:11px;padding:14px;margin-top:14px}
</style></head>
<body>\(demo)<div class='step'><b>1 课程学习</b><span>\(task.mode == .exam ? "2 在线考试" : "完成学习")</span></div><h1>\(escape(task.title))</h1><p class='muted'>\(escape(task.course.title))</p><p class='muted'>\(meta)</p><p class='muted'>\(escape(task.course.introduction))</p><div class='reading'>\(sections)</div>\(attachments)</body></html>
""", 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("""
<!doctype html><html lang="zh-CN"><head><meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
<style>
*{box-sizing:border-box}body{font:15px -apple-system,BlinkMacSystemFont,sans-serif;color:#34435b;background:#f5f8fc;margin:0;padding:14px 13px;line-height:1.95;overflow-wrap:anywhere}
h1{font-size:17px;font-weight:600;line-height:1.6;color:#172033;margin:14px 0 6px}h2{font-size:15.5px;font-weight:600;color:#172033;margin:0 0 10px}img{max-width:100%;height:auto}table{max-width:100%;display:block;overflow:auto}a{color:#2379ff}
.step{display:flex;gap:20px;background:#edf1f7;padding:9px 12px;border-radius:8px;font-size:13px;color:#8994a6}.step b{font-weight:500;color:#2379ff}
.muted{font-size:12.5px;color:#8491a6;line-height:1.65;margin:6px 0}.reading{background:white;border:1px solid #e3ebf5;border-radius:11px;padding:14px;margin-top:14px}
</style></head><body><div class='step'><b>1 课程学习</b><span>\(task.mode == .exam ? "2 在线考试" : "完成学习")</span></div>
<h1>\(escape(task.title))</h1><p class='muted'>\(escape(course.title))</p><p class='muted'>\(metadata)</p><p class='muted'>\(escape(course.introduction))</p>
<p class='muted'>第 \(section.order) / \(course.sectionCount) 节</p><div class='reading'><h2>\(escape(section.title))</h2>\(section.contentHTML)</div></body></html>
""", baseURL: nil)
}
private func escape(_ text: String) -> String {
text.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
}
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<Int, Item>!
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<Int, Item>(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<Int, Item>()
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() }
}
@@ -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<Int>
private let currentIndex: Int
private let collectionView: UICollectionView
private var dataSource: UICollectionViewDiffableDataSource<Int, Int>!
/// 关闭答题卡后将用户选择的题目位置返回考试页面。
var onSelect: ((Int) -> Void)?
/// 根据本次草稿展示已答和当前题,不显示正确答案。
init(task: TrainingTask, answers: TrainingAnswers, currentIndex: Int) {
self.task = task
self.answers = answers
/// 使用总题数和已答题号展示答题卡,无需下载题目或全部答案。
init(questionCount: Int, answeredOrders: Set<Int>, 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<Int, Int>(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<Int, Int>()
snapshot.appendSections([0])
snapshot.appendItems(Array(task.questions.indices))
snapshot.appendItems(Array(0..<questionCount))
dataSource.apply(snapshot, animatingDifferences: true)
}
}
@@ -6,21 +6,35 @@ import UIKit
final class TrainingResultViewController: TrainingBaseViewController {
private let taskID: String
private let attemptID: String
private let service: any TrainingServing
private var loadedTask: TrainingTask?
private var loadedAttempt: TrainingAttempt?
private let service: any TrainingDataServing
private let viewModel: TrainingRemoteResultViewModel
private let validateIdentity: () -> Bool
private var loadFailed = false
private var showsDetails = false
private var usesInitialDetail: Bool
private var resultLoadTask: Task<Void, Never>?
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<Void, Never> { @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>) -> 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)
+31
View File
@@ -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
}
}
/// 培训页面在账号或景区切换时立即关闭,停止展示旧身份记录。