feat(drone-dock): 对接我的拍摄订单筛选与分页

This commit is contained in:
2026-10-28 17:38:48 +08:00
parent 2793f6b113
commit 06460fe7e6
17 changed files with 1827 additions and 34 deletions
@@ -0,0 +1,349 @@
import UIKit
import XCTest
@testable import suixinkan
/// 使用真实请求构造验证独立拍摄订单页的筛选、分页、完整卡及准备入口。
@MainActor
final class DroneDockOrdersViewTests: XCTestCase {
private weak var previousKeyWindow: UIWindow?
/// 页面显示后才读取张工订单,完整卡保留游客、时间、套餐和次数进度。
func testAppearingLoadsOnlyOrdersAndDisplaysFullOrderCard() async throws {
let (controller, session) = makeController(responses: [try envelope([record("FIRST")], total: 1)])
XCTAssertTrue(session.requests.isEmpty)
let window = makeWindow(root: controller)
defer { close(window) }
let list = try collection(in: controller)
try await settle(window) { controller.viewModel.total == 1 && list.numberOfItems(inSection: 0) == 1 }
let cell = try await card(at: 0, in: list, window: window)
let texts = visibleTexts(in: cell)
XCTAssertEqual(controller.title, "我的拍摄订单")
XCTAssertTrue(texts.contains("游客 130****0001"))
XCTAssertTrue(texts.contains { $0.contains("TEST-ORDER-FIRST") && $0.contains("2026-10-28 10:00:00") })
XCTAssertTrue(texts.contains { $0.contains("测试多点位套餐") })
XCTAssertTrue(texts.contains("待拍摄"))
XCTAssertTrue(texts.contains { $0.contains("已拍摄") && $0.contains("0") && $0.contains("5") })
XCTAssertTrue(texts.contains { $0.contains("剩余") && $0.contains("5") })
XCTAssertEqual(try countLabel(in: controller).text, "全部订单(1)")
XCTAssertNotNil(views(in: cell).first { $0 is UIProgressView })
XCTAssertEqual(session.requests.count, 1)
assertOnlyOrders(session)
XCTAssertEqual(query(session.requests[0])["status"], "all")
assertUnambiguousLayout(in: controller.view)
capture(window, name: "我的拍摄订单-真实完整卡")
}
/// 四个状态分别向服务端查询且从第一页加载,不在已加载页面上本地筛选。
func testEachStatusFilterStartsAtPageOneAndKeepsServerResults() async throws {
let payloads = try [envelope([record("ALL")], total: 1),
envelope([record("PENDING")], total: 1),
envelope([record("PROCESSING", status: "processing")], total: 1),
envelope([record("COMPLETED", status: "completed")], total: 1),
envelope([record("ALL-NEW")], total: 1)]
let (controller, session) = makeController(responses: payloads)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.orders.first?.orderID == "TEST-ORDER-ALL" }
for (filter, id, title) in [("pending", "PENDING", "待拍摄订单(1)"),
("inProgress", "PROCESSING", "进行中订单(1)"),
("completed", "COMPLETED", "已完成订单(1)"),
("all", "ALL-NEW", "全部订单(1)")] {
try button(in: controller.view, id: "drone.orders.filter.\(filter)").sendActions(for: .touchUpInside)
try await settle(window) { controller.viewModel.orders.first?.orderID == "TEST-ORDER-\(id)" && self.visibleTexts(in: controller.view).contains(title) }
XCTAssertTrue(try button(in: controller.view, id: "drone.orders.filter.\(filter)").accessibilityTraits.contains(.selected))
}
XCTAssertEqual(session.requests.map { query($0)["status"] }, ["all", "pending", "processing", "completed", "all"])
XCTAssertEqual(session.requests.map { query($0)["page"] }, Array(repeating: "1", count: 5))
assertOnlyOrders(session)
}
/// 次数耗尽的进行中订单仍展示服务端状态,不能自行变成已完成。
func testExhaustedProcessingOrderRemainsInProgressUntilVisitorConfirms() async throws {
var order = record("EXHAUSTED", status: "processing")
order["shot_count"] = 5
order["remaining_count"] = 0
order["can_create_task"] = false
order["can_confirm"] = true
order["can_upload_film"] = true
let (controller, session) = makeController(responses: [try envelope([order], total: 1)])
let window = makeWindow(root: controller)
defer { close(window) }
let list = try collection(in: controller)
try await settle(window) { controller.viewModel.total == 1 }
let cell = try await card(at: 0, in: list, window: window)
XCTAssertTrue(visibleTexts(in: cell).contains("进行中"))
XCTAssertFalse(visibleTexts(in: cell).contains("已完成"))
XCTAssertFalse(visibleTexts(in: cell).contains("开始拍摄"))
XCTAssertTrue(visibleTexts(in: cell).contains { $0.contains("剩余") && $0.contains("0") })
let primary = try button(in: cell, id: "drone.orders.order.TEST-ORDER-EXHAUSTED.primary")
XCTAssertEqual(primary.title(for: .normal), "邀请确认")
XCTAssertTrue(primary.isEnabled)
assertOnlyOrders(session)
}
/// 首屏错误展示重试;成功空态保留零总数,之后下拉刷新可恢复真实数据。
func testInitialFailureRetryEmptyAndPullRefreshRecovery() async throws {
let (controller, session) = makeController(responses: [
try TestJSON.errorEnvelope(code: 160001, msg: "测试订单暂不可用"),
try envelope([], total: 0), try envelope([record("RECOVERED")], total: 1)
])
let window = makeWindow(root: controller)
defer { close(window) }
let list = try collection(in: controller)
try await settle(window) { self.visibleTexts(in: controller.view).contains { $0.contains("订单加载失败") } }
XCTAssertNil(controller.viewModel.total)
XCTAssertFalse(visibleTexts(in: controller.view).contains { $0.contains("暂无拍摄订单") })
try button(in: controller.view, id: "drone.orders.retry").sendActions(for: .touchUpInside)
try await settle(window) { controller.viewModel.total == 0 && self.visibleTexts(in: controller.view).contains { $0.contains("暂无拍摄订单") } }
XCTAssertEqual(try countLabel(in: controller).text, "全部订单(0)")
XCTAssertNil(find(in: controller.view, id: "drone.orders.loadMore"))
try XCTUnwrap(list.refreshControl).sendActions(for: .valueChanged)
try await settle(window) { controller.viewModel.orders.first?.orderID == "TEST-ORDER-RECOVERED" }
XCTAssertEqual(session.requests.count, 3)
XCTAssertEqual(session.requests.map { query($0)["page"] }, ["1", "1", "1"])
assertOnlyOrders(session)
}
/// 翻页失败不丢第一页,重试读取相同页,成功后追加订单并结束分页。
func testPageFailurePreservesCardsAndRetryAppendsSecondPage() async throws {
let first = (1...20).map { record(String($0)) }
let (controller, session) = makeController(responses: [
try envelope(first, total: 21),
try TestJSON.errorEnvelope(code: 160001, msg: "测试分页暂不可用"),
try envelope([record("21")], total: 21, page: 2)
])
let window = makeWindow(root: controller)
defer { close(window) }
let list = try collection(in: controller)
try await settle(window) { controller.viewModel.orders.count == 20 && list.numberOfItems(inSection: 0) == 21 }
list.scrollToItem(at: IndexPath(item: 20, section: 0), at: .centeredVertically, animated: false)
try await settle(window) { self.find(in: controller.view, id: "drone.orders.loadMore") != nil }
try button(in: controller.view, id: "drone.orders.loadMore").sendActions(for: .touchUpInside)
try await settle(window) { controller.viewModel.loadMoreErrorMessage != nil && session.requests.count == 2 }
XCTAssertEqual(controller.viewModel.orders.count, 20)
XCTAssertEqual(try countLabel(in: controller).text, "全部订单(21)")
// 错误说明会增加分页行高度,重新滚入视口后再读取当前复用行的重试按钮。
let footerPath = IndexPath(item: 20, section: 0)
list.scrollToItem(at: footerPath, at: .bottom, animated: false)
try await settle(window) {
guard let cell = list.cellForItem(at: footerPath),
let retry = self.find(in: cell, id: "drone.orders.loadMore") as? UIButton else { return false }
return retry.isEnabled && retry.title(for: .normal) == "重试加载更多"
}
let retryCell = try XCTUnwrap(list.cellForItem(at: footerPath))
try button(in: retryCell, id: "drone.orders.loadMore").sendActions(for: .touchUpInside)
try await settle(window) { controller.viewModel.orders.count == 21 && !controller.viewModel.hasMore && list.numberOfItems(inSection: 0) == 21 }
XCTAssertEqual(controller.viewModel.orders.last?.orderID, "TEST-ORDER-21")
XCTAssertNil(controller.viewModel.loadMoreErrorMessage)
XCTAssertEqual(session.requests.map { query($0)["page"] }, ["1", "2", "2"])
assertOnlyOrders(session)
}
/// 从完整卡开始拍摄传递选中订单和当前范围,跳转前只有读取订单请求。
func testShootingPassesSelectedOrderAndContextWithoutCreatingTasks() async throws {
var receivedOrder: DroneDockHomeOrder?
var receivedContext: DroneDockHomeContext?
var second = record("SECOND")
second["project_id"] = 202
let destination = UIViewController()
let (controller, session) = makeController(responses: [try envelope([record("FIRST"), second], total: 2)]) { order, context in
receivedOrder = order
receivedContext = context
return destination
}
let window = makeWindow(root: controller)
defer { close(window) }
let list = try collection(in: controller)
try await settle(window) { controller.viewModel.orders.count == 2 }
let cell = try await card(at: 1, in: list, window: window)
try button(in: cell, id: "drone.orders.order.TEST-ORDER-SECOND.primary").sendActions(for: .touchUpInside)
try await settle(window) { controller.navigationController?.topViewController === destination && controller.navigationController?.transitionCoordinator == nil }
XCTAssertEqual(receivedOrder?.orderNumber, "TEST-ORDER-SECOND")
XCTAssertEqual(receivedOrder?.projectID, 202)
XCTAssertEqual(receivedContext?.scenicID, 128)
XCTAssertEqual(receivedContext?.storeID, 37)
XCTAssertEqual(controller.navigationController?.viewControllers.count, 2)
XCTAssertEqual(session.requests.count, 1)
assertOnlyOrders(session)
}
/// 素材与交付仍只提示暂未开放,不发送写接口也不进入演示履约页面。
func testUnconnectedMaterialAndDeliveryActionsStayOutsideDemoFlow() async throws {
var order = record("ACTIONS", status: "processing")
order["can_create_task"] = false
order["can_confirm"] = true
order["can_upload_film"] = true
order["material_status"] = 1
order["film_count"] = 2
let (controller, session) = makeController(responses: [try envelope([order], total: 1)])
let window = makeWindow(root: controller)
defer { close(window) }
let list = try collection(in: controller)
try await settle(window) { controller.viewModel.total == 1 }
let cell = try await card(at: 0, in: list, window: window)
for (suffix, title) in [("materials", "订单素材"), ("delivery", "交付成片"), ("primary", "交付确认")] {
let control = try XCTUnwrap(find(in: cell, id: "drone.orders.order.TEST-ORDER-ACTIONS.\(suffix)") as? UIControl)
XCTAssertTrue(control.isEnabled)
control.sendActions(for: .touchUpInside)
try await settle(window) { controller.presentedViewController is UIAlertController }
let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController)
XCTAssertEqual(alert.title, title)
XCTAssertEqual(alert.message, "该功能暂未开放")
controller.dismiss(animated: false)
try await settle(window) { controller.presentedViewController == nil }
}
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
XCTAssertEqual(session.requests.count, 1)
assertOnlyOrders(session)
}
/// 同订单刷新缺失字段时清除上一张卡的游客、套餐、次数及动作,未知不补零。
func testRefreshClearsMissingFieldsAndShowsUnknownCounts() async throws {
let minimal: [String: Any] = ["order_number": "TEST-ORDER-UNKNOWN", "project_id": 101]
let (controller, session) = makeController(responses: [try envelope([record("UNKNOWN")], total: 1), try envelope([minimal], total: 1)])
let window = makeWindow(root: controller)
defer { close(window) }
let list = try collection(in: controller)
try await settle(window) { controller.viewModel.total == 1 }
_ = try await card(at: 0, in: list, window: window)
try XCTUnwrap(list.refreshControl).sendActions(for: .valueChanged)
try await settle(window) { controller.viewModel.orders.first?.shotTotal == nil && self.visibleTexts(in: controller.view).contains("游客信息待确认") }
let cell = try await card(at: 0, in: list, window: window)
let texts = visibleTexts(in: cell)
XCTAssertTrue(texts.contains("套餐信息待确认"))
XCTAssertTrue(texts.contains("状态待确认"))
XCTAssertTrue(texts.contains { $0.contains("—") })
XCTAssertFalse(texts.contains("游客 130****0001"))
XCTAssertFalse(texts.contains { $0.contains("测试多点位套餐") })
XCTAssertFalse(texts.contains("开始拍摄"))
XCTAssertFalse(texts.contains { $0.contains("0/0") })
let primary = find(in: cell, id: "drone.orders.order.TEST-ORDER-UNKNOWN.primary") as? UIButton
XCTAssertTrue(primary == nil || hidden(primary!) || primary?.isEnabled == false)
XCTAssertEqual(session.requests.count, 2)
assertOnlyOrders(session)
}
private func makeController(responses: [Data], factory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) -> (DroneDockOrdersViewController, MockURLSession) {
let context = DroneDockHomeContext(userID: "orders-ui-user", accountType: "store_user", scenicID: 128,
scenicName: "测试景区", storeID: 37, photographerName: "测试工作人员", token: "orders-ui-token")
let session = MockURLSession(responses: responses)
let client = APIClient(environment: .testing, session: session, notificationCenter: NotificationCenter())
client.bindAuthTokenProvider { "orders-ui-token" }
let model = DroneDockOrdersViewModel(context: context, service: DroneDockAPI(client: client), currentContext: { context })
return (DroneDockOrdersViewController(viewModel: model, preparationControllerFactory: factory ?? { _, _ in UIViewController() }), session)
}
private func record(_ id: String, status: String = "pending") -> [String: Any] {
["order_number": "TEST-ORDER-\(id)", "project_id": 101, "created_at": "2026-10-28 10:00:00",
"user_phone": "130****0001", "project_name": "测试多点位套餐", "shoot_count": 5,
"shot_count": status == "completed" ? 5 : status == "pending" ? 0 : 1,
"remaining_count": status == "completed" ? 0 : status == "pending" ? 5 : 4,
"shoot_status": status, "order_status": status == "completed" ? 30 : 20,
"material_status": 0, "film_count": 0, "confirm_status": status == "completed" ? 2 : 0,
"can_create_task": status != "completed", "can_upload_film": false, "can_confirm": false]
}
private func envelope(_ orders: [[String: Any]], total: Int, page: Int = 1) throws -> Data {
try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": [
"list": orders, "total": total, "page": page, "page_size": 20
]])
}
private func query(_ request: URLRequest) -> [String: String] {
let items = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems ?? []
return Dictionary(uniqueKeysWithValues: items.map { ($0.name, $0.value ?? "") })
}
private func assertOnlyOrders(_ session: MockURLSession, file: StaticString = #filePath, line: UInt = #line) {
XCTAssertFalse(session.requests.isEmpty, file: file, line: line)
for request in session.requests {
XCTAssertEqual(request.httpMethod, "GET", file: file, line: line)
XCTAssertEqual(request.url?.path, "/api/yf-handset-app/photog/multi-plane/orders", file: file, line: line)
XCTAssertNil(request.httpBody, file: file, line: line)
XCTAssertEqual(query(request)["scenic_id"], "128", file: file, line: line)
XCTAssertEqual(query(request)["page_size"], "20", file: file, line: line)
XCTAssertNil(query(request)["lat"], file: file, line: line)
XCTAssertNil(query(request)["lng"], file: file, line: line)
}
}
private func collection(in controller: UIViewController) throws -> UICollectionView {
controller.loadViewIfNeeded()
return try XCTUnwrap(find(in: controller.view, id: "drone.orders.remote.list") as? UICollectionView)
}
private func countLabel(in controller: UIViewController) throws -> UILabel {
try XCTUnwrap(find(in: controller.view, id: "drone.orders.count") as? UILabel)
}
private func button(in root: UIView, id: String) throws -> UIButton {
try XCTUnwrap(find(in: root, id: id) as? UIButton)
}
private func card(at index: Int, in list: UICollectionView, window: UIWindow) async throws -> UICollectionViewCell {
let path = IndexPath(item: index, section: 0)
list.scrollToItem(at: path, at: .centeredVertically, animated: false)
try await settle(window) { list.cellForItem(at: path) is DroneShootingOrderCell }
return try XCTUnwrap(list.cellForItem(at: 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()
}
private func settle(_ window: UIWindow, file: StaticString = #filePath, line: UInt = #line,
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)
}
capture(window, name: "拍摄订单页等待超时-\(line)")
XCTFail("拍摄订单页未在预期时间内稳定显示", file: file, line: line)
throw NSError(domain: "DroneDockOrdersViewTests", 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 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)
}
}