Files
suixinkan_uikit/suixinkan/Features/Training/Models/TrainingAPIModels.swift
T
lujiuyin 27be1f30ed feat(training): 新增已结束筛选并精简课程展示
新增已结束任务筛选与只读回顾资格,保留搜索和游标分页。移除任务小节数量及课程附件文件名、切换入口,并更新接口和界面回归测试。
2026-10-20 14:04:25 +08:00

722 lines
24 KiB
Swift

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
case "ended": self = .ended
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 { switch self { case .pendingExam: "pending"; case .completed: "completed"; case .ended: "ended" } }
}
/// 游标分页;小节、附件、任务和成绩复用相同分页边界。
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"
}
}