From 27be1f30ede9f54cc54f05c59c27316cf36a8ffc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=89=E7=A7=8B?= <497055328@qq.com> Date: Tue, 20 Oct 2026 14:04:25 +0800 Subject: [PATCH] =?UTF-8?q?feat(training):=20=E6=96=B0=E5=A2=9E=E5=B7=B2?= =?UTF-8?q?=E7=BB=93=E6=9D=9F=E7=AD=9B=E9=80=89=E5=B9=B6=E7=B2=BE=E7=AE=80?= =?UTF-8?q?=E8=AF=BE=E7=A8=8B=E5=B1=95=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增已结束任务筛选与只读回顾资格,保留搜索和游标分页。移除任务小节数量及课程附件文件名、切换入口,并更新接口和界面回归测试。 --- .../Training/Models/TrainingAPIModels.swift | 3 +- .../Training/Models/TrainingModels.swift | 6 +- .../TrainingRemoteExamViewModel.swift | 8 +-- .../TrainingRemoteReadingViewModel.swift | 5 +- .../TrainingCenterViewController.swift | 30 +++++++--- .../TrainingCourseViewController.swift | 52 ++++------------ .../TrainingResultViewController.swift | 4 +- suixinkan/UI/Training/TrainingUI.swift | 15 ++--- suixinkanTests/TrainingAPITests.swift | 53 +++++++++++++++++ suixinkanTests/TrainingDataTestSupport.swift | 22 +++++-- suixinkanTests/TrainingRemoteExamTests.swift | 6 +- suixinkanTests/TrainingRemoteListTests.swift | 19 ++++-- .../TrainingRemoteReadingTests.swift | 22 +++++++ suixinkanTests/TrainingUIRenderingTests.swift | 59 +++++++++++++++++++ 14 files changed, 227 insertions(+), 77 deletions(-) diff --git a/suixinkan/Features/Training/Models/TrainingAPIModels.swift b/suixinkan/Features/Training/Models/TrainingAPIModels.swift index bebf7aa..48a4556 100644 --- a/suixinkan/Features/Training/Models/TrainingAPIModels.swift +++ b/suixinkan/Features/Training/Models/TrainingAPIModels.swift @@ -79,6 +79,7 @@ extension TrainingLearnerStatus: Codable { switch try container.decode(String.self) { case "pending": self = .pendingExam case "completed": self = .completed + case "ended": self = .ended default: throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unknown training learner status") } } @@ -88,7 +89,7 @@ extension TrainingLearnerStatus: Codable { try container.encode(apiValue) } /// 查询参数使用的正式状态值。 - var apiValue: String { self == .completed ? "completed" : "pending" } + var apiValue: String { switch self { case .pendingExam: "pending"; case .completed: "completed"; case .ended: "ended" } } } /// 游标分页;小节、附件、任务和成绩复用相同分页边界。 diff --git a/suixinkan/Features/Training/Models/TrainingModels.swift b/suixinkan/Features/Training/Models/TrainingModels.swift index fea04ff..00e0e0c 100644 --- a/suixinkan/Features/Training/Models/TrainingModels.swift +++ b/suixinkan/Features/Training/Models/TrainingModels.swift @@ -6,12 +6,12 @@ enum TrainingMode: String, Codable, Sendable { case study, exam } /// 任务发布状态;关闭后只允许回顾。 enum TrainingTaskStatus: String, Codable, Sendable { case published, closed } -/// 学员列表统一展示的两种状态。 +/// 学员任务列表的待办、完成与结束状态。 enum TrainingLearnerStatus: String, CaseIterable, Sendable { - case pendingExam, completed + case pendingExam, completed, ended /// 面向学员的状态名称。 - var title: String { self == .completed ? "已完成" : "待考试" } + var title: String { switch self { case .pendingExam: "待考试"; case .completed: "已完成"; case .ended: "已结束" } } } /// 单选和多选题型。 diff --git a/suixinkan/Features/Training/ViewModels/TrainingRemoteExamViewModel.swift b/suixinkan/Features/Training/ViewModels/TrainingRemoteExamViewModel.swift index c560bb9..4031d47 100644 --- a/suixinkan/Features/Training/ViewModels/TrainingRemoteExamViewModel.swift +++ b/suixinkan/Features/Training/ViewModels/TrainingRemoteExamViewModel.swift @@ -122,12 +122,12 @@ final class TrainingRemoteExamViewModel { var canRetryCurrentPage: Bool { !isBusy && identityIsValid && !hasPendingSubmission && !isResetPending && !recoveryStorageFailed && !shouldReturnToCenter && submittedAttempt == nil && paper != nil && !isCurrentPageReady - && progress?.canStartExam == true && progress?.learnerStatus != .completed + && progress?.canStartExam == true && progress?.learnerStatus == .pendingExam } /// 权威资格及当前页就绪时可编辑,后台保存不会阻断本机选择。 var canEdit: Bool { !isBusy && identityIsValid && !hasPendingSubmission && !isResetPending && !needsDraftRefresh && !recoveryStorageFailed - && submittedAttempt == nil && progress?.canStartExam == true && progress?.learnerStatus != .completed + && submittedAttempt == nil && progress?.canStartExam == true && progress?.learnerStatus == .pendingExam && !shouldReturnToCenter && paper != nil && isCurrentPageReady } @@ -420,8 +420,8 @@ final class TrainingRemoteExamViewModel { 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, + guard task?.mode == .exam, task?.learnerStatus == .pendingExam, + progress?.learnerStatus == .pendingExam, progress?.completedAt == nil, progress?.canStartExam == true, progress?.readingCompleted == true else { throw TrainingRemoteError.examNotAllowed("当前任务暂不能考试,请返回课程确认学习进度和任务状态") } diff --git a/suixinkan/Features/Training/ViewModels/TrainingRemoteReadingViewModel.swift b/suixinkan/Features/Training/ViewModels/TrainingRemoteReadingViewModel.swift index bcf8d24..2ac9056 100644 --- a/suixinkan/Features/Training/ViewModels/TrainingRemoteReadingViewModel.swift +++ b/suixinkan/Features/Training/ViewModels/TrainingRemoteReadingViewModel.swift @@ -98,7 +98,10 @@ final class TrainingRemoteReadingViewModel { } /// 当前后端是否允许继续有效学习,完成或只读任务不建立新会话。 - var canStudy: Bool { progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated } + var canStudy: Bool { + task?.summary.learnerStatus == .pendingExam && progress?.learnerStatus == .pendingExam + && progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated + } /// 首次只读课程元信息、附件第一页与进度,并为首个附件授权;不请求小节标题或 HTML。 func load() async { diff --git a/suixinkan/UI/Training/TrainingCenterViewController.swift b/suixinkan/UI/Training/TrainingCenterViewController.swift index e7eea64..2df2fe0 100644 --- a/suixinkan/UI/Training/TrainingCenterViewController.swift +++ b/suixinkan/UI/Training/TrainingCenterViewController.swift @@ -100,9 +100,14 @@ final class TrainingCenterViewController: TrainingBaseViewController { body.addArrangedSubview(heading) filters.distribution = .fillEqually filters.spacing = 9 - for state in TrainingLearnerStatus.allCases { + for (index, state) in TrainingLearnerStatus.allCases.enumerated() { let button = TrainingUI.button(state.title, secondary: true) - button.tag = state == .pendingExam ? 0 : 1 + var configuration = button.configuration + configuration?.contentInsets = NSDirectionalEdgeInsets(top: 12, leading: 6, bottom: 12, trailing: 6) + configuration?.titleAlignment = .center + configuration?.titleLineBreakMode = .byWordWrapping + button.configuration = configuration + button.tag = index button.accessibilityIdentifier = "training.filter.\(button.tag)" button.addTarget(self, action: #selector(filterTapped(_:)), for: .touchUpInside) filterButtons.append(button) @@ -231,11 +236,18 @@ final class TrainingCenterViewController: TrainingBaseViewController { filters.isHidden = viewModel.tab != .tasks searchField.isHidden = viewModel.tab != .tasks for (index, button) in filterButtons.enumerated() { + let state = TrainingLearnerStatus.allCases[index] + let selected = state == viewModel.filter 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 + configuration?.title = switch state { + case .pendingExam: "待考试 \(viewModel.pendingCount)" + case .completed: "已完成 \(viewModel.completedCount)" + case .ended: state.title + } + configuration?.background.backgroundColor = selected ? TrainingUI.primary.withAlphaComponent(0.09) : .white + configuration?.baseForegroundColor = selected ? TrainingUI.primary : TrainingUI.muted button.configuration = configuration + button.accessibilityTraits = selected ? [.button, .selected] : .button } for (index, button) in tabButtons.enumerated() { var configuration = button.configuration @@ -316,7 +328,11 @@ final class TrainingCenterViewController: TrainingBaseViewController { } } @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; reloadTapped() } + @objc private func filterTapped(_ button: UIButton) { + guard TrainingLearnerStatus.allCases.indices.contains(button.tag) else { return } + viewModel.filter = TrainingLearnerStatus.allCases[button.tag] + reloadTapped() + } @objc private func searchChanged() { viewModel.setKeyword(searchField.text ?? "") reloadTask?.cancel() @@ -351,7 +367,7 @@ final class TrainingCenterViewController: TrainingBaseViewController { @objc private func viewAllTapped() { viewModel.filter = .pendingExam; selectTab(.tasks) } private func openTask(_ task: TrainingTaskSummary, directAction: Bool) { - let controller: UIViewController = directAction && task.learning.canStartExam ? TrainingExamViewController(taskID: task.id, service: service) : TrainingCourseViewController(taskID: task.id, service: service) + let controller: UIViewController = directAction && task.learnerStatus == .pendingExam && task.learning.canStartExam ? TrainingExamViewController(taskID: task.id, service: service) : TrainingCourseViewController(taskID: task.id, service: service) navigationController?.pushViewController(controller, animated: true) } } diff --git a/suixinkan/UI/Training/TrainingCourseViewController.swift b/suixinkan/UI/Training/TrainingCourseViewController.swift index bdc705f..ef6eac5 100644 --- a/suixinkan/UI/Training/TrainingCourseViewController.swift +++ b/suixinkan/UI/Training/TrainingCourseViewController.swift @@ -16,7 +16,6 @@ final class TrainingCourseViewController: TrainingBaseViewController { private let courseNameLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted) private let examInfoLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted) private let introductionLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted) - private let attachmentButton = TrainingUI.button("", plain: true) private let previewView = TrainingDocumentPreviewView() private var previewHeightConstraint: Constraint? private var localDocument: TrainingLocalDocument? @@ -84,12 +83,7 @@ final class TrainingCourseViewController: TrainingBaseViewController { courseNameLabel.accessibilityIdentifier = "training.reading.courseName" examInfoLabel.accessibilityIdentifier = "training.reading.examInfo" introductionLabel.accessibilityIdentifier = "training.reading.introduction" - attachmentButton.contentHorizontalAlignment = .leading - attachmentButton.accessibilityIdentifier = "training.reading.documentPicker" - attachmentButton.showsMenuAsPrimaryAction = true - attachmentButton.isHidden = true contentStack.addArrangedSubview(metadataStack) - contentStack.addArrangedSubview(attachmentButton) contentStack.addArrangedSubview(previewView) stepView.isHidden = true bottomStack.axis = .vertical @@ -289,37 +283,6 @@ final class TrainingCourseViewController: TrainingBaseViewController { examInfoLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格" : "仅学习" introductionLabel.text = course.introduction introductionLabel.isHidden = course.introduction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - attachmentButton.isHidden = viewModel.currentAttachment == nil - var configuration = attachmentButton.configuration - configuration?.title = viewModel.currentAttachment?.name - let canSwitch = viewModel.attachments.count > 1 || viewModel.hasMoreAttachments - configuration?.image = canSwitch ? UIImage(systemName: "chevron.down") : nil - configuration?.imagePlacement = .trailing - configuration?.imagePadding = 8 - configuration?.contentInsets = .zero - configuration?.titleLineBreakMode = .byWordWrapping - attachmentButton.configuration = configuration - attachmentButton.isUserInteractionEnabled = canSwitch && userRequestID == nil - var actions = viewModel.attachments.map { attachment in - UIAction(title: attachment.name, state: attachment.id == viewModel.currentAttachmentID ? .on : .off) { [weak self] _ in - guard attachment.id != self?.viewModel.currentAttachmentID else { return } - self?.selectAttachment(attachment.id) - } - } - if viewModel.hasMoreAttachments { - actions.append(UIAction(title: "加载更多附件") { [weak self] _ in self?.loadMoreAttachments() }) - } - attachmentButton.menu = UIMenu(children: actions) - } - - private func loadMoreAttachments() { - guard let request = beginUserRequest(showsLoading: true) else { return } - Task { @MainActor [weak self] in - guard let self else { return } - await performUserRequest(request) { await self.viewModel.loadAttachments(loadMore: true) } - applyMetadata() - if let message = viewModel.attachmentListErrorMessage { showToast(message) } - } } private func applyState() { @@ -330,7 +293,6 @@ final class TrainingCourseViewController: TrainingBaseViewController { } let canInteract = userRequestID == nil actionButton.isUserInteractionEnabled = canInteract - attachmentButton.isUserInteractionEnabled = canInteract && (viewModel.attachments.count > 1 || viewModel.hasMoreAttachments) guard canInteract else { return } if contentLoadFailed || viewModel.attachmentErrorMessage != nil || viewModel.task == nil { noticeLabel.text = viewModel.errorMessage ?? "正在加载课程…" @@ -344,9 +306,18 @@ final class TrainingCourseViewController: TrainingBaseViewController { actionButton.isEnabled = true return } + if viewModel.progress?.learnerStatus == .ended { + noticeLabel.text = "任务已结束,仅可回顾课程内容" + setActionTitle("返回培训中心") + actionButton.isEnabled = true + readingTimer?.invalidate() + readingTimer = nil + return + } if let progress = viewModel.progress, progress.readingCompleted { noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成" - if viewModel.task?.summary.mode == .exam && progress.canStartExam { setActionTitle("开始考试") } + if viewModel.task?.summary.mode == .exam && viewModel.task?.summary.learnerStatus == .pendingExam + && progress.learnerStatus == .pendingExam && progress.canStartExam { setActionTitle("开始考试") } else { setActionTitle("返回培训中心") } actionButton.isEnabled = true readingTimer?.invalidate() @@ -487,7 +458,8 @@ final class TrainingCourseViewController: TrainingBaseViewController { } else if viewModel.attachments.isEmpty { returnToCenter() } else if let progress = viewModel.progress, progress.readingCompleted { pauseReading() - if viewModel.task?.summary.mode == .exam && progress.canStartExam { + if viewModel.task?.summary.mode == .exam && viewModel.task?.summary.learnerStatus == .pendingExam + && progress.learnerStatus == .pendingExam && progress.canStartExam { navigationController?.pushViewController(TrainingExamViewController(taskID: taskID, service: service), animated: true) } else { returnToCenter() } } else if !viewModel.canStudy { returnToCenter() } diff --git a/suixinkan/UI/Training/TrainingResultViewController.swift b/suixinkan/UI/Training/TrainingResultViewController.swift index 3201640..d6805f1 100644 --- a/suixinkan/UI/Training/TrainingResultViewController.swift +++ b/suixinkan/UI/Training/TrainingResultViewController.swift @@ -239,7 +239,7 @@ final class TrainingResultViewController: TrainingBaseViewController { contentStack.addArrangedSubview(more) } } - let canRetry = !attempt.passed && detail.taskState.canRetry + let canRetry = !attempt.passed && detail.taskState.learnerStatus == .pendingExam && detail.taskState.canRetry contentStack.addArrangedSubview(TrainingUI.text(canRetry ? "截止前可不限次数重考,每次成绩都会保留。" : "本次记录只读,可回顾课程内容和答案解析。", size: 12, color: TrainingUI.muted)) setActionTitle(canRetry ? "再考一次" : "完成,返回培训中心") } @@ -294,7 +294,7 @@ final class TrainingResultViewController: TrainingBaseViewController { if loadFailed { loadResult(); return } guard let detail = viewModel.detail, let navigationController else { return } finishCurrentRequestBeforeNavigation() - if !detail.attempt.passed, detail.taskState.canRetry { + if !detail.attempt.passed, detail.taskState.learnerStatus == .pendingExam, detail.taskState.canRetry { 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) diff --git a/suixinkan/UI/Training/TrainingUI.swift b/suixinkan/UI/Training/TrainingUI.swift index d87c18d..b535516 100644 --- a/suixinkan/UI/Training/TrainingUI.swift +++ b/suixinkan/UI/Training/TrainingUI.swift @@ -121,7 +121,7 @@ enum TrainingUI { } } -/// 任务卡显示截止、课程小节、提示、进度条和对应的操作入口。 +/// 任务卡显示截止、考试信息、提示、进度条和对应的操作入口。 @MainActor final class TrainingTaskCell: UITableViewCell { static let reuseIdentifier = "TrainingTaskCell" @@ -188,7 +188,7 @@ final class TrainingTaskCell: UITableViewCell { 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) 节" + metaLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.questions.count) 题 · \(task.passScore) 分及格" : "仅学习" hintLabel.text = presentation.hint progressView.progress = Float(presentation.progressPercent) / 100 progressLabel.text = "学习进度 \(presentation.progressPercent)%" @@ -204,19 +204,20 @@ final class TrainingTaskCell: UITableViewCell { titleLabel.text = task.title deadlineLabel.text = task.endAt.map { "截止时间:\(TrainingUI.date($0))" } ?? "未设置截止时间" statusLabel.text = task.learnerStatus.title - statusLabel.textColor = task.learnerStatus == .completed ? TrainingUI.success : TrainingUI.primary + statusLabel.textColor = switch task.learnerStatus { case .pendingExam: TrainingUI.primary; case .completed: TrainingUI.success; case .ended: TrainingUI.muted } let publisher = task.publisherName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" publisherLabel.text = "发布人:\(publisher.isEmpty ? "未记录" : publisher)" - metaLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.sectionCount) 节 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格" : "仅学习 · \(task.sectionCount) 节" + metaLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格" : "仅学习" let completed = task.learnerStatus == .completed - hintLabel.text = completed ? "已完成本次学习任务" : task.learning.canStartExam ? "课程已学完,可以开始考试" : task.learning.canStudy ? "请阅读课程,完成学习要求" : "任务暂不可提交,可回顾课程内容" + let ended = task.learnerStatus == .ended + hintLabel.text = ended ? "任务已结束,仅可回顾课程内容" : completed ? "已完成本次学习任务" : task.learning.canStartExam ? "课程已学完,可以开始考试" : task.learning.canStudy ? "请阅读课程,完成学习要求" : "任务暂不可提交,可回顾课程内容" let progress = min(100, max(0, task.learning.progressPercent)) progressView.progress = Float(progress) / 100 progressLabel.text = "学习进度 \(progress)%" var configuration = actionButton.configuration - configuration?.title = completed ? "回顾学习" : task.learning.canStartExam ? (task.learning.hasDraft ? "继续答题" : "开始考试") : task.learning.canStudy ? "去学习" : "查看课程" + configuration?.title = ended || completed ? "回顾学习" : task.learning.canStartExam ? (task.learning.hasDraft ? "继续答题" : "开始考试") : task.learning.canStudy ? "去学习" : "查看课程" actionButton.configuration = configuration - actionButton.isEnabled = task.learning.canViewCourse || task.learning.canStartExam + actionButton.isEnabled = task.learning.canViewCourse || (!ended && task.learning.canStartExam) actionButton.accessibilityIdentifier = "training.task.action.\(task.id)" footer.axis = traitCollection.preferredContentSizeCategory.isAccessibilityCategory ? .vertical : .horizontal } diff --git a/suixinkanTests/TrainingAPITests.swift b/suixinkanTests/TrainingAPITests.swift index 7d06c8e..e399b94 100644 --- a/suixinkanTests/TrainingAPITests.swift +++ b/suixinkanTests/TrainingAPITests.swift @@ -44,6 +44,59 @@ final class TrainingAPITests: XCTestCase { XCTAssertEqual(session.requests[0].value(forHTTPHeaderField: "X-OS-TYPE"), "iOS") } + func testEndedTaskFilterAndReadOnlyResourcesDecodeServerState() async throws { + var endedFlags = flagsJSON + endedFlags.merge(["can_study": false, "can_start_exam": false, "block_reason": "ended"]) { _, new in new } + var endedTask = taskJSON + endedTask.merge(["task_status": "closed", "learner_status": "ended", "learning": endedFlags]) { _, new in new } + var endedDetail = endedTask + endedDetail.merge(["required_reading_seconds": 20, "reading_rule": "course_duration", "scoring": NSNull(), "server_time": dateText]) { _, new in new } + var endedProgress = progressJSON + endedProgress.merge(endedFlags) { _, new in new } + endedProgress["learner_status"] = "ended" + let taskState: [String: Any] = ["learner_status": "ended", "completed_at": dateText, "can_retry": false, "block_reason": "ended"] + let session = MockURLSession(responses: [ + try envelope(["items": [endedTask], "next_cursor": NSNull(), "has_more": false, "server_time": dateText]), + try envelope(endedDetail), + try envelope(endedProgress), + try envelope(["attempt": attemptJSON, "task_state": taskState, "server_time": dateText]), + ]) + let api = TrainingAPI(client: APIClient(environment: .testing, session: session)) + + let page = try await api.tasks(status: .ended, keyword: "规范", cursor: nil, limit: 20) + let task = try await api.task(id: "task_101") + let progress = try await api.progress(taskID: "task_101") + let attempt = try await api.attempt(id: "attempt_12") + + let summary = try XCTUnwrap(page.items.first) + for item in [summary, task.summary] { + XCTAssertEqual(item.learnerStatus, .ended) + XCTAssertEqual(item.taskStatus, .closed) + XCTAssertTrue(item.learning.canViewCourse) + XCTAssertFalse(item.learning.canStudy) + XCTAssertFalse(item.learning.canStartExam) + XCTAssertEqual(item.learning.blockReason, "ended") + } + XCTAssertEqual(progress.learnerStatus, .ended) + XCTAssertTrue(progress.canViewCourse) + XCTAssertFalse(progress.canStudy) + XCTAssertFalse(progress.canStartExam) + XCTAssertFalse(progress.canRetry) + XCTAssertEqual(progress.blockReason, "ended") + XCTAssertEqual(attempt.taskState.learnerStatus, .ended) + XCTAssertNotNil(attempt.taskState.completedAt, "已结束状态仍保留此前完成记录") + XCTAssertFalse(attempt.taskState.canRetry) + XCTAssertEqual(attempt.taskState.blockReason, "ended") + XCTAssertEqual(try query(session.requests[0]), ["learner_status": "ended", "keyword": "规范", "limit": "20"]) + XCTAssertEqual(session.requests.map { $0.url?.path }, [ + "/api/app/training/tasks", "/api/app/training/tasks/task_101", + "/api/app/training/tasks/task_101/progress", "/api/app/training/attempts/attempt_12", + ]) + XCTAssertTrue(session.requests.allSatisfy { $0.httpMethod == "GET" }) + let encoded = try JSONEncoder().encode(TrainingLearnerStatus.ended) + XCTAssertEqual(try JSONDecoder().decode(String.self, from: encoded), "ended") + } + func testCourseResourcesCarryTaskAuthorizationAndDoNotAggregate() async throws { let session = MockURLSession(responses: [ try envelope(["course_snapshot_id": "cs_3", "title": "规范", "introduction": "简介", "section_count": 1, "attachment_count": 1]), diff --git a/suixinkanTests/TrainingDataTestSupport.swift b/suixinkanTests/TrainingDataTestSupport.swift index 6c5c9cb..0f17db3 100644 --- a/suixinkanTests/TrainingDataTestSupport.swift +++ b/suixinkanTests/TrainingDataTestSupport.swift @@ -9,16 +9,30 @@ enum TrainingRemoteFixtures { TrainingQuestionItem(id: "q\(order)", order: order, type: .single, stem: "培训题目 \(order)", options: [TrainingQuestionOption(id: "A", text: "正确选择"), TrainingQuestionOption(id: "B", text: "另一选择")]) } /// 不含正文和答案的任务摘要。 - static func task(id: String = "task_1", title: String = "一线服务规范学习", questionCount: Int = 30, readingCompleted: Bool = true) -> TrainingTaskSummary { - TrainingTaskSummary(id: id, title: title, publisherName: "培训负责人", mode: .exam, taskStatus: .published, learnerStatus: .pendingExam, startAt: nil, endAt: nil, courseSnapshotID: "course_1", courseTitle: "景区服务规范", paperSnapshotID: "paper_1", sectionCount: 2, questionCount: questionCount, passScore: 80, learning: TrainingLearningFlags(progressPercent: readingCompleted ? 100 : 0, readingCompleted: readingCompleted, hasDraft: false, canViewCourse: true, canStudy: !readingCompleted, canStartExam: readingCompleted, blockReason: readingCompleted ? nil : "reading_required")) + static func task(id: String = "task_1", title: String = "一线服务规范学习", questionCount: Int = 30, readingCompleted: Bool = true, learnerStatus: TrainingLearnerStatus = .pendingExam) -> TrainingTaskSummary { + TrainingTaskSummary(id: id, title: title, publisherName: "培训负责人", mode: .exam, + taskStatus: learnerStatus == .ended ? .closed : .published, learnerStatus: learnerStatus, + startAt: nil, endAt: nil, courseSnapshotID: "course_1", courseTitle: "景区服务规范", paperSnapshotID: "paper_1", + sectionCount: 2, questionCount: questionCount, passScore: 80, + learning: TrainingLearningFlags(progressPercent: readingCompleted ? 100 : 0, readingCompleted: readingCompleted, + hasDraft: false, canViewCourse: true, canStudy: learnerStatus == .pendingExam && !readingCompleted, + canStartExam: learnerStatus == .pendingExam && readingCompleted, + blockReason: learnerStatus == .ended ? "ended" : readingCompleted ? nil : "reading_required")) } /// 轻量任务详情。 static func detail(questionCount: Int = 30, readingCompleted: Bool = true) -> TrainingTaskDetail { TrainingTaskDetail(summary: task(questionCount: questionCount, readingCompleted: readingCompleted), requiredReadingSeconds: 20, readingRule: "course_duration", scoring: "equal-percentage-v1", serverTime: now) } /// 服务端确认读时与资格。 - static func progress(seconds: Int = 20, completed: Bool = false) -> TrainingProgressSnapshot { - TrainingProgressSnapshot(taskID: "task_1", readingSeconds: seconds, requiredReadingSeconds: 20, completedSectionCount: seconds >= 20 ? 2 : 0, sectionCount: 2, progressPercent: seconds >= 20 ? 100 : 0, readingCompleted: seconds >= 20, learnerStatus: completed ? .completed : .pendingExam, completedAt: completed ? now : nil, hasDraft: false, canViewCourse: true, canStudy: seconds < 20 && !completed, canStartExam: seconds >= 20 && !completed, canRetry: !completed, blockReason: completed ? "completed" : seconds < 20 ? "reading_required" : nil, serverTime: now) + static func progress(seconds: Int = 20, completed: Bool = false, learnerStatus: TrainingLearnerStatus? = nil) -> TrainingProgressSnapshot { + let status = learnerStatus ?? (completed ? .completed : .pendingExam) + return TrainingProgressSnapshot(taskID: "task_1", readingSeconds: seconds, requiredReadingSeconds: 20, + completedSectionCount: seconds >= 20 ? 2 : 0, sectionCount: 2, progressPercent: seconds >= 20 ? 100 : 0, + readingCompleted: seconds >= 20, learnerStatus: status, completedAt: completed ? now : nil, hasDraft: false, + canViewCourse: true, canStudy: seconds < 20 && status == .pendingExam, + canStartExam: seconds >= 20 && status == .pendingExam, canRetry: status == .pendingExam, + blockReason: status == .ended ? "ended" : completed ? "completed" : seconds < 20 ? "reading_required" : nil, + serverTime: now) } /// 轻量课程文档,默认使用可由本地替身稳定预览的纯文本。 static func attachment(id: String = "file_1", name: String = "培训资料.txt", mimeType: String = "text/plain") -> TrainingAttachmentInfo { diff --git a/suixinkanTests/TrainingRemoteExamTests.swift b/suixinkanTests/TrainingRemoteExamTests.swift index 6c937d2..6f682c4 100644 --- a/suixinkanTests/TrainingRemoteExamTests.swift +++ b/suixinkanTests/TrainingRemoteExamTests.swift @@ -378,12 +378,12 @@ struct TrainingRemoteExamTests { #expect(try store.load(taskID: "task_1", context: context) == pending) } - @Test("服务端已完成资格阻止读取试卷和新的交卷") - func completedGatePreventsNewSubmission() async throws { + @Test("服务端已完成或已结束资格阻止读取试卷和新的交卷", arguments: [TrainingLearnerStatus.completed, .ended]) + func completedGatePreventsNewSubmission(status: TrainingLearnerStatus) async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } var configuration = TrainingDataStub.Configuration() - configuration.progressHandler = { _ in TrainingRemoteFixtures.progress(completed: true) } + configuration.progressHandler = { _ in TrainingRemoteFixtures.progress(completed: status == .completed, learnerStatus: status) } let source = TrainingDataStub(configuration: configuration) let model = makeModel(defaults: domain.defaults) await model.load(service: source) diff --git a/suixinkanTests/TrainingRemoteListTests.swift b/suixinkanTests/TrainingRemoteListTests.swift index 1985e1e..25497aa 100644 --- a/suixinkanTests/TrainingRemoteListTests.swift +++ b/suixinkanTests/TrainingRemoteListTests.swift @@ -8,6 +8,14 @@ struct TrainingRemoteListTests { @Test("首页只请求概览与三条任务摘要") func homeUsesSmallResources() async { let source = TrainingDataStub() + await source.configure { + $0.tasksHandler = { status, _, cursor, limit in + #expect(status == .pendingExam) + #expect(cursor == nil) + #expect(limit == 3) + return TrainingCursorPage(items: [TrainingRemoteFixtures.task()], nextCursor: nil, hasMore: false, serverTime: nil) + } + } let model = TrainingRemoteCenterViewModel() await model.load(service: source) let calls = await source.calls @@ -17,25 +25,26 @@ struct TrainingRemoteListTests { #expect(model.latestScore == "—") } - @Test("任务筛选传给服务端,用户翻页才消费游标") - func serverFilteringAndPagination() async { + @Test("任务筛选传给服务端,用户翻页才消费游标", arguments: [TrainingLearnerStatus.completed, .ended]) + func serverFilteringAndPagination(status expectedStatus: TrainingLearnerStatus) async { let source = TrainingDataStub() await source.configure { $0.tasksHandler = { status, keyword, cursor, _ in - #expect(status == .completed) + #expect(status == expectedStatus) #expect(keyword == "服务") - return TrainingCursorPage(items: [TrainingRemoteFixtures.task(id: cursor == nil ? "first" : "second")], nextCursor: cursor == nil ? "next" : nil, hasMore: cursor == nil, serverTime: nil) + return TrainingCursorPage(items: [TrainingRemoteFixtures.task(id: cursor == nil ? "first" : "second", learnerStatus: expectedStatus)], nextCursor: cursor == nil ? "next" : nil, hasMore: cursor == nil, serverTime: nil) } } let model = TrainingRemoteCenterViewModel() model.selectTab(.tasks) - model.filter = .completed + model.filter = expectedStatus model.keyword = " 服务 " await model.load(service: source) #expect(model.tasks.map(\.id) == ["first"]) #expect(model.hasMore) await model.loadMore(service: source) #expect(model.tasks.map(\.id) == ["first", "second"]) + #expect(model.tasks.allSatisfy { $0.learnerStatus == expectedStatus }) #expect(!model.hasMore) #expect(await source.calls.count == 3) } diff --git a/suixinkanTests/TrainingRemoteReadingTests.swift b/suixinkanTests/TrainingRemoteReadingTests.swift index 6536274..0e4d977 100644 --- a/suixinkanTests/TrainingRemoteReadingTests.swift +++ b/suixinkanTests/TrainingRemoteReadingTests.swift @@ -31,6 +31,28 @@ struct TrainingRemoteReadingTests { } } + @Test("已结束任务可加载附件回顾,但不建立学习会话或上报读时") + func endedTaskIsReadOnly() async { + let source = source(seconds: 0) + await source.configure { + $0.taskHandler = { _ in + TrainingTaskDetail(summary: TrainingRemoteFixtures.task(readingCompleted: false, learnerStatus: .ended), + requiredReadingSeconds: 20, readingRule: "course_duration", scoring: "equal-percentage-v1", serverTime: TrainingRemoteFixtures.now) + } + $0.progressHandler = { _ in TrainingRemoteFixtures.progress(seconds: 0, learnerStatus: .ended) } + } + let model = model(source) + await loadRendered(model) + #expect(model.currentAttachmentLink != nil) + #expect(model.isAttachmentRendered) + #expect(!model.canStudy) + await model.startReading(at: 0) + await model.recordVisibleTime(at: 10) + #expect(!model.isReading) + #expect(!(await source.calls).contains { ["startReading", "heartbeat"].contains($0.name) }) + #expect(await source.heartbeats.isEmpty) + } + /// 首屏只读取一页附件并授权首项,不请求已经停用的小节 HTML。 @Test("首次仅请求附件第一页并授权首项,不加载小节 HTML") func lazyCourseResources() async { diff --git a/suixinkanTests/TrainingUIRenderingTests.swift b/suixinkanTests/TrainingUIRenderingTests.swift index 3d595de..3ea8f11 100644 --- a/suixinkanTests/TrainingUIRenderingTests.swift +++ b/suixinkanTests/TrainingUIRenderingTests.swift @@ -25,6 +25,7 @@ struct TrainingUIRenderingTests { 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 == "学习 + 考试 · 30 题 · 80 分及格" }) #expect(!labels.contains { $0.text?.contains("未同步景区后台") == true }) let original = try await source.task(id: "demo-service") @@ -34,6 +35,9 @@ struct TrainingUIRenderingTests { scoring: original.scoring, course: original.course, questions: original.questions, progress: original.progress) let cell = TrainingTaskCell(style: .default, reuseIdentifier: nil) cell.configure(task: longTask) + #expect(allViews(cell.contentView).compactMap { $0 as? UILabel }.contains { + $0.text == "学习 + 考试 · \(longTask.questions.count) 题 · \(longTask.passScore) 分及格" + }) let width: CGFloat = 320 let shortCell = TrainingTaskCell(style: .default, reuseIdentifier: nil) shortCell.configure(task: original) @@ -55,6 +59,59 @@ struct TrainingUIRenderingTests { cell.layer.render(in: context.cgContext) } Attachment.record(cardImage, named: "320点长标题任务卡", as: .png) + cell.configure(task: try await source.task(id: "demo-study")) + #expect(allViews(cell.contentView).compactMap { $0 as? UILabel }.contains { $0.text == "仅学习" }) + } + + @Test("任务页三种筛选独立查询,已结束任务显示回顾入口") + func endedFilterAndReadOnlyCard() async throws { + let source = TrainingDataStub() + await source.configure { + $0.tasksHandler = { status, _, _, _ in + let state = status ?? .pendingExam + return TrainingCursorPage(items: [TrainingRemoteFixtures.task(id: state.apiValue, + title: "\(state.title)任务", learnerStatus: state)], nextCursor: nil, hasMore: false, serverTime: nil) + } + } + for width: CGFloat in [320, 390] { + let controller = TrainingCenterViewController(service: source) + let navigation = UINavigationController(rootViewController: controller) + let window = try makeWindow(navigation, width: width) + defer { window.isHidden = true } + controller.selectTab(.tasks) + let buttons = allViews(controller.view).compactMap { $0 as? UIButton } + .filter { $0.accessibilityIdentifier?.hasPrefix("training.filter.") == true } + #expect(buttons.count == 3) + for state in [TrainingLearnerStatus.ended, .completed, .pendingExam, .ended] { + let index = try #require(TrainingLearnerStatus.allCases.firstIndex(of: state)) + let button = try #require(buttons.first { $0.tag == index }) + button.sendActions(for: .touchUpInside) + let deadline = ContinuousClock.now.advanced(by: .seconds(5)) + while ContinuousClock.now < deadline { + navigation.view.layoutIfNeeded() + let hasTask = allViews(controller.view).compactMap { $0 as? UILabel }.contains { $0.text == "\(state.title)任务" } + if button.accessibilityTraits.contains(.selected), hasTask { break } + try await Task.sleep(for: .milliseconds(10)) + } + #expect(button.accessibilityTraits.contains(.selected)) + #expect(buttons.filter { $0.accessibilityTraits.contains(.selected) }.count == 1) + #expect(allViews(controller.view).compactMap { $0 as? UILabel }.contains { $0.text == "\(state.title)任务" }) + } + #expect(buttons.map { $0.configuration?.title } == ["待考试 1", "已完成 0", "已结束"]) + for button in buttons { + let frame = button.convert(button.bounds, to: controller.view) + #expect(frame.minX >= 0 && frame.maxX <= width + 1) + #expect(frame.height >= 44) + } + let labels = allViews(controller.view).compactMap { $0 as? UILabel } + #expect(labels.contains { $0.text == "已结束" && $0.textColor == TrainingUI.muted }) + #expect(labels.contains { $0.text == "任务已结束,仅可回顾课程内容" }) + let action = try #require(allViews(controller.view).compactMap { $0 as? UIButton } + .first { $0.accessibilityIdentifier == "training.task.action.ended" }) + #expect(action.configuration?.title == "回顾学习") + #expect(action.isEnabled) + Attachment.record(render(navigation.view), named: "\(Int(width))点-已结束筛选与只读任务", as: .png) + } } @Test("课程与考试步骤等宽居中,窄屏和大字体不裁切") @@ -103,6 +160,8 @@ struct TrainingUIRenderingTests { let buttons = allViews(controller.view).compactMap { $0 as? UIButton } #expect(!buttons.contains { $0.accessibilityIdentifier == "training.reading.sections" || $0.accessibilityIdentifier == "training.reading.attachments" }) #expect(!buttons.contains { $0.configuration?.title == "章节目录" || $0.configuration?.title == "课程附件" }) + #expect(!buttons.contains { $0.accessibilityIdentifier == "training.reading.documentPicker" }) + #expect(!buttons.contains { $0.configuration?.title == "切换附件" || $0.configuration?.title == "培训资料.txt" }) let frame = step.convert(step.bounds, to: controller.view) #expect(abs(frame.minY - controller.view.safeAreaInsets.top - 8) < 1) let preview = try #require(allViews(controller.view).compactMap { $0 as? TrainingDocumentPreviewView }.first)