diff --git a/AGENTS.md b/AGENTS.md index 5364d1b..15ebf9e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -85,3 +85,12 @@ Swift · UIKit · SnapKit(代码布局,约束写在 `setupUI()` / `setupCons - SnapKit 布局、Kingfisher 图片、Diffable 列表带动画 - 以 Android 工程为功能参考,命令式 UIKit,不用 Observable / Combine - 新增功能必测、类型与公开 API 必注释、保持简洁 + +## 当前禁飞调试限制(2026-10-29 用户要求) + +- 当前无人机禁止飞行。调试只能模拟,禁止向真实无人机下发任何指令;模拟器、测试账号、测试环境都不代表模拟设备。 +- 不通过 App、curl、脚本、浏览器或其他工具真实调用 `airport/shoot`、`airport/start-shoot`、`airport/command`,也不启动实时图传或尝试未确认的设备操作接口。暂停、恢复、返航同样属于设备指令。 +- 创建、召唤、拍摄、失败和返航流程使用纯内存演示或 Mock 响应;必须标明模拟来源,不能把模拟结果记为后端真实成功。不为流程验证创建真实待飞任务。 +- 可继续调试已确认只读的订单、项目、素材及状态接口;`plane-status/shooting` 使用 `live_battery=0`,`status` 使用 `live_metrics=0`,不主动请求设备实时采集。 +- Debug 客户端默认拦截机场操作及真实 `tasks/create`,无运行时放行开关;本地模拟传输不能转发网络。用户明确解除禁飞并授权真实联调前,不删除或绕过保护,也不改用 Release 构建规避。 +- 使用模拟器及隔离网络替身验证本限制,不进行真机飞行测试。 diff --git a/docs/9.9.1/materials-ui-2026-10-29/demo-completed.jpg b/docs/9.9.1/materials-ui-2026-10-29/demo-completed.jpg new file mode 100644 index 0000000..9c46a9f Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/demo-completed.jpg differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/demo-partialFailure.jpg b/docs/9.9.1/materials-ui-2026-10-29/demo-partialFailure.jpg new file mode 100644 index 0000000..6c8a507 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/demo-partialFailure.jpg differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/empty-402.jpg b/docs/9.9.1/materials-ui-2026-10-29/empty-402.jpg new file mode 100644 index 0000000..4964198 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/empty-402.jpg differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/error-402.jpg b/docs/9.9.1/materials-ui-2026-10-29/error-402.jpg new file mode 100644 index 0000000..dc673f4 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/error-402.jpg differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/film-402.png b/docs/9.9.1/materials-ui-2026-10-29/film-402.png new file mode 100644 index 0000000..fe11267 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/film-402.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/loading-402.png b/docs/9.9.1/materials-ui-2026-10-29/loading-402.png new file mode 100644 index 0000000..2f7e880 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/loading-402.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/mixed-375.png b/docs/9.9.1/materials-ui-2026-10-29/mixed-375.png new file mode 100644 index 0000000..c6f4218 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/mixed-375.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/mixed-402.png b/docs/9.9.1/materials-ui-2026-10-29/mixed-402.png new file mode 100644 index 0000000..d9488db Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/mixed-402.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/mixed-runtime.jpg b/docs/9.9.1/materials-ui-2026-10-29/mixed-runtime.jpg new file mode 100644 index 0000000..a6623d4 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/mixed-runtime.jpg differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/ready-402.png b/docs/9.9.1/materials-ui-2026-10-29/ready-402.png new file mode 100644 index 0000000..131f735 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/ready-402.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/selected-402.png b/docs/9.9.1/materials-ui-2026-10-29/selected-402.png new file mode 100644 index 0000000..d470bdd Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/selected-402.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/taskFailed-402.png b/docs/9.9.1/materials-ui-2026-10-29/taskFailed-402.png new file mode 100644 index 0000000..d92d1bc Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/taskFailed-402.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/taskUploading-402.png b/docs/9.9.1/materials-ui-2026-10-29/taskUploading-402.png new file mode 100644 index 0000000..387133b Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/taskUploading-402.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/uploadFailed-402.png b/docs/9.9.1/materials-ui-2026-10-29/uploadFailed-402.png new file mode 100644 index 0000000..1d5b231 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/uploadFailed-402.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-29/uploading-402.png b/docs/9.9.1/materials-ui-2026-10-29/uploading-402.png new file mode 100644 index 0000000..811c5a3 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-29/uploading-402.png differ diff --git a/docs/9.9.1/order-delivery-sheet-2026-10-30/cloud-delivery.png b/docs/9.9.1/order-delivery-sheet-2026-10-30/cloud-delivery.png new file mode 100644 index 0000000..71a2abd Binary files /dev/null and b/docs/9.9.1/order-delivery-sheet-2026-10-30/cloud-delivery.png differ diff --git a/docs/9.9.1/order-delivery-sheet-2026-10-30/delivery-method.png b/docs/9.9.1/order-delivery-sheet-2026-10-30/delivery-method.png new file mode 100644 index 0000000..8779375 Binary files /dev/null and b/docs/9.9.1/order-delivery-sheet-2026-10-30/delivery-method.png differ diff --git a/docs/9.9.1/scenic-ui-2026-10-30/completed.jpg b/docs/9.9.1/scenic-ui-2026-10-30/completed.jpg new file mode 100644 index 0000000..f4bf03d Binary files /dev/null and b/docs/9.9.1/scenic-ui-2026-10-30/completed.jpg differ diff --git a/docs/9.9.1/scenic-ui-2026-10-30/date-filter.jpg b/docs/9.9.1/scenic-ui-2026-10-30/date-filter.jpg new file mode 100644 index 0000000..9c6643a Binary files /dev/null and b/docs/9.9.1/scenic-ui-2026-10-30/date-filter.jpg differ diff --git a/docs/9.9.1/scenic-ui-2026-10-30/downloading.jpg b/docs/9.9.1/scenic-ui-2026-10-30/downloading.jpg new file mode 100644 index 0000000..0c43651 Binary files /dev/null and b/docs/9.9.1/scenic-ui-2026-10-30/downloading.jpg differ diff --git a/docs/9.9.1/scenic-ui-2026-10-30/library.jpg b/docs/9.9.1/scenic-ui-2026-10-30/library.jpg new file mode 100644 index 0000000..3cd68f1 Binary files /dev/null and b/docs/9.9.1/scenic-ui-2026-10-30/library.jpg differ diff --git a/docs/9.9.1/scenic-ui-2026-10-30/partial-failure.jpg b/docs/9.9.1/scenic-ui-2026-10-30/partial-failure.jpg new file mode 100644 index 0000000..10d8dcc Binary files /dev/null and b/docs/9.9.1/scenic-ui-2026-10-30/partial-failure.jpg differ diff --git a/docs/9.9.1/scenic-ui-2026-10-30/preview.jpg b/docs/9.9.1/scenic-ui-2026-10-30/preview.jpg new file mode 100644 index 0000000..8e565f1 Binary files /dev/null and b/docs/9.9.1/scenic-ui-2026-10-30/preview.jpg differ diff --git a/docs/9.9.1/scenic-ui-2026-10-30/route-filter.jpg b/docs/9.9.1/scenic-ui-2026-10-30/route-filter.jpg new file mode 100644 index 0000000..ed39994 Binary files /dev/null and b/docs/9.9.1/scenic-ui-2026-10-30/route-filter.jpg differ diff --git a/docs/9.9.1/start-shoot-mock-2026-10-29/README.md b/docs/9.9.1/start-shoot-mock-2026-10-29/README.md new file mode 100644 index 0000000..ef0f5cc --- /dev/null +++ b/docs/9.9.1/start-shoot-mock-2026-10-29/README.md @@ -0,0 +1,40 @@ +# 开始拍摄:本地模拟调试记录 + +日期:2026-10-29。**全部回执来自纯内存 Mock,未调用后端、未向无人机发送指令,不代表真实接口或设备执行成功。** + +## 调试结果 + +- 提供人:朱工;合同为 `POST /api/app/airport/start-shoot`,请求仅传 `{"id":901}`。901 是合成的订单飞行任务 ID。 +- 模拟器手动操作顺序:进入任务页 GET `shooting` → 点击开始拍摄 POST `start-shoot` → 成功后 GET 同一任务 `shooting` 一次。没有定时轮询、创建、召唤或控制请求。 +- 初始状态为就绪,点击后保留原 UI,状态回查后显示“无人机正在拍摄中(模拟)”。顶部、底部位置保持固定。 +- 模拟器相关测试 **84 项通过,0 失败**:开拍 API 10、开拍 ViewModel 12、模拟页面 3、原任务 ViewModel 16、原任务页面 15、阶段展示 14、固定布局 8、禁飞保护 6。 +- 覆盖成功、明确业务拒绝、超时结果未知、重复点击、身份不匹配、离页取消、旧数据显示、提交后单次回查和真实传输前阻断。明确拒绝可手动重试;超时等不确定结果禁止重复提交。 + +## 证据 + +- [完整三次请求与回执](success-flow.mock.json):从本次模拟器日志提取,标记 `source=local_mock`、`network_sent=false`。 +- [开始拍摄完整模拟回执](start-shoot-response.mock.json)。 +- [模拟器成功态截图](start-shoot-success-mock.jpg)。 +- 测试结果:本机 XcodeBuildMCP `test_sim_2026-10-29T10-06-20-605Z_pid15238_c1dd52ad.xcresult`。 + +## 复现方式与边界 + +### 从拍摄准备进入拍摄任务 + +Debug 的真实准备页右上角点击“本地模拟”,打开独立的“拍摄准备 · 本地模拟”。选择默认模拟点位、航线,点击“确认并召唤(模拟)”,即可进入同一任务 901 的“拍摄任务 · 本地模拟”。也可用启动参数 `--dock-preparation-mock` 直接打开模拟准备页。 + +准备信息、飞机状态、创建、召唤及任务查询全部复用同一内存传输。原订单和登录身份不参与模拟,不生成真实待飞任务;真实准备页的提交按钮仍受禁飞保护。模拟创建仅发送四个合同字段,模拟召唤使用 `{"id":901,"restart":false}`,进入任务页后查询同一 `id=901`。 + +返回模拟准备页后按钮变为“查看拍摄任务”,重新进入只读取原模拟任务,不再创建或召唤。准备页与任务页均提供“查看模拟接口回执”;准备页提交期间禁用该入口,避免打断导航。 + +本次衔接验证:模拟器 **35 项相关测试全部通过**(准备页 19、完整模拟流程 2、禁飞准备页 5、网络保护 6、原开拍模拟页 3)。新增用例检查真实准备页的原服务没有提交、连续点击只创建/召唤一次、同任务进入并开拍,以及返回重进不重复写入。结果包:`test_sim_2026-10-29T10-19-41-808Z_pid15238_387aa23e.xcresult`。 + +模拟器手动操作也已通过:[准备页截图](preparation-mock.jpg)、[跳转后的任务页截图](preparation-to-task-mock.jpg)、[完整内存请求及回执](preparation-to-task.mock.json)。日志为准备配置与设备状态读取、点击后的配置复核、创建一次、召唤一次、同任务查询一次;没有真实后端请求,也未自动开始拍摄。 + +### 直接从拍摄任务开始 + +Debug 启动参数 `--dock-start-shoot-mock`,可加 `--dock-start-shoot-result=success`(默认)、`business-failure` 或 `timeout`。右上角“查看模拟接口回执”显示该会话 JSON。 + +此入口使用独立客户端 `https://mock.invalid` 和纯内存传输;未知请求直接本地失败,不回退网络。`live_battery=1` 仅用于验证 Mock 的查询合同,不触发实时采集;真实 Debug 查询强制改为 0。合成订单、飞机 ID、任务 UUID 和机巢序列号均不可作为真实业务参数。 + +正式任务页未注入开拍服务,按钮仍禁用;统一网络层继续阻断真实 `tasks/create/shoot/start-shoot/command/live`。底部暂停和返航也未启用。后端目前没有约定不会下发设备指令的模拟协议,因此本次只验证客户端行为,不验证后端接收及实际执行。 diff --git a/docs/9.9.1/start-shoot-mock-2026-10-29/preparation-mock.jpg b/docs/9.9.1/start-shoot-mock-2026-10-29/preparation-mock.jpg new file mode 100644 index 0000000..7dbb555 Binary files /dev/null and b/docs/9.9.1/start-shoot-mock-2026-10-29/preparation-mock.jpg differ diff --git a/docs/9.9.1/start-shoot-mock-2026-10-29/preparation-to-task-mock.jpg b/docs/9.9.1/start-shoot-mock-2026-10-29/preparation-to-task-mock.jpg new file mode 100644 index 0000000..29e29c1 Binary files /dev/null and b/docs/9.9.1/start-shoot-mock-2026-10-29/preparation-to-task-mock.jpg differ diff --git a/docs/9.9.1/start-shoot-mock-2026-10-29/preparation-to-task.mock.json b/docs/9.9.1/start-shoot-mock-2026-10-29/preparation-to-task.mock.json new file mode 100644 index 0000000..9961f80 --- /dev/null +++ b/docs/9.9.1/start-shoot-mock-2026-10-29/preparation-to-task.mock.json @@ -0,0 +1,313 @@ +{ + "source": "local_mock", + "network_sent": false, + "description": "从模拟器手动操作日志提取;模拟准备→创建→召唤→任务查询,没有后端请求。", + "records": [ + { + "method": "GET", + "path": "/api/yf-handset-app/photog/multi-plane/project-info", + "network_sent": false, + "query": { + "scenic_id": "128", + "project_id": "101", + "order_number": "LOCAL-MOCK-ORDER-901" + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "can_confirm": false, + "can_create_task": true, + "can_upload_film": false, + "film_count": 0, + "order_number": "LOCAL-MOCK-ORDER-901", + "order_status": 20, + "project_id": 101, + "project_name": "模拟五次套餐", + "remaining_count": 5, + "shoot_count": 5, + "shoot_status": "processing", + "shot_count": 0, + "spot": [ + { + "air_lines": [ + { + "air_line_id": 401, + "air_line_name": "模拟航线", + "available": true, + "samples": [] + } + ], + "available": true, + "scenic_spot_id": 301, + "scenic_spot_name": "模拟点位" + } + ], + "user_phone": "本地模拟游客" + }, + "msg": "local mock success" + } + }, + { + "method": "GET", + "path": "/api/app/airport/plane-status", + "network_sent": false, + "query": { + "scenic_id": "128", + "live_battery": "1" + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "connected": true, + "planes": [ + { + "battery_percent": 95, + "can_fly": true, + "id": 201, + "is_receive_order": 1, + "name": "本地模拟无人机", + "online_status": 1, + "sn_number": "LOCAL-MOCK-PLANE-201", + "status_text": "本地模拟 · 电量 95%", + "work_status": 1, + "work_status_label": "空闲(模拟)" + } + ], + "poll_hint_ms": 30000, + "recommend": { + "battery_percent": 95, + "can_fly": true, + "id": 201, + "is_receive_order": 1, + "name": "本地模拟无人机", + "online_status": 1, + "sn_number": "LOCAL-MOCK-PLANE-201", + "status_text": "本地模拟 · 电量 95%", + "work_status": 1, + "work_status_label": "空闲(模拟)" + }, + "scenic_id": 128 + }, + "msg": "local mock success" + } + }, + { + "method": "GET", + "path": "/api/yf-handset-app/photog/multi-plane/project-info", + "network_sent": false, + "query": { + "scenic_id": "128", + "project_id": "101", + "order_number": "LOCAL-MOCK-ORDER-901" + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "can_confirm": false, + "can_create_task": true, + "can_upload_film": false, + "film_count": 0, + "order_number": "LOCAL-MOCK-ORDER-901", + "order_status": 20, + "project_id": 101, + "project_name": "模拟五次套餐", + "remaining_count": 5, + "shoot_count": 5, + "shoot_status": "processing", + "shot_count": 0, + "spot": [ + { + "air_lines": [ + { + "air_line_id": 401, + "air_line_name": "模拟航线", + "available": true, + "samples": [] + } + ], + "available": true, + "scenic_spot_id": 301, + "scenic_spot_name": "模拟点位" + } + ], + "user_phone": "本地模拟游客" + }, + "msg": "local mock success" + } + }, + { + "method": "POST", + "path": "/api/yf-handset-app/photog/multi-plane/tasks/create", + "network_sent": false, + "request_body": { + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_spot_id": 301, + "scenic_id": 128, + "air_line_id": 401 + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "can_confirm": false, + "can_create_task": true, + "can_upload_film": false, + "film_count": 0, + "order_number": "LOCAL-MOCK-ORDER-901", + "order_status": 20, + "project_id": 101, + "project_name": "模拟五次套餐", + "remaining_count": 5, + "shoot_count": 5, + "shoot_status": "processing", + "shot_count": 0, + "task_id": 901, + "user_phone": "本地模拟游客" + }, + "msg": "local mock success" + } + }, + { + "method": "POST", + "path": "/api/app/airport/shoot", + "network_sent": false, + "request_body": { + "restart": false, + "id": 901 + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "airport_sn": "LOCAL-MOCK-DOCK-201", + "order_flight_task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "order_flight_task_id": 901, + "plane_id": 201, + "task_uuid": "LOCAL-MOCK-TASK-UUID-901", + "ui": { + "message": "本地模拟召唤成功,没有网络或设备指令。", + "phase": "arrived_pending_start", + "title": "无人机已到达(模拟)" + } + }, + "msg": "local mock success" + } + }, + { + "method": "GET", + "path": "/api/app/airport/shooting", + "network_sent": false, + "query": { + "id": "901", + "live_battery": "1" + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "air_line": { + "id": 401, + "name": "模拟航线", + "scenic_spot_id": 301 + }, + "current_plane": { + "id": 201, + "online_status": 1, + "sn_number": "LOCAL-MOCK-PLANE-201", + "status_text": "模拟就绪 · 电量95%", + "work_status": 1, + "work_status_label": "空闲" + }, + "execute_gate": { + "can_execute": true, + "code": "ok", + "message": "本地模拟:允许验证开拍请求", + "primary_action": "start_shoot", + "primary_action_label": "开始拍摄" + }, + "header": { + "order_number": "LOCAL-MOCK-ORDER-901", + "package_name": "模拟套餐 · 含5次拍摄", + "title": "模拟点位 · 模拟航线", + "tourist_label": "本地模拟,无设备指令" + }, + "metrics": [ + { + "key": "battery", + "value": "95%" + }, + { + "key": "env_temp", + "value": "20.3℃" + }, + { + "key": "wind_speed", + "value": "0m/s" + }, + { + "key": "rainfall", + "value": "无雨" + }, + { + "key": "signal", + "value": "良好" + }, + { + "key": "satellite", + "value": "36颗" + } + ], + "order_flight_task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "order_number": "LOCAL-MOCK-ORDER-901", + "plane_status": { + "connected": true, + "poll_hint_ms": 5000, + "scenic_id": 128 + }, + "scenic": { + "id": 128, + "name": "本地模拟景区" + }, + "scenic_spot": { + "id": 301, + "name": "模拟点位" + }, + "task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "ui": { + "message": "点击开始拍摄,仅验证本地接口流程。", + "phase": "arrived_pending_start", + "title": "无人机已到达(模拟)" + } + }, + "msg": "local mock success" + } + } + ] +} diff --git a/docs/9.9.1/start-shoot-mock-2026-10-29/start-shoot-response.mock.json b/docs/9.9.1/start-shoot-mock-2026-10-29/start-shoot-response.mock.json new file mode 100644 index 0000000..aeb1f9c --- /dev/null +++ b/docs/9.9.1/start-shoot-mock-2026-10-29/start-shoot-response.mock.json @@ -0,0 +1,41 @@ +{ + "source": "local_mock", + "network_sent": false, + "response_body": { + "code": 100000, + "data": { + "airport_sn": "LOCAL-MOCK-DOCK-201", + "order_flight_task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "order_flight_task_id": 901, + "plane_id": 201, + "task_uuid": "LOCAL-MOCK-TASK-UUID-901", + "ui": { + "commands": [ + { + "command": "flighttask_pause", + "label": "紧急暂停", + "sub": "悬停待命" + }, + { + "command": "return_home", + "label": "立即返航", + "sub": "中断任务" + } + ], + "message": "本地模拟开拍回执,不代表真实设备执行。", + "phase": "shooting", + "primary_action": "shooting", + "title": "无人机正在拍摄中(模拟)" + } + }, + "msg": "local mock success" + } +} diff --git a/docs/9.9.1/start-shoot-mock-2026-10-29/start-shoot-success-mock.jpg b/docs/9.9.1/start-shoot-mock-2026-10-29/start-shoot-success-mock.jpg new file mode 100644 index 0000000..0322bea Binary files /dev/null and b/docs/9.9.1/start-shoot-mock-2026-10-29/start-shoot-success-mock.jpg differ diff --git a/docs/9.9.1/start-shoot-mock-2026-10-29/success-flow.mock.json b/docs/9.9.1/start-shoot-mock-2026-10-29/success-flow.mock.json new file mode 100644 index 0000000..6b57052 --- /dev/null +++ b/docs/9.9.1/start-shoot-mock-2026-10-29/success-flow.mock.json @@ -0,0 +1,264 @@ +{ + "source": "local_mock", + "description": "纯内存模拟,未调用后端或设备;从模拟器日志提取,不代表后端实测响应。", + "network_sent": false, + "scenario": "success", + "records": [ + { + "method": "GET", + "path": "/api/app/airport/shooting", + "network_sent": false, + "query": { + "id": "901", + "live_battery": "1" + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "air_line": { + "id": 401, + "name": "模拟航线", + "scenic_spot_id": 301 + }, + "current_plane": { + "id": 201, + "online_status": 1, + "sn_number": "LOCAL-MOCK-PLANE-201", + "status_text": "模拟就绪 · 电量95%", + "work_status": 1, + "work_status_label": "空闲" + }, + "execute_gate": { + "can_execute": true, + "code": "ok", + "message": "本地模拟:允许验证开拍请求", + "primary_action": "start_shoot", + "primary_action_label": "开始拍摄" + }, + "header": { + "order_number": "LOCAL-MOCK-ORDER-901", + "package_name": "模拟套餐 · 含5次拍摄", + "title": "模拟点位 · 模拟航线", + "tourist_label": "本地模拟,无设备指令" + }, + "metrics": [ + { + "key": "battery", + "value": "95%" + }, + { + "key": "env_temp", + "value": "20.3℃" + }, + { + "key": "wind_speed", + "value": "0m/s" + }, + { + "key": "rainfall", + "value": "无雨" + }, + { + "key": "signal", + "value": "良好" + }, + { + "key": "satellite", + "value": "36颗" + } + ], + "order_flight_task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "order_number": "LOCAL-MOCK-ORDER-901", + "plane_status": { + "connected": true, + "poll_hint_ms": 5000, + "scenic_id": 128 + }, + "scenic": { + "id": 128, + "name": "本地模拟景区" + }, + "scenic_spot": { + "id": 301, + "name": "模拟点位" + }, + "task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "ui": { + "message": "点击开始拍摄,仅验证本地接口流程。", + "phase": "arrived_pending_start", + "title": "无人机已到达(模拟)" + } + }, + "msg": "local mock success" + } + }, + { + "method": "POST", + "path": "/api/app/airport/start-shoot", + "network_sent": false, + "request_body": { + "id": 901 + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "airport_sn": "LOCAL-MOCK-DOCK-201", + "order_flight_task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "order_flight_task_id": 901, + "plane_id": 201, + "task_uuid": "LOCAL-MOCK-TASK-UUID-901", + "ui": { + "commands": [ + { + "command": "flighttask_pause", + "label": "紧急暂停", + "sub": "悬停待命" + }, + { + "command": "return_home", + "label": "立即返航", + "sub": "中断任务" + } + ], + "message": "本地模拟开拍回执,不代表真实设备执行。", + "phase": "shooting", + "primary_action": "shooting", + "title": "无人机正在拍摄中(模拟)" + } + }, + "msg": "local mock success" + } + }, + { + "method": "GET", + "path": "/api/app/airport/shooting", + "network_sent": false, + "query": { + "id": "901", + "live_battery": "1" + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "air_line": { + "id": 401, + "name": "模拟航线", + "scenic_spot_id": 301 + }, + "current_plane": { + "id": 201, + "online_status": 1, + "sn_number": "LOCAL-MOCK-PLANE-201", + "status_text": "模拟拍摄中 · 电量95%", + "work_status": 2, + "work_status_label": "拍摄中" + }, + "execute_gate": { + "can_execute": false, + "code": "already_started", + "message": "本地模拟:开拍已受理", + "primary_action": "shooting", + "primary_action_label": "拍摄中" + }, + "header": { + "order_number": "LOCAL-MOCK-ORDER-901", + "package_name": "模拟套餐 · 含5次拍摄", + "title": "模拟点位 · 模拟航线", + "tourist_label": "本地模拟,无设备指令" + }, + "metrics": [ + { + "key": "battery", + "value": "95%" + }, + { + "key": "env_temp", + "value": "20.3℃" + }, + { + "key": "wind_speed", + "value": "0m/s" + }, + { + "key": "rainfall", + "value": "无雨" + }, + { + "key": "signal", + "value": "良好" + }, + { + "key": "satellite", + "value": "36颗" + } + ], + "order_flight_task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "order_number": "LOCAL-MOCK-ORDER-901", + "plane_status": { + "connected": true, + "poll_hint_ms": 5000, + "scenic_id": 128 + }, + "scenic": { + "id": 128, + "name": "本地模拟景区" + }, + "scenic_spot": { + "id": 301, + "name": "模拟点位" + }, + "task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "ui": { + "message": "本地模拟状态回查:拍摄中,未向设备发送指令。", + "phase": "shooting", + "title": "无人机正在拍摄中(模拟)" + } + }, + "msg": "local mock success" + } + } + ] +} diff --git a/docs/9.9.1/交付成片UI实现说明.md b/docs/9.9.1/交付成片UI实现说明.md index 509578f..2b52344 100644 --- a/docs/9.9.1/交付成片UI实现说明.md +++ b/docs/9.9.1/交付成片UI实现说明.md @@ -2,6 +2,8 @@ 实现日期:2026-10-23。分支:`dev_9_9_1`。 +2026-10-30:正式订单列表已接入交付方式弹窗,云端继续复用已接接口,见[订单交付方式弹窗](订单交付方式弹窗-2026-10-30.md)。下文为原本地演示的历史实现说明。 + ## 范围与依据 本轮按用户指示搭建交付成片 UI,收款页面继续暂缓,不接真实接口。采用[新版原型复核](UI更新复核-2026-10-23.md)中的交付方式、点位选择、演示视频选择、上传队列、整单核对、确认码和确认记录样式。 diff --git a/docs/9.9.1/景区空境库UI对齐-2026-10-30.md b/docs/9.9.1/景区空境库UI对齐-2026-10-30.md new file mode 100644 index 0000000..2bedda7 --- /dev/null +++ b/docs/9.9.1/景区空境库UI对齐-2026-10-30.md @@ -0,0 +1,54 @@ +# 景区空境库 UI 对齐记录(2026-10-30) + +## 对照范围 + +依据当日实际打开的[产品体验网页](https://voicestudio.suixinkan.cn/)核对主列表、航线筛选、时间筛选、视频预览及下载状态。页面名称继续使用“景区空境库”,首页权限标识继续使用 `sceniclibrary`。 + +## 本次调整 + +| 区域 | 对齐内容 | +| --- | --- | +| 顶部筛选 | 左对齐文字、右侧箭头,40 点高度、11 点圆角及细边框;采用网页主蓝色 `#066BFF`。 | +| 航线筛选 | 底部抓手、紧凑列表、细分隔线;选中项为蓝字及普通勾号,移除圆形选择框和右上关闭按钮;点选后应用。 | +| 时间筛选 | 月/日两列滚轮、起止日期卡片、文字“全部时间”、底部取消/确定;只展示保留期内已到来的日期。 | +| 视频预览 | 16:9 封面、小型白色播放图标、独立进度条、左右两侧时长/规格信息、航线及时间、通栏蓝色返回按钮;移除右上关闭按钮。 | +| 选择底栏 | 左侧“已选 N 段”,数量蓝色强调;右侧下载按钮,零选择时保留可读的禁用标题。 | +| 下载/暂停 | 摘要与取消同行,下面放进度条和通栏主按钮;下载中保持蓝底、显示加载指示器且禁止重复触发,暂停后可手动继续。 | +| 部分失败 | 摘要及结果说明,上方不再堆叠下载按钮;下方并排“继续选择”和“重试失败”。 | +| 完成 | 摘要及保存结果说明,下方通栏“继续选择素材”;增加实际窗口中的按钮文字宽度回归检查。 | + +## 保留的行为与平台适配 + +- 日期打开后先编辑草稿。与网页一致,从全部时间打开后直接确定会提交当天范围;取消不改变原筛选。“全部时间”仍在确定后提交 `nil/nil`。 +- 月份内部保留年份,处理跨年、闰年、月末、首尾月份截断及夏令时;不把一年简单视作固定秒数。 +- 视频进度来自实际 `AVPlayer` 播放时间,支持暂停、继续、结束重播;关闭时释放观察令牌和播放器,迟到的异步结果不能恢复已关闭页面。 +- 演示封面所标原片时长与包内实际短片时长分别说明,演示下载不写入系统相册。正式素材缺少 URL 时不会回退为演示视频。 +- 使用 UIKit 原生 Sheet、抓手、安全区和滚轮,保留 iOS 平台的弹出动画与边缘外观。 +- 当前正式账号暂无素材,本次有数据页面使用本地演示数据核对;真实非空接口数据映射不属于本次 UI 调整范围。 +- 本次验证只使用模拟器及隔离测试替身,无真机测试、真实相册写入或无人机指令。 + +## 验证结果 + +- `suixinkan-Simulator` / `SimulatorDebug` 构建成功。 +- 最终在 iPhone 17e / iOS 27.0 模拟器运行本模块相关 **67 项测试,全部通过,0 失败、0 跳过**。首轮视觉检查使用 iPhone 18 Pro 模拟器。 +- 覆盖日期跨年、月末、闰年和保留期边界,取消/全部时间确认,真实播放时间与暂停/关闭清理,选择及下载状态切换、失败重试、远程空响应和权限入口。 +- 底栏额外在 320 / 375 / 393 点宽度下检查布局,并在实际 UIWindow 中验证初始完成态和连续状态切换后,按钮标题仍完整单行显示。 +- 修复了加载指示器约束依赖 UIButton 内部标题布局时造成的标题挤窄;指示器现在相对按钮自身定位。 +- 最终测试结果:`/private/tmp/suixinkan-scenic-ui-final-20261030.xcresult`。 +- `git diff --check` 通过;截图已逐张核对。 + +## 模拟器截图 + +以下均为本地演示页面。 + +| 主列表 | 航线筛选 | +| --- | --- | +| ![主列表](scenic-ui-2026-10-30/library.jpg) | ![航线筛选](scenic-ui-2026-10-30/route-filter.jpg) | + +| 时间筛选 | 视频预览 | +| --- | --- | +| ![时间筛选](scenic-ui-2026-10-30/date-filter.jpg) | ![视频预览](scenic-ui-2026-10-30/preview.jpg) | + +| 下载中 | 部分失败 | 完成 | +| --- | --- | --- | +| ![下载中](scenic-ui-2026-10-30/downloading.jpg) | ![部分失败](scenic-ui-2026-10-30/partial-failure.jpg) | ![完成](scenic-ui-2026-10-30/completed.jpg) | diff --git a/docs/9.9.1/景区空镜库UI实现说明.md b/docs/9.9.1/景区空镜库UI实现说明.md index e0f701d..fc0dd0b 100644 --- a/docs/9.9.1/景区空镜库UI实现说明.md +++ b/docs/9.9.1/景区空镜库UI实现说明.md @@ -2,6 +2,18 @@ 实现日期:2026-10-26。分支:`dev_9_9_1`。 +## 2026-10-29 接口接入进度 + +- 正式入口为 `sceniclibrary`,使用当前账号和景区,进入后请求 `GET /api/app/scenic-media/sessions`。列表支持加载、空态、下拉刷新、错误重试及日期参数;正式入口不会生成演示素材。 +- 依据朱工《随心瞰9.9.1-App机巢与素材库接口.md》接入列表和 `session-detail?scenic_media_id=...` 只读 API。测试环境实测沿用 `token` 请求头和 `code=100000/msg` 包装,而非文档示意的 `code=0/message`。保留期上限实测为 365 天。 +- 已验证列表根字段 `list/groups/total/page/page_size/retention_days/retention_tips/filter/filter_options.air_lines`;当前景区 271 的 90 天及 365 天查询均为空。用户确认目前尚未准备数据。 +- **尚未完成非空展示映射**:文档缺少场次、航线筛选项、详情场次身份、素材 ID、文件类型、时长/大小单位及封面字段的完整示例。API 无损保留这些对象;非空响应暂提示加载失败,不能将未知记录误当空库,也不猜 ID 请求详情。需朱工提供非空 `sessions` 与 `session-detail` 成功 JSON 后继续接入分组、航线筛选、翻页和片段展示。 +- 已准备真实封面加载、远程原片预览、串行下载和 Photos 添加保存能力。仅保存成功计为完成,支持取消、暂停和重试去重;这些能力仍需非空素材映射后才能从正式列表使用。 +- `mark-download` 仅接受 `order_flight_task_media.id`,不用于本空境库。本文档所述空境数据源为 `scenic_media`、`view_album/view_album_detail`,后台新增入口需后端确认。 +- 仅按用户要求运行模拟器测试:首轮 55 项全部通过;生命周期修正后追加 13 项 UI/加载回归全部通过。下载测试使用替身验证 HTTP 下载与相册保存的成功/失败/取消边界,未真实保存业务素材。不调用设备、飞行或订单写接口。 + +以下为初版 UI 历史记录。 + ## 范围与入口 依据 2026-10-26 实际查看的[产品体验网页](https://voicestudio.suixinkan.cn/)搭建独立景区空镜库。页面标题沿用原型的“景区素材”,采用白底、航线/时间筛选、首段大图和后续双列卡片、按拍摄时间分组、底部固定下载栏。 diff --git a/docs/9.9.1/素材库UI实现说明.md b/docs/9.9.1/素材库UI实现说明.md index f6c7ced..8d01df7 100644 --- a/docs/9.9.1/素材库UI实现说明.md +++ b/docs/9.9.1/素材库UI实现说明.md @@ -4,6 +4,8 @@ 后续更新:成片交付入口已在下一轮接通,参见[交付成片 UI 实现说明](交付成片UI实现说明.md);下文保留素材库交付时的范围记录。 +2026-10-29:已将原型布局适配到读取真实接口的 `DroneDockMaterialsViewController`,并更新本地下载演示各状态的视觉组合。范围、边界及验证见[订单素材库 UI 对齐](订单素材库UI对齐-2026-10-29.md)。真实下载与上传重试仍未开放,不将演示进度或结果用于真实订单。 + ## 本轮范围 接通工作台、我的拍摄订单和当前任务的素材入口,实现本地订单素材库、照片/视频预览、多选及下载演示。布局按[新版原型复核](UI更新复核-2026-10-23.md)中的素材页面:订单摘要、点位标签、拍摄记录分组、两列缩略图、固定下载底栏。 diff --git a/docs/9.9.1/订单交付方式弹窗-2026-10-30.md b/docs/9.9.1/订单交付方式弹窗-2026-10-30.md new file mode 100644 index 0000000..660b609 --- /dev/null +++ b/docs/9.9.1/订单交付方式弹窗-2026-10-30.md @@ -0,0 +1,41 @@ +# 我的拍摄订单:交付方式弹窗 + +依据:[产品体验网页](https://voicestudio.suixinkan.cn/),2026-10-30 实际核对“我的拍摄订单 → 交付成片 → 面对面闪传 / 云端上传”。 + +## 本轮交互 + +- 订单卡片的主、副“交付成片”按钮均先打开底部弹窗,显示游客、方式卡片、关闭按钮和底部说明。 +- 面对面闪传显示“闪传流程待确认”,可返回方式选择或改用云端上传;不建立热点、不调用设备或传输接口。 +- 选择云端后在同一弹窗导航内打开共用的真实交付页面。订单列表保留在下层,任务不默认选中。 +- 云端可以返回方式选择;关闭云端或返回方式后关闭弹窗,会重新读取订单列表。仅打开、取消方式弹窗保留当前筛选和已加载订单,不额外刷新。 +- 云端页面禁止下拉直接关闭,提供明确关闭按钮;正在准备文件、上传或保存时需先确认停止。取消侧滑返回后会恢复云端页的导航栏、大弹窗和退出保护。 +- 素材库的任务交付入口继续保留原导航和任务预选方式。 + +## 接口边界 + +| 操作 | 接口行为 | +| --- | --- | +| 打开交付方式、切换闪传说明、关闭方式弹窗 | 无新增请求 | +| 选择云端上传 | 张工 `GET orders/detail`、`GET tasks` | +| 切换点位、选择任务 | 使用已读取的数据,本地筛选 | +| 选择视频并提交 | 沿用既有 STS/OSS 上传、张工 `POST tasks/film`,本轮不改变协议 | + +正式云端页仍按当前后端协议:明确选择点位和任务,每个任务交付一个视频;已有成片需要确认替换。网页的多视频演示不作为新增接口能力。只调整交付入口及弹窗导航,不执行真实上传验收。 + +## 验证与截图 + +使用 iPhone 18 Pro 模拟器、隔离窗口和网络/上传替身验证。测试图片中的订单、任务和视频均为合成数据,不代表后端真实交付成功。禁飞保护保持生效,本轮未创建真实任务或发送设备指令。 + +构建通过;共 24 项相关用例最终通过,覆盖订单主副入口、重复点击、取消保留筛选、闪传返回、云端返回、任务不预选、上传/失败/替换原有流程及素材库入口兼容。首轮退出确认测试因弹窗动画未结束而提前断言,补齐等待条件后,与取消侧滑恢复测试及订单云端入口一并复跑,3 项均通过。 + +- 订单及交付原有测试首轮:22 通过、1 失败;新增和修正后的定向复跑:3 通过、0 失败。 +- 复跑结果包:`test_sim_2026-10-30T01-45-41-769Z_pid48214_67f25551.xcresult`。 +- `git diff --check` 通过。构建中的其他模块既有警告未在本轮调整。 + +交付方式弹窗: + +![交付方式弹窗(模拟数据)](order-delivery-sheet-2026-10-30/delivery-method.png) + +弹窗内复用的云端交付页: + +![云端交付(模拟数据)](order-delivery-sheet-2026-10-30/cloud-delivery.png) diff --git a/docs/9.9.1/订单素材库UI对齐-2026-10-29.md b/docs/9.9.1/订单素材库UI对齐-2026-10-29.md new file mode 100644 index 0000000..c1a677c --- /dev/null +++ b/docs/9.9.1/订单素材库UI对齐-2026-10-29.md @@ -0,0 +1,63 @@ +# 订单素材库 UI 对齐 + +核对日期:2026-10-29。依据:[产品交互体验网页](https://voicestudio.suixinkan.cn/)。本轮在独立浏览器标签中实际切换并检查页面状态,未操作真实后端或无人机。 + +## 网页布局与状态 + +| 区域/状态 | 网页表现 | iOS 对应处理 | +| --- | --- | --- | +| 订单信息 | 游客标题与小状态徽章同排;下一行订单号,再下一行购买/已拍/剩余次数 | 使用真实订单摘要,未知次数仍为“—” | +| 点位筛选 | 浅蓝选中标签、白底描边未选标签 | 点位身份来自 `orders/detail.spot`,切换仍只请求 `tasks` | +| 拍摄记录 | 次数与“最新在前”提示、右侧全选;点位标题和交付按钮同排,航线/时间/记录序号为次行 | 保持任务身份、顺序和原交付入口权限;不把任务总数当成成功拍摄次数 | +| 上传中 | 两列灰色缩略图,中央播放/图片占位,无勾选,蓝色状态文字 | 根据单文件 `upload_status=2` 展示 | +| 上传完成/未选择 | 两列 16:9 缩略图、右上角选择圆圈、绿色“上传完成 · 可下载” | 只有明确就绪且有效地址的原素材可选择与预览 | +| 已选择 | 蓝色勾选与边框,固定底栏更新所选数量,主按钮启用 | 选择使用任务 ID+素材 ID,不包含独立成片;切点/刷新后清空 | +| 上传失败 | 红色叉圈、文件名右侧重试入口、红色失败说明 | 失败原因保留;正式页重试入口禁用,因为尚无上传重试接口 | +| 下载中/重试中 | 底栏显示本次数量、完成数量、进度条、保持页面开启提示和禁用主按钮 | 通过本地演示验证布局,未接真实下载/保存 | +| 部分下载失败 | 橙色警示图标、成功/失败数量、重试失败素材主按钮及选择其他素材 | 本地演示只重试失败项,不重复处理完成项 | +| 下载完成 | 绿色勾圈、完成说明、继续选择按钮及描边交付按钮 | 本地演示明确未写入系统相册,不能作为真实下载成功 | +| 离开确认 | 下载仍进行中的提示、离开并停止/继续下载 | 保留 UIKit 确认交互及演示批次暂停行为 | +| 相册权限不足 | 无法保存到相册提示,暂不下载/去设置 | 本地演示不请求 Photos 权限,不打开设置或伪装已保存 | +| 无任务/读取失败/首次加载 | 原型基础布局之外的真实接口边界状态 | 居中图标、明确标题/说明,错误提供只读重试 | +| 任务尚无文件 | 文件数量不能从空数组推测 | 按任务 `material_status` 区分待生成、上传中、失败或暂无可用文件 | + +正式页仅调整展示与本地选择,不新增真实下载、上传重试、素材同步或飞控写入。`film` 继续作为独立交付成片展示,不计入原素材选择。 + +## 验收入口 + +- `--dock-materials-mock=ready`:通过真实页面渲染内存素材数据。还支持 `uploading`、`uploadFailed`、`mixed`、`empty`、`loading`、`error`、`taskUploading`、`taskFailed`、`film`。订单、任务和媒体全部为合成数据,图片来自随包演示资源。 +- `--dock-ui-materials-preview --dock-materials-scenario=downloading`:原有本地下载演示。可替换为 `paused`、`partialFailure`、`permissionDenied`、`saveFailure`、`completed`,不连接后端、不保存系统相册。 + +## 验证结果 + +- iPhone 18 Pro / iOS 27 模拟器;使用 `suixinkan-Simulator` + `SimulatorDebug`,未运行真机。 +- 相关 API、选择状态、页面、预览和演示流程共覆盖 75 项测试,已全部通过。首次发现旧测试仍从 `title(for:)` 读取配置式按钮标题,更新为 `configuration.title` 后复测通过。 +- 最后一轮正式页、状态截图、演示流程和固定底栏 19/19 通过;随后白色勾选图标和加载指示器调整后,两项状态/选择用例再次 2/2 通过,并重新导出 21 张测试截图。 +- 375pt、402pt 两种宽度覆盖 10 个正式页隔离场景;校验底栏不覆盖列表、按钮触控高度至少 44pt、缩略图比例 16:9、未就绪素材不可勾选,预览返回后仍保留选择。 +- 实际启动模拟器核对上传就绪与演示下载失败/完成状态。运行日志未发现 Auto Layout 冲突或 API 请求;未写入系统相册。 +- 图片为本地合成订单与随包演示资源,不能作为真实接口成功或实际下载成功的证据。 + +测试结果包(本机): + +- 19 项页面测试:`~/Library/Developer/XcodeBuildMCP/workspaces/suixinkan-a3033d697ba3/result-bundles/test_sim_2026-10-29T10-44-05-564Z_pid15238_fa6eb119.xcresult` +- 最终 2 项状态/选择测试:`~/Library/Developer/XcodeBuildMCP/workspaces/suixinkan-a3033d697ba3/result-bundles/test_sim_2026-10-29T10-51-59-931Z_pid15238_d80b3ec7.xcresult` + +## 状态截图 + +### 上传完成与已选择 + +![上传完成](materials-ui-2026-10-29/ready-402.png) +![已选择](materials-ui-2026-10-29/selected-402.png) + +### 上传中、失败与混合状态 + +![上传中](materials-ui-2026-10-29/uploading-402.png) +![上传失败](materials-ui-2026-10-29/uploadFailed-402.png) +![375pt 混合状态](materials-ui-2026-10-29/mixed-375.png) + +### 本地下载演示 + +![部分失败](materials-ui-2026-10-29/demo-partialFailure.jpg) +![演示完成](materials-ui-2026-10-29/demo-completed.jpg) + +其他边界状态见同目录中的 `empty`、`error`、`loading`、`taskUploading`、`taskFailed`、`film` 截图。 diff --git a/suixinkan/Core/Networking/APIClient.swift b/suixinkan/Core/Networking/APIClient.swift index 63aa342..5d681b0 100644 --- a/suixinkan/Core/Networking/APIClient.swift +++ b/suixinkan/Core/Networking/APIClient.swift @@ -11,6 +11,9 @@ protocol URLSessionProtocol { func data(for request: URLRequest) async throws -> (Data, URLResponse) } +/// 仅供完全在内存中返回预设响应的传输实现,不得转发至 URLSession 或外部服务。 +protocol LocalSimulationURLSession: URLSessionProtocol {} + extension URLSession: URLSessionProtocol {} @MainActor @@ -63,7 +66,9 @@ final class APIClient { _ apiRequest: APIRequest, tokenOverride: String? = nil ) async throws -> Response { - let request = try makeURLRequest(apiRequest, tokenOverride: tokenOverride) + let request = try DeviceCommandDebugPolicy.prepare( + makeURLRequest(apiRequest, tokenOverride: tokenOverride), + isLocalSimulation: session is any LocalSimulationURLSession) logRequest(request, includeBody: apiRequest.logsPayload) let data: Data @@ -120,6 +125,7 @@ final class APIClient { } request.httpBody = jsonBody.data(using: .utf8) + request = try DeviceCommandDebugPolicy.prepare(request, isLocalSimulation: session is any LocalSimulationURLSession) logRequest(request) let data: Data @@ -191,6 +197,7 @@ final class APIClient { request.setValue(token, forHTTPHeaderField: "token") } request.httpBody = body + request = try DeviceCommandDebugPolicy.prepare(request, isLocalSimulation: session is any LocalSimulationURLSession) logRequest(request) let responseData: Data diff --git a/suixinkan/Core/Networking/DeviceCommandDebugPolicy.swift b/suixinkan/Core/Networking/DeviceCommandDebugPolicy.swift new file mode 100644 index 0000000..4df12ef --- /dev/null +++ b/suixinkan/Core/Networking/DeviceCommandDebugPolicy.swift @@ -0,0 +1,55 @@ +import Foundation + +/// 禁飞期间的 Debug 请求边界;模拟器和测试环境均不能视为没有真实设备副作用。 +enum DeviceCommandDebugPolicy { + /// 所有 Debug 构建禁止真实设备操作,没有启动参数或设置开关可临时放行。 + static var blocksLiveRequests: Bool { + #if DEBUG + true + #else + false + #endif + } + + /// 页面与本地拦截共用的说明,不将未发送的请求表述为服务端执行失败。 + static let blockedMessage = "当前禁止真实设备指令,请使用本地模拟调试" + + /// 在日志和传输之前阻断操作请求;允许的状态读取关闭实时设备采集。 + static func prepare(_ request: URLRequest, isLocalSimulation: Bool) throws -> URLRequest { + guard blocksLiveRequests, !isLocalSimulation, let url = request.url else { return request } + let path = "/" + url.path.split(separator: "/").joined(separator: "/") + // 创建虽不直接起飞,但会改变真实订单状态;禁飞调试使用本地待飞任务。 + if path == "/api/yf-handset-app/photog/multi-plane/tasks/create" { + throw DeviceCommandDebugBlockedError() + } + guard path == "/api/app/airport" || path.hasPrefix("/api/app/airport/") else { return request } + let readablePaths: Set = [ + "/api/app/airport/home", "/api/app/airport/plane-status", + "/api/app/airport/shooting", "/api/app/airport/status" + ] + guard request.httpMethod == "GET", readablePaths.contains(path) else { + throw DeviceCommandDebugBlockedError() + } + let liveKey: String + switch path { + case "/api/app/airport/plane-status", "/api/app/airport/shooting": liveKey = "live_battery" + case "/api/app/airport/status": liveKey = "live_metrics" + default: return request + } + guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { throw APIError.invalidURL } + var items = components.queryItems ?? [] + items.removeAll { $0.name == liveKey } + items.append(URLQueryItem(name: liveKey, value: "0")) + components.queryItems = items + guard let safeURL = components.url else { throw APIError.invalidURL } + var safeRequest = request + safeRequest.url = safeURL + return safeRequest + } +} + +/// 明确表示请求在本机被阻断,任何设备指令或任务创建都未发送。 +struct DeviceCommandDebugBlockedError: Error, LocalizedError { + /// 提示使用本地模拟,不伪造后端错误码或成功回执。 + var errorDescription: String? { DeviceCommandDebugPolicy.blockedMessage } +} diff --git a/suixinkan/Features/DroneDock/API/DroneDockStartShootAPI.swift b/suixinkan/Features/DroneDock/API/DroneDockStartShootAPI.swift new file mode 100644 index 0000000..a30e811 --- /dev/null +++ b/suixinkan/Features/DroneDock/API/DroneDockStartShootAPI.swift @@ -0,0 +1,39 @@ +import Foundation + +/// 朱工开始拍摄服务,只使用已创建并召唤的订单飞行任务身份。 +protocol DroneDockStartShooting: Sendable { + /// 提交一次开拍请求;调用方负责校验执行门禁并阻止重复提交。 + @MainActor + func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse +} + +/// start-shoot 合同适配;禁飞期间真实传输仍由统一客户端阻断,仅用 Mock 验证。 +@MainActor +final class DroneDockStartShootAPI: DroneDockStartShooting { + private let client: APIClient + + /// 注入统一客户端,测试使用不会联网的本地模拟传输。 + init(client: APIClient) { self.client = client } + + /// 仅 POST 任务 ID,不附带飞机、航线或未约定的模拟参数,也不自动重试。 + func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse { + try Task.checkCancellation() + guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请返回任务页确认") } + let response: DroneDockStartShootResponse = try await client.send(APIRequest( + method: .post, path: "/api/app/airport/start-shoot", body: StartShootBody(taskID: taskID) + )) + guard let returnedID = response.orderFlightTaskID, returnedID > 0, returnedID == taskID, + response.orderFlightTask?.id == nil || response.orderFlightTask?.id == taskID else { + throw APIError.decodeFailed("开始拍摄回执的任务身份缺失或不一致,请核对原任务状态") + } + return response + } + + /// 开拍只提交订单飞行任务身份,不使用航线任务 ID。 + private struct StartShootBody: Encodable { + let taskID: Int + + /// 朱工开拍请求的 JSON 字段。 + private enum CodingKeys: String, CodingKey { case taskID = "id" } + } +} diff --git a/suixinkan/Features/DroneDock/Models/DroneDockMaterialSelectionID.swift b/suixinkan/Features/DroneDock/Models/DroneDockMaterialSelectionID.swift new file mode 100644 index 0000000..a50c953 --- /dev/null +++ b/suixinkan/Features/DroneDock/Models/DroneDockMaterialSelectionID.swift @@ -0,0 +1,9 @@ +import Foundation + +/// 原素材的选择身份;文件 ID 只在所属任务内唯一,成片不计入原素材选择。 +struct DroneDockMaterialSelectionID: Hashable, Sendable { + /// 所属订单飞行任务。 + let taskID: Int + /// 任务中的原素材 ID。 + let fileID: Int +} diff --git a/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift b/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift index 0b43aaa..b1ee324 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift @@ -22,7 +22,7 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable { let metrics: [DroneDockHomeMetric] /// 景区设备连接与轮询建议,不在客户端改选推荐飞机。 let planeStatus: DroneDockShootingPlaneStatus? - /// 服务端执行门禁只用于展示,本次接入不执行其动作。 + /// 执行门禁参与展示及本地模拟开拍校验,不能解除真实飞控禁令。 let executeGate: DroneDockShootingExecuteGate? /// 服务端拍摄阶段和页面提示。 let ui: DroneDockShootingUI? @@ -169,7 +169,7 @@ struct DroneDockShootingExecuteGate: Decodable, Equatable, Sendable { let code: String? /// 服务端门禁说明。 let message: String? - /// 服务端建议动作,本阶段仅展示。 + /// 服务端建议动作;本地模拟开拍要求明确为 start_shoot。 let primaryAction: String? /// 服务端建议动作名称。 let primaryActionLabel: String? diff --git a/suixinkan/Features/DroneDock/Models/DroneDockStartShootModels.swift b/suixinkan/Features/DroneDock/Models/DroneDockStartShootModels.swift new file mode 100644 index 0000000..8dea5fc --- /dev/null +++ b/suixinkan/Features/DroneDock/Models/DroneDockStartShootModels.swift @@ -0,0 +1,58 @@ +import Foundation + +/// start-shoot 的受理回执;不凭请求成功推断飞行、拍摄或素材已完成。 +struct DroneDockStartShootResponse: Decodable, Equatable, Sendable { + /// 文档约定的订单飞行任务 ID,API 必须核对其与请求一致。 + let orderFlightTaskID: Int? + /// 服务端提供的任务摘要,嵌套身份存在时同样参与核对。 + let orderFlightTask: DroneDockShootingTaskIdentity? + /// 当前任务锁定的飞机,不由客户端选择或覆盖。 + let planeID: Int? + /// 服务端任务 UUID,用于后续核对,不等于订单飞行任务 ID。 + let taskUUID: String? + /// 服务端返回的机场标识,仅保留已有值。 + let airportSN: String? + /// 服务端受理后的阶段文案,最新设备状态由 shooting 单次回查确认。 + let ui: DroneDockShootingUI? + /// 完整 data 的格式化 JSON,保留未知字段与原始类型供模拟联调展示。 + let dataJSON: String + + /// 朱工开拍回执字段映射。 + private enum CodingKeys: String, CodingKey { + case orderFlightTaskID = "order_flight_task_id", orderFlightTask = "order_flight_task" + case planeID = "plane_id", taskUUID = "task_uuid", airportSN = "airport_sn", ui + } + + /// 仅解析响应实际提供的字段,不补造任务身份或成功状态。 + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + orderFlightTaskID = try container.decodeIfPresent(Int.self, forKey: .orderFlightTaskID) + orderFlightTask = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .orderFlightTask) + planeID = try container.decodeIfPresent(Int.self, forKey: .planeID) + taskUUID = try container.decodeIfPresent(String.self, forKey: .taskUUID) + airportSN = try container.decodeIfPresent(String.self, forKey: .airportSN) + ui = try container.decodeIfPresent(DroneDockShootingUI.self, forKey: .ui) + let raw = try DroneDockHomeJSONValue(from: decoder) + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + dataJSON = String(decoding: try encoder.encode(DroneDockStartShootJSONSnapshot(value: raw)), as: UTF8.self) + } +} + +/// 将已有 JSON 值完整格式化,不给模拟响应添加后端未提供的字段。 +private struct DroneDockStartShootJSONSnapshot: Encodable { + let value: DroneDockHomeJSONValue + + /// 保留字符串、数字、布尔、空值和嵌套对象,不追加业务码包裹。 + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch value { + case .object(let object): try container.encode(object.mapValues { DroneDockStartShootJSONSnapshot(value: $0) }) + case .array(let array): try container.encode(array.map { DroneDockStartShootJSONSnapshot(value: $0) }) + case .string(let text): try container.encode(text) + case .number(let number): try container.encode(number) + case .bool(let flag): try container.encode(flag) + case .null: try container.encodeNil() + } + } +} diff --git a/suixinkan/Features/DroneDock/Models/DroneDockTaskPresentation.swift b/suixinkan/Features/DroneDock/Models/DroneDockTaskPresentation.swift index c2521da..7900583 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockTaskPresentation.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockTaskPresentation.swift @@ -26,11 +26,11 @@ enum DroneDockTaskDisplayPhase: String, Equatable, Sendable { case readError } -/// 任务状态区可呈现的动作;开始与恢复在本轮仅禁用展示,不发送飞控。 +/// 任务状态区可呈现的动作;开始仅在明确注入本地模拟服务时可用,真实飞控保持禁用。 enum DroneDockTaskDisplayAction: Equatable, Sendable { /// 重新读取同一任务。 case refresh - /// 开始拍摄占位动作,本轮禁用。 + /// 开始拍摄动作;真实入口无服务,只有本地模拟可提交验证。 case start /// 恢复拍摄占位动作,本轮禁用。 case resume @@ -56,7 +56,7 @@ struct DroneDockTaskPresentation: Equatable, Sendable { let action: DroneDockTaskDisplayAction /// 主动作名称,无动作时为 nil。 let actionTitle: String? - /// 是否可触发动作;未对接的开始、恢复和重新召唤始终为 false。 + /// 是否可触发动作;真实开始、恢复和重新召唤保持禁用。 let isActionEnabled: Bool /// 主动作下方的真实设备限制说明,未提供时不展示。 let actionNote: String? diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockMaterialsViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockMaterialsViewModel.swift index 559d7b0..7a9c475 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockMaterialsViewModel.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockMaterialsViewModel.swift @@ -24,6 +24,25 @@ final class DroneDockMaterialsViewModel { private(set) var tasksErrorMessage: String? /// 点位标签始终来自整单购买快照,不从当前任务推导。 var spots: [DroneDockMaterialSpot] { detail?.spots ?? [] } + /// 当前范围内已选择的就绪原素材,不包含独立交付成片。 + private(set) var selectedMaterialIDs: Set = [] + /// 只有完整读取成功且具备有效文件地址的原素材允许选择。 + var selectableMaterialIDs: Set { + guard detail != nil, !isLoading, !isLoadingTasks, + detailErrorMessage == nil, tasksErrorMessage == nil else { return [] } + return Set(tasks.flatMap { task in + task.materials.filter { $0.previewURL != nil }.map { + DroneDockMaterialSelectionID(taskID: task.id, fileID: $0.id) + } + }) + } + /// 当前选择数量仅用于界面展示,不表示已经下载或保存。 + var selectedCount: Int { selectedMaterialIDs.count } + /// 空列表不展示全选;全部当前可用原素材被选中时才标记全选。 + var allDownloadableSelected: Bool { + let selectable = selectableMaterialIDs + return !selectable.isEmpty && selectedMaterialIDs == selectable + } private let service: any DroneDockMaterialsServing private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext @@ -39,6 +58,38 @@ final class DroneDockMaterialsViewModel { self.currentContext = currentContext } + /// 勾选只修改本地状态;无效、未就绪或其他任务的素材不会进入选择集合。 + @MainActor + func toggleSelection(taskID: Int, fileID: Int) { + guard acceptsSelectionContext() else { return } + let identifier = DroneDockMaterialSelectionID(taskID: taskID, fileID: fileID) + guard selectableMaterialIDs.contains(identifier) else { return } + if selectedMaterialIDs.contains(identifier) { + selectedMaterialIDs.remove(identifier) + } else { + selectedMaterialIDs.insert(identifier) + } + } + + /// 全选仅覆盖当前点位可用的原素材,不跨点位、订单或成片扩大范围。 + @MainActor + func toggleSelectAll() { + guard acceptsSelectionContext() else { return } + let selectable = selectableMaterialIDs + guard !selectable.isEmpty else { return } + selectedMaterialIDs = selectedMaterialIDs == selectable ? [] : selectable + } + + @MainActor + private func acceptsSelectionContext() -> Bool { + guard context.hasSameIdentity(as: currentContext()) else { + invalidate() + detailErrorMessage = "账号或景区已变化,请返回工作台重新进入" + return false + } + return true + } + /// 先刷新整单摘要,再读取任务;保留仍在购买快照中的点位筛选。 @MainActor func refresh() async { @@ -156,6 +207,7 @@ final class DroneDockMaterialsViewModel { @MainActor private func clearTasks() { tasks = [] + selectedMaterialIDs = [] total = nil tasksErrorMessage = nil } diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift index 7a3a9bb..e9abf2a 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift @@ -43,6 +43,7 @@ final class DroneDockPreparationViewModel { private let planeStatusService: any DroneDockPlaneStatusServing private let taskCreationService: any DroneDockTaskCreating private let shootService: any DroneDockShootServing + private let allowsTaskSubmission: Bool private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext private var generation = 0 private var planeStatusGeneration = 0 @@ -62,6 +63,7 @@ final class DroneDockPreparationViewModel { planeStatusService: any DroneDockPlaneStatusServing, taskCreationService: any DroneDockTaskCreating, shootService: any DroneDockShootServing, + allowsTaskSubmission: Bool = true, currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) { self.context = context self.order = order @@ -69,12 +71,13 @@ final class DroneDockPreparationViewModel { self.planeStatusService = planeStatusService self.taskCreationService = taskCreationService self.shootService = shootService + self.allowsTaskSubmission = allowsTaskSubmission self.currentContext = currentContext } /// 当前阶段只创建待飞任务,不以设备电量或位置作为创建任务条件。 var canCreateTask: Bool { - guard context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask, + guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask, !hasCreatedTask, !taskCreationOutcomeUnknown, errorMessage == nil, let info = projectInfo, info.order.canCreateTask == true, let total = info.order.shotTotal, total > 0, @@ -86,6 +89,9 @@ final class DroneDockPreparationViewModel { return info.order.orderNumber == number && info.order.projectID == projectID } + /// 当前入口是否被禁飞限制禁止提交,用于提供独立模拟入口而不放开真实写入。 + var isTaskSubmissionBlocked: Bool { !allowsTaskSubmission } + /// 提交中和已有回执/不确定结果时冻结点位航线,避免显示与任务归属不一致。 var isTaskSelectionLocked: Bool { isCreatingTask || isSummoning || isPerformingPrimaryAction || hasCreatedTask || taskCreationOutcomeUnknown @@ -107,7 +113,7 @@ final class DroneDockPreparationViewModel { /// 首次允许创建再召唤;明确业务拒绝后可对同任务重试,成功和未知结果锁定。 var isPrimaryActionEnabled: Bool { - guard context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask, + guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask, !isSummoning, !isPerformingPrimaryAction, !taskCreationOutcomeUnknown, !hasSubmittedSummon, !summonOutcomeUnknown else { return false } if let createdTask { return createdTask.taskID > 0 } @@ -117,7 +123,8 @@ final class DroneDockPreparationViewModel { /// 主按钮串接创建与召唤;已有任务跳过创建,成功后的导航由页面处理。 @MainActor func prepareAndSummon(onStateChange: @escaping @MainActor () -> Void = {}) async { - guard isPrimaryActionEnabled else { return } + // 禁飞调试在整条链开始前阻断,避免先残留真实待飞任务再拦截召唤。 + guard allowsTaskSubmission, isPrimaryActionEnabled else { return } primaryActionGeneration &+= 1 let actionGeneration = primaryActionGeneration isPerformingPrimaryAction = true @@ -136,7 +143,7 @@ final class DroneDockPreparationViewModel { /// 对明确创建成功的任务发送一次召唤;只有明确业务拒绝允许之后再次提交。 @MainActor private func summonCreatedTask(onStateChange: @escaping @MainActor () -> Void) async { - guard !isCreatingTask, !isSummoning, !taskCreationOutcomeUnknown, + guard allowsTaskSubmission, !isCreatingTask, !isSummoning, !taskCreationOutcomeUnknown, !hasSubmittedSummon, !summonOutcomeUnknown, let taskID = createdTask?.taskID, taskID > 0 else { return } summonGeneration &+= 1 @@ -162,8 +169,13 @@ final class DroneDockPreparationViewModel { hasSubmittedSummon = true summonOutcomeUnknown = false } catch { + if error is DeviceCommandDebugBlockedError, summonGeneration == requestGeneration { + didSendSummon = false + } guard acceptsSummon(requestGeneration, taskID: taskID) else { return } - if case APIError.serverCode = error { + if error is DeviceCommandDebugBlockedError { + shootErrorMessage = DeviceCommandDebugPolicy.blockedMessage + } else if case APIError.serverCode = error { shootErrorMessage = error.localizedDescription } else { markSummonUnknown(reason: error.localizedDescription) @@ -189,7 +201,7 @@ final class DroneDockPreparationViewModel { /// 点击后先校验最新购买配置,再发送一次创建请求;成功留在准备页供核对。 @MainActor func createTask(onStateChange: @escaping @MainActor () -> Void = {}) async { - guard canCreateTask, let spotID = selectedSpotID, let routeID = selectedRouteID, + guard allowsTaskSubmission, canCreateTask, let spotID = selectedSpotID, let routeID = selectedRouteID, let number = order.orderNumber, let projectID = order.projectID else { return } taskCreationGeneration &+= 1 let requestGeneration = taskCreationGeneration @@ -238,8 +250,13 @@ final class DroneDockPreparationViewModel { hasCreatedTask = true taskCreationOutcomeUnknown = false } catch { + if error is DeviceCommandDebugBlockedError, taskCreationGeneration == requestGeneration { + didSendTaskCreation = false + } guard acceptsTaskCreation(requestGeneration) else { return } - if didSendTaskCreation { + if error is DeviceCommandDebugBlockedError { + taskCreationErrorMessage = DeviceCommandDebugPolicy.blockedMessage + } else if didSendTaskCreation { if case APIError.serverCode = error { taskCreationErrorMessage = error.localizedDescription } else { @@ -414,6 +431,7 @@ final class DroneDockPreparationViewModel { if isCreatingTask { return "正在创建任务…" } if isSummoning { return "正在召唤无人机…" } if hasSubmittedSummon { return "查看拍摄任务" } + if !allowsTaskSubmission { return "仅限模拟调试" } if summonOutcomeUnknown { return "召唤结果待核对" } if hasCreatedTask { return shootErrorMessage == nil ? "确认并召唤" : "重试召唤" } if taskCreationOutcomeUnknown { return "结果待核对" } @@ -426,6 +444,7 @@ final class DroneDockPreparationViewModel { if isCreatingTask { return "正在创建待飞任务,请勿重复点击" } if isSummoning { return "任务已创建,正在提交召唤请求" } if creationContextInvalidated, let errorMessage { return errorMessage } + if !allowsTaskSubmission && !hasSubmittedSummon { return DeviceCommandDebugPolicy.blockedMessage } if let createdTask { if hasSubmittedSummon { return "任务 \(createdTask.taskID) 的召唤请求已提交,请等待任务状态更新" } if let shootErrorMessage { return shootErrorMessage } diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift index f35d4b5..b4038a2 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift @@ -1,6 +1,6 @@ import Foundation -/// 真实拍摄任务页只读状态,只按准备页传入的既有任务 ID 读取 shooting。 +/// 拍摄任务状态及可选开拍流程,始终复用同一任务;禁飞调试仅为本地模拟注入开拍服务。 final class DroneDockShootingTaskViewModel { /// 页面绑定的账号、景区和门店身份。 let context: DroneDockHomeContext @@ -14,27 +14,47 @@ final class DroneDockShootingTaskViewModel { private(set) var isLoading = false /// 读取失败或身份变化时的提示。 private(set) var errorMessage: String? + /// 开拍提交及其后单次状态核对期间禁用重复操作,保留之前的显示快照。 + private(set) var isStartingShooting = false + /// 开拍业务拒绝、本地拦截或结果待核对的说明。 + private(set) var startErrorMessage: String? + /// 已发送但无法确认的开拍请求,不因后续读取仍允许开始而自动解除。 + private(set) var startOutcomeUnknown = false + /// 当前页面是否已收到明确开拍受理回执,收到后不会再次提交。 + private(set) var hasSubmittedStart = false + /// 同任务开拍回执;受理成功不直接替代 shooting 的完整状态快照。 + private(set) var startResponse: DroneDockStartShootResponse? private let service: any DroneDockShootingServing + private let startService: (any DroneDockStartShooting)? private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext private var generation = 0 private var identityInvalidated = false + private var startGeneration = 0 + private var didSendStart = false - /// 只注入读取服务,不依赖创建、召唤、开始拍摄或控制服务。 + /// 默认只读;只有显式注入开拍服务才提供开拍动作,当前正式入口不注入该服务。 init(context: DroneDockHomeContext, taskID: Int, order: DroneDockHomeOrder, service: any DroneDockShootingServing, + startService: (any DroneDockStartShooting)? = nil, currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) { self.context = context self.taskID = taskID self.order = order self.service = service + self.startService = startService self.currentContext = currentContext } /// 页面可见时读取同一任务;刷新及普通失败保留旧快照,身份失效立即清除。 @MainActor func refresh() async { - guard !isLoading, !identityInvalidated else { return } + await refreshSnapshot(allowWhileStarting: false) + } + + @MainActor + private func refreshSnapshot(allowWhileStarting: Bool) async { + guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting else { return } generation &+= 1 let requestGeneration = generation isLoading = true @@ -68,11 +88,14 @@ final class DroneDockShootingTaskViewModel { /// 使旧请求失效;同一身份离页或进入后台可保留快照,账号变化始终清除并停止旧任务读取。 @MainActor func invalidate(preservingSnapshot: Bool = false) { + invalidateStartShooting() generation &+= 1 isLoading = false if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true } if identityInvalidated { response = nil + startResponse = nil + startErrorMessage = nil errorMessage = "账号或景区已变化,请返回工作台重新进入" } else { if !preservingSnapshot { response = nil } @@ -80,6 +103,83 @@ final class DroneDockShootingTaskViewModel { } } + /// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;默认真实页面保持禁用。 + var canStartShooting: Bool { + startService != nil && context.canLoad && taskID > 0 && !identityInvalidated + && !isLoading && !isStartingShooting && errorMessage == nil + && !hasSubmittedStart && !startOutcomeUnknown + && resolvedDisplayPhase().0 == .ready + && response?.executeGate?.canExecute == true + && response?.executeGate?.primaryAction == "start_shoot" + && (response?.currentPlane?.id ?? 0) > 0 + } + + /// 提交一次开拍并单次读取同任务;失败保留原快照,不轮询、不重建、不自动重发。 + @MainActor + func startShooting(onStateChange: @escaping @MainActor () -> Void = {}) async { + guard canStartShooting, let startService else { return } + guard context.hasSameIdentity(as: currentContext()) else { + identityInvalidated = true + invalidate() + onStateChange() + return + } + guard !Task.isCancelled else { return } + let planeID = response?.currentPlane?.id + startGeneration &+= 1 + let requestGeneration = startGeneration + isStartingShooting = true + didSendStart = false + startErrorMessage = nil + onStateChange() + defer { + if startGeneration == requestGeneration { + if Task.isCancelled && didSendStart && !hasSubmittedStart { markStartUnknown() } + isStartingShooting = false + didSendStart = false + onStateChange() + } + } + guard acceptsStart(requestGeneration) else { return } + do { + didSendStart = true + let value = try await startService.startShooting(taskID: taskID) + guard acceptsStart(requestGeneration) else { return } + guard value.orderFlightTaskID == taskID, + value.orderFlightTask?.id == nil || value.orderFlightTask?.id == taskID, + value.orderFlightTask?.orderNumber == nil || value.orderFlightTask?.orderNumber == order.orderNumber, + value.orderFlightTask?.scenicID == nil || value.orderFlightTask?.scenicID == context.scenicID, + value.planeID == nil || value.planeID == planeID else { + throw APIError.decodeFailed("开始拍摄回执与当前任务或飞机不一致,请先核对任务状态") + } + startResponse = value + hasSubmittedStart = true + startOutcomeUnknown = false + onStateChange() + guard acceptsStart(requestGeneration) else { return } + await refreshSnapshot(allowWhileStarting: true) + } catch { + if error is DeviceCommandDebugBlockedError, startGeneration == requestGeneration { didSendStart = false } + guard acceptsStart(requestGeneration) else { return } + if error is DeviceCommandDebugBlockedError { + startErrorMessage = DeviceCommandDebugPolicy.blockedMessage + } else if case APIError.serverCode = error { + startErrorMessage = error.localizedDescription + } else { + markStartUnknown(reason: error.localizedDescription) + } + } + } + + /// 离页或进入后台后拒绝迟到回执;已发而未确认的请求保留待核对锁。 + @MainActor + func invalidateStartShooting() { + if isStartingShooting && didSendStart && !hasSubmittedStart { markStartUnknown() } + startGeneration &+= 1 + isStartingShooting = false + didSendStart = false + } + /// 优先使用当前接口标题,缺失时展示当前接口的点位和航线名称。 var title: String { if let title = usable(response?.header?.title) { return title } @@ -111,13 +211,18 @@ final class DroneDockShootingTaskViewModel { ?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认" } - /// 保留服务端阶段说明与执行门禁原因;本模块不执行门禁给出的动作。 + /// 保留服务端阶段说明;未确认的开拍结果明确提示核对,不伪装为正在拍摄。 var statusMessage: String { if response == nil { if let errorMessage { return errorMessage } if isLoading { return "正在读取当前拍摄任务" } } if resolvedDisplayPhase().0 == .failed { return failureMessage } + if startOutcomeUnknown, let startErrorMessage { return startErrorMessage } + if resolvedDisplayPhase().0 == .ready { + if let startErrorMessage { return startErrorMessage } + if hasSubmittedStart { return "开始拍摄请求已受理,请刷新确认任务状态" } + } return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—" } @@ -138,10 +243,15 @@ final class DroneDockShootingTaskViewModel { let actionTitle: String? let enabled: Bool switch phase { + case .ready where hasSubmittedStart || startOutcomeUnknown: + action = .refresh + actionTitle = "刷新状态" + enabled = !identityInvalidated case .ready: action = .start - actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "开始拍摄" - enabled = false + actionTitle = isStartingShooting ? "正在提交开拍…" + : startErrorMessage == nil ? (usable(response?.executeGate?.primaryActionLabel) ?? "开始拍摄") : "重试开始拍摄" + enabled = canStartShooting case .paused where response?.executeGate?.canExecute == true: action = .resume actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "继续拍摄" @@ -161,7 +271,7 @@ final class DroneDockShootingTaskViewModel { } return DroneDockTaskPresentation(phase: phase, title: title, message: message, deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle, - isActionEnabled: enabled && !isLoading && !identityInvalidated && (errorMessage == nil || action == .refresh), + isActionEnabled: enabled && !isLoading && !isStartingShooting && !identityInvalidated && (errorMessage == nil || action == .refresh), actionNote: phase == .failed ? retryUnavailableNote : nil) } @@ -189,6 +299,22 @@ final class DroneDockShootingTaskViewModel { return !Task.isCancelled } + @MainActor + private func acceptsStart(_ requestGeneration: Int) -> Bool { + guard startGeneration == requestGeneration else { return false } + guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else { + identityInvalidated = true + invalidate() + return false + } + return !Task.isCancelled + } + + private func markStartUnknown(reason: String? = nil) { + startOutcomeUnknown = true + startErrorMessage = (reason.map { "\($0)。" } ?? "") + "开始拍摄结果待核对,请刷新任务状态,勿重复提交" + } + private func matchesIdentity(_ value: DroneDockShootingResponse) -> Bool { let taskIDs = [value.orderFlightTask?.id, value.task?.id].compactMap { $0 } let orderNumbers = [value.orderNumber, value.orderFlightTask?.orderNumber, diff --git a/suixinkan/Features/Home/Services/HomeRouteHandler.swift b/suixinkan/Features/Home/Services/HomeRouteHandler.swift index 327c138..8d8ac66 100644 --- a/suixinkan/Features/Home/Services/HomeRouteHandler.swift +++ b/suixinkan/Features/Home/Services/HomeRouteHandler.swift @@ -83,8 +83,7 @@ enum HomeRouteHandler { let context = ScenicMaterialContext(userID: session.userId, scenicID: String(session.currentScenicId), scenicName: session.currentScenicName) - // 素材接口尚未接入,正式入口使用当前景区空态,避免生成预览素材。 - let viewModel = ScenicMaterialsViewModel(context: context, routes: [], groups: []) + let viewModel = ScenicMaterialsViewModel(context: context, isRemote: true) viewController.navigationController?.pushViewController(ScenicMaterialsViewController(viewModel: viewModel), animated: true) case "checkin_points": viewController.navigationController?.pushViewController(PunchPointListViewController(), animated: true) diff --git a/suixinkan/Features/ScenicMaterials/API/ScenicMaterialsAPI.swift b/suixinkan/Features/ScenicMaterials/API/ScenicMaterialsAPI.swift new file mode 100644 index 0000000..24f45e0 --- /dev/null +++ b/suixinkan/Features/ScenicMaterials/API/ScenicMaterialsAPI.swift @@ -0,0 +1,43 @@ +import Foundation + +/// 景区空境库的只读场次及详情接口,素材下载不回写订单素材状态。 +protocol ScenicMaterialsServing: Sendable { + /// 按当前景区及筛选分页读取场次。 + @MainActor + func sessions(query: ScenicMaterialsQuery) async throws -> ScenicMaterialsSessionsResponse + /// 使用场次身份读取完整片段信息和授权文件地址。 + @MainActor + func sessionDetail(scenicMediaID: Int) async throws -> ScenicMaterialsSessionDetailResponse +} + +/// 朱工景区空境库接口,复用部署环境验证过的 token 鉴权和统一业务包。 +@MainActor +final class ScenicMaterialsAPI: ScenicMaterialsServing { + private let client: APIClient + + /// 注入统一网络客户端,单元测试可使用 MockURLSession。 + init(client: APIClient) { self.client = client } + + /// 验证请求范围及响应页码,避免拼入其他页或其他筛选的数据。 + func sessions(query: ScenicMaterialsQuery) async throws -> ScenicMaterialsSessionsResponse { + let response: ScenicMaterialsSessionsResponse = try await client.send(APIRequest( + method: .get, path: "/api/app/scenic-media/sessions", queryItems: try query.queryItems(), logsPayload: false + )) + guard response.page == query.page, response.pageSize == query.pageSize, + response.retentionDays == query.retentionDays, + response.filter.airLineID == (query.airLineID ?? 0), + response.filter.dateFrom == (query.dateFrom ?? ""), response.filter.dateTo == (query.dateTo ?? "") else { + throw APIError.decodeFailed("空境库场次与当前查询条件不一致,请刷新重试") + } + return response + } + + /// 只传文档定义的 scenic_media_id,不传订单、任务或机巢身份。 + func sessionDetail(scenicMediaID: Int) async throws -> ScenicMaterialsSessionDetailResponse { + guard scenicMediaID > 0 else { throw APIError.networkFailed("空境场次无效,请刷新重试") } + return try await client.send(APIRequest( + method: .get, path: "/api/app/scenic-media/session-detail", + queryItems: [URLQueryItem(name: "scenic_media_id", value: String(scenicMediaID))], logsPayload: false + )) + } +} diff --git a/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialDatePickerOptions.swift b/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialDatePickerOptions.swift new file mode 100644 index 0000000..d6c5732 --- /dev/null +++ b/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialDatePickerOptions.swift @@ -0,0 +1,74 @@ +import Foundation + +/// 为月、日两列滚轮提供保留期内的真实日期,月份保留年份以正确处理跨年。 +struct ScenicMaterialDatePickerOptions { + /// 一个月中实际可选的日期;首月和末月只包含保留期覆盖的部分。 + struct Month { + /// 日历中的年份,供跨年识别及辅助功能使用。 + let year: Int + /// 日历中的月份。 + let number: Int + /// 当前月份内按先后排列且允许选择的日期。 + let dates: [Date] + } + + /// 包含端点、按日归一化的最早日期。 + let minimumDate: Date + /// 包含端点、按日归一化的最晚日期。 + let maximumDate: Date + /// 从最早到最晚排列的可选月份。 + let months: [Month] + private let calendar: Calendar + + /// 将闭区间展开为有限选项,不依赖每月天数或一天固定为 24 小时的假设。 + init(minimumDate: Date, maximumDate: Date, calendar: Calendar) { + self.calendar = calendar + let minimum = calendar.startOfDay(for: minimumDate) + let maximum = max(minimum, calendar.startOfDay(for: maximumDate)) + self.minimumDate = minimum + self.maximumDate = maximum + var months: [Month] = [] + var day = minimum + while day <= maximum { + let year = calendar.component(.year, from: day) + let number = calendar.component(.month, from: day) + if let last = months.last, last.year == year, last.number == number { + months[months.count - 1] = Month(year: year, number: number, dates: last.dates + [day]) + } else { + months.append(Month(year: year, number: number, dates: [day])) + } + guard let next = calendar.date(byAdding: .day, value: 1, to: day), next > day else { break } + day = next + } + self.months = months + } + + /// 将外部值归一到允许范围内的日历日。 + func clamped(_ date: Date) -> Date { + min(max(calendar.startOfDay(for: date), minimumDate), maximumDate) + } + + /// 找到日期对应的月份行,保留期外值先收敛到边界。 + func monthIndex(for date: Date) -> Int { + let value = clamped(date) + return months.firstIndex { month in + month.dates.first.map { $0 <= value } == true && month.dates.last.map { value <= $0 } == true + } ?? 0 + } + + /// 切换月份时尽量保留原日号;月末或截断的保留期会收敛到最近可选日。 + func date(inMonthAt index: Int, preferredDay: Int) -> Date { + let month = months[min(max(index, 0), months.count - 1)] + return month.dates.min { + abs(calendar.component(.day, from: $0) - preferredDay) + < abs(calendar.component(.day, from: $1) - preferredDay) + } ?? minimumDate + } + + /// 普通范围只显示月份;范围含同名月份时补年份,避免用户混淆。 + func monthTitle(at index: Int) -> String { + let month = months[index] + let repeats = months.filter { $0.number == month.number }.count > 1 + return repeats ? "\(month.year)年\(month.number)月" : "\(month.number)月" + } +} diff --git a/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialModels.swift b/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialModels.swift index fc4e2f1..3cee7cf 100644 --- a/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialModels.swift +++ b/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialModels.swift @@ -70,12 +70,21 @@ struct ScenicMaterialClip: Hashable, Sendable { let resolution: String /// 本地演示封面资源名。 let coverAssetName: String + /// 正式素材原片地址;预览素材为空。 + let remoteURL: URL? + /// 正式素材封面地址。 + let coverURL: URL? + /// 后端返回的片段名称。 + let fileLabel: String? + /// 是否来自正式接口,缺失地址时禁止回退到演示视频。 + let isRemote: Bool /// 文件是否仍可预览和下载;不可用文件仍可展示其元数据。 let isAvailable: Bool /// 创建片段元数据,不读取本地相册或请求网络。 init(id: String, groupID: String, ordinal: Int, durationSeconds: Int, fileSizeBytes: Int64, - resolution: String, coverAssetName: String, isAvailable: Bool = true) { + resolution: String, coverAssetName: String, isAvailable: Bool = true, + remoteURL: URL? = nil, coverURL: URL? = nil, fileLabel: String? = nil, isRemote: Bool = false) { self.id = id self.groupID = groupID self.ordinal = ordinal @@ -84,16 +93,22 @@ struct ScenicMaterialClip: Hashable, Sendable { self.resolution = resolution self.coverAssetName = coverAssetName self.isAvailable = isAvailable + self.remoteURL = remoteURL + self.coverURL = coverURL + self.fileLabel = fileLabel + self.isRemote = isRemote } /// 用于封面与预览信息的分秒时长。 var durationText: String { + guard durationSeconds >= 0 else { return "时长未知" } let value = max(durationSeconds, 0) return String(format: "%02d:%02d", value / 60, value % 60) } /// 使用十进制 MB 展示片段大小,避免将原文件与本地示例文件混淆。 var sizeText: String { + guard fileSizeBytes >= 0 else { return "大小未知" } let megabytes = Double(max(fileSizeBytes, 0)) / 1_000_000 return megabytes.rounded() == megabytes ? String(format: "%.0fMB", megabytes) : String(format: "%.1fMB", megabytes) } diff --git a/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialsAPIModels.swift b/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialsAPIModels.swift new file mode 100644 index 0000000..b7ea57c --- /dev/null +++ b/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialsAPIModels.swift @@ -0,0 +1,113 @@ +import Foundation + +/// 场次接口中已由部署响应确认的分页和保留策略;子项保留原始字段供合同映射使用。 +struct ScenicMaterialsSessionsResponse: Decodable, Equatable, Sendable { + /// 当前页场次原始对象,不能把未确认的子项结构当成空列表。 + let list: [[String: ScenicMaterialsJSONValue]] + /// 服务端航线分组原始对象。 + let groups: [[String: ScenicMaterialsJSONValue]] + /// 当前筛选场次总数。 + let total: Int + /// 服务端实际返回的页码。 + let page: Int + /// 服务端实际返回的每页数量。 + let pageSize: Int + /// 本次查询的素材保留窗口。 + let retentionDays: Int + /// 服务端提供的保留期提示。 + let retentionTips: String + /// 服务端实际应用的筛选。 + let filter: ScenicMaterialsFilter + /// 当前景区可用的航线筛选对象。 + let airLines: [[String: ScenicMaterialsJSONValue]] + + /// 部署接口的根字段。 + private enum CodingKeys: String, CodingKey { + case list, groups, total, page, pageSize = "page_size", retentionDays = "retention_days" + case retentionTips = "retention_tips", filter, filterOptions = "filter_options" + } + + /// 只接受真实容器和有效分页,避免缺字段响应被误显示成空态。 + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + list = try container.decode([[String: ScenicMaterialsJSONValue]].self, forKey: .list) + groups = try container.decode([[String: ScenicMaterialsJSONValue]].self, forKey: .groups) + total = try container.decode(Int.self, forKey: .total) + page = try container.decode(Int.self, forKey: .page) + pageSize = try container.decode(Int.self, forKey: .pageSize) + retentionDays = try container.decode(Int.self, forKey: .retentionDays) + retentionTips = try container.decode(String.self, forKey: .retentionTips) + filter = try container.decode(ScenicMaterialsFilter.self, forKey: .filter) + airLines = try container.decode(ScenicMaterialsFilterOptions.self, forKey: .filterOptions).airLines + guard total >= 0, page > 0, (1...100).contains(pageSize), (1...365).contains(retentionDays), + list.count <= pageSize, list.count <= total else { + throw DecodingError.dataCorruptedError(forKey: .list, in: container, debugDescription: "空境库场次分页或保留期无效") + } + } +} + +/// 后端实际应用的筛选,全部航线为 0、全部日期为空字符串。 +struct ScenicMaterialsFilter: Decodable, Equatable, Sendable { + /// 当前航线筛选值。 + let airLineID: Int + /// 当前起始日期筛选值。 + let dateFrom: String + /// 当前结束日期筛选值。 + let dateTo: String + + /// 部署响应中的筛选字段。 + private enum CodingKeys: String, CodingKey { + case airLineID = "air_line_id", dateFrom = "date_from", dateTo = "date_to" + } +} + +/// filter_options 下独立返回当前景区的航线集合。 +private struct ScenicMaterialsFilterOptions: Decodable { + let airLines: [[String: ScenicMaterialsJSONValue]] + /// 部署响应中的航线容器。 + private enum CodingKeys: String, CodingKey { case airLines = "air_lines" } +} + +/// 场次详情的已确认素材数组及完整场次信息,不借用订单素材 ID 模型。 +struct ScenicMaterialsSessionDetailResponse: Decodable, Equatable, Sendable { + /// 文档明确返回的全部素材项,保留服务端所有字段。 + let materials: [[String: ScenicMaterialsJSONValue]] + /// 场次详情完整对象,供依据实际合同解码归属与展示信息。 + let fields: [String: ScenicMaterialsJSONValue] + + /// 缺少 materials 或容器错误时报错,不伪装成没有素材。 + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + fields = try container.decode([String: ScenicMaterialsJSONValue].self) + guard case let .array(values)? = fields["materials"] else { + throw DecodingError.dataCorruptedError(in: container, debugDescription: "空境场次详情缺少 materials 数组") + } + materials = try values.map { value in + guard case let .object(fields) = value else { + throw DecodingError.dataCorruptedError(in: container, debugDescription: "空境素材必须为对象") + } + return fields + } + } +} + +/// 保留空境库尚未完整描述的子项 JSON,不猜测字段类型或单位。 +indirect enum ScenicMaterialsJSONValue: Decodable, Equatable, Sendable { + case object([String: ScenicMaterialsJSONValue]) + case array([ScenicMaterialsJSONValue]) + case string(String) + case number(Decimal) + case bool(Bool) + case null + + /// 按真实 JSON 类型读取,未知字段不会静默丢失。 + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if container.decodeNil() { self = .null } + else if let value = try? container.decode(Bool.self) { self = .bool(value) } + else if let value = try? container.decode(String.self) { self = .string(value) } + else if let value = try? container.decode(Decimal.self) { self = .number(value) } + else if let value = try? container.decode([String: ScenicMaterialsJSONValue].self) { self = .object(value) } + else { self = .array(try container.decode([ScenicMaterialsJSONValue].self)) } + } +} diff --git a/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialsQuery.swift b/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialsQuery.swift new file mode 100644 index 0000000..d844177 --- /dev/null +++ b/suixinkan/Features/ScenicMaterials/Models/ScenicMaterialsQuery.swift @@ -0,0 +1,67 @@ +import Foundation + +/// 朱工空境库场次查询范围,分页和筛选均由服务端执行。 +struct ScenicMaterialsQuery: Equatable, Sendable { + /// 当前景区身份,不依赖订单、机巢或飞行任务。 + let scenicID: Int + /// 从 1 开始的场次页码。 + let page: Int + /// 每页场次数,接口允许 1 到 100。 + let pageSize: Int + /// 指定航线;nil 表示全部航线。 + let airLineID: Int? + /// 可选起始日期,格式为 yyyy-MM-dd。 + let dateFrom: String? + /// 可选结束日期,格式为 yyyy-MM-dd。 + let dateTo: String? + /// 保留期查询窗口,默认 90 天,部署接口允许 1 到 365。 + let retentionDays: Int + + /// 创建完整查询快照,便于判断翻页和筛选请求是否过期。 + init(scenicID: Int, page: Int = 1, pageSize: Int = 20, airLineID: Int? = nil, + dateFrom: String? = nil, dateTo: String? = nil, retentionDays: Int = 90) { + self.scenicID = scenicID + self.page = page + self.pageSize = pageSize + self.airLineID = airLineID + self.dateFrom = dateFrom + self.dateTo = dateTo + self.retentionDays = retentionDays + } + + /// 校验范围后生成文档规定的 GET 参数,全部航线和全部日期不发送占位值。 + func queryItems() throws -> [URLQueryItem] { + guard scenicID > 0 else { throw APIError.networkFailed("请先选择景区") } + guard page > 0, (1...100).contains(pageSize), (1...365).contains(retentionDays), + airLineID.map({ $0 > 0 }) ?? true else { + throw APIError.networkFailed("景区空境库查询参数无效") + } + guard Self.isValidDate(dateFrom), Self.isValidDate(dateTo) else { + throw APIError.networkFailed("请选择有效的日期范围") + } + if let dateFrom, let dateTo, dateFrom > dateTo { + throw APIError.networkFailed("请选择有效的日期范围") + } + var result = [URLQueryItem(name: "scenic_id", value: String(scenicID)), + URLQueryItem(name: "page", value: String(page)), + URLQueryItem(name: "page_size", value: String(pageSize)), + URLQueryItem(name: "retention_days", value: String(retentionDays))] + if let airLineID { result.append(URLQueryItem(name: "air_line_id", value: String(airLineID))) } + if let dateFrom { result.append(URLQueryItem(name: "date_from", value: dateFrom)) } + if let dateTo { result.append(URLQueryItem(name: "date_to", value: dateTo)) } + return result + } + + /// 严格校验公历日期,拒绝 DateFormatter 自动纠正的越界日期。 + private static func isValidDate(_ value: String?) -> Bool { + guard let value else { return true } + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .gregorian) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + formatter.isLenient = false + guard let date = formatter.date(from: value) else { return false } + return formatter.string(from: date) == value + } +} diff --git a/suixinkan/Features/ScenicMaterials/Services/ScenicMaterialDownloadService.swift b/suixinkan/Features/ScenicMaterials/Services/ScenicMaterialDownloadService.swift new file mode 100644 index 0000000..fcf08c6 --- /dev/null +++ b/suixinkan/Features/ScenicMaterials/Services/ScenicMaterialDownloadService.swift @@ -0,0 +1,175 @@ +import Foundation +import Photos + +/// 一项待保存的空境素材;身份仅在当前账号、景区页面的服务实例内使用。 +struct ScenicMaterialDownloadItem: Sendable { + /// 当前素材的稳定标识。 + let id: String + /// 服务端提供的可下载原片地址。 + let remoteURL: URL + /// 本地临时文件名,保留媒体扩展名以便 Photos 识别。 + let fileName: String + /// 与相册保存器一致:1 为视频,其他值为图片。 + let fileType: Int + + /// 创建下载项,不附加 App 登录凭证到 OSS 地址。 + init(id: String, remoteURL: URL, fileName: String = "scenic-material.mp4", fileType: Int = 1) { + self.id = id + self.remoteURL = remoteURL + self.fileName = fileName + self.fileType = fileType + } +} + +/// 串行下载并保存真实空境素材;取消后屏蔽旧回执,已保存的文件不重复写入相册。 +@MainActor +final class ScenicMaterialDownloadService { + private let downloader: any CloudFileDownloading + private let photoSaver: any CloudPhotoSaving + private var task: Task? + private var activeBatchID: UUID? + private var savedIDs = Set() + + /// 注入下载和相册保存依赖,测试不访问网络或系统相册。 + init(downloader: any CloudFileDownloading = ScenicMaterialURLSessionDownloader(), + photoSaver: any CloudPhotoSaving = ScenicMaterialPhotoLibrarySaver()) { + self.downloader = downloader + self.photoSaver = photoSaver + } + + /// 开始当前批次;同一批次的重复启动无效,重新启动会等待前次相册事务结束。 + func start(items: [ScenicMaterialDownloadItem], batchID: UUID, + onEvent: @escaping @MainActor @Sendable (String, UUID, ScenicMaterialTransferEvent) -> Void, + onFailure: (@MainActor @Sendable (String, Error) -> Void)? = nil) { + guard activeBatchID != batchID else { return } + let previous = task + previous?.cancel() + activeBatchID = batchID + task = Task { @MainActor [weak self] in + // Photos 的已提交保存不可取消;先等旧事务落定,再决定是否需要重下。 + await previous?.value + guard let self else { return } + defer { if self.activeBatchID == batchID { self.activeBatchID = nil } } + var visited = Set() + for item in items where visited.insert(item.id).inserted { + guard self.isActive(batchID) else { return } + if self.savedIDs.contains(item.id) { + onEvent(item.id, batchID, .completed) + continue + } + var localURL: URL? + defer { if let localURL { try? FileManager.default.removeItem(at: localURL) } } + do { + localURL = try await self.downloader.downloadFile(remoteURL: item.remoteURL.absoluteString, + fileName: item.fileName) { [weak self] percent in + Task { @MainActor [weak self] in + guard let self, self.isActive(batchID), !self.savedIDs.contains(item.id) else { return } + // 下载完成只占 90%,最后一步是系统相册保存成功。 + onEvent(item.id, batchID, .progress(Double(min(max(percent, 0), 100)) / 100 * 0.9)) + } + } + guard self.isActive(batchID), let localURL else { return } + try await self.photoSaver.saveToPhotoLibrary(fileURL: localURL, fileType: item.fileType) + // 保存已落定,即便用户此时暂停,也保留事实以免继续时重复保存。 + self.savedIDs.insert(item.id) + guard self.isActive(batchID) else { return } + onEvent(item.id, batchID, .completed) + } catch { + guard self.isActive(batchID) else { return } + onEvent(item.id, batchID, .failed) + onFailure?(item.id, error) + } + } + } + } + + /// 停止下载并作废当前回执;正在提交的相册事务完成后会清理临时文件。 + func stop() { + activeBatchID = nil + task?.cancel() + } + + /// 等待已经启动的传输及临时文件清理完成。 + func waitForPendingOperations() async { await task?.value } + + private func isActive(_ batchID: UUID) -> Bool { + !Task.isCancelled && activeBatchID == batchID + } +} + +/// 检查 HTTP 状态与非空响应文件的空境原片下载器。 +struct ScenicMaterialURLSessionDownloader: CloudFileDownloading { + private let session: URLSession + + /// 注入 URLSession 便于使用 URLProtocol 验证状态码及错误响应。 + init(session: URLSession = .shared) { self.session = session } + + /// 下载到唯一临时路径;失败响应及取消下载均清理 URLSession 临时文件。 + func downloadFile(remoteURL: String, fileName: String, + onProgress: @escaping @Sendable (Int) -> Void) async throws -> URL { + guard let url = URL(string: remoteURL), ["https", "http"].contains(url.scheme?.lowercased() ?? ""), + url.host != nil else { throw ScenicMaterialDownloadError.invalidURL } + let delegate = ScenicMaterialDownloadProgress(onProgress: onProgress) + let (temporaryURL, response) = try await session.download(from: url, delegate: delegate) + defer { try? FileManager.default.removeItem(at: temporaryURL) } + try Task.checkCancellation() + guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else { + throw ScenicMaterialDownloadError.httpFailure((response as? HTTPURLResponse)?.statusCode ?? 0) + } + let attributes = try FileManager.default.attributesOfItem(atPath: temporaryURL.path) + guard (attributes[.size] as? NSNumber)?.int64Value ?? 0 > 0 else { + throw ScenicMaterialDownloadError.emptyFile + } + let destination = FileManager.default.temporaryDirectory + .appendingPathComponent("\(UUID().uuidString)-\(CloudTransferFileName.sanitized(fileName))") + try FileManager.default.moveItem(at: temporaryURL, to: destination) + onProgress(100) + return destination + } +} + +/// 将 URLSession 的实际字节进度传回下载服务,不虚构中间进度。 +private final class ScenicMaterialDownloadProgress: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { + private let onProgress: @Sendable (Int) -> Void + + init(onProgress: @escaping @Sendable (Int) -> Void) { self.onProgress = onProgress } + + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {} + + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + guard totalBytesExpectedToWrite > 0 else { return } + onProgress(Int(min(Double(totalBytesWritten) / Double(totalBytesExpectedToWrite), 1) * 100)) + } +} + +/// 只请求添加相册权限,Photos 成功创建资产后才返回成功。 +struct ScenicMaterialPhotoLibrarySaver: CloudPhotoSaving { + /// 保存本地真实图片或视频;授权期间取消操作不会继续提交相册事务。 + func saveToPhotoLibrary(fileURL: URL, fileType: Int) async throws { + let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly) + try Task.checkCancellation() + guard status == .authorized || status == .limited else { throw CloudTransferError.photoPermissionDenied } + guard FileManager.default.fileExists(atPath: fileURL.path) else { throw CloudTransferError.localFileMissing } + try await PHPhotoLibrary.shared().performChanges { + let request = PHAssetCreationRequest.forAsset() + request.addResource(with: fileType == 1 ? .video : .photo, fileURL: fileURL, options: nil) + } + } +} + +/// 空境原片下载中可向用户解释的错误。 +enum ScenicMaterialDownloadError: LocalizedError, Equatable { + case invalidURL + case httpFailure(Int) + case emptyFile + + /// 下载失败原因,避免将服务端错误页作为素材保存。 + var errorDescription: String? { + switch self { + case .invalidURL: "素材地址无效" + case .httpFailure(let status): "素材下载失败(HTTP \(status))" + case .emptyFile: "素材文件为空,请稍后重试" + } + } +} diff --git a/suixinkan/Features/ScenicMaterials/ViewModels/ScenicMaterialsViewModel.swift b/suixinkan/Features/ScenicMaterials/ViewModels/ScenicMaterialsViewModel.swift index 69743ba..be15da7 100644 --- a/suixinkan/Features/ScenicMaterials/ViewModels/ScenicMaterialsViewModel.swift +++ b/suixinkan/Features/ScenicMaterials/ViewModels/ScenicMaterialsViewModel.swift @@ -2,14 +2,16 @@ import Foundation /// 独立景区空镜库的筛选、选择和前台下载演示逻辑;不依赖 UIKit 或机巢业务。 final class ScenicMaterialsViewModel { + /// 正式模式使用网络素材与真实相册保存,预览模式使用本地演示。 + let isRemote: Bool /// 本次页面的独立账号与景区范围。 let context: ScenicMaterialContext /// 用于筛选的日历及其时区。 let calendar: Calendar /// 本地演示保留天数,正式对接后由服务端配置决定。 - let retentionDays = 90 + private(set) var retentionDays = 90 /// 保留期首日零点,包含今天一共 90 个日历日。 - let minimumDate: Date + private(set) var minimumDate: Date /// 可选的最后一天零点,不允许选择未来日期。 let maximumDate: Date /// 当前景区的独立空镜航线,含暂无片段的航线。 @@ -37,18 +39,29 @@ final class ScenicMaterialsViewModel { /// 当前批次的逐项演示进度。 private(set) var progressByID: [String: Double] = [:] + /// 已确认接口的加载状态。 + private(set) var isLoading = false + /// 请求失败或素材字段尚无法映射时的可重试提示。 + private(set) var loadError: String? + /// 保留完整响应,非空且未确认字段时不能被当成空库。 + private(set) var remoteSessions: ScenicMaterialsSessionsResponse? + /// 素材保留说明优先使用后端返回的文案。 + private(set) var retentionTips = "素材保留 90 天,请及时下载" + private var loadID: UUID? + private let initialGroups: [ScenicMaterialGroup] /// 创建演示库;可注入日历、日期和数据,测试不依赖时间、网络或登录单例。 init(context: ScenicMaterialContext = .demo, now: Date = Date(), calendar: Calendar = .current, - routes: [ScenicMaterialRoute]? = nil, groups: [ScenicMaterialGroup]? = nil) { + routes: [ScenicMaterialRoute]? = nil, groups: [ScenicMaterialGroup]? = nil, isRemote: Bool = false) { + self.isRemote = isRemote self.context = context self.calendar = calendar maximumDate = calendar.startOfDay(for: now) minimumDate = calendar.date(byAdding: .day, value: -(retentionDays - 1), to: maximumDate) ?? maximumDate - let demoRoutes = Self.makeRoutes(context: context) + let demoRoutes = isRemote ? [] : Self.makeRoutes(context: context) self.routes = routes ?? demoRoutes - let data = groups ?? Self.makeGroups(context: context, routes: demoRoutes, today: maximumDate, calendar: calendar) + let data = groups ?? (isRemote ? [] : Self.makeGroups(context: context, routes: demoRoutes, today: maximumDate, calendar: calendar)) initialGroups = data allGroups = data } @@ -113,10 +126,55 @@ final class ScenicMaterialsViewModel { } } /// 当前空态标题,区分全库为空与有筛选但无结果。 - var emptyTitle: String { hasAnyMaterials ? "没有符合条件的素材" : "暂无景区素材" } + var emptyTitle: String { + if isLoading { return "正在加载素材" } + if loadError != nil { return "素材加载失败" } + return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "没有符合条件的素材" : "暂无景区素材" + } /// 当前空态说明。 var emptyMessage: String { - hasAnyMaterials ? "试试其他航线或时间范围" : "景区空镜上传后,将显示在这里" + if isLoading { return "请稍候" } + if let loadError { return loadError } + return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "试试其他航线或时间范围" : "景区空镜上传后,将显示在这里" + } + + /// 读取当前景区的真实列表;在有样本确认子项合同前保留原始响应并明确报错。 + func loadRemoteSessions(api: any ScenicMaterialsServing) async { + guard isRemote, !isSelectionLocked else { return } + let requestID = UUID() + loadID = requestID + defer { if loadID == requestID { isLoading = false } } + isLoading = true + loadError = nil + let query = ScenicMaterialsQuery(scenicID: Int(context.scenicID) ?? 0, + airLineID: selectedRouteID.flatMap(Int.init), + dateFrom: dateRange.map { formatDate($0.start, format: "yyyy-MM-dd") }, + dateTo: dateRange.map { formatDate($0.end, format: "yyyy-MM-dd") }, retentionDays: retentionDays) + do { + let response = try await api.sessions(query: query) + guard loadID == requestID, !Task.isCancelled else { return } + remoteSessions = response + retentionDays = response.retentionDays + retentionTips = response.retentionTips + minimumDate = calendar.date(byAdding: .day, value: -(retentionDays - 1), to: maximumDate) ?? maximumDate + allGroups = [] + routes = [] + selectedIDs.removeAll() + if response.total > 0 || !response.list.isEmpty || !response.groups.isEmpty || !response.airLines.isEmpty { + // 当前文档没有非空场次/航线的字段合同,不使用猜测的 ID 下载或错配素材。 + loadError = "暂时无法显示素材,请稍后重试" + } + } catch is CancellationError { + } catch { + guard loadID == requestID else { return } + loadError = error.localizedDescription + } + } + + /// 离页或身份变化后作废尚未返回的列表请求。 + func cancelRemoteLoad() { + loadID = nil + isLoading = false } /// 查找稳定航线,不依赖名称。 @@ -171,7 +229,7 @@ final class ScenicMaterialsViewModel { /// 当前可选状态;完成、不可用、隐藏片段或锁定批次均不可新选。 func canSelect(id: String) -> Bool { - !isSelectionLocked && filteredClips.contains { $0.id == id && $0.isAvailable && !completedIDs.contains(id) } + !isSelectionLocked && filteredClips.contains { $0.id == id && $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains(id) } } /// 切换单项选择,不涉及预览或下载。 @@ -215,7 +273,7 @@ final class ScenicMaterialsViewModel { @discardableResult func startDownload() -> Bool { guard !isSelectionLocked else { return false } - let items = filteredClips.filter { selectedIDs.contains($0.id) && $0.isAvailable && !completedIDs.contains($0.id) } + let items = filteredClips.filter { selectedIDs.contains($0.id) && $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) } guard !items.isEmpty else { return false } batchItemIDs = items.map(\.id) selectedIDs = Set(batchItemIDs) @@ -285,6 +343,7 @@ final class ScenicMaterialsViewModel { /// 切换本地状态预览,不读取真实相册,也不更改登录身份或订单。 func applyScenario(_ scenario: ScenicMaterialsScenario) { + guard !isRemote else { return } clearBatch() completedIDs.removeAll() allGroups = initialGroups @@ -320,11 +379,11 @@ final class ScenicMaterialsViewModel { private func selectableIDs(in groupID: String) -> Set { guard let group = filteredGroups.first(where: { $0.id == groupID }) else { return [] } - return Set(group.clips.filter { $0.isAvailable && !completedIDs.contains($0.id) }.map(\.id)) + return Set(group.clips.filter { $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) }.map(\.id)) } private func pruneSelection() { - let valid = Set(filteredClips.filter { $0.isAvailable && !completedIDs.contains($0.id) }.map(\.id)) + let valid = Set(filteredClips.filter { $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) }.map(\.id)) selectedIDs.formIntersection(valid) } diff --git a/suixinkan/UI/DroneDock/DroneDockDeliveryEntry.swift b/suixinkan/UI/DroneDock/DroneDockDeliveryEntry.swift index bcb2de2..ca30c60 100644 --- a/suixinkan/UI/DroneDock/DroneDockDeliveryEntry.swift +++ b/suixinkan/UI/DroneDock/DroneDockDeliveryEntry.swift @@ -3,6 +3,33 @@ import UIKit /// 订单列表与素材库共用的真实成片交付页面工厂。 @MainActor enum DroneDockDeliveryEntry { + /// 订单列表先展示方式选择,云端页面在同一弹窗内继续,关闭后再通知列表刷新。 + static func makeMethodSheet(order: DroneDockHomeOrder, context: DroneDockHomeContext, + controllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController, + onDidCloseCloud: @escaping () -> Void = {}) -> UINavigationController { + let methods = DroneDockDeliveryMethodViewController(customerTitle: order.touristTitle) + let navigation = DroneDockDeliverySheetNavigationController(rootViewController: methods) + navigation.modalPresentationStyle = .pageSheet + navigation.onDidCloseCloud = onDidCloseCloud + methods.onClose = { [weak navigation] in navigation?.dismiss(animated: true) } + methods.onCloudUpload = { [weak navigation, weak methods] in + guard let navigation, let methods, navigation.topViewController === methods else { return } + let cloud = controllerFactory(order, context, nil) + if let cloud = cloud as? DroneDockDeliveryViewController { + cloud.configureSheetPresentation { [weak navigation] in navigation?.dismiss(animated: true) } + } + navigation.didOpenCloud = true + navigation.isModalInPresentation = true + navigation.sheetPresentationController?.animateChanges { + navigation.sheetPresentationController?.detents = [.large()] + navigation.sheetPresentationController?.selectedDetentIdentifier = .large + } + navigation.setNavigationBarHidden(false, animated: true) + navigation.pushViewController(cloud, animated: true) + } + return navigation + } + /// 同时传递订单与可选任务,进入页面后重新校验当前身份和上传权限。 static func makeController(order: DroneDockHomeOrder, context: DroneDockHomeContext, taskID: Int?) -> UIViewController { let client = NetworkServices.shared.apiClient @@ -15,3 +42,32 @@ enum DroneDockDeliveryEntry { )) } } + +/// 统一处理手动关闭与下拉关闭,云端交付结束后只通知来源列表一次。 +@MainActor +private final class DroneDockDeliverySheetNavigationController: UINavigationController, UIAdaptivePresentationControllerDelegate { + /// 云端页面已经进入,关闭弹窗后需要重读订单状态。 + var didOpenCloud = false + /// 不因仅查看交付方式而刷新订单。 + var onDidCloseCloud: (() -> Void)? + private var didNotifyClose = false + + override func viewDidLoad() { + super.viewDidLoad() + presentationController?.delegate = self + } + + override func viewDidDisappear(_ animated: Bool) { + super.viewDidDisappear(animated) + if isBeingDismissed || presentingViewController == nil { notifyClose() } + } + + /// 系统下拉关闭与按钮关闭使用同一去重通知。 + func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { notifyClose() } + + private func notifyClose() { + guard !didNotifyClose else { return } + didNotifyClose = true + if didOpenCloud { onDidCloseCloud?() } + } +} diff --git a/suixinkan/UI/DroneDock/DroneDockDeliveryMethodViewController.swift b/suixinkan/UI/DroneDock/DroneDockDeliveryMethodViewController.swift new file mode 100644 index 0000000..4371c85 --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneDockDeliveryMethodViewController.swift @@ -0,0 +1,170 @@ +import SnapKit +import UIKit + +/// 真实订单的交付方式弹窗,只展示方式选择并将云端交付导航交回入口。 +@MainActor +final class DroneDockDeliveryMethodViewController: BaseViewController { + /// 用户选择云端上传后,由入口打开现有真实交付页。 + var onCloudUpload: (() -> Void)? + /// 用户关闭弹窗后,由入口统一结束当前模态流程。 + var onClose: (() -> Void)? + + /// 闪传只显示未接入说明,不创建传输任务或连接设备。 + private enum Phase: Equatable { case methods, nearby } + /// 两种交付方式与闪传说明使用独立、稳定的列表身份。 + private enum Item: Hashable { case nearby, cloud, nearbyMessage } + + private let customerTitle: String + private let headerView = DroneDeliveryUploadHeaderView() + private let footerView = DroneDeliveryUploadFooterView() + private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout()) + private var dataSource: UICollectionViewDiffableDataSource! + private var phase = Phase.methods + private var hasRequestedCloud = false + + /// 游客标题由选中的订单传入,本弹窗不读取网络或改变订单状态。 + init(customerTitle: String) { + self.customerTitle = customerTitle + super.init(nibName: nil, bundle: nil) + modalPresentationStyle = .pageSheet + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + hasRequestedCloud = false + navigationController?.isModalInPresentation = false + isModalInPresentation = false + navigationController?.setNavigationBarHidden(true, animated: false) + configureSheet() + } + + override func setupNavigationBar() { + title = "交付成片" + navigationController?.setNavigationBarHidden(true, animated: false) + } + + override func setupUI() { + view.backgroundColor = .white + collectionView.backgroundColor = .white + collectionView.alwaysBounceVertical = false + collectionView.showsVerticalScrollIndicator = false + collectionView.accessibilityIdentifier = "drone.delivery.method.list" + collectionView.delegate = self + collectionView.register(DroneDeliveryUploadMethodCell.self, forCellWithReuseIdentifier: "method") + collectionView.register(DroneDeliveryUploadMessageCell.self, forCellWithReuseIdentifier: "message") + [headerView, collectionView, footerView].forEach(view.addSubview) + configureDataSource() + applySnapshot(animated: false) + } + + override func setupConstraints() { + headerView.snp.makeConstraints { make in + make.top.equalTo(view.safeAreaLayoutGuide) + make.leading.trailing.equalToSuperview() + } + collectionView.snp.makeConstraints { make in + make.top.equalTo(headerView.snp.bottom) + make.leading.trailing.equalToSuperview() + make.bottom.equalTo(footerView.snp.top) + } + footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() } + } + + override func bindActions() { + headerView.onCloseTap = { [weak self] in self?.onClose?() } + footerView.onPrimaryTap = { [weak self] in self?.requestCloudUpload() } + footerView.onSecondaryTap = { [weak self] in self?.showPhase(.methods) } + } + + private func configureSheet() { + guard let sheet = navigationController?.sheetPresentationController ?? sheetPresentationController else { return } + let identifier = UISheetPresentationController.Detent.Identifier("drone.delivery.method") + sheet.detents = [ + .custom(identifier: identifier) { context in min(410, context.maximumDetentValue) }, + .large() + ] + sheet.selectedDetentIdentifier = identifier + sheet.prefersGrabberVisible = true + sheet.preferredCornerRadius = 22 + sheet.prefersScrollingExpandsWhenScrolledToEdge = false + } + + private func makeLayout() -> UICollectionViewLayout { + UICollectionViewCompositionalLayout { [weak self] _, _ in + guard let self else { return nil } + let height: CGFloat = self.phase == .methods ? 88 : 132 + let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1))) + let group = NSCollectionLayoutGroup.vertical( + layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(height)), subitems: [item]) + let section = NSCollectionLayoutSection(group: group) + section.interGroupSpacing = self.phase == .methods ? 12 : 0 + section.contentInsets = .init(top: 4, leading: 20, bottom: 4, trailing: 20) + return section + } + } + + private func configureDataSource() { + dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { collection, path, item in + switch item { + case .nearby, .cloud: + let cell = collection.dequeueReusableCell(withReuseIdentifier: "method", for: path) as! DroneDeliveryUploadMethodCell + if item == .nearby { + cell.apply(title: "面对面闪传", detail: "近距离传给游客 · 流程待确认", symbol: "wifi", identifier: "drone.delivery.method.nearby") + } else { + cell.apply(title: "云端上传", detail: "选择打卡点,上传后游客可查看", symbol: "icloud.and.arrow.up", identifier: "drone.delivery.method.cloud") + } + return cell + case .nearbyMessage: + let cell = collection.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DroneDeliveryUploadMessageCell + cell.apply(title: "闪传流程待确认", detail: "热点连接与游客接收流程暂未接入。\n请使用云端上传交付成片。", symbol: "wifi") + cell.accessibilityIdentifier = "drone.delivery.method.nearbyMessage" + return cell + } + } + } + + private func applySnapshot(animated: Bool) { + guard dataSource != nil else { return } + var snapshot = NSDiffableDataSourceSnapshot() + snapshot.appendSections([0]) + switch phase { + case .methods: + headerView.apply(title: "交付成片", customer: customerTitle, detail: "请选择本次交付方式") + footerView.apply(primaryTitle: nil, enabled: false, identifier: "", detail: "可分批交付多个作品,不影响拍摄次数", secondaryTitle: nil) + snapshot.appendItems([.nearby, .cloud]) + case .nearby: + headerView.apply(title: "面对面闪传", customer: customerTitle, detail: "本次仅展示交付入口") + footerView.apply(primaryTitle: "改用云端上传", enabled: true, identifier: "drone.delivery.method.useCloud", detail: "", secondaryTitle: "返回交付方式") + snapshot.appendItems([.nearbyMessage]) + } + dataSource.apply(snapshot, animatingDifferences: animated) + collectionView.collectionViewLayout.invalidateLayout() + } + + private func showPhase(_ phase: Phase) { + self.phase = phase + applySnapshot(animated: true) + collectionView.setContentOffset(.zero, animated: false) + } + + private func requestCloudUpload() { + guard !hasRequestedCloud, let onCloudUpload else { return } + hasRequestedCloud = true + onCloudUpload() + } +} + +extension DroneDockDeliveryMethodViewController: UICollectionViewDelegate { + /// 云端方式交回调用方,闪传方式只在当前弹窗展示待接入说明。 + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + guard let item = dataSource.itemIdentifier(for: indexPath), !hasRequestedCloud else { return } + switch item { + case .nearby: showPhase(.nearby) + case .cloud: requestCloudUpload() + case .nearbyMessage: break + } + } +} diff --git a/suixinkan/UI/DroneDock/DroneDockDeliveryViewController.swift b/suixinkan/UI/DroneDock/DroneDockDeliveryViewController.swift index a42121d..3fa3f58 100644 --- a/suixinkan/UI/DroneDock/DroneDockDeliveryViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockDeliveryViewController.swift @@ -19,6 +19,7 @@ final class DroneDockDeliveryViewController: BaseViewController { private var pickerError: String? private var ownedVideoURLs: Set = [] private var previousGestureEnabled: Bool? + private var onCloseSheet: (() -> Void)? private weak var trackedNavigationController: UINavigationController? private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout()) private var dataSource: UICollectionViewDiffableDataSource! @@ -50,15 +51,26 @@ final class DroneDockDeliveryViewController: BaseViewController { ownedVideoURLs.forEach(DroneDockDeliveryVideoLoader.discard) } + /// 订单列表以弹窗展示时复用上传流程,并将关闭动作纳入处理中退出确认。 + func configureSheetPresentation(onClose: @escaping () -> Void) { + onCloseSheet = onClose + } + override func setupNavigationBar() { - title = "交付成片" + title = onCloseSheet == nil ? "交付成片" : "云端上传" navigationItem.backButtonDisplayMode = .minimal - let back = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(backTapped)) + let back = UIBarButtonItem(title: onCloseSheet == nil ? "返回" : "交付方式", style: .plain, target: self, action: #selector(backTapped)) back.accessibilityIdentifier = "drone.delivery.back" navigationItem.leftBarButtonItem = back let refresh = UIBarButtonItem(title: "刷新", style: .plain, target: self, action: #selector(refreshTapped)) refresh.accessibilityIdentifier = "drone.delivery.refresh" navigationItem.rightBarButtonItem = refresh + if onCloseSheet != nil { + let close = UIBarButtonItem(image: UIImage(systemName: "xmark"), style: .plain, target: self, action: #selector(closeSheetTapped)) + close.accessibilityLabel = "关闭成片交付" + close.accessibilityIdentifier = "drone.delivery.sheet.close" + navigationItem.rightBarButtonItems = [close, refresh] + } } override func setupUI() { @@ -110,6 +122,12 @@ final class DroneDockDeliveryViewController: BaseViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) + if onCloseSheet != nil { + navigationController?.setNavigationBarHidden(false, animated: false) + navigationController?.isModalInPresentation = true + navigationController?.sheetPresentationController?.detents = [.large()] + navigationController?.sheetPresentationController?.selectedDetentIdentifier = .large + } trackedNavigationController = navigationController if previousGestureEnabled == nil { previousGestureEnabled = navigationController?.interactivePopGestureRecognizer?.isEnabled } guard !hasAppeared else { updateFooter(); return } @@ -246,7 +264,7 @@ final class DroneDockDeliveryViewController: BaseViewController { submitButton.setTitle(working ? "处理中…" : title, for: .normal) submitButton.isEnabled = viewModel.canSubmit && !locked submitButton.backgroundColor = submitButton.isEnabled ? DroneDockStyle.primary : DroneDockStyle.secondary.withAlphaComponent(0.45) - navigationItem.rightBarButtonItem?.isEnabled = !working && !isPicking && !isRefreshing + navigationItem.rightBarButtonItems?.first { $0.accessibilityIdentifier == "drone.delivery.refresh" }?.isEnabled = !working && !isPicking && !isRefreshing navigationController?.interactivePopGestureRecognizer?.isEnabled = !working && !isStartingSubmission && !isPicking && (previousGestureEnabled ?? true) } @@ -368,14 +386,23 @@ final class DroneDockDeliveryViewController: BaseViewController { } @objc private func backTapped() { - guard viewModel.isSubmitting || isStartingSubmission || isPicking else { navigationController?.popViewController(animated: true); return } + requestExit { [weak self] in self?.navigationController?.popViewController(animated: true) } + } + + @objc private func closeSheetTapped() { + requestExit { [weak self] in self?.onCloseSheet?() } + } + + private func requestExit(_ exit: @escaping () -> Void) { + guard presentedViewController == nil else { return } + guard viewModel.isSubmitting || isStartingSubmission || isPicking else { exit(); return } let alert = UIAlertController(title: "停止处理并返回?", message: "未完成的上传将停止。如果正在保存成片,返回素材库刷新可核对实际结果。", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "继续处理", style: .cancel)) alert.addAction(UIAlertAction(title: "停止并返回", style: .destructive) { [weak self] _ in guard let self else { return } self.operationTask?.cancel() self.viewModel.invalidate() - self.navigationController?.popViewController(animated: true) + exit() }) present(alert, animated: true) } diff --git a/suixinkan/UI/DroneDock/DroneDockHomeViewController.swift b/suixinkan/UI/DroneDock/DroneDockHomeViewController.swift index 54f8dd7..348a79c 100644 --- a/suixinkan/UI/DroneDock/DroneDockHomeViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockHomeViewController.swift @@ -309,6 +309,7 @@ final class DroneDockHomeViewController: BaseViewController { planeStatusService: DroneDockPlaneStatusAPI(client: NetworkServices.shared.apiClient), taskCreationService: DroneDockTaskCreationAPI(client: NetworkServices.shared.apiClient), shootService: DroneDockShootAPI(client: NetworkServices.shared.apiClient), + allowsTaskSubmission: !DeviceCommandDebugPolicy.blocksLiveRequests, currentContext: { Self.currentContext() } )) } diff --git a/suixinkan/UI/DroneDock/DroneDockMaterialComponents.swift b/suixinkan/UI/DroneDock/DroneDockMaterialComponents.swift new file mode 100644 index 0000000..b853efb --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneDockMaterialComponents.swift @@ -0,0 +1,365 @@ +import Kingfisher +import SnapKit +import UIKit + +/// 真实订单素材库摘要:游客与状态同排,次数始终来自订单详情。 +@MainActor +final class DroneDockMaterialOrderCell: UICollectionViewCell { + private let customerLabel = DroneDockStyle.label(size: 19, weight: .semibold) + private let statusLabel = DroneDockStatusLabel() + private let numberLabel = DroneDockStyle.label(size: 13, color: UIColor(hex: 0x70809D)) + private let countLabel = DroneDockStyle.label(size: 13, color: UIColor(hex: 0x5D6C88)) + + override init(frame: CGRect) { + super.init(frame: frame) + let row = UIStackView(arrangedSubviews: [customerLabel, statusLabel, UIView()]) + row.axis = .horizontal + row.spacing = 8 + row.alignment = .center + customerLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + customerLabel.lineBreakMode = .byTruncatingTail + statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal) + numberLabel.numberOfLines = 2 + countLabel.numberOfLines = 2 + let stack = UIStackView(arrangedSubviews: [row, numberLabel, countLabel]) + stack.axis = .vertical + stack.spacing = 9 + contentView.addSubview(stack) + stack.snp.makeConstraints { make in + make.top.equalToSuperview().offset(16) + make.leading.trailing.equalToSuperview() + make.bottom.equalToSuperview().inset(18) + } + accessibilityIdentifier = "drone.materials.remote.order" + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 不根据任务数量或素材上传状态推导订单拍摄履约状态。 + func apply(order: DroneDockHomeOrder) { + customerLabel.text = order.touristTitle + let tone: DroneDockStatusTone = switch order.shootStatus { + case "completed": .green + case "processing": .blue + case "pending": .orange + default: .gray + } + statusLabel.apply(title: order.statusTitle, tone: tone) + numberLabel.text = order.orderNumberText + let total = order.shotTotal.map(String.init) ?? "—" + let used = order.shotUsed.map(String.init) ?? "—" + let remain = order.shotRemain.map(String.init) ?? "—" + countLabel.text = "含\(total)次拍摄 · 已拍摄\(used)次 · 剩余\(remain)次" + accessibilityLabel = [order.touristTitle, order.statusTitle, order.orderNumberText, countLabel.text].compactMap { $0 }.joined(separator: ",") + } +} + +/// 素材记录标题:点位和交付按钮同排,航线、时间、记录序号位于次行。 +@MainActor +final class DroneDockMaterialRecordCell: UICollectionViewCell { + private let titleLabel = DroneDockStyle.label(size: 17, weight: .semibold) + private let metadataLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary) + private let deliveryButton = UIButton(type: .system) + private let emptyIcon = UIImageView() + private let emptyTitle = DroneDockStyle.label(size: 13, weight: .medium) + private let emptyDetail = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary) + private let emptyPanel = UIStackView() + private let separator = UIView() + private var action: (() -> Void)? + + override init(frame: CGRect) { + super.init(frame: frame) + titleLabel.numberOfLines = 1 + titleLabel.lineBreakMode = .byTruncatingTail + titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + deliveryButton.setContentCompressionResistancePriority(.required, for: .horizontal) + deliveryButton.tintColor = DroneDockStyle.primary + deliveryButton.addTarget(self, action: #selector(deliveryTapped), for: .touchUpInside) + let titleRow = UIStackView(arrangedSubviews: [titleLabel, UIView(), deliveryButton]) + titleRow.axis = .horizontal + titleRow.alignment = .center + titleRow.spacing = 8 + metadataLabel.numberOfLines = 2 + emptyIcon.contentMode = .scaleAspectFit + emptyTitle.numberOfLines = 2 + emptyDetail.numberOfLines = 0 + emptyPanel.axis = .vertical + emptyPanel.alignment = .leading + emptyPanel.spacing = 6 + let emptyHeading = UIStackView(arrangedSubviews: [emptyIcon, emptyTitle]) + emptyHeading.axis = .horizontal + emptyHeading.alignment = .center + emptyHeading.spacing = 6 + emptyIcon.snp.makeConstraints { $0.size.equalTo(16).priority(999) } + emptyPanel.addArrangedSubview(emptyHeading) + emptyPanel.addArrangedSubview(emptyDetail) + let stack = UIStackView(arrangedSubviews: [titleRow, metadataLabel, emptyPanel]) + stack.axis = .vertical + stack.spacing = 7 + stack.setCustomSpacing(14, after: metadataLabel) + contentView.addSubview(stack) + stack.snp.makeConstraints { make in + make.top.equalToSuperview().offset(14) + make.leading.trailing.equalToSuperview() + make.bottom.equalToSuperview().inset(14) + } + deliveryButton.snp.makeConstraints { $0.height.equalTo(44) } + separator.backgroundColor = DroneDockStyle.border + contentView.addSubview(separator) + separator.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview(); make.height.equalTo(0.5) } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 保留无素材任务的独立飞行与上传状态,不伪造文件或上传进度。 + func apply(task: DroneDockMaterialTask, canDeliver: Bool, action: @escaping () -> Void) { + titleLabel.text = usable(task.spotName, fallback: "点位 \(task.spotID)") + let record = task.sequence.map { String(format: "记录%02d", $0) } ?? "记录序号待确认" + metadataLabel.text = "\(usable(task.airLineName, fallback: "航线待确认")) · \(shortDate(task.createdAt)) · \(record)" + var configuration = UIButton.Configuration.plain() + configuration.title = task.film == nil ? "交付成片" : "替换成片" + configuration.image = UIImage(systemName: "play.rectangle") + configuration.imagePadding = 5 + configuration.contentInsets = .zero + configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 13) + configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { value in + var attributes = value + attributes.font = .systemFont(ofSize: 12) + return attributes + } + deliveryButton.configuration = configuration + deliveryButton.isHidden = !canDeliver + deliveryButton.accessibilityIdentifier = "drone.materials.remote.delivery.\(task.id)" + self.action = action + emptyPanel.isHidden = !task.materials.isEmpty + separator.isHidden = !task.materials.isEmpty || task.film != nil + let state: (String, String, String, UIColor) = switch task.materialStatus { + case 0: ("素材待上传", "拍摄完成后将自动上传,请稍后刷新", "icloud.and.arrow.up", DroneDockStyle.secondary) + case 1: ("暂无可用原素材", "素材记录尚未返回,请刷新查看", "photo.on.rectangle", DroneDockStyle.secondary) + case 2: ("素材上传中", "素材正在上传,请稍后刷新查看", "icloud.and.arrow.up", DroneDockStyle.primary) + case 3: ("素材上传失败", "请刷新查看最新状态,或联系工作人员", "xmark.circle", DroneDockStyle.color(for: .red)) + default: ("素材状态待确认", "暂无原素材,请稍后刷新查看", "questionmark.circle", DroneDockStyle.secondary) + } + emptyTitle.text = state.0 + emptyTitle.textColor = state.3 + emptyIcon.image = UIImage(systemName: state.2) + emptyIcon.tintColor = state.3 + let film = task.film == nil ? " · 暂无视频成片" : "" + emptyDetail.text = "\(flightTitle(task.flightStatus))\(film)\n\(state.1)" + accessibilityIdentifier = "drone.materials.remote.task.\(task.id)" + } + + private func usable(_ value: String?, fallback: String) -> String { DroneDockHomeMetric.usableText(value) ?? fallback } + private func shortDate(_ raw: String?) -> String { + guard let raw = DroneDockHomeMetric.usableText(raw) else { return "时间待确认" } + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" + guard let date = formatter.date(from: raw) else { return raw } + formatter.dateFormat = "MM-dd HH:mm" + return formatter.string(from: date) + } + private func flightTitle(_ value: Int?) -> String { + switch value { + case 10: "待飞行" + case 20: "执行中" + case 30: "飞行成功" + case 40: "飞行失败" + case 50: "已取消" + case 60: "待确认" + default: "飞行状态待确认" + } + } + @objc private func deliveryTapped() { action?() } +} + +/// 真实文件的缩略图、状态和选择控件;预览与选择使用独立点击区域。 +@MainActor +final class DroneDockMaterialMediaCell: UICollectionViewCell { + private let thumbnail = UIImageView() + private let icon = UIImageView() + private let previewButton = UIButton(type: .custom) + private let selectionButton = UIButton(type: .custom) + private let videoBadge = DroneDockStyle.label("视频", size: 10, color: .white) + private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium) + private let stateLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary) + private let retryLabel = DroneDockStyle.label("重试上传", size: 11, color: DroneDockStyle.primary.withAlphaComponent(0.5)) + private var previewAction: (() -> Void)? + private var selectionAction: (() -> Void)? + + override init(frame: CGRect) { + super.init(frame: frame) + thumbnail.contentMode = .scaleAspectFill + thumbnail.clipsToBounds = true + thumbnail.layer.cornerRadius = 6 + thumbnail.layer.borderWidth = 2 + thumbnail.backgroundColor = UIColor(hex: 0xE9EDF5) + thumbnail.accessibilityIdentifier = "drone.materials.remote.thumbnail" + icon.contentMode = .scaleAspectFit + titleLabel.lineBreakMode = .byTruncatingMiddle + titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + retryLabel.setContentCompressionResistancePriority(.required, for: .horizontal) + retryLabel.accessibilityTraits = [.button, .notEnabled] + retryLabel.accessibilityHint = "当前接口不支持重试上传,可通过页面刷新查看最新状态" + videoBadge.textAlignment = .center + videoBadge.backgroundColor = UIColor.black.withAlphaComponent(0.48) + videoBadge.layer.cornerRadius = 3 + videoBadge.clipsToBounds = true + previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside) + selectionButton.addTarget(self, action: #selector(selectionTapped), for: .touchUpInside) + let nameRow = UIStackView(arrangedSubviews: [titleLabel, retryLabel]) + nameRow.axis = .horizontal + nameRow.spacing = 4 + nameRow.alignment = .center + [thumbnail, icon, previewButton, videoBadge, selectionButton, nameRow, stateLabel].forEach(contentView.addSubview) + thumbnail.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview(); make.height.equalTo(thumbnail.snp.width).multipliedBy(9.0 / 16.0) } + icon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(28) } + previewButton.snp.makeConstraints { $0.edges.equalTo(thumbnail) } + selectionButton.snp.makeConstraints { make in make.top.trailing.equalTo(thumbnail); make.size.equalTo(44) } + videoBadge.snp.makeConstraints { make in make.leading.bottom.equalTo(thumbnail).inset(6); make.size.equalTo(CGSize(width: 32, height: 18)) } + nameRow.snp.makeConstraints { make in make.top.equalTo(thumbnail.snp.bottom).offset(7); make.leading.trailing.equalToSuperview() } + stateLabel.snp.makeConstraints { make in make.top.equalTo(nameRow.snp.bottom).offset(4); make.leading.trailing.equalToSuperview(); make.bottom.lessThanOrEqualToSuperview().inset(5) } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + override func prepareForReuse() { + super.prepareForReuse() + thumbnail.kf.cancelDownloadTask() + thumbnail.image = nil + previewAction = nil + selectionAction = nil + } + + /// 原素材上传就绪且 URL 有效才可勾选;Mock 图片存在时不请求远程缩略图。 + func apply(file: DroneDockMaterialFile, taskID: Int, selected: Bool, selectionEnabled: Bool, + localImage: UIImage?, allowsRemoteImage: Bool, preview: @escaping () -> Void, select: @escaping () -> Void) { + let ready = file.previewURL != nil + let state: (String, UIColor) = switch file.uploadStatus { + case 0: ("待上传", DroneDockStyle.secondary) + case 1: (ready ? "上传完成 · 可下载" : "暂不可预览", ready ? DroneDockStyle.success : DroneDockStyle.secondary) + case 2: ("上传中", DroneDockStyle.primary) + case 3: ("上传失败", DroneDockStyle.color(for: .red)) + default: ("素材状态待确认", DroneDockStyle.secondary) + } + let title = DroneDockHomeMetric.usableText(file.fileName) ?? "原素材 \(file.id)" + apply(title: title, state: state.0, color: state.1, cover: ready ? file.coverURL : nil, + fallback: ready && file.fileType == 1 ? file.previewURL : nil, video: file.fileType == 2, + enabled: ready, failed: file.uploadStatus == 3, localImage: ready ? localImage : nil, + allowsRemoteImage: allowsRemoteImage, identifier: "drone.materials.remote.file.\(taskID).\(file.id)") + previewAction = preview + selectionAction = select + selectionButton.isHidden = !ready + selectionButton.isEnabled = ready && selectionEnabled + selectionButton.accessibilityIdentifier = "drone.materials.remote.select.\(taskID).\(file.id)" + selectionButton.accessibilityLabel = "选择\(title)" + selectionButton.accessibilityTraits = selected ? [.button, .selected] : .button + selectionButton.setImage(DroneMaterialSelectionIcon.image(selected: selected, tint: selected ? DroneDockStyle.primary : .white), for: .normal) + selectionButton.imageView?.layer.shadowColor = UIColor.black.cgColor + selectionButton.imageView?.layer.shadowOpacity = 0.25 + selectionButton.imageView?.layer.shadowRadius = 2 + selectionButton.imageView?.layer.shadowOffset = .zero + thumbnail.layer.borderColor = selected ? DroneDockStyle.primary.cgColor : UIColor.clear.cgColor + previewButton.accessibilityHint = file.uploadStatus == 3 ? DroneDockHomeMetric.usableText(file.failureReason) : nil + } + + /// 已交付成片独立标记且不参与原素材全选。 + func apply(film: DroneDockMaterialFilm, taskID: Int, localImage: UIImage?, allowsRemoteImage: Bool, + preview: @escaping () -> Void) { + let ready = film.previewURL != nil + apply(title: DroneDockHomeMetric.usableText(film.fileName) ?? "视频成片", state: ready ? "视频成片 · 点击播放" : "视频成片 · 暂不可预览", + color: ready ? DroneDockStyle.success : DroneDockStyle.secondary, cover: film.coverURL, fallback: nil, + video: true, enabled: ready, failed: false, localImage: localImage, allowsRemoteImage: allowsRemoteImage, + identifier: "drone.materials.remote.film.\(taskID).\(film.id)") + selectionButton.isHidden = true + selectionAction = nil + previewAction = preview + previewButton.accessibilityHint = nil + thumbnail.layer.borderColor = UIColor.clear.cgColor + } + + private func apply(title: String, state: String, color: UIColor, cover: String?, fallback: URL?, video: Bool, + enabled: Bool, failed: Bool, localImage: UIImage?, allowsRemoteImage: Bool, identifier: String) { + thumbnail.kf.cancelDownloadTask() + thumbnail.image = localImage + let coverURL = cover.flatMap(URL.init(string:)).flatMap { url in + ["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host != nil ? url : nil + } + if allowsRemoteImage, enabled { thumbnail.kf.setImage(with: coverURL ?? fallback) } + icon.image = UIImage(systemName: failed ? "xmark.circle" : video ? "play.fill" : "photo") + icon.tintColor = failed ? DroneDockStyle.color(for: .red) : UIColor(hex: 0x9CA6B6) + icon.isHidden = enabled && (localImage != nil || coverURL != nil || fallback != nil) + titleLabel.text = title + stateLabel.text = state + stateLabel.textColor = color + retryLabel.isHidden = !failed + retryLabel.accessibilityIdentifier = identifier + ".retryUpload" + videoBadge.isHidden = !video || !enabled + previewButton.isEnabled = enabled + previewButton.accessibilityIdentifier = identifier + ".preview" + previewButton.accessibilityLabel = "\(title),\(state)" + accessibilityIdentifier = identifier + accessibilityLabel = "\(title),\(state)" + accessibilityTraits = enabled ? .button : [.notEnabled] + } + + @objc private func previewTapped() { previewAction?() } + @objc private func selectionTapped() { selectionAction?() } +} + +/// 居中展示列表加载、空态和错误;刷新失败与没有素材是不同状态。 +@MainActor +final class DroneDockMaterialMessageCell: UICollectionViewCell { + private let icon = UIImageView() + private let titleLabel = DroneDockStyle.label(size: 16, weight: .medium) + private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary) + private let button = UIButton(type: .system) + private let spinner = UIActivityIndicatorView(style: .medium) + private var action: (() -> Void)? + + override init(frame: CGRect) { + super.init(frame: frame) + icon.contentMode = .scaleAspectFit + icon.tintColor = DroneDockStyle.secondary + titleLabel.textAlignment = .center + titleLabel.numberOfLines = 2 + detailLabel.textAlignment = .center + detailLabel.numberOfLines = 0 + button.tintColor = DroneDockStyle.primary + button.addTarget(self, action: #selector(retryTapped), for: .touchUpInside) + let stack = UIStackView(arrangedSubviews: [icon, spinner, titleLabel, detailLabel, button]) + stack.axis = .vertical + stack.alignment = .center + stack.spacing = 12 + contentView.addSubview(stack) + stack.snp.makeConstraints { make in make.centerY.equalToSuperview(); make.leading.trailing.equalToSuperview().inset(12) } + icon.snp.makeConstraints { $0.size.equalTo(38).priority(999) } + button.snp.makeConstraints { $0.height.equalTo(44).priority(999) } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 不将错误转换为空列表,未提供重试闭包时隐藏操作。 + func apply(title: String, detail: String, identifier: String, loading: Bool = false, + error: Bool = false, retry: (() -> Void)? = nil) { + titleLabel.text = title + detailLabel.text = detail + detailLabel.isHidden = detail.isEmpty + icon.image = UIImage(systemName: error ? "exclamationmark.circle" : "photo.on.rectangle.angled") + icon.isHidden = loading + if loading { spinner.startAnimating() } else { spinner.stopAnimating() } + spinner.isHidden = !loading + spinner.alpha = loading ? 1 : 0 + button.isHidden = retry == nil + button.setTitle("重试", for: .normal) + button.accessibilityIdentifier = "drone.materials.remote.retry" + action = retry + accessibilityIdentifier = identifier + } + + @objc private func retryTapped() { action?() } +} diff --git a/suixinkan/UI/DroneDock/DroneDockMaterialsSimulation.swift b/suixinkan/UI/DroneDock/DroneDockMaterialsSimulation.swift new file mode 100644 index 0000000..67ee4b6 --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneDockMaterialsSimulation.swift @@ -0,0 +1,196 @@ +import SnapKit +import UIKit + +#if DEBUG +/// 使用正式订单素材页和内存服务验证各展示状态,不读取登录身份或连接后端。 +@MainActor +enum DroneDockMaterialsSimulation { + /// 支持显式场景参数,未传场景的模拟入口默认展示混合上传状态。 + static func makeController(arguments: [String]) -> UIViewController? { + let flag = "--dock-materials-mock" + guard arguments.contains(flag) || arguments.contains(where: { $0.hasPrefix(flag + "=") }) else { return nil } + let value = arguments.first(where: { $0.hasPrefix(flag + "=") }).map { String($0.dropFirst(flag.count + 1)) } + return makeController(scenario: value ?? "mixed") + } + + /// 创建全新模拟会话;同一页的点位筛选、选择及刷新仍由正式 ViewModel 执行。 + static func makeController(scenario: String) -> UIViewController? { + let state = DroneDockMaterialsMockScenario(rawValue: scenario) ?? .mixed + guard let service = try? DroneDockMaterialsMockService(scenario: state) else { return nil } + let context = DroneDockHomeContext(userID: "local-materials-mock", accountType: "store_user", + scenicID: 901, scenicName: "本地模拟景区", storeID: 901, + photographerName: "本地演示", token: "local-materials-only") + let model = DroneDockMaterialsViewModel(context: context, order: service.order, + service: service, currentContext: { context }) + let controller = DroneDockMaterialsViewController(viewModel: model, + deliveryControllerFactory: { _, _, _ in + DroneDockMaterialsMockPreviewController(title: "交付成片 · 本地演示", image: nil, + message: "本地演示仅验证入口,不连接云端或上传文件。") + }, + thumbnailProvider: { taskID, fileID, isFilm in + guard isFilm || service.isReady(taskID: taskID, fileID: fileID) else { return nil } + return UIImage(named: taskID == 902 ? "drone_demo_pagoda" : fileID.isMultiple(of: 2) ? "drone_demo_mountain" : "drone_demo_tourists") + }, + mediaPreviewControllerFactory: { _, isVideo, title in + DroneDockMaterialsMockPreviewController(title: title, image: UIImage(named: "drone_demo_tourists"), + message: isVideo ? "本地演示视频封面,不请求远程片源。" : "本地演示图片,不请求远程文件。") + }) + controller.navigationItem.prompt = "本地演示 · 未联网" + return controller + } +} + +/// 上传、记录及首屏异常的固定样例,不表示实际接口或设备状态。 +private enum DroneDockMaterialsMockScenario: String { + case ready, uploading, uploadFailed, mixed, empty, loading, error, taskUploading, taskFailed, film +} + +/// 通过正式解码器构造的纯内存素材服务,没有真实网络或共享账号依赖。 +@MainActor +private final class DroneDockMaterialsMockService: DroneDockMaterialsServing { + private let scenario: DroneDockMaterialsMockScenario + private let detailValue: DroneDockMaterialDetail + private let taskValues: [[String: Any]] + + /// 合成订单用于正式页面的入口身份,不可用于真实请求。 + var order: DroneDockHomeOrder { detailValue.order } + + /// 固定三条拍摄记录与两处购买点位,文件状态由场景决定。 + init(scenario: DroneDockMaterialsMockScenario) throws { + self.scenario = scenario + let detail: [String: Any] = [ + "order_number": "LOCAL-MOCK-MATERIALS-901", "project_id": 901, + "project_name": "模拟航拍套餐", "user_phone": "158****8888", + "shoot_count": 5, "shot_count": scenario == .empty ? 0 : 3, + "remaining_count": scenario == .empty ? 5 : 2, "shoot_status": "processing", + "order_status": 20, "can_upload_film": true, "can_create_task": true, + "spot": [["scenic_spot_id": 301, "scenic_spot_name": "三皇寨"], + ["scenic_spot_id": 302, "scenic_spot_name": "金阙云宫"]] + ] + detailValue = try JSONDecoder().decode(DroneDockMaterialDetail.self, + from: JSONSerialization.data(withJSONObject: detail)) + taskValues = scenario == .empty ? [] : [3, 2, 1].map { sequence in + let taskID = 900 + sequence + let isPagoda = sequence == 2 + let files: [[String: Any]] = [sequence * 2 - 1, sequence * 2].map { fileID in + let status = Self.uploadStatus(scenario: scenario, sequence: sequence, fileID: fileID) + return ["id": fileID, "file_name": String(format: "素材%02d", fileID), + "file_type": fileID.isMultiple(of: 2) ? 1 : 2, + "file_size": 4_194_304, + "file_url": status == 1 ? "https://mock.invalid/media/\(taskID)/\(fileID)" : "", + "cover_url": "", "upload_status": status, + "failure_reason": status == 3 ? "本地演示:素材上传失败,请刷新查看最新状态" : ""] + } + let taskOnly = scenario == .taskUploading || scenario == .taskFailed + var task: [String: Any] = [ + "id": taskID, "order_number": "LOCAL-MOCK-MATERIALS-901", "seq": sequence, + "scenic_spot_id": isPagoda ? 302 : 301, + "scenic_spot_name": isPagoda ? "金阙云宫" : "三皇寨", + "air_line_name": isPagoda ? "云宫环绕" : "经典航线", + "created_at": "2026-10-29 \(sequence == 3 ? "14:32:00" : sequence == 2 ? "14:10:00" : "13:45:00")", + "flight_status": 30, + "material_status": scenario == .taskFailed || scenario == .uploadFailed ? 3 : scenario == .ready || scenario == .film ? 1 : 2, + "materials": taskOnly ? [] : files, "film": NSNull() + ] + if scenario == .film, sequence == 3 { + task["film"] = ["id": 8001, "task_id": taskID, "file_name": "已交付成片", + "file_size": 8_388_608, "cover_url": "", + "file_url": "https://mock.invalid/film/\(taskID)"] + } + return task + } + } + + /// 纯内存详情;加载场景等待取消,错误场景提供明确失败。 + func detail(scenicID: Int, orderNumber: String) async throws -> DroneDockMaterialDetail { + try validate(scenicID: scenicID, orderNumber: orderNumber) + if scenario == .loading { + while true { try await Task.sleep(nanoseconds: 30_000_000_000) } + } + if scenario == .error { throw APIError.networkFailed("本地演示:订单素材读取失败,请稍后重试") } + try Task.checkCancellation() + return detailValue + } + + /// 根据所选点位过滤内存任务,不发出 HTTP 请求。 + func tasks(scenicID: Int, orderNumber: String, spotID: Int?) async throws -> DroneDockMaterialTasks { + try validate(scenicID: scenicID, orderNumber: orderNumber) + try Task.checkCancellation() + let values = taskValues.filter { spotID == nil || ($0["scenic_spot_id"] as? Int) == spotID } + return try JSONDecoder().decode(DroneDockMaterialTasks.self, from: JSONSerialization.data(withJSONObject: [ + "order_number": orderNumber, "total": values.count, "list": values + ])) + } + + /// 仅就绪样例使用本地缩略图,上传中和失败仍保留页面占位样式。 + func isReady(taskID: Int, fileID: Int) -> Bool { + guard let task = taskValues.first(where: { $0["id"] as? Int == taskID }), + let files = task["materials"] as? [[String: Any]], + let file = files.first(where: { $0["id"] as? Int == fileID }) else { return false } + return file["upload_status"] as? Int == 1 + } + + private func validate(scenicID: Int, orderNumber: String) throws { + guard scenicID == 901, orderNumber == "LOCAL-MOCK-MATERIALS-901" else { + throw APIError.networkFailed("本地素材演示不接受真实订单身份") + } + } + + private static func uploadStatus(scenario: DroneDockMaterialsMockScenario, sequence: Int, fileID: Int) -> Int { + switch scenario { + case .uploading, .taskUploading: return 2 + case .uploadFailed, .taskFailed: return 3 + case .mixed: + if sequence == 3, fileID.isMultiple(of: 2) { return 2 } + if sequence == 2, !fileID.isMultiple(of: 2) { return 3 } + return 1 + default: return 1 + } + } +} + +/// 图片预览及交付入口的本地占位,不使用播放器、云端上传或相册权限。 +@MainActor +private final class DroneDockMaterialsMockPreviewController: BaseViewController { + private let image: UIImage? + private let message: String + private let imageView = UIImageView() + private let messageLabel = UILabel() + + /// 固定当前演示内容,防止跳入真实媒体或上传服务。 + init(title: String, image: UIImage?, message: String) { + self.image = image + self.message = message + super.init(nibName: nil, bundle: nil) + self.title = title + navigationItem.prompt = "本地演示 · 未联网" + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + override func setupUI() { + view.backgroundColor = .systemBackground + imageView.image = image + imageView.contentMode = .scaleAspectFit + messageLabel.text = message + messageLabel.numberOfLines = 0 + messageLabel.font = .systemFont(ofSize: 14) + messageLabel.textAlignment = .center + view.addSubview(imageView) + view.addSubview(messageLabel) + } + + override func setupConstraints() { + imageView.snp.makeConstraints { make in + make.leading.trailing.equalToSuperview().inset(16) + make.top.equalTo(view.safeAreaLayoutGuide).offset(24) + make.height.equalTo(view).multipliedBy(0.5) + } + messageLabel.snp.makeConstraints { make in + make.top.equalTo(imageView.snp.bottom).offset(16) + make.leading.trailing.equalTo(imageView) + } + } +} +#endif diff --git a/suixinkan/UI/DroneDock/DroneDockMaterialsViewController.swift b/suixinkan/UI/DroneDock/DroneDockMaterialsViewController.swift index b997b1b..b1682a1 100644 --- a/suixinkan/UI/DroneDock/DroneDockMaterialsViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockMaterialsViewController.swift @@ -8,6 +8,9 @@ import UIKit final class DroneDockMaterialsViewController: BaseViewController { /// 保存当前订单摘要、点位和任务的真实状态。 let viewModel: DroneDockMaterialsViewModel + private let thumbnailProvider: ((Int, Int, Bool) -> UIImage?)? + private let mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)? + private let footerView = DroneMaterialsFooterView() private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController /// 元数据与媒体分区独立,任务没有素材时也保留其状态。 @@ -28,8 +31,12 @@ final class DroneDockMaterialsViewController: BaseViewController { /// 注入冻结订单范围的只读素材服务。 init(viewModel: DroneDockMaterialsViewModel, - deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil) { + deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil, + thumbnailProvider: ((Int, Int, Bool) -> UIImage?)? = nil, + mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)? = nil) { self.viewModel = viewModel + self.thumbnailProvider = thumbnailProvider + self.mediaPreviewControllerFactory = mediaPreviewControllerFactory self.deliveryControllerFactory = deliveryControllerFactory ?? DroneDockDeliveryEntry.makeController super.init(nibName: nil, bundle: nil) hidesBottomBarWhenPushed = true @@ -43,7 +50,8 @@ final class DroneDockMaterialsViewController: BaseViewController { override func setupNavigationBar() { title = "订单素材库" navigationItem.backButtonDisplayMode = .minimal - let refresh = UIBarButtonItem(title: "刷新", style: .plain, target: self, action: #selector(refreshTapped)) + let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain, target: self, action: #selector(refreshTapped)) + refresh.accessibilityLabel = "刷新素材状态" refresh.accessibilityIdentifier = "drone.materials.remote.refresh" navigationItem.rightBarButtonItem = refresh } @@ -52,9 +60,16 @@ final class DroneDockMaterialsViewController: BaseViewController { view.backgroundColor = .white collectionView.backgroundColor = .white collectionView.alwaysBounceVertical = true + collectionView.showsVerticalScrollIndicator = false collectionView.accessibilityIdentifier = "drone.materials.remote.list" collectionView.delegate = self - collectionView.register(DroneDockMaterialTextCell.self, forCellWithReuseIdentifier: "text") + collectionView.register(DroneDockMaterialOrderCell.self, forCellWithReuseIdentifier: "order") + collectionView.register(DroneMaterialSelectionCell.self, forCellWithReuseIdentifier: "summary") + collectionView.register(DroneDockMaterialRecordCell.self, forCellWithReuseIdentifier: "record") + collectionView.register(DroneDockMaterialMessageCell.self, forCellWithReuseIdentifier: "message") + collectionView.register(DroneMaterialSeparatorView.self, + forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, + withReuseIdentifier: "separator") collectionView.register(DroneMaterialFilterCell.self, forCellWithReuseIdentifier: "filter") collectionView.register(DroneDockMaterialMediaCell.self, forCellWithReuseIdentifier: "media") let refresh = UIRefreshControl() @@ -62,6 +77,9 @@ final class DroneDockMaterialsViewController: BaseViewController { refresh.addTarget(self, action: #selector(refreshTapped), for: .valueChanged) collectionView.refreshControl = refresh view.addSubview(collectionView) + view.addSubview(footerView) + footerView.accessibilityIdentifier = "drone.materials.remote.footer" + footerView.onPrimaryTap = { [weak self] in self?.downloadTapped() } configureDataSource() applySnapshot(animated: false) } @@ -69,8 +87,10 @@ final class DroneDockMaterialsViewController: BaseViewController { override func setupConstraints() { collectionView.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide) - make.leading.trailing.bottom.equalToSuperview() + make.leading.trailing.equalToSuperview() + make.bottom.equalTo(footerView.snp.top) } + footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() } } override func viewWillAppear(_ animated: Bool) { @@ -101,60 +121,81 @@ final class DroneDockMaterialsViewController: BaseViewController { dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { [weak self] collection, path, item in guard let self else { return nil } switch item { + case .order: + let cell = collection.dequeueReusableCell(withReuseIdentifier: "order", for: path) as! DroneDockMaterialOrderCell + if let order = self.viewModel.detail?.order { cell.apply(order: order) } + return cell + case .summary: + let cell = collection.dequeueReusableCell(withReuseIdentifier: "summary", for: path) as! DroneMaterialSelectionCell + cell.apply(recordCount: self.viewModel.total ?? 0, + allSelected: self.viewModel.allDownloadableSelected, + enabled: self.operation == nil && !self.viewModel.selectableMaterialIDs.isEmpty) + cell.accessibilityIdentifier = "drone.materials.remote.summary" + cell.onSelectAllTap = { [weak self] in + guard let self, self.operation == nil else { return } + self.viewModel.toggleSelectAll() + self.applySnapshot(animated: false) + } + return cell case .filter(let id): let cell = collection.dequeueReusableCell(withReuseIdentifier: "filter", for: path) as! DroneMaterialFilterCell let title = id.flatMap { id in self.viewModel.spots.first { $0.id == id } }.map { Self.usable($0.name, fallback: "点位 \($0.id)") } ?? "全部点位" cell.apply(title: title, id: id.map(String.init), selected: id == self.displayedSpotID, locked: self.viewModel.detail == nil) return cell + case .task(let taskID): + let cell = collection.dequeueReusableCell(withReuseIdentifier: "record", for: path) as! DroneDockMaterialRecordCell + if let task = self.task(taskID) { + cell.apply(task: task, canDeliver: self.operation == nil && self.viewModel.detail?.order.canUploadFilm == true) { [weak self] in + self?.openDelivery(taskID: taskID) + } + } + return cell case .file(let taskID, let fileID): let cell = collection.dequeueReusableCell(withReuseIdentifier: "media", for: path) as! DroneDockMaterialMediaCell if let file = self.task(taskID)?.materials.first(where: { $0.id == fileID }) { - cell.apply(file: file, taskID: taskID) + let identity = DroneDockMaterialSelectionID(taskID: taskID, fileID: fileID) + cell.apply(file: file, taskID: taskID, + selected: self.viewModel.selectedMaterialIDs.contains(identity), + selectionEnabled: self.operation == nil && self.viewModel.selectableMaterialIDs.contains(identity), + localImage: self.thumbnailProvider?(taskID, fileID, false), + allowsRemoteImage: self.thumbnailProvider == nil, + preview: { [weak self] in self?.previewFile(taskID: taskID, fileID: fileID) }, + select: { [weak self] in + guard let self, self.operation == nil else { return } + self.viewModel.toggleSelection(taskID: taskID, fileID: fileID) + self.applySnapshot(animated: false) + }) } return cell case .film(let taskID, _): let cell = collection.dequeueReusableCell(withReuseIdentifier: "media", for: path) as! DroneDockMaterialMediaCell - if let film = self.task(taskID)?.film { cell.apply(film: film, taskID: taskID) } + if let film = self.task(taskID)?.film { + cell.apply(film: film, taskID: taskID, localImage: self.thumbnailProvider?(taskID, film.id, true), + allowsRemoteImage: self.thumbnailProvider == nil) { [weak self] in self?.previewFilm(taskID: taskID) } + } return cell - default: - let cell = collection.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! DroneDockMaterialTextCell - self.configureText(cell, item: item) + case .message: + let cell = collection.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DroneDockMaterialMessageCell + self.configureMessage(cell) return cell } } + dataSource.supplementaryViewProvider = { collection, kind, path in + collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "separator", for: path) + } } - private func configureText(_ cell: DroneDockMaterialTextCell, item: Item) { - switch item { - case .order: - guard let order = viewModel.detail?.order else { return } - cell.apply(title: order.touristTitle, body: "\(order.orderNumberText)\n\(order.packageTitle) · \(order.statusTitle)\n\(order.progressTitle)", identifier: "drone.materials.remote.order") - case .summary: - let text = viewModel.total.map { "\($0) 条任务记录 · 最新在前" } ?? "任务记录" - cell.apply(title: text, body: nil, identifier: "drone.materials.remote.summary", compact: true) - case .task(let id): - guard let task = task(id) else { return } - let number = task.sequence.map { "任务 \($0)" } ?? "任务 \(id)" - let title = "\(number) · \(Self.usable(task.spotName, fallback: "点位 \(task.spotID)"))" - var lines = ["\(Self.usable(task.airLineName, fallback: "航线待确认")) · \(Self.flightTitle(task.flightStatus))", - Self.usable(task.createdAt, fallback: "时间待确认")] - if task.materials.isEmpty { lines.append("暂无原素材") } - if task.film == nil { lines.append("暂无视频成片") } - let canDeliver = operation == nil && viewModel.detail?.order.canUploadFilm == true - cell.apply(title: title, body: lines.joined(separator: "\n"), identifier: "drone.materials.remote.task.\(id)", - button: canDeliver ? (task.film == nil ? "交付成片" : "替换成片") : nil, - actionID: "drone.materials.remote.delivery.\(id)") { [weak self] in self?.openDelivery(taskID: id) } - case .message: - if operation != nil || viewModel.isLoading || viewModel.isLoadingTasks { - cell.apply(title: viewModel.detail == nil ? "正在加载订单素材库" : "正在加载任务素材", body: nil, identifier: "drone.materials.remote.loading") - } else if let error = viewModel.detailErrorMessage { - cell.apply(title: "订单信息加载失败", body: error, identifier: "drone.materials.remote.error", button: "重试", actionID: "drone.materials.remote.retry") { [weak self] in self?.load(.refresh) } - } else if let error = viewModel.tasksErrorMessage { - cell.apply(title: "任务素材加载失败", body: error, identifier: "drone.materials.remote.error", button: "重试", actionID: "drone.materials.remote.retry") { [weak self] in self?.load(.retry) } - } else { - cell.apply(title: displayedSpotID == nil ? "暂无任务记录" : "当前点位暂无任务记录", body: "拍摄任务与素材更新后,可下拉刷新查看", identifier: "drone.materials.remote.empty") - } - default: break + private func configureMessage(_ cell: DroneDockMaterialMessageCell) { + if operation != nil || viewModel.isLoading || viewModel.isLoadingTasks { + cell.apply(title: viewModel.detail == nil ? "正在加载订单素材库" : "正在加载任务素材", + detail: "请稍候", identifier: "drone.materials.remote.loading", loading: true) + } else if let error = viewModel.detailErrorMessage { + cell.apply(title: "订单信息加载失败", detail: error, identifier: "drone.materials.remote.error", error: true) { [weak self] in self?.load(.refresh) } + } else if let error = viewModel.tasksErrorMessage { + cell.apply(title: "任务素材加载失败", detail: error, identifier: "drone.materials.remote.error", error: true) { [weak self] in self?.load(.retry) } + } else { + cell.apply(title: displayedSpotID == nil ? "暂无任务记录" : "当前点位暂无任务记录", + detail: "拍摄任务与素材更新后,可下拉刷新查看", identifier: "drone.materials.remote.empty") } } @@ -175,22 +216,33 @@ final class DroneDockMaterialsViewController: BaseViewController { case .media: let width = (environment.container.effectiveContentSize.width - 44) / 2 let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1))) - let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(width * 0.57 + 72)), repeatingSubitem: item, count: 2) + let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(width * 9 / 16 + 51)), repeatingSubitem: item, count: 2) group.interItemSpacing = .fixed(12) let section = NSCollectionLayoutSection(group: group) section.contentInsets = .init(top: 0, leading: 16, bottom: 16, trailing: 16) section.interGroupSpacing = 12 + section.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem( + layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(1)), + elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom)] return section + case .message: + return self.singleColumnSection(height: .absolute(250)) + case .summary: + return self.singleColumnSection(height: .absolute(46)) default: - let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .estimated(80))) - let group = NSCollectionLayoutGroup.vertical(layoutSize: item.layoutSize, subitems: [item]) - let section = NSCollectionLayoutSection(group: group) - section.contentInsets = .init(top: 0, leading: 16, bottom: 0, trailing: 16) - return section + return self.singleColumnSection(height: .estimated(90)) } } } + private func singleColumnSection(height: NSCollectionLayoutDimension) -> NSCollectionLayoutSection { + let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: height)) + let group = NSCollectionLayoutGroup.vertical(layoutSize: item.layoutSize, subitems: [item]) + let section = NSCollectionLayoutSection(group: group) + section.contentInsets = .init(top: 0, leading: 16, bottom: 0, trailing: 16) + return section + } + private func applySnapshot(animated: Bool) { guard dataSource != nil else { return } var snapshot = NSDiffableDataSourceSnapshot() @@ -217,6 +269,11 @@ final class DroneDockMaterialsViewController: BaseViewController { snapshot.appendSections([.message]) snapshot.appendItems([.message], toSection: .message) } + footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "", + primaryTitle: "下载所选素材", primarySymbol: "arrow.down.to.line", + enabled: operation == nil && viewModel.selectedCount > 0, + identifier: "drone.materials.remote.download", progress: nil, + trailingText: "仅可选择已上传素材") let previous = Set(dataSource.snapshot().itemIdentifiers) snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { previous.contains($0) }) dataSource.apply(snapshot, animatingDifferences: animated) @@ -250,8 +307,25 @@ final class DroneDockMaterialsViewController: BaseViewController { navigationController.pushViewController(deliveryControllerFactory(order, viewModel.context, taskID), animated: true) } + private func downloadTapped() { + guard operation == nil, viewModel.selectedCount > 0 else { return } + showAlert(title: "下载功能暂未开放", message: "已选择的素材会保留。当前版本尚未接入下载和保存相册功能。") + } + + private func previewFile(taskID: Int, fileID: Int) { + guard operation == nil, let file = task(taskID)?.materials.first(where: { $0.id == fileID }), let url = file.previewURL else { return } + preview(url: url, isVideo: file.fileType == 2, title: file.fileName ?? "原素材") + } + + private func previewFilm(taskID: Int) { + guard operation == nil, let film = task(taskID)?.film, let url = film.previewURL else { return } + preview(url: url, isVideo: true, title: film.fileName ?? "视频成片") + } + private func preview(url: URL, isVideo: Bool, title: String) { - if isVideo { + if let mediaPreviewControllerFactory { + navigationController?.pushViewController(mediaPreviewControllerFactory(url, isVideo, title), animated: true) + } else if isVideo { let player = AVPlayerViewController() player.player = AVPlayer(url: url) present(player, animated: true) { player.player?.play() } @@ -264,17 +338,7 @@ final class DroneDockMaterialsViewController: BaseViewController { DroneDockHomeMetric.usableText(value) ?? fallback } - private static func flightTitle(_ status: Int?) -> String { - switch status { - case 10: "待飞行" - case 20: "执行中" - case 30: "飞行成功" - case 40: "飞行失败" - case 50: "已取消" - case 60: "待确认" - default: "飞行状态待确认" - } - } + } extension DroneDockMaterialsViewController: UICollectionViewDelegate { @@ -286,138 +350,14 @@ extension DroneDockMaterialsViewController: UICollectionViewDelegate { guard viewModel.detail != nil, id != displayedSpotID else { return } load(.filter(id)) case .file(let taskID, let fileID): - guard operation == nil, let file = task(taskID)?.materials.first(where: { $0.id == fileID }), let url = file.previewURL else { return } - preview(url: url, isVideo: file.fileType == 2, title: file.fileName ?? "原素材") + previewFile(taskID: taskID, fileID: fileID) case .film(let taskID, _): - guard operation == nil, let film = task(taskID)?.film, let url = film.previewURL else { return } - preview(url: url, isVideo: true, title: film.fileName ?? "视频成片") + previewFilm(taskID: taskID) default: break } } } -/// 摘要、任务状态及可恢复错误共用的自适应文字行。 -@MainActor -private final class DroneDockMaterialTextCell: UICollectionViewCell { - private let titleLabel = DroneDockStyle.label(size: 15, weight: .semibold) - private let bodyLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary) - private let button = UIButton(type: .system) - private var action: (() -> Void)? - - override init(frame: CGRect) { - super.init(frame: frame) - titleLabel.numberOfLines = 0 - bodyLabel.numberOfLines = 0 - let stack = UIStackView(arrangedSubviews: [titleLabel, bodyLabel, button]) - stack.axis = .vertical - stack.spacing = 8 - stack.alignment = .leading - contentView.addSubview(stack) - stack.snp.makeConstraints { make in make.edges.equalToSuperview().inset(UIEdgeInsets(top: 14, left: 0, bottom: 16, right: 0)) } - titleLabel.snp.makeConstraints { $0.width.equalTo(stack) } - bodyLabel.snp.makeConstraints { $0.width.equalTo(stack) } - button.tintColor = DroneDockStyle.primary - button.addTarget(self, action: #selector(tapped), for: .touchUpInside) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } - - /// 切换内容时同时清除复用单元的旧操作。 - func apply(title: String, body: String?, identifier: String, compact: Bool = false, - button buttonTitle: String? = nil, actionID: String? = nil, action: (() -> Void)? = nil) { - titleLabel.text = title - titleLabel.font = .systemFont(ofSize: compact ? 13 : 15, weight: .semibold) - bodyLabel.text = body - bodyLabel.isHidden = body == nil - button.isHidden = buttonTitle == nil - button.setTitle(buttonTitle, for: .normal) - button.accessibilityIdentifier = actionID - self.action = action - accessibilityIdentifier = identifier - } - - @objc private func tapped() { action?() } -} - -/// 加载远程缩略图并明确区分原素材、视频成片及不可预览状态。 -@MainActor -private final class DroneDockMaterialMediaCell: UICollectionViewCell { - private let thumbnail = UIImageView() - private let icon = UIImageView() - private let titleLabel = DroneDockStyle.label(size: 12, weight: .medium) - private let stateLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary) - - override init(frame: CGRect) { - super.init(frame: frame) - thumbnail.contentMode = .scaleAspectFill - thumbnail.clipsToBounds = true - thumbnail.layer.cornerRadius = 8 - thumbnail.backgroundColor = DroneDockStyle.background - icon.tintColor = DroneDockStyle.secondary - icon.contentMode = .scaleAspectFit - titleLabel.numberOfLines = 2 - stateLabel.numberOfLines = 2 - [thumbnail, icon, titleLabel, stateLabel].forEach(contentView.addSubview) - thumbnail.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview(); make.height.equalTo(thumbnail.snp.width).multipliedBy(0.57) } - icon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(28) } - titleLabel.snp.makeConstraints { make in make.top.equalTo(thumbnail.snp.bottom).offset(8); make.leading.trailing.equalToSuperview() } - stateLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(4); make.leading.trailing.equalToSuperview(); make.bottom.lessThanOrEqualToSuperview() } - isAccessibilityElement = true - } - - @available(*, unavailable) - required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } - - override func prepareForReuse() { - super.prepareForReuse() - thumbnail.kf.cancelDownloadTask() - thumbnail.image = nil - } - - /// 未就绪的原素材仍显示服务端状态,但不会启动播放或下载。 - func apply(file: DroneDockMaterialFile, taskID: Int) { - let state: String - switch file.uploadStatus { - case 0: state = "待上传" - case 1: state = file.previewURL == nil ? "暂不可预览" : (file.fileType == 2 ? "点击播放" : "点击预览") - case 2: state = "上传中" - case 3: state = "上传失败" - default: state = "素材状态待确认" - } - let kind = file.fileType == 1 ? "图片" : file.fileType == 2 ? "视频" : "文件" - let title = DroneDockHomeMetric.usableText(file.fileName) ?? "原素材 \(file.id)" - apply(title: title, state: "原素材 · \(kind) · \(state)", cover: file.coverURL, - fallback: file.fileType == 1 ? file.previewURL : nil, video: file.fileType == 2, - enabled: file.previewURL != nil, identifier: "drone.materials.remote.file.\(taskID).\(file.id)") - accessibilityHint = file.uploadStatus == 3 ? DroneDockHomeMetric.usableText(file.failureReason) : nil - } - - /// 成片是任务中的独立视频,不混入原素材数量或上传状态。 - func apply(film: DroneDockMaterialFilm, taskID: Int) { - apply(title: DroneDockHomeMetric.usableText(film.fileName) ?? "视频成片", state: "视频成片 · \(film.previewURL == nil ? "暂不可预览" : "点击播放")", - cover: film.coverURL, fallback: nil, video: true, enabled: film.previewURL != nil, - identifier: "drone.materials.remote.film.\(taskID).\(film.id)") - accessibilityHint = nil - } - - private func apply(title: String, state: String, cover: String?, fallback: URL?, video: Bool, enabled: Bool, identifier: String) { - thumbnail.kf.cancelDownloadTask() - thumbnail.image = nil - let coverURL = cover.flatMap(URL.init(string:)).flatMap { url in - ["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host != nil ? url : nil - } - thumbnail.kf.setImage(with: coverURL ?? fallback) - icon.image = UIImage(systemName: video && enabled ? "play.circle.fill" : video ? "video" : "photo") - icon.isHidden = !video && (coverURL ?? fallback) != nil - titleLabel.text = title - stateLabel.text = state - accessibilityIdentifier = identifier - accessibilityLabel = "\(title),\(state)" - accessibilityTraits = enabled ? .button : [.notEnabled] - } -} - /// 通过 Kingfisher 展示真实图片,加载失败保留明确提示。 @MainActor private final class DroneDockMaterialImageViewController: UIViewController { diff --git a/suixinkan/UI/DroneDock/DroneDockOrdersViewController.swift b/suixinkan/UI/DroneDock/DroneDockOrdersViewController.swift index a6326d9..9a6f35e 100644 --- a/suixinkan/UI/DroneDock/DroneDockOrdersViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockOrdersViewController.swift @@ -16,6 +16,7 @@ final class DroneDockOrdersViewController: BaseViewController { private var dataSource: UICollectionViewDiffableDataSource! private var loadTask: Task? private var operation: LoadAction? + private weak var deliverySheet: UINavigationController? /// 使用订单号更新同一张卡片,空态和分页入口也纳入快照。 private enum Item: Hashable { case order(String), message, more } @@ -92,11 +93,13 @@ final class DroneDockOrdersViewController: BaseViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) + guard deliverySheet == nil else { return } load(.refresh) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) + guard deliverySheet == nil else { return } loadTask?.cancel() operation = nil collectionView.refreshControl?.endRefreshing() @@ -205,9 +208,16 @@ final class DroneDockOrdersViewController: BaseViewController { private func showUnavailable(_ feature: String) { showAlert(title: feature, message: "该功能暂未开放") } private func openDelivery(orderID: String) { - guard operation == nil, let order = viewModel.orders.first(where: { $0.orderID == orderID }), + guard operation == nil, presentedViewController == nil, + let order = viewModel.orders.first(where: { $0.orderID == orderID }), order.canUploadFilm == true else { return } - navigationController?.pushViewController(deliveryControllerFactory(order, viewModel.context, nil), animated: true) + let sheet = DroneDockDeliveryEntry.makeMethodSheet(order: order, context: viewModel.context, + controllerFactory: deliveryControllerFactory) { [weak self] in + guard let self, self.viewIfLoaded?.window != nil else { return } + self.load(.refresh) + } + deliverySheet = sheet + present(sheet, animated: true) } private func openMaterials(orderID: String) { diff --git a/suixinkan/UI/DroneDock/DroneDockPreview.swift b/suixinkan/UI/DroneDock/DroneDockPreview.swift index a9c0c30..43a2517 100644 --- a/suixinkan/UI/DroneDock/DroneDockPreview.swift +++ b/suixinkan/UI/DroneDock/DroneDockPreview.swift @@ -6,6 +6,12 @@ import UIKit enum DroneDockPreview { /// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。 static func navigationController(arguments: [String]) -> UINavigationController? { + if let materials = DroneDockMaterialsSimulation.makeController(arguments: arguments) { + return UINavigationController(rootViewController: materials) + } + if let simulation = DroneDockStartShootSimulation.makeController(arguments: arguments) { + return UINavigationController(rootViewController: simulation) + } // 仅打开已存在任务进行只读联调;不经过创建或召唤流程。 if let taskArgument = arguments.first(where: { $0.hasPrefix("--dock-task-live=") }), let taskID = Int(taskArgument.dropFirst("--dock-task-live=".count)), taskID > 0, diff --git a/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift b/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift index 06a0b63..8b74a1f 100644 --- a/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift @@ -26,12 +26,15 @@ final class DroneDockRemotePreparationViewController: BaseViewController { private var isApplicationActive = false private var automaticallyOpenedTaskID: Int? private let taskControllerFactory: @MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController + private let simulationRecordsProvider: (@MainActor () -> String)? /// 注入准备页业务状态和轮询等待,便于验证任务创建及页面生命周期。 init(viewModel: DroneDockPreparationViewModel, taskControllerFactory: (@MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil, + simulationRecordsProvider: (@MainActor () -> String)? = nil, planeStatusPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) { self.viewModel = viewModel + self.simulationRecordsProvider = simulationRecordsProvider self.taskControllerFactory = taskControllerFactory ?? { taskID, order, context in DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context) } @@ -51,8 +54,42 @@ final class DroneDockRemotePreparationViewController: BaseViewController { } override func setupNavigationBar() { - title = "拍摄准备" + title = simulationRecordsProvider == nil ? "拍摄准备" : "拍摄准备 · 本地模拟" navigationItem.backButtonDisplayMode = .minimal + if simulationRecordsProvider != nil { + let records = UIBarButtonItem(image: UIImage(systemName: "doc.text"), style: .plain, + target: self, action: #selector(showSimulationRecords)) + records.accessibilityLabel = "查看模拟接口回执" + records.accessibilityIdentifier = "drone.preparation.mock.recordsButton" + navigationItem.rightBarButtonItem = records + } + #if DEBUG + if simulationRecordsProvider == nil, DeviceCommandDebugPolicy.blocksLiveRequests, + viewModel.isTaskSubmissionBlocked { + let simulation = UIBarButtonItem(title: "本地模拟", style: .plain, + target: self, action: #selector(openLocalSimulation)) + simulation.accessibilityIdentifier = "drone.preparation.mock.entry" + navigationItem.rightBarButtonItem = simulation + } + #endif + } + + #if DEBUG + /// 打开独立模拟订单,不沿用真实会话、服务或当前订单创建任务。 + @objc private func openLocalSimulation() { + guard !isStartingCreation, !viewModel.isCreatingTask, !viewModel.isSummoning, + let navigationController, navigationController.topViewController === self, + let controller = DroneDockStartShootSimulation.makePreparationController() else { return } + navigationController.pushViewController(controller, animated: true) + } + #endif + + /// 显示内存传输记录,并明确说明其不是后端真实回执。 + @objc private func showSimulationRecords() { + guard let simulationRecordsProvider, presentedViewController == nil, + !isStartingCreation, !viewModel.isCreatingTask, !viewModel.isSummoning else { return } + let controller = DroneDockSimulationRecordsViewController(records: simulationRecordsProvider()) + present(UINavigationController(rootViewController: controller), animated: true) } override func setupUI() { @@ -200,7 +237,8 @@ final class DroneDockRemotePreparationViewController: BaseViewController { if viewModel.errorMessage != nil { applySnapshot(animated: false) } else { - footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation) + footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation, + isLocalSimulation: simulationRecordsProvider != nil) } return viewModel.pollIntervalNanoseconds } @@ -214,7 +252,8 @@ final class DroneDockRemotePreparationViewController: BaseViewController { @objc private func applicationWillResignActive() { isApplicationActive = false stopPlaneStatusPolling() - footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation) + footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation, + isLocalSimulation: simulationRecordsProvider != nil) } @objc private func applicationDidBecomeActive() { @@ -290,6 +329,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController { } private func applySnapshot(animated: Bool, completion: (() -> Void)? = nil) { + navigationItem.rightBarButtonItem?.isEnabled = !isStartingCreation && !viewModel.isCreatingTask && !viewModel.isSummoning guard dataSource != nil else { return } let previous = dataSource.snapshot() let existing = Set(previous.itemIdentifiers) @@ -312,7 +352,8 @@ final class DroneDockRemotePreparationViewController: BaseViewController { snapshot.appendItems([.shootResult], toSection: .shootResult) } snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) }) - footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation) + footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation, + isLocalSimulation: simulationRecordsProvider != nil) 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) diff --git a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift index eebe9f8..f66e176 100644 --- a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift @@ -1,7 +1,7 @@ import SnapKit import UIKit -/// 真实拍摄任务页:进入后仅查询同一任务,展示状态与遥测,不发送飞行控制。 +/// 拍摄任务页:真实入口只读,本地模拟入口可注入开始拍摄服务验证接口流程。 @MainActor final class DroneDockShootingTaskViewController: BaseViewController { /// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。 @@ -20,16 +20,21 @@ final class DroneDockShootingTaskViewController: BaseViewController { private var compactLayout: Bool? private var bottomInset: CGFloat = -1 private let materialsControllerFactory: @MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController + private let simulationRecordsProvider: (@MainActor () -> String)? private var refreshTask: Task? + private var startTask: Task? private var requestGeneration = 0 private var isPageVisible = false private var isApplicationActive = false private var isRequesting = false + private var isStartingAction = false /// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。 init(viewModel: DroneDockShootingTaskViewModel, - materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) { + materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil, + simulationRecordsProvider: (@MainActor () -> String)? = nil) { self.viewModel = viewModel + self.simulationRecordsProvider = simulationRecordsProvider self.materialsControllerFactory = materialsControllerFactory ?? { order, context in DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel( context: context, order: order, @@ -45,18 +50,26 @@ final class DroneDockShootingTaskViewController: BaseViewController { deinit { refreshTask?.cancel() + startTask?.cancel() NotificationCenter.default.removeObserver(self) } /// 使用常规导航返回准备页,不劫持返回手势或自动创建任务。 override func setupNavigationBar() { - title = "拍摄任务" + title = simulationRecordsProvider == nil ? "拍摄任务" : "拍摄任务 · 本地模拟" navigationItem.backButtonDisplayMode = .minimal let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain, target: self, action: #selector(refreshTriggered)) refresh.accessibilityLabel = "刷新任务状态" refresh.accessibilityIdentifier = "drone.task.remote.navigationRefresh" navigationItem.rightBarButtonItem = refresh + if simulationRecordsProvider != nil { + let records = UIBarButtonItem(image: UIImage(systemName: "doc.text"), style: .plain, + target: self, action: #selector(showSimulationRecords)) + records.accessibilityLabel = "查看模拟接口回执" + records.accessibilityIdentifier = "drone.task.mock.recordsButton" + navigationItem.rightBarButtonItems = [refresh, records] + } } /// 顶部、中间状态和安全控制分开布局,状态切换不影响外部区域大小。 @@ -139,7 +152,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { taskTitleLabel.font = .systemFont(ofSize: compact ? 16 : 17, weight: .semibold) } - /// 仅绑定读取、详情和已有素材入口;本轮不发送飞控指令。 + /// 模拟服务明确注入时才允许开始;真实入口仍只提供读取、详情和已有素材。 override func bindActions() { statusView.onPrimaryAction = { [weak self] in self?.primaryActionTriggered() } statusView.onDetails = { [weak self] in self?.showStatusDetails() } @@ -166,7 +179,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { private func applySnapshot() { guard isViewLoaded else { return } - let loading = isRequesting || viewModel.isLoading + let loading = isRequesting || viewModel.isLoading || isStartingAction || viewModel.isStartingShooting taskTitleLabel.text = viewModel.title subtitleLabel.text = viewModel.subtitle let telemetry = viewModel.telemetry @@ -178,21 +191,24 @@ final class DroneDockShootingTaskViewController: BaseViewController { deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation statusView.apply(value, isRefreshing: loading) statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading - navigationItem.rightBarButtonItem?.isEnabled = isPageVisible && isApplicationActive && !loading + navigationItem.rightBarButtonItems?.forEach { $0.isEnabled = isPageVisible && isApplicationActive && !loading } navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil } private func primaryActionTriggered() { - guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return } + guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading, + !isStartingAction, !viewModel.isStartingShooting else { return } let state = viewModel.presentation guard state.isActionEnabled else { return } switch state.action { case .refresh: refreshTaskIfVisible() + case .start: + startShootingIfAllowed() case .materials: guard let navigationController, navigationController.topViewController === self else { return } navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true) - case .start, .resume, .retry, .none: + case .resume, .retry, .none: break } } @@ -204,6 +220,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { if viewModel.response != nil, let error = viewModel.errorMessage { texts.append("刷新失败,当前显示上次数据:\(error)") } + if let error = viewModel.startErrorMessage { texts.append(error) } var distinct: [String] = [] for text in texts where !distinct.contains(text) { distinct.append(text) } let alert = UIAlertController(title: "任务状态详情", message: distinct.joined(separator: "\n\n"), preferredStyle: .alert) @@ -213,7 +230,8 @@ final class DroneDockShootingTaskViewController: BaseViewController { /// 页面进入、回到前台或手动刷新时各读一次,请求结束后不安排下一次读取。 private func refreshTaskIfVisible() { - guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return } + guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading, + !isStartingAction, !viewModel.isStartingShooting else { return } requestGeneration &+= 1 let generation = requestGeneration isRequesting = true @@ -236,11 +254,44 @@ final class DroneDockShootingTaskViewController: BaseViewController { requestGeneration &+= 1 refreshTask?.cancel() refreshTask = nil + startTask?.cancel() + startTask = nil + isStartingAction = false isRequesting = false viewModel.invalidate(preservingSnapshot: true) applySnapshot() } + /// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。 + private func startShootingIfAllowed() { + guard !isStartingAction, viewModel.canStartShooting else { return } + requestGeneration &+= 1 + let generation = requestGeneration + isStartingAction = true + applySnapshot() + startTask = Task { @MainActor [weak self] in + guard let self else { return } + await self.viewModel.startShooting { [weak self] in self?.applySnapshot() } + guard self.isPageVisible, self.isApplicationActive, + self.requestGeneration == generation, !Task.isCancelled else { return } + self.startTask = nil + self.isStartingAction = false + self.applySnapshot() + if let error = self.viewModel.startErrorMessage { + self.showToast(error) + } else if let error = self.viewModel.errorMessage { + self.showToast("开始请求已受理,状态刷新失败:\(error)") + } + } + } + + /// 模拟入口专用记录页,内容由内存传输提供,不请求后端日志或设备。 + @objc private func showSimulationRecords() { + guard let simulationRecordsProvider, presentedViewController == nil else { return } + let controller = DroneDockSimulationRecordsViewController(records: simulationRecordsProvider()) + present(UINavigationController(rootViewController: controller), animated: true) + } + @objc private func refreshTriggered() { guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return @@ -260,6 +311,44 @@ final class DroneDockShootingTaskViewController: BaseViewController { } } +/// 以可选择的 JSON 文本展示本地模拟请求与回执,避免与真实接口联调混淆。 +@MainActor +final class DroneDockSimulationRecordsViewController: BaseViewController { + private let records: String + private let textView = UITextView() + + /// 固定展示打开时的内存记录快照。 + init(records: String) { + self.records = records + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + override func setupNavigationBar() { + title = "本地模拟回执(未联网)" + navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: .done, + target: self, action: #selector(close)) + } + + override func setupUI() { + view.backgroundColor = .systemBackground + textView.isEditable = false + textView.font = .monospacedSystemFont(ofSize: 12, weight: .regular) + textView.text = records + textView.accessibilityIdentifier = "drone.task.mock.records" + textView.textContainerInset = UIEdgeInsets(top: 16, left: 12, bottom: 24, right: 12) + view.addSubview(textView) + } + + override func setupConstraints() { + textView.snp.makeConstraints { make in make.edges.equalTo(view.safeAreaLayoutGuide) } + } + + @objc private func close() { dismiss(animated: true) } +} + /// 固定底部的安全控制占位,尚未接入控制接口时不提供可执行的飞控动作。 @MainActor private final class DroneDockTaskSafetyView: UIView { diff --git a/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift b/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift new file mode 100644 index 0000000..9d9de9d --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift @@ -0,0 +1,300 @@ +import Foundation +import UIKit + +#if DEBUG +/// 独立的准备、召唤与开拍模拟入口;所有请求在内存中处理,不复用账号或真实网络服务。 +@MainActor +enum DroneDockStartShootSimulation { + /// 显式启动参数选择准备页或任务页,两个入口始终使用隔离的模拟会话。 + static func makeController(arguments: [String]) -> UIViewController? { + let startsAtPreparation = arguments.contains("--dock-preparation-mock") + guard startsAtPreparation || arguments.contains("--dock-start-shoot-mock") else { return nil } + let resultArgument = arguments.first { $0.hasPrefix("--dock-start-shoot-result=") } + let result = resultArgument.flatMap { + DroneDockStartShootMockResult(rawValue: String($0.dropFirst("--dock-start-shoot-result=".count))) + } ?? .success + return makeFlow(result: result, startsAtPreparation: startsAtPreparation) + } + + /// 从正式准备页进入全新的纯内存模拟,不携带真实订单、账号或设备身份。 + static func makePreparationController() -> DroneDockRemotePreparationViewController? { + makeFlow(result: .success, startsAtPreparation: true) as? DroneDockRemotePreparationViewController + } + + private static func makeFlow(result: DroneDockStartShootMockResult, + startsAtPreparation: Bool) -> UIViewController? { + let session = DroneDockStartShootMockSession(result: result, requiresPreparation: startsAtPreparation) + let environment = APIEnvironment(baseURL: URL(string: "https://mock.invalid")!, + webSocketURL: URL(string: "wss://mock.invalid/unused")!) + let client = APIClient(environment: environment, session: session) + let context = DroneDockHomeContext(userID: "local-start-shoot-mock", accountType: "store_user", + scenicID: 128, scenicName: "本地模拟景区", storeID: 38, + photographerName: "模拟操作员", token: "local-simulation-only") + let orderData = Data(#"{"order_number":"LOCAL-MOCK-ORDER-901","project_id":101,"project_name":"模拟五次套餐","user_phone":"本地模拟游客","shoot_count":5,"shot_count":0,"remaining_count":5}"#.utf8) + guard let order = try? JSONDecoder().decode(DroneDockHomeOrder.self, from: orderData) else { return nil } + let taskFactory: @MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController = { taskID, taskOrder, taskContext in + let model = DroneDockShootingTaskViewModel(context: taskContext, taskID: taskID, order: taskOrder, + service: DroneDockShootingAPI(client: client), + startService: DroneDockStartShootAPI(client: client), currentContext: { context }) + return DroneDockShootingTaskViewController(viewModel: model, + materialsControllerFactory: { _, _ in + let unavailable = UIViewController() + unavailable.title = "本地模拟不连接素材库" + unavailable.view.backgroundColor = .systemBackground + return unavailable + }, + simulationRecordsProvider: { session.transcriptJSON }) + } + guard startsAtPreparation else { return taskFactory(901, order, context) } + let model = DroneDockPreparationViewModel(context: context, order: order, + service: DroneDockPreparationAPI(client: client), + planeStatusService: DroneDockPlaneStatusAPI(client: client), + taskCreationService: DroneDockTaskCreationAPI(client: client), + shootService: DroneDockShootAPI(client: client), allowsTaskSubmission: true, + currentContext: { context }) + return DroneDockRemotePreparationViewController(viewModel: model, + taskControllerFactory: taskFactory, + simulationRecordsProvider: { session.transcriptJSON }) + } +} + +/// 模拟开拍请求的三种结果,不构成真实接口结果或设备执行反馈。 +private enum DroneDockStartShootMockResult: String { + case success + case businessFailure = "business-failure" + case timeout +} + +/// 无任何网络转发能力的响应替身;仅接受 mock.invalid 上约定的准备、模拟召唤和开拍请求。 +private final class DroneDockStartShootMockSession: LocalSimulationURLSession { + private let result: DroneDockStartShootMockResult + private let lock = NSLock() + private var hasCreated: Bool + private var hasSummoned: Bool + private var hasStarted = false + private var exchanges: [Exchange] = [] + + /// 固定当前实例结果,不能用参数切换到真实传输。 + init(result: DroneDockStartShootMockResult, requiresPreparation: Bool) { + self.result = result + hasCreated = !requiresPreparation + hasSummoned = !requiresPreparation + } + + /// 全部本地请求及完整模拟回执;任务、设备、游客均为虚构测试身份。 + var transcriptJSON: String { + let records = lock.withLock { exchanges } + let items: [[String: Any]] = records.map { record in + var item: [String: Any] = ["method": record.request.httpMethod ?? "", + "path": record.request.url?.path ?? ""] + if let query = record.request.url?.query { item["query"] = query } + if let body = record.request.httpBody { + item["request_body"] = (try? JSONSerialization.jsonObject(with: body)) ?? String(decoding: body, as: UTF8.self) + } + if let response = record.responseData { + item["http_status"] = 200 + item["response_body"] = (try? JSONSerialization.jsonObject(with: response)) ?? String(decoding: response, as: UTF8.self) + } + if let error = record.error { item["error"] = error } + return item + } + let object: [String: Any] = ["source": "local_mock", "description": "纯内存模拟,未调用后端或设备", + "network_sent": false, "scenario": result.rawValue, "records": items] + guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) else { + return "本地模拟记录暂不可显示;没有网络请求。" + } + return String(decoding: data, as: UTF8.self) + } + + /// 模拟少量等待后返回内存响应,任何未知请求均在本机失败,绝不回退真实请求。 + func data(for request: URLRequest) async throws -> (Data, URLResponse) { + print("[LOCAL MOCK][Request] \(request.httpMethod ?? "") \(request.url?.absoluteString ?? "") — 不联网") + if let body = request.httpBody { print(String(decoding: body, as: UTF8.self)) } + do { + try Task.checkCancellation() + if request.httpMethod == "POST" { try await Task.sleep(nanoseconds: 400_000_000) } + try Task.checkCancellation() + let data = try lock.withLock { try responseData(for: request) } + lock.withLock { exchanges.append(Exchange(request: request, responseData: data, error: nil)) } + guard let url = request.url, + let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil) else { + throw URLError(.badURL) + } + print("[LOCAL MOCK][Response] \(String(decoding: data, as: UTF8.self))") + return (data, response) + } catch { + let message = error is CancellationError ? "本地模拟请求取消" : error.localizedDescription + lock.withLock { exchanges.append(Exchange(request: request, responseData: nil, error: message)) } + print("[LOCAL MOCK][Error] \(message) — 没有网络或设备指令") + throw error + } + } + + private func responseData(for request: URLRequest) throws -> Data { + guard let url = request.url, url.scheme == "https", url.host == "mock.invalid" else { + throw URLError(.unsupportedURL) + } + if request.httpMethod == "GET", url.path == "/api/yf-handset-app/photog/multi-plane/project-info" { + guard queryMatches(url, required: ["scenic_id": "128", "project_id": "101", + "order_number": "LOCAL-MOCK-ORDER-901"]) else { throw URLError(.badURL) } + var payload = orderData() + payload["spot"] = [["scenic_spot_id": 301, "scenic_spot_name": "模拟点位", "available": true, + "air_lines": [["air_line_id": 401, "air_line_name": "模拟航线", + "available": true, "samples": []]]]] + return try envelope(payload) + } + if request.httpMethod == "GET", url.path == "/api/app/airport/plane-status" { + guard queryMatches(url, required: ["scenic_id": "128", "live_battery": "1"]) else { throw URLError(.badURL) } + let plane: [String: Any] = ["id": 201, "name": "本地模拟无人机", "sn_number": "LOCAL-MOCK-PLANE-201", + "online_status": 1, "work_status": 1, "work_status_label": "空闲(模拟)", + "status_text": "本地模拟 · 电量 95%", "battery_percent": 95, + "can_fly": true, "is_receive_order": 1] + return try envelope(["scenic_id": 128, "connected": true, "planes": [plane], + "recommend": plane, "poll_hint_ms": 30000]) + } + if request.httpMethod == "POST", url.path == "/api/yf-handset-app/photog/multi-plane/tasks/create" { + guard url.query == nil, let body = request.httpBody, + let object = try JSONSerialization.jsonObject(with: body) as? [String: Any], + Set(object.keys) == ["scenic_id", "order_number", "scenic_spot_id", "air_line_id"], + let values = try? JSONDecoder().decode(CreateBody.self, from: body), + values.scenicID == 128, values.orderNumber == "LOCAL-MOCK-ORDER-901", + values.spotID == 301, values.airLineID == 401 else { throw URLError(.badURL) } + guard !hasCreated else { return try envelope([:], code: 100099, message: "本地模拟:任务已经创建") } + hasCreated = true + var payload = orderData() + payload["task_id"] = 901 + return try envelope(payload) + } + if request.httpMethod == "POST", url.path == "/api/app/airport/shoot" { + guard url.query == nil, let body = request.httpBody, + let object = try JSONSerialization.jsonObject(with: body) as? [String: Any], + Set(object.keys) == ["id", "restart"], + let values = try? JSONDecoder().decode(ShootBody.self, from: body), + values.id == 901, !values.restart else { throw URLError(.badURL) } + guard hasCreated, !hasSummoned else { + return try envelope([:], code: 100099, message: "本地模拟:任务尚未创建或已召唤") + } + hasSummoned = true + return try envelope(["order_flight_task": taskData(), "order_flight_task_id": 901, + "plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201", + "task_uuid": "LOCAL-MOCK-TASK-UUID-901", + "ui": ["phase": "arrived_pending_start", "title": "无人机已到达(模拟)", + "message": "本地模拟召唤成功,没有网络或设备指令。"]]) + } + if request.httpMethod == "GET", url.path == "/api/app/airport/shooting" { + let query = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] + guard query.filter({ $0.name == "id" }).map(\.value) == ["901"] else { + throw URLError(.badURL) + } + guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") } + return try envelope(shootingData()) + } + guard request.httpMethod == "POST", url.path == "/api/app/airport/start-shoot", + url.query == nil, let body = request.httpBody, + let object = try JSONSerialization.jsonObject(with: body) as? [String: Any], + Set(object.keys) == ["id"], + (try? JSONDecoder().decode(StartBody.self, from: body).id) == 901 else { + throw URLError(.unsupportedURL) + } + guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") } + guard !hasStarted else { + return try envelope([:], code: 100099, message: "本地模拟:该任务已开始,请读取任务状态") + } + switch result { + case .businessFailure: + return try envelope([:], code: 100099, message: "本地模拟:电量不足,暂不可开始拍摄") + case .timeout: + throw URLError(.timedOut) + case .success: + hasStarted = true + return try envelope([ + "task_uuid": "LOCAL-MOCK-TASK-UUID-901", "order_flight_task_id": 901, + "order_flight_task": taskData(), "plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201", + "ui": ["phase": "shooting", "title": "无人机正在拍摄中(模拟)", + "message": "本地模拟开拍回执,不代表真实设备执行。", "primary_action": "shooting", + "commands": [["command": "flighttask_pause", "label": "紧急暂停", "sub": "悬停待命"], + ["command": "return_home", "label": "立即返航", "sub": "中断任务"]]] + ]) + } + } + + private func queryMatches(_ url: URL, required: [String: String]) -> Bool { + let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] + return items.count == required.count && required.allSatisfy { key, value in + items.filter { $0.name == key }.map(\.value) == [value] + } + } + + private func orderData() -> [String: Any] { + ["order_number": "LOCAL-MOCK-ORDER-901", "project_id": 101, "project_name": "模拟五次套餐", + "user_phone": "本地模拟游客", "shoot_count": 5, "shot_count": 0, "remaining_count": 5, + "shoot_status": "processing", "order_status": 20, "can_create_task": true, + "can_upload_film": false, "can_confirm": false, "film_count": 0] + } + + private func shootingData() -> [String: Any] { + ["order_number": "LOCAL-MOCK-ORDER-901", "order_flight_task": taskData(), "task": taskData(), + "scenic": ["id": 128, "name": "本地模拟景区"], + "scenic_spot": ["id": 301, "name": "模拟点位"], + "air_line": ["id": 401, "name": "模拟航线", "scenic_spot_id": 301], + "header": ["order_number": "LOCAL-MOCK-ORDER-901", "title": "模拟点位 · 模拟航线", + "tourist_label": "本地模拟,无设备指令", "package_name": "模拟套餐 · 含5次拍摄"], + "current_plane": ["id": 201, "sn_number": "LOCAL-MOCK-PLANE-201", "online_status": 1, + "work_status": hasStarted ? 2 : 1, "work_status_label": hasStarted ? "拍摄中" : "空闲", + "status_text": hasStarted ? "模拟拍摄中 · 电量95%" : "模拟就绪 · 电量95%"], + "metrics": [["key": "battery", "value": "95%"], ["key": "env_temp", "value": "20.3℃"], + ["key": "wind_speed", "value": "0m/s"], ["key": "rainfall", "value": "无雨"], + ["key": "signal", "value": "良好"], ["key": "satellite", "value": "36颗"]], + "plane_status": ["scenic_id": 128, "connected": true, "poll_hint_ms": 5000], + "execute_gate": ["can_execute": !hasStarted, "code": hasStarted ? "already_started" : "ok", + "message": hasStarted ? "本地模拟:开拍已受理" : "本地模拟:允许验证开拍请求", + "primary_action": hasStarted ? "shooting" : "start_shoot", + "primary_action_label": hasStarted ? "拍摄中" : "开始拍摄"], + "ui": ["phase": hasStarted ? "shooting" : "arrived_pending_start", + "title": hasStarted ? "无人机正在拍摄中(模拟)" : "无人机已到达(模拟)", + "message": hasStarted ? "本地模拟状态回查:拍摄中,未向设备发送指令。" : "点击开始拍摄,仅验证本地接口流程。"]] + } + + private func taskData() -> [String: Any] { + ["id": 901, "order_number": "LOCAL-MOCK-ORDER-901", "scenic_id": 128, + "status": 20, "status_label": "执行中(模拟)", "wayline_status": 20, "wayline_status_label": "执行中(模拟)"] + } + + private func envelope(_ data: [String: Any], code: Int = 100000, message: String = "local mock success") throws -> Data { + try JSONSerialization.data(withJSONObject: ["code": code, "msg": message, "data": data], + options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) + } + + /// 完整记录每次本地请求结果,数据不落到真实接口或共享会话中。 + private struct Exchange { + let request: URLRequest + let responseData: Data? + let error: String? + } + + /// 创建模拟任务仍验证真实合同的四项身份,不接受其他订单或航线。 + private struct CreateBody: Decodable { + let scenicID: Int + let orderNumber: String + let spotID: Int + let airLineID: Int + + /// 张工任务创建请求字段。 + private enum CodingKeys: String, CodingKey { + case scenicID = "scenic_id", orderNumber = "order_number" + case spotID = "scenic_spot_id", airLineID = "air_line_id" + } + } + + /// 召唤只接受同一模拟任务且禁止重启,不产生真实设备操作。 + private struct ShootBody: Decodable { + let id: Int + let restart: Bool + } + + /// 用强类型解码确认本地开拍请求的 id 为整数。 + private struct StartBody: Decodable { + let id: Int + } +} +#endif diff --git a/suixinkan/UI/DroneDock/DroneMaterialComponents.swift b/suixinkan/UI/DroneDock/DroneMaterialComponents.swift index e2a77e6..e91b548 100644 --- a/suixinkan/UI/DroneDock/DroneMaterialComponents.swift +++ b/suixinkan/UI/DroneDock/DroneMaterialComponents.swift @@ -1,6 +1,34 @@ import SnapKit import UIKit +/// 缩略图上的选择圆圈,显式绘制白色勾选以免透出背景图片。 +@MainActor +enum DroneMaterialSelectionIcon { + /// 使用固定配色绘制选择状态,避免按钮重新应用系统 tint。 + static func image(selected: Bool, tint: UIColor, opacity: CGFloat = 1) -> UIImage { + UIGraphicsImageRenderer(size: CGSize(width: 24, height: 24)).image { context in + context.cgContext.setAlpha(opacity) + let circle = UIBezierPath(ovalIn: CGRect(x: 1, y: 1, width: 22, height: 22)) + tint.set() + if selected { + circle.fill() + UIColor.white.setStroke() + let check = UIBezierPath() + check.move(to: CGPoint(x: 6.5, y: 12)) + check.addLine(to: CGPoint(x: 10.5, y: 16)) + check.addLine(to: CGPoint(x: 17.5, y: 7.5)) + check.lineWidth = 2.2 + check.lineCapStyle = .round + check.lineJoinStyle = .round + check.stroke() + } else { + circle.lineWidth = 1.6 + circle.stroke() + } + }.withRenderingMode(.alwaysOriginal) + } +} + /// 素材库的订单摘要,保留拍摄履约与素材处理相互独立的表达。 @MainActor final class DroneMaterialOrderCell: UICollectionViewCell { @@ -154,6 +182,15 @@ final class DroneMaterialSelectionCell: UICollectionViewCell { config.imagePadding = 6 config.contentInsets = .zero config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 15) + let foreground = enabled ? DroneDockStyle.primary : UIColor(hex: 0xC2C9D4) + config.baseForegroundColor = foreground + config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in + var attributes = incoming + attributes.font = .systemFont(ofSize: 12) + attributes.foregroundColor = foreground + return attributes + } + config.imageColorTransformer = UIConfigurationColorTransformer { _ in foreground } selectAllButton.configuration = config selectAllButton.isEnabled = enabled selectAllButton.accessibilityLabel = "全选可下载" @@ -181,6 +218,13 @@ final class DroneMaterialRecordHeaderView: UICollectionReusableView { config.imagePadding = 5 config.contentInsets = .zero config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 13) + config.baseForegroundColor = DroneDockStyle.primary + config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in + var attributes = incoming + attributes.font = .systemFont(ofSize: 12) + attributes.foregroundColor = DroneDockStyle.primary + return attributes + } deliveryButton.configuration = config deliveryButton.tintColor = DroneDockStyle.primary deliveryButton.addTarget(self, action: #selector(deliveryTapped), for: .touchUpInside) @@ -193,7 +237,7 @@ final class DroneMaterialRecordHeaderView: UICollectionReusableView { deliveryButton.snp.makeConstraints { make in make.trailing.equalToSuperview() make.centerY.equalTo(titleLabel) - make.height.equalTo(40) + make.height.equalTo(44) } detailLabel.snp.makeConstraints { make in make.leading.trailing.equalToSuperview() @@ -229,8 +273,10 @@ final class DroneMaterialCell: UICollectionViewCell { private let selectionButton = UIButton(type: .custom) private let placeholderIcon = UIImageView() private let videoBadge = UILabel() - private let nameLabel = DroneDockStyle.label(size: 12, weight: .medium) - private let statusLabel = DroneDockStyle.label(size: 11) + private let nameLabel = DroneDockStyle.label(size: 13, weight: .medium) + private let statusLabel = DroneDockStyle.label(size: 12) + private let retryUploadButton = UIButton(type: .system) + private let nameRow = UIStackView() override init(frame: CGRect) { super.init(frame: frame) @@ -252,10 +298,23 @@ final class DroneMaterialCell: UICollectionViewCell { selectionButton.imageView?.contentMode = .scaleAspectFit selectionButton.addTarget(self, action: #selector(selectionTapped), for: .touchUpInside) previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside) - [thumbnail, placeholderIcon, previewButton, videoBadge, selectionButton, nameLabel, statusLabel].forEach(contentView.addSubview) + retryUploadButton.setTitle("重试上传", for: .normal) + retryUploadButton.titleLabel?.font = .systemFont(ofSize: 11) + retryUploadButton.isEnabled = false + retryUploadButton.setTitleColor(DroneDockStyle.primary.withAlphaComponent(0.55), for: .disabled) + retryUploadButton.accessibilityHint = "当前演示不执行上传重试" + nameRow.axis = .horizontal + nameRow.alignment = .center + nameRow.spacing = 6 + nameRow.addArrangedSubview(nameLabel) + nameRow.addArrangedSubview(retryUploadButton) + retryUploadButton.setContentHuggingPriority(.required, for: .horizontal) + retryUploadButton.setContentCompressionResistancePriority(UILayoutPriority(999), for: .horizontal) + retryUploadButton.snp.makeConstraints { make in make.height.equalTo(16) } + [thumbnail, placeholderIcon, previewButton, videoBadge, selectionButton, nameRow, statusLabel].forEach(contentView.addSubview) thumbnail.snp.makeConstraints { make in make.leading.trailing.top.equalToSuperview() - make.height.equalTo(thumbnail.snp.width).multipliedBy(0.57) + make.height.equalTo(thumbnail.snp.width).multipliedBy(9.0 / 16.0) } previewButton.snp.makeConstraints { make in make.edges.equalTo(thumbnail) } placeholderIcon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(29) } @@ -269,13 +328,13 @@ final class DroneMaterialCell: UICollectionViewCell { make.top.trailing.equalTo(thumbnail) make.size.equalTo(44) } - nameLabel.snp.makeConstraints { make in + nameRow.snp.makeConstraints { make in make.leading.trailing.equalToSuperview() make.top.equalTo(thumbnail.snp.bottom).offset(7) } statusLabel.snp.makeConstraints { make in make.leading.trailing.equalToSuperview() - make.top.equalTo(nameLabel.snp.bottom).offset(4) + make.top.equalTo(nameRow.snp.bottom).offset(4) make.bottom.lessThanOrEqualToSuperview().inset(5) } } @@ -291,7 +350,10 @@ final class DroneMaterialCell: UICollectionViewCell { thumbnail.image = material.canPreview ? UIImage(named: material.previewAssetName) : nil thumbnail.layer.borderColor = selected ? DroneDockStyle.primary.cgColor : UIColor.clear.cgColor placeholderIcon.isHidden = material.canPreview - placeholderIcon.image = UIImage(systemName: material.uploadState == .failed ? "exclamationmark.icloud" : "play.fill") + placeholderIcon.image = UIImage(systemName: material.uploadState == .failed ? "xmark.circle" : "play.fill") + placeholderIcon.tintColor = material.uploadState == .failed ? DroneDockStyle.color(for: .red) : UIColor(hex: 0x9CA6B6) + retryUploadButton.isHidden = material.uploadState != .failed + retryUploadButton.accessibilityIdentifier = "drone.materials.retryUpload.\(material.id)" videoBadge.isHidden = material.kind != .video || !material.canPreview previewButton.isEnabled = material.canPreview previewButton.accessibilityIdentifier = "drone.materials.preview.\(material.id)" @@ -301,11 +363,9 @@ final class DroneMaterialCell: UICollectionViewCell { selectionButton.accessibilityIdentifier = "drone.materials.select.\(material.id)" selectionButton.accessibilityLabel = completed ? "\(material.title),演示完成,未写入相册" : "选择\(material.title)" selectionButton.accessibilityTraits = selected || completed ? [.button, .selected] : .button - let symbol = UIImage(systemName: selected || completed ? "checkmark.circle.fill" : "circle", - withConfiguration: UIImage.SymbolConfiguration(pointSize: 22, weight: .regular)) let tint = completed ? DroneDockStyle.success : selected ? DroneDockStyle.primary : UIColor.white - selectionButton.setImage(symbol?.withTintColor(tint, renderingMode: .alwaysOriginal), for: .normal) - selectionButton.setImage(symbol?.withTintColor(tint.withAlphaComponent(0.6), renderingMode: .alwaysOriginal), for: .disabled) + selectionButton.setImage(DroneMaterialSelectionIcon.image(selected: selected || completed, tint: tint), for: .normal) + selectionButton.setImage(DroneMaterialSelectionIcon.image(selected: selected || completed, tint: tint, opacity: 0.6), for: .disabled) selectionButton.imageView?.layer.shadowColor = UIColor.black.cgColor selectionButton.imageView?.layer.shadowOpacity = 0.22 selectionButton.imageView?.layer.shadowRadius = 2 @@ -375,6 +435,9 @@ final class DroneMaterialsFooterView: UIView { /// 返回选择状态或请求预留的交付入口。 var onSecondaryTap: (() -> Void)? private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium) + private let trailingLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary) + private let resultIcon = UIImageView() + private let titleRow = UIStackView() private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary) private let progressView = UIProgressView(progressViewStyle: .default) private let primaryButton = UIButton(type: .system) @@ -389,7 +452,19 @@ final class DroneMaterialsFooterView: UIView { stack.axis = .vertical stack.spacing = 10 titleLabel.numberOfLines = 2 + titleLabel.accessibilityIdentifier = "drone.materials.footer.title" + trailingLabel.accessibilityIdentifier = "drone.materials.footer.trailing" + trailingLabel.textAlignment = .right + trailingLabel.setContentHuggingPriority(.required, for: .horizontal) + trailingLabel.setContentCompressionResistancePriority(UILayoutPriority(999), for: .horizontal) + resultIcon.contentMode = .scaleAspectFit + resultIcon.accessibilityIdentifier = "drone.materials.footer.resultIcon" + titleRow.axis = .horizontal + titleRow.alignment = .center + titleRow.spacing = 8 + [resultIcon, titleLabel, trailingLabel].forEach(titleRow.addArrangedSubview) detailLabel.numberOfLines = 2 + detailLabel.accessibilityIdentifier = "drone.materials.footer.detail" progressView.progressTintColor = DroneDockStyle.primary progressView.trackTintColor = UIColor(hex: 0xE8EDF7) progressView.accessibilityLabel = "本次演示下载完成项数" @@ -403,7 +478,7 @@ final class DroneMaterialsFooterView: UIView { secondaryButton.tintColor = DroneDockStyle.secondary primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside) secondaryButton.addTarget(self, action: #selector(secondaryTapped), for: .touchUpInside) - [titleLabel, progressView, detailLabel, primaryButton, secondaryButton].forEach(stack.addArrangedSubview) + [titleRow, progressView, detailLabel, primaryButton, secondaryButton].forEach(stack.addArrangedSubview) addSubview(divider) addSubview(stack) divider.snp.makeConstraints { make in make.leading.trailing.top.equalToSuperview(); make.height.equalTo(1 / UIScreen.main.scale) } @@ -413,8 +488,9 @@ final class DroneMaterialsFooterView: UIView { make.bottom.equalTo(safeAreaLayoutGuide).inset(10) } primaryButton.snp.makeConstraints { make in make.height.equalTo(44) } - secondaryButton.snp.makeConstraints { make in make.height.equalTo(24) } - progressView.snp.makeConstraints { make in make.height.equalTo(3) } + secondaryButton.snp.makeConstraints { make in make.height.equalTo(44).priority(999) } + resultIcon.snp.makeConstraints { make in make.width.height.equalTo(21).priority(999) } + progressView.snp.makeConstraints { make in make.height.equalTo(3).priority(999) } } @available(*, unavailable) @@ -423,9 +499,17 @@ final class DroneMaterialsFooterView: UIView { /// 只接受显示值,按钮语义和下载状态由控制器及 ViewModel 决定。 func apply(title: String, detail: String, primaryTitle: String, primarySymbol: String, enabled: Bool, identifier: String, progress: Double?, secondaryTitle: String? = nil, - tone: DroneDockStatusTone = .gray) { + tone: DroneDockStatusTone = .gray, trailingText: String? = nil, + resultSymbol: String? = nil, secondaryOutlined: Bool = false, secondaryEnabled: Bool = true) { titleLabel.text = title - titleLabel.textColor = tone == .gray ? DroneDockStyle.text : DroneDockStyle.color(for: tone) + titleLabel.textColor = DroneDockStyle.text + titleLabel.font = .systemFont(ofSize: 13, weight: resultSymbol == nil ? .regular : .semibold) + trailingLabel.text = trailingText + trailingLabel.isHidden = trailingText == nil + trailingLabel.textColor = progress == nil ? DroneDockStyle.secondary : DroneDockStyle.primary + resultIcon.image = resultSymbol.flatMap(UIImage.init(systemName:)) + resultIcon.isHidden = resultSymbol == nil + resultIcon.tintColor = DroneDockStyle.color(for: tone) detailLabel.text = detail detailLabel.isHidden = detail.isEmpty progressView.isHidden = progress == nil @@ -436,13 +520,47 @@ final class DroneMaterialsFooterView: UIView { config.imagePadding = 7 config.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12) config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 16) + let primaryForeground: UIColor = enabled || progress == nil ? .white : DroneDockStyle.primary + let primaryBackground = enabled ? DroneDockStyle.primary : UIColor(hex: 0xCEDBFC) + config.cornerStyle = .fixed + config.background.cornerRadius = 7 + config.background.backgroundColor = primaryBackground + config.background.backgroundColorTransformer = UIConfigurationColorTransformer { _ in primaryBackground } + config.baseForegroundColor = primaryForeground + config.imageColorTransformer = UIConfigurationColorTransformer { _ in primaryForeground } + config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in + var attributes = incoming + attributes.font = .systemFont(ofSize: 15, weight: .medium) + attributes.foregroundColor = primaryForeground + return attributes + } primaryButton.configuration = config primaryButton.isEnabled = enabled - primaryButton.backgroundColor = enabled ? DroneDockStyle.primary : UIColor(hex: 0xCEDBFC) + primaryButton.backgroundColor = .clear primaryButton.accessibilityIdentifier = identifier - secondaryButton.setTitle(secondaryTitle, for: .normal) + var secondary = UIButton.Configuration.plain() + secondary.title = secondaryTitle + secondary.image = secondaryOutlined ? UIImage(systemName: "play.rectangle") : nil + secondary.imagePadding = 6 + secondary.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 14) + let secondaryForeground = secondaryOutlined ? DroneDockStyle.primary : DroneDockStyle.secondary + secondary.cornerStyle = .fixed + secondary.background.cornerRadius = 7 + secondary.baseForegroundColor = secondaryForeground + secondary.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in + var attributes = incoming + attributes.font = .systemFont(ofSize: 12) + attributes.foregroundColor = secondaryForeground + return attributes + } + secondaryButton.configuration = secondary + secondaryButton.tintColor = secondaryOutlined ? DroneDockStyle.primary : DroneDockStyle.secondary + secondaryButton.layer.cornerRadius = 7 + secondaryButton.layer.borderWidth = secondaryOutlined ? 1 : 0 + secondaryButton.layer.borderColor = DroneDockStyle.primary.cgColor secondaryButton.isHidden = secondaryTitle == nil - secondaryButton.accessibilityIdentifier = "drone.materials.continueSelecting" + secondaryButton.isEnabled = secondaryEnabled + secondaryButton.accessibilityIdentifier = secondaryOutlined ? "drone.materials.completedDelivery" : "drone.materials.continueSelecting" } @objc private func primaryTapped() { onPrimaryTap?() } diff --git a/suixinkan/UI/DroneDock/DroneMaterialsViewController.swift b/suixinkan/UI/DroneDock/DroneMaterialsViewController.swift index 1fe6de3..1cd3ef3 100644 --- a/suixinkan/UI/DroneDock/DroneMaterialsViewController.swift +++ b/suixinkan/UI/DroneDock/DroneMaterialsViewController.swift @@ -83,7 +83,7 @@ final class DroneMaterialsViewController: BaseViewController { } override func setupNavigationBar() { - title = "订单素材库" + title = "订单素材库 · 演示" navigationItem.backButtonDisplayMode = .minimal let back = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain, target: self, action: #selector(backTapped)) @@ -170,6 +170,10 @@ final class DroneMaterialsViewController: BaseViewController { footerView.onPrimaryTap = { [weak self] in self?.performFooterAction() } footerView.onSecondaryTap = { [weak self] in guard let self else { return } + if self.viewModel.downloadPhase == .completed { + self.chooseCompletedDelivery() + return + } self.viewModel.clearBatch() self.applySnapshot(animated: true) } @@ -373,37 +377,41 @@ final class DroneMaterialsViewController: BaseViewController { footerAction = .permission footerView.apply(title: "无法保存到手机相册", detail: "演示相册权限未开启,恢复后请手动继续。", primaryTitle: "检查相册权限", primarySymbol: "lock", enabled: true, - identifier: "drone.materials.permission", progress: nil, tone: .orange) + identifier: "drone.materials.permission", progress: nil, tone: .blue, resultSymbol: "lock") return } switch viewModel.downloadPhase { case .idle: footerAction = .download - footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "仅可选择已上传素材 · 本次为本地演示", + footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "", primaryTitle: "下载所选素材", primarySymbol: "arrow.down.to.line", enabled: viewModel.canStartDownload, - identifier: "drone.materials.download", progress: nil) + identifier: "drone.materials.download", progress: nil, trailingText: "仅可选择已上传素材") case .downloading, .awaitingSave, .saving: footerAction = .none - footerView.apply(title: "本次下载\(viewModel.batchTotalCount)项 · 已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项", + footerView.apply(title: "本次下载\(viewModel.batchTotalCount)项", detail: "请保持本页开启,下载期间不可更改选择", primaryTitle: viewModel.downloadButtonTitle, primarySymbol: "arrow.triangle.2.circlepath", enabled: false, - identifier: "drone.materials.download", progress: viewModel.batchProgress, tone: .blue) + identifier: "drone.materials.download", progress: viewModel.batchProgress, tone: .blue, + trailingText: "已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项") case .paused: footerAction = .resume - footerView.apply(title: "下载已暂停 · 已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项", + footerView.apply(title: "下载已暂停", detail: "已完成项会保留;继续时仅处理未完成文件。", primaryTitle: "继续下载", primarySymbol: "play.fill", enabled: true, - identifier: "drone.materials.continue", progress: viewModel.batchProgress, tone: .orange) + identifier: "drone.materials.continue", progress: viewModel.batchProgress, tone: .orange, + trailingText: "已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项", resultSymbol: "pause.circle") case .partialFailure: footerAction = .retry - footerView.apply(title: "部分素材下载失败", detail: "演示完成\(viewModel.completedCount)项 · 失败\(viewModel.failedCount)项,重试仅处理失败项", + footerView.apply(title: "部分素材下载失败", detail: "演示成功\(viewModel.completedCount)项 · 失败\(viewModel.failedCount)项,已完成的无需重复下载", primaryTitle: "重试失败素材(\(viewModel.failedCount))", primarySymbol: "arrow.clockwise", enabled: viewModel.failedCount > 0, - identifier: "drone.materials.retry", progress: nil, secondaryTitle: "选择其他素材", tone: .orange) + identifier: "drone.materials.retry", progress: nil, secondaryTitle: "选择其他素材", tone: .orange, + resultSymbol: "exclamationmark.triangle") case .completed: footerAction = .selectMore - footerView.apply(title: "本次素材演示完成", detail: "\(viewModel.completedCount)项演示完成,未写入系统相册", - primaryTitle: "继续选择素材", primarySymbol: "checkmark.circle", enabled: true, - identifier: "drone.materials.continueSelecting", progress: nil, tone: .green) + footerView.apply(title: "本次素材下载完成(演示)", detail: "\(viewModel.completedCount)项演示完成,未写入系统相册", + primaryTitle: "继续选择素材", primarySymbol: "", enabled: true, + identifier: "drone.materials.continueSelecting", progress: nil, secondaryTitle: "交付成片", tone: .green, + resultSymbol: "checkmark.circle", secondaryOutlined: true, secondaryEnabled: delegate != nil) } } @@ -419,7 +427,7 @@ final class DroneMaterialsViewController: BaseViewController { case .selectMore: viewModel.clearBatch() case .permission: - showAlert(title: "相册权限演示", message: "当前为本地演示,不读取或修改系统相册权限。可在右上角演示状态中选择“模拟相册权限恢复”,再手动继续下载。") + showPermissionSimulation() case .none: return } @@ -432,6 +440,37 @@ final class DroneMaterialsViewController: BaseViewController { transferDriver.start(viewModel: viewModel) { [weak self] in self?.applySnapshot(animated: true) } } + /// 权限说明与恢复只作用于演示状态,不打开系统设置或请求真实 Photos 授权。 + private func showPermissionSimulation() { + let alert = UIAlertController(title: "无法保存到手机相册", + message: "相册权限未开启。当前为本地演示,不读取或修改系统相册权限;模拟恢复后请手动继续下载。", preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "暂不下载", style: .cancel)) + alert.addAction(UIAlertAction(title: "模拟恢复权限", style: .default) { [weak self] _ in + guard let self else { return } + self.viewModel.setPhotoPermission(.allowed) + self.applySnapshot(animated: true) + }) + present(alert, animated: true) + } + + /// 完成底栏的交付入口先明确拍摄记录,不根据下载批次猜测目标点位。 + private func chooseCompletedDelivery() { + guard delegate != nil, !viewModel.sections.isEmpty else { return } + if viewModel.sections.count == 1, let record = viewModel.sections.first { + delegate?.materialsViewController(self, didRequestDelivery: record) + return + } + let sheet = UIAlertController(title: "选择拍摄记录", message: "选择需要交付成片的拍摄记录", preferredStyle: .actionSheet) + for record in viewModel.sections { + sheet.addAction(UIAlertAction(title: "\(record.pointName) · 记录\(record.sequenceNumber)", style: .default) { [weak self] _ in + guard let self else { return } + self.delegate?.materialsViewController(self, didRequestDelivery: record) + }) + } + sheet.addAction(UIAlertAction(title: "取消", style: .cancel)) + present(sheet, animated: true) + } + private func updateInteractivePopGesture() { guard let gesture = navigationController?.interactivePopGestureRecognizer else { return } if hasRunningDownload { diff --git a/suixinkan/UI/DroneDock/DronePreparationComponents.swift b/suixinkan/UI/DroneDock/DronePreparationComponents.swift index b97a7f8..eb6617a 100644 --- a/suixinkan/UI/DroneDock/DronePreparationComponents.swift +++ b/suixinkan/UI/DroneDock/DronePreparationComponents.swift @@ -500,13 +500,15 @@ final class DronePreparationFooterView: UIView { refreshButton.isHidden = !viewModel.shouldShowSummonRefresh } - /// 按购买权限启用待飞任务创建;本阶段不提供无人机召唤或起飞入口。 - func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: Bool = false) { + /// 绑定准备页提交许可;模拟来源仅影响文案,不改变业务权限或真实传输保护。 + func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: Bool = false, + isLocalSimulation: Bool = false) { connectionLabel.apply(title: viewModel.connectionTitle, tone: viewModel.connectionTone) selectionLabel.text = viewModel.selectionSummary selectionLabel.numberOfLines = 2 deviceLabel.apply(title: viewModel.deviceStatusText, tone: viewModel.deviceTone) - primaryButton.setTitle(viewModel.primaryButtonTitle, for: .normal) + let title = isLocalSimulation && viewModel.canCreateTask ? "确认并召唤(模拟)" : viewModel.primaryButtonTitle + primaryButton.setTitle(title, for: .normal) primaryButton.isEnabled = (viewModel.isPrimaryActionEnabled || viewModel.canOpenShootingTask) && !isRefreshing primaryButton.backgroundColor = primaryButton.isEnabled ? DroneDockStyle.primary : UIColor(hex: 0xE1E7F0) primaryButton.setTitleColor(.white, for: .normal) @@ -516,6 +518,9 @@ final class DronePreparationFooterView: UIView { } else { messageLabel.text = viewModel.planeStatusErrorMessage.map { "无人机状态获取失败:\($0)" } ?? viewModel.admissionMessage } + if isLocalSimulation { + messageLabel.text = "本地模拟,不会向无人机发送指令\n" + (messageLabel.text ?? "") + } messageLabel.textColor = DroneDockStyle.secondary refreshButton.isHidden = false refreshButton.isEnabled = !viewModel.isLoading && !viewModel.isCreatingTask && !viewModel.isSummoning && !isRefreshing diff --git a/suixinkan/UI/ScenicMaterials/ScenicMaterialComponents.swift b/suixinkan/UI/ScenicMaterials/ScenicMaterialComponents.swift index f57b5e6..aea1794 100644 --- a/suixinkan/UI/ScenicMaterials/ScenicMaterialComponents.swift +++ b/suixinkan/UI/ScenicMaterials/ScenicMaterialComponents.swift @@ -1,14 +1,15 @@ +import Kingfisher import SnapKit import UIKit /// 景区素材模块的局部样式,可独立于机巢业务使用。 @MainActor enum ScenicMaterialsStyle { - static let primary = UIColor(hex: 0x3164FF) + static let primary = UIColor(hex: 0x066BFF) static let background = UIColor.white - static let text = UIColor(hex: 0x20242C) - static let secondary = UIColor(hex: 0x9297A1) - static let border = UIColor(hex: 0xECEEF2) + static let text = UIColor(hex: 0x151515) + static let secondary = UIColor(hex: 0x8490A5) + static let border = UIColor(hex: 0xE7E9EF) static let success = UIColor(hex: 0x17986A) static let warning = UIColor(hex: 0xD98926) @@ -79,8 +80,11 @@ final class ScenicMaterialClipCell: UICollectionViewCell { /// 显示片段及本机演示传输状态;首段大图额外显示分辨率和体积。 func configure(clip: ScenicMaterialClip, selected: Bool, isSelectionEnabled: Bool, statusText: String? = nil, progress: Double? = nil, isHero: Bool = false) { - cover.image = UIImage(named: clip.coverAssetName) - ordinalLabel.text = String(format: "片段 %02d", clip.ordinal) + cover.kf.cancelDownloadTask() + if clip.isRemote { + cover.kf.setImage(with: clip.coverURL, placeholder: UIImage(systemName: "photo")) + } else { cover.image = UIImage(named: clip.coverAssetName) } + ordinalLabel.text = clip.fileLabel ?? String(format: "片段 %02d", clip.ordinal) metadataLabel.text = isHero ? "\(clip.durationText) · \(clip.resolution) · \(clip.sizeText)" : clip.durationText metadataLabel.font = .monospacedDigitSystemFont(ofSize: isHero ? 11 : 10, weight: .regular) selectionButton.setImage(UIImage(systemName: selected ? "checkmark.circle.fill" : "circle", @@ -269,27 +273,46 @@ final class ScenicMaterialExpandCell: UICollectionViewCell { @objc private func tapped() { onToggleExpanded?() } } -/// 固定底部的选择/下载摘要,不直接持有 ViewModel 或执行文件操作。 +/// 固定底部的选择/下载摘要,由页面显式传入布局和状态,不执行文件操作。 @MainActor final class ScenicMaterialsFooterView: UIView { + /// 选择态左右排列;传输态显示摘要、进度和通栏按钮;结果态显示摘要和操作行。 + enum Layout { case selection, progress, result } + /// 当前阶段的主要操作,例如下载、继续或重试。 var onPrimaryTap: (() -> Void)? /// 当前阶段的次要操作,例如取消或继续选择。 var onSecondaryTap: (() -> Void)? - private let titleLabel = ScenicMaterialsStyle.label(size: 14, weight: .medium) - private let detailLabel = ScenicMaterialsStyle.label(size: 10, color: ScenicMaterialsStyle.secondary) + private let titleLabel = ScenicMaterialsStyle.label(size: 14) + private let detailLabel = ScenicMaterialsStyle.label(size: 11, color: ScenicMaterialsStyle.secondary) private let primaryButton = UIButton(type: .custom) private let secondaryButton = UIButton(type: .custom) private let progressView = UIProgressView(progressViewStyle: .bar) + private let activity = UIActivityIndicatorView(style: .medium) + private let summaryRow = UIStackView() + private let actionRow = UIStackView() + private let stack = UIStackView() + private var currentLayout: Layout? + private var hasSecondaryAction = false /// 创建随安全区延伸的白色底栏。 override init(frame: CGRect) { super.init(frame: frame) + setupUI() + setupConstraints() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + private func setupUI() { backgroundColor = .white titleLabel.numberOfLines = 2 + titleLabel.accessibilityIdentifier = "scenic.materials.footer.title" detailLabel.numberOfLines = 2 - primaryButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .semibold) - primaryButton.titleLabel?.numberOfLines = 2 + detailLabel.accessibilityIdentifier = "scenic.materials.footer.detail" + primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold) + primaryButton.titleLabel?.numberOfLines = 1 primaryButton.titleLabel?.textAlignment = .center primaryButton.setTitleColor(.white, for: .normal) primaryButton.setTitleColor(.white, for: .disabled) @@ -297,64 +320,137 @@ final class ScenicMaterialsFooterView: UIView { primaryButton.clipsToBounds = true primaryButton.accessibilityIdentifier = "scenic.materials.primary" primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside) - secondaryButton.tintColor = ScenicMaterialsStyle.primary - secondaryButton.setTitleColor(ScenicMaterialsStyle.primary, for: .normal) - secondaryButton.titleLabel?.font = .systemFont(ofSize: 13) + secondaryButton.setTitleColor(ScenicMaterialsStyle.secondary, for: .normal) + secondaryButton.titleLabel?.font = .systemFont(ofSize: 15) + secondaryButton.titleLabel?.numberOfLines = 1 + secondaryButton.titleLabel?.textAlignment = .center + secondaryButton.layer.cornerRadius = 10 secondaryButton.accessibilityIdentifier = "scenic.materials.secondary" secondaryButton.addTarget(self, action: #selector(secondaryTapped), for: .touchUpInside) progressView.progressTintColor = ScenicMaterialsStyle.primary - progressView.trackTintColor = ScenicMaterialsStyle.border - let labels = UIStackView(arrangedSubviews: [titleLabel, detailLabel]) - labels.axis = .vertical - labels.spacing = 5 - let row = UIStackView(arrangedSubviews: [labels, primaryButton]) - row.axis = .horizontal - row.spacing = 12 - row.alignment = .center - let stack = UIStackView(arrangedSubviews: [row, progressView, secondaryButton]) + progressView.trackTintColor = UIColor(hex: 0xE7EDF7) + progressView.accessibilityIdentifier = "scenic.materials.footer.progress" + activity.color = .white + activity.hidesWhenStopped = true + activity.isUserInteractionEnabled = false + activity.accessibilityIdentifier = "scenic.materials.footer.activity" + primaryButton.addSubview(activity) + summaryRow.axis = .horizontal + summaryRow.alignment = .center + summaryRow.spacing = 8 + actionRow.axis = .horizontal + actionRow.alignment = .center + actionRow.spacing = 16 stack.axis = .vertical - stack.spacing = 10 - let separator = UIView() - separator.backgroundColor = ScenicMaterialsStyle.border - addSubview(separator) + stack.spacing = 8 addSubview(stack) - separator.snp.makeConstraints { $0.top.leading.trailing.equalToSuperview(); $0.height.equalTo(0.5) } - stack.snp.makeConstraints { - $0.top.equalToSuperview().offset(14) - $0.leading.trailing.equalToSuperview().inset(20) - $0.bottom.equalTo(safeAreaLayoutGuide).inset(12) - } - primaryButton.snp.makeConstraints { $0.width.equalTo(158); $0.height.equalTo(46) } - progressView.snp.makeConstraints { $0.height.equalTo(3).priority(999) } - secondaryButton.snp.makeConstraints { $0.height.equalTo(32).priority(999) } } - @available(*, unavailable) - required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + private func setupConstraints() { + stack.snp.makeConstraints { + $0.top.equalToSuperview().offset(14) + $0.leading.trailing.equalToSuperview().inset(18) + $0.bottom.equalTo(safeAreaLayoutGuide).inset(14) + } + primaryButton.snp.makeConstraints { $0.height.equalTo(46) } + progressView.snp.makeConstraints { $0.height.equalTo(3).priority(999) } + activity.snp.makeConstraints { + $0.centerY.equalToSuperview() + $0.centerX.equalToSuperview() + $0.size.equalTo(18) + } + } - /// 由当前页面状态显式刷新底栏,始终保留禁用按钮的可读标题。 + /// 按产品页面的状态布局刷新底栏,忙碌按钮保持蓝色但不可重复触发。 func configure(title: String, detail: String?, primaryTitle: String, primaryEnabled: Bool, - secondaryTitle: String? = nil, progress: Float? = nil) { + secondaryTitle: String? = nil, progress: Float? = nil, + layout: Layout = .selection, isBusy: Bool = false) { UIView.performWithoutAnimation { + if currentLayout != layout || hasSecondaryAction != (secondaryTitle != nil) { + arrange(layout, hasSecondary: secondaryTitle != nil) + } + titleLabel.attributedText = nil titleLabel.text = title + if layout == .selection, let range = title.range(of: #"\d+"#, options: .regularExpression) { + let attributed = NSMutableAttributedString(string: title) + attributed.addAttributes([.foregroundColor: ScenicMaterialsStyle.primary, + .font: UIFont.systemFont(ofSize: 20, weight: .bold)], + range: NSRange(range, in: title)) + titleLabel.attributedText = attributed + } detailLabel.text = detail - detailLabel.isHidden = detail == nil - if primaryButton.title(for: .normal) != primaryTitle { - primaryButton.setTitle(primaryTitle, for: .normal) - primaryButton.setTitle(primaryTitle, for: .disabled) - } - primaryButton.backgroundColor = primaryEnabled ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.primary.withAlphaComponent(0.25) + detailLabel.isHidden = detail == nil || layout == .progress + primaryButton.accessibilityHint = detail + primaryButton.setTitle(primaryTitle, for: .normal) + primaryButton.setTitle(primaryTitle, for: .disabled) + let titleFont = primaryButton.titleLabel?.font ?? .systemFont(ofSize: 15, weight: .semibold) + let titleWidth = ceil(primaryTitle.size(withAttributes: [.font: titleFont]).width) + 2 + activity.snp.updateConstraints { $0.centerX.equalToSuperview().offset(-titleWidth / 2 - 4) } + primaryButton.backgroundColor = primaryEnabled || isBusy ? ScenicMaterialsStyle.primary : UIColor(hex: 0xCDDFFF) primaryButton.isEnabled = primaryEnabled - if secondaryButton.title(for: .normal) != secondaryTitle { - secondaryButton.setTitle(secondaryTitle, for: .normal) - } + secondaryButton.setTitle(secondaryTitle, for: .normal) secondaryButton.isHidden = secondaryTitle == nil + secondaryButton.isEnabled = secondaryTitle != nil progressView.isHidden = progress == nil progressView.progress = min(max(progress ?? 0, 0), 1) + if isBusy { activity.startAnimating() } else { activity.stopAnimating() } layoutIfNeeded() } } - @objc private func primaryTapped() { onPrimaryTap?() } - @objc private func secondaryTapped() { onSecondaryTap?() } + private func arrange(_ layout: Layout, hasSecondary: Bool) { + for container in [stack, summaryRow, actionRow] { + container.arrangedSubviews.forEach { container.removeArrangedSubview($0); $0.removeFromSuperview() } + } + titleLabel.snp.removeConstraints() + detailLabel.snp.removeConstraints() + secondaryButton.snp.removeConstraints() + actionRow.distribution = .fill + titleLabel.font = .systemFont(ofSize: layout == .selection ? 17 : 12) + detailLabel.textAlignment = layout == .selection ? .left : .right + secondaryButton.backgroundColor = layout == .result ? UIColor(hex: 0xF2F4F7) : .clear + secondaryButton.titleLabel?.font = .systemFont(ofSize: layout == .progress ? 12 : 15) + switch layout { + case .selection: + actionRow.addArrangedSubview(titleLabel) + actionRow.addArrangedSubview(primaryButton) + titleLabel.snp.makeConstraints { $0.width.equalTo(126).priority(999) } + stack.addArrangedSubview(actionRow) + stack.addArrangedSubview(detailLabel) + case .progress: + summaryRow.addArrangedSubview(titleLabel) + if hasSecondary { + summaryRow.addArrangedSubview(secondaryButton) + secondaryButton.snp.makeConstraints { $0.width.equalTo(44); $0.height.equalTo(28) } + } + actionRow.addArrangedSubview(primaryButton) + stack.addArrangedSubview(summaryRow) + stack.addArrangedSubview(progressView) + stack.addArrangedSubview(actionRow) + case .result: + summaryRow.addArrangedSubview(titleLabel) + summaryRow.addArrangedSubview(detailLabel) + titleLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) + detailLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + if hasSecondary { + actionRow.addArrangedSubview(secondaryButton) + secondaryButton.snp.makeConstraints { $0.height.equalTo(46) } + actionRow.distribution = .fillEqually + } + actionRow.addArrangedSubview(primaryButton) + stack.addArrangedSubview(summaryRow) + stack.addArrangedSubview(actionRow) + } + currentLayout = layout + hasSecondaryAction = hasSecondary + } + + @objc private func primaryTapped() { + guard primaryButton.isEnabled else { return } + onPrimaryTap?() + } + @objc private func secondaryTapped() { + guard secondaryButton.isEnabled, !secondaryButton.isHidden else { return } + onSecondaryTap?() + } } diff --git a/suixinkan/UI/ScenicMaterials/ScenicMaterialFilterViewControllers.swift b/suixinkan/UI/ScenicMaterials/ScenicMaterialFilterViewControllers.swift index 22b9a90..7bb8c10 100644 --- a/suixinkan/UI/ScenicMaterials/ScenicMaterialFilterViewControllers.swift +++ b/suixinkan/UI/ScenicMaterials/ScenicMaterialFilterViewControllers.swift @@ -29,35 +29,31 @@ final class ScenicMaterialRouteFilterViewController: UIViewController, UITableVi override func viewDidLoad() { super.viewDidLoad() setupUI() - let desiredHeight = min(CGFloat(routes.count + 1) * 58 + 90, 460) + let desiredHeight = min(CGFloat(routes.count + 1) * 50 + 100, 460) sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, desiredHeight) }] sheetPresentationController?.prefersGrabberVisible = true - sheetPresentationController?.preferredCornerRadius = 24 + sheetPresentationController?.preferredCornerRadius = 22 } private func setupUI() { view.backgroundColor = .white view.accessibilityIdentifier = "scenic.materials.route.sheet" - let title = ScenicMaterialsStyle.label("选择航线", size: 19, weight: .semibold) - let close = UIButton(type: .system) - close.setImage(UIImage(systemName: "xmark"), for: .normal) - close.tintColor = ScenicMaterialsStyle.secondary - close.accessibilityLabel = "关闭航线筛选" - close.accessibilityIdentifier = "scenic.materials.route.close" - close.addTarget(self, action: #selector(closeTapped), for: .touchUpInside) + let title = ScenicMaterialsStyle.label("选择航线", size: 18, weight: .semibold) tableView.backgroundColor = .white - tableView.separatorStyle = .none - tableView.rowHeight = 58 + tableView.separatorStyle = .singleLine + tableView.separatorColor = ScenicMaterialsStyle.border + tableView.separatorInset = .zero + tableView.tableFooterView = UIView() + tableView.rowHeight = 50 tableView.delegate = self tableView.accessibilityIdentifier = "scenic.materials.route.list" tableView.register(UITableViewCell.self, forCellReuseIdentifier: "route") - [title, close, tableView].forEach(view.addSubview) - title.snp.makeConstraints { $0.top.equalTo(view.safeAreaLayoutGuide).offset(20); $0.leading.equalToSuperview().offset(22) } - close.snp.makeConstraints { $0.trailing.equalToSuperview().inset(10); $0.centerY.equalTo(title); $0.size.equalTo(44) } + [title, tableView].forEach(view.addSubview) + title.snp.makeConstraints { $0.top.equalTo(view.safeAreaLayoutGuide).offset(22); $0.leading.equalToSuperview().offset(18) } tableView.snp.makeConstraints { - $0.top.equalTo(title.snp.bottom).offset(14) - $0.leading.trailing.equalToSuperview().inset(8) - $0.bottom.equalTo(view.safeAreaLayoutGuide) + $0.top.equalTo(title.snp.bottom).offset(12) + $0.leading.trailing.equalToSuperview().inset(22) + $0.bottom.equalTo(view.safeAreaLayoutGuide).inset(10) } dataSource = UITableViewDiffableDataSource(tableView: tableView) { [weak self] table, indexPath, row in guard let self else { return nil } @@ -71,15 +67,27 @@ final class ScenicMaterialRouteFilterViewController: UIViewController, UITableVi name = self.routes.first { $0.id == routeID }?.name ?? "航线暂不可用" } let selected = id == self.selectedRouteID - cell.textLabel?.text = name - cell.textLabel?.font = .systemFont(ofSize: 15, weight: selected ? .medium : .regular) - cell.textLabel?.textColor = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text + var configuration = cell.defaultContentConfiguration() + configuration.text = name + configuration.textProperties.font = .systemFont(ofSize: 14, weight: selected ? .medium : .regular) + configuration.textProperties.color = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text + configuration.directionalLayoutMargins = .zero + cell.contentConfiguration = configuration cell.backgroundColor = .white - let image = UIImageView(image: UIImage(systemName: selected ? "checkmark.circle.fill" : "circle", - withConfiguration: UIImage.SymbolConfiguration(pointSize: 22))) - image.tintColor = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.border - image.frame = CGRect(x: 0, y: 0, width: 24, height: 24) - cell.accessoryView = image + cell.selectionStyle = .none + cell.layoutMargins = .zero + cell.preservesSuperviewLayoutMargins = false + cell.separatorInset = .zero + if selected { + let image = UIImageView(image: UIImage(systemName: "checkmark", + withConfiguration: UIImage.SymbolConfiguration(pointSize: 16, weight: .medium))) + image.tintColor = ScenicMaterialsStyle.primary + image.frame = CGRect(x: 0, y: 0, width: 20, height: 20) + cell.accessoryView = image + } else { + cell.accessoryView = nil + } + cell.accessibilityLabel = name cell.accessibilityIdentifier = "scenic.materials.route.\(id ?? "all")" cell.accessibilityTraits = selected ? [.button, .selected] : .button return cell @@ -99,19 +107,17 @@ final class ScenicMaterialRouteFilterViewController: UIViewController, UITableVi dismiss(animated: true) { completion?(id) } } - @objc private func closeTapped() { dismiss(animated: true) } } /// 景区素材起止日期筛选 Sheet,临时选择只在点击确定后应用。 @MainActor -final class ScenicMaterialDateFilterViewController: UIViewController { +final class ScenicMaterialDateFilterViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { /// nil/nil 表示保留期内的全部时间,其他值为按日包含端点的区间。 var onSelectRange: ((Date?, Date?) -> Void)? /// 当前正在编辑的日期端点。 private enum Endpoint: Equatable { case start, end } - private let minimumDate: Date - private let maximumDate: Date + private let dateOptions: ScenicMaterialDatePickerOptions private let calendar: Calendar private var startDate: Date private var endDate: Date @@ -120,18 +126,19 @@ final class ScenicMaterialDateFilterViewController: UIViewController { private let allButton = UIButton(type: .system) private let startButton = UIButton(type: .custom) private let endButton = UIButton(type: .custom) - private let picker = UIDatePicker() + private let picker = UIPickerView() /// 约束到服务端约定或演示给定的保留区间,不提供未来日期。 init(start: Date?, end: Date?, minimumDate: Date, maximumDate: Date, calendar: Calendar = .current) { self.calendar = calendar - self.minimumDate = calendar.startOfDay(for: minimumDate) - self.maximumDate = max(calendar.startOfDay(for: minimumDate), calendar.startOfDay(for: maximumDate)) - let clampedStart = min(max(calendar.startOfDay(for: start ?? maximumDate), self.minimumDate), self.maximumDate) - let clampedEnd = min(max(calendar.startOfDay(for: end ?? maximumDate), self.minimumDate), self.maximumDate) + let options = ScenicMaterialDatePickerOptions(minimumDate: minimumDate, maximumDate: maximumDate, calendar: calendar) + dateOptions = options + let clampedStart = options.clamped(start ?? maximumDate) + let clampedEnd = options.clamped(end ?? maximumDate) self.startDate = min(clampedStart, clampedEnd) self.endDate = max(clampedStart, clampedEnd) - usesAllDates = start == nil && end == nil + // 打开面板先编辑日期草稿;取消不会改变列表当前的“全部时间”。 + usesAllDates = false super.init(nibName: nil, bundle: nil) modalPresentationStyle = .pageSheet } @@ -143,15 +150,15 @@ final class ScenicMaterialDateFilterViewController: UIViewController { super.viewDidLoad() setupUI() updateUI() - sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 530) }] + sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 531) }] sheetPresentationController?.prefersGrabberVisible = true - sheetPresentationController?.preferredCornerRadius = 24 + sheetPresentationController?.preferredCornerRadius = 22 } private func setupUI() { view.backgroundColor = .white view.accessibilityIdentifier = "scenic.materials.date.sheet" - let title = ScenicMaterialsStyle.label("选择时间", size: 19, weight: .semibold) + let title = ScenicMaterialsStyle.label("选择时间", size: 18, weight: .semibold) let hint = ScenicMaterialsStyle.label("选择起止日期", size: 13, color: ScenicMaterialsStyle.secondary) allButton.addTarget(self, action: #selector(allTapped), for: .touchUpInside) allButton.accessibilityIdentifier = "scenic.materials.date.all" @@ -166,19 +173,14 @@ final class ScenicMaterialDateFilterViewController: UIViewController { let dateRow = UIStackView(arrangedSubviews: [startButton, endButton]) dateRow.distribution = .fillEqually dateRow.spacing = 12 - picker.datePickerMode = .date - picker.preferredDatePickerStyle = .wheels - picker.locale = Locale(identifier: "zh_CN") - picker.calendar = calendar - picker.timeZone = calendar.timeZone - picker.minimumDate = minimumDate - picker.maximumDate = maximumDate + picker.dataSource = self + picker.delegate = self picker.accessibilityIdentifier = "scenic.materials.date.picker" - picker.addTarget(self, action: #selector(dateChanged), for: .valueChanged) let retention = ScenicMaterialsStyle.label("仅显示保留期内已到来的日期", size: 11, color: ScenicMaterialsStyle.secondary) retention.textAlignment = .center let cancel = UIButton(type: .system) cancel.setTitle("取消", for: .normal) + cancel.titleLabel?.font = .systemFont(ofSize: 15, weight: .medium) cancel.tintColor = ScenicMaterialsStyle.secondary cancel.backgroundColor = UIColor(hex: 0xF5F6F8) cancel.layer.cornerRadius = 10 @@ -186,6 +188,7 @@ final class ScenicMaterialDateFilterViewController: UIViewController { cancel.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside) let confirm = UIButton(type: .system) confirm.setTitle("确定", for: .normal) + confirm.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold) confirm.setTitleColor(.white, for: .normal) confirm.backgroundColor = ScenicMaterialsStyle.primary confirm.layer.cornerRadius = 10 @@ -201,7 +204,7 @@ final class ScenicMaterialDateFilterViewController: UIViewController { scrollView.addSubview(content) [title, hint, allButton, dateRow, picker, retention].forEach(content.addSubview) actions.snp.makeConstraints { - $0.leading.trailing.equalToSuperview().inset(22) + $0.leading.trailing.equalToSuperview().inset(18) $0.bottom.equalTo(view.safeAreaLayoutGuide).inset(12) $0.height.equalTo(46) } @@ -210,21 +213,19 @@ final class ScenicMaterialDateFilterViewController: UIViewController { $0.bottom.equalTo(actions.snp.top).offset(-12) } content.snp.makeConstraints { $0.edges.equalTo(scrollView.contentLayoutGuide); $0.width.equalTo(scrollView.frameLayoutGuide) } - title.snp.makeConstraints { $0.top.equalToSuperview().offset(20); $0.leading.equalToSuperview().offset(22) } - hint.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(12); $0.leading.equalTo(title) } - allButton.snp.makeConstraints { $0.centerY.equalTo(hint); $0.trailing.equalToSuperview().inset(22); $0.height.equalTo(44) } - dateRow.snp.makeConstraints { $0.top.equalTo(hint.snp.bottom).offset(16); $0.leading.trailing.equalToSuperview().inset(22); $0.height.equalTo(65) } - picker.snp.makeConstraints { $0.top.equalTo(dateRow.snp.bottom).offset(4); $0.leading.trailing.equalToSuperview().inset(12); $0.height.equalTo(210) } - retention.snp.makeConstraints { $0.top.equalTo(picker.snp.bottom).offset(4); $0.leading.trailing.equalToSuperview().inset(20); $0.bottom.equalToSuperview().inset(4) } + title.snp.makeConstraints { $0.top.equalToSuperview().offset(24); $0.leading.equalToSuperview().offset(18) } + hint.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(22); $0.leading.equalTo(title) } + allButton.snp.makeConstraints { $0.centerY.equalTo(hint); $0.trailing.equalToSuperview().inset(18); $0.height.equalTo(36) } + dateRow.snp.makeConstraints { $0.top.equalTo(hint.snp.bottom).offset(20); $0.leading.trailing.equalToSuperview().inset(18); $0.height.equalTo(72) } + picker.snp.makeConstraints { $0.top.equalTo(dateRow.snp.bottom).offset(10); $0.leading.trailing.equalToSuperview().inset(18); $0.height.equalTo(200) } + retention.snp.makeConstraints { $0.top.equalTo(picker.snp.bottom).offset(12); $0.leading.trailing.equalToSuperview().inset(18); $0.bottom.equalToSuperview().inset(4) } } private func updateUI() { var allConfiguration = UIButton.Configuration.plain() allConfiguration.title = "全部时间" - allConfiguration.image = UIImage(systemName: usesAllDates ? "checkmark.circle.fill" : "circle") - allConfiguration.imagePadding = 5 - allConfiguration.baseForegroundColor = usesAllDates ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.secondary - allConfiguration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 16) + allConfiguration.baseForegroundColor = ScenicMaterialsStyle.primary + allConfiguration.contentInsets = .zero allConfiguration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { input in var output = input; output.font = .systemFont(ofSize: 12); return output } @@ -234,11 +235,11 @@ final class ScenicMaterialDateFilterViewController: UIViewController { formatter.calendar = calendar formatter.timeZone = calendar.timeZone formatter.locale = Locale(identifier: "zh_CN") - formatter.dateFormat = "M 月 d 日" + formatter.dateFormat = "M月d日" for (button, value, name, candidate) in [(startButton, startDate, "开始日期", Endpoint.start), (endButton, endDate, "结束日期", Endpoint.end)] { let active = endpoint == candidate && !usesAllDates let foreground = active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text - let titleColor = active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.secondary + let titleColor = ScenicMaterialsStyle.secondary var configuration = UIButton.Configuration.plain() configuration.title = name configuration.subtitle = formatter.string(from: value) @@ -254,7 +255,7 @@ final class ScenicMaterialDateFilterViewController: UIViewController { } configuration.subtitleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in var result = attributes - result.font = .systemFont(ofSize: 14, weight: active ? .medium : .regular) + result.font = .systemFont(ofSize: 18, weight: .semibold) result.foregroundColor = foreground return result } @@ -263,11 +264,17 @@ final class ScenicMaterialDateFilterViewController: UIViewController { button.layoutIfNeeded() } button.backgroundColor = active ? ScenicMaterialsStyle.primary.withAlphaComponent(0.06) : UIColor(hex: 0xF7F8FA) - button.layer.borderColor = (active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.border).cgColor + button.layer.borderColor = (active ? ScenicMaterialsStyle.primary.withAlphaComponent(0.35) : ScenicMaterialsStyle.border).cgColor button.accessibilityTraits = active ? [.button, .selected] : .button button.accessibilityLabel = "\(name),\(formatter.string(from: value))" } - picker.setDate(endpoint == .start ? startDate : endDate, animated: false) + let value = endpoint == .start ? startDate : endDate + let monthIndex = dateOptions.monthIndex(for: value) + picker.selectRow(monthIndex, inComponent: 0, animated: false) + picker.reloadComponent(1) + let dayIndex = dateOptions.months[monthIndex].dates.firstIndex(of: value) ?? 0 + picker.selectRow(dayIndex, inComponent: 1, animated: false) + picker.accessibilityLabel = endpoint == .start ? "开始日期,月份和日期" : "结束日期,月份和日期" picker.alpha = usesAllDates ? 0.4 : 1 picker.isUserInteractionEnabled = !usesAllDates } @@ -276,8 +283,50 @@ final class ScenicMaterialDateFilterViewController: UIViewController { @objc private func startTapped() { endpoint = .start; usesAllDates = false; updateUI() } @objc private func endTapped() { endpoint = .end; usesAllDates = false; updateUI() } - @objc private func dateChanged() { - let value = min(max(calendar.startOfDay(for: picker.date), minimumDate), maximumDate) + /// 两列分别表示保留期内的月份与所选月份内的日号。 + func numberOfComponents(in pickerView: UIPickerView) -> Int { 2 } + + /// 首尾月份按保留期裁剪,滚轮中不会出现不可提交的日期。 + func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + if component == 0 { return dateOptions.months.count } + return dateOptions.months[max(pickerView.selectedRow(inComponent: 0), 0)].dates.count + } + + /// 使用与网页一致的 40 点行高。 + func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { 40 } + + /// 月份和日期占据等宽两列。 + func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { pickerView.bounds.width / 2 } + + /// 日期文案不显示年份列,辅助功能仍包含月份的年份。 + func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { + let label = (view as? UILabel) ?? UILabel() + label.font = .systemFont(ofSize: 20, weight: .medium) + label.textColor = ScenicMaterialsStyle.text + label.textAlignment = .center + if component == 0 { + let month = dateOptions.months[row] + label.text = dateOptions.monthTitle(at: row) + label.accessibilityLabel = "\(month.year)年\(month.number)月" + } else { + let month = dateOptions.months[max(pickerView.selectedRow(inComponent: 0), 0)] + label.text = "\(calendar.component(.day, from: month.dates[row]))日" + label.accessibilityLabel = label.text + } + return label + } + + /// 更改月份时保留日号并收敛月末;更改端点后同步修正倒置区间。 + func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { + usesAllDates = false + let monthIndex = max(pickerView.selectedRow(inComponent: 0), 0) + let value: Date + if component == 0 { + let current = endpoint == .start ? startDate : endDate + value = dateOptions.date(inMonthAt: row, preferredDay: calendar.component(.day, from: current)) + } else { + value = dateOptions.months[monthIndex].dates[row] + } if endpoint == .start { startDate = value if endDate < value { endDate = value } diff --git a/suixinkan/UI/ScenicMaterials/ScenicMaterialPreviewViewController.swift b/suixinkan/UI/ScenicMaterials/ScenicMaterialPreviewViewController.swift index cca03ee..5ba552a 100644 --- a/suixinkan/UI/ScenicMaterials/ScenicMaterialPreviewViewController.swift +++ b/suixinkan/UI/ScenicMaterials/ScenicMaterialPreviewViewController.swift @@ -1,9 +1,10 @@ +import Kingfisher import AVFoundation import AVKit import SnapKit import UIKit -/// 景区空镜独立预览面板,仅播放应用内演示短片,不接入订单或网络素材。 +/// 景区空境视频预览,正式素材播放服务端地址,Debug 素材保留本地预览。 @MainActor final class ScenicMaterialPreviewViewController: UIViewController { private let clip: ScenicMaterialClip @@ -11,10 +12,17 @@ final class ScenicMaterialPreviewViewController: UIViewController { private let capturedAt: Date private let calendar: Calendar private let playerController = AVPlayerViewController() + private let contentView = UIView() private let coverView = UIImageView() private let playButton = UIButton(type: .system) - private let playbackStatus = ScenicMaterialsStyle.label("本地演示短片 · 非真实景区视频", size: 11, color: ScenicMaterialsStyle.secondary) + private let playbackStatus = ScenicMaterialsStyle.label(size: 13, color: ScenicMaterialsStyle.secondary) + private let playbackTime = ScenicMaterialsStyle.label(size: 11, color: ScenicMaterialsStyle.secondary) + private let progressView = UIProgressView(progressViewStyle: .bar) private var playbackTask: Task? + private var playbackObservation: ScenicMaterialPlaybackObservation? + private var playbackGeneration = UUID() + private var playbackDuration: Double? + private var playbackFinished = false /// 预览指定片段,原片元信息与本地演示视频时长明确区分。 init(clip: ScenicMaterialClip, routeName: String, capturedAt: Date, calendar: Calendar = .current) { @@ -32,9 +40,16 @@ final class ScenicMaterialPreviewViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setupUI() - sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 510) }] + sheetPresentationController?.detents = [.custom { [weak self] context in + guard let self else { return min(context.maximumDetentValue, 490) } + let width = max(self.view.bounds.width, 320) + let fittingSize = self.contentView.systemLayoutSizeFitting( + CGSize(width: width, height: UIView.layoutFittingCompressedSize.height), + withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel) + return min(context.maximumDetentValue, fittingSize.height) + }] sheetPresentationController?.prefersGrabberVisible = true - sheetPresentationController?.preferredCornerRadius = 24 + sheetPresentationController?.preferredCornerRadius = 22 NotificationCenter.default.addObserver(self, selector: #selector(pausePlayback), name: UIApplication.willResignActiveNotification, object: nil) } @@ -42,37 +57,51 @@ final class ScenicMaterialPreviewViewController: UIViewController { override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) pausePlayback() - playbackTask?.cancel() - playbackTask = nil + } + + override func viewDidDisappear(_ animated: Bool) { + super.viewDidDisappear(animated) + stopPlayback() } private func setupUI() { view.backgroundColor = .white view.accessibilityIdentifier = "scenic.materials.preview.sheet" - let title = ScenicMaterialsStyle.label("视频预览", size: 19, weight: .semibold) - let closeButton = UIButton(type: .system) - closeButton.setImage(UIImage(systemName: "xmark"), for: .normal) - closeButton.tintColor = ScenicMaterialsStyle.secondary - closeButton.accessibilityLabel = "关闭景区视频预览" - closeButton.accessibilityIdentifier = "scenic.materials.preview.close" - closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside) + let title = ScenicMaterialsStyle.label("视频预览", size: 18, weight: .semibold) let mediaContainer = UIView() mediaContainer.backgroundColor = .black - mediaContainer.layer.cornerRadius = 12 + mediaContainer.layer.cornerRadius = 10 mediaContainer.clipsToBounds = true - coverView.image = UIImage(named: clip.coverAssetName) + mediaContainer.accessibilityIdentifier = "scenic.materials.preview.media" + if clip.isRemote { + coverView.kf.setImage(with: clip.coverURL, placeholder: UIImage(systemName: "photo")) + playbackStatus.text = "点击播放原片" + } else { + coverView.image = UIImage(named: clip.coverAssetName) + playbackStatus.text = "本地演示短片 · 非真实景区视频" + } coverView.contentMode = .scaleAspectFill coverView.clipsToBounds = true - playButton.setImage(UIImage(systemName: "play.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 48)), for: .normal) playButton.tintColor = .white - playButton.accessibilityLabel = "播放本地演示视频" playButton.accessibilityIdentifier = "scenic.materials.preview.play" playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside) + updatePlayButton(isPlaying: false) playbackStatus.numberOfLines = 2 - let metadata = ScenicMaterialsStyle.label("片段 \(String(format: "%02d", clip.ordinal)) · 原片 \(clip.durationText) · \(clip.resolution) · \(clip.sizeText)", size: 12, color: ScenicMaterialsStyle.secondary) + progressView.progressTintColor = ScenicMaterialsStyle.primary + progressView.trackTintColor = ScenicMaterialsStyle.border + progressView.accessibilityIdentifier = "scenic.materials.preview.progress" + progressView.accessibilityLabel = "播放进度" + playbackTime.accessibilityIdentifier = "scenic.materials.preview.playbackTime" + resetPlaybackTime() + let metadata = ScenicMaterialsStyle.label("\(clip.resolution) · \(clip.sizeText)", size: 11, color: ScenicMaterialsStyle.secondary) metadata.numberOfLines = 2 + metadata.textAlignment = .right metadata.accessibilityIdentifier = "scenic.materials.preview.metadata" - let route = ScenicMaterialsStyle.label(routeName, size: 17, weight: .semibold) + let timeline = UIStackView(arrangedSubviews: [playbackTime, metadata]) + timeline.alignment = .top + timeline.distribution = .fillEqually + timeline.spacing = 8 + let route = ScenicMaterialsStyle.label(routeName, size: 16, weight: .semibold) route.numberOfLines = 2 route.accessibilityIdentifier = "scenic.materials.preview.route" let formatter = DateFormatter() @@ -80,80 +109,192 @@ final class ScenicMaterialPreviewViewController: UIViewController { formatter.timeZone = calendar.timeZone formatter.locale = Locale(identifier: "zh_CN") formatter.dateFormat = "MM-dd HH:mm" - let time = ScenicMaterialsStyle.label(formatter.string(from: capturedAt), size: 12, color: ScenicMaterialsStyle.secondary) + let time = ScenicMaterialsStyle.label("\(formatter.string(from: capturedAt)) · 片段 \(clip.ordinal)", size: 12, color: ScenicMaterialsStyle.secondary) + time.accessibilityIdentifier = "scenic.materials.preview.capturedAt" let done = UIButton(type: .system) done.setTitle("返回素材列表", for: .normal) - done.setTitleColor(ScenicMaterialsStyle.primary, for: .normal) - done.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium) - done.backgroundColor = ScenicMaterialsStyle.primary.withAlphaComponent(0.07) + done.setTitleColor(.white, for: .normal) + done.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold) + done.backgroundColor = ScenicMaterialsStyle.primary done.layer.cornerRadius = 10 done.accessibilityIdentifier = "scenic.materials.preview.done" done.addTarget(self, action: #selector(closeTapped), for: .touchUpInside) let scroll = UIScrollView() - let content = UIView() view.addSubview(scroll) - scroll.addSubview(content) - [title, closeButton, playbackStatus, mediaContainer, metadata, route, time, done].forEach(content.addSubview) + scroll.addSubview(contentView) + [title, playbackStatus, mediaContainer, progressView, timeline, route, time, done].forEach(contentView.addSubview) addChild(playerController) playerController.view.backgroundColor = .black playerController.view.isHidden = true + playerController.showsPlaybackControls = false playerController.allowsPictureInPicturePlayback = false - playerController.exitsFullScreenWhenPlaybackEnds = true mediaContainer.addSubview(playerController.view) playerController.didMove(toParent: self) mediaContainer.addSubview(coverView) mediaContainer.addSubview(playButton) scroll.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) } - content.snp.makeConstraints { $0.edges.equalTo(scroll.contentLayoutGuide); $0.width.equalTo(scroll.frameLayoutGuide) } - title.snp.makeConstraints { $0.top.equalToSuperview().offset(20); $0.leading.equalToSuperview().offset(22) } - closeButton.snp.makeConstraints { $0.trailing.equalToSuperview().inset(10); $0.centerY.equalTo(title); $0.size.equalTo(44) } - playbackStatus.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(10); $0.leading.trailing.equalToSuperview().inset(22) } + contentView.snp.makeConstraints { $0.edges.equalTo(scroll.contentLayoutGuide); $0.width.equalTo(scroll.frameLayoutGuide) } + title.snp.makeConstraints { $0.top.equalToSuperview().offset(24); $0.leading.trailing.equalToSuperview().inset(18) } + playbackStatus.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(6); $0.leading.trailing.equalTo(title) } mediaContainer.snp.makeConstraints { - $0.top.equalTo(playbackStatus.snp.bottom).offset(14) - $0.leading.trailing.equalToSuperview().inset(22) + $0.top.equalTo(playbackStatus.snp.bottom).offset(18) + $0.leading.trailing.equalTo(title) $0.height.equalTo(mediaContainer.snp.width).multipliedBy(9.0 / 16.0) } playerController.view.snp.makeConstraints { $0.edges.equalToSuperview() } coverView.snp.makeConstraints { $0.edges.equalToSuperview() } - playButton.snp.makeConstraints { $0.edges.equalToSuperview() } - metadata.snp.makeConstraints { $0.top.equalTo(mediaContainer.snp.bottom).offset(10); $0.leading.trailing.equalTo(mediaContainer) } - route.snp.makeConstraints { $0.top.equalTo(metadata.snp.bottom).offset(17); $0.leading.trailing.equalTo(mediaContainer) } - time.snp.makeConstraints { $0.top.equalTo(route.snp.bottom).offset(8); $0.leading.trailing.equalTo(mediaContainer) } + playButton.snp.makeConstraints { $0.center.equalToSuperview(); $0.size.equalTo(44) } + progressView.snp.makeConstraints { $0.top.equalTo(mediaContainer.snp.bottom).offset(16); $0.leading.trailing.equalTo(mediaContainer); $0.height.equalTo(3) } + timeline.snp.makeConstraints { $0.top.equalTo(progressView.snp.bottom).offset(8); $0.leading.trailing.equalTo(mediaContainer) } + route.snp.makeConstraints { $0.top.equalTo(timeline.snp.bottom).offset(22); $0.leading.trailing.equalTo(mediaContainer) } + time.snp.makeConstraints { $0.top.equalTo(route.snp.bottom).offset(7); $0.leading.trailing.equalTo(mediaContainer) } done.snp.makeConstraints { - $0.top.equalTo(time.snp.bottom).offset(18) + $0.top.equalTo(time.snp.bottom).offset(20) $0.leading.trailing.equalTo(mediaContainer) - $0.height.equalTo(44) - $0.bottom.equalToSuperview().inset(14) + $0.height.equalTo(46) + $0.bottom.equalToSuperview().inset(18) } } @objc private func playTapped() { guard playbackTask == nil, clip.isAvailable else { return } - guard let url = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4") - ?? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4", subdirectory: "DroneDock") else { - playbackStatus.text = "本地演示视频暂不可用" + if let player = playerController.player { + if player.rate > 0 { + pausePlayback() + } else { + if playbackFinished { player.seek(to: .zero); playbackFinished = false } + player.play() + updatePlayButton(isPlaying: true) + updatePlayingStatus() + } + return + } + let demoURL = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4") + ?? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4", subdirectory: "DroneDock") + guard let url = clip.isRemote ? clip.remoteURL : demoURL else { + playbackStatus.text = "视频地址暂不可用" return } playButton.isEnabled = false + playbackGeneration = UUID() + let generation = playbackGeneration playbackTask = Task { @MainActor [weak self] in - let playable = (try? await AVURLAsset(url: url).load(.isPlayable)) == true - guard let self else { return } + let asset = AVURLAsset(url: url) + let playable = (try? await asset.load(.isPlayable)) == true + let duration = try? await asset.load(.duration) + guard let self, self.playbackGeneration == generation else { return } self.playbackTask = nil self.playButton.isEnabled = true guard !Task.isCancelled, self.view.window != nil else { return } guard playable else { - self.playbackStatus.text = "本地演示视频暂不可播放" + self.playbackStatus.text = "视频暂不可播放,请稍后重试" return } - self.playerController.player = AVPlayer(url: url) + let seconds = duration?.seconds ?? .nan + self.playbackDuration = seconds.isFinite && seconds > 0 ? seconds : nil + let player = AVPlayer(playerItem: AVPlayerItem(asset: asset)) + self.playerController.player = player self.playerController.view.isHidden = false self.coverView.isHidden = true - self.playButton.isHidden = true - self.playbackStatus.text = "正在播放 3 秒本地演示 · 原片时长见下方" - self.playerController.player?.play() + self.playbackFinished = false + self.playbackObservation = ScenicMaterialPlaybackObservation(player: player) { [weak self] time in + Task { @MainActor [weak self] in + guard let self, self.playbackGeneration == generation else { return } + self.updatePlaybackProgress(time) + } + } + NotificationCenter.default.addObserver(self, selector: #selector(playbackEnded), + name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem) + self.updatePlaybackProgress(.zero) + self.updatePlayingStatus() + self.updatePlayButton(isPlaying: true) + player.play() } } - @objc private func pausePlayback() { playerController.player?.pause() } - @objc private func closeTapped() { pausePlayback(); dismiss(animated: true) } + private func updatePlaybackProgress(_ time: CMTime) { + let seconds = time.seconds.isFinite ? max(time.seconds, 0) : 0 + progressView.progress = playbackDuration.map { Float(min(seconds / $0, 1)) } ?? 0 + let total = playbackDuration.map(Self.durationText) ?? "时长未知" + playbackTime.text = "\(Self.durationText(seconds)) / \(total)" + } + + private func updatePlayingStatus() { + if clip.isRemote { + playbackStatus.text = "正在播放原片" + } else if let duration = playbackDuration { + playbackStatus.text = "正在播放 \(Int(duration.rounded())) 秒本地演示 · 原片 \(clip.durationText)" + } else { + playbackStatus.text = "正在播放本地演示 · 原片 \(clip.durationText)" + } + } + + private func updatePlayButton(isPlaying: Bool) { + let symbol = isPlaying ? "pause.fill" : "play.fill" + playButton.setImage(UIImage(systemName: symbol, withConfiguration: UIImage.SymbolConfiguration(pointSize: 24)), for: .normal) + playButton.accessibilityLabel = isPlaying ? "暂停播放" : (clip.isRemote ? "播放景区视频" : "播放本地演示视频") + } + + private func resetPlaybackTime() { + playbackTime.text = "00:00 / \(clip.isRemote ? "" : "原片 ")\(clip.durationText)" + } + + private static func durationText(_ seconds: Double) -> String { + let value = max(Int(seconds), 0) + return String(format: "%02d:%02d", value / 60, value % 60) + } + + @objc private func playbackEnded() { + playbackFinished = true + if let duration = playbackDuration { updatePlaybackProgress(CMTime(seconds: duration, preferredTimescale: 600)) } + updatePlayButton(isPlaying: false) + playbackStatus.text = clip.isRemote ? "播放结束,点击重新播放" : "本地演示已结束 · 原片 \(clip.durationText)" + } + + @objc private func pausePlayback() { + playerController.player?.pause() + if playbackTask != nil { + playbackGeneration = UUID() + playbackTask?.cancel() + playbackTask = nil + playButton.isEnabled = true + } + updatePlayButton(isPlaying: false) + if playerController.player != nil { + playbackStatus.text = clip.isRemote ? "已暂停,点击继续播放" : "本地演示已暂停 · 原片 \(clip.durationText)" + } + } + + private func stopPlayback() { + pausePlayback() + playbackGeneration = UUID() + NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: playerController.player?.currentItem) + playbackObservation = nil + playerController.player = nil + playerController.view.isHidden = true + coverView.isHidden = false + playbackDuration = nil + playbackFinished = false + progressView.progress = 0 + resetPlaybackTime() + } + + @objc private func closeTapped() { + stopPlayback() + dismiss(animated: true) + } +} + +/// 与播放器成对持有周期观察令牌,释放时移除观察,避免弹窗销毁后残留定时回调。 +private final class ScenicMaterialPlaybackObservation { + private let player: AVPlayer + private let token: Any + + init(player: AVPlayer, onTime: @escaping @Sendable (CMTime) -> Void) { + self.player = player + token = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.1, preferredTimescale: 600), + queue: .main, using: onTime) + } + + deinit { player.removeTimeObserver(token) } } diff --git a/suixinkan/UI/ScenicMaterials/ScenicMaterialsViewController.swift b/suixinkan/UI/ScenicMaterials/ScenicMaterialsViewController.swift index 90282fd..dbc74b0 100644 --- a/suixinkan/UI/ScenicMaterials/ScenicMaterialsViewController.swift +++ b/suixinkan/UI/ScenicMaterials/ScenicMaterialsViewController.swift @@ -1,3 +1,4 @@ +import Photos import SnapKit import UIKit @@ -21,6 +22,11 @@ final class ScenicMaterialsViewController: BaseViewController { private let emptyMessage = ScenicMaterialsStyle.label(size: 14, color: ScenicMaterialsStyle.secondary) private let resetButton = UIButton(type: .system) private let driver = ScenicMaterialDemoDownloadDriver() + private let downloadService = ScenicMaterialDownloadService() + private var loadTask: Task? + private let refreshControl = UIRefreshControl() + private let retryButton = UIButton(type: .system) + private var authorizationTask: Task? private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout()) private var dataSource: UICollectionViewDiffableDataSource! private var isDemoPhotoPermissionAllowed: Bool @@ -36,6 +42,36 @@ final class ScenicMaterialsViewController: BaseViewController { @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + override func viewDidLoad() { + super.viewDidLoad() + if viewModel.isRemote { reloadRemoteMaterials() } + } + + @objc private func reloadRemoteMaterials() { + guard viewModel.isRemote, !viewModel.isSelectionLocked else { refreshControl.endRefreshing(); return } + loadTask?.cancel() + let session = AppStore.shared.session + guard session.accountType == .storeUser, session.userId == viewModel.context.userID, + String(session.currentScenicId) == viewModel.context.scenicID else { + refreshControl.endRefreshing() + showToast("请使用门店账号并重新进入当前景区素材库") + return + } + let api = ScenicMaterialsAPI(client: NetworkServices.shared.apiClient) + emptyTitle.text = "正在加载素材" + emptyMessage.text = "请稍候" + retryButton.isHidden = true + routeButton.isEnabled = false + dateButton.isEnabled = false + loadTask = Task { @MainActor [weak self] in + guard let self else { return } + await self.viewModel.loadRemoteSessions(api: api) + guard !Task.isCancelled else { return } + self.refreshControl.endRefreshing() + self.refreshDisplay() + } + } + override func setupNavigationBar() { title = "景区空境库" navigationItem.backButtonDisplayMode = .minimal @@ -48,12 +84,14 @@ final class ScenicMaterialsViewController: BaseViewController { navigationItem.standardAppearance = appearance navigationItem.scrollEdgeAppearance = appearance #if DEBUG + guard !viewModel.isRemote else { return } var actions: [UIAction] = ScenicMaterialsScenario.allCases.map { scenario in UIAction(title: scenario.title) { [weak self] _ in self?.applyPreviewScenario(scenario) } } actions.append(UIAction(title: "相册权限不足") { [weak self] _ in guard let self else { return } self.driver.stop() + self.downloadService.stop() self.viewModel.pauseDownload() self.isDemoPhotoPermissionAllowed = false self.refreshDisplay(animated: false) @@ -89,6 +127,10 @@ final class ScenicMaterialsViewController: BaseViewController { view.addSubview(filterBar) view.addSubview(collectionView) view.addSubview(footer) + if viewModel.isRemote { + collectionView.refreshControl = refreshControl + refreshControl.addTarget(self, action: #selector(reloadRemoteMaterials), for: .valueChanged) + } setupEmptyView() configureDataSource() refreshDisplay(animated: false) @@ -98,7 +140,7 @@ final class ScenicMaterialsViewController: BaseViewController { filterBar.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide).offset(10) make.leading.trailing.equalToSuperview().inset(16) - make.height.equalTo(42) + make.height.equalTo(40) } collectionView.snp.makeConstraints { make in make.top.equalTo(filterBar.snp.bottom).offset(8) @@ -116,6 +158,7 @@ final class ScenicMaterialsViewController: BaseViewController { footer.onSecondaryTap = { [weak self] in guard let self else { return } self.driver.stop() + self.downloadService.stop() if self.viewModel.phase == .downloading || self.viewModel.phase == .paused { self.viewModel.cancelDownload() } else { @@ -133,20 +176,30 @@ final class ScenicMaterialsViewController: BaseViewController { guard isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true else { return } if let coordinator = transitionCoordinator, coordinator.isInteractive { coordinator.animate(alongsideTransition: nil) { [weak self] context in - if !context.isCancelled { self?.pauseForBackground() } + if !context.isCancelled { self?.finishLeaving() } } } else { - pauseForBackground() + finishLeaving() } } + /// 仅在确认离开页面后作废异步工作,取消返回手势继续保留原来的加载及下载。 + private func finishLeaving() { + loadTask?.cancel() + viewModel.cancelRemoteLoad() + authorizationTask?.cancel() + authorizationTask = nil + pauseForBackground() + } + /// 外部演示回执后显式刷新,不自动开始或继续任何传输。 func refreshDisplay(animated: Bool = true) { guard dataSource != nil else { return } routeButton.setTitle(viewModel.routeFilterTitle, for: .normal) dateButton.setTitle(viewModel.dateFilterTitle, for: .normal) - routeButton.isEnabled = !viewModel.isSelectionLocked - dateButton.isEnabled = !viewModel.isSelectionLocked + routeButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading + dateButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading + retryButton.isHidden = viewModel.loadError == nil emptyTitle.text = viewModel.emptyTitle emptyMessage.text = viewModel.emptyMessage resetButton.isHidden = viewModel.selectedRouteID == nil && viewModel.dateRange == nil @@ -184,21 +237,26 @@ final class ScenicMaterialsViewController: BaseViewController { private func configureFilterButton(_ button: UIButton, identifier: String) { var configuration = UIButton.Configuration.plain() - configuration.image = UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .medium)) - configuration.imagePlacement = .trailing - configuration.imagePadding = 8 configuration.baseForegroundColor = ScenicMaterialsStyle.text - configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12) + configuration.cornerStyle = .fixed + configuration.background.cornerRadius = 11 + configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 32) configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in - var result = incoming; result.font = .systemFont(ofSize: 13); return result + var result = incoming; result.font = .systemFont(ofSize: 15, weight: .medium); return result } button.configuration = configuration - button.backgroundColor = UIColor(hex: 0xF6F7F9) - button.layer.cornerRadius = 10 - button.layer.borderWidth = 0.5 + button.contentHorizontalAlignment = .leading + button.backgroundColor = UIColor(hex: 0xF7F8FA) + button.layer.cornerRadius = 11 + button.layer.borderWidth = 1 button.layer.borderColor = ScenicMaterialsStyle.border.cgColor button.titleLabel?.lineBreakMode = .byTruncatingTail button.accessibilityIdentifier = identifier + let chevron = UIImageView(image: UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .medium))) + chevron.tintColor = ScenicMaterialsStyle.secondary + chevron.isUserInteractionEnabled = false + button.addSubview(chevron) + chevron.snp.makeConstraints { $0.trailing.equalToSuperview().inset(12); $0.centerY.equalToSuperview() } } private func setupEmptyView() { @@ -213,7 +271,10 @@ final class ScenicMaterialsViewController: BaseViewController { resetButton.tintColor = ScenicMaterialsStyle.primary resetButton.accessibilityIdentifier = "scenic.materials.resetFilters" emptyView.accessibilityIdentifier = "scenic.materials.empty" - let stack = UIStackView(arrangedSubviews: [icon, emptyTitle, emptyMessage, resetButton]) + retryButton.setTitle("重新加载", for: .normal) + retryButton.accessibilityIdentifier = "scenic.materials.retry" + retryButton.addTarget(self, action: #selector(reloadRemoteMaterials), for: .touchUpInside) + let stack = UIStackView(arrangedSubviews: [icon, emptyTitle, emptyMessage, resetButton, retryButton]) stack.axis = .vertical stack.spacing = 14 emptyView.addSubview(stack) @@ -246,7 +307,7 @@ final class ScenicMaterialsViewController: BaseViewController { return cell case .retention, .end: let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! ScenicMaterialTextCell - cell.configure(item == .retention ? "素材保留 90 天,请及时下载" : "已显示保留期内的全部演示记录", identifier: item == .retention ? "scenic.materials.retention" : "scenic.materials.end") + cell.configure(item == .retention ? self.viewModel.retentionTips : (self.viewModel.isRemote ? "已显示全部素材" : "已显示保留期内的全部演示记录"), identifier: item == .retention ? "scenic.materials.retention" : "scenic.materials.end") return cell } } @@ -265,7 +326,7 @@ final class ScenicMaterialsViewController: BaseViewController { let completed = viewModel.completedIDs.contains(clip.id) let failed = viewModel.failedIDs.contains(clip.id) let inBatch = viewModel.batchItemIDs.contains(clip.id) - let status: String? = completed ? "演示已下载" : failed ? "下载失败" : inBatch && viewModel.phase == .paused ? "已暂停" : nil + let status: String? = completed ? (viewModel.isRemote ? "已保存相册" : "演示已下载") : failed ? "下载失败" : inBatch && viewModel.phase == .paused ? "已暂停" : nil cell.configure(clip: clip, selected: viewModel.selectedIDs.contains(clip.id), isSelectionEnabled: viewModel.canSelect(id: clip.id), statusText: status, progress: inBatch && viewModel.phase == .downloading && !completed ? viewModel.progressByID[clip.id] ?? 0 : nil, @@ -356,20 +417,20 @@ final class ScenicMaterialsViewController: BaseViewController { let total = viewModel.totalCount switch viewModel.phase { case .idle: - footer.configure(title: "已选 \(viewModel.selectedCount) 段", detail: "本地演示 · 不下载或保存真实文件", - primaryTitle: viewModel.selectedCount > 0 ? "下载所选(\(viewModel.selectedCount))" : "下载所选", primaryEnabled: viewModel.canStartDownload) + footer.configure(title: "已选 \(viewModel.selectedCount) 段", detail: viewModel.isRemote ? nil : "本地演示 · 不下载或保存真实文件", + primaryTitle: "下载所选", primaryEnabled: viewModel.canStartDownload) case .downloading: footer.configure(title: "下载中 · \(completed)/\(total) 段", detail: "请保持页面开启,切后台将暂停", - primaryTitle: "正在下载…", primaryEnabled: false, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress)) + primaryTitle: "正在下载…", primaryEnabled: false, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress), layout: .progress, isBusy: true) case .paused: - footer.configure(title: "已暂停 · 已完成 \(completed)/\(total) 段", detail: "演示进度已保留,请手动继续", - primaryTitle: "继续下载", primaryEnabled: true, secondaryTitle: "取消") + footer.configure(title: "已暂停 · 已完成 \(completed)/\(total) 段", detail: "已完成项已保留,请手动继续", + primaryTitle: "继续下载", primaryEnabled: true, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress), layout: .progress) case .partialFailure: - footer.configure(title: "演示完成 \(completed) 段 · 失败 \(viewModel.failedCount) 段", detail: "未保存真实文件,成功项不重复下载", - primaryTitle: "重试失败(\(viewModel.failedCount))", primaryEnabled: true, secondaryTitle: "继续选择") + footer.configure(title: "已下载 \(completed) 段 · 失败 \(viewModel.failedCount) 段", detail: viewModel.isRemote ? "成功项已保存相册" : "演示结果 · 未保存真实文件", + primaryTitle: "重试失败(\(viewModel.failedCount))", primaryEnabled: true, secondaryTitle: "继续选择", layout: .result) case .completed: - footer.configure(title: "演示完成 \(completed) 段", detail: "未写入系统相册", - primaryTitle: "继续选择素材", primaryEnabled: true) + footer.configure(title: viewModel.isRemote ? "已保存 \(completed) 段" : "演示完成 \(completed) 段", detail: viewModel.isRemote ? "可在系统相册查看" : "未写入系统相册", + primaryTitle: "继续选择素材", primaryEnabled: true, layout: .result) } } @@ -377,7 +438,27 @@ final class ScenicMaterialsViewController: BaseViewController { if viewModel.phase == .completed { viewModel.continueSelecting(); refreshDisplay(); return } + if viewModel.isRemote { + guard authorizationTask == nil else { return } + authorizationTask = Task { @MainActor [weak self] in + let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly) + guard let self else { return } + self.authorizationTask = nil + guard !Task.isCancelled, self.view.window != nil, + UIApplication.shared.applicationState == .active else { return } + guard status == .authorized || status == .limited else { + self.presentPhotoPermissionSettings() + return + } + self.startTransfer() + } + return + } guard isDemoPhotoPermissionAllowed else { presentPermissionDemo(); return } + startTransfer() + } + + private func startTransfer() { let started: Bool switch viewModel.phase { case .idle: started = viewModel.startDownload() @@ -386,11 +467,25 @@ final class ScenicMaterialsViewController: BaseViewController { case .downloading, .completed: started = false } refreshDisplay(animated: false) - if started { driver.start(viewModel: viewModel) { [weak self] in self?.refreshDisplay(animated: false) } } + guard started else { return } + if viewModel.isRemote, let batchID = viewModel.batchID { + let items = viewModel.pendingIDs.compactMap { id -> ScenicMaterialDownloadItem? in + guard let clip = viewModel.clip(id: id), let url = clip.remoteURL else { return nil } + return ScenicMaterialDownloadItem(id: id, remoteURL: url, + fileName: url.pathExtension.isEmpty ? "scenic-material.mp4" : url.lastPathComponent) + } + downloadService.start(items: items, batchID: batchID) { [weak self] id, token, event in + self?.viewModel.receive(event, clipID: id, batchID: token) + self?.refreshDisplay(animated: false) + } onFailure: { [weak self] _, error in self?.showToast(error.localizedDescription) } + } else { + driver.start(viewModel: viewModel) { [weak self] in self?.refreshDisplay(animated: false) } + } } @objc private func pauseForBackground() { driver.stop() + downloadService.stop() viewModel.pauseDownload() if isViewLoaded { refreshDisplay(animated: false) } } @@ -400,6 +495,7 @@ final class ScenicMaterialsViewController: BaseViewController { let picker = ScenicMaterialRouteFilterViewController(routes: viewModel.routes, selectedRouteID: viewModel.selectedRouteID) picker.onSelectRoute = { [weak self] id in self?.viewModel.setRoute(id: id) + self?.reloadRemoteMaterials() self?.refreshDisplay() self?.collectionView.setContentOffset(.zero, animated: false) } @@ -414,6 +510,7 @@ final class ScenicMaterialsViewController: BaseViewController { picker.onSelectRange = { [weak self] start, end in guard let self else { return } if self.viewModel.setDateRange(start: start, end: end) { + self.reloadRemoteMaterials() self.refreshDisplay() self.collectionView.setContentOffset(.zero, animated: false) } else { self.showToast("请选择保留期内的有效日期范围") } @@ -423,6 +520,7 @@ final class ScenicMaterialsViewController: BaseViewController { @objc private func resetFilters() { viewModel.resetFilters() + reloadRemoteMaterials() refreshDisplay() } @@ -433,6 +531,16 @@ final class ScenicMaterialsViewController: BaseViewController { present(controller, animated: true) } + private func presentPhotoPermissionSettings() { + guard presentedViewController == nil else { return } + let alert = UIAlertController(title: "需要相册保存权限", message: "请允许添加照片和视频,以保存所选素材。", preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "取消", style: .cancel)) + alert.addAction(UIAlertAction(title: "去设置", style: .default) { _ in + if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) } + }) + present(alert, animated: true) + } + private func presentPermissionDemo() { guard presentedViewController == nil else { return } let alert = UIAlertController(title: "需要相册保存权限", message: "真实下载需允许保存视频。此处仅演示权限流程,不读取或修改系统权限。", preferredStyle: .alert) diff --git a/suixinkanTests/DeviceCommandDebugPolicyTests.swift b/suixinkanTests/DeviceCommandDebugPolicyTests.swift new file mode 100644 index 0000000..bab563f --- /dev/null +++ b/suixinkanTests/DeviceCommandDebugPolicyTests.swift @@ -0,0 +1,113 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 验证禁飞调试在进入传输层之前拦截真实操作,所有探针本身也不联网。 +@MainActor +final class DeviceCommandDebugPolicyTests: XCTestCase { + /// 即使切到生产地址或未来新增机场动作,默认传输也不能发送设备操作。 + func testTypedCommandsAreBlockedBeforeTransportInBothEnvironments() async throws { + XCTAssertTrue(DeviceCommandDebugPolicy.blocksLiveRequests) + for environment in [APIEnvironment.testing, .production] { + let session = CommandTransportProbe() + let client = APIClient(environment: environment, session: session) + for path in ["/api/app/airport/shoot", "/api/app/airport/start-shoot", + "/api/app/airport/command", "/api/app/airport/future-control", + "/api/yf-handset-app/photog/multi-plane/tasks/create"] { + do { + let _: EmptyDebugPayload = try await client.send(APIRequest(method: .post, path: path)) + XCTFail("禁飞请求不得进入传输层:\(path)") + } catch is DeviceCommandDebugBlockedError {} catch { XCTFail("错误类型不应伪装为后端失败:\(error)") } + } + XCTAssertTrue(session.requests.isEmpty) + } + } + + /// 更换 HTTP 方法、尾部斜杠或调用图传不能绕过允许读取的接口列表。 + func testReadVerbDoesNotBypassCommandRestriction() async throws { + let session = CommandTransportProbe() + let client = APIClient(environment: .testing, session: session) + for path in ["/api/app/airport/shoot/", "/api/app/airport/command", "/api/app/airport/live"] { + do { + let _: EmptyDebugPayload = try await client.send(APIRequest(method: .get, path: path)) + XCTFail("操作接口即使使用 GET 也不允许发送") + } catch is DeviceCommandDebugBlockedError {} + } + XCTAssertTrue(session.requests.isEmpty) + } + + /// 裸 JSON 和 multipart 与强类型发送具有相同的保护边界。 + func testRawAndMultipartCannotBypassRestriction() async throws { + let session = CommandTransportProbe() + let client = APIClient(environment: .testing, session: session) + do { + let _: EmptyDebugPayload = try await client.sendRawJSON( + method: .post, path: "/api/app/airport/shoot", jsonBody: #"{"id":501}"#) + XCTFail("裸 JSON 不得发送") + } catch is DeviceCommandDebugBlockedError {} + do { + let _: EmptyDebugPayload = try await client.sendMultipart( + path: "/api/app/airport/command", fileName: "test.json", mimeType: "application/json", data: Data()) + XCTFail("multipart 不得发送") + } catch is DeviceCommandDebugBlockedError {} + XCTAssertTrue(session.requests.isEmpty) + } + + /// 只读状态仍可联调,但关闭实时设备采集;任务身份及其他参数不变。 + func testStateReadsDisableLiveCollectionEvenWhenRequestedOrOmitted() async throws { + let session = CommandTransportProbe() + let client = APIClient(environment: .testing, session: session) + for (path, key) in [("plane-status", "live_battery"), ("shooting", "live_battery"), ("status", "live_metrics")] { + for supplied in [false, true] { + var query = [URLQueryItem(name: "id", value: "501")] + if supplied { query += [URLQueryItem(name: key, value: "1"), URLQueryItem(name: key, value: "true")] } + let _: EmptyDebugPayload = try await client.send(APIRequest( + method: .get, path: "/api/app/airport/\(path)", queryItems: query)) + let request = try XCTUnwrap(session.requests.last) + let items = try XCTUnwrap(URLComponents(url: XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems) + XCTAssertEqual(items.filter { $0.name == key }, [URLQueryItem(name: key, value: "0")]) + XCTAssertEqual(items.first { $0.name == "id" }?.value, "501") + } + } + XCTAssertEqual(session.requests.count, 6) + } + + /// 普通订单读取保持原有请求,不给所有业务泛化地加禁飞限制。 + func testUnrelatedRequestsKeepTheirPayloadAndQuery() async throws { + let session = CommandTransportProbe() + let client = APIClient(environment: .testing, session: session) + let _: EmptyDebugPayload = try await client.send(APIRequest( + method: .get, path: "/api/yf-handset-app/photog/multi-plane/orders", + queryItems: [URLQueryItem(name: "scenic_id", value: "128")])) + XCTAssertEqual(session.requests.count, 1) + XCTAssertEqual(session.requests[0].url?.query, "scenic_id=128") + } + + /// 纯内存 Mock 可核验原始指令合同,调用不代表服务器或设备实际执行。 + func testLocalSimulationRetainsCommandAndLiveReadContracts() async throws { + let session = MockURLSession(responses: [Data(#"{"code":100000,"data":{}}"#.utf8), + Data(#"{"code":100000,"data":{}}"#.utf8)]) + let client = APIClient(environment: .testing, session: session) + let _: EmptyDebugPayload = try await client.sendRawJSON( + method: .post, path: "/api/app/airport/shoot", jsonBody: #"{"id":501}"#) + let _: EmptyDebugPayload = try await client.send(APIRequest( + method: .get, path: "/api/app/airport/shooting", queryItems: [URLQueryItem(name: "live_battery", value: "1")])) + XCTAssertEqual(session.requests.count, 2) + XCTAssertEqual(session.requests[0].httpBody, Data(#"{"id":501}"#.utf8)) + XCTAssertEqual(session.requests[1].url?.query, "live_battery=1") + } +} + +/// 不声明模拟豁免的记录探针,验证默认客户端会在传输前拦截;自身绝不调用 URLSession。 +private final class CommandTransportProbe: URLSessionProtocol { + private(set) var requests: [URLRequest] = [] + + func data(for request: URLRequest) async throws -> (Data, URLResponse) { + requests.append(request) + let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + return (Data(#"{"code":100000,"data":{}}"#.utf8), response) + } +} + +/// 无业务字段的测试响应,不使用真实任务或设备数据。 +private struct EmptyDebugPayload: Decodable {} diff --git a/suixinkanTests/DroneDockDeliveryViewTests.swift b/suixinkanTests/DroneDockDeliveryViewTests.swift index 3c4a09b..dd65e5a 100644 --- a/suixinkanTests/DroneDockDeliveryViewTests.swift +++ b/suixinkanTests/DroneDockDeliveryViewTests.swift @@ -7,6 +7,56 @@ import XCTest final class DroneDockDeliveryViewTests: XCTestCase { private weak var previousKeyWindow: UIWindow? + /// 弹窗关闭与普通返回共享处理中确认,取消提示不会结束正在进行的上传。 + func testSheetCloseRequiresConfirmationDuringUpload() async throws { + let fixture = try DeliveryUIFixture() + fixture.uploader.hold = true + let controller = fixture.controller(initialTaskID: 1) + var closed = 0 + controller.configureSheetPresentation { closed += 1 } + let window = show(controller) + defer { fixture.uploader.release(); close(window) } + try await settle(window) { controller.viewModel.selectedTaskID == 1 } + try await chooseVideo(controller, window: window) + try button(controller.view, "drone.delivery.submit").sendActions(for: .touchUpInside) + try await settle(window) { controller.viewModel.phase == .uploading } + let closeItem = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first { $0.accessibilityIdentifier == "drone.delivery.sheet.close" }) + let refreshItem = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first { $0.accessibilityIdentifier == "drone.delivery.refresh" }) + XCTAssertTrue(closeItem.isEnabled) + XCTAssertFalse(refreshItem.isEnabled) + UIApplication.shared.sendAction(try XCTUnwrap(closeItem.action), to: closeItem.target, from: closeItem, for: nil) + try await settle(window) { controller.presentedViewController is UIAlertController && controller.presentedViewController?.transitionCoordinator == nil } + let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController) + XCTAssertEqual(alert.title, "停止处理并返回?") + XCTAssertEqual(alert.actions.map(\.title), ["继续处理", "停止并返回"]) + XCTAssertEqual(closed, 0) + XCTAssertEqual(controller.viewModel.phase, .uploading) + controller.dismiss(animated: false) + try await settle(window) { controller.presentedViewController == nil } + fixture.uploader.release() + try await settle(window) { controller.viewModel.successMessage != nil && !controller.viewModel.isSubmitting } + UIApplication.shared.sendAction(try XCTUnwrap(closeItem.action), to: closeItem.target, from: closeItem, for: nil) + XCTAssertEqual(closed, 1) + } + + /// 取消侧滑返回后云端页重新出现,必须恢复大弹窗与退出保护。 + func testSheetReappearanceRestoresModalProtection() async throws { + let fixture = try DeliveryUIFixture() + let controller = fixture.controller() + controller.configureSheetPresentation { XCTFail("恢复外观不能关闭弹窗") } + let window = show(controller) + defer { close(window) } + try await settle(window) { controller.viewModel.detail != nil && !controller.viewModel.isLoading } + let navigation = try XCTUnwrap(controller.navigationController) + navigation.setNavigationBarHidden(true, animated: false) + navigation.isModalInPresentation = false + controller.beginAppearanceTransition(true, animated: false) + controller.endAppearanceTransition() + XCTAssertFalse(navigation.isNavigationBarHidden) + XCTAssertTrue(navigation.isModalInPresentation) + XCTAssertEqual(controller.viewModel.detail?.order.orderNumber, "TEST-DELIVERY-UI") + } + /// 订单入口不自动选择任务,用户明确点位、任务和视频后才可提交。 func testOrderEntryRequiresExplicitTaskAndVideoSelection() async throws { let fixture = try DeliveryUIFixture() diff --git a/suixinkanTests/DroneDockMaterialsSimulationViewTests.swift b/suixinkanTests/DroneDockMaterialsSimulationViewTests.swift new file mode 100644 index 0000000..5b14cff --- /dev/null +++ b/suixinkanTests/DroneDockMaterialsSimulationViewTests.swift @@ -0,0 +1,113 @@ +import UIKit +import XCTest +@testable import suixinkan + +/// 用正式素材页的隔离场景检查窄屏布局与交互,所有媒体都来自随包资源。 +@MainActor +final class DroneDockMaterialsSimulationViewTests: XCTestCase { + private weak var previousKeyWindow: UIWindow? + + /// 十种真实接口边界状态均保留固定底栏,内容和操作区不互相遮挡。 + func testAllMockStatesKeepFooterAndContentSeparateOnPhoneWidths() async throws { + for width in [375.0, 402.0] { + for scenario in ["ready", "uploading", "uploadFailed", "mixed", "empty", "loading", "error", "taskUploading", "taskFailed", "film"] { + let controller = try XCTUnwrap(DroneDockMaterialsSimulation.makeController(scenario: scenario) as? DroneDockMaterialsViewController) + let window = show(controller, width: width) + defer { close(window) } + try await settle(window) { + if scenario == "loading" { return controller.viewModel.isLoading } + if scenario == "error" { return controller.viewModel.detailErrorMessage != nil } + return controller.viewModel.total != nil + } + let list = try XCTUnwrap(find(controller.view, "drone.materials.remote.list") as? UICollectionView) + let footer = try XCTUnwrap(find(controller.view, "drone.materials.remote.footer")) + let button = try XCTUnwrap(find(footer, "drone.materials.remote.download") as? UIButton) + XCTAssertLessThanOrEqual(list.frame.maxY, footer.frame.minY + 1, scenario) + XCTAssertGreaterThanOrEqual(button.bounds.height, 44, scenario) + XCTAssertLessThanOrEqual(footer.frame.maxY, controller.view.bounds.maxY + 1, scenario) + XCTAssertFalse(button.isEnabled, scenario) + XCTAssertEqual(controller.viewModel.selectedCount, 0) + for thumbnail in views(list).filter({ $0.accessibilityIdentifier == "drone.materials.remote.thumbnail" }) { + XCTAssertEqual(thumbnail.bounds.height, thumbnail.bounds.width * 9 / 16, accuracy: 1) + } + if scenario == "uploading" || scenario == "uploadFailed" || scenario.hasPrefix("task") { + XCTAssertTrue(controller.viewModel.selectableMaterialIDs.isEmpty, scenario) + } + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + let attachment = XCTAttachment(image: image) + attachment.name = "订单素材库-\(scenario)-\(Int(width))" + attachment.lifetime = .keepAlways + add(attachment) + } + } + } + + /// 选择不打开预览,预览不改变选择;返回时继续显示固定底栏中的已选数量。 + func testLocalSelectionAndPreviewAreIndependent() async throws { + let controller = try XCTUnwrap(DroneDockMaterialsSimulation.makeController(scenario: "ready") as? DroneDockMaterialsViewController) + let window = show(controller, width: 402) + defer { close(window) } + try await settle(window) { controller.viewModel.total == 3 } + let selection = try XCTUnwrap(find(controller.view, "drone.materials.remote.select.903.5") as? UIButton) + selection.sendActions(for: .touchUpInside) + XCTAssertEqual(controller.viewModel.selectedCount, 1) + XCTAssertEqual(controller.navigationController?.viewControllers.count, 1) + window.layoutIfNeeded() + let selectedImage = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + let selectedAttachment = XCTAttachment(image: selectedImage) + selectedAttachment.name = "订单素材库-selected-402" + selectedAttachment.lifetime = .keepAlways + add(selectedAttachment) + let preview = try XCTUnwrap(find(controller.view, "drone.materials.remote.file.903.5.preview") as? UIButton) + preview.sendActions(for: .touchUpInside) + let navigation = try XCTUnwrap(controller.navigationController) + try await settle(window) { navigation.viewControllers.count == 2 } + XCTAssertEqual(controller.viewModel.selectedCount, 1) + navigation.popViewController(animated: false) + try await settle(window) { navigation.topViewController === controller } + XCTAssertEqual(controller.viewModel.selectedCount, 1) + let download = try XCTUnwrap(find(controller.view, "drone.materials.remote.download") as? UIButton) + XCTAssertTrue(download.isEnabled) + } + + private func show(_ controller: UIViewController, width: CGFloat) -> 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() + window.frame = CGRect(x: 0, y: 0, width: width, height: width == 375 ? 812 : 874) + window.overrideUserInterfaceStyle = .light + window.rootViewController = UINavigationController(rootViewController: controller) + window.makeKeyAndVisible() + return window + } + + private func close(_ window: UIWindow) { + window.rootViewController?.dismiss(animated: false) + window.isHidden = true + window.rootViewController = nil + previousKeyWindow?.makeKeyAndVisible() + } + + private func settle(_ window: UIWindow, until condition: () -> Bool) async throws { + for _ in 0..<150 { + window.layoutIfNeeded() + if condition() { + // 等待 Diffable 的淡入结束,避免截图叠加上一帧的加载占位。 + try await Task.sleep(nanoseconds: 400_000_000) + window.layoutIfNeeded() + if condition() { return } + } + try await Task.sleep(nanoseconds: 15_000_000) + } + XCTFail("素材演示未完成状态展示") + throw NSError(domain: "DroneDockMaterialsSimulationViewTests", code: 1) + } + + private func views(_ root: UIView) -> [UIView] { [root] + root.subviews.flatMap { views($0) } } + private func find(_ root: UIView, _ identifier: String) -> UIView? { views(root).first { $0.accessibilityIdentifier == identifier } } +} diff --git a/suixinkanTests/DroneDockMaterialsViewModelTests.swift b/suixinkanTests/DroneDockMaterialsViewModelTests.swift index ca1b11e..769db77 100644 --- a/suixinkanTests/DroneDockMaterialsViewModelTests.swift +++ b/suixinkanTests/DroneDockMaterialsViewModelTests.swift @@ -307,6 +307,113 @@ final class DroneDockMaterialsViewModelTests: XCTestCase { XCTAssertFalse(model.isLoading || model.isLoadingTasks) } + /// 上传状态、类型和文件地址均需就绪;成片与其他任务同名文件不会误入选择。 + func testSelectionOnlyIncludesReadyOriginalFilesWithCompositeIdentity() async throws { + let service = try MaterialsViewModelService() + service.tasksResponse = .success(try MaterialsViewModelFixtures.tasksWithFiles(ids: [10, 11])) + let model = try makeModel(service: service) + await model.refresh() + let expected: Set = [ + .init(taskID: 10, fileID: 1), .init(taskID: 10, fileID: 2), + .init(taskID: 11, fileID: 1), .init(taskID: 11, fileID: 2) + ] + XCTAssertEqual(model.selectableMaterialIDs, expected) + for fileID in [3, 4, 5, 6, 7, 8, 90] { model.toggleSelection(taskID: 10, fileID: fileID) } + model.toggleSelection(taskID: 999, fileID: 1) + XCTAssertEqual(model.selectedCount, 0) + model.toggleSelection(taskID: 10, fileID: 1) + model.toggleSelection(taskID: 11, fileID: 1) + XCTAssertEqual(model.selectedMaterialIDs, [.init(taskID: 10, fileID: 1), .init(taskID: 11, fileID: 1)]) + model.toggleSelection(taskID: 10, fileID: 1) + XCTAssertEqual(model.selectedMaterialIDs, [.init(taskID: 11, fileID: 1)]) + XCTAssertEqual(service.requests.count, 2, "勾选不得发出网络请求") + } + + /// 全选只覆盖当前可用文件,第二次点击清空;无文件时不显示全选。 + func testSelectAllTogglesOnlyAvailableOriginals() async throws { + let service = try MaterialsViewModelService() + let model = try makeModel(service: service) + model.toggleSelectAll() + XCTAssertFalse(model.allDownloadableSelected) + service.tasksResponse = .success(try MaterialsViewModelFixtures.tasksWithFiles()) + await model.refresh() + model.toggleSelection(taskID: 10, fileID: 1) + XCTAssertFalse(model.allDownloadableSelected) + model.toggleSelectAll() + XCTAssertEqual(model.selectedCount, 2) + XCTAssertTrue(model.allDownloadableSelected) + model.toggleSelectAll() + XCTAssertTrue(model.selectedMaterialIDs.isEmpty) + XCTAssertFalse(model.allDownloadableSelected) + XCTAssertEqual(service.requests.count, 2) + } + + /// 切点、刷新和读取失败都清除旧选择;重新获取的数据不会自动恢复勾选。 + func testFilterRefreshAndFailureClearPreviousSelection() async throws { + let service = try MaterialsViewModelService() + service.tasksResponse = .success(try MaterialsViewModelFixtures.tasksWithFiles()) + let model = try makeModel(service: service) + await model.refresh() + model.toggleSelectAll() + service.tasksResponse = .success(try MaterialsViewModelFixtures.tasksWithFiles(ids: [20], spotID: 202)) + await model.selectSpot(id: 202) + XCTAssertTrue(model.selectedMaterialIDs.isEmpty) + XCTAssertEqual(model.selectableMaterialIDs, [.init(taskID: 20, fileID: 1), .init(taskID: 20, fileID: 2)]) + model.toggleSelectAll() + await model.refresh() + XCTAssertEqual(model.selectedCount, 0) + model.toggleSelectAll() + service.tasksResponse = .failure(APIError.networkFailed("测试任务读取失败")) + await model.retryTasks() + model.toggleSelection(taskID: 20, fileID: 1) + model.toggleSelectAll() + XCTAssertTrue(model.selectedMaterialIDs.isEmpty) + XCTAssertTrue(model.selectableMaterialIDs.isEmpty) + XCTAssertFalse(model.allDownloadableSelected) + } + + /// 读取期间没有可选旧数据,离页后迟到响应不能恢复文件或选择。 + func testPendingLoadAndInvalidationCannotRestoreSelection() async throws { + let service = try MaterialsViewModelService() + service.tasksResponse = .success(try MaterialsViewModelFixtures.tasksWithFiles()) + let model = try makeModel(service: service) + await model.refresh() + model.toggleSelectAll() + service.suspendTasks = true + let started = expectation(description: "任务选择刷新挂起") + service.requestStarted = { if $0 == 2 { started.fulfill() } } + let pending = Task { await model.selectSpot(id: 201) } + await fulfillment(of: [started], timeout: 2) + XCTAssertTrue(model.isLoadingTasks) + model.toggleSelectAll() + model.toggleSelection(taskID: 10, fileID: 1) + XCTAssertTrue(model.selectedMaterialIDs.isEmpty) + XCTAssertTrue(model.selectableMaterialIDs.isEmpty) + model.invalidate() + service.finishTasks(2, .success(try MaterialsViewModelFixtures.tasksWithFiles())) + await pending.value + XCTAssertTrue(model.tasks.isEmpty) + XCTAssertTrue(model.selectedMaterialIDs.isEmpty) + XCTAssertFalse(model.allDownloadableSelected) + } + + /// 即使尚未刷新,账号身份改变后的勾选也会撤下旧订单和旧选择。 + func testSelectionContextChangeClearsOrderWithoutRequesting() async throws { + let service = try MaterialsViewModelService() + service.tasksResponse = .success(try MaterialsViewModelFixtures.tasksWithFiles()) + let scope = MaterialsContextBox(makeContext()) + let model = try makeModel(service: service, scope: scope) + await model.refresh() + model.toggleSelectAll() + scope.value = makeContext(userID: "new-test-user") + model.toggleSelection(taskID: 10, fileID: 1) + XCTAssertNil(model.detail) + XCTAssertTrue(model.tasks.isEmpty) + XCTAssertTrue(model.selectedMaterialIDs.isEmpty) + XCTAssertNotNil(model.detailErrorMessage) + XCTAssertEqual(service.requests.count, 2) + } + private func makeModel(service: MaterialsViewModelService, scope: MaterialsContextBox? = nil) throws -> DroneDockMaterialsViewModel { let scope = scope ?? MaterialsContextBox(makeContext()) return DroneDockMaterialsViewModel(context: scope.value, order: try MaterialsViewModelFixtures.detail().order, @@ -353,6 +460,28 @@ private enum MaterialsViewModelFixtures { "order_number": orderNumber, "total": list.count, "list": list ])) } + + /// 每个任务复用文件 ID,混合就绪、上传中、失败和无效地址,并包含独立成片。 + static func tasksWithFiles(ids: [Int] = [10], spotID: Int = 201) throws -> DroneDockMaterialTasks { + let files: [[String: Any]] = [ + ["id": 1, "file_type": 1, "upload_status": 1, "file_url": "https://example.com/photo.jpg"], + ["id": 2, "file_type": 2, "upload_status": 1, "file_url": "https://example.com/video.mp4"], + ["id": 3, "file_type": 1, "upload_status": 0, "file_url": "https://example.com/pending.jpg"], + ["id": 4, "file_type": 1, "upload_status": 2, "file_url": "https://example.com/uploading.jpg"], + ["id": 5, "file_type": 1, "upload_status": 3, "file_url": "https://example.com/failed.jpg"], + ["id": 6, "file_type": 1, "upload_status": 1, "file_url": "file:///tmp/not-remote.jpg"], + ["id": 7, "file_type": 99, "upload_status": 1, "file_url": "https://example.com/unknown"], + ["id": 8, "file_type": 1, "file_url": "https://example.com/unconfirmed.jpg"] + ] + let list: [[String: Any]] = ids.map { id in + ["id": id, "order_number": "ORDER-1", "scenic_spot_id": spotID, + "scenic_spot_name": "测试点位", "materials": files, + "film": ["id": 90, "task_id": id, "file_url": "https://example.com/film.mp4"]] + } + return try JSONDecoder().decode(DroneDockMaterialTasks.self, from: JSONSerialization.data(withJSONObject: [ + "order_number": "ORDER-1", "total": list.count, "list": list + ])) + } } /// 记录两类只读请求,并可分别挂起以验证迟到响应保护。 diff --git a/suixinkanTests/DroneDockMaterialsViewTests.swift b/suixinkanTests/DroneDockMaterialsViewTests.swift index feb185b..69218e7 100644 --- a/suixinkanTests/DroneDockMaterialsViewTests.swift +++ b/suixinkanTests/DroneDockMaterialsViewTests.swift @@ -8,6 +8,88 @@ final class DroneDockMaterialsViewTests: XCTestCase { private weak var previousKeyWindow: UIWindow? private let number = "TEST-MATERIAL-ORDER" + /// 全选只计入可用原素材,勾选不会预览,下载不会伪造完成或调用新接口。 + func testSelectionControlsMatchReadyFilesAndDownloadShowsUnavailable() async throws { + var record = task(1, status: 30) + record["materials"] = [file(11, status: 1, url: "https://example.invalid/raw.mp4"), + file(12, status: 2), file(13, status: 3)] + record["film"] = ["id": 21, "task_id": 1, "file_name": "测试成片.mp4", "file_url": "https://example.invalid/film.mp4"] + let (controller, session) = try makeController([detail(), taskList([record])]) + let window = show(controller) + defer { close(window) } + try await settle(window) { controller.viewModel.total == 1 } + let list = try collection(controller) + let first = try await visibleCell(list, path: IndexPath(item: 0, section: 4), window: window) + let select = try XCTUnwrap(find(first, id: "drone.materials.remote.select.1.11") as? UIButton) + select.sendActions(for: .touchUpInside) + try await settle(window) { controller.viewModel.selectedCount == 1 } + XCTAssertNil(controller.presentedViewController) + XCTAssertTrue(controller.navigationController?.topViewController === controller) + XCTAssertTrue(texts(controller.view).contains("已选择1项")) + let unavailable = try await visibleCell(list, path: IndexPath(item: 1, section: 4), window: window) + XCTAssertNil(find(unavailable, id: "drone.materials.remote.select.1.12")) + let failed = try await visibleCell(list, path: IndexPath(item: 2, section: 4), window: window) + let retry = try XCTUnwrap(find(failed, id: "drone.materials.remote.file.1.13.retryUpload")) + XCTAssertTrue(retry.accessibilityTraits.contains(.notEnabled)) + let film = try await visibleCell(list, path: IndexPath(item: 3, section: 4), window: window) + XCTAssertNil(find(film, id: "drone.materials.remote.select.1.21")) + let download = try XCTUnwrap(find(controller.view, id: "drone.materials.remote.download") as? UIButton) + XCTAssertTrue(download.isEnabled) + download.sendActions(for: .touchUpInside) + try await settle(window) { controller.presentedViewController is UIAlertController } + let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController) + XCTAssertEqual(alert.title, "下载功能暂未开放") + XCTAssertEqual(session.requests.count, 2) + XCTAssertEqual(controller.viewModel.selectedCount, 1) + } + + /// 固定下载底栏不随列表滚动移动,预览保持选择且只打开被点击文件。 + func testFooterStaysFixedAndPreviewPreservesSelection() async throws { + var record = task(1, status: 30) + record["materials"] = [file(11, status: 1, url: "https://example.invalid/raw.mp4")] + var previews = 0 + let (controller, session) = try makeController([detail(), taskList([record])], previewFactory: { url, isVideo, _ in + previews += 1 + XCTAssertEqual(url.absoluteString, "https://example.invalid/raw.mp4") + XCTAssertTrue(isVideo) + return UIViewController() + }) + let window = show(controller) + defer { close(window) } + try await settle(window) { controller.viewModel.total == 1 } + let list = try collection(controller) + let footer = try XCTUnwrap(find(controller.view, id: "drone.materials.remote.footer")) + let frame = footer.frame + let all = try XCTUnwrap(find(controller.view, id: "drone.materials.selectAll") as? UIButton) + all.sendActions(for: .touchUpInside) + try await settle(window) { controller.viewModel.selectedCount == 1 } + let cell = try await visibleCell(list, path: IndexPath(item: 0, section: 4), window: window) + XCTAssertEqual(footer.frame, frame) + XCTAssertLessThanOrEqual(list.frame.maxY, footer.frame.minY + 0.5) + try XCTUnwrap(find(cell, id: "drone.materials.remote.file.1.11.preview") as? UIButton).sendActions(for: .touchUpInside) + try await settle(window) { controller.navigationController?.viewControllers.count == 2 } + XCTAssertEqual(previews, 1) + XCTAssertEqual(controller.viewModel.selectedCount, 1) + XCTAssertEqual(session.requests.count, 2) + } + + /// 空文件任务依据聚合状态呈现上传等待、同步、失败或未知,不补造素材。 + func testEmptyTaskMaterialsShowAggregateStatus() async throws { + var records = [task(1), task(2), task(3), task(4), task(5)] + for index in 0..<4 { records[index]["material_status"] = index } + let (controller, _) = try makeController([detail(), taskList(records)]) + let window = show(controller) + defer { close(window) } + try await settle(window) { controller.viewModel.total == 5 } + let list = try collection(controller) + for (index, title) in ["素材待上传", "暂无可用原素材", "素材上传中", "素材上传失败", "素材状态待确认"].enumerated() { + let cell = try await visibleCell(list, path: IndexPath(item: 0, section: index + 3), window: window) + XCTAssertTrue(texts(cell).contains(title)) + } + XCTAssertEqual(controller.viewModel.selectableMaterialIDs.count, 0) + XCTAssertFalse(try XCTUnwrap(find(controller.view, id: "drone.materials.remote.download") as? UIButton).isEnabled) + } + /// 进入页面后才读取两个接口,整单次数来自详情而不是任务总数。 func testAppearanceLoadsDetailAndTasksWithWholeOrderCounts() async throws { let tasks = [task(3, status: 40), task(2, status: 10), task(1, status: 30)] @@ -15,10 +97,10 @@ final class DroneDockMaterialsViewTests: XCTestCase { XCTAssertTrue(session.requests.isEmpty) let window = show(controller) defer { close(window) } - try await settle(window) { controller.viewModel.total == 3 && self.texts(controller.view).contains("3 条任务记录 · 最新在前") } + try await settle(window) { controller.viewModel.total == 3 && self.texts(controller.view).contains("3次拍摄 · 最新在前") } XCTAssertEqual(controller.title, "订单素材库") XCTAssertTrue(texts(controller.view).contains("游客 130****0001")) - XCTAssertTrue(texts(controller.view).contains { $0.contains("已拍摄 1/5 次,剩余 4 次") }) + XCTAssertTrue(texts(controller.view).contains { $0.contains("含5次拍摄 · 已拍摄1次 · 剩余4次") }) XCTAssertEqual(controller.viewModel.tasks.map(\.id), [3, 2, 1]) XCTAssertEqual(session.requests.map { $0.url?.path.components(separatedBy: "/").suffix(2).joined(separator: "/") }, ["orders/detail", "multi-plane/tasks"]) for request in session.requests { @@ -42,7 +124,7 @@ final class DroneDockMaterialsViewTests: XCTestCase { let list = try collection(controller) try selectFilter(201, list: list) try await settle(window) { controller.viewModel.total == 0 && self.texts(controller.view).contains("当前点位暂无任务记录") } - XCTAssertTrue(texts(controller.view).contains { $0.contains("已拍摄 1/5 次,剩余 4 次") }) + XCTAssertTrue(texts(controller.view).contains { $0.contains("含5次拍摄 · 已拍摄1次 · 剩余4次") }) XCTAssertEqual(controller.viewModel.spots.map(\.id), [201, 202]) let selected = try XCTUnwrap(find(controller.view, id: "drone.materials.filter.201")) XCTAssertTrue(selected.accessibilityTraits.contains(.selected)) @@ -67,7 +149,7 @@ final class DroneDockMaterialsViewTests: XCTestCase { XCTAssertFalse(texts(controller.view).contains("暂无任务记录")) try retry(controller) try await settle(window) { self.texts(controller.view).contains("暂无任务记录") } - XCTAssertTrue(texts(controller.view).contains("0 条任务记录 · 最新在前")) + XCTAssertTrue(texts(controller.view).contains("0次拍摄 · 最新在前")) XCTAssertEqual(session.requests.filter { $0.url?.path.hasSuffix("/orders/detail") == true }.count, 2) XCTAssertEqual(session.requests.filter { $0.url?.path.hasSuffix("/tasks") == true }.count, 2) } @@ -105,7 +187,7 @@ final class DroneDockMaterialsViewTests: XCTestCase { defer { close(window) } let list = try collection(controller) try await settle(window) { controller.viewModel.total == 1 && list.numberOfSections == 5 } - let expected = ["原素材 · 视频 · 点击播放", "原素材 · 视频 · 上传中", "原素材 · 视频 · 上传失败", "原素材 · 视频 · 暂不可预览", "视频成片 · 点击播放"] + let expected = ["上传完成 · 可下载", "上传中", "上传失败", "暂不可预览", "视频成片 · 点击播放"] for (index, state) in expected.enumerated() { let path = IndexPath(item: index, section: 4) let cell = try await visibleCell(list, path: path, window: window) @@ -133,7 +215,7 @@ final class DroneDockMaterialsViewTests: XCTestCase { try selectFilter(201, list: list) try await settle(window) { controller.viewModel.selectedSpotID == 201 && session.requests.count == 3 } try XCTUnwrap(list.refreshControl).sendActions(for: .valueChanged) - try await settle(window) { controller.viewModel.detail?.order.shotUsed == 2 && session.requests.count == 5 && self.texts(controller.view).contains { $0.contains("已拍摄 2/5 次,剩余 3 次") } } + try await settle(window) { controller.viewModel.detail?.order.shotUsed == 2 && session.requests.count == 5 && self.texts(controller.view).contains { $0.contains("含5次拍摄 · 已拍摄2次 · 剩余3次") } } XCTAssertEqual(controller.viewModel.selectedSpotID, 201) XCTAssertEqual(query(session.requests[3])["scenic_spot_id"], nil) XCTAssertEqual(query(session.requests[4])["scenic_spot_id"], "201") @@ -160,7 +242,7 @@ final class DroneDockMaterialsViewTests: XCTestCase { try await settle(window) { controller.viewModel.total == 1 && list.numberOfSections == 5 } let taskCell = try await visibleCell(list, path: IndexPath(item: 0, section: 3), window: window) let button = try XCTUnwrap(find(taskCell, id: "drone.materials.remote.delivery.2") as? UIButton) - XCTAssertEqual(button.title(for: .normal), "替换成片") + XCTAssertEqual(button.configuration?.title, "替换成片") button.sendActions(for: .touchUpInside) try await settle(window) { guard let page = controller.navigationController?.topViewController as? DroneDockDeliveryViewController else { return false } @@ -177,7 +259,8 @@ final class DroneDockMaterialsViewTests: XCTestCase { } private func makeController(_ responses: [Data], - deliveryFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil) throws -> (DroneDockMaterialsViewController, MockURLSession) { + deliveryFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil, + previewFactory: ((URL, Bool, String) -> UIViewController)? = nil) throws -> (DroneDockMaterialsViewController, MockURLSession) { let context = DroneDockHomeContext(userID: "materials-ui-user", accountType: "store_user", scenicID: 128, scenicName: "测试景区", storeID: 37, photographerName: "测试工作人员", token: "materials-ui-token") let session = MockURLSession(responses: responses) @@ -185,7 +268,9 @@ final class DroneDockMaterialsViewTests: XCTestCase { client.bindAuthTokenProvider { "materials-ui-token" } let order = try JSONDecoder().decode(DroneDockHomeOrder.self, from: JSONSerialization.data(withJSONObject: ["order_number": number])) let model = DroneDockMaterialsViewModel(context: context, order: order, service: DroneDockMaterialsAPI(client: client), currentContext: { context }) - return (DroneDockMaterialsViewController(viewModel: model, deliveryControllerFactory: deliveryFactory), session) + return (DroneDockMaterialsViewController(viewModel: model, deliveryControllerFactory: deliveryFactory, + thumbnailProvider: { _, _, _ in nil }, + mediaPreviewControllerFactory: previewFactory), session) } private func detail(used: Int = 1, canUpload: Bool = false) throws -> Data { diff --git a/suixinkanTests/DroneDockNoFlightPreparationTests.swift b/suixinkanTests/DroneDockNoFlightPreparationTests.swift new file mode 100644 index 0000000..7208d5e --- /dev/null +++ b/suixinkanTests/DroneDockNoFlightPreparationTests.swift @@ -0,0 +1,154 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 验证禁飞调试阻断准备页写入整链,读取和显式注入的本地模拟仍可独立验证。 +@MainActor +final class DroneDockNoFlightPreparationTests: XCTestCase { + /// 尚未加载时的直接方法调用也不得触发创建前预检、创建或召唤。 + func testDisabledSubmissionBlocksDirectCallsBeforeLoading() async throws { + let fixture = try NoFlightPreparationFixture(allowsTaskSubmission: false) + var callbacks = 0 + await fixture.model.createTask { callbacks += 1 } + await fixture.model.prepareAndSummon { callbacks += 1 } + + XCTAssertEqual(callbacks, 0) + XCTAssertEqual(fixture.projects.requestCount, 0) + XCTAssertTrue(fixture.creation.requests.isEmpty) + XCTAssertTrue(fixture.shoot.requests.isEmpty) + XCTAssertFalse(fixture.model.canCreateTask) + XCTAssertFalse(fixture.model.isPrimaryActionEnabled) + XCTAssertEqual(fixture.model.primaryButtonTitle, "仅限模拟调试") + XCTAssertEqual(fixture.model.admissionMessage, DeviceCommandDebugPolicy.blockedMessage) + } + + /// 即使购买配置和设备都满足条件,禁飞模式也不生成待飞任务或产生结果未知锁。 + func testValidPurchaseAndReadyPlaneCannotBypassDisabledSubmission() async throws { + let fixture = try NoFlightPreparationFixture(allowsTaskSubmission: false) + await fixture.model.refresh() + await fixture.model.refreshPlaneStatus() + XCTAssertNotNil(fixture.model.projectInfo) + XCTAssertEqual(fixture.model.projectInfo?.order.canCreateTask, true) + XCTAssertEqual(fixture.model.selectedSpotID, 201) + XCTAssertEqual(fixture.model.selectedRouteID, 301) + XCTAssertEqual(fixture.model.deviceStatusText, "空闲 · 电量 95%") + XCTAssertFalse(fixture.model.canCreateTask) + XCTAssertFalse(fixture.model.isPrimaryActionEnabled) + + await fixture.model.createTask() + await fixture.model.prepareAndSummon() + await fixture.model.refresh() + await fixture.model.prepareAndSummon() + + XCTAssertEqual(fixture.projects.requestCount, 2, "只允许两次显式读取,不追加创建预检") + XCTAssertEqual(fixture.planes.requests, [128]) + XCTAssertTrue(fixture.creation.requests.isEmpty) + XCTAssertTrue(fixture.shoot.requests.isEmpty) + XCTAssertNil(fixture.model.createdTask) + XCTAssertNil(fixture.model.shootResponse) + XCTAssertFalse(fixture.model.taskCreationOutcomeUnknown) + XCTAssertFalse(fixture.model.summonOutcomeUnknown) + XCTAssertFalse(fixture.model.canOpenShootingTask) + XCTAssertEqual(fixture.model.primaryButtonTitle, "仅限模拟调试") + XCTAssertEqual(fixture.model.admissionMessage, DeviceCommandDebugPolicy.blockedMessage) + } + + /// 允许注入的纯内存模拟可验证原有串接,成功后仅查看同一任务,不重发写入。 + func testExplicitLocalSimulationPreservesExistingTaskNavigation() async throws { + let fixture = try NoFlightPreparationFixture(allowsTaskSubmission: true) + await fixture.model.refresh() + XCTAssertTrue(fixture.model.canCreateTask) + XCTAssertTrue(fixture.model.isPrimaryActionEnabled) + await fixture.model.prepareAndSummon() + + XCTAssertEqual(fixture.creation.requests.count, 1) + XCTAssertEqual(fixture.shoot.requests, [501]) + XCTAssertTrue(fixture.model.canOpenShootingTask) + XCTAssertEqual(fixture.model.primaryButtonTitle, "查看拍摄任务") + await fixture.model.prepareAndSummon() + await fixture.model.createTask() + XCTAssertEqual(fixture.creation.requests.count, 1) + XCTAssertEqual(fixture.shoot.requests, [501]) + } + + /// 底层明确在本机阻断创建时,不误报真实待飞任务可能已经写入。 + func testTransportBlockedCreationShowsLocalReasonWithoutUnknownOutcome() async throws { + let fixture = try NoFlightPreparationFixture(allowsTaskSubmission: true) + fixture.creation.result = .failure(DeviceCommandDebugBlockedError()) + await fixture.model.refresh() + await fixture.model.prepareAndSummon() + + XCTAssertEqual(fixture.creation.requests.count, 1, "替身记录方法调用,错误表示请求未传输") + XCTAssertTrue(fixture.shoot.requests.isEmpty) + XCTAssertNil(fixture.model.createdTask) + XCTAssertNil(fixture.model.shootResponse) + XCTAssertFalse(fixture.model.taskCreationOutcomeUnknown) + XCTAssertFalse(fixture.model.summonOutcomeUnknown) + XCTAssertFalse(fixture.model.isCreatingTask) + XCTAssertEqual(fixture.model.taskCreationErrorMessage, DeviceCommandDebugPolicy.blockedMessage) + XCTAssertEqual(fixture.model.admissionMessage, DeviceCommandDebugPolicy.blockedMessage) + fixture.model.invalidate() + XCTAssertFalse(fixture.model.taskCreationOutcomeUnknown) + XCTAssertFalse(fixture.model.summonOutcomeUnknown) + } + + /// 底层明确在本机阻断召唤时保留已建模拟任务,不进入服务端结果待核对状态。 + func testTransportBlockedSummonKeepsTaskWithoutUnknownOutcome() async throws { + let fixture = try NoFlightPreparationFixture(allowsTaskSubmission: true) + fixture.shoot.result = .failure(DeviceCommandDebugBlockedError()) + await fixture.model.refresh() + await fixture.model.prepareAndSummon() + + XCTAssertEqual(fixture.creation.requests.count, 1) + XCTAssertEqual(fixture.shoot.requests, [501]) + XCTAssertEqual(fixture.model.createdTask?.taskID, 501) + XCTAssertNil(fixture.model.shootResponse) + XCTAssertFalse(fixture.model.taskCreationOutcomeUnknown) + XCTAssertFalse(fixture.model.summonOutcomeUnknown) + XCTAssertFalse(fixture.model.isSummoning) + XCTAssertFalse(fixture.model.canOpenShootingTask) + XCTAssertEqual(fixture.model.shootErrorMessage, DeviceCommandDebugPolicy.blockedMessage) + XCTAssertEqual(fixture.model.admissionMessage, DeviceCommandDebugPolicy.blockedMessage) + fixture.model.invalidateSummon() + XCTAssertFalse(fixture.model.summonOutcomeUnknown) + } +} + +/// 四项服务全部为内存替身,测试不会建立真实 URLSession 或连接无人机。 +@MainActor +private struct NoFlightPreparationFixture { + let projects: NoFlightProjectService + let planes: DroneDockPlaneStatusTestService + let creation: DroneDockTaskCreationTestService + let shoot: DroneDockShootTestService + let model: DroneDockPreparationViewModel + + /// 使用匿名订单、点位和测试凭证构建可读且具备创建条件的准备状态。 + init(allowsTaskSubmission: Bool) throws { + let context = DroneDockHomeContext(userID: "no-flight-test-user", accountType: "store_user", + scenicID: 128, scenicName: "测试景区", storeID: 37, photographerName: "测试人员", token: "no-flight-test-token") + let order = try JSONDecoder().decode(DroneDockHomeOrder.self, + from: Data(#"{"order_number":"TEST-PREPARATION-001","project_id":101}"#.utf8)) + projects = NoFlightProjectService() + let plane = DroneDockPlaneStatusTestData.plane() + planes = try DroneDockPlaneStatusTestService(response: DroneDockPlaneStatusTestData.response( + planes: [plane], recommend: plane, connected: true)) + creation = DroneDockTaskCreationTestService(result: .success(try DroneDockTaskCreationTestData.response())) + shoot = DroneDockShootTestService(result: .success(try DroneDockShootTestData.response())) + model = DroneDockPreparationViewModel(context: context, order: order, service: projects, + planeStatusService: planes, taskCreationService: creation, shootService: shoot, + allowsTaskSubmission: allowsTaskSubmission, currentContext: { context }) + } +} + +/// 返回固定合法购买数据并记录读取次数,用于区分正常查询与写入前预检。 +@MainActor +private final class NoFlightProjectService: DroneDockPreparationServing { + private(set) var requestCount = 0 + + /// 仅从内存 JSON 解码,不请求任何后端。 + func projectInfo(scenicID: Int, projectID: Int, orderNumber: String) async throws -> DroneDockProjectInfoResponse { + requestCount += 1 + return try JSONDecoder().decode(DroneDockProjectInfoResponse.self, from: Data(#"{"order_number":"TEST-PREPARATION-001","project_id":101,"shoot_count":5,"shot_count":0,"remaining_count":5,"can_create_task":true,"spot":[{"scenic_spot_id":201,"scenic_spot_name":"测试点位","available":true,"air_lines":[{"air_line_id":301,"air_line_name":"测试航线","available":true}]}]}"#.utf8)) + } +} diff --git a/suixinkanTests/DroneDockOrdersViewTests.swift b/suixinkanTests/DroneDockOrdersViewTests.swift index 6bcf1bb..5c9177c 100644 --- a/suixinkanTests/DroneDockOrdersViewTests.swift +++ b/suixinkanTests/DroneDockOrdersViewTests.swift @@ -197,14 +197,16 @@ final class DroneDockOrdersViewTests: XCTestCase { assertOnlyOrders(session) } - /// 主、副交付按钮都进入同一真实页面,整单入口不猜测本次任务。 + /// 主、副交付按钮先展示方式弹窗;选择云端后才在弹窗内读取真实交付数据。 func testDeliveryButtonsOpenSharedPageWithoutPreselectingTask() async throws { for hasShootingPermission in [true, false] { var order = record("DELIVERY", status: "processing") order["can_upload_film"] = true order["can_create_task"] = hasShootingPermission var destinationSession: MockURLSession? + var factoryCount = 0 let (controller, session) = makeController(responses: [try envelope([order], total: 1)], deliveryFactory: { order, context, taskID in + factoryCount += 1 XCTAssertNil(taskID) let pair = try! DroneDockDeliveryNavigationFixtures.controller(context: context, order: order, taskID: taskID) destinationSession = pair.1 @@ -220,20 +222,115 @@ final class DroneDockOrdersViewTests: XCTestCase { let action = try button(in: cell, id: "drone.orders.order.TEST-ORDER-DELIVERY.\(suffix)") XCTAssertEqual(action.title(for: .normal), "交付成片") action.sendActions(for: .touchUpInside) + try await settle(window) { self.deliveryNavigation(from: controller)?.topViewController is DroneDockDeliveryMethodViewController } + let sheet = try XCTUnwrap(deliveryNavigation(from: controller)) + let methods = try XCTUnwrap(sheet.topViewController as? DroneDockDeliveryMethodViewController) + XCTAssertEqual(sheet.modalPresentationStyle, .pageSheet) + XCTAssertEqual(factoryCount, 0) + XCTAssertNil(destinationSession) + XCTAssertEqual(controller.navigationController?.viewControllers.count, 1) + XCTAssertTrue(controller.navigationController?.topViewController === controller) + XCTAssertEqual(session.requests.count, 1) + XCTAssertTrue(visibleTexts(in: methods.view).contains("请选择本次交付方式")) + capture(window, name: "我的拍摄订单-交付方式弹窗") + try await selectDeliveryMethod("cloud", in: methods, window: window) try await settle(window) { - guard let page = controller.navigationController?.topViewController as? DroneDockDeliveryViewController else { return false } - return page.viewModel.tasks.count == 2 && controller.navigationController?.transitionCoordinator == nil + guard let page = sheet.topViewController as? DroneDockDeliveryViewController else { return false } + return page.viewModel.tasks.count == 2 && sheet.transitionCoordinator == nil } - let page = try XCTUnwrap(controller.navigationController?.topViewController as? DroneDockDeliveryViewController) + let page = try XCTUnwrap(sheet.topViewController as? DroneDockDeliveryViewController) + XCTAssertEqual(factoryCount, 1) + XCTAssertTrue(sheet.isModalInPresentation) + XCTAssertEqual(sheet.viewControllers.count, 2) + XCTAssertTrue(controller.navigationController?.topViewController === controller) XCTAssertEqual(page.viewModel.order.orderNumber, "TEST-ORDER-DELIVERY") XCTAssertNil(page.viewModel.selectedTaskID) XCTAssertEqual(page.viewModel.context.scenicID, 128) XCTAssertEqual(destinationSession?.requests.compactMap { $0.url?.lastPathComponent }, ["detail", "tasks"]) XCTAssertTrue(destinationSession?.requests.allSatisfy { $0.httpMethod == "GET" } == true) XCTAssertEqual(session.requests.count, 1) + capture(window, name: "我的拍摄订单-弹窗内云端交付") + let back = try XCTUnwrap(page.navigationItem.leftBarButtonItem) + let backAction = try XCTUnwrap(back.action) + UIApplication.shared.sendAction(backAction, to: back.target, from: back, for: nil) + try await settle(window) { sheet.topViewController === methods && sheet.transitionCoordinator == nil } + XCTAssertFalse(sheet.isModalInPresentation) + XCTAssertEqual(sheet.viewControllers.count, 1) + XCTAssertTrue(sheet.isNavigationBarHidden) + XCTAssertEqual(factoryCount, 1) + XCTAssertEqual(destinationSession?.requests.count, 2) + XCTAssertEqual(session.requests.count, 1) } } + /// 连点只显示一个弹窗,取消不会读取交付接口或重置订单筛选和已加载卡片。 + func testDeliverySheetCancelPreservesFilterWithoutExtraRequests() async throws { + var order = record("CANCEL", status: "processing") + order["can_upload_film"] = true + var factoryCount = 0 + let (controller, session) = makeController(responses: [ + try envelope([record("INITIAL")], total: 1), try envelope([order], total: 1) + ], deliveryFactory: { _, _, _ in factoryCount += 1; return UIViewController() }) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.orders.first?.orderID == "TEST-ORDER-INITIAL" } + try button(in: controller.view, id: "drone.orders.filter.inProgress").sendActions(for: .touchUpInside) + try await settle(window) { controller.viewModel.orders.first?.orderID == "TEST-ORDER-CANCEL" } + let list = try collection(in: controller) + let cell = try await card(at: 0, in: list, window: window) + let action = try button(in: cell, id: "drone.orders.order.TEST-ORDER-CANCEL.delivery") + action.sendActions(for: .touchUpInside) + action.sendActions(for: .touchUpInside) + try await settle(window) { self.deliveryNavigation(from: controller)?.topViewController is DroneDockDeliveryMethodViewController } + let firstSheet = try XCTUnwrap(deliveryNavigation(from: controller)) + action.sendActions(for: .touchUpInside) + XCTAssertTrue(deliveryNavigation(from: controller) === firstSheet) + XCTAssertNil(firstSheet.presentedViewController) + XCTAssertEqual(factoryCount, 0) + XCTAssertEqual(session.requests.count, 2) + let methods = try XCTUnwrap(firstSheet.topViewController) + try button(in: methods.view, id: "drone.delivery.upload.close").sendActions(for: .touchUpInside) + try await settle(window) { self.deliveryNavigation(from: controller) == nil } + XCTAssertEqual(controller.viewModel.selectedFilter, .inProgress) + XCTAssertEqual(controller.viewModel.orders.map(\.orderID), ["TEST-ORDER-CANCEL"]) + XCTAssertEqual(try countLabel(in: controller).text, "进行中订单(1)") + XCTAssertEqual(session.requests.count, 2) + XCTAssertEqual(factoryCount, 0) + assertOnlyOrders(session) + } + + /// 闪传说明与方式选择均是本地 UI,返回和关闭不会启动真实上传或设备流程。 + func testNearbyMethodReturnsToChoicesWithoutOpeningCloud() async throws { + var order = record("NEARBY", status: "processing") + order["can_upload_film"] = true + var factoryCount = 0 + let (controller, session) = makeController(responses: [try envelope([order], total: 1)], + deliveryFactory: { _, _, _ in factoryCount += 1; return UIViewController() }) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.orders.count == 1 } + let cell = try await card(at: 0, in: collection(in: controller), window: window) + try button(in: cell, id: "drone.orders.order.TEST-ORDER-NEARBY.delivery").sendActions(for: .touchUpInside) + try await settle(window) { self.deliveryNavigation(from: controller)?.topViewController is DroneDockDeliveryMethodViewController } + let sheet = try XCTUnwrap(deliveryNavigation(from: controller)) + let methods = try XCTUnwrap(sheet.topViewController as? DroneDockDeliveryMethodViewController) + try await selectDeliveryMethod("nearby", in: methods, window: window) + try await settle(window) { self.visibleTexts(in: methods.view).contains("闪传流程待确认") } + XCTAssertTrue(try button(in: methods.view, id: "drone.delivery.method.useCloud").isEnabled) + XCTAssertEqual(sheet.viewControllers.count, 1) + XCTAssertEqual(factoryCount, 0) + XCTAssertEqual(session.requests.count, 1) + capture(window, name: "我的拍摄订单-面对面闪传待确认") + try button(in: methods.view, id: "drone.delivery.upload.secondary").sendActions(for: .touchUpInside) + try await settle(window) { self.find(in: methods.view, id: "drone.delivery.method.cloud") != nil } + XCTAssertTrue(visibleTexts(in: methods.view).contains("请选择本次交付方式")) + XCTAssertEqual(factoryCount, 0) + try button(in: methods.view, id: "drone.delivery.upload.close").sendActions(for: .touchUpInside) + try await settle(window) { self.deliveryNavigation(from: controller) == nil } + XCTAssertEqual(session.requests.count, 1) + XCTAssertEqual(controller.viewModel.orders.count, 1) + } + /// 素材入口按选中订单进入真实页面,页面出现后才读取摘要与任务,不创建任务。 func testMaterialsLoadsSelectedOrderDetailAndTasksAfterNavigation() async throws { var materialsSession: MockURLSession? @@ -344,6 +441,19 @@ final class DroneDockOrdersViewTests: XCTestCase { } } + private func deliveryNavigation(from controller: UIViewController) -> UINavigationController? { + (controller.presentedViewController ?? controller.navigationController?.presentedViewController) as? UINavigationController + } + + private func selectDeliveryMethod(_ method: String, in controller: UIViewController, window: UIWindow) async throws { + let list = try XCTUnwrap(find(in: controller.view, id: "drone.delivery.method.list") as? UICollectionView) + let identifier = "drone.delivery.method.\(method)" + try await settle(window) { self.find(in: list, id: identifier) != nil } + let cell = try XCTUnwrap(find(in: list, id: identifier) as? UICollectionViewCell) + let path = try XCTUnwrap(list.indexPath(for: cell)) + list.delegate?.collectionView?(list, didSelectItemAt: path) + } + private func collection(in controller: UIViewController) throws -> UICollectionView { controller.loadViewIfNeeded() return try XCTUnwrap(find(in: controller.view, id: "drone.orders.remote.list") as? UICollectionView) diff --git a/suixinkanTests/DroneDockPreparationSimulationTests.swift b/suixinkanTests/DroneDockPreparationSimulationTests.swift new file mode 100644 index 0000000..0176eeb --- /dev/null +++ b/suixinkanTests/DroneDockPreparationSimulationTests.swift @@ -0,0 +1,144 @@ +import UIKit +import XCTest +@testable import suixinkan + +/// 使用独立内存服务走完整准备与任务页面,不创建真实订单任务或下发设备指令。 +@MainActor +final class DroneDockPreparationSimulationTests: XCTestCase { + private weak var previousKeyWindow: UIWindow? + + /// 仅点击后模拟创建并召唤,再读相同任务;开拍仍使用同一个隔离会话。 + func testPreparationCreatesSummonsAndOpensSameMockTask() async throws { + let preparation = try XCTUnwrap(DroneDockStartShootSimulation.makeController( + arguments: ["--dock-preparation-mock"]) as? DroneDockRemotePreparationViewController) + let window = makeWindow(preparation) + defer { close(window) } + let button = try button(in: preparation.view, id: "drone.preparation.summon") + try await settle(window) { button.isEnabled && preparation.viewModel.planeStatus != nil } + XCTAssertEqual(preparation.viewModel.selectedSpotID, 301) + XCTAssertEqual(preparation.viewModel.selectedRouteID, 401) + XCTAssertEqual(preparation.viewModel.planeStatus?.recommend?.id, 201) + XCTAssertNil(preparation.viewModel.createdTask) + XCTAssertNil(preparation.viewModel.shootResponse) + button.sendActions(for: .touchUpInside) + button.sendActions(for: .touchUpInside) + let navigation = try XCTUnwrap(preparation.navigationController) + try await settle(window) { + (navigation.topViewController as? DroneDockShootingTaskViewController)?.viewModel.canStartShooting == true + } + let task = try XCTUnwrap(navigation.topViewController as? DroneDockShootingTaskViewController) + XCTAssertEqual(navigation.viewControllers.count, 2) + XCTAssertEqual(task.viewModel.taskID, 901) + XCTAssertEqual(task.viewModel.order.orderNumber, "LOCAL-MOCK-ORDER-901") + XCTAssertEqual(task.viewModel.context, preparation.viewModel.context) + XCTAssertEqual(preparation.viewModel.createdTask?.taskID, 901) + try self.button(in: task.view, id: "drone.task.remote.primary").sendActions(for: .touchUpInside) + try await settle(window) { task.viewModel.hasSubmittedStart && task.viewModel.presentation.phase == .shooting } + let transcript = try await records(task, window: window) + let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) + let posts = entries.filter { $0["method"] as? String == "POST" } + XCTAssertEqual(posts.map { $0["path"] as? String }, [ + "/api/yf-handset-app/photog/multi-plane/tasks/create", "/api/app/airport/shoot", "/api/app/airport/start-shoot" + ]) + let creation = try XCTUnwrap(posts.first?["request_body"] as? [String: Any]) + XCTAssertEqual(Set(creation.keys), ["scenic_id", "order_number", "scenic_spot_id", "air_line_id"]) + XCTAssertEqual(creation["scenic_id"] as? Int, 128) + XCTAssertEqual(creation["order_number"] as? String, "LOCAL-MOCK-ORDER-901") + XCTAssertEqual(creation["scenic_spot_id"] as? Int, 301) + XCTAssertEqual(creation["air_line_id"] as? Int, 401) + let summon = try XCTUnwrap(posts[1]["request_body"] as? [String: Any]) + XCTAssertEqual(Set(summon.keys), ["id", "restart"]) + XCTAssertEqual(summon["id"] as? Int, 901) + XCTAssertEqual(summon["restart"] as? Bool, false) + XCTAssertEqual((posts[2]["request_body"] as? [String: Int]), ["id": 901]) + let taskReads = entries.filter { $0["path"] as? String == "/api/app/airport/shooting" } + XCTAssertEqual(taskReads.count, 2) + XCTAssertTrue(taskReads.allSatisfy { ($0["query"] as? String)?.contains("id=901") == true }) + XCTAssertEqual(transcript["source"] as? String, "local_mock") + XCTAssertEqual(transcript["network_sent"] as? Bool, false) + } + + /// 返回准备页后只查看原模拟任务,不重复创建或召唤,也不会自动跳转。 + func testReturningToPreparationReopensTaskWithoutRepeatedWrites() async throws { + let preparation = try XCTUnwrap(DroneDockStartShootSimulation.makePreparationController()) + let window = makeWindow(preparation) + defer { close(window) } + let button = try button(in: preparation.view, id: "drone.preparation.summon") + try await settle(window) { button.isEnabled } + button.sendActions(for: .touchUpInside) + let navigation = try XCTUnwrap(preparation.navigationController) + try await settle(window) { + (navigation.topViewController as? DroneDockShootingTaskViewController)?.viewModel.response != nil + } + navigation.popViewController(animated: false) + try await settle(window) { preparation.viewModel.canOpenShootingTask && button.isEnabled } + XCTAssertTrue(navigation.topViewController === preparation) + XCTAssertEqual(navigation.viewControllers.count, 1) + button.sendActions(for: .touchUpInside) + try await settle(window) { + (navigation.topViewController as? DroneDockShootingTaskViewController)?.viewModel.response != nil + } + let task = try XCTUnwrap(navigation.topViewController as? DroneDockShootingTaskViewController) + XCTAssertEqual(task.viewModel.taskID, 901) + let transcript = try await records(task, window: window) + let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) + XCTAssertEqual(entries.filter { $0["method"] as? String == "POST" }.map { $0["path"] as? String }, [ + "/api/yf-handset-app/photog/multi-plane/tasks/create", "/api/app/airport/shoot" + ]) + XCTAssertEqual(entries.filter { $0["path"] as? String == "/api/app/airport/shooting" }.count, 2) + XCTAssertEqual(transcript["network_sent"] as? Bool, false) + } + + private func records(_ controller: UIViewController, window: UIWindow) async throws -> [String: Any] { + let item = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first { + $0.accessibilityIdentifier == "drone.task.mock.recordsButton" + }) + let action = try XCTUnwrap(item.action) + _ = UIApplication.shared.sendAction(action, to: item.target, from: item, for: nil) + try await settle(window) { controller.presentedViewController != nil } + let sheet = try XCTUnwrap(controller.presentedViewController) + let text = try XCTUnwrap(allViews(sheet.view).first { + $0.accessibilityIdentifier == "drone.task.mock.records" + } as? UITextView) + return try XCTUnwrap(JSONSerialization.jsonObject(with: Data(text.text.utf8)) as? [String: Any]) + } + + private func button(in root: UIView, id: String) throws -> UIButton { + try XCTUnwrap(allViews(root).first { $0.accessibilityIdentifier == id } as? UIButton) + } + + private func makeWindow(_ controller: 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: controller) + window.makeKeyAndVisible() + return window + } + + private func close(_ window: UIWindow) { + window.rootViewController?.dismiss(animated: false) + window.isHidden = true + window.rootViewController = nil + previousKeyWindow?.makeKeyAndVisible() + } + + 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: "DroneDockPreparationSimulationTests", code: 1) + } + + private func allViews(_ root: UIView) -> [UIView] { [root] + root.subviews.flatMap { allViews($0) } } +} diff --git a/suixinkanTests/DroneDockPreparationViewTests.swift b/suixinkanTests/DroneDockPreparationViewTests.swift index 55835cf..bb678b8 100644 --- a/suixinkanTests/DroneDockPreparationViewTests.swift +++ b/suixinkanTests/DroneDockPreparationViewTests.swift @@ -7,6 +7,35 @@ import XCTest final class DroneDockPreparationViewTests: XCTestCase { private weak var previousKeyWindow: UIWindow? + /// 禁飞准备页只通过显式入口打开独立模拟订单,不放开原订单的创建和召唤。 + func testNoFlightEntryOpensIsolatedPreparationWithoutSubmittingOriginalOrder() async throws { + let creation = DroneDockTaskCreationTestService() + let shoot = DroneDockShootTestService() + let (controller, session) = try DroneDockPreparationViewFixtures.controller( + context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(), + creationService: creation, shootService: shoot, allowsTaskSubmission: false) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.projectInfo != nil } + XCTAssertFalse(try button(in: controller.view, id: "drone.preparation.summon").isEnabled) + let item = try XCTUnwrap(controller.navigationItem.rightBarButtonItem) + XCTAssertEqual(item.accessibilityIdentifier, "drone.preparation.mock.entry") + let action = try XCTUnwrap(item.action) + _ = UIApplication.shared.sendAction(action, to: item.target, from: item, for: nil) + try await settle(window) { controller.navigationController?.viewControllers.count == 2 } + let simulation = try XCTUnwrap(controller.navigationController?.topViewController as? DroneDockRemotePreparationViewController) + try await settle(window) { simulation.viewModel.projectInfo != nil } + XCTAssertEqual(simulation.title, "拍摄准备 · 本地模拟") + XCTAssertEqual(simulation.viewModel.order.orderNumber, "LOCAL-MOCK-ORDER-901") + XCTAssertNotEqual(simulation.viewModel.context, controller.viewModel.context) + XCTAssertTrue(simulation.viewModel.isPrimaryActionEnabled) + XCTAssertNil(controller.viewModel.createdTask) + XCTAssertNil(controller.viewModel.shootResponse) + XCTAssertTrue(creation.requests.isEmpty) + XCTAssertTrue(shoot.requests.isEmpty) + assertOnlyPreparationReads(session) + } + /// 页面只读取准备信息,有效购买配置允许明确点击创建任务,出现时不自动写入。 func testProjectSnapshotDisplaysOrderPointsRoutesAfterPageAppears() async throws { let (controller, session) = try makeController(responses: [DroneDockPreparationViewFixtures.projectEnvelope()]) @@ -703,6 +732,7 @@ enum DroneDockPreparationViewFixtures { planeService: (any DroneDockPlaneStatusServing)? = nil, creationService: (any DroneDockTaskCreating)? = nil, shootService: (any DroneDockShootServing)? = nil, + allowsTaskSubmission: Bool = true, taskControllerFactory: (@MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil, pollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }, currentContext: (@MainActor @Sendable () -> DroneDockHomeContext)? = nil) throws -> (DroneDockRemotePreparationViewController, MockURLSession) { @@ -715,6 +745,7 @@ enum DroneDockPreparationViewFixtures { planeStatusService: try planeService ?? DroneDockPlaneStatusTestService(), taskCreationService: creationService ?? DroneDockTaskCreationTestService(), shootService: shootService ?? DroneDockShootTestService(), + allowsTaskSubmission: allowsTaskSubmission, currentContext: currentContext ?? { context }) let factory = taskControllerFactory ?? { taskID, _, _ in DroneDockPreparationTaskDestinationStub(taskID: taskID) } return (DroneDockRemotePreparationViewController(viewModel: model, taskControllerFactory: factory, diff --git a/suixinkanTests/DroneDockStartShootAPITests.swift b/suixinkanTests/DroneDockStartShootAPITests.swift new file mode 100644 index 0000000..ad6bb82 --- /dev/null +++ b/suixinkanTests/DroneDockStartShootAPITests.swift @@ -0,0 +1,180 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 通过纯内存 Mock 核验开拍合同,任何用例都不连接后端或真实无人机。 +@MainActor +final class DroneDockStartShootAPITests: XCTestCase { + /// 单次请求只携带原任务 ID,保留鉴权,不发送选机、重启或未经约定的模拟标志。 + func testStartSendsOneAuthenticatedPOSTWithOnlyOrderFlightTaskID() async throws { + let session = MockURLSession(responses: [try envelope(data: payload())]) + let client = APIClient(environment: .testing, session: session) + client.bindAuthTokenProvider { "start-shoot-test-token" } + let response = try await DroneDockStartShootAPI(client: client).startShooting(taskID: 501) + + XCTAssertEqual(session.requests.count, 1) + let request = try XCTUnwrap(session.requests.first) + XCTAssertEqual(request.httpMethod, "POST") + XCTAssertEqual(request.url?.path, "/api/app/airport/start-shoot") + XCTAssertNil(request.url?.query) + XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "start-shoot-test-token") + let body = try XCTUnwrap(JSONSerialization.jsonObject(with: XCTUnwrap(request.httpBody)) as? [String: Any]) + XCTAssertEqual(Set(body.keys), ["id"]) + XCTAssertEqual(body["id"] as? Int, 501) + XCTAssertEqual(response.orderFlightTaskID, 501) + XCTAssertEqual(response.orderFlightTask?.id, 501) + XCTAssertEqual(response.planeID, 58) + XCTAssertEqual(response.taskUUID, "TEST-START-UUID") + XCTAssertEqual(response.airportSN, "TEST-AIRPORT-058") + XCTAssertEqual(response.ui?.phase, "shooting") + XCTAssertEqual(response.ui?.title, "模拟:无人机正在拍摄中") + } + + /// 无效任务身份在调用传输前被拒绝,不尝试创建或召唤。 + func testInvalidTaskIDNeverReachesTransport() async throws { + let session = MockURLSession(responses: []) + let api = DroneDockStartShootAPI(client: APIClient(environment: .testing, session: session)) + for taskID in [0, -1] { + do { + _ = try await api.startShooting(taskID: taskID) + XCTFail("无效任务 ID 不应提交开拍") + } catch let APIError.networkFailed(message) { XCTAssertFalse(message.isEmpty) } + } + XCTAssertTrue(session.requests.isEmpty) + } + + /// 调用前已取消时不产生开拍写请求。 + func testCancelledStartDoesNotReachTransport() async throws { + let session = MockURLSession(responses: []) + let api = DroneDockStartShootAPI(client: APIClient(environment: .testing, session: session)) + let pending = Task { @MainActor in try await api.startShooting(taskID: 501) } + pending.cancel() + do { + _ = try await pending.value + XCTFail("已取消请求不应发出") + } catch is CancellationError {} + XCTAssertTrue(session.requests.isEmpty) + } + + /// 明确业务拒绝优先于 data 内容,保留后端原因而不转换成成功。 + func testBusinessFailurePreservesBackendCodeAndReason() async throws { + for data: Any in [NSNull(), [:] as [String: Any], [] as [Any], payload()] { + let session = MockURLSession(responses: [try envelope(data: data, code: 100099, message: "模拟:任务当前不可开始拍摄")]) + do { + _ = try await DroneDockStartShootAPI(client: APIClient(environment: .testing, session: session)).startShooting(taskID: 501) + XCTFail("业务拒绝不能算成功") + } catch let APIError.serverCode(code, message) { + XCTAssertEqual(code, 100099) + XCTAssertEqual(message, "模拟:任务当前不可开始拍摄") + } + XCTAssertEqual(session.requests.count, 1) + } + } + + /// 超时不自动重复写入;结果是否执行须由上层核对同一任务。 + func testTimeoutIsReturnedWithoutAutomaticRetry() async throws { + let session = MockURLSession(results: [.failure(URLError(.timedOut))]) + do { + _ = try await DroneDockStartShootAPI(client: APIClient(environment: .testing, session: session)).startShooting(taskID: 501) + XCTFail("超时不能伪造成功") + } catch let APIError.networkFailed(message) { XCTAssertFalse(message.isEmpty) } + XCTAssertEqual(session.requests.count, 1) + } + + /// HTTP 失败即使包含成功业务包裹也不视为开拍受理。 + func testHTTPFailureIsNotConvertedToSuccess() async throws { + let session = MockURLSession(responses: [try envelope(data: payload())], statusCode: 503) + do { + _ = try await DroneDockStartShootAPI(client: APIClient(environment: .testing, session: session)).startShooting(taskID: 501) + XCTFail("HTTP 失败不能算开拍成功") + } catch let APIError.httpStatus(code, _) { XCTAssertEqual(code, 503) } + XCTAssertEqual(session.requests.count, 1) + } + + /// 无 data、空对象或缺少顶层任务身份都不构造成功回执。 + func testMissingDataAndMissingIdentityAreRejected() async throws { + let envelopes = [ + try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success"]), + try envelope(data: NSNull()), try envelope(data: [:]), try envelope(data: []), + try envelope(data: ["order_flight_task": ["id": 501], "ui": ["phase": "shooting"]]) + ] + for data in envelopes { + let session = MockURLSession(responses: [data]) + do { + _ = try await DroneDockStartShootAPI(client: APIClient(environment: .testing, session: session)).startShooting(taskID: 501) + XCTFail("缺少开拍回执身份不得返回成功") + } catch let error as APIError { + switch error { + case .emptyData, .decodeFailed: break + default: XCTFail("应保留数据缺失或解析错误:\(error)") + } + } + XCTAssertEqual(session.requests.count, 1) + } + } + + /// 顶层任务身份与嵌套任务身份分别核对,不把另一个任务的回执交给当前页面。 + func testMismatchedOrInvalidTaskIdentityIsRejectedWithoutRetry() async throws { + let changes: [[String: Any]] = [ + ["order_flight_task_id": 502], ["order_flight_task_id": 0], + ["order_flight_task_id": -1], ["order_flight_task_id": "501"], + ["order_flight_task_id": true], ["order_flight_task": ["id": 502]], + ["order_flight_task": ["id": 0]] + ] + for change in changes { + let session = MockURLSession(responses: [try envelope(data: payload().merging(change) { _, new in new })]) + do { + _ = try await DroneDockStartShootAPI(client: APIClient(environment: .testing, session: session)).startShooting(taskID: 501) + XCTFail("不同或无效任务身份应拒绝") + } catch let APIError.decodeFailed(message) { XCTAssertFalse(message.isEmpty) } + XCTAssertEqual(session.requests.count, 1) + } + } + + /// 后续回执新增字段不丢失,数字、字符串、空值和动作列表保持原 JSON 类型。 + func testFullDataPreservesUnknownFieldsAndOptionalNulls() async throws { + var data = payload() + data["future"] = ["flag": false, "count": 0, "text": "001", "items": [NSNull(), 12.5]] as [String: Any] + data["order_flight_task"] = NSNull() + data["plane_id"] = NSNull() + let session = MockURLSession(responses: [try envelope(data: data)]) + let response = try await DroneDockStartShootAPI(client: APIClient(environment: .testing, session: session)).startShooting(taskID: 501) + XCTAssertNil(response.orderFlightTask) + XCTAssertNil(response.planeID) + let displayed = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: Data(response.dataJSON.utf8)) + let original = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: JSONSerialization.data(withJSONObject: data)) + XCTAssertEqual(displayed, original) + } + + /// 开拍 API 本身仍受禁飞边界约束,未标记本地模拟的传输一次也不会被调用。 + func testDebugPolicyBlocksStartBeforeLiveTransport() async throws { + let session = StartShootTransportProbe() + do { + _ = try await DroneDockStartShootAPI(client: APIClient(environment: .testing, session: session)).startShooting(taskID: 501) + XCTFail("禁飞保护不能因新增开拍 API 而失效") + } catch is DeviceCommandDebugBlockedError {} + XCTAssertEqual(session.requestCount, 0) + } + + private func payload() -> [String: Any] { + ["order_flight_task_id": 501, + "order_flight_task": ["id": 501, "order_number": "TEST-START-501", "scenic_id": 128, "status": 20], + "plane_id": 58, "task_uuid": "TEST-START-UUID", "airport_sn": "TEST-AIRPORT-058", + "ui": ["phase": "shooting", "title": "模拟:无人机正在拍摄中", "message": "本地模拟,未发送设备指令", + "primary_action": "shooting", "commands": [["command": "flighttask_pause", "label": "紧急暂停"]]]] + } + + private func envelope(data: Any, code: Int = 100000, message: String = "success") throws -> Data { + try JSONSerialization.data(withJSONObject: ["code": code, "msg": message, "data": data]) + } +} + +/// 不提供本地模拟豁免的拦截探针,内部也不联网,用于验证真实传输路径被禁止。 +private final class StartShootTransportProbe: URLSessionProtocol { + private(set) var requestCount = 0 + + func data(for request: URLRequest) async throws -> (Data, URLResponse) { + requestCount += 1 + throw URLError(.unsupportedURL) + } +} diff --git a/suixinkanTests/DroneDockStartShootViewModelTests.swift b/suixinkanTests/DroneDockStartShootViewModelTests.swift new file mode 100644 index 0000000..0f44161 --- /dev/null +++ b/suixinkanTests/DroneDockStartShootViewModelTests.swift @@ -0,0 +1,343 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 开拍流程仅使用纯内存服务,验证同任务串接、门禁和不可重复提交的边界。 +@MainActor +final class DroneDockStartShootViewModelTests: XCTestCase { + /// 正式入口默认未注入写服务,即使后端允许开始也不能发送开拍。 + func testMissingStartServiceKeepsReadyActionDisabled() async throws { + let fixture = try StartTaskFixture(allowStart: false) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .ready) + XCTAssertEqual(fixture.model.presentation.action, .start) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertFalse(fixture.model.presentation.isActionEnabled) + await fixture.model.startShooting() + XCTAssertTrue(fixture.start.requests.isEmpty) + } + + /// 到达、明确门禁、动作及锁定飞机四项缺一不可,订单状态 20 本身不等于可开始。 + func testStartRequiresAllExplicitReadyConditions() async throws { + let changes: [[String: Any]] = [ + ["execute_gate": ["can_execute": false, "primary_action": "start_shoot"]], + ["execute_gate": ["can_execute": true]], + ["execute_gate": ["can_execute": true, "primary_action": "blocked"]], + ["current_plane": ["status_text": "空闲"]], + ["current_plane": ["id": 0]], + ["ui": ["phase": "shooting"]], + ["ui": ["phase": "unknown"]], + ["ui": NSNull()], + ["task": ["id": 501, "status": 20, "wayline_status": 91]] + ] + for change in changes { + let fixture = try StartTaskFixture() + fixture.read.result = .success(try StartTaskData.ready(changes: change)) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.canStartShooting, "\(change)") + await fixture.model.startShooting() + XCTAssertTrue(fixture.start.requests.isEmpty) + } + } + + /// 点击只提交既有任务一次,明确受理后查询同一任务,以查询结果更新阶段。 + func testSuccessStartsOnceThenReadsSameTaskWithoutPolling() async throws { + let fixture = try StartTaskFixture() + await fixture.model.refresh() + let oldResponse = fixture.model.response + let shooting = try StartTaskData.shooting() + fixture.start.onRequest = { fixture.read.result = .success(shooting) } + var observedAcceptedOldSnapshot = false + await fixture.model.startShooting { + if fixture.model.hasSubmittedStart && fixture.model.response == oldResponse { + observedAcceptedOldSnapshot = true + XCTAssertTrue(fixture.model.isStartingShooting) + XCTAssertFalse(fixture.model.presentation.isActionEnabled) + } + } + XCTAssertTrue(observedAcceptedOldSnapshot) + XCTAssertEqual(fixture.start.requests, [501]) + XCTAssertEqual(fixture.read.requests, [501, 501]) + XCTAssertTrue(fixture.model.hasSubmittedStart) + XCTAssertNotNil(fixture.model.startResponse?.dataJSON) + XCTAssertEqual(fixture.model.response, shooting) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertFalse(fixture.model.startOutcomeUnknown) + await fixture.model.startShooting() + fixture.model.invalidate(preservingSnapshot: true) + await fixture.model.refresh() + await fixture.model.startShooting() + XCTAssertEqual(fixture.start.requests, [501]) + XCTAssertEqual(fixture.read.requests, [501, 501, 501]) + } + + /// 已受理后的状态查询失败保留旧画面,刷新即便仍显示 ready 也不能再提交。 + func testAcceptedStartWithFailedFollowupReadRemainsLocked() async throws { + let fixture = try StartTaskFixture() + await fixture.model.refresh() + let old = fixture.model.response + fixture.read.result = .failure(APIError.networkFailed("模拟查询超时")) + await fixture.model.startShooting() + XCTAssertTrue(fixture.model.hasSubmittedStart) + XCTAssertNotNil(fixture.model.startResponse) + XCTAssertFalse(fixture.model.startOutcomeUnknown) + XCTAssertEqual(fixture.model.response, old) + XCTAssertNotNil(fixture.model.errorMessage) + XCTAssertEqual(fixture.model.presentation.action, .refresh) + XCTAssertTrue(fixture.model.statusMessage.contains("已受理")) + fixture.read.result = .success(try StartTaskData.ready()) + await fixture.model.refresh() + await fixture.model.startShooting() + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertEqual(fixture.start.requests, [501]) + } + + /// 明确业务拒绝可以再次点击,重试仍用同一任务且不自动重发。 + func testExplicitRejectionAllowsOnlyManualRetry() async throws { + let fixture = try StartTaskFixture() + await fixture.model.refresh() + fixture.start.result = .failure(APIError.serverCode(100099, "模拟设备暂不可开始")) + await fixture.model.startShooting() + XCTAssertEqual(fixture.start.requests, [501]) + XCTAssertEqual(fixture.read.requests, [501]) + XCTAssertFalse(fixture.model.hasSubmittedStart) + XCTAssertFalse(fixture.model.startOutcomeUnknown) + XCTAssertEqual(fixture.model.startErrorMessage, "模拟设备暂不可开始") + XCTAssertTrue(fixture.model.canStartShooting) + XCTAssertEqual(fixture.model.presentation.actionTitle, "重试开始拍摄") + fixture.start.result = .success(try StartTaskData.receipt()) + fixture.read.result = .success(try StartTaskData.shooting()) + await fixture.model.startShooting() + XCTAssertEqual(fixture.start.requests, [501, 501]) + XCTAssertNil(fixture.model.startErrorMessage) + XCTAssertTrue(fixture.model.hasSubmittedStart) + } + + /// 网络、HTTP 或解析结果不明确时锁定提交,刷新成功也不把旧门禁当作重试许可。 + func testAmbiguousFailureNeverRetriesAfterRefreshOrReentry() async throws { + for error in [APIError.networkFailed("模拟超时"), APIError.httpStatus(500, "模拟异常"), + APIError.decodeFailed("模拟回执不可解析")] { + let fixture = try StartTaskFixture() + await fixture.model.refresh() + let previous = fixture.model.response + fixture.start.result = .failure(error) + await fixture.model.startShooting() + XCTAssertTrue(fixture.model.startOutcomeUnknown) + XCTAssertFalse(fixture.model.hasSubmittedStart) + XCTAssertNil(fixture.model.startResponse) + XCTAssertEqual(fixture.model.response, previous) + XCTAssertTrue(fixture.model.startErrorMessage?.contains("勿重复提交") == true) + XCTAssertEqual(fixture.model.presentation.action, .refresh) + XCTAssertTrue(fixture.model.presentation.isActionEnabled) + fixture.model.invalidate(preservingSnapshot: true) + await fixture.model.refresh() + await fixture.model.startShooting() + XCTAssertEqual(fixture.start.requests, [501]) + } + } + + /// 本地禁飞拦截明确未发送,不得伪装为远端超时或成功。 + func testLocalBlockShowsRestrictionWithoutUnknownLock() async throws { + let fixture = try StartTaskFixture() + await fixture.model.refresh() + fixture.start.result = .failure(DeviceCommandDebugBlockedError()) + await fixture.model.startShooting() + XCTAssertEqual(fixture.model.startErrorMessage, DeviceCommandDebugPolicy.blockedMessage) + XCTAssertFalse(fixture.model.startOutcomeUnknown) + XCTAssertFalse(fixture.model.hasSubmittedStart) + XCTAssertNil(fixture.model.startResponse) + XCTAssertEqual(fixture.read.requests, [501]) + fixture.model.invalidate(preservingSnapshot: true) + XCTAssertFalse(fixture.model.startOutcomeUnknown) + } + + /// 挂起提交期间只保留一次 POST,刷新和二次点击不会并发覆盖准备快照。 + func testPendingStartRetainsSnapshotAndRejectsConcurrentActions() async throws { + let fixture = try StartTaskFixture() + await fixture.model.refresh() + let previous = fixture.model.response + fixture.start.suspend = true + let submitted = expectation(description: "开拍请求进入内存服务") + fixture.start.onRequest = { submitted.fulfill() } + defer { fixture.start.finish() } + let pending = Task { await fixture.model.startShooting() } + await fulfillment(of: [submitted], timeout: 2) + XCTAssertTrue(fixture.model.isStartingShooting) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertEqual(fixture.model.response, previous) + await fixture.model.startShooting() + await fixture.model.refresh() + XCTAssertEqual(fixture.start.requests, [501]) + XCTAssertEqual(fixture.read.requests, [501]) + fixture.read.result = .success(try StartTaskData.shooting()) + fixture.start.finish() + await pending.value + XCTAssertEqual(fixture.read.requests, [501, 501]) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + } + + /// 取消或离页后的迟到成功回执不能更新页面,也不能触发后续查询或重新提交。 + func testCancellationOrLeavingAfterSubmissionLocksUnknown() async throws { + for leavePage in [false, true] { + let fixture = try StartTaskFixture() + await fixture.model.refresh() + let previous = fixture.model.response + fixture.start.suspend = true + let submitted = expectation(description: "等待取消开拍") + fixture.start.onRequest = { submitted.fulfill() } + defer { fixture.start.finish() } + let pending = Task { await fixture.model.startShooting() } + await fulfillment(of: [submitted], timeout: 2) + if leavePage { fixture.model.invalidate(preservingSnapshot: true) } else { pending.cancel() } + fixture.start.finish() + await pending.value + XCTAssertTrue(fixture.model.startOutcomeUnknown) + XCTAssertFalse(fixture.model.hasSubmittedStart) + XCTAssertNil(fixture.model.startResponse) + XCTAssertEqual(fixture.model.response, previous) + XCTAssertEqual(fixture.read.requests, [501]) + await fixture.model.refresh() + await fixture.model.startShooting() + XCTAssertEqual(fixture.start.requests, [501]) + } + } + + /// 点击前任务已取消或账号已变化,不开始发送;账号变化会清除旧页面快照。 + func testCancellationAndIdentityChangeBeforeSubmitSendNothing() async throws { + let fixture = try StartTaskFixture() + await fixture.model.refresh() + let cancelled = Task { await fixture.model.startShooting() } + cancelled.cancel() + await cancelled.value + XCTAssertTrue(fixture.start.requests.isEmpty) + XCTAssertFalse(fixture.model.startOutcomeUnknown) + fixture.scope.scenicID = 999 + await fixture.model.startShooting() + XCTAssertTrue(fixture.start.requests.isEmpty) + XCTAssertNil(fixture.model.response) + XCTAssertFalse(fixture.model.canStartShooting) + } + + /// 回执必须仍属于页面任务和锁定飞机,即使 API 替身返回异常身份也不接受成功。 + func testMismatchedReceiptCannotUpdateStateOrTriggerRead() async throws { + let changes: [[String: Any]] = [ + ["order_flight_task_id": 999], ["plane_id": 999], + ["order_flight_task": ["id": 501, "order_number": "ANOTHER-ORDER"]], + ["order_flight_task": ["id": 501, "scenic_id": 999]] + ] + for change in changes { + let fixture = try StartTaskFixture() + await fixture.model.refresh() + fixture.start.result = .success(try StartTaskData.receipt(changes: change)) + await fixture.model.startShooting() + XCTAssertTrue(fixture.model.startOutcomeUnknown) + XCTAssertFalse(fixture.model.hasSubmittedStart) + XCTAssertNil(fixture.model.startResponse) + XCTAssertEqual(fixture.read.requests, [501]) + } + } + + /// 只读刷新失败后虽然仍显示上次 ready 快照,也必须先读到有效新状态再允许开拍。 + func testStaleReadySnapshotCannotBeUsedAfterFailedRefresh() async throws { + let fixture = try StartTaskFixture() + await fixture.model.refresh() + fixture.read.result = .failure(APIError.networkFailed("模拟读取失败")) + await fixture.model.refresh() + XCTAssertNotNil(fixture.model.response) + XCTAssertFalse(fixture.model.canStartShooting) + await fixture.model.startShooting() + XCTAssertTrue(fixture.start.requests.isEmpty) + } +} + +/// 独立的任务、账号与内存服务组合,不连接共享网络或真实无人机。 +@MainActor +private struct StartTaskFixture { + let scope: StartTaskScope + let read: StartTaskReadService + let start: StartTaskWriteService + let model: DroneDockShootingTaskViewModel + + init(allowStart: Bool = true) throws { + scope = StartTaskScope() + read = StartTaskReadService(result: .success(try StartTaskData.ready())) + start = StartTaskWriteService(result: .success(try StartTaskData.receipt())) + let boundScope = scope + model = DroneDockShootingTaskViewModel(context: boundScope.value, taskID: 501, + order: try DroneDockShootingTaskTestData.order(), service: read, + startService: allowStart ? start : nil, currentContext: { boundScope.value }) + } +} + +/// 显式可切换景区的测试身份,避免修改共享登录状态。 +@MainActor +private final class StartTaskScope { + var scenicID = 128 + var value: DroneDockHomeContext { DroneDockShootingTaskTestData.context(scenicID: scenicID) } +} + +/// 单次返回指定状态的读取替身,记录每次同任务查询。 +@MainActor +private final class StartTaskReadService: DroneDockShootingServing { + var result: Result + private(set) var requests: [Int] = [] + + init(result: Result) { self.result = result } + + func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse { + requests.append(taskID) + return try result.get() + } +} + +/// 可挂起并返回成功或错误的开拍替身,始终只处理内存回执。 +@MainActor +private final class StartTaskWriteService: DroneDockStartShooting { + var result: Result + var onRequest: (() -> Void)? + var suspend = false + private(set) var requests: [Int] = [] + private var continuation: CheckedContinuation? + + init(result: Result) { self.result = result } + + func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse { + requests.append(taskID) + onRequest?() + if suspend { return try await withCheckedThrowingContinuation { continuation = $0 } } + return try result.get() + } + + func finish() { + continuation?.resume(with: result) + continuation = nil + } +} + +/// 根据接口文档组装匿名模拟响应,不能作为真实设备执行证据。 +private enum StartTaskData { + static func ready(changes: [String: Any] = [:]) throws -> DroneDockShootingResponse { + try DroneDockShootingTaskTestData.response(changes: [ + "order_flight_task": ["id": 501, "order_number": "TEST-TASK-PAGE-001", "scenic_id": 128, "status": 20], + "task": ["id": 501, "status": 20], + "execute_gate": ["can_execute": true, "primary_action": "start_shoot", "primary_action_label": "开始拍摄"], + "ui": ["phase": "arrived_pending_start", "title": "模拟无人机已到达", "message": "模拟确认游客站位"] + ].merging(changes) { _, new in new }) + } + + static func shooting() throws -> DroneDockShootingResponse { + try ready(changes: ["ui": ["phase": "shooting", "title": "模拟无人机正在拍摄中", "message": "本地模拟,未下发设备指令"], + "execute_gate": ["can_execute": false, "primary_action": "shooting"]]) + } + + static func receipt(changes: [String: Any] = [:]) throws -> DroneDockStartShootResponse { + let payload: [String: Any] = [ + "order_flight_task_id": 501, "plane_id": 58, "task_uuid": "LOCAL-START-501", + "order_flight_task": ["id": 501, "order_number": "TEST-TASK-PAGE-001", "scenic_id": 128], + "ui": ["phase": "shooting", "title": "模拟无人机正在拍摄中", "message": "本地模拟"] + ] + return try JSONDecoder().decode(DroneDockStartShootResponse.self, + from: JSONSerialization.data(withJSONObject: payload.merging(changes) { _, new in new })) + } +} diff --git a/suixinkanTests/DroneDockStartShootViewTests.swift b/suixinkanTests/DroneDockStartShootViewTests.swift new file mode 100644 index 0000000..7c0d91f --- /dev/null +++ b/suixinkanTests/DroneDockStartShootViewTests.swift @@ -0,0 +1,147 @@ +import UIKit +import XCTest +@testable import suixinkan + +/// 通过独立内存传输驱动真实任务页,验证开始按钮与接口流程,不连接任何后端。 +@MainActor +final class DroneDockStartShootViewTests: XCTestCase { + private weak var previousKeyWindow: UIWindow? + + /// 双击只提交一次,回执后读同一任务并显示拍摄中,固定区域和旧读数不闪空。 + func testLocalSuccessRefreshesSameTaskAndRejectsDoubleTap() async throws { + let controller = try makeController(result: "success") + let window = makeWindow(controller) + defer { close(window) } + try await settle(window) { controller.viewModel.canStartShooting } + XCTAssertEqual(controller.title, "拍摄任务 · 本地模拟") + let fixedIDs = ["top", "stateContainer", "safety"] + let frames = try fixedIDs.map { try XCTUnwrap(find(controller.view, suffix: $0)).frame } + let oldTitle = controller.viewModel.presentation.title + let oldBattery = find(controller.view, suffix: "metric.battery")?.accessibilityValue + let button = try XCTUnwrap(find(controller.view, suffix: "primary") as? UIButton) + button.sendActions(for: .touchUpInside) + button.sendActions(for: .touchUpInside) + XCTAssertFalse(button.isEnabled) + XCTAssertEqual(find(controller.view, suffix: "metric.battery")?.accessibilityValue, oldBattery) + XCTAssertEqual(controller.viewModel.presentation.title, oldTitle) + try await settle(window) { controller.viewModel.hasSubmittedStart && controller.viewModel.presentation.phase == .shooting } + XCTAssertFalse(controller.viewModel.canStartShooting) + for (index, suffix) in fixedIDs.enumerated() { + XCTAssertEqual(try XCTUnwrap(find(controller.view, suffix: suffix)).frame, frames[index]) + } + let transcript = try await records(controller, window: window) + let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) + XCTAssertEqual(transcript["network_sent"] as? Bool, false) + XCTAssertEqual(entries.map { $0["method"] as? String }, ["GET", "POST", "GET"]) + XCTAssertEqual(entries.filter { $0["method"] as? String == "POST" }.count, 1) + } + + /// 明确业务拒绝保留旧页面,只有再次点击才再次提交;不偷偷创建或召唤。 + func testLocalBusinessFailureAllowsOnlyExplicitRetry() async throws { + let controller = try makeController(result: "business-failure") + let window = makeWindow(controller) + defer { close(window) } + try await settle(window) { controller.viewModel.canStartShooting } + let button = try XCTUnwrap(find(controller.view, suffix: "primary") as? UIButton) + button.sendActions(for: .touchUpInside) + try await settle(window) { controller.viewModel.startErrorMessage != nil && !controller.viewModel.isStartingShooting } + XCTAssertFalse(controller.viewModel.startOutcomeUnknown) + XCTAssertFalse(controller.viewModel.hasSubmittedStart) + XCTAssertTrue(controller.viewModel.canStartShooting) + XCTAssertTrue(button.isEnabled) + button.sendActions(for: .touchUpInside) + try await settle(window) { controller.viewModel.startErrorMessage != nil && !controller.viewModel.isStartingShooting } + let transcript = try await records(controller, window: window) + let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) + XCTAssertEqual(entries.map { $0["method"] as? String }, ["GET", "POST", "POST"]) + XCTAssertFalse(entries.contains { ($0["path"] as? String)?.contains("/tasks/create") == true }) + XCTAssertFalse(entries.contains { $0["path"] as? String == "/api/app/airport/shoot" }) + } + + /// 超时结果未知时即使读回旧的可开始状态,也不能重发开始请求。 + func testLocalTimeoutLocksStartWhileReadRefreshRemainsAvailable() async throws { + let controller = try makeController(result: "timeout") + let window = makeWindow(controller) + defer { close(window) } + try await settle(window) { controller.viewModel.canStartShooting } + let button = try XCTUnwrap(find(controller.view, suffix: "primary") as? UIButton) + button.sendActions(for: .touchUpInside) + try await settle(window) { controller.viewModel.startOutcomeUnknown && !controller.viewModel.isStartingShooting } + XCTAssertFalse(controller.viewModel.canStartShooting) + let refresh = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first { + $0.accessibilityIdentifier == "drone.task.remote.navigationRefresh" + }) + XCTAssertTrue(refresh.isEnabled) + send(refresh) + try await settle(window) { !controller.viewModel.isLoading } + XCTAssertFalse(controller.viewModel.canStartShooting) + let transcript = try await records(controller, window: window) + let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) + XCTAssertEqual(entries.filter { $0["method"] as? String == "POST" }.count, 1) + XCTAssertEqual(transcript["network_sent"] as? Bool, false) + } + + private func makeController(result: String) throws -> DroneDockShootingTaskViewController { + try XCTUnwrap(DroneDockStartShootSimulation.makeController( + arguments: ["--dock-start-shoot-mock", "--dock-start-shoot-result=\(result)"]) + as? DroneDockShootingTaskViewController) + } + + private func records(_ controller: UIViewController, window: UIWindow) async throws -> [String: Any] { + let item = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first { + $0.accessibilityIdentifier == "drone.task.mock.recordsButton" + }) + XCTAssertTrue(item.isEnabled) + send(item) + try await settle(window) { controller.presentedViewController != nil } + let sheet = try XCTUnwrap(controller.presentedViewController) + let text = try XCTUnwrap(allViews(sheet.view).first { + $0.accessibilityIdentifier == "drone.task.mock.records" + } as? UITextView) + return try XCTUnwrap(JSONSerialization.jsonObject(with: Data(text.text.utf8)) as? [String: Any]) + } + + private func send(_ item: UIBarButtonItem) { + guard let action = item.action else { return XCTFail("缺少按钮操作") } + _ = UIApplication.shared.sendAction(action, to: item.target, from: item, for: nil) + } + + private func makeWindow(_ controller: 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: controller) + window.makeKeyAndVisible() + return window + } + + private func close(_ window: UIWindow) { + window.rootViewController?.dismiss(animated: false) + window.isHidden = true + window.rootViewController = nil + previousKeyWindow?.makeKeyAndVisible() + } + + private func settle(_ window: UIWindow, until condition: () -> Bool) async throws { + for _ in 0..<200 { + window.layoutIfNeeded() + if condition() { + try await Task.sleep(nanoseconds: 80_000_000) + window.layoutIfNeeded() + if condition() { return } + } + try await Task.sleep(nanoseconds: 15_000_000) + } + XCTFail("模拟开拍页面未在预期时间内完成状态更新") + throw NSError(domain: "DroneDockStartShootViewTests", code: 1) + } + + private func find(_ root: UIView, suffix: String) -> UIView? { + allViews(root).first { $0.accessibilityIdentifier == "drone.task.remote.\(suffix)" } + } + + private func allViews(_ root: UIView) -> [UIView] { [root] + root.subviews.flatMap { allViews($0) } } +} diff --git a/suixinkanTests/DroneMaterialsFlowViewTests.swift b/suixinkanTests/DroneMaterialsFlowViewTests.swift index d97d14a..77b9d31 100644 --- a/suixinkanTests/DroneMaterialsFlowViewTests.swift +++ b/suixinkanTests/DroneMaterialsFlowViewTests.swift @@ -235,7 +235,8 @@ final class DroneMaterialsFlowViewTests: XCTestCase { try button(in: denied.view, identifier: "drone.materials.permission").sendActions(for: .touchUpInside) try await settle(window) { denied.presentedViewController is UIAlertController } let alert = try XCTUnwrap(denied.presentedViewController as? UIAlertController) - XCTAssertEqual(alert.title, "相册权限演示") + XCTAssertEqual(alert.title, "无法保存到手机相册") + XCTAssertEqual(alert.actions.map(\.title), ["暂不下载", "模拟恢复权限"]) XCTAssertTrue(alert.message?.contains("不读取或修改系统相册权限") == true) XCTAssertEqual(viewModel.photoPermission, .denied) XCTAssertEqual(viewModel.selectedIDs, deniedSelection) diff --git a/suixinkanTests/DroneMaterialsFooterLayoutTests.swift b/suixinkanTests/DroneMaterialsFooterLayoutTests.swift new file mode 100644 index 0000000..84e31e2 --- /dev/null +++ b/suixinkanTests/DroneMaterialsFooterLayoutTests.swift @@ -0,0 +1,85 @@ +import UIKit +import XCTest +@testable import suixinkan + +/// 验证演示下载底栏的状态组合在小屏与标准宽度下不裁切、不覆盖操作。 +@MainActor +final class DroneMaterialsFooterLayoutTests: XCTestCase { + /// 选择、下载、暂停、失败、完成与权限状态在不同宽度下保持标题、说明和操作顺序。 + func testFooterStatesFitCompactAndRegularWidths() throws { + for width in [375.0, 402.0] { + let footer = DroneMaterialsFooterView() + for state in 0..<6 { + apply(state, to: footer) + layout(footer, width: width) + let primary = try XCTUnwrap(allViews(footer).first { + $0.accessibilityIdentifier == "footer.primary" + } as? UIButton) + XCTAssertGreaterThanOrEqual(primary.bounds.height, 44) + XCTAssertLessThanOrEqual(primary.convert(primary.bounds, to: footer).maxY, footer.bounds.maxY + 0.5) + for view in allViews(footer).filter({ !$0.isHidden && ($0.accessibilityIdentifier?.hasPrefix("drone.materials.footer.") == true || $0 is UIButton) && isVisible($0, within: footer) }) { + let rect = view.convert(view.bounds, to: footer) + XCTAssertGreaterThanOrEqual(rect.minX, -0.5) + XCTAssertLessThanOrEqual(rect.maxX, width + 0.5) + XCTAssertGreaterThan(view.bounds.height, 0) + } + let title = try XCTUnwrap(allViews(footer).first { $0.accessibilityIdentifier == "drone.materials.footer.title" }) + let trailing = try XCTUnwrap(allViews(footer).first { $0.accessibilityIdentifier == "drone.materials.footer.trailing" }) + if !trailing.isHidden { + XCTAssertLessThanOrEqual(title.convert(title.bounds, to: footer).maxX, + trailing.convert(trailing.bounds, to: footer).minX) + } + } + } + } + + /// 完成后回到选择状态不残留结果图标、交付按钮或旧进度;演示提示仍明确不写相册。 + func testCompletedFooterResetsCleanlyToSelection() throws { + let footer = DroneMaterialsFooterView() + apply(4, to: footer) + layout(footer, width: 375) + let delivery = try XCTUnwrap(allViews(footer).first { $0.accessibilityIdentifier == "drone.materials.completedDelivery" } as? UIButton) + XCTAssertFalse(delivery.isHidden) + XCTAssertEqual(delivery.layer.borderWidth, 1) + let detail = try XCTUnwrap(allViews(footer).first { $0.accessibilityIdentifier == "drone.materials.footer.detail" } as? UILabel) + XCTAssertTrue(detail.text?.contains("未写入系统相册") == true) + apply(0, to: footer) + layout(footer, width: 375) + XCTAssertTrue(delivery.isHidden) + XCTAssertEqual(delivery.layer.borderWidth, 0) + XCTAssertTrue(detail.isHidden) + let icon = try XCTUnwrap(allViews(footer).first { $0.accessibilityIdentifier == "drone.materials.footer.resultIcon" }) + XCTAssertTrue(icon.isHidden) + } + + private func apply(_ state: Int, to footer: DroneMaterialsFooterView) { + let titles = ["已选择2项", "本次下载2项", "下载已暂停", "部分素材下载失败", "本次素材下载完成(演示)", "无法保存到手机相册"] + let details = ["", "请保持本页开启,下载期间不可更改选择", "已完成项会保留;继续时仅处理未完成文件。", "演示成功1项 · 失败1项,已完成的无需重复下载", "2项演示完成,未写入系统相册", "演示相册权限未开启,恢复后请手动继续。"] + let symbols: [String?] = [nil, nil, "pause.circle", "exclamationmark.triangle", "checkmark.circle", "lock"] + footer.apply(title: titles[state], detail: details[state], primaryTitle: state == 3 ? "重试失败素材(1)" : "下载所选素材", + primarySymbol: "arrow.down.to.line", enabled: state != 1, identifier: "footer.primary", + progress: state == 1 || state == 2 ? 0.5 : nil, + secondaryTitle: state == 3 ? "选择其他素材" : state == 4 ? "交付成片" : nil, + tone: state == 4 ? .green : .orange, + trailingText: state == 0 ? "仅可选择已上传素材" : state == 1 || state == 2 ? "已完成1/2项" : nil, + resultSymbol: symbols[state], secondaryOutlined: state == 4) + } + + private func layout(_ footer: UIView, width: Double) { + let size = footer.systemLayoutSizeFitting(CGSize(width: width, height: 1), + withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel) + footer.frame = CGRect(origin: .zero, size: size) + footer.layoutIfNeeded() + } + + private func allViews(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap { allViews($0) } } + + private func isVisible(_ view: UIView, within root: UIView) -> Bool { + var ancestor = view.superview + while let current = ancestor, current !== root { + if current.isHidden { return false } + ancestor = current.superview + } + return true + } +} diff --git a/suixinkanTests/MockURLSession.swift b/suixinkanTests/MockURLSession.swift index 96faa88..aab0917 100644 --- a/suixinkanTests/MockURLSession.swift +++ b/suixinkanTests/MockURLSession.swift @@ -7,7 +7,7 @@ import Foundation @testable import suixinkan /// 按顺序返回预设响应的 URLSession 测试替身。 -final class MockURLSession: URLSessionProtocol { +final class MockURLSession: LocalSimulationURLSession { private(set) var requests: [URLRequest] = [] private var responses: [Result<(Data, URLResponse), Error>] private var responseIndex = 0 diff --git a/suixinkanTests/ScenicMaterialDatePickerOptionsTests.swift b/suixinkanTests/ScenicMaterialDatePickerOptionsTests.swift new file mode 100644 index 0000000..2ea6dca --- /dev/null +++ b/suixinkanTests/ScenicMaterialDatePickerOptionsTests.swift @@ -0,0 +1,90 @@ +import XCTest +@testable import suixinkan + +/// 验证两列日期滚轮只有保留期内的日期,跨年与月末不会生成越界值。 +final class ScenicMaterialDatePickerOptionsTests: XCTestCase { + /// 首尾月只保留允许的日号,所有选项都包含在闭区间内。 + func testPartialBoundaryMonthsContainOnlyRetainedDays() { + let options = makeOptions(from: date(2026, 7, 29), through: date(2026, 10, 26)) + XCTAssertEqual(options.months.map(\.number), [7, 8, 9, 10]) + XCTAssertEqual(options.months.map { $0.dates.count }, [3, 31, 30, 26]) + XCTAssertEqual(options.months.first?.dates.first, date(2026, 7, 29)) + XCTAssertEqual(options.months.last?.dates.last, date(2026, 10, 26)) + XCTAssertTrue(options.months.flatMap(\.dates).allSatisfy { options.minimumDate <= $0 && $0 <= options.maximumDate }) + XCTAssertEqual(options.date(inMonthAt: 0, preferredDay: 1), date(2026, 7, 29)) + XCTAssertEqual(options.date(inMonthAt: 3, preferredDay: 31), date(2026, 10, 26)) + } + + /// 12 月与次年 1 月属于不同年月,滚轮日号不会回到上一年。 + func testCrossYearMonthsPreserveYearAndChronologicalOrder() { + let options = makeOptions(from: date(2026, 11, 30), through: date(2027, 1, 5)) + XCTAssertEqual(options.months.map(\.year), [2026, 2026, 2027]) + XCTAssertEqual(options.months.map(\.number), [11, 12, 1]) + XCTAssertEqual(options.monthIndex(for: date(2027, 1, 1)), 2) + XCTAssertEqual(options.monthTitle(at: 2), "1月") + XCTAssertEqual(options.date(inMonthAt: 2, preferredDay: 31), date(2027, 1, 5)) + } + + /// 从 31 日切换到平年 2 月时落到 28 日,再切换长月可以正常选 31 日。 + func testShortMonthClampsDayWithoutOverflowingIntoMarch() { + let options = makeOptions(from: date(2026, 1, 1), through: date(2026, 3, 31)) + XCTAssertEqual(options.date(inMonthAt: 1, preferredDay: 31), date(2026, 2, 28)) + XCTAssertEqual(options.date(inMonthAt: 2, preferredDay: 31), date(2026, 3, 31)) + XCTAssertEqual(options.months[1].dates.count, 28) + } + + /// 闰年 2 月 29 日保留为有效选项,不硬编码每月天数。 + func testLeapDayIsSelectable() { + let options = makeOptions(from: date(2028, 1, 31), through: date(2028, 3, 1)) + XCTAssertEqual(options.months[1].dates.count, 29) + XCTAssertEqual(options.date(inMonthAt: 1, preferredDay: 31), date(2028, 2, 29)) + } + + /// 保留期外的传入日期收敛到最近边界,同时去除时分秒。 + func testExternalDatesClampToInclusiveDayBoundaries() { + let options = makeOptions(from: date(2026, 10, 1), through: date(2026, 10, 30)) + XCTAssertEqual(options.clamped(date(2026, 9, 30)), date(2026, 10, 1)) + XCTAssertEqual(options.clamped(date(2026, 10, 31)), date(2026, 10, 30)) + XCTAssertEqual(options.clamped(date(2026, 10, 15).addingTimeInterval(12 * 3600)), date(2026, 10, 15)) + } + + /// 非法倒置边界收敛成一天,滚轮仍有可选值。 + func testInvertedBoundsProduceOneValidDay() { + let options = makeOptions(from: date(2026, 10, 30), through: date(2026, 10, 1)) + XCTAssertEqual(options.months.flatMap(\.dates), [date(2026, 10, 30)]) + XCTAssertEqual(options.maximumDate, options.minimumDate) + } + + /// 长区间出现同名月份时显示年份,防止两条“1 月”无法区分。 + func testRepeatedMonthNamesIncludeYear() { + let options = makeOptions(from: date(2026, 1, 31), through: date(2027, 1, 1)) + XCTAssertEqual(options.monthTitle(at: 0), "2026年1月") + XCTAssertEqual(options.monthTitle(at: 12), "2027年1月") + XCTAssertEqual(options.monthTitle(at: 1), "2月") + } + + /// 夏令时切换不跳过日期,也不会生成非零点的日期选项。 + func testDayEnumerationUsesCalendarAcrossDaylightSavingTransition() throws { + var localCalendar = Calendar(identifier: .gregorian) + localCalendar.timeZone = try XCTUnwrap(TimeZone(identifier: "America/Los_Angeles")) + let start = try XCTUnwrap(localCalendar.date(from: DateComponents(year: 2026, month: 3, day: 7))) + let end = try XCTUnwrap(localCalendar.date(from: DateComponents(year: 2026, month: 3, day: 10))) + let options = ScenicMaterialDatePickerOptions(minimumDate: start, maximumDate: end, calendar: localCalendar) + XCTAssertEqual(options.months[0].dates.map { localCalendar.component(.day, from: $0) }, [7, 8, 9, 10]) + XCTAssertTrue(options.months[0].dates.allSatisfy { localCalendar.component(.hour, from: $0) == 0 }) + } + + private var calendar: Calendar { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(secondsFromGMT: 8 * 3600)! + return calendar + } + + private func date(_ year: Int, _ month: Int, _ day: Int) -> Date { + calendar.date(from: DateComponents(year: year, month: month, day: day))! + } + + private func makeOptions(from minimum: Date, through maximum: Date) -> ScenicMaterialDatePickerOptions { + ScenicMaterialDatePickerOptions(minimumDate: minimum, maximumDate: maximum, calendar: calendar) + } +} diff --git a/suixinkanTests/ScenicMaterialDownloadServiceTests.swift b/suixinkanTests/ScenicMaterialDownloadServiceTests.swift new file mode 100644 index 0000000..7fc5dc2 --- /dev/null +++ b/suixinkanTests/ScenicMaterialDownloadServiceTests.swift @@ -0,0 +1,212 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 真实空境下载的成功边界、取消竞态和临时文件清理,不访问系统相册或外网。 +@MainActor +final class ScenicMaterialDownloadServiceTests: XCTestCase { + /// 同一素材重复出现只下载保存一次,成功回执之后临时文件已清理。 + func testSuccessfulSaveDeduplicatesItemsAndCleansTemporaryFiles() async throws { + let downloader = ScenicDownloadStub() + let saver = ScenicPhotoSaveStub() + let service = ScenicMaterialDownloadService(downloader: downloader, photoSaver: saver) + let token = UUID() + let recorder = ScenicDownloadEventRecorder() + let item = makeItem() + + service.start(items: [item, item], batchID: token, onEvent: recorder.receive) + await service.waitForPendingOperations() + + XCTAssertEqual(recorder.completedTokens, [token]) + XCTAssertTrue(recorder.failedTokens.isEmpty) + let downloadCount = await downloader.calls + let saveCount = await saver.calls + XCTAssertEqual(downloadCount, 1) + XCTAssertEqual(saveCount, 1) + let files = await downloader.files + XCTAssertEqual(files.count, 1) + XCTAssertFalse(FileManager.default.fileExists(atPath: try XCTUnwrap(files.first).path)) + } + + /// 下载失败不会提交相册事务或产生成功事件。 + func testDownloadFailureDoesNotSaveOrComplete() async { + let downloader = ScenicDownloadStub(failure: .httpFailure(403)) + let saver = ScenicPhotoSaveStub() + let service = ScenicMaterialDownloadService(downloader: downloader, photoSaver: saver) + let token = UUID() + let recorder = ScenicDownloadEventRecorder() + + service.start(items: [makeItem()], batchID: token, onEvent: recorder.receive) + await service.waitForPendingOperations() + + XCTAssertEqual(recorder.failedTokens, [token]) + XCTAssertTrue(recorder.completedTokens.isEmpty) + let count = await saver.calls + XCTAssertEqual(count, 0) + } + + /// 相册拒绝或保存失败只产生失败回执,同时删除已经下载的临时文件。 + func testPhotoPermissionFailureCleansDownloadWithoutCompleting() async throws { + let downloader = ScenicDownloadStub() + let saver = ScenicPhotoSaveStub(failure: true) + let service = ScenicMaterialDownloadService(downloader: downloader, photoSaver: saver) + let token = UUID() + let recorder = ScenicDownloadEventRecorder() + + service.start(items: [makeItem()], batchID: token, onEvent: recorder.receive) + await service.waitForPendingOperations() + + XCTAssertEqual(recorder.failedTokens, [token]) + XCTAssertTrue(recorder.completedTokens.isEmpty) + let files = await downloader.files + XCTAssertFalse(FileManager.default.fileExists(atPath: try XCTUnwrap(files.first).path)) + } + + /// 已提交的 Photos 事务在暂停后成功,继续时只同步成功事实,不再次下载或保存。 + func testResumeWaitsForUncancellableSaveAndAvoidsDuplicateAsset() async { + let downloader = ScenicDownloadStub() + let saver = ScenicPhotoSaveStub(isSuspended: true) + let service = ScenicMaterialDownloadService(downloader: downloader, photoSaver: saver) + let oldToken = UUID() + let newToken = UUID() + let recorder = ScenicDownloadEventRecorder() + let item = makeItem() + service.start(items: [item], batchID: oldToken, onEvent: recorder.receive) + await saver.waitForSaveStart() + + service.stop() + service.start(items: [item], batchID: newToken, onEvent: recorder.receive) + await saver.finishSave() + await service.waitForPendingOperations() + + XCTAssertEqual(recorder.completedTokens, [newToken]) + XCTAssertTrue(recorder.failedTokens.isEmpty) + let saveCount = await saver.calls + let downloadCount = await downloader.calls + XCTAssertEqual(saveCount, 1) + XCTAssertEqual(downloadCount, 1) + } + + /// 即使下载器取消后仍返回文件,服务也会清理文件并拒绝旧回执及相册保存。 + func testCancelledDownloadDoesNotSaveLateFileOrPublishOldReceipt() async throws { + let downloader = ScenicDownloadStub(isSuspended: true) + let saver = ScenicPhotoSaveStub() + let service = ScenicMaterialDownloadService(downloader: downloader, photoSaver: saver) + let recorder = ScenicDownloadEventRecorder() + service.start(items: [makeItem()], batchID: UUID(), onEvent: recorder.receive) + await downloader.waitForDownloadStart() + + service.stop() + await downloader.finishDownload() + await service.waitForPendingOperations() + + XCTAssertTrue(recorder.completedTokens.isEmpty) + XCTAssertTrue(recorder.failedTokens.isEmpty) + let saveCount = await saver.calls + XCTAssertEqual(saveCount, 0) + let files = await downloader.files + XCTAssertFalse(FileManager.default.fileExists(atPath: try XCTUnwrap(files.first).path)) + } + + /// 原片 URL 仅允许 HTTP(S),不读取本地路径或执行非下载协议。 + func testDownloaderRejectsNonHTTPURL() async { + do { + _ = try await ScenicMaterialURLSessionDownloader().downloadFile(remoteURL: "file:///tmp/video.mp4", + fileName: "video.mp4", onProgress: { _ in }) + XCTFail("本地文件不能当作远程素材地址") + } catch { + XCTAssertEqual(error as? ScenicMaterialDownloadError, .invalidURL) + } + } + + private func makeItem() -> ScenicMaterialDownloadItem { + ScenicMaterialDownloadItem(id: "session-1/material-2", remoteURL: URL(string: "https://example.com/video.mp4")!) + } +} + +/// 主线程事件收集器,只记录终态,便于检验过期批次不会回写 UI。 +@MainActor +private final class ScenicDownloadEventRecorder { + private(set) var completedTokens: [UUID] = [] + private(set) var failedTokens: [UUID] = [] + + func receive(_ id: String, _ token: UUID, _ event: ScenicMaterialTransferEvent) { + switch event { + case .completed: completedTokens.append(token) + case .failed: failedTokens.append(token) + case .progress: break + } + } +} + +/// 下载替身可模拟错误与忽略取消的迟到响应,用独立临时文件验证清理。 +private actor ScenicDownloadStub: CloudFileDownloading { + private let failure: ScenicMaterialDownloadError? + private let isSuspended: Bool + private var continuation: CheckedContinuation? + private var startWaiter: CheckedContinuation? + private(set) var calls = 0 + private(set) var files: [URL] = [] + + init(failure: ScenicMaterialDownloadError? = nil, isSuspended: Bool = false) { + self.failure = failure + self.isSuspended = isSuspended + } + + func downloadFile(remoteURL: String, fileName: String, onProgress: @escaping @Sendable (Int) -> Void) async throws -> URL { + calls += 1 + if let failure { throw failure } + if isSuspended { + await withCheckedContinuation { continuation in + self.continuation = continuation + self.startWaiter?.resume() + self.startWaiter = nil + } + } + let file = FileManager.default.temporaryDirectory.appendingPathComponent("scenic-test-\(UUID().uuidString).mp4") + try Data("test-video".utf8).write(to: file) + files.append(file) + onProgress(100) + return file + } + + func waitForDownloadStart() async { + if continuation != nil { return } + await withCheckedContinuation { startWaiter = $0 } + } + + func finishDownload() { continuation?.resume(); continuation = nil } +} + +/// 模拟 Photos 不可取消的提交窗口,支持授权拒绝和手动完成保存。 +private actor ScenicPhotoSaveStub: CloudPhotoSaving { + private let failure: Bool + private let isSuspended: Bool + private var continuation: CheckedContinuation? + private var startWaiter: CheckedContinuation? + private(set) var calls = 0 + + init(failure: Bool = false, isSuspended: Bool = false) { + self.failure = failure + self.isSuspended = isSuspended + } + + func saveToPhotoLibrary(fileURL: URL, fileType: Int) async throws { + calls += 1 + if failure { throw CloudTransferError.photoPermissionDenied } + if isSuspended { + await withCheckedContinuation { continuation in + self.continuation = continuation + self.startWaiter?.resume() + self.startWaiter = nil + } + } + } + + func waitForSaveStart() async { + if continuation != nil { return } + await withCheckedContinuation { startWaiter = $0 } + } + + func finishSave() { continuation?.resume(); continuation = nil } +} diff --git a/suixinkanTests/ScenicMaterialPreviewPlaybackTests.swift b/suixinkanTests/ScenicMaterialPreviewPlaybackTests.swift new file mode 100644 index 0000000..91dadd6 --- /dev/null +++ b/suixinkanTests/ScenicMaterialPreviewPlaybackTests.swift @@ -0,0 +1,75 @@ +import AVKit +import UIKit +import XCTest +@testable import suixinkan + +/// 使用包内短片验证预览进度来自真实播放器,并在暂停和关闭时停止推进。 +@MainActor +final class ScenicMaterialPreviewPlaybackTests: XCTestCase { + /// 本地演示的实际 3 秒时长不能伪装为素材元信息的 28 秒,关闭后也不能继续回调进度。 + func testDemoProgressUsesAssetDurationAndStopsAfterClosing() async throws { + let clip = ScenicMaterialClip(id: "preview:1", groupID: "preview", ordinal: 1, + durationSeconds: 28, fileSizeBytes: 178_000_000, resolution: "4K", + coverAssetName: "drone_demo_mountain") + let controller = ScenicMaterialPreviewViewController(clip: clip, routeName: "测试航线", + capturedAt: Date(timeIntervalSince1970: 1_700_000_000)) + let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first + let previousKeyWindow = scene?.windows.first { $0.isKeyWindow } + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + window.rootViewController = controller + window.makeKeyAndVisible() + window.layoutIfNeeded() + defer { + controller.viewWillDisappear(false) + controller.viewDidDisappear(false) + window.isHidden = true + window.rootViewController = nil + previousKeyWindow?.makeKeyAndVisible() + } + let play = try XCTUnwrap(find(in: controller.view, identifier: "scenic.materials.preview.play") as? UIButton) + let progress = try XCTUnwrap(find(in: controller.view, identifier: "scenic.materials.preview.progress") as? UIProgressView) + let time = try XCTUnwrap(find(in: controller.view, identifier: "scenic.materials.preview.playbackTime") as? UILabel) + let playerController = try XCTUnwrap(controller.children.compactMap { $0 as? AVPlayerViewController }.first) + XCTAssertEqual(time.text, "00:00 / 原片 00:28") + + play.sendActions(for: .touchUpInside) + try await waitUntil { progress.progress > 0.05 } + let player = try XCTUnwrap(playerController.player) + XCTAssertTrue(time.text?.hasSuffix(" / 00:03") == true) + XCTAssertFalse(time.text?.contains("00:28") == true) + + play.sendActions(for: .touchUpInside) + XCTAssertEqual(player.rate, 0) + try await Task.sleep(nanoseconds: 150_000_000) + let pausedProgress = progress.progress + try await Task.sleep(nanoseconds: 200_000_000) + XCTAssertEqual(progress.progress, pausedProgress, accuracy: 0.02) + + play.sendActions(for: .touchUpInside) + XCTAssertTrue(playerController.player === player) + try await waitUntil { progress.progress > pausedProgress + 0.04 } + + let done = try XCTUnwrap(find(in: controller.view, identifier: "scenic.materials.preview.done") as? UIButton) + done.sendActions(for: .touchUpInside) + XCTAssertNil(playerController.player) + XCTAssertEqual(player.rate, 0) + XCTAssertEqual(progress.progress, 0) + try await Task.sleep(nanoseconds: 250_000_000) + XCTAssertEqual(progress.progress, 0) + XCTAssertEqual(time.text, "00:00 / 原片 00:28") + } + + private func waitUntil(_ condition: () -> Bool) async throws { + let deadline = Date().addingTimeInterval(4) + while Date() < deadline { + if condition() { return } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTFail("本地预览播放器未在限定时间内推进") + } + + private func find(in root: UIView, identifier: String) -> UIView? { + if root.accessibilityIdentifier == identifier { return root } + return root.subviews.lazy.compactMap { self.find(in: $0, identifier: identifier) }.first + } +} diff --git a/suixinkanTests/ScenicMaterialRemotePreviewTests.swift b/suixinkanTests/ScenicMaterialRemotePreviewTests.swift new file mode 100644 index 0000000..c6ffdf7 --- /dev/null +++ b/suixinkanTests/ScenicMaterialRemotePreviewTests.swift @@ -0,0 +1,84 @@ +import AVKit +import UIKit +import XCTest +@testable import suixinkan + +/// 验证正式空境预览使用真实素材说明,且缺失地址时不会播放包内演示文件。 +@MainActor +final class ScenicMaterialRemotePreviewTests: XCTestCase { + /// 仅构造预览界面,不点击远程播放,也不提供封面地址以避免测试联网。 + func testRemotePreviewShowsOriginalVideoInstructionsAndMetadata() throws { + let clip = makeClip(remoteURL: URL(string: "https://example.invalid/original.mp4")) + let controller = makePreview(clip) + + XCTAssertTrue(labels(in: controller.view).contains { $0.text == "点击播放原片" }) + XCTAssertFalse(labels(in: controller.view).contains { $0.text?.contains("本地演示") == true }) + let play = try XCTUnwrap(view(in: controller.view, identifier: "scenic.materials.preview.play") as? UIButton) + XCTAssertEqual(play.accessibilityLabel, "播放景区视频") + let metadata = try XCTUnwrap(view(in: controller.view, identifier: "scenic.materials.preview.metadata") as? UILabel) + let playbackTime = try XCTUnwrap(view(in: controller.view, identifier: "scenic.materials.preview.playbackTime") as? UILabel) + XCTAssertEqual(playbackTime.text, "00:00 / 01:05") + XCTAssertTrue(metadata.text?.contains("1920×1080") == true) + XCTAssertTrue(metadata.text?.contains("12MB") == true) + let route = try XCTUnwrap(view(in: controller.view, identifier: "scenic.materials.preview.route") as? UILabel) + XCTAssertEqual(route.text, "测试景区航线") + XCTAssertNil(controller.children.compactMap { $0 as? AVPlayerViewController }.first?.player) + } + + /// 即便片段标为可用且演示文件存在,正式片段地址缺失也只显示可重试提示。 + func testMissingRemoteAddressDoesNotFallBackToBundledDemoVideo() throws { + let controller = makePreview(makeClip(remoteURL: nil)) + let play = try XCTUnwrap(view(in: controller.view, identifier: "scenic.materials.preview.play") as? UIButton) + + play.sendActions(for: .touchUpInside) + + XCTAssertTrue(labels(in: controller.view).contains { $0.text == "视频地址暂不可用" }) + XCTAssertTrue(play.isEnabled) + XCTAssertFalse(play.isHidden) + XCTAssertNil(controller.children.compactMap { $0 as? AVPlayerViewController }.first?.player) + XCTAssertFalse(labels(in: controller.view).contains { $0.text?.contains("本地演示") == true }) + } + + /// 缺失元信息以未知展示,不能用 0 秒或 0 MB 暗示已知的空文件。 + func testUnknownMetadataIsNotPresentedAsZero() throws { + let clip = ScenicMaterialClip(id: "session-1:media-2", groupID: "session-1", ordinal: 2, + durationSeconds: -1, fileSizeBytes: -1, resolution: "分辨率未知", + coverAssetName: "", isAvailable: false, isRemote: true) + let controller = makePreview(clip) + let metadata = try XCTUnwrap(view(in: controller.view, identifier: "scenic.materials.preview.metadata") as? UILabel) + let playbackTime = try XCTUnwrap(view(in: controller.view, identifier: "scenic.materials.preview.playbackTime") as? UILabel) + + XCTAssertEqual(clip.durationText, "时长未知") + XCTAssertEqual(clip.sizeText, "大小未知") + XCTAssertEqual(playbackTime.text, "00:00 / 时长未知") + XCTAssertTrue(metadata.text?.contains("大小未知") == true) + XCTAssertFalse(metadata.text?.contains("00:00") == true) + XCTAssertFalse(metadata.text?.contains("0MB") == true) + } + + /// 创建不含封面网络请求的正式片段,测试仅检查界面及缺失地址分支。 + private func makeClip(remoteURL: URL?) -> ScenicMaterialClip { + ScenicMaterialClip(id: "session-1:media-1", groupID: "session-1", ordinal: 1, + durationSeconds: 65, fileSizeBytes: 12_000_000, + resolution: "1920×1080", coverAssetName: "drone_demo_mountain", + isAvailable: true, remoteURL: remoteURL, coverURL: nil, + fileLabel: "本次素材01", isRemote: true) + } + + /// 直接加载 UIKit 视图,测试无需登录账号、可见窗口或系统相册。 + private func makePreview(_ clip: ScenicMaterialClip) -> ScenicMaterialPreviewViewController { + let controller = ScenicMaterialPreviewViewController(clip: clip, routeName: "测试景区航线", + capturedAt: Date(timeIntervalSince1970: 1_700_000_000)) + controller.loadViewIfNeeded() + return controller + } + + private func view(in root: UIView, identifier: String) -> UIView? { + if root.accessibilityIdentifier == identifier { return root } + return root.subviews.lazy.compactMap { self.view(in: $0, identifier: identifier) }.first + } + + private func labels(in root: UIView) -> [UILabel] { + (root as? UILabel).map { [$0] } ?? root.subviews.flatMap { labels(in: $0) } + } +} diff --git a/suixinkanTests/ScenicMaterialsAPITests.swift b/suixinkanTests/ScenicMaterialsAPITests.swift new file mode 100644 index 0000000..eac4d31 --- /dev/null +++ b/suixinkanTests/ScenicMaterialsAPITests.swift @@ -0,0 +1,166 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 验证景区空境库请求按文档携带分页与筛选范围,不使用订单素材身份。 +@MainActor +final class ScenicMaterialsAPITests: XCTestCase { + /// 部署接口返回 100000/msg,沿用 token 头,并保留空库和服务端保留期提示。 + func testSessionsUsesObservedEnvelopeAndExactReadOnlyParameters() async throws { + let session = MockURLSession(responses: [Self.emptyResponse]) + let client = APIClient(environment: .testing, session: session) + client.bindAuthTokenProvider { "scenic-library-test-token" } + let response = try await ScenicMaterialsAPI(client: client).sessions(query: ScenicMaterialsQuery(scenicID: 271)) + let request = try XCTUnwrap(session.requests.first) + XCTAssertEqual(request.httpMethod, "GET") + XCTAssertEqual(request.url?.path, "/api/app/scenic-media/sessions") + XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "scenic-library-test-token") + XCTAssertNil(request.httpBody) + XCTAssertEqual(try requestQuery(request), ["scenic_id": "271", "page": "1", "page_size": "20", "retention_days": "90"]) + XCTAssertEqual(response.total, 0) + XCTAssertTrue(response.list.isEmpty) + XCTAssertTrue(response.groups.isEmpty) + XCTAssertTrue(response.airLines.isEmpty) + XCTAssertEqual(response.retentionTips, "素材保留 90 天,请及时下载") + } + + /// 场次详情只使用 scenic_media_id,原素材字段按实际 JSON 类型保留。 + func testSessionDetailUsesOnlyScenicMediaIDAndPreservesMaterialFields() async throws { + let payload = Data(#"{"code":100000,"msg":"success","data":{"materials":[{"file_label":"片段一","selectable":true,"oss_url":"https://example.com/clip.mp4?signature=scenic-signed-url-do-not-log"}]}}"#.utf8) + let session = MockURLSession(responses: [payload]) + let response = try await ScenicMaterialsAPI(client: APIClient(environment: .testing, session: session)) + .sessionDetail(scenicMediaID: 501) + let request = try XCTUnwrap(session.requests.first) + XCTAssertEqual(request.httpMethod, "GET") + XCTAssertEqual(request.url?.path, "/api/app/scenic-media/session-detail") + XCTAssertEqual(try requestQuery(request), ["scenic_media_id": "501"]) + XCTAssertNil(request.httpBody) + XCTAssertEqual(response.materials.first?["file_label"], .string("片段一")) + XCTAssertEqual(response.materials.first?["selectable"], .bool(true)) + XCTAssertEqual(response.materials.first?["oss_url"], .string("https://example.com/clip.mp4?signature=scenic-signed-url-do-not-log")) + } + + /// 后端账号或景区拒绝必须显示为错误,不能当作真实空库。 + func testBusinessErrorsArePreserved() async throws { + let payload = Data(#"{"code":100099,"msg":"请使用门店账号登录","data":[]}"#.utf8) + let session = MockURLSession(responses: [payload]) + do { + _ = try await ScenicMaterialsAPI(client: APIClient(environment: .testing, session: session)) + .sessions(query: ScenicMaterialsQuery(scenicID: 271)) + XCTFail("账号权限错误不能转为空库") + } catch let APIError.serverCode(code, message) { + XCTAssertEqual(code, 100099) + XCTAssertEqual(message, "请使用门店账号登录") + } + } + + /// 文档的 code=0 示例不是部署接口成功码,不能悄悄改变全局鉴权和响应规则。 + func testUndeployedZeroSuccessCodeIsRejected() async throws { + let payload = Data(#"{"code":0,"message":"success","data":{"materials":[]}}"#.utf8) + let session = MockURLSession(responses: [payload]) + do { + _ = try await ScenicMaterialsAPI(client: APIClient(environment: .testing, session: session)).sessionDetail(scenicMediaID: 501) + XCTFail("应保持部署接口的成功码语义") + } catch let APIError.serverCode(code, _) { + XCTAssertEqual(code, 0) + } + } + + /// 请求校验在网络之前执行,场次身份不接受 0 或负值。 + func testInvalidRequestsDoNotReachNetwork() async { + let session = MockURLSession(responses: []) + let api = ScenicMaterialsAPI(client: APIClient(environment: .testing, session: session)) + do { + _ = try await api.sessions(query: ScenicMaterialsQuery(scenicID: 0)) + XCTFail("非法景区不应请求网络") + } catch {} + for id in [0, -1] { + do { _ = try await api.sessionDetail(scenicMediaID: id); XCTFail("非法场次不应请求网络") } + catch {} + } + XCTAssertTrue(session.requests.isEmpty) + } + + /// 缺失或错误数组不得伪装成空列表;详情要求材料对象数组。 + func testMalformedContainersAreRejected() throws { + var root = try XCTUnwrap(JSONSerialization.jsonObject(with: Self.emptyResponse) as? [String: Any]) + let original = try XCTUnwrap(root["data"] as? [String: Any]) + for key in ["list", "groups", "filter_options"] { + var payload = original + payload.removeValue(forKey: key) + root["data"] = payload + XCTAssertThrowsError(try JSONDecoder().decode(APIEnvelope.self, + from: JSONSerialization.data(withJSONObject: root))) + } + for payload in [#"{}"#, #"{"materials":null}"#, #"{"materials":[1]}"#] { + XCTAssertThrowsError(try JSONDecoder().decode(ScenicMaterialsSessionDetailResponse.self, from: Data(payload.utf8))) + } + } + + /// 返回其他页或筛选的响应不能混入当前页面。 + func testMismatchedResponsePageAndFiltersAreRejected() async { + for query in [ScenicMaterialsQuery(scenicID: 271, page: 2), ScenicMaterialsQuery(scenicID: 271, airLineID: 123), + ScenicMaterialsQuery(scenicID: 271, dateFrom: "2026-10-01"), ScenicMaterialsQuery(scenicID: 271, retentionDays: 30)] { + let session = MockURLSession(responses: [Self.emptyResponse]) + do { + _ = try await ScenicMaterialsAPI(client: APIClient(environment: .testing, session: session)).sessions(query: query) + XCTFail("响应条件必须与请求一致") + } catch let error as APIError { + guard case .decodeFailed = error else { return XCTFail("应拒绝响应范围不一致") } + } catch { XCTFail("应使用统一接口错误") } + } + } + + /// 默认请求显式传递分页和 90 天窗口,全部筛选省略可选参数。 + func testDefaultQueryContainsOnlyDocumentedScopeAndPagination() throws { + let query = ScenicMaterialsQuery(scenicID: 271) + XCTAssertEqual(try values(query), ["scenic_id": "271", "page": "1", "page_size": "20", "retention_days": "90"]) + } + + /// 航线和日期均作为服务端查询参数发送;翻页保留原筛选。 + func testFilteredQueryKeepsDateRangeAndAirLineWhenPaginating() throws { + let query = ScenicMaterialsQuery(scenicID: 271, page: 2, pageSize: 100, airLineID: 123, + dateFrom: "2026-10-01", dateTo: "2026-10-29", retentionDays: 30) + XCTAssertEqual(try values(query), ["scenic_id": "271", "page": "2", "page_size": "100", "retention_days": "30", + "air_line_id": "123", "date_from": "2026-10-01", "date_to": "2026-10-29"]) + } + + /// 无效分页、身份和日期不能发出请求,日期不自动修正为其他日期。 + func testInvalidScopePaginationAndDatesAreRejected() { + let invalid = [ + ScenicMaterialsQuery(scenicID: 0), + ScenicMaterialsQuery(scenicID: 271, page: 0), + ScenicMaterialsQuery(scenicID: 271, pageSize: 0), + ScenicMaterialsQuery(scenicID: 271, pageSize: 101), + ScenicMaterialsQuery(scenicID: 271, airLineID: 0), + ScenicMaterialsQuery(scenicID: 271, retentionDays: 0), + ScenicMaterialsQuery(scenicID: 271, retentionDays: 366), + ScenicMaterialsQuery(scenicID: 271, dateFrom: "2026-02-30"), + ScenicMaterialsQuery(scenicID: 271, dateTo: "2026-1-1"), + ScenicMaterialsQuery(scenicID: 271, dateFrom: ""), + ScenicMaterialsQuery(scenicID: 271, dateFrom: "2026-10-30", dateTo: "2026-10-29"), + ] + for query in invalid { XCTAssertThrowsError(try query.queryItems()) } + } + + /// 文档允许起止字段分别可选,单端日期不能被客户端抛弃。 + func testSingleDateEndpointIsPreserved() throws { + XCTAssertEqual(try values(ScenicMaterialsQuery(scenicID: 271, dateFrom: "2024-02-29"))["date_from"], "2024-02-29") + XCTAssertEqual(try values(ScenicMaterialsQuery(scenicID: 271, dateTo: "2026-10-29"))["date_to"], "2026-10-29") + } + + /// 转为键值表检查完整参数集合,避免额外订单或任务参数混入。 + private func values(_ query: ScenicMaterialsQuery) throws -> [String: String] { + Dictionary(uniqueKeysWithValues: try query.queryItems().map { ($0.name, $0.value ?? "") }) + } + + /// 从请求检查完整查询字段。 + private func requestQuery(_ request: URLRequest) throws -> [String: String] { + let url = try XCTUnwrap(request.url) + let items = try XCTUnwrap(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems) + return Dictionary(uniqueKeysWithValues: items.map { ($0.name, $0.value ?? "") }) + } + + /// 依据 2026-10-29 当前景区部署接口的实际空库响应。 + private static let emptyResponse = Data(#"{"code":100000,"msg":"success","data":{"list":[],"groups":[],"total":0,"page":1,"page_size":20,"retention_days":90,"retention_tips":"素材保留 90 天,请及时下载","filter":{"air_line_id":0,"date_from":"","date_to":""},"filter_options":{"air_lines":[]}}}"#.utf8) +} diff --git a/suixinkanTests/ScenicMaterialsFlowViewTests.swift b/suixinkanTests/ScenicMaterialsFlowViewTests.swift index 9c5c198..7518681 100644 --- a/suixinkanTests/ScenicMaterialsFlowViewTests.swift +++ b/suixinkanTests/ScenicMaterialsFlowViewTests.swift @@ -3,7 +3,7 @@ import XCTest @testable import suixinkan #if DEBUG -/// 在真机隔离窗口验证独立空镜库的布局、筛选、预览与本地下载流程。 +/// 在隔离窗口验证独立空镜库的布局、筛选、预览与本地下载流程。 @MainActor final class ScenicMaterialsFlowViewTests: XCTestCase { private weak var previousKeyWindow: UIWindow? @@ -109,21 +109,20 @@ final class ScenicMaterialsFlowViewTests: XCTestCase { try button(in: controller.view, identifier: "scenic.materials.dateFilter").sendActions(for: .touchUpInside) try await settle(window) { self.isPresentationSettled(controller, type: ScenicMaterialDateFilterViewController.self) } let dateSheet = try XCTUnwrap(controller.presentedViewController as? ScenicMaterialDateFilterViewController) - let picker = try XCTUnwrap(find(in: dateSheet.view, identifier: "scenic.materials.date.picker") as? UIDatePicker) + let picker = try XCTUnwrap(find(in: dateSheet.view, identifier: "scenic.materials.date.picker") as? UIPickerView) + XCTAssertEqual(picker.numberOfComponents, 2, "日期筛选只展示月、日两列") let start = try button(in: dateSheet.view, identifier: "scenic.materials.date.start") assertReachable(start, window: window) start.sendActions(for: .touchUpInside) - picker.setDate(day, animated: false) - picker.sendActions(for: .valueChanged) + try selectDate(day, in: picker, minimumDate: model.minimumDate, calendar: model.calendar) let end = try button(in: dateSheet.view, identifier: "scenic.materials.date.end") end.sendActions(for: .touchUpInside) - picker.setDate(day, animated: false) - picker.sendActions(for: .valueChanged) + try selectDate(day, in: picker, minimumDate: model.minimumDate, calendar: model.calendar) let formatter = DateFormatter() formatter.calendar = model.calendar formatter.timeZone = model.calendar.timeZone formatter.locale = Locale(identifier: "zh_CN") - formatter.dateFormat = "M 月 d 日" + formatter.dateFormat = "M月d日" let selectedDay = formatter.string(from: day) try await settle(window) { self.visibleLabel(in: start, text: "开始日期") != nil && self.visibleLabel(in: start, text: selectedDay) != nil @@ -153,6 +152,38 @@ final class ScenicMaterialsFlowViewTests: XCTestCase { capture(window, named: "空镜库-日期筛选结果") } + /// 月日滚轮编辑与全部时间都是草稿;取消不提交,确定才清除已有日期筛选。 + func testDateDraftCancellationAndAllDatesRequireConfirmation() async throws { + let controller = ScenicMaterialsViewController() + let window = makeWindow(root: controller) + defer { close(window) } + let model = controller.viewModel + _ = try await waitForLibrary(controller, window: window) + let day = try XCTUnwrap(model.filteredGroups.first?.capturedAt) + XCTAssertTrue(model.setDateRange(start: day, end: day)) + let originalRange = model.dateRange + controller.refreshDisplay(animated: false) + + try button(in: controller.view, identifier: "scenic.materials.dateFilter").sendActions(for: .touchUpInside) + try await settle(window) { self.isPresentationSettled(controller, type: ScenicMaterialDateFilterViewController.self) } + let cancelledSheet = try XCTUnwrap(controller.presentedViewController as? ScenicMaterialDateFilterViewController) + let picker = try XCTUnwrap(find(in: cancelledSheet.view, identifier: "scenic.materials.date.picker") as? UIPickerView) + try selectDate(model.minimumDate, in: picker, minimumDate: model.minimumDate, calendar: model.calendar) + XCTAssertEqual(model.dateRange, originalRange) + try button(in: cancelledSheet.view, identifier: "scenic.materials.date.cancel").sendActions(for: .touchUpInside) + try await settle(window) { controller.presentedViewController == nil } + XCTAssertEqual(model.dateRange, originalRange) + + try button(in: controller.view, identifier: "scenic.materials.dateFilter").sendActions(for: .touchUpInside) + try await settle(window) { self.isPresentationSettled(controller, type: ScenicMaterialDateFilterViewController.self) } + let allDatesSheet = try XCTUnwrap(controller.presentedViewController as? ScenicMaterialDateFilterViewController) + try button(in: allDatesSheet.view, identifier: "scenic.materials.date.all").sendActions(for: .touchUpInside) + XCTAssertEqual(model.dateRange, originalRange) + try button(in: allDatesSheet.view, identifier: "scenic.materials.date.confirm").sendActions(for: .touchUpInside) + try await settle(window) { controller.presentedViewController == nil && model.dateRange == nil } + XCTAssertEqual(model.dateFilterTitle, "全部时间") + } + /// 预览从真实卡片打开并关闭,暂停中的选择和下载批次不受 Sheet 生命周期影响。 func testPreviewOpenAndClosePreservesPausedBatchAndSelection() async throws { let model = ScenicMaterialsViewModel() @@ -180,7 +211,7 @@ final class ScenicMaterialsFlowViewTests: XCTestCase { } XCTAssertEqual(model.batchID, token) XCTAssertEqual(model.phase, .paused) - let closeButton = try button(in: sheet.view, identifier: "scenic.materials.preview.close") + let closeButton = try button(in: sheet.view, identifier: "scenic.materials.preview.done") assertReachable(closeButton, window: window) closeButton.sendActions(for: .touchUpInside) try await settle(window) { controller.presentedViewController == nil && controller.navigationController?.transitionCoordinator == nil } @@ -321,6 +352,21 @@ final class ScenicMaterialsFlowViewTests: XCTestCase { return window } + /// 通过两列滚轮的真实 delegate 路径选择日期,覆盖月份重载和按日提交。 + private func selectDate(_ date: Date, in picker: UIPickerView, minimumDate: Date, calendar: Calendar) throws { + let firstMonth = try XCTUnwrap(calendar.dateInterval(of: .month, for: minimumDate)?.start) + let desiredMonth = try XCTUnwrap(calendar.dateInterval(of: .month, for: date)?.start) + let monthRow = try XCTUnwrap(calendar.dateComponents([.month], from: firstMonth, to: desiredMonth).month) + picker.selectRow(monthRow, inComponent: 0, animated: false) + picker.delegate?.pickerView?(picker, didSelectRow: monthRow, inComponent: 0) + let firstDay = monthRow == 0 ? calendar.component(.day, from: minimumDate) : 1 + let dayRow = calendar.component(.day, from: date) - firstDay + XCTAssertGreaterThanOrEqual(dayRow, 0) + XCTAssertLessThan(dayRow, picker.numberOfRows(inComponent: 1)) + picker.selectRow(dayRow, inComponent: 1, animated: false) + picker.delegate?.pickerView?(picker, didSelectRow: dayRow, inComponent: 1) + } + private func close(_ window: UIWindow) { NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil) window.endEditing(true) @@ -402,7 +448,7 @@ final class ScenicMaterialsFlowViewTests: XCTestCase { XCTAssertTrue(ambiguous.isEmpty, "布局歧义:\(ambiguous.map { String(describing: type(of: $0)) + " " + ($0.accessibilityIdentifier ?? "") })", file: file, line: line) } - /// 真机截图保存在 xcresult 及应用临时目录,便于导出视觉证据。 + /// 截图保存在 xcresult 及应用临时目录,便于导出视觉证据。 private func capture(_ window: UIWindow, named name: String) { window.layoutIfNeeded() let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in diff --git a/suixinkanTests/ScenicMaterialsFooterLayoutTests.swift b/suixinkanTests/ScenicMaterialsFooterLayoutTests.swift new file mode 100644 index 0000000..822015c --- /dev/null +++ b/suixinkanTests/ScenicMaterialsFooterLayoutTests.swift @@ -0,0 +1,254 @@ +import UIKit +import XCTest +@testable import suixinkan + +/// 验证景区素材下载底栏在窄屏及状态切换后仍能完整展示摘要并正确响应操作。 +@MainActor +final class ScenicMaterialsFooterLayoutTests: XCTestCase { + /// 选择、下载、暂停、失败和完成状态均不裁切文字、进度或操作按钮。 + func testFooterStatesFitCompactAndRegularWidths() throws { + for width in [320.0, 375.0, 393.0] { + let footer = ScenicMaterialsFooterView() + for state in 0..<6 { + apply(state, to: footer) + layout(footer, width: width) + XCTAssertGreaterThan(footer.bounds.height, 0) + let primary: UIButton = try control("scenic.materials.primary", in: footer) + XCTAssertGreaterThanOrEqual(primary.bounds.height, 44) + try assertCompleteSingleLineTitle(primary) + let visibleControls = allViews(footer).filter { + ($0.accessibilityIdentifier?.hasPrefix("scenic.materials.") == true) && isVisible($0, within: footer) + } + for view in visibleControls { + let rect = view.convert(view.bounds, to: footer) + XCTAssertGreaterThan(rect.width, 0, "状态 \(state):\(view.accessibilityIdentifier ?? "") 无宽度") + XCTAssertGreaterThan(rect.height, 0) + XCTAssertGreaterThanOrEqual(rect.minX, -0.5) + XCTAssertGreaterThanOrEqual(rect.minY, -0.5) + XCTAssertLessThanOrEqual(rect.maxX, width + 0.5) + XCTAssertLessThanOrEqual(rect.maxY, footer.bounds.maxY + 0.5) + if let label = view as? UILabel, !(label.text ?? "").isEmpty { + let needed = label.sizeThatFits(CGSize(width: label.bounds.width, height: .greatestFiniteMagnitude)) + XCTAssertLessThanOrEqual(needed.height, label.bounds.height + 1, "状态 \(state):文字被裁切") + } + if let button = view as? UIButton { try assertCompleteSingleLineTitle(button) } + } + } + } + } + + /// 真正挂载窗口后,初始完成态及从选择态切入完成态都显示完整按钮文字,防止内部标题被约束挤成窄列。 + func testButtonTitlesStayReadableInWindowAcrossInitialAndTransitionedStates() async throws { + for width in [320.0, 375.0, 393.0] { + for states in [[5], [0, 5], [1, 2, 3, 4, 5, 1, 5]] { + let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + .first { $0.activationState == .foregroundActive } + ?? UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first + let 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 + let controller = UIViewController() + let footer = ScenicMaterialsFooterView() + // 在入窗前设置首个状态,覆盖直接打开“下载完成”演示时的初次布局。 + apply(try XCTUnwrap(states.first), to: footer) + window.rootViewController = controller + controller.loadViewIfNeeded() + controller.view.addSubview(footer) + footer.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + footer.widthAnchor.constraint(equalToConstant: width), + footer.centerXAnchor.constraint(equalTo: controller.view.centerXAnchor), + footer.bottomAnchor.constraint(equalTo: controller.view.bottomAnchor) + ]) + window.makeKeyAndVisible() + defer { + window.isHidden = true + window.rootViewController = nil + previousKeyWindow?.makeKeyAndVisible() + } + for state in states { + apply(state, to: footer) + window.setNeedsLayout() + window.layoutIfNeeded() + try await Task.sleep(nanoseconds: 20_000_000) + controller.view.layoutIfNeeded() + footer.layoutIfNeeded() + XCTAssertTrue(footer.window === window) + XCTAssertEqual(footer.bounds.width, width, accuracy: 0.5) + let primary: UIButton = try control("scenic.materials.primary", in: footer) + try assertCompleteSingleLineTitle(primary) + if let secondary = allViews(footer).first(where: { + $0.accessibilityIdentifier == "scenic.materials.secondary" + }) as? UIButton, isVisible(secondary, within: footer) { + try assertCompleteSingleLineTitle(secondary) + } + if state == 5 { + XCTAssertEqual(primary.titleLabel?.text, "继续选择素材") + XCTAssertGreaterThan(primary.bounds.width, width * 0.8) + } + } + } + } + } + + /// 下载摘要和取消位于同一行,进度条与通栏按钮依次放在其下方。 + func testDownloadingKeepsCancelBesideSummaryAndPrimaryBelowProgress() throws { + let footer = ScenicMaterialsFooterView() + apply(2, to: footer) + layout(footer, width: 375) + let title: UILabel = try control("scenic.materials.footer.title", in: footer) + let cancel: UIButton = try control("scenic.materials.secondary", in: footer) + let progress: UIProgressView = try control("scenic.materials.footer.progress", in: footer) + let primary: UIButton = try control("scenic.materials.primary", in: footer) + let titleRect = title.convert(title.bounds, to: footer) + let cancelRect = cancel.convert(cancel.bounds, to: footer) + let progressRect = progress.convert(progress.bounds, to: footer) + let primaryRect = primary.convert(primary.bounds, to: footer) + XCTAssertEqual(titleRect.midY, cancelRect.midY, accuracy: 1) + XCTAssertLessThanOrEqual(titleRect.maxX, cancelRect.minX) + XCTAssertLessThanOrEqual(max(titleRect.maxY, cancelRect.maxY), progressRect.minY) + XCTAssertLessThan(progressRect.maxY, primaryRect.minY) + XCTAssertEqual(primaryRect.minX, progressRect.minX, accuracy: 1) + XCTAssertEqual(primaryRect.maxX, progressRect.maxX, accuracy: 1) + } + + /// 失败时继续选择和重试并排;完成后仅保留通栏主操作,回到选择态不残留旧进度。 + func testResultAndSelectionTransitionsRemoveStaleControls() throws { + let footer = ScenicMaterialsFooterView() + apply(1, to: footer) + layout(footer, width: 320) + let selectionHeight = footer.bounds.height + for _ in 0..<3 { + apply(2, to: footer) + layout(footer, width: 320) + let progress: UIProgressView = try control("scenic.materials.footer.progress", in: footer) + apply(4, to: footer) + layout(footer, width: 320) + let secondary: UIButton = try control("scenic.materials.secondary", in: footer) + let primary: UIButton = try control("scenic.materials.primary", in: footer) + let secondaryRect = secondary.convert(secondary.bounds, to: footer) + let primaryRect = primary.convert(primary.bounds, to: footer) + XCTAssertTrue(isVisible(secondary, within: footer)) + XCTAssertEqual(secondaryRect.midY, primaryRect.midY, accuracy: 1) + XCTAssertLessThan(secondaryRect.maxX, primaryRect.minX) + XCTAssertEqual(secondaryRect.width, primaryRect.width, accuracy: 1) + + apply(5, to: footer) + layout(footer, width: 320) + XCTAssertFalse(isVisible(secondary, within: footer)) + let detail: UILabel = try control("scenic.materials.footer.detail", in: footer) + XCTAssertTrue(detail.text?.contains("未写入系统相册") == true) + XCTAssertGreaterThan(primary.bounds.width, primaryRect.width * 1.8) + + apply(1, to: footer) + layout(footer, width: 320) + XCTAssertEqual(footer.bounds.height, selectionHeight, accuracy: 1) + XCTAssertEqual(primary.title(for: .normal), "下载所选(2)") + let activity: UIActivityIndicatorView = try control("scenic.materials.footer.activity", in: footer) + XCTAssertFalse(isVisible(secondary, within: footer)) + XCTAssertFalse(isVisible(progress, within: footer)) + XCTAssertFalse(activity.isAnimating) + XCTAssertFalse(isVisible(activity, within: footer)) + } + } + + /// 忙碌时主操作禁用而取消可用;暂停及失败状态继续派发各自的操作回调。 + func testBusyPrimaryCannotDispatchButCancelAndResumeCan() throws { + let footer = ScenicMaterialsFooterView() + var primaryCalls = 0 + var secondaryCalls = 0 + footer.onPrimaryTap = { primaryCalls += 1 } + footer.onSecondaryTap = { secondaryCalls += 1 } + apply(2, to: footer) + layout(footer, width: 393) + let primary: UIButton = try control("scenic.materials.primary", in: footer) + let secondary: UIButton = try control("scenic.materials.secondary", in: footer) + let activity: UIActivityIndicatorView = try control("scenic.materials.footer.activity", in: footer) + XCTAssertFalse(primary.isEnabled) + XCTAssertEqual(primary.backgroundColor, ScenicMaterialsStyle.primary) + XCTAssertTrue(activity.isAnimating) + XCTAssertTrue(secondary.isEnabled) + primary.sendActions(for: .touchUpInside) + secondary.sendActions(for: .touchUpInside) + XCTAssertEqual(primaryCalls, 0) + XCTAssertEqual(secondaryCalls, 1) + + for state in [3, 4] { + apply(state, to: footer) + layout(footer, width: 393) + XCTAssertTrue(primary.isEnabled) + XCTAssertFalse(activity.isAnimating) + primary.sendActions(for: .touchUpInside) + secondary.sendActions(for: .touchUpInside) + } + XCTAssertEqual(primaryCalls, 2) + XCTAssertEqual(secondaryCalls, 3) + } + + private func apply(_ state: Int, to footer: ScenicMaterialsFooterView) { + switch state { + case 0, 1: + footer.configure(title: "已选 \(state == 0 ? 0 : 2) 段", detail: "本地演示 · 不下载或保存真实文件", + primaryTitle: state == 0 ? "下载所选" : "下载所选(2)", primaryEnabled: state == 1, + layout: .selection) + case 2: + footer.configure(title: "下载中 · 0/2 段", detail: nil, primaryTitle: "正在下载…", primaryEnabled: false, + secondaryTitle: "取消", progress: 0.35, layout: .progress, isBusy: true) + case 3: + footer.configure(title: "已暂停 · 已完成 1/2 段", detail: "已完成项已保留,请手动继续", + primaryTitle: "继续下载", primaryEnabled: true, secondaryTitle: "取消", + progress: 0.5, layout: .progress) + case 4: + footer.configure(title: "完成 1 段 · 失败 1 段", detail: "演示结果 · 未保存真实文件", + primaryTitle: "重试失败(1)", primaryEnabled: true, secondaryTitle: "继续选择", + layout: .result) + default: + footer.configure(title: "演示完成 2 段", detail: "未写入系统相册", primaryTitle: "继续选择素材", + primaryEnabled: true, layout: .result) + } + } + + private func layout(_ footer: UIView, width: Double) { + let size = footer.systemLayoutSizeFitting(CGSize(width: width, height: 1), + withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel) + footer.frame = CGRect(origin: .zero, size: size) + footer.setNeedsLayout() + footer.layoutIfNeeded() + } + + private func control(_ identifier: String, in root: UIView) throws -> T { + try XCTUnwrap(allViews(root).first { $0.accessibilityIdentifier == identifier } as? T) + } + + private func assertCompleteSingleLineTitle(_ button: UIButton, + file: StaticString = #filePath, line: UInt = #line) throws { + let label = try XCTUnwrap(button.titleLabel, file: file, line: line) + let title = try XCTUnwrap(button.currentTitle, file: file, line: line) + let font = try XCTUnwrap(label.font, file: file, line: line) + let measured = (title as NSString).size(withAttributes: [.font: font]) + let rect = label.convert(label.bounds, to: button) + XCTAssertEqual(label.text, title, file: file, line: line) + XCTAssertEqual(label.numberOfLines, 1, "按钮应单行完整显示:\(title)", file: file, line: line) + XCTAssertTrue(isVisible(label, within: button), file: file, line: line) + XCTAssertGreaterThanOrEqual(rect.width + 1, measured.width, "按钮标题被挤窄:\(title)", file: file, line: line) + XCTAssertGreaterThanOrEqual(rect.height + 1, font.lineHeight, file: file, line: line) + XCTAssertGreaterThanOrEqual(rect.minX, -0.5, file: file, line: line) + XCTAssertGreaterThanOrEqual(rect.minY, -0.5, file: file, line: line) + XCTAssertLessThanOrEqual(rect.maxX, button.bounds.maxX + 0.5, file: file, line: line) + XCTAssertLessThanOrEqual(rect.maxY, button.bounds.maxY + 0.5, file: file, line: line) + let fitted = label.sizeThatFits(CGSize(width: rect.width, height: .greatestFiniteMagnitude)) + XCTAssertLessThanOrEqual(fitted.height, font.lineHeight + 1, "按钮标题被挤成多行:\(title)", file: file, line: line) + } + + private func allViews(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap { allViews($0) } } + + private func isVisible(_ view: UIView, within root: UIView) -> Bool { + var current: UIView? = view + while let candidate = current { + if candidate.isHidden || candidate.alpha == 0 { return false } + if candidate === root { return true } + current = candidate.superview + } + return false + } +} diff --git a/suixinkanTests/ScenicMaterialsRemoteLoadingTests.swift b/suixinkanTests/ScenicMaterialsRemoteLoadingTests.swift new file mode 100644 index 0000000..5becf9f --- /dev/null +++ b/suixinkanTests/ScenicMaterialsRemoteLoadingTests.swift @@ -0,0 +1,193 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 验证正式空境库的真实请求、可重试错误和离页后迟到响应隔离。 +@MainActor +final class ScenicMaterialsRemoteLoadingTests: XCTestCase { + /// 正式模式不生成预览素材;真实空响应仍保存保留策略与原始响应。 + func testEmptyResponseFinishesLoadingWithoutGeneratingDemoData() async throws { + let session = MockURLSession(responses: [try envelope()]) + let model = makeModel() + XCTAssertTrue(model.routes.isEmpty) + XCTAssertTrue(model.allGroups.isEmpty) + + await model.loadRemoteSessions(api: ScenicMaterialsAPI(client: APIClient(environment: .testing, session: session))) + + XCTAssertFalse(model.isLoading) + XCTAssertNil(model.loadError) + XCTAssertEqual(model.remoteSessions?.total, 0) + XCTAssertEqual(model.retentionDays, 90) + XCTAssertEqual(model.retentionTips, "素材保留 90 天,请及时下载") + XCTAssertTrue(model.routes.isEmpty) + XCTAssertTrue(model.allGroups.isEmpty) + XCTAssertTrue(model.selectedIDs.isEmpty) + XCTAssertFalse(model.canStartDownload) + XCTAssertEqual(model.emptyTitle, "暂无景区素材") + XCTAssertEqual(try query(session.requests[0])["scenic_id"], "271") + } + + /// 业务错误不能成为真实空库,用户重试成功后清除错误。 + func testBusinessErrorCanRecoverWithExplicitRetry() async throws { + let failure = Data(#"{"code":100099,"msg":"景区素材暂不可用","data":[]}"#.utf8) + let session = MockURLSession(responses: [failure, try envelope()]) + let api = ScenicMaterialsAPI(client: APIClient(environment: .testing, session: session)) + let model = makeModel() + + await model.loadRemoteSessions(api: api) + + XCTAssertFalse(model.isLoading) + XCTAssertEqual(model.loadError, "景区素材暂不可用") + XCTAssertEqual(model.emptyTitle, "素材加载失败") + XCTAssertNil(model.remoteSessions) + + await model.loadRemoteSessions(api: api) + + XCTAssertEqual(session.requests.count, 2) + XCTAssertFalse(model.isLoading) + XCTAssertNil(model.loadError) + XCTAssertEqual(model.emptyTitle, "暂无景区素材") + XCTAssertNotNil(model.remoteSessions) + } + + /// 日期筛选实际发送到接口,空筛选结果不称为全库无素材。 + func testDateFilterIsSentAsInclusiveCalendarDates() async throws { + let session = MockURLSession(responses: [try envelope(dateFrom: "2026-10-01", dateTo: "2026-10-29")]) + let model = makeModel() + XCTAssertTrue(model.setDateRange(start: date(2026, 10, 1), end: date(2026, 10, 29))) + + await model.loadRemoteSessions(api: ScenicMaterialsAPI(client: APIClient(environment: .testing, session: session))) + + XCTAssertEqual(try query(session.requests[0]), ["scenic_id": "271", "page": "1", "page_size": "20", + "retention_days": "90", "date_from": "2026-10-01", "date_to": "2026-10-29"]) + XCTAssertNil(model.loadError) + XCTAssertEqual(model.emptyTitle, "没有符合条件的素材") + XCTAssertEqual(model.emptyMessage, "试试其他航线或时间范围") + } + + /// 未确认的非空对象必须保留原值并显示可重试错误,不能冒充空库或演示素材。 + func testUnknownNonemptyObjectsRemainAvailableForContractInspection() async throws { + let session = MockURLSession(responses: [try envelope(list: [["unconfirmed_identity": 501]], total: 1)]) + let model = makeModel() + + await model.loadRemoteSessions(api: ScenicMaterialsAPI(client: APIClient(environment: .testing, session: session))) + + XCTAssertFalse(model.isLoading) + XCTAssertNotNil(model.loadError) + XCTAssertEqual(model.emptyTitle, "素材加载失败") + XCTAssertEqual(model.remoteSessions?.total, 1) + XCTAssertEqual(model.remoteSessions?.list.first?["unconfirmed_identity"], .number(Decimal(501))) + XCTAssertTrue(model.allGroups.isEmpty) + XCTAssertTrue(model.routes.isEmpty) + XCTAssertFalse(model.canStartDownload) + } + + /// 离页先作废请求,即使网络无法及时取消,迟到成功也不恢复页面数据。 + func testCancelRemoteLoadRejectsLateSuccess() async throws { + let requested = expectation(description: "场次请求已发出") + let api = ScenicMaterialsDeferredAPI { requested.fulfill() } + let model = makeModel() + let task = Task { await model.loadRemoteSessions(api: api) } + await fulfillment(of: [requested], timeout: 1) + XCTAssertTrue(model.isLoading) + XCTAssertEqual(model.emptyTitle, "正在加载素材") + + model.cancelRemoteLoad() + api.complete(try response()) + await task.value + + XCTAssertFalse(model.isLoading) + XCTAssertNil(model.remoteSessions) + XCTAssertNil(model.loadError) + XCTAssertTrue(model.allGroups.isEmpty) + } + + /// 调用方只取消任务时,不能留下永久加载状态或接纳随后返回的成功值。 + func testTaskCancellationFinishesLoadingAndRejectsLateSuccess() async throws { + let requested = expectation(description: "场次请求已发出") + let api = ScenicMaterialsDeferredAPI { requested.fulfill() } + let model = makeModel() + let task = Task { await model.loadRemoteSessions(api: api) } + await fulfillment(of: [requested], timeout: 1) + + task.cancel() + api.complete(try response()) + await task.value + + XCTAssertFalse(model.isLoading) + XCTAssertNil(model.remoteSessions) + XCTAssertNil(model.loadError) + } + + /// 使用固定公历和上海时区,日期查询不依赖运行机器的日历或当天时间。 + private func makeModel() -> ScenicMaterialsViewModel { + ScenicMaterialsViewModel(context: ScenicMaterialContext(userID: "remote-loading-user", scenicID: "271", scenicName: "测试景区"), + now: date(2026, 10, 29), calendar: calendar, isRemote: true) + } + + /// 接口日期与页面日历统一使用上海日期。 + private var calendar: Calendar { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "Asia/Shanghai")! + return calendar + } + + /// 构造测试内固定日界限。 + private func date(_ year: Int, _ month: Int, _ day: Int) -> Date { + calendar.date(from: DateComponents(year: year, month: month, day: day))! + } + + /// 保留部署接口真实根结构,未知非空子项只用于验证原样保留而不表示协议。 + private func envelope(list: [[String: Any]] = [], total: Int = 0, dateFrom: String = "", dateTo: String = "") throws -> Data { + let payload: [String: Any] = [ + "list": list, "groups": [] as [Any], "total": total, "page": 1, "page_size": 20, + "retention_days": 90, "retention_tips": "素材保留 90 天,请及时下载", + "filter": ["air_line_id": 0, "date_from": dateFrom, "date_to": dateTo], + "filter_options": ["air_lines": [] as [Any]], + ] + return try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": payload]) + } + + /// 延迟替身返回与真实接口一致的空响应。 + private func response() throws -> ScenicMaterialsSessionsResponse { + try XCTUnwrap(JSONDecoder().decode(APIEnvelope.self, from: envelope()).data) + } + + /// 检查完整服务端查询范围。 + private func query(_ request: URLRequest) throws -> [String: String] { + let url = try XCTUnwrap(request.url) + let items = try XCTUnwrap(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems) + return Dictionary(uniqueKeysWithValues: items.map { ($0.name, $0.value ?? "") }) + } +} + +/// 可控制响应返回时机的只读服务替身,模拟取消后仍返回成功的网络层。 +@MainActor +private final class ScenicMaterialsDeferredAPI: ScenicMaterialsServing { + private var continuation: CheckedContinuation? + private let onRequest: () -> Void + + /// 请求挂起后通过回调唤醒测试,避免轮询或固定等待。 + init(onRequest: @escaping () -> Void) { self.onRequest = onRequest } + + /// 挂起场次请求直到测试发出回执。 + func sessions(query: ScenicMaterialsQuery) async throws -> ScenicMaterialsSessionsResponse { + try await withCheckedThrowingContinuation { continuation in + self.continuation = continuation + onRequest() + } + } + + /// 列表加载测试不应请求任何场次详情。 + func sessionDetail(scenicMediaID: Int) async throws -> ScenicMaterialsSessionDetailResponse { + XCTFail("列表加载不应请求场次详情") + throw APIError.networkFailed("测试不提供详情") + } + + /// 返回一次成功结果,模拟异步请求的迟到回执。 + func complete(_ response: ScenicMaterialsSessionsResponse) { + let pending = continuation + continuation = nil + pending?.resume(returning: response) + } +} diff --git a/景区空境库页面接口对接记录.md b/景区空境库页面接口对接记录.md new file mode 100644 index 0000000..d3897de --- /dev/null +++ b/景区空境库页面接口对接记录.md @@ -0,0 +1,379 @@ +# 景区空境库页面接口对接记录 + +> 更新日期:2026-10-29(北京时间)\ +> 范围:随心瞰商家版 iOS「景区空境库」,首页权限 URI 为 `sceniclibrary`。朱工文档中的「景区空镜库」指同一模块。\ +> 用途:按页面记录接口、调用时机、请求参数、返回 JSON、代码位置和待补齐事项。 + +## 1. 当前接入状态与证据说明 + +**当前正式页面已调用场次列表接口;场次详情 API 已封装,但尚未由页面调用。非空场次、航线和素材字段映射仍待补齐。** + +| 标记 | 含义 | +| --- | --- | +| 真实响应 | 2026-10-29 使用当前登录账号只读查询测试环境取得,可作为本次联调证据。 | +| 缓存节选 | 从 App 已缓存的权限内容中摘取,不是本次重新请求的完整响应。 | +| 结构示意 | 为说明已知容器或参数而整理;不能当作后端实际返回或完整字段合同。 | +| 待确认 | 朱工文档未列出完整结构,且当前账号没有非空数据,尚无法确认。 | + +当前景区 `271` 在 90 天、365 天窗口中均返回空列表。用户已确认账号尚未准备数据。不能据此推断非空 `list[]`、`groups[]`、`filter_options.air_lines[]` 和 `materials[]` 的完整字段。 + +本记录依据: + +- 朱工提供的 `随心瞰9.9.1-App机巢与素材库接口.md`(2026-10-29 本轮提供的版本)。 +- 当前工程代码及本轮联调响应。 +- [景区空镜库 UI 实现说明](docs/9.9.1/景区空镜库UI实现说明.md)。 + +## 2. 页面与接口总表 + +| 页面 / 区域 | 接口或系统能力 | 调用时机 | 当前状态 | +| --- | --- | --- | --- | +| 首页「景区空境库」入口 | `GET /api/yf-handset-app/role-permission` | 首页初始化、需要重新加载权限时 | 已接入,按当前角色顶层权限展示入口。 | +| 「全部功能」中的空境库入口 | 读取首页缓存的权限,无独立素材请求 | 进入全部功能、权限更新、调整常用应用时 | 已接入;添加常用只保存本地配置。 | +| 景区空境库主页面 | `GET /api/app/scenic-media/sessions` | 首次进入、下拉刷新、失败重试、应用/重置筛选时 | 已接入真实空态;非空展示待确认。 | +| 航线筛选弹层 | 使用列表的 `filter_options.air_lines`;确认后由主页面再请求 `sessions` | 打开弹层不发请求,确认选项后更新查询 | 筛选参数已支持;非空航线项映射未完成。 | +| 时间筛选弹层 | 确认后由主页面再请求 `sessions` | 确认有效日期范围或选择全部时间 | 已接入日期参数;弹层本身没有单独接口。 | +| 场次片段展示(主页面内分组,非独立详情页) | `GET /api/app/scenic-media/session-detail` | 预期用于取得一个场次的完整片段 | API 已封装,尚未确定 UI 调用时机与场次 ID 映射。 | +| 视频预览弹层 | AVPlayer 读取素材原片 URL;Kingfisher 读取封面 URL | 点击预览/播放 | 远程播放能力已实现;正式片段数据链路未串通。无新增业务 JSON 接口。 | +| 下载栏 / 进度 / 失败重试 | URLSession 下载素材 URL,Photos 保存相册 | 用户开始、继续或重试下载 | 下载保存能力已实现;待详情数据映射后从真实列表使用。 | +| 相册权限提示 / 去设置 | Photos `.addOnly` 授权、系统设置 | 下载前无添加权限 | 系统能力,无业务 JSON。 | +| Debug「空镜预览」与状态菜单 | 本地演示数据和随包视频 | 显式打开 Debug 预览 | 不请求上述素材业务接口,不保存真实素材。 | + +## 3. 公共请求与响应约定 + +| 项目 | 当前工程与联调结果 | +| --- | --- | +| 测试环境 | `https://api-test.zhifly.cn` | +| 生产环境 | `https://api.zhifly.cn`(本记录未进行生产联调) | +| 账号要求 | `store_user` 门店账号;正式页检查当前账号与当前景区是否匹配。 | +| 鉴权 | 统一 `APIClient` 注入 HTTP Header `token`;本文不保存实际凭证。 | +| 公共请求头 | `Accept: application/json`、`X-APP-VERSION`、`X-OS-TYPE`。 | +| GET 参数 | URL 查询串。 | +| 实际成功包 | `code: 100000`、`msg: "success"`、`data`,实测另含 `time`。 | +| 实际业务失败包 | 非成功 `code` 与 `msg`;不能只凭 HTTP 200 判断成功。 | +| 日志 | 场次与详情请求设置 `logsPayload: false`,避免将素材签名地址写入正文日志。 | + +朱工文档顶部写有 `YFHandSetAppToken` 鉴权标识,示意成功包为 `code=0/message`;本轮部署接口实际使用 `token` 请求头和 `100000/msg` 包装。当前实现沿用经过实测的统一客户端,不把文档示意的 `code=0` 当成功。 + +## 4. 首页与全部功能:权限入口 + +**接口:** `GET /api/yf-handset-app/role-permission` + +本模块不增加请求参数。首页将当前角色的顶层 `role.permission` 映射为菜单,识别 URI `sceniclibrary`。本地入口标题是「景区空境库」;后台缓存名称为「景区空镜库」。 + +### 4.1 权限 JSON + +**结构示意:以下仅为响应结构与本模块节点的精简示意,不是完整抓包。** `data` 为角色数组;角色、景区、门店均可能有其他项。 + +```json +{ + "code": 100000, + "msg": "success", + "data": [ + { + "role": { + "id": 41, + "name": "app摄影师", + "role_code": "photographer", + "notes": "", + "permission": [ + { + "id": 370, + "pid": 0, + "name": "景区空镜库", + "uri": "sceniclibrary", + "icon_src": "" + } + ] + }, + "scenic": [], + "store": [] + } + ] +} +``` + +其中 `id=370` 的权限节点来自本轮已查看的 App 缓存;代码只匹配 `uri`,不硬编码权限 ID。示意中的空 `scenic/store` 只为精简结构,不表示当前账号没有景区或门店。 + +### 4.2 页面行为 + +- 有该权限时入口进入可用菜单;已有常用配置时,可在「更多功能」中加入首页常用。 +- 没有自定义配置时沿用默认前四项规则,不保证新权限直接出现在首页常用区。 +- 权限刷新后撤销该 URI,入口从首页和全部功能隐藏;旧常用配置不能绕过权限。 +- 首页路由要求已选择景区;正式素材页发请求前进一步要求门店账号与进入页时的账号、景区一致。 + +代码:[HomeAPI](suixinkan/Features/Home/API/HomeAPI.swift)、[HomeViewModel](suixinkan/Features/Home/ViewModels/HomeViewModel.swift)、[HomeMenuCatalog](suixinkan/Features/Home/Services/HomeMenuCatalog.swift)、[HomeRouteHandler](suixinkan/Features/Home/Services/HomeRouteHandler.swift)。 + +## 5. 景区空境库主页面:场次列表 + +页面:`ScenicMaterialsViewController`。 + +**接口:** `GET /api/app/scenic-media/sessions` + +### 5.1 请求参数 + +| 参数 | 必填 | 默认值 / 范围 | 用途 | +| --- | --- | --- | --- | +| `scenic_id` | 是 | 当前景区,正整数 | 限定景区。 | +| `page` | 否 | `1`,正整数 | 场次页码。 | +| `page_size` | 否 | `20`,`1...100` | 每页场次数。 | +| `air_line_id` | 否 | 不传代表全部航线;指定时正整数 | 航线筛选。 | +| `date_from` | 否 | `yyyy-MM-dd` | 起始日期。 | +| `date_to` | 否 | `yyyy-MM-dd` | 结束日期。 | +| `retention_days` | 否 | `90`;客户端限制 `1...365` | 保留期查询窗口;上限 365 已由真实错误响应验证。 | + +当前主页面固定请求第 1 页、每页 20 条。API 参数层已支持分页,列表追加下一页尚未实现。 + +正式页面首次请求示意: + +```http +GET /api/app/scenic-media/sessions?scenic_id=271&page=1&page_size=20&retention_days=90 +``` + +### 5.2 真实返回 JSON:90 天空列表 + +采集时间:2026-10-29 17:49:53。只读联调请求传入 `scenic_id=271&page=1&page_size=20`,未显式传 `retention_days`,服务端按默认 90 天返回。 + +```json +{ + "code": 100000, + "msg": "success", + "data": { + "list": [], + "groups": [], + "total": 0, + "page": 1, + "page_size": 20, + "retention_days": 90, + "retention_tips": "素材保留 90 天,请及时下载", + "filter": { + "air_line_id": 0, + "date_from": "", + "date_to": "" + }, + "filter_options": { + "air_lines": [] + } + }, + "time": "2026-10-29 17:49:53" +} +``` + +### 5.3 已确认的根字段 + +| JSON 路径 | 实测形态 | 页面用途与当前限制 | +| --- | --- | --- | +| `data.list` | 空数组 | 场次列表;非空项字段待确认。 | +| `data.groups` | 空数组 | 航线分组;分组身份和子列表层级待确认。 | +| `data.total` | 整数 | 当前筛选的总场次数。 | +| `data.page` / `data.page_size` | 整数 | 当前页与每页数量;API 校验与请求一致。 | +| `data.retention_days` | 整数 | 查询窗口及日期范围限制。 | +| `data.retention_tips` | 字符串 | 页面保留期说明。 | +| `data.filter.air_line_id` | 整数,全部为 `0` | 回显实际航线筛选。 | +| `data.filter.date_from` / `date_to` | 字符串,未筛选为空字符串 | 回显实际日期筛选。 | +| `data.filter_options.air_lines` | 空数组 | 可用航线选项;非空项字段待确认。 | +| `time` | 字符串 | 后端响应时间,当前业务模型不使用它定位素材。 | + +子项在客户端暂以 JSON 对象无损保留。**空数组只能确认容器,不能证明子项的 ID、名称、时间、单位或嵌套关系。** + +当前 `total > 0`,或 `list/groups/air_lines` 任一非空时,页面暂显示「素材加载失败 / 暂时无法显示素材,请稍后重试」,保留响应供后续映射;不会把未知非空结果显示成「暂无景区素材」。 + +### 5.4 真实返回 JSON:365 天空列表 + +采集时间:2026-10-29 17:50:45。此请求仅用于检查是否有历史样本,不是正式页面默认窗口。 + +```http +GET /api/app/scenic-media/sessions?scenic_id=271&page=1&page_size=100&retention_days=365 +``` + +```json +{ + "code": 100000, + "msg": "success", + "data": { + "list": [], + "groups": [], + "total": 0, + "page": 1, + "page_size": 100, + "retention_days": 365, + "retention_tips": "素材保留 365 天,请及时下载", + "filter": { + "air_line_id": 0, + "date_from": "", + "date_to": "" + }, + "filter_options": { + "air_lines": [] + } + }, + "time": "2026-10-29 17:50:45" +} +``` + +### 5.5 真实返回 JSON:保留期超限 + +联调时传入 `retention_days=3650`,服务端返回如下错误,随后改用上限 365 查询。正式客户端会在发请求前拒绝超限参数。 + +```json +{ + "code": 100099, + "msg": "The retention days may not be greater than 365.", + "data": [], + "time": "2026-10-29 17:50:26" +} +``` + +### 5.6 加载、刷新与重试 + +首次进入、下拉刷新、点击「重新加载」都重新请求 `sessions`。素材下载批次锁定期间不刷新;确认离页后取消加载并丢弃迟到回执,取消返回手势则保留原加载。当前没有定时轮询。 + +代码:[ScenicMaterialsAPI](suixinkan/Features/ScenicMaterials/API/ScenicMaterialsAPI.swift)、[ScenicMaterialsQuery](suixinkan/Features/ScenicMaterials/Models/ScenicMaterialsQuery.swift)、[ScenicMaterialsAPIModels](suixinkan/Features/ScenicMaterials/Models/ScenicMaterialsAPIModels.swift)、[ScenicMaterialsViewModel](suixinkan/Features/ScenicMaterials/ViewModels/ScenicMaterialsViewModel.swift)、[ScenicMaterialsViewController](suixinkan/UI/ScenicMaterials/ScenicMaterialsViewController.swift)。 + +## 6. 航线筛选弹层 + +页面:`ScenicMaterialRouteFilterViewController`。 + +打开弹层没有独立接口,使用主页面已有航线。航线选项预期来自 `sessions` 响应的 `data.filter_options.air_lines`;当前非空航线映射未完成,正式页不能展示真实航线选项。 + +用户确认航线后由主页面重查 `sessions`。以下是参数示意,`123` 不是本轮已验证的有效航线: + +```http +GET /api/app/scenic-media/sessions?scenic_id=271&page=1&page_size=20&retention_days=90&air_line_id=123 +``` + +响应采用第 5 节同一 JSON 包装,`data.filter.air_line_id` 应回显所选航线。**尚无真实航线筛选的非空响应**,不在此伪造 `air_lines[]` 项结构。选择「全部航线」时省略 `air_line_id`。 + +代码:[ScenicMaterialFilterViewControllers](suixinkan/UI/ScenicMaterials/ScenicMaterialFilterViewControllers.swift)。 + +## 7. 时间筛选弹层 + +页面:`ScenicMaterialDateFilterViewController`。 + +打开弹层、滚动日期、取消弹层均不请求接口;确认有效起止日期后由主页面重查 `sessions`。主页面使用同一日历格式化为 `yyyy-MM-dd`,UI 选区包含首尾日期且不允许未来或保留期之外的日期。后端对拍摄时间边界的实际包含规则仍需有数据后联调。 + +筛选请求示意,非本轮真实抓包: + +```http +GET /api/app/scenic-media/sessions?scenic_id=271&page=1&page_size=20&retention_days=90&date_from=2026-10-01&date_to=2026-10-29 +``` + +响应沿用第 5 节结构。下面**仅为预期回显的结构示意**,不是完整响应,也不是后端实测记录: + +```json +{ + "filter": { + "air_line_id": 0, + "date_from": "2026-10-01", + "date_to": "2026-10-29" + } +} +``` + +选择全部时间时不传 `date_from/date_to`;主页面「重置筛选」同时清空航线与时间并重新请求。API 层允许只传一个日期端点,当前页面交互要求两个日期一起确定。 + +## 8. 场次片段展示:场次详情接口 + +现有 UI 没有单独的场次详情控制器,片段计划在空境库主页面按场次分组显示。 + +**接口:** `GET /api/app/scenic-media/session-detail` + +| 参数 | 必填 | 说明 | +| --- | --- | --- | +| `scenic_media_id` | 是 | 空境场次身份,正整数;来源字段尚需非空列表确认。不是订单 ID、飞行任务 ID 或订单素材 ID。 | + +```http +GET /api/app/scenic-media/session-detail?scenic_media_id=<后端返回的空境场次ID> +``` + +### 8.1 返回 JSON 的已知范围 + +**尚无该接口的真实成功响应。** 朱工文档只说明「场次信息 + `materials[]`」,并提到素材字段 `file_label`、`selectable`、`oss_url`。 + +下面仅为当前解码器接受的**最小结构示意**。其中 `materials: []` 用来展示已知容器,不代表接口实际返回了空素材,也不表示完整返回只有这一个字段: + +```json +{ + "code": 100000, + "msg": "success", + "data": { + "materials": [] + } +} +``` + +| 文档提及字段 | 文档可确认的用途 | 仍待确认 | +| --- | --- | --- | +| `materials` | 场次片段集合 | 每项完整结构、顺序、稳定 ID、是否返回全部片段。 | +| `materials[].file_label` | 片段显示名称 | 实际类型、空值与缺省行为。 | +| `materials[].selectable` | 是否可选 | 实际为布尔还是数值,以及不可选原因。 | +| `materials[].oss_url` | 原片地址 | 空值、签名有效期、过期后刷新方式、是否可直接用于播放。 | +| 场次信息 | 确认场次身份、航线与拍摄时间 | 根节点或嵌套位置及字段名均待确认。 | + +API 已有 `sessionDetail(scenicMediaID:)`,会保留完整对象和 `materials`;**当前生产 UI 没有调用此方法**。后续需先确认列表到场次 ID 的映射,再确定首屏、展开或选择时的详情请求策略。 + +代码:[ScenicMaterialsAPI](suixinkan/Features/ScenicMaterials/API/ScenicMaterialsAPI.swift)、[ScenicMaterialsAPIModels](suixinkan/Features/ScenicMaterials/Models/ScenicMaterialsAPIModels.swift)。 + +## 9. 视频预览弹层与封面 + +页面:`ScenicMaterialPreviewViewController`;列表封面由 `ScenicMaterialClipCell` 展示。 + +| 行为 | 数据来源 / 请求 | 返回内容 | +| --- | --- | --- | +| 显示封面 | Kingfisher 读取页面模型 `coverURL` | 图片二进制,没有业务 JSON。封面后端字段仍待确认。 | +| 点击播放 | AVPlayer / AVURLAsset 读取页面模型 `remoteURL` | 媒体文件或播放器需要的资源,不经过 App 业务 JSON 包装。 | +| 显示名称、时长、大小、分辨率 | 读取片段模型 | 不再发接口;后端字段及单位尚待映射。 | +| 关闭或退到后台 | 暂停播放器 | 无接口、无 JSON。 | + +文档提到的 `oss_url` 是后续原片地址映射的依据;当前真实详情数据尚未转换成片段模型。已有远程预览代码不等于正式素材已完成播放联调。正式素材缺少地址时不会回退到随包演示视频。 + +代码:[ScenicMaterialPreviewViewController](suixinkan/UI/ScenicMaterials/ScenicMaterialPreviewViewController.swift)、[ScenicMaterialComponents](suixinkan/UI/ScenicMaterials/ScenicMaterialComponents.swift)。 + +## 10. 下载栏、进度、重试与相册权限 + +这些是主页面内的操作状态和系统弹窗,没有独立业务页面接口。 + +| 步骤 | 调用内容 | 返回内容 / 成功标准 | +| --- | --- | --- | +| 请求相册权限 | `PHPhotoLibrary.requestAuthorization(for: .addOnly)` | 系统授权状态枚举,无 JSON。 | +| 下载原片 | URLSession 对片段 `remoteURL` 发出 HTTP(S) 下载请求 | 文件二进制;要求 HTTP 2xx 且本地文件非空。 | +| 写入相册 | `PHPhotoLibrary.performChanges` 添加视频资源 | 系统完成回调或错误,无 JSON;保存成功才计为已完成。 | +| 暂停 / 取消 | 停止当前下载并作废旧回执 | 本地状态变化,无业务 JSON。已提交的 Photos 保存需等待落定。 | +| 继续 / 重试失败 | 重新处理未完成项或失败项 | 复用素材地址;当前服务实例记录已保存素材,避免重复保存。 | +| 去设置 | 打开 iOS 系统设置 | 无业务接口、无 JSON。 | + +下载请求不向素材 URL 附加 App 的登录凭证。此能力已实现并经隔离测试,但正式页面尚无完成字段映射的真实素材可供选择下载。实际 URL 过期、文件类型和素材样本仍待后端数据联调;保存记录目前不是跨页面的持久化下载历史。 + +代码:[ScenicMaterialDownloadService](suixinkan/Features/ScenicMaterials/Services/ScenicMaterialDownloadService.swift)、[ScenicMaterialsViewController](suixinkan/UI/ScenicMaterials/ScenicMaterialsViewController.swift)。 + +### 10.1 本模块不调用的同前缀接口 + +| 接口 | 当前不用于景区空境库的原因 | +| --- | --- | +| `GET /api/app/scenic-media/order-materials` | 查询订单素材,按订单号组织,不是空境场次列表。 | +| `POST /api/app/scenic-media/mark-download` | 文档的 `media_id` 明确为 `order_flight_task_media.id`,不能用空境场次/片段 ID 回写。 | +| `POST /api/app/scenic-media/retry-upload` | 重试订单素材上传,不能当作空境文件下载重试。 | +| `POST /api/app/scenic-media/retry-failed` | 整单重试失败上传,属于订单素材。 | + +本模块不调用机巢召唤、开始拍摄、飞控或实时图传接口。 + +## 11. 待后端补充的 JSON 与联调项目 + +| 所需样本 / 说明 | 用途 | +| --- | --- | +| 含至少一个场次的 `sessions` 完整成功响应 | 确认 `list/groups` 的关系、场次 ID、航线 ID、拍摄时间。 | +| 含航线选项的 `filter_options.air_lines` | 确认筛选项 ID/名称,并保留暂无素材航线的规则。 | +| 与上述场次对应的 `session-detail` 完整成功响应 | 确认素材 ID、所属场次、名称、可选状态、播放/下载 URL。 | +| 封面、时长、文件大小、分辨率、文件类型字段及单位 | 完成真实卡片与预览元信息展示。 | +| 第二页及最后一页样本 | 完成分页、去重、追加加载和结束判断。 | +| 日期边界、签名过期、不可下载片段样本 | 确认日期筛选、URL 刷新及失败提示。 | + +文档指明空境数据来自 `scenic_media` 场次和 `view_album / view_album_detail` 拍摄文件;具体后台录入入口未提供,需朱工确认。不能用订单素材样本代替空境场次样本。 + +## 12. 验证记录与后续维护 + +- 2026-10-29:测试环境景区 271 的 90 天和 365 天列表查询成功,均为空;3650 天请求得到保留期超限错误。 +- 2026-10-29:模拟器首轮 55 项测试通过;生命周期修正后追加 13 项 UI/加载回归通过。涵盖 API 参数、错误解析、空态、取消、权限入口、预览与下载保存替身。 +- 测试中的构造 JSON 仅验证客户端行为,不能升级为非空后端协议的真实证据;真实素材播放、下载保存全链路仍未完成联调。 +- 本文档生成时仅核对源码和已有记录,不重新请求接口,不修改业务代码。 + +后续每次更新请保留:页面与调用时机、实际请求参数、完整脱敏响应、采集时间和环境、当前接入状态。真实凭证和有效的签名下载 URL 不写入文档;新增示例必须标明是抓包、文档示意还是测试构造。 diff --git a/机巢工作台页面接口对接记录.md b/机巢工作台页面接口对接记录.md index 9d4154f..388b5ad 100644 --- a/机巢工作台页面接口对接记录.md +++ b/机巢工作台页面接口对接记录.md @@ -1,11 +1,18 @@ # 机巢工作台页面接口对接记录 > 更新日期:2026-10-29 -> 核对范围:当前工作区。准备页使用张工 `project-info` 和朱工 `plane-status`;“确认并召唤”按 `project-info → tasks/create → shoot` 执行,召唤业务成功后进入任务页;按用户最新要求,`shooting` 已取消定时轮询,仅在进入页面、页面可见时返回前台或手动刷新时各读取一次同一任务。准备页 `plane-status` 保持轮询。最新 2026-10-29 17:18–17:19 模拟器实操新建任务 11,再以 `{id:11,restart:false}` 召唤;两个接口均成功,绑定飞机 61、航线任务 1931。17:19:04 首次查询允许开始,17:19:59 手动回查已为航线执行失败、禁止拍摄,当前待朱工定位 1931 失败原因与自动派机条件(见 7.7.3)。任务 6 / 航线 1926 的先前失败记录保留。召唤回执的“已到达”不是物理验证,本轮未调用开始拍摄或控制接口。任务 2 的参数、订单类型及机场状态失败保留为历史,原因不因新任务成功而作推断。`workbench`、定位请求已停用;图传、`start-shoot/command` 尚未接入,真实成片上传仍待联调。 +> **当前禁飞限制(优先于下文历史联调记录):**按用户最新要求,调试不得向真实无人机下发指令。Debug 准备页禁止真实创建和召唤;统一网络层在传输前阻断 `tasks/create`、机场操作请求(包括 `shoot/start-shoot/command/live` 及未确认的新接口)。状态 GET 仅允许已确认的 `home/plane-status/shooting/status`,其中实时采集参数强制为 `live_battery=0` 或 `live_metrics=0`。只有完全不联网的 Mock 传输可以验证原始请求合同。下文任务 6、11 的真实召唤均发生于此限制之前,不作为继续真实联调的授权。 +> 核对范围:当前工作区。准备页使用张工 `project-info` 和朱工 `plane-status`;“确认并召唤”按 `project-info → tasks/create → shoot` 执行,召唤业务成功后进入任务页;按用户最新要求,`shooting` 已取消定时轮询,仅在进入页面、页面可见时返回前台或手动刷新时各读取一次同一任务。准备页 `plane-status` 保持轮询。最新 2026-10-29 17:18–17:19 模拟器实操新建任务 11,再以 `{id:11,restart:false}` 召唤;两个接口均成功,绑定飞机 61、航线任务 1931。17:19:04 首次查询允许开始,17:19:59 手动回查已为航线执行失败、禁止拍摄,当前待朱工定位 1931 失败原因与自动派机条件(见 7.7.3)。任务 6 / 航线 1926 的先前失败记录保留。召唤回执的“已到达”不是物理验证,本轮未调用开始拍摄或控制接口。任务 2 的参数、订单类型及机场状态失败保留为历史,原因不因新任务成功而作推断。`workbench`、定位请求已停用;`start-shoot` 已实现纯本地模拟(见 7.6.2),真实开拍入口保持禁用;图传、`command` 尚未接入,真实成片上传仍待联调。 > 用途:记录每个页面实际调用的接口、提供人、调用时机、请求参数和返回 JSON,供 iOS 与后端持续联调。 ## 1. 阅读说明 +- **开始拍摄模拟入口**:`--dock-start-shoot-mock`;只使用内存响应,不联网。成功/业务拒绝/超时三种场景与完整回执见第 7.6.2 节。 +- **准备到任务的模拟入口**:Debug 真实准备页右上角“本地模拟”,或启动参数 `--dock-preparation-mock`。进入独立模拟准备页后点击“确认并召唤(模拟)”,在内存中完成创建、召唤并带同一任务 ID 跳到模拟任务页;真实提交保护不变。 +- **当前模拟调试方式**:`--dock-ui-preparation-preview`、`--dock-ui-task-preview` 使用纯内存演示状态;接口合同用 Mock 响应验证参数、解析、成功/失败和页面切换。模拟结果不能记成真实接口成功。`--dock-*-live` 仍连接真实服务,受 Debug 禁飞保护,不能用于执行飞控。 +- **后端模拟协议**:当前提供的文档没有 `dry_run` 或模拟设备参数。不得自行添加一个未约定的字段后调用真实 `shoot`;后端提供明确不会向设备下发指令的独立模拟协议并经用户确认后,才对接该模拟服务,不能因此放行真实飞控。 +- **禁飞保护验证**:2026-10-29 模拟器 77 项相关测试通过,全部使用内存响应或不联网探针;覆盖真实传输零指令、创建前阻断、强类型/裸 JSON/multipart 三条发送入口、只读查询关闭实时采集、本地拦截不进入结果未知锁及既有 Mock 合同。未调用真实创建、召唤或设备控制接口。 + - **已接入**:当前正式页面已发出请求并处理响应。 - **已实现,待真实联调**:代码和测试已接入,但尚未取得该动作的真实成功响应。 - **历史已停用**:保留此前联调响应供追溯,当前正式页面不再调用。 @@ -17,7 +24,7 @@ ## 2. 页面与接口总览 -当前机巢模块共 **8 个正式页面,已实现 14 个业务接口及 1 个通用 STS 接口**。新增拍摄任务页复用已实现的 `shooting` API,接口总数不增加;它由任务页读取,准备页不直接调用。`shooting` 已取得类型 25 的真实响应;`tasks/create → shoot` 对任务 6 业务成功,但随后回查显示航线执行失败、禁止拍摄。任务页成功导航仍有网络替身测试覆盖;成片保存与 STS 上传流程仍待真实联调。独立订单页复用首页已使用的 `orders`。 +当前机巢模块共 **8 个正式页面,已实现 15 个业务接口及 1 个通用 STS 接口**(其中 `start-shoot` 仅启用纯本地模拟)。新增拍摄任务页复用已实现的 `shooting` API,接口总数不增加;它由任务页读取,准备页不直接调用。`shooting` 已取得类型 25 的真实响应;`tasks/create → shoot` 对任务 6 业务成功,但随后回查显示航线执行失败、禁止拍摄。任务页成功导航仍有网络替身测试覆盖;成片保存与 STS 上传流程仍待真实联调。独立订单页复用首页已使用的 `orders`。 | 页面/区域 | 提供人 | 方法与完整路径 | 当前状态 | | --- | --- | --- | --- | @@ -33,6 +40,7 @@ | 拍摄准备页:创建待飞任务并展示回执 | 张工 | `POST /api/yf-handset-app/photog/multi-plane/tasks/create` | 已实测成功;最新 16:03:01 创建 task_id=6,剩余 5,随后调用 shoot | | 拍摄准备页:对已创建任务确认并召唤 | 朱工 | `POST /api/app/airport/shoot` | 16:03:31 真实成功,id=6 且省略 plane_id;回执绑定飞机 61、航线任务 1926,业务成功后进入同任务页 | | 拍摄任务页:任务摘要、六项读数与阶段状态 | 朱工 | `GET /api/app/airport/shooting` | 已接入,取消定时轮询;进入、可见时返回前台或手动刷新各读一次;16:04:52 任务 6 的航线执行失败、门禁阻止拍摄 | +| 拍摄任务页:开始拍摄 | 朱工 | `POST /api/app/airport/start-shoot` | 已实现纯内存 Mock;真实入口禁用,84 项相关测试通过,见 7.6.2 | | 订单素材库:整单摘要与点位标签 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/orders/detail` | 已接入 | | 订单素材库:任务、原素材、成片与点位筛选 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/tasks` | 已接入,不分页 | | 交付成片:订单权限与购买点位 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/orders/detail` | 复用已接入接口 | @@ -40,7 +48,7 @@ | 交付成片:上传凭证 | 既有通用接口,张工文档指定复用 | `GET /api/app/config/get-sts-token` | 已实现,待本页真实上传联调 | | 交付成片:保存或替换成片 | 张工 | `POST /api/yf-handset-app/photog/multi-plane/tasks/film` | 已实现,待真实联调 | -准备页已停用朱工 `workbench`,历史响应保留在第 7.3 节;召唤 `shoot` 见第 7.7 节。订单素材库见第 8 节;交付成片见第 9 节。到达后开始拍摄、暂停、返航、批量下载和游客交付确认尚未接入,见第 10 节。 +准备页已停用朱工 `workbench`,历史响应保留在第 7.3 节;召唤 `shoot` 见第 7.7 节。订单素材库见第 8 节;交付成片见第 9 节。到达后开始拍摄已通过纯本地模拟,真实入口禁用,见第 7.6.2 节;暂停、返航、批量下载和游客交付确认尚未接入,见第 10 节。 ## 3. 公共约定 @@ -1010,13 +1018,13 @@ API:[DroneDockShootingAPI.swift](suixinkan/Features/DroneDock/API/DroneDockSho | 参数 | 必填 | 当前来源 | | --- | --- | --- | | `id` | 是 | 已明确创建成功的 `tasks/create.data.task_id`,不是订单号、点位 ID 或航线 ID | -| `live_battery` | 否 | 当前显式发送 `1`;布尔查询使用 `1/0` 编码 | +| `live_battery` | 否 | API 合同及纯内存 Mock 使用 `1`;禁飞期间 Debug 真实传输强制为 `0`,不触发实时采集;布尔查询使用 `1/0` 编码 | -该 GET 不发送 JSON body,不额外传景区、订单、点位、航线或经纬度参数。任务页只注入查询服务,没有创建、召唤或飞行控制依赖。 +该 GET 不发送 JSON body,不额外传景区、订单、点位、航线或经纬度参数。正式任务页只注入查询服务,没有创建、召唤或飞行控制依赖;独立 DEBUG 本地模拟入口另外注入开拍服务,见第 7.6.2 节。 **当前布局与状态动作:**顶部固定显示订单摘要、16:9 图传占位和六项读数,底部固定保留安全控制;加载、错误或业务状态变化不改变这两块区域的位置。中间占用剩余高度,按加载、前往、就绪、拍摄、暂停、返航、完成、失败、阻止、未知或读取错误组合图标、标题、说明、设备状态和主操作,没有滚动容器,也不使用整体 transform 缩放。 -空间不足时收紧间距、图标和字号,正文不小于 12 点,操作点击高度不小于 44 点;紧凑布局可隐藏设备摘要、截断长文案,通过“详情”查看完整说明。未确认或冲突状态显示待确认,不补造进度。开始/恢复拍摄及底部暂停/返航仍是禁用状态,不调用控制接口;只有明确完成态提供“查看素材”,进入当前订单的真实订单素材库。 +空间不足时收紧间距、图标和字号,正文不小于 12 点,操作点击高度不小于 44 点;紧凑布局可隐藏设备摘要、截断长文案,通过“详情”查看完整说明。未确认或冲突状态显示待确认,不补造进度。正式页面开始/恢复拍摄及底部暂停/返航仍是禁用状态;仅独立本地模拟入口允许开始拍摄,不调用真实控制接口;只有明确完成态提供“查看素材”,进入当前订单的真实订单素材库。 2026-10-29 失败态按产品体验网页单独组合:淡红圆底警示图标、固定标题“任务执行失败”、淡红失败原因条、排查提示、全宽带循环箭头的“重新召唤无人机”按钮和设备限制提示。不再显示通用“刷新状态+详情”按钮行;点击失败原因区域仍可查看完整说明,导航栏仍可手动刷新。原因优先使用 `order_flight_task.result_message / task.result_message`,再使用 `execute_gate.message / ui.message`;任务 11 当前明确离线,显示“无人机离线,暂不可召唤”,不套用网页示例的“返航中”。重新召唤尚未接入,始终禁用,不能将 `can_execute` 开始拍摄许可用于重召。顶部、底部位置固定,小屏仅收紧中间区域排版。 @@ -1149,6 +1157,58 @@ HTTP 200,完整业务响应: 此前读取串接阶段验证:模拟器构建通过;相关 **83 项不同测试全部通过**(shooting API/Model 8、shooting 串接 ViewModel 10、创建 API/Model 8、创建 ViewModel 14、准备页 ViewModel 28、页面 15)。包括创建后携同一 ID 读取、GET 失败后不重建、并发点击、取消/身份切换、原始 JSON 回显、购买读取失败仍保留任务回执。该阶段测试中的成功回执均为匿名替身,当时尚无真实成功响应;后续 15:07 的真实成功记录单列于上文。 +#### 7.6.2 开始拍摄:朱工 start-shoot,仅本地模拟 + +**本节 JSON 均为合成 Mock 回执,不是后端响应。** 禁飞期间未向后端或无人机发送开拍请求。正式任务页未注入开拍服务,按钮保持禁用;网络层在传输前继续阻断真实指令。 + +**准备页衔接:**Debug 真实准备页提供显式“本地模拟”入口,打开使用合成订单 `LOCAL-MOCK-ORDER-901` 的独立准备页。模拟 `project-info/plane-status` 读取后,点击“确认并召唤(模拟)”依次触发内存 `tasks/create`(返回任务 901)、`shoot`(`id=901,restart=false`),成功跳转任务页并读取 `shooting?id=901`。全部服务由同一模拟客户端注入,没有真实网络回退;模拟准备页及任务页标题、底部提示和回执均标明来源。返回后只“查看拍摄任务”,不重复创建或召唤。复现说明见[本地模拟调试记录](docs/9.9.1/start-shoot-mock-2026-10-29/README.md)。 + +准备页衔接验证:模拟器 **35 项相关测试全部通过**,其中准备页面 19、完整模拟流程 2、禁飞准备页 5、网络保护 6、原开拍模拟页 3;覆盖独立模拟入口、同任务导航、重复点击及返回重进。 + +请求合同:`POST /api/app/airport/start-shoot`,参数只传当前 `order_flight_task.id`,与任务页 `shooting.id` 相同,不传航线 ID、`plane_id` 或未约定的 `dry_run`。 + +```json +{"id": 901} +``` + +模拟成功回执主要字段如下;[完整 JSON](docs/9.9.1/start-shoot-mock-2026-10-29/start-shoot-response.mock.json) 保留其余字段。 + +```json +{ + "code": 100000, + "msg": "local mock success", + "data": { + "order_flight_task_id": 901, + "order_flight_task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "plane_id": 201, + "task_uuid": "LOCAL-MOCK-TASK-UUID-901", + "airport_sn": "LOCAL-MOCK-DOCK-201", + "ui": { + "phase": "shooting", + "title": "无人机正在拍摄中(模拟)", + "message": "本地模拟开拍回执,不代表真实设备执行。", + "primary_action": "shooting" + } + } +} +``` + +客户端仅在已注入开拍服务、最近一次读取成功、就绪状态无冲突、`execute_gate.can_execute=true`、`ui.primary_action=start_shoot`、已绑定正数飞机 ID,且没有进行中/已成功/结果未知的开拍请求时启用按钮。POST 成功并核对任务、订单、景区与飞机身份后,单次 GET 同一任务 `shooting`,不恢复轮询。刷新期间保留旧快照,直到回查成功再更新页面,不把 POST 成功直接当成设备开始拍摄。 + +连续点击只发送一次;明确业务拒绝可手动重试,超时、响应无法确认、发送后取消等锁定重复提交,只允许状态回查。页面离开或身份变化后丢弃迟到回执。底部暂停/返航始终不发送请求。 + +2026-10-29 模拟器手动走通 `GET shooting → POST start-shoot → GET shooting`,本地状态由就绪变为拍摄中;全部请求交给 `https://mock.invalid` 对应的内存传输,不会回退真实网络。右上角可查看带 `source=local_mock`、`network_sent=false` 的完整模拟接口记录。 + +验证:**84 项相关测试全部通过**,涵盖开拍 API 10、开拍 ViewModel 12、模拟页面 3、原任务 ViewModel 16、原任务页面 15、阶段展示 14、固定布局 8、禁飞保护 6。成功、业务拒绝、超时、重复点击、身份核对、离页取消及真实传输前阻断均有覆盖。调试参数、[完整三次请求回执与截图](docs/9.9.1/start-shoot-mock-2026-10-29/README.md) 已保存;后端接收和真实设备执行尚未验证。 + ### 7.7 “确认并召唤”:朱工 shoot,复用已创建任务 API:[DroneDockShootAPI.swift](suixinkan/Features/DroneDock/API/DroneDockShootAPI.swift) @@ -1280,6 +1340,8 @@ API:[DroneDockMaterialsAPI.swift](suixinkan/Features/DroneDock/API/DroneDockMa 首页和“我的拍摄订单”的“查看素材”均进入此真实页面。进入页面后先读摘要与点位,再读全部任务;整页刷新重读两个接口。切换点位、切回全部或重试任务只读 `tasks`,顶部整单统计与完整点位标签保持不变。点位刷新后若已不在购买快照内,恢复为全部点位。不会调用 `workbench`,不会创建飞行任务或主动同步素材。 +2026-10-29 已按产品体验网页适配正式页 UI:订单状态徽章、整单次数、点位标签、拍摄记录标题与交付入口、两列素材图、独立勾选、全选和固定底栏。上传状态使用单文件 `upload_status`;任务尚无文件时使用 `material_status` 区分等待、上传中、失败与未知。选择只包含当前点位就绪且地址有效的原素材,以任务 ID+素材 ID 唯一标识,切点/刷新/离页后清空。真实下载、保存相册及上传重试仍未开放;下载过程只在本地演示页验证。详情见[UI 对齐记录](docs/9.9.1/订单素材库UI对齐-2026-10-29.md)。 + ### 8.1 整单摘要与点位:张工 orders/detail `GET /api/yf-handset-app/photog/multi-plane/orders/detail?scenic_id=271&order_number=TEST-ORDER-004` @@ -1389,11 +1451,13 @@ API:[DroneDockDeliveryAPI.swift](suixinkan/Features/DroneDock/API/DroneDockDel | 入口 | 进入交付页后的行为 | | --- | --- | -| 我的拍摄订单 → 交付成片 | 传当前订单,重新读取摘要与全部任务;由用户选择点位、任务和视频,不默认绑定第一条任务 | +| 我的拍摄订单 → 交付成片 | 先打开交付方式弹窗,无新增请求;选择云端后在同一弹窗内读取摘要与全部任务;用户选择点位、任务和视频,不默认绑定第一条任务 | | 订单素材库 → 某任务的交付成片/替换成片 | 传当前订单与该任务 ID,从最新任务列表定位并预选点位、任务;原任务失效时提示重新选择 | 入口依据后端 `can_upload_film` 显示。交付页还会核对 `order_status=20`,提交前和视频上传后均重新读取权限与任务,避免使用进入页面时的过期状态。返回订单列表或素材库会刷新对应数据。 +2026-10-30 交互调整:仅取消交付方式弹窗保留原订单列表和筛选,不额外刷新;进入云端后关闭弹窗才刷新订单。面对面闪传只展示待接入说明。云端禁止下拉绕过退出确认,上传处理中关闭需确认停止。见[弹窗适配记录](docs/9.9.1/订单交付方式弹窗-2026-10-30.md)。 + 1. 进入、刷新时依次调用 `orders/detail` 和不带点位参数的 `tasks`;切点位只筛选已读取的全部任务。 2. 用户选择单个视频,复制到本功能临时目录并检查视频轨道、大小和格式;支持相册或文件选择、本地预览与移除。当前沿用 App 的 2 GB 文件上限。 3. 点击上传后重新读取摘要、任务;已有成片先弹出替换确认。 @@ -1499,7 +1563,7 @@ GET /api/yf-handset-app/photog/multi-plane/tasks?scenic_id=271&order_number=TEST | 页面/功能 | 当前实现状态 | 文档中的后续候选接口与提供人 | 返回 JSON 记录 | | --- | --- | --- | --- | | 历史演示订单页 `DroneShootingOrdersViewController` | 仅演示流程继续使用本地数据;正式首页“查看全部”已进入真实 `DroneDockOrdersViewController` | 正式页张工 `GET /orders` 已接入,见 4.4 | 演示数据不能作为接口实测证据 | -| 拍摄任务页 `DroneDockShootingTaskViewController` | 顶部和底部固定,中间按状态组合且无滚动;进入、可见时返回前台或导航栏/中间刷新各只读一次,无下拉刷新或定时轮询;明确完成态可查看订单素材 | 朱工 `/airport/shooting` 已接入;图传 `/airport/live`、开始拍摄 `/airport/start-shoot`、控制 `/airport/command` 尚未接入,当前不另调 `/airport/status` | 类型 25 真实读取成功见 7.6;任务 6 已有真实召唤成功回执,尚无开始拍摄或控制成功记录 | +| 拍摄任务页 `DroneDockShootingTaskViewController` | 顶部和底部固定,中间按状态组合且无滚动;进入、可见时返回前台或导航栏/中间刷新各只读一次,无下拉刷新或定时轮询;明确完成态可查看订单素材 | 朱工 `/airport/shooting` 已接入;`/airport/start-shoot` 已实现纯本地模拟、真实入口禁用;图传 `/airport/live`、控制 `/airport/command` 尚未接入,当前不另调 `/airport/status` | 类型 25 真实读取成功见 7.6;开始拍摄模拟回执见 7.6.2;尚无真实开始拍摄或控制成功记录 | | 历史素材演示/下载 `DroneMaterialsViewController`、`DroneMaterialPreviewViewController` | 仅演示流程保留;正式入口已切换真实素材库,尚未接入批量下载或保存相册 | 下载可使用张工返回的有效文件 URL;当前正式页面只支持查看与预览 | 正式页面响应见第 8 节 | | 历史交付演示 `DroneDeliveryUploadViewController`、`DroneDeliveryReviewViewController` | 仅演示流程保留;正式上传使用第 9 节新共用页,游客确认尚未接入 | 后续张工 `POST /orders/confirm-code`、`GET /orders/detail` | 正式上传记录见第 9 节;暂无游客确认实测响应 | | 收款页“线下收款” | 跳转既有 `OfflineCollectionRegistrationViewController` | 复用原通用线下收款模块,不属于本次机巢类型 25 专用接口接入 | 本文未审计该旧模块 JSON,不将它记为新接口已打通 |