feat(training): 新增培训中心学习答题演示及成绩回顾

新增首页和个人页培训入口,支持课程阅读、答题卡、未交卷答案恢复、成绩记录及重考。
对齐小程序的培训首页与成绩页,答案解析默认收起并提供返回对应课程的入口。

开发版使用隔离的本机演示数据,正式培训服务尚未接入。
This commit is contained in:
han xin
2026-10-10 11:36:49 +08:00
parent e1175066b9
commit 74c451c5e5
17 changed files with 2612 additions and 7 deletions
@@ -0,0 +1,251 @@
#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,67 @@
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
}