feat(training): 同步培训中心学习答题功能
新增首页和个人页入口,支持课程阅读、答题卡、草稿恢复、成绩解析、历史记录与重考。保留独立的 Debug 本地演示数据源及后端接入协议,并对齐列表动画和答题卡布局约定。 来源:xh_test 的 74c451c。验证:iPhone 11 真机 59 项相关测试全部通过;全量测试中的 8 个既有失败已在同步前版本复现。
This commit is contained in:
@@ -21,6 +21,7 @@ enum HomeMenuCatalog {
|
|||||||
HomeMenuItem(uri: "schedule_management", title: "日程管理", iconName: "calendar"),
|
HomeMenuItem(uri: "schedule_management", title: "日程管理", iconName: "calendar"),
|
||||||
HomeMenuItem(uri: "system_settings", title: "设置中心", iconName: "gearshape.fill"),
|
HomeMenuItem(uri: "system_settings", title: "设置中心", iconName: "gearshape.fill"),
|
||||||
HomeMenuItem(uri: "message_center", title: "消息中心", iconName: "bell.fill"),
|
HomeMenuItem(uri: "message_center", title: "消息中心", iconName: "bell.fill"),
|
||||||
|
HomeMenuItem(uri: "/training", title: "培训中心", iconName: "graduationcap.fill"),
|
||||||
HomeMenuItem(uri: "checkin_points", title: "打卡点管理", iconName: "home_menu_punch_point"),
|
HomeMenuItem(uri: "checkin_points", title: "打卡点管理", iconName: "home_menu_punch_point"),
|
||||||
HomeMenuItem(uri: "sample_management", title: "样片管理", iconName: "sample_ic_home_menu_route"),
|
HomeMenuItem(uri: "sample_management", title: "样片管理", iconName: "sample_ic_home_menu_route"),
|
||||||
HomeMenuItem(uri: "live_stream_management", title: "直播管理", iconName: "dot.radiowaves.left.and.right"),
|
HomeMenuItem(uri: "live_stream_management", title: "直播管理", iconName: "dot.radiowaves.left.and.right"),
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ enum HomeRouteHandler {
|
|||||||
viewController.navigationController?.pushViewController(SettingViewController(), animated: true)
|
viewController.navigationController?.pushViewController(SettingViewController(), animated: true)
|
||||||
case "message_center":
|
case "message_center":
|
||||||
viewController.navigationController?.pushViewController(MessageCenterViewController(), animated: true)
|
viewController.navigationController?.pushViewController(MessageCenterViewController(), animated: true)
|
||||||
|
case "/training":
|
||||||
|
viewController.navigationController?.pushViewController(TrainingCenterViewController(), animated: true)
|
||||||
case "space_settings":
|
case "space_settings":
|
||||||
viewController.navigationController?.pushViewController(ProfileSpaceSettingsViewController(), animated: true)
|
viewController.navigationController?.pushViewController(ProfileSpaceSettingsViewController(), animated: true)
|
||||||
case "cloud_management":
|
case "cloud_management":
|
||||||
|
|||||||
@@ -293,12 +293,19 @@ final class HomeViewModel {
|
|||||||
commonMenuStore.saveCommonURIs(defaultURIs, accountScope: accountScope, roleCode: roleCode)
|
commonMenuStore.saveCommonURIs(defaultURIs, accountScope: accountScope, roleCode: roleCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
commonMenus = commonMenuStore.commonMenus(
|
var resolvedMenus = commonMenuStore.commonMenus(
|
||||||
from: allMenus,
|
from: allMenus,
|
||||||
permissions: permissions,
|
permissions: permissions,
|
||||||
accountScope: accountScope,
|
accountScope: accountScope,
|
||||||
roleCode: roleCode
|
roleCode: roleCode
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 所有角色均可进入个人培训;培训名单仍由服务端授权。
|
||||||
|
if let entry = HomeMenuCatalog.item(for: "/training"),
|
||||||
|
!resolvedMenus.contains(where: { $0.uri == entry.uri }) {
|
||||||
|
resolvedMenus.append(entry)
|
||||||
|
}
|
||||||
|
commonMenus = resolvedMenus
|
||||||
}
|
}
|
||||||
|
|
||||||
func hidePermissionDialog() {
|
func hidePermissionDialog() {
|
||||||
|
|||||||
@@ -0,0 +1,265 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 培训任务类型:仅学习或学习后考试。
|
||||||
|
enum TrainingMode: String, Codable, Sendable { case study, exam }
|
||||||
|
|
||||||
|
/// 任务发布状态;关闭后只允许回顾。
|
||||||
|
enum TrainingTaskStatus: String, Codable, Sendable { case published, closed }
|
||||||
|
|
||||||
|
/// 学员列表统一展示的两种状态。
|
||||||
|
enum TrainingLearnerStatus: String, CaseIterable, Sendable {
|
||||||
|
case pendingExam, completed
|
||||||
|
|
||||||
|
/// 面向学员的状态名称。
|
||||||
|
var title: String { self == .completed ? "已完成" : "待考试" }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 单选和多选题型。
|
||||||
|
enum TrainingQuestionType: String, Codable, Sendable { case single, multiple }
|
||||||
|
|
||||||
|
/// 发布时冻结的课程图文小节,HTML 应由服务端清洗。
|
||||||
|
struct TrainingSection: Codable, Equatable, Sendable {
|
||||||
|
let id: String
|
||||||
|
let title: String
|
||||||
|
let contentHTML: String
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 具有授权 HTTPS 地址的课程附件。
|
||||||
|
struct TrainingAttachment: Codable, Equatable, Sendable {
|
||||||
|
let id: String
|
||||||
|
let name: String
|
||||||
|
let url: URL?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 学习端课程快照,保留文字小节和附件。
|
||||||
|
struct TrainingCourse: Codable, Equatable, Sendable {
|
||||||
|
let title: String
|
||||||
|
let introduction: String
|
||||||
|
let sections: [TrainingSection]
|
||||||
|
let attachments: [TrainingAttachment]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 试题选项 ID 与正文。
|
||||||
|
struct TrainingOption: Codable, Equatable, Sendable {
|
||||||
|
let id: String
|
||||||
|
let text: String
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 考前试题不携带正确答案和解析。
|
||||||
|
struct TrainingQuestion: Codable, Equatable, Sendable {
|
||||||
|
let id: String
|
||||||
|
let type: TrainingQuestionType
|
||||||
|
let stem: String
|
||||||
|
let options: [TrainingOption]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 答题草稿,以题目和选项快照 ID 保存。
|
||||||
|
typealias TrainingAnswers = [String: Set<String>]
|
||||||
|
|
||||||
|
/// 交卷后返回的单题解析与本次所选答案。
|
||||||
|
struct TrainingQuestionReview: Codable, Equatable, Sendable {
|
||||||
|
let question: TrainingQuestion
|
||||||
|
let selectedIDs: Set<String>
|
||||||
|
let correctIDs: Set<String>
|
||||||
|
let explanation: String
|
||||||
|
|
||||||
|
/// 多选必须集合完全相等才算答对。
|
||||||
|
var isCorrect: Bool { selectedIDs == correctIDs }
|
||||||
|
|
||||||
|
/// 将选项 ID 转为可读的字母序号和正文。
|
||||||
|
func answerText(ids: Set<String>) -> String {
|
||||||
|
let values = question.options.enumerated().compactMap { index, option in
|
||||||
|
ids.contains(option.id) ? "\(TrainingQuestion.optionLetter(index)).\(option.text)" : nil
|
||||||
|
}
|
||||||
|
return values.isEmpty ? "未作答" : values.joined(separator: "\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension TrainingQuestion {
|
||||||
|
/// 题目最多六个选项,对外显示 A–F,提交仍使用原始 ID。
|
||||||
|
static func optionLetter(_ index: Int) -> String {
|
||||||
|
let letters = ["A", "B", "C", "D", "E", "F"]
|
||||||
|
return letters.indices.contains(index) ? letters[index] : "?"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 小程序任务卡的展示状态;学习进度由已保存小节计算。
|
||||||
|
struct TrainingTaskPresentation {
|
||||||
|
let task: TrainingTask
|
||||||
|
/// 判断任务开始与截止状态的时间,可注入以验证时间边界。
|
||||||
|
var now = Date()
|
||||||
|
|
||||||
|
/// 已保存完成的小节占全部课程小节的整数百分比。
|
||||||
|
var progressPercent: Int {
|
||||||
|
guard !task.course.sections.isEmpty else { return 0 }
|
||||||
|
return task.course.sections.filter { task.progress.completedSectionIDs.contains($0.id) }.count * 100 / task.course.sections.count
|
||||||
|
}
|
||||||
|
/// 已完成阅读且任务允许提交时才能进入考试。
|
||||||
|
var canStartExam: Bool { task.mode == .exam && task.hasFinishedReading && task.submissionBlockReason(now: now) == nil }
|
||||||
|
|
||||||
|
/// 根据完成状态、有效期与草稿决定任务卡主按钮文案。
|
||||||
|
var actionTitle: String {
|
||||||
|
if task.learnerStatus == .completed { return "回顾学习" }
|
||||||
|
if task.submissionBlockReason(now: now) != nil { return "查看课程" }
|
||||||
|
if canStartExam { return task.progress.draftAnswers.values.contains(where: { !$0.isEmpty }) ? "继续答题" : "开始考试" }
|
||||||
|
return "去学习"
|
||||||
|
}
|
||||||
|
/// 解释任务当前可执行操作或继续学习的条件。
|
||||||
|
var hint: String {
|
||||||
|
if task.learnerStatus == .completed { return "已完成本次学习任务" }
|
||||||
|
if task.submissionBlockReason(now: now) != nil { return now < task.startAt ? "任务尚未开始,暂不能提交" : "任务已结束,仅可回顾内容" }
|
||||||
|
if canStartExam { return "课程已学完,可以开始考试" }
|
||||||
|
return "请阅读课程内容,倒计时结束后" + (task.mode == .exam ? "即可考试" : "完成学习")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 服务端考试记录;演示成绩必须明确标记。
|
||||||
|
struct TrainingAttempt: Codable, Equatable, Sendable {
|
||||||
|
let id: String
|
||||||
|
let submittedAt: Date
|
||||||
|
let scoreHundredths: Int
|
||||||
|
let correctCount: Int
|
||||||
|
let questionCount: Int
|
||||||
|
let passed: Bool
|
||||||
|
let isDemo: Bool
|
||||||
|
let reviews: [TrainingQuestionReview]
|
||||||
|
|
||||||
|
/// 分数最多两位小数,使用已经截断的百分之一分整数。
|
||||||
|
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 TrainingProgress: Codable, Equatable, Sendable {
|
||||||
|
var readingSeconds = 0
|
||||||
|
var completedSectionIDs: Set<String> = []
|
||||||
|
var completedAt: Date?
|
||||||
|
var draftAnswers: TrainingAnswers = [:]
|
||||||
|
var attempts: [TrainingAttempt] = []
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前学员被分配的任务,内容以发布快照为准。
|
||||||
|
struct TrainingTask: Codable, Equatable, Sendable {
|
||||||
|
let id: String
|
||||||
|
let title: String
|
||||||
|
let publisherName: String?
|
||||||
|
let mode: TrainingMode
|
||||||
|
var status: TrainingTaskStatus
|
||||||
|
let startAt: Date
|
||||||
|
let endAt: Date
|
||||||
|
let passScore: Int
|
||||||
|
let scoring: String
|
||||||
|
let course: TrainingCourse
|
||||||
|
let questions: [TrainingQuestion]
|
||||||
|
var progress: TrainingProgress
|
||||||
|
|
||||||
|
/// 与小程序统一的前台阅读门槛。
|
||||||
|
static let requiredReadingSeconds = 20
|
||||||
|
/// 当前百分制计分规则版本。
|
||||||
|
static let equalPercentageScoring = "equal-percentage-v1"
|
||||||
|
|
||||||
|
/// 所有未完成状态均归入待考试。
|
||||||
|
var learnerStatus: TrainingLearnerStatus {
|
||||||
|
progress.completedAt != nil || progress.attempts.contains(where: \.passed) ? .completed : .pendingExam
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 读满时长且全部小节已经成功保存后才允许考试。
|
||||||
|
var hasFinishedReading: Bool {
|
||||||
|
progress.readingSeconds >= Self.requiredReadingSeconds
|
||||||
|
&& !course.sections.isEmpty
|
||||||
|
&& Set(course.sections.map(\.id)).isSubset(of: progress.completedSectionIDs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 显示真实发布人;缺失时不从课程创建人推测。
|
||||||
|
var publisherText: String {
|
||||||
|
guard let name = publisherName?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty else {
|
||||||
|
return "未记录"
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 时间窗口包含开始边界、不包含截止边界,完成后只可回顾。
|
||||||
|
func submissionBlockReason(now: Date) -> String? {
|
||||||
|
if learnerStatus == .completed { return "任务已完成,可回顾课程和考试记录" }
|
||||||
|
if status == .closed { return "任务已结束,可回顾课程和考试记录" }
|
||||||
|
if now < startAt { return "任务尚未开始" }
|
||||||
|
if now >= endAt { return "任务已截止,可回顾课程和考试记录" }
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 培训业务和存储失败;避免把保存失败显示为完成。
|
||||||
|
enum TrainingError: Error, LocalizedError, Equatable {
|
||||||
|
case unavailable, identityChanged, notFound, corruptStorage, saveFailed
|
||||||
|
case blocked(String), readingRequired, invalidPaper, invalidAnswers, unanswered(Int)
|
||||||
|
|
||||||
|
/// 直接用于页面提示的错误说明。
|
||||||
|
var errorDescription: String? {
|
||||||
|
switch self {
|
||||||
|
case .unavailable: "培训服务尚未接入,请等待景区开通"
|
||||||
|
case .identityChanged: "学习账号或景区已切换,请重新进入培训中心"
|
||||||
|
case .notFound: "任务不存在或未分配给当前账号"
|
||||||
|
case .corruptStorage: "本地演示数据异常,请联系管理员;原有记录未覆盖"
|
||||||
|
case .saveFailed: "保存失败,请重试;本次操作尚未完成"
|
||||||
|
case .blocked(let reason): reason
|
||||||
|
case .readingRequired: "请先完成课程阅读"
|
||||||
|
case .invalidPaper: "试卷或计分规则异常,请联系管理员"
|
||||||
|
case .invalidAnswers: "答案包含无效题目或选项,请重新进入考试"
|
||||||
|
case .unanswered(let count): "还有 \(count) 道题未作答"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 校验试卷和答案的纯逻辑;正式成绩由服务端核算。
|
||||||
|
enum TrainingValidation {
|
||||||
|
/// 校验百分制、唯一题目/选项及题型数量。
|
||||||
|
static func validatePaper(_ task: TrainingTask) throws {
|
||||||
|
guard task.scoring == TrainingTask.equalPercentageScoring,
|
||||||
|
(1...100).contains(task.passScore), !task.questions.isEmpty,
|
||||||
|
task.questions.count <= 500,
|
||||||
|
Set(task.questions.map(\.id)).count == task.questions.count else { throw TrainingError.invalidPaper }
|
||||||
|
for question in task.questions {
|
||||||
|
guard !question.id.isEmpty, !question.stem.isEmpty,
|
||||||
|
(2...6).contains(question.options.count),
|
||||||
|
question.options.allSatisfy({ !$0.id.isEmpty && !$0.text.isEmpty }),
|
||||||
|
Set(question.options.map(\.id)).count == question.options.count else { throw TrainingError.invalidPaper }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 校验所选 ID;完整交卷时返回漏答数量。
|
||||||
|
static func validateAnswers(_ answers: TrainingAnswers, task: TrainingTask, requireComplete: Bool) throws {
|
||||||
|
try validatePaper(task)
|
||||||
|
guard Set(answers.keys).isSubset(of: Set(task.questions.map(\.id))) else { throw TrainingError.invalidAnswers }
|
||||||
|
var missing = 0
|
||||||
|
for question in task.questions {
|
||||||
|
let selected = answers[question.id] ?? []
|
||||||
|
guard selected.isSubset(of: Set(question.options.map(\.id))),
|
||||||
|
question.type != .single || selected.count <= 1 else { throw TrainingError.invalidAnswers }
|
||||||
|
if selected.isEmpty { missing += 1 }
|
||||||
|
}
|
||||||
|
if requireComplete, missing > 0 { throw TrainingError.unanswered(missing) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 使用单调时间累计前台整秒,暂停后不补记后台或离开页面的时间。
|
||||||
|
struct TrainingReadingClock {
|
||||||
|
private var lastUptime: TimeInterval?
|
||||||
|
|
||||||
|
/// 页面内容可见且 App 活跃时开始一个新的计时片段。
|
||||||
|
mutating func resume(at uptime: TimeInterval) { lastUptime = uptime }
|
||||||
|
|
||||||
|
/// 失去前台可见性时丢弃未满一秒的片段。
|
||||||
|
mutating func pause() { lastUptime = nil }
|
||||||
|
|
||||||
|
/// 每次最多累计一秒,不补记 run loop 阻塞期间的大段时间。
|
||||||
|
mutating func takeSecond(at uptime: TimeInterval) -> Bool {
|
||||||
|
guard let lastUptime, uptime - lastUptime >= 1 else { return false }
|
||||||
|
self.lastUptime = uptime
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
#if DEBUG
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 可替换的演示存储,用于验证原子保存与存储失败。
|
||||||
|
protocol TrainingDemoStoring: Sendable {
|
||||||
|
/// 不存在时返回 nil;读取错误必须向调用者报告。
|
||||||
|
func read(key: String) throws -> Data?
|
||||||
|
/// 原子写入一个作用域的完整快照。
|
||||||
|
func write(_ data: Data, key: String) throws
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 使用原子文件保存本机演示,实际磁盘错误不会被忽略。
|
||||||
|
struct TrainingDemoFileStorage: TrainingDemoStoring {
|
||||||
|
let directory: URL
|
||||||
|
|
||||||
|
/// 默认存储在 App Application Support,不接触后台数据。
|
||||||
|
init(directory: URL = URL.applicationSupportDirectory.appendingPathComponent("TrainingDemo", isDirectory: true)) {
|
||||||
|
self.directory = directory
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 保留读取失败,避免把坏文件当作首次使用。
|
||||||
|
func read(key: String) throws -> Data? {
|
||||||
|
let url = fileURL(key: key)
|
||||||
|
guard FileManager.default.fileExists(atPath: url.path) else { return nil }
|
||||||
|
return try Data(contentsOf: url)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 写入失败时原子文件不会被替换成不完整内容。
|
||||||
|
func write(_ data: Data, key: String) throws {
|
||||||
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||||
|
try data.write(to: fileURL(key: key), options: .atomic)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func fileURL(key: String) -> URL {
|
||||||
|
let name = Data(key.utf8).map { String(format: "%02x", $0) }.joined()
|
||||||
|
return directory.appendingPathComponent(name).appendingPathExtension("json")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 仅开发演示使用的答案和解析,绝不进入正式试卷模型。
|
||||||
|
struct TrainingDemoSolution: Codable, Sendable {
|
||||||
|
let correctIDs: Set<String>
|
||||||
|
let explanation: String
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 冻结任务内容、开发判分材料和学员进度。
|
||||||
|
struct TrainingDemoPack: Codable, Sendable {
|
||||||
|
var task: TrainingTask
|
||||||
|
let solutions: [String: TrainingDemoSolution]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 带版本的开发记录;未知版本和损坏文件均保留原数据。
|
||||||
|
private struct TrainingDemoState: Codable {
|
||||||
|
let version: Int
|
||||||
|
var packs: [TrainingDemoPack]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开发演示数据源;actor 串行处理草稿、阅读和幂等交卷。
|
||||||
|
actor TrainingDemoService: TrainingServing {
|
||||||
|
/// 页面据此标记本机演示任务与成绩,区分正式数据源。
|
||||||
|
nonisolated let isDemo = true
|
||||||
|
private let context: TrainingContext
|
||||||
|
private let storage: any TrainingDemoStoring
|
||||||
|
private let now: @Sendable () -> Date
|
||||||
|
private let seed: @Sendable (Date) -> [TrainingDemoPack]
|
||||||
|
private let validateContext: @MainActor @Sendable () -> Bool
|
||||||
|
|
||||||
|
/// 注入时钟、存储与身份校验,便于真机测试全部边界。
|
||||||
|
init(
|
||||||
|
context: TrainingContext,
|
||||||
|
storage: any TrainingDemoStoring = TrainingDemoFileStorage(),
|
||||||
|
now: @escaping @Sendable () -> Date = { Date() },
|
||||||
|
seed: @escaping @Sendable (Date) -> [TrainingDemoPack] = TrainingDemoFixtures.makePacks,
|
||||||
|
validateContext: @escaping @MainActor @Sendable () -> Bool = { true }
|
||||||
|
) {
|
||||||
|
self.context = context
|
||||||
|
self.storage = storage
|
||||||
|
self.now = now
|
||||||
|
self.seed = seed
|
||||||
|
self.validateContext = validateContext
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 获取当前作用域全部本人演示任务。
|
||||||
|
func listTasks() async throws -> [TrainingTask] {
|
||||||
|
try await authorize()
|
||||||
|
return try load().packs.map(\.task)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 读取固定快照,后续示例代码更新不会覆盖已保存内容。
|
||||||
|
func task(id: String) async throws -> TrainingTask {
|
||||||
|
try await authorize()
|
||||||
|
let state = try load()
|
||||||
|
return state.packs[try index(id, in: state)].task
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 前台阅读每次增加一秒,写入成功后才向页面返回完成进度。
|
||||||
|
func recordReadingSecond(taskID: String) async throws -> TrainingTask {
|
||||||
|
try await authorize()
|
||||||
|
var state = try load()
|
||||||
|
let index = try index(taskID, in: state)
|
||||||
|
var task = state.packs[index].task
|
||||||
|
if task.learnerStatus == .completed || task.hasFinishedReading { return task }
|
||||||
|
try ensureOpen(task)
|
||||||
|
guard !task.course.sections.isEmpty,
|
||||||
|
Set(task.course.sections.map(\.id)).count == task.course.sections.count else { throw TrainingError.invalidPaper }
|
||||||
|
task.progress.readingSeconds = min(TrainingTask.requiredReadingSeconds, task.progress.readingSeconds + 1)
|
||||||
|
if task.progress.readingSeconds >= TrainingTask.requiredReadingSeconds {
|
||||||
|
task.progress.completedSectionIDs = Set(task.course.sections.map(\.id))
|
||||||
|
if task.mode == .study { task.progress.completedAt = now() }
|
||||||
|
}
|
||||||
|
state.packs[index].task = task
|
||||||
|
try save(state)
|
||||||
|
return task
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 答案校验和保存作为同一笔操作,失败不清空原有草稿。
|
||||||
|
func saveDraft(taskID: String, answers: TrainingAnswers) async throws {
|
||||||
|
try await authorize()
|
||||||
|
var state = try load()
|
||||||
|
let index = try index(taskID, in: state)
|
||||||
|
let task = state.packs[index].task
|
||||||
|
try ensureExamAllowed(task)
|
||||||
|
try TrainingValidation.validateAnswers(answers, task: task, requireComplete: false)
|
||||||
|
state.packs[index].task.progress.draftAnswers = answers
|
||||||
|
try save(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 演示百分制本地判分;同一幂等键和答案返回原记录,正式服务须改为服务端判分。
|
||||||
|
func submit(taskID: String, answers: TrainingAnswers, submissionID: String) async throws -> TrainingAttempt {
|
||||||
|
try await authorize()
|
||||||
|
var state = try load()
|
||||||
|
let index = try index(taskID, in: state)
|
||||||
|
let pack = state.packs[index]
|
||||||
|
guard !submissionID.isEmpty else { throw TrainingError.invalidAnswers }
|
||||||
|
if let attempt = pack.task.progress.attempts.first(where: { $0.id == submissionID }) {
|
||||||
|
let submitted = Dictionary(uniqueKeysWithValues: attempt.reviews.map { ($0.question.id, $0.selectedIDs) })
|
||||||
|
guard submitted == answers else { throw TrainingError.invalidAnswers }
|
||||||
|
return attempt
|
||||||
|
}
|
||||||
|
try ensureExamAllowed(pack.task)
|
||||||
|
try TrainingValidation.validateAnswers(answers, task: pack.task, requireComplete: true)
|
||||||
|
let reviews = try pack.task.questions.map { question in
|
||||||
|
guard let solution = pack.solutions[question.id],
|
||||||
|
!solution.correctIDs.isEmpty,
|
||||||
|
solution.correctIDs.isSubset(of: Set(question.options.map(\.id))),
|
||||||
|
question.type == .single ? solution.correctIDs.count == 1 : solution.correctIDs.count >= 2 else {
|
||||||
|
throw TrainingError.invalidPaper
|
||||||
|
}
|
||||||
|
return TrainingQuestionReview(question: question, selectedIDs: answers[question.id] ?? [],
|
||||||
|
correctIDs: solution.correctIDs, explanation: solution.explanation)
|
||||||
|
}
|
||||||
|
let correct = reviews.filter(\.isCorrect).count
|
||||||
|
let count = reviews.count
|
||||||
|
let attempt = TrainingAttempt(id: submissionID, submittedAt: now(), scoreHundredths: correct * 10_000 / count,
|
||||||
|
correctCount: correct, questionCount: count,
|
||||||
|
passed: correct * 100 >= pack.task.passScore * count, isDemo: true, reviews: reviews)
|
||||||
|
state.packs[index].task.progress.attempts.append(attempt)
|
||||||
|
state.packs[index].task.progress.draftAnswers = [:]
|
||||||
|
if attempt.passed { state.packs[index].task.progress.completedAt = attempt.submittedAt }
|
||||||
|
try save(state)
|
||||||
|
return attempt
|
||||||
|
}
|
||||||
|
|
||||||
|
private func authorize() async throws {
|
||||||
|
guard await validateContext() else { throw TrainingError.identityChanged }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func ensureOpen(_ task: TrainingTask) throws {
|
||||||
|
if let reason = task.submissionBlockReason(now: now()) { throw TrainingError.blocked(reason) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func ensureExamAllowed(_ task: TrainingTask) throws {
|
||||||
|
try ensureOpen(task)
|
||||||
|
guard task.mode == .exam else { throw TrainingError.invalidPaper }
|
||||||
|
guard task.hasFinishedReading else { throw TrainingError.readingRequired }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func index(_ id: String, in state: TrainingDemoState) throws -> Int {
|
||||||
|
guard let index = state.packs.firstIndex(where: { $0.task.id == id }) else { throw TrainingError.notFound }
|
||||||
|
return index
|
||||||
|
}
|
||||||
|
|
||||||
|
private func load() throws -> TrainingDemoState {
|
||||||
|
let data: Data?
|
||||||
|
do { data = try storage.read(key: context.storageKey) } catch { throw TrainingError.saveFailed }
|
||||||
|
guard let data else {
|
||||||
|
let initial = TrainingDemoState(version: 1, packs: seed(now()))
|
||||||
|
try save(initial)
|
||||||
|
return initial
|
||||||
|
}
|
||||||
|
guard let state = try? JSONDecoder().decode(TrainingDemoState.self, from: data), state.version == 1,
|
||||||
|
Set(state.packs.map { $0.task.id }).count == state.packs.count,
|
||||||
|
state.packs.allSatisfy({ !$0.task.id.isEmpty }) else { throw TrainingError.corruptStorage }
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
|
||||||
|
private func save(_ state: TrainingDemoState) throws {
|
||||||
|
do { try storage.write(JSONEncoder().encode(state), key: context.storageKey) }
|
||||||
|
catch { throw TrainingError.saveFailed }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 示例取材于小程序培训内容;不代表正式景区政策。
|
||||||
|
enum TrainingDemoFixtures {
|
||||||
|
/// 首次建立固定课程和试卷快照,不根据真实人员名单生成任务。
|
||||||
|
/// 任务有效期相对首次建立时间设置,后续读取保持已持久化快照。
|
||||||
|
static func makePacks(now: Date) -> [TrainingDemoPack] {
|
||||||
|
let sections = [
|
||||||
|
TrainingSection(id: "section-1", title: "接待礼仪与服务告知", contentHTML: """
|
||||||
|
<h2>让游客明白,再开始服务</h2><p>主动问候,介绍服务项目、费用、交付内容与时间。未经游客确认,不增加收费项目。</p>
|
||||||
|
<p>遇到相似套餐,要讲清包含和不包含的项目。如果游客没有听清,应换一种表达再次说明,不把沉默当作确认。</p>
|
||||||
|
<ul><li>主动、清晰地说明服务范围</li><li>尊重游客的知情与选择</li><li>保持耐心,不作无法兑现的承诺</li></ul>
|
||||||
|
"""),
|
||||||
|
TrainingSection(id: "section-2", title: "问题反馈与协同处理", contentHTML: """
|
||||||
|
<h2>先倾听,再记录,再处理</h2><p>遇到问题先完整听取诉求,客观记录事情经过。超出职责范围时,联系景区工作人员协同处理,并跟进反馈。</p>
|
||||||
|
<p>交接时说明已核实的信息、尚未解决的问题及后续负责人。预计无法按原时间反馈时,及时说明变化。</p>
|
||||||
|
<p><strong>演示提醒:</strong>实际处理要求以景区发布的正式制度为准。</p>
|
||||||
|
""")
|
||||||
|
]
|
||||||
|
let questions = [
|
||||||
|
TrainingQuestion(id: "q1", type: .single, stem: "开始服务前,应先完成哪项工作?", options: [
|
||||||
|
TrainingOption(id: "A", text: "说明项目、费用并取得游客确认"), TrainingOption(id: "B", text: "直接拍摄,结束后告知费用"),
|
||||||
|
TrainingOption(id: "C", text: "仅口头承诺,不介绍交付内容")]),
|
||||||
|
TrainingQuestion(id: "q2", type: .multiple, stem: "遇到超出职责范围的问题,以下做法正确的是?", options: [
|
||||||
|
TrainingOption(id: "A", text: "倾听并记录游客诉求"), TrainingOption(id: "B", text: "联系景区工作人员协同处理"),
|
||||||
|
TrainingOption(id: "C", text: "忽略问题,不再反馈")]),
|
||||||
|
TrainingQuestion(id: "q3", type: .single, stem: "无法确定交付时间时,应该怎样回应?", options: [
|
||||||
|
TrainingOption(id: "A", text: "随口给出一个时间"), TrainingOption(id: "B", text: "说明需要核实并约定反馈方式"),
|
||||||
|
TrainingOption(id: "C", text: "先保证今天完成")]),
|
||||||
|
TrainingQuestion(id: "q4", type: .multiple, stem: "交接服务时应明确哪些内容?", options: [
|
||||||
|
TrainingOption(id: "A", text: "尚未解决的问题"), TrainingOption(id: "B", text: "后续负责人"),
|
||||||
|
TrainingOption(id: "C", text: "已核实的信息"), TrainingOption(id: "D", text: "把未经核实的猜测作为事实")])
|
||||||
|
]
|
||||||
|
let solutions = [
|
||||||
|
"q1": TrainingDemoSolution(correctIDs: ["A"], explanation: "开始服务前应清晰告知项目、费用及交付约定,并取得游客确认。"),
|
||||||
|
"q2": TrainingDemoSolution(correctIDs: ["A", "B"], explanation: "先倾听记录,再协同处理,并跟进反馈。多选必须全部选对。"),
|
||||||
|
"q3": TrainingDemoSolution(correctIDs: ["B"], explanation: "不确定的信息应核实后反馈,不作无法兑现的承诺。"),
|
||||||
|
"q4": TrainingDemoSolution(correctIDs: ["A", "B", "C"], explanation: "交接应包含已核实信息、待办事项和后续负责人。")
|
||||||
|
]
|
||||||
|
let course = TrainingCourse(title: "景区服务规范与游客沟通", introduction: "从接待到反馈,统一一线服务标准。以下为开发演示材料。", sections: sections, attachments: [])
|
||||||
|
func make(id: String, title: String, mode: TrainingMode, passScore: Int) -> TrainingDemoPack {
|
||||||
|
let task = TrainingTask(id: id, title: title, publisherName: "演示管理员", mode: mode, status: .published,
|
||||||
|
startAt: now.addingTimeInterval(-86400), endAt: now.addingTimeInterval(7 * 86400),
|
||||||
|
passScore: passScore, scoring: TrainingTask.equalPercentageScoring, course: course,
|
||||||
|
questions: mode == .exam ? questions : [], progress: TrainingProgress())
|
||||||
|
return TrainingDemoPack(task: task, solutions: mode == .exam ? solutions : [:])
|
||||||
|
}
|
||||||
|
return [make(id: "demo-service", title: "一线服务规范学习(演示)", mode: .exam, passScore: 100),
|
||||||
|
make(id: "demo-review", title: "游客沟通巩固练习(演示)", mode: .exam, passScore: 75),
|
||||||
|
make(id: "demo-study", title: "接待礼仪课程学习(演示)", mode: .study, passScore: 100)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 培训数据源接口。正式实现应使用登录态授权,不接受任意学员 ID。
|
||||||
|
protocol TrainingServing: Sendable {
|
||||||
|
/// 是否为本机开发演示。
|
||||||
|
var isDemo: Bool { get }
|
||||||
|
/// 获取本人任务列表。
|
||||||
|
func listTasks() async throws -> [TrainingTask]
|
||||||
|
/// 获取本人任务、发布快照与进度。
|
||||||
|
func task(id: String) async throws -> TrainingTask
|
||||||
|
/// 累计一秒有效前台阅读,服务端实现需核验学习会话。
|
||||||
|
func recordReadingSecond(taskID: String) async throws -> TrainingTask
|
||||||
|
/// 保存本人当前试卷草稿。
|
||||||
|
func saveDraft(taskID: String, answers: TrainingAnswers) async throws
|
||||||
|
/// 按幂等键提交试卷,返回服务端成绩和考后解析。
|
||||||
|
func submit(taskID: String, answers: TrainingAnswers, submissionID: String) async throws -> TrainingAttempt
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 尚未联调的正式数据源,不生成假任务或假成绩。
|
||||||
|
struct UnconnectedTrainingService: TrainingServing {
|
||||||
|
/// 占位正式服务不会生成本地演示内容。
|
||||||
|
let isDemo = false
|
||||||
|
/// 无正式接口时拒绝生成任务。
|
||||||
|
func listTasks() async throws -> [TrainingTask] { throw TrainingError.unavailable }
|
||||||
|
/// 无正式接口时拒绝生成课程或进度。
|
||||||
|
func task(id: String) async throws -> TrainingTask { throw TrainingError.unavailable }
|
||||||
|
/// 无正式接口时禁止记录真实学习完成。
|
||||||
|
func recordReadingSecond(taskID: String) async throws -> TrainingTask { throw TrainingError.unavailable }
|
||||||
|
/// 无正式接口时禁止保存正式草稿。
|
||||||
|
func saveDraft(taskID: String, answers: TrainingAnswers) async throws { throw TrainingError.unavailable }
|
||||||
|
/// 无正式接口时禁止返回正式成绩。
|
||||||
|
func submit(taskID: String, answers: TrainingAnswers, submissionID: String) async throws -> TrainingAttempt {
|
||||||
|
throw TrainingError.unavailable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 按登录账号、景区和店铺隔离本地开发记录;不表示自然人认证。
|
||||||
|
struct TrainingContext: Equatable, Sendable {
|
||||||
|
let accountScope: String
|
||||||
|
let scenicID: Int
|
||||||
|
let storeID: Int
|
||||||
|
|
||||||
|
/// 缺少有效登录身份时禁止初始化演示记录。
|
||||||
|
@MainActor static func current() -> TrainingContext? {
|
||||||
|
let session = AppStore.shared.session
|
||||||
|
guard session.isLoggedIn, !session.accountCachePrefix.isEmpty, session.currentScenicId > 0 else { return nil }
|
||||||
|
return TrainingContext(accountScope: session.accountCachePrefix, scenicID: session.currentScenicId, storeID: session.currentStoreId)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 使用不含凭证的账号与业务上下文作为持久化作用域。
|
||||||
|
var storageKey: String { "training-demo:v1:\(accountScope):scenic_\(scenicID):store_\(storeID)" }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开发环境显式提供示例入口,Release 始终使用待接入服务。
|
||||||
|
enum TrainingServiceFactory {
|
||||||
|
/// 正式入口默认处于待接入状态,避免演示替代真实任务。
|
||||||
|
static func production() -> any TrainingServing { UnconnectedTrainingService() }
|
||||||
|
|
||||||
|
#if DEBUG
|
||||||
|
/// 只在开发版本中创建隔离的本机演示数据源。
|
||||||
|
@MainActor static func demo() throws -> any TrainingServing {
|
||||||
|
guard let context = TrainingContext.current() else { throw TrainingError.identityChanged }
|
||||||
|
return TrainingDemoService(context: context, validateContext: {
|
||||||
|
TrainingContext.current() == context
|
||||||
|
})
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 培训中心与小程序一致的三个入口。
|
||||||
|
enum TrainingCenterTab: Int, CaseIterable {
|
||||||
|
case home, tasks, records
|
||||||
|
|
||||||
|
/// 培训中心底部入口的展示名称。
|
||||||
|
var title: String { switch self { case .home: "首页"; case .tasks: "任务"; case .records: "记录" } }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 培训中心任务与历史记录状态,页面在加载完成后主动刷新。
|
||||||
|
final class TrainingCenterViewModel {
|
||||||
|
/// 最近成功加载的本人任务,加载失败时清空。
|
||||||
|
private(set) var tasks: [TrainingTask] = []
|
||||||
|
/// 正在加载任务时阻止重复请求。
|
||||||
|
private(set) var isLoading = false
|
||||||
|
/// 最近一次加载失败的页面提示。
|
||||||
|
private(set) var errorMessage: String?
|
||||||
|
/// 任务列表当前选择的学员完成状态。
|
||||||
|
var filter: TrainingLearnerStatus = .pendingExam
|
||||||
|
/// 当前培训中心入口,决定页面展示的数据范围。
|
||||||
|
var tab: TrainingCenterTab = .home
|
||||||
|
/// 按任务或课程名称筛选任务的搜索词。
|
||||||
|
var keyword = ""
|
||||||
|
/// 记录页当前展示的记录数量上限,由页面增加以加载更多。
|
||||||
|
var recordLimit = 20
|
||||||
|
|
||||||
|
/// 本人全部任务中已完成的数量,不受搜索与筛选影响。
|
||||||
|
var completedCount: Int { tasks.filter { $0.learnerStatus == .completed }.count }
|
||||||
|
/// 本人全部任务中尚未完成的数量。
|
||||||
|
var pendingCount: Int { tasks.count - completedCount }
|
||||||
|
/// 合并各任务的考试记录,按提交时间从新到旧排列。
|
||||||
|
var records: [(task: TrainingTask, attempt: TrainingAttempt)] {
|
||||||
|
tasks.flatMap { task in task.progress.attempts.map { (task: task, attempt: $0) } }
|
||||||
|
.sorted { $0.attempt.submittedAt > $1.attempt.submittedAt }
|
||||||
|
}
|
||||||
|
/// 最近一次考试的得分,无考试记录时显示占位符。
|
||||||
|
var latestScore: String { records.first?.attempt.scoreText ?? "—" }
|
||||||
|
|
||||||
|
/// 当前筛选的任务列表。
|
||||||
|
var filteredTasks: [TrainingTask] {
|
||||||
|
let query = keyword.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
return tasks.filter { $0.learnerStatus == filter && (query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) || $0.course.title.localizedCaseInsensitiveContains(query)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 首页展示前三项必读任务,任务页提供完整筛选与搜索。
|
||||||
|
var visibleTasks: [TrainingTask] {
|
||||||
|
tab == .home ? Array(tasks.filter { $0.learnerStatus == .pendingExam }.prefix(3)) : filteredTasks
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 切换入口时清除搜索,保留用户选择的任务状态。
|
||||||
|
func selectTab(_ tab: TrainingCenterTab) { self.tab = tab; keyword = "" }
|
||||||
|
|
||||||
|
/// 加载失败时清除旧任务,防止切换身份后展示旧账号内容。
|
||||||
|
func load(service: any TrainingServing) async {
|
||||||
|
guard !isLoading else { return }
|
||||||
|
isLoading = true
|
||||||
|
errorMessage = nil
|
||||||
|
defer { isLoading = false }
|
||||||
|
do { tasks = try await service.listTasks() }
|
||||||
|
catch { tasks = []; errorMessage = error.localizedDescription }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 连续课程阅读状态;计时只由前台可见页面驱动。
|
||||||
|
final class TrainingReadingViewModel {
|
||||||
|
/// 当前阅读页面对应的本人任务标识。
|
||||||
|
let taskID: String
|
||||||
|
/// 最近一次成功读取或保存的课程与学习进度。
|
||||||
|
private(set) var task: TrainingTask?
|
||||||
|
/// 加载课程或保存阅读秒数时阻止重复操作。
|
||||||
|
private(set) var isBusy = false
|
||||||
|
/// 最近一次加载或保存失败的页面提示。
|
||||||
|
private(set) var errorMessage: String?
|
||||||
|
|
||||||
|
/// 指定当前本人任务。
|
||||||
|
init(taskID: String) { self.taskID = taskID }
|
||||||
|
|
||||||
|
/// 剩余有效阅读秒数。
|
||||||
|
var remainingSeconds: Int { max(0, TrainingTask.requiredReadingSeconds - (task?.progress.readingSeconds ?? 0)) }
|
||||||
|
|
||||||
|
/// 读取最新进度,不重置已经完成的课程。
|
||||||
|
func load(service: any TrainingServing) async {
|
||||||
|
guard !isBusy else { return }
|
||||||
|
isBusy = true
|
||||||
|
errorMessage = nil
|
||||||
|
defer { isBusy = false }
|
||||||
|
do { task = try await service.task(id: taskID) }
|
||||||
|
catch { task = nil; errorMessage = error.localizedDescription }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 每次只记一秒;失败保留上一次成功进度,并停止页面计时。
|
||||||
|
func recordSecond(service: any TrainingServing) async {
|
||||||
|
guard !isBusy, let task, !task.hasFinishedReading, task.learnerStatus != .completed else { return }
|
||||||
|
isBusy = true
|
||||||
|
defer { isBusy = false }
|
||||||
|
do {
|
||||||
|
self.task = try await service.recordReadingSecond(taskID: taskID)
|
||||||
|
errorMessage = nil
|
||||||
|
} catch { errorMessage = error.localizedDescription }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 逐题答题、答题卡、自动草稿保存与幂等交卷状态。
|
||||||
|
final class TrainingExamViewModel {
|
||||||
|
/// 当前考试页面对应的本人任务标识。
|
||||||
|
let taskID: String
|
||||||
|
/// 已通过时间、阅读门槛和试卷校验的考试任务。
|
||||||
|
private(set) var task: TrainingTask?
|
||||||
|
/// 已成功保存的草稿选择,保存失败时保留原值。
|
||||||
|
private(set) var answers: TrainingAnswers = [:]
|
||||||
|
/// 当前展示题目在试卷中的索引。
|
||||||
|
private(set) var currentIndex = 0
|
||||||
|
/// 加载、保存草稿或交卷期间阻止重复操作和题目跳转。
|
||||||
|
private(set) var isBusy = false
|
||||||
|
/// 最近一次加载、保存或交卷失败的页面提示。
|
||||||
|
private(set) var errorMessage: String?
|
||||||
|
private var submissionID: String?
|
||||||
|
|
||||||
|
/// 指定任务,默认恢复草稿;重考从空白试卷开始。
|
||||||
|
init(taskID: String) { self.taskID = taskID }
|
||||||
|
|
||||||
|
/// 当前题目,无效试卷时为空。
|
||||||
|
var currentQuestion: TrainingQuestion? {
|
||||||
|
guard let task, task.questions.indices.contains(currentIndex) else { return nil }
|
||||||
|
return task.questions[currentIndex]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 第一处漏答位置,用于交卷时定位。
|
||||||
|
var firstUnansweredIndex: Int? {
|
||||||
|
task?.questions.firstIndex { (answers[$0.id] ?? []).isEmpty }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前作答数量。
|
||||||
|
var answeredCount: Int { task?.questions.filter { !(answers[$0.id] ?? []).isEmpty }.count ?? 0 }
|
||||||
|
|
||||||
|
/// 进入考试时重新验证任务时间与学习完成状态。
|
||||||
|
func load(service: any TrainingServing, now: Date = Date(), resetDraft: Bool = false) async {
|
||||||
|
guard !isBusy else { return }
|
||||||
|
isBusy = true
|
||||||
|
errorMessage = nil
|
||||||
|
defer { isBusy = false }
|
||||||
|
do {
|
||||||
|
let loaded = try await service.task(id: taskID)
|
||||||
|
if let reason = loaded.submissionBlockReason(now: now) { throw TrainingError.blocked(reason) }
|
||||||
|
guard loaded.mode == .exam else { throw TrainingError.invalidPaper }
|
||||||
|
guard loaded.hasFinishedReading else { throw TrainingError.readingRequired }
|
||||||
|
let draft = resetDraft ? [:] : loaded.progress.draftAnswers
|
||||||
|
try TrainingValidation.validateAnswers(draft, task: loaded, requireComplete: false)
|
||||||
|
if resetDraft { try await service.saveDraft(taskID: taskID, answers: [:]) }
|
||||||
|
task = loaded
|
||||||
|
answers = draft
|
||||||
|
currentIndex = min(currentIndex, loaded.questions.count - 1)
|
||||||
|
} catch { task = nil; errorMessage = error.localizedDescription }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 选择有效选项,保存成功后再更新页面,失败允许重试。
|
||||||
|
func select(optionID: String, service: any TrainingServing) async {
|
||||||
|
guard !isBusy, let question = currentQuestion,
|
||||||
|
question.options.contains(where: { $0.id == optionID }) else { return }
|
||||||
|
var changed = answers
|
||||||
|
var selected = changed[question.id] ?? []
|
||||||
|
if question.type == .single { selected = [optionID] }
|
||||||
|
else if selected.contains(optionID) { selected.remove(optionID) }
|
||||||
|
else { selected.insert(optionID) }
|
||||||
|
changed[question.id] = selected
|
||||||
|
isBusy = true
|
||||||
|
defer { isBusy = false }
|
||||||
|
do {
|
||||||
|
try await service.saveDraft(taskID: taskID, answers: changed)
|
||||||
|
answers = changed
|
||||||
|
submissionID = nil
|
||||||
|
errorMessage = nil
|
||||||
|
} catch { errorMessage = error.localizedDescription }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 上一题、下一题和答题卡使用同一个安全跳转方法。
|
||||||
|
func goToQuestion(_ index: Int) {
|
||||||
|
guard !isBusy, let task, task.questions.indices.contains(index) else { return }
|
||||||
|
currentIndex = index
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 交卷失败重试沿用同一 submissionID,避免新增重复考试记录。
|
||||||
|
func submit(service: any TrainingServing) async -> TrainingAttempt? {
|
||||||
|
guard !isBusy, let task else { return nil }
|
||||||
|
if let missing = firstUnansweredIndex {
|
||||||
|
currentIndex = missing
|
||||||
|
errorMessage = TrainingError.unanswered(task.questions.count - answeredCount).localizedDescription
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
isBusy = true
|
||||||
|
errorMessage = nil
|
||||||
|
defer { isBusy = false }
|
||||||
|
let id = submissionID ?? UUID().uuidString
|
||||||
|
submissionID = id
|
||||||
|
do { return try await service.submit(taskID: taskID, answers: answers, submissionID: id) }
|
||||||
|
catch { errorMessage = error.localizedDescription; return nil }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -30,6 +30,7 @@ final class ProfileViewController: BaseViewController {
|
|||||||
private let realNameRow = ProfileInfoRowView(title: "认证状态")
|
private let realNameRow = ProfileInfoRowView(title: "认证状态")
|
||||||
private let statusRow = ProfileInfoRowView(title: "账号状态")
|
private let statusRow = ProfileInfoRowView(title: "账号状态")
|
||||||
private let scenicRow = ProfileInfoRowView(title: "当前景区")
|
private let scenicRow = ProfileInfoRowView(title: "当前景区")
|
||||||
|
private let trainingRow = ProfileInfoRowView(title: "培训中心")
|
||||||
private let settingRow = ProfileInfoRowView(title: "设置中心")
|
private let settingRow = ProfileInfoRowView(title: "设置中心")
|
||||||
private let logoutButton = UIButton(type: .system)
|
private let logoutButton = UIButton(type: .system)
|
||||||
private var hasLoadedProfileOnce = false
|
private var hasLoadedProfileOnce = false
|
||||||
@@ -92,6 +93,7 @@ final class ProfileViewController: BaseViewController {
|
|||||||
withdrawalRow.addTarget(self, action: #selector(withdrawalTapped), for: .touchUpInside)
|
withdrawalRow.addTarget(self, action: #selector(withdrawalTapped), for: .touchUpInside)
|
||||||
realNameRow.addTarget(self, action: #selector(realNameTapped), for: .touchUpInside)
|
realNameRow.addTarget(self, action: #selector(realNameTapped), for: .touchUpInside)
|
||||||
settingRow.addTarget(self, action: #selector(settingTapped), for: .touchUpInside)
|
settingRow.addTarget(self, action: #selector(settingTapped), for: .touchUpInside)
|
||||||
|
trainingRow.addTarget(self, action: #selector(trainingTapped), for: .touchUpInside)
|
||||||
|
|
||||||
NotificationCenter.default.addObserver(
|
NotificationCenter.default.addObserver(
|
||||||
self,
|
self,
|
||||||
@@ -183,7 +185,7 @@ final class ProfileViewController: BaseViewController {
|
|||||||
[
|
[
|
||||||
nameRow, accountRow, phoneRow, withdrawalRow,
|
nameRow, accountRow, phoneRow, withdrawalRow,
|
||||||
passwordRow, realNameRow, statusRow, scenicRow,
|
passwordRow, realNameRow, statusRow, scenicRow,
|
||||||
settingRow
|
trainingRow, settingRow
|
||||||
].forEach { infoCard.addArrangedSubview($0) }
|
].forEach { infoCard.addArrangedSubview($0) }
|
||||||
|
|
||||||
nameRow.isUserInteractionEnabled = false
|
nameRow.isUserInteractionEnabled = false
|
||||||
@@ -202,6 +204,7 @@ final class ProfileViewController: BaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func applyViewModel() {
|
private func applyViewModel() {
|
||||||
|
trainingRow.configure(value: "学习课程与答题", accessory: .chevron)
|
||||||
nicknameField.text = viewModel.displayNickname
|
nicknameField.text = viewModel.displayNickname
|
||||||
uidLabel.text = "UID:\(viewModel.displayUID)"
|
uidLabel.text = "UID:\(viewModel.displayUID)"
|
||||||
avatarImageView.loadRemoteImage(urlString: viewModel.displayAvatarURL)
|
avatarImageView.loadRemoteImage(urlString: viewModel.displayAvatarURL)
|
||||||
@@ -353,6 +356,10 @@ final class ProfileViewController: BaseViewController {
|
|||||||
navigationController?.pushViewController(SettingViewController(), animated: true)
|
navigationController?.pushViewController(SettingViewController(), animated: true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@objc private func trainingTapped() {
|
||||||
|
HomeRouteHandler.open(uri: "/training", from: self, storeItem: nil)
|
||||||
|
}
|
||||||
|
|
||||||
@objc private func logoutTapped() {
|
@objc private func logoutTapped() {
|
||||||
let alert = UIAlertController(title: "确定退出登录?", message: "退出后将需要重新登录", preferredStyle: .alert)
|
let alert = UIAlertController(title: "确定退出登录?", message: "退出后将需要重新登录", preferredStyle: .alert)
|
||||||
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
|
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
|
||||||
|
|||||||
@@ -0,0 +1,304 @@
|
|||||||
|
import SnapKit
|
||||||
|
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 let tableView = UITableView(frame: .zero, style: .plain)
|
||||||
|
private let refreshControl = UIRefreshControl()
|
||||||
|
private let header = UIStackView()
|
||||||
|
private let hero = UIStackView()
|
||||||
|
private let greetingLabel = TrainingUI.text(size: 14, color: .white)
|
||||||
|
private let titleLabel = TrainingUI.text("我的培训中心", size: 18, weight: .bold, color: .white)
|
||||||
|
private var statLabels: [UILabel] = []
|
||||||
|
private let headingLabel = TrainingUI.text(size: 15.5, weight: .semibold)
|
||||||
|
private let viewAllButton = TrainingUI.button("查看全部", plain: true)
|
||||||
|
private let filters = UIStackView()
|
||||||
|
private var filterButtons: [UIButton] = []
|
||||||
|
private let searchField = UITextField()
|
||||||
|
private let tabBar = UIStackView()
|
||||||
|
private let tabBackground = UIView()
|
||||||
|
private var tabButtons: [UIButton] = []
|
||||||
|
private let footer = UIStackView()
|
||||||
|
private let stateLabel = TrainingUI.text(size: 14, color: TrainingUI.muted)
|
||||||
|
private let retryButton = TrainingUI.button("重新加载", secondary: true)
|
||||||
|
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
|
||||||
|
viewModel.tab = showsHistory ? .records : .home
|
||||||
|
super.init(nibName: nil, bundle: nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
|
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() {
|
||||||
|
view.backgroundColor = TrainingUI.background
|
||||||
|
header.axis = .vertical
|
||||||
|
header.spacing = 0
|
||||||
|
hero.axis = .vertical
|
||||||
|
hero.spacing = 8
|
||||||
|
hero.backgroundColor = UIColor(red: 45/255, green: 128/255, blue: 250/255, alpha: 1)
|
||||||
|
hero.layer.cornerRadius = 14
|
||||||
|
hero.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
|
||||||
|
hero.isLayoutMarginsRelativeArrangement = true
|
||||||
|
hero.layoutMargins = UIEdgeInsets(top: 19, left: 17, bottom: 18, right: 17)
|
||||||
|
hero.addArrangedSubview(greetingLabel)
|
||||||
|
hero.addArrangedSubview(titleLabel)
|
||||||
|
let stats = UIStackView()
|
||||||
|
stats.distribution = .fillEqually
|
||||||
|
stats.alignment = .fill
|
||||||
|
for caption in ["待考试", "已完成", "最近得分"] {
|
||||||
|
let value = TrainingUI.text("—", size: 23, weight: .bold, color: .white)
|
||||||
|
value.textAlignment = .center
|
||||||
|
statLabels.append(value)
|
||||||
|
let name = TrainingUI.text(caption, size: 12.5, color: .white)
|
||||||
|
name.textAlignment = .center
|
||||||
|
let column = UIStackView(arrangedSubviews: [value, name])
|
||||||
|
column.axis = .vertical
|
||||||
|
column.spacing = 6
|
||||||
|
stats.addArrangedSubview(column)
|
||||||
|
if statLabels.count > 1 {
|
||||||
|
let line = UIView()
|
||||||
|
line.backgroundColor = UIColor.white.withAlphaComponent(0.4)
|
||||||
|
column.addSubview(line)
|
||||||
|
line.snp.makeConstraints { $0.leading.top.bottom.equalToSuperview(); $0.width.equalTo(1) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hero.setCustomSpacing(18, after: titleLabel)
|
||||||
|
hero.addArrangedSubview(stats)
|
||||||
|
header.addArrangedSubview(hero)
|
||||||
|
let body = UIStackView()
|
||||||
|
body.axis = .vertical
|
||||||
|
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
|
||||||
|
headingLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
|
||||||
|
viewAllButton.setContentHuggingPriority(.required, for: .horizontal)
|
||||||
|
body.addArrangedSubview(heading)
|
||||||
|
filters.distribution = .fillEqually
|
||||||
|
filters.spacing = 9
|
||||||
|
for state in TrainingLearnerStatus.allCases {
|
||||||
|
let button = TrainingUI.button(state.title, secondary: true)
|
||||||
|
button.tag = state == .pendingExam ? 0 : 1
|
||||||
|
button.accessibilityIdentifier = "training.filter.\(button.tag)"
|
||||||
|
button.addTarget(self, action: #selector(filterTapped(_:)), for: .touchUpInside)
|
||||||
|
filterButtons.append(button)
|
||||||
|
filters.addArrangedSubview(button)
|
||||||
|
}
|
||||||
|
body.addArrangedSubview(filters)
|
||||||
|
searchField.font = .systemFont(ofSize: 13)
|
||||||
|
searchField.backgroundColor = .white
|
||||||
|
searchField.layer.cornerRadius = 8
|
||||||
|
searchField.placeholder = "搜索任务或课程名称"
|
||||||
|
searchField.clearButtonMode = .whileEditing
|
||||||
|
searchField.returnKeyType = .search
|
||||||
|
searchField.accessibilityIdentifier = "training.search"
|
||||||
|
searchField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: 1))
|
||||||
|
searchField.leftViewMode = .always
|
||||||
|
searchField.snp.makeConstraints { $0.height.equalTo(44) }
|
||||||
|
body.addArrangedSubview(searchField)
|
||||||
|
header.addArrangedSubview(body)
|
||||||
|
tableView.backgroundColor = .clear
|
||||||
|
tableView.separatorStyle = .none
|
||||||
|
tableView.rowHeight = UITableView.automaticDimension
|
||||||
|
tableView.estimatedRowHeight = 250
|
||||||
|
tableView.delegate = self
|
||||||
|
tableView.keyboardDismissMode = .onDrag
|
||||||
|
tableView.refreshControl = refreshControl
|
||||||
|
tableView.register(TrainingTaskCell.self, forCellReuseIdentifier: TrainingTaskCell.reuseIdentifier)
|
||||||
|
tableView.register(TrainingRecordCell.self, forCellReuseIdentifier: TrainingRecordCell.reuseIdentifier)
|
||||||
|
tableView.tableHeaderView = header
|
||||||
|
footer.axis = .vertical
|
||||||
|
footer.spacing = 12
|
||||||
|
footer.isLayoutMarginsRelativeArrangement = true
|
||||||
|
footer.layoutMargins = UIEdgeInsets(top: 24, left: 26, bottom: 24, right: 26)
|
||||||
|
stateLabel.textAlignment = .center
|
||||||
|
[stateLabel, retryButton, moreButton].forEach(footer.addArrangedSubview)
|
||||||
|
tableView.tableFooterView = footer
|
||||||
|
tabBackground.backgroundColor = .white
|
||||||
|
let line = UIView()
|
||||||
|
line.backgroundColor = TrainingUI.border
|
||||||
|
tabBackground.addSubview(line)
|
||||||
|
line.snp.makeConstraints { $0.top.leading.trailing.equalToSuperview(); $0.height.equalTo(1) }
|
||||||
|
tabBar.distribution = .fillEqually
|
||||||
|
for tab in TrainingCenterTab.allCases {
|
||||||
|
let button = TrainingUI.button(tab.title, plain: true)
|
||||||
|
button.tag = tab.rawValue
|
||||||
|
button.accessibilityIdentifier = "training.tab.\(tab.rawValue)"
|
||||||
|
button.addTarget(self, action: #selector(tabTapped(_:)), for: .touchUpInside)
|
||||||
|
tabButtons.append(button)
|
||||||
|
tabBar.addArrangedSubview(button)
|
||||||
|
}
|
||||||
|
view.addSubview(tableView)
|
||||||
|
view.addSubview(tabBackground)
|
||||||
|
tabBackground.addSubview(tabBar)
|
||||||
|
configureDataSource()
|
||||||
|
applyState()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func setupConstraints() {
|
||||||
|
tabBackground.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() }
|
||||||
|
tabBar.snp.makeConstraints {
|
||||||
|
$0.leading.trailing.equalToSuperview().inset(12)
|
||||||
|
$0.top.equalToSuperview().offset(7)
|
||||||
|
$0.bottom.equalTo(view.safeAreaLayoutGuide).offset(-7)
|
||||||
|
}
|
||||||
|
tableView.snp.makeConstraints {
|
||||||
|
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
|
||||||
|
$0.bottom.equalTo(tabBackground.snp.top)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override func viewDidLayoutSubviews() {
|
||||||
|
super.viewDidLayoutSubviews()
|
||||||
|
sizeTableSupplementaryViews()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func sizeTableSupplementaryViews() {
|
||||||
|
let width = tableView.bounds.width
|
||||||
|
guard width > 0 else { return }
|
||||||
|
for stack in [header, footer] {
|
||||||
|
let height = stack.systemLayoutSizeFitting(CGSize(width: width, height: 0), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel).height
|
||||||
|
if abs(stack.frame.height - height) > 0.5 || stack.frame.width != width {
|
||||||
|
stack.frame = CGRect(x: 0, y: 0, width: width, height: height)
|
||||||
|
if stack === header { tableView.tableHeaderView = header } else { tableView.tableFooterView = footer }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override func bindActions() {
|
||||||
|
refreshControl.addTarget(self, action: #selector(reloadTapped), for: .valueChanged)
|
||||||
|
retryButton.addTarget(self, action: #selector(reloadTapped), for: .touchUpInside)
|
||||||
|
viewAllButton.addTarget(self, action: #selector(viewAllTapped), for: .touchUpInside)
|
||||||
|
searchField.addTarget(self, action: #selector(searchChanged), for: .editingChanged)
|
||||||
|
moreButton.addTarget(self, action: #selector(moreTapped), for: .touchUpInside)
|
||||||
|
}
|
||||||
|
|
||||||
|
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); reloadTapped() }
|
||||||
|
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
|
||||||
|
|
||||||
|
private func configureDataSource() {
|
||||||
|
dataSource = UITableViewDiffableDataSource<Int, Item>(tableView: tableView) { [weak self] table, indexPath, item in
|
||||||
|
guard let self else { return nil }
|
||||||
|
switch item {
|
||||||
|
case .task(let id):
|
||||||
|
guard let task = self.viewModel.tasks.first(where: { $0.id == id }), let cell = table.dequeueReusableCell(withIdentifier: TrainingTaskCell.reuseIdentifier, for: indexPath) as? TrainingTaskCell else { return nil }
|
||||||
|
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)
|
||||||
|
return cell
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func applyState(completion: (() -> Void)? = nil) {
|
||||||
|
let session = AppStore.shared.session
|
||||||
|
let name = [session.realName, session.userName].first { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } ?? "当前学员"
|
||||||
|
greetingLabel.text = "你好,\(name)"
|
||||||
|
let context = session.currentScenicName.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
titleLabel.text = context.isEmpty ? "我的培训中心" : "\(context) · 培训中心"
|
||||||
|
for (label, value) in zip(statLabels, [String(viewModel.pendingCount), String(viewModel.completedCount), viewModel.latestScore]) { label.text = value }
|
||||||
|
headingLabel.text = switch viewModel.tab { case .home: "新政策与必读内容"; case .tasks: "我的学习任务"; case .records: "考试记录" }
|
||||||
|
viewAllButton.isHidden = viewModel.tab != .home
|
||||||
|
filters.isHidden = viewModel.tab != .tasks
|
||||||
|
searchField.isHidden = viewModel.tab != .tasks
|
||||||
|
for (index, button) in filterButtons.enumerated() {
|
||||||
|
var configuration = button.configuration
|
||||||
|
configuration?.title = index == 0 ? "待考试 \(viewModel.pendingCount)" : "已完成 \(viewModel.completedCount)"
|
||||||
|
configuration?.background.backgroundColor = index == (viewModel.filter == .pendingExam ? 0 : 1) ? TrainingUI.primary.withAlphaComponent(0.09) : .white
|
||||||
|
configuration?.baseForegroundColor = index == (viewModel.filter == .pendingExam ? 0 : 1) ? TrainingUI.primary : TrainingUI.muted
|
||||||
|
button.configuration = configuration
|
||||||
|
}
|
||||||
|
for (index, button) in tabButtons.enumerated() {
|
||||||
|
var configuration = button.configuration
|
||||||
|
configuration?.baseForegroundColor = index == viewModel.tab.rawValue ? TrainingUI.primary : TrainingUI.muted
|
||||||
|
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) }
|
||||||
|
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
|
||||||
|
snapshot.appendSections([0])
|
||||||
|
snapshot.appendItems(items)
|
||||||
|
snapshot.reconfigureItems(items.filter { dataSource.snapshot().indexOfItem($0) != nil })
|
||||||
|
dataSource.apply(snapshot, animatingDifferences: true, completion: completion)
|
||||||
|
stateLabel.text = viewModel.errorMessage ?? (viewModel.isLoading ? "正在加载培训任务…" : viewModel.tab == .records ? "暂无考试记录\n交卷后可在此查看成绩和解析" : "暂无符合条件的任务\n景区分配给当前账号的任务会显示在这里")
|
||||||
|
stateLabel.isHidden = !items.isEmpty
|
||||||
|
retryButton.isHidden = viewModel.errorMessage == nil
|
||||||
|
retryButton.isEnabled = !viewModel.isLoading
|
||||||
|
moreButton.isHidden = viewModel.tab != .records || viewModel.records.count <= viewModel.recordLimit
|
||||||
|
if !viewModel.isLoading { refreshControl.endRefreshing() }
|
||||||
|
sizeTableSupplementaryViews()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 页面出现和下拉刷新都读取最新本人任务。
|
||||||
|
func reload() async {
|
||||||
|
await viewModel.load(service: service)
|
||||||
|
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||||||
|
applyState { continuation.resume() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 在同一页面切换入口,返回课程时保留筛选上下文。
|
||||||
|
func selectTab(_ tab: TrainingCenterTab) {
|
||||||
|
view.endEditing(true)
|
||||||
|
viewModel.selectTab(tab)
|
||||||
|
searchField.text = ""
|
||||||
|
applyState()
|
||||||
|
tableView.setContentOffset(.zero, animated: false)
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func reloadTapped() {
|
||||||
|
guard !viewModel.isLoading else { return }
|
||||||
|
Task { @MainActor in await 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 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)
|
||||||
|
navigationController?.pushViewController(controller, animated: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension TrainingCenterViewController: UITableViewDelegate {
|
||||||
|
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
|
||||||
|
tableView.deselectRow(at: indexPath, animated: true)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
import SafariServices
|
||||||
|
import SnapKit
|
||||||
|
import UIKit
|
||||||
|
import WebKit
|
||||||
|
|
||||||
|
/// 全部图文小节连续阅读,唯一底部按钮展示 20 秒倒计时。
|
||||||
|
@MainActor
|
||||||
|
final class TrainingCourseViewController: TrainingBaseViewController {
|
||||||
|
private let service: any TrainingServing
|
||||||
|
private let viewModel: TrainingReadingViewModel
|
||||||
|
private let webView: WKWebView
|
||||||
|
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 contentIsReady = false
|
||||||
|
private var contentLoadFailed = false
|
||||||
|
private var pageIsVisible = false
|
||||||
|
private var readingClock = TrainingReadingClock()
|
||||||
|
|
||||||
|
/// 开启当前任务的连续阅读页面,禁用课程 HTML 中的 JavaScript。
|
||||||
|
init(taskID: String, service: any TrainingServing) {
|
||||||
|
self.service = service
|
||||||
|
viewModel = TrainingReadingViewModel(taskID: taskID)
|
||||||
|
let configuration = WKWebViewConfiguration()
|
||||||
|
configuration.defaultWebpagePreferences.allowsContentJavaScript = false
|
||||||
|
webView = WKWebView(frame: .zero, configuration: configuration)
|
||||||
|
super.init(nibName: nil, bundle: nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
|
override func setupNavigationBar() { TrainingUI.navigation(self, title: "课程学习") }
|
||||||
|
|
||||||
|
override func setupUI() {
|
||||||
|
webView.navigationDelegate = self
|
||||||
|
view.backgroundColor = TrainingUI.background
|
||||||
|
webView.backgroundColor = TrainingUI.background
|
||||||
|
webView.isOpaque = false
|
||||||
|
bottomStack.axis = .vertical
|
||||||
|
bottomStack.spacing = 8
|
||||||
|
bottomStack.layoutMargins = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12)
|
||||||
|
bottomStack.isLayoutMarginsRelativeArrangement = true
|
||||||
|
bottomStack.backgroundColor = AppColor.cardBackground
|
||||||
|
bottomStack.addArrangedSubview(noticeLabel)
|
||||||
|
bottomStack.addArrangedSubview(actionButton)
|
||||||
|
actionButton.accessibilityIdentifier = "training.reading.action"
|
||||||
|
view.addSubview(webView)
|
||||||
|
view.addSubview(bottomStack)
|
||||||
|
}
|
||||||
|
|
||||||
|
override func setupConstraints() {
|
||||||
|
webView.snp.makeConstraints {
|
||||||
|
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
|
||||||
|
$0.bottom.equalTo(bottomStack.snp.top)
|
||||||
|
}
|
||||||
|
bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
override func viewDidAppear(_ animated: Bool) {
|
||||||
|
super.viewDidAppear(animated)
|
||||||
|
pageIsVisible = true
|
||||||
|
loadCourse()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func viewWillDisappear(_ animated: Bool) {
|
||||||
|
super.viewWillDisappear(animated)
|
||||||
|
pageIsVisible = false
|
||||||
|
pauseReading()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func onSessionDidExpire() {
|
||||||
|
pauseReading()
|
||||||
|
navigationController?.popToRootViewController(animated: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
applyState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func escape(_ text: String) -> String {
|
||||||
|
text.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<")
|
||||||
|
.replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func applyState() {
|
||||||
|
if let error = viewModel.errorMessage ?? (contentLoadFailed ? "课程加载失败,请重试" : nil) {
|
||||||
|
pauseReading()
|
||||||
|
noticeLabel.text = error
|
||||||
|
setActionTitle("重新加载")
|
||||||
|
actionButton.isEnabled = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
guard let task = viewModel.task else { return }
|
||||||
|
if let reason = task.submissionBlockReason(now: Date()) {
|
||||||
|
pauseReading()
|
||||||
|
noticeLabel.text = reason
|
||||||
|
setActionTitle("返回培训中心")
|
||||||
|
actionButton.isEnabled = true
|
||||||
|
} else if task.hasFinishedReading {
|
||||||
|
pauseReading()
|
||||||
|
noticeLabel.text = "课程阅读已完成"
|
||||||
|
setActionTitle(task.mode == .exam ? "开始考试" : "完成学习")
|
||||||
|
actionButton.isEnabled = true
|
||||||
|
} else {
|
||||||
|
noticeLabel.text = "请阅读课程内容,倒计时结束后" + (task.mode == .exam ? "即可考试" : "完成学习")
|
||||||
|
setActionTitle("\(task.mode == .exam ? "开始考试" : "完成学习")(\(viewModel.remainingSeconds)s)")
|
||||||
|
actionButton.isEnabled = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
|
@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)
|
||||||
|
let timer = Timer(timeInterval: 0.25, repeats: true) { [weak self] _ in
|
||||||
|
Task { @MainActor in await self?.recordSecond() }
|
||||||
|
}
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
|
@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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension TrainingCourseViewController: WKNavigationDelegate {
|
||||||
|
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
||||||
|
contentIsReady = true
|
||||||
|
contentLoadFailed = false
|
||||||
|
applyState()
|
||||||
|
resumeReading()
|
||||||
|
}
|
||||||
|
|
||||||
|
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
|
||||||
|
contentIsReady = false
|
||||||
|
contentLoadFailed = true
|
||||||
|
pauseReading()
|
||||||
|
applyState()
|
||||||
|
}
|
||||||
|
|
||||||
|
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
|
||||||
|
contentIsReady = false
|
||||||
|
contentLoadFailed = true
|
||||||
|
pauseReading()
|
||||||
|
applyState()
|
||||||
|
}
|
||||||
|
|
||||||
|
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
|
||||||
|
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
|
||||||
|
if navigationAction.navigationType == .other, navigationAction.request.url?.absoluteString == "about:blank" {
|
||||||
|
decisionHandler(.allow)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
decisionHandler(.cancel)
|
||||||
|
guard navigationAction.navigationType == .linkActivated,
|
||||||
|
let url = navigationAction.request.url, url.scheme?.lowercased() == "https", url.host != nil else { return }
|
||||||
|
pauseReading()
|
||||||
|
let controller = SFSafariViewController(url: url)
|
||||||
|
controller.delegate = self
|
||||||
|
present(controller, animated: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension TrainingCourseViewController: SFSafariViewControllerDelegate {
|
||||||
|
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
|
||||||
|
controller.dismiss(animated: true) { [weak self] in self?.resumeReading() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
import SnapKit
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
/// 原生单选/多选答题页,支持逐题跳转、草稿恢复与确认交卷。
|
||||||
|
@MainActor
|
||||||
|
final class TrainingExamViewController: TrainingBaseViewController {
|
||||||
|
private let service: any TrainingServing
|
||||||
|
private let viewModel: TrainingExamViewModel
|
||||||
|
private let resetDraft: Bool
|
||||||
|
private let scrollView = UIScrollView()
|
||||||
|
private let contentStack = TrainingUI.card()
|
||||||
|
private let positionLabel = TrainingUI.label(style: .subheadline, color: AppColor.primary)
|
||||||
|
private let questionLabel = TrainingUI.label(style: .title3)
|
||||||
|
private let hintLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
|
||||||
|
private let optionStack = UIStackView()
|
||||||
|
private let navigationStack = UIStackView()
|
||||||
|
private let previousButton = AppButton(title: "上一题", style: .secondary)
|
||||||
|
private let nextButton = AppButton(title: "下一题", style: .secondary)
|
||||||
|
private let bottomStack = UIStackView()
|
||||||
|
private let statusLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
|
||||||
|
private let submitButton = AppButton(title: "交卷")
|
||||||
|
|
||||||
|
/// 重考时清除旧草稿,普通进入时恢复本人已保存的答案。
|
||||||
|
init(taskID: String, service: any TrainingServing, resetDraft: Bool = false) {
|
||||||
|
self.service = service
|
||||||
|
viewModel = TrainingExamViewModel(taskID: taskID)
|
||||||
|
self.resetDraft = resetDraft
|
||||||
|
super.init(nibName: nil, bundle: nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
|
override func setupNavigationBar() {
|
||||||
|
title = "培训答题"
|
||||||
|
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "答题卡", style: .plain, target: self, action: #selector(answerCardTapped))
|
||||||
|
}
|
||||||
|
|
||||||
|
override func setupUI() {
|
||||||
|
scrollView.alwaysBounceVertical = true
|
||||||
|
optionStack.axis = .vertical
|
||||||
|
optionStack.spacing = 12
|
||||||
|
navigationStack.axis = .horizontal
|
||||||
|
navigationStack.spacing = 12
|
||||||
|
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
|
||||||
|
bottomStack.backgroundColor = AppColor.cardBackground
|
||||||
|
bottomStack.layoutMargins = UIEdgeInsets(top: 12, left: 20, bottom: 12, right: 20)
|
||||||
|
bottomStack.isLayoutMarginsRelativeArrangement = true
|
||||||
|
bottomStack.addArrangedSubview(statusLabel)
|
||||||
|
bottomStack.addArrangedSubview(submitButton)
|
||||||
|
submitButton.accessibilityIdentifier = "training.exam.submit"
|
||||||
|
scrollView.addSubview(contentStack)
|
||||||
|
view.addSubview(scrollView)
|
||||||
|
view.addSubview(bottomStack)
|
||||||
|
applyState()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func setupConstraints() {
|
||||||
|
scrollView.snp.makeConstraints {
|
||||||
|
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
|
||||||
|
$0.bottom.equalTo(bottomStack.snp.top)
|
||||||
|
}
|
||||||
|
contentStack.snp.makeConstraints {
|
||||||
|
$0.edges.equalTo(scrollView.contentLayoutGuide).inset(16)
|
||||||
|
$0.width.equalTo(scrollView.frameLayoutGuide).offset(-32)
|
||||||
|
}
|
||||||
|
bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override func bindActions() {
|
||||||
|
previousButton.addTarget(self, action: #selector(previousTapped), for: .touchUpInside)
|
||||||
|
nextButton.addTarget(self, action: #selector(nextTapped), for: .touchUpInside)
|
||||||
|
submitButton.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
|
||||||
|
}
|
||||||
|
|
||||||
|
override func viewDidLoad() {
|
||||||
|
super.viewDidLoad()
|
||||||
|
loadExam()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
|
||||||
|
|
||||||
|
private func loadExam() {
|
||||||
|
submitButton.isEnabled = false
|
||||||
|
Task { @MainActor in
|
||||||
|
await viewModel.load(service: service, resetDraft: resetDraft)
|
||||||
|
applyState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func applyState() {
|
||||||
|
for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() }
|
||||||
|
guard let task = viewModel.task, let question = viewModel.currentQuestion else {
|
||||||
|
positionLabel.text = ""
|
||||||
|
questionLabel.text = viewModel.errorMessage ?? "正在加载试卷…"
|
||||||
|
hintLabel.text = ""
|
||||||
|
navigationStack.isHidden = true
|
||||||
|
submitButton.setTitle("重新加载", for: .normal)
|
||||||
|
submitButton.isEnabled = viewModel.errorMessage != 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 ? "单选题" : "多选题")"
|
||||||
|
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 button = UIButton(type: .system)
|
||||||
|
var configuration = UIButton.Configuration.filled()
|
||||||
|
configuration.title = "\(TrainingQuestion.optionLetter(index)).\(option.text)"
|
||||||
|
configuration.baseBackgroundColor = selected ? AppColor.primaryLight : AppColor.pageBackgroundSoft
|
||||||
|
configuration.baseForegroundColor = selected ? AppColor.primary : AppColor.textPrimary
|
||||||
|
configuration.contentInsets = NSDirectionalEdgeInsets(top: 18, leading: 16, bottom: 18, trailing: 16)
|
||||||
|
configuration.image = UIImage(systemName: selected ? "checkmark.circle.fill" : "circle")
|
||||||
|
configuration.imagePadding = 12
|
||||||
|
configuration.titleAlignment = .leading
|
||||||
|
configuration.cornerStyle = .medium
|
||||||
|
button.configuration = configuration
|
||||||
|
button.contentHorizontalAlignment = .leading
|
||||||
|
button.titleLabel?.numberOfLines = 0
|
||||||
|
button.titleLabel?.lineBreakMode = .byWordWrapping
|
||||||
|
button.isEnabled = !viewModel.isBusy
|
||||||
|
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) · 答案已保存,可稍后继续"
|
||||||
|
statusLabel.textColor = viewModel.errorMessage == nil ? AppColor.textSecondary : AppColor.danger
|
||||||
|
submitButton.setTitle(viewModel.isBusy ? "正在保存…" : "交卷", for: .normal)
|
||||||
|
submitButton.isEnabled = !viewModel.isBusy
|
||||||
|
}
|
||||||
|
|
||||||
|
private func selectOption(_ id: String) {
|
||||||
|
Task { @MainActor in
|
||||||
|
let operation = Task { await viewModel.select(optionID: id, service: service) }
|
||||||
|
await Task.yield()
|
||||||
|
applyState()
|
||||||
|
await operation.value
|
||||||
|
applyState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func goToQuestion(_ index: Int) {
|
||||||
|
viewModel.goToQuestion(index)
|
||||||
|
applyState()
|
||||||
|
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)
|
||||||
|
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 }
|
||||||
|
present(navigation, animated: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
@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) 道题未作答,已定位到第一道")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let alert = UIAlertController(title: "确认交卷?", message: "已完成 \(task.questions.count) 道题,提交后将生成本次考试记录。", 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() {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 可滚动的网格答题卡,支持最多 500 道题。
|
||||||
|
@MainActor
|
||||||
|
final class TrainingAnswerCardViewController: UIViewController {
|
||||||
|
private let task: TrainingTask
|
||||||
|
private let answers: TrainingAnswers
|
||||||
|
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
|
||||||
|
self.currentIndex = currentIndex
|
||||||
|
collectionView = UICollectionView(frame: .zero, collectionViewLayout: Self.makeLayout())
|
||||||
|
super.init(nibName: nil, bundle: nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 保持原有五列、52 点行高与 12 点间距,随可用宽度自动计算列宽。
|
||||||
|
private static func makeLayout() -> UICollectionViewCompositionalLayout {
|
||||||
|
UICollectionViewCompositionalLayout { _, environment in
|
||||||
|
let columns = 5
|
||||||
|
let spacing: CGFloat = 12
|
||||||
|
let inset: CGFloat = 20
|
||||||
|
let availableWidth = environment.container.effectiveContentSize.width - inset * 2
|
||||||
|
let itemWidth = max(0, floor((availableWidth - spacing * CGFloat(columns - 1)) / CGFloat(columns)))
|
||||||
|
let itemSize = NSCollectionLayoutSize(widthDimension: .absolute(itemWidth), heightDimension: .absolute(52))
|
||||||
|
let item = NSCollectionLayoutItem(layoutSize: itemSize)
|
||||||
|
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(52))
|
||||||
|
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, repeatingSubitem: item, count: columns)
|
||||||
|
group.interItemSpacing = .fixed(spacing)
|
||||||
|
let section = NSCollectionLayoutSection(group: group)
|
||||||
|
section.interGroupSpacing = spacing
|
||||||
|
section.contentInsets = NSDirectionalEdgeInsets(top: inset, leading: inset, bottom: inset, trailing: inset)
|
||||||
|
return section
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
|
override func viewDidLoad() {
|
||||||
|
super.viewDidLoad()
|
||||||
|
title = "答题卡 · 蓝色为已答"
|
||||||
|
navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak self] _ in self?.dismiss(animated: true) })
|
||||||
|
collectionView.backgroundColor = AppColor.pageBackgroundSoft
|
||||||
|
collectionView.delegate = self
|
||||||
|
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "question")
|
||||||
|
view.addSubview(collectionView)
|
||||||
|
collectionView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
|
||||||
|
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
|
||||||
|
var content = UIListContentConfiguration.cell()
|
||||||
|
content.text = "\(index + 1)"
|
||||||
|
content.textProperties.alignment = .center
|
||||||
|
content.textProperties.color = answered ? AppColor.primary : AppColor.textSecondary
|
||||||
|
content.directionalLayoutMargins = .zero
|
||||||
|
cell.contentConfiguration = content
|
||||||
|
cell.backgroundColor = answered ? AppColor.primaryLight : AppColor.cardBackground
|
||||||
|
cell.layer.cornerRadius = 10
|
||||||
|
cell.layer.borderWidth = index == self.currentIndex ? 2 : 0
|
||||||
|
cell.layer.borderColor = AppColor.primary.cgColor
|
||||||
|
cell.isAccessibilityElement = true
|
||||||
|
cell.accessibilityLabel = "第 \(index + 1) 题,\(answered ? "已答" : "未答")\(index == self.currentIndex ? ",当前题" : "")"
|
||||||
|
cell.accessibilityTraits = .button
|
||||||
|
return cell
|
||||||
|
}
|
||||||
|
var snapshot = NSDiffableDataSourceSnapshot<Int, Int>()
|
||||||
|
snapshot.appendSections([0])
|
||||||
|
snapshot.appendItems(Array(task.questions.indices))
|
||||||
|
dataSource.apply(snapshot, animatingDifferences: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension TrainingAnswerCardViewController: UICollectionViewDelegate {
|
||||||
|
/// 选中题号后关闭答题卡并通知考试页面跳转。
|
||||||
|
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||||
|
guard let index = dataSource.itemIdentifier(for: indexPath) else { return }
|
||||||
|
let selection = onSelect
|
||||||
|
dismiss(animated: true) { selection?(index) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
import SnapKit
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
/// 成绩概览、可展开解析和返回学习入口,历史记录只按最新任务状态提供重考。
|
||||||
|
@MainActor
|
||||||
|
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 var loadFailed = false
|
||||||
|
private var showsDetails = false
|
||||||
|
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) {
|
||||||
|
self.taskID = taskID
|
||||||
|
self.attemptID = attemptID
|
||||||
|
self.service = service
|
||||||
|
super.init(nibName: nil, bundle: nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
|
override func setupNavigationBar() { TrainingUI.navigation(self, title: "考试结果") }
|
||||||
|
|
||||||
|
override func setupUI() {
|
||||||
|
view.backgroundColor = TrainingUI.background
|
||||||
|
contentStack.axis = .vertical
|
||||||
|
contentStack.spacing = 12
|
||||||
|
scrollView.addSubview(contentStack)
|
||||||
|
view.addSubview(scrollView)
|
||||||
|
footer.backgroundColor = .white
|
||||||
|
let line = UIView()
|
||||||
|
line.backgroundColor = TrainingUI.border
|
||||||
|
footer.addSubview(line)
|
||||||
|
line.snp.makeConstraints { $0.leading.trailing.top.equalToSuperview(); $0.height.equalTo(1) }
|
||||||
|
footer.addSubview(actionButton)
|
||||||
|
view.addSubview(footer)
|
||||||
|
actionButton.accessibilityIdentifier = "training.result.action"
|
||||||
|
}
|
||||||
|
|
||||||
|
override func setupConstraints() {
|
||||||
|
footer.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() }
|
||||||
|
actionButton.snp.makeConstraints {
|
||||||
|
$0.leading.trailing.equalToSuperview().inset(12)
|
||||||
|
$0.top.equalToSuperview().offset(10)
|
||||||
|
$0.bottom.equalTo(view.safeAreaLayoutGuide).offset(-10)
|
||||||
|
}
|
||||||
|
scrollView.snp.makeConstraints { $0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide); $0.bottom.equalTo(footer.snp.top) }
|
||||||
|
contentStack.snp.makeConstraints {
|
||||||
|
$0.edges.equalTo(scrollView.contentLayoutGuide).inset(UIEdgeInsets(top: 14, left: 13, bottom: 20, right: 13))
|
||||||
|
$0.width.equalTo(scrollView.frameLayoutGuide).offset(-26)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override func bindActions() { actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside) }
|
||||||
|
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); loadResult() }
|
||||||
|
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
|
||||||
|
|
||||||
|
private func loadResult() { Task { @MainActor in await reload() } }
|
||||||
|
|
||||||
|
/// 页面出现时重新读取记录,失败可重试,不展示上个任务成绩。
|
||||||
|
func reload() 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
|
||||||
|
loadFailed = false
|
||||||
|
render(task: task, attempt: attempt)
|
||||||
|
} catch {
|
||||||
|
loadedTask = nil
|
||||||
|
loadedAttempt = nil
|
||||||
|
loadFailed = true
|
||||||
|
clearContent()
|
||||||
|
contentStack.addArrangedSubview(TrainingUI.text(error.localizedDescription, color: TrainingUI.muted))
|
||||||
|
setActionTitle("重新加载")
|
||||||
|
}
|
||||||
|
actionButton.isEnabled = true
|
||||||
|
}
|
||||||
|
|
||||||
|
private func clearContent() {
|
||||||
|
for child in contentStack.arrangedSubviews { contentStack.removeArrangedSubview(child); child.removeFromSuperview() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func setActionTitle(_ title: String) { var configuration = actionButton.configuration; configuration?.title = title; actionButton.configuration = configuration }
|
||||||
|
|
||||||
|
private func render(task: TrainingTask, attempt: TrainingAttempt) {
|
||||||
|
clearContent()
|
||||||
|
if attempt.isDemo { contentStack.addArrangedSubview(TrainingUI.demoNotice()) }
|
||||||
|
let summary = UIStackView()
|
||||||
|
summary.axis = .vertical
|
||||||
|
summary.spacing = 11
|
||||||
|
summary.alignment = .center
|
||||||
|
summary.backgroundColor = .white
|
||||||
|
summary.layer.cornerRadius = 11
|
||||||
|
summary.layer.borderWidth = 1
|
||||||
|
summary.layer.borderColor = TrainingUI.border.cgColor
|
||||||
|
summary.isLayoutMarginsRelativeArrangement = true
|
||||||
|
summary.layoutMargins = UIEdgeInsets(top: 25, left: 12, bottom: 25, right: 12)
|
||||||
|
let symbol = UIImageView(image: UIImage(systemName: attempt.passed ? "checkmark.circle.fill" : "info.circle.fill"))
|
||||||
|
symbol.tintColor = attempt.passed ? TrainingUI.success : UIColor(red: 237/255, green: 140/255, blue: 36/255, alpha: 1)
|
||||||
|
symbol.contentMode = .scaleAspectFit
|
||||||
|
symbol.snp.makeConstraints { $0.size.equalTo(54) }
|
||||||
|
summary.addArrangedSubview(symbol)
|
||||||
|
let title = TrainingUI.text(attempt.passed ? "考试通过,学习任务已完成" : "本次未通过,再接再厉", size: 16.5, weight: .bold)
|
||||||
|
title.textAlignment = .center
|
||||||
|
summary.addArrangedSubview(title)
|
||||||
|
let score = UIStackView(arrangedSubviews: [TrainingUI.text(attempt.scoreText, size: 46, weight: .bold, color: TrainingUI.primary), TrainingUI.text("/ 100 分", size: 13, color: TrainingUI.muted)])
|
||||||
|
score.alignment = .firstBaseline
|
||||||
|
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)
|
||||||
|
contentStack.addArrangedSubview(summary)
|
||||||
|
let counts = TrainingUI.card()
|
||||||
|
let row = UIStackView(arrangedSubviews: [TrainingUI.text("答对 \(attempt.correctCount) 题"), TrainingUI.text("答错 \(attempt.questionCount - attempt.correctCount) 题")])
|
||||||
|
row.distribution = .fillEqually
|
||||||
|
for label in row.arrangedSubviews.compactMap({ $0 as? UILabel }) { label.textAlignment = .center }
|
||||||
|
counts.addArrangedSubview(row)
|
||||||
|
contentStack.addArrangedSubview(counts)
|
||||||
|
let details = TrainingUI.button(showsDetails ? "收起答案解析" : "查看答案解析", secondary: true)
|
||||||
|
details.accessibilityIdentifier = "training.result.details"
|
||||||
|
details.addTarget(self, action: #selector(toggleDetails), for: .touchUpInside)
|
||||||
|
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() {
|
||||||
|
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)])
|
||||||
|
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("\(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 }
|
||||||
|
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.notice(review.explanation.isEmpty ? "暂无解析" : review.explanation))
|
||||||
|
contentStack.addArrangedSubview(card)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let canRetry = !attempt.passed && task.submissionBlockReason(now: Date()) == nil
|
||||||
|
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 }
|
||||||
|
showsDetails.toggle()
|
||||||
|
render(task: task, attempt: attempt)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 无论是否通过都能返回本次课程,优先复用导航栈中的课程页面。
|
||||||
|
@objc private func returnToLearning() {
|
||||||
|
guard loadedTask != nil, let navigationController else { return }
|
||||||
|
if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) {
|
||||||
|
navigationController.popToViewController(course, animated: true)
|
||||||
|
} else {
|
||||||
|
navigationController.pushViewController(TrainingCourseViewController(taskID: taskID, service: service), animated: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func actionTapped() {
|
||||||
|
if loadFailed { loadResult(); return }
|
||||||
|
guard let task = loadedTask, let attempt = loadedAttempt, let navigationController else { return }
|
||||||
|
if !attempt.passed, task.submissionBlockReason(now: Date()) == nil {
|
||||||
|
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)
|
||||||
|
} else { navigationController.setViewControllers([TrainingCenterViewController(service: service)], animated: true) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
import SnapKit
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
/// 与小程序培训页面一致的色彩、字体和内容间距。
|
||||||
|
@MainActor
|
||||||
|
enum TrainingUI {
|
||||||
|
static let primary = UIColor(red: 35/255, green: 121/255, blue: 1, alpha: 1)
|
||||||
|
static let background = UIColor(red: 245/255, green: 248/255, blue: 252/255, alpha: 1)
|
||||||
|
static let textColor = UIColor(red: 23/255, green: 32/255, blue: 51/255, alpha: 1)
|
||||||
|
static let muted = UIColor(red: 132/255, green: 145/255, blue: 166/255, alpha: 1)
|
||||||
|
static let border = UIColor(red: 227/255, green: 235/255, blue: 245/255, alpha: 1)
|
||||||
|
static let hintColor = UIColor(red: 189/255, green: 121/255, blue: 24/255, alpha: 1)
|
||||||
|
static let hintBackground = UIColor(red: 1, green: 246/255, blue: 233/255, alpha: 1)
|
||||||
|
static let success = UIColor(red: 21/255, green: 151/255, blue: 108/255, alpha: 1)
|
||||||
|
|
||||||
|
/// 创建支持系统字体缩放的标签。
|
||||||
|
static func text(_ value: String = "", size: CGFloat = 14, weight: UIFont.Weight = .regular, color: UIColor = textColor) -> UILabel {
|
||||||
|
let label = UILabel()
|
||||||
|
label.text = value
|
||||||
|
label.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: .systemFont(ofSize: size, weight: weight))
|
||||||
|
label.adjustsFontForContentSizeCategory = true
|
||||||
|
label.textColor = color
|
||||||
|
label.numberOfLines = 0
|
||||||
|
return label
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 为答题等现有页面保留语义字体入口。
|
||||||
|
static func label(_ text: String = "", style: UIFont.TextStyle = .body, color: UIColor = textColor) -> UILabel {
|
||||||
|
let label = self.text(text, color: color)
|
||||||
|
label.font = .preferredFont(forTextStyle: style)
|
||||||
|
return label
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 白色内容卡片使用细边框和统一内边距。
|
||||||
|
static func card() -> UIStackView {
|
||||||
|
let stack = UIStackView()
|
||||||
|
stack.axis = .vertical
|
||||||
|
stack.spacing = 10
|
||||||
|
stack.backgroundColor = .white
|
||||||
|
stack.layer.cornerRadius = 11
|
||||||
|
stack.layer.borderWidth = 1
|
||||||
|
stack.layer.borderColor = border.cgColor
|
||||||
|
stack.layoutMargins = UIEdgeInsets(top: 14, left: 14, bottom: 14, right: 14)
|
||||||
|
stack.isLayoutMarginsRelativeArrangement = true
|
||||||
|
return stack
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 提示内容在浅橙背景中展示。
|
||||||
|
static func notice(_ value: String, demo: Bool = false) -> UIStackView {
|
||||||
|
let box = UIStackView(arrangedSubviews: [text(value, size: demo ? 11 : 12, color: hintColor)])
|
||||||
|
box.axis = .vertical
|
||||||
|
box.backgroundColor = hintBackground
|
||||||
|
box.layer.cornerRadius = 6
|
||||||
|
box.isLayoutMarginsRelativeArrangement = true
|
||||||
|
box.layoutMargins = UIEdgeInsets(top: 9, left: 10, bottom: 9, right: 10)
|
||||||
|
return box
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 明确标识本机演示边界。
|
||||||
|
static func demoNotice() -> UIStackView {
|
||||||
|
notice("开发演示 · 记录仅保存在本机,未同步景区后台", demo: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 使用本地时区展示任务截止和考试时间。
|
||||||
|
static func date(_ date: Date) -> String {
|
||||||
|
let formatter = DateFormatter()
|
||||||
|
formatter.locale = Locale(identifier: "zh_CN")
|
||||||
|
formatter.dateFormat = "MM-dd HH:mm"
|
||||||
|
return formatter.string(from: date)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 培训专用按钮,文字缩放时高度随内容增加。
|
||||||
|
static func button(_ title: String, secondary: Bool = false, plain: Bool = false, pill: Bool = false) -> UIButton {
|
||||||
|
let button = UIButton(type: .system)
|
||||||
|
var configuration = UIButton.Configuration.plain()
|
||||||
|
configuration.title = title
|
||||||
|
configuration.baseForegroundColor = plain || secondary ? primary : .white
|
||||||
|
configuration.background.backgroundColor = plain ? .clear : secondary ? primary.withAlphaComponent(0.08) : primary
|
||||||
|
configuration.background.cornerRadius = pill ? 24 : 11
|
||||||
|
configuration.contentInsets = NSDirectionalEdgeInsets(top: plain ? 10 : 12, leading: 14, bottom: plain ? 10 : 12, trailing: 14)
|
||||||
|
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
|
||||||
|
var output = incoming
|
||||||
|
output.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: .systemFont(ofSize: 14, weight: plain ? .regular : .semibold))
|
||||||
|
return output
|
||||||
|
}
|
||||||
|
button.configuration = configuration
|
||||||
|
if !plain, !secondary {
|
||||||
|
button.configurationUpdateHandler = { button in
|
||||||
|
var updated = button.configuration
|
||||||
|
updated?.background.backgroundColor = button.isEnabled ? primary : border
|
||||||
|
updated?.baseForegroundColor = button.isEnabled ? .white : muted
|
||||||
|
button.configuration = updated
|
||||||
|
}
|
||||||
|
}
|
||||||
|
button.titleLabel?.adjustsFontForContentSizeCategory = true
|
||||||
|
button.snp.makeConstraints { $0.height.greaterThanOrEqualTo(44) }
|
||||||
|
return button
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 导航栏保持普通白色背景,入口使用文本与箭头。
|
||||||
|
static func navigation(_ controller: UIViewController, title: String) {
|
||||||
|
controller.title = title
|
||||||
|
let appearance = UINavigationBarAppearance()
|
||||||
|
appearance.configureWithOpaqueBackground()
|
||||||
|
appearance.backgroundColor = .white
|
||||||
|
appearance.shadowColor = .clear
|
||||||
|
appearance.titleTextAttributes = [.font: UIFont.systemFont(ofSize: 17, weight: .medium), .foregroundColor: textColor]
|
||||||
|
controller.navigationItem.standardAppearance = appearance
|
||||||
|
controller.navigationItem.scrollEdgeAppearance = appearance
|
||||||
|
controller.navigationItem.compactAppearance = appearance
|
||||||
|
controller.navigationItem.backButtonDisplayMode = .minimal
|
||||||
|
let back = UIButton(type: .system)
|
||||||
|
back.tintColor = textColor
|
||||||
|
back.setImage(UIImage(systemName: "chevron.left", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .medium)), for: .normal)
|
||||||
|
back.accessibilityLabel = "返回"
|
||||||
|
back.snp.makeConstraints { $0.size.equalTo(44) }
|
||||||
|
back.addAction(UIAction { [weak controller] _ in controller?.navigationController?.popViewController(animated: true) }, for: .touchUpInside)
|
||||||
|
let item = UIBarButtonItem(customView: back)
|
||||||
|
if #available(iOS 26.0, *) { item.hidesSharedBackground = true }
|
||||||
|
controller.navigationItem.leftBarButtonItem = item
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 任务卡显示截止、课程小节、提示、进度条和对应的操作入口。
|
||||||
|
@MainActor
|
||||||
|
final class TrainingTaskCell: UITableViewCell {
|
||||||
|
static let reuseIdentifier = "TrainingTaskCell"
|
||||||
|
private let stack = TrainingUI.card()
|
||||||
|
private let deadlineLabel = TrainingUI.text(size: 11.5, color: .systemRed)
|
||||||
|
private let statusLabel = TrainingUI.text(size: 11, color: TrainingUI.primary)
|
||||||
|
private let titleLabel = TrainingUI.text(size: 15.5, weight: .semibold)
|
||||||
|
private let publisherLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
|
||||||
|
private let metaLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
|
||||||
|
private let hintLabel = TrainingUI.text(size: 12, color: TrainingUI.hintColor)
|
||||||
|
private let progressView = UIProgressView(progressViewStyle: .bar)
|
||||||
|
private let progressLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
|
||||||
|
private let actionButton = TrainingUI.button("去学习", pill: true)
|
||||||
|
private let footer = UIStackView()
|
||||||
|
var onAction: (() -> Void)?
|
||||||
|
|
||||||
|
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
|
||||||
|
super.init(style: style, reuseIdentifier: reuseIdentifier)
|
||||||
|
backgroundColor = .clear
|
||||||
|
selectionStyle = .none
|
||||||
|
contentView.addSubview(stack)
|
||||||
|
let deadline = UIStackView(arrangedSubviews: [deadlineLabel])
|
||||||
|
deadline.backgroundColor = UIColor.systemRed.withAlphaComponent(0.06)
|
||||||
|
deadline.layer.cornerRadius = 12
|
||||||
|
deadline.isLayoutMarginsRelativeArrangement = true
|
||||||
|
deadline.layoutMargins = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8)
|
||||||
|
let top = UIStackView(arrangedSubviews: [deadline, UIView(), statusLabel])
|
||||||
|
top.alignment = .center
|
||||||
|
top.spacing = 8
|
||||||
|
statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||||
|
let hint = UIStackView(arrangedSubviews: [hintLabel])
|
||||||
|
hint.backgroundColor = TrainingUI.hintBackground
|
||||||
|
hint.layer.cornerRadius = 6
|
||||||
|
hint.isLayoutMarginsRelativeArrangement = true
|
||||||
|
hint.layoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
|
||||||
|
progressView.progressTintColor = TrainingUI.primary
|
||||||
|
progressView.trackTintColor = TrainingUI.border
|
||||||
|
progressView.layer.cornerRadius = 3
|
||||||
|
progressView.clipsToBounds = true
|
||||||
|
progressView.snp.makeConstraints { $0.height.equalTo(6) }
|
||||||
|
footer.spacing = 12
|
||||||
|
footer.alignment = .center
|
||||||
|
footer.addArrangedSubview(progressLabel)
|
||||||
|
footer.addArrangedSubview(actionButton)
|
||||||
|
progressLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
|
||||||
|
actionButton.setContentHuggingPriority(.defaultHigh, for: .horizontal)
|
||||||
|
actionButton.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||||
|
actionButton.snp.makeConstraints { $0.width.greaterThanOrEqualTo(140).priority(750) }
|
||||||
|
[top, titleLabel, publisherLabel, metaLabel, hint, progressView, footer].forEach(stack.addArrangedSubview)
|
||||||
|
stack.setCustomSpacing(14, after: top)
|
||||||
|
stack.setCustomSpacing(14, after: metaLabel)
|
||||||
|
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 13, bottom: 10, right: 13)) }
|
||||||
|
actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside)
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
|
/// 每个任务始终可回顾课程,只有已读完且有效时直接进入考试。
|
||||||
|
func configure(task: TrainingTask) {
|
||||||
|
let presentation = TrainingTaskPresentation(task: task)
|
||||||
|
titleLabel.text = task.title
|
||||||
|
deadlineLabel.text = "截止时间:\(TrainingUI.date(task.endAt))"
|
||||||
|
statusLabel.text = task.learnerStatus.title
|
||||||
|
statusLabel.textColor = task.learnerStatus == .completed ? TrainingUI.success : TrainingUI.primary
|
||||||
|
publisherLabel.text = "发布人:\(task.publisherText)"
|
||||||
|
metaLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.course.sections.count) 节 · \(task.questions.count) 题 · \(task.passScore) 分及格" : "仅学习 · \(task.course.sections.count) 节"
|
||||||
|
hintLabel.text = presentation.hint
|
||||||
|
progressView.progress = Float(presentation.progressPercent) / 100
|
||||||
|
progressLabel.text = "学习进度 \(presentation.progressPercent)%"
|
||||||
|
var configuration = actionButton.configuration
|
||||||
|
configuration?.title = presentation.actionTitle
|
||||||
|
actionButton.configuration = configuration
|
||||||
|
actionButton.accessibilityIdentifier = "training.task.action.\(task.id)"
|
||||||
|
footer.axis = traitCollection.preferredContentSizeCategory.isAccessibilityCategory ? .vertical : .horizontal
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func actionTapped() { onAction?() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 考试记录沿用小程序的标题、蓝色得分和通过状态卡片。
|
||||||
|
@MainActor
|
||||||
|
final class TrainingRecordCell: UITableViewCell {
|
||||||
|
static let reuseIdentifier = "TrainingRecordCell"
|
||||||
|
private let stack = TrainingUI.card()
|
||||||
|
private let titleLabel = TrainingUI.text(weight: .semibold)
|
||||||
|
private let scoreLabel = TrainingUI.text(weight: .semibold, color: TrainingUI.primary)
|
||||||
|
private let detailLabel = TrainingUI.text(size: 11.5, color: TrainingUI.muted)
|
||||||
|
private let statusLabel = TrainingUI.text(size: 11.5)
|
||||||
|
|
||||||
|
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
|
||||||
|
super.init(style: style, reuseIdentifier: reuseIdentifier)
|
||||||
|
backgroundColor = .clear
|
||||||
|
selectionStyle = .none
|
||||||
|
let top = UIStackView(arrangedSubviews: [titleLabel, scoreLabel])
|
||||||
|
top.spacing = 12
|
||||||
|
top.alignment = .top
|
||||||
|
scoreLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||||
|
scoreLabel.setContentHuggingPriority(.required, for: .horizontal)
|
||||||
|
titleLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
|
||||||
|
let bottom = UIStackView(arrangedSubviews: [detailLabel, statusLabel])
|
||||||
|
bottom.spacing = 12
|
||||||
|
bottom.alignment = .top
|
||||||
|
statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||||
|
statusLabel.setContentHuggingPriority(.required, for: .horizontal)
|
||||||
|
detailLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
|
||||||
|
stack.addArrangedSubview(top)
|
||||||
|
stack.addArrangedSubview(bottom)
|
||||||
|
contentView.addSubview(stack)
|
||||||
|
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 13, bottom: 10, right: 13)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
|
/// 展示已提交记录,点击后进入该次成绩。
|
||||||
|
func configure(task: TrainingTask, attempt: TrainingAttempt) {
|
||||||
|
titleLabel.text = task.title
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 培训页面在账号或景区切换时立即关闭,停止展示旧身份记录。
|
||||||
|
@MainActor
|
||||||
|
class TrainingBaseViewController: BaseViewController {
|
||||||
|
override func viewDidLoad() {
|
||||||
|
super.viewDidLoad()
|
||||||
|
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange] {
|
||||||
|
NotificationCenter.default.addObserver(self, selector: #selector(contextChanged), name: name, object: nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func contextChanged() { navigationController?.popToRootViewController(animated: false) }
|
||||||
|
}
|
||||||
@@ -83,7 +83,7 @@ final class HomeViewModelTests: XCTestCase {
|
|||||||
])
|
])
|
||||||
let viewModel = HomeViewModel(appStore: appStore)
|
let viewModel = HomeViewModel(appStore: appStore)
|
||||||
viewModel.rebuildCommonMenus()
|
viewModel.rebuildCommonMenus()
|
||||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet"])
|
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "/training"])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testRebuildCommonMenusPersistsDefaultURIsOnFirstLoad() {
|
func testRebuildCommonMenusPersistsDefaultURIsOnFirstLoad() {
|
||||||
@@ -100,7 +100,7 @@ final class HomeViewModelTests: XCTestCase {
|
|||||||
viewModel.rebuildCommonMenus()
|
viewModel.rebuildCommonMenus()
|
||||||
|
|
||||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), [
|
XCTAssertEqual(viewModel.commonMenus.map(\.uri), [
|
||||||
"wallet", "cloud_management", "task_management", "system_settings",
|
"wallet", "cloud_management", "task_management", "system_settings", "/training",
|
||||||
])
|
])
|
||||||
XCTAssertEqual(
|
XCTAssertEqual(
|
||||||
menuStore.savedCommonURIs(
|
menuStore.savedCommonURIs(
|
||||||
@@ -120,7 +120,7 @@ final class HomeViewModelTests: XCTestCase {
|
|||||||
await viewModel.loadPermissions(api: api, force: true)
|
await viewModel.loadPermissions(api: api, force: true)
|
||||||
|
|
||||||
XCTAssertTrue(viewModel.showPermissionDialog)
|
XCTAssertTrue(viewModel.showPermissionDialog)
|
||||||
XCTAssertTrue(viewModel.commonMenus.isEmpty)
|
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["/training"])
|
||||||
}
|
}
|
||||||
|
|
||||||
func testPermissionApplyDestinationRoutesReviewingAndRejectedToStatus() async throws {
|
func testPermissionApplyDestinationRoutesReviewingAndRejectedToStatus() async throws {
|
||||||
@@ -200,7 +200,7 @@ final class HomeViewModelTests: XCTestCase {
|
|||||||
|
|
||||||
XCTAssertFalse(viewModel.showPermissionDialog)
|
XCTAssertFalse(viewModel.showPermissionDialog)
|
||||||
XCTAssertTrue(viewModel.isMinimalTopRole)
|
XCTAssertTrue(viewModel.isMinimalTopRole)
|
||||||
XCTAssertEqual(viewModel.commonMenus.count, 2)
|
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "cloud_management", "/training"])
|
||||||
XCTAssertEqual(viewModel.storeItem?.name, "测试门店")
|
XCTAssertEqual(viewModel.storeItem?.name, "测试门店")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,7 +227,7 @@ final class HomeViewModelTests: XCTestCase {
|
|||||||
viewModel.markNeedsPermissionReload()
|
viewModel.markNeedsPermissionReload()
|
||||||
await viewModel.reloadIfNeeded(api: api)
|
await viewModel.reloadIfNeeded(api: api)
|
||||||
|
|
||||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet"])
|
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "/training"])
|
||||||
XCTAssertEqual(session.requests.count, 1)
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,389 @@
|
|||||||
|
import Foundation
|
||||||
|
import Testing
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
#if DEBUG
|
||||||
|
/// 所有状态均为每个测试独立创建的可失败存储。
|
||||||
|
private final class TrainingMemoryStorage: TrainingDemoStoring, @unchecked Sendable {
|
||||||
|
private let lock = NSLock()
|
||||||
|
private var values: [String: Data] = [:]
|
||||||
|
private var writeFailure = false
|
||||||
|
|
||||||
|
/// 模拟持久化失败,不修改原有记录。
|
||||||
|
func failWrites(_ value: Bool) { lock.lock(); defer { lock.unlock() }; writeFailure = value }
|
||||||
|
func read(key: String) throws -> Data? { lock.lock(); defer { lock.unlock() }; return values[key] }
|
||||||
|
func write(_ data: Data, key: String) throws {
|
||||||
|
lock.lock()
|
||||||
|
defer { lock.unlock() }
|
||||||
|
if writeFailure { throw TrainingError.saveFailed }
|
||||||
|
values[key] = data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 培训功能边界测试,仅 mock 数据源,不发起真实网络或提交成绩。
|
||||||
|
@Suite("培训中心学习与答题")
|
||||||
|
@MainActor
|
||||||
|
struct TrainingFeatureTests {
|
||||||
|
private let now = Date(timeIntervalSince1970: 1_800_000_000)
|
||||||
|
private let context = TrainingContext(accountScope: "scenic_user_1001", scenicID: 10, storeID: 3)
|
||||||
|
private let storage = TrainingMemoryStorage()
|
||||||
|
|
||||||
|
private func service(packs: [TrainingDemoPack]? = nil, date: Date? = nil,
|
||||||
|
context: TrainingContext? = nil) -> TrainingDemoService {
|
||||||
|
let date = date ?? now
|
||||||
|
let fixtures = packs ?? TrainingDemoFixtures.makePacks(now: now)
|
||||||
|
return TrainingDemoService(context: context ?? self.context, storage: storage, now: { date }, seed: { _ in fixtures })
|
||||||
|
}
|
||||||
|
|
||||||
|
private func readCourse(_ service: TrainingDemoService, id: String = "demo-service") async throws {
|
||||||
|
for _ in 0..<TrainingTask.requiredReadingSeconds { _ = try await service.recordReadingSecond(taskID: id) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private var correctAnswers: TrainingAnswers { ["q1": ["A"], "q2": ["A", "B"], "q3": ["B"], "q4": ["A", "B", "C"]] }
|
||||||
|
|
||||||
|
@Test("任务卡入口随学习、草稿、通过和截止状态变化")
|
||||||
|
func taskCardActions() async throws {
|
||||||
|
let source = service()
|
||||||
|
var task = try await source.task(id: "demo-service")
|
||||||
|
#expect(TrainingTaskPresentation(task: task, now: now).actionTitle == "去学习")
|
||||||
|
#expect(TrainingTaskPresentation(task: task, now: now).progressPercent == 0)
|
||||||
|
try await readCourse(source)
|
||||||
|
task = try await source.task(id: task.id)
|
||||||
|
#expect(TrainingTaskPresentation(task: task, now: now).canStartExam)
|
||||||
|
#expect(TrainingTaskPresentation(task: task, now: now).progressPercent == 100)
|
||||||
|
try await source.saveDraft(taskID: task.id, answers: ["q1": ["A"]])
|
||||||
|
task = try await source.task(id: task.id)
|
||||||
|
#expect(TrainingTaskPresentation(task: task, now: now).actionTitle == "继续答题")
|
||||||
|
task.status = .closed
|
||||||
|
#expect(TrainingTaskPresentation(task: task, now: now).actionTitle == "查看课程")
|
||||||
|
#expect(!TrainingTaskPresentation(task: task, now: now).canStartExam)
|
||||||
|
_ = try await source.submit(taskID: task.id, answers: correctAnswers, submissionID: "passed")
|
||||||
|
task = try await source.task(id: task.id)
|
||||||
|
#expect(TrainingTaskPresentation(task: task, now: now).actionTitle == "回顾学习")
|
||||||
|
#expect(!TrainingTaskPresentation(task: task, now: now).canStartExam)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("首页统计、任务搜索与考试记录排序保持同一数据源")
|
||||||
|
func centerTabsSearchAndRecords() async throws {
|
||||||
|
let source = service()
|
||||||
|
let model = TrainingCenterViewModel()
|
||||||
|
await model.load(service: source)
|
||||||
|
#expect(model.pendingCount == 3)
|
||||||
|
#expect(model.completedCount == 0)
|
||||||
|
#expect(model.latestScore == "—")
|
||||||
|
model.keyword = "不会匹配"
|
||||||
|
#expect(model.visibleTasks.count == 3)
|
||||||
|
model.selectTab(.tasks)
|
||||||
|
model.keyword = "巩固练习"
|
||||||
|
#expect(model.visibleTasks.map(\.id) == ["demo-review"])
|
||||||
|
model.keyword = "景区服务规范与游客沟通"
|
||||||
|
#expect(model.visibleTasks.count == 3)
|
||||||
|
try await readCourse(source)
|
||||||
|
_ = try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "passed")
|
||||||
|
await model.load(service: source)
|
||||||
|
#expect(model.pendingCount == 2)
|
||||||
|
#expect(model.completedCount == 1)
|
||||||
|
model.filter = .completed
|
||||||
|
#expect(model.visibleTasks.map(\.id) == ["demo-service"])
|
||||||
|
model.selectTab(.records)
|
||||||
|
#expect(model.keyword.isEmpty)
|
||||||
|
#expect(model.records.first?.attempt.id == "passed")
|
||||||
|
#expect(model.latestScore == "100")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("未满20秒禁止考试,阅读完成与草稿可以恢复")
|
||||||
|
func readingGateAndPersistence() async throws {
|
||||||
|
let source = service()
|
||||||
|
for _ in 0..<19 { _ = try await source.recordReadingSecond(taskID: "demo-service") }
|
||||||
|
await #expect(throws: TrainingError.readingRequired) {
|
||||||
|
try await source.saveDraft(taskID: "demo-service", answers: ["q1": ["A"]])
|
||||||
|
}
|
||||||
|
let finished = try await source.recordReadingSecond(taskID: "demo-service")
|
||||||
|
#expect(finished.hasFinishedReading)
|
||||||
|
#expect(finished.learnerStatus == .pendingExam)
|
||||||
|
try await source.saveDraft(taskID: finished.id, answers: ["q1": ["A"]])
|
||||||
|
let restored = try await service().task(id: finished.id)
|
||||||
|
#expect(restored.progress.readingSeconds == 20)
|
||||||
|
#expect(restored.progress.completedSectionIDs == ["section-1", "section-2"])
|
||||||
|
#expect(restored.progress.draftAnswers["q1"] == ["A"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("前后台暂停恢复不累计离开的时间,整秒才计时")
|
||||||
|
func foregroundClock() {
|
||||||
|
var clock = TrainingReadingClock()
|
||||||
|
clock.resume(at: 10)
|
||||||
|
let partial = clock.takeSecond(at: 10.99)
|
||||||
|
let whole = clock.takeSecond(at: 11)
|
||||||
|
#expect(!partial)
|
||||||
|
#expect(whole)
|
||||||
|
clock.pause()
|
||||||
|
let background = clock.takeSecond(at: 1000)
|
||||||
|
#expect(!background)
|
||||||
|
clock.resume(at: 1000)
|
||||||
|
let resumedPartial = clock.takeSecond(at: 1000.5)
|
||||||
|
let resumedWhole = clock.takeSecond(at: 1001)
|
||||||
|
let delayedTick = clock.takeSecond(at: 2000)
|
||||||
|
let repeatedTick = clock.takeSecond(at: 2000)
|
||||||
|
#expect(!resumedPartial)
|
||||||
|
#expect(resumedWhole)
|
||||||
|
#expect(delayedTick)
|
||||||
|
#expect(!repeatedTick)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("仅学习任务读满即完成,不允许交卷")
|
||||||
|
func studyOnlyCompletion() async throws {
|
||||||
|
let source = service()
|
||||||
|
try await readCourse(source, id: "demo-study")
|
||||||
|
let task = try await source.task(id: "demo-study")
|
||||||
|
#expect(task.learnerStatus == .completed)
|
||||||
|
#expect(task.progress.attempts.isEmpty)
|
||||||
|
#expect(task.progress.completedAt == now)
|
||||||
|
await #expect(throws: TrainingError.self) {
|
||||||
|
try await source.submit(taskID: task.id, answers: [:], submissionID: "study")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("多选少选、多选和错选均不得分", arguments: [Set(["A"]), Set(["A", "B", "C"]), Set(["B", "C"])])
|
||||||
|
func multipleChoiceRequiresExactAnswer(selected: Set<String>) async throws {
|
||||||
|
let source = service()
|
||||||
|
try await readCourse(source)
|
||||||
|
var answers = correctAnswers
|
||||||
|
answers["q2"] = selected
|
||||||
|
let attempt = try await source.submit(taskID: "demo-service", answers: answers, submissionID: "attempt")
|
||||||
|
#expect(attempt.correctCount == 3)
|
||||||
|
#expect(attempt.scoreText == "75")
|
||||||
|
#expect(!attempt.passed)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("全对100分;交卷幂等,通过后不可再次提交")
|
||||||
|
func passingAndIdempotency() async throws {
|
||||||
|
let source = service()
|
||||||
|
try await readCourse(source)
|
||||||
|
let first = try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "same")
|
||||||
|
let repeated = try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "same")
|
||||||
|
#expect(first == repeated)
|
||||||
|
#expect(first.passed)
|
||||||
|
#expect(first.scoreText == "100")
|
||||||
|
let task = try await source.task(id: "demo-service")
|
||||||
|
#expect(task.progress.attempts.count == 1)
|
||||||
|
#expect(task.progress.draftAnswers.isEmpty)
|
||||||
|
#expect(task.learnerStatus == .completed)
|
||||||
|
await #expect(throws: TrainingError.self) {
|
||||||
|
try await source.submit(taskID: task.id, answers: correctAnswers, submissionID: "new")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("未通过可不限次重考,保留每次成绩")
|
||||||
|
func unlimitedRetakesAndHistory() async throws {
|
||||||
|
let source = service()
|
||||||
|
try await readCourse(source)
|
||||||
|
var wrong = correctAnswers
|
||||||
|
wrong["q1"] = ["B"]
|
||||||
|
for number in 1...6 {
|
||||||
|
let result = try await source.submit(taskID: "demo-service", answers: wrong, submissionID: "fail-\(number)")
|
||||||
|
#expect(!result.passed)
|
||||||
|
}
|
||||||
|
let before = try await source.task(id: "demo-service")
|
||||||
|
#expect(before.learnerStatus == .pendingExam)
|
||||||
|
#expect(before.progress.attempts.count == 6)
|
||||||
|
let passed = try await source.submit(taskID: before.id, answers: correctAnswers, submissionID: "pass")
|
||||||
|
#expect(passed.passed)
|
||||||
|
let after = try await source.task(id: before.id)
|
||||||
|
#expect(after.progress.attempts.count == 7)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("500题边界不逐题取整,小数舍去且按精确比例判断及格")
|
||||||
|
func exactPercentageScoring() async throws {
|
||||||
|
for (count, correct, passScore, score, passed) in [(100, 80, 80, "80", true), (3, 2, 67, "66.66", false), (499, 494, 99, "98.99", false), (500, 500, 100, "100", true)] {
|
||||||
|
let base = TrainingDemoFixtures.makePacks(now: now)[0].task
|
||||||
|
let questions = (0..<count).map { TrainingQuestion(id: "q\($0)", type: .single, stem: "题目\($0)", options: [TrainingOption(id: "A", text: "正确"), TrainingOption(id: "B", text: "错误")]) }
|
||||||
|
let task = TrainingTask(id: "score-\(count)", title: "计分", publisherName: nil, mode: .exam, status: .published,
|
||||||
|
startAt: base.startAt, endAt: base.endAt, passScore: passScore, scoring: base.scoring,
|
||||||
|
course: base.course, questions: questions, progress: TrainingProgress())
|
||||||
|
let solutions = Dictionary(uniqueKeysWithValues: questions.map { ($0.id, TrainingDemoSolution(correctIDs: ["A"], explanation: "解析")) })
|
||||||
|
let uniqueContext = TrainingContext(accountScope: "test_\(count)", scenicID: 10, storeID: 3)
|
||||||
|
let source = service(packs: [TrainingDemoPack(task: task, solutions: solutions)], context: uniqueContext)
|
||||||
|
try await readCourse(source, id: task.id)
|
||||||
|
let answers = Dictionary(uniqueKeysWithValues: questions.enumerated().map { ($0.element.id, Set([$0.offset < correct ? "A" : "B"])) })
|
||||||
|
let result = try await source.submit(taskID: task.id, answers: answers, submissionID: "score")
|
||||||
|
#expect(result.scoreText == score)
|
||||||
|
#expect(result.passed == passed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("开始边界可提交,截止边界不可提交")
|
||||||
|
func taskTimeBoundaries() async throws {
|
||||||
|
let source = service()
|
||||||
|
try await readCourse(source)
|
||||||
|
let task = try await source.task(id: "demo-service")
|
||||||
|
#expect(task.submissionBlockReason(now: task.startAt) == nil)
|
||||||
|
#expect(task.submissionBlockReason(now: task.startAt.addingTimeInterval(-0.01)) != nil)
|
||||||
|
#expect(task.submissionBlockReason(now: task.endAt.addingTimeInterval(-0.01)) == nil)
|
||||||
|
#expect(task.submissionBlockReason(now: task.endAt) != nil)
|
||||||
|
await #expect(throws: TrainingError.self) {
|
||||||
|
try await service(date: task.endAt).submit(taskID: task.id, answers: correctAnswers, submissionID: "late")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("已关闭任务不可学习或交卷,历史仍可读取")
|
||||||
|
func closedTasksAreReadOnly() async throws {
|
||||||
|
var packs = TrainingDemoFixtures.makePacks(now: now)
|
||||||
|
packs[0].task.status = .closed
|
||||||
|
let source = service(packs: packs)
|
||||||
|
_ = try await source.task(id: "demo-service")
|
||||||
|
await #expect(throws: TrainingError.self) { try await source.recordReadingSecond(taskID: "demo-service") }
|
||||||
|
await #expect(throws: TrainingError.self) { try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "closed") }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("无效选项、单选多选和漏答禁止交卷")
|
||||||
|
func rejectsInvalidAnswers() async throws {
|
||||||
|
let source = service()
|
||||||
|
try await readCourse(source)
|
||||||
|
for invalid in [["q1": Set(["unknown"])], ["unknown": Set(["A"])], ["q1": Set(["A", "B"])]] {
|
||||||
|
await #expect(throws: TrainingError.invalidAnswers) { try await source.saveDraft(taskID: "demo-service", answers: invalid) }
|
||||||
|
}
|
||||||
|
await #expect(throws: TrainingError.unanswered(4)) {
|
||||||
|
try await source.submit(taskID: "demo-service", answers: [:], submissionID: "empty")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("未知计分版本及重复选项明确拒绝")
|
||||||
|
func rejectsInvalidPaper() throws {
|
||||||
|
let base = TrainingDemoFixtures.makePacks(now: now)[0].task
|
||||||
|
let old = TrainingTask(id: base.id, title: base.title, publisherName: nil, mode: .exam, status: .published,
|
||||||
|
startAt: base.startAt, endAt: base.endAt, passScore: 100, scoring: "unknown",
|
||||||
|
course: base.course, questions: base.questions, progress: base.progress)
|
||||||
|
#expect(throws: TrainingError.invalidPaper) { try TrainingValidation.validatePaper(old) }
|
||||||
|
let question = TrainingQuestion(id: "q", type: .single, stem: "重复", options: [TrainingOption(id: "A", text: "一"), TrainingOption(id: "A", text: "二")])
|
||||||
|
let invalid = TrainingTask(id: base.id, title: base.title, publisherName: nil, mode: .exam, status: .published,
|
||||||
|
startAt: base.startAt, endAt: base.endAt, passScore: 100, scoring: base.scoring,
|
||||||
|
course: base.course, questions: [question], progress: base.progress)
|
||||||
|
#expect(throws: TrainingError.invalidPaper) { try TrainingValidation.validatePaper(invalid) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("保存失败不放行阅读、不丢草稿、不新增成绩")
|
||||||
|
func failedPersistenceDoesNotCompleteOrSubmit() async throws {
|
||||||
|
let source = service()
|
||||||
|
for _ in 0..<19 { _ = try await source.recordReadingSecond(taskID: "demo-service") }
|
||||||
|
storage.failWrites(true)
|
||||||
|
await #expect(throws: TrainingError.saveFailed) { try await source.recordReadingSecond(taskID: "demo-service") }
|
||||||
|
let unfinished = try await source.task(id: "demo-service")
|
||||||
|
#expect(!unfinished.hasFinishedReading)
|
||||||
|
#expect(unfinished.progress.readingSeconds == 19)
|
||||||
|
storage.failWrites(false)
|
||||||
|
_ = try await source.recordReadingSecond(taskID: "demo-service")
|
||||||
|
try await source.saveDraft(taskID: "demo-service", answers: correctAnswers)
|
||||||
|
storage.failWrites(true)
|
||||||
|
await #expect(throws: TrainingError.saveFailed) { try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "retry") }
|
||||||
|
let unchanged = try await source.task(id: "demo-service")
|
||||||
|
#expect(unchanged.progress.attempts.isEmpty)
|
||||||
|
#expect(unchanged.progress.draftAnswers == correctAnswers)
|
||||||
|
storage.failWrites(false)
|
||||||
|
_ = try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "retry")
|
||||||
|
let submitted = try await source.task(id: "demo-service")
|
||||||
|
#expect(submitted.progress.attempts.count == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("账号、景区、店铺分别隔离;身份切换拒绝旧页面操作")
|
||||||
|
func accountAndScenicIsolation() async throws {
|
||||||
|
try await readCourse(service())
|
||||||
|
for other in [TrainingContext(accountScope: "store_user_1001", scenicID: 10, storeID: 3),
|
||||||
|
TrainingContext(accountScope: context.accountScope, scenicID: 11, storeID: 3),
|
||||||
|
TrainingContext(accountScope: context.accountScope, scenicID: 10, storeID: 4)] {
|
||||||
|
let task = try await service(context: other).task(id: "demo-service")
|
||||||
|
#expect(task.progress.readingSeconds == 0)
|
||||||
|
}
|
||||||
|
let denied = TrainingDemoService(context: context, storage: storage, validateContext: { false })
|
||||||
|
await #expect(throws: TrainingError.identityChanged) { try await denied.listTasks() }
|
||||||
|
await #expect(throws: TrainingError.identityChanged) { try await denied.saveDraft(taskID: "demo-service", answers: [:]) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("损坏或未知版本数据不被自动重建覆盖")
|
||||||
|
func corruptDataIsPreserved() async throws {
|
||||||
|
for data in [Data("broken".utf8), Data(#"{"version":999,"packs":[]}"#.utf8)] {
|
||||||
|
try storage.write(data, key: context.storageKey)
|
||||||
|
await #expect(throws: TrainingError.corruptStorage) { try await service().listTasks() }
|
||||||
|
#expect(try storage.read(key: context.storageKey) == data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("首次演示快照保持固定,不随示例更新重置")
|
||||||
|
func taskSnapshotsRemainFrozen() async throws {
|
||||||
|
let original = try await service().task(id: "demo-service")
|
||||||
|
let changed = try await service(packs: [], date: now.addingTimeInterval(30 * 86400)).task(id: "demo-service")
|
||||||
|
#expect(original == changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("草稿恢复、单选替换、多选切换、漏答定位和安全跳转")
|
||||||
|
func examViewModelBehavior() async throws {
|
||||||
|
let source = service()
|
||||||
|
try await readCourse(source)
|
||||||
|
try await source.saveDraft(taskID: "demo-service", answers: ["q1": ["B"]])
|
||||||
|
let model = TrainingExamViewModel(taskID: "demo-service")
|
||||||
|
await model.load(service: source, now: now)
|
||||||
|
#expect(model.answers["q1"] == ["B"])
|
||||||
|
await model.select(optionID: "A", service: source)
|
||||||
|
#expect(model.answers["q1"] == ["A"])
|
||||||
|
model.goToQuestion(1)
|
||||||
|
await model.select(optionID: "A", service: source)
|
||||||
|
await model.select(optionID: "B", service: source)
|
||||||
|
#expect(model.answers["q2"] == ["A", "B"])
|
||||||
|
await model.select(optionID: "B", service: source)
|
||||||
|
#expect(model.answers["q2"] == ["A"])
|
||||||
|
model.goToQuestion(999)
|
||||||
|
#expect(model.currentIndex == 1)
|
||||||
|
#expect(await model.submit(service: source) == nil)
|
||||||
|
#expect(model.currentIndex == 2)
|
||||||
|
#expect(model.answeredCount == 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("答案保存失败保留原选择,重考清空草稿")
|
||||||
|
func examViewModelSaveFailureAndRetake() async throws {
|
||||||
|
let source = service()
|
||||||
|
try await readCourse(source)
|
||||||
|
try await source.saveDraft(taskID: "demo-service", answers: ["q1": ["B"]])
|
||||||
|
let model = TrainingExamViewModel(taskID: "demo-service")
|
||||||
|
await model.load(service: source, now: now)
|
||||||
|
storage.failWrites(true)
|
||||||
|
await model.select(optionID: "A", service: source)
|
||||||
|
#expect(model.answers["q1"] == ["B"])
|
||||||
|
#expect(model.errorMessage != nil)
|
||||||
|
storage.failWrites(false)
|
||||||
|
await model.load(service: source, now: now, resetDraft: true)
|
||||||
|
#expect(model.answers.isEmpty)
|
||||||
|
let task = try await source.task(id: "demo-service")
|
||||||
|
#expect(task.progress.draftAnswers.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("正式入口无示例任务、不可记录学习或提交成绩")
|
||||||
|
func productionServiceIsUnconnected() async throws {
|
||||||
|
let source = TrainingServiceFactory.production()
|
||||||
|
#expect(!source.isDemo)
|
||||||
|
await #expect(throws: TrainingError.unavailable) { try await source.listTasks() }
|
||||||
|
await #expect(throws: TrainingError.unavailable) { try await source.recordReadingSecond(taskID: "demo-service") }
|
||||||
|
await #expect(throws: TrainingError.unavailable) { try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "real") }
|
||||||
|
let model = TrainingCenterViewModel()
|
||||||
|
await model.load(service: source)
|
||||||
|
#expect(model.tasks.isEmpty)
|
||||||
|
#expect(model.errorMessage != nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("首页所有角色都有培训入口,服务端下发时不重复")
|
||||||
|
func trainingEntryForEveryRole() {
|
||||||
|
let suite = "TrainingMenuTests-\(UUID().uuidString)"
|
||||||
|
guard let defaults = UserDefaults(suiteName: suite) else { Issue.record("无法创建独立存储"); return }
|
||||||
|
defer { defaults.removePersistentDomain(forName: suite) }
|
||||||
|
let appStore = AppStore(defaults: defaults)
|
||||||
|
appStore.session.userId = "1001"
|
||||||
|
appStore.session.accountType = .scenicUser
|
||||||
|
for role in AppRoleCode.allCases {
|
||||||
|
appStore.session.roleCode = role.rawValue
|
||||||
|
appStore.permissions.savePermissionItems([HomePermissionItem(id: "training", name: "培训", uri: "/training")])
|
||||||
|
let model = HomeViewModel(appStore: appStore, commonMenuStore: HomeCommonMenuStore(defaults: defaults))
|
||||||
|
model.rebuildCommonMenus()
|
||||||
|
#expect(model.commonMenus.filter { $0.uri == "/training" }.count == 1)
|
||||||
|
}
|
||||||
|
#expect(HomeMenuCatalog.item(for: "/training")?.title == "培训中心")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
import Foundation
|
||||||
|
import Testing
|
||||||
|
import UIKit
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
#if DEBUG
|
||||||
|
/// 在连接的 iPhone 真机中渲染任务列表、成绩页和答题卡,附件用于视觉检查。
|
||||||
|
@Suite("培训中心原生布局", .serialized)
|
||||||
|
@MainActor
|
||||||
|
struct TrainingUIRenderingTests {
|
||||||
|
@Test("原生任务列表与窄屏长文本卡片不裁切")
|
||||||
|
func taskListAndLongTitleLayout() async throws {
|
||||||
|
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||||
|
defer { try? FileManager.default.removeItem(at: directory) }
|
||||||
|
let source = TrainingDemoService(context: TrainingContext(accountScope: "render", scenicID: 1, storeID: 1),
|
||||||
|
storage: TrainingDemoFileStorage(directory: directory))
|
||||||
|
let controller = TrainingCenterViewController(service: source)
|
||||||
|
controller.loadViewIfNeeded()
|
||||||
|
await controller.reload()
|
||||||
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
|
let window = try makeWindow(navigation)
|
||||||
|
defer { window.isHidden = true }
|
||||||
|
navigation.view.layoutIfNeeded()
|
||||||
|
Attachment.record(render(navigation.view), named: "培训首页", as: .png)
|
||||||
|
let labels = allViews(controller.view).compactMap { $0 as? UILabel }
|
||||||
|
#expect(labels.contains { $0.text == "一线服务规范学习(演示)" })
|
||||||
|
#expect(labels.contains { $0.text?.contains("未同步景区后台") == true })
|
||||||
|
|
||||||
|
let original = try await source.task(id: "demo-service")
|
||||||
|
let longTask = TrainingTask(id: original.id, title: String(repeating: "游客沟通与接待服务规范培训", count: 3),
|
||||||
|
publisherName: "景区培训负责人", mode: .exam, status: .published,
|
||||||
|
startAt: original.startAt, endAt: original.endAt, passScore: original.passScore,
|
||||||
|
scoring: original.scoring, course: original.course, questions: original.questions, progress: original.progress)
|
||||||
|
let cell = TrainingTaskCell(style: .default, reuseIdentifier: nil)
|
||||||
|
cell.configure(task: longTask)
|
||||||
|
let width: CGFloat = 320
|
||||||
|
let shortCell = TrainingTaskCell(style: .default, reuseIdentifier: nil)
|
||||||
|
shortCell.configure(task: original)
|
||||||
|
let shortSize = shortCell.contentView.systemLayoutSizeFitting(CGSize(width: width, height: 0),
|
||||||
|
withHorizontalFittingPriority: .required,
|
||||||
|
verticalFittingPriority: .fittingSizeLevel)
|
||||||
|
let size = cell.contentView.systemLayoutSizeFitting(CGSize(width: width, height: 0),
|
||||||
|
withHorizontalFittingPriority: .required,
|
||||||
|
verticalFittingPriority: .fittingSizeLevel)
|
||||||
|
cell.frame = CGRect(x: 0, y: 0, width: width, height: size.height)
|
||||||
|
cell.layoutIfNeeded()
|
||||||
|
#expect(size.height > shortSize.height)
|
||||||
|
for label in allViews(cell.contentView).compactMap({ $0 as? UILabel }).filter(isVisible) {
|
||||||
|
let frame = label.convert(label.bounds, to: cell.contentView)
|
||||||
|
#expect(frame.minX >= 0 && frame.maxX <= width + 1)
|
||||||
|
#expect(frame.minY >= 0 && frame.maxY <= size.height + 1)
|
||||||
|
}
|
||||||
|
let cardImage = UIGraphicsImageRenderer(size: cell.bounds.size).image { context in
|
||||||
|
cell.layer.render(in: context.cgContext)
|
||||||
|
}
|
||||||
|
Attachment.record(cardImage, named: "320点长标题任务卡", as: .png)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("未通过成绩可展开解析并返回已有课程,旧失败成绩在通过后不可重考")
|
||||||
|
func resultLearningAndReviewNavigation() async throws {
|
||||||
|
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||||
|
defer { try? FileManager.default.removeItem(at: directory) }
|
||||||
|
let source = TrainingDemoService(context: TrainingContext(accountScope: "result-render", scenicID: 1, storeID: 1), storage: TrainingDemoFileStorage(directory: directory))
|
||||||
|
for _ in 0..<20 { _ = try await source.recordReadingSecond(taskID: "demo-service") }
|
||||||
|
let wrong: TrainingAnswers = ["q1": ["B"], "q2": ["C"], "q3": ["A"], "q4": ["D"]]
|
||||||
|
let attempt = try await source.submit(taskID: "demo-service", answers: wrong, submissionID: "failed")
|
||||||
|
let center = TrainingCenterViewController(service: source)
|
||||||
|
let course = TrainingCourseViewController(taskID: "demo-service", service: source)
|
||||||
|
let result = TrainingResultViewController(taskID: "demo-service", attemptID: attempt.id, service: source)
|
||||||
|
let navigation = UINavigationController()
|
||||||
|
navigation.setViewControllers([center, course, result], animated: false)
|
||||||
|
let window = try makeWindow(navigation)
|
||||||
|
defer { window.isHidden = true }
|
||||||
|
result.loadViewIfNeeded()
|
||||||
|
await result.reload()
|
||||||
|
navigation.view.layoutIfNeeded()
|
||||||
|
let learning = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.learning" })
|
||||||
|
let details = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.details" })
|
||||||
|
let action = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.action" })
|
||||||
|
#expect(action.configuration?.title == "再考一次")
|
||||||
|
#expect(!allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == attempt.reviews.first?.question.stem })
|
||||||
|
Attachment.record(render(navigation.view), named: "未通过成绩默认收起解析", as: .png)
|
||||||
|
details.sendActions(for: .touchUpInside)
|
||||||
|
navigation.view.layoutIfNeeded()
|
||||||
|
#expect(allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == attempt.reviews.first?.question.stem })
|
||||||
|
Attachment.record(render(navigation.view), named: "成绩答案解析展开", as: .png)
|
||||||
|
learning.sendActions(for: .touchUpInside)
|
||||||
|
#expect(navigation.topViewController === course)
|
||||||
|
navigation.setViewControllers([center, result], animated: false)
|
||||||
|
await result.reload()
|
||||||
|
let newLearning = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.learning" })
|
||||||
|
newLearning.sendActions(for: .touchUpInside)
|
||||||
|
#expect((navigation.topViewController as? TrainingCourseViewController)?.taskID == "demo-service")
|
||||||
|
let passed = try await source.submit(taskID: "demo-service", answers: ["q1": ["A"], "q2": ["A", "B"], "q3": ["B"], "q4": ["A", "B", "C"]], submissionID: "passed")
|
||||||
|
navigation.setViewControllers([center, result], animated: false)
|
||||||
|
await result.reload()
|
||||||
|
#expect(action.configuration?.title == "完成,返回培训中心")
|
||||||
|
let passedResult = TrainingResultViewController(taskID: "demo-service", attemptID: passed.id, service: source)
|
||||||
|
navigation.setViewControllers([center, passedResult], animated: false)
|
||||||
|
await passedResult.reload()
|
||||||
|
navigation.view.layoutIfNeeded()
|
||||||
|
Attachment.record(render(navigation.view), named: "通过成绩仍可返回学习", as: .png)
|
||||||
|
let completion = try #require(allViews(passedResult.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.action" })
|
||||||
|
completion.sendActions(for: .touchUpInside)
|
||||||
|
#expect(navigation.topViewController === center)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeWindow(_ navigation: UINavigationController) throws -> UIWindow {
|
||||||
|
let scene = try #require(UIApplication.shared.connectedScenes.first as? UIWindowScene)
|
||||||
|
let window = UIWindow(windowScene: scene)
|
||||||
|
window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||||
|
window.rootViewController = navigation
|
||||||
|
window.makeKeyAndVisible()
|
||||||
|
navigation.view.layoutIfNeeded()
|
||||||
|
return window
|
||||||
|
}
|
||||||
|
|
||||||
|
private func render(_ view: UIView) -> UIImage {
|
||||||
|
UIGraphicsImageRenderer(size: view.bounds.size).image { context in view.layer.render(in: context.cgContext) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("100题答题卡可滚动并保留当前题与已答状态")
|
||||||
|
func largeAnswerCardIsScrollable() async throws {
|
||||||
|
let original = TrainingDemoFixtures.makePacks(now: Date())[0].task
|
||||||
|
let questions = (0..<100).map { TrainingQuestion(id: "q\($0)", type: .single, stem: "题目\($0)", options: original.questions[0].options) }
|
||||||
|
let task = TrainingTask(id: original.id, title: original.title, publisherName: nil, mode: .exam, status: .published,
|
||||||
|
startAt: original.startAt, endAt: original.endAt, passScore: 80, scoring: original.scoring,
|
||||||
|
course: original.course, questions: questions, progress: original.progress)
|
||||||
|
let controller = TrainingAnswerCardViewController(task: task, answers: ["q0": ["A"], "q4": ["B"]], currentIndex: 4)
|
||||||
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
|
let window = try makeWindow(navigation)
|
||||||
|
defer { window.isHidden = true }
|
||||||
|
let collection = try #require(allViews(controller.view).first { $0 is UICollectionView } as? UICollectionView)
|
||||||
|
let currentCell = try await waitForVisibleCell(at: IndexPath(item: 4, section: 0), in: collection)
|
||||||
|
#expect(collection.numberOfItems(inSection: 0) == 100)
|
||||||
|
#expect(collection.contentSize.height > collection.bounds.height)
|
||||||
|
#expect(currentCell.accessibilityLabel == "第 5 题,已答,当前题")
|
||||||
|
let firstCell = try #require(collection.cellForItem(at: IndexPath(item: 0, section: 0)))
|
||||||
|
let secondRowCell = try #require(collection.cellForItem(at: IndexPath(item: 5, section: 0)))
|
||||||
|
#expect(abs(firstCell.frame.minY - currentCell.frame.minY) < 1)
|
||||||
|
#expect(currentCell.frame.maxX <= collection.bounds.width)
|
||||||
|
#expect(secondRowCell.frame.minY > currentCell.frame.maxY)
|
||||||
|
let image = UIGraphicsImageRenderer(size: controller.view.bounds.size).image { context in
|
||||||
|
controller.view.layer.render(in: context.cgContext)
|
||||||
|
}
|
||||||
|
Attachment.record(image, named: "100题答题卡", as: .png)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 按实际可见状态等待差异化列表动画,超时后让测试明确失败。
|
||||||
|
private func waitForVisibleCell(at indexPath: IndexPath, in collection: UICollectionView) async throws -> UICollectionViewCell {
|
||||||
|
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
||||||
|
while ContinuousClock.now < deadline {
|
||||||
|
collection.layoutIfNeeded()
|
||||||
|
if let cell = collection.cellForItem(at: indexPath) { return cell }
|
||||||
|
try await Task.sleep(for: .milliseconds(10))
|
||||||
|
}
|
||||||
|
return try #require(collection.cellForItem(at: indexPath))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func allViews(_ view: UIView) -> [UIView] {
|
||||||
|
[view] + view.subviews.flatMap(allViews)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func isVisible(_ view: UIView) -> Bool {
|
||||||
|
if view.isHidden { return false }
|
||||||
|
return view.superview.map(isVisible) ?? true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
Reference in New Issue
Block a user