#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 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: """

让游客明白,再开始服务

主动问候,介绍服务项目、费用、交付内容与时间。未经游客确认,不增加收费项目。

遇到相似套餐,要讲清包含和不包含的项目。如果游客没有听清,应换一种表达再次说明,不把沉默当作确认。

"""), TrainingSection(id: "section-2", title: "问题反馈与协同处理", contentHTML: """

先倾听,再记录,再处理

遇到问题先完整听取诉求,客观记录事情经过。超出职责范围时,联系景区工作人员协同处理,并跟进反馈。

交接时说明已核实的信息、尚未解决的问题及后续负责人。预计无法按原时间反馈时,及时说明变化。

演示提醒:实际处理要求以景区发布的正式制度为准。

""") ] 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