合并 9.9.1 机巢工作台与拍摄交付流程 #1

Merged
lujiuyin merged 70 commits from dev_9_9_1 into main 2026-11-18 07:05:44 +00:00
18 changed files with 1055 additions and 98 deletions
Showing only changes of commit e827bf8725 - Show all commits
@@ -75,11 +75,14 @@ struct DroneDockShootingTaskIdentity: Decodable, Equatable, Sendable {
let waylineStatus: Int?
/// 服务端航线状态文案;执行失败优先于笼统的订单任务执行中。
let waylineStatusLabel: String?
/// 服务端实际记录的任务结果原因,空值不视为具体失败说明。
let resultMessage: String?
/// 已确认嵌套任务字段映射。
private enum CodingKeys: String, CodingKey {
case id, orderNumber = "order_number", scenicID = "scenic_id", status, statusLabel = "status_label"
case waylineStatus = "wayline_status", waylineStatusLabel = "wayline_status_label"
case resultMessage = "result_message"
}
}
@@ -142,6 +145,10 @@ struct DroneDockShootingPlane: Decodable, Equatable, Sendable {
let id: Int?
/// 当前设备序列号。
let snNumber: String?
/// 服务端连接状态;实测 2 为离线,不从电量推导连接状态。
let onlineStatus: Int?
/// 文档工作状态:0 离线、1 空闲、2 拍摄中;不据此推断返航完成。
let workStatus: Int?
/// 服务端工作状态文案。
let workStatusLabel: String?
/// 服务端完整状态文案。
@@ -150,6 +157,7 @@ struct DroneDockShootingPlane: Decodable, Equatable, Sendable {
/// 当前设备字段映射。
private enum CodingKeys: String, CodingKey {
case id, snNumber = "sn_number", workStatusLabel = "work_status_label", statusText = "status_text"
case onlineStatus = "online_status", workStatus = "work_status"
}
}
@@ -34,6 +34,8 @@ enum DroneDockTaskDisplayAction: Equatable, Sendable {
case start
/// 恢复拍摄占位动作,本轮禁用。
case resume
/// 失败后的重新召唤占位动作;尚未接入重新准备流程,始终禁用。
case retry
/// 查看已明确完成任务的订单素材。
case materials
/// 当前无主动作。
@@ -54,6 +56,21 @@ struct DroneDockTaskPresentation: Equatable, Sendable {
let action: DroneDockTaskDisplayAction
/// 主动作名称,无动作时为 nil。
let actionTitle: String?
/// 是否可触发动作;未对接的开始和恢复始终为 false。
/// 是否可触发动作;未对接的开始、恢复和重新召唤始终为 false。
let isActionEnabled: Bool
/// 主动作下方的真实设备限制说明,未提供时不展示。
let actionNote: String?
/// 创建状态展示;动作提示默认为空,既有非失败状态保持原布局。
init(phase: DroneDockTaskDisplayPhase, title: String, message: String, deviceStatus: String,
action: DroneDockTaskDisplayAction, actionTitle: String?, isActionEnabled: Bool, actionNote: String? = nil) {
self.phase = phase
self.title = title
self.message = message
self.deviceStatus = deviceStatus
self.action = action
self.actionTitle = actionTitle
self.isActionEnabled = isActionEnabled
self.actionNote = actionNote
}
}
@@ -8,7 +8,7 @@ final class DroneDockShootingTaskViewModel {
let taskID: Int
/// 进入页面携带的订单摘要,仅作未返回展示字段时的订单文案备用。
let order: DroneDockHomeOrder
/// 当前通过身份检查的服务端快照。
/// 最近一次通过身份检查的服务端快照,刷新期间保留,成功后整体替换。
private(set) var response: DroneDockShootingResponse?
/// 同一页面最多存在一个读取请求。
private(set) var isLoading = false
@@ -31,7 +31,7 @@ final class DroneDockShootingTaskViewModel {
self.currentContext = currentContext
}
/// 页面可见时读取同一任务;失败、取消或身份失效不沿用之前的执行门禁与读数。
/// 页面可见时读取同一任务;刷新及普通失败保留旧快照,身份失效立即清除。
@MainActor
func refresh() async {
guard !isLoading, !identityInvalidated else { return }
@@ -39,16 +39,15 @@ final class DroneDockShootingTaskViewModel {
let requestGeneration = generation
isLoading = true
errorMessage = nil
response = nil
defer {
if generation == requestGeneration {
isLoading = false
if Task.isCancelled { response = nil }
}
}
guard accepts(requestGeneration) else { return }
guard context.canLoad, taskID > 0,
DroneDockHomeMetric.usableText(order.orderNumber) != nil else {
response = nil
errorMessage = "缺少有效任务、订单或景区信息,请返回工作台重新进入"
return
}
@@ -56,23 +55,29 @@ final class DroneDockShootingTaskViewModel {
let value = try await service.shooting(taskID: taskID, liveBattery: true)
guard accepts(requestGeneration) else { return }
guard matchesIdentity(value) else {
response = nil
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
}
response = value
} catch {
guard accepts(requestGeneration) else { return }
response = nil
errorMessage = error is CancellationError ? nil : error.localizedDescription
}
}
/// 离开或进入后台时使旧请求失效;再次进入仍读取同一任务,不创建或召唤。
/// 使旧请求失效;同一身份离页或进入后台可保留快照,账号变化始终清除并停止旧任务读取。
@MainActor
func invalidate() {
func invalidate(preservingSnapshot: Bool = false) {
generation &+= 1
isLoading = false
response = nil
if !identityInvalidated { errorMessage = nil }
if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true }
if identityInvalidated {
response = nil
errorMessage = "账号或景区已变化,请返回工作台重新进入"
} else {
if !preservingSnapshot { response = nil }
errorMessage = nil
}
}
/// 优先使用当前接口标题,缺失时展示当前接口的点位和航线名称。
@@ -97,26 +102,32 @@ final class DroneDockShootingTaskViewModel {
/// 使用服务端阶段标题或任务状态,不从 GET 成功推导到达或拍摄完成。
var statusTitle: String {
if errorMessage != nil { return "任务状态读取失败" }
if isLoading { return "正在获取任务状态" }
if response == nil {
if errorMessage != nil { return "任务状态读取失败" }
if isLoading { return "正在获取任务状态" }
}
if resolvedDisplayPhase().0 == .failed { return "任务执行失败" }
return usable(response?.ui?.title) ?? usable(response?.task?.statusLabel)
?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认"
}
/// 保留服务端阶段说明与执行门禁原因;本模块不执行门禁给出的动作。
var statusMessage: String {
if let errorMessage { return errorMessage }
if isLoading { return "正在读取当前拍摄任务" }
if response == nil {
if let errorMessage { return errorMessage }
if isLoading { return "正在读取当前拍摄任务" }
}
if resolvedDisplayPhase().0 == .failed { return failureMessage }
return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—"
}
/// 组合可信阶段与本轮可用动作,不从请求成功、执行中或指令列表推断飞行进度。
var presentation: DroneDockTaskPresentation {
if isLoading {
if response == nil, isLoading {
return DroneDockTaskPresentation(phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: deviceStatusText, action: .none, actionTitle: nil, isActionEnabled: false)
}
if let errorMessage {
if response == nil, let errorMessage {
return DroneDockTaskPresentation(phase: .readError, title: "任务状态读取失败", message: errorMessage,
deviceStatus: deviceStatusText, action: .refresh, actionTitle: "重新读取", isActionEnabled: !identityInvalidated)
}
@@ -139,13 +150,19 @@ final class DroneDockShootingTaskViewModel {
action = .materials
actionTitle = "查看素材"
enabled = true
case .failed:
action = .retry
actionTitle = "重新召唤无人机"
enabled = false
default:
action = .refresh
actionTitle = "刷新状态"
enabled = !identityInvalidated
}
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle, isActionEnabled: enabled)
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
isActionEnabled: enabled && !isLoading && !identityInvalidated && (errorMessage == nil || action == .refresh),
actionNote: phase == .failed ? retryUnavailableNote : nil)
}
/// 后端六项展示读数,不解析文案反推设备状态或数值单位。
@@ -155,21 +172,21 @@ final class DroneDockShootingTaskViewModel {
windText: text("wind_speed"), rainText: text("rainfall"), signalText: text("signal"), satelliteText: text("satellite"))
}
/// 无有效快照时不展示旧读数;连接 false 自身不被转换为飞行阶段。
/// 仅无快照时使用未知读数;刷新期间继续展示最近一次成功快照。
var isTelemetryStale: Bool { response == nil }
/// 完整服务端 data,供页面展示和联调查看。
var dataJSON: String? { response?.dataJSON }
@MainActor
private func accepts(_ requestGeneration: Int) -> Bool {
guard generation == requestGeneration, !Task.isCancelled else { return false }
guard generation == requestGeneration else { return false }
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
identityInvalidated = true
invalidate()
errorMessage = "账号或景区已变化,请返回工作台重新进入"
return false
}
return true
return !Task.isCancelled
}
private func matchesIdentity(_ value: DroneDockShootingResponse) -> Bool {
@@ -222,12 +239,7 @@ final class DroneDockShootingTaskViewModel {
private func presentationTitle(for phase: DroneDockTaskDisplayPhase, conflict: Bool) -> String {
if conflict { return "状态待确认" }
let tasks = [response?.task, response?.orderFlightTask].compactMap { $0 }
if phase == .failed, let failed = tasks.first(where: { $0.waylineStatus == 91 }) {
return usable(failed.waylineStatusLabel) ?? "任务执行失败"
}
if phase == .failed, let failed = tasks.first(where: { $0.status == 40 }) {
return usable(failed.statusLabel) ?? "任务执行失败"
}
if phase == .failed { return "任务执行失败" }
if phase == .blocked, let cancelled = tasks.first(where: { $0.status == 50 }) {
return usable(cancelled.statusLabel) ?? "任务已取消"
}
@@ -251,6 +263,24 @@ final class DroneDockShootingTaskViewModel {
}
private func usable(_ value: String?) -> String? { DroneDockHomeMetric.usableText(value) }
/// 明确失败后优先展示任务结果原因,再保留执行门禁的实际限制,不用通用阶段标题充当原因。
private var failureMessage: String {
usable(response?.orderFlightTask?.resultMessage) ?? usable(response?.task?.resultMessage)
?? usable(response?.executeGate?.message) ?? usable(response?.ui?.message) ?? "暂未返回具体失败原因"
}
/// 重新召唤尚未接入;只补充明确设备状态,不将开始许可、空闲或失败推断为允许重试。
private var retryUnavailableNote: String {
let plane = response?.currentPlane
if plane?.onlineStatus == 2 || plane?.workStatus == 0 || usable(plane?.workStatusLabel) == "离线" {
return "无人机离线,暂不可召唤"
}
if let status = usable(plane?.workStatusLabel), ["返航中", "正在返航"].contains(status) {
return "无人机返航中,暂不可召唤"
}
return "暂不可重新召唤,请返回准备页确认设备状态"
}
}
/// 任务页六项读数的后端展示文本,保持服务端单位与零值。
@@ -16,6 +16,7 @@ enum HomeMenuCatalog {
HomeMenuItem(uri: "wallet", title: "我的钱包", iconName: "home_menu_wallet"),
HomeMenuItem(uri: "cloud_management", title: "相册云盘", iconName: "icloud.fill"),
HomeMenuItem(uri: "asset_management", title: "素材管理", iconName: "home_menu_material"),
HomeMenuItem(uri: "sceniclibrary", title: "景区空境库", iconName: "photo.on.rectangle.angled"),
HomeMenuItem(uri: "task_management", title: "任务管理", iconName: "checklist"),
HomeMenuItem(uri: "task_management_editor", title: "任务管理", iconName: "checklist"),
HomeMenuItem(uri: "schedule_management", title: "日程管理", iconName: "calendar"),
@@ -78,6 +78,14 @@ enum HomeRouteHandler {
viewController.navigationController?.pushViewController(SampleListViewController(), animated: true)
case "asset_management":
viewController.navigationController?.pushViewController(MaterialListViewController(), animated: true)
case "sceniclibrary":
let session = AppStore.shared.session
let context = ScenicMaterialContext(userID: session.userId,
scenicID: String(session.currentScenicId),
scenicName: session.currentScenicName)
// 素材接口尚未接入,正式入口使用当前景区空态,避免生成预览素材。
let viewModel = ScenicMaterialsViewModel(context: context, routes: [], groups: [])
viewController.navigationController?.pushViewController(ScenicMaterialsViewController(viewModel: viewModel), animated: true)
case "checkin_points":
viewController.navigationController?.pushViewController(PunchPointListViewController(), animated: true)
case "live_stream_management":
+11 -11
View File
@@ -2,17 +2,6 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>vipsky.oss-cn-shanghai.aliyuncs.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
<key>CFBundleURLTypes</key>
<array>
<dict>
@@ -36,6 +25,17 @@
<string>qqmap</string>
<string>comgooglemaps</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>vipsky.oss-cn-shanghai.aliyuncs.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
@@ -172,13 +172,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
let telemetry = viewModel.telemetry
telemetryView.apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText,
telemetry.rainText, telemetry.signalText, telemetry.satelliteText],
isStale: loading || viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric")
let value = loading ? DroneDockTaskPresentation(
isStale: viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric")
let value = loading && viewModel.response == nil ? DroneDockTaskPresentation(
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation
statusView.apply(value)
statusView.apply(value, isRefreshing: loading)
statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading
navigationItem.rightBarButtonItem?.isEnabled = isPageVisible && isApplicationActive && !loading
navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil
}
private func primaryActionTriggered() {
@@ -191,7 +192,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
case .materials:
guard let navigationController, navigationController.topViewController === self else { return }
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
case .start, .resume, .none:
case .start, .resume, .retry, .none:
break
}
}
@@ -199,7 +200,10 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func showStatusDetails() {
guard isPageVisible, isApplicationActive, presentedViewController == nil else { return }
let state = viewModel.presentation
let texts = [state.title, state.message, state.deviceStatus].filter { !$0.isEmpty && $0 != "—" }
var texts = [state.title, state.message, state.deviceStatus].filter { !$0.isEmpty && $0 != "—" }
if viewModel.response != nil, let error = viewModel.errorMessage {
texts.append("刷新失败,当前显示上次数据:\(error)")
}
var distinct: [String] = []
for text in texts where !distinct.contains(text) { distinct.append(text) }
let alert = UIAlertController(title: "任务状态详情", message: distinct.joined(separator: "\n\n"), preferredStyle: .alert)
@@ -222,6 +226,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.refreshTask = nil
self.isRequesting = false
self.applySnapshot()
if self.viewModel.response != nil, let error = self.viewModel.errorMessage {
self.showToast("刷新失败,当前显示上次数据:\(error)")
}
}
}
@@ -230,7 +237,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
refreshTask?.cancel()
refreshTask = nil
isRequesting = false
viewModel.invalidate()
viewModel.invalidate(preservingSnapshot: true)
applySnapshot()
}
@@ -0,0 +1,208 @@
import SnapKit
import UIKit
/// 对齐体验网页的任务失败组合:警示、原因、排查提示、重召占位及设备提示。
@MainActor
final class DroneDockTaskFailureView: UIView {
/// 点击原因区域查看完整后端说明,页面无需额外占用一个详情按钮。
var onDetails: (() -> Void)?
/// 内部排版参考比例,不对视图或点击区域使用整体缩放。
private(set) var effectiveScale: CGFloat = 1
/// 当前是否使用适配固定小高度的紧凑排版。
private(set) var usesCompactLayout = false
private let content = UIStackView()
private let notice = UIButton(type: .custom)
private let iconBackground = UIView()
private let icon = UIImageView(image: UIImage(systemName: "exclamationmark.circle.fill"))
private let body = UIStackView()
private let titleLabel = DroneDockStyle.label(size: 23, weight: .semibold)
private let reasonContainer = UIView()
private let reasonLabel = DroneDockStyle.label(size: 14, color: UIColor(hex: 0xF53242))
private let adviceLabel = DroneDockStyle.label("请排查错误后再次召唤无人机。", size: 14, color: UIColor(hex: 0x6A79A0))
private let retryButton = UIButton(type: .system)
private let noteLabel = DroneDockStyle.label(size: 12, color: UIColor(hex: 0x7E8BA9))
private var presentation: DroneDockTaskPresentation?
private var contentTop: Constraint?
private var noticeHeight: Constraint?
private var iconSize: Constraint?
private var bodyLeading: Constraint?
private var titleHeight: Constraint?
private var reasonHeight: Constraint?
private var adviceHeight: Constraint?
private var buttonHeight: Constraint?
private var noteHeight: Constraint?
/// 建立失败态专用层级,外部任务页仍决定该区域尺寸。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 更新真实失败原因及不可重召原因,不把开始拍摄许可当作重召许可。
func apply(_ value: DroneDockTaskPresentation) {
presentation = value
titleLabel.text = value.title
let reason = DroneDockHomeMetric.usableText(value.message).flatMap { $0 == "—" ? nil : $0 }
?? "服务端暂未提供具体原因"
reasonLabel.text = reason.hasPrefix("失败原因:") ? reason : "失败原因:\(reason)"
noteLabel.text = value.actionNote ?? "暂不可重新召唤,请返回准备页确认设备状态"
notice.accessibilityLabel = [value.title, reasonLabel.text, adviceLabel.text].compactMap { $0 }.joined(separator: "。")
setNeedsLayout()
}
/// 只收紧内部字号、行数和间距;主按钮保留至少 44 点高度。
override func layoutSubviews() {
updateLayout()
super.layoutSubviews()
}
private func setupUI() {
accessibilityIdentifier = "drone.task.remote.failure"
content.axis = .vertical
content.spacing = 10
addSubview(content)
content.addArrangedSubview(notice)
content.addArrangedSubview(retryButton)
content.addArrangedSubview(noteLabel)
notice.accessibilityIdentifier = "drone.task.remote.failureDetails"
notice.accessibilityHint = "查看完整失败原因"
notice.addTarget(self, action: #selector(showDetails), for: .touchUpInside)
notice.addSubview(iconBackground)
iconBackground.backgroundColor = UIColor(hex: 0xFFEDED)
iconBackground.isUserInteractionEnabled = false
iconBackground.addSubview(icon)
icon.tintColor = UIColor(hex: 0xFF303B)
icon.contentMode = .scaleAspectFit
body.axis = .vertical
body.spacing = 5
body.isUserInteractionEnabled = false
notice.addSubview(body)
body.addArrangedSubview(titleLabel)
body.addArrangedSubview(reasonContainer)
body.addArrangedSubview(adviceLabel)
titleLabel.textColor = UIColor(hex: 0x101523)
titleLabel.accessibilityIdentifier = "drone.task.remote.failureTitle"
reasonContainer.backgroundColor = UIColor(hex: 0xFFF0F2)
reasonContainer.layer.cornerRadius = 6
reasonContainer.addSubview(reasonLabel)
reasonLabel.accessibilityIdentifier = "drone.task.remote.failureReason"
adviceLabel.accessibilityIdentifier = "drone.task.remote.failureAdvice"
noteLabel.accessibilityIdentifier = "drone.task.remote.failureNote"
noteLabel.textAlignment = .center
[titleLabel, reasonLabel, adviceLabel, noteLabel].forEach { $0.lineBreakMode = .byTruncatingTail }
var configuration = UIButton.Configuration.filled()
configuration.title = "重新召唤无人机"
configuration.image = UIImage(systemName: "arrow.triangle.2.circlepath")
configuration.imagePadding = 12
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 21, weight: .regular)
configuration.background.backgroundColor = UIColor(hex: 0xE8EBF1)
configuration.background.cornerRadius = 8
configuration.baseForegroundColor = UIColor(hex: 0x939CB0)
configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8)
retryButton.configuration = configuration
retryButton.configurationUpdateHandler = { button in
button.configuration?.baseForegroundColor = UIColor(hex: 0x939CB0)
button.configuration?.background.backgroundColor = UIColor(hex: 0xE8EBF1)
}
retryButton.isEnabled = false
retryButton.accessibilityIdentifier = "drone.task.remote.failureRetry"
}
private func setupConstraints() {
content.snp.makeConstraints { make in
contentTop = make.top.equalToSuperview().offset(16).constraint
make.leading.trailing.equalToSuperview().inset(18)
}
notice.snp.makeConstraints { make in noticeHeight = make.height.equalTo(90).constraint }
iconBackground.snp.makeConstraints { make in
make.top.leading.equalToSuperview()
iconSize = make.size.equalTo(41).constraint
}
icon.snp.makeConstraints { make in make.center.equalToSuperview(); make.size.equalToSuperview().multipliedBy(24.0 / 41.0) }
body.snp.makeConstraints { make in
make.top.trailing.equalToSuperview()
bodyLeading = make.leading.equalToSuperview().offset(53).constraint
}
titleLabel.snp.makeConstraints { make in titleHeight = make.height.equalTo(30).constraint }
reasonLabel.snp.makeConstraints { make in make.leading.trailing.equalToSuperview().inset(8); make.centerY.equalToSuperview() }
reasonContainer.snp.makeConstraints { make in reasonHeight = make.height.equalTo(30).priority(999).constraint }
adviceLabel.snp.makeConstraints { make in adviceHeight = make.height.equalTo(22).priority(999).constraint }
retryButton.snp.makeConstraints { make in buttonHeight = make.height.equalTo(50).constraint }
noteLabel.snp.makeConstraints { make in noteHeight = make.height.equalTo(18).constraint }
}
private func updateLayout() {
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
let width = max(1, bounds.width - 36)
let naturalReason = textHeight(reasonLabel.text, font: .systemFont(ofSize: 14), width: width - 53 - 16, lines: 3) + 10
let naturalHeight: CGFloat = 30 + naturalReason + 22 + 10 + 50 + 18 + 14 + 32
effectiveScale = min(1, max(0.8, bounds.height / naturalHeight))
usesCompactLayout = bounds.height < 190
let compact = usesCompactLayout
let extreme = bounds.height < 120
let scale = compact ? 0.8 : effectiveScale
let top: CGFloat = compact ? 6 : 16 * scale
let gap: CGFloat = compact ? 3 : 5 * scale
let diameter: CGFloat = compact ? 32 : 41 * scale
let iconGap: CGFloat = compact ? 8 : 12 * scale
let textWidth = max(1, width - diameter - iconGap)
titleLabel.font = .systemFont(ofSize: compact ? 20 : max(20, 23 * scale), weight: .semibold)
reasonLabel.font = .systemFont(ofSize: max(12, 14 * scale))
adviceLabel.font = .systemFont(ofSize: max(12, 14 * scale))
titleLabel.numberOfLines = 1
reasonLabel.numberOfLines = compact ? 1 : 3
adviceLabel.numberOfLines = 1
noteLabel.numberOfLines = 1
adviceLabel.isHidden = extreme
let title = textHeight(presentation.title, font: titleLabel.font, width: textWidth, lines: 1)
let reasonPadding: CGFloat = compact ? 6 : 10 * scale
var reason = textHeight(reasonLabel.text, font: reasonLabel.font, width: textWidth - 16,
lines: reasonLabel.numberOfLines) + reasonPadding
let advice = extreme ? 0 : textHeight(adviceLabel.text, font: adviceLabel.font, width: textWidth, lines: 1)
let note = textHeight(noteLabel.text, font: noteLabel.font, width: width, lines: 1)
let actionHeight: CGFloat = compact ? 44 : max(44, 50 * scale)
let actionGap: CGFloat = compact ? 5 : 10 * scale
let noteGap: CGFloat = compact ? 3 : 4
var bodyHeight: CGFloat { title + reason + advice + gap * (extreme ? 1 : 2) }
// 长原因先限制可见行数,完整文本仍可点开;不挤压固定页脚或按钮。
while top * 2 + max(44, bodyHeight) + actionGap + actionHeight + noteGap + note > bounds.height,
reasonLabel.numberOfLines > 1 {
reasonLabel.numberOfLines -= 1
reason = textHeight(reasonLabel.text, font: reasonLabel.font, width: textWidth - 16,
lines: reasonLabel.numberOfLines) + reasonPadding
}
contentTop?.update(offset: top)
noticeHeight?.update(offset: max(44, bodyHeight))
iconSize?.update(offset: diameter)
iconBackground.layer.cornerRadius = diameter / 2
bodyLeading?.update(offset: diameter + iconGap)
titleHeight?.update(offset: title)
reasonHeight?.update(offset: reason)
adviceHeight?.update(offset: max(1, advice))
buttonHeight?.update(offset: actionHeight)
noteHeight?.update(offset: note)
body.spacing = gap
content.setCustomSpacing(actionGap, after: notice)
content.setCustomSpacing(noteGap, after: retryButton)
retryButton.configuration?.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var result = attributes
result.font = .systemFont(ofSize: compact ? 16 : max(16, 18 * scale), weight: .semibold)
return result
}
}
private func textHeight(_ text: String?, font: UIFont, width: CGFloat, lines: Int) -> CGFloat {
let height = ((text ?? "") as NSString).boundingRect(
with: CGSize(width: max(1, width), height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font: font], context: nil).height
return ceil(min(max(font.lineHeight, height), font.lineHeight * CGFloat(lines)))
}
@objc private func showDetails() { onDetails?() }
}
@@ -22,6 +22,7 @@ final class DroneDockTaskStatusView: UIView {
private let actionRow = UIView()
private let primaryButton = UIButton(type: .system)
private let detailsButton = UIButton(type: .system)
private let failureView = DroneDockTaskFailureView()
private var presentation: DroneDockTaskPresentation?
private var contentTop: Constraint?
private var contentLeading: Constraint?
@@ -47,9 +48,17 @@ final class DroneDockTaskStatusView: UIView {
CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)
}
/// 更新真实状态文案与动作许可,不补造百分比或自行推导飞行阶段。
func apply(_ presentation: DroneDockTaskPresentation) {
/// 更新真实状态与动作许可;刷新期间保留内容,只暂时禁用主操作。
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false) {
self.presentation = presentation
let isFailure = presentation.phase == .failed
contentStack.isHidden = isFailure
failureView.isHidden = !isFailure
if isFailure {
failureView.apply(presentation)
setNeedsLayout()
return
}
titleLabel.text = presentation.title
messageLabel.text = presentation.message
deviceLabel.text = presentation.deviceStatus
@@ -59,7 +68,7 @@ final class DroneDockTaskStatusView: UIView {
let actionTitle = DroneDockHomeMetric.usableText(presentation.actionTitle)
primaryButton.isHidden = presentation.action == .none || actionTitle == nil
primaryButton.setTitle(actionTitle, for: .normal)
primaryButton.isEnabled = presentation.isActionEnabled && !primaryButton.isHidden
primaryButton.isEnabled = presentation.isActionEnabled && !primaryButton.isHidden && !isRefreshing
primaryButton.backgroundColor = primaryButton.isEnabled
? DroneDockStyle.primary : DroneDockStyle.primary.withAlphaComponent(0.35)
primaryButton.accessibilityIdentifier = presentation.action == .refresh
@@ -69,12 +78,22 @@ final class DroneDockTaskStatusView: UIView {
/// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。
override func layoutSubviews() {
if presentation?.phase == .failed {
super.layoutSubviews()
failureView.layoutIfNeeded()
effectiveScale = failureView.effectiveScale
usesCompactLayout = failureView.usesCompactLayout
return
}
updateContentLayout()
super.layoutSubviews()
}
private func setupUI() {
backgroundColor = .white
addSubview(failureView)
failureView.isHidden = true
failureView.onDetails = { [weak self] in self?.onDetails?() }
contentStack.axis = .vertical
contentStack.alignment = .fill
contentStack.spacing = 10
@@ -115,6 +134,7 @@ final class DroneDockTaskStatusView: UIView {
}
private func setupConstraints() {
failureView.snp.makeConstraints { make in make.edges.equalToSuperview() }
contentStack.snp.makeConstraints { make in
contentTop = make.top.equalToSuperview().offset(12).constraint
contentLeading = make.leading.equalToSuperview().offset(16).constraint
@@ -4,7 +4,7 @@ import UIKit
/// 空镜库独立调试入口,不伪造正式首页权限,也不创建机巢工作台或订单。
@MainActor
enum ScenicMaterialsPreview {
/// 指定启动参数时展示独立素材库;正式首页入口等待实际权限 URI 配置。
/// 指定启动参数时展示演示素材;正式首页由 sceniclibrary 权限控制入口。
static func navigationController(arguments: [String]) -> UINavigationController? {
guard arguments.contains("--scenic-materials-preview") else { return nil }
let model = ScenicMaterialsViewModel()
@@ -37,7 +37,7 @@ final class ScenicMaterialsViewController: BaseViewController {
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupNavigationBar() {
title = "景区素材"
title = "景区空境库"
navigationItem.backButtonDisplayMode = .minimal
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
@@ -2,7 +2,7 @@ import Foundation
import XCTest
@testable import suixinkan
/// 验证真实任务页只读、同任务重入、身份检查及过期快照清除,不接入飞控。
/// 验证真实任务页只读刷新保留快照、同任务重入和身份隔离,不接入飞控。
@MainActor
final class DroneDockShootingTaskViewModelTests: XCTestCase {
/// 进入、刷新和返回始终读取传入的同一任务,构造本身不发请求。
@@ -51,17 +51,19 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase {
windText: "—", rainText: "—", signalText: "—", satelliteText: "—"))
}
/// 最近读取失败后不能继续展示上次的允许执行标记或设备读数。
func testFailureClearsPreviousResponseAndCanRecoverSameTask() async throws {
/// 普通刷新失败保留最近一次成功快照,错误单独提供,成功重试后清除错误。
func testFailurePreservesPreviousResponseAndCanRecoverSameTask() async throws {
let fixture = try ShootingTaskFixture(response: DroneDockShootingTaskTestData.response(changes: ["execute_gate": ["can_execute": true]]))
await fixture.model.refresh()
XCTAssertEqual(fixture.model.response?.executeGate?.canExecute, true)
let previousJSON = fixture.model.dataJSON
let previousPresentation = fixture.model.presentation
fixture.service.result = .failure(APIError.networkFailed("测试断网"))
await fixture.model.refresh()
XCTAssertNil(fixture.model.response)
XCTAssertNil(fixture.model.dataJSON)
XCTAssertTrue(fixture.model.isTelemetryStale)
XCTAssertEqual(fixture.model.telemetry.batteryText, "—")
XCTAssertEqual(fixture.model.dataJSON, previousJSON)
XCTAssertEqual(fixture.model.presentation, previousPresentation)
XCTAssertFalse(fixture.model.isTelemetryStale)
XCTAssertEqual(fixture.model.telemetry.batteryText, "0%")
XCTAssertEqual(fixture.model.errorMessage, "网络请求失败:测试断网")
fixture.service.result = .success(try DroneDockShootingTaskTestData.response())
await fixture.model.refresh()
@@ -69,6 +71,123 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase {
XCTAssertNil(fixture.model.errorMessage)
}
/// 挂起刷新时保留旧标题、阶段与读数,成功回包后一次性换为新快照。
func testRefreshRetainsSnapshotUntilNewSuccessfulSnapshotArrives() async throws {
let service = DeferredShootingTaskService()
let fixture = try ShootingTaskFixture(service: service)
defer { service.cancelAll() }
try await seedSnapshot(fixture, service: service)
let previousJSON = fixture.model.dataJSON
let previousTelemetry = fixture.model.telemetry
let pending = Task { await fixture.model.refresh() }
await waitForRequests(2, service: service)
XCTAssertTrue(fixture.model.isLoading)
XCTAssertEqual(fixture.model.dataJSON, previousJSON)
XCTAssertEqual(fixture.model.title, "测试点位 · 测试航线")
XCTAssertEqual(fixture.model.statusTitle, "任务尚未关联航线")
XCTAssertEqual(fixture.model.statusMessage, "测试阶段说明")
XCTAssertEqual(fixture.model.presentation.phase, .blocked)
XCTAssertFalse(fixture.model.presentation.isActionEnabled)
XCTAssertEqual(fixture.model.telemetry, previousTelemetry)
XCTAssertFalse(fixture.model.isTelemetryStale)
let next = try DroneDockShootingTaskTestData.response(changes: [
"header": ["title": "新的点位摘要"],
"ui": ["phase": "shooting", "title": "正在拍摄", "message": "新的任务说明"],
"current_plane": ["status_text": "拍摄中 · 电量 92%"],
"metrics": [["key": "battery", "value": "92%"]]
])
service.resolve(1, with: .success(next))
await pending.value
XCTAssertFalse(fixture.model.isLoading)
XCTAssertEqual(fixture.model.dataJSON, next.dataJSON)
XCTAssertEqual(fixture.model.title, "新的点位摘要")
XCTAssertEqual(fixture.model.presentation.phase, .shooting)
XCTAssertEqual(fixture.model.statusMessage, "新的任务说明")
XCTAssertEqual(fixture.model.deviceStatusText, "拍摄中 · 电量 92%")
XCTAssertEqual(fixture.model.telemetry.batteryText, "92%")
}
/// 取消刷新不能使已有内容闪空,也不能接纳被取消请求的迟到成功。
func testCancelledRefreshPreservesSnapshotAndRejectsLateData() async throws {
let service = DeferredShootingTaskService()
let fixture = try ShootingTaskFixture(service: service)
defer { service.cancelAll() }
try await seedSnapshot(fixture, service: service)
let previousJSON = fixture.model.dataJSON
let pending = Task { await fixture.model.refresh() }
await waitForRequests(2, service: service)
pending.cancel()
service.resolve(1, with: .success(try DroneDockShootingTaskTestData.response(changes: ["ui": ["title": "迟到状态"]])))
await pending.value
XCTAssertEqual(fixture.model.dataJSON, previousJSON)
XCTAssertFalse(fixture.model.isLoading)
XCTAssertFalse(fixture.model.isTelemetryStale)
XCTAssertNil(fixture.model.errorMessage)
}
/// 后台保留快照并使旧代次失效,回前台的新读取成功后旧请求不能覆盖。
func testPreservedInvalidationRejectsLateResponseAndAllowsNewRead() async throws {
let service = DeferredShootingTaskService()
let fixture = try ShootingTaskFixture(service: service)
defer { service.cancelAll() }
try await seedSnapshot(fixture, service: service)
let previousJSON = fixture.model.dataJSON
let oldRequest = Task { await fixture.model.refresh() }
await waitForRequests(2, service: service)
fixture.model.invalidate(preservingSnapshot: true)
XCTAssertEqual(fixture.model.dataJSON, previousJSON)
XCTAssertFalse(fixture.model.isLoading)
let newRequest = Task { await fixture.model.refresh() }
await waitForRequests(3, service: service)
XCTAssertEqual(fixture.model.dataJSON, previousJSON)
service.resolve(2, with: .success(try DroneDockShootingTaskTestData.response(changes: ["ui": ["title": "前台最新状态"]])))
await newRequest.value
service.resolve(1, with: .success(try DroneDockShootingTaskTestData.response(changes: ["ui": ["title": "后台迟到状态"]])))
await oldRequest.value
XCTAssertEqual(fixture.model.statusTitle, "前台最新状态")
XCTAssertEqual(service.requests, [501, 501, 501])
}
/// 即使要求保留快照,账号、景区或凭证变化也立即清除旧内容并锁定旧任务。
func testPreservedInvalidationClearsSnapshotAfterContextChange() async throws {
let fixture = try ShootingTaskFixture()
await fixture.model.refresh()
fixture.scope.context = DroneDockShootingTaskTestData.context(token: "changed-token")
fixture.model.invalidate(preservingSnapshot: true)
XCTAssertNil(fixture.model.response)
XCTAssertTrue(fixture.model.errorMessage?.contains("账号或景区已变化") == true)
await fixture.model.refresh()
XCTAssertEqual(fixture.service.requests.count, 1)
}
/// 保留旧快照的刷新途中换景区,回包时必须撤下旧快照并拒绝新数据。
func testContextChangeDuringRefreshClearsRetainedSnapshot() async throws {
let service = DeferredShootingTaskService()
let fixture = try ShootingTaskFixture(service: service)
defer { service.cancelAll() }
try await seedSnapshot(fixture, service: service)
let pending = Task { await fixture.model.refresh() }
await waitForRequests(2, service: service)
fixture.scope.context = DroneDockShootingTaskTestData.context(scenicID: 129)
service.resolve(1, with: .success(try DroneDockShootingTaskTestData.response()))
await pending.value
XCTAssertNil(fixture.model.response)
XCTAssertTrue(fixture.model.errorMessage?.contains("账号或景区已变化") == true)
await fixture.model.refresh()
XCTAssertEqual(service.requests.count, 2)
}
/// 服务端返回另一任务时清空缓存,不能把身份不匹配当作普通刷新失败。
func testMismatchedRefreshResponseClearsRetainedSnapshot() async throws {
let fixture = try ShootingTaskFixture()
await fixture.model.refresh()
fixture.service.result = .success(try DroneDockShootingTaskTestData.response(changes: ["task": ["id": 502]]))
await fixture.model.refresh()
XCTAssertNil(fixture.model.response)
XCTAssertTrue(fixture.model.isTelemetryStale)
XCTAssertTrue(fixture.model.errorMessage?.contains("不一致") == true)
}
/// 所有实际返回的任务、订单及景区身份都必须一致,不能只校验根层订单号。
func testAnyMismatchedReturnedIdentityIsRejected() async throws {
let cases: [[String: Any]] = [
@@ -176,6 +295,13 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase {
for _ in 0..<100 where service.requests.count < count { await Task.yield() }
XCTAssertEqual(service.requests.count, count)
}
private func seedSnapshot(_ fixture: ShootingTaskFixture, service: DeferredShootingTaskService) async throws {
let initial = Task { await fixture.model.refresh() }
await waitForRequests(1, service: service)
service.resolve(0, with: .success(try DroneDockShootingTaskTestData.response()))
await initial.value
}
}
/// 每项测试隔离订单、会话和读取服务,避免共享可变全局状态。
@@ -63,6 +63,58 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
capture(window, name: "真实拍摄任务-服务端状态与六项读数")
}
/// 航线失败使用产品失败组合,离线设备不能重召;刷新和查看原因都不发送飞控。
func testWaylineFailureShowsReasonAndOfflineNoteWithoutEnablingRetry() async throws {
let reason = "航线任务状态不可拍摄(当前:执行失败)"
var payload = TaskViewData.payload()
payload["task"] = ["id": 501, "status": 20, "wayline_status": 91, "wayline_status_label": "执行失败"]
payload["order_flight_task"] = ["id": 501, "order_number": "TEST-TASK-501", "scenic_id": 128, "status": 20]
payload["current_plane"] = ["id": 1, "online_status": 2, "work_status": 0,
"work_status_label": "离线", "status_text": "离线 · 电量94%"]
payload["execute_gate"] = ["can_execute": false, "code": "wayline_not_shooting", "message": reason]
payload["ui"] = ["phase": "blocked", "title": reason, "message": reason]
let response = try JSONDecoder().decode(DroneDockShootingResponse.self,
from: JSONSerialization.data(withJSONObject: payload))
let service = try TaskViewReadService(response: response)
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { service.cancelAll(); close(window) }
try await settle(window) { controller.viewModel.response != nil }
let texts = visibleTexts(in: controller.view)
XCTAssertTrue(texts.contains("任务执行失败"))
XCTAssertTrue(texts.contains("失败原因:\(reason)"))
XCTAssertTrue(texts.contains("请排查错误后再次召唤无人机。"))
XCTAssertTrue(texts.contains("无人机离线,暂不可召唤"))
XCTAssertFalse(texts.contains("无人机返航中,暂不可召唤"))
XCTAssertFalse(texts.contains("详情"))
XCTAssertFalse(texts.contains("刷新状态"))
let retry = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.failureRetry") as? UIButton)
XCTAssertEqual(retry.configuration?.title, "重新召唤无人机")
XCTAssertFalse(hidden(retry))
XCTAssertFalse(retry.isEnabled)
retry.sendActions(for: .touchUpInside)
XCTAssertEqual(service.requests, [501])
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
assertUnambiguousLayout(in: controller.view)
capture(window, name: "真实任务失败-原因条与离线重召禁用")
service.suspendNext = true
try tapNavigationRefresh(controller)
try await settle(window) { controller.viewModel.isLoading && service.requests.count == 2 }
XCTAssertEqual(visibleTexts(in: controller.view), texts, "失败态刷新也保留完整旧内容")
XCTAssertFalse(retry.isEnabled)
service.finish()
try await settle(window) { !controller.viewModel.isLoading && controller.navigationItem.rightBarButtonItem?.isEnabled == true }
let details = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.failureDetails") as? UIButton)
details.sendActions(for: .touchUpInside)
try await settle(window) { controller.presentedViewController is UIAlertController }
let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController)
XCTAssertTrue(alert.message?.contains(reason) == true)
XCTAssertTrue(alert.message?.contains("任务执行失败") == true)
XCTAssertEqual(service.requests, [501, 501])
controller.dismiss(animated: false)
}
/// 业务错误留在本页,重新加载只 GET 同一任务,不产生任何写请求。
func testFailureAndRetryOnlyReadSameTask() async throws {
let session = MockURLSession(responses: [
@@ -108,7 +160,7 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
try await Task.sleep(nanoseconds: 140_000_000)
XCTAssertEqual(service.requests, [501])
XCTAssertNil(controller.viewModel.response)
XCTAssertNotNil(controller.viewModel.response)
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
try await settle(window) { service.requests.count == 2 && controller.viewModel.response != nil }
@@ -118,7 +170,8 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
let navigation = try XCTUnwrap(controller.navigationController)
navigation.pushViewController(UIViewController(), animated: false)
try await settle(window) { controller.viewModel.response == nil && navigation.topViewController !== controller }
try await settle(window) { navigation.topViewController !== controller }
XCTAssertNotNil(controller.viewModel.response)
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
@@ -148,20 +201,29 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
XCTAssertEqual(service.requests, [501, 501, 501])
}
/// 新请求期间撤下旧状态与读数,连续刷新不会形成并发请求。
func testPendingRefreshShowsUnknownReadingsAndRejectsDoubleTap() async throws {
/// 新请求期间完整保留旧状态和读数,成功后一次替换,连续点击不形成并发请求。
func testPendingRefreshKeepsSnapshotUntilResponseAndRejectsDoubleTap() async throws {
let service = try TaskViewReadService()
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { service.cancelAll(); close(window) }
try await settle(window) { controller.viewModel.response != nil }
let oldTexts = visibleTexts(in: controller.view)
var payload = TaskViewData.payload()
payload["header"] = ["title": "更新后的点位与航线", "package_name": "更新后的套餐"]
payload["ui"] = ["phase": "shooting", "title": "正在拍摄", "message": "新的拍摄阶段"]
payload["current_plane"] = ["id": 1, "status_text": "拍摄中 · 电量81%"]
payload["metrics"] = [["key": "battery", "value": "81%"], ["key": "satellite", "value": "30颗"]]
service.response = try JSONDecoder().decode(DroneDockShootingResponse.self, from: JSONSerialization.data(withJSONObject: payload))
service.suspendNext = true
let refreshButton = try button(in: controller.view)
refreshButton.sendActions(for: .touchUpInside)
XCTAssertEqual(visibleTexts(in: controller.view), oldTexts, "发送请求前的同步刷新也不切换为空态")
try await settle(window) { controller.viewModel.isLoading && service.requests.count == 2 }
XCTAssertTrue(visibleTexts(in: controller.view).contains("正在获取任务状态"))
XCTAssertFalse(visibleTexts(in: controller.view).contains("空闲 · 电量93%"))
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "—")
XCTAssertEqual(visibleTexts(in: controller.view), oldTexts)
XCTAssertFalse(visibleTexts(in: controller.view).contains("正在获取任务状态"))
XCTAssertTrue(visibleTexts(in: controller.view).contains("空闲 · 电量93%"))
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "93%")
XCTAssertFalse(refreshButton.isEnabled)
XCTAssertEqual(controller.navigationItem.rightBarButtonItem?.isEnabled, false)
refreshButton.sendActions(for: .touchUpInside)
@@ -169,7 +231,12 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
XCTAssertEqual(service.requests.count, 2)
service.finish()
try await settle(window) { controller.viewModel.response != nil && !controller.viewModel.isLoading }
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "93%")
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "81%")
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.satellite")?.accessibilityValue, "30颗")
XCTAssertTrue(visibleTexts(in: controller.view).contains("更新后的点位与航线"))
XCTAssertTrue(visibleTexts(in: controller.view).contains("正在拍摄"))
XCTAssertFalse(visibleTexts(in: controller.view).contains("空闲 · 电量93%"))
XCTAssertTrue(refreshButton.isEnabled)
}
/// 后台取消后迟到回执不重新展示当前设备或遥测。
@@ -180,6 +247,7 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
let window = makeWindow(root: controller)
defer { service.cancelAll(); close(window) }
try await settle(window) { service.requests.count == 1 && controller.viewModel.isLoading }
XCTAssertTrue(visibleTexts(in: controller.view).contains("正在获取任务状态"))
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
service.finish()
try await Task.sleep(nanoseconds: 120_000_000)
@@ -190,6 +258,53 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
XCTAssertEqual(service.requests, [501])
}
/// 恢复前台发起的读取同样保留上次数据,等待新响应期间不出现空态。
func testForegroundRefreshKeepsPreviousSnapshotUntilNewResponse() async throws {
let service = try TaskViewReadService()
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { service.cancelAll(); close(window) }
try await settle(window) { controller.viewModel.response != nil }
let oldTexts = visibleTexts(in: controller.view)
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
XCTAssertNotNil(controller.viewModel.response)
service.suspendNext = true
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
try await settle(window) { controller.viewModel.isLoading && service.requests.count == 2 }
XCTAssertEqual(visibleTexts(in: controller.view), oldTexts)
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "93%")
service.finish()
try await settle(window) { !controller.viewModel.isLoading }
XCTAssertEqual(service.requests, [501, 501])
}
/// 二次刷新失败只提示错误,旧状态和读数继续显示,用户可以明确重试。
func testRefreshFailurePreservesDataAndOffersRetry() async throws {
let service = try TaskViewReadService()
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.response != nil }
service.nextError = APIError.networkFailed("测试刷新断网")
try tapNavigationRefresh(controller)
try await settle(window) { controller.viewModel.errorMessage != nil && !controller.viewModel.isLoading }
XCTAssertNotNil(controller.viewModel.response)
XCTAssertTrue(visibleTexts(in: controller.view).contains("航线任务未关联"))
XCTAssertTrue(visibleTexts(in: controller.view).contains("空闲 · 电量93%"))
XCTAssertFalse(visibleTexts(in: controller.view).contains("任务状态读取失败"))
XCTAssertTrue(visibleTexts(in: controller.view).contains { $0.contains("刷新失败,当前显示上次数据") })
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "93%")
let details = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.details") as? UIButton)
details.sendActions(for: .touchUpInside)
try await settle(window) { controller.presentedViewController is UIAlertController }
let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController)
XCTAssertTrue(alert.message?.contains("测试刷新断网") == true)
controller.dismiss(animated: false)
try button(in: controller.view).sendActions(for: .touchUpInside)
try await settle(window) { service.requests.count == 3 && controller.viewModel.errorMessage == nil }
XCTAssertNotNil(controller.viewModel.response)
}
/// 身份变化后重新读取撤下旧响应,不显示原账号的执行门禁或设备读数。
func testContextChangeRemovesPreviousTaskState() async throws {
let service = try TaskViewReadService()
@@ -395,6 +510,7 @@ private enum TaskViewData {
private final class TaskViewReadService: DroneDockShootingServing {
var response: DroneDockShootingResponse
var suspendNext = false
var nextError: Error?
private(set) var requests: [Int] = []
private var continuation: CheckedContinuation<DroneDockShootingResponse, Error>?
@@ -403,6 +519,10 @@ private final class TaskViewReadService: DroneDockShootingServing {
func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse {
XCTAssertTrue(liveBattery)
requests.append(taskID)
if let error = nextError {
nextError = nil
throw error
}
if suspendNext {
suspendNext = false
return try await withCheckedThrowingContinuation { continuation = $0 }
@@ -23,7 +23,7 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase {
}
}
/// 常规屏支持全部阶段,并保留完整设备状态行而不放大外部容器。
/// 常规屏支持全部阶段,失败态用独立原因区替代通用设备摘要。
func testAllPhasesFitRegularStatusArea() throws {
let status = makeStatus(size: regularSize)
for phase in phases {
@@ -31,8 +31,15 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase {
XCTAssertFalse(status.usesCompactLayout, "\(phase)")
XCTAssertEqual(status.bounds.size, regularSize)
let device = try XCTUnwrap(find(in: status, suffix: "deviceStatus") as? UILabel)
XCTAssertFalse(isHidden(device))
XCTAssertEqual(device.text, "空闲 · 电量 93%")
if phase == .failed {
XCTAssertTrue(isHidden(device))
let note = try XCTUnwrap(find(in: status, suffix: "failureNote") as? UILabel)
XCTAssertFalse(isHidden(note))
XCTAssertEqual(note.text, "无人机离线,暂不可召唤")
} else {
XCTAssertFalse(isHidden(device))
XCTAssertEqual(device.text, "空闲 · 电量 93%")
}
try assertReadableContainedContent(in: status)
}
}
@@ -46,10 +53,12 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase {
apply(value, to: status)
XCTAssertEqual(status.bounds.size, size)
XCTAssertEqual(status.transform, .identity)
let title = try XCTUnwrap(find(in: status, suffix: "statusTitle") as? UILabel)
let message = try XCTUnwrap(find(in: status, suffix: "statusMessage") as? UILabel)
let title = try XCTUnwrap(find(in: status, suffix: phase == .failed ? "failureTitle" : "statusTitle") as? UILabel)
let message = try XCTUnwrap(find(in: status, suffix: phase == .failed ? "failureReason" : "statusMessage") as? UILabel)
XCTAssertFalse(isHidden(title))
XCTAssertFalse(isHidden(message))
XCTAssertEqual(title.text, value.title, "视觉截断不能丢弃原始详情")
XCTAssertEqual(message.text, value.message)
XCTAssertEqual(message.text, phase == .failed ? "失败原因:\(value.message)" : value.message)
try assertReadableContainedContent(in: status)
}
}
@@ -74,6 +83,38 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase {
try assertReadableContainedContent(in: status)
}
/// 失败长原因在固定小屏与真实剩余高度内可展开,主按钮保持全宽且不能触发召唤。
func testFailureReasonDetailsAndDisabledRetryFitFixedAreas() throws {
for size in [compactSize, regularSize, CGSize(width: 402, height: 207.875)] {
let status = makeStatus(size: size)
let value = presentation(.failed, longCopy: true)
apply(value, to: status)
var detailsCalls = 0
var actionCalls = 0
status.onDetails = { detailsCalls += 1 }
status.onPrimaryAction = { actionCalls += 1 }
let details = try XCTUnwrap(find(in: status, suffix: "failureDetails") as? UIButton)
let retry = try XCTUnwrap(find(in: status, suffix: "failureRetry") as? UIButton)
let reason = try XCTUnwrap(find(in: status, suffix: "failureReason") as? UILabel)
XCTAssertEqual(reason.text, "失败原因:\(value.message)")
XCTAssertTrue(details.accessibilityLabel?.contains(value.message) == true)
XCTAssertFalse(isHidden(details))
XCTAssertGreaterThanOrEqual(details.bounds.height, 44)
let center = details.convert(CGPoint(x: details.bounds.midX, y: details.bounds.midY), to: status)
let hit = status.hitTest(center, with: nil)
XCTAssertTrue(hit === details || hit?.isDescendant(of: details) == true)
details.sendActions(for: .touchUpInside)
XCTAssertEqual(detailsCalls, 1)
XCTAssertEqual(retry.configuration?.title, "重新召唤无人机")
XCTAssertFalse(retry.isEnabled)
XCTAssertEqual(retry.bounds.width, details.bounds.width, accuracy: 0.5)
retry.sendActions(for: .touchUpInside)
XCTAssertEqual(actionCalls, 0)
XCTAssertTrue(isHidden(try XCTUnwrap(find(in: status, suffix: "details"))))
try assertReadableContainedContent(in: status)
}
}
/// 状态区只转发已允许的主操作,未接通的开始拍摄按钮不能借布局切换被启用。
func testActionAvailabilitySurvivesLayoutChanges() throws {
let status = makeStatus(size: compactSize)
@@ -160,7 +201,10 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase {
let samples: [(CGSize, DroneDockTaskPresentation, String)] = [
(regularSize, presentation(.ready), "状态区-常规402x220-准备就绪"),
(compactSize, presentation(.shooting), "状态区-紧凑375x146-拍摄中"),
(compactSize, presentation(.readError, longCopy: true), "状态区-紧凑375x146-超长错误")
(compactSize, presentation(.readError, longCopy: true), "状态区-紧凑375x146-超长错误"),
(regularSize, presentation(.failed), "状态区-常规402x220-任务执行失败"),
(compactSize, presentation(.failed, longCopy: true), "状态区-紧凑375x146-失败长原因"),
(CGSize(width: 402, height: 207.875), presentation(.failed), "状态区-实际402x208-任务执行失败")
]
for (size, value, name) in samples {
let status = makeStatus(size: size)
@@ -196,16 +240,17 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase {
case .paused: (title, action, actionTitle, enabled) = ("拍摄已暂停", .resume, "继续拍摄", false)
case .returning: (title, action, actionTitle, enabled) = ("无人机正在返航", .refresh, "刷新任务状态", true)
case .completed: (title, action, actionTitle, enabled) = ("本次拍摄已完成", .materials, "查看素材", true)
case .failed: (title, action, actionTitle, enabled) = ("航线任务执行失败", .refresh, "刷新任务状态", true)
case .failed: (title, action, actionTitle, enabled) = ("任务执行失败", .retry, "重新召唤无人机", false)
case .blocked: (title, action, actionTitle, enabled) = ("当前无法继续拍摄", .refresh, "刷新任务状态", true)
case .unknown: (title, action, actionTitle, enabled) = ("状态待确认", .refresh, "刷新任务状态", true)
case .readError: (title, action, actionTitle, enabled) = ("任务状态读取失败", .refresh, "重新加载", true)
}
let longTitle = String(repeating: "航线任务状态需要确认,", count: 8)
let longMessage = String(repeating: "服务端返回的完整错误说明需要保留供工作人员查看,请检查任务和设备状态。", count: 12)
return DroneDockTaskPresentation(phase: phase, title: longCopy ? longTitle : title,
message: longCopy ? longMessage : "请确认当前状态后继续操作。", deviceStatus: "空闲 · 电量 93%",
action: action, actionTitle: actionTitle, isActionEnabled: enabled)
return DroneDockTaskPresentation(phase: phase, title: longCopy && phase != .failed ? longTitle : title,
message: longCopy ? longMessage : phase == .failed ? "拍摄指令执行失败" : "请确认当前状态后继续操作。",
deviceStatus: "空闲 · 电量 93%", action: action, actionTitle: actionTitle, isActionEnabled: enabled,
actionNote: phase == .failed ? "无人机离线,暂不可召唤" : nil)
}
private func makeController(service: any DroneDockShootingServing, size: CGSize) throws -> DroneDockShootingTaskViewController {
@@ -248,7 +293,9 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase {
}
}
}
let details = try XCTUnwrap(find(in: status, suffix: "details") as? UIButton, file: file, line: line)
let failure = try XCTUnwrap(find(in: status, suffix: "failure"), file: file, line: line)
let detailsSuffix = isHidden(failure) ? "details" : "failureDetails"
let details = try XCTUnwrap(find(in: status, suffix: detailsSuffix) as? UIButton, file: file, line: line)
XCTAssertFalse(isHidden(details), file: file, line: line)
}
@@ -9,7 +9,7 @@ final class DroneDockTaskPresentationTests: XCTestCase {
func testExplicitDisplayPhaseFixturesPreserveBackendText() async throws {
let phases: [(String, DroneDockTaskDisplayPhase)] = [
("navigating", .navigating), ("shooting", .shooting), ("paused", .paused),
("returning", .returning), ("failed", .failed), ("blocked", .blocked)
("returning", .returning), ("blocked", .blocked)
]
for (phase, expected) in phases {
let result = try await presentation([
@@ -71,10 +71,71 @@ final class DroneDockTaskPresentationTests: XCTestCase {
"commands": [["command": "flighttask_pause", "label": "紧急暂停"], ["command": "return_home", "label": "立即返航"]]]
])
XCTAssertEqual(result.phase, .failed)
XCTAssertEqual(result.title, "执行失败")
XCTAssertEqual(result.title, "任务执行失败")
XCTAssertEqual(result.message, reason)
XCTAssertEqual(result.action, .refresh)
XCTAssertTrue(result.isActionEnabled)
XCTAssertEqual(result.action, .retry)
XCTAssertEqual(result.actionTitle, "重新召唤无人机")
XCTAssertFalse(result.isActionEnabled)
XCTAssertEqual(result.actionNote, "暂不可重新召唤,请返回准备页确认设备状态")
}
/// 开始拍摄门禁允许也不代表可重新召唤,失败标题与按钮保持产品失败态。
func testWaylineFailureRetryRemainsDisabledDespiteExecutePermission() async throws {
let result = try await presentation([
"task": ["id": 501, "status": 20, "wayline_status": 91],
"ui": ["phase": "arrived_pending_start", "title": "无人机已到达"],
"execute_gate": ["can_execute": true, "primary_action": "start_shoot"]
])
XCTAssertEqual(result.phase, .failed)
XCTAssertEqual(result.title, "任务执行失败")
XCTAssertEqual(result.action, .retry)
XCTAssertEqual(result.actionTitle, "重新召唤无人机")
XCTAssertFalse(result.isActionEnabled)
XCTAssertEqual(result.message, "暂未返回具体失败原因")
}
/// 任务结果中的具体失败原因优先于门禁通用说明,空结果退回门禁,不丢失真实原因。
func testFailureReasonPrefersTaskResultThenGateThenUI() async throws {
let base: [String: Any] = [
"ui": ["phase": "failed", "title": "服务端标题", "message": "阶段说明"],
"execute_gate": ["message": "航线不可拍摄"]
]
let cases: [([String: Any], String)] = [
(["order_flight_task": ["result_message": "任务明确失败原因"], "task": ["result_message": "摘要原因"]], "任务明确失败原因"),
(["order_flight_task": ["result_message": " "], "task": ["result_message": "摘要失败原因"]], "摘要失败原因"),
(["order_flight_task": ["result_message": NSNull()]], "航线不可拍摄"),
(["execute_gate": ["message": " "]], "阶段说明")
]
for (changes, expected) in cases {
let result = try await presentation(base.merging(changes) { _, new in new })
XCTAssertEqual(result.title, "任务执行失败")
XCTAssertEqual(result.message, expected)
XCTAssertFalse(result.isActionEnabled)
}
}
/// 明确离线或返航才显示对应限制,空闲与未知保持中性,不能冒称已具备重新召唤条件。
func testFailureActionNoteUsesOnlyExplicitDeviceState() async throws {
let neutral = "暂不可重新召唤,请返回准备页确认设备状态"
let cases: [([String: Any], String)] = [
(["online_status": 2, "work_status": 0, "work_status_label": "离线"], "无人机离线,暂不可召唤"),
(["online_status": 2, "work_status_label": "返航中"], "无人机离线,暂不可召唤"),
(["work_status": 0], "无人机离线,暂不可召唤"),
(["work_status_label": "返航中"], "无人机返航中,暂不可召唤"),
(["work_status_label": "正在返航"], "无人机返航中,暂不可召唤"),
(["online_status": 1, "work_status": 1, "work_status_label": "空闲"], neutral),
([:], neutral)
]
for (plane, expected) in cases {
let result = try await presentation([
"task": ["wayline_status": 91], "current_plane": plane
])
XCTAssertEqual(result.actionNote, expected)
XCTAssertEqual(result.action, .retry)
XCTAssertFalse(result.isActionEnabled)
}
let normal = try await presentation(["ui": ["phase": "navigating"]])
XCTAssertNil(normal.actionNote)
}
/// 仅明确完成且无活动阶段冲突时开放素材入口;完成后仍返航时继续展示返航。
@@ -119,32 +180,37 @@ final class DroneDockTaskPresentationTests: XCTestCase {
func testFailedAndCancelledTaskStatesOverrideOptimisticUI() async throws {
let failed = try await presentation(["task": ["status": 40, "status_label": "执行失败"], "ui": ["phase": "completed"]])
XCTAssertEqual(failed.phase, .failed)
XCTAssertEqual(failed.title, "执行失败")
XCTAssertEqual(failed.action, .refresh)
XCTAssertEqual(failed.title, "任务执行失败")
XCTAssertEqual(failed.action, .retry)
XCTAssertFalse(failed.isActionEnabled)
let cancelled = try await presentation(["task": ["status": 50, "status_label": "任务已取消"], "ui": ["phase": "shooting"]])
XCTAssertEqual(cancelled.phase, .blocked)
XCTAssertEqual(cancelled.title, "任务已取消")
XCTAssertEqual(cancelled.action, .refresh)
}
/// 当前请求失败后覆盖旧完成态,清除素材入口并提供只读重试。
func testReadErrorOverridesPreviousCompletedPresentation() async throws {
/// 刷新失败继续展示旧完成态,但不允许按旧快照进入素材,错误由页面另行提示。
func testReadErrorPreservesPreviousCompletedPresentationAndDisablesAction() async throws {
let service = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.decode(["task": ["status": 30]])))
let model = try makeModel(service: service)
await model.refresh()
XCTAssertEqual(model.presentation.action, .materials)
let previous = model.presentation
let readError = APIError.networkFailed("测试读取失败")
service.result = .failure(readError)
await model.refresh()
XCTAssertEqual(model.presentation.phase, .readError)
XCTAssertEqual(model.presentation.message, readError.localizedDescription)
XCTAssertEqual(model.presentation.action, .refresh)
XCTAssertTrue(model.presentation.isActionEnabled)
XCTAssertEqual(model.presentation.phase, .completed)
XCTAssertEqual(model.presentation.title, previous.title)
XCTAssertEqual(model.presentation.message, previous.message)
XCTAssertEqual(model.presentation.action, .materials)
XCTAssertEqual(model.presentation.actionTitle, previous.actionTitle)
XCTAssertFalse(model.presentation.isActionEnabled)
XCTAssertEqual(model.errorMessage, readError.localizedDescription)
XCTAssertEqual(model.presentation.deviceStatus, "—")
}
/// 请求进行中仅显示加载,无可执行主动作,也不保留前一次完成入口。
func testLoadingOverridesPreviousCompletedPresentation() async throws {
/// 刷新中保留上一阶段及动作文案,主动作禁用至本次读取成功。
func testLoadingPreservesPreviousCompletedPresentationWithDisabledAction() async throws {
let service = PresentationPendingService(response: try DroneDockShootingTaskTestData.decode(["task": ["status": 30]]))
let model = try makeModel(service: service)
await model.refresh()
@@ -152,13 +218,43 @@ final class DroneDockTaskPresentationTests: XCTestCase {
let pending = Task { await model.refresh() }
for _ in 0..<100 where !service.isPending { await Task.yield() }
XCTAssertTrue(service.isPending)
XCTAssertEqual(model.presentation.phase, .loading)
XCTAssertEqual(model.presentation.action, .none)
XCTAssertNil(model.presentation.actionTitle)
XCTAssertEqual(model.presentation.phase, .completed)
XCTAssertEqual(model.presentation.action, .materials)
XCTAssertEqual(model.presentation.actionTitle, "查看素材")
XCTAssertFalse(model.presentation.isActionEnabled)
service.finish()
await pending.value
XCTAssertEqual(model.presentation.phase, .completed)
XCTAssertTrue(model.presentation.isActionEnabled)
}
/// 没有任何成功快照时仍显示首次加载,不能虚构此前阶段。
func testInitialReadWithoutSnapshotShowsLoading() async throws {
let service = PresentationPendingService(response: try DroneDockShootingTaskTestData.decode(["task": ["status": 30]]))
service.shouldHold = true
let model = try makeModel(service: service)
let pending = Task { await model.refresh() }
for _ in 0..<100 where !service.isPending { await Task.yield() }
XCTAssertTrue(service.isPending)
XCTAssertEqual(model.presentation.phase, .loading)
XCTAssertEqual(model.presentation.action, .none)
XCTAssertFalse(model.presentation.isActionEnabled)
XCTAssertNil(model.response)
service.finish()
await pending.value
}
/// 首次读取失败没有快照可保留,继续显示错误及重新读取动作。
func testInitialReadErrorWithoutSnapshotShowsFailure() async throws {
let readError = APIError.networkFailed("首次读取失败")
let service = DroneDockShootingTaskTestService(result: .failure(readError))
let model = try makeModel(service: service)
await model.refresh()
XCTAssertEqual(model.presentation.phase, .readError)
XCTAssertEqual(model.presentation.message, readError.localizedDescription)
XCTAssertEqual(model.presentation.action, .refresh)
XCTAssertTrue(model.presentation.isActionEnabled)
XCTAssertNil(model.response)
}
private func presentation(_ payload: [String: Any]) async throws -> DroneDockTaskPresentation {
@@ -0,0 +1,73 @@
import UIKit
import XCTest
@testable import suixinkan
/// 验证空境库正式权限入口使用当前景区,且不注入本地预览素材。
@MainActor
final class ScenicLibraryHomeRouteTests: XCTestCase {
/// 未选景区时沿用首页提示,不能打开空境库。
func testScenicLibraryRequiresSelectedScenic() {
withTemporaryScenic(0) {
let root = ScenicLibraryRouteProbeController()
let navigation = UINavigationController(rootViewController: root)
HomeRouteHandler.open(uri: "sceniclibrary", from: root, storeItem: nil)
XCTAssertTrue(navigation.topViewController === root)
XCTAssertEqual(navigation.viewControllers.count, 1)
XCTAssertEqual(root.lastPresentedMessage, "请先选择景区")
}
}
/// 正式入口传递真实账号和景区;未接入素材接口前不展示演示航线或片段。
func testScenicLibraryOpensCurrentScenicWithoutDemoMaterials() throws {
try withTemporaryScenic(271) {
let session = AppStore.shared.session
let root = ScenicLibraryRouteProbeController()
let navigation = UINavigationController(rootViewController: root)
HomeRouteHandler.open(uri: "sceniclibrary", from: root, storeItem: nil)
let library = try XCTUnwrap(navigation.topViewController as? ScenicMaterialsViewController)
XCTAssertEqual(navigation.viewControllers.count, 2)
XCTAssertTrue(library.hidesBottomBarWhenPushed)
XCTAssertEqual(library.viewModel.context.userID, session.userId)
XCTAssertEqual(library.viewModel.context.scenicID, "271")
XCTAssertEqual(library.viewModel.context.scenicName, "测试景区")
XCTAssertTrue(library.viewModel.routes.isEmpty)
XCTAssertTrue(library.viewModel.allGroups.isEmpty)
XCTAssertFalse(library.viewModel.canStartDownload)
XCTAssertNil(root.lastPresentedMessage)
library.loadViewIfNeeded()
XCTAssertEqual(library.title, "景区空境库")
}
}
/// 使用独立账号键,退出测试后还原真机会话并删除临时景区数据。
private func withTemporaryScenic(_ scenicID: Int, perform body: () throws -> Void) rethrows {
let session = AppStore.shared.session
let originalUserID = session.userId
let originalAccountType = session.accountType
session.configureTestAccount(userId: "scenic-library-route-\(UUID().uuidString)", scenicId: scenicID)
session.currentScenicName = "测试景区"
let temporaryKeys = ["key_in_current_scenic_id", "key_in_current_scenic_name"]
.compactMap { session.accountScopedKey($0) }
defer {
temporaryKeys.forEach { UserDefaults.standard.removeObject(forKey: $0) }
session.userId = originalUserID
session.accountType = originalAccountType
}
try body()
}
}
/// 捕获首页的景区选择提示,测试不创建真实弹层。
@MainActor
private final class ScenicLibraryRouteProbeController: UIViewController {
private(set) var lastPresentedMessage: String?
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
lastPresentedMessage = (viewControllerToPresent as? UIAlertController)?.message
completion?()
}
}
@@ -0,0 +1,178 @@
import XCTest
@testable import suixinkan
/// 验证景区空境库由后台权限控制,并沿用首页与全部功能共享的常用配置。
@MainActor
final class ScenicLibraryPermissionTests: XCTestCase {
/// 接口顶层权限生成本地入口;撤权后残留常用配置不能继续展示或重新添加入口。
func testPermissionResponseBuildsEntryAndRevocationHidesSavedMenu() async throws {
let fixture = try makeFixture()
defer { fixture.defaults.removePersistentDomain(forName: fixture.suiteName) }
let appStore = fixture.appStore
let menuStore = fixture.menuStore
let session = MockURLSession(responses: [
permissionResponse(includeScenicLibrary: true),
permissionResponse(includeScenicLibrary: false),
])
let api = HomeAPI(client: APIClient(environment: .testing, session: session))
let home = makeHome(appStore: appStore, menuStore: menuStore)
let functions = AllFunctionsViewModel(appStore: appStore, commonMenuStore: menuStore)
await home.loadPermissions(api: api, force: true)
functions.loadFunctions()
XCTAssertFalse(home.showPermissionDialog)
XCTAssertEqual(appStore.permissions.permissionItems().map(\.id), ["1", "369"])
XCTAssertEqual(appStore.permissions.permissionItems().map(\.uri), ["wallet", "sceniclibrary"])
XCTAssertEqual(home.commonMenus.map(\.uri), ["wallet", "sceniclibrary"])
let scenicLibrary = try XCTUnwrap(home.commonMenus.first { $0.uri == "sceniclibrary" })
XCTAssertEqual(scenicLibrary.title, "景区空境库")
XCTAssertEqual(scenicLibrary.iconName, "photo.on.rectangle.angled")
XCTAssertEqual(scenicLibrary.serverName, "后台配置的空境入口")
XCTAssertEqual(functions.commonMenus.map(\.uri), ["wallet", "sceniclibrary"])
XCTAssertTrue(functions.moreMenus.isEmpty)
await home.loadPermissions(api: api, force: true)
functions.loadFunctions()
XCTAssertFalse(home.showPermissionDialog)
XCTAssertEqual(appStore.permissions.permissionItems().map(\.uri), ["wallet"])
XCTAssertEqual(home.commonMenus.map(\.uri), ["wallet"])
XCTAssertEqual(functions.commonMenus.map(\.uri), ["wallet"])
XCTAssertTrue(functions.moreMenus.isEmpty)
XCTAssertEqual(menuStore.savedCommonURIs(accountScope: appStore.session.accountCachePrefix,
roleCode: appStore.session.roleCode),
["wallet", "sceniclibrary"])
functions.addToCommon(scenicLibrary)
home.rebuildCommonMenus()
XCTAssertEqual(functions.commonMenus.map(\.uri), ["wallet"])
XCTAssertTrue(functions.moreMenus.isEmpty)
XCTAssertEqual(home.commonMenus.map(\.uri), ["wallet"])
XCTAssertEqual(session.requests.map { $0.httpMethod }, ["GET", "GET"])
XCTAssertEqual(session.requests.map { $0.url?.path }, [
"/api/yf-handset-app/role-permission",
"/api/yf-handset-app/role-permission",
])
}
/// 已保存的钱包常用配置保持有效,用户增删空境库后首页读取同一份配置。
func testExistingCommonSelectionChangesOnlyAfterAddingOrRemovingScenicLibrary() throws {
let fixture = try makeFixture()
defer { fixture.defaults.removePersistentDomain(forName: fixture.suiteName) }
let appStore = fixture.appStore
let menuStore = fixture.menuStore
appStore.permissions.savePermissionItems([walletPermission, scenicLibraryPermission])
menuStore.saveCommonURIs(["wallet"], accountScope: appStore.session.accountCachePrefix,
roleCode: appStore.session.roleCode)
let functions = AllFunctionsViewModel(appStore: appStore, commonMenuStore: menuStore)
let home = makeHome(appStore: appStore, menuStore: menuStore)
functions.loadFunctions()
home.rebuildCommonMenus()
XCTAssertEqual(functions.commonMenus.map(\.uri), ["wallet"])
XCTAssertEqual(functions.moreMenus.map(\.uri), ["sceniclibrary"])
XCTAssertEqual(home.commonMenus.map(\.uri), ["wallet"])
let scenicLibrary = try XCTUnwrap(functions.moreMenus.first)
functions.addToCommon(scenicLibrary)
home.rebuildCommonMenus()
XCTAssertEqual(functions.commonMenus.map(\.uri), ["wallet", "sceniclibrary"])
XCTAssertTrue(functions.moreMenus.isEmpty)
XCTAssertEqual(home.commonMenus.map(\.uri), ["wallet", "sceniclibrary"])
XCTAssertEqual(menuStore.savedCommonURIs(accountScope: appStore.session.accountCachePrefix,
roleCode: appStore.session.roleCode),
["wallet", "sceniclibrary"])
functions.removeFromCommon(scenicLibrary)
functions.loadFunctions()
home.rebuildCommonMenus()
XCTAssertEqual(functions.commonMenus.map(\.uri), ["wallet"])
XCTAssertEqual(functions.moreMenus.map(\.uri), ["sceniclibrary"])
XCTAssertEqual(home.commonMenus.map(\.uri), ["wallet"])
XCTAssertEqual(menuStore.savedCommonURIs(accountScope: appStore.session.accountCachePrefix,
roleCode: appStore.session.roleCode), ["wallet"])
}
/// 首次无自定义时沿用权限前四项策略,第五项空境库保留在更多功能。
func testDefaultFirstFourKeepsScenicLibraryInMoreFunctions() throws {
let fixture = try makeFixture()
defer { fixture.defaults.removePersistentDomain(forName: fixture.suiteName) }
let appStore = fixture.appStore
let menuStore = fixture.menuStore
appStore.permissions.savePermissionItems([
walletPermission,
HomePermissionItem(id: "cloud", name: "云盘", uri: "cloud_management"),
HomePermissionItem(id: "task", name: "任务", uri: "task_management"),
HomePermissionItem(id: "settings", name: "设置", uri: "system_settings"),
scenicLibraryPermission,
])
let functions = AllFunctionsViewModel(appStore: appStore, commonMenuStore: menuStore)
let home = makeHome(appStore: appStore, menuStore: menuStore)
functions.loadFunctions()
home.rebuildCommonMenus()
let expected = ["wallet", "cloud_management", "task_management", "system_settings"]
XCTAssertEqual(functions.commonMenus.map(\.uri), expected)
XCTAssertEqual(home.commonMenus.map(\.uri), expected)
XCTAssertEqual(functions.moreMenus.map(\.uri), ["sceniclibrary"])
XCTAssertEqual(menuStore.savedCommonURIs(accountScope: appStore.session.accountCachePrefix,
roleCode: appStore.session.roleCode), expected)
}
private var walletPermission: HomePermissionItem {
HomePermissionItem(id: "1", name: "我的钱包", uri: "wallet")
}
private var scenicLibraryPermission: HomePermissionItem {
HomePermissionItem(id: "369", name: "后台配置的空境入口", uri: "sceniclibrary")
}
/// 模拟后台顶层节点省略 children 的授权与撤权响应,角色保持不变。
private func permissionResponse(includeScenicLibrary: Bool) -> Data {
let scenicLibrary = includeScenicLibrary
? #",{"icon_src":"","id":369,"name":"后台配置的空境入口","pid":0,"uri":"sceniclibrary"}"#
: ""
return Data("""
{
"code": 100000,
"msg": "success",
"data": [{
"role": {
"id": 41,
"name": "摄影师",
"role_code": "photographer",
"notes": null,
"permission": [
{"icon_src":"","id":1,"name":"我的钱包","pid":0,"uri":"wallet"}\(scenicLibrary)
]
},
"scenic": [{"id":11,"name":"测试景区","status":1}],
"store": []
}]
}
""".utf8)
}
/// 独立账号与 UserDefaults 隔离权限、景区和常用配置,不读写真机现有会话。
private func makeFixture() throws -> (suiteName: String, defaults: UserDefaults, appStore: AppStore, menuStore: HomeCommonMenuStore) {
let suiteName = "ScenicLibraryPermissionTests.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName))
let appStore = AppStore(defaults: defaults)
appStore.session.configureTestAccount(userId: "scenic-library-menu", scenicId: 11)
appStore.session.currentScenicName = "测试景区"
appStore.session.roleCode = AppRoleCode.photographer.rawValue
return (suiteName, defaults, appStore, HomeCommonMenuStore(defaults: defaults))
}
/// 定位与在线状态均使用隔离替身,菜单测试不触发真实接口或系统授权。
private func makeHome(appStore: AppStore, menuStore: HomeCommonMenuStore) -> HomeViewModel {
HomeViewModel(appStore: appStore, locationStateStore: HomeLocationStateStore(store: appStore),
commonMenuStore: menuStore, locationProvider: MockLocationProvider())
}
}
+24 -6
View File
@@ -1,7 +1,7 @@
# 机巢工作台页面接口对接记录
> 更新日期:2026-10-29
> 核对范围:当前工作区。准备页使用张工 `project-info` 和朱工 `plane-status`;“确认并召唤”按 `project-info → tasks/create → shoot` 执行,召唤业务成功后进入任务页;按用户最新要求,`shooting` 已取消定时轮询,仅在进入页面、页面可见时返回前台或手动刷新时各读取一次同一任务。准备页 `plane-status` 保持轮询。2026-10-29 16:03 按用户明确要求新建任务 6,再以 `{id:6,restart:false}` 召唤,两个接口均业务成功并绑定飞机 61、航线任务 1926;但 16:04:52 只读回查显示航线“执行失败”、禁止拍摄,当前待排查 1926 失败原因及飞机 61 在线状态。召唤回执的“已到达”不是物理验证,本轮未调用开始拍摄或控制接口。任务 2 的参数、订单类型及机场状态失败保留为历史,原因不因新任务成功而作推断。`workbench`、定位请求已停用;图传、`start-shoot/command` 尚未接入,真实成片上传仍待联调。
> 核对范围:当前工作区。准备页使用张工 `project-info` 和朱工 `plane-status`;“确认并召唤”按 `project-info → tasks/create → shoot` 执行,召唤业务成功后进入任务页;按用户最新要求,`shooting` 已取消定时轮询,仅在进入页面、页面可见时返回前台或手动刷新时各读取一次同一任务。准备页 `plane-status` 保持轮询。最新 2026-10-29 17:18–17:19 模拟器实操新建任务 11,再以 `{id:11,restart:false}` 召唤;两个接口均成功,绑定飞机 61、航线任务 1931。17:19:04 首次查询允许开始,17:19:59 手动回查已为航线执行失败、禁止拍摄,当前待朱工定位 1931 失败原因与自动派机条件(见 7.7.3)。任务 6 / 航线 1926 的先前失败记录保留。召唤回执的“已到达”不是物理验证,本轮未调用开始拍摄或控制接口。任务 2 的参数、订单类型及机场状态失败保留为历史,原因不因新任务成功而作推断。`workbench`、定位请求已停用;图传、`start-shoot/command` 尚未接入,真实成片上传仍待联调。
> 用途:记录每个页面实际调用的接口、提供人、调用时机、请求参数和返回 JSON,供 iOS 与后端持续联调。
## 1. 阅读说明
@@ -1005,7 +1005,7 @@ API:[DroneDockShootingAPI.swift](suixinkan/Features/DroneDock/API/DroneDockSho
`GET /api/app/airport/shooting?id=<tasks/create 返回的 task_id>&live_battery=1`
**当前状态:真实拍摄任务页已接入,类型 25 已读取成功;最新任务 6 的召唤后回查显示航线执行失败、禁止拍摄,见 7.7.2。** 朱工 2026-10-29 14:50 版文档约定根据外部已创建的 `order_flight_task.id` 反查任务、航线、点位、景区及飞机信息;该接口只读任务,不创建或召唤。准备页在 `shoot` 业务成功后自动进入此页,首次 GET 在任务页实际出现后发送;任务 ID 始终来自同次创建回执。DEBUG 只读入口还可读取明确已存在的测试任务,不代表已执行召唤。
**当前状态:真实拍摄任务页已接入,类型 25 已读取成功;最新任务 11 的召唤后回查显示航线执行失败、禁止拍摄,见 7.7.3。** 朱工 2026-10-29 14:50 版文档约定根据外部已创建的 `order_flight_task.id` 反查任务、航线、点位、景区及飞机信息;该接口只读任务,不创建或召唤。准备页在 `shoot` 业务成功后自动进入此页,首次 GET 在任务页实际出现后发送;任务 ID 始终来自同次创建回执。DEBUG 只读入口还可读取明确已存在的测试任务,不代表已执行召唤。
| 参数 | 必填 | 当前来源 |
| --- | --- | --- |
@@ -1018,6 +1018,10 @@ API:[DroneDockShootingAPI.swift](suixinkan/Features/DroneDock/API/DroneDockSho
空间不足时收紧间距、图标和字号,正文不小于 12 点,操作点击高度不小于 44 点;紧凑布局可隐藏设备摘要、截断长文案,通过“详情”查看完整说明。未确认或冲突状态显示待确认,不补造进度。开始/恢复拍摄及底部暂停/返航仍是禁用状态,不调用控制接口;只有明确完成态提供“查看素材”,进入当前订单的真实订单素材库。
2026-10-29 失败态按产品体验网页单独组合:淡红圆底警示图标、固定标题“任务执行失败”、淡红失败原因条、排查提示、全宽带循环箭头的“重新召唤无人机”按钮和设备限制提示。不再显示通用“刷新状态+详情”按钮行;点击失败原因区域仍可查看完整说明,导航栏仍可手动刷新。原因优先使用 `order_flight_task.result_message / task.result_message`,再使用 `execute_gate.message / ui.message`;任务 11 当前明确离线,显示“无人机离线,暂不可召唤”,不套用网页示例的“返航中”。重新召唤尚未接入,始终禁用,不能将 `can_execute` 开始拍摄许可用于重召。顶部、底部位置固定,小屏仅收紧中间区域排版。
失败态对齐验证:模拟器 **65 项相关测试通过**(API 12、ViewModel 16、页面 15、固定布局 8、展示 14)。覆盖 375×146、402×220、402×207.875 的中间区域、长原因查看详情、禁用重召、固定三区及刷新保留旧内容;另以任务 11 的真实只读 `shooting` 响应验证页面,没有重新创建或召唤任务。
2026-10-29 16:56 模拟器重新运行此固定布局页面,只读 `shooting?id=6&live_battery=1` 一次。真实回执仍显示航线执行失败、当前设备离线,页面如实展示错误原因与当前六项读数;没有调用创建、召唤或飞行控制。本地截图(不纳入 Git):`docs/9.9.1/shooting-integration-2026-10-29/task6-fixed-layout-real.jpg`。
固定布局阶段验证:模拟器构建成功,相关 **52 项不同测试通过**(任务 API 12、任务 ViewModel 10、任务页面 12、布局 7、阶段展示 9、准备页串接 1、共用遥测旧页面回归 1)。首轮错误文案用例遗漏通用网络错误前缀,修正测试预期后阶段展示 9 项复跑通过;实际内容区域 `375×603`、`402×734` 的布局 7 项再次通过。覆盖 11 种展示状态、长文案与详情、固定区域不随加载/状态/遥测变化、最小点击尺寸、完成态素材导航、单次 GET 及无轮询。阶段组合使用匿名替身验证;真实任务仍处于失败态,没有模拟飞控执行成功。
@@ -1025,11 +1029,13 @@ API:[DroneDockShootingAPI.swift](suixinkan/Features/DroneDock/API/DroneDockSho
**当前刷新与生命周期(按用户要求取消任务页定时轮询):**
1. 每次进入任务页且 App 活跃时读取一次;返回前台且任务页仍可见时读取一次。不设定时器,不按 5 秒或 `plane_status.poll_hint_ms` 自动重复请求,不叠加未完成请求。
2. 已移除下拉刷新;点击导航栏刷新按钮、中间状态区的“刷新状态”或错误后的“重新读取”,各只 GET 同一个任务 ID 一次。读取失败撤下旧任务状态、执行门禁和读数,显示错误,不自动重试;后续进入页面、返回前台或手动刷新仍只读,不重建任务或重新召唤。
3. 离开任务页或 App 失去活跃状态时取消进行中的请求,清除旧快照并拒绝迟到响应;不在后台或页面不可见时读取。
2. 已移除下拉刷新;点击导航栏刷新按钮、中间状态区的“刷新状态”或错误后的“重新读取”,各只 GET 同一个任务 ID 一次。首次读取无数据时显示加载;已有成功快照时,刷新期间保留标题、任务状态、设备状态和六项读数,成功后一次性替换为新快照,不先切成空态。刷新中暂时禁用操作,防止重复请求。普通刷新失败保留旧数据并提示“刷新失败,当前显示上次数据”,详情也保留错误原因;非刷新动作保持禁用,用户可通过导航栏重试。首次读取失败仍显示错误页,不自动重试。
3. 离开任务页或 App 失去活跃状态时取消进行中的请求并拒绝迟到响应;同一个页面实例、同一身份保留最近成功快照,返回后继续展示至新请求成功。不在后台或页面不可见时读取,不重建任务或重新召唤;账号、景区或门店等身份变化、响应身份不匹配时仍清除旧快照。
4. 响应内提供的任务 ID、订单号、景区 ID 均与页面身份核对;账号、Token、景区或门店变化后不再使用旧页面读取。
5. 返回同一个准备页实例后保留创建和召唤回执,按钮为“查看拍摄任务”;再次点击仅导航到原任务,没有第二次 `tasks/create` 或 `shoot`。自动跳转对同一任务只触发一次。
保留刷新快照阶段验证:模拟器 **49 项相关测试通过**(任务 ViewModel 16、阶段展示 11、任务页面 14、固定布局 7、准备页串接 1)。挂起网络请求验证同步点击及等待期间标题、状态和读数均不变,成功回包后更新为新数据;另覆盖首次加载、刷新失败提示与重试、回前台保留、重复点击抑制、取消后迟到数据隔离和身份变化清空。测试使用网络替身,没有发送真实创建、召唤或飞行控制请求。
**文档字段结构与页面使用:**以下字段来自朱工合同及 15:07 的真实响应,未返回的展示值保持未知;完整 `data` 保留原始 JSON,当前页面按字段展示,不额外铺开 JSON 文本。
| 返回字段 | 当前解析与展示 |
@@ -1038,11 +1044,11 @@ API:[DroneDockShootingAPI.swift](suixinkan/Features/DroneDock/API/DroneDockSho
| `header.title` | 顶部标题;缺失时组合当前响应的点位和航线名称,仍缺失则显示“拍摄任务” |
| `header.tourist_label/package_name` | 顶部游客与套餐;仅缺失时使用入口订单摘要,不覆盖后端已返回文案;当前套餐口径冲突见下文 |
| `scenic`、`scenic_spot`、`air_line` | 解析景区、点位与航线摘要;用于身份核对和缺失标题的备用文本 |
| `current_plane.status_text/work_status_label` | 展示接口返回的任务设备状态;不使用准备页或 `plane_status.recommend` 自行替换 |
| `current_plane.status_text/work_status_label/online_status/work_status` | 展示接口返回的任务设备状态;失败态依据明确离线或返航状态显示重召限制,不自行推断设备就绪;不使用准备页或 `plane_status.recommend` 替换 |
| `metrics[]` | 展示 `battery/env_temp/wind_speed/rainfall/signal/satellite` 六项,使用服务端文案及单位,0 为有效值,缺失显示“—” |
| `plane_status` | 保留设备列表、推荐设备、连接状态及原始 `poll_hint_ms`;任务页不再使用该建议间隔驱动请求,不作为派机或起飞许可 |
| `ui.title/message` | 结合任务、航线状态与门禁确定当前显示阶段;保留后端说明,缺失时使用 execute_gate.message。长文案在固定中间区域省略,详情可查看完整文字;不将任务总状态 20 直接当作正在拍摄 |
| `execute_gate`、`ui.primary_action/commands` | 保留门禁、原因及建议动作;开始/恢复拍摄和底部暂停/返航禁用,不发控制请求;明确完成态提供“查看素材”进入当前订单素材库,其余可读状态提供单次刷新 |
| `execute_gate`、`ui.primary_action/commands` | 保留门禁、原因及建议动作;开始/恢复/重新召唤和底部暂停/返航禁用,不发控制请求;明确完成态提供“查看素材”进入当前订单素材库;失败态刷新位于导航栏,其余可读状态保留单次刷新入口 |
| 图传区域 | 显示“图传暂未接入”的中性占位;未调用 `/airport/live`,不填充演示画面 |
**真实成功响应:2026-10-29 15:07:25,HTTP 200、业务码 100000。** 只读已存在的 `task_id=1`,没有新的 `tasks/create` 或真实 `shoot` POST。完整响应见 [shooting-success-redacted.json](docs/9.9.1/shooting-integration-2026-10-29/shooting-success-redacted.json);以下为关键字段节选,省略字段不表示原响应缺失:
@@ -1252,6 +1258,18 @@ API:[DroneDockShootAPI.swift](suixinkan/Features/DroneDock/API/DroneDockShootA
本轮仅创建 1 次、召唤 POST 1 次、随后任务 GET 1 次,无自动重试或任何 `start-shoot/command`。接口业务成功不等于航线执行成功,当前被阻止继续拍摄;不据此解释旧任务 2 的失败原因,也不自动重建或重发召唤。
#### 7.7.3 任务 11:新版文档后的模拟器起飞流程实测
2026-10-29 按用户要求,在模拟器从真实首页订单 `261027271004` 进入准备页,选择点位 `412` / 航线 `302`,点击一次“确认并召唤”。17:18:59 张工 `tasks/create` 返回任务 **11**;17:19:01 朱工 `shoot {"id":11,"restart":false}` 返回成功,绑定飞机 **61**、航线任务 **1931**,随后自动进入拍摄任务页。同一任务的两次 GET 均使用 `shooting?id=11&live_battery=1`。
- 17:19:04 首次查询:`wayline_status=20`、`execute_gate.can_execute=true`,`ui.phase=arrived_pending_start`。
- 17:19:59 手动刷新:`wayline_status=91` 执行失败、`can_execute=false`、`code=wayline_not_shooting`,飞机 61 显示离线。
- 创建 1 次、召唤 1 次、任务 GET 2 次;没有重试召唤、调用 `start-shoot/command` 或恢复任务页轮询。召唤业务受理成功不代表实际起飞、到达成功。
- 召唤前 `plane-status` 中所有飞机 `can_fly=false`,飞机 61 为离线却被派机;首次任务查询设备 `online_status=2` 与 `can_execute=true` 并存。需朱工核对派机和执行门禁以及航线 1931 的具体失败原因,现有回执不足以确认因果。
- 订单次数仍有差异:张工总/剩余 5 次,朱工总/剩余 1 次。文档成功码 0 与实测 100000 的差异也已记录。
完整操作、请求参数、逐步响应和待核对事项保存在本机 `docs/9.9.1/takeoff-integration-2026-10-29-1718/README.md`(本地联调资料,不随代码提交)。记录包含全部 25 次请求(24 份响应、1 次离页取消的准备页状态读取),设备标识及游客脱敏手机号已替换为测试值;截图与原始记录也保留本地。本次模拟器构建运行通过,没有修改业务代码。
## 8. 订单素材库
页面:[DroneDockMaterialsViewController.swift](suixinkan/UI/DroneDock/DroneDockMaterialsViewController.swift)