From cd90c3648bb47abd15ec8e3a53d514da569870c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=89=E7=A7=8B?= <497055328@qq.com> Date: Thu, 5 Nov 2026 12:35:58 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=82=E9=85=8D=E4=B8=8A=E4=BC=A0=E4=B8=AD?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=B9=B6=E5=AE=8C=E5=96=84=E6=9C=BA=E5=B7=A2?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E4=B8=8E=E8=AE=A2=E9=98=85=E5=85=9C=E5=BA=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 支持订单状态 25 和持续拍摄、交付确认;安全指令点击后直接提交;鉴权超时保留 HTTP 兜底并退避换票重连。补充对应隔离回归测试。 --- .../Models/DroneDockHomeModels.swift | 41 ++++++- .../DroneDockShootingSocketMessage.swift | 12 +- .../DroneDockShootingRealtimeSession.swift | 3 + .../DroneDockConfirmationViewModel.swift | 4 +- .../DroneDock/DroneDockCompactOrderCell.swift | 2 +- .../DroneDockMaterialComponents.swift | 8 +- .../DroneDockShootingTaskViewController.swift | 21 +--- .../DroneShootingOrderCardView.swift | 8 +- .../DroneDockCommandViewTests.swift | 45 +++++--- .../DroneDockConfirmationViewModelTests.swift | 30 +++++ .../DroneDockConfirmationViewTests.swift | 34 +++++- .../DroneDockDeliveryViewModelTests.swift | 15 +++ suixinkanTests/DroneDockHomeOrderTests.swift | 47 +++++++- .../DroneDockMaterialsViewTests.swift | 18 +++ suixinkanTests/DroneDockOrdersViewTests.swift | 2 +- .../DroneDockPreparationViewModelTests.swift | 23 +++- .../DroneDockShootingRealtimeTests.swift | 103 ++++++++++++++++++ .../DroneDockTaskControlStateViewTests.swift | 28 +++-- 18 files changed, 373 insertions(+), 71 deletions(-) diff --git a/suixinkan/Features/DroneDock/Models/DroneDockHomeModels.swift b/suixinkan/Features/DroneDock/Models/DroneDockHomeModels.swift index ea30820..6b48c7b 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockHomeModels.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockHomeModels.swift @@ -185,6 +185,13 @@ struct DroneDockHomeToday: Decodable, Equatable, Sendable { } } +/// 整单履约阶段,与订单飞行任务、航线任务的数字状态分别解析。 +enum DroneDockOrderStatus: Int, Sendable { + case executing = 20 + case uploading = 25 + case completed = 30 +} + /// 张工类型 25 订单摘要;操作入口取后端 can_* 权限,进入准备页仍需校验设备条件。 struct DroneDockHomeOrder: Decodable, Equatable, Sendable { /// 订单号同时作为 Diffable 稳定身份,不虚构接口未提供的整数 ID。 @@ -207,7 +214,7 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable { let shotRemain: Int? /// 拍摄列表状态 pending、processing、completed;未知值保留。 let shootStatus: String? - /// 订单支付和交付状态,与飞行任务状态分开。 + /// 整单履约状态:20 执行中、25 素材上传中、30 已完成;保留未知原值。 let orderStatus: Int? /// 整单原素材汇总状态。 let materialStatus: Int? @@ -295,8 +302,20 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable { /// 缺失项目名称时保留未知。 var packageTitle: String { DroneDockHomeMetric.usableText(packageName) ?? "套餐信息待确认" } - /// 仅映射文档定义的拍摄列表状态,不根据次数推导完成。 + /// 已知整单状态;未知值仍保留在原始 orderStatus 中。 + var knownOrderStatus: DroneDockOrderStatus? { orderStatus.flatMap(DroneDockOrderStatus.init(rawValue:)) } + + /// 执行和素材上传均为未完成订单,具体操作仍由各自后端许可决定。 + var isActiveOrderStatus: Bool { knownOrderStatus == .executing || knownOrderStatus == .uploading } + + /// 上传、完成优先使用整单状态;执行中的未拍订单保留明确的待拍摄提示。 var statusTitle: String { + switch knownOrderStatus { + case .uploading: return "素材上传中" + case .completed: return "已完成" + case .executing: return shootStatus == "pending" ? "待拍摄" : "执行中" + case nil: break + } switch shootStatus { case "pending": return "待拍摄" case "processing": return "进行中" @@ -305,6 +324,22 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable { } } + /// 卡片使用统一语义色,不把素材上传中显示为任务失败或订单已完成。 + var statusTone: DroneDockStatusTone { + switch knownOrderStatus { + case .uploading: return .blue + case .completed: return .green + case .executing: return shootStatus == "pending" ? .blue : .orange + case nil: + switch shootStatus { + case "pending": return .blue + case "processing": return .orange + case "completed": return .green + default: return .gray + } + } + } + /// 逐项展示真实计数和未知占位,不把任务数当作已使用次数。 var progressTitle: String { let used = shotUsed.map(String.init) ?? "—" @@ -326,7 +361,7 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable { var canDeliverFilm: Bool { switch orderStatus { case 30: true - case 20, nil: canUploadFilm == true + case 20, 25, nil: canUploadFilm == true default: false } } diff --git a/suixinkan/Features/DroneDock/Models/DroneDockShootingSocketMessage.swift b/suixinkan/Features/DroneDock/Models/DroneDockShootingSocketMessage.swift index c7355c7..558bb0b 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockShootingSocketMessage.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockShootingSocketMessage.swift @@ -18,6 +18,7 @@ enum DroneDockShootingSocketMessage { case subscribed(taskID: Int) case subscriptionMetadata(taskID: Int, hasSnapshot: Bool, executionBatch: Int?) case snapshot(DroneDockShootingResponse) + case subscriptionTimedOut(message: String) case subscriptionRejected(code: Int, message: String) case rejected(code: Int, message: String) case unrelated @@ -32,10 +33,19 @@ enum DroneDockShootingSocketMessage { if json as? String == "Opened" { return .opened } guard let root = json as? [String: Any], let code = root["code"] as? Int else { throw APIError.invalidResponse } + // 鉴权硬超时是服务暂不可用。合同以正式失败回执的 hint 标识,未约定专用错误码; + // 即使返回 100099,也不能按无权限永久关闭 HTTP 和 Socket 读取。 + if let body = root["data"] as? [String: Any], + body["type"] as? Int == 310, body["ack"] as? String == "subscribe", + boolean(body["subscribed"]) == false, + let hint = body["hint"] as? String, hint.contains("鉴权超时") { + return .subscriptionTimedOut(message: hint.trimmingCharacters(in: .whitespacesAndNewlines)) + } if code != 100000 { let message = root["msg"] as? String ?? "任务订阅失败" if let body = root["data"] as? [String: Any], - body["type"] as? Int == 310, boolean(body["subscribed"]) == false { + body["type"] as? Int == 310, body["ack"] as? String == "subscribe", + boolean(body["subscribed"]) == false { return .subscriptionRejected(code: code, message: message) } return .rejected(code: code, message: message) diff --git a/suixinkan/Features/DroneDock/Services/DroneDockShootingRealtimeSession.swift b/suixinkan/Features/DroneDock/Services/DroneDockShootingRealtimeSession.swift index f18a94e..2050557 100644 --- a/suixinkan/Features/DroneDock/Services/DroneDockShootingRealtimeSession.swift +++ b/suixinkan/Features/DroneDock/Services/DroneDockShootingRealtimeSession.swift @@ -201,6 +201,9 @@ final class DroneDockShootingRealtimeSession { log("websocket.snapshot_ignored", fields: ["reason": "old_version"]) case .invalid: throw APIError.decodeFailed("任务快照身份或结构不一致") } + case .subscriptionTimedOut(let message): + // 收到服务端三秒鉴权超时便结束本轮等待,保留 HTTP,并退避取新票重连。 + fail(message) case .subscriptionRejected(let code, let message): // 310 明确拒绝可按错误码处理,不依赖服务端说明的语言或措辞。 if code == 100099 { deny(message) } diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockConfirmationViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockConfirmationViewModel.swift index cbd3418..f497a48 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockConfirmationViewModel.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockConfirmationViewModel.swift @@ -29,7 +29,7 @@ final class DroneDockConfirmationViewModel { var isCompleted: Bool { detail?.order.orderStatus == 30 } /// 最新订单仍待游客确认;本次出码成功后,无需等详情中的确认状态更新。 var isAwaitingConfirmation: Bool { - detail?.order.orderStatus == 20 && (order.confirmStatus == 1 || code != nil) + detail?.order.isActiveOrderStatus == true && (order.confirmStatus == 1 || code != nil) } /// 允许无云端成片的订单生成码,权限由服务端 can_confirm 决定。 var canGenerate: Bool { @@ -178,7 +178,7 @@ final class DroneDockConfirmationViewModel { func validateContext() -> Bool { accepts(generation) } private var permitsInvitation: Bool { - detail?.order.orderStatus == 20 && detail?.order.canConfirm == true + detail?.order.isActiveOrderStatus == true && detail?.order.canConfirm == true } @MainActor diff --git a/suixinkan/UI/DroneDock/DroneDockCompactOrderCell.swift b/suixinkan/UI/DroneDock/DroneDockCompactOrderCell.swift index 3c8371f..ed975a7 100644 --- a/suixinkan/UI/DroneDock/DroneDockCompactOrderCell.swift +++ b/suixinkan/UI/DroneDock/DroneDockCompactOrderCell.swift @@ -53,7 +53,7 @@ final class DroneDockCompactOrderCell: UICollectionViewCell { customerLabel.text = order.touristTitle orderNumberLabel.isHidden = false orderNumberLabel.text = "订单号 \(order.orderNumberText)" - statusLabel.apply(title: order.statusTitle, tone: order.statusTitle == "待拍摄" ? .blue : .gray) + statusLabel.apply(title: order.statusTitle, tone: order.statusTone) packageLabel.text = order.packageTitle packageLabel.numberOfLines = 0 countsLabel.numberOfLines = 0 diff --git a/suixinkan/UI/DroneDock/DroneDockMaterialComponents.swift b/suixinkan/UI/DroneDock/DroneDockMaterialComponents.swift index 75ee79e..dcf03dd 100644 --- a/suixinkan/UI/DroneDock/DroneDockMaterialComponents.swift +++ b/suixinkan/UI/DroneDock/DroneDockMaterialComponents.swift @@ -39,13 +39,7 @@ final class DroneDockMaterialOrderCell: UICollectionViewCell { /// 不根据任务数量或素材上传状态推导订单拍摄履约状态。 func apply(order: DroneDockHomeOrder) { customerLabel.text = order.touristTitle - let tone: DroneDockStatusTone = switch order.shootStatus { - case "completed": .green - case "processing": .blue - case "pending": .orange - default: .gray - } - statusLabel.apply(title: order.statusTitle, tone: tone) + statusLabel.apply(title: order.statusTitle, tone: order.statusTone) numberLabel.text = order.orderNumberText let total = order.shotTotal.map(String.init) ?? "—" let used = order.shotUsed.map(String.init) ?? "—" diff --git a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift index 2804e2b..777c1f6 100644 --- a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift @@ -670,7 +670,7 @@ final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController feedPlaceholder.apply(liveViewModel) } - /// 返航会中断任务,先明确展示其含义再提交一次。 + /// 安全动作点击后直接提交,沿用当前任务的权限与防重校验。 private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) { logEvent("action.safety", fields: ["command": command.rawValue, "enabled": viewModel.canSendCommand(command)]) guard isPageVisible, isApplicationActive, @@ -679,24 +679,7 @@ final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController logSafetyRejection(command, stage: "tap") return } - if command == .returnHome { - let simulated = simulationRecordsProvider != nil - let alert = UIAlertController(title: simulated ? "立即返航(本地模拟)" : "立即返航", - message: simulated - ? "模拟返航会中断本次任务。取消返航也不会恢复已经中断的任务。\n仅验证本地请求与回执,不向无人机发送指令。" - : "返航会中断本次任务。取消返航也不会恢复已经中断的任务。确定立即返航?", preferredStyle: .alert) - alert.addAction(UIAlertAction(title: "取消", style: .cancel) { [weak self] _ in - self?.logEvent("action.return_confirmation.cancelled") - }) - alert.addAction(UIAlertAction(title: simulated ? "模拟返航" : "立即返航", style: .destructive) { [weak self] _ in - self?.logEvent("action.return_confirmation.confirmed") - self?.sendSafetyCommand(command) - }) - logEvent("action.return_confirmation.shown") - present(alert, animated: true) - } else { - sendSafetyCommand(command) - } + sendSafetyCommand(command) } /// 同步锁只覆盖同一按钮;不同安全动作可各自等待,设备确认由 ViewModel 和快照处理。 diff --git a/suixinkan/UI/DroneDock/DroneShootingOrderCardView.swift b/suixinkan/UI/DroneDock/DroneShootingOrderCardView.swift index 6a2303c..fed9686 100644 --- a/suixinkan/UI/DroneDock/DroneShootingOrderCardView.swift +++ b/suixinkan/UI/DroneDock/DroneShootingOrderCardView.swift @@ -86,13 +86,7 @@ final class DroneShootingOrderCardView: UIView { metadataLabel.text = "订单号 \(order.orderNumberText) · \(createdAt)" packageLabel.text = order.packageTitle statusLabel.text = order.statusTitle - let tone: DroneDockStatusTone = switch order.shootStatus { - case "pending": .blue - case "processing": .orange - case "completed": .green - default: .gray - } - applyStatusAppearance(tone: tone) + applyStatusAppearance(tone: order.statusTone) let used = order.shotUsed.map(String.init) ?? "—" let total = order.shotTotal.map(String.init) ?? "—" diff --git a/suixinkanTests/DroneDockCommandViewTests.swift b/suixinkanTests/DroneDockCommandViewTests.swift index 3c95384..f6314ab 100644 --- a/suixinkanTests/DroneDockCommandViewTests.swift +++ b/suixinkanTests/DroneDockCommandViewTests.swift @@ -7,7 +7,7 @@ import XCTest final class DroneDockCommandViewTests: XCTestCase { private weak var previousKeyWindow: UIWindow? - /// 暂停和继续均使用同一任务,连点仅提交一次,刷新期间保留旧数据与固定区域。 + /// 暂停和继续点击即提交且不弹确认,连点仅提交一次,刷新期间保留旧数据与固定区域。 func testPauseAndResumeUseSameTaskWithoutDuplicateRequestsOrLayoutChanges() async throws { let controller = try makeController(result: "success") let window = makeWindow(controller) @@ -24,6 +24,7 @@ final class DroneDockCommandViewTests: XCTestCase { pause.sendActions(for: .touchUpInside) pause.sendActions(for: .touchUpInside) + XCTAssertNil(controller.presentedViewController, "暂停直接提交,不显示确认弹窗") XCTAssertFalse(pause.isEnabled) XCTAssertTrue(returnHome.isEnabled) XCTAssertEqual(model.presentation.title, oldTitle) @@ -47,6 +48,8 @@ final class DroneDockCommandViewTests: XCTestCase { XCTAssertTrue(resume.isEnabled) resume.sendActions(for: .touchUpInside) resume.sendActions(for: .touchUpInside) + XCTAssertNil(controller.presentedViewController, "继续任务直接提交,不显示确认弹窗") + XCTAssertFalse(resume.isEnabled) try await settle(window) { model.canSendCommand(.pause) && !model.isSendingCommand && (pause.accessibilityLabel?.contains("暂停") == true) @@ -72,31 +75,39 @@ final class DroneDockCommandViewTests: XCTestCase { XCTAssertEqual(Set(bodies.compactMap { $0["client_request_id"] as? String }).count, 2) } - /// 返航必须先显示模拟确认,关闭确认不会产生任何指令请求。 - func testReturnConfirmationCanBeCancelledWithoutSendingCommand() async throws { + /// 返航点击即提交且不弹确认;同步锁覆盖连点,受理后仍等待同任务状态核对。 + func testReturnSubmitsImmediatelyOnceWithoutConfirmation() async throws { let controller = try makeController(result: "success") let window = makeWindow(controller) defer { close(window) } - try await settle(window) { controller.viewModel.canSendCommand(.returnHome) } + let model = controller.viewModel + try await settle(window) { model.canSendCommand(.returnHome) } let returnHome = try button(controller, suffix: "return") + let oldTitle = model.presentation.title returnHome.sendActions(for: .touchUpInside) returnHome.sendActions(for: .touchUpInside) - try await settle(window) { - controller.presentedViewController is UIAlertController - && controller.presentedViewController?.transitionCoordinator == nil - } - let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController) - XCTAssertEqual(alert.title, "立即返航(本地模拟)") - XCTAssertEqual(alert.actions.compactMap(\.title), ["取消", "模拟返航"]) - XCTAssertFalse(controller.viewModel.isSendingCommand) - XCTAssertNil(controller.viewModel.commandResponse) - capture(window, name: "安全控制-返航确认-本地模拟") + XCTAssertNil(controller.presentedViewController, "返航直接提交,不需要再次确认") + XCTAssertFalse(returnHome.isEnabled) + XCTAssertTrue(try XCTUnwrap(find(controller.view, suffix: "return.loading") as? UIActivityIndicatorView).isAnimating) + XCTAssertEqual(model.presentation.title, oldTitle, "点击本身不伪造设备已返航状态") + try await settle(window) { model.presentation.phase == .returning && !model.isSendingCommand } + XCTAssertNil(controller.presentedViewController) + XCTAssertFalse(returnHome.isEnabled) + XCTAssertEqual(model.commandResponse?.command, DroneDockSafetyCommand.returnHome.rawValue) + XCTAssertFalse(model.shouldPresentRecordingCompletion) + returnHome.sendActions(for: .touchUpInside) + capture(window, name: "安全控制-直接返航-本地模拟") - alert.dismiss(animated: false) - try await settle(window) { controller.presentedViewController == nil } let transcript = try await records(controller, window: window) let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) - XCTAssertFalse(entries.contains { $0["method"] as? String == "POST" }) + XCTAssertEqual(entries.compactMap { $0["method"] as? String }, ["GET", "POST", "GET"]) + let posts = entries.filter { $0["method"] as? String == "POST" } + XCTAssertEqual(posts.count, 1) + XCTAssertEqual(posts.first?["path"] as? String, "/api/app/airport/command") + let body = try XCTUnwrap(posts.first?["request_body"] as? [String: Any]) + XCTAssertEqual(body["id"] as? Int, 901) + XCTAssertEqual(body["command"] as? String, "return_home") + XCTAssertFalse(try XCTUnwrap(body["client_request_id"] as? String).isEmpty) XCTAssertEqual(transcript["network_sent"] as? Bool, false) } diff --git a/suixinkanTests/DroneDockConfirmationViewModelTests.swift b/suixinkanTests/DroneDockConfirmationViewModelTests.swift index fb77413..9fbbc11 100644 --- a/suixinkanTests/DroneDockConfirmationViewModelTests.swift +++ b/suixinkanTests/DroneDockConfirmationViewModelTests.swift @@ -26,6 +26,36 @@ final class DroneDockConfirmationViewModelTests: XCTestCase { XCTAssertFalse(fixture.model.isCompleted) } + /// 25 可邀请确认,但仍须后端许可、成功读取清单及人工核对,不因上传状态放宽。 + func testUploadingOrderInvitationKeepsPermissionReadAndReviewGates() async throws { + let fixture = try ConfirmationVMFixture() + fixture.service.detailValue = try ConfirmationVMData.detail(allowed: false, status: 25) + await fixture.model.refresh() + fixture.model.setReviewed(true) + await fixture.model.generateCode() + XCTAssertFalse(fixture.model.canGenerate) + XCTAssertEqual(fixture.service.createCalls, 0) + + fixture.service.detailValue = try ConfirmationVMData.detail(status: 25) + fixture.service.tasksError = APIError.networkFailed("测试清单读取失败") + await fixture.model.refresh() + fixture.model.setReviewed(true) + await fixture.model.generateCode() + XCTAssertFalse(fixture.model.canGenerate) + XCTAssertEqual(fixture.service.createCalls, 0) + + fixture.service.tasksError = nil + await fixture.model.refresh() + XCTAssertFalse(fixture.model.canGenerate) + fixture.model.setReviewed(true) + XCTAssertTrue(fixture.model.canGenerate) + await fixture.model.generateCode() + XCTAssertEqual(fixture.service.createCalls, 1) + XCTAssertEqual(fixture.model.order.orderStatus, 25) + XCTAssertTrue(fixture.model.isAwaitingConfirmation) + XCTAssertFalse(fixture.model.isCompleted) + } + /// 素材上传失败不增加文档之外的交付确认门槛。 func testMaterialFailureDoesNotOverrideBackendConfirmationPermission() async throws { let fixture = try ConfirmationVMFixture() diff --git a/suixinkanTests/DroneDockConfirmationViewTests.swift b/suixinkanTests/DroneDockConfirmationViewTests.swift index b54c6cd..1f8b934 100644 --- a/suixinkanTests/DroneDockConfirmationViewTests.swift +++ b/suixinkanTests/DroneDockConfirmationViewTests.swift @@ -187,6 +187,36 @@ final class DroneDockConfirmationViewTests: XCTestCase { XCTAssertEqual(session.requests.map { $0.url?.lastPathComponent }, ["detail", "tasks", "detail", "confirm-code", "detail", "detail"]) } + /// 上传中的待确认订单每五秒只读核对,后端变为 30 后自动结束等待与轮询。 + func testUploadingOrderPollsUntilConfirmedWithoutCreatingAnotherInvitation() async throws { + let clock = DroneDockPollTestClock() + let images = DroneDockPaymentImageLoaderStub() + let pending = try detail(confirmStatus: 1, orderStatus: 25) + let (controller, session) = try makeController(responses: [ + pending, tasks(), pending, detail(completed: true, confirmStatus: 2) + ], images: images, clock: clock) + let window = show(controller) + defer { close(window) } + try await settle(window) { clock.pendingCount == 1 } + XCTAssertEqual(controller.viewModel.order.orderStatus, 25) + XCTAssertTrue(controller.viewModel.isAwaitingConfirmation) + XCTAssertFalse(controller.viewModel.isCompleted) + XCTAssertEqual(session.requests.count, 2) + + clock.advance() + try await settle(window) { session.requests.count == 3 && clock.pendingCount == 1 } + XCTAssertEqual(controller.viewModel.order.orderStatus, 25) + XCTAssertFalse(controller.viewModel.isCompleted) + clock.advance() + try await settle(window) { controller.viewModel.isCompleted && self.texts(controller.view).contains("游客已确认收货") } + XCTAssertFalse(controller.viewModel.isAwaitingConfirmation) + XCTAssertEqual(clock.pendingCount, 0) + XCTAssertEqual(clock.intervals, [5_000_000_000, 5_000_000_000]) + XCTAssertEqual(session.requests.map { $0.url?.lastPathComponent }, ["detail", "tasks", "detail", "detail"]) + XCTAssertTrue(session.requests.allSatisfy { $0.httpMethod == "GET" }) + XCTAssertTrue(images.requests.isEmpty) + } + /// 已有待确认订单即使本地无码也会查询;后台、离页和交付弹窗暂停,恢复时立即读取。 func testPendingOrderResumesStatusCheckOnlyWhenVisibleAndActive() async throws { let clock = DroneDockPollTestClock() @@ -247,8 +277,8 @@ final class DroneDockConfirmationViewTests: XCTestCase { return (controller, session) } - private func detail(completed: Bool = false, confirmStatus: Int = 0) throws -> Data { - try envelope(["order_number": number, "user_phone": "130****0001", "order_status": completed ? 30 : 20, + private func detail(completed: Bool = false, confirmStatus: Int = 0, orderStatus: Int? = nil) throws -> Data { + try envelope(["order_number": number, "user_phone": "130****0001", "order_status": orderStatus ?? (completed ? 30 : 20), "shoot_count": 1, "shot_count": 1, "remaining_count": 0, "can_confirm": !completed, "confirm_status": confirmStatus, "confirmed_at": completed ? "2026-10-30 15:00:00" as Any : NSNull(), "can_create_task": false, "can_upload_film": !completed, "film_count": 0, "material_status": 3, "spot": []]) diff --git a/suixinkanTests/DroneDockDeliveryViewModelTests.swift b/suixinkanTests/DroneDockDeliveryViewModelTests.swift index 577e0a2..1180f5d 100644 --- a/suixinkanTests/DroneDockDeliveryViewModelTests.swift +++ b/suixinkanTests/DroneDockDeliveryViewModelTests.swift @@ -77,6 +77,21 @@ final class DroneDockDeliveryViewModelTests: XCTestCase { XCTAssertFalse(fixture.model.canSubmit) } + /// 整单上传中仍可交付成片,但不能把状态 25 本身当作上传许可。 + func testUploadingOrderDeliveryRequiresExplicitPermission() async throws { + for allowed in [false, true] { + let fixture = try DeliveryVMFixture(initialTaskID: 11) + fixture.service.detailValue = try DeliveryVMData.detail(allowed: allowed, status: 25) + await fixture.prepare() + XCTAssertEqual(fixture.model.canChooseVideo, allowed) + XCTAssertEqual(fixture.model.canSubmit, allowed) + await fixture.model.submit() + XCTAssertEqual(fixture.uploader.calls, allowed ? 1 : 0) + XCTAssertEqual(fixture.service.saves.count, allowed ? 1 : 0) + if allowed { XCTAssertEqual(fixture.model.phase, .succeeded) } + } + } + /// 无上传权限、已取消、已退款和不支持的视频均不发送写请求。 func testPermissionAndVideoValidationDisableSubmission() async throws { for (allowed, status) in [(false, 20), (true, 10), (true, 40), (true, 50)] { diff --git a/suixinkanTests/DroneDockHomeOrderTests.swift b/suixinkanTests/DroneDockHomeOrderTests.swift index 28377e4..d788e75 100644 --- a/suixinkanTests/DroneDockHomeOrderTests.swift +++ b/suixinkanTests/DroneDockHomeOrderTests.swift @@ -4,6 +4,51 @@ import XCTest /// 验证张工订单摘要、稳定订单号与权限,所有载荷均为匿名测试数据。 final class DroneDockHomeOrderTests: XCTestCase { + /// 整单上传、完成优先于拍摄分类;未拍和未知订单仍保留原分类语义。 + func testOrderStatusOverridesBadgesWithoutChangingPendingOrUnknownFallback() throws { + let cases: [(Int?, String?, String, DroneDockStatusTone)] = [ + (25, "pending", "素材上传中", .blue), + (25, "processing", "素材上传中", .blue), + (25, "completed", "素材上传中", .blue), + (30, "pending", "已完成", .green), + (20, "pending", "待拍摄", .blue), + (20, "processing", "执行中", .orange), + (20, nil, "执行中", .orange), + (nil, "processing", "进行中", .orange), + (99, "pending", "待拍摄", .blue), + (99, nil, "状态待确认", .gray) + ] + for (status, shootStatus, title, tone) in cases { + var payload: [String: Any] = ["order_number": "TEST-STATUS"] + payload["order_status"] = status + payload["shoot_status"] = shootStatus + let order = try JSONDecoder().decode(DroneDockHomeOrder.self, + from: JSONSerialization.data(withJSONObject: payload)) + XCTAssertEqual(order.orderStatus, status) + XCTAssertEqual(order.knownOrderStatus?.rawValue, status.flatMap { [20, 25, 30].contains($0) ? $0 : nil }) + XCTAssertEqual(order.isActiveOrderStatus, status == 20 || status == 25) + XCTAssertEqual(order.statusTitle, title, "order_status=\(String(describing: status)), shoot_status=\(String(describing: shootStatus))") + XCTAssertEqual(order.statusTone, tone) + } + } + + /// 25 是先前素材处理,不覆盖新拍摄许可;后端活动任务仍优先于继续新增。 + func testUploadingOrderKeepsCreationPermissionAndActiveTaskPrioritySeparate() throws { + for (canCreate, activeTaskID, action) in [(true, nil, "start_shoot"), (false, nil, "view_materials"), + (true, 501, "view_task"), (false, 501, "view_task")] as [(Bool, Int?, String)] { + var payload: [String: Any] = ["order_number": "TEST-UPLOADING", "order_status": 25, + "shoot_status": "processing", "shoot_count": 5, "shot_count": 1, "remaining_count": 4, + "can_create_task": canCreate, "can_upload_film": true] + payload["active_task_id"] = activeTaskID + let order = try JSONDecoder().decode(DroneDockHomeOrder.self, + from: JSONSerialization.data(withJSONObject: payload)) + XCTAssertEqual(order.statusTitle, "素材上传中") + XCTAssertEqual(order.shotRemain, 4) + XCTAssertEqual(order.primaryAction, action) + XCTAssertEqual(order.activeTaskID, activeTaskID) + } + } + /// 后端选定任务优先于新增、交付和确认权限,不从剩余次数推断是否飞行中。 func testActiveTaskTakesPriorityOverAllOtherActions() throws { let order = try decodeOrder(#"{"order_number":"TEST-ACTIVE","active_task_id":501,"active_task_status":20,"can_create_task":true,"can_upload_film":true,"can_confirm":true,"shoot_count":5,"shot_count":5}"#) @@ -61,7 +106,7 @@ final class DroneDockHomeOrderTests: XCTestCase { XCTAssertEqual(order.createdAt, "2026-10-27 10:00:00") XCTAssertEqual(order.touristTitle, "游客 138****0000") XCTAssertEqual(order.packageTitle, "多点位航拍") - XCTAssertEqual(order.statusTitle, "进行中") + XCTAssertEqual(order.statusTitle, "执行中") XCTAssertEqual(order.shotTotal, 3) XCTAssertEqual(order.shotUsed, 1) XCTAssertEqual(order.shotRemain, 2) diff --git a/suixinkanTests/DroneDockMaterialsViewTests.swift b/suixinkanTests/DroneDockMaterialsViewTests.swift index 6446b44..fadd6f2 100644 --- a/suixinkanTests/DroneDockMaterialsViewTests.swift +++ b/suixinkanTests/DroneDockMaterialsViewTests.swift @@ -8,6 +8,24 @@ final class DroneDockMaterialsViewTests: XCTestCase { private weak var previousKeyWindow: UIWindow? private let number = "TEST-MATERIAL-ORDER" + /// 同一摘要复用时整单状态同时更新文案和颜色,不沿用相冲突的拍摄分类颜色。 + func testOrderSummaryUsesUploadingAndCompletedOrderColorsWhenShootStatusConflicts() throws { + let cell = DroneDockMaterialOrderCell(frame: CGRect(x: 0, y: 0, width: 350, height: 140)) + for (status, shootStatus, title, color) in [(25, "completed", "素材上传中", DroneDockStyle.primary), + (30, "pending", "已完成", DroneDockStyle.success)] { + let order = try JSONDecoder().decode(DroneDockHomeOrder.self, + from: JSONSerialization.data(withJSONObject: ["order_number": number, "order_status": status, + "shoot_status": shootStatus, "shoot_count": 5, "shot_count": 1, "remaining_count": 4])) + cell.apply(order: order) + cell.layoutIfNeeded() + let badge = try XCTUnwrap(descendants(cell).compactMap { $0 as? DroneDockStatusLabel }.first) + XCTAssertEqual(badge.text, title) + XCTAssertEqual(badge.textColor, color) + XCTAssertEqual(badge.backgroundColor, color.withAlphaComponent(0.09)) + XCTAssertTrue(cell.accessibilityLabel?.contains(title) == true) + } + } + /// 有任务的素材库仅保留刷新入口,不再从导航栏打开拍摄任务。 func testNavigationOnlyShowsRefreshForExistingTasks() async throws { let (controller, session) = try makeController([detail(), taskList([task(51)])]) diff --git a/suixinkanTests/DroneDockOrdersViewTests.swift b/suixinkanTests/DroneDockOrdersViewTests.swift index d2b1411..902b884 100644 --- a/suixinkanTests/DroneDockOrdersViewTests.swift +++ b/suixinkanTests/DroneDockOrdersViewTests.swift @@ -122,7 +122,7 @@ final class DroneDockOrdersViewTests: XCTestCase { let list = try collection(in: controller) try await settle(window) { controller.viewModel.total == 1 } let cell = try await card(at: 0, in: list, window: window) - XCTAssertTrue(visibleTexts(in: cell).contains("进行中")) + XCTAssertTrue(visibleTexts(in: cell).contains("执行中")) XCTAssertFalse(visibleTexts(in: cell).contains("已完成")) XCTAssertFalse(visibleTexts(in: cell).contains("开始拍摄")) XCTAssertTrue(visibleTexts(in: cell).contains { $0.contains("剩余") && $0.contains("0") }) diff --git a/suixinkanTests/DroneDockPreparationViewModelTests.swift b/suixinkanTests/DroneDockPreparationViewModelTests.swift index 4961ee9..f5d83a2 100644 --- a/suixinkanTests/DroneDockPreparationViewModelTests.swift +++ b/suixinkanTests/DroneDockPreparationViewModelTests.swift @@ -183,6 +183,23 @@ final class DroneDockPreparationViewModelTests: XCTestCase { XCTAssertNil(model.errorMessage) } + /// 先前素材上传不阻止继续拍摄,最新购买额度与许可仍独立限制创建。 + func testUploadingOrderCanPrepareNextShotOnlyWithRemainingQuotaAndPermission() async throws { + let service = try ImmediatePreparationService() + let model = try makeModel(service: service, orderStatus: 25) + for (remaining, canCreate, expected) in [(4, true, true), (0, true, false), (4, false, false)] { + service.projectResult = .success(try PreparationFixture.project(remaining: remaining, + canCreate: canCreate, orderStatus: 25)) + await model.refresh() + XCTAssertEqual(model.projectInfo?.order.orderStatus, 25) + XCTAssertEqual(model.projectInfo?.order.shotRemain, remaining) + XCTAssertEqual(model.canCreateTask, expected) + if remaining == 0 { XCTAssertEqual(model.primaryButtonTitle, "拍摄次数已用完") } + } + XCTAssertEqual(service.projectRequests.count, 3) + XCTAssertNil(model.createdTask, "只核对准备门禁,不调用创建或召唤") + } + /// 购买权限与次数各自独立,未知或已耗尽不能允许新增任务。 func testAdmissionUsesPurchasedPermissionAndKnownQuota() async throws { let service = try ImmediatePreparationService() @@ -559,11 +576,12 @@ final class DroneDockPreparationViewModelTests: XCTestCase { /// 每例使用内存订单和会话,不接触真实账号。 private func makeModel(service: any DroneDockPreparationServing, scope: PreparationContextBox? = nil, - projectID: Int? = 101, planeService: (any DroneDockPlaneStatusServing)? = nil) throws -> DroneDockPreparationViewModel { + projectID: Int? = 101, orderStatus: Int? = nil, planeService: (any DroneDockPlaneStatusServing)? = nil) throws -> DroneDockPreparationViewModel { let scope = scope ?? PreparationContextBox(context()) var order: [String: Any] = ["order_number": "TEST-PREPARATION-001", "project_name": "旧列表套餐", "shoot_count": 9, "shot_count": 2, "remaining_count": 7] order["project_id"] = projectID + order["order_status"] = orderStatus let decoded = try JSONDecoder().decode(DroneDockHomeOrder.self, from: JSONSerialization.data(withJSONObject: order)) return DroneDockPreparationViewModel(context: scope.value, order: decoded, service: service, planeStatusService: try planeService ?? DroneDockPlaneStatusTestService(), @@ -585,11 +603,12 @@ private enum PreparationFixture { /// 购买快照使用五次额度,刻意与首页旧数据不同。 static func project(spots: [[String: Any]]? = nil, projectID: Int = 101, number: String = "TEST-PREPARATION-001", remaining: Int? = 5, - canCreate: Bool = true) throws -> DroneDockProjectInfoResponse { + canCreate: Bool = true, orderStatus: Int? = nil) throws -> DroneDockProjectInfoResponse { var value: [String: Any] = ["order_number": number, "project_id": projectID, "project_name": "已购五次套餐", "shoot_count": 5, "shot_count": 0, "can_create_task": canCreate, "spot": spots ?? [point(201), point(202, routes: [401, 402])]] value["remaining_count"] = remaining + value["order_status"] = orderStatus return try JSONDecoder().decode(DroneDockProjectInfoResponse.self, from: JSONSerialization.data(withJSONObject: value)) } diff --git a/suixinkanTests/DroneDockShootingRealtimeTests.swift b/suixinkanTests/DroneDockShootingRealtimeTests.swift index 375ea7d..b9db5d9 100644 --- a/suixinkanTests/DroneDockShootingRealtimeTests.swift +++ b/suixinkanTests/DroneDockShootingRealtimeTests.swift @@ -54,6 +54,55 @@ final class DroneDockShootingRealtimeTests: XCTestCase { } } + /// 鉴权超时由正式失败回执的明确 hint 区分,不猜测错误码或要求失败包带任务 ID。 + func testFormalAuthenticationTimeoutUsesTrimmedHintForDifferentBusinessCodes() throws { + for code in [100000, 100050, 100099] { + let message = try DroneDockShootingSocketMessage.decode( + RealtimeTestData.authenticationTimeout(code: code, hint: " 鉴权超时,请稍后重试 \n")) + guard case .subscriptionTimedOut(let reason) = message else { + return XCTFail("正式鉴权超时应保留 HTTP 兜底,不按 \(code) 误判永久无权限") + } + XCTAssertEqual(reason, "鉴权超时,请稍后重试") + } + } + + /// 就绪/入站提示及非明确失败字段不能冒充正式鉴权超时。 + func testTimeoutHintOnDiagnosticOrMalformedAckDoesNotBecomeFormalTimeout() throws { + let variants: [[String: Any]] = [ + ["type": 310, "ack": "ready", "subscribed": false], + ["type": 310, "ack": "received", "subscribed": false], + ["type": 311, "ack": "subscribe", "subscribed": false], + ["type": 310, "ack": "subscribe", "subscribed": true, "order_flight_task_id": 501] + ] + for variant in variants { + let data = try JSONSerialization.data(withJSONObject: ["code": 100000, "data": + variant.merging(["hint": "鉴权超时"]) { old, _ in old }]) + if case .subscriptionTimedOut = try DroneDockShootingSocketMessage.decode(data) { + XCTFail("只有 type310 + subscribe + JSON false 能识别正式超时:\(variant)") + } + } + for subscribed in [0, 1] { + let data = try JSONSerialization.data(withJSONObject: ["code": 100000, "data": [ + "type": 310, "ack": "subscribe", "subscribed": subscribed, "hint": "鉴权超时" + ]]) + XCTAssertThrowsError(try DroneDockShootingSocketMessage.decode(data), "数值不能替代 JSON false") + } + } + + /// 入站回执可能携带 subscribed=false,只有正式 subscribe 才能声明订阅被拒绝。 + func testFailedDiagnosticAckCannotBecomeFormalSubscriptionRejection() throws { + for ack in ["ready", "received", "subscribe_meta"] { + let data = try JSONSerialization.data(withJSONObject: ["code": 100099, "msg": "暂不可用", "data": [ + "type": 310, "ack": ack, "subscribed": false, "hint": "鉴权超时" + ]]) + guard case .rejected(let code, let message) = try DroneDockShootingSocketMessage.decode(data) else { + return XCTFail("非正式失败回执不能按权限永久停止读取") + } + XCTAssertEqual(code, 100099) + XCTAssertEqual(message, "暂不可用") + } + } + /// 下行就绪和订阅入站回执只提供诊断,不能冒充正式订阅结果或吞掉错误码。 func testReadyAndReceivedAreDiagnosticMessagesOnly() throws { for ack in ["ready", "received"] { @@ -201,6 +250,55 @@ final class DroneDockShootingRealtimeTests: XCTestCase { } } + /// 服务端三秒鉴权失败立刻结束本轮等待;保留只读兜底并换票,旧连接不能恢复实时态。 + func testAuthenticationTimeoutImmediatelyFallsBackAndReconnectsWithoutAccessDenial() async throws { + for code in [100000, 100050, 100099] { + let harness = RealtimeHarness() + let model = try model() + await model.refresh() + var acceptedSnapshots = 0 + var states: [DroneDockShootingRealtimeSession.State] = [] + harness.session.onSnapshot = { _ in acceptedSnapshots += 1; return .applied } + harness.session.onConnectionState = { state in + states.append(state) + if case .denied(let reason) = state { model.stopReading(message: reason) } + } + harness.session.start() + defer { harness.session.stop() } + await settle { harness.sockets.count == 1 && harness.sockets[0].sent.count == 1 && harness.clock.has(12) } + let first = harness.sockets[0] + first.emit(try RealtimeTestData.transportAck("received")) + harness.time = 3 + first.emit(try RealtimeTestData.authenticationTimeout(code: code)) + await settle { harness.clock.has(1) && !harness.clock.has(12) } + XCTAssertEqual(harness.session.state, .fallback("鉴权超时,请稍后重试")) + XCTAssertEqual(harness.clock.waitCount(seconds: 12), 1) + XCTAssertEqual(first.closeCount, 1) + XCTAssertTrue(model.canContinuePolling) + XCTAssertNil(model.readAccessError) + XCTAssertNotNil(model.response) + XCTAssertFalse(states.contains { if case .denied = $0 { return true }; return false }) + + harness.clock.fire(seconds: 1) + await settle { harness.sockets.count == 2 && harness.sockets[1].sent.count == 1 } + XCTAssertEqual(harness.tickets.count, 2) + XCTAssertTrue(harness.sockets[1].sent[0].contains("MOCK-TICKET-2")) + first.emit(try RealtimeTestData.ack()) + first.emit(try RealtimeTestData.push(RealtimeTestData.payload())) + for _ in 0..<10 { await Task.yield() } + XCTAssertEqual(harness.session.state, .connecting) + XCTAssertEqual(acceptedSnapshots, 0, "旧连接迟到正式回执及快照不能补齐新连接") + + let second = harness.sockets[1] + second.emit(try RealtimeTestData.ack()) + await settle { second.receiveCount >= 3 } + XCTAssertNotEqual(harness.session.state, .live, "新连接仍需有效完整快照") + second.emit(try RealtimeTestData.push(RealtimeTestData.payload(version: 2))) + await settle { harness.session.state == .live } + XCTAssertEqual(acceptedSnapshots, 1) + } + } + /// 新版无 ID 的票据失败只换票重连,不停止任务读取或误判 App 登录失效。 func testExpiredSubscriptionFailureAckRenewsTicket() async throws { let harness = RealtimeHarness() @@ -940,6 +1038,11 @@ enum RealtimeTestData { if ack == "received" { body["type"] = 310 } return try JSONSerialization.data(withJSONObject: ["code": code, "data": body]) } + /// 只注入文档明确的超时 hint;错误码可变化,不能用于推断永久无权限。 + static func authenticationTimeout(code: Int, hint: String = "鉴权超时,请稍后重试") throws -> Data { + try JSONSerialization.data(withJSONObject: ["code": code, "msg": "订阅失败", + "data": ["type": 310, "ack": "subscribe", "subscribed": false, "hint": hint]]) + } static func subscriptionFailure(_ code: Int, _ message: String) throws -> Data { try JSONSerialization.data(withJSONObject: ["code": code, "msg": message, "data": ["type": 310, "ack": "subscribe", "subscribed": false]]) diff --git a/suixinkanTests/DroneDockTaskControlStateViewTests.swift b/suixinkanTests/DroneDockTaskControlStateViewTests.swift index 8e64955..91811f2 100644 --- a/suixinkanTests/DroneDockTaskControlStateViewTests.swift +++ b/suixinkanTests/DroneDockTaskControlStateViewTests.swift @@ -275,7 +275,7 @@ final class DroneDockTaskControlStateViewTests: XCTestCase { XCTAssertFalse(spinner.isAnimating) } - /// 继续任务的受理不覆盖暂停面板,仅中央按钮加载;返航入口仍能打开确认提示。 + /// 继续任务待确认时保留暂停面板与独立返航权限,返航可直接提交且不重复发送。 func testPendingResumeLoadsOnlyPrimaryAndKeepsReturnAvailable() async throws { let service = try ControlStateViewService(state: "paused") service.confirmsCommand = false @@ -306,14 +306,26 @@ final class DroneDockTaskControlStateViewTests: XCTestCase { XCTAssertTrue(returnButton.isEnabled) capture(window, name: "恢复受理待设备确认-保持暂停(隔离模拟)") returnButton.sendActions(for: .touchUpInside) - try await settle(window) { controller.presentedViewController is UIAlertController } - XCTAssertEqual((controller.presentedViewController as? UIAlertController)?.actions.compactMap(\.title), ["取消", "模拟返航"]) - controller.dismiss(animated: false) - try await settle(window) { controller.presentedViewController == nil } - service.response = try ControlStateViewService.snapshot(state: "executing", version: 3, - pendingCommand: service.progress(for: 0, status: "succeeded")) + returnButton.sendActions(for: .touchUpInside) + XCTAssertNil(controller.presentedViewController, "恢复待确认不会让返航新增确认弹窗") + XCTAssertFalse(returnButton.isEnabled) + let returnSpinner = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return.loading") as? UIActivityIndicatorView) + XCTAssertTrue(returnSpinner.isAnimating) + try await settle(window) { service.commands.count == 2 && !controller.viewModel.isSendingCommand } + XCTAssertEqual(service.commands.map(\.command), [.resume, .returnHome]) + XCTAssertEqual(Set(service.commands.map(\.clientRequestID)).count, 2) + XCTAssertTrue(service.commands.allSatisfy { $0.taskID == 501 }) + XCTAssertTrue(controller.viewModel.isCommandLoading(.returnHome)) + XCTAssertFalse(controller.viewModel.isCommandLoading(.resume), "后受理返航替代旧的继续意图") + XCTAssertEqual(controller.viewModel.presentation.phase, .paused, "受理本身不替代完整设备快照") + XCTAssertNil(controller.presentedViewController) + service.response = try ControlStateViewService.snapshot(state: "returning", version: 3, + pendingCommand: service.progress(for: 1, status: "succeeded")) try tapNavigationRefresh(controller) - try await settle(window) { controller.viewModel.presentation.phase == .shooting && !controller.viewModel.isCommandLoading(.resume) } + try await settle(window) { controller.viewModel.presentation.phase == .returning && !controller.viewModel.isCommandLoading(.returnHome) } + XCTAssertFalse(returnSpinner.isAnimating) + XCTAssertFalse(returnButton.isEnabled) + XCTAssertEqual(service.commands.count, 2) XCTAssertFalse(visibleTexts(in: controller.view).contains("指令已受理")) }