feat(training): 接入真实培训接口与学习答题恢复
This commit is contained in:
@@ -0,0 +1,472 @@
|
||||
import Foundation
|
||||
|
||||
/// 分页考试状态;全局已答题号与当前页答案分离,交卷只消费服务端草稿版本。
|
||||
final class TrainingRemoteExamViewModel {
|
||||
/// 固定的本人任务标识。
|
||||
let taskID: String
|
||||
/// 已验证的轻量任务摘要。
|
||||
private(set) var task: TrainingTaskSummary?
|
||||
/// 服务端当前考试资格。
|
||||
private(set) var progress: TrainingProgressSnapshot?
|
||||
/// 冻结试卷规则与总题数。
|
||||
private(set) var paper: TrainingPaperInfo?
|
||||
/// 当前展示题位,使用从零开始的索引。
|
||||
private(set) var currentIndex = 0
|
||||
/// 服务端确认的全部已答题号,题号从一开始。
|
||||
private(set) var answeredQuestionOrders: Set<Int> = []
|
||||
/// 最近确认的草稿版本,未加载前为零。
|
||||
private(set) var draftRevision = 0
|
||||
/// 当前操作期间阻止并发写入。
|
||||
private(set) var isBusy = false
|
||||
/// 最近失败的展示文案,业务分支不依赖文案。
|
||||
private(set) var errorMessage: String?
|
||||
/// 已提交或恢复的成绩,可直接进入成绩页面。
|
||||
private(set) var submittedAttempt: TrainingAttemptSummary?
|
||||
/// 首次交卷返回的成绩及资格,成绩首屏可复用而无需等待额外请求。
|
||||
private(set) var submittedResult: TrainingAttemptDetail?
|
||||
/// 账号不支持培训或任务无访问权限时返回培训中心,身份变化时退出到根页面。
|
||||
private(set) var shouldReturnToCenter = false
|
||||
|
||||
private let pageSize: Int
|
||||
private let pendingStore: TrainingPendingSubmissionStore
|
||||
private let currentContext: @MainActor @Sendable () -> TrainingContext?
|
||||
private var context: TrainingContext?
|
||||
private var questionCache: [Int: TrainingQuestionItem] = [:]
|
||||
private var answerCache: TrainingAnswers = [:]
|
||||
private var loadedDraftIndices: Set<Int> = []
|
||||
private var pendingSubmission: TrainingPendingSubmission?
|
||||
private var pendingMutation: DraftMutation?
|
||||
private var initialResetRequested = false
|
||||
private var needsDraftRefresh = false
|
||||
private var recoveryStorageFailed = false
|
||||
private var identityIsValid = true
|
||||
|
||||
/// 未确认的草稿写入保持原请求 ID、版本和内容,不能被新的选择替换。
|
||||
private enum DraftMutation {
|
||||
case save(TrainingDraftSaveRequest)
|
||||
case reset(TrainingDraftResetRequest)
|
||||
}
|
||||
|
||||
/// 注入身份与持久化域,测试不访问全局登录态或网络。
|
||||
init(taskID: String, context: TrainingContext? = nil, pageSize: Int = 10,
|
||||
pendingStore: TrainingPendingSubmissionStore = TrainingPendingSubmissionStore(),
|
||||
currentContext: @escaping @MainActor @Sendable () -> TrainingContext? = { TrainingPendingSubmissionStore.currentContext() }) {
|
||||
self.taskID = taskID
|
||||
self.context = context
|
||||
self.pageSize = min(20, max(1, pageSize))
|
||||
self.pendingStore = pendingStore
|
||||
self.currentContext = currentContext
|
||||
}
|
||||
|
||||
/// 已知总题数,无需获取全部题目正文。
|
||||
var questionCount: Int { paper?.questionCount ?? 0 }
|
||||
/// 全局已答数量,不把未下载的答案当成漏答。
|
||||
var answeredCount: Int { answeredQuestionOrders.count }
|
||||
/// 当前已加载的题目。
|
||||
var currentQuestion: TrainingQuestionItem? { questionCache[currentIndex] }
|
||||
/// 当前题已确认保存的选择。
|
||||
var currentSelectedIDs: Set<String> { currentQuestion.flatMap { answerCache[$0.id] } ?? [] }
|
||||
/// 第一处真正漏答的题位。
|
||||
var firstUnansweredIndex: Int? {
|
||||
guard questionCount > 0 else { return nil }
|
||||
return (1...questionCount).first { !answeredQuestionOrders.contains($0) }.map { $0 - 1 }
|
||||
}
|
||||
/// 存在未确认交卷时暂停编辑,直到恢复同一次结果。
|
||||
var hasPendingSubmission: Bool { pendingSubmission != nil }
|
||||
/// 页面所属账号、景区或店铺已变化,不能继续显示原身份的数据。
|
||||
var isIdentityInvalid: Bool { !identityIsValid }
|
||||
/// 草稿请求失败后只允许重试原操作。
|
||||
var hasPendingMutation: Bool { pendingMutation != nil }
|
||||
/// 当前题正文和对应草稿范围均成功读取后,才可展示为可编辑答案。
|
||||
var isCurrentPageReady: Bool { currentQuestion != nil && loadedDraftIndices.contains(currentIndex) && !needsDraftRefresh }
|
||||
/// 页读取或冲突后的恢复失败时,沿当前题位重试读取,保留其它页缓存。
|
||||
var canRetryCurrentPage: Bool {
|
||||
!isBusy && identityIsValid && !hasPendingSubmission && !hasPendingMutation && !recoveryStorageFailed
|
||||
&& !shouldReturnToCenter && submittedAttempt == nil && paper != nil && !isCurrentPageReady
|
||||
&& progress?.canStartExam == true && progress?.learnerStatus != .completed
|
||||
}
|
||||
/// 只有权威资格允许且所有写入均确认后才能修改答案。
|
||||
var canEdit: Bool {
|
||||
!isBusy && identityIsValid && !hasPendingSubmission && !hasPendingMutation && !needsDraftRefresh && !recoveryStorageFailed
|
||||
&& submittedAttempt == nil && progress?.canStartExam == true && progress?.learnerStatus != .completed
|
||||
&& !shouldReturnToCenter && paper != nil && isCurrentPageReady
|
||||
}
|
||||
|
||||
/// 返回已提交页面前再次核对身份,避免把缓存成绩显示给切换后的账号。
|
||||
func validateIdentity() async {
|
||||
do { try await authorize() }
|
||||
catch { report(error) }
|
||||
}
|
||||
|
||||
/// 恢复待确认提交优先于考试资格校验;正常加载只取恢复题位所在的一页。
|
||||
func load(service: any TrainingDataServing, resetDraft: Bool = false) async {
|
||||
guard !isBusy else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await authorize()
|
||||
guard let context else { throw TrainingRemoteError.identityChanged }
|
||||
do {
|
||||
pendingSubmission = try pendingStore.load(taskID: taskID, context: context)
|
||||
recoveryStorageFailed = false
|
||||
} catch {
|
||||
recoveryStorageFailed = true
|
||||
throw error
|
||||
}
|
||||
if pendingSubmission != nil {
|
||||
_ = try await recoverSubmission(service: service)
|
||||
return
|
||||
}
|
||||
if pendingMutation != nil {
|
||||
try await performMutation(service: service)
|
||||
return
|
||||
}
|
||||
let detail = try await service.task(id: taskID)
|
||||
try await authorize()
|
||||
let latestProgress = try await service.progress(taskID: taskID)
|
||||
try await authorize()
|
||||
task = detail.summary
|
||||
progress = latestProgress
|
||||
try requireExamAllowed()
|
||||
guard let paperID = task?.paperSnapshotID else { throw TrainingError.invalidPaper }
|
||||
let loadedPaper = try await service.paper(id: paperID, taskID: taskID)
|
||||
try await authorize()
|
||||
guard loadedPaper.id == paperID, (1...500).contains(loadedPaper.questionCount),
|
||||
loadedPaper.scoring == TrainingTask.equalPercentageScoring else { throw TrainingError.invalidPaper }
|
||||
if paper?.id != loadedPaper.id { questionCache = [:]; answerCache = [:]; loadedDraftIndices = [] }
|
||||
paper = loadedPaper
|
||||
let metadata = try await service.draft(taskID: taskID, offset: 0, limit: 0)
|
||||
try await authorize()
|
||||
try applyMetadata(metadata)
|
||||
currentIndex = (1...questionCount).contains(metadata.lastQuestionOrder) ? metadata.lastQuestionOrder - 1 : 0
|
||||
if resetDraft, !initialResetRequested {
|
||||
initialResetRequested = true
|
||||
pendingMutation = .reset(TrainingDraftResetRequest(requestID: UUID().uuidString, paperSnapshotID: paperID, baseRevision: draftRevision))
|
||||
try await performMutation(service: service)
|
||||
} else {
|
||||
try await loadCurrentPage(service: service)
|
||||
}
|
||||
} catch { report(error) }
|
||||
}
|
||||
|
||||
/// 随机跳题直接获取所在页,并保存浏览位置;不遍历前面的题目页。
|
||||
func goToQuestion(_ index: Int, service: any TrainingDataServing) async {
|
||||
guard canEdit, (0..<questionCount).contains(index) else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await authorize()
|
||||
currentIndex = index
|
||||
try await loadCurrentPage(service: service)
|
||||
guard let paper else { throw TrainingError.invalidPaper }
|
||||
pendingMutation = .save(TrainingDraftSaveRequest(requestID: UUID().uuidString, paperSnapshotID: paper.id,
|
||||
baseRevision: draftRevision, lastQuestionOrder: index + 1, changes: []))
|
||||
try await performMutation(service: service)
|
||||
} catch { report(error) }
|
||||
}
|
||||
|
||||
/// 增量保存当前一题,网络结果未知时保留原 ID 和完整请求供重试。
|
||||
func select(optionID: String, service: any TrainingDataServing) async {
|
||||
guard canEdit, let question = currentQuestion, let paper,
|
||||
question.options.contains(where: { $0.id == optionID }) else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await authorize()
|
||||
var selected = currentSelectedIDs
|
||||
if question.type == .single { selected = [optionID] }
|
||||
else if selected.contains(optionID) { selected.remove(optionID) }
|
||||
else { selected.insert(optionID) }
|
||||
pendingMutation = .save(TrainingDraftSaveRequest(requestID: UUID().uuidString, paperSnapshotID: paper.id,
|
||||
baseRevision: draftRevision, lastQuestionOrder: question.order,
|
||||
changes: [TrainingDraftChange(questionID: question.id, selectedOptionIDs: selected.sorted())]))
|
||||
try await performMutation(service: service)
|
||||
} catch { report(error) }
|
||||
}
|
||||
|
||||
/// 沿用失败草稿写入的原请求,不生成新的幂等键。
|
||||
func retryMutation(service: any TrainingDataServing) async {
|
||||
guard !isBusy, pendingMutation != nil, !hasPendingSubmission else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do { try await authorize(); try await performMutation(service: service) }
|
||||
catch { report(error) }
|
||||
}
|
||||
|
||||
/// 仅重读当前未就绪题位;已确认的其它页不会因一次网络失败被清空。
|
||||
func retryCurrentPage(service: any TrainingDataServing) async {
|
||||
guard canRetryCurrentPage else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await authorize()
|
||||
if needsDraftRefresh { try await refreshDraft(service: service) }
|
||||
else { try await loadCurrentPage(service: service) }
|
||||
} catch { report(error) }
|
||||
}
|
||||
|
||||
/// 持久保存交卷请求后提交;未知结果先查原键,再重试原版本。
|
||||
func submit(service: any TrainingDataServing) async -> TrainingAttemptSummary? {
|
||||
guard !isBusy, !hasPendingMutation, !recoveryStorageFailed else { return nil }
|
||||
let wasEditable = canEdit
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await authorize()
|
||||
if pendingSubmission != nil { return try await recoverSubmission(service: service) }
|
||||
guard let context else { throw TrainingRemoteError.identityChanged }
|
||||
if let persisted = try pendingStore.load(taskID: taskID, context: context) {
|
||||
pendingSubmission = persisted
|
||||
return try await recoverSubmission(service: service)
|
||||
}
|
||||
guard wasEditable, firstUnansweredIndex == nil else {
|
||||
errorMessage = "还有 \(questionCount - answeredCount) 道题未作答"
|
||||
return nil
|
||||
}
|
||||
try requireExamAllowed()
|
||||
guard let paper else { throw TrainingError.invalidPaper }
|
||||
let request = TrainingSubmissionRequest(submissionID: UUID().uuidString, paperSnapshotID: paper.id, draftRevision: draftRevision)
|
||||
let pending = TrainingPendingSubmission(taskID: taskID, request: request, context: context)
|
||||
do { try pendingStore.save(pending) }
|
||||
catch TrainingPendingSubmissionError.alreadyPending {
|
||||
pendingSubmission = try pendingStore.load(taskID: taskID, context: context)
|
||||
return try await recoverSubmission(service: service)
|
||||
}
|
||||
pendingSubmission = pending
|
||||
return try await sendSubmission(pending, service: service)
|
||||
} catch { report(error); return nil }
|
||||
}
|
||||
|
||||
private func report(_ error: Error) {
|
||||
errorMessage = error.localizedDescription
|
||||
switch error {
|
||||
case TrainingRemoteError.identityChanged:
|
||||
identityIsValid = false
|
||||
shouldReturnToCenter = true
|
||||
task = nil
|
||||
progress = nil
|
||||
paper = nil
|
||||
questionCache = [:]
|
||||
answerCache = [:]
|
||||
loadedDraftIndices = []
|
||||
answeredQuestionOrders = []
|
||||
draftRevision = 0
|
||||
currentIndex = 0
|
||||
submittedAttempt = nil
|
||||
submittedResult = nil
|
||||
// 保留原身份的未知请求,不能因切换账号而删除或换键重试。
|
||||
case TrainingRemoteError.forbidden, TrainingRemoteError.accountInvalid: shouldReturnToCenter = true
|
||||
default: break
|
||||
}
|
||||
}
|
||||
|
||||
private func authorize() async throws {
|
||||
guard let actual = await currentContext() else { identityIsValid = false; throw TrainingRemoteError.identityChanged }
|
||||
if context == nil { context = actual }
|
||||
guard actual == context else { identityIsValid = false; throw TrainingRemoteError.identityChanged }
|
||||
identityIsValid = true
|
||||
}
|
||||
|
||||
private func requireExamAllowed() throws {
|
||||
guard task?.id == taskID, progress?.taskID == taskID else { throw TrainingError.invalidPaper }
|
||||
guard task?.mode == .exam, task?.learnerStatus != .completed,
|
||||
progress?.learnerStatus != .completed, progress?.completedAt == nil,
|
||||
progress?.canStartExam == true, progress?.readingCompleted == true else {
|
||||
throw TrainingRemoteError.examNotAllowed("当前任务暂不能考试,请返回课程确认学习进度和任务状态")
|
||||
}
|
||||
}
|
||||
|
||||
private func applyMetadata(_ value: TrainingDraftPage) throws {
|
||||
let orders = Set(value.answeredQuestionOrders)
|
||||
guard value.taskID == taskID, value.paperSnapshotID == paper?.id, value.total == questionCount,
|
||||
value.draftRevision > 0, orders.count == value.answeredCount,
|
||||
orders.allSatisfy({ (1...questionCount).contains($0) }) else { throw TrainingError.invalidAnswers }
|
||||
if value.draftRevision != draftRevision { answerCache = [:]; loadedDraftIndices = [] }
|
||||
draftRevision = value.draftRevision
|
||||
answeredQuestionOrders = orders
|
||||
}
|
||||
|
||||
private func loadCurrentPage(service: any TrainingDataServing) async throws {
|
||||
guard let paper else { throw TrainingError.invalidPaper }
|
||||
let offset = currentIndex / pageSize * pageSize
|
||||
if questionCache[currentIndex] == nil {
|
||||
try await fetchQuestions(offset: offset, paperID: paper.id, service: service)
|
||||
// 大小预算允许后端缩短页;远处题号直接请求目标位置,避免遍历此前的页。
|
||||
if questionCache[currentIndex] == nil, currentIndex != offset {
|
||||
try await fetchQuestions(offset: currentIndex, paperID: paper.id, service: service)
|
||||
}
|
||||
guard currentQuestion != nil else { throw TrainingError.invalidPaper }
|
||||
}
|
||||
if !loadedDraftIndices.contains(currentIndex) {
|
||||
try await fetchDraft(offset: offset, service: service)
|
||||
if !loadedDraftIndices.contains(currentIndex), currentIndex != offset {
|
||||
try await fetchDraft(offset: currentIndex, service: service)
|
||||
}
|
||||
guard loadedDraftIndices.contains(currentIndex) else { throw TrainingError.invalidAnswers }
|
||||
}
|
||||
if let question = currentQuestion {
|
||||
let selected = answerCache[question.id] ?? []
|
||||
guard selected.isSubset(of: Set(question.options.map(\.id))),
|
||||
question.type != .single || selected.count <= 1 else { throw TrainingError.invalidAnswers }
|
||||
}
|
||||
needsDraftRefresh = false
|
||||
}
|
||||
|
||||
private func fetchQuestions(offset: Int, paperID: String, service: any TrainingDataServing) async throws {
|
||||
let page = try await service.questions(paperID: paperID, taskID: taskID, offset: offset, limit: pageSize)
|
||||
try await authorize()
|
||||
let end = min(questionCount, offset + pageSize)
|
||||
guard page.paperSnapshotID == paperID, page.total == questionCount, page.offset == offset,
|
||||
!page.items.isEmpty, page.items.count <= end - offset,
|
||||
Set(page.items.map(\.order)).count == page.items.count,
|
||||
Set(page.items.map(\.id)).count == page.items.count else { throw TrainingError.invalidPaper }
|
||||
for question in page.items {
|
||||
guard (offset + 1...end).contains(question.order), !question.id.isEmpty,
|
||||
(2...6).contains(question.options.count), Set(question.options.map(\.id)).count == question.options.count,
|
||||
!questionCache.values.contains(where: { $0.id == question.id && $0.order != question.order }) else {
|
||||
throw TrainingError.invalidPaper
|
||||
}
|
||||
questionCache[question.order - 1] = question
|
||||
}
|
||||
}
|
||||
|
||||
private func fetchDraft(offset: Int, service: any TrainingDataServing) async throws {
|
||||
let page = try await service.draft(taskID: taskID, offset: offset, limit: pageSize)
|
||||
try await authorize()
|
||||
try applyMetadata(page)
|
||||
let requestedEnd = min(questionCount, offset + pageSize)
|
||||
let coveredEnd = page.nextOffset ?? requestedEnd
|
||||
guard page.offset == offset, coveredEnd > offset, coveredEnd <= requestedEnd,
|
||||
Set(page.items.map(\.questionID)).count == page.items.count,
|
||||
Set(page.items.map(\.order)).count == page.items.count else { throw TrainingError.invalidAnswers }
|
||||
for index in offset..<coveredEnd {
|
||||
if let question = questionCache[index] { answerCache[question.id] = [] }
|
||||
}
|
||||
for answer in page.items {
|
||||
guard (offset + 1...coveredEnd).contains(answer.order), !answer.questionID.isEmpty,
|
||||
Set(answer.selectedOptionIDs).count == answer.selectedOptionIDs.count else { throw TrainingError.invalidAnswers }
|
||||
if let question = questionCache[answer.order - 1] {
|
||||
guard question.id == answer.questionID,
|
||||
Set(answer.selectedOptionIDs).isSubset(of: Set(question.options.map(\.id))),
|
||||
question.type != .single || answer.selectedOptionIDs.count <= 1 else { throw TrainingError.invalidAnswers }
|
||||
}
|
||||
answerCache[answer.questionID] = Set(answer.selectedOptionIDs)
|
||||
}
|
||||
loadedDraftIndices.formUnion(offset..<coveredEnd)
|
||||
}
|
||||
|
||||
private func refreshDraft(service: any TrainingDataServing) async throws {
|
||||
needsDraftRefresh = true
|
||||
let metadata = try await service.draft(taskID: taskID, offset: 0, limit: 0)
|
||||
try await authorize()
|
||||
answerCache = [:]
|
||||
loadedDraftIndices = []
|
||||
try applyMetadata(metadata)
|
||||
try await loadCurrentPage(service: service)
|
||||
}
|
||||
|
||||
private func performMutation(service: any TrainingDataServing) async throws {
|
||||
guard let mutation = pendingMutation else { return }
|
||||
do {
|
||||
let confirmation: TrainingDraftConfirmation
|
||||
switch mutation {
|
||||
case .save(let request): confirmation = try await service.saveDraft(taskID: taskID, request: request)
|
||||
case .reset(let request): confirmation = try await service.resetDraft(taskID: taskID, request: request)
|
||||
}
|
||||
try await authorize()
|
||||
guard confirmation.draftRevision >= draftRevision, (0...questionCount).contains(confirmation.answeredCount) else {
|
||||
throw TrainingError.invalidAnswers
|
||||
}
|
||||
pendingMutation = nil
|
||||
draftRevision = confirmation.draftRevision
|
||||
switch mutation {
|
||||
case .reset:
|
||||
// 重置重试返回当前实况,不能根据成功响应把之后的新答案清空。
|
||||
currentIndex = 0
|
||||
try await refreshDraft(service: service)
|
||||
case .save(let request):
|
||||
for change in request.changes {
|
||||
answerCache[change.questionID] = Set(change.selectedOptionIDs)
|
||||
if let question = questionCache.values.first(where: { $0.id == change.questionID }) {
|
||||
if change.selectedOptionIDs.isEmpty { answeredQuestionOrders.remove(question.order) }
|
||||
else { answeredQuestionOrders.insert(question.order) }
|
||||
}
|
||||
}
|
||||
if answeredCount != confirmation.answeredCount { try await refreshDraft(service: service) }
|
||||
}
|
||||
} catch {
|
||||
if case TrainingRemoteError.draftRevisionConflict = error {
|
||||
pendingMutation = nil
|
||||
try? await refreshDraft(service: service)
|
||||
} else if let remote = error as? TrainingRemoteError, remote.code != nil {
|
||||
if case .idempotencyConflict = remote { /* 保留原请求,禁止换键覆盖。 */ }
|
||||
else {
|
||||
pendingMutation = nil
|
||||
if let latest = try? await service.progress(taskID: taskID) {
|
||||
try await authorize()
|
||||
progress = latest
|
||||
} else { progress = nil }
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private func recoverSubmission(service: any TrainingDataServing) async throws -> TrainingAttemptSummary? {
|
||||
guard let pending = pendingSubmission else { return nil }
|
||||
let page = try await service.attempts(taskID: taskID, submissionID: pending.request.submissionID, cursor: nil, limit: 1)
|
||||
try await authorize()
|
||||
guard page.items.count <= 1 else { throw TrainingError.invalidAnswers }
|
||||
if let attempt = page.items.first {
|
||||
return try finishSubmission(pending, attempt: attempt, serverTime: page.serverTime ?? attempt.submittedAt)
|
||||
}
|
||||
return try await sendSubmission(pending, service: service)
|
||||
}
|
||||
|
||||
private func sendSubmission(_ pending: TrainingPendingSubmission, service: any TrainingDataServing) async throws -> TrainingAttemptSummary? {
|
||||
do {
|
||||
let result = try await service.submit(taskID: taskID, request: pending.request)
|
||||
try await authorize()
|
||||
draftRevision = max(draftRevision, result.draftRevision)
|
||||
let attempt = try finishSubmission(pending, attempt: result.attempt, serverTime: result.serverTime)
|
||||
submittedResult = TrainingAttemptDetail(attempt: result.attempt, taskState: result.taskState, serverTime: result.serverTime)
|
||||
return attempt
|
||||
} catch {
|
||||
if let remote = error as? TrainingRemoteError, remote.code != nil {
|
||||
switch remote {
|
||||
case .idempotencyConflict, .forbidden, .accountInvalid:
|
||||
// 权限拒绝无法证明原请求未成功,保留恢复键。
|
||||
break
|
||||
default:
|
||||
try await authorize()
|
||||
try pendingStore.remove(pending)
|
||||
pendingSubmission = nil
|
||||
needsDraftRefresh = true
|
||||
if let latest = try? await service.progress(taskID: taskID) {
|
||||
try await authorize()
|
||||
progress = latest
|
||||
if latest.canStartExam { try? await refreshDraft(service: service) }
|
||||
}
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private func finishSubmission(_ pending: TrainingPendingSubmission, attempt: TrainingAttemptSummary, serverTime: Date) throws -> TrainingAttemptSummary {
|
||||
guard attempt.taskID == taskID, attempt.paperSnapshotID == pending.request.paperSnapshotID else { throw TrainingError.invalidAnswers }
|
||||
try pendingStore.remove(pending)
|
||||
pendingSubmission = nil
|
||||
submittedAttempt = attempt
|
||||
let state = TrainingTaskState(learnerStatus: attempt.passed ? .completed : .pendingExam,
|
||||
completedAt: attempt.passed ? attempt.submittedAt : nil, canRetry: false, blockReason: attempt.passed ? "completed" : nil)
|
||||
submittedResult = TrainingAttemptDetail(attempt: attempt, taskState: state, serverTime: serverTime)
|
||||
return attempt
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user