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

Merged
lujiuyin merged 70 commits from dev_9_9_1 into main 2026-11-18 07:05:44 +00:00
12 changed files with 2041 additions and 39 deletions
Showing only changes of commit 79884cf588 - Show all commits
@@ -0,0 +1,32 @@
import Foundation
/// 拍摄准备页只读数据源,不创建订单任务或发送飞行控制指令。
protocol DroneDockPreparationServing: Sendable {
/// 获取指定订单的点位、航线与召唤门禁;无有效定位时省略坐标。
@MainActor
func workbench(scenicID: Int, orderNumber: String, coordinate: DroneDockPreparationCoordinate?) async throws -> DroneDockPreparationResponse
}
/// 朱工的拍摄准备接口,登录凭证由统一客户端注入。
@MainActor
final class DroneDockPreparationAPI: DroneDockPreparationServing {
private let client: APIClient
/// 注入统一客户端,正式页面和测试使用相同请求构造。
init(client: APIClient) { self.client = client }
/// 只读取准备快照,未知位置不会补零或替换成景区坐标。
func workbench(scenicID: Int, orderNumber: String, coordinate: DroneDockPreparationCoordinate?) async throws -> DroneDockPreparationResponse {
guard scenicID > 0, !orderNumber.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw APIError.networkFailed("缺少当前景区或订单信息,请返回重试")
}
var query = [URLQueryItem(name: "scenic_id", value: String(scenicID)),
URLQueryItem(name: "order_number", value: orderNumber)]
if let coordinate {
guard coordinate.isValid else { throw APIError.networkFailed("定位结果无效,请重新定位") }
query.append(URLQueryItem(name: "lat", value: String(coordinate.latitude)))
query.append(URLQueryItem(name: "lng", value: String(coordinate.longitude)))
}
return try await client.send(APIRequest(method: .get, path: "/api/app/airport/workbench", queryItems: query))
}
}
@@ -0,0 +1,247 @@
import Foundation
/// 本次定位得到的准备页坐标;未知位置使用 nil,不以零坐标替代。
struct DroneDockPreparationCoordinate: Equatable, Sendable {
/// 定位服务返回的纬度。
let latitude: Double
/// 定位服务返回的经度。
let longitude: Double
/// 保存一次实际定位结果,发送请求前再校验有效性。
init(latitude: Double, longitude: Double) {
self.latitude = latitude
self.longitude = longitude
}
/// 仅接受有限且处于地理范围内的坐标,拒绝未定位时常见的零点占位。
var isValid: Bool {
latitude.isFinite && longitude.isFinite
&& (-90...90).contains(latitude) && (-180...180).contains(longitude)
&& (latitude != 0 || longitude != 0)
}
}
/// 朱工 workbench 的真实准备快照,仅描述当前订单、点位航线与服务端许可。
struct DroneDockPreparationResponse: Decodable, Equatable, Sendable {
/// 响应所属景区。
let scenicID: Int
/// 响应所属订单号。
let orderNumber: String
/// 服务端最新订单进度;缺失时不沿用旧额度。
let orderProgress: DroneDockPreparationOrderProgress?
/// 真实机巢摘要,不将它等同于已派机结果。
let airports: [DroneDockHomeAirport]
/// 该订单的拍摄点位,保持服务端顺序。
let spots: [DroneDockPreparationSpot]
/// 后端召唤许可快照,缺失时保持未知。
let shootGate: DroneDockPreparationShootGate?
/// 后端规则提示原文。
let tips: String?
/// workbench 已验证的顶层字段。
private enum CodingKeys: String, CodingKey {
case scenicID = "scenic_id", orderNumber = "order_number", orderProgress = "order_progress"
case airports, spots, shootGate = "shoot_gate", tips
}
/// 严格读取订单范围和列表身份,避免坏响应伪装成成功空态或破坏 Diffable 更新。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
scenicID = try container.positivePreparationID(forKey: .scenicID)
orderNumber = try container.decode(String.self, forKey: .orderNumber)
guard !orderNumber.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw DecodingError.dataCorruptedError(forKey: .orderNumber, in: container, debugDescription: "订单号不能为空")
}
orderProgress = try container.decodeIfPresent(DroneDockPreparationOrderProgress.self, forKey: .orderProgress)
if let progressOrder = orderProgress?.orderNumber, progressOrder != orderNumber {
throw DecodingError.dataCorruptedError(forKey: .orderProgress, in: container, debugDescription: "订单进度与当前订单不一致")
}
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 重复")
}
spots = try container.decode([DroneDockPreparationSpot].self, forKey: .spots)
guard Set(spots.map(\.id)).count == spots.count else {
throw DecodingError.dataCorruptedError(forKey: .spots, in: container, debugDescription: "拍摄点 ID 重复")
}
shootGate = try container.decodeIfPresent(DroneDockPreparationShootGate.self, forKey: .shootGate)
tips = try container.decodeIfPresent(String.self, forKey: .tips)
}
}
/// 准备页服务端订单进度,不在客户端推算剩余次数或扣减额度。
struct DroneDockPreparationOrderProgress: Decodable, Equatable, Sendable {
/// 进度所属订单号,存在时需与顶层一致。
let orderNumber: String?
/// 服务端套餐说明。
let packageName: String?
/// 服务端拍摄总次数。
let shotTotal: Int?
/// 服务端已拍次数,保留合法零值。
let shotUsed: Int?
/// 服务端剩余次数,缺失时保持未知。
let shotRemain: Int?
/// 服务端订单状态文案。
let statusLabel: String?
/// 订单进度字段名。
private enum CodingKeys: String, CodingKey {
case orderNumber = "order_number", packageName = "package_name", shotTotal = "shot_total"
case shotUsed = "shot_used", shotRemain = "shot_remain", statusLabel = "status_label"
}
/// 兼容整数及整数字符串,同时区分未知次数与零次。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
orderNumber = try container.decodeIfPresent(String.self, forKey: .orderNumber)
packageName = try container.decodeIfPresent(String.self, forKey: .packageName)
shotTotal = try container.preparationCountIfPresent(forKey: .shotTotal)
shotUsed = try container.preparationCountIfPresent(forKey: .shotUsed)
shotRemain = try container.preparationCountIfPresent(forKey: .shotRemain)
statusLabel = try container.decodeIfPresent(String.self, forKey: .statusLabel)
}
}
/// 拍摄点的服务端距离、已拍状态与可选航线;距离是否可用由请求是否带定位决定。
struct DroneDockPreparationSpot: Decodable, Equatable, Sendable {
/// 拍摄点稳定 ID。
let id: Int
/// 拍摄点名称。
let name: String
/// 服务端格式化距离,不自行换算距离文案。
let distanceLabel: String?
/// 服务端距离米数。
let distanceM: Double?
/// 服务端范围判断,缺失时不默认在范围内。
let inRange: Bool?
/// 本点位已拍次数。
let shotCount: Int?
/// 本点位已拍状态文案。
let shotStatusLabel: String?
/// 点位所属航线,按后端顺序展示。
let airLines: [DroneDockPreparationAirLine]
/// 已验证的点位字段名。
private enum CodingKeys: String, CodingKey {
case id = "scenic_spot_id", name, distanceLabel = "distance_label", distanceM = "distance_m"
case inRange = "in_range", shotCount = "shot_count", shotStatusLabel = "shot_status_label", airLines = "air_lines"
}
/// 点位和航线身份必须有效且点位内唯一,缺失距离与次数保留未知。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.positivePreparationID(forKey: .id)
name = try container.decode(String.self, forKey: .name)
distanceLabel = try container.decodeIfPresent(String.self, forKey: .distanceLabel)
distanceM = try container.decodeIfPresent(DroneDockPreparationNumber.self, forKey: .distanceM)?.value
if let distanceM, distanceM < 0 {
throw DecodingError.dataCorruptedError(forKey: .distanceM, in: container, debugDescription: "距离不能为负数")
}
inRange = try container.decodeIfPresent(Bool.self, forKey: .inRange)
shotCount = try container.preparationCountIfPresent(forKey: .shotCount)
shotStatusLabel = try container.decodeIfPresent(String.self, forKey: .shotStatusLabel)
airLines = try container.decode([DroneDockPreparationAirLine].self, forKey: .airLines)
guard Set(airLines.map(\.id)).count == airLines.count else {
throw DecodingError.dataCorruptedError(forKey: .airLines, in: container, debugDescription: "点位内航线 ID 重复")
}
}
}
/// 准备页返回的航线信息;不从飞行类型或时长推断设备执行许可。
struct DroneDockPreparationAirLine: Decodable, Equatable, Sendable {
/// 航线稳定 ID。
let id: Int
/// 航线名称。
let name: String
/// 服务端预计飞行时长原值。
let estimatedFlyTime: Int?
/// 服务端航线视频时长原值。
let lineVideoDuration: Int?
/// 服务端飞行类型原值。
let flyType: Int?
/// 已验证的航线字段名。
private enum CodingKeys: String, CodingKey {
case id = "air_line_id", name, estimatedFlyTime = "estimated_fly_time"
case lineVideoDuration = "line_video_duration", flyType = "fly_type"
}
/// 航线 ID 必须有效,时长未知时不显示伪造零值。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.positivePreparationID(forKey: .id)
name = try container.decode(String.self, forKey: .name)
estimatedFlyTime = try container.preparationCountIfPresent(forKey: .estimatedFlyTime)
lineVideoDuration = try container.preparationCountIfPresent(forKey: .lineVideoDuration)
flyType = try container.decodeIfPresent(DroneDockPreparationInteger.self, forKey: .flyType)?.value
}
}
/// 后端召唤门禁,仅提供当前许可与原因,不等于客户端已实现或执行召唤。
struct DroneDockPreparationShootGate: Decodable, Equatable, Sendable {
/// 后端明确允许召唤时为 true,缺失仍为未知。
let canShoot: Bool?
/// 后端门禁代码,保留未知新值。
let code: String?
/// 后端原因说明。
let message: String?
/// 后端主操作标识。
let primaryAction: String?
/// 后端主操作文案。
let primaryActionLabel: String?
/// 门禁字段名。
private enum CodingKeys: String, CodingKey {
case canShoot = "can_shoot", code, message
case primaryAction = "primary_action", primaryActionLabel = "primary_action_label"
}
}
/// 本接口整数与整数字符串的兼容读取器,不接受布尔、分数或部分数字。
private struct DroneDockPreparationInteger: 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 DroneDockPreparationNumber: Decodable {
let value: Double
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let number: Double
if let decoded = try? container.decode(Double.self) { number = decoded }
else if let text = try? container.decode(String.self), let decoded = Double(text) { number = decoded }
else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "需要数字或数字字符串") }
guard number.isFinite else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "数字必须为有限值")
}
value = number
}
}
private extension KeyedDecodingContainer {
/// 读取会作为列表身份的正整数。
func positivePreparationID(forKey key: Key) throws -> Int {
let value = try decode(DroneDockPreparationInteger.self, forKey: key).value
guard value > 0 else {
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "ID 必须为正整数")
}
return value
}
/// 读取可缺失的非负次数或时长。
func preparationCountIfPresent(forKey key: Key) throws -> Int? {
guard let value = try decodeIfPresent(DroneDockPreparationInteger.self, forKey: key)?.value else { return nil }
guard value >= 0 else {
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "次数或时长不能为负数")
}
return value
}
}
@@ -0,0 +1,200 @@
import CoreLocation
import Foundation
/// 真实拍摄准备状态:读取订单、定位和点位航线,选择过程不创建或执行飞行任务。
final class DroneDockPreparationViewModel {
/// 页面进入时固定的账号、景区及门店范围。
let context: DroneDockHomeContext
/// 首页选中的真实订单,仅用于身份及进入时的摘要展示。
let order: DroneDockHomeOrder
/// 最新通过身份校验的准备信息。
private(set) var response: DroneDockPreparationResponse?
/// 是否正在定位或读取准备信息。
private(set) var isLoading = false
/// 加载失败或身份改变时的提示。
private(set) var errorMessage: String?
/// 没有取得有效位置时的说明,不使用后端无坐标时返回的距离。
private(set) var locationMessage: String?
/// 当前响应是否基于本次成功定位的坐标。
private(set) var hasLocation = false
/// 当前点位与航线的稳定身份。
private(set) var selectedSpotID: Int?
/// 航线只属于当前选中的点位。
private(set) var selectedRouteID: Int?
private let service: any DroneDockPreparationServing
private let locationProvider: any LocationProviding
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private var generation = 0
/// 注入真实只读接口、可替换定位服务和最新登录范围。
init(context: DroneDockHomeContext, order: DroneDockHomeOrder,
service: any DroneDockPreparationServing, locationProvider: any LocationProviding,
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.order = order
self.service = service
self.locationProvider = locationProvider
self.currentContext = currentContext
}
/// 当前订单的点位,保持服务端顺序。
var spots: [DroneDockPreparationSpot] { response?.spots ?? [] }
/// 当前选中点位,刷新后不再存在时会重新选择。
var selectedSpot: DroneDockPreparationSpot? { spots.first { $0.id == selectedSpotID } }
/// 只展示当前点位所属的航线。
var routes: [DroneDockPreparationAirLine] { selectedSpot?.airLines ?? [] }
/// 当前选中航线,不跨点位保留旧选择。
var selectedRoute: DroneDockPreparationAirLine? { routes.first { $0.id == selectedRouteID } }
/// 获取一次位置和准备快照;定位失败仍可浏览点位航线,但范围保持未知。
func refresh() async {
generation &+= 1
let requestGeneration = generation
isLoading = true
errorMessage = nil
locationMessage = nil
hasLocation = false
defer { if generation == requestGeneration { isLoading = false } }
guard await accepts(requestGeneration) else { return }
guard context.canLoad, let number = DroneDockHomeMetric.usableText(order.orderNumber) else {
clearResponse()
errorMessage = "缺少当前景区或订单信息,请返回工作台重新进入"
return
}
var coordinate: DroneDockPreparationCoordinate?
do {
let result = try await locationProvider.requestCoordinate(desiredAccuracy: kCLLocationAccuracyBest)
let value = DroneDockPreparationCoordinate(latitude: result.latitude, longitude: result.longitude)
guard value.isValid else { throw LocationProviderError.locationFailed }
coordinate = value
} catch {
guard await accepts(requestGeneration) else { return }
locationMessage = "\(error.localizedDescription),距离和拍摄范围待确认"
}
guard await accepts(requestGeneration) else { return }
do {
let result = try await service.workbench(scenicID: context.scenicID, orderNumber: number, coordinate: coordinate)
guard await accepts(requestGeneration) else { return }
guard result.scenicID == context.scenicID, result.orderNumber == number,
result.orderProgress?.orderNumber == nil || result.orderProgress?.orderNumber == number else {
clearResponse()
errorMessage = "接口返回的景区或订单与当前订单不一致,请刷新重试"
return
}
response = result
hasLocation = coordinate != nil
if !spots.contains(where: { $0.id == selectedSpotID }) { selectedSpotID = spots.first?.id }
if !routes.contains(where: { $0.id == selectedRouteID }) { selectedRouteID = routes.first?.id }
} catch {
guard await accepts(requestGeneration) else { return }
clearResponse()
errorMessage = error.localizedDescription
}
}
/// 选择现有点位,切点后航线重置为该点位的第一条,不复用另一点位的航线。
func selectSpot(id: Int) {
guard !isLoading, spots.contains(where: { $0.id == id }), selectedSpotID != id else { return }
selectedSpotID = id
selectedRouteID = routes.first?.id
}
/// 选择当前点位中的航线,忽略过期或不属于该点位的点击。
func selectRoute(id: Int) {
guard !isLoading, routes.contains(where: { $0.id == id }) else { return }
selectedRouteID = id
}
/// 页面离开后使定位和网络的迟到结果失效。
func invalidate() {
generation &+= 1
isLoading = false
errorMessage = nil
locationMessage = nil
clearResponse()
}
/// 根据实际机巢摘要展示连接状态,不将 can_shoot 当作设备连接证明。
var connectionTitle: String {
guard let airports = response?.airports, !airports.isEmpty else { return "机巢连接待确认" }
if airports.contains(where: { $0.onlineStatus == 1 }) { return "有机巢在线" }
if airports.allSatisfy({ $0.onlineStatus == 2 }) { return "机巢未连接" }
return "机巢连接待确认"
}
/// 只为明确在线的设备摘要显示绿色状态。
var connectionTone: DroneDockStatusTone {
response?.airports.contains(where: { $0.onlineStatus == 1 }) == true ? .green : .gray
}
/// 只有请求携带有效定位时才采用服务端范围结论。
var rangeTitle: String {
guard hasLocation else { return "位置待确认" }
guard let selectedSpot else { return "请选择拍摄点" }
switch selectedSpot.inRange {
case true: return "在拍摄范围内"
case false: return "不在拍摄范围内"
default: return "拍摄范围待确认"
}
}
/// 未知位置或范围不显示绿色。
var rangeTone: DroneDockStatusTone { hasLocation && selectedSpot?.inRange == true ? .green : .gray }
/// 当前航线选择的展示摘要。
var selectionSummary: String {
guard let selectedSpot else { return "请选择拍摄点" }
guard let selectedRoute else { return "\(selectedSpot.name) · 未选航线" }
return "\(selectedSpot.name) · \(selectedRoute.name)"
}
/// 多机状态一致时展示该状态,不假定某台机巢已被选派。
var deviceStatusText: String {
let labels = Set(response?.airports.map(\.statusTitle) ?? [])
return labels.count == 1 ? labels.first! : "状态待确认"
}
/// 准备阶段尚未派机,状态标签使用中性色。
var deviceTone: DroneDockStatusTone { .gray }
/// 保留后端明确的阻止原因,允许准备时展示下一步按钮标题。
var primaryButtonTitle: String {
if let gate = response?.shootGate, gate.canShoot == false {
return DroneDockHomeMetric.usableText(gate.primaryActionLabel) ?? "暂不可召唤"
}
return "确认并召唤"
}
/// 展示当前阻止原因;本阶段仅对接准备信息,不发送召唤指令。
var admissionMessage: String {
if isLoading { return "正在获取位置和拍摄准备信息" }
if let errorMessage { return errorMessage }
guard let response else { return "正在加载拍摄准备信息" }
if let gate = response.shootGate, gate.canShoot == false {
return DroneDockHomeMetric.usableText(gate.message)
?? DroneDockHomeMetric.usableText(gate.primaryActionLabel) ?? "当前暂不可召唤,请刷新状态"
}
if let locationMessage { return locationMessage }
if spots.isEmpty { return "当前暂无可用拍摄点" }
if routes.isEmpty { return "当前拍摄点暂无可用航线" }
if !hasLocation || selectedSpot?.inRange == nil { return "拍摄范围待确认,请重新定位" }
if selectedSpot?.inRange == false { return "请前往所选拍摄点的拍摄范围内" }
guard response.shootGate?.canShoot == true else { return "拍摄条件待确认,请刷新状态" }
return "召唤功能暂未开放"
}
private func clearResponse() {
response = nil
selectedSpotID = nil
selectedRouteID = nil
hasLocation = false
}
private func accepts(_ requestGeneration: Int) async -> Bool {
guard generation == requestGeneration, !Task.isCancelled else { return false }
let latest = await currentContext()
guard generation == requestGeneration, !Task.isCancelled else { return false }
guard context.hasSameIdentity(as: latest) else {
generation &+= 1
isLoading = false
clearResponse()
errorMessage = "账号或景区已变化,请返回工作台重新进入"
return false
}
return true
}
}
@@ -17,6 +17,8 @@ protocol CoreLocationManaging: AnyObject {
func requestWhenInUseAuthorization() func requestWhenInUseAuthorization()
/// 请求一次当前位置。 /// 请求一次当前位置。
func requestLocation() func requestLocation()
/// 结束已取消或已超时的定位,释放系统中的单次请求。
func stopUpdatingLocation()
} }
extension CLLocationManager: CoreLocationManaging {} extension CLLocationManager: CoreLocationManaging {}
@@ -31,7 +33,11 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
private var manager: any CoreLocationManaging = CLLocationManager() private var manager: any CoreLocationManaging = CLLocationManager()
private var geocoder: any LocationAddressGeocoding = LocationGeocoder.shared private var geocoder: any LocationAddressGeocoding = LocationGeocoder.shared
private var permissionContinuation: CheckedContinuation<Void, Error>? private var permissionContinuation: CheckedContinuation<Void, Error>?
private var permissionRequestID: UUID?
private var locationContinuation: CheckedContinuation<CLLocationCoordinate2D, Error>? private var locationContinuation: CheckedContinuation<CLLocationCoordinate2D, Error>?
private var locationRequestID: UUID?
private var locationTimeoutTask: Task<Void, Never>?
private var locationTimeoutNanoseconds: UInt64 = 10_000_000_000
nonisolated override init() { nonisolated override init() {
super.init() super.init()
@@ -41,11 +47,13 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
init( init(
appStore: AppStore, appStore: AppStore,
manager: any CoreLocationManaging, manager: any CoreLocationManaging,
geocoder: any LocationAddressGeocoding geocoder: any LocationAddressGeocoding,
locationTimeoutNanoseconds: UInt64 = 10_000_000_000
) { ) {
self.appStore = appStore self.appStore = appStore
self.manager = manager self.manager = manager
self.geocoder = geocoder self.geocoder = geocoder
self.locationTimeoutNanoseconds = max(1, locationTimeoutNanoseconds)
super.init() super.init()
manager.delegate = self manager.delegate = self
} }
@@ -66,22 +74,42 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
) )
} }
/// 请求一次当前位置坐标。 /// 请求一次当前位置坐标;系统未回调时超时结束,调用方取消时清理本次等待。
func requestCoordinate( func requestCoordinate(
desiredAccuracy: CLLocationAccuracy desiredAccuracy: CLLocationAccuracy
) async throws -> CLLocationCoordinate2D { ) async throws -> CLLocationCoordinate2D {
try Task.checkCancellation()
try requirePrivacyAgreement() try requirePrivacyAgreement()
try await ensureLocationPermission() try await ensureLocationPermission()
try Task.checkCancellation()
guard locationContinuation == nil else { guard locationContinuation == nil else {
throw LocationProviderError.locationFailed throw LocationProviderError.locationFailed
} }
manager.delegate = self manager.delegate = self
manager.desiredAccuracy = desiredAccuracy manager.desiredAccuracy = desiredAccuracy
return try await withCheckedThrowingContinuation { continuation in let requestID = UUID()
let timeout = locationTimeoutNanoseconds
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
guard !Task.isCancelled else {
continuation.resume(throwing: CancellationError())
return
}
locationRequestID = requestID
locationContinuation = continuation locationContinuation = continuation
locationTimeoutTask = Task { @MainActor [weak self] in
do { try await Task.sleep(nanoseconds: timeout) }
catch { return }
self?.finishLocation(requestID: requestID, result: .failure(LocationProviderError.locationFailed))
}
manager.requestLocation() manager.requestLocation()
} }
} onCancel: {
Task { @MainActor [weak self] in
self?.finishLocation(requestID: requestID, result: .failure(CancellationError()))
}
}
} }
/// 使用系统服务将坐标解析为地址。 /// 使用系统服务将坐标解析为地址。
@@ -92,6 +120,7 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
/// 请求系统定位权限,等待用户完成首次授权。 /// 请求系统定位权限,等待用户完成首次授权。
func ensureLocationPermission() async throws { func ensureLocationPermission() async throws {
try Task.checkCancellation()
manager.delegate = self manager.delegate = self
switch manager.authorizationStatus { switch manager.authorizationStatus {
case .authorizedAlways, .authorizedWhenInUse: case .authorizedAlways, .authorizedWhenInUse:
@@ -102,10 +131,22 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
guard permissionContinuation == nil else { guard permissionContinuation == nil else {
throw LocationProviderError.locationFailed throw LocationProviderError.locationFailed
} }
try await withCheckedThrowingContinuation { continuation in let requestID = UUID()
try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
guard !Task.isCancelled else {
continuation.resume(throwing: CancellationError())
return
}
permissionRequestID = requestID
permissionContinuation = continuation permissionContinuation = continuation
manager.requestWhenInUseAuthorization() manager.requestWhenInUseAuthorization()
} }
} onCancel: {
Task { @MainActor [weak self] in
self?.finishPermission(requestID: requestID, result: .failure(CancellationError()))
}
}
@unknown default: @unknown default:
throw LocationProviderError.permissionDenied throw LocationProviderError.permissionDenied
} }
@@ -116,21 +157,19 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
} }
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let continuation = locationContinuation else { return } guard let requestID = locationRequestID else { return }
locationContinuation = nil
guard let coordinate = locations.last?.coordinate, guard let coordinate = locations.last?.coordinate,
CLLocationCoordinate2DIsValid(coordinate), CLLocationCoordinate2DIsValid(coordinate),
coordinate.latitude != 0 || coordinate.longitude != 0 else { coordinate.latitude != 0 || coordinate.longitude != 0 else {
continuation.resume(throwing: LocationProviderError.locationFailed) finishLocation(requestID: requestID, result: .failure(LocationProviderError.locationFailed))
return return
} }
continuation.resume(returning: coordinate) finishLocation(requestID: requestID, result: .success(coordinate))
} }
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
guard let continuation = locationContinuation else { return } guard let requestID = locationRequestID else { return }
locationContinuation = nil finishLocation(requestID: requestID, result: .failure(LocationProviderError.locationFailed))
continuation.resume(throwing: LocationProviderError.locationFailed)
} }
private func requirePrivacyAgreement() throws { private func requirePrivacyAgreement() throws {
@@ -140,21 +179,37 @@ final class CoreLocationProvider: NSObject, LocationProviding, CLLocationManager
} }
private func resolvePermission(status: CLAuthorizationStatus) { private func resolvePermission(status: CLAuthorizationStatus) {
guard let continuation = permissionContinuation else { return } guard let requestID = permissionRequestID else { return }
switch status { switch status {
case .authorizedAlways, .authorizedWhenInUse: case .authorizedAlways, .authorizedWhenInUse:
permissionContinuation = nil finishPermission(requestID: requestID, result: .success(()))
continuation.resume()
case .denied, .restricted: case .denied, .restricted:
permissionContinuation = nil finishPermission(requestID: requestID, result: .failure(LocationProviderError.permissionDenied))
continuation.resume(throwing: LocationProviderError.permissionDenied)
case .notDetermined: case .notDetermined:
break break
@unknown default: @unknown default:
permissionContinuation = nil finishPermission(requestID: requestID, result: .failure(LocationProviderError.permissionDenied))
continuation.resume(throwing: LocationProviderError.permissionDenied)
} }
} }
/// 仅结束匹配的授权等待,旧任务的取消不能清除后续请求。
private func finishPermission(requestID: UUID, result: Result<Void, Error>) {
guard permissionRequestID == requestID, let continuation = permissionContinuation else { return }
permissionRequestID = nil
permissionContinuation = nil
continuation.resume(with: result)
}
/// 统一处理成功、失败、超时和取消,先清理状态再恢复等待中的调用方。
private func finishLocation(requestID: UUID, result: Result<CLLocationCoordinate2D, Error>) {
guard locationRequestID == requestID, let continuation = locationContinuation else { return }
locationRequestID = nil
locationContinuation = nil
locationTimeoutTask?.cancel()
locationTimeoutTask = nil
manager.stopUpdatingLocation()
continuation.resume(with: result)
}
} }
#if targetEnvironment(simulator) #if targetEnvironment(simulator)
@@ -6,6 +6,7 @@ final class DroneDockHomeViewController: BaseViewController {
/// 与演示数据源隔离的首页状态。 /// 与演示数据源隔离的首页状态。
let viewModel: DroneDockHomeViewModel let viewModel: DroneDockHomeViewModel
private let paymentControllerFactory: (() -> UIViewController)? private let paymentControllerFactory: (() -> UIViewController)?
private let preparationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)?
private var refreshTask: Task<Void, Never>? private var refreshTask: Task<Void, Never>?
private var isRefreshing = false private var isRefreshing = false
private var devicePage = 0 private var devicePage = 0
@@ -28,9 +29,11 @@ final class DroneDockHomeViewController: BaseViewController {
} }
/// 注入可测试的数据源,不加载演示数据。 /// 注入可测试的数据源,不加载演示数据。
init(viewModel: DroneDockHomeViewModel, paymentControllerFactory: (() -> UIViewController)? = nil) { init(viewModel: DroneDockHomeViewModel, paymentControllerFactory: (() -> UIViewController)? = nil,
preparationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
self.viewModel = viewModel self.viewModel = viewModel
self.paymentControllerFactory = paymentControllerFactory self.paymentControllerFactory = paymentControllerFactory
self.preparationControllerFactory = preparationControllerFactory
super.init(nibName: nil, bundle: nil) super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true hidesBottomBarWhenPushed = true
} }
@@ -131,7 +134,7 @@ final class DroneDockHomeViewController: BaseViewController {
if let order = self.viewModel.response?.orders.first(where: { $0.orderID == id }) { if let order = self.viewModel.response?.orders.first(where: { $0.orderID == id }) {
cell.apply(homeOrder: order) cell.apply(homeOrder: order)
cell.onShootingTap = { [weak self] in cell.onShootingTap = { [weak self] in
self?.showAlert(title: order.actionTitle ?? "拍摄订单", message: "拍摄流程暂未接入,请稍后再试") self?.openPreparation(orderID: id)
} }
cell.onMaterialsTap = { [weak self] in self?.showUnavailable("订单素材") } cell.onMaterialsTap = { [weak self] in self?.showUnavailable("订单素材") }
} }
@@ -246,6 +249,27 @@ final class DroneDockHomeViewController: BaseViewController {
showAlert(title: feature, message: "该功能暂未开放") showAlert(title: feature, message: "该功能暂未开放")
} }
private func openPreparation(orderID: Int) {
guard !isRefreshing, let order = viewModel.response?.orders.first(where: { $0.orderID == orderID }) else { return }
guard order.primaryAction == "start_shoot" else {
showUnavailable(order.actionTitle ?? "拍摄订单")
return
}
guard DroneDockHomeMetric.usableText(order.orderNumber) != nil else {
showAlert(title: "拍摄准备", message: "缺少订单号,请刷新工作台后重试")
return
}
let context = viewModel.context
let controller = preparationControllerFactory?(order, context) ?? DroneDockRemotePreparationViewController(
viewModel: DroneDockPreparationViewModel(
context: context, order: order,
service: DroneDockPreparationAPI(client: NetworkServices.shared.apiClient),
locationProvider: LocationProvider.shared,
currentContext: { Self.currentContext() }
))
navigationController?.pushViewController(controller, animated: true)
}
@objc private func receiptTapped() { @objc private func receiptTapped() {
let controller = paymentControllerFactory?() ?? DroneDockPaymentViewController() let controller = paymentControllerFactory?() ?? DroneDockPaymentViewController()
navigationController?.pushViewController(controller, animated: true) navigationController?.pushViewController(controller, animated: true)
@@ -0,0 +1,284 @@
import SnapKit
import UIKit
/// 读取 workbench 的真实拍摄准备页,点位和航线选择只影响页面展示。
@MainActor
final class DroneDockRemotePreparationViewController: BaseViewController {
/// 当前订单与准备页的真实读取状态。
let viewModel: DroneDockPreparationViewModel
/// 点位与航线沿用原准备页顺序,状态区单独承载加载、错误和定位说明。
private enum Section: Int, CaseIterable { case order, points, routes, status }
/// 点位与航线使用后端稳定 ID,刷新时保留有效选择。
private enum Item: Hashable { case order, point(Int), route(Int), emptyPoints, emptyRoutes, status }
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private let footerView = DronePreparationFooterView()
private let refreshControl = UIRefreshControl()
private var refreshTask: Task<Void, Never>?
private var isRefreshing = false
/// 注入只读状态源,不初始化本地演示订单或任务。
init(viewModel: DroneDockPreparationViewModel) {
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 = "拍摄准备"
navigationItem.backButtonDisplayMode = .minimal
}
override func setupUI() {
view.backgroundColor = .white
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = true
collectionView.showsVerticalScrollIndicator = false
collectionView.delegate = self
collectionView.accessibilityIdentifier = "drone.preparation.remote.list"
collectionView.register(DronePreparationOrderCell.self, forCellWithReuseIdentifier: "order")
collectionView.register(DronePreparationPointCell.self, forCellWithReuseIdentifier: "point")
collectionView.register(DronePreparationRouteCell.self, forCellWithReuseIdentifier: "route")
collectionView.register(DronePreparationEmptyCell.self, forCellWithReuseIdentifier: "message")
collectionView.register(DronePreparationHeadingView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: "heading")
refreshControl.tintColor = DroneDockStyle.primary
collectionView.refreshControl = refreshControl
view.addSubview(collectionView)
view.addSubview(footerView)
configureDataSource()
applySnapshot(animated: false)
}
override func setupConstraints() {
collectionView.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.equalToSuperview()
make.bottom.equalTo(footerView.snp.top)
}
footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() }
}
override func bindActions() {
refreshControl.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged)
footerView.onRefreshTap = { [weak self] in self?.refreshPreparation() }
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshPreparation()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
refreshTask?.cancel()
isRefreshing = false
refreshControl.endRefreshing()
viewModel.invalidate()
}
private func refreshPreparation() {
guard !isRefreshing else { return }
isRefreshing = true
refreshTask = Task { @MainActor [weak self] in
guard let self else { return }
let isInitialLoad = self.viewModel.response == nil
self.applySnapshot(animated: false)
await self.viewModel.refresh()
guard !Task.isCancelled else { return }
self.isRefreshing = false
self.refreshControl.endRefreshing()
self.applySnapshot(animated: true) { [weak self] in
guard let self else { return }
if isInitialLoad {
self.collectionView.layoutIfNeeded()
self.collectionView.setContentOffset(CGPoint(x: 0, y: -self.collectionView.adjustedContentInset.top), animated: false)
}
#if DEBUG
Task { @MainActor [weak self] in await self?.capturePreparationIfRequested() }
#endif
}
}
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, path, item in
guard let self else { return nil }
switch item {
case .order:
let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: path) as! DronePreparationOrderCell
cell.apply(homeOrder: self.viewModel.order, progress: self.viewModel.response?.orderProgress,
usesHomeSnapshot: self.viewModel.response == nil && self.viewModel.errorMessage == nil)
return cell
case .point(let id):
let cell = list.dequeueReusableCell(withReuseIdentifier: "point", for: path) as! DronePreparationPointCell
if let spot = self.viewModel.spots.first(where: { $0.id == id }) {
cell.apply(spot: spot, selected: self.viewModel.selectedSpotID == id, hasLocation: self.viewModel.hasLocation)
}
return cell
case .route(let id):
let cell = list.dequeueReusableCell(withReuseIdentifier: "route", for: path) as! DronePreparationRouteCell
if let route = self.viewModel.routes.first(where: { $0.id == id }) {
cell.apply(route: route, selected: self.viewModel.selectedRouteID == id)
}
return cell
case .emptyPoints, .emptyRoutes, .status:
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DronePreparationEmptyCell
if item == .status {
self.applyStatus(to: cell)
} else if item == .emptyPoints {
cell.apply(title: "暂无可用拍摄点", detail: "当前订单暂无拍摄点配置,请刷新重试")
} else if self.viewModel.selectedSpot == nil {
cell.apply(title: "请选择拍摄点", detail: "选择拍摄点后查看对应航线")
} else {
cell.apply(title: "暂无可用航线", detail: "请选择其他拍摄点,或稍后刷新重试")
}
return cell
}
}
dataSource.supplementaryViewProvider = { [weak self] list, kind, path in
guard let self else { return nil }
let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "heading", for: path) as! DronePreparationHeadingView
self.applyHeading(header, section: Section(rawValue: path.section))
return header
}
}
private func applyStatus(to cell: DronePreparationEmptyCell) {
if isRefreshing, viewModel.response == nil {
cell.apply(title: "正在加载", detail: "正在获取拍摄点、航线和设备状态")
} else if let error = viewModel.errorMessage {
cell.apply(title: "准备信息加载失败", detail: error + ",请下拉或点击刷新状态重试")
} else if let message = viewModel.locationMessage, viewModel.response != nil {
cell.apply(title: "位置待确认", detail: message)
} else {
cell.apply(title: "正在加载", detail: "正在获取拍摄准备信息")
}
}
private func applySnapshot(animated: Bool, completion: (() -> Void)? = nil) {
guard dataSource != nil else { return }
let previous = dataSource.snapshot()
let existing = Set(previous.itemIdentifiers)
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections(Section.allCases)
snapshot.appendItems([.order], toSection: .order)
if viewModel.response != nil, viewModel.errorMessage == nil {
snapshot.appendItems(viewModel.spots.isEmpty ? [.emptyPoints] : viewModel.spots.map { .point($0.id) }, toSection: .points)
if !viewModel.spots.isEmpty {
snapshot.appendItems(viewModel.routes.isEmpty ? [.emptyRoutes] : viewModel.routes.map { .route($0.id) }, toSection: .routes)
}
if viewModel.locationMessage != nil { snapshot.appendItems([.status], toSection: .status) }
} else {
snapshot.appendItems([.status], toSection: .status)
}
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing)
let previousPointCount = previous.sectionIdentifiers.contains(.points) ? previous.numberOfItems(inSection: .points) : 0
let previousRouteCount = previous.sectionIdentifiers.contains(.routes) ? previous.numberOfItems(inSection: .routes) : 0
let layoutChanged = previousPointCount != snapshot.numberOfItems(inSection: .points)
|| previous.itemIdentifiers.contains(.emptyPoints) != snapshot.itemIdentifiers.contains(.emptyPoints)
|| previous.itemIdentifiers.contains(.emptyRoutes) != snapshot.itemIdentifiers.contains(.emptyRoutes)
|| previousRouteCount != snapshot.numberOfItems(inSection: .routes)
if layoutChanged { collectionView.collectionViewLayout.invalidateLayout() }
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
guard let self else { return }
let kind = UICollectionView.elementKindSectionHeader
for path in self.collectionView.indexPathsForVisibleSupplementaryElements(ofKind: kind) {
if let header = self.collectionView.supplementaryView(forElementKind: kind, at: path) as? DronePreparationHeadingView {
self.applyHeading(header, section: Section(rawValue: path.section))
}
}
completion?()
}
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] index, _ in
guard let self, let section = Section(rawValue: index) else { return nil }
let height: NSCollectionLayoutDimension
let width: NSCollectionLayoutDimension
switch section {
case .order: height = .estimated(100); width = .fractionalWidth(1)
case .points:
height = .absolute(self.viewModel.spots.isEmpty ? 150 : 80)
width = self.viewModel.spots.isEmpty ? .fractionalWidth(1) : .absolute(160)
case .routes:
height = .absolute(self.viewModel.routes.isEmpty ? 160 : 64)
width = .fractionalWidth(1)
case .status: height = .absolute(160); width = .fractionalWidth(1)
}
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height))
let group = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item])
let layout = NSCollectionLayoutSection(group: group)
layout.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: section == .status ? 12 : 0, trailing: 16)
if section == .points, !self.viewModel.spots.isEmpty {
layout.orthogonalScrollingBehavior = .continuous
layout.interGroupSpacing = 8
}
let showsHeading = self.viewModel.response != nil && self.viewModel.errorMessage == nil
&& (section == .points || (section == .routes && !self.viewModel.spots.isEmpty))
if showsHeading {
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(section == .points ? 46 : 64)),
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)]
}
return layout
}
}
private func applyHeading(_ header: DronePreparationHeadingView, section: Section?) {
switch section {
case .points: header.apply(title: "拍摄点", detail: nil)
case .routes:
header.apply(title: viewModel.selectedSpot.map { "\($0.name)的航线" } ?? "拍摄航线", detail: "共 \(viewModel.routes.count) 条")
default: header.apply(title: "", detail: nil)
}
}
@objc private func refreshTriggered() { refreshPreparation() }
#if DEBUG
/// 显式联调时只保存本应用窗口,不截取其他应用内容。
private func capturePreparationIfRequested() async {
guard ProcessInfo.processInfo.arguments.contains("--dock-preparation-capture") else { return }
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("DronePreparationDiagnostics", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
try image.pngData()?.write(to: directory.appendingPathComponent("preparation-real.png"), options: .atomic)
print("[DronePreparation] App window screenshot saved")
} catch { print("[DronePreparation] Screenshot failed: \(error.localizedDescription)") }
}
#endif
}
extension DroneDockRemotePreparationViewController: UICollectionViewDelegate {
/// 点位和航线只在当前成功快照中选择,刷新期间不切换旧配置。
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
!isRefreshing && viewModel.response != nil && viewModel.errorMessage == nil
}
/// 更新本地点位、航线及底部摘要,不创建拍摄任务。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard !isRefreshing, let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .point(let id): viewModel.selectSpot(id: id)
case .route(let id): viewModel.selectRoute(id: id)
default: return
}
applySnapshot(animated: true)
}
}
@@ -24,8 +24,10 @@ final class DronePreparationOrderCell: UICollectionViewCell {
packageLabel.snp.makeConstraints { make in packageLabel.snp.makeConstraints { make in
make.top.equalTo(customerLabel.snp.bottom).offset(8) make.top.equalTo(customerLabel.snp.bottom).offset(8)
make.leading.equalTo(customerLabel) make.leading.equalTo(customerLabel)
make.trailing.lessThanOrEqualTo(separator.snp.leading).offset(-12)
make.bottom.equalToSuperview().inset(14) make.bottom.equalToSuperview().inset(14)
} }
packageLabel.numberOfLines = 2
separator.snp.makeConstraints { make in separator.snp.makeConstraints { make in
make.trailing.equalToSuperview().inset(94) make.trailing.equalToSuperview().inset(94)
make.centerY.equalToSuperview() make.centerY.equalToSuperview()
@@ -65,6 +67,20 @@ final class DronePreparationOrderCell: UICollectionViewCell {
accessibilityLabel = "\(order.customerName),含\(order.totalShootingCount)次拍摄,已拍摄\(order.successfulShootingCount)次,剩余\(order.remainingShootingCount)次" accessibilityLabel = "\(order.customerName),含\(order.totalShootingCount)次拍摄,已拍摄\(order.successfulShootingCount)次,剩余\(order.remainingShootingCount)次"
} }
/// 使用真实首页游客信息与准备页最新次数;准备响应中的未知次数不回填成旧值。
func apply(homeOrder: DroneDockHomeOrder, progress: DroneDockPreparationOrderProgress?, usesHomeSnapshot: Bool = false) {
let total = usesHomeSnapshot ? homeOrder.shotTotal : progress?.shotTotal
let used = usesHomeSnapshot ? homeOrder.shotUsed : progress?.shotUsed
let remaining = usesHomeSnapshot ? homeOrder.shotRemain : progress?.shotRemain
let package = progress == nil ? homeOrder.packageTitle : progress?.packageName
customerLabel.text = homeOrder.touristTitle
packageLabel.text = package?.isEmpty == false ? package : "含 \(total.map(String.init) ?? "—") 次拍摄"
completedLabel.text = "已拍摄 \(used.map(String.init) ?? "—") 次"
remainingLabel.attributedText = remainingText(remaining.map(String.init) ?? "—")
accessibilityLabel = "\(homeOrder.touristTitle),\(packageLabel.text ?? ""),已拍摄\(used.map(String.init) ?? "—")次,剩余\(remaining.map(String.init) ?? "—")次"
accessibilityIdentifier = "drone.preparation.order"
}
private func remainingText(_ value: String) -> NSAttributedString { private func remainingText(_ value: String) -> NSAttributedString {
let text = NSMutableAttributedString(string: "剩余 ", attributes: [.font: UIFont.systemFont(ofSize: 12), .foregroundColor: DroneDockStyle.secondary]) let text = NSMutableAttributedString(string: "剩余 ", attributes: [.font: UIFont.systemFont(ofSize: 12), .foregroundColor: DroneDockStyle.secondary])
text.append(NSAttributedString(string: value, attributes: [.font: UIFont.systemFont(ofSize: 26, weight: .medium), .foregroundColor: DroneDockStyle.primary])) text.append(NSAttributedString(string: value, attributes: [.font: UIFont.systemFont(ofSize: 26, weight: .medium), .foregroundColor: DroneDockStyle.primary]))
@@ -73,7 +89,7 @@ final class DronePreparationOrderCell: UICollectionViewCell {
} }
} }
/// 横向点位小卡,使用原型同款本地缩略图展示演示点位。 /// 横向点位小卡,展示点位、距离与拍摄记录,真实数据缺图时使用中性占位。
@MainActor @MainActor
final class DronePreparationPointCell: UICollectionViewCell { final class DronePreparationPointCell: UICollectionViewCell {
private let nameLabel = DroneDockStyle.label(size: 13, weight: .semibold) private let nameLabel = DroneDockStyle.label(size: 13, weight: .semibold)
@@ -127,6 +143,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
/// 仅映射模型提供的范围和次数,已拍摄的点位仍保持可选择。 /// 仅映射模型提供的范围和次数,已拍摄的点位仍保持可选择。
func apply(point: DroneShootingPoint, selected: Bool) { func apply(point: DroneShootingPoint, selected: Bool) {
nameLabel.text = point.name nameLabel.text = point.name
thumbnail.contentMode = .scaleAspectFill
thumbnail.image = UIImage(named: point.id == "point-jinque" ? "drone_demo_pagoda" : "drone_demo_mountain") thumbnail.image = UIImage(named: point.id == "point-jinque" ? "drone_demo_pagoda" : "drone_demo_mountain")
rangeLabel.text = point.range.title rangeLabel.text = point.range.title
switch point.range { switch point.range {
@@ -142,6 +159,34 @@ final class DronePreparationPointCell: UICollectionViewCell {
accessibilityTraits = selected ? [.button, .selected] : .button accessibilityTraits = selected ? [.button, .selected] : .button
accessibilityIdentifier = "drone.preparation.point.\(point.id)" accessibilityIdentifier = "drone.preparation.point.\(point.id)"
} }
/// 距离只在请求携带有效定位时展示,服务端未提供点位图片时不使用演示山景。
func apply(spot: DroneDockPreparationSpot, selected: Bool, hasLocation: Bool) {
nameLabel.text = spot.name
thumbnail.image = UIImage(systemName: "mappin.and.ellipse")
thumbnail.contentMode = .center
thumbnail.tintColor = DroneDockStyle.secondary
if hasLocation {
rangeLabel.text = spot.distanceLabel?.isEmpty == false ? spot.distanceLabel : "距离待确认"
rangeLabel.textColor = spot.inRange == true ? DroneDockStyle.success : DroneDockStyle.secondary
} else {
rangeLabel.text = "待定位"
rangeLabel.textColor = DroneDockStyle.warning
}
locationIcon.tintColor = rangeLabel.textColor
if let status = spot.shotStatusLabel, !status.isEmpty {
countLabel.text = status
} else if let count = spot.shotCount {
countLabel.text = count == 0 ? "未拍摄" : "已拍摄 \(count) 次"
} else {
countLabel.text = "已拍摄 — 次"
}
contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.07) : .white
contentView.layer.borderColor = (selected ? DroneDockStyle.primary : DroneDockStyle.border).cgColor
accessibilityLabel = "\(spot.name),\(rangeLabel.text ?? ""),\(countLabel.text ?? "")"
accessibilityTraits = selected ? [.button, .selected] : .button
accessibilityIdentifier = "drone.preparation.point.\(spot.id)"
}
} }
/// 纵向单选航线行,点击整行后由 ViewModel 保留有效选择。 /// 纵向单选航线行,点击整行后由 ViewModel 保留有效选择。
@@ -197,6 +242,20 @@ final class DronePreparationRouteCell: UICollectionViewCell {
accessibilityTraits = selected ? [.button, .selected] : .button accessibilityTraits = selected ? [.button, .selected] : .button
accessibilityIdentifier = "drone.preparation.route.\(route.id)" accessibilityIdentifier = "drone.preparation.route.\(route.id)"
} }
/// 展示当前真实点位的航线选择,不从行点击发起任何飞行操作。
func apply(route: DroneDockPreparationAirLine, selected: Bool) {
nameLabel.text = route.name
nameLabel.textColor = selected ? DroneDockStyle.primary : DroneDockStyle.text
routeIcon.apply(selected: selected)
checkmark.image = UIImage(systemName: selected ? "checkmark.circle.fill" : "circle")
checkmark.tintColor = selected ? DroneDockStyle.primary : UIColor(hex: 0xA4ABB8)
contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.08) : .white
separator.isHidden = selected
accessibilityLabel = route.name
accessibilityTraits = selected ? [.button, .selected] : .button
accessibilityIdentifier = "drone.preparation.route.\(route.id)"
}
} }
/// 源码绘制的小航线图标,不依赖远程图片和拍摄素材。 /// 源码绘制的小航线图标,不依赖远程图片和拍摄素材。
@@ -309,6 +368,12 @@ final class DronePreparationEmptyCell: UICollectionViewCell {
titleLabel.text = isPointEmpty ? "暂无可用拍摄点" : "暂无可用航线" titleLabel.text = isPointEmpty ? "暂无可用拍摄点" : "暂无可用航线"
detailLabel.text = isPointEmpty ? "当前景区尚未配置拍摄点" : "请选择其他拍摄点,或稍后重试" detailLabel.text = isPointEmpty ? "当前景区尚未配置拍摄点" : "请选择其他拍摄点,或稍后重试"
} }
/// 展示真实页面的加载、失败或未配置状态,不将请求失败描述为空数据。
func apply(title: String, detail: String) {
titleLabel.text = title
detailLabel.text = detail
}
} }
/// 固定底部许可栏,独立刷新连接、范围、设备与主按钮。 /// 固定底部许可栏,独立刷新连接、范围、设备与主按钮。
@@ -422,6 +487,23 @@ final class DronePreparationFooterView: UIView {
refreshButton.isHidden = !viewModel.shouldShowSummonRefresh refreshButton.isHidden = !viewModel.shouldShowSummonRefresh
} }
/// 展示真实准备状态;本阶段保留召唤按钮文案,但尚不提供飞行执行入口。
func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: Bool = false) {
connectionLabel.apply(title: viewModel.connectionTitle, tone: viewModel.connectionTone)
rangeLabel.apply(title: viewModel.rangeTitle, tone: viewModel.rangeTone)
selectionLabel.text = viewModel.selectionSummary
selectionLabel.numberOfLines = 2
deviceLabel.apply(title: viewModel.deviceStatusText, tone: viewModel.deviceTone)
primaryButton.setTitle(viewModel.primaryButtonTitle, for: .normal)
primaryButton.isEnabled = false
primaryButton.backgroundColor = UIColor(hex: 0xE1E7F0)
primaryButton.setTitleColor(UIColor(hex: 0x8792A5), for: .disabled)
messageLabel.text = viewModel.admissionMessage
messageLabel.textColor = DroneDockStyle.secondary
refreshButton.isHidden = false
refreshButton.isEnabled = !viewModel.isLoading && !isRefreshing
}
@objc private func primaryTapped() { onPrimaryTap?() } @objc private func primaryTapped() { onPrimaryTap?() }
@objc private func refreshTapped() { onRefreshTap?() } @objc private func refreshTapped() { onRefreshTap?() }
} }
+100 -4
View File
@@ -84,6 +84,81 @@ final class CoreLocationProviderTests: XCTestCase {
XCTAssertEqual(snapshot.address, "") XCTAssertEqual(snapshot.address, "")
} }
/// 系统始终不回调时结束本次定位,清理后可再次正常获取坐标。
func testLocationTimeoutReleasesRequestAndAllowsRetry() async throws {
let context = makeContext(locationResult: .noCallback, locationTimeoutNanoseconds: 30_000_000)
await assertLocationError(.locationFailed) {
_ = try await context.provider.requestCoordinate()
}
XCTAssertEqual(context.manager.requestLocationCallCount, 1)
XCTAssertEqual(context.manager.stopUpdatingLocationCallCount, 1)
context.manager.locationResult = .success(CLLocation(latitude: 31.2, longitude: 121.4))
let coordinate = try await context.provider.requestCoordinate()
XCTAssertEqual(coordinate.latitude, 31.2, accuracy: 0.000_001)
XCTAssertEqual(context.manager.requestLocationCallCount, 2)
XCTAssertEqual(context.manager.stopUpdatingLocationCallCount, 2)
}
/// 离页取消会立即恢复等待并停止定位,不占用下一次请求。
func testCancellationStopsPendingLocationAndAllowsRetry() async throws {
let context = makeContext(locationResult: .noCallback)
let task = Task { try await context.provider.requestCoordinate() }
try await waitUntil { context.manager.requestLocationCallCount == 1 }
task.cancel()
do {
_ = try await task.value
XCTFail("取消定位后不应成功返回坐标")
} catch {
XCTAssertTrue(error is CancellationError)
}
XCTAssertEqual(context.manager.stopUpdatingLocationCallCount, 1)
context.manager.locationResult = .success(CLLocation(latitude: 30.3, longitude: 120.2))
let coordinate = try await context.provider.requestCoordinate()
XCTAssertEqual(coordinate.longitude, 120.2, accuracy: 0.000_001)
XCTAssertEqual(context.manager.requestLocationCallCount, 2)
}
/// 授权弹窗尚未响应时取消,不残留等待者或在迟到授权后发起定位。
func testCancellationWhileWaitingForPermissionAllowsNewRequest() async throws {
let context = makeContext(authorizationStatus: .notDetermined, requestedAuthorizationStatus: .notDetermined)
let task = Task { try await context.provider.requestCoordinate() }
try await waitUntil { context.manager.requestAuthorizationCallCount == 1 }
task.cancel()
do {
_ = try await task.value
XCTFail("取消授权等待后不应继续定位")
} catch {
XCTAssertTrue(error is CancellationError)
}
XCTAssertEqual(context.manager.requestLocationCallCount, 0)
context.manager.requestedAuthorizationStatus = .authorizedWhenInUse
_ = try await context.provider.requestCoordinate()
XCTAssertEqual(context.manager.requestAuthorizationCallCount, 2)
XCTAssertEqual(context.manager.requestLocationCallCount, 1)
}
/// 已取消任务不能在注册取消处理之前启动授权或定位。
func testAlreadyCancelledTaskDoesNotStartLocation() async {
let context = makeContext(authorizationStatus: .notDetermined)
let task = Task { try await context.provider.requestCoordinate() }
task.cancel()
do {
_ = try await task.value
XCTFail("已取消任务不应返回坐标")
} catch {
XCTAssertTrue(error is CancellationError)
}
XCTAssertEqual(context.manager.requestAuthorizationCallCount, 0)
XCTAssertEqual(context.manager.requestLocationCallCount, 0)
}
private func makeContext( private func makeContext(
privacyAccepted: Bool = true, privacyAccepted: Bool = true,
authorizationStatus: CLAuthorizationStatus = .authorizedWhenInUse, authorizationStatus: CLAuthorizationStatus = .authorizedWhenInUse,
@@ -91,7 +166,8 @@ final class CoreLocationProviderTests: XCTestCase {
locationResult: FakeCoreLocationManager.LocationResult = .success( locationResult: FakeCoreLocationManager.LocationResult = .success(
CLLocation(latitude: 39.9042, longitude: 116.4074) CLLocation(latitude: 39.9042, longitude: 116.4074)
), ),
geocodedAddress: String = "北京市东城区" geocodedAddress: String = "北京市东城区",
locationTimeoutNanoseconds: UInt64 = 10_000_000_000
) -> TestContext { ) -> TestContext {
let suiteName = "CoreLocationProviderTests.\(UUID().uuidString)" let suiteName = "CoreLocationProviderTests.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suiteName)! let defaults = UserDefaults(suiteName: suiteName)!
@@ -108,7 +184,8 @@ final class CoreLocationProviderTests: XCTestCase {
let provider = CoreLocationProvider( let provider = CoreLocationProvider(
appStore: appStore, appStore: appStore,
manager: manager, manager: manager,
geocoder: geocoder geocoder: geocoder,
locationTimeoutNanoseconds: locationTimeoutNanoseconds
) )
return TestContext(provider: provider, manager: manager, geocoder: geocoder) return TestContext(provider: provider, manager: manager, geocoder: geocoder)
} }
@@ -124,6 +201,16 @@ final class CoreLocationProviderTests: XCTestCase {
XCTAssertEqual(error as? LocationProviderError, expected) XCTAssertEqual(error as? LocationProviderError, expected)
} }
} }
/// 等待替身请求开始再取消,避免用固定睡眠决定请求是否已挂起。
private func waitUntil(_ condition: () -> Bool) async throws {
for _ in 0..<100 {
if condition() { return }
try await Task.sleep(nanoseconds: 1_000_000)
}
XCTFail("定位替身未收到预期请求")
throw NSError(domain: "CoreLocationProviderTests", code: 1)
}
} }
/// Core Location fallback 测试依赖集合。 /// Core Location fallback 测试依赖集合。
@@ -142,6 +229,7 @@ private final class FakeCoreLocationManager: CoreLocationManaging {
enum LocationResult { enum LocationResult {
case success(CLLocation) case success(CLLocation)
case failure case failure
case noCallback
} }
var authorizationStatus: CLAuthorizationStatus var authorizationStatus: CLAuthorizationStatus
@@ -149,9 +237,10 @@ private final class FakeCoreLocationManager: CoreLocationManaging {
weak var delegate: CLLocationManagerDelegate? weak var delegate: CLLocationManagerDelegate?
private(set) var requestAuthorizationCallCount = 0 private(set) var requestAuthorizationCallCount = 0
private(set) var requestLocationCallCount = 0 private(set) var requestLocationCallCount = 0
private(set) var stopUpdatingLocationCallCount = 0
private let requestedAuthorizationStatus: CLAuthorizationStatus var requestedAuthorizationStatus: CLAuthorizationStatus
private let locationResult: LocationResult var locationResult: LocationResult
init( init(
authorizationStatus: CLAuthorizationStatus, authorizationStatus: CLAuthorizationStatus,
@@ -180,8 +269,15 @@ private final class FakeCoreLocationManager: CoreLocationManaging {
callbackManager, callbackManager,
didFailWithError: CLError(.locationUnknown) didFailWithError: CLError(.locationUnknown)
) )
case .noCallback:
break
} }
} }
/// 记录被测服务是否释放超时或取消的单次请求。
func stopUpdatingLocation() {
stopUpdatingLocationCallCount += 1
}
} }
/// 可控的逆地理编码替身。 /// 可控的逆地理编码替身。
@@ -0,0 +1,229 @@
import Foundation
import XCTest
@testable import suixinkan
/// 使用匿名 workbench 样例验证真实字段与只读请求,全部网络由替身提供。
@MainActor
final class DroneDockPreparationAPITests: XCTestCase {
/// 有定位时发送当前订单及坐标,使用既有 token 注入且只发送一次 GET。
func testWorkbenchReadsObservedShapeWithOrderAndCoordinate() async throws {
let session = MockURLSession(responses: [envelope(Self.payload)])
let client = APIClient(environment: .testing, session: session)
client.bindAuthTokenProvider { "preparation-test-token" }
let api = DroneDockPreparationAPI(client: client)
let response = try await api.workbench(scenicID: 128, orderNumber: "TEST-ORDER-001",
coordinate: DroneDockPreparationCoordinate(latitude: 31.25, longitude: 121.5))
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/workbench")
XCTAssertEqual(try query(request), ["scenic_id": "128", "order_number": "TEST-ORDER-001", "lat": "31.25", "lng": "121.5"])
XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "preparation-test-token")
XCTAssertNil(request.httpBody)
XCTAssertEqual(response.scenicID, 128)
XCTAssertEqual(response.orderNumber, "TEST-ORDER-001")
XCTAssertEqual(response.orderProgress?.packageName, "测试套餐 · 含 1 次拍摄")
XCTAssertEqual(response.orderProgress?.shotUsed, 0)
XCTAssertEqual(response.orderProgress?.shotRemain, 1)
XCTAssertEqual(response.airports.first?.statusTitle, "离线")
XCTAssertEqual(response.spots.map(\.id), [201, 202])
let spot = try XCTUnwrap(response.spots.first)
XCTAssertEqual(spot.name, "测试点位一")
XCTAssertEqual(spot.distanceM, 123.5)
XCTAssertEqual(spot.distanceLabel, "123.5 m")
XCTAssertEqual(spot.inRange, false)
XCTAssertEqual(spot.shotCount, 0)
XCTAssertEqual(spot.shotStatusLabel, "未拍摄")
XCTAssertEqual(spot.airLines.first?.id, 301)
XCTAssertEqual(spot.airLines.first?.name, "测试航线一")
XCTAssertEqual(spot.airLines.first?.estimatedFlyTime, 279)
XCTAssertEqual(spot.airLines.first?.lineVideoDuration, 14)
XCTAssertEqual(spot.airLines.first?.flyType, 1)
XCTAssertEqual(response.shootGate?.canShoot, false)
XCTAssertEqual(response.shootGate?.code, "dock_offline")
XCTAssertEqual(response.shootGate?.message, "机巢未连接")
XCTAssertEqual(response.shootGate?.primaryAction, "blocked")
XCTAssertEqual(response.shootGate?.primaryActionLabel, "机巢未连接")
XCTAssertEqual(response.tips, "测试拍摄规则")
}
/// 未定位也可读取准备信息,但不会上传零点、景区中心或其他伪造位置。
func testUnknownCoordinateOmitsBothLocationParameters() async throws {
let session = MockURLSession(responses: [envelope(Self.payload)])
_ = try await DroneDockPreparationAPI(client: APIClient(environment: .testing, session: session))
.workbench(scenicID: 128, orderNumber: "TEST-ORDER-001", coordinate: nil)
XCTAssertEqual(try query(XCTUnwrap(session.requests.first)), ["scenic_id": "128", "order_number": "TEST-ORDER-001"])
XCTAssertEqual(session.requests.count, 1)
}
/// 请求范围或定位无效时在网络前失败,不能查询其他景区或使用占位坐标。
func testInvalidScopeAndCoordinatesDoNotSendNetworkRequests() async {
let session = MockURLSession(responses: [])
let api = DroneDockPreparationAPI(client: APIClient(environment: .testing, session: session))
for (scenicID, orderNumber) in [(0, "TEST-ORDER-001"), (-1, "TEST-ORDER-001"), (128, " \n")] {
do {
_ = try await api.workbench(scenicID: scenicID, orderNumber: orderNumber, coordinate: nil)
XCTFail("无效范围必须拒绝请求")
} catch {}
}
for coordinate in [
DroneDockPreparationCoordinate(latitude: 0, longitude: 0),
DroneDockPreparationCoordinate(latitude: 91, longitude: 100),
DroneDockPreparationCoordinate(latitude: 30, longitude: -181),
DroneDockPreparationCoordinate(latitude: .nan, longitude: 100),
DroneDockPreparationCoordinate(latitude: 30, longitude: .infinity)
] {
XCTAssertFalse(coordinate.isValid)
do {
_ = try await api.workbench(scenicID: 128, orderNumber: "TEST-ORDER-001", coordinate: coordinate)
XCTFail("无效定位必须拒绝请求")
} catch {}
}
XCTAssertTrue(DroneDockPreparationCoordinate(latitude: 0, longitude: 100).isValid)
XCTAssertTrue(session.requests.isEmpty)
}
/// 保留后端业务错误,不将拒绝访问当成没有点位。
func testBackendFailureKeepsBusinessMessage() async throws {
let session = MockURLSession(responses: [try TestJSON.errorEnvelope(code: 160001, msg: "当前订单不可访问")])
do {
_ = try await DroneDockPreparationAPI(client: APIClient(environment: .testing, session: session))
.workbench(scenicID: 128, orderNumber: "TEST-ORDER-001", coordinate: nil)
XCTFail("业务错误不能作为准备快照返回")
} catch let APIError.serverCode(code, message) {
XCTAssertEqual(code, 160001)
XCTAssertEqual(message, "当前订单不可访问")
}
}
/// 整数字符串与真实零值均能解析;剩余次数独立读取,不用总数重算。
func testNumericStringsAndZeroValuesRemainAccurate() throws {
let response = try decode(#"""
{"scenic_id":"128","order_number":"TEST-ORDER-001","airports":[],
"order_progress":{"shot_total":"1","shot_used":"2","shot_remain":0},
"spots":[{"scenic_spot_id":"201","name":"测试点位","distance_m":"0","shot_count":"0","in_range":true,
"air_lines":[{"air_line_id":"301","name":"测试航线","estimated_fly_time":"0","line_video_duration":0,"fly_type":"1"}]}]}
"""#)
XCTAssertEqual(response.scenicID, 128)
XCTAssertEqual(response.orderProgress?.shotTotal, 1)
XCTAssertEqual(response.orderProgress?.shotUsed, 2)
XCTAssertEqual(response.orderProgress?.shotRemain, 0)
XCTAssertEqual(response.spots[0].distanceM, 0)
XCTAssertEqual(response.spots[0].shotCount, 0)
XCTAssertEqual(response.spots[0].inRange, true)
XCTAssertEqual(response.spots[0].airLines[0].estimatedFlyTime, 0)
XCTAssertEqual(response.spots[0].airLines[0].lineVideoDuration, 0)
}
/// 缺失或 null 的可选字段保持未知,不生成额度或可召唤结论。
func testMissingAndNullOptionalFieldsRemainUnknown() throws {
let response = try decode(#"""
{"scenic_id":128,"order_number":"TEST-ORDER-001","airports":[],"tips":null,
"order_progress":{"shot_total":null},"shoot_gate":{},
"spots":[{"scenic_spot_id":201,"name":"测试点位","in_range":null,
"air_lines":[{"air_line_id":301,"name":"测试航线","estimated_fly_time":null}]}]}
"""#)
XCTAssertNil(response.orderProgress?.orderNumber)
XCTAssertNil(response.orderProgress?.packageName)
XCTAssertNil(response.orderProgress?.shotTotal)
XCTAssertNil(response.orderProgress?.shotUsed)
XCTAssertNil(response.orderProgress?.shotRemain)
XCTAssertNil(response.orderProgress?.statusLabel)
XCTAssertNil(response.shootGate?.canShoot)
XCTAssertNil(response.shootGate?.code)
XCTAssertNil(response.shootGate?.primaryAction)
XCTAssertNil(response.tips)
XCTAssertNil(response.spots[0].distanceLabel)
XCTAssertNil(response.spots[0].distanceM)
XCTAssertNil(response.spots[0].inRange)
XCTAssertNil(response.spots[0].shotCount)
XCTAssertNil(response.spots[0].airLines[0].estimatedFlyTime)
}
/// 缺失与错误列表不能伪装成准备页正常空态。
func testMalformedRequiredListsAndScopeAreRejected() {
for payload in [
#"{"scenic_id":128,"order_number":"TEST","spots":[]}"#,
#"{"scenic_id":128,"order_number":"TEST","airports":[],"spots":null}"#,
#"{"scenic_id":128,"order_number":"TEST","airports":[],"spots":{}}"#,
#"{"scenic_id":0,"order_number":"TEST","airports":[],"spots":[]}"#,
#"{"scenic_id":128,"order_number":" ","airports":[],"spots":[]}"#,
#"{"scenic_id":128,"order_number":"TEST","airports":[],"spots":[{"scenic_spot_id":201,"name":"测试点位"}]}"#,
#"{"scenic_id":128,"order_number":"TEST","airports":[],"spots":[{"scenic_spot_id":201,"name":"测试点位","air_lines":[null]}]}"#
] { XCTAssertThrowsError(try decode(payload), payload) }
}
/// 列表身份必须正整数且各自唯一,同一航线可归属不同点位而不产生虚假重复。
func testInvalidAndDuplicateIdentitiesAreRejected() throws {
for id in ["0", "-1", "1.5", "true", "\"invalid\""] {
XCTAssertThrowsError(try decode("{\"scenic_id\":128,\"order_number\":\"TEST\",\"airports\":[],\"spots\":[{\"scenic_spot_id\":\(id),\"name\":\"测试\",\"air_lines\":[]}] }"))
}
let route = #"{"air_line_id":301,"name":"测试航线"}"#
let point = "{\"scenic_spot_id\":201,\"name\":\"测试点位\",\"air_lines\":[\(route)]}"
XCTAssertThrowsError(try decode("{\"scenic_id\":128,\"order_number\":\"TEST\",\"airports\":[],\"spots\":[\(point),\(point)]}"))
XCTAssertThrowsError(try decode("{\"scenic_id\":128,\"order_number\":\"TEST\",\"airports\":[],\"spots\":[{\"scenic_spot_id\":201,\"name\":\"测试点位\",\"air_lines\":[\(route),\(route)]}]}"))
XCTAssertThrowsError(try decode(#"{"scenic_id":128,"order_number":"TEST","airports":[{"id":1,"name":"测试设备"},{"id":1,"name":"测试设备"}],"spots":[]}"#))
let otherPoint = point.replacingOccurrences(of: "201", with: "202")
let response = try decode("{\"scenic_id\":128,\"order_number\":\"TEST\",\"airports\":[],\"spots\":[\(point),\(otherPoint)]}")
XCTAssertEqual(response.spots.map { $0.airLines.first?.id }, [301, 301])
}
/// 进度属于其他订单时拒绝响应,防止串单额度显示。
func testMismatchingProgressOrderIsRejected() {
XCTAssertThrowsError(try decode(#"{"scenic_id":128,"order_number":"TEST-ORDER-001","order_progress":{"order_number":"TEST-ORDER-002"},"airports":[],"spots":[]}"#))
}
/// 非法次数、距离和布尔类型明确报错,不静默变成零或允许操作。
func testMalformedCountsDistancesAndGateAreRejected() {
for value in ["-1", "1.5", "true", "\"invalid\""] {
XCTAssertThrowsError(try decode("{\"scenic_id\":128,\"order_number\":\"TEST\",\"airports\":[],\"spots\":[],\"order_progress\":{\"shot_used\":\(value)}}"))
}
for value in ["-1", "\"NaN\"", "\"infinity\"", "true", "\"invalid\""] {
XCTAssertThrowsError(try decode("{\"scenic_id\":128,\"order_number\":\"TEST\",\"airports\":[],\"spots\":[{\"scenic_spot_id\":201,\"name\":\"测试\",\"air_lines\":[],\"distance_m\":\(value)}]}"))
}
XCTAssertThrowsError(try decode(#"{"scenic_id":128,"order_number":"TEST","airports":[],"spots":[],"shoot_gate":{"can_shoot":"true"}}"#))
}
/// 未知门禁代码和文案原样保留,不将未识别状态视为允许召唤。
func testNewGateCodesArePreservedWithoutInventingPermission() throws {
let response = try decode(#"{"scenic_id":128,"order_number":"TEST","airports":[],"spots":[],"shoot_gate":{"code":"future_check","message":"需要新的检查","primary_action":"future_action","primary_action_label":"检查状态"}}"#)
XCTAssertEqual(response.shootGate?.code, "future_check")
XCTAssertEqual(response.shootGate?.message, "需要新的检查")
XCTAssertEqual(response.shootGate?.primaryAction, "future_action")
XCTAssertEqual(response.shootGate?.primaryActionLabel, "检查状态")
XCTAssertNil(response.shootGate?.canShoot)
}
/// 与实测字段形状一致的匿名夹具,不包含真实设备、游客或业务订单。
private static let payload = #"""
{"scenic_id":128,"order_number":"TEST-ORDER-001",
"airports":[{"id":51,"name":"测试机巢","sn_number":"test-airport-sn","online_status":2,"work_status":0,"work_status_label":"离线","metrics":[]}],
"order_progress":{"order_number":"TEST-ORDER-001","package_name":"测试套餐 · 含 1 次拍摄","shot_total":1,"shot_used":0,"shot_remain":1,"status_label":"待拍摄"},
"recommend_plane":null,
"shoot_gate":{"can_shoot":false,"code":"dock_offline","message":"机巢未连接","primary_action":"blocked","primary_action_label":"机巢未连接"},
"spots":[{"scenic_spot_id":201,"name":"测试点位一","distance_label":"123.5 m","distance_m":123.5,"in_range":false,"shot_count":0,"shot_status_label":"未拍摄",
"air_lines":[{"air_line_id":301,"name":"测试航线一","estimated_fly_time":279,"line_video_duration":14,"fly_type":1}]},
{"scenic_spot_id":202,"name":"测试点位二","air_lines":[]}],
"tips":"测试拍摄规则"}
"""#
/// 为匿名载荷补齐业务响应外层。
private func envelope(_ payload: String) -> Data {
Data("{\"code\":100000,\"msg\":\"success\",\"data\":\(payload)}".utf8)
}
/// 解码独立准备载荷,便于定位字段错误。
private func decode(_ payload: String) throws -> DroneDockPreparationResponse {
try JSONDecoder().decode(DroneDockPreparationResponse.self, from: Data(payload.utf8))
}
/// 读取请求查询参数,不依赖 URL 参数顺序。
private func query(_ request: URLRequest) throws -> [String: String] {
let url = try XCTUnwrap(request.url)
let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
return Dictionary(uniqueKeysWithValues: items.map { ($0.name, $0.value ?? "") })
}
}
@@ -0,0 +1,421 @@
import CoreLocation
import Foundation
import XCTest
@testable import suixinkan
/// 验证真实准备页的选择、定位缺失与请求身份隔离,不访问后端或发送飞行操作。
@MainActor
final class DroneDockPreparationViewModelTests: XCTestCase {
/// 最新准备快照保留零次,初次按服务端顺序选取点位和航线。
func testSuccessfulSnapshotPreservesZeroCountsAndSelectsFirstSpotAndRoute() async throws {
let scope = PreparationContextBox(context())
let service = ImmediatePreparationService(result: .success(try response()))
let location = MockLocationProvider()
let model = try makeModel(scope: scope, service: service, location: location)
XCTAssertNil(model.response)
XCTAssertNil(model.selectedSpotID)
XCTAssertNil(model.selectedRouteID)
await model.refresh()
XCTAssertEqual(model.response?.orderProgress?.shotUsed, 0)
XCTAssertEqual(model.response?.orderProgress?.shotRemain, 1)
XCTAssertEqual(model.spots.map(\.id), [201, 202])
XCTAssertEqual(model.selectedSpotID, 201)
XCTAssertEqual(model.selectedRouteID, 301)
XCTAssertEqual(model.routes.map(\.id), [301, 302])
XCTAssertTrue(model.hasLocation)
XCTAssertNil(model.errorMessage)
XCTAssertNil(model.locationMessage)
XCTAssertEqual(service.requests.count, 1)
XCTAssertEqual(service.requests.first?.scenicID, 128)
XCTAssertEqual(service.requests.first?.orderNumber, "TEST-PREPARATION-001")
XCTAssertEqual(service.requests.first?.coordinate?.latitude, location.coordinate.latitude)
XCTAssertEqual(service.requests.first?.coordinate?.longitude, location.coordinate.longitude)
XCTAssertEqual(location.requestedAccuracies.count, 1)
}
/// 点位切换重选所属航线,非法身份与其他点位的航线不会影响当前选择。
func testChangingSpotResetsRouteAndUnknownSelectionsAreIgnored() async throws {
let scope = PreparationContextBox(context())
let service = ImmediatePreparationService(result: .success(try response()))
let model = try makeModel(scope: scope, service: service)
await model.refresh()
model.selectRoute(id: 302)
XCTAssertEqual(model.selectedRouteID, 302)
model.selectSpot(id: 202)
XCTAssertEqual(model.selectedSpotID, 202)
XCTAssertEqual(model.selectedRouteID, 401)
XCTAssertEqual(model.routes.map(\.id), [401, 402])
model.selectRoute(id: 402)
model.selectSpot(id: 999)
model.selectRoute(id: 301)
model.selectRoute(id: 999)
XCTAssertEqual(model.selectedSpotID, 202)
XCTAssertEqual(model.selectedRouteID, 402)
XCTAssertEqual(model.selectedSpot?.id, 202)
XCTAssertEqual(model.selectedRoute?.id, 402)
XCTAssertEqual(service.requests.count, 1, "选择仅更新本地准备状态,不创建或召唤任务")
}
/// 刷新保留仍有效的选择,已移除的航线或点位回落到服务端首项,空列表清除选择。
func testRefreshPreservesValidSelectionsAndReplacesRemovedSelections() async throws {
let scope = PreparationContextBox(context())
let service = ImmediatePreparationService(result: .success(try response()))
let model = try makeModel(scope: scope, service: service)
await model.refresh()
model.selectSpot(id: 202)
model.selectRoute(id: 402)
await model.refresh()
XCTAssertEqual(model.selectedSpotID, 202)
XCTAssertEqual(model.selectedRouteID, 402)
var changed = spots()
changed[1]["air_lines"] = [route(id: 401)]
service.result = .success(try response(spots: changed))
await model.refresh()
XCTAssertEqual(model.selectedSpotID, 202)
XCTAssertEqual(model.selectedRouteID, 401)
service.result = .success(try response(spots: [spots()[0]]))
await model.refresh()
XCTAssertEqual(model.selectedSpotID, 201)
XCTAssertEqual(model.selectedRouteID, 301)
service.result = .success(try response(spots: []))
await model.refresh()
XCTAssertTrue(model.spots.isEmpty)
XCTAssertTrue(model.routes.isEmpty)
XCTAssertNil(model.selectedSpotID)
XCTAssertNil(model.selectedRouteID)
XCTAssertNil(model.selectedSpot)
XCTAssertNil(model.selectedRoute)
}
/// 网络失败后旧准备数据与选项失效,重试成功才重新展示点位。
func testRefreshFailureClearsSnapshotAndSelectionsAndCanRetry() async throws {
let scope = PreparationContextBox(context())
let service = ImmediatePreparationService(result: .success(try response()))
let model = try makeModel(scope: scope, service: service)
await model.refresh()
model.selectSpot(id: 202)
service.result = .failure(APIError.networkFailed("测试准备请求超时"))
await model.refresh()
XCTAssertNil(model.response)
XCTAssertNil(model.selectedSpotID)
XCTAssertNil(model.selectedRouteID)
XCTAssertTrue(model.spots.isEmpty)
XCTAssertTrue(model.errorMessage?.contains("测试准备请求超时") == true)
service.result = .success(try response())
await model.refresh()
XCTAssertNotNil(model.response)
XCTAssertNil(model.errorMessage)
XCTAssertEqual(model.selectedSpotID, 201)
XCTAssertEqual(model.selectedRouteID, 301)
}
/// 未定位时仍可读取点位;请求不伪造坐标,界面不信任后端缺坐标时返回的距离或范围。
func testLocationFailureOmitsCoordinatesAndKeepsRangeUnknown() async throws {
let location = MockLocationProvider()
location.requestCoordinateError = LocationProviderError.permissionDenied
let session = MockURLSession(responses: [try envelope()])
let api = DroneDockPreparationAPI(client: APIClient(environment: .testing, session: session))
let scope = PreparationContextBox(context())
let model = try makeModel(scope: scope, service: api, location: location)
await model.refresh()
XCTAssertNotNil(model.response)
XCTAssertFalse(model.hasLocation)
XCTAssertNotNil(model.locationMessage)
XCTAssertEqual(model.rangeTitle, "位置待确认")
XCTAssertNil(model.errorMessage)
let request = try XCTUnwrap(session.requests.first)
XCTAssertEqual(session.requests.count, 1)
XCTAssertEqual(request.httpMethod, "GET")
XCTAssertEqual(request.url?.path, "/api/app/airport/workbench")
XCTAssertNil(request.httpBody)
let queryItems = URLComponents(url: try XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems ?? []
let query = Dictionary(uniqueKeysWithValues: queryItems.map { ($0.name, $0.value ?? "") })
XCTAssertEqual(query["scenic_id"], "128")
XCTAssertEqual(query["order_number"], "TEST-PREPARATION-001")
XCTAssertNil(query["lat"])
XCTAssertNil(query["lng"])
}
/// 定位恢复后新请求携带新位置,原位置错误不残留在准备状态中。
func testLocationRecoveryRefreshesCoordinateAndClearsLocationError() async throws {
let location = MockLocationProvider()
location.requestCoordinateError = LocationProviderError.locationFailed
let scope = PreparationContextBox(context())
let service = ImmediatePreparationService(result: .success(try response()))
let model = try makeModel(scope: scope, service: service, location: location)
await model.refresh()
XCTAssertFalse(model.hasLocation)
XCTAssertNil(service.requests.first?.coordinate)
location.requestCoordinateError = nil
location.coordinate = CLLocationCoordinate2D(latitude: 30.1, longitude: 120.2)
await model.refresh()
XCTAssertTrue(model.hasLocation)
XCTAssertNil(model.locationMessage)
XCTAssertEqual(service.requests.last?.coordinate, DroneDockPreparationCoordinate(latitude: 30.1, longitude: 120.2))
}
/// 景区、顶层订单号或嵌套进度订单号不匹配时,不能展示成当前订单的准备数据。
func testMismatchedScenicAndOrderResponsesAreRejected() async throws {
let invalidResponses = try [
envelope(scenicID: 999),
envelope(orderNumber: "TEST-OTHER-ORDER"),
envelope(progressOrderNumber: "TEST-OTHER-PROGRESS")
]
for payload in invalidResponses {
let scope = PreparationContextBox(context())
let session = MockURLSession(responses: [payload])
let api = DroneDockPreparationAPI(client: APIClient(environment: .testing, session: session))
let model = try makeModel(scope: scope, service: api)
await model.refresh()
XCTAssertNil(model.response)
XCTAssertNil(model.selectedSpotID)
XCTAssertNil(model.selectedRouteID)
XCTAssertNotNil(model.errorMessage)
}
}
/// 账号、景区、门店或凭证在等待期间变化,旧请求完成后不得展示旧订单准备数据。
func testIdentityChangesRejectInFlightResponses() async throws {
let changedContexts = [
context(userID: "second-test-user"), context(scenicID: 129),
context(storeID: 38), context(token: "second-test-token")
]
for (index, changedContext) in changedContexts.enumerated() {
let scope = PreparationContextBox(context())
let service = SuspendedPreparationService()
let started = expectation(description: "准备请求已挂起 \(index)")
service.requestStarted = { _ in started.fulfill() }
defer { service.cancelAll() }
let model = try makeModel(scope: scope, service: service)
let pending = Task { await model.refresh() }
await fulfillment(of: [started], timeout: 2)
scope.value = changedContext
service.finish(index: 0, result: .success(try response()))
await pending.value
XCTAssertNil(model.response)
XCTAssertNil(model.selectedSpotID)
XCTAssertNil(model.selectedRouteID)
XCTAssertNotNil(model.errorMessage)
}
}
/// 离页使当前请求失效,迟到的成功响应不能重新填充已清空的页面。
func testInvalidationRejectsLateResponse() async throws {
let scope = PreparationContextBox(context())
let service = SuspendedPreparationService()
let started = expectation(description: "待失效准备请求已挂起")
service.requestStarted = { _ in started.fulfill() }
defer { service.cancelAll() }
let model = try makeModel(scope: scope, service: service)
let pending = Task { await model.refresh() }
await fulfillment(of: [started], timeout: 2)
model.invalidate()
service.finish(index: 0, result: .success(try response()))
await pending.value
XCTAssertNil(model.response)
XCTAssertNil(model.selectedSpotID)
XCTAssertNil(model.selectedRouteID)
XCTAssertNil(model.errorMessage)
XCTAssertEqual(scope.value, context(), "页面失效不得修改登录或景区选择")
}
/// 较早请求最后返回时,不覆盖已经完成的新准备快照。
func testOlderRefreshCannotOverwriteNewerSnapshot() async throws {
let scope = PreparationContextBox(context())
let service = SuspendedPreparationService()
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 = try makeModel(scope: scope, service: service)
let first = Task { await model.refresh() }
await fulfillment(of: [firstStarted], timeout: 2)
let second = Task { await model.refresh() }
await fulfillment(of: [secondStarted], timeout: 2)
service.finish(index: 1, result: .success(try response(spots: [spots()[1]])))
await second.value
service.finish(index: 0, result: .success(try response()))
await first.value
XCTAssertEqual(model.spots.map(\.id), [202])
XCTAssertEqual(model.selectedSpotID, 202)
XCTAssertEqual(model.selectedRouteID, 401)
XCTAssertNil(model.errorMessage)
}
/// 身份或订单编号不完整时不发出范围不明的准备请求。
func testMissingIdentityOrOrderNumberDoesNotCallService() async throws {
for scopeValue in [context(scenicID: 0), context(token: "")] {
let scope = PreparationContextBox(scopeValue)
let service = ImmediatePreparationService(result: .success(try response()))
let model = try makeModel(scope: scope, service: service)
await model.refresh()
XCTAssertTrue(service.requests.isEmpty)
XCTAssertNil(model.response)
XCTAssertNotNil(model.errorMessage)
}
let scope = PreparationContextBox(context())
let service = ImmediatePreparationService(result: .success(try response()))
let model = try makeModel(scope: scope, service: service, orderNumber: nil)
await model.refresh()
XCTAssertTrue(service.requests.isEmpty)
XCTAssertNil(model.response)
XCTAssertNotNil(model.errorMessage)
}
/// 注入只在本例内变化的身份、网络及定位替身。
private func makeModel(scope: PreparationContextBox, service: any DroneDockPreparationServing,
location: MockLocationProvider = MockLocationProvider(),
orderNumber: String? = "TEST-PREPARATION-001") throws -> DroneDockPreparationViewModel {
var object: [String: Any] = [
"order_id": 101, "tourist_label": "测试游客", "package_name": "旧列表套餐",
"shot_total": 5, "shot_used": 2, "shot_remain": 3
]
object["order_number"] = orderNumber
let order = try JSONDecoder().decode(DroneDockHomeOrder.self, from: JSONSerialization.data(withJSONObject: object))
return DroneDockPreparationViewModel(context: scope.value, order: order, service: service,
locationProvider: location, currentContext: { scope.value })
}
/// 使用匿名且独立的会话,避免污染模拟器上的实际账号。
private func context(userID: String = "preparation-test-user", scenicID: Int = 128,
storeID: Int = 37, token: String = "preparation-test-token") -> DroneDockHomeContext {
DroneDockHomeContext(userID: userID, accountType: "store_user", scenicID: scenicID,
scenicName: "测试景区", storeID: storeID, photographerName: "测试工作人员", token: token)
}
/// 构造与实测字段一致的匿名准备响应。
private func payload(scenicID: Int = 128, orderNumber: String = "TEST-PREPARATION-001",
progressOrderNumber: String? = nil, spots: [[String: Any]]? = nil) -> [String: Any] {
[
"scenic_id": scenicID, "order_number": orderNumber,
"order_progress": ["order_number": progressOrderNumber ?? orderNumber,
"package_name": "测试单次套餐", "shot_total": 1, "shot_used": 0,
"shot_remain": 1, "status_label": "待拍摄"],
"airports": [["id": 51, "name": "测试机巢", "sn_number": "test-preparation-airport",
"online_status": 2, "work_status": 0, "work_status_label": "离线", "metrics": []]],
"recommend_plane": NSNull(), "spots": spots ?? self.spots(),
"shoot_gate": ["can_shoot": false, "code": "dock_offline", "message": "机巢未连接",
"primary_action": "blocked", "primary_action_label": "机巢未连接"],
"tips": "测试规则提示"
]
}
/// 成功响应的内存模型供可挂起的服务替身返回。
private func response(spots: [[String: Any]]? = nil) throws -> DroneDockPreparationResponse {
try JSONDecoder().decode(DroneDockPreparationResponse.self,
from: JSONSerialization.data(withJSONObject: payload(spots: spots)))
}
/// 为真实 APIClient 替身构造响应包裹,验证请求及响应范围校验。
private func envelope(scenicID: Int = 128, orderNumber: String = "TEST-PREPARATION-001",
progressOrderNumber: String? = nil) throws -> Data {
try JSONSerialization.data(withJSONObject: [
"code": 100000, "msg": "success",
"data": payload(scenicID: scenicID, orderNumber: orderNumber, progressOrderNumber: progressOrderNumber)
])
}
/// 两个匿名点位各有两条航线,便于验证跨点位选择隔离。
private func spots() -> [[String: Any]] {
[
["scenic_spot_id": 201, "name": "测试点位一", "distance_label": "0 m", "distance_m": 0,
"in_range": true, "shot_count": 0, "shot_status_label": "未拍摄", "air_lines": [route(id: 301), route(id: 302)]],
["scenic_spot_id": 202, "name": "测试点位二", "distance_label": "100 m", "distance_m": 100,
"in_range": false, "shot_count": 0, "shot_status_label": "未拍摄", "air_lines": [route(id: 401), route(id: 402)]]
]
}
/// 提供真实接口字段名的匿名航线。
private func route(id: Int) -> [String: Any] {
["air_line_id": id, "name": "测试航线 \(id)", "estimated_fly_time": 120,
"fly_type": 1, "line_video_duration": 15]
}
}
/// 主线程上的可变会话替身,只影响当前测试模型。
@MainActor
private final class PreparationContextBox {
var value: DroneDockHomeContext
/// 保存本例当前会话。
init(_ value: DroneDockHomeContext) { self.value = value }
}
/// 准备请求参数快照,用于确认定位与订单范围不被替换。
private struct PreparationRequestRecord {
let scenicID: Int
let orderNumber: String
let coordinate: DroneDockPreparationCoordinate?
}
/// 返回可替换结果的只读准备服务,不具备创建任务或控制飞行的方法。
@MainActor
private final class ImmediatePreparationService: DroneDockPreparationServing {
var result: Result<DroneDockPreparationResponse, Error>
private(set) var requests: [PreparationRequestRecord] = []
/// 注入本例初始响应。
init(result: Result<DroneDockPreparationResponse, Error>) { self.result = result }
/// 记录读取参数并返回当前响应。
func workbench(scenicID: Int, orderNumber: String,
coordinate: DroneDockPreparationCoordinate?) async throws -> DroneDockPreparationResponse {
requests.append(PreparationRequestRecord(scenicID: scenicID, orderNumber: orderNumber, coordinate: coordinate))
return try result.get()
}
}
/// 由测试显式完成的准备请求,用于验证乱序返回与离页后的结果失效。
@MainActor
private final class SuspendedPreparationService: DroneDockPreparationServing {
var requestStarted: ((Int) -> Void)?
private var continuations: [CheckedContinuation<DroneDockPreparationResponse, Error>?] = []
/// 挂起当前请求,等待测试模拟后端回包。
func workbench(scenicID: Int, orderNumber: String,
coordinate: DroneDockPreparationCoordinate?) async throws -> DroneDockPreparationResponse {
try await withCheckedThrowingContinuation { continuation in
let index = continuations.count
continuations.append(continuation)
requestStarted?(index)
}
}
/// 完成指定请求一次,防止 continuation 重复恢复。
func finish(index: Int, result: Result<DroneDockPreparationResponse, Error>) {
guard continuations.indices.contains(index), let continuation = continuations[index] else { return }
continuations[index] = nil
continuation.resume(with: result)
}
/// 在测试退出时恢复尚未完成的请求,避免泄漏等待任务。
func cancelAll() {
for index in continuations.indices { finish(index: index, result: .failure(CancellationError())) }
}
}
@@ -0,0 +1,312 @@
import UIKit
import XCTest
@testable import suixinkan
/// 验证真实准备页的字段、点位航线选择及错误状态,全部接口与定位均使用替身。
@MainActor
final class DroneDockPreparationViewTests: XCTestCase {
private weak var previousKeyWindow: UIWindow?
/// 准备页使用后端最新额度和设备原因,召唤按钮不会进入演示或发送飞行请求。
func testServerSnapshotDisplaysOrderPointsRoutesAndOfflineGate() async throws {
let (controller, session) = try makeController(responses: [DroneDockPreparationViewFixtures.envelope()])
let window = makeWindow(root: controller)
defer { close(window) }
let list = try collection(in: controller)
try await settle(window) { controller.viewModel.response != nil && list.numberOfItems(inSection: 2) == 2 }
let texts = visibleTexts(in: controller.view)
XCTAssertEqual(controller.title, "拍摄准备")
XCTAssertTrue(texts.contains("游客 130****0001"))
XCTAssertTrue(texts.contains("测试套餐 · 含 1 次拍摄"))
XCTAssertTrue(texts.contains("已拍摄 0 次"))
XCTAssertTrue(texts.contains("剩余 1 次"))
XCTAssertTrue(texts.contains("测试点一"))
XCTAssertTrue(texts.contains("测试航线甲"))
XCTAssertTrue(texts.contains("机巢未连接"))
XCTAssertEqual(list.numberOfItems(inSection: 1), 2)
XCTAssertNil(controller.navigationItem.rightBarButtonItem, "真实准备页不显示演示状态菜单")
let summon = try button(in: controller.view, id: "drone.preparation.summon")
XCTAssertFalse(summon.isEnabled)
XCTAssertEqual(summon.title(for: .normal), "机巢未连接")
summon.sendActions(for: .touchUpInside)
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
XCTAssertNil(controller.presentedViewController)
XCTAssertEqual(session.requests.count, 1)
assertOnlyWorkbenchReads(session)
assertUnambiguousLayout(in: controller.view)
capture(window, name: "真实准备页-订单点位航线与离线提示")
}
/// 点击点位切换航线和标题,选择航线只更新本地状态且不沿用其他点位的航线。
func testSelectingPointReplacesRoutesAndKeepsSingleSelection() async throws {
let (controller, session) = try makeController(responses: [DroneDockPreparationViewFixtures.envelope()])
let window = makeWindow(root: controller)
defer { close(window) }
let list = try collection(in: controller)
try await settle(window) { controller.viewModel.selectedRouteID == 201 && list.numberOfItems(inSection: 2) == 2 }
try select(IndexPath(item: 1, section: 2), in: list)
try await settle(window) { controller.viewModel.selectedRouteID == 202 }
let selectedRoute = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 1, section: 2)))
XCTAssertTrue(selectedRoute.accessibilityTraits.contains(.selected))
try select(IndexPath(item: 1, section: 1), in: list)
try await settle(window) {
controller.viewModel.selectedSpotID == 102 && list.numberOfItems(inSection: 2) == 1
&& self.visibleTexts(in: controller.view).contains("测试点二的航线")
}
XCTAssertEqual(controller.viewModel.selectedRouteID, 301)
let route = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 0, section: 2)))
XCTAssertEqual(route.accessibilityIdentifier, "drone.preparation.route.301")
XCTAssertTrue(route.accessibilityTraits.contains(.selected))
XCTAssertTrue(visibleTexts(in: route).contains("测试航线丙"))
XCTAssertFalse(visibleTexts(in: route).contains("测试航线乙"))
XCTAssertTrue(visibleTexts(in: controller.view).contains("测试点二 · 测试航线丙"))
XCTAssertEqual(session.requests.count, 1)
assertOnlyWorkbenchReads(session)
}
/// 定位失败仍可看点位航线,但不显示无坐标响应中的距离或在范围内结论。
func testLocationFailureHidesUntrustedDistanceAndRange() async throws {
let location = MockLocationProvider()
location.requestCoordinateError = LocationProviderError.permissionDenied
let (controller, session) = try makeController(responses: [DroneDockPreparationViewFixtures.envelope(canShoot: true)], location: location)
let window = makeWindow(root: controller)
defer { close(window) }
let list = try collection(in: controller)
try await settle(window) { controller.viewModel.response != nil && list.numberOfItems(inSection: 1) == 2 }
let texts = visibleTexts(in: controller.view)
XCTAssertTrue(texts.contains("待定位"))
XCTAssertTrue(texts.contains("位置待确认"))
XCTAssertFalse(texts.contains("12 m"))
XCTAssertFalse(texts.contains("24 m"))
XCTAssertFalse(texts.contains("在拍摄范围内"))
XCTAssertFalse(try button(in: controller.view, id: "drone.preparation.summon").isEnabled)
let request = try XCTUnwrap(session.requests.first)
let query = URLComponents(url: try XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems ?? []
XCTAssertFalse(query.contains { $0.name == "lat" || $0.name == "lng" })
assertOnlyWorkbenchReads(session)
}
/// 请求失败会移除旧点位航线,刷新成功后才重新显示,不将错误当作成功空态。
func testRefreshFailureClearsOldOptionsAndRetryRestoresThem() async throws {
let payload = try DroneDockPreparationViewFixtures.envelope()
let failure = try TestJSON.errorEnvelope(code: 160001, msg: "测试准备信息暂不可用")
let (controller, session) = try makeController(responses: [payload, failure, payload])
let window = makeWindow(root: controller)
defer { close(window) }
let list = try collection(in: controller)
try await settle(window) { controller.viewModel.response != nil && list.numberOfItems(inSection: 1) == 2 }
try button(in: controller.view, id: "drone.preparation.refreshSummon").sendActions(for: .touchUpInside)
try await settle(window) { self.visibleTexts(in: controller.view).contains("准备信息加载失败") }
XCTAssertNil(controller.viewModel.response)
XCTAssertEqual(list.numberOfItems(inSection: 1), 0)
XCTAssertEqual(list.numberOfItems(inSection: 2), 0)
XCTAssertFalse(visibleTexts(in: controller.view).contains("暂无可用拍摄点"))
XCTAssertFalse(try button(in: controller.view, id: "drone.preparation.summon").isEnabled)
let failedSummary = try XCTUnwrap(find(in: controller.view, id: "drone.preparation.order"))
XCTAssertTrue(visibleTexts(in: failedSummary).contains("已拍摄 — 次"))
XCTAssertTrue(visibleTexts(in: failedSummary).contains("剩余 — 次"))
XCTAssertFalse(visibleTexts(in: failedSummary).contains("已拍摄 0 次"))
XCTAssertFalse(visibleTexts(in: failedSummary).contains("剩余 1 次"))
try button(in: controller.view, id: "drone.preparation.refreshSummon").sendActions(for: .touchUpInside)
try await settle(window) { controller.viewModel.response != nil && list.numberOfItems(inSection: 1) == 2 }
XCTAssertNil(controller.viewModel.errorMessage)
XCTAssertFalse(visibleTexts(in: controller.view).contains("准备信息加载失败"))
XCTAssertEqual(session.requests.count, 3)
assertOnlyWorkbenchReads(session)
}
/// 没有点位和已选点位没有航线使用不同空态,空态刷新不残留旧选择。
func testEmptyPointsAndEmptyRoutesHaveDistinctMessages() async throws {
var pointWithoutRoutes = DroneDockPreparationViewFixtures.spots()[0]
pointWithoutRoutes["air_lines"] = []
let (controller, session) = try makeController(responses: [
DroneDockPreparationViewFixtures.envelope(spots: []),
DroneDockPreparationViewFixtures.envelope(spots: [pointWithoutRoutes])
])
let window = makeWindow(root: controller)
defer { close(window) }
let list = try collection(in: controller)
try await settle(window) { self.visibleTexts(in: controller.view).contains("暂无可用拍摄点") }
XCTAssertNil(controller.viewModel.selectedSpotID)
XCTAssertNil(controller.viewModel.selectedRouteID)
XCTAssertEqual(list.numberOfItems(inSection: 2), 0)
try button(in: controller.view, id: "drone.preparation.refreshSummon").sendActions(for: .touchUpInside)
try await settle(window) { self.visibleTexts(in: controller.view).contains("暂无可用航线") }
XCTAssertEqual(controller.viewModel.selectedSpotID, 101)
XCTAssertNil(controller.viewModel.selectedRouteID)
XCTAssertFalse(visibleTexts(in: controller.view).contains("暂无可用拍摄点"))
XCTAssertFalse(try button(in: controller.view, id: "drone.preparation.summon").isEnabled)
XCTAssertEqual(session.requests.count, 2)
assertOnlyWorkbenchReads(session)
}
/// 进度对象缺失、为 null 或缺少次数时均显示未知,不用首页旧次数填充最新额度。
func testMissingProgressCountsDoNotReuseHomeCounts() async throws {
let incomplete = try DroneDockPreparationViewFixtures.envelope(progress: ["package_name": "待核对套餐"])
var envelope = try XCTUnwrap(JSONSerialization.jsonObject(with: incomplete) as? [String: Any])
var data = try XCTUnwrap(envelope["data"] as? [String: Any])
data["order_progress"] = NSNull()
envelope["data"] = data
let nullProgress = try JSONSerialization.data(withJSONObject: envelope)
data.removeValue(forKey: "order_progress")
envelope["data"] = data
let missingProgress = try JSONSerialization.data(withJSONObject: envelope)
for payload in [incomplete, nullProgress, missingProgress] {
let (controller, session) = try makeController(responses: [payload])
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.response != nil && self.visibleTexts(in: controller.view).contains("已拍摄 — 次") }
let summary = try XCTUnwrap(find(in: controller.view, id: "drone.preparation.order"))
XCTAssertTrue(visibleTexts(in: summary).contains("剩余 — 次"))
XCTAssertFalse(visibleTexts(in: summary).contains("已拍摄 0 次"))
XCTAssertFalse(visibleTexts(in: summary).contains("剩余 1 次"))
assertOnlyWorkbenchReads(session)
}
}
/// 创建固定身份和只使用匿名替身的准备页。
private func makeController(responses: [Data], location: MockLocationProvider = MockLocationProvider()) throws -> (DroneDockRemotePreparationViewController, MockURLSession) {
try DroneDockPreparationViewFixtures.controller(context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(), responses: responses, location: location)
}
private func collection(in controller: UIViewController) throws -> UICollectionView {
controller.loadViewIfNeeded()
return try XCTUnwrap(find(in: controller.view, id: "drone.preparation.remote.list") as? UICollectionView)
}
private func button(in root: UIView, id: String) throws -> UIButton {
try XCTUnwrap(find(in: root, id: id) as? UIButton)
}
/// 经真实 collection delegate 执行选择,保持与用户点击相同的页面路径。
private func select(_ path: IndexPath, in list: UICollectionView) throws {
XCTAssertTrue(list.delegate?.collectionView?(list, shouldSelectItemAt: path) == true)
list.selectItem(at: path, animated: false, scrollPosition: [])
list.delegate?.collectionView?(list, didSelectItemAt: path)
}
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..<200 {
window.layoutIfNeeded()
if condition() {
try await Task.sleep(nanoseconds: 300_000_000)
window.layoutIfNeeded()
if condition() { return }
}
try await Task.sleep(nanoseconds: 20_000_000)
}
XCTFail("拍摄准备页未在预期时间内稳定显示")
throw NSError(domain: "DroneDockPreparationViewTests", code: 1)
}
private func views(in root: UIView) -> [UIView] { [root] + root.subviews.flatMap { views(in: $0) } }
private func hidden(_ view: UIView) -> Bool { view.isHidden || view.alpha < 0.01 || (view.superview.map(hidden) ?? false) }
private func find(in root: UIView, id: String) -> UIView? { views(in: root).first { $0.accessibilityIdentifier == id } }
private func visibleTexts(in root: UIView) -> [String] {
views(in: root).compactMap { view in
guard let label = view as? UILabel, !hidden(label), !label.bounds.isEmpty else { return nil }
return label.text
}
}
private func assertOnlyWorkbenchReads(_ 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/workbench" && $0.httpBody == nil }, file: file, line: line)
}
private func assertUnambiguousLayout(in root: UIView, file: StaticString = #filePath, line: UInt = #line) {
let ambiguous = views(in: root).filter { !hidden($0) && !$0.bounds.isEmpty && $0.hasAmbiguousLayout }
XCTAssertTrue(ambiguous.isEmpty, "可见布局存在歧义:\(ambiguous.map { String(describing: type(of: $0)) })", file: file, line: line)
}
private func capture(_ window: UIWindow, 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)
}
}
/// 真实准备页 UI 与首页导航共用的匿名夹具,不接触真实会话或设备。
@MainActor
enum DroneDockPreparationViewFixtures {
/// 创建用于临时测试窗口的登录范围。
static func context() -> DroneDockHomeContext {
DroneDockHomeContext(userID: "preparation-ui-user", accountType: "store_user", scenicID: 128,
scenicName: "测试景区", storeID: 37, photographerName: "测试工作人员", token: "preparation-test-token")
}
/// 首页所选订单使用固定匿名字段。
static func order() throws -> DroneDockHomeOrder {
try JSONDecoder().decode(DroneDockHomeOrder.self, from: Data(#"{"order_id":701,"order_number":"TEST-PREPARATION-001","tourist_label":"游客 130****0001","package_name":"测试套餐 · 含 1 次拍摄","shot_total":1,"shot_used":0,"shot_remain":1,"status_label":"待拍摄","primary_action":"start_shoot","primary_action_label":"开始拍摄"}"#.utf8))
}
/// 每个点位含自身航线,用于验证切换后不沿用原航线。
static func spots() -> [[String: Any]] {
[
["scenic_spot_id": 101, "name": "测试点一", "distance_label": "12 m", "distance_m": 12, "in_range": true,
"shot_count": 0, "shot_status_label": "未拍摄", "air_lines": [["air_line_id": 201, "name": "测试航线甲"], ["air_line_id": 202, "name": "测试航线乙"]]],
["scenic_spot_id": 102, "name": "测试点二", "distance_label": "24 m", "distance_m": 24, "in_range": false,
"shot_count": 0, "shot_status_label": "未拍摄", "air_lines": [["air_line_id": 301, "name": "测试航线丙"]]]
]
}
/// 按实际结构生成匿名响应,可替换点位、门禁和进度以覆盖状态变化。
static func envelope(orderNumber: String = "TEST-PREPARATION-001", scenicID: Int = 128,
spots: [[String: Any]]? = nil, canShoot: Bool = false,
progress: [String: Any]? = nil) throws -> Data {
let data: [String: Any] = [
"scenic_id": scenicID, "order_number": orderNumber,
"order_progress": progress ?? ["order_number": orderNumber, "package_name": "测试套餐 · 含 1 次拍摄", "shot_total": 1, "shot_used": 0, "shot_remain": 1],
"airports": [["id": 1, "name": "测试机巢", "online_status": 2, "work_status": 0, "work_status_label": "离线", "metrics": []]],
"spots": spots ?? Self.spots(),
"shoot_gate": ["can_shoot": canShoot, "code": canShoot ? "ok" : "dock_offline", "message": canShoot ? "" : "机巢未连接", "primary_action": canShoot ? "shoot" : "blocked", "primary_action_label": canShoot ? "确认并召唤" : "机巢未连接"]
]
return try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": data])
}
/// 创建使用真实请求构造和替身传输的页面,便于验证导航参数与请求范围。
static func controller(context: DroneDockHomeContext, order: DroneDockHomeOrder,
responses: [Data]? = nil, location: MockLocationProvider = MockLocationProvider()) throws -> (DroneDockRemotePreparationViewController, MockURLSession) {
let payloads = try responses ?? [envelope(orderNumber: order.orderNumber ?? "", scenicID: context.scenicID)]
let session = MockURLSession(responses: payloads)
let client = APIClient(environment: .testing, session: session, notificationCenter: NotificationCenter())
client.bindAuthTokenProvider { "preparation-test-token" }
let model = DroneDockPreparationViewModel(context: context, order: order,
service: DroneDockPreparationAPI(client: client), locationProvider: location,
currentContext: { context })
return (DroneDockRemotePreparationViewController(viewModel: model), session)
}
}
@@ -288,9 +288,14 @@ final class DroneDockRemoteHomeViewTests: XCTestCase {
assertOnlyReadHomeRequests(session) assertOnlyReadHomeRequests(session)
} }
/// 真实订单的拍摄按钮只说明待接入流程,不进入演示任务或发送设备控制请求。 /// 首页将正确订单与景区传给真实准备页,导航只读取准备信息,不进入演示任务或发送飞行指令。
func testOrderShootingActionOnlyShowsIntegrationNotice() async throws { func testOrderShootingActionOpensRealPreparationForSelectedOrder() async throws {
let (controller, session) = makeController(responses: [try orderEnvelope([orderRecord(id: 701)])]) var preparationSession: MockURLSession?
let (controller, session) = makeController(responses: [try orderEnvelope([orderRecord(id: 701)])], preparationControllerFactory: { order, context in
let result = try! DroneDockPreparationViewFixtures.controller(context: context, order: order)
preparationSession = result.1
return result.0
})
let window = makeWindow(root: controller) let window = makeWindow(root: controller)
defer { close(window) } defer { close(window) }
let collection = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.remote.list") as? UICollectionView) let collection = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.remote.list") as? UICollectionView)
@@ -300,11 +305,26 @@ final class DroneDockRemoteHomeViewTests: XCTestCase {
XCTAssertTrue(button.isEnabled) XCTAssertTrue(button.isEnabled)
button.sendActions(for: .touchUpInside) button.sendActions(for: .touchUpInside)
try await settle(window: window) { controller.presentedViewController is UIAlertController } try await settle(window: window) {
let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController) (controller.navigationController?.topViewController as? DroneDockRemotePreparationViewController)?.viewModel.response != nil
XCTAssertEqual(alert.title, "开始拍摄") && controller.navigationController?.transitionCoordinator == nil
XCTAssertEqual(alert.message, "拍摄流程暂未接入,请稍后再试") }
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1) let preparation = try XCTUnwrap(controller.navigationController?.topViewController as? DroneDockRemotePreparationViewController)
XCTAssertEqual(preparation.viewModel.order.orderID, 701)
XCTAssertEqual(preparation.viewModel.order.orderNumber, "TEST-ORDER-701")
XCTAssertEqual(preparation.viewModel.context.scenicID, 128)
XCTAssertEqual(preparation.viewModel.context.storeID, 37)
XCTAssertEqual(preparation.viewModel.response?.orderNumber, "TEST-ORDER-701")
XCTAssertEqual(controller.navigationController?.viewControllers.count, 2)
XCTAssertNil(controller.presentedViewController)
XCTAssertFalse(try XCTUnwrap(find(in: preparation.view, identifier: "drone.preparation.summon") as? UIButton).isEnabled)
let request = try XCTUnwrap(preparationSession?.requests.first)
XCTAssertEqual(preparationSession?.requests.count, 1)
XCTAssertEqual(request.httpMethod, "GET")
XCTAssertEqual(request.url?.path, "/api/app/airport/workbench")
let query = URLComponents(url: try XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems ?? []
XCTAssertEqual(query.first { $0.name == "order_number" }?.value, "TEST-ORDER-701")
XCTAssertEqual(query.first { $0.name == "scenic_id" }?.value, "128")
XCTAssertEqual(session.requests.count, 1) XCTAssertEqual(session.requests.count, 1)
assertOnlyReadHomeRequests(session) assertOnlyReadHomeRequests(session)
} }
@@ -437,7 +457,7 @@ final class DroneDockRemoteHomeViewTests: XCTestCase {
} }
/// 创建只接替身网络的正式首页,不读取或修改当前登录状态。 /// 创建只接替身网络的正式首页,不读取或修改当前登录状态。
private func makeController(responses: [Data]) -> (DroneDockHomeViewController, MockURLSession) { private func makeController(responses: [Data], preparationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) -> (DroneDockHomeViewController, MockURLSession) {
let context = DroneDockHomeContext( let context = DroneDockHomeContext(
userID: "remote-home-ui-test", accountType: "store_user", scenicID: 128, userID: "remote-home-ui-test", accountType: "store_user", scenicID: 128,
scenicName: "测试景区", storeID: 37, photographerName: "测试工作人员", token: "test-token" scenicName: "测试景区", storeID: 37, photographerName: "测试工作人员", token: "test-token"
@@ -449,7 +469,7 @@ final class DroneDockRemoteHomeViewTests: XCTestCase {
return (DroneDockHomeViewController(viewModel: viewModel, paymentControllerFactory: { return (DroneDockHomeViewController(viewModel: viewModel, paymentControllerFactory: {
// 夹具均为固定合法 JSON,路由测试不使用 NetworkServices 或真机登录信息。 // 夹具均为固定合法 JSON,路由测试不使用 NetworkServices 或真机登录信息。
try! DroneDockPaymentViewFixtures.controller(context: context) try! DroneDockPaymentViewFixtures.controller(context: context)
}), session) }, preparationControllerFactory: preparationControllerFactory), session)
} }
/// 创建临时测试窗口,结束后恢复原窗口。 /// 创建临时测试窗口,结束后恢复原窗口。