feat(training): 接入真实培训接口与学习答题恢复
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
import Foundation
|
||||
|
||||
/// 正式培训 API,显式在主 Actor 协调网络及登录上下文,不加载无关子资源。
|
||||
@MainActor
|
||||
final class TrainingAPI: TrainingDataServing {
|
||||
private let client: APIClient
|
||||
private let tokenOverride: String?
|
||||
private let eligible: Bool
|
||||
private let validateContext: (@MainActor () -> Bool)?
|
||||
private let prefix = "/api/app/training"
|
||||
|
||||
/// 注入网络客户端;正式页面通过工厂固定本次身份,测试可单独注入校验。
|
||||
init(client: APIClient, tokenOverride: String? = nil, eligible: Bool = true, validateContext: (@MainActor () -> Bool)? = nil) {
|
||||
self.client = client
|
||||
self.tokenOverride = tokenOverride
|
||||
self.eligible = eligible
|
||||
self.validateContext = validateContext
|
||||
}
|
||||
|
||||
/// 为一次页面会话建立固定凭证及身份校验的数据源。
|
||||
func scoped(token: String, eligible: Bool, validateContext: @escaping @MainActor () -> Bool) -> TrainingAPI {
|
||||
TrainingAPI(client: client, tokenOverride: token, eligible: eligible, validateContext: validateContext)
|
||||
}
|
||||
|
||||
/// GET /summary:读取本人统计。
|
||||
func summary() async throws -> TrainingSummary { try await read("/summary") }
|
||||
|
||||
/// GET /tasks:状态和关键词只影响本次摘要页。
|
||||
func tasks(status: TrainingLearnerStatus?, keyword: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingTaskSummary> {
|
||||
var query = cursorQuery(cursor, limit: limit, maximum: 50)
|
||||
if let status { query.append(item("learner_status", status.apiValue)) }
|
||||
if !keyword.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { query.append(item("keyword", keyword)) }
|
||||
return try await read("/tasks", query: query)
|
||||
}
|
||||
|
||||
/// GET /tasks/{id}:平铺任务规则,不读取正文或试卷。
|
||||
func task(id: String) async throws -> TrainingTaskDetail { try await read("/tasks/" + component(id)) }
|
||||
|
||||
/// GET /courses/{id}:快照访问带本人 task_id。
|
||||
func course(id: String, taskID: String) async throws -> TrainingCourseInfo {
|
||||
try await read("/courses/" + component(id), query: taskQuery(taskID))
|
||||
}
|
||||
|
||||
/// GET /courses/{id}/sections:只读取目录页。
|
||||
func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingSectionInfo> {
|
||||
try await read("/courses/" + component(courseID) + "/sections", query: taskQuery(taskID) + cursorQuery(cursor, limit: limit, maximum: 50))
|
||||
}
|
||||
|
||||
/// GET /courses/{id}/sections/{id}:只读取一个小节。
|
||||
func section(courseID: String, sectionID: String, taskID: String) async throws -> TrainingSectionContent {
|
||||
try await read("/courses/" + component(courseID) + "/sections/" + component(sectionID), query: taskQuery(taskID))
|
||||
}
|
||||
|
||||
/// GET /courses/{id}/attachments:只读取附件元信息页。
|
||||
func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttachmentInfo> {
|
||||
try await read("/courses/" + component(courseID) + "/attachments", query: taskQuery(taskID) + cursorQuery(cursor, limit: limit, maximum: 50))
|
||||
}
|
||||
|
||||
/// GET /courses/{id}/attachments/{id}:获取短时授权访问地址。
|
||||
func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink {
|
||||
try await read("/courses/" + component(courseID) + "/attachments/" + component(attachmentID), query: taskQuery(taskID))
|
||||
}
|
||||
|
||||
/// GET /tasks/{id}/progress:读取已保存进度及资格。
|
||||
func progress(taskID: String) async throws -> TrainingProgressSnapshot { try await read("/tasks/" + component(taskID) + "/progress") }
|
||||
|
||||
/// POST /tasks/{id}/study-sessions:幂等创建阅读会话。
|
||||
func startReading(taskID: String, requestID: String) async throws -> TrainingStudySession {
|
||||
try await write(.post, "/tasks/" + component(taskID) + "/study-sessions", body: ReadingStartBody(requestID: requestID))
|
||||
}
|
||||
|
||||
/// POST /study-sessions/{id}/heartbeat:确认当前会话读时,不自动生成新序号。
|
||||
func heartbeat(sessionID: String, sequence: Int, activeSecondsTotal: Int, final: Bool) async throws -> TrainingHeartbeatConfirmation {
|
||||
try await write(.post, "/study-sessions/" + component(sessionID) + "/heartbeat", body: HeartbeatBody(sequence: sequence, activeSecondsTotal: activeSecondsTotal, final: final))
|
||||
}
|
||||
|
||||
/// GET /papers/{id}:读取冻结计分规则。
|
||||
func paper(id: String, taskID: String) async throws -> TrainingPaperInfo {
|
||||
try await read("/papers/" + component(id), query: taskQuery(taskID))
|
||||
}
|
||||
|
||||
/// GET /papers/{id}/questions:按固定题位读取考前题目页。
|
||||
func questions(paperID: String, taskID: String, offset: Int, limit: Int) async throws -> TrainingQuestionPage {
|
||||
try await read("/papers/" + component(paperID) + "/questions", query: taskQuery(taskID) + offsetQuery(offset, limit: limit, maximum: 20))
|
||||
}
|
||||
|
||||
/// GET /tasks/{id}/draft:允许 limit=0 获取恢复位置和答题卡。
|
||||
func draft(taskID: String, offset: Int, limit: Int) async throws -> TrainingDraftPage {
|
||||
try await read("/tasks/" + component(taskID) + "/draft", query: offsetQuery(offset, limit: limit, maximum: 100, minimum: 0))
|
||||
}
|
||||
|
||||
/// PATCH /tasks/{id}/draft:只传变化题目的完整选择集合。
|
||||
func saveDraft(taskID: String, request: TrainingDraftSaveRequest) async throws -> TrainingDraftConfirmation {
|
||||
try await write(.patch, "/tasks/" + component(taskID) + "/draft", body: request)
|
||||
}
|
||||
|
||||
/// POST /tasks/{id}/draft/reset:返回当前草稿实况,调用者按版本同步。
|
||||
func resetDraft(taskID: String, request: TrainingDraftResetRequest) async throws -> TrainingDraftConfirmation {
|
||||
try await write(.post, "/tasks/" + component(taskID) + "/draft/reset", body: request)
|
||||
}
|
||||
|
||||
/// POST /tasks/{id}/submissions:消费已确认的草稿版本,不回传全部答案。
|
||||
func submit(taskID: String, request: TrainingSubmissionRequest) async throws -> TrainingSubmissionResult {
|
||||
try await write(.post, "/tasks/" + component(taskID) + "/submissions", body: request)
|
||||
}
|
||||
|
||||
/// GET /attempts:任务筛选和提交恢复复用成绩分页接口。
|
||||
func attempts(taskID: String?, submissionID: String?, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttemptSummary> {
|
||||
var query = cursorQuery(cursor, limit: limit, maximum: 50)
|
||||
if let taskID { query.append(item("task_id", taskID)) }
|
||||
if let submissionID { query.append(item("submission_id", submissionID)) }
|
||||
return try await read("/attempts", query: query)
|
||||
}
|
||||
|
||||
/// GET /attempts/{id}:单次成绩和最新重考资格。
|
||||
func attempt(id: String) async throws -> TrainingAttemptDetail { try await read("/attempts/" + component(id)) }
|
||||
|
||||
/// GET /attempts/{id}/reviews:单页最多十条,不自动下载全部解析。
|
||||
func reviews(attemptID: String, cursor: String?, limit: Int) async throws -> TrainingReviewPage {
|
||||
try await read("/attempts/" + component(attemptID) + "/reviews", query: cursorQuery(cursor, limit: limit, maximum: 10))
|
||||
}
|
||||
|
||||
private func read<Response: Decodable>(_ path: String, query: [URLQueryItem] = []) async throws -> Response {
|
||||
try await perform(APIRequest<Response>(method: .get, path: prefix + path, queryItems: query, logsPayload: false))
|
||||
}
|
||||
|
||||
private func write<Response: Decodable, Body: Encodable>(_ method: HTTPMethod, _ path: String, body: Body) async throws -> Response {
|
||||
try await perform(APIRequest<Response>(method: method, path: prefix + path, body: body, logsPayload: false))
|
||||
}
|
||||
|
||||
private func perform<Response: Decodable>(_ request: APIRequest<Response>) async throws -> Response {
|
||||
try checkContext()
|
||||
do {
|
||||
let response = try await client.send(request, tokenOverride: tokenOverride)
|
||||
try checkContext()
|
||||
return response
|
||||
} catch {
|
||||
try checkContext()
|
||||
throw TrainingRemoteError.map(error)
|
||||
}
|
||||
}
|
||||
|
||||
private func checkContext() throws {
|
||||
guard eligible else { throw TrainingRemoteError.accountInvalid("请切换到店铺账号后进入培训中心") }
|
||||
guard validateContext?() != false else { throw TrainingRemoteError.identityChanged }
|
||||
}
|
||||
|
||||
nonisolated private func item(_ name: String, _ value: String) -> URLQueryItem { URLQueryItem(name: name, value: value) }
|
||||
nonisolated private func taskQuery(_ id: String) -> [URLQueryItem] { [item("task_id", id)] }
|
||||
nonisolated private func cursorQuery(_ cursor: String?, limit: Int, maximum: Int) -> [URLQueryItem] {
|
||||
var query = [item("limit", String(min(max(limit, 1), maximum)))]
|
||||
if let cursor, !cursor.isEmpty { query.append(item("cursor", cursor)) }
|
||||
return query
|
||||
}
|
||||
nonisolated private func offsetQuery(_ offset: Int, limit: Int, maximum: Int, minimum: Int = 1) -> [URLQueryItem] {
|
||||
[item("offset", String(max(offset, 0))), item("limit", String(min(max(limit, minimum), maximum)))]
|
||||
}
|
||||
nonisolated private func component(_ id: String) -> String {
|
||||
id.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~"))) ?? id
|
||||
}
|
||||
|
||||
/// 阅读会话创建请求,幂等键由业务状态持久保留。
|
||||
private struct ReadingStartBody: Encodable {
|
||||
let requestID: String
|
||||
enum CodingKeys: String, CodingKey { case requestID = "request_id" }
|
||||
}
|
||||
|
||||
/// 会话心跳请求;累计读时为本会话范围。
|
||||
private struct HeartbeatBody: Encodable {
|
||||
let sequence: Int
|
||||
let activeSecondsTotal: Int
|
||||
let final: Bool
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case sequence, final
|
||||
case activeSecondsTotal = "active_seconds_total"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import Foundation
|
||||
|
||||
/// 正式培训数据源;各资源独立读取,不为页面拼接全量任务聚合。
|
||||
protocol TrainingDataServing: Sendable {
|
||||
/// 获取当前学员全局统计。
|
||||
func summary() async throws -> TrainingSummary
|
||||
/// 按状态和关键词读取任务摘要页。
|
||||
func tasks(status: TrainingLearnerStatus?, keyword: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingTaskSummary>
|
||||
/// 获取任务规则和快照引用。
|
||||
func task(id: String) async throws -> TrainingTaskDetail
|
||||
/// 获取课程元信息,附当前授权任务。
|
||||
func course(id: String, taskID: String) async throws -> TrainingCourseInfo
|
||||
/// 获取小节目录页。
|
||||
func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingSectionInfo>
|
||||
/// 读取一个小节的正式正文。
|
||||
func section(courseID: String, sectionID: String, taskID: String) async throws -> TrainingSectionContent
|
||||
/// 读取附件元信息页。
|
||||
func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttachmentInfo>
|
||||
/// 获取短期附件授权链接。
|
||||
func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink
|
||||
/// 刷新服务端已保存进度与操作资格。
|
||||
func progress(taskID: String) async throws -> TrainingProgressSnapshot
|
||||
/// 按幂等键建立阅读会话。
|
||||
func startReading(taskID: String, requestID: String) async throws -> TrainingStudySession
|
||||
/// 按会话序号确认有效读时;重试保持相同请求内容。
|
||||
func heartbeat(sessionID: String, sequence: Int, activeSecondsTotal: Int, final: Bool) async throws -> TrainingHeartbeatConfirmation
|
||||
/// 读取考试规则,不获取全部试题。
|
||||
func paper(id: String, taskID: String) async throws -> TrainingPaperInfo
|
||||
/// 按固定题位读取试题页。
|
||||
func questions(paperID: String, taskID: String, offset: Int, limit: Int) async throws -> TrainingQuestionPage
|
||||
/// 获取草稿元信息及当前题位答案;limit=0 只读取元信息。
|
||||
func draft(taskID: String, offset: Int, limit: Int) async throws -> TrainingDraftPage
|
||||
/// 串行增量保存本人选择。
|
||||
func saveDraft(taskID: String, request: TrainingDraftSaveRequest) async throws -> TrainingDraftConfirmation
|
||||
/// 用户确认重考后重置草稿;响应是当前实况而非恒定空草稿。
|
||||
func resetDraft(taskID: String, request: TrainingDraftResetRequest) async throws -> TrainingDraftConfirmation
|
||||
/// 消费已保存草稿版本并幂等交卷。
|
||||
func submit(taskID: String, request: TrainingSubmissionRequest) async throws -> TrainingSubmissionResult
|
||||
/// 分页读取成绩;taskID+submissionID 可恢复一次交卷结果。
|
||||
func attempts(taskID: String?, submissionID: String?, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttemptSummary>
|
||||
/// 读取一条成绩和最新重考资格。
|
||||
func attempt(id: String) async throws -> TrainingAttemptDetail
|
||||
/// 用户展开时读取解析页。
|
||||
func reviews(attemptID: String, cursor: String?, limit: Int) async throws -> TrainingReviewPage
|
||||
}
|
||||
|
||||
/// 培训稳定业务码及身份切换;保留服务器文案,恢复逻辑只依据枚举或 code。
|
||||
enum TrainingRemoteError: Error, LocalizedError, Equatable, Sendable {
|
||||
case accountInvalid(String), forbidden(String), notWritable(String), readingRequired(String)
|
||||
case sessionExpired(String), sessionConflict(String), draftRevisionConflict(String), idempotencyConflict(String)
|
||||
case answerInvalid(String), answerIncomplete(String), examNotAllowed(String), contentMissing(String)
|
||||
case attemptNotFound(String), paramInvalid(String), identityChanged
|
||||
|
||||
/// 返回稳定业务码,身份切换属于本地拒绝,没有服务端 code。
|
||||
var code: Int? {
|
||||
switch self {
|
||||
case .accountInvalid: 150100
|
||||
case .forbidden: 150101
|
||||
case .notWritable: 150102
|
||||
case .readingRequired: 150103
|
||||
case .sessionExpired: 150104
|
||||
case .sessionConflict: 150105
|
||||
case .draftRevisionConflict: 150106
|
||||
case .idempotencyConflict: 150107
|
||||
case .answerInvalid: 150108
|
||||
case .answerIncomplete: 150109
|
||||
case .examNotAllowed: 150110
|
||||
case .contentMissing: 150111
|
||||
case .attemptNotFound: 150112
|
||||
case .paramInvalid: 150113
|
||||
case .identityChanged: nil
|
||||
}
|
||||
}
|
||||
|
||||
/// 用于页面展示的错误文案,不参与错误分类。
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case let .accountInvalid(message), let .forbidden(message), let .notWritable(message), let .readingRequired(message),
|
||||
let .sessionExpired(message), let .sessionConflict(message), let .draftRevisionConflict(message),
|
||||
let .idempotencyConflict(message), let .answerInvalid(message), let .answerIncomplete(message),
|
||||
let .examNotAllowed(message), let .contentMissing(message), let .attemptNotFound(message), let .paramInvalid(message): message
|
||||
case .identityChanged: "学习账号或业务身份已切换,请重新进入培训中心"
|
||||
}
|
||||
}
|
||||
|
||||
/// 转换培训业务错误;网络和真正登录失效错误仍保留原类型。
|
||||
static func map(_ error: Error) -> Error {
|
||||
guard let apiError = error as? APIError,
|
||||
case let .serverCode(code, message) = apiError else { return error }
|
||||
switch code {
|
||||
case 150100: return Self.accountInvalid(message)
|
||||
case 150101: return Self.forbidden(message)
|
||||
case 150102: return Self.notWritable(message)
|
||||
case 150103: return Self.readingRequired(message)
|
||||
case 150104: return Self.sessionExpired(message)
|
||||
case 150105: return Self.sessionConflict(message)
|
||||
case 150106: return Self.draftRevisionConflict(message)
|
||||
case 150107: return Self.idempotencyConflict(message)
|
||||
case 150108: return Self.answerInvalid(message)
|
||||
case 150109: return Self.answerIncomplete(message)
|
||||
case 150110: return Self.examNotAllowed(message)
|
||||
case 150111: return Self.contentMissing(message)
|
||||
case 150112: return Self.attemptNotFound(message)
|
||||
case 150113: return Self.paramInvalid(message)
|
||||
default: return error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 生产数据源固定进入时的账号和业务上下文,拒绝切换身份后的迟到响应。
|
||||
enum TrainingRemoteServiceFactory {
|
||||
/// 当前店铺身份才可接入;Token 与业务范围固定在本次页面会话。
|
||||
@MainActor static func production() -> any TrainingDataServing {
|
||||
let session = AppStore.shared.session
|
||||
let token = session.token
|
||||
let scope = session.accountCachePrefix
|
||||
let scenicID = session.currentScenicId
|
||||
let storeID = session.currentStoreId
|
||||
let eligible = !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
&& session.accountType == .storeUser && !scope.isEmpty
|
||||
return NetworkServices.shared.trainingAPI.scoped(token: token, eligible: eligible, validateContext: {
|
||||
let current = AppStore.shared.session
|
||||
return current.isLoggedIn && current.accountType == .storeUser
|
||||
&& current.accountCachePrefix == scope && current.token == token
|
||||
&& current.currentScenicId == scenicID && current.currentStoreId == storeID
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import Foundation
|
||||
|
||||
/// 未确认交卷的原始请求及所属业务身份,供 App 重启后沿原键恢复。
|
||||
struct TrainingPendingSubmission: Codable, Equatable, Sendable {
|
||||
let taskID: String
|
||||
let request: TrainingSubmissionRequest
|
||||
let accountScope: String
|
||||
let scenicID: Int
|
||||
let storeID: Int
|
||||
|
||||
/// 固定本次提交的身份和请求,恢复时不读取新的草稿版本替换它。
|
||||
init(taskID: String, request: TrainingSubmissionRequest, context: TrainingContext) {
|
||||
self.taskID = taskID
|
||||
self.request = request
|
||||
accountScope = context.accountScope
|
||||
scenicID = context.scenicID
|
||||
storeID = context.storeID
|
||||
}
|
||||
|
||||
/// 本次交卷的持久化作用域,不包含 Token。
|
||||
var context: TrainingContext {
|
||||
TrainingContext(accountScope: accountScope, scenicID: scenicID, storeID: storeID)
|
||||
}
|
||||
}
|
||||
|
||||
/// 待恢复记录损坏时停止生成新提交,避免重复成绩。
|
||||
enum TrainingPendingSubmissionError: Error, LocalizedError, Equatable, Sendable {
|
||||
case invalidRecord, alreadyPending
|
||||
|
||||
/// 告知用户尚不能安全恢复本次提交。
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidRecord: "上次交卷状态暂无法确认,请联系工作人员核查成绩后重试"
|
||||
case .alreadyPending: "上次交卷尚未确认,请先恢复原提交结果"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 按账号、景区、店铺和任务隔离待确认交卷,支持注入独立 UserDefaults 测试。
|
||||
final class TrainingPendingSubmissionStore {
|
||||
private static let lock = NSRecursiveLock()
|
||||
private let defaults: UserDefaults
|
||||
|
||||
/// 使用指定的持久化域保存不含凭证的交卷请求。
|
||||
init(defaults: UserDefaults = .standard) { self.defaults = defaults }
|
||||
|
||||
/// 当前店铺登录身份;与正式数据源一致,不要求景区 ID 大于零。
|
||||
@MainActor static func currentContext() -> TrainingContext? {
|
||||
let session = AppStore.shared.session
|
||||
guard session.isLoggedIn, session.accountType == .storeUser, !session.accountCachePrefix.isEmpty else { return nil }
|
||||
return TrainingContext(accountScope: session.accountCachePrefix, scenicID: session.currentScenicId, storeID: session.currentStoreId)
|
||||
}
|
||||
|
||||
/// 读取当前作用域记录,损坏记录不当作首次交卷处理。
|
||||
func load(taskID: String, context: TrainingContext) throws -> TrainingPendingSubmission? {
|
||||
Self.lock.lock()
|
||||
defer { Self.lock.unlock() }
|
||||
guard let data = defaults.data(forKey: key(taskID: taskID, context: context)) else { return nil }
|
||||
guard let value = try? JSONDecoder().decode(TrainingPendingSubmission.self, from: data),
|
||||
value.taskID == taskID, value.context == context,
|
||||
!value.request.submissionID.isEmpty, !value.request.paperSnapshotID.isEmpty,
|
||||
value.request.draftRevision > 0 else { throw TrainingPendingSubmissionError.invalidRecord }
|
||||
return value
|
||||
}
|
||||
|
||||
/// 在发起网络提交前保存原始请求;不得用当前版本覆盖待恢复版本。
|
||||
func save(_ value: TrainingPendingSubmission) throws {
|
||||
Self.lock.lock()
|
||||
defer { Self.lock.unlock() }
|
||||
if let existing = try load(taskID: value.taskID, context: value.context), existing != value {
|
||||
throw TrainingPendingSubmissionError.alreadyPending
|
||||
}
|
||||
let storageKey = key(taskID: value.taskID, context: value.context)
|
||||
defaults.set(try JSONEncoder().encode(value), forKey: storageKey)
|
||||
}
|
||||
|
||||
/// 只移除仍对应这次提交的记录,避免迟到响应删除后续待恢复请求。
|
||||
func remove(_ value: TrainingPendingSubmission) throws {
|
||||
Self.lock.lock()
|
||||
defer { Self.lock.unlock() }
|
||||
guard try load(taskID: value.taskID, context: value.context) == value else { return }
|
||||
defaults.removeObject(forKey: key(taskID: value.taskID, context: value.context))
|
||||
}
|
||||
|
||||
private func key(taskID: String, context: TrainingContext) -> String {
|
||||
let scope = Data(context.accountScope.utf8).map { String(format: "%02x", $0) }.joined()
|
||||
let task = Data(taskID.utf8).map { String(format: "%02x", $0) }.joined()
|
||||
return "training-pending-submission:v1:\(scope):scenic_\(context.scenicID):store_\(context.storeID):task_\(task)"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user