feat(drone-dock): 接入首页真实数据并完善设备卡片
通过 airport/home 读取当前景区和门店的设备与统计,隔离失效会话回包,未知遥测显示破折号。完善状态圆点、分割线和卫星图标;订单详情等待后端测试数据。 验证:iPhone 11 上 49 项相关测试、样式调整后 9 项界面回归,以及测试样例匿名化后 20 项测试均通过。真实联调响应、日志和截图仅保留在本地。
This commit is contained in:
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "drone_telemetry_satellite.svg",
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
},
|
||||
"properties" : {
|
||||
"preserves-vector-representation" : true,
|
||||
"template-rendering-intent" : "template"
|
||||
}
|
||||
}
|
||||
suixinkan/Assets.xcassets/DroneDock/drone_telemetry_satellite.imageset/drone_telemetry_satellite.svg
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
<!-- Tabler Icons satellite, as used by https://voicestudio.suixinkan.cn/.
|
||||
Copyright (c) 2020-2026 Paweł Kuna, MIT License.
|
||||
Full notice: Resources/DroneDock/TablerIcons-LICENSE.txt -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#000000" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M3.707 6.293l2.586 -2.586a1 1 0 0 1 1.414 0l5.586 5.586a1 1 0 0 1 0 1.414l-2.586 2.586a1 1 0 0 1 -1.414 0l-5.586 -5.586a1 1 0 0 1 0 -1.414"/>
|
||||
<path d="M6 10l-3 3l3 3l3 -3"/>
|
||||
<path d="M10 6l3 -3l3 3l-3 3"/>
|
||||
<path d="M12 12l1.5 1.5"/>
|
||||
<path d="M14.5 17a2.5 2.5 0 0 0 2.5 -2.5"/>
|
||||
<path d="M15 21a6 6 0 0 0 6 -6"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 715 B |
@@ -0,0 +1,29 @@
|
||||
import Foundation
|
||||
|
||||
/// 机巢首页只读数据源;通过主 Actor 的统一客户端读取,不提供飞行控制能力。
|
||||
protocol DroneDockHomeServing: Sendable {
|
||||
/// 获取指定景区、门店的首页快照。
|
||||
@MainActor
|
||||
func home(scenicID: Int, storeID: Int) async throws -> DroneDockHomeResponse
|
||||
}
|
||||
|
||||
/// 朱工提供的机巢首页接口;身份由统一网络客户端注入。
|
||||
@MainActor
|
||||
final class DroneDockAPI: DroneDockHomeServing {
|
||||
private let client: APIClient
|
||||
|
||||
/// 注入统一网络客户端,供正式页面及网络测试使用。
|
||||
init(client: APIClient) { self.client = client }
|
||||
|
||||
/// 获取当前景区、门店的工作台首页,不创建订单或飞行任务。
|
||||
func home(scenicID: Int, storeID: Int) async throws -> DroneDockHomeResponse {
|
||||
guard scenicID > 0, storeID > 0 else {
|
||||
throw APIError.networkFailed("请先选择景区和门店")
|
||||
}
|
||||
return try await client.send(APIRequest(
|
||||
method: .get, path: "/api/app/airport/home",
|
||||
queryItems: [URLQueryItem(name: "scenic_id", value: String(scenicID)),
|
||||
URLQueryItem(name: "store_id", value: String(storeID))]
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import Foundation
|
||||
|
||||
/// 朱工首页接口的已验证结构;数组缺失或类型异常视为解析错误,不伪装成空列表。
|
||||
struct DroneDockHomeResponse: Decodable, Equatable, Sendable {
|
||||
/// 服务端返回的数据所属景区。
|
||||
let scenicID: Int
|
||||
/// 当前景区的机巢设备,按真实非空响应的字段读取。
|
||||
let airports: [DroneDockHomeAirport]
|
||||
/// 订单原始记录;不将未知字段猜测成演示订单。
|
||||
let orders: [DroneDockHomeRecord]
|
||||
/// 今日数据缺失时保留未知,不生成零值统计。
|
||||
let today: DroneDockHomeToday?
|
||||
|
||||
/// 已验证的首页顶层字段名。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case scenicID = "scenic_id"
|
||||
case airports, orders, today
|
||||
}
|
||||
|
||||
/// 严格读取首页骨架,兼容服务端使用整数或整数字符串表示景区 ID。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
scenicID = try container.decode(DroneDockHomeInteger.self, forKey: .scenicID).value
|
||||
guard scenicID > 0 else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .scenicID, in: container, debugDescription: "景区 ID 必须为正整数")
|
||||
}
|
||||
airports = try container.decode([DroneDockHomeAirport].self, forKey: .airports)
|
||||
guard Set(airports.map(\.id)).count == airports.count else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .airports, in: container, debugDescription: "设备 ID 重复,无法确定设备身份")
|
||||
}
|
||||
orders = try container.decode([DroneDockHomeRecord].self, forKey: .orders)
|
||||
today = try container.decodeIfPresent(DroneDockHomeToday.self, forKey: .today)
|
||||
}
|
||||
}
|
||||
|
||||
/// 首页设备卡的数据,只表达后端展示信息,不推导起飞或拍摄许可。
|
||||
struct DroneDockHomeAirport: Decodable, Equatable, Sendable {
|
||||
/// 后端设备稳定 ID,用于 Diffable 项身份。
|
||||
let id: Int
|
||||
/// 后端设备名称。
|
||||
let name: String
|
||||
/// 后端设备序列号,不将它与尚未确认的飞控参数混用。
|
||||
let snNumber: String?
|
||||
/// 后端设备所属景区 ID。
|
||||
let scenicAreaID: Int?
|
||||
/// 原始在线状态;尚未取得完整枚举约定。
|
||||
let onlineStatus: Int?
|
||||
/// 原始工作状态;不据此决定设备可否执行任务。
|
||||
let workStatus: Int?
|
||||
/// 后端工作状态展示文案。
|
||||
let workStatusLabel: String?
|
||||
/// 原始接单配置;不等同于本次起飞许可。
|
||||
let isReceiveOrder: Int?
|
||||
/// 任务类型原始值;当前样本为 null,暂不假定其枚举或值类型。
|
||||
let taskType: DroneDockHomeJSONValue?
|
||||
/// 后端读数列表,展示时按稳定 key 匹配,不依赖返回顺序。
|
||||
let metrics: [DroneDockHomeMetric]
|
||||
|
||||
/// 已实测的设备字段名。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case id, name, metrics
|
||||
case snNumber = "sn_number"
|
||||
case scenicAreaID = "scenic_area_id"
|
||||
case onlineStatus = "online_status"
|
||||
case workStatus = "work_status"
|
||||
case workStatusLabel = "work_status_label"
|
||||
case isReceiveOrder = "is_receive_order"
|
||||
case taskType = "task_type"
|
||||
}
|
||||
|
||||
/// 读取实际设备结构;身份缺失时报错,缺失遥测保持未知。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
id = try container.decode(DroneDockHomeInteger.self, forKey: .id).value
|
||||
guard id > 0 else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .id, in: container, debugDescription: "设备 ID 必须为正整数")
|
||||
}
|
||||
name = try container.decode(String.self, forKey: .name)
|
||||
snNumber = try container.decodeIfPresent(String.self, forKey: .snNumber)
|
||||
scenicAreaID = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .scenicAreaID)?.value
|
||||
onlineStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .onlineStatus)?.value
|
||||
workStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .workStatus)?.value
|
||||
workStatusLabel = try container.decodeIfPresent(String.self, forKey: .workStatusLabel)
|
||||
isReceiveOrder = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .isReceiveOrder)?.value
|
||||
taskType = try container.decodeIfPresent(DroneDockHomeJSONValue.self, forKey: .taskType)
|
||||
metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? []
|
||||
}
|
||||
|
||||
/// 状态标签使用后端文案;缺失、空白或占位文案不显示成空闲。
|
||||
var statusTitle: String { DroneDockHomeMetric.usableText(workStatusLabel) ?? "状态待确认" }
|
||||
|
||||
/// 只映射已验证的空闲状态样本,其余保持中性色,不新增业务状态推断。
|
||||
var statusTone: DroneDockStatusTone { workStatus == 1 && statusTitle == "空闲" ? .green : .gray }
|
||||
|
||||
/// 返回指定读数的后端展示值,保留单位;未知值不从 raw 猜测生成。
|
||||
func metricText(for key: String) -> String {
|
||||
metrics.first { $0.key == key }?.displayText ?? "—"
|
||||
}
|
||||
|
||||
/// 仅在电量原始值为 0~100 的真实数字时绘制环形进度,零电量与未知分开。
|
||||
var batteryProgress: Double? {
|
||||
guard let metric = metrics.first(where: { $0.key == "battery" }),
|
||||
case let .number(value)? = metric.raw, value >= 0, value <= 100 else { return nil }
|
||||
return NSDecimalNumber(decimal: value).doubleValue / 100
|
||||
}
|
||||
}
|
||||
|
||||
/// 首页单项设备读数,区分可展示的后端文案和未经解释的原始值。
|
||||
struct DroneDockHomeMetric: Decodable, Equatable, Sendable {
|
||||
/// 后端读数稳定键,如 battery、env_temp。
|
||||
let key: String
|
||||
/// 后端读数名称。
|
||||
let label: String?
|
||||
/// 后端原始读数;除合法数值电量环外不据此推测单位或设备许可。
|
||||
let raw: DroneDockHomeJSONValue?
|
||||
/// 后端格式化展示值。
|
||||
let value: String?
|
||||
|
||||
/// 统一未知占位,但保留有效零值及服务端单位。
|
||||
var displayText: String { Self.usableText(value) ?? "—" }
|
||||
|
||||
/// 将空白和仅由破折号组成的占位文案判为未知。
|
||||
static func usableText(_ value: String?) -> String? {
|
||||
guard let value else { return nil }
|
||||
let text = value.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !text.isEmpty, !text.allSatisfy({ "-–—−― ".contains($0) }) else { return nil }
|
||||
return text
|
||||
}
|
||||
}
|
||||
|
||||
/// 首页今日统计;保留服务端字段语义,未知项不显示为零。
|
||||
struct DroneDockHomeToday: Decodable, Equatable, Sendable {
|
||||
/// 服务端的今日订单数量。
|
||||
let orderCount: Int?
|
||||
/// 服务端的今日订单金额,使用十进制金额避免二进制浮点误差。
|
||||
let orderAmount: Decimal?
|
||||
/// 服务端 finished_shoot 数值,其业务统计口径仍需与后端核对。
|
||||
let finishedShoot: Int?
|
||||
|
||||
/// 已验证的统计字段名。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case orderCount = "order_count"
|
||||
case orderAmount = "order_amount"
|
||||
case finishedShoot = "finished_shoot"
|
||||
}
|
||||
|
||||
/// 兼容数字和数字字符串;缺失或 null 保持 nil,非法文本拒绝解析。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
orderCount = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .orderCount)?.value
|
||||
orderAmount = try container.decodeIfPresent(DroneDockHomeDecimal.self, forKey: .orderAmount)?.value
|
||||
finishedShoot = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .finishedShoot)?.value
|
||||
}
|
||||
}
|
||||
|
||||
/// 尚未取得真实样本的订单行,保留对象字段供后续精确接入和诊断。
|
||||
struct DroneDockHomeRecord: Decodable, Equatable, Sendable {
|
||||
/// 原始对象键值,不猜测订单状态或拍摄次数的字段别名。
|
||||
let fields: [String: DroneDockHomeJSONValue]
|
||||
|
||||
/// 只接受 JSON 对象作为列表记录,拒绝 null、标量和嵌套数组。
|
||||
init(from decoder: Decoder) throws {
|
||||
fields = try decoder.singleValueContainer().decode([String: DroneDockHomeJSONValue].self)
|
||||
}
|
||||
}
|
||||
|
||||
/// 保留未知记录的 JSON 结构;数字采用 Decimal,不参与未确认业务计算。
|
||||
indirect enum DroneDockHomeJSONValue: Decodable, Equatable, Sendable {
|
||||
/// JSON 对象。
|
||||
case object([String: DroneDockHomeJSONValue])
|
||||
/// JSON 数组。
|
||||
case array([DroneDockHomeJSONValue])
|
||||
/// JSON 字符串。
|
||||
case string(String)
|
||||
/// JSON 数字。
|
||||
case number(Decimal)
|
||||
/// JSON 布尔值。
|
||||
case bool(Bool)
|
||||
/// JSON 空值。
|
||||
case null
|
||||
|
||||
/// 按 JSON 实际类型解码,不把字符串自动转换为其他类型。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
if container.decodeNil() { self = .null }
|
||||
else if let value = try? container.decode(Bool.self) { self = .bool(value) }
|
||||
else if let value = try? container.decode(String.self) { self = .string(value) }
|
||||
else if let value = try? container.decode(Decimal.self) { self = .number(value) }
|
||||
else if let value = try? container.decode([String: DroneDockHomeJSONValue].self) { self = .object(value) }
|
||||
else { self = .array(try container.decode([DroneDockHomeJSONValue].self)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// 已知整数统计字段的严格兼容解码器。
|
||||
private struct DroneDockHomeInteger: Decodable {
|
||||
let value: Int
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
if let number = try? container.decode(Int.self) {
|
||||
value = number
|
||||
} else if let text = try? container.decode(String.self), let number = Int(text) {
|
||||
value = number
|
||||
} else {
|
||||
throw DecodingError.dataCorruptedError(in: container, debugDescription: "需要整数或整数字符串")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 已知金额字段的十进制兼容解码器,拒绝只含部分合法数字的字符串。
|
||||
private struct DroneDockHomeDecimal: Decodable {
|
||||
let value: Decimal
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
if let text = try? container.decode(String.self) {
|
||||
let normalized = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard normalized.range(of: #"^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$"#, options: .regularExpression) != nil,
|
||||
let number = Decimal(string: normalized, locale: Locale(identifier: "en_US_POSIX")),
|
||||
!number.isNaN else {
|
||||
throw DecodingError.dataCorruptedError(in: container, debugDescription: "金额必须为有效十进制数")
|
||||
}
|
||||
value = number
|
||||
} else {
|
||||
value = try container.decode(Decimal.self)
|
||||
guard !value.isNaN else {
|
||||
throw DecodingError.dataCorruptedError(in: container, debugDescription: "金额必须为有效十进制数")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import Foundation
|
||||
|
||||
/// 一次真实首页请求的账号、景区和门店范围;凭证只参与隔离,不对外提供展示。
|
||||
struct DroneDockHomeContext: Equatable, Sendable {
|
||||
/// 当前登录工作人员的稳定 ID。
|
||||
let userID: String
|
||||
/// 当前账号类型,用于区分相同 ID 的不同账号域。
|
||||
let accountType: String
|
||||
/// 当前景区 ID。
|
||||
let scenicID: Int
|
||||
/// 当前景区名称。
|
||||
let scenicName: String
|
||||
/// 当前景区下的门店 ID。
|
||||
let storeID: Int
|
||||
/// 当前工作人员展示名称。
|
||||
let photographerName: String
|
||||
private let token: String
|
||||
|
||||
/// 冻结请求范围及登录凭证,仅用于与最新会话比较。
|
||||
init(userID: String, accountType: String, scenicID: Int, scenicName: String,
|
||||
storeID: Int, photographerName: String, token: String) {
|
||||
self.userID = userID
|
||||
self.accountType = accountType
|
||||
self.scenicID = scenicID
|
||||
self.scenicName = scenicName
|
||||
self.storeID = storeID
|
||||
self.photographerName = photographerName
|
||||
self.token = token.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
/// 是否具备查询当前首页所需的登录及景区、门店上下文。
|
||||
var canLoad: Bool { !userID.isEmpty && !token.isEmpty && scenicID > 0 && storeID > 0 }
|
||||
|
||||
/// 判断响应是否仍属于当前会话,包含登录 Token 更新但忽略展示名称变化。
|
||||
func hasSameIdentity(as other: DroneDockHomeContext) -> Bool {
|
||||
userID == other.userID && accountType == other.accountType && scenicID == other.scenicID
|
||||
&& storeID == other.storeID && token == other.token
|
||||
}
|
||||
}
|
||||
|
||||
/// 真实机巢首页的独立读取状态;不使用演示订单、演示设备或本地拍摄任务。
|
||||
final class DroneDockHomeViewModel {
|
||||
/// 当前页面所属的真实账号、景区和门店。
|
||||
private(set) var context: DroneDockHomeContext
|
||||
/// 最近一次成功读取的当前范围首页;加载失败或身份变更时清除。
|
||||
private(set) var response: DroneDockHomeResponse?
|
||||
/// 当前最新一次请求是否尚未结束。
|
||||
private(set) var isLoading = false
|
||||
/// 当前请求的可展示错误;与成功空列表分开表达。
|
||||
private(set) var errorMessage: String?
|
||||
|
||||
private let service: any DroneDockHomeServing
|
||||
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
||||
private var generation = 0
|
||||
|
||||
/// 注入读取服务与最新会话提供器,调用方在刷新完成后主动更新界面。
|
||||
init(context: DroneDockHomeContext, service: any DroneDockHomeServing,
|
||||
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
|
||||
self.context = context
|
||||
self.service = service
|
||||
self.currentContext = currentContext
|
||||
}
|
||||
|
||||
/// 刷新真实首页;拒绝旧请求、旧登录凭证、旧景区及旧门店的迟到结果。
|
||||
func refresh() async {
|
||||
generation &+= 1
|
||||
let requestGeneration = generation
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
defer { if generation == requestGeneration { isLoading = false } }
|
||||
let requestedContext = await currentContext()
|
||||
guard generation == requestGeneration, !Task.isCancelled else { return }
|
||||
if !context.hasSameIdentity(as: requestedContext) { response = nil }
|
||||
context = requestedContext
|
||||
guard requestedContext.canLoad else {
|
||||
response = nil
|
||||
isLoading = false
|
||||
errorMessage = "请先登录并选择景区和门店"
|
||||
return
|
||||
}
|
||||
do {
|
||||
let result = try await service.home(scenicID: requestedContext.scenicID, storeID: requestedContext.storeID)
|
||||
guard await accepts(requestGeneration, context: requestedContext) else { return }
|
||||
guard result.scenicID == requestedContext.scenicID else {
|
||||
response = nil
|
||||
errorMessage = "接口返回的景区与当前景区不一致,请刷新重试"
|
||||
return
|
||||
}
|
||||
response = result
|
||||
} catch {
|
||||
guard await accepts(requestGeneration, context: requestedContext) else { return }
|
||||
response = nil
|
||||
if error is CancellationError { return }
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// 离开或取消当前读取时使所有在途结果失效;再次刷新仍可重新加载。
|
||||
func invalidate() {
|
||||
generation &+= 1
|
||||
response = nil
|
||||
errorMessage = nil
|
||||
isLoading = false
|
||||
}
|
||||
|
||||
private func accepts(_ requestGeneration: Int, context requested: DroneDockHomeContext) async -> Bool {
|
||||
guard generation == requestGeneration, !Task.isCancelled else { return false }
|
||||
let latest = await currentContext()
|
||||
guard generation == requestGeneration, !Task.isCancelled else { return false }
|
||||
guard requested.hasSameIdentity(as: latest) else {
|
||||
generation &+= 1
|
||||
context = latest
|
||||
response = nil
|
||||
isLoading = false
|
||||
errorMessage = "账号或景区已变化,请刷新工作台"
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,7 @@ enum HomeRouteHandler {
|
||||
case "/scenic-queue":
|
||||
viewController.navigationController?.pushViewController(ScenicQueueViewController(), animated: true)
|
||||
case "drone_dock":
|
||||
viewController.navigationController?.pushViewController(DroneDockWorkbenchViewController(), animated: true)
|
||||
viewController.navigationController?.pushViewController(DroneDockHomeViewController(), animated: true)
|
||||
case "task_management", "task_management_editor":
|
||||
viewController.navigationController?.pushViewController(TaskAddViewController(), animated: true)
|
||||
case "travel_album":
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
Tabler Icons — satellite
|
||||
Source: https://github.com/tabler/tabler-icons
|
||||
Used by the device card to match https://voicestudio.suixinkan.cn/.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020-2026 Paweł Kuna
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -4,7 +4,7 @@ import UIKit
|
||||
/// 设备遥测卡:只展示设备状态,横向浏览不会选择执行拍摄的无人机。
|
||||
final class DroneDockDeviceCardView: UIView {
|
||||
private let nameLabel = DroneDockStyle.label(size: 15, weight: .semibold)
|
||||
private let statusLabel = DroneDockStatusLabel()
|
||||
private let statusLabel = DroneDockDeviceStatusView()
|
||||
private let batteryView = DroneDockBatteryView()
|
||||
private let signalValue = DroneDockStyle.label(size: 19, weight: .semibold)
|
||||
private let satelliteValue = DroneDockStyle.label(size: 19, weight: .semibold)
|
||||
@@ -40,7 +40,26 @@ final class DroneDockDeviceCardView: UIView {
|
||||
accessibilityLabel = "\(device.name),\(device.state.title)"
|
||||
}
|
||||
|
||||
/// 展示 home 返回的机巢名称、工作状态及格式化读数,不根据展示状态推断起飞许可。
|
||||
func apply(airport: DroneDockHomeAirport) {
|
||||
nameLabel.text = airport.name
|
||||
statusLabel.apply(title: airport.statusTitle, tone: airport.statusTone)
|
||||
batteryView.apply(text: airport.metricText(for: "battery"), progress: airport.batteryProgress)
|
||||
temperatureValue.text = airport.metricText(for: "env_temp")
|
||||
windValue.text = airport.metricText(for: "wind_speed")
|
||||
rainValue.text = airport.metricText(for: "rainfall")
|
||||
signalValue.text = airport.metricText(for: "signal")
|
||||
satelliteValue.text = airport.metricText(for: "satellite")
|
||||
accessibilityIdentifier = "drone.device.\(airport.id)"
|
||||
accessibilityLabel = "\(airport.name),\(airport.statusTitle)"
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
temperatureValue.accessibilityIdentifier = "drone.metric.env_temp"
|
||||
windValue.accessibilityIdentifier = "drone.metric.wind_speed"
|
||||
rainValue.accessibilityIdentifier = "drone.metric.rainfall"
|
||||
signalValue.accessibilityIdentifier = "drone.metric.signal"
|
||||
satelliteValue.accessibilityIdentifier = "drone.metric.satellite"
|
||||
[nameLabel, statusLabel, batteryView].forEach(addSubview)
|
||||
nameLabel.snp.makeConstraints { make in
|
||||
make.top.leading.equalToSuperview().inset(16)
|
||||
@@ -57,7 +76,7 @@ final class DroneDockDeviceCardView: UIView {
|
||||
}
|
||||
|
||||
let signal = telemetryRow(symbol: "antenna.radiowaves.left.and.right", title: "信号状态", value: signalValue)
|
||||
let satellites = telemetryRow(symbol: "sparkles", title: "搜星状态", value: satelliteValue)
|
||||
let satellites = telemetryRow(image: UIImage(named: "drone_telemetry_satellite"), title: "搜星状态", value: satelliteValue)
|
||||
let radioStack = UIStackView(arrangedSubviews: [signal, satellites])
|
||||
radioStack.axis = .vertical
|
||||
radioStack.distribution = .fillEqually
|
||||
@@ -77,11 +96,12 @@ final class DroneDockDeviceCardView: UIView {
|
||||
make.leading.trailing.equalToSuperview().inset(16)
|
||||
make.height.equalTo(0.5)
|
||||
}
|
||||
let metrics = UIStackView(arrangedSubviews: [
|
||||
let metricColumns = [
|
||||
metric(value: temperatureValue, symbol: "thermometer.medium", title: "环境温度"),
|
||||
metric(value: windValue, symbol: "wind", title: "风速"),
|
||||
metric(value: rainValue, symbol: "cloud", title: "雨量")
|
||||
])
|
||||
metric(value: rainValue, symbol: "cloud.rain", title: "雨量")
|
||||
]
|
||||
let metrics = UIStackView(arrangedSubviews: metricColumns)
|
||||
metrics.axis = .horizontal
|
||||
metrics.distribution = .fillEqually
|
||||
addSubview(metrics)
|
||||
@@ -90,10 +110,24 @@ final class DroneDockDeviceCardView: UIView {
|
||||
make.leading.trailing.equalToSuperview().inset(12)
|
||||
make.bottom.equalToSuperview().inset(14)
|
||||
}
|
||||
for column in metricColumns.dropFirst() {
|
||||
let separator = UIView()
|
||||
separator.backgroundColor = DroneDockStyle.border
|
||||
metrics.addSubview(separator)
|
||||
separator.snp.makeConstraints { make in
|
||||
make.leading.equalTo(column.snp.leading)
|
||||
make.top.bottom.equalToSuperview()
|
||||
make.width.equalTo(0.5)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func telemetryRow(symbol: String, title: String, value: UILabel) -> UIView {
|
||||
let icon = UIImageView(image: UIImage(systemName: symbol))
|
||||
telemetryRow(image: UIImage(systemName: symbol), title: title, value: value)
|
||||
}
|
||||
|
||||
private func telemetryRow(image: UIImage?, title: String, value: UILabel) -> UIView {
|
||||
let icon = UIImageView(image: image?.withRenderingMode(.alwaysTemplate))
|
||||
icon.tintColor = DroneDockStyle.secondary
|
||||
icon.contentMode = .scaleAspectFit
|
||||
let label = DroneDockStyle.label(title, size: 11, color: DroneDockStyle.secondary)
|
||||
@@ -128,6 +162,39 @@ final class DroneDockDeviceCardView: UIView {
|
||||
}
|
||||
}
|
||||
|
||||
/// 设备专用状态标签,圆点与文字共用语义颜色,不改变其他业务标签。
|
||||
private final class DroneDockDeviceStatusView: UIView {
|
||||
private let dot = UIView()
|
||||
private let titleLabel = DroneDockStyle.label(size: 11, weight: .medium)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
layer.cornerRadius = 6
|
||||
dot.layer.cornerRadius = 3
|
||||
dot.snp.makeConstraints { $0.size.equalTo(6) }
|
||||
let content = UIStackView(arrangedSubviews: [dot, titleLabel])
|
||||
content.axis = .horizontal
|
||||
content.alignment = .center
|
||||
content.spacing = 5
|
||||
addSubview(content)
|
||||
content.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 4, left: 7, bottom: 4, right: 7)) }
|
||||
titleLabel.setContentHuggingPriority(.required, for: .horizontal)
|
||||
titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 圆点、文字及浅色背景同步更新,复用时不残留上一设备的状态色。
|
||||
func apply(title: String, tone: DroneDockStatusTone) {
|
||||
let color = DroneDockStyle.color(for: tone)
|
||||
titleLabel.text = title
|
||||
titleLabel.textColor = color
|
||||
dot.backgroundColor = color
|
||||
backgroundColor = color.withAlphaComponent(0.09)
|
||||
}
|
||||
}
|
||||
|
||||
/// 环形电量组件,未知电量只显示轨道和占位读数。
|
||||
private final class DroneDockBatteryView: UIView {
|
||||
private let track = CAShapeLayer()
|
||||
@@ -136,6 +203,7 @@ private final class DroneDockBatteryView: UIView {
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
valueLabel.accessibilityIdentifier = "drone.metric.battery"
|
||||
for layer in [track, progress] {
|
||||
layer.fillColor = UIColor.clear.cgColor
|
||||
layer.lineWidth = 7
|
||||
@@ -165,9 +233,14 @@ private final class DroneDockBatteryView: UIView {
|
||||
}
|
||||
|
||||
func apply(telemetry: DroneDockTelemetry) {
|
||||
valueLabel.text = telemetry.batteryText
|
||||
progress.strokeEnd = telemetry.batteryProgress ?? 0
|
||||
accessibilityLabel = "电池电量 \(telemetry.batteryText)"
|
||||
apply(text: telemetry.batteryText, progress: telemetry.batteryProgress)
|
||||
}
|
||||
|
||||
/// 有效电量才绘制进度;未知值只保留环形轨道与破折号。
|
||||
func apply(text: String, progress value: Double?) {
|
||||
valueLabel.text = text
|
||||
progress.strokeEnd = value.map { CGFloat(min(1, max(0, $0))) } ?? 0
|
||||
accessibilityLabel = "电池电量 \(text)"
|
||||
isAccessibilityElement = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 正式机巢首页,仅展示 airport/home 的真实快照,不进入本地演示业务。
|
||||
final class DroneDockHomeViewController: BaseViewController {
|
||||
/// 与演示数据源隔离的首页状态。
|
||||
let viewModel: DroneDockHomeViewModel
|
||||
private var refreshTask: Task<Void, Never>?
|
||||
private var isRefreshing = false
|
||||
private var devicePage = 0
|
||||
private let pageControl = UIPageControl()
|
||||
|
||||
/// 首页固定分区;设备与订单的数据结构以实际联调结果为准。
|
||||
private enum Section: Int, CaseIterable { case context, devices, orders, statistics }
|
||||
/// 稳定身份确保刷新使用 Diffable 更新。
|
||||
private enum Item: Hashable { case context, devices, device(Int), orders, statistics }
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
||||
|
||||
/// 使用当前登录身份及选择的景区、门店构造正式首页。
|
||||
convenience init() {
|
||||
self.init(viewModel: DroneDockHomeViewModel(
|
||||
context: Self.currentContext(),
|
||||
service: DroneDockAPI(client: NetworkServices.shared.apiClient),
|
||||
currentContext: { Self.currentContext() }
|
||||
))
|
||||
}
|
||||
|
||||
/// 注入可测试的数据源,不加载演示数据。
|
||||
init(viewModel: DroneDockHomeViewModel) {
|
||||
self.viewModel = viewModel
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
deinit { refreshTask?.cancel() }
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "机巢工作台"
|
||||
let button = UIBarButtonItem(title: "收款码", image: UIImage(systemName: "qrcode"),
|
||||
target: self, action: #selector(receiptTapped))
|
||||
button.accessibilityIdentifier = "drone.home.receipt"
|
||||
navigationItem.rightBarButtonItem = button
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = DroneDockStyle.background
|
||||
collectionView.backgroundColor = .clear
|
||||
collectionView.alwaysBounceVertical = true
|
||||
collectionView.accessibilityIdentifier = "drone.home.remote.list"
|
||||
collectionView.register(DroneDockHomeContentCell.self, forCellWithReuseIdentifier: "content")
|
||||
collectionView.register(DroneDockDeviceCell.self, forCellWithReuseIdentifier: "device")
|
||||
collectionView.register(DroneDockHomeHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
|
||||
withReuseIdentifier: "header")
|
||||
collectionView.register(DroneDockHomePageFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
|
||||
withReuseIdentifier: "pages")
|
||||
pageControl.currentPageIndicatorTintColor = DroneDockStyle.primary
|
||||
pageControl.pageIndicatorTintColor = DroneDockStyle.border
|
||||
pageControl.isUserInteractionEnabled = false
|
||||
pageControl.accessibilityIdentifier = "drone.home.devicePages"
|
||||
let refresh = UIRefreshControl()
|
||||
refresh.tintColor = DroneDockStyle.primary
|
||||
refresh.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged)
|
||||
collectionView.refreshControl = refresh
|
||||
view.addSubview(collectionView)
|
||||
configureDataSource()
|
||||
applySnapshot(animated: false)
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
collectionView.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide)
|
||||
make.leading.trailing.bottom.equalToSuperview()
|
||||
}
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
refreshHome()
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
refreshTask?.cancel()
|
||||
isRefreshing = false
|
||||
viewModel.invalidate()
|
||||
}
|
||||
|
||||
private func refreshHome() {
|
||||
refreshTask?.cancel()
|
||||
isRefreshing = true
|
||||
refreshTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
self.applySnapshot(animated: false)
|
||||
await self.viewModel.refresh()
|
||||
guard !Task.isCancelled else { return }
|
||||
self.isRefreshing = false
|
||||
self.collectionView.refreshControl?.endRefreshing()
|
||||
self.applySnapshot(animated: true) { [weak self] in
|
||||
#if DEBUG
|
||||
Task { @MainActor [weak self] in await self?.captureHomeIfRequested() }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] collection, path, item in
|
||||
guard let self else { return nil }
|
||||
if case .device(let id) = item {
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "device", for: path) as! DroneDockDeviceCell
|
||||
if let airport = self.viewModel.response?.airports.first(where: { $0.id == id }) {
|
||||
cell.cardView.apply(airport: airport)
|
||||
}
|
||||
return cell
|
||||
}
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "content", for: path) as! DroneDockHomeContentCell
|
||||
switch item {
|
||||
case .context:
|
||||
let context = self.viewModel.context
|
||||
let title = [context.scenicName, context.photographerName].filter { !$0.isEmpty }.joined(separator: " · ")
|
||||
cell.applyContext(title.isEmpty ? "机巢工作台" : title)
|
||||
case .statistics:
|
||||
cell.applyStatistics(self.viewModel.response?.today)
|
||||
case .devices, .orders:
|
||||
self.applyDataState(to: cell, isDevice: item == .devices)
|
||||
case .device: break
|
||||
}
|
||||
return cell
|
||||
}
|
||||
dataSource.supplementaryViewProvider = { [weak self] collection, kind, path in
|
||||
guard let self else { return nil }
|
||||
if kind == UICollectionView.elementKindSectionFooter {
|
||||
let footer = collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "pages", for: path) as! DroneDockHomePageFooter
|
||||
footer.install(self.pageControl)
|
||||
return footer
|
||||
}
|
||||
let header = collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: path) as! DroneDockHomeHeader
|
||||
let isOrders = Section(rawValue: path.section) == .orders
|
||||
header.apply(title: isOrders ? "我的拍摄订单" : "今日统计", showsAction: isOrders)
|
||||
header.onViewAll = { [weak self] in self?.showUnavailable("拍摄订单") }
|
||||
return header
|
||||
}
|
||||
}
|
||||
|
||||
private func applyDataState(to cell: DroneDockHomeContentCell, isDevice: Bool) {
|
||||
if isRefreshing, viewModel.response == nil {
|
||||
cell.applyMessage(symbol: "arrow.triangle.2.circlepath", title: "正在加载", detail: "正在获取最新数据")
|
||||
return
|
||||
}
|
||||
if let error = viewModel.errorMessage {
|
||||
cell.applyMessage(symbol: "wifi.exclamationmark", title: "首页加载失败", detail: error + ",请下拉重试")
|
||||
return
|
||||
}
|
||||
guard let response = viewModel.response else {
|
||||
cell.applyMessage(symbol: "arrow.triangle.2.circlepath", title: "正在加载", detail: "正在获取最新数据")
|
||||
return
|
||||
}
|
||||
let recordCount = isDevice ? response.airports.count : response.orders.count
|
||||
if recordCount == 0 {
|
||||
cell.applyMessage(symbol: isDevice ? "airplane" : "doc.text",
|
||||
title: isDevice ? "暂无无人机" : "暂无待拍摄订单",
|
||||
detail: isDevice ? "当前景区暂无设备数据" : "当前景区暂无拍摄订单数据")
|
||||
} else {
|
||||
// 订单仍等待真实非空样例,不影响已接入的设备卡片。
|
||||
cell.applyMessage(symbol: "exclamationmark.circle", title: "订单信息暂不可用",
|
||||
detail: "已获取 \(recordCount) 条数据,暂时无法展示详情")
|
||||
}
|
||||
}
|
||||
|
||||
private func applySnapshot(animated: Bool, completion: (() -> Void)? = nil) {
|
||||
guard dataSource != nil else { return }
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
|
||||
snapshot.appendSections(Section.allCases)
|
||||
snapshot.appendItems([.context], toSection: .context)
|
||||
let airports = viewModel.response?.airports ?? []
|
||||
snapshot.appendItems(airports.isEmpty ? [.devices] : airports.map { .device($0.id) }, toSection: .devices)
|
||||
snapshot.appendItems([.orders], toSection: .orders)
|
||||
snapshot.appendItems([.statistics], toSection: .statistics)
|
||||
let old = Set(dataSource.snapshot().itemIdentifiers)
|
||||
let previousDeviceCount = old.filter { if case .device = $0 { return true }; return false }.count
|
||||
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { old.contains($0) })
|
||||
devicePage = min(devicePage, max(0, airports.count - 1))
|
||||
pageControl.numberOfPages = airports.count
|
||||
pageControl.currentPage = devicePage
|
||||
if previousDeviceCount != airports.count {
|
||||
collectionView.setCollectionViewLayout(makeLayout(), animated: false)
|
||||
}
|
||||
dataSource.apply(snapshot, animatingDifferences: animated, completion: completion)
|
||||
}
|
||||
|
||||
private func makeLayout() -> UICollectionViewLayout {
|
||||
UICollectionViewCompositionalLayout { [weak self] index, environment in
|
||||
guard let section = Section(rawValue: index) else { return nil }
|
||||
let deviceCount = self?.viewModel.response?.airports.count ?? 0
|
||||
let hasDevices = section == .devices && deviceCount > 0
|
||||
let multipleDevices = section == .devices && deviceCount > 1
|
||||
let height: NSCollectionLayoutDimension = hasDevices ? .absolute(248) : section == .context ? .estimated(40) : .estimated(132)
|
||||
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height))
|
||||
let width: NSCollectionLayoutDimension = multipleDevices ? .absolute(environment.container.effectiveContentSize.width - 48) : .fractionalWidth(1)
|
||||
let group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item])
|
||||
let layout = NSCollectionLayoutSection(group: group)
|
||||
layout.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: section == .statistics ? 24 : 0, trailing: 16)
|
||||
if multipleDevices {
|
||||
layout.interGroupSpacing = 12
|
||||
layout.orthogonalScrollingBehavior = .groupPaging
|
||||
layout.visibleItemsInvalidationHandler = { [weak self] _, offset, _ in
|
||||
guard let self else { return }
|
||||
let step = max(1, environment.container.effectiveContentSize.width - 36)
|
||||
let page = min(deviceCount - 1, max(0, Int((offset.x / step).rounded())))
|
||||
self.devicePage = page
|
||||
self.pageControl.currentPage = page
|
||||
}
|
||||
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
|
||||
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(24)),
|
||||
elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom)]
|
||||
}
|
||||
if section == .orders || section == .statistics {
|
||||
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
|
||||
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(54)),
|
||||
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)]
|
||||
}
|
||||
return layout
|
||||
}
|
||||
}
|
||||
|
||||
private func showUnavailable(_ feature: String) {
|
||||
showAlert(title: feature, message: "该功能暂未开放")
|
||||
}
|
||||
|
||||
@objc private func receiptTapped() { showUnavailable("套餐收款") }
|
||||
@objc private func refreshTriggered() { refreshHome() }
|
||||
|
||||
#if DEBUG
|
||||
/// 显式联调参数下只保存本应用窗口,不截取用户切换后的其他 App。
|
||||
private func captureHomeIfRequested() async {
|
||||
guard ProcessInfo.processInfo.arguments.contains("--dock-home-capture") else { return }
|
||||
// Diffable 完成回调仍可能处于旧卡片的移除事务内,等下一轮屏幕提交后再取图。
|
||||
try? await Task.sleep(nanoseconds: 400_000_000)
|
||||
guard !Task.isCancelled, !isRefreshing, let window = view.window else { return }
|
||||
window.layoutIfNeeded()
|
||||
let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in
|
||||
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
|
||||
}
|
||||
do {
|
||||
let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
|
||||
.appendingPathComponent("AirportHomeDiagnostics", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
try image.pngData()?.write(to: directory.appendingPathComponent("airport-home-real.png"), options: .atomic)
|
||||
print("[AirportHome] App window screenshot saved")
|
||||
} catch { print("[AirportHome] Screenshot failed: \(error.localizedDescription)") }
|
||||
}
|
||||
#endif
|
||||
|
||||
/// 只从现有会话读取身份,不修改登录状态或当前选择。
|
||||
private static func currentContext() -> DroneDockHomeContext {
|
||||
let session = AppStore.shared.session
|
||||
return DroneDockHomeContext(userID: session.userId, accountType: session.accountType.rawValue,
|
||||
scenicID: session.currentScenicId, scenicName: session.currentScenicName,
|
||||
storeID: session.currentStoreId, photographerName: session.userName, token: session.token)
|
||||
}
|
||||
}
|
||||
|
||||
/// 多设备横向轮播的页码容器。
|
||||
private final class DroneDockHomePageFooter: UICollectionReusableView {
|
||||
/// 安装首页维护的页码控件,避免复用时重复添加。
|
||||
func install(_ control: UIPageControl) {
|
||||
guard control.superview !== self else { return }
|
||||
control.removeFromSuperview()
|
||||
addSubview(control)
|
||||
control.snp.makeConstraints { make in
|
||||
make.center.equalToSuperview()
|
||||
make.height.equalTo(24)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 真实首页的空态、加载状态及统计展示。
|
||||
private final class DroneDockHomeContentCell: UICollectionViewCell {
|
||||
private var embeddedView: UIView?
|
||||
|
||||
/// 展示当前身份与景区。
|
||||
func applyContext(_ text: String) {
|
||||
let label = DroneDockStyle.label(text, size: 12, color: DroneDockStyle.secondary)
|
||||
label.numberOfLines = 2
|
||||
install(label, insets: UIEdgeInsets(top: 6, left: 0, bottom: 12, right: 0), card: false)
|
||||
}
|
||||
|
||||
/// 展示明确空态或错误,避免将接口失败解释为没有订单。
|
||||
func applyMessage(symbol: String, title: String, detail: String) {
|
||||
let image = UIImageView(image: UIImage(systemName: symbol))
|
||||
image.tintColor = DroneDockStyle.secondary.withAlphaComponent(0.6)
|
||||
image.contentMode = .scaleAspectFit
|
||||
image.snp.makeConstraints { $0.size.equalTo(28) }
|
||||
let titleLabel = DroneDockStyle.label(title, size: 14, weight: .medium)
|
||||
let detailLabel = DroneDockStyle.label(detail, size: 12, color: DroneDockStyle.secondary)
|
||||
detailLabel.numberOfLines = 0
|
||||
detailLabel.textAlignment = .center
|
||||
let stack = UIStackView(arrangedSubviews: [image, titleLabel, detailLabel])
|
||||
stack.axis = .vertical
|
||||
stack.alignment = .center
|
||||
stack.spacing = 9
|
||||
install(stack, insets: UIEdgeInsets(top: 22, left: 16, bottom: 22, right: 16), card: true)
|
||||
}
|
||||
|
||||
/// 使用服务端 today 字段;缺失数据保持未知,不显示为零。
|
||||
func applyStatistics(_ today: DroneDockHomeToday?) {
|
||||
let formatter = NumberFormatter()
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.numberStyle = .decimal
|
||||
formatter.minimumFractionDigits = 2
|
||||
formatter.maximumFractionDigits = 2
|
||||
let amount = today?.orderAmount.flatMap { formatter.string(from: NSDecimalNumber(decimal: $0)) }.map { "¥" + $0 } ?? "—"
|
||||
let values = [(today?.orderCount.map(String.init) ?? "—", "成交订单"),
|
||||
(amount, "成交金额"), (today?.finishedShoot.map(String.init) ?? "—", "完成拍摄")]
|
||||
let columns = values.map { value, title in
|
||||
let label = DroneDockStyle.label(value, size: 23, weight: .semibold)
|
||||
label.adjustsFontSizeToFitWidth = true
|
||||
label.minimumScaleFactor = 0.6
|
||||
let stack = UIStackView(arrangedSubviews: [label, DroneDockStyle.label(title, size: 12, color: DroneDockStyle.secondary)])
|
||||
stack.axis = .vertical
|
||||
stack.alignment = .center
|
||||
stack.spacing = 9
|
||||
return stack
|
||||
}
|
||||
let stack = UIStackView(arrangedSubviews: columns)
|
||||
stack.distribution = .fillEqually
|
||||
install(stack, insets: UIEdgeInsets(top: 23, left: 10, bottom: 23, right: 10), card: true)
|
||||
}
|
||||
|
||||
private func install(_ view: UIView, insets: UIEdgeInsets, card: Bool) {
|
||||
embeddedView?.removeFromSuperview()
|
||||
embeddedView = view
|
||||
if card { DroneDockStyle.applyCard(to: contentView) } else { contentView.backgroundColor = .clear }
|
||||
contentView.addSubview(view)
|
||||
view.snp.makeConstraints { $0.edges.equalToSuperview().inset(insets) }
|
||||
}
|
||||
}
|
||||
|
||||
/// 首页分区标题与后续订单列表入口。
|
||||
private final class DroneDockHomeHeader: UICollectionReusableView {
|
||||
/// 用户请求查看完整订单列表。
|
||||
var onViewAll: (() -> Void)?
|
||||
private let label = DroneDockStyle.label(size: 17, weight: .semibold)
|
||||
private let button = UIButton(type: .system)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
button.setTitle("查看全部 ›", for: .normal)
|
||||
button.titleLabel?.font = .systemFont(ofSize: 13)
|
||||
button.tintColor = DroneDockStyle.primary
|
||||
button.accessibilityIdentifier = "drone.home.allOrders"
|
||||
button.addTarget(self, action: #selector(tapped), for: .touchUpInside)
|
||||
button.snp.makeConstraints { $0.height.equalTo(44) }
|
||||
let stack = UIStackView(arrangedSubviews: [label, UIView(), button])
|
||||
stack.alignment = .center
|
||||
addSubview(stack)
|
||||
stack.snp.makeConstraints { $0.leading.trailing.centerY.equalToSuperview() }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 刷新区块标题和入口可见性。
|
||||
func apply(title: String, showsAction: Bool) {
|
||||
label.text = title
|
||||
button.isHidden = !showsAction
|
||||
}
|
||||
|
||||
@objc private func tapped() { onViewAll?() }
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
import UIKit
|
||||
|
||||
#if DEBUG
|
||||
/// 独立的本地预览入口,不伪造登录、权限或真实业务数据。
|
||||
/// Debug 页面入口:本地演示与使用当前登录身份的真实首页联调分别进入。
|
||||
@MainActor
|
||||
enum DroneDockPreview {
|
||||
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
|
||||
static func navigationController(arguments: [String]) -> UINavigationController? {
|
||||
if arguments.contains("--dock-home-live"), AppStore.shared.session.isLoggedIn {
|
||||
return UINavigationController(rootViewController: DroneDockHomeViewController())
|
||||
}
|
||||
let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview", "--dock-ui-materials-preview", "--dock-ui-delivery-preview", "--dock-ui-delivery-review-preview"]
|
||||
guard arguments.contains(where: { entryFlags.contains($0) }) else { return nil }
|
||||
let store = DroneDockDemoStore()
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
@testable import suixinkan
|
||||
|
||||
/// 使用真机实测的首页结构验证接口参数、统计精度与未知列表的保留规则。
|
||||
@MainActor
|
||||
final class DroneDockHomeAPITests: XCTestCase {
|
||||
/// 首页仅发起一次带当前景区、门店和登录凭证的 GET,真实空数据不替换为演示数据。
|
||||
func testHomeUsesReadOnlyRequestAndDecodesObservedEmptyResponse() async throws {
|
||||
let session = MockURLSession(responses: [envelope(Self.observedPayload)])
|
||||
let client = APIClient(environment: .testing, session: session)
|
||||
client.bindAuthTokenProvider { "home-contract-test-token" }
|
||||
|
||||
let response = try await DroneDockAPI(client: client).home(scenicID: 128, storeID: 37)
|
||||
|
||||
XCTAssertEqual(session.requests.count, 1)
|
||||
let request = try XCTUnwrap(session.requests.first)
|
||||
XCTAssertEqual(request.httpMethod, "GET")
|
||||
XCTAssertEqual(request.url?.host, "api-test.zhifly.cn")
|
||||
XCTAssertEqual(request.url?.path, "/api/app/airport/home")
|
||||
let query = URLComponents(url: try XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems ?? []
|
||||
XCTAssertEqual(Dictionary(uniqueKeysWithValues: query.map { ($0.name, $0.value ?? "") }),
|
||||
["scenic_id": "128", "store_id": "37"])
|
||||
XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "home-contract-test-token")
|
||||
XCTAssertNil(request.httpBody)
|
||||
XCTAssertEqual(response.scenicID, 128)
|
||||
XCTAssertTrue(response.airports.isEmpty)
|
||||
XCTAssertTrue(response.orders.isEmpty)
|
||||
XCTAssertEqual(response.today?.orderCount, 0)
|
||||
XCTAssertEqual(response.today?.orderAmount, Decimal.zero)
|
||||
XCTAssertEqual(response.today?.finishedShoot, 0)
|
||||
}
|
||||
|
||||
/// 兼容后端数字和字符串,使用十进制金额避免二进制浮点金额误差。
|
||||
func testStatisticsDecodeNumbersAndNumericStringsWithoutLosingAmountPrecision() throws {
|
||||
for amount in ["1896.10", "\"1896.10\""] {
|
||||
let data = Data("""
|
||||
{"scenic_id":"128","airports":[],"orders":[],
|
||||
"today":{"order_count":"12","order_amount":\(amount),"finished_shoot":"9"}}
|
||||
""".utf8)
|
||||
let response = try JSONDecoder().decode(DroneDockHomeResponse.self, from: data)
|
||||
XCTAssertEqual(response.scenicID, 128)
|
||||
XCTAssertEqual(response.today?.orderCount, 12)
|
||||
XCTAssertEqual(response.today?.finishedShoot, 9)
|
||||
XCTAssertEqual(response.today?.orderAmount, Decimal(string: "1896.10"))
|
||||
}
|
||||
}
|
||||
|
||||
/// 缺失或 null 的统计保留为未知,不显示伪造的零成交、零金额或零次拍摄。
|
||||
func testMissingStatisticsRemainUnknown() throws {
|
||||
for suffix in ["", ",\"today\":null", ",\"today\":{}",
|
||||
",\"today\":{\"order_count\":null,\"order_amount\":null,\"finished_shoot\":null}"] {
|
||||
let data = Data("{\"scenic_id\":128,\"airports\":[],\"orders\":[]\(suffix)}".utf8)
|
||||
let response = try JSONDecoder().decode(DroneDockHomeResponse.self, from: data)
|
||||
XCTAssertNil(response.today?.orderCount)
|
||||
XCTAssertNil(response.today?.orderAmount)
|
||||
XCTAssertNil(response.today?.finishedShoot)
|
||||
}
|
||||
}
|
||||
|
||||
/// 缺失、null 或类型错误的列表不能误展示为正常的空景区。
|
||||
func testMalformedRequiredListsAreRejected() {
|
||||
let payloads = [
|
||||
#"{"scenic_id":128,"orders":[]}"#,
|
||||
#"{"scenic_id":128,"airports":[]}"#,
|
||||
#"{"scenic_id":128,"airports":null,"orders":[]}"#,
|
||||
#"{"scenic_id":128,"airports":[],"orders":{}}"#,
|
||||
#"{"scenic_id":128,"airports":[12],"orders":[]}"#,
|
||||
#"{"scenic_id":128,"airports":[],"orders":[null]}"#
|
||||
]
|
||||
for payload in payloads {
|
||||
XCTAssertThrowsError(try JSONDecoder().decode(DroneDockHomeResponse.self, from: Data(payload.utf8)))
|
||||
}
|
||||
}
|
||||
|
||||
/// 设备按已验证字段读取,订单继续保留未知对象,不猜测订单契约。
|
||||
func testVerifiedAirportAndUnverifiedOrderArePreserved() throws {
|
||||
let payload = #"{"scenic_id":128,"airports":[{"id":58,"name":"测试机巢M4D","sn_number":"test-airport-sn","scenic_area_id":128,"online_status":1,"work_status":1,"work_status_label":"空闲","is_receive_order":1,"task_type":null,"metrics":[{"key":"battery","label":"电池电量","raw":null,"value":"—"}]}],"orders":[{"custom_order_key":"B","extra":false}],"today":null}"#
|
||||
let response = try JSONDecoder().decode(DroneDockHomeResponse.self, from: Data(payload.utf8))
|
||||
XCTAssertEqual(response.airports.count, 1)
|
||||
XCTAssertEqual(response.orders.count, 1)
|
||||
XCTAssertEqual(response.airports[0].id, 58)
|
||||
XCTAssertEqual(response.airports[0].name, "测试机巢M4D")
|
||||
XCTAssertEqual(response.airports[0].snNumber, "test-airport-sn")
|
||||
XCTAssertEqual(response.airports[0].statusTitle, "空闲")
|
||||
XCTAssertEqual(response.airports[0].metricText(for: "battery"), "—")
|
||||
XCTAssertNil(response.airports[0].batteryProgress)
|
||||
XCTAssertEqual(Set(response.orders[0].fields.keys), ["custom_order_key", "extra"])
|
||||
}
|
||||
|
||||
/// 无效统计值明确报解析错误,避免错误数据悄悄显示成零。
|
||||
func testInvalidStatisticsAreRejected() {
|
||||
for today in [#"{"order_count":"not-a-number"}"#, #"{"order_amount":"invalid"}"#,
|
||||
#"{"finished_shoot":1.5}"#] {
|
||||
let payload = "{\"scenic_id\":128,\"airports\":[],\"orders\":[],\"today\":\(today)}"
|
||||
XCTAssertThrowsError(try JSONDecoder().decode(DroneDockHomeResponse.self, from: Data(payload.utf8)))
|
||||
}
|
||||
}
|
||||
|
||||
/// 业务错误保留后端说明,不将失败响应当作空首页。
|
||||
func testBackendFailurePropagatesAsBusinessError() async throws {
|
||||
let session = MockURLSession(responses: [try TestJSON.errorEnvelope(code: 160001, msg: "当前门店无权访问该景区")])
|
||||
let api = DroneDockAPI(client: APIClient(environment: .testing, session: session))
|
||||
do {
|
||||
_ = try await api.home(scenicID: 128, storeID: 37)
|
||||
XCTFail("业务失败不能返回首页成功数据")
|
||||
} catch let APIError.serverCode(code, message) {
|
||||
XCTAssertEqual(code, 160001)
|
||||
XCTAssertEqual(message, "当前门店无权访问该景区")
|
||||
}
|
||||
}
|
||||
|
||||
/// 未选择景区或门店时不向服务器发送范围不明的请求。
|
||||
func testInvalidContextDoesNotSendRequest() async {
|
||||
let session = MockURLSession(responses: [])
|
||||
let api = DroneDockAPI(client: APIClient(environment: .testing, session: session))
|
||||
for (scenicID, storeID) in [(0, 37), (128, 0)] {
|
||||
do {
|
||||
_ = try await api.home(scenicID: scenicID, storeID: storeID)
|
||||
XCTFail("无效上下文应该拒绝请求")
|
||||
} catch {}
|
||||
}
|
||||
XCTAssertTrue(session.requests.isEmpty)
|
||||
}
|
||||
|
||||
/// 与已捕获的空数据响应一致的业务载荷,不包含真机登录信息。
|
||||
private static let observedPayload = #"{"scenic_id":128,"airports":[],"orders":[],"today":{"finished_shoot":0,"order_amount":0,"order_count":0}}"#
|
||||
|
||||
/// 为隔离网络替身补齐统一业务包裹。
|
||||
private func envelope(_ payload: String) -> Data {
|
||||
Data("{\"code\":100000,\"msg\":\"success\",\"data\":\(payload),\"time\":\"2026-10-27 14:13:24\"}".utf8)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
@testable import suixinkan
|
||||
|
||||
/// 验证实际设备字段、按键匹配的六项读数及未知状态,不访问设备或后端。
|
||||
final class DroneDockHomeAirportTests: XCTestCase {
|
||||
/// 六项读数即使乱序返回,也按 key 展示后端文案及单位。
|
||||
func testMetricsMatchKeysInsteadOfArrayPositions() throws {
|
||||
let airport = try decodeAirport(metrics: #"""
|
||||
[
|
||||
{"key":"satellite","label":"搜星状态","raw":30,"value":"30颗"},
|
||||
{"key":"rainfall","label":"雨量","raw":0,"value":"无雨"},
|
||||
{"key":"battery","label":"电池电量","raw":85,"value":"85%"},
|
||||
{"key":"signal","label":"信号状态","raw":4,"value":"良好"},
|
||||
{"key":"wind_speed","label":"风速","raw":1.2,"value":"1.2m/s"},
|
||||
{"key":"env_temp","label":"环境温度","raw":19.3,"value":"19.3°C"}
|
||||
]
|
||||
"""#)
|
||||
|
||||
let expected = ["battery": "85%", "env_temp": "19.3°C", "wind_speed": "1.2m/s",
|
||||
"rainfall": "无雨", "signal": "良好", "satellite": "30颗"]
|
||||
for (key, value) in expected { XCTAssertEqual(airport.metricText(for: key), value) }
|
||||
XCTAssertEqual(try XCTUnwrap(airport.batteryProgress), 0.85, accuracy: 0.0001)
|
||||
}
|
||||
|
||||
/// 原始值存在也不猜测展示单位;缺项、null、空白及破折占位统一显示未知。
|
||||
func testMissingAndPlaceholderMetricsStayUnknownWithoutGuessingRawUnits() throws {
|
||||
let airport = try decodeAirport(metrics: #"""
|
||||
[
|
||||
{"key":"battery","raw":null,"value":null},
|
||||
{"key":"env_temp","raw":20,"value":""},
|
||||
{"key":"wind_speed","raw":2,"value":" "},
|
||||
{"key":"rainfall","raw":0,"value":"--"},
|
||||
{"key":"signal","raw":4,"value":" – "}
|
||||
]
|
||||
"""#)
|
||||
|
||||
for key in metricKeys { XCTAssertEqual(airport.metricText(for: key), "—") }
|
||||
XCTAssertNil(airport.batteryProgress)
|
||||
|
||||
let noMetrics = try JSONDecoder().decode(DroneDockHomeAirport.self, from: Data(#"{"id":58,"name":"测试设备"}"#.utf8))
|
||||
for key in metricKeys { XCTAssertEqual(noMetrics.metricText(for: key), "—") }
|
||||
XCTAssertNil(noMetrics.batteryProgress)
|
||||
}
|
||||
|
||||
/// 真实零值保留零值和零进度,不能与未知电量混为一谈。
|
||||
func testMeasuredZeroDiffersFromUnknown() throws {
|
||||
let zero = try decodeAirport(metrics: #"[{"key":"battery","raw":0,"value":"0%"},{"key":"wind_speed","raw":0,"value":"0m/s"}]"#)
|
||||
let unknown = try decodeAirport(metrics: #"[{"key":"battery","raw":null,"value":"—"}]"#)
|
||||
|
||||
XCTAssertEqual(zero.metricText(for: "battery"), "0%")
|
||||
XCTAssertEqual(zero.metricText(for: "wind_speed"), "0m/s")
|
||||
XCTAssertEqual(zero.batteryProgress, 0)
|
||||
XCTAssertEqual(unknown.metricText(for: "battery"), "—")
|
||||
XCTAssertNil(unknown.batteryProgress)
|
||||
}
|
||||
|
||||
/// 电量环仅接受合法数值 raw;不把展示文本、数字字符串或越界值当作读数。
|
||||
func testBatteryProgressRejectsNonNumericAndOutOfRangeRaw() throws {
|
||||
for raw in ["null", "-1", "101", "\"85\"", "true", "{}"] {
|
||||
let airport = try decodeAirport(metrics: "[{\"key\":\"battery\",\"raw\":\(raw),\"value\":\"85%\"}]")
|
||||
XCTAssertNil(airport.batteryProgress, "raw=\(raw)")
|
||||
XCTAssertEqual(airport.metricText(for: "battery"), "85%")
|
||||
}
|
||||
let full = try decodeAirport(metrics: #"[{"key":"battery","raw":100,"value":"100%"}]"#)
|
||||
XCTAssertEqual(full.batteryProgress, 1)
|
||||
}
|
||||
|
||||
/// 只按后端状态文案及已验证状态着色,在线和接单标记不会生成空闲状态。
|
||||
func testStatusUsesBackendLabelWithoutInferringFlightReadiness() throws {
|
||||
let idle = try decodeAirport(metrics: "[]")
|
||||
XCTAssertEqual(idle.statusTitle, "空闲")
|
||||
XCTAssertEqual(idle.statusTone, .green)
|
||||
|
||||
let unknown = try JSONDecoder().decode(DroneDockHomeAirport.self, from: Data(#"{"id":58,"name":"测试设备","online_status":1,"is_receive_order":1,"work_status":1,"work_status_label":null}"#.utf8))
|
||||
XCTAssertEqual(unknown.statusTitle, "状态待确认")
|
||||
XCTAssertEqual(unknown.statusTone, .gray)
|
||||
|
||||
let occupied = try JSONDecoder().decode(DroneDockHomeAirport.self, from: Data(#"{"id":58,"name":"测试设备","work_status":2,"work_status_label":"占用中"}"#.utf8))
|
||||
XCTAssertEqual(occupied.statusTitle, "占用中")
|
||||
XCTAssertEqual(occupied.statusTone, .gray)
|
||||
}
|
||||
|
||||
/// 重复设备 ID 会破坏 Diffable 稳定身份,接口层明确拒绝而非触发页面崩溃。
|
||||
func testDuplicateAirportIDsAreRejected() {
|
||||
let payload = #"{"scenic_id":128,"airports":[{"id":58,"name":"设备A"},{"id":58,"name":"设备B"}],"orders":[]}"#
|
||||
XCTAssertThrowsError(try JSONDecoder().decode(DroneDockHomeResponse.self, from: Data(payload.utf8)))
|
||||
}
|
||||
|
||||
/// 测试固定的六项读数键。
|
||||
private var metricKeys: [String] { ["battery", "env_temp", "wind_speed", "rainfall", "signal", "satellite"] }
|
||||
|
||||
/// 使用当前真实设备结构搭配可控读数,不添加未经验证的字段别名。
|
||||
private func decodeAirport(metrics: String) throws -> DroneDockHomeAirport {
|
||||
let payload = """
|
||||
{"id":58,"name":"测试机巢M4D","sn_number":"test-airport-sn","scenic_area_id":128,
|
||||
"online_status":1,"work_status":1,"work_status_label":"空闲","is_receive_order":1,
|
||||
"task_type":null,"metrics":\(metrics)}
|
||||
"""
|
||||
return try JSONDecoder().decode(DroneDockHomeAirport.self, from: Data(payload.utf8))
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ final class DroneDockHomeRouteTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
/// 后台配置的正式 URI 打开现有演示工作台,保留普通导航和本地数据模式。
|
||||
/// 正式 URI 打开真实首页,加载前不生成演示设备或订单。
|
||||
func testDroneDockRouteOpensWorkbenchAfterSelectingScenic() throws {
|
||||
try withTemporaryScenic(26) {
|
||||
let root = DroneDockHomeRouteProbeController()
|
||||
@@ -27,10 +27,11 @@ final class DroneDockHomeRouteTests: XCTestCase {
|
||||
|
||||
HomeRouteHandler.open(uri: "drone_dock", from: root, storeItem: nil)
|
||||
|
||||
let workbench = try XCTUnwrap(navigation.topViewController as? DroneDockWorkbenchViewController)
|
||||
let workbench = try XCTUnwrap(navigation.topViewController as? DroneDockHomeViewController)
|
||||
XCTAssertEqual(navigation.viewControllers.count, 2)
|
||||
XCTAssertTrue(workbench.hidesBottomBarWhenPushed)
|
||||
XCTAssertFalse(workbench.viewModel.store.orders.isEmpty)
|
||||
XCTAssertNil(workbench.viewModel.response)
|
||||
XCTAssertEqual(workbench.viewModel.context.scenicID, 26)
|
||||
XCTAssertNil(root.lastPresentedMessage)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
@testable import suixinkan
|
||||
|
||||
/// 验证真实首页的空态、失败、账号隔离及乱序刷新,不访问真机账号或外部接口。
|
||||
@MainActor
|
||||
final class DroneDockRemoteHomeViewModelTests: XCTestCase {
|
||||
/// 真正返回空列表时才显示空态和零统计,初始化不带本地演示数据。
|
||||
func testSuccessfulEmptyResponseRemainsRealEmptyData() async throws {
|
||||
let scope = HomeContextBox(context())
|
||||
let service = ImmediateHomeService(result: .success(try response(orderCount: 0)))
|
||||
let model = makeModel(scope: scope, service: service)
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNil(model.errorMessage)
|
||||
XCTAssertFalse(model.isLoading)
|
||||
|
||||
await model.refresh()
|
||||
|
||||
let value = try XCTUnwrap(model.response)
|
||||
XCTAssertTrue(value.airports.isEmpty)
|
||||
XCTAssertTrue(value.orders.isEmpty)
|
||||
XCTAssertEqual(value.today?.orderCount, 0)
|
||||
XCTAssertFalse(model.isLoading)
|
||||
XCTAssertNil(model.errorMessage)
|
||||
XCTAssertEqual(service.requests.count, 1)
|
||||
XCTAssertEqual(service.requests.first?.scenicID, 128)
|
||||
XCTAssertEqual(service.requests.first?.storeID, 37)
|
||||
}
|
||||
|
||||
/// 刷新失败后不继续把上次快照当作最新数据,也不以演示数据掩盖错误。
|
||||
func testRefreshFailureClearsOldSnapshotAndCanRetry() async throws {
|
||||
let scope = HomeContextBox(context())
|
||||
let service = ImmediateHomeService(result: .success(try response(orderCount: 12)))
|
||||
let model = makeModel(scope: scope, service: service)
|
||||
await model.refresh()
|
||||
XCTAssertEqual(model.response?.today?.orderCount, 12)
|
||||
|
||||
service.result = .failure(APIError.networkFailed("测试网络超时"))
|
||||
await model.refresh()
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertTrue(model.errorMessage?.contains("测试网络超时") == true)
|
||||
XCTAssertFalse(model.isLoading)
|
||||
|
||||
service.result = .success(try response(orderCount: 13))
|
||||
await model.refresh()
|
||||
XCTAssertEqual(model.response?.today?.orderCount, 13)
|
||||
XCTAssertNil(model.errorMessage)
|
||||
XCTAssertFalse(model.isLoading)
|
||||
}
|
||||
|
||||
/// 后端返回另一景区的快照时拒绝显示,防止跨景区数据串用。
|
||||
func testMismatchedResponseScenicIsRejected() async throws {
|
||||
let scope = HomeContextBox(context())
|
||||
let service = ImmediateHomeService(result: .success(try response(scenicID: 999, orderCount: 8)))
|
||||
let model = makeModel(scope: scope, service: service)
|
||||
|
||||
await model.refresh()
|
||||
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNotNil(model.errorMessage)
|
||||
XCTAssertFalse(model.isLoading)
|
||||
}
|
||||
|
||||
/// 登录信息或选择范围不完整时在本地提示,不查询任何门店首页。
|
||||
func testMissingSessionOrSelectionDoesNotCallService() async throws {
|
||||
for missing in [context(scenicID: 0), context(token: "")] {
|
||||
let scope = HomeContextBox(missing)
|
||||
let service = ImmediateHomeService(result: .success(try response(orderCount: 12)))
|
||||
let model = makeModel(scope: scope, service: service)
|
||||
|
||||
await model.refresh()
|
||||
|
||||
XCTAssertTrue(service.requests.isEmpty)
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNotNil(model.errorMessage)
|
||||
XCTAssertFalse(model.isLoading)
|
||||
}
|
||||
}
|
||||
|
||||
/// 第二次刷新先完成时,第一次的迟到响应不能覆盖新统计。
|
||||
func testOlderRefreshCannotOverwriteNewerResponse() async throws {
|
||||
let scope = HomeContextBox(context())
|
||||
let service = SuspendedHomeService()
|
||||
let firstStarted = expectation(description: "首个首页请求已挂起")
|
||||
let secondStarted = expectation(description: "第二个首页请求已挂起")
|
||||
service.requestStarted = { index in
|
||||
if index == 0 { firstStarted.fulfill() }
|
||||
if index == 1 { secondStarted.fulfill() }
|
||||
}
|
||||
defer { service.cancelAll() }
|
||||
let model = makeModel(scope: scope, service: service)
|
||||
let first = Task { await model.refresh() }
|
||||
await fulfillment(of: [firstStarted], timeout: 2)
|
||||
XCTAssertTrue(model.isLoading)
|
||||
|
||||
let second = Task { await model.refresh() }
|
||||
await fulfillment(of: [secondStarted], timeout: 2)
|
||||
service.finish(index: 1, result: .success(try response(orderCount: 20)))
|
||||
await second.value
|
||||
service.finish(index: 0, result: .success(try response(orderCount: 10)))
|
||||
await first.value
|
||||
|
||||
XCTAssertEqual(model.response?.today?.orderCount, 20)
|
||||
XCTAssertFalse(model.isLoading)
|
||||
XCTAssertNil(model.errorMessage)
|
||||
}
|
||||
|
||||
/// 用户已经切换景区后,原景区的成功回包不能落到当前首页。
|
||||
func testChangedScenicDiscardsInFlightResponse() async throws {
|
||||
let scope = HomeContextBox(context())
|
||||
let service = SuspendedHomeService()
|
||||
let started = expectation(description: "旧景区请求已挂起")
|
||||
service.requestStarted = { _ in started.fulfill() }
|
||||
defer { service.cancelAll() }
|
||||
let model = makeModel(scope: scope, service: service)
|
||||
let pending = Task { await model.refresh() }
|
||||
await fulfillment(of: [started], timeout: 2)
|
||||
|
||||
scope.value = context(scenicID: 129)
|
||||
service.finish(index: 0, result: .success(try response(orderCount: 12)))
|
||||
await pending.value
|
||||
|
||||
XCTAssertEqual(model.context.scenicID, 129)
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNotNil(model.errorMessage)
|
||||
XCTAssertFalse(model.isLoading)
|
||||
}
|
||||
|
||||
/// 同一账号和景区重新登录换 Token 后,旧会话请求也必须失效。
|
||||
func testChangedTokenDiscardsInFlightResponse() async throws {
|
||||
let scope = HomeContextBox(context(token: "first-test-session"))
|
||||
let service = SuspendedHomeService()
|
||||
let started = expectation(description: "旧登录请求已挂起")
|
||||
service.requestStarted = { _ in started.fulfill() }
|
||||
defer { service.cancelAll() }
|
||||
let model = makeModel(scope: scope, service: service)
|
||||
let pending = Task { await model.refresh() }
|
||||
await fulfillment(of: [started], timeout: 2)
|
||||
|
||||
scope.value = context(token: "second-test-session")
|
||||
service.finish(index: 0, result: .success(try response(orderCount: 12)))
|
||||
await pending.value
|
||||
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNotNil(model.errorMessage)
|
||||
XCTAssertFalse(model.isLoading)
|
||||
}
|
||||
|
||||
/// 新景区请求尚未返回时,旧请求失败不能清除新请求的加载状态或写入旧错误。
|
||||
func testOldFailureDoesNotChangeNewContextLoadingState() async throws {
|
||||
let scope = HomeContextBox(context())
|
||||
let service = SuspendedHomeService()
|
||||
let firstStarted = expectation(description: "旧景区请求已挂起")
|
||||
let secondStarted = expectation(description: "新景区请求已挂起")
|
||||
service.requestStarted = { index in
|
||||
if index == 0 { firstStarted.fulfill() }
|
||||
if index == 1 { secondStarted.fulfill() }
|
||||
}
|
||||
defer { service.cancelAll() }
|
||||
let model = makeModel(scope: scope, service: service)
|
||||
let first = Task { await model.refresh() }
|
||||
await fulfillment(of: [firstStarted], timeout: 2)
|
||||
scope.value = context(scenicID: 129)
|
||||
let second = Task { await model.refresh() }
|
||||
await fulfillment(of: [secondStarted], timeout: 2)
|
||||
|
||||
service.finish(index: 0, result: .failure(APIError.networkFailed("旧景区网络错误")))
|
||||
await first.value
|
||||
XCTAssertTrue(model.isLoading)
|
||||
XCTAssertNil(model.errorMessage)
|
||||
XCTAssertNil(model.response)
|
||||
|
||||
service.finish(index: 1, result: .success(try response(scenicID: 129, orderCount: 3)))
|
||||
await second.value
|
||||
XCTAssertEqual(model.context.scenicID, 129)
|
||||
XCTAssertEqual(model.response?.today?.orderCount, 3)
|
||||
XCTAssertFalse(model.isLoading)
|
||||
XCTAssertNil(model.errorMessage)
|
||||
}
|
||||
|
||||
/// 页面主动失效后,仍在途中的成功回包不能重新填充已清空的数据。
|
||||
func testInvalidateRejectsPendingResponse() async throws {
|
||||
let scope = HomeContextBox(context())
|
||||
let service = SuspendedHomeService()
|
||||
let started = expectation(description: "待失效请求已挂起")
|
||||
service.requestStarted = { _ in started.fulfill() }
|
||||
defer { service.cancelAll() }
|
||||
let model = makeModel(scope: scope, service: service)
|
||||
let pending = Task { await model.refresh() }
|
||||
await fulfillment(of: [started], timeout: 2)
|
||||
|
||||
model.invalidate()
|
||||
XCTAssertFalse(model.isLoading)
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNil(model.errorMessage)
|
||||
service.finish(index: 0, result: .success(try response(orderCount: 12)))
|
||||
await pending.value
|
||||
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNil(model.errorMessage)
|
||||
XCTAssertFalse(model.isLoading)
|
||||
}
|
||||
|
||||
/// 每例使用内存身份,避免修改设备上的已登录账号。
|
||||
private func context(scenicID: Int = 128, token: String = "home-view-model-test-token") -> DroneDockHomeContext {
|
||||
DroneDockHomeContext(userID: "home-test-user", accountType: "store_user", scenicID: scenicID,
|
||||
scenicName: "测试景区", storeID: 37, photographerName: "测试人员", token: token)
|
||||
}
|
||||
|
||||
/// 从确定性 JSON 构造返回快照,不依赖 Model 的额外测试初始化器。
|
||||
private func response(scenicID: Int = 128, orderCount: Int) throws -> DroneDockHomeResponse {
|
||||
let payload = """
|
||||
{"scenic_id":\(scenicID),"airports":[],"orders":[],
|
||||
"today":{"order_count":\(orderCount),"order_amount":0,"finished_shoot":0}}
|
||||
"""
|
||||
return try JSONDecoder().decode(DroneDockHomeResponse.self, from: Data(payload.utf8))
|
||||
}
|
||||
|
||||
/// 注入可变化身份提供者,供模拟账号或景区切换。
|
||||
private func makeModel(scope: HomeContextBox, service: any DroneDockHomeServing) -> DroneDockHomeViewModel {
|
||||
DroneDockHomeViewModel(context: scope.value, service: service, currentContext: { scope.value })
|
||||
}
|
||||
}
|
||||
|
||||
/// 主线程隔离的当前身份替身,模拟会话变化且不接触 AppStore。
|
||||
@MainActor
|
||||
private final class HomeContextBox {
|
||||
var value: DroneDockHomeContext
|
||||
|
||||
/// 保存本例初始身份。
|
||||
init(_ value: DroneDockHomeContext) { self.value = value }
|
||||
}
|
||||
|
||||
/// 立即返回指定快照或错误的只读首页替身。
|
||||
@MainActor
|
||||
private final class ImmediateHomeService: DroneDockHomeServing {
|
||||
var result: Result<DroneDockHomeResponse, Error>
|
||||
private(set) var requests: [(scenicID: Int, storeID: Int)] = []
|
||||
|
||||
/// 注入本例响应。
|
||||
init(result: Result<DroneDockHomeResponse, Error>) { self.result = result }
|
||||
|
||||
/// 记录请求范围并返回预设结果。
|
||||
func home(scenicID: Int, storeID: Int) async throws -> DroneDockHomeResponse {
|
||||
requests.append((scenicID, storeID))
|
||||
return try result.get()
|
||||
}
|
||||
}
|
||||
|
||||
/// 由测试逐项完成响应,精确构造乱序回包而不依赖网络延迟。
|
||||
@MainActor
|
||||
private final class SuspendedHomeService: DroneDockHomeServing {
|
||||
var requestStarted: ((Int) -> Void)?
|
||||
private var nextIndex = 0
|
||||
private var pending: [Int: CheckedContinuation<DroneDockHomeResponse, Error>] = [:]
|
||||
|
||||
/// 挂起本次请求,允许测试先改变身份或发出下一次刷新。
|
||||
func home(scenicID: Int, storeID: Int) async throws -> DroneDockHomeResponse {
|
||||
let index = nextIndex
|
||||
nextIndex += 1
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
pending[index] = continuation
|
||||
requestStarted?(index)
|
||||
}
|
||||
}
|
||||
|
||||
/// 只完成指定的一次请求,模拟真实响应先后顺序。
|
||||
func finish(index: Int, result: Result<DroneDockHomeResponse, Error>) {
|
||||
pending.removeValue(forKey: index)?.resume(with: result)
|
||||
}
|
||||
|
||||
/// 测试异常退出时释放所有挂起调用,避免遗留 continuation。
|
||||
func cancelAll() {
|
||||
let remaining = pending.values
|
||||
pending.removeAll()
|
||||
remaining.forEach { $0.resume(throwing: CancellationError()) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
import UIKit
|
||||
import XCTest
|
||||
@testable import suixinkan
|
||||
|
||||
/// 在真机窗口验证正式首页的真实空态、错误显示和演示流程隔离,网络全部使用替身。
|
||||
@MainActor
|
||||
final class DroneDockRemoteHomeViewTests: XCTestCase {
|
||||
private weak var previousKeyWindow: UIWindow?
|
||||
|
||||
/// 成功空响应显示接口零值,不混入演示设备、订单或演示统计。
|
||||
func testSuccessfulEmptyHomeDisplaysZeroStatisticsWithoutDemoData() async throws {
|
||||
let (controller, session) = makeController(responses: [emptyEnvelope])
|
||||
let window = makeWindow(root: controller)
|
||||
defer { close(window) }
|
||||
|
||||
try await settle(window: window) {
|
||||
self.visibleTexts(in: controller.view).contains("¥0.00")
|
||||
&& self.visibleTexts(in: controller.view).contains("暂无待拍摄订单")
|
||||
}
|
||||
|
||||
let texts = visibleTexts(in: controller.view)
|
||||
XCTAssertEqual(controller.title, "机巢工作台")
|
||||
XCTAssertTrue(texts.contains("测试景区 · 测试工作人员"))
|
||||
XCTAssertTrue(texts.contains("暂无无人机"))
|
||||
XCTAssertTrue(texts.contains("成交订单"))
|
||||
XCTAssertTrue(texts.contains("成交金额"))
|
||||
XCTAssertTrue(texts.contains("完成拍摄"))
|
||||
XCTAssertEqual(texts.filter { $0 == "0" }.count, 2)
|
||||
XCTAssertFalse(texts.contains("演示状态 ⌄"))
|
||||
XCTAssertFalse(texts.contains("01号无人机"))
|
||||
XCTAssertFalse(texts.contains("¥1,896"))
|
||||
XCTAssertTrue(controller.viewModel.response?.airports.isEmpty == true)
|
||||
XCTAssertTrue(controller.viewModel.response?.orders.isEmpty == true)
|
||||
assertOnlyReadHomeRequests(session)
|
||||
capture(window, named: "机巢真实首页-成功空态和零值统计")
|
||||
}
|
||||
|
||||
/// 接口失败显示重试信息,不能展示成功空态或虚构零值。
|
||||
func testFailedHomeShowsErrorInsteadOfEmptyDataOrZeroStatistics() async throws {
|
||||
let errorEnvelope = try TestJSON.errorEnvelope(code: 160001, msg: "机巢首页暂不可用")
|
||||
let (controller, session) = makeController(responses: [errorEnvelope])
|
||||
let window = makeWindow(root: controller)
|
||||
defer { close(window) }
|
||||
|
||||
try await settle(window: window) {
|
||||
self.visibleTexts(in: controller.view).contains("首页加载失败")
|
||||
}
|
||||
|
||||
let texts = visibleTexts(in: controller.view)
|
||||
XCTAssertTrue(texts.contains { $0.contains("机巢首页暂不可用") && $0.contains("请下拉重试") })
|
||||
XCTAssertFalse(texts.contains("暂无无人机"))
|
||||
XCTAssertFalse(texts.contains("暂无待拍摄订单"))
|
||||
XCTAssertFalse(texts.contains("¥0.00"))
|
||||
XCTAssertFalse(texts.contains("0"))
|
||||
XCTAssertEqual(texts.filter { $0 == "—" }.count, 3)
|
||||
XCTAssertNil(controller.viewModel.response)
|
||||
assertOnlyReadHomeRequests(session)
|
||||
}
|
||||
|
||||
/// 正式首页的后续入口不会把真实账号送入本地演示拍摄、订单或收款流程。
|
||||
func testOrderAndReceiptEntriesStayOutOfDemoFlows() async throws {
|
||||
let (controller, session) = makeController(responses: Array(repeating: emptyEnvelope, count: 4))
|
||||
let window = makeWindow(root: controller)
|
||||
defer { close(window) }
|
||||
|
||||
try await settle(window: window) {
|
||||
self.visibleTexts(in: controller.view).contains("暂无待拍摄订单")
|
||||
&& self.find(in: controller.view, identifier: "drone.home.allOrders") != nil
|
||||
}
|
||||
|
||||
let viewAll = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.allOrders") as? UIButton)
|
||||
XCTAssertTrue(viewAll.isEnabled)
|
||||
viewAll.sendActions(for: .touchUpInside)
|
||||
try await settle(window: window) {
|
||||
(controller.presentedViewController as? UIAlertController)?.title == "拍摄订单"
|
||||
}
|
||||
XCTAssertEqual((controller.presentedViewController as? UIAlertController)?.message, "该功能暂未开放")
|
||||
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
|
||||
XCTAssertTrue(controller.navigationController?.topViewController === controller)
|
||||
|
||||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||||
controller.dismiss(animated: false) { continuation.resume() }
|
||||
}
|
||||
try await settle(window: window) { controller.presentedViewController == nil }
|
||||
|
||||
let receipt = try XCTUnwrap(controller.navigationItem.rightBarButtonItem)
|
||||
XCTAssertEqual(receipt.accessibilityIdentifier, "drone.home.receipt")
|
||||
let action = try XCTUnwrap(receipt.action)
|
||||
XCTAssertTrue(UIApplication.shared.sendAction(action, to: receipt.target, from: receipt, for: nil))
|
||||
try await settle(window: window) {
|
||||
(controller.presentedViewController as? UIAlertController)?.title == "套餐收款"
|
||||
}
|
||||
XCTAssertEqual((controller.presentedViewController as? UIAlertController)?.message, "该功能暂未开放")
|
||||
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
|
||||
XCTAssertTrue(controller.navigationController?.topViewController === controller)
|
||||
assertOnlyReadHomeRequests(session)
|
||||
}
|
||||
|
||||
/// 真实机巢样例按服务端名称、状态展示;尚无遥测时六项读数都保持未知。
|
||||
func testRealAirportDisplaysServerNameStatusAndUnknownMetrics() async throws {
|
||||
let (controller, session) = makeController(responses: [populatedEnvelope])
|
||||
let window = makeWindow(root: controller)
|
||||
defer { close(window) }
|
||||
|
||||
try await settle(window: window) {
|
||||
self.find(in: controller.view, identifier: "drone.device.58") != nil
|
||||
&& self.metricTexts(in: controller.view).count == 6
|
||||
}
|
||||
|
||||
let card = try XCTUnwrap(find(in: controller.view, identifier: "drone.device.58"))
|
||||
let texts = visibleTexts(in: card)
|
||||
XCTAssertTrue(texts.contains("测试机巢M4D"))
|
||||
XCTAssertTrue(texts.contains("空闲"))
|
||||
XCTAssertEqual(metricTexts(in: card), Dictionary(uniqueKeysWithValues: metricKeys.map { ($0, "—") }))
|
||||
XCTAssertFalse(visibleTexts(in: controller.view).contains("设备信息暂不可用"))
|
||||
XCTAssertFalse(visibleTexts(in: controller.view).contains("暂无无人机"))
|
||||
assertOnlyReadHomeRequests(session)
|
||||
capture(window, named: "机巢真实首页-设备名称状态与未知读数")
|
||||
}
|
||||
|
||||
/// 同一机巢刷新时保留合法零值,之后读数变未知会清除旧值而不残留在复用卡片里。
|
||||
func testDeviceRefreshKeepsZeroValuesAndClearsUnavailableReadings() async throws {
|
||||
let nonzero: [String: (Double, String)] = [
|
||||
"battery": (88, "88%"), "env_temp": (21.5, "21.5°C"), "wind_speed": (4.2, "4.2m/s"),
|
||||
"rainfall": (1, "小雨"), "signal": (4, "良好"), "satellite": (32, "32颗")
|
||||
]
|
||||
let zero: [String: (Double, String)] = [
|
||||
"battery": (0, "0%"), "env_temp": (0, "0°C"), "wind_speed": (0, "0m/s"),
|
||||
"rainfall": (0, "0"), "signal": (0, "0"), "satellite": (0, "0颗")
|
||||
]
|
||||
let responses = try [deviceEnvelope(metricValues: nonzero), deviceEnvelope(metricValues: zero), populatedEnvelope]
|
||||
let (controller, session) = makeController(responses: responses)
|
||||
let window = makeWindow(root: controller)
|
||||
defer { close(window) }
|
||||
|
||||
try await settle(window: window) { self.metricTexts(in: controller.view) == nonzero.mapValues { $0.1 } }
|
||||
let collection = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.remote.list") as? UICollectionView)
|
||||
let refresh = try XCTUnwrap(collection.refreshControl)
|
||||
refresh.sendActions(for: .valueChanged)
|
||||
try await settle(window: window) { self.metricTexts(in: controller.view) == zero.mapValues { $0.1 } }
|
||||
|
||||
XCTAssertEqual(session.requests.count, 2)
|
||||
XCTAssertEqual(collection.numberOfItems(inSection: 1), 1)
|
||||
refresh.sendActions(for: .valueChanged)
|
||||
let unknown = Dictionary(uniqueKeysWithValues: metricKeys.map { ($0, "—") })
|
||||
try await settle(window: window) { self.metricTexts(in: controller.view) == unknown }
|
||||
|
||||
XCTAssertEqual(session.requests.count, 3)
|
||||
XCTAssertEqual(collection.numberOfItems(inSection: 1), 1)
|
||||
XCTAssertNotNil(find(in: controller.view, identifier: "drone.device.58"))
|
||||
assertOnlyReadHomeRequests(session)
|
||||
}
|
||||
|
||||
/// 从单机刷新为多机时完整应用设备列表,并切换为能提示横向浏览的卡片宽度。
|
||||
func testRefreshingFromOneToTwoAirportsUpdatesCarousel() async throws {
|
||||
let (controller, session) = makeController(responses: [populatedEnvelope, try deviceEnvelope(addSecondAirport: true)])
|
||||
let window = makeWindow(root: controller)
|
||||
defer { close(window) }
|
||||
|
||||
try await settle(window: window) { self.find(in: controller.view, identifier: "drone.device.58") != nil }
|
||||
let collection = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.remote.list") as? UICollectionView)
|
||||
XCTAssertEqual(collection.numberOfItems(inSection: 1), 1)
|
||||
let devicePath = IndexPath(item: 0, section: 1)
|
||||
let singleWidth = try XCTUnwrap(collection.collectionViewLayout.layoutAttributesForItem(at: devicePath)).frame.width
|
||||
|
||||
let refresh = try XCTUnwrap(collection.refreshControl)
|
||||
refresh.sendActions(for: .valueChanged)
|
||||
try await settle(window: window) {
|
||||
collection.numberOfItems(inSection: 1) == 2
|
||||
&& (collection.collectionViewLayout.layoutAttributesForItem(at: devicePath)?.frame.width ?? singleWidth) < singleWidth
|
||||
&& (self.find(in: controller.view, identifier: "drone.home.devicePages") as? UIPageControl)?.numberOfPages == 2
|
||||
}
|
||||
|
||||
let multipleWidth = try XCTUnwrap(collection.collectionViewLayout.layoutAttributesForItem(at: devicePath)).frame.width
|
||||
XCTAssertGreaterThan(multipleWidth, 0)
|
||||
XCTAssertLessThan(multipleWidth, singleWidth)
|
||||
XCTAssertEqual(controller.viewModel.response?.airports.count, 2)
|
||||
let pages = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.devicePages") as? UIPageControl)
|
||||
XCTAssertEqual(pages.currentPage, 0)
|
||||
XCTAssertEqual(session.requests.count, 2)
|
||||
assertOnlyReadHomeRequests(session)
|
||||
capture(window, named: "机巢真实首页-多设备横向卡片")
|
||||
}
|
||||
|
||||
/// 服务端确定的六项读数键,按标识查找而不依赖数组排序。
|
||||
private var metricKeys: [String] { ["battery", "env_temp", "wind_speed", "rainfall", "signal", "satellite"] }
|
||||
|
||||
/// 按实际 home 响应结构构造替身,设备名称和序列号使用测试值。
|
||||
private var populatedEnvelope: Data {
|
||||
Data(#"{"code":100000,"msg":"success","data":{"scenic_id":128,"airports":[{"id":58,"name":"测试机巢M4D","sn_number":"test-airport-sn","scenic_area_id":128,"online_status":1,"work_status":1,"work_status_label":"空闲","is_receive_order":1,"task_type":null,"metrics":[{"key":"battery","label":"电池电量","raw":null,"value":"—"},{"key":"env_temp","label":"环境温度","raw":null,"value":"—"},{"key":"wind_speed","label":"风速","raw":null,"value":"—"},{"key":"rainfall","label":"雨量","raw":null,"value":"—"},{"key":"signal","label":"信号状态","raw":null,"value":"—"},{"key":"satellite","label":"搜星状态","raw":null,"value":"—"}]}],"orders":[],"today":{"finished_shoot":0,"order_amount":0,"order_count":0}},"time":"2026-10-27 14:38:58"}"#.utf8)
|
||||
}
|
||||
|
||||
/// 在真实结构中替换遥测或追加设备,构造确定的刷新与多机测试输入。
|
||||
private func deviceEnvelope(metricValues: [String: (Double, String)]? = nil, addSecondAirport: Bool = false) throws -> Data {
|
||||
var envelope = try XCTUnwrap(JSONSerialization.jsonObject(with: populatedEnvelope) as? [String: Any])
|
||||
var data = try XCTUnwrap(envelope["data"] as? [String: Any])
|
||||
var airports = try XCTUnwrap(data["airports"] as? [[String: Any]])
|
||||
if let metricValues {
|
||||
var metrics = try XCTUnwrap(airports[0]["metrics"] as? [[String: Any]])
|
||||
for index in metrics.indices {
|
||||
let key = try XCTUnwrap(metrics[index]["key"] as? String)
|
||||
let value = try XCTUnwrap(metricValues[key])
|
||||
metrics[index]["raw"] = value.0
|
||||
metrics[index]["value"] = value.1
|
||||
}
|
||||
airports[0]["metrics"] = metrics
|
||||
}
|
||||
if addSecondAirport {
|
||||
var second = airports[0]
|
||||
second["id"] = 59
|
||||
second["name"] = "测试二号无人机"
|
||||
second["sn_number"] = "ui-test-second-airport"
|
||||
airports.append(second)
|
||||
}
|
||||
data["airports"] = airports
|
||||
envelope["data"] = data
|
||||
return try JSONSerialization.data(withJSONObject: envelope)
|
||||
}
|
||||
|
||||
/// 从实际设备卡获取已呈现的读数,缺少标签时不会伪造占位值。
|
||||
private func metricTexts(in view: UIView) -> [String: String] {
|
||||
var values: [String: String] = [:]
|
||||
for key in metricKeys {
|
||||
guard let label = find(in: view, identifier: "drone.metric.\(key)") as? UILabel,
|
||||
!isHiddenByAncestor(label), !label.bounds.isEmpty, let text = label.text else { continue }
|
||||
values[key] = text
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
/// 与实际控制台响应结构一致的成功空数据,不依赖当前真机账户。
|
||||
private var emptyEnvelope: Data {
|
||||
Data(#"{"code":100000,"msg":"success","data":{"scenic_id":128,"airports":[],"orders":[],"today":{"finished_shoot":0,"order_amount":0,"order_count":0}}}"#.utf8)
|
||||
}
|
||||
|
||||
/// 创建只接替身网络的正式首页,不读取或修改真机登录状态。
|
||||
private func makeController(responses: [Data]) -> (DroneDockHomeViewController, MockURLSession) {
|
||||
let context = DroneDockHomeContext(
|
||||
userID: "remote-home-ui-test", accountType: "store_user", scenicID: 128,
|
||||
scenicName: "测试景区", storeID: 37, photographerName: "测试工作人员", token: "test-token"
|
||||
)
|
||||
let session = MockURLSession(responses: responses)
|
||||
let client = APIClient(environment: .testing, session: session, notificationCenter: NotificationCenter())
|
||||
client.bindAuthTokenProvider { "test-token" }
|
||||
let viewModel = DroneDockHomeViewModel(context: context, service: DroneDockAPI(client: client), currentContext: { context })
|
||||
return (DroneDockHomeViewController(viewModel: viewModel), session)
|
||||
}
|
||||
|
||||
/// 创建临时真机窗口,结束后恢复原窗口。
|
||||
private func makeWindow(root: UIViewController) -> UIWindow {
|
||||
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
|
||||
let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
|
||||
previousKeyWindow = scene?.windows.first { $0.isKeyWindow }
|
||||
let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds)
|
||||
window.frame = scene?.coordinateSpace.bounds ?? UIScreen.main.bounds
|
||||
window.overrideUserInterfaceStyle = .light
|
||||
window.rootViewController = UINavigationController(rootViewController: root)
|
||||
window.makeKeyAndVisible()
|
||||
window.layoutIfNeeded()
|
||||
return window
|
||||
}
|
||||
|
||||
/// 清理弹层与异步页面任务,不改变原账户及业务窗口。
|
||||
private func close(_ window: UIWindow) {
|
||||
window.endEditing(true)
|
||||
window.rootViewController?.dismiss(animated: false)
|
||||
window.isHidden = true
|
||||
window.rootViewController = nil
|
||||
previousKeyWindow?.makeKeyAndVisible()
|
||||
}
|
||||
|
||||
/// 等待网络替身、Diffable 和实际窗口布局完成,不靠固定长延迟判断结果。
|
||||
private func settle(window: UIWindow, until condition: () -> Bool) async throws {
|
||||
for _ in 0..<150 {
|
||||
window.layoutIfNeeded()
|
||||
window.rootViewController?.view.layoutIfNeeded()
|
||||
if condition() {
|
||||
try await Task.sleep(nanoseconds: 250_000_000)
|
||||
window.layoutIfNeeded()
|
||||
return
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
XCTFail("真实机巢首页未在预期时间内完成渲染")
|
||||
throw NSError(domain: "DroneDockRemoteHomeViewTests", code: 1)
|
||||
}
|
||||
|
||||
/// 从实际可见子视图获取文本,排除被隐藏的复用视图。
|
||||
private func visibleTexts(in root: UIView) -> [String] {
|
||||
allViews(in: root).compactMap { view in
|
||||
guard let label = view as? UILabel, !isHiddenByAncestor(label), !label.bounds.isEmpty else { return nil }
|
||||
return label.text
|
||||
}
|
||||
}
|
||||
|
||||
/// 枚举测试窗口里的真实视图,避免读取生产代码私有字段。
|
||||
private func allViews(in view: UIView) -> [UIView] {
|
||||
[view] + view.subviews.flatMap { allViews(in: $0) }
|
||||
}
|
||||
|
||||
/// 按稳定的辅助功能标识定位实际控件。
|
||||
private func find(in root: UIView, identifier: String) -> UIView? {
|
||||
allViews(in: root).first { $0.accessibilityIdentifier == identifier }
|
||||
}
|
||||
|
||||
/// 排除隐藏祖先和完全透明的控件。
|
||||
private func isHiddenByAncestor(_ view: UIView) -> Bool {
|
||||
if view.isHidden || view.alpha < 0.01 { return true }
|
||||
return view.superview.map { isHiddenByAncestor($0) } ?? false
|
||||
}
|
||||
|
||||
/// 证明页面入口只读取 home,没有发送其他业务或设备控制请求。
|
||||
private func assertOnlyReadHomeRequests(_ session: MockURLSession, file: StaticString = #filePath, line: UInt = #line) {
|
||||
XCTAssertFalse(session.requests.isEmpty, file: file, line: line)
|
||||
XCTAssertTrue(session.requests.allSatisfy { $0.httpMethod == "GET" && $0.url?.path == "/api/app/airport/home" }, file: file, line: line)
|
||||
}
|
||||
|
||||
/// 保存测试窗口截图到真机 xcresult,便于核对空态样式。
|
||||
private func capture(_ window: UIWindow, named name: String) {
|
||||
let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in
|
||||
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
|
||||
}
|
||||
let attachment = XCTAttachment(image: image)
|
||||
attachment.name = name
|
||||
attachment.lifetime = .keepAlways
|
||||
add(attachment)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user