合并 9.9.1 机巢工作台与拍摄交付流程 #1
@@ -0,0 +1,70 @@
|
|||||||
|
{
|
||||||
|
"code": 100000,
|
||||||
|
"data": {
|
||||||
|
"connected": true,
|
||||||
|
"has_idle": true,
|
||||||
|
"has_shooting": false,
|
||||||
|
"planes": [
|
||||||
|
{
|
||||||
|
"battery_label": "电量 93%",
|
||||||
|
"battery_percent": 93,
|
||||||
|
"can_fly": true,
|
||||||
|
"id": 58,
|
||||||
|
"is_receive_order": 1,
|
||||||
|
"name": "测试设备 58",
|
||||||
|
"online_status": 1,
|
||||||
|
"sn_number": "TEST-PLANE-58",
|
||||||
|
"status_text": "空闲 · 电量 93%",
|
||||||
|
"task_type": null,
|
||||||
|
"work_status": 1,
|
||||||
|
"work_status_label": "空闲"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"battery_label": "",
|
||||||
|
"battery_percent": null,
|
||||||
|
"can_fly": false,
|
||||||
|
"id": 61,
|
||||||
|
"is_receive_order": 1,
|
||||||
|
"name": "测试设备 61",
|
||||||
|
"online_status": 2,
|
||||||
|
"sn_number": "TEST-PLANE-61",
|
||||||
|
"status_text": "离线",
|
||||||
|
"task_type": null,
|
||||||
|
"work_status": 0,
|
||||||
|
"work_status_label": "离线"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"battery_label": "",
|
||||||
|
"battery_percent": null,
|
||||||
|
"can_fly": false,
|
||||||
|
"id": 57,
|
||||||
|
"is_receive_order": 2,
|
||||||
|
"name": "测试设备 57",
|
||||||
|
"online_status": 2,
|
||||||
|
"sn_number": "TEST-PLANE-57",
|
||||||
|
"status_text": "离线",
|
||||||
|
"task_type": null,
|
||||||
|
"work_status": 0,
|
||||||
|
"work_status_label": "离线"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"poll_hint_ms": 5000,
|
||||||
|
"recommend": {
|
||||||
|
"battery_label": "电量 93%",
|
||||||
|
"battery_percent": 93,
|
||||||
|
"can_fly": true,
|
||||||
|
"id": 58,
|
||||||
|
"is_receive_order": 1,
|
||||||
|
"name": "测试设备 58",
|
||||||
|
"online_status": 1,
|
||||||
|
"sn_number": "TEST-PLANE-58",
|
||||||
|
"status_text": "空闲 · 电量 93%",
|
||||||
|
"task_type": null,
|
||||||
|
"work_status": 1,
|
||||||
|
"work_status_label": "空闲"
|
||||||
|
},
|
||||||
|
"scenic_id": 271
|
||||||
|
},
|
||||||
|
"msg": "success",
|
||||||
|
"time": "2026-10-29 11:06:12"
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"code": 180031,
|
||||||
|
"msg": "无法获取机场状态,暂时不可起飞",
|
||||||
|
"data": [],
|
||||||
|
"time": "2026-10-29 15:58:52"
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
{
|
||||||
|
"code": 100000,
|
||||||
|
"msg": "success",
|
||||||
|
"data": {
|
||||||
|
"order_flight_task": {
|
||||||
|
"id": 6,
|
||||||
|
"order_id": 0,
|
||||||
|
"order_number": "TEST-ORDER-004",
|
||||||
|
"scenic_id": 271,
|
||||||
|
"store_id": 38,
|
||||||
|
"store_user_id": 51,
|
||||||
|
"scenic_spot_id": 412,
|
||||||
|
"air_line_id": 302,
|
||||||
|
"plane_id": 61,
|
||||||
|
"airport_sn": "TEST-PLANE-61",
|
||||||
|
"wayline_task_id": 1926,
|
||||||
|
"task_uuid": "00000000-0000-4000-8000-000000001926",
|
||||||
|
"seq": 6,
|
||||||
|
"spot_attempt": 6,
|
||||||
|
"status": 20,
|
||||||
|
"status_label": "执行中",
|
||||||
|
"result_code": "",
|
||||||
|
"result_message": "",
|
||||||
|
"deducted": 0,
|
||||||
|
"started_at": "2026-10-29 16:03:30",
|
||||||
|
"finished_at": null,
|
||||||
|
"medias": []
|
||||||
|
},
|
||||||
|
"order_progress": {
|
||||||
|
"order_number": "TEST-ORDER-004",
|
||||||
|
"package_name": "单次航拍 · 含 1 次拍摄",
|
||||||
|
"shot_total": 1,
|
||||||
|
"shot_used": 0,
|
||||||
|
"shot_remain": 1,
|
||||||
|
"status_label": "待拍摄"
|
||||||
|
},
|
||||||
|
"task_id": 1926,
|
||||||
|
"task_uuid": "00000000-0000-4000-8000-000000001926",
|
||||||
|
"plane_id": 61,
|
||||||
|
"airport_sn": "TEST-PLANE-61",
|
||||||
|
"air_line_id": 302,
|
||||||
|
"air_line_name": "天门寻梦",
|
||||||
|
"ui": {
|
||||||
|
"phase": "arrived_pending_start",
|
||||||
|
"title": "无人机已到达",
|
||||||
|
"message": "是否开始拍摄?确认游客站位与取景后开始",
|
||||||
|
"primary_action": "start_shoot",
|
||||||
|
"commands": [
|
||||||
|
{
|
||||||
|
"command": "flighttask_pause",
|
||||||
|
"label": "紧急暂停",
|
||||||
|
"sub": "悬停待命"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "return_home",
|
||||||
|
"label": "立即返航",
|
||||||
|
"sub": "中断任务"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"time": "2026-10-29 16:03:31"
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"code": 100099,
|
||||||
|
"msg": "不支持的订单类型",
|
||||||
|
"data": [],
|
||||||
|
"time": "2026-10-29 15:34:31"
|
||||||
|
}
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"code": 100099,
|
||||||
|
"msg": "不支持的订单类型",
|
||||||
|
"data": [],
|
||||||
|
"time": "2026-10-29 15:41:41"
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"code": 100099,
|
||||||
|
"data": [],
|
||||||
|
"msg": "多点位航拍请使用专用订单接口",
|
||||||
|
"time": "2026-10-29 14:14:42"
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
{
|
||||||
|
"code": 100000,
|
||||||
|
"data": {
|
||||||
|
"air_line": {
|
||||||
|
"estimated_fly_time": 376,
|
||||||
|
"fly_type": 1,
|
||||||
|
"id": 302,
|
||||||
|
"line_video_duration": 25,
|
||||||
|
"name": "天门寻梦",
|
||||||
|
"scenic_spot_id": 412
|
||||||
|
},
|
||||||
|
"airport_sn": "",
|
||||||
|
"airport_status": {
|
||||||
|
"sn": "TEST-PLANE-58",
|
||||||
|
"status": 1,
|
||||||
|
"task_type": null,
|
||||||
|
"work_status_label": "空闲"
|
||||||
|
},
|
||||||
|
"current_plane": {
|
||||||
|
"battery_label": "电量 93%",
|
||||||
|
"battery_percent": 93,
|
||||||
|
"can_fly": true,
|
||||||
|
"id": 58,
|
||||||
|
"is_receive_order": 1,
|
||||||
|
"name": "测试设备 58",
|
||||||
|
"online_status": 1,
|
||||||
|
"sn_number": "TEST-PLANE-58",
|
||||||
|
"status_text": "空闲 · 电量 93%",
|
||||||
|
"task_type": null,
|
||||||
|
"work_status": 1,
|
||||||
|
"work_status_label": "空闲"
|
||||||
|
},
|
||||||
|
"execute_gate": {
|
||||||
|
"can_execute": false,
|
||||||
|
"code": "wayline_missing",
|
||||||
|
"message": "航线任务未关联,请先完成召唤起飞",
|
||||||
|
"primary_action": "blocked",
|
||||||
|
"primary_action_label": "航线任务未关联,请先完成召唤起飞"
|
||||||
|
},
|
||||||
|
"header": {
|
||||||
|
"order_number": "TEST-ORDER-004",
|
||||||
|
"package_name": "单次航拍 · 含 1 次拍摄",
|
||||||
|
"shot_remain": 1,
|
||||||
|
"shot_total": 1,
|
||||||
|
"title": "天门寻梦 · 天门寻梦",
|
||||||
|
"tourist_label": "游客 130****0004",
|
||||||
|
"tourist_phone_mask": "130****0004"
|
||||||
|
},
|
||||||
|
"metrics": [
|
||||||
|
{
|
||||||
|
"key": "battery",
|
||||||
|
"label": "电池电量",
|
||||||
|
"raw": 93,
|
||||||
|
"value": "93%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "env_temp",
|
||||||
|
"label": "环境温度",
|
||||||
|
"raw": null,
|
||||||
|
"value": "—"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "wind_speed",
|
||||||
|
"label": "风速",
|
||||||
|
"raw": 0,
|
||||||
|
"value": "0m/s"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "rainfall",
|
||||||
|
"label": "雨量",
|
||||||
|
"raw": null,
|
||||||
|
"value": "—"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "signal",
|
||||||
|
"label": "信号状态",
|
||||||
|
"raw": null,
|
||||||
|
"value": "—"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "satellite",
|
||||||
|
"label": "搜星状态",
|
||||||
|
"raw": 32,
|
||||||
|
"value": "32颗"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"order_flight_task": {
|
||||||
|
"air_line_id": 302,
|
||||||
|
"airport_sn": "",
|
||||||
|
"deducted": 0,
|
||||||
|
"finished_at": null,
|
||||||
|
"id": 1,
|
||||||
|
"medias": [],
|
||||||
|
"order_id": 0,
|
||||||
|
"order_number": "TEST-ORDER-004",
|
||||||
|
"plane_id": 0,
|
||||||
|
"result_code": "",
|
||||||
|
"result_message": "",
|
||||||
|
"scenic_id": 271,
|
||||||
|
"scenic_spot_id": 412,
|
||||||
|
"seq": 1,
|
||||||
|
"spot_attempt": 1,
|
||||||
|
"started_at": null,
|
||||||
|
"status": 10,
|
||||||
|
"status_label": "待执行",
|
||||||
|
"store_id": 38,
|
||||||
|
"store_user_id": 51,
|
||||||
|
"task_uuid": "",
|
||||||
|
"wayline_task_id": 0
|
||||||
|
},
|
||||||
|
"order_type": 25,
|
||||||
|
"order_type_label": "多点位航拍",
|
||||||
|
"plane_id": 0,
|
||||||
|
"plane_status": {
|
||||||
|
"connected": true,
|
||||||
|
"has_idle": true,
|
||||||
|
"has_shooting": false,
|
||||||
|
"planes": [
|
||||||
|
{
|
||||||
|
"battery_label": "",
|
||||||
|
"battery_percent": null,
|
||||||
|
"can_fly": true,
|
||||||
|
"id": 58,
|
||||||
|
"is_receive_order": 1,
|
||||||
|
"name": "测试设备 58",
|
||||||
|
"online_status": 1,
|
||||||
|
"sn_number": "TEST-PLANE-58",
|
||||||
|
"status_text": "空闲",
|
||||||
|
"task_type": null,
|
||||||
|
"work_status": 1,
|
||||||
|
"work_status_label": "空闲"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"battery_label": "",
|
||||||
|
"battery_percent": null,
|
||||||
|
"can_fly": false,
|
||||||
|
"id": 61,
|
||||||
|
"is_receive_order": 1,
|
||||||
|
"name": "测试设备 61",
|
||||||
|
"online_status": 2,
|
||||||
|
"sn_number": "TEST-PLANE-61",
|
||||||
|
"status_text": "离线",
|
||||||
|
"task_type": null,
|
||||||
|
"work_status": 0,
|
||||||
|
"work_status_label": "离线"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"battery_label": "",
|
||||||
|
"battery_percent": null,
|
||||||
|
"can_fly": false,
|
||||||
|
"id": 57,
|
||||||
|
"is_receive_order": 2,
|
||||||
|
"name": "测试设备 57",
|
||||||
|
"online_status": 2,
|
||||||
|
"sn_number": "TEST-PLANE-57",
|
||||||
|
"status_text": "离线",
|
||||||
|
"task_type": null,
|
||||||
|
"work_status": 0,
|
||||||
|
"work_status_label": "离线"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"poll_hint_ms": 5000,
|
||||||
|
"recommend": {
|
||||||
|
"battery_label": "电量 93%",
|
||||||
|
"battery_percent": 93,
|
||||||
|
"can_fly": true,
|
||||||
|
"id": 58,
|
||||||
|
"is_receive_order": 1,
|
||||||
|
"name": "测试设备 58",
|
||||||
|
"online_status": 1,
|
||||||
|
"sn_number": "TEST-PLANE-58",
|
||||||
|
"status_text": "空闲 · 电量 93%",
|
||||||
|
"task_type": null,
|
||||||
|
"work_status": 1,
|
||||||
|
"work_status_label": "空闲"
|
||||||
|
},
|
||||||
|
"scenic_id": 271
|
||||||
|
},
|
||||||
|
"scenic": {
|
||||||
|
"id": 271,
|
||||||
|
"name": "北大科技园"
|
||||||
|
},
|
||||||
|
"scenic_spot": {
|
||||||
|
"id": 412,
|
||||||
|
"name": "天门寻梦"
|
||||||
|
},
|
||||||
|
"task": {
|
||||||
|
"id": 1,
|
||||||
|
"status": 10,
|
||||||
|
"status_label": "待执行",
|
||||||
|
"task_uuid": "",
|
||||||
|
"wayline_status": 0,
|
||||||
|
"wayline_status_label": "",
|
||||||
|
"wayline_task_id": 0
|
||||||
|
},
|
||||||
|
"ui": {
|
||||||
|
"commands": [
|
||||||
|
{
|
||||||
|
"command": "flighttask_pause",
|
||||||
|
"label": "紧急暂停",
|
||||||
|
"sub": "悬停待命"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "return_home",
|
||||||
|
"label": "立即返航",
|
||||||
|
"sub": "中断任务"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"message": "航线任务未关联,请先完成召唤起飞",
|
||||||
|
"phase": "blocked",
|
||||||
|
"primary_action": "blocked",
|
||||||
|
"primary_action_label": "航线任务未关联,请先完成召唤起飞",
|
||||||
|
"title": "航线任务未关联,请先完成召唤起飞"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"msg": "success",
|
||||||
|
"time": "2026-10-29 15:07:25"
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
{
|
||||||
|
"code": 100000,
|
||||||
|
"msg": "success",
|
||||||
|
"data": {
|
||||||
|
"order_flight_task": {
|
||||||
|
"id": 6,
|
||||||
|
"order_id": 0,
|
||||||
|
"order_number": "TEST-ORDER-004",
|
||||||
|
"scenic_id": 271,
|
||||||
|
"store_id": 38,
|
||||||
|
"store_user_id": 51,
|
||||||
|
"scenic_spot_id": 412,
|
||||||
|
"air_line_id": 302,
|
||||||
|
"plane_id": 61,
|
||||||
|
"airport_sn": "TEST-PLANE-61",
|
||||||
|
"wayline_task_id": 1926,
|
||||||
|
"task_uuid": "00000000-0000-4000-8000-000000001926",
|
||||||
|
"seq": 6,
|
||||||
|
"spot_attempt": 6,
|
||||||
|
"status": 20,
|
||||||
|
"status_label": "执行中",
|
||||||
|
"result_code": "",
|
||||||
|
"result_message": "",
|
||||||
|
"deducted": 0,
|
||||||
|
"started_at": "2026-10-29 16:03:30",
|
||||||
|
"finished_at": null,
|
||||||
|
"medias": []
|
||||||
|
},
|
||||||
|
"order_type": 25,
|
||||||
|
"order_type_label": "多点位航拍",
|
||||||
|
"task": {
|
||||||
|
"id": 6,
|
||||||
|
"task_uuid": "00000000-0000-4000-8000-000000001926",
|
||||||
|
"wayline_task_id": 1926,
|
||||||
|
"wayline_status": 91,
|
||||||
|
"wayline_status_label": "执行失败",
|
||||||
|
"status": 20,
|
||||||
|
"status_label": "执行中"
|
||||||
|
},
|
||||||
|
"scenic": {
|
||||||
|
"id": 271,
|
||||||
|
"name": "北大科技园"
|
||||||
|
},
|
||||||
|
"scenic_spot": {
|
||||||
|
"id": 412,
|
||||||
|
"name": "天门寻梦"
|
||||||
|
},
|
||||||
|
"air_line": {
|
||||||
|
"id": 302,
|
||||||
|
"name": "天门寻梦",
|
||||||
|
"scenic_spot_id": 412,
|
||||||
|
"fly_type": 1,
|
||||||
|
"estimated_fly_time": 376,
|
||||||
|
"line_video_duration": 25
|
||||||
|
},
|
||||||
|
"header": {
|
||||||
|
"title": "天门寻梦 · 天门寻梦",
|
||||||
|
"order_number": "TEST-ORDER-004",
|
||||||
|
"tourist_phone_mask": "130****0004",
|
||||||
|
"tourist_label": "游客 130****0004",
|
||||||
|
"package_name": "单次航拍 · 含 1 次拍摄",
|
||||||
|
"shot_total": 1,
|
||||||
|
"shot_remain": 1
|
||||||
|
},
|
||||||
|
"airport_sn": "TEST-PLANE-61",
|
||||||
|
"plane_id": 61,
|
||||||
|
"current_plane": {
|
||||||
|
"id": 61,
|
||||||
|
"sn_number": "TEST-PLANE-61",
|
||||||
|
"name": "测试设备 61",
|
||||||
|
"online_status": 2,
|
||||||
|
"is_receive_order": 1,
|
||||||
|
"work_status": 0,
|
||||||
|
"work_status_label": "离线",
|
||||||
|
"task_type": null,
|
||||||
|
"battery_percent": 94,
|
||||||
|
"battery_label": "电量 94%",
|
||||||
|
"can_fly": false,
|
||||||
|
"status_text": "离线 · 电量 94%"
|
||||||
|
},
|
||||||
|
"plane_status": {
|
||||||
|
"scenic_id": 271,
|
||||||
|
"planes": [
|
||||||
|
{
|
||||||
|
"id": 61,
|
||||||
|
"sn_number": "TEST-PLANE-61",
|
||||||
|
"name": "测试设备 61",
|
||||||
|
"online_status": 2,
|
||||||
|
"is_receive_order": 1,
|
||||||
|
"work_status": 0,
|
||||||
|
"work_status_label": "离线",
|
||||||
|
"task_type": null,
|
||||||
|
"battery_percent": 94,
|
||||||
|
"battery_label": "电量 94%",
|
||||||
|
"can_fly": false,
|
||||||
|
"status_text": "离线 · 电量 94%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 58,
|
||||||
|
"sn_number": "TEST-PLANE-58",
|
||||||
|
"name": "测试设备 58",
|
||||||
|
"online_status": 1,
|
||||||
|
"is_receive_order": 2,
|
||||||
|
"work_status": 1,
|
||||||
|
"work_status_label": "空闲",
|
||||||
|
"task_type": null,
|
||||||
|
"battery_percent": null,
|
||||||
|
"battery_label": "",
|
||||||
|
"can_fly": false,
|
||||||
|
"status_text": "空闲"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 57,
|
||||||
|
"sn_number": "TEST-PLANE-57",
|
||||||
|
"name": "测试设备 57",
|
||||||
|
"online_status": 2,
|
||||||
|
"is_receive_order": 2,
|
||||||
|
"work_status": 0,
|
||||||
|
"work_status_label": "离线",
|
||||||
|
"task_type": null,
|
||||||
|
"battery_percent": null,
|
||||||
|
"battery_label": "",
|
||||||
|
"can_fly": false,
|
||||||
|
"status_text": "离线"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"recommend": {
|
||||||
|
"id": 61,
|
||||||
|
"sn_number": "TEST-PLANE-61",
|
||||||
|
"name": "测试设备 61",
|
||||||
|
"online_status": 2,
|
||||||
|
"is_receive_order": 1,
|
||||||
|
"work_status": 0,
|
||||||
|
"work_status_label": "离线",
|
||||||
|
"task_type": null,
|
||||||
|
"battery_percent": 94,
|
||||||
|
"battery_label": "电量 94%",
|
||||||
|
"can_fly": false,
|
||||||
|
"status_text": "离线 · 电量 94%"
|
||||||
|
},
|
||||||
|
"has_idle": true,
|
||||||
|
"has_shooting": false,
|
||||||
|
"connected": true,
|
||||||
|
"poll_hint_ms": 5000
|
||||||
|
},
|
||||||
|
"metrics": [
|
||||||
|
{
|
||||||
|
"key": "battery",
|
||||||
|
"label": "电池电量",
|
||||||
|
"value": "94%",
|
||||||
|
"raw": 94
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "env_temp",
|
||||||
|
"label": "环境温度",
|
||||||
|
"value": "10.3℃",
|
||||||
|
"raw": 10.3
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "wind_speed",
|
||||||
|
"label": "风速",
|
||||||
|
"value": "0m/s",
|
||||||
|
"raw": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "rainfall",
|
||||||
|
"label": "雨量",
|
||||||
|
"value": "无雨",
|
||||||
|
"raw": "no_rain"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "signal",
|
||||||
|
"label": "信号状态",
|
||||||
|
"value": "信号良好",
|
||||||
|
"raw": "信号良好"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "satellite",
|
||||||
|
"label": "搜星状态",
|
||||||
|
"value": "17颗",
|
||||||
|
"raw": 17
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"airport_status": {
|
||||||
|
"sn": "TEST-PLANE-61",
|
||||||
|
"status": 0,
|
||||||
|
"task_type": null,
|
||||||
|
"work_status_label": "离线"
|
||||||
|
},
|
||||||
|
"execute_gate": {
|
||||||
|
"can_execute": false,
|
||||||
|
"code": "wayline_not_shooting",
|
||||||
|
"message": "航线任务状态不可拍摄(当前:执行失败)",
|
||||||
|
"primary_action": "blocked",
|
||||||
|
"primary_action_label": "航线任务状态不可拍摄(当前:执行失败)"
|
||||||
|
},
|
||||||
|
"ui": {
|
||||||
|
"phase": "blocked",
|
||||||
|
"title": "航线任务状态不可拍摄(当前:执行失败)",
|
||||||
|
"message": "航线任务状态不可拍摄(当前:执行失败)",
|
||||||
|
"primary_action": "blocked",
|
||||||
|
"primary_action_label": "航线任务状态不可拍摄(当前:执行失败)",
|
||||||
|
"commands": [
|
||||||
|
{
|
||||||
|
"command": "flighttask_pause",
|
||||||
|
"label": "紧急暂停",
|
||||||
|
"sub": "悬停待命"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "return_home",
|
||||||
|
"label": "立即返航",
|
||||||
|
"sub": "中断任务"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"time": "2026-10-29 16:04:52"
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"code": 100000,
|
||||||
|
"msg": "success",
|
||||||
|
"data": {
|
||||||
|
"order_number": "TEST-ORDER-004",
|
||||||
|
"project_id": 386,
|
||||||
|
"project_name": "多点位航拍",
|
||||||
|
"created_at": "2026-10-27 17:39:10",
|
||||||
|
"user_phone": "130****0004",
|
||||||
|
"shoot_count": 5,
|
||||||
|
"shot_count": 0,
|
||||||
|
"remaining_count": 5,
|
||||||
|
"shoot_status": "processing",
|
||||||
|
"order_status": 20,
|
||||||
|
"material_status": 0,
|
||||||
|
"film_count": 0,
|
||||||
|
"can_create_task": true,
|
||||||
|
"can_upload_film": true,
|
||||||
|
"can_confirm": false,
|
||||||
|
"confirm_status": 0,
|
||||||
|
"confirmed_at": null,
|
||||||
|
"task_id": 6
|
||||||
|
},
|
||||||
|
"time": "2026-10-29 16:03:01"
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"code": 100000,
|
||||||
|
"data": {
|
||||||
|
"can_confirm": false,
|
||||||
|
"can_create_task": true,
|
||||||
|
"can_upload_film": true,
|
||||||
|
"confirm_status": 0,
|
||||||
|
"confirmed_at": null,
|
||||||
|
"created_at": "2026-10-27 17:39:10",
|
||||||
|
"film_count": 0,
|
||||||
|
"material_status": 0,
|
||||||
|
"order_number": "TEST-ORDER-004",
|
||||||
|
"order_status": 20,
|
||||||
|
"project_id": 386,
|
||||||
|
"project_name": "多点位航拍",
|
||||||
|
"remaining_count": 5,
|
||||||
|
"shoot_count": 5,
|
||||||
|
"shoot_status": "processing",
|
||||||
|
"shot_count": 0,
|
||||||
|
"task_id": 1,
|
||||||
|
"user_phone": "130****0004"
|
||||||
|
},
|
||||||
|
"msg": "success",
|
||||||
|
"time": "2026-10-29 11:56:26"
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 准备页的独立无人机状态只读服务,不读取定位或创建飞行任务。
|
||||||
|
protocol DroneDockPlaneStatusServing: Sendable {
|
||||||
|
/// 读取当前景区可展示的设备状态与实时电量。
|
||||||
|
@MainActor
|
||||||
|
func planeStatus(scenicID: Int) async throws -> DroneDockPlaneStatusResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 朱工 plane-status 接口适配,复用统一 Token 与业务错误处理。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockPlaneStatusAPI: DroneDockPlaneStatusServing {
|
||||||
|
private let client: APIClient
|
||||||
|
|
||||||
|
/// 注入统一客户端,便于替换网络测试依赖。
|
||||||
|
init(client: APIClient) { self.client = client }
|
||||||
|
|
||||||
|
/// 明确请求实时电量,返回景区不一致时拒绝将状态回填当前页面。
|
||||||
|
func planeStatus(scenicID: Int) async throws -> DroneDockPlaneStatusResponse {
|
||||||
|
guard scenicID > 0 else { throw APIError.networkFailed("请先选择景区") }
|
||||||
|
let response: DroneDockPlaneStatusResponse = try await client.send(APIRequest(
|
||||||
|
method: .get,
|
||||||
|
path: "/api/app/airport/plane-status",
|
||||||
|
queryItems: [URLQueryItem(name: "scenic_id", value: String(scenicID)),
|
||||||
|
URLQueryItem(name: "live_battery", value: "1")]
|
||||||
|
))
|
||||||
|
guard response.scenicID == scenicID else {
|
||||||
|
throw APIError.decodeFailed("无人机状态与当前景区不一致,请刷新重试")
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 对已创建的订单飞行任务请求召唤,复用该任务及服务端锁定的飞机。
|
||||||
|
protocol DroneDockShootServing: Sendable {
|
||||||
|
/// 只提交已有任务 ID;调用方负责防止重复提交及核对不确定结果。
|
||||||
|
@MainActor
|
||||||
|
func shoot(taskID: Int) async throws -> DroneDockShootResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 朱工 shoot 接口适配,业务成功仅表示接口受理结果,不推断飞机已经到达。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockShootAPI: DroneDockShootServing {
|
||||||
|
private let client: APIClient
|
||||||
|
|
||||||
|
/// 注入统一网络客户端,沿用登录凭证、HTTP 与业务码处理。
|
||||||
|
init(client: APIClient) { self.client = client }
|
||||||
|
|
||||||
|
/// 仅发送一次召唤 POST;不创建任务、不重试、不修改任务已选航线。
|
||||||
|
func shoot(taskID: Int) async throws -> DroneDockShootResponse {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请先创建任务") }
|
||||||
|
do {
|
||||||
|
return try await client.send(APIRequest(
|
||||||
|
method: .post,
|
||||||
|
path: "/api/app/airport/shoot",
|
||||||
|
body: ShootBody(taskID: taskID)
|
||||||
|
))
|
||||||
|
} catch APIError.emptyData {
|
||||||
|
// 统一客户端仅在 HTTP 和业务码均成功后抛 emptyData;此接口尚未约定成功 data 结构。
|
||||||
|
return DroneDockShootResponse(dataJSON: nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 本轮联调仅发送任务身份和非重启标记,完全省略 plane_id 与航线覆盖字段。
|
||||||
|
private struct ShootBody: Encodable {
|
||||||
|
let taskID: Int
|
||||||
|
let restart = false
|
||||||
|
|
||||||
|
/// 朱工已建任务召唤参数映射。
|
||||||
|
private enum CodingKeys: String, CodingKey {
|
||||||
|
case taskID = "id", restart
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 朱工拍摄任务信息只读服务,读取张工已创建的任务,不发送飞行控制。
|
||||||
|
protocol DroneDockShootingServing: Sendable {
|
||||||
|
/// 按已有任务 ID 获取拍摄页信息;读取失败后可对同一 ID 再次读取。
|
||||||
|
@MainActor
|
||||||
|
func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
/// shooting GET 接口适配,鉴权及业务码由统一客户端处理。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockShootingAPI: DroneDockShootingServing {
|
||||||
|
private let client: APIClient
|
||||||
|
|
||||||
|
/// 注入共享网络客户端,便于验证请求只包含已创建任务的查询参数。
|
||||||
|
init(client: APIClient) { self.client = client }
|
||||||
|
|
||||||
|
/// 仅发送一次无请求体的 GET,不创建任务、不召唤、不调用 start-shoot。
|
||||||
|
func shooting(taskID: Int, liveBattery: Bool = true) async throws -> DroneDockShootingResponse {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请先创建任务") }
|
||||||
|
return try await client.send(APIRequest(
|
||||||
|
method: .get,
|
||||||
|
path: "/api/app/airport/shooting",
|
||||||
|
queryItems: [URLQueryItem(name: "id", value: String(taskID)),
|
||||||
|
URLQueryItem(name: "live_battery", value: liveBattery ? "1" : "0")]
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 创建张工订单待飞任务,不派机、不调用朱工召唤或开始拍摄接口。
|
||||||
|
protocol DroneDockTaskCreating: Sendable {
|
||||||
|
/// 提交当前订单购买范围内的点位与航线,返回任务身份及订单摘要。
|
||||||
|
@MainActor
|
||||||
|
func createTask(scenicID: Int, orderNumber: String, spotID: Int, airLineID: Int) async throws -> DroneDockCreatedTask
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 张工 tasks/create 接口,登录凭证和业务码由统一客户端处理。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockTaskCreationAPI: DroneDockTaskCreating {
|
||||||
|
private let client: APIClient
|
||||||
|
|
||||||
|
/// 注入共享网络客户端,测试可替换传输层。
|
||||||
|
init(client: APIClient) { self.client = client }
|
||||||
|
|
||||||
|
/// 单次调用仅发一次创建请求;响应身份异常交由页面核对,不自动重试写入。
|
||||||
|
func createTask(scenicID: Int, orderNumber: String, spotID: Int, airLineID: Int) async throws -> DroneDockCreatedTask {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
guard scenicID > 0, spotID > 0, airLineID > 0, !orderNumber.isEmpty,
|
||||||
|
orderNumber.count <= 128,
|
||||||
|
orderNumber == orderNumber.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||||
|
orderNumber.rangeOfCharacter(from: .controlCharacters) == nil else {
|
||||||
|
throw APIError.networkFailed("缺少有效景区、订单、拍摄点或航线,请刷新准备信息")
|
||||||
|
}
|
||||||
|
let response: DroneDockCreatedTask = try await client.send(APIRequest(
|
||||||
|
method: .post, path: "/api/yf-handset-app/photog/multi-plane/tasks/create",
|
||||||
|
body: CreateTaskBody(scenicID: scenicID, orderNumber: orderNumber, spotID: spotID, airLineID: airLineID)
|
||||||
|
))
|
||||||
|
guard response.order.orderNumber == orderNumber else {
|
||||||
|
throw APIError.decodeFailed("创建任务返回的订单与当前订单不一致,请先核对任务结果")
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建仅提交四项身份,不发送选机、位置或任何起飞参数。
|
||||||
|
private struct CreateTaskBody: Encodable {
|
||||||
|
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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 朱工提供的景区无人机状态快照,推荐设备由服务端选择。
|
||||||
|
struct DroneDockPlaneStatusResponse: Decodable, Equatable, Sendable {
|
||||||
|
/// 本次状态所属景区,必须与请求一致。
|
||||||
|
let scenicID: Int
|
||||||
|
/// 当前景区的设备状态;空数组表示没有设备。
|
||||||
|
let planes: [DroneDockPlaneStatus]
|
||||||
|
/// 服务端推荐设备,缺失时不在客户端另选一台。
|
||||||
|
let recommend: DroneDockPlaneStatus?
|
||||||
|
/// 服务端是否存在空闲设备,未知时不当作 false。
|
||||||
|
let hasIdle: Bool?
|
||||||
|
/// 服务端是否存在拍摄中的设备。
|
||||||
|
let hasShooting: Bool?
|
||||||
|
/// 景区连接状态,缺失时仍为未知。
|
||||||
|
let connected: Bool?
|
||||||
|
/// 服务端建议的轮询间隔;实际定时由页面生命周期控制。
|
||||||
|
let pollHintMS: Int?
|
||||||
|
|
||||||
|
/// 保留 plane-status 原始字段映射,不复用首页的不同状态枚举。
|
||||||
|
private enum CodingKeys: String, CodingKey {
|
||||||
|
case scenicID = "scenic_id", planes, recommend
|
||||||
|
case hasIdle = "has_idle", hasShooting = "has_shooting", connected, pollHintMS = "poll_hint_ms"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 校验景区和设备身份,不把缺失或错误列表当作正常空态。
|
||||||
|
init(from decoder: Decoder) throws {
|
||||||
|
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
|
scenicID = try container.decode(DroneDockPlaneStatusInteger.self, forKey: .scenicID).value
|
||||||
|
guard scenicID > 0 else {
|
||||||
|
throw DecodingError.dataCorruptedError(forKey: .scenicID, in: container, debugDescription: "景区 ID 必须为正整数")
|
||||||
|
}
|
||||||
|
planes = try container.decode([DroneDockPlaneStatus].self, forKey: .planes)
|
||||||
|
guard Set(planes.map(\.id)).count == planes.count else {
|
||||||
|
throw DecodingError.dataCorruptedError(forKey: .planes, in: container, debugDescription: "无人机 ID 重复")
|
||||||
|
}
|
||||||
|
recommend = try container.decodeIfPresent(DroneDockPlaneStatus.self, forKey: .recommend)
|
||||||
|
hasIdle = try container.decodeIfPresent(Bool.self, forKey: .hasIdle)
|
||||||
|
hasShooting = try container.decodeIfPresent(Bool.self, forKey: .hasShooting)
|
||||||
|
connected = try container.decodeIfPresent(Bool.self, forKey: .connected)
|
||||||
|
pollHintMS = try container.decodeIfPresent(DroneDockPlaneStatusInteger.self, forKey: .pollHintMS)?.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 单台无人机的工作状态和电量,仅供准备页展示,不代表召唤许可。
|
||||||
|
struct DroneDockPlaneStatus: Decodable, Equatable, Sendable {
|
||||||
|
/// 后端设备稳定身份。
|
||||||
|
let id: Int
|
||||||
|
/// 设备序列号,不作为飞行任务 ID 使用。
|
||||||
|
let snNumber: String?
|
||||||
|
/// 后端设备名称。
|
||||||
|
let name: String?
|
||||||
|
/// 0 离线、1 空闲、2 拍摄中;其他整数原样保留。
|
||||||
|
let workStatus: Int?
|
||||||
|
/// 后端工作状态名称。
|
||||||
|
let workStatusLabel: String?
|
||||||
|
/// 原始电量百分比,0 与缺失分开表示。
|
||||||
|
let batteryPercent: Int?
|
||||||
|
/// 后端格式化电量文案。
|
||||||
|
let batteryLabel: String?
|
||||||
|
/// 后端设备可飞标记,不据此启用当前订单的召唤按钮。
|
||||||
|
let canFly: Bool?
|
||||||
|
/// 准备页底栏优先展示的完整状态文案。
|
||||||
|
let statusText: String?
|
||||||
|
|
||||||
|
/// 后端字段映射。
|
||||||
|
private enum CodingKeys: String, CodingKey {
|
||||||
|
case id, snNumber = "sn_number", name, workStatus = "work_status", workStatusLabel = "work_status_label"
|
||||||
|
case batteryPercent = "battery_percent", batteryLabel = "battery_label", canFly = "can_fly", statusText = "status_text"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 状态允许未知,设备身份必须明确;不从电量或工作状态推导 can_fly。
|
||||||
|
init(from decoder: Decoder) throws {
|
||||||
|
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
|
id = try container.decode(DroneDockPlaneStatusInteger.self, forKey: .id).value
|
||||||
|
guard id > 0 else {
|
||||||
|
throw DecodingError.dataCorruptedError(forKey: .id, in: container, debugDescription: "无人机 ID 必须为正整数")
|
||||||
|
}
|
||||||
|
snNumber = try container.decodeIfPresent(String.self, forKey: .snNumber)
|
||||||
|
name = try container.decodeIfPresent(String.self, forKey: .name)
|
||||||
|
workStatus = try container.decodeIfPresent(DroneDockPlaneStatusInteger.self, forKey: .workStatus)?.value
|
||||||
|
workStatusLabel = try container.decodeIfPresent(String.self, forKey: .workStatusLabel)
|
||||||
|
batteryPercent = try container.decodeIfPresent(DroneDockPlaneStatusInteger.self, forKey: .batteryPercent)?.value
|
||||||
|
batteryLabel = try container.decodeIfPresent(String.self, forKey: .batteryLabel)
|
||||||
|
canFly = try container.decodeIfPresent(Bool.self, forKey: .canFly)
|
||||||
|
statusText = try container.decodeIfPresent(String.self, forKey: .statusText)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 兼容整数与整数字符串,拒绝布尔值、浮点截断及非法数字。
|
||||||
|
private struct DroneDockPlaneStatusInteger: Decodable {
|
||||||
|
let value: Int
|
||||||
|
|
||||||
|
init(from decoder: Decoder) throws {
|
||||||
|
let container = try decoder.singleValueContainer()
|
||||||
|
if let number = try? container.decode(Int.self) {
|
||||||
|
value = number
|
||||||
|
} else if let text = try? container.decode(String.self), let number = Int(text) {
|
||||||
|
value = number
|
||||||
|
} else {
|
||||||
|
throw DecodingError.dataCorruptedError(in: container, debugDescription: "需要整数或整数字符串")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// shoot 业务成功后的原始 data 回执,不假设或构造飞机、任务及飞行阶段字段。
|
||||||
|
struct DroneDockShootResponse: Decodable, Equatable, Sendable {
|
||||||
|
/// 完整 data JSON;nil 表示统一客户端未提供 data,不补造 null 或空对象。
|
||||||
|
let dataJSON: String?
|
||||||
|
|
||||||
|
/// 保留已格式化回执;业务成功但 data 缺失或为 null 时使用 nil。
|
||||||
|
init(dataJSON: String?) { self.dataJSON = dataJSON }
|
||||||
|
|
||||||
|
/// 支持任意真实 JSON 值,保留未知结构、空数组、布尔值及原始字段类型。
|
||||||
|
init(from decoder: Decoder) throws {
|
||||||
|
let raw = try DroneDockHomeJSONValue(from: decoder)
|
||||||
|
let encoder = JSONEncoder()
|
||||||
|
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
|
||||||
|
dataJSON = String(decoding: try encoder.encode(DroneDockShootJSONSnapshot(value: raw)), as: UTF8.self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 将现有 JSON 值解码结果格式化,完整保留 shoot 尚未约定的成功数据结构。
|
||||||
|
private struct DroneDockShootJSONSnapshot: Encodable {
|
||||||
|
let value: DroneDockHomeJSONValue
|
||||||
|
|
||||||
|
/// 按真实 JSON 类型编码,不推导任务身份或追加外层业务字段。
|
||||||
|
func encode(to encoder: Encoder) throws {
|
||||||
|
var container = encoder.singleValueContainer()
|
||||||
|
switch value {
|
||||||
|
case .object(let object): try container.encode(object.mapValues { DroneDockShootJSONSnapshot(value: $0) })
|
||||||
|
case .array(let array): try container.encode(array.map { DroneDockShootJSONSnapshot(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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 朱工 shooting 的只读快照;完整 data 用于展示,不表示已召唤或已开始拍摄。
|
||||||
|
struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
|
||||||
|
/// 后端若明确提供订单号则保留,不由请求上下文伪造响应身份。
|
||||||
|
let orderNumber: String?
|
||||||
|
/// 实测返回的订单飞行任务身份;存在时必须与请求上下文核对。
|
||||||
|
let orderFlightTask: DroneDockShootingTaskIdentity?
|
||||||
|
/// 实测返回的任务摘要,不以其状态推导控制动作。
|
||||||
|
let task: DroneDockShootingTaskIdentity?
|
||||||
|
/// 拍摄任务关联的景区信息。
|
||||||
|
let scenic: DroneDockShootingPlace?
|
||||||
|
/// 拍摄任务关联的点位信息。
|
||||||
|
let scenicSpot: DroneDockShootingPlace?
|
||||||
|
/// 拍摄任务关联的航线信息。
|
||||||
|
let airLine: DroneDockShootingAirLine?
|
||||||
|
/// 服务端给出的页面标题、游客及套餐文案。
|
||||||
|
let header: DroneDockShootingHeader?
|
||||||
|
/// 服务端给出的当前设备,不由准备页推荐设备替代。
|
||||||
|
let currentPlane: DroneDockShootingPlane?
|
||||||
|
/// 六项读数使用后端格式化文案,保留未知值与真实零值。
|
||||||
|
let metrics: [DroneDockHomeMetric]
|
||||||
|
/// 景区设备连接与轮询建议,不在客户端改选推荐飞机。
|
||||||
|
let planeStatus: DroneDockShootingPlaneStatus?
|
||||||
|
/// 服务端执行门禁只用于展示,本次接入不执行其动作。
|
||||||
|
let executeGate: DroneDockShootingExecuteGate?
|
||||||
|
/// 服务端拍摄阶段和页面提示。
|
||||||
|
let ui: DroneDockShootingUI?
|
||||||
|
/// 完整 data 的格式化 JSON,保留未知字段、空值及原 JSON 类型。
|
||||||
|
let dataJSON: String
|
||||||
|
|
||||||
|
/// 只映射已知展示字段,不假设响应中的任务 ID 位置。
|
||||||
|
private enum CodingKeys: String, CodingKey {
|
||||||
|
case orderNumber = "order_number", orderFlightTask = "order_flight_task", task
|
||||||
|
case scenic, scenicSpot = "scenic_spot", airLine = "air_line"
|
||||||
|
case header, currentPlane = "current_plane", executeGate = "execute_gate", ui
|
||||||
|
case metrics, planeStatus = "plane_status"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 可选字段缺失或为 null 时保持未知;不把缺失执行门禁推断为允许。
|
||||||
|
init(from decoder: Decoder) throws {
|
||||||
|
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
|
orderNumber = try container.decodeIfPresent(String.self, forKey: .orderNumber)
|
||||||
|
orderFlightTask = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .orderFlightTask)
|
||||||
|
task = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .task)
|
||||||
|
scenic = try container.decodeIfPresent(DroneDockShootingPlace.self, forKey: .scenic)
|
||||||
|
scenicSpot = try container.decodeIfPresent(DroneDockShootingPlace.self, forKey: .scenicSpot)
|
||||||
|
airLine = try container.decodeIfPresent(DroneDockShootingAirLine.self, forKey: .airLine)
|
||||||
|
header = try container.decodeIfPresent(DroneDockShootingHeader.self, forKey: .header)
|
||||||
|
currentPlane = try container.decodeIfPresent(DroneDockShootingPlane.self, forKey: .currentPlane)
|
||||||
|
metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? []
|
||||||
|
planeStatus = try container.decodeIfPresent(DroneDockShootingPlaneStatus.self, forKey: .planeStatus)
|
||||||
|
executeGate = try container.decodeIfPresent(DroneDockShootingExecuteGate.self, forKey: .executeGate)
|
||||||
|
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(DroneDockShootingJSONSnapshot(value: raw)), as: UTF8.self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// shooting 实测返回的已有任务身份和状态摘要,各身份仅在实际提供时参与核对。
|
||||||
|
struct DroneDockShootingTaskIdentity: Decodable, Equatable, Sendable {
|
||||||
|
/// 订单飞行任务 ID。
|
||||||
|
let id: Int?
|
||||||
|
/// 任务所属订单号。
|
||||||
|
let orderNumber: String?
|
||||||
|
/// 任务所属景区。
|
||||||
|
let scenicID: Int?
|
||||||
|
/// 后端原始任务状态,不与订单状态混用。
|
||||||
|
let status: Int?
|
||||||
|
/// 服务端任务状态文案。
|
||||||
|
let statusLabel: String?
|
||||||
|
/// 实测航线任务状态,与订单飞行任务状态分别保留。
|
||||||
|
let waylineStatus: Int?
|
||||||
|
/// 服务端航线状态文案;执行失败优先于笼统的订单任务执行中。
|
||||||
|
let waylineStatusLabel: String?
|
||||||
|
|
||||||
|
/// 已确认嵌套任务字段映射。
|
||||||
|
private enum CodingKeys: String, CodingKey {
|
||||||
|
case id, orderNumber = "order_number", scenicID = "scenic_id", status, statusLabel = "status_label"
|
||||||
|
case waylineStatus = "wayline_status", waylineStatusLabel = "wayline_status_label"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// shooting 的设备轮询提示与连接结果;缺失布尔保持未知。
|
||||||
|
struct DroneDockShootingPlaneStatus: Decodable, Equatable, Sendable {
|
||||||
|
/// 后端实际提供的设备列表所属景区。
|
||||||
|
let scenicID: Int?
|
||||||
|
/// 后端景区连接状态。
|
||||||
|
let connected: Bool?
|
||||||
|
/// 保留后端建议间隔;当前任务页不据此安排定时请求。
|
||||||
|
let pollHintMS: Int?
|
||||||
|
|
||||||
|
/// 设备快照字段映射,其余字段仍保留在完整 dataJSON 中。
|
||||||
|
private enum CodingKeys: String, CodingKey {
|
||||||
|
case scenicID = "scenic_id", connected, pollHintMS = "poll_hint_ms"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// shooting 返回的景区或点位信息,缺失身份不由客户端补齐。
|
||||||
|
struct DroneDockShootingPlace: Decodable, Equatable, Sendable {
|
||||||
|
/// 服务端场景身份,未知时为 nil。
|
||||||
|
let id: Int?
|
||||||
|
/// 服务端显示名称。
|
||||||
|
let name: String?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// shooting 返回的航线及其所属点位。
|
||||||
|
struct DroneDockShootingAirLine: Decodable, Equatable, Sendable {
|
||||||
|
/// 服务端航线身份。
|
||||||
|
let id: Int?
|
||||||
|
/// 服务端航线名称。
|
||||||
|
let name: String?
|
||||||
|
/// 航线所属点位,不用于推导当前任务 ID。
|
||||||
|
let scenicSpotID: Int?
|
||||||
|
|
||||||
|
/// 航线字段映射。
|
||||||
|
private enum CodingKeys: String, CodingKey { case id, name, scenicSpotID = "scenic_spot_id" }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// shooting 拍摄页的服务端摘要文案。
|
||||||
|
struct DroneDockShootingHeader: Decodable, Equatable, Sendable {
|
||||||
|
/// 实测摘要返回的订单身份,不能忽略其与请求订单的一致性。
|
||||||
|
let orderNumber: String?
|
||||||
|
/// 页面主标题。
|
||||||
|
let title: String?
|
||||||
|
/// 服务端提供的游客显示文案。
|
||||||
|
let touristLabel: String?
|
||||||
|
/// 订单套餐显示文案。
|
||||||
|
let packageName: String?
|
||||||
|
|
||||||
|
/// 页面摘要字段映射。
|
||||||
|
private enum CodingKeys: String, CodingKey {
|
||||||
|
case orderNumber = "order_number", title, touristLabel = "tourist_label", packageName = "package_name"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// shooting 当前设备的展示信息,不代表调用方已发送飞行指令。
|
||||||
|
struct DroneDockShootingPlane: Decodable, Equatable, Sendable {
|
||||||
|
/// 当前设备身份。
|
||||||
|
let id: Int?
|
||||||
|
/// 当前设备序列号。
|
||||||
|
let snNumber: String?
|
||||||
|
/// 服务端工作状态文案。
|
||||||
|
let workStatusLabel: String?
|
||||||
|
/// 服务端完整状态文案。
|
||||||
|
let statusText: String?
|
||||||
|
|
||||||
|
/// 当前设备字段映射。
|
||||||
|
private enum CodingKeys: String, CodingKey {
|
||||||
|
case id, snNumber = "sn_number", workStatusLabel = "work_status_label", statusText = "status_text"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// shooting 执行门禁的原始结果;false 与未知分别保留。
|
||||||
|
struct DroneDockShootingExecuteGate: Decodable, Equatable, Sendable {
|
||||||
|
/// 服务端明确的执行许可,不从文案或 action 推导。
|
||||||
|
let canExecute: Bool?
|
||||||
|
/// 服务端门禁原因码。
|
||||||
|
let code: String?
|
||||||
|
/// 服务端门禁说明。
|
||||||
|
let message: String?
|
||||||
|
/// 服务端建议动作,本阶段仅展示。
|
||||||
|
let primaryAction: String?
|
||||||
|
/// 服务端建议动作名称。
|
||||||
|
let primaryActionLabel: String?
|
||||||
|
|
||||||
|
/// 门禁字段映射。
|
||||||
|
private enum CodingKeys: String, CodingKey {
|
||||||
|
case canExecute = "can_execute", code, message
|
||||||
|
case primaryAction = "primary_action", primaryActionLabel = "primary_action_label"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// shooting 返回的拍摄阶段显示信息。
|
||||||
|
struct DroneDockShootingUI: Decodable, Equatable, Sendable {
|
||||||
|
/// 原始阶段标识,未知值原样保留。
|
||||||
|
let phase: String?
|
||||||
|
/// 服务端页面提示。
|
||||||
|
let title: String?
|
||||||
|
/// 服务端阶段说明,不由 GET 请求成功拼造飞行进度。
|
||||||
|
let message: String?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 将现有 JSON 值解码结果重新格式化,完整保留 shooting 的未建模字段。
|
||||||
|
private struct DroneDockShootingJSONSnapshot: Encodable {
|
||||||
|
let value: DroneDockHomeJSONValue
|
||||||
|
|
||||||
|
/// 保留字符串、数字、布尔、null 及嵌套结构,不添加外层业务包裹。
|
||||||
|
func encode(to encoder: Encoder) throws {
|
||||||
|
var container = encoder.singleValueContainer()
|
||||||
|
switch value {
|
||||||
|
case .object(let object): try container.encode(object.mapValues { DroneDockShootingJSONSnapshot(value: $0) })
|
||||||
|
case .array(let array): try container.encode(array.map { DroneDockShootingJSONSnapshot(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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 张工创建待飞任务的回执,保留最新订单摘要和完整 data 字段供联调展示。
|
||||||
|
struct DroneDockCreatedTask: Decodable, Equatable, Sendable {
|
||||||
|
/// 后端创建的订单飞行任务 ID,后续召唤应复用该任务。
|
||||||
|
let taskID: Int
|
||||||
|
/// 创建后的权威订单摘要,待飞任务不由客户端扣减次数。
|
||||||
|
let order: DroneDockHomeOrder
|
||||||
|
/// 格式化后的完整 data JSON;不添加或伪造外层 code、msg、time。
|
||||||
|
let dataJSON: String
|
||||||
|
|
||||||
|
/// 创建任务回执的必需身份字段。
|
||||||
|
private enum CodingKeys: String, CodingKey { case taskID = "task_id" }
|
||||||
|
|
||||||
|
/// 任务身份允许整数字符串,但必须为正整数;额外字段保留原 JSON 类型。
|
||||||
|
init(from decoder: Decoder) throws {
|
||||||
|
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
|
if let value = try? container.decode(Int.self, forKey: .taskID) {
|
||||||
|
taskID = value
|
||||||
|
} else if let text = try? container.decode(String.self, forKey: .taskID), let value = Int(text) {
|
||||||
|
taskID = value
|
||||||
|
} else {
|
||||||
|
throw DecodingError.dataCorruptedError(forKey: .taskID, in: container, debugDescription: "创建任务未返回有效任务 ID")
|
||||||
|
}
|
||||||
|
guard taskID > 0 else {
|
||||||
|
throw DecodingError.dataCorruptedError(forKey: .taskID, in: container, debugDescription: "创建任务返回的任务 ID 必须为正整数")
|
||||||
|
}
|
||||||
|
order = try DroneDockHomeOrder(from: decoder)
|
||||||
|
let rawData = try DroneDockHomeJSONValue(from: decoder)
|
||||||
|
let encoder = JSONEncoder()
|
||||||
|
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
|
||||||
|
dataJSON = String(decoding: try encoder.encode(DroneDockTaskJSONSnapshot(value: rawData)), as: UTF8.self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 复用现有 JSON 值解码器,将回执 data 格式化,保留未建模字段和空值。
|
||||||
|
private struct DroneDockTaskJSONSnapshot: Encodable {
|
||||||
|
let value: DroneDockHomeJSONValue
|
||||||
|
|
||||||
|
/// JSON 类型保持不变,数字使用 Decimal 避免先转换为 Double 丢失精度。
|
||||||
|
func encode(to encoder: Encoder) throws {
|
||||||
|
var container = encoder.singleValueContainer()
|
||||||
|
switch value {
|
||||||
|
case .object(let object):
|
||||||
|
try container.encode(object.mapValues { DroneDockTaskJSONSnapshot(value: $0) })
|
||||||
|
case .array(let array):
|
||||||
|
try container.encode(array.map { DroneDockTaskJSONSnapshot(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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 真实任务页的显示阶段;未确认或冲突数据保持未知,不代表客户端已发送控制指令。
|
||||||
|
enum DroneDockTaskDisplayPhase: String, Equatable, Sendable {
|
||||||
|
/// 正在读取任务。
|
||||||
|
case loading
|
||||||
|
/// 服务端明确正在前往拍摄点。
|
||||||
|
case navigating
|
||||||
|
/// 服务端明确已到达且允许开始。
|
||||||
|
case ready
|
||||||
|
/// 服务端明确正在拍摄。
|
||||||
|
case shooting
|
||||||
|
/// 服务端明确已暂停。
|
||||||
|
case paused
|
||||||
|
/// 服务端明确正在返航。
|
||||||
|
case returning
|
||||||
|
/// 服务端明确任务已完成。
|
||||||
|
case completed
|
||||||
|
/// 已确认的任务或航线执行失败。
|
||||||
|
case failed
|
||||||
|
/// 服务端阻止执行或任务已取消。
|
||||||
|
case blocked
|
||||||
|
/// 尚无足够信息确定阶段。
|
||||||
|
case unknown
|
||||||
|
/// 当前读取失败,不能沿用旧阶段。
|
||||||
|
case readError
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 任务状态区可呈现的动作;开始与恢复在本轮仅禁用展示,不发送飞控。
|
||||||
|
enum DroneDockTaskDisplayAction: Equatable, Sendable {
|
||||||
|
/// 重新读取同一任务。
|
||||||
|
case refresh
|
||||||
|
/// 开始拍摄占位动作,本轮禁用。
|
||||||
|
case start
|
||||||
|
/// 恢复拍摄占位动作,本轮禁用。
|
||||||
|
case resume
|
||||||
|
/// 查看已明确完成任务的订单素材。
|
||||||
|
case materials
|
||||||
|
/// 当前无主动作。
|
||||||
|
case none
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 状态区的纯展示数据,供固定区域布局使用,不依赖 UIKit 或虚构进度。
|
||||||
|
struct DroneDockTaskPresentation: Equatable, Sendable {
|
||||||
|
/// 当前可信显示阶段。
|
||||||
|
let phase: DroneDockTaskDisplayPhase
|
||||||
|
/// 阶段标题。
|
||||||
|
let title: String
|
||||||
|
/// 服务端说明或读取错误,完整文字可由界面展开。
|
||||||
|
let message: String
|
||||||
|
/// 当前任务设备的状态文案。
|
||||||
|
let deviceStatus: String
|
||||||
|
/// 本轮允许展示的主动作。
|
||||||
|
let action: DroneDockTaskDisplayAction
|
||||||
|
/// 主动作名称,无动作时为 nil。
|
||||||
|
let actionTitle: String?
|
||||||
|
/// 是否可触发动作;未对接的开始和恢复始终为 false。
|
||||||
|
let isActionEnabled: Bool
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
/// 拍摄准备状态:只读取张工的已购配置,不创建飞行任务。
|
/// 拍摄准备状态:明确点击创建待飞任务,再用同一任务 ID 召唤,保留回执并防止重复提交。
|
||||||
final class DroneDockPreparationViewModel {
|
final class DroneDockPreparationViewModel {
|
||||||
/// 页面进入时固定的账号、景区及门店范围。
|
/// 页面进入时固定的账号、景区及门店范围。
|
||||||
let context: DroneDockHomeContext
|
let context: DroneDockHomeContext
|
||||||
@@ -16,21 +16,291 @@ final class DroneDockPreparationViewModel {
|
|||||||
private(set) var selectedSpotID: Int?
|
private(set) var selectedSpotID: Int?
|
||||||
/// 当前点位下已购且可用的航线。
|
/// 当前点位下已购且可用的航线。
|
||||||
private(set) var selectedRouteID: Int?
|
private(set) var selectedRouteID: Int?
|
||||||
|
/// 朱工返回的当前景区无人机快照,与购买配置独立刷新。
|
||||||
|
private(set) var planeStatus: DroneDockPlaneStatusResponse?
|
||||||
|
/// 无人机状态读取失败时不沿用旧的空闲或电量信息。
|
||||||
|
private(set) var planeStatusErrorMessage: String?
|
||||||
|
/// 同一页面只保留一个无人机状态请求,避免轮询与手动刷新重叠。
|
||||||
|
private(set) var isLoadingPlaneStatus = false
|
||||||
|
/// 创建期间冻结选择和重复点击,不发送飞行指令。
|
||||||
|
private(set) var isCreatingTask = false
|
||||||
|
/// 创建成功的任务回执,后续召唤应复用此任务 ID。
|
||||||
|
private(set) var createdTask: DroneDockCreatedTask?
|
||||||
|
/// 创建预检或业务拒绝的具体提示。
|
||||||
|
private(set) var taskCreationErrorMessage: String?
|
||||||
|
/// POST 结果不明确时禁止盲目重试,需核对服务端任务后再继续。
|
||||||
|
private(set) var taskCreationOutcomeUnknown = false
|
||||||
|
/// 召唤提交期间禁用重复点击;请求成功不等于已经到达或开始拍摄。
|
||||||
|
private(set) var isSummoning = false
|
||||||
|
/// 朱工接受召唤请求的回执,data 缺失时仍以明确业务成功为准。
|
||||||
|
private(set) var shootResponse: DroneDockShootResponse?
|
||||||
|
/// 召唤业务拒绝或结果未知的提示,始终保留已创建任务身份。
|
||||||
|
private(set) var shootErrorMessage: String?
|
||||||
|
/// 召唤写请求结果不明确时禁止重发,等待后续核对任务状态。
|
||||||
|
private(set) var summonOutcomeUnknown = false
|
||||||
|
|
||||||
private let service: any DroneDockPreparationServing
|
private let service: any DroneDockPreparationServing
|
||||||
|
private let planeStatusService: any DroneDockPlaneStatusServing
|
||||||
|
private let taskCreationService: any DroneDockTaskCreating
|
||||||
|
private let shootService: any DroneDockShootServing
|
||||||
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
||||||
private var generation = 0
|
private var generation = 0
|
||||||
|
private var planeStatusGeneration = 0
|
||||||
|
private var taskCreationGeneration = 0
|
||||||
|
private var didSendTaskCreation = false
|
||||||
|
private var hasCreatedTask = false
|
||||||
|
private var creationContextInvalidated = false
|
||||||
|
private var summonGeneration = 0
|
||||||
|
private var didSendSummon = false
|
||||||
|
private var hasSubmittedSummon = false
|
||||||
|
private var primaryActionGeneration = 0
|
||||||
|
private var isPerformingPrimaryAction = false
|
||||||
|
|
||||||
/// 注入只读接口及最新会话,不绑定默认 MainActor。
|
/// 注入购买、设备、任务创建与召唤服务及最新会话,不绑定默认 MainActor。
|
||||||
init(context: DroneDockHomeContext, order: DroneDockHomeOrder,
|
init(context: DroneDockHomeContext, order: DroneDockHomeOrder,
|
||||||
service: any DroneDockPreparationServing,
|
service: any DroneDockPreparationServing,
|
||||||
|
planeStatusService: any DroneDockPlaneStatusServing,
|
||||||
|
taskCreationService: any DroneDockTaskCreating,
|
||||||
|
shootService: any DroneDockShootServing,
|
||||||
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
|
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
|
||||||
self.context = context
|
self.context = context
|
||||||
self.order = order
|
self.order = order
|
||||||
self.service = service
|
self.service = service
|
||||||
|
self.planeStatusService = planeStatusService
|
||||||
|
self.taskCreationService = taskCreationService
|
||||||
|
self.shootService = shootService
|
||||||
self.currentContext = currentContext
|
self.currentContext = currentContext
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 当前阶段只创建待飞任务,不以设备电量或位置作为创建任务条件。
|
||||||
|
var canCreateTask: Bool {
|
||||||
|
guard context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
|
||||||
|
!hasCreatedTask, !taskCreationOutcomeUnknown, errorMessage == nil,
|
||||||
|
let info = projectInfo, info.order.canCreateTask == true,
|
||||||
|
let total = info.order.shotTotal, total > 0,
|
||||||
|
let remaining = info.order.shotRemain, remaining > 0,
|
||||||
|
selectedSpot?.available == true, selectedRoute?.available == true,
|
||||||
|
let number = DroneDockHomeMetric.usableText(order.orderNumber), number.count <= 128,
|
||||||
|
number.rangeOfCharacter(from: .controlCharacters) == nil,
|
||||||
|
number == order.orderNumber, let projectID = order.projectID, projectID > 0 else { return false }
|
||||||
|
return info.order.orderNumber == number && info.order.projectID == projectID
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 提交中和已有回执/不确定结果时冻结点位航线,避免显示与任务归属不一致。
|
||||||
|
var isTaskSelectionLocked: Bool {
|
||||||
|
isCreatingTask || isSummoning || isPerformingPrimaryAction || hasCreatedTask || taskCreationOutcomeUnknown
|
||||||
|
}
|
||||||
|
/// 仅展示真实返回的 data JSON,不拼造业务包裹或召唤结果。
|
||||||
|
var creationDataJSON: String? { createdTask?.dataJSON }
|
||||||
|
/// 仅保留 shoot 实际返回的 data;缺失时不拼造成功 JSON。
|
||||||
|
var shootDataJSON: String? { shootResponse?.dataJSON }
|
||||||
|
/// 创建回执携带的最新订单摘要优先于创建前购买摘要。
|
||||||
|
var latestOrderSummary: DroneDockHomeOrder? { createdTask?.order ?? projectInfo?.order }
|
||||||
|
|
||||||
|
/// 召唤已明确受理后只允许查看原任务,导航与再次提交召唤分开判断。
|
||||||
|
var canOpenShootingTask: Bool {
|
||||||
|
context.canLoad && !creationContextInvalidated && !isLoading && !isCreatingTask
|
||||||
|
&& !isSummoning && !isPerformingPrimaryAction && !taskCreationOutcomeUnknown
|
||||||
|
&& !summonOutcomeUnknown && hasSubmittedSummon && shootResponse != nil
|
||||||
|
&& (createdTask?.taskID ?? 0) > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 首次允许创建再召唤;明确业务拒绝后可对同任务重试,成功和未知结果锁定。
|
||||||
|
var isPrimaryActionEnabled: Bool {
|
||||||
|
guard context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
|
||||||
|
!isSummoning, !isPerformingPrimaryAction, !taskCreationOutcomeUnknown,
|
||||||
|
!hasSubmittedSummon, !summonOutcomeUnknown else { return false }
|
||||||
|
if let createdTask { return createdTask.taskID > 0 }
|
||||||
|
return canCreateTask
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 主按钮串接创建与召唤;已有任务跳过创建,成功后的导航由页面处理。
|
||||||
|
@MainActor
|
||||||
|
func prepareAndSummon(onStateChange: @escaping @MainActor () -> Void = {}) async {
|
||||||
|
guard isPrimaryActionEnabled else { return }
|
||||||
|
primaryActionGeneration &+= 1
|
||||||
|
let actionGeneration = primaryActionGeneration
|
||||||
|
isPerformingPrimaryAction = true
|
||||||
|
onStateChange()
|
||||||
|
defer {
|
||||||
|
if primaryActionGeneration == actionGeneration {
|
||||||
|
isPerformingPrimaryAction = false
|
||||||
|
onStateChange()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if createdTask == nil { await createTask(onStateChange: onStateChange) }
|
||||||
|
guard primaryActionGeneration == actionGeneration, !Task.isCancelled else { return }
|
||||||
|
await summonCreatedTask(onStateChange: onStateChange)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 对明确创建成功的任务发送一次召唤;只有明确业务拒绝允许之后再次提交。
|
||||||
|
@MainActor
|
||||||
|
private func summonCreatedTask(onStateChange: @escaping @MainActor () -> Void) async {
|
||||||
|
guard !isCreatingTask, !isSummoning, !taskCreationOutcomeUnknown,
|
||||||
|
!hasSubmittedSummon, !summonOutcomeUnknown,
|
||||||
|
let taskID = createdTask?.taskID, taskID > 0 else { return }
|
||||||
|
summonGeneration &+= 1
|
||||||
|
let requestGeneration = summonGeneration
|
||||||
|
isSummoning = true
|
||||||
|
didSendSummon = false
|
||||||
|
shootErrorMessage = nil
|
||||||
|
onStateChange()
|
||||||
|
defer {
|
||||||
|
if summonGeneration == requestGeneration {
|
||||||
|
if Task.isCancelled && didSendSummon && !hasSubmittedSummon { markSummonUnknown() }
|
||||||
|
isSummoning = false
|
||||||
|
didSendSummon = false
|
||||||
|
onStateChange()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
guard acceptsSummon(requestGeneration, taskID: taskID) else { return }
|
||||||
|
do {
|
||||||
|
didSendSummon = true
|
||||||
|
let response = try await shootService.shoot(taskID: taskID)
|
||||||
|
guard acceptsSummon(requestGeneration, taskID: taskID) else { return }
|
||||||
|
shootResponse = response
|
||||||
|
hasSubmittedSummon = true
|
||||||
|
summonOutcomeUnknown = false
|
||||||
|
} catch {
|
||||||
|
guard acceptsSummon(requestGeneration, taskID: taskID) else { return }
|
||||||
|
if case APIError.serverCode = error {
|
||||||
|
shootErrorMessage = error.localizedDescription
|
||||||
|
} else {
|
||||||
|
markSummonUnknown(reason: error.localizedDescription)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 页面暂停使迟到召唤回执失效;已发送请求保留未知锁,成功回执和任务 ID 不清除。
|
||||||
|
@MainActor
|
||||||
|
func invalidateSummon() {
|
||||||
|
if isSummoning && didSendSummon && !hasSubmittedSummon { markSummonUnknown() }
|
||||||
|
primaryActionGeneration &+= 1
|
||||||
|
isPerformingPrimaryAction = false
|
||||||
|
summonGeneration &+= 1
|
||||||
|
isSummoning = false
|
||||||
|
didSendSummon = false
|
||||||
|
if creationContextInvalidated {
|
||||||
|
shootResponse = nil
|
||||||
|
shootErrorMessage = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 点击后先校验最新购买配置,再发送一次创建请求;成功留在准备页供核对。
|
||||||
|
@MainActor
|
||||||
|
func createTask(onStateChange: @escaping @MainActor () -> Void = {}) async {
|
||||||
|
guard canCreateTask, let spotID = selectedSpotID, let routeID = selectedRouteID,
|
||||||
|
let number = order.orderNumber, let projectID = order.projectID else { return }
|
||||||
|
taskCreationGeneration &+= 1
|
||||||
|
let requestGeneration = taskCreationGeneration
|
||||||
|
isCreatingTask = true
|
||||||
|
didSendTaskCreation = false
|
||||||
|
taskCreationErrorMessage = nil
|
||||||
|
onStateChange()
|
||||||
|
defer {
|
||||||
|
if taskCreationGeneration == requestGeneration {
|
||||||
|
if Task.isCancelled && didSendTaskCreation && !hasCreatedTask { markTaskCreationUnknown() }
|
||||||
|
isCreatingTask = false
|
||||||
|
didSendTaskCreation = false
|
||||||
|
onStateChange()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
guard acceptsTaskCreation(requestGeneration) else { return }
|
||||||
|
do {
|
||||||
|
let latest = try await service.projectInfo(scenicID: context.scenicID, projectID: projectID, orderNumber: number)
|
||||||
|
guard acceptsTaskCreation(requestGeneration) else { return }
|
||||||
|
guard latest.order.orderNumber == number, latest.order.projectID == projectID else {
|
||||||
|
throw APIError.decodeFailed("购买配置与当前订单或项目不一致,请刷新重试")
|
||||||
|
}
|
||||||
|
projectInfo = latest
|
||||||
|
guard latest.order.canCreateTask == true,
|
||||||
|
let total = latest.order.shotTotal, total > 0,
|
||||||
|
let remaining = latest.order.shotRemain, remaining > 0 else {
|
||||||
|
taskCreationErrorMessage = "当前订单已不可新增拍摄任务,请刷新状态"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
guard let spot = latest.spots.first(where: { $0.id == spotID }), spot.available == true,
|
||||||
|
spot.airLines.contains(where: { $0.id == routeID && $0.available == true }) else {
|
||||||
|
restoreValidSelection()
|
||||||
|
taskCreationErrorMessage = "所选点位或航线已不可用,请重新选择"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
guard acceptsTaskCreation(requestGeneration) else { return }
|
||||||
|
didSendTaskCreation = true
|
||||||
|
let response = try await taskCreationService.createTask(scenicID: context.scenicID,
|
||||||
|
orderNumber: number, spotID: spotID, airLineID: routeID)
|
||||||
|
guard acceptsTaskCreation(requestGeneration) else { return }
|
||||||
|
guard response.taskID > 0, response.order.orderNumber == number,
|
||||||
|
response.order.projectID == nil || response.order.projectID == projectID else {
|
||||||
|
throw APIError.decodeFailed("创建回执与当前订单或项目不一致,请核对任务")
|
||||||
|
}
|
||||||
|
createdTask = response
|
||||||
|
hasCreatedTask = true
|
||||||
|
taskCreationOutcomeUnknown = false
|
||||||
|
} catch {
|
||||||
|
guard acceptsTaskCreation(requestGeneration) else { return }
|
||||||
|
if didSendTaskCreation {
|
||||||
|
if case APIError.serverCode = error {
|
||||||
|
taskCreationErrorMessage = error.localizedDescription
|
||||||
|
} else {
|
||||||
|
markTaskCreationUnknown(reason: error.localizedDescription)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
taskCreationErrorMessage = Self.message(for: error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 读取当前景区的无人机状态,不重读购买配置、不改变点位或航线选择。
|
||||||
|
@MainActor
|
||||||
|
func refreshPlaneStatus() async {
|
||||||
|
guard !isLoadingPlaneStatus else { return }
|
||||||
|
planeStatusGeneration &+= 1
|
||||||
|
let requestGeneration = planeStatusGeneration
|
||||||
|
isLoadingPlaneStatus = true
|
||||||
|
planeStatusErrorMessage = nil
|
||||||
|
defer {
|
||||||
|
if planeStatusGeneration == requestGeneration {
|
||||||
|
isLoadingPlaneStatus = false
|
||||||
|
if Task.isCancelled { planeStatus = nil }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
guard acceptsPlaneStatus(requestGeneration) else { return }
|
||||||
|
guard context.canLoad else {
|
||||||
|
planeStatus = nil
|
||||||
|
planeStatusErrorMessage = "缺少当前景区或登录信息,请返回工作台重新进入"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
let response = try await planeStatusService.planeStatus(scenicID: context.scenicID)
|
||||||
|
guard acceptsPlaneStatus(requestGeneration) else { return }
|
||||||
|
guard response.scenicID == context.scenicID else {
|
||||||
|
planeStatus = nil
|
||||||
|
planeStatusErrorMessage = "无人机状态与当前景区不一致,请刷新重试"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
planeStatus = response
|
||||||
|
} catch {
|
||||||
|
guard acceptsPlaneStatus(requestGeneration) else { return }
|
||||||
|
planeStatus = nil
|
||||||
|
planeStatusErrorMessage = Self.message(for: error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 采用服务端轮询建议;缺失使用五秒,限制到五至六十秒避免密集请求。
|
||||||
|
var pollIntervalNanoseconds: UInt64 {
|
||||||
|
UInt64(min(60_000, max(5_000, planeStatus?.pollHintMS ?? 5_000))) * 1_000_000
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 暂停或离开时只使无人机请求失效,购买配置与选中航线继续保留。
|
||||||
|
@MainActor
|
||||||
|
func invalidatePlaneStatus() {
|
||||||
|
planeStatusGeneration &+= 1
|
||||||
|
isLoadingPlaneStatus = false
|
||||||
|
planeStatus = nil
|
||||||
|
planeStatusErrorMessage = nil
|
||||||
|
}
|
||||||
|
|
||||||
/// 只展示购买快照中的点位,保持张工返回顺序。
|
/// 只展示购买快照中的点位,保持张工返回顺序。
|
||||||
var spots: [DroneDockPurchasedSpot] { projectInfo?.spots ?? [] }
|
var spots: [DroneDockPurchasedSpot] { projectInfo?.spots ?? [] }
|
||||||
/// 当前有效点位。
|
/// 当前有效点位。
|
||||||
@@ -41,6 +311,7 @@ final class DroneDockPreparationViewModel {
|
|||||||
var selectedRoute: DroneDockPurchasedAirLine? { routes.first { $0.id == selectedRouteID } }
|
var selectedRoute: DroneDockPurchasedAirLine? { routes.first { $0.id == selectedRouteID } }
|
||||||
/// 进入页面后直接请求购买快照,不等待定位或设备接口。
|
/// 进入页面后直接请求购买快照,不等待定位或设备接口。
|
||||||
func refresh() async {
|
func refresh() async {
|
||||||
|
guard !isCreatingTask else { return }
|
||||||
generation &+= 1
|
generation &+= 1
|
||||||
let requestGeneration = generation
|
let requestGeneration = generation
|
||||||
isLoading = true
|
isLoading = true
|
||||||
@@ -76,62 +347,109 @@ final class DroneDockPreparationViewModel {
|
|||||||
|
|
||||||
/// 不可用或可用性未知的点位不能选中,切点后选择首条明确可用的已购航线。
|
/// 不可用或可用性未知的点位不能选中,切点后选择首条明确可用的已购航线。
|
||||||
func selectSpot(id: Int) {
|
func selectSpot(id: Int) {
|
||||||
guard !isLoading, spots.contains(where: { $0.id == id && $0.available == true }), selectedSpotID != id else { return }
|
guard !isLoading, !isTaskSelectionLocked, spots.contains(where: { $0.id == id && $0.available == true }), selectedSpotID != id else { return }
|
||||||
selectedSpotID = id
|
selectedSpotID = id
|
||||||
selectedRouteID = routes.first(where: { $0.available == true })?.id
|
selectedRouteID = routes.first(where: { $0.available == true })?.id
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 忽略其他点位、不可用及身份不明的航线选择。
|
/// 忽略其他点位、不可用及身份不明的航线选择。
|
||||||
func selectRoute(id: Int) {
|
func selectRoute(id: Int) {
|
||||||
guard !isLoading, selectedSpot?.available == true,
|
guard !isLoading, !isTaskSelectionLocked, selectedSpot?.available == true,
|
||||||
routes.contains(where: { $0.id == id && $0.available == true }) else { return }
|
routes.contains(where: { $0.id == id && $0.available == true }) else { return }
|
||||||
selectedRouteID = id
|
selectedRouteID = id
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 离开后使购买快照请求失效,避免旧响应回填。
|
/// 离开后使请求失效,保留创建回执或不确定结果,避免返回后重复建任务。
|
||||||
|
@MainActor
|
||||||
func invalidate() {
|
func invalidate() {
|
||||||
|
if isCreatingTask && didSendTaskCreation { markTaskCreationUnknown() }
|
||||||
|
taskCreationGeneration &+= 1
|
||||||
|
isCreatingTask = false
|
||||||
|
didSendTaskCreation = false
|
||||||
generation &+= 1
|
generation &+= 1
|
||||||
isLoading = false
|
isLoading = false
|
||||||
errorMessage = nil
|
errorMessage = nil
|
||||||
clearProject()
|
clearProject()
|
||||||
|
invalidatePlaneStatus()
|
||||||
|
invalidateSummon()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 当前接口没有机巢连接信息,不能由购买权限推导设备状态。
|
/// 连接状态仅使用 plane-status 的 connected,不由是否空闲推导。
|
||||||
var connectionTitle: String { "机巢连接待确认" }
|
var connectionTitle: String {
|
||||||
/// 设备连接未知时使用中性色。
|
switch planeStatus?.connected {
|
||||||
var connectionTone: DroneDockStatusTone { .gray }
|
case true: "机巢已连接"
|
||||||
|
case false: "机巢未连接"
|
||||||
|
default: "机巢连接待确认"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// 明确连接时标绿,离线或未知保持中性色。
|
||||||
|
var connectionTone: DroneDockStatusTone { planeStatus?.connected == true ? .green : .gray }
|
||||||
/// 以购买快照中的名称展示当前选择。
|
/// 以购买快照中的名称展示当前选择。
|
||||||
var selectionSummary: String {
|
var selectionSummary: String {
|
||||||
guard let selectedSpot else { return "请选择拍摄点" }
|
guard let selectedSpot else { return "请选择拍摄点" }
|
||||||
guard let selectedRoute else { return "\(selectedSpot.name) · 未选航线" }
|
guard let selectedRoute else { return "\(selectedSpot.name) · 未选航线" }
|
||||||
return "\(selectedSpot.name) · \(selectedRoute.name)"
|
return "\(selectedSpot.name) · \(selectedRoute.name)"
|
||||||
}
|
}
|
||||||
/// 当前未读取设备状态,也尚未派机。
|
/// 优先展示服务端推荐无人机的完整文案,不自行重选列表中的另一架。
|
||||||
var deviceStatusText: String { "状态待确认" }
|
var deviceStatusText: String {
|
||||||
/// 准备阶段尚未派机。
|
guard let planeStatus else { return "状态待确认" }
|
||||||
var deviceTone: DroneDockStatusTone { .gray }
|
guard let recommendation = planeStatus.recommend else {
|
||||||
/// 文案反映购买权限,不开放实际召唤操作。
|
return planeStatus.planes.isEmpty ? "暂无无人机" : "状态待确认"
|
||||||
|
}
|
||||||
|
if let text = DroneDockHomeMetric.usableText(recommendation.statusText) { return text }
|
||||||
|
let state = DroneDockHomeMetric.usableText(recommendation.workStatusLabel) ?? "状态待确认"
|
||||||
|
let battery = DroneDockHomeMetric.usableText(recommendation.batteryLabel)
|
||||||
|
return battery.map { "\(state) · \($0)" } ?? state
|
||||||
|
}
|
||||||
|
/// 状态颜色只映射文档定义的工作状态,未知值不展示为空闲。
|
||||||
|
var deviceTone: DroneDockStatusTone {
|
||||||
|
switch planeStatus?.recommend?.workStatus {
|
||||||
|
case 1: .green
|
||||||
|
case 2: .orange
|
||||||
|
default: .gray
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// 文案区分创建、召唤提交与待核对,不将请求被接受表述为到达或拍摄成功。
|
||||||
var primaryButtonTitle: String {
|
var primaryButtonTitle: String {
|
||||||
|
if isCreatingTask { return "正在创建任务…" }
|
||||||
|
if isSummoning { return "正在召唤无人机…" }
|
||||||
|
if hasSubmittedSummon { return "查看拍摄任务" }
|
||||||
|
if summonOutcomeUnknown { return "召唤结果待核对" }
|
||||||
|
if hasCreatedTask { return shootErrorMessage == nil ? "确认并召唤" : "重试召唤" }
|
||||||
|
if taskCreationOutcomeUnknown { return "结果待核对" }
|
||||||
if projectInfo?.order.shotRemain == 0 { return "拍摄次数已用完" }
|
if projectInfo?.order.shotRemain == 0 { return "拍摄次数已用完" }
|
||||||
if let info = projectInfo, info.order.canCreateTask != true { return "暂不可召唤" }
|
if let info = projectInfo, info.order.canCreateTask != true { return "暂不可召唤" }
|
||||||
return "确认并召唤"
|
return "确认并召唤"
|
||||||
}
|
}
|
||||||
/// 检查购买范围与额度;条件有效后仍提示召唤尚未开放。
|
/// 说明创建与召唤提交结果,实际飞行状态需要后续任务状态核对。
|
||||||
var admissionMessage: String {
|
var admissionMessage: String {
|
||||||
|
if isCreatingTask { return "正在创建待飞任务,请勿重复点击" }
|
||||||
|
if isSummoning { return "任务已创建,正在提交召唤请求" }
|
||||||
|
if creationContextInvalidated, let errorMessage { return errorMessage }
|
||||||
|
if let createdTask {
|
||||||
|
if hasSubmittedSummon { return "任务 \(createdTask.taskID) 的召唤请求已提交,请等待任务状态更新" }
|
||||||
|
if let shootErrorMessage { return shootErrorMessage }
|
||||||
|
if summonOutcomeUnknown { return "召唤结果待核对,请勿重复提交" }
|
||||||
|
return "任务 \(createdTask.taskID) 已创建,等待召唤"
|
||||||
|
}
|
||||||
|
if let taskCreationErrorMessage { return taskCreationErrorMessage }
|
||||||
|
if taskCreationOutcomeUnknown { return "创建结果待核对,请勿重复提交" }
|
||||||
if isLoading { return "正在获取拍摄准备信息" }
|
if isLoading { return "正在获取拍摄准备信息" }
|
||||||
if let errorMessage { return errorMessage }
|
if let errorMessage { return errorMessage }
|
||||||
guard let info = projectInfo else { return "正在加载拍摄准备信息" }
|
guard let info = projectInfo else { return "正在加载拍摄准备信息" }
|
||||||
if info.order.shotRemain == 0 { return "当前订单拍摄次数已用完" }
|
if info.order.shotRemain == 0 { return "当前订单拍摄次数已用完" }
|
||||||
guard let remaining = info.order.shotRemain, remaining > 0, info.order.shotTotal != nil else { return "拍摄次数待确认,请刷新状态" }
|
guard let remaining = info.order.shotRemain, remaining > 0,
|
||||||
|
let total = info.order.shotTotal, total > 0 else { return "拍摄次数待确认,请刷新状态" }
|
||||||
guard info.order.canCreateTask == true else { return "当前订单暂不可新增拍摄任务,请刷新状态" }
|
guard info.order.canCreateTask == true else { return "当前订单暂不可新增拍摄任务,请刷新状态" }
|
||||||
if spots.isEmpty { return "当前暂无可用拍摄点" }
|
if spots.isEmpty { return "当前暂无可用拍摄点" }
|
||||||
guard let spot = selectedSpot, spot.available == true else { return "请选择可用拍摄点" }
|
guard let spot = selectedSpot, spot.available == true else { return "请选择可用拍摄点" }
|
||||||
if routes.isEmpty { return "当前拍摄点暂无可用航线" }
|
if routes.isEmpty { return "当前拍摄点暂无可用航线" }
|
||||||
guard selectedRoute?.available == true else { return "请选择可用航线" }
|
guard selectedRoute?.available == true else { return "请选择可用航线" }
|
||||||
return "召唤功能暂未开放"
|
return "点击后创建任务并召唤无人机"
|
||||||
}
|
}
|
||||||
|
|
||||||
private func restoreValidSelection() {
|
private func restoreValidSelection() {
|
||||||
|
guard !hasCreatedTask, !taskCreationOutcomeUnknown else { return }
|
||||||
if !spots.contains(where: { $0.id == selectedSpotID && $0.available == true }) {
|
if !spots.contains(where: { $0.id == selectedSpotID && $0.available == true }) {
|
||||||
selectedSpotID = spots.first(where: { $0.available == true })?.id
|
selectedSpotID = spots.first(where: { $0.available == true })?.id
|
||||||
selectedRouteID = nil
|
selectedRouteID = nil
|
||||||
@@ -143,6 +461,8 @@ final class DroneDockPreparationViewModel {
|
|||||||
|
|
||||||
private func clearProject() {
|
private func clearProject() {
|
||||||
projectInfo = nil
|
projectInfo = nil
|
||||||
|
// 已提交的任务仍归属原点位航线,暂时清空购买快照不能替它重新选项。
|
||||||
|
guard creationContextInvalidated || !isTaskSelectionLocked else { return }
|
||||||
selectedSpotID = nil
|
selectedSpotID = nil
|
||||||
selectedRouteID = nil
|
selectedRouteID = nil
|
||||||
}
|
}
|
||||||
@@ -152,6 +472,42 @@ final class DroneDockPreparationViewModel {
|
|||||||
let latest = await currentContext()
|
let latest = await currentContext()
|
||||||
guard generation == requestGeneration, !Task.isCancelled else { return false }
|
guard generation == requestGeneration, !Task.isCancelled else { return false }
|
||||||
guard context.hasSameIdentity(as: latest) else {
|
guard context.hasSameIdentity(as: latest) else {
|
||||||
|
creationContextInvalidated = true
|
||||||
|
createdTask = nil
|
||||||
|
await invalidate()
|
||||||
|
errorMessage = "账号或景区已变化,请返回工作台重新进入"
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 无人机回包独立验证请求代次、取消状态与当前登录身份。
|
||||||
|
@MainActor
|
||||||
|
private func acceptsPlaneStatus(_ requestGeneration: Int) -> Bool {
|
||||||
|
guard planeStatusGeneration == requestGeneration, !Task.isCancelled else { return false }
|
||||||
|
guard context.hasSameIdentity(as: currentContext()) else {
|
||||||
|
creationContextInvalidated = true
|
||||||
|
createdTask = nil
|
||||||
|
invalidate()
|
||||||
|
let message = "账号或景区已变化,请返回工作台重新进入"
|
||||||
|
errorMessage = message
|
||||||
|
planeStatusErrorMessage = message
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 写请求代次和身份检查;取消或切换会话后不显示迟到的成功回执。
|
||||||
|
@MainActor
|
||||||
|
private func acceptsTaskCreation(_ requestGeneration: Int) -> Bool {
|
||||||
|
guard taskCreationGeneration == requestGeneration else { return false }
|
||||||
|
guard !Task.isCancelled else {
|
||||||
|
if didSendTaskCreation { markTaskCreationUnknown() }
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
guard context.hasSameIdentity(as: currentContext()), !creationContextInvalidated else {
|
||||||
|
creationContextInvalidated = true
|
||||||
|
createdTask = nil
|
||||||
invalidate()
|
invalidate()
|
||||||
errorMessage = "账号或景区已变化,请返回工作台重新进入"
|
errorMessage = "账号或景区已变化,请返回工作台重新进入"
|
||||||
return false
|
return false
|
||||||
@@ -159,6 +515,36 @@ final class DroneDockPreparationViewModel {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 召唤只接受同一任务、同一会话及当前请求代次;提交后取消保留未知锁。
|
||||||
|
@MainActor
|
||||||
|
private func acceptsSummon(_ requestGeneration: Int, taskID: Int) -> Bool {
|
||||||
|
guard summonGeneration == requestGeneration else { return false }
|
||||||
|
guard !Task.isCancelled else {
|
||||||
|
if didSendSummon && !hasSubmittedSummon { markSummonUnknown() }
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
guard
|
||||||
|
createdTask?.taskID == taskID, !taskCreationOutcomeUnknown else { return false }
|
||||||
|
guard context.hasSameIdentity(as: currentContext()), !creationContextInvalidated else {
|
||||||
|
creationContextInvalidated = true
|
||||||
|
createdTask = nil
|
||||||
|
invalidate()
|
||||||
|
errorMessage = "账号或景区已变化,请返回工作台重新进入"
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private func markSummonUnknown(reason: String? = nil) {
|
||||||
|
summonOutcomeUnknown = true
|
||||||
|
shootErrorMessage = (reason.map { "\($0)。" } ?? "") + "召唤结果待核对,请先核对任务状态,勿重复提交"
|
||||||
|
}
|
||||||
|
|
||||||
|
private func markTaskCreationUnknown(reason: String? = nil) {
|
||||||
|
taskCreationOutcomeUnknown = true
|
||||||
|
taskCreationErrorMessage = (reason.map { "\($0)。" } ?? "") + "创建结果待核对,请先查看订单任务,勿重复提交"
|
||||||
|
}
|
||||||
|
|
||||||
private static func message(for error: Error) -> String? {
|
private static func message(for error: Error) -> String? {
|
||||||
error is CancellationError ? nil : error.localizedDescription
|
error is CancellationError ? nil : error.localizedDescription
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,270 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// 真实拍摄任务页只读状态,只按准备页传入的既有任务 ID 读取 shooting。
|
||||||
|
final class DroneDockShootingTaskViewModel {
|
||||||
|
/// 页面绑定的账号、景区和门店身份。
|
||||||
|
let context: DroneDockHomeContext
|
||||||
|
/// 创建并召唤时使用的同一订单飞行任务 ID。
|
||||||
|
let taskID: Int
|
||||||
|
/// 进入页面携带的订单摘要,仅作未返回展示字段时的订单文案备用。
|
||||||
|
let order: DroneDockHomeOrder
|
||||||
|
/// 当前通过身份检查的服务端快照。
|
||||||
|
private(set) var response: DroneDockShootingResponse?
|
||||||
|
/// 同一页面最多存在一个读取请求。
|
||||||
|
private(set) var isLoading = false
|
||||||
|
/// 读取失败或身份变化时的提示。
|
||||||
|
private(set) var errorMessage: String?
|
||||||
|
|
||||||
|
private let service: any DroneDockShootingServing
|
||||||
|
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
||||||
|
private var generation = 0
|
||||||
|
private var identityInvalidated = false
|
||||||
|
|
||||||
|
/// 只注入读取服务,不依赖创建、召唤、开始拍摄或控制服务。
|
||||||
|
init(context: DroneDockHomeContext, taskID: Int, order: DroneDockHomeOrder,
|
||||||
|
service: any DroneDockShootingServing,
|
||||||
|
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
|
||||||
|
self.context = context
|
||||||
|
self.taskID = taskID
|
||||||
|
self.order = order
|
||||||
|
self.service = service
|
||||||
|
self.currentContext = currentContext
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 页面可见时读取同一任务;失败、取消或身份失效不沿用之前的执行门禁与读数。
|
||||||
|
@MainActor
|
||||||
|
func refresh() async {
|
||||||
|
guard !isLoading, !identityInvalidated else { return }
|
||||||
|
generation &+= 1
|
||||||
|
let requestGeneration = generation
|
||||||
|
isLoading = true
|
||||||
|
errorMessage = nil
|
||||||
|
response = nil
|
||||||
|
defer {
|
||||||
|
if generation == requestGeneration {
|
||||||
|
isLoading = false
|
||||||
|
if Task.isCancelled { response = nil }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
guard accepts(requestGeneration) else { return }
|
||||||
|
guard context.canLoad, taskID > 0,
|
||||||
|
DroneDockHomeMetric.usableText(order.orderNumber) != nil else {
|
||||||
|
errorMessage = "缺少有效任务、订单或景区信息,请返回工作台重新进入"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
let value = try await service.shooting(taskID: taskID, liveBattery: true)
|
||||||
|
guard accepts(requestGeneration) else { return }
|
||||||
|
guard matchesIdentity(value) else {
|
||||||
|
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
|
||||||
|
}
|
||||||
|
response = value
|
||||||
|
} catch {
|
||||||
|
guard accepts(requestGeneration) else { return }
|
||||||
|
response = nil
|
||||||
|
errorMessage = error is CancellationError ? nil : error.localizedDescription
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 离开或进入后台时使旧请求失效;再次进入仍读取同一任务,不创建或召唤。
|
||||||
|
@MainActor
|
||||||
|
func invalidate() {
|
||||||
|
generation &+= 1
|
||||||
|
isLoading = false
|
||||||
|
response = nil
|
||||||
|
if !identityInvalidated { errorMessage = nil }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 优先使用当前接口标题,缺失时展示当前接口的点位和航线名称。
|
||||||
|
var title: String {
|
||||||
|
if let title = usable(response?.header?.title) { return title }
|
||||||
|
let names = [usable(response?.scenicSpot?.name), usable(response?.airLine?.name)].compactMap { $0 }
|
||||||
|
return names.isEmpty ? "拍摄任务" : names.joined(separator: " · ")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 服务端游客和套餐文案优先,后端已返回的套餐不被进入页摘要覆盖。
|
||||||
|
var subtitle: String {
|
||||||
|
let tourist = usable(response?.header?.touristLabel) ?? usable(order.touristPhoneMask)
|
||||||
|
let package = usable(response?.header?.packageName) ?? usable(order.packageName)
|
||||||
|
let parts = [tourist, package].compactMap { $0 }
|
||||||
|
return parts.isEmpty ? "—" : parts.joined(separator: " · ")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 只展示本任务当前设备状态,不以景区推荐设备替代任务锁定设备。
|
||||||
|
var deviceStatusText: String {
|
||||||
|
usable(response?.currentPlane?.statusText) ?? usable(response?.currentPlane?.workStatusLabel) ?? "—"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 使用服务端阶段标题或任务状态,不从 GET 成功推导到达或拍摄完成。
|
||||||
|
var statusTitle: String {
|
||||||
|
if errorMessage != nil { return "任务状态读取失败" }
|
||||||
|
if isLoading { return "正在获取任务状态" }
|
||||||
|
return usable(response?.ui?.title) ?? usable(response?.task?.statusLabel)
|
||||||
|
?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 保留服务端阶段说明与执行门禁原因;本模块不执行门禁给出的动作。
|
||||||
|
var statusMessage: String {
|
||||||
|
if let errorMessage { return errorMessage }
|
||||||
|
if isLoading { return "正在读取当前拍摄任务" }
|
||||||
|
return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 组合可信阶段与本轮可用动作,不从请求成功、执行中或指令列表推断飞行进度。
|
||||||
|
var presentation: DroneDockTaskPresentation {
|
||||||
|
if isLoading {
|
||||||
|
return DroneDockTaskPresentation(phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
|
||||||
|
deviceStatus: deviceStatusText, action: .none, actionTitle: nil, isActionEnabled: false)
|
||||||
|
}
|
||||||
|
if let errorMessage {
|
||||||
|
return DroneDockTaskPresentation(phase: .readError, title: "任务状态读取失败", message: errorMessage,
|
||||||
|
deviceStatus: deviceStatusText, action: .refresh, actionTitle: "重新读取", isActionEnabled: !identityInvalidated)
|
||||||
|
}
|
||||||
|
let (phase, conflict) = resolvedDisplayPhase()
|
||||||
|
let message = conflict ? "任务状态信息不一致,请刷新后确认。" + (statusMessage == "—" ? "" : statusMessage) : statusMessage
|
||||||
|
let title = presentationTitle(for: phase, conflict: conflict)
|
||||||
|
let action: DroneDockTaskDisplayAction
|
||||||
|
let actionTitle: String?
|
||||||
|
let enabled: Bool
|
||||||
|
switch phase {
|
||||||
|
case .ready:
|
||||||
|
action = .start
|
||||||
|
actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "开始拍摄"
|
||||||
|
enabled = false
|
||||||
|
case .paused where response?.executeGate?.canExecute == true:
|
||||||
|
action = .resume
|
||||||
|
actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "继续拍摄"
|
||||||
|
enabled = false
|
||||||
|
case .completed:
|
||||||
|
action = .materials
|
||||||
|
actionTitle = "查看素材"
|
||||||
|
enabled = true
|
||||||
|
default:
|
||||||
|
action = .refresh
|
||||||
|
actionTitle = "刷新状态"
|
||||||
|
enabled = !identityInvalidated
|
||||||
|
}
|
||||||
|
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
|
||||||
|
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle, isActionEnabled: enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 后端六项展示读数,不解析文案反推设备状态或数值单位。
|
||||||
|
var telemetry: DroneDockShootingTelemetry {
|
||||||
|
func text(_ key: String) -> String { response?.metrics.first(where: { $0.key == key })?.displayText ?? "—" }
|
||||||
|
return DroneDockShootingTelemetry(batteryText: text("battery"), temperatureText: text("env_temp"),
|
||||||
|
windText: text("wind_speed"), rainText: text("rainfall"), signalText: text("signal"), satelliteText: text("satellite"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 无有效快照时不展示旧读数;连接 false 自身不被转换为飞行阶段。
|
||||||
|
var isTelemetryStale: Bool { response == nil }
|
||||||
|
/// 完整服务端 data,供页面展示和联调查看。
|
||||||
|
var dataJSON: String? { response?.dataJSON }
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
private func accepts(_ requestGeneration: Int) -> Bool {
|
||||||
|
guard generation == requestGeneration, !Task.isCancelled else { return false }
|
||||||
|
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
|
||||||
|
identityInvalidated = true
|
||||||
|
invalidate()
|
||||||
|
errorMessage = "账号或景区已变化,请返回工作台重新进入"
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private func matchesIdentity(_ value: DroneDockShootingResponse) -> Bool {
|
||||||
|
let taskIDs = [value.orderFlightTask?.id, value.task?.id].compactMap { $0 }
|
||||||
|
let orderNumbers = [value.orderNumber, value.orderFlightTask?.orderNumber,
|
||||||
|
value.task?.orderNumber, value.header?.orderNumber].compactMap { $0 }
|
||||||
|
let scenicIDs = [value.scenic?.id, value.orderFlightTask?.scenicID,
|
||||||
|
value.task?.scenicID, value.planeStatus?.scenicID].compactMap { $0 }
|
||||||
|
return taskIDs.allSatisfy { $0 == taskID }
|
||||||
|
&& orderNumbers.allSatisfy { $0 == order.orderNumber }
|
||||||
|
&& scenicIDs.allSatisfy { $0 == context.scenicID }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 只认识显式阶段和已确认任务状态;91 为真实航线执行失败,不把订单状态 20 当作正在拍摄。
|
||||||
|
private func resolvedDisplayPhase() -> (DroneDockTaskDisplayPhase, Bool) {
|
||||||
|
guard let response else { return (.unknown, false) }
|
||||||
|
let tasks = [response.task, response.orderFlightTask].compactMap { $0 }
|
||||||
|
let statuses = Set(tasks.compactMap(\.status))
|
||||||
|
if tasks.contains(where: { $0.waylineStatus == 91 }) || statuses.contains(40) { return (.failed, false) }
|
||||||
|
if statuses.contains(50) { return (.blocked, false) }
|
||||||
|
if statuses.count > 1 { return (.unknown, true) }
|
||||||
|
let known: [String: DroneDockTaskDisplayPhase] = [
|
||||||
|
"navigating": .navigating, "arrived_pending_start": .ready, "shooting": .shooting,
|
||||||
|
"paused": .paused, "returning": .returning, "completed": .completed, "failed": .failed, "blocked": .blocked
|
||||||
|
]
|
||||||
|
let rawPhase = usable(response.ui?.phase)
|
||||||
|
let phase = rawPhase.flatMap { known[$0] }
|
||||||
|
if rawPhase != nil && phase == nil { return (.unknown, false) }
|
||||||
|
if phase == .failed { return (.failed, false) }
|
||||||
|
if statuses.contains(30) {
|
||||||
|
if phase == .returning { return (.returning, false) }
|
||||||
|
if let phase, [.navigating, .ready, .shooting, .paused].contains(phase) { return (.unknown, true) }
|
||||||
|
return (.completed, false)
|
||||||
|
}
|
||||||
|
if phase == .completed {
|
||||||
|
return statuses.isEmpty ? (.completed, false) : (.unknown, true)
|
||||||
|
}
|
||||||
|
if phase == .ready {
|
||||||
|
guard let allowed = response.executeGate?.canExecute else { return (.unknown, false) }
|
||||||
|
if !allowed { return (.blocked, false) }
|
||||||
|
if let action = usable(response.executeGate?.primaryAction), action != "start_shoot" {
|
||||||
|
return (.unknown, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if phase == .paused, response.executeGate?.canExecute == true,
|
||||||
|
response.executeGate?.primaryAction == "blocked" { return (.unknown, true) }
|
||||||
|
return (phase ?? .unknown, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func presentationTitle(for phase: DroneDockTaskDisplayPhase, conflict: Bool) -> String {
|
||||||
|
if conflict { return "状态待确认" }
|
||||||
|
let tasks = [response?.task, response?.orderFlightTask].compactMap { $0 }
|
||||||
|
if phase == .failed, let failed = tasks.first(where: { $0.waylineStatus == 91 }) {
|
||||||
|
return usable(failed.waylineStatusLabel) ?? "任务执行失败"
|
||||||
|
}
|
||||||
|
if phase == .failed, let failed = tasks.first(where: { $0.status == 40 }) {
|
||||||
|
return usable(failed.statusLabel) ?? "任务执行失败"
|
||||||
|
}
|
||||||
|
if phase == .blocked, let cancelled = tasks.first(where: { $0.status == 50 }) {
|
||||||
|
return usable(cancelled.statusLabel) ?? "任务已取消"
|
||||||
|
}
|
||||||
|
if phase == .blocked, response?.ui?.phase == "arrived_pending_start" { return "暂不可开始拍摄" }
|
||||||
|
if phase == .completed {
|
||||||
|
return usable(response?.ui?.phase == "completed" ? response?.ui?.title : nil)
|
||||||
|
?? tasks.first(where: { $0.status == 30 }).flatMap { usable($0.statusLabel) } ?? "拍摄已完成"
|
||||||
|
}
|
||||||
|
if phase == .unknown { return "状态待确认" }
|
||||||
|
if let title = usable(response?.ui?.title) { return title }
|
||||||
|
switch phase {
|
||||||
|
case .navigating: return "无人机正在前往拍摄点"
|
||||||
|
case .ready: return "无人机已到达"
|
||||||
|
case .shooting: return "正在拍摄"
|
||||||
|
case .paused: return "拍摄已暂停"
|
||||||
|
case .returning: return "无人机正在返航"
|
||||||
|
case .failed: return "任务执行失败"
|
||||||
|
case .blocked: return "当前任务暂不可执行"
|
||||||
|
default: return "状态待确认"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func usable(_ value: String?) -> String? { DroneDockHomeMetric.usableText(value) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 任务页六项读数的后端展示文本,保持服务端单位与零值。
|
||||||
|
struct DroneDockShootingTelemetry: Equatable, Sendable {
|
||||||
|
/// 电量读数。
|
||||||
|
let batteryText: String
|
||||||
|
/// 环境温度读数。
|
||||||
|
let temperatureText: String
|
||||||
|
/// 风速读数。
|
||||||
|
let windText: String
|
||||||
|
/// 雨量读数。
|
||||||
|
let rainText: String
|
||||||
|
/// 信号状态。
|
||||||
|
let signalText: String
|
||||||
|
/// 搜星状态。
|
||||||
|
let satelliteText: String
|
||||||
|
}
|
||||||
@@ -306,6 +306,9 @@ final class DroneDockHomeViewController: BaseViewController {
|
|||||||
DroneDockRemotePreparationViewController(viewModel: DroneDockPreparationViewModel(
|
DroneDockRemotePreparationViewController(viewModel: DroneDockPreparationViewModel(
|
||||||
context: context, order: order,
|
context: context, order: order,
|
||||||
service: DroneDockPreparationAPI(client: NetworkServices.shared.apiClient),
|
service: DroneDockPreparationAPI(client: NetworkServices.shared.apiClient),
|
||||||
|
planeStatusService: DroneDockPlaneStatusAPI(client: NetworkServices.shared.apiClient),
|
||||||
|
taskCreationService: DroneDockTaskCreationAPI(client: NetworkServices.shared.apiClient),
|
||||||
|
shootService: DroneDockShootAPI(client: NetworkServices.shared.apiClient),
|
||||||
currentContext: { Self.currentContext() }
|
currentContext: { Self.currentContext() }
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,22 @@ import UIKit
|
|||||||
enum DroneDockPreview {
|
enum DroneDockPreview {
|
||||||
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
|
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
|
||||||
static func navigationController(arguments: [String]) -> UINavigationController? {
|
static func navigationController(arguments: [String]) -> UINavigationController? {
|
||||||
|
// 仅打开已存在任务进行只读联调;不经过创建或召唤流程。
|
||||||
|
if let taskArgument = arguments.first(where: { $0.hasPrefix("--dock-task-live=") }),
|
||||||
|
let taskID = Int(taskArgument.dropFirst("--dock-task-live=".count)), taskID > 0,
|
||||||
|
let orderArgument = arguments.first(where: { $0.hasPrefix("--dock-task-order=") }),
|
||||||
|
AppStore.shared.session.isLoggedIn {
|
||||||
|
let number = String(orderArgument.dropFirst("--dock-task-order=".count)).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
if !number.isEmpty,
|
||||||
|
let data = try? JSONEncoder().encode(["order_number": number]),
|
||||||
|
let order = try? JSONDecoder().decode(DroneDockHomeOrder.self, from: data) {
|
||||||
|
let task = DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order,
|
||||||
|
context: DroneDockHomeViewController.currentContext())
|
||||||
|
let navigation = UINavigationController()
|
||||||
|
navigation.setViewControllers([DroneDockHomeViewController(), task], animated: false)
|
||||||
|
return navigation
|
||||||
|
}
|
||||||
|
}
|
||||||
if let argument = arguments.first(where: { $0.hasPrefix("--dock-delivery-live=") }), AppStore.shared.session.isLoggedIn {
|
if let argument = arguments.first(where: { $0.hasPrefix("--dock-delivery-live=") }), AppStore.shared.session.isLoggedIn {
|
||||||
let number = String(argument.dropFirst("--dock-delivery-live=".count))
|
let number = String(argument.dropFirst("--dock-delivery-live=".count))
|
||||||
if let data = try? JSONEncoder().encode(["order_number": number]),
|
if let data = try? JSONEncoder().encode(["order_number": number]),
|
||||||
@@ -29,6 +45,18 @@ enum DroneDockPreview {
|
|||||||
return navigation
|
return navigation
|
||||||
}
|
}
|
||||||
if arguments.contains("--dock-home-live"), AppStore.shared.session.isLoggedIn {
|
if arguments.contains("--dock-home-live"), AppStore.shared.session.isLoggedIn {
|
||||||
|
// 显式联调既有任务,只读取 shooting,避免为检查响应额外创建订单任务。
|
||||||
|
if let argument = arguments.first(where: { $0.hasPrefix("--dock-shooting-probe=") }),
|
||||||
|
let taskID = Int(argument.dropFirst("--dock-shooting-probe=".count)), taskID > 0 {
|
||||||
|
Task { @MainActor in
|
||||||
|
do {
|
||||||
|
_ = try await DroneDockShootingAPI(client: NetworkServices.shared.apiClient)
|
||||||
|
.shooting(taskID: taskID, liveBattery: true)
|
||||||
|
} catch {
|
||||||
|
print("[DroneDockShooting] Existing task read failed: \(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
return UINavigationController(rootViewController: DroneDockHomeViewController())
|
return UINavigationController(rootViewController: DroneDockHomeViewController())
|
||||||
}
|
}
|
||||||
let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview", "--dock-ui-materials-preview", "--dock-ui-delivery-preview", "--dock-ui-delivery-review-preview"]
|
let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview", "--dock-ui-materials-preview", "--dock-ui-delivery-preview", "--dock-ui-delivery-review-preview"]
|
||||||
|
|||||||
@@ -1,27 +1,41 @@
|
|||||||
import SnapKit
|
import SnapKit
|
||||||
import UIKit
|
import UIKit
|
||||||
|
|
||||||
/// 进入页面后通过 project-info 读取已购套餐、点位和航线。
|
/// 展示准备信息并提交召唤;业务成功后携同一任务 ID 进入真实拍摄任务页。
|
||||||
@MainActor
|
@MainActor
|
||||||
final class DroneDockRemotePreparationViewController: BaseViewController {
|
final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||||
/// 当前订单与准备页的真实读取状态。
|
/// 当前订单、准备信息及任务创建状态。
|
||||||
let viewModel: DroneDockPreparationViewModel
|
let viewModel: DroneDockPreparationViewModel
|
||||||
|
|
||||||
/// 点位与航线沿用原准备页顺序,状态区单独承载加载和错误说明。
|
/// 点位与航线沿用原准备页顺序,状态区单独承载加载和错误说明。
|
||||||
private enum Section: Int, CaseIterable { case order, points, routes, status }
|
private enum Section: Int, CaseIterable { case order, points, routes, status, creationResult, shootResult }
|
||||||
/// 点位与航线使用后端稳定 ID,刷新时保留有效选择。
|
/// 点位与航线使用后端稳定 ID,刷新时保留有效选择。
|
||||||
private enum Item: Hashable { case order, point(Int), route(Int), emptyPoints, emptyRoutes, status }
|
private enum Item: Hashable { case order, point(Int), route(Int), emptyPoints, emptyRoutes, status, creationResult, shootResult }
|
||||||
|
|
||||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||||
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
||||||
private let footerView = DronePreparationFooterView()
|
private let footerView = DronePreparationFooterView()
|
||||||
private let refreshControl = UIRefreshControl()
|
private let refreshControl = UIRefreshControl()
|
||||||
private var refreshTask: Task<Void, Never>?
|
private var refreshTask: Task<Void, Never>?
|
||||||
|
private var planeStatusTask: Task<Void, Never>?
|
||||||
|
private var creationTask: Task<Void, Never>?
|
||||||
|
private var isStartingCreation = false
|
||||||
|
private let planeStatusPollDelay: @Sendable (UInt64) async throws -> Void
|
||||||
private var isRefreshing = false
|
private var isRefreshing = false
|
||||||
|
private var isPageVisible = false
|
||||||
|
private var isApplicationActive = false
|
||||||
|
private var automaticallyOpenedTaskID: Int?
|
||||||
|
private let taskControllerFactory: @MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
|
||||||
|
|
||||||
/// 注入只读状态源,不初始化本地演示订单或任务。
|
/// 注入准备页业务状态和轮询等待,便于验证任务创建及页面生命周期。
|
||||||
init(viewModel: DroneDockPreparationViewModel) {
|
init(viewModel: DroneDockPreparationViewModel,
|
||||||
|
taskControllerFactory: (@MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
|
||||||
|
planeStatusPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
|
||||||
self.viewModel = viewModel
|
self.viewModel = viewModel
|
||||||
|
self.taskControllerFactory = taskControllerFactory ?? { taskID, order, context in
|
||||||
|
DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context)
|
||||||
|
}
|
||||||
|
self.planeStatusPollDelay = planeStatusPollDelay
|
||||||
super.init(nibName: nil, bundle: nil)
|
super.init(nibName: nil, bundle: nil)
|
||||||
hidesBottomBarWhenPushed = true
|
hidesBottomBarWhenPushed = true
|
||||||
}
|
}
|
||||||
@@ -29,7 +43,12 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
|||||||
@available(*, unavailable)
|
@available(*, unavailable)
|
||||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
deinit { refreshTask?.cancel() }
|
deinit {
|
||||||
|
refreshTask?.cancel()
|
||||||
|
planeStatusTask?.cancel()
|
||||||
|
creationTask?.cancel()
|
||||||
|
NotificationCenter.default.removeObserver(self)
|
||||||
|
}
|
||||||
|
|
||||||
override func setupNavigationBar() {
|
override func setupNavigationBar() {
|
||||||
title = "拍摄准备"
|
title = "拍摄准备"
|
||||||
@@ -47,6 +66,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
|||||||
collectionView.register(DronePreparationPointCell.self, forCellWithReuseIdentifier: "point")
|
collectionView.register(DronePreparationPointCell.self, forCellWithReuseIdentifier: "point")
|
||||||
collectionView.register(DronePreparationRouteCell.self, forCellWithReuseIdentifier: "route")
|
collectionView.register(DronePreparationRouteCell.self, forCellWithReuseIdentifier: "route")
|
||||||
collectionView.register(DronePreparationEmptyCell.self, forCellWithReuseIdentifier: "message")
|
collectionView.register(DronePreparationEmptyCell.self, forCellWithReuseIdentifier: "message")
|
||||||
|
collectionView.register(DroneDockTaskCreationResultCell.self, forCellWithReuseIdentifier: "creationResult")
|
||||||
collectionView.register(DronePreparationHeadingView.self,
|
collectionView.register(DronePreparationHeadingView.self,
|
||||||
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
|
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
|
||||||
withReuseIdentifier: "heading")
|
withReuseIdentifier: "heading")
|
||||||
@@ -70,22 +90,35 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
|||||||
override func bindActions() {
|
override func bindActions() {
|
||||||
refreshControl.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged)
|
refreshControl.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged)
|
||||||
footerView.onRefreshTap = { [weak self] in self?.refreshPreparation() }
|
footerView.onRefreshTap = { [weak self] in self?.refreshPreparation() }
|
||||||
|
footerView.onPrimaryTap = { [weak self] in self?.createSelectedTask() }
|
||||||
|
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
|
||||||
|
name: UIApplication.willResignActiveNotification, object: nil)
|
||||||
|
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
|
||||||
|
name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
override func viewWillAppear(_ animated: Bool) {
|
override func viewWillAppear(_ animated: Bool) {
|
||||||
super.viewWillAppear(animated)
|
super.viewWillAppear(animated)
|
||||||
|
isPageVisible = true
|
||||||
|
isApplicationActive = UIApplication.shared.applicationState == .active
|
||||||
refreshPreparation()
|
refreshPreparation()
|
||||||
}
|
}
|
||||||
|
|
||||||
override func viewWillDisappear(_ animated: Bool) {
|
override func viewWillDisappear(_ animated: Bool) {
|
||||||
super.viewWillDisappear(animated)
|
super.viewWillDisappear(animated)
|
||||||
|
isPageVisible = false
|
||||||
|
stopPlaneStatusPolling()
|
||||||
refreshTask?.cancel()
|
refreshTask?.cancel()
|
||||||
|
creationTask?.cancel()
|
||||||
|
isStartingCreation = false
|
||||||
isRefreshing = false
|
isRefreshing = false
|
||||||
refreshControl.endRefreshing()
|
refreshControl.endRefreshing()
|
||||||
viewModel.invalidate()
|
viewModel.invalidate()
|
||||||
}
|
}
|
||||||
|
|
||||||
private func refreshPreparation() {
|
private func refreshPreparation() {
|
||||||
|
guard !isStartingCreation, !viewModel.isCreatingTask, !viewModel.isSummoning else { refreshControl.endRefreshing(); return }
|
||||||
|
startPlaneStatusPolling()
|
||||||
guard !isRefreshing else { return }
|
guard !isRefreshing else { return }
|
||||||
isRefreshing = true
|
isRefreshing = true
|
||||||
refreshTask = Task { @MainActor [weak self] in
|
refreshTask = Task { @MainActor [weak self] in
|
||||||
@@ -109,13 +142,93 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 首次创建并召唤;成功后进入原任务,再次查看不经过创建或召唤接口。
|
||||||
|
private func createSelectedTask() {
|
||||||
|
guard !isRefreshing, !isStartingCreation else { return }
|
||||||
|
if viewModel.canOpenShootingTask {
|
||||||
|
_ = openShootingTask(automatically: false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
guard viewModel.isPrimaryActionEnabled else { return }
|
||||||
|
isStartingCreation = true
|
||||||
|
applySnapshot(animated: false)
|
||||||
|
creationTask = Task { @MainActor [weak self] in
|
||||||
|
guard let self else { return }
|
||||||
|
await self.viewModel.prepareAndSummon { [weak self] in self?.applySnapshot(animated: false) }
|
||||||
|
guard !Task.isCancelled else { return }
|
||||||
|
self.isStartingCreation = false
|
||||||
|
if self.openShootingTask(automatically: true) { return }
|
||||||
|
self.applySnapshot(animated: true) { [weak self] in
|
||||||
|
guard let self,
|
||||||
|
let path = self.dataSource.indexPath(for: .shootResult) ?? self.dataSource.indexPath(for: .creationResult) else { return }
|
||||||
|
self.collectionView.scrollToItem(at: path, at: .top, animated: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 只在准备页可见且召唤已成功时导航一次;返回后允许主动查看同一任务。
|
||||||
|
@discardableResult
|
||||||
|
private func openShootingTask(automatically: Bool) -> Bool {
|
||||||
|
guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask,
|
||||||
|
let taskID = viewModel.createdTask?.taskID,
|
||||||
|
let navigationController, navigationController.topViewController === self,
|
||||||
|
!automatically || automaticallyOpenedTaskID != taskID else { return false }
|
||||||
|
automaticallyOpenedTaskID = taskID
|
||||||
|
let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context)
|
||||||
|
navigationController.pushViewController(controller, animated: true)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 设备请求与购买快照各自更新,轮询不重载列表或改变点位、航线选择。
|
||||||
|
private func startPlaneStatusPolling() {
|
||||||
|
guard isPageVisible, isApplicationActive else { return }
|
||||||
|
stopPlaneStatusPolling()
|
||||||
|
let delay = planeStatusPollDelay
|
||||||
|
planeStatusTask = Task { @MainActor [weak self] in
|
||||||
|
while !Task.isCancelled {
|
||||||
|
guard let interval = await self?.refreshPlaneStatusIfVisible() else { return }
|
||||||
|
do { try await delay(interval) }
|
||||||
|
catch { return }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func refreshPlaneStatusIfVisible() async -> UInt64? {
|
||||||
|
guard isPageVisible, isApplicationActive, !Task.isCancelled else { return nil }
|
||||||
|
await viewModel.refreshPlaneStatus()
|
||||||
|
guard isPageVisible, isApplicationActive, !Task.isCancelled else { return nil }
|
||||||
|
if viewModel.errorMessage != nil {
|
||||||
|
applySnapshot(animated: false)
|
||||||
|
} else {
|
||||||
|
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
|
||||||
|
}
|
||||||
|
return viewModel.pollIntervalNanoseconds
|
||||||
|
}
|
||||||
|
|
||||||
|
private func stopPlaneStatusPolling() {
|
||||||
|
planeStatusTask?.cancel()
|
||||||
|
planeStatusTask = nil
|
||||||
|
viewModel.invalidatePlaneStatus()
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func applicationWillResignActive() {
|
||||||
|
isApplicationActive = false
|
||||||
|
stopPlaneStatusPolling()
|
||||||
|
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func applicationDidBecomeActive() {
|
||||||
|
isApplicationActive = true
|
||||||
|
startPlaneStatusPolling()
|
||||||
|
}
|
||||||
|
|
||||||
private func configureDataSource() {
|
private func configureDataSource() {
|
||||||
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, path, item in
|
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, path, item in
|
||||||
guard let self else { return nil }
|
guard let self else { return nil }
|
||||||
switch item {
|
switch item {
|
||||||
case .order:
|
case .order:
|
||||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: path) as! DronePreparationOrderCell
|
let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: path) as! DronePreparationOrderCell
|
||||||
cell.apply(homeOrder: self.viewModel.order, summary: self.viewModel.projectInfo?.order,
|
cell.apply(homeOrder: self.viewModel.order, summary: self.viewModel.latestOrderSummary,
|
||||||
usesHomeSnapshot: self.viewModel.projectInfo == nil && self.viewModel.errorMessage == nil)
|
usesHomeSnapshot: self.viewModel.projectInfo == nil && self.viewModel.errorMessage == nil)
|
||||||
return cell
|
return cell
|
||||||
case .point(let id):
|
case .point(let id):
|
||||||
@@ -130,6 +243,20 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
|||||||
cell.apply(route: route, selected: self.viewModel.selectedRouteID == id)
|
cell.apply(route: route, selected: self.viewModel.selectedRouteID == id)
|
||||||
}
|
}
|
||||||
return cell
|
return cell
|
||||||
|
case .creationResult:
|
||||||
|
let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell
|
||||||
|
cell.apply(task: self.viewModel.createdTask, errorMessage: self.viewModel.taskCreationErrorMessage,
|
||||||
|
outcomeUnknown: self.viewModel.taskCreationOutcomeUnknown)
|
||||||
|
return cell
|
||||||
|
case .shootResult:
|
||||||
|
let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell
|
||||||
|
cell.applyShoot(taskID: self.viewModel.createdTask?.taskID,
|
||||||
|
dataJSON: self.viewModel.shootDataJSON,
|
||||||
|
errorMessage: self.viewModel.shootErrorMessage,
|
||||||
|
isLoading: self.viewModel.isSummoning,
|
||||||
|
hasSucceeded: self.viewModel.shootResponse != nil,
|
||||||
|
outcomeUnknown: self.viewModel.summonOutcomeUnknown)
|
||||||
|
return cell
|
||||||
case .emptyPoints, .emptyRoutes, .status:
|
case .emptyPoints, .emptyRoutes, .status:
|
||||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DronePreparationEmptyCell
|
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DronePreparationEmptyCell
|
||||||
if item == .status {
|
if item == .status {
|
||||||
@@ -177,8 +304,15 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
|||||||
} else {
|
} else {
|
||||||
snapshot.appendItems([.status], toSection: .status)
|
snapshot.appendItems([.status], toSection: .status)
|
||||||
}
|
}
|
||||||
|
if viewModel.createdTask != nil || (viewModel.errorMessage == nil && viewModel.projectInfo != nil && viewModel.taskCreationErrorMessage != nil) {
|
||||||
|
snapshot.appendItems([.creationResult], toSection: .creationResult)
|
||||||
|
}
|
||||||
|
if viewModel.createdTask != nil,
|
||||||
|
viewModel.isSummoning || viewModel.shootResponse != nil || viewModel.shootErrorMessage != nil {
|
||||||
|
snapshot.appendItems([.shootResult], toSection: .shootResult)
|
||||||
|
}
|
||||||
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
|
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
|
||||||
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing)
|
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
|
||||||
let previousPointCount = previous.sectionIdentifiers.contains(.points) ? previous.numberOfItems(inSection: .points) : 0
|
let previousPointCount = previous.sectionIdentifiers.contains(.points) ? previous.numberOfItems(inSection: .points) : 0
|
||||||
let previousRouteCount = previous.sectionIdentifiers.contains(.routes) ? previous.numberOfItems(inSection: .routes) : 0
|
let previousRouteCount = previous.sectionIdentifiers.contains(.routes) ? previous.numberOfItems(inSection: .routes) : 0
|
||||||
let layoutChanged = previousPointCount != snapshot.numberOfItems(inSection: .points)
|
let layoutChanged = previousPointCount != snapshot.numberOfItems(inSection: .points)
|
||||||
@@ -212,11 +346,13 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
|||||||
height = self.viewModel.routes.isEmpty ? .absolute(160) : .estimated(64)
|
height = self.viewModel.routes.isEmpty ? .absolute(160) : .estimated(64)
|
||||||
width = .fractionalWidth(1)
|
width = .fractionalWidth(1)
|
||||||
case .status: height = .absolute(160); width = .fractionalWidth(1)
|
case .status: height = .absolute(160); width = .fractionalWidth(1)
|
||||||
|
case .creationResult: height = .absolute(380); width = .fractionalWidth(1)
|
||||||
|
case .shootResult: height = .absolute(420); width = .fractionalWidth(1)
|
||||||
}
|
}
|
||||||
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height))
|
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height))
|
||||||
let group = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item])
|
let group = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item])
|
||||||
let layout = NSCollectionLayoutSection(group: group)
|
let layout = NSCollectionLayoutSection(group: group)
|
||||||
layout.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: section == .status ? 12 : 0, trailing: 16)
|
layout.contentInsets = NSDirectionalEdgeInsets(top: section == .shootResult ? 12 : 0, leading: 16, bottom: section == .status ? 12 : 0, trailing: 16)
|
||||||
if section == .points, !self.viewModel.spots.isEmpty {
|
if section == .points, !self.viewModel.spots.isEmpty {
|
||||||
layout.orthogonalScrollingBehavior = .continuous
|
layout.orthogonalScrollingBehavior = .continuous
|
||||||
layout.interGroupSpacing = 8
|
layout.interGroupSpacing = 8
|
||||||
@@ -265,7 +401,9 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
|||||||
extension DroneDockRemotePreparationViewController: UICollectionViewDelegate {
|
extension DroneDockRemotePreparationViewController: UICollectionViewDelegate {
|
||||||
/// 点位和航线只在当前成功快照中选择,刷新期间不切换旧配置。
|
/// 点位和航线只在当前成功快照中选择,刷新期间不切换旧配置。
|
||||||
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
|
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
|
||||||
guard !isRefreshing, viewModel.projectInfo != nil, viewModel.errorMessage == nil,
|
guard !isRefreshing, !isStartingCreation, !viewModel.isCreatingTask,
|
||||||
|
viewModel.createdTask == nil, !viewModel.taskCreationOutcomeUnknown,
|
||||||
|
viewModel.projectInfo != nil, viewModel.errorMessage == nil,
|
||||||
let item = dataSource.itemIdentifier(for: indexPath) else { return false }
|
let item = dataSource.itemIdentifier(for: indexPath) else { return false }
|
||||||
switch item {
|
switch item {
|
||||||
case .point(let id): return viewModel.spots.first { $0.id == id }?.available == true
|
case .point(let id): return viewModel.spots.first { $0.id == id }?.available == true
|
||||||
@@ -276,7 +414,9 @@ extension DroneDockRemotePreparationViewController: UICollectionViewDelegate {
|
|||||||
|
|
||||||
/// 更新本地点位、航线及底部摘要,不创建拍摄任务。
|
/// 更新本地点位、航线及底部摘要,不创建拍摄任务。
|
||||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||||
guard !isRefreshing, let item = dataSource.itemIdentifier(for: indexPath) else { return }
|
guard !isRefreshing, !isStartingCreation, !viewModel.isCreatingTask,
|
||||||
|
viewModel.createdTask == nil, !viewModel.taskCreationOutcomeUnknown,
|
||||||
|
let item = dataSource.itemIdentifier(for: indexPath) else { return }
|
||||||
switch item {
|
switch item {
|
||||||
case .point(let id): viewModel.selectSpot(id: id)
|
case .point(let id): viewModel.selectSpot(id: id)
|
||||||
case .route(let id): viewModel.selectRoute(id: id)
|
case .route(let id): viewModel.selectRoute(id: id)
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import UIKit
|
||||||
|
|
||||||
|
/// 组装真实拍摄任务页;构造时不发请求,页面出现后才读取同一任务。
|
||||||
|
@MainActor
|
||||||
|
enum DroneDockShootingTaskEntry {
|
||||||
|
/// 使用当前共享网络服务读取已创建、已召唤任务,不创建或控制无人机。
|
||||||
|
static func makeController(taskID: Int, order: DroneDockHomeOrder,
|
||||||
|
context: DroneDockHomeContext) -> UIViewController {
|
||||||
|
DroneDockShootingTaskViewController(viewModel: DroneDockShootingTaskViewModel(
|
||||||
|
context: context, taskID: taskID, order: order,
|
||||||
|
service: DroneDockShootingAPI(client: NetworkServices.shared.apiClient),
|
||||||
|
currentContext: { DroneDockHomeViewController.currentContext() }
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,344 @@
|
|||||||
|
import SnapKit
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
/// 真实拍摄任务页:进入后仅查询同一任务,展示状态与遥测,不发送飞行控制。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockShootingTaskViewController: BaseViewController {
|
||||||
|
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
|
||||||
|
let viewModel: DroneDockShootingTaskViewModel
|
||||||
|
|
||||||
|
private let topView = UIView()
|
||||||
|
private let summaryView = UIView()
|
||||||
|
private let taskTitleLabel = DroneDockStyle.label(size: 17, weight: .semibold)
|
||||||
|
private let subtitleLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||||
|
private let feedPlaceholder = DroneDockTaskFeedPlaceholderView()
|
||||||
|
private let telemetryView = DroneShootingTaskTelemetryView()
|
||||||
|
private let statusView = DroneDockTaskStatusView()
|
||||||
|
private let safetyView = DroneDockTaskSafetyView()
|
||||||
|
private var summaryHeight: Constraint?
|
||||||
|
private var safetyHeight: Constraint?
|
||||||
|
private var compactLayout: Bool?
|
||||||
|
private var bottomInset: CGFloat = -1
|
||||||
|
private let materialsControllerFactory: @MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
|
||||||
|
private var refreshTask: Task<Void, Never>?
|
||||||
|
private var requestGeneration = 0
|
||||||
|
private var isPageVisible = false
|
||||||
|
private var isApplicationActive = false
|
||||||
|
private var isRequesting = false
|
||||||
|
|
||||||
|
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
|
||||||
|
init(viewModel: DroneDockShootingTaskViewModel,
|
||||||
|
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
|
||||||
|
self.viewModel = viewModel
|
||||||
|
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
|
||||||
|
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
|
||||||
|
context: context, order: order,
|
||||||
|
service: DroneDockMaterialsAPI(client: NetworkServices.shared.apiClient),
|
||||||
|
currentContext: { DroneDockHomeViewController.currentContext() }))
|
||||||
|
}
|
||||||
|
super.init(nibName: nil, bundle: nil)
|
||||||
|
hidesBottomBarWhenPushed = true
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
refreshTask?.cancel()
|
||||||
|
NotificationCenter.default.removeObserver(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 使用常规导航返回准备页,不劫持返回手势或自动创建任务。
|
||||||
|
override func setupNavigationBar() {
|
||||||
|
title = "拍摄任务"
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 顶部、中间状态和安全控制分开布局,状态切换不影响外部区域大小。
|
||||||
|
override func setupUI() {
|
||||||
|
view.backgroundColor = .white
|
||||||
|
topView.accessibilityIdentifier = "drone.task.remote.top"
|
||||||
|
summaryView.accessibilityIdentifier = "drone.task.remote.summary"
|
||||||
|
statusView.accessibilityIdentifier = "drone.task.remote.stateContainer"
|
||||||
|
safetyView.accessibilityIdentifier = "drone.task.remote.safety"
|
||||||
|
view.addSubview(topView)
|
||||||
|
view.addSubview(statusView)
|
||||||
|
view.addSubview(safetyView)
|
||||||
|
topView.addSubview(summaryView)
|
||||||
|
summaryView.addSubview(taskTitleLabel)
|
||||||
|
summaryView.addSubview(subtitleLabel)
|
||||||
|
taskTitleLabel.numberOfLines = 1
|
||||||
|
taskTitleLabel.lineBreakMode = .byTruncatingTail
|
||||||
|
taskTitleLabel.accessibilityIdentifier = "drone.task.remote.title"
|
||||||
|
subtitleLabel.numberOfLines = 1
|
||||||
|
subtitleLabel.lineBreakMode = .byTruncatingTail
|
||||||
|
subtitleLabel.accessibilityIdentifier = "drone.task.remote.subtitle"
|
||||||
|
topView.addSubview(feedPlaceholder)
|
||||||
|
topView.addSubview(telemetryView)
|
||||||
|
telemetryView.accessibilityIdentifier = "drone.task.remote.telemetry"
|
||||||
|
telemetryView.configureFixedLayout(compact: false)
|
||||||
|
applySnapshot()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 图传保持 16:9,底部贴安全区,中间占满剩余空间且没有滚动容器。
|
||||||
|
override func setupConstraints() {
|
||||||
|
topView.snp.makeConstraints { make in
|
||||||
|
make.top.equalTo(view.safeAreaLayoutGuide)
|
||||||
|
make.leading.trailing.equalToSuperview()
|
||||||
|
}
|
||||||
|
summaryView.snp.makeConstraints { make in
|
||||||
|
make.top.leading.trailing.equalToSuperview()
|
||||||
|
summaryHeight = make.height.equalTo(60).constraint
|
||||||
|
}
|
||||||
|
taskTitleLabel.snp.makeConstraints { make in
|
||||||
|
make.leading.trailing.equalToSuperview().inset(16)
|
||||||
|
make.bottom.equalTo(summaryView.snp.centerY).offset(-1)
|
||||||
|
}
|
||||||
|
subtitleLabel.snp.makeConstraints { make in
|
||||||
|
make.leading.trailing.equalToSuperview().inset(16)
|
||||||
|
make.top.equalTo(summaryView.snp.centerY).offset(2)
|
||||||
|
}
|
||||||
|
feedPlaceholder.snp.makeConstraints { make in
|
||||||
|
make.top.equalTo(summaryView.snp.bottom)
|
||||||
|
make.leading.trailing.equalToSuperview()
|
||||||
|
make.height.equalTo(feedPlaceholder.snp.width).multipliedBy(9.0 / 16.0)
|
||||||
|
}
|
||||||
|
telemetryView.snp.makeConstraints { make in
|
||||||
|
make.top.equalTo(feedPlaceholder.snp.bottom)
|
||||||
|
make.leading.trailing.bottom.equalToSuperview()
|
||||||
|
}
|
||||||
|
safetyView.snp.makeConstraints { make in
|
||||||
|
make.leading.trailing.bottom.equalToSuperview()
|
||||||
|
safetyHeight = make.height.equalTo(104).constraint
|
||||||
|
}
|
||||||
|
statusView.snp.makeConstraints { make in
|
||||||
|
make.top.equalTo(topView.snp.bottom)
|
||||||
|
make.bottom.equalTo(safetyView.snp.top)
|
||||||
|
make.leading.trailing.equalToSuperview()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 只按设备可用尺寸调整固定区域,数据、错误和加载状态不会改变它们的高度。
|
||||||
|
override func viewDidLayoutSubviews() {
|
||||||
|
super.viewDidLayoutSubviews()
|
||||||
|
let availableHeight = view.bounds.height - view.safeAreaInsets.top - view.safeAreaInsets.bottom
|
||||||
|
let compact = availableHeight < 680
|
||||||
|
let inset = view.safeAreaInsets.bottom
|
||||||
|
guard compactLayout != compact || bottomInset != inset else { return }
|
||||||
|
compactLayout = compact
|
||||||
|
bottomInset = inset
|
||||||
|
summaryHeight?.update(offset: compact ? 44 : 60)
|
||||||
|
safetyHeight?.update(offset: (compact ? 90 : 104) + inset)
|
||||||
|
telemetryView.configureFixedLayout(compact: compact)
|
||||||
|
safetyView.configure(compact: compact)
|
||||||
|
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() }
|
||||||
|
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
|
||||||
|
name: UIApplication.willResignActiveNotification, object: nil)
|
||||||
|
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
|
||||||
|
name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 每次完整进入任务页只查询一次,不定时重读同一任务。
|
||||||
|
override func viewDidAppear(_ animated: Bool) {
|
||||||
|
super.viewDidAppear(animated)
|
||||||
|
isPageVisible = true
|
||||||
|
isApplicationActive = UIApplication.shared.applicationState == .active
|
||||||
|
refreshTaskIfVisible()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 离页立即取消未完成的读取,使迟到响应失效。
|
||||||
|
override func viewWillDisappear(_ animated: Bool) {
|
||||||
|
super.viewWillDisappear(animated)
|
||||||
|
isPageVisible = false
|
||||||
|
cancelRefresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func applySnapshot() {
|
||||||
|
guard isViewLoaded else { return }
|
||||||
|
let loading = isRequesting || viewModel.isLoading
|
||||||
|
taskTitleLabel.text = viewModel.title
|
||||||
|
subtitleLabel.text = viewModel.subtitle
|
||||||
|
let telemetry = viewModel.telemetry
|
||||||
|
telemetryView.apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText,
|
||||||
|
telemetry.rainText, telemetry.signalText, telemetry.satelliteText],
|
||||||
|
isStale: loading || viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric")
|
||||||
|
let value = loading ? DroneDockTaskPresentation(
|
||||||
|
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
|
||||||
|
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation
|
||||||
|
statusView.apply(value)
|
||||||
|
statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading
|
||||||
|
navigationItem.rightBarButtonItem?.isEnabled = isPageVisible && isApplicationActive && !loading
|
||||||
|
}
|
||||||
|
|
||||||
|
private func primaryActionTriggered() {
|
||||||
|
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return }
|
||||||
|
let state = viewModel.presentation
|
||||||
|
guard state.isActionEnabled else { return }
|
||||||
|
switch state.action {
|
||||||
|
case .refresh:
|
||||||
|
refreshTaskIfVisible()
|
||||||
|
case .materials:
|
||||||
|
guard let navigationController, navigationController.topViewController === self else { return }
|
||||||
|
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
|
||||||
|
case .start, .resume, .none:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func showStatusDetails() {
|
||||||
|
guard isPageVisible, isApplicationActive, presentedViewController == nil else { return }
|
||||||
|
let state = viewModel.presentation
|
||||||
|
let texts = [state.title, state.message, state.deviceStatus].filter { !$0.isEmpty && $0 != "—" }
|
||||||
|
var 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)
|
||||||
|
alert.addAction(UIAlertAction(title: "关闭", style: .cancel))
|
||||||
|
present(alert, animated: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 页面进入、回到前台或手动刷新时各读一次,请求结束后不安排下一次读取。
|
||||||
|
private func refreshTaskIfVisible() {
|
||||||
|
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return }
|
||||||
|
requestGeneration &+= 1
|
||||||
|
let generation = requestGeneration
|
||||||
|
isRequesting = true
|
||||||
|
applySnapshot()
|
||||||
|
refreshTask = Task { @MainActor [weak self] in
|
||||||
|
guard let self else { return }
|
||||||
|
await self.viewModel.refresh()
|
||||||
|
guard self.isPageVisible, self.isApplicationActive,
|
||||||
|
self.requestGeneration == generation, !Task.isCancelled else { return }
|
||||||
|
self.refreshTask = nil
|
||||||
|
self.isRequesting = false
|
||||||
|
self.applySnapshot()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func cancelRefresh() {
|
||||||
|
requestGeneration &+= 1
|
||||||
|
refreshTask?.cancel()
|
||||||
|
refreshTask = nil
|
||||||
|
isRequesting = false
|
||||||
|
viewModel.invalidate()
|
||||||
|
applySnapshot()
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func refreshTriggered() {
|
||||||
|
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
refreshTaskIfVisible()
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func applicationWillResignActive() {
|
||||||
|
isApplicationActive = false
|
||||||
|
cancelRefresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func applicationDidBecomeActive() {
|
||||||
|
guard !isApplicationActive else { return }
|
||||||
|
isApplicationActive = true
|
||||||
|
refreshTaskIfVisible()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 固定底部的安全控制占位,尚未接入控制接口时不提供可执行的飞控动作。
|
||||||
|
@MainActor
|
||||||
|
private final class DroneDockTaskSafetyView: UIView {
|
||||||
|
private let header = DroneDockStyle.label("安全控制", size: 11, color: DroneDockStyle.secondary)
|
||||||
|
private let pauseButton = DroneShootingTaskSafetyButton(symbol: "pause.circle", color: UIColor(hex: 0xEC982A), filled: true)
|
||||||
|
private let returnButton = DroneShootingTaskSafetyButton(symbol: "arrow.uturn.backward", color: UIColor(hex: 0xD85762), filled: false)
|
||||||
|
private let buttons = UIStackView()
|
||||||
|
private var headerTop: Constraint?
|
||||||
|
private var headerHeight: Constraint?
|
||||||
|
private var buttonGap: Constraint?
|
||||||
|
private var buttonHeight: Constraint?
|
||||||
|
|
||||||
|
/// 复用安全按钮样式,按钮始终保留占位与明确的不可用状态。
|
||||||
|
override init(frame: CGRect) {
|
||||||
|
super.init(frame: frame)
|
||||||
|
backgroundColor = .white
|
||||||
|
let divider = UIView()
|
||||||
|
divider.backgroundColor = DroneDockStyle.border
|
||||||
|
addSubview(divider)
|
||||||
|
divider.snp.makeConstraints { make in
|
||||||
|
make.top.leading.trailing.equalToSuperview()
|
||||||
|
make.height.equalTo(0.5)
|
||||||
|
}
|
||||||
|
header.textAlignment = .center
|
||||||
|
addSubview(header)
|
||||||
|
buttons.axis = .horizontal
|
||||||
|
buttons.spacing = 8
|
||||||
|
buttons.distribution = .fillEqually
|
||||||
|
buttons.addArrangedSubview(pauseButton)
|
||||||
|
buttons.addArrangedSubview(returnButton)
|
||||||
|
addSubview(buttons)
|
||||||
|
pauseButton.accessibilityIdentifier = "drone.task.remote.pause"
|
||||||
|
returnButton.accessibilityIdentifier = "drone.task.remote.return"
|
||||||
|
pauseButton.apply(title: "紧急暂停", subtitle: "暂不可用", enabled: false)
|
||||||
|
returnButton.apply(title: "立即返航", subtitle: "暂不可用", enabled: false)
|
||||||
|
header.snp.makeConstraints { make in
|
||||||
|
headerTop = make.top.equalToSuperview().offset(10).constraint
|
||||||
|
make.leading.trailing.equalToSuperview().inset(16)
|
||||||
|
headerHeight = make.height.equalTo(14).constraint
|
||||||
|
}
|
||||||
|
buttons.snp.makeConstraints { make in
|
||||||
|
buttonGap = make.top.equalTo(header.snp.bottom).offset(8).constraint
|
||||||
|
make.leading.trailing.equalToSuperview().inset(16)
|
||||||
|
buttonHeight = make.height.equalTo(62).constraint
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
|
/// 高度仅依设备空间切换,不随任务状态、按钮文案或网络响应变化。
|
||||||
|
func configure(compact: Bool) {
|
||||||
|
headerTop?.update(offset: compact ? 8 : 10)
|
||||||
|
headerHeight?.update(offset: compact ? 12 : 14)
|
||||||
|
buttonGap?.update(offset: compact ? 6 : 8)
|
||||||
|
buttonHeight?.update(offset: compact ? 56 : 62)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 真实图传尚未接入时的中性占位,不使用演示图片、播放进度或虚假连接状态。
|
||||||
|
@MainActor
|
||||||
|
private final class DroneDockTaskFeedPlaceholderView: UIView {
|
||||||
|
override init(frame: CGRect) {
|
||||||
|
super.init(frame: frame)
|
||||||
|
backgroundColor = UIColor(hex: 0x172033)
|
||||||
|
accessibilityIdentifier = "drone.task.remote.feedPlaceholder"
|
||||||
|
let icon = UIImageView(image: UIImage(systemName: "video.slash"))
|
||||||
|
icon.contentMode = .scaleAspectFit
|
||||||
|
icon.tintColor = UIColor.white.withAlphaComponent(0.6)
|
||||||
|
let title = DroneDockStyle.label("图传暂未接入", size: 15, weight: .medium, color: .white)
|
||||||
|
let detail = DroneDockStyle.label("任务状态将在下方更新", size: 12, color: .white.withAlphaComponent(0.65))
|
||||||
|
let stack = UIStackView(arrangedSubviews: [icon, title, detail])
|
||||||
|
stack.axis = .vertical
|
||||||
|
stack.spacing = 9
|
||||||
|
stack.alignment = .center
|
||||||
|
addSubview(stack)
|
||||||
|
icon.snp.makeConstraints { make in make.size.equalTo(31) }
|
||||||
|
stack.snp.makeConstraints { make in
|
||||||
|
make.center.equalToSuperview()
|
||||||
|
make.leading.greaterThanOrEqualToSuperview().offset(20)
|
||||||
|
make.trailing.lessThanOrEqualToSuperview().offset(-20)
|
||||||
|
}
|
||||||
|
isAccessibilityElement = true
|
||||||
|
accessibilityLabel = "图传暂未接入,任务状态将在下方更新"
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import SnapKit
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
/// 在准备页展示任务创建或召唤请求的回执,保留 data 原文结构并支持滚动与选择文本。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockTaskCreationResultCell: UICollectionViewCell {
|
||||||
|
private let titleLabel = DroneDockStyle.label(size: 16, weight: .semibold)
|
||||||
|
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||||
|
private let responseView = UITextView()
|
||||||
|
|
||||||
|
override init(frame: CGRect) {
|
||||||
|
super.init(frame: frame)
|
||||||
|
contentView.backgroundColor = DroneDockStyle.background
|
||||||
|
contentView.layer.cornerRadius = 10
|
||||||
|
titleLabel.numberOfLines = 0
|
||||||
|
detailLabel.numberOfLines = 0
|
||||||
|
responseView.backgroundColor = .clear
|
||||||
|
responseView.isEditable = false
|
||||||
|
responseView.isSelectable = true
|
||||||
|
responseView.alwaysBounceVertical = true
|
||||||
|
responseView.textContainerInset = .zero
|
||||||
|
responseView.textContainer.lineFragmentPadding = 0
|
||||||
|
responseView.accessibilityIdentifier = "drone.preparation.creationResponse"
|
||||||
|
[titleLabel, detailLabel, responseView].forEach(contentView.addSubview)
|
||||||
|
titleLabel.snp.makeConstraints { make in
|
||||||
|
make.top.leading.trailing.equalToSuperview().inset(12)
|
||||||
|
}
|
||||||
|
detailLabel.snp.makeConstraints { make in
|
||||||
|
make.top.equalTo(titleLabel.snp.bottom).offset(6)
|
||||||
|
make.leading.trailing.equalTo(titleLabel)
|
||||||
|
}
|
||||||
|
responseView.snp.makeConstraints { make in
|
||||||
|
make.top.equalTo(detailLabel.snp.bottom).offset(12)
|
||||||
|
make.leading.trailing.equalTo(titleLabel)
|
||||||
|
make.bottom.equalToSuperview().inset(12)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
|
/// 成功保留完整 data,失败显示真实错误,不构造任务 ID 或成功响应。
|
||||||
|
func apply(task: DroneDockCreatedTask?, errorMessage: String?, outcomeUnknown: Bool) {
|
||||||
|
responseView.accessibilityIdentifier = "drone.preparation.creationResponse"
|
||||||
|
if let task {
|
||||||
|
titleLabel.text = "任务已创建 · ID \(task.taskID)"
|
||||||
|
titleLabel.textColor = DroneDockStyle.success
|
||||||
|
detailLabel.text = "tasks/create 返回的 data"
|
||||||
|
responseView.font = .monospacedSystemFont(ofSize: 12, weight: .regular)
|
||||||
|
if responseView.text != task.dataJSON { responseView.text = task.dataJSON }
|
||||||
|
} else {
|
||||||
|
titleLabel.text = outcomeUnknown ? "任务创建结果待确认" : "任务创建未成功"
|
||||||
|
titleLabel.textColor = DroneDockStyle.warning
|
||||||
|
detailLabel.text = outcomeUnknown ? "请先核对订单任务,避免重复创建" : "接口返回的错误信息"
|
||||||
|
responseView.font = .systemFont(ofSize: 14)
|
||||||
|
responseView.text = errorMessage
|
||||||
|
}
|
||||||
|
responseView.textColor = DroneDockStyle.text
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 展示 shoot 回执;提交成功不代表无人机已到达,结果未知不能引导直接重发。
|
||||||
|
func applyShoot(taskID: Int?, dataJSON: String?, errorMessage: String?, isLoading: Bool,
|
||||||
|
hasSucceeded: Bool, outcomeUnknown: Bool) {
|
||||||
|
responseView.accessibilityIdentifier = "drone.preparation.shootResponse"
|
||||||
|
let suffix = taskID.map { " · ID \($0)" } ?? ""
|
||||||
|
let title: String
|
||||||
|
if isLoading { title = "正在召唤无人机" }
|
||||||
|
else if hasSucceeded { title = "召唤请求已提交" }
|
||||||
|
else { title = outcomeUnknown ? "召唤结果待核对" : "召唤请求未成功" }
|
||||||
|
titleLabel.text = title + suffix
|
||||||
|
titleLabel.textColor = hasSucceeded ? DroneDockStyle.success : errorMessage == nil ? DroneDockStyle.text : DroneDockStyle.warning
|
||||||
|
if isLoading { detailLabel.text = "正在为已创建的任务提交召唤请求" }
|
||||||
|
else if hasSucceeded { detailLabel.text = "shoot 返回信息;飞行进度以任务状态为准" }
|
||||||
|
else { detailLabel.text = outcomeUnknown ? "请先核对任务状态,避免重复发送召唤" : "任务已保留,可重试召唤" }
|
||||||
|
responseView.font = dataJSON == nil ? .systemFont(ofSize: 14) : .monospacedSystemFont(ofSize: 12, weight: .regular)
|
||||||
|
let text = dataJSON ?? errorMessage ?? (hasSucceeded ? "接口已返回业务成功,未提供可展示的 data。" : "")
|
||||||
|
if responseView.text != text { responseView.text = text }
|
||||||
|
responseView.textColor = DroneDockStyle.text
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
import SnapKit
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
/// 固定区域内组合任务状态与主操作,根据可用高度收紧内容,不滚动或改变外部尺寸。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockTaskStatusView: UIView {
|
||||||
|
/// 当前状态的主操作,由页面协调执行,不在组件中调用接口。
|
||||||
|
var onPrimaryAction: (() -> Void)?
|
||||||
|
/// 展开完整状态说明,由页面提供详情展示。
|
||||||
|
var onDetails: (() -> Void)?
|
||||||
|
/// 当前内容采用的字号和间距参考比例,始终介于 0.8 与 1。
|
||||||
|
private(set) var effectiveScale: CGFloat = 1
|
||||||
|
/// 中间区域不足以显示常规内容时采用紧凑布局。
|
||||||
|
private(set) var usesCompactLayout = false
|
||||||
|
|
||||||
|
private let contentStack = UIStackView()
|
||||||
|
private let titleRow = UIView()
|
||||||
|
private let iconView = UIImageView()
|
||||||
|
private let titleLabel = DroneDockStyle.label(size: 22, weight: .semibold)
|
||||||
|
private let messageLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
|
||||||
|
private let deviceLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||||
|
private let actionRow = UIView()
|
||||||
|
private let primaryButton = UIButton(type: .system)
|
||||||
|
private let detailsButton = UIButton(type: .system)
|
||||||
|
private var presentation: DroneDockTaskPresentation?
|
||||||
|
private var contentTop: Constraint?
|
||||||
|
private var contentLeading: Constraint?
|
||||||
|
private var contentTrailing: Constraint?
|
||||||
|
private var iconSize: Constraint?
|
||||||
|
private var titleLeading: Constraint?
|
||||||
|
private var titleRowHeight: Constraint?
|
||||||
|
private var messageHeight: Constraint?
|
||||||
|
private var deviceHeight: Constraint?
|
||||||
|
|
||||||
|
/// 创建稳定的标题、说明、设备摘要与操作槽,所有状态复用同一组视图。
|
||||||
|
override init(frame: CGRect) {
|
||||||
|
super.init(frame: frame)
|
||||||
|
setupUI()
|
||||||
|
setupConstraints()
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
|
/// 外部容器决定高度;状态内容不会通过固有尺寸推高底部安全区。
|
||||||
|
override var intrinsicContentSize: CGSize {
|
||||||
|
CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 更新真实状态文案与动作许可,不补造百分比或自行推导飞行阶段。
|
||||||
|
func apply(_ presentation: DroneDockTaskPresentation) {
|
||||||
|
self.presentation = presentation
|
||||||
|
titleLabel.text = presentation.title
|
||||||
|
messageLabel.text = presentation.message
|
||||||
|
deviceLabel.text = presentation.deviceStatus
|
||||||
|
let style = Self.style(for: presentation.phase)
|
||||||
|
iconView.image = UIImage(systemName: style.symbol)
|
||||||
|
iconView.tintColor = style.color
|
||||||
|
let actionTitle = DroneDockHomeMetric.usableText(presentation.actionTitle)
|
||||||
|
primaryButton.isHidden = presentation.action == .none || actionTitle == nil
|
||||||
|
primaryButton.setTitle(actionTitle, for: .normal)
|
||||||
|
primaryButton.isEnabled = presentation.isActionEnabled && !primaryButton.isHidden
|
||||||
|
primaryButton.backgroundColor = primaryButton.isEnabled
|
||||||
|
? DroneDockStyle.primary : DroneDockStyle.primary.withAlphaComponent(0.35)
|
||||||
|
primaryButton.accessibilityIdentifier = presentation.action == .refresh
|
||||||
|
? "drone.task.remote.refresh" : "drone.task.remote.primary"
|
||||||
|
setNeedsLayout()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。
|
||||||
|
override func layoutSubviews() {
|
||||||
|
updateContentLayout()
|
||||||
|
super.layoutSubviews()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func setupUI() {
|
||||||
|
backgroundColor = .white
|
||||||
|
contentStack.axis = .vertical
|
||||||
|
contentStack.alignment = .fill
|
||||||
|
contentStack.spacing = 10
|
||||||
|
addSubview(contentStack)
|
||||||
|
contentStack.addArrangedSubview(titleRow)
|
||||||
|
contentStack.addArrangedSubview(messageLabel)
|
||||||
|
contentStack.addArrangedSubview(deviceLabel)
|
||||||
|
contentStack.addArrangedSubview(actionRow)
|
||||||
|
titleRow.addSubview(iconView)
|
||||||
|
titleRow.addSubview(titleLabel)
|
||||||
|
iconView.contentMode = .scaleAspectFit
|
||||||
|
titleLabel.numberOfLines = 2
|
||||||
|
titleLabel.lineBreakMode = .byTruncatingTail
|
||||||
|
titleLabel.accessibilityTraits = .header
|
||||||
|
titleLabel.accessibilityIdentifier = "drone.task.remote.statusTitle"
|
||||||
|
messageLabel.numberOfLines = 3
|
||||||
|
messageLabel.lineBreakMode = .byTruncatingTail
|
||||||
|
messageLabel.accessibilityIdentifier = "drone.task.remote.statusMessage"
|
||||||
|
deviceLabel.numberOfLines = 1
|
||||||
|
deviceLabel.lineBreakMode = .byTruncatingTail
|
||||||
|
deviceLabel.accessibilityIdentifier = "drone.task.remote.deviceStatus"
|
||||||
|
actionRow.addSubview(primaryButton)
|
||||||
|
actionRow.addSubview(detailsButton)
|
||||||
|
primaryButton.layer.cornerRadius = 9
|
||||||
|
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
|
||||||
|
primaryButton.titleLabel?.lineBreakMode = .byTruncatingTail
|
||||||
|
primaryButton.setTitleColor(.white, for: .normal)
|
||||||
|
primaryButton.setTitleColor(.white.withAlphaComponent(0.9), for: .disabled)
|
||||||
|
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
|
||||||
|
detailsButton.setTitle("详情", for: .normal)
|
||||||
|
detailsButton.setTitleColor(DroneDockStyle.primary, for: .normal)
|
||||||
|
detailsButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
|
||||||
|
detailsButton.backgroundColor = DroneDockStyle.background
|
||||||
|
detailsButton.layer.cornerRadius = 9
|
||||||
|
detailsButton.accessibilityIdentifier = "drone.task.remote.details"
|
||||||
|
detailsButton.accessibilityLabel = "查看完整任务状态"
|
||||||
|
detailsButton.addTarget(self, action: #selector(detailsTapped), for: .touchUpInside)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func setupConstraints() {
|
||||||
|
contentStack.snp.makeConstraints { make in
|
||||||
|
contentTop = make.top.equalToSuperview().offset(12).constraint
|
||||||
|
contentLeading = make.leading.equalToSuperview().offset(16).constraint
|
||||||
|
contentTrailing = make.trailing.equalToSuperview().inset(16).constraint
|
||||||
|
}
|
||||||
|
titleRow.snp.makeConstraints { make in titleRowHeight = make.height.equalTo(36).priority(999).constraint }
|
||||||
|
iconView.snp.makeConstraints { make in
|
||||||
|
make.leading.centerY.equalToSuperview()
|
||||||
|
iconSize = make.size.equalTo(36).constraint
|
||||||
|
}
|
||||||
|
titleLabel.snp.makeConstraints { make in
|
||||||
|
titleLeading = make.leading.equalTo(iconView.snp.trailing).offset(10).constraint
|
||||||
|
make.trailing.centerY.equalToSuperview()
|
||||||
|
}
|
||||||
|
messageLabel.snp.makeConstraints { make in messageHeight = make.height.equalTo(34).priority(999).constraint }
|
||||||
|
deviceLabel.snp.makeConstraints { make in deviceHeight = make.height.equalTo(16).priority(999).constraint }
|
||||||
|
actionRow.snp.makeConstraints { make in make.height.equalTo(44) }
|
||||||
|
detailsButton.snp.makeConstraints { make in
|
||||||
|
make.top.trailing.bottom.equalToSuperview()
|
||||||
|
make.width.equalTo(64)
|
||||||
|
}
|
||||||
|
primaryButton.snp.makeConstraints { make in
|
||||||
|
make.top.leading.bottom.equalToSuperview()
|
||||||
|
make.trailing.equalTo(detailsButton.snp.leading).offset(-8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func updateContentLayout() {
|
||||||
|
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
|
||||||
|
let isExtreme = bounds.height < 120
|
||||||
|
let horizontalInset: CGFloat = isExtreme ? 12 : 16
|
||||||
|
let verticalInset: CGFloat = isExtreme ? 6 : 12
|
||||||
|
let width = max(1, bounds.width - horizontalInset * 2)
|
||||||
|
let availableHeight = max(1, bounds.height - verticalInset * 2)
|
||||||
|
let message = DroneDockHomeMetric.usableText(presentation.message)
|
||||||
|
let hasMessage = message != nil && message != DroneDockHomeMetric.usableText(presentation.title)
|
||||||
|
let device = DroneDockHomeMetric.usableText(presentation.deviceStatus)
|
||||||
|
let hasDevice = device != nil && device != "—"
|
||||||
|
|
||||||
|
let naturalTitle = max(36, Self.textHeight(presentation.title, font: .systemFont(ofSize: 22, weight: .semibold),
|
||||||
|
width: width - 46, lines: 2))
|
||||||
|
let naturalMessage = hasMessage ? Self.textHeight(message, font: .systemFont(ofSize: 14), width: width, lines: 3) : 0
|
||||||
|
let naturalDevice = hasDevice ? UIFont.systemFont(ofSize: 12).lineHeight : 0
|
||||||
|
let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0)) * 10
|
||||||
|
let naturalHeight = naturalTitle + naturalMessage + naturalDevice + 44 + naturalGaps
|
||||||
|
effectiveScale = min(1, max(0.8, availableHeight / max(1, naturalHeight)))
|
||||||
|
usesCompactLayout = bounds.height < 190 || naturalHeight * effectiveScale > availableHeight
|
||||||
|
|
||||||
|
// 先收紧图标和间距;只有不足九成空间时才缩小文字。
|
||||||
|
let fontScale: CGFloat = effectiveScale >= 0.9 ? 1 : effectiveScale / 0.9
|
||||||
|
titleLabel.font = .systemFont(ofSize: max(17, 22 * fontScale), weight: .semibold)
|
||||||
|
messageLabel.font = .systemFont(ofSize: max(12, 14 * fontScale))
|
||||||
|
deviceLabel.font = .systemFont(ofSize: 12)
|
||||||
|
let icon: CGFloat = isExtreme ? 20 : usesCompactLayout ? 24 : 36 * effectiveScale
|
||||||
|
let gap: CGFloat = isExtreme ? 4 : max(4, 10 * effectiveScale)
|
||||||
|
let titleGap: CGFloat = usesCompactLayout ? 8 : 10 * effectiveScale
|
||||||
|
titleLabel.numberOfLines = usesCompactLayout ? 1 : 2
|
||||||
|
messageLabel.numberOfLines = usesCompactLayout ? 2 : 3
|
||||||
|
messageLabel.isHidden = !hasMessage || isExtreme
|
||||||
|
deviceLabel.isHidden = !hasDevice || usesCompactLayout
|
||||||
|
let titleWidth = max(1, width - icon - titleGap)
|
||||||
|
var titleHeight = max(icon, Self.textHeight(presentation.title, font: titleLabel.font,
|
||||||
|
width: titleWidth, lines: titleLabel.numberOfLines))
|
||||||
|
var messageLineCount = messageLabel.numberOfLines
|
||||||
|
var bodyHeight = messageLabel.isHidden ? 0 : Self.textHeight(message, font: messageLabel.font,
|
||||||
|
width: width, lines: messageLineCount)
|
||||||
|
let deviceTextHeight = deviceLabel.isHidden ? 0 : ceil(deviceLabel.font.lineHeight)
|
||||||
|
var contentHeight: CGFloat {
|
||||||
|
titleHeight + bodyHeight + deviceTextHeight + 44
|
||||||
|
+ CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1)) * gap
|
||||||
|
}
|
||||||
|
while contentHeight > availableHeight && messageLineCount > 1 && !messageLabel.isHidden {
|
||||||
|
messageLineCount -= 1
|
||||||
|
bodyHeight = Self.textHeight(message, font: messageLabel.font, width: width, lines: messageLineCount)
|
||||||
|
}
|
||||||
|
if contentHeight > availableHeight && titleLabel.numberOfLines > 1 {
|
||||||
|
titleLabel.numberOfLines = 1
|
||||||
|
titleHeight = max(icon, ceil(titleLabel.font.lineHeight))
|
||||||
|
}
|
||||||
|
if contentHeight > availableHeight && !messageLabel.isHidden {
|
||||||
|
messageLabel.isHidden = true
|
||||||
|
bodyHeight = 0
|
||||||
|
}
|
||||||
|
messageLabel.numberOfLines = messageLineCount
|
||||||
|
let top = verticalInset + max(0, (availableHeight - contentHeight) / 2)
|
||||||
|
contentTop?.update(offset: top)
|
||||||
|
contentLeading?.update(offset: horizontalInset)
|
||||||
|
contentTrailing?.update(inset: horizontalInset)
|
||||||
|
iconSize?.update(offset: icon)
|
||||||
|
titleLeading?.update(offset: titleGap)
|
||||||
|
titleRowHeight?.update(offset: titleHeight)
|
||||||
|
messageHeight?.update(offset: max(1, bodyHeight))
|
||||||
|
deviceHeight?.update(offset: max(1, deviceTextHeight))
|
||||||
|
contentStack.spacing = gap
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func textHeight(_ text: String?, font: UIFont, width: CGFloat, lines: Int) -> CGFloat {
|
||||||
|
guard let text, !text.isEmpty else { return ceil(font.lineHeight) }
|
||||||
|
let height = (text as NSString).boundingRect(with: CGSize(width: max(1, width), height: .greatestFiniteMagnitude),
|
||||||
|
options: [.usesLineFragmentOrigin, .usesFontLeading],
|
||||||
|
attributes: [.font: font], context: nil).height
|
||||||
|
return ceil(min(height, font.lineHeight * CGFloat(lines)))
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func style(for phase: DroneDockTaskDisplayPhase) -> (symbol: String, color: UIColor) {
|
||||||
|
switch phase {
|
||||||
|
case .loading: ("clock.arrow.circlepath", DroneDockStyle.primary)
|
||||||
|
case .navigating: ("paperplane.fill", DroneDockStyle.primary)
|
||||||
|
case .ready: ("checkmark.circle.fill", DroneDockStyle.success)
|
||||||
|
case .shooting: ("video.fill", DroneDockStyle.primary)
|
||||||
|
case .paused: ("pause.circle.fill", DroneDockStyle.warning)
|
||||||
|
case .returning: ("arrow.uturn.backward.circle.fill", DroneDockStyle.warning)
|
||||||
|
case .completed: ("checkmark.circle.fill", DroneDockStyle.success)
|
||||||
|
case .failed: ("xmark.circle.fill", UIColor(hex: 0xD46B62))
|
||||||
|
case .blocked, .readError: ("exclamationmark.circle.fill", DroneDockStyle.warning)
|
||||||
|
case .unknown: ("questionmark.circle.fill", DroneDockStyle.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func primaryTapped() {
|
||||||
|
guard primaryButton.isEnabled, !primaryButton.isHidden else { return }
|
||||||
|
onPrimaryAction?()
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func detailsTapped() { onDetails?() }
|
||||||
|
}
|
||||||
@@ -416,6 +416,9 @@ final class DronePreparationFooterView: UIView {
|
|||||||
let divider = UIView()
|
let divider = UIView()
|
||||||
divider.backgroundColor = DroneDockStyle.border
|
divider.backgroundColor = DroneDockStyle.border
|
||||||
let deviceRow = UIStackView(arrangedSubviews: [deviceCaption, deviceLabel, UIView()])
|
let deviceRow = UIStackView(arrangedSubviews: [deviceCaption, deviceLabel, UIView()])
|
||||||
|
deviceLabel.accessibilityIdentifier = "drone.preparation.planeStatus"
|
||||||
|
deviceLabel.numberOfLines = 2
|
||||||
|
deviceLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
|
||||||
deviceRow.axis = .horizontal
|
deviceRow.axis = .horizontal
|
||||||
deviceRow.alignment = .center
|
deviceRow.alignment = .center
|
||||||
deviceRow.spacing = 3
|
deviceRow.spacing = 3
|
||||||
@@ -497,20 +500,25 @@ final class DronePreparationFooterView: UIView {
|
|||||||
refreshButton.isHidden = !viewModel.shouldShowSummonRefresh
|
refreshButton.isHidden = !viewModel.shouldShowSummonRefresh
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 展示真实准备状态;本阶段保留召唤按钮文案,但尚不提供飞行执行入口。
|
/// 按购买权限启用待飞任务创建;本阶段不提供无人机召唤或起飞入口。
|
||||||
func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: Bool = false) {
|
func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: Bool = false) {
|
||||||
connectionLabel.apply(title: viewModel.connectionTitle, tone: viewModel.connectionTone)
|
connectionLabel.apply(title: viewModel.connectionTitle, tone: viewModel.connectionTone)
|
||||||
selectionLabel.text = viewModel.selectionSummary
|
selectionLabel.text = viewModel.selectionSummary
|
||||||
selectionLabel.numberOfLines = 2
|
selectionLabel.numberOfLines = 2
|
||||||
deviceLabel.apply(title: viewModel.deviceStatusText, tone: viewModel.deviceTone)
|
deviceLabel.apply(title: viewModel.deviceStatusText, tone: viewModel.deviceTone)
|
||||||
primaryButton.setTitle(viewModel.primaryButtonTitle, for: .normal)
|
primaryButton.setTitle(viewModel.primaryButtonTitle, for: .normal)
|
||||||
primaryButton.isEnabled = false
|
primaryButton.isEnabled = (viewModel.isPrimaryActionEnabled || viewModel.canOpenShootingTask) && !isRefreshing
|
||||||
primaryButton.backgroundColor = UIColor(hex: 0xE1E7F0)
|
primaryButton.backgroundColor = primaryButton.isEnabled ? DroneDockStyle.primary : UIColor(hex: 0xE1E7F0)
|
||||||
|
primaryButton.setTitleColor(.white, for: .normal)
|
||||||
primaryButton.setTitleColor(UIColor(hex: 0x8792A5), for: .disabled)
|
primaryButton.setTitleColor(UIColor(hex: 0x8792A5), for: .disabled)
|
||||||
messageLabel.text = viewModel.admissionMessage
|
if viewModel.isTaskSelectionLocked || viewModel.taskCreationErrorMessage != nil {
|
||||||
|
messageLabel.text = viewModel.admissionMessage
|
||||||
|
} else {
|
||||||
|
messageLabel.text = viewModel.planeStatusErrorMessage.map { "无人机状态获取失败:\($0)" } ?? viewModel.admissionMessage
|
||||||
|
}
|
||||||
messageLabel.textColor = DroneDockStyle.secondary
|
messageLabel.textColor = DroneDockStyle.secondary
|
||||||
refreshButton.isHidden = false
|
refreshButton.isHidden = false
|
||||||
refreshButton.isEnabled = !viewModel.isLoading && !isRefreshing
|
refreshButton.isEnabled = !viewModel.isLoading && !viewModel.isCreatingTask && !viewModel.isSummoning && !isRefreshing
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc private func primaryTapped() { onPrimaryTap?() }
|
@objc private func primaryTapped() { onPrimaryTap?() }
|
||||||
|
|||||||
@@ -158,6 +158,9 @@ final class DroneShootingTaskTelemetryView: UIView {
|
|||||||
private let stackView = UIStackView()
|
private let stackView = UIStackView()
|
||||||
private let staleLabel = DroneDockStyle.label("ⓘ 状态暂未更新", size: 11, color: DroneDockStyle.secondary)
|
private let staleLabel = DroneDockStyle.label("ⓘ 状态暂未更新", size: 11, color: DroneDockStyle.secondary)
|
||||||
private var cells: [DroneShootingTaskTelemetryCell] = []
|
private var cells: [DroneShootingTaskTelemetryCell] = []
|
||||||
|
private var rowHeights: [Constraint] = []
|
||||||
|
private var contentEdges: Constraint?
|
||||||
|
private var usesFixedLayout = false
|
||||||
|
|
||||||
/// 以两行三列固定展示电量、温度、风速、雨量、信号与搜星。
|
/// 以两行三列固定展示电量、温度、风速、雨量、信号与搜星。
|
||||||
override init(frame: CGRect) {
|
override init(frame: CGRect) {
|
||||||
@@ -184,22 +187,38 @@ final class DroneShootingTaskTelemetryView: UIView {
|
|||||||
row.addArrangedSubview(cell)
|
row.addArrangedSubview(cell)
|
||||||
}
|
}
|
||||||
stackView.addArrangedSubview(row)
|
stackView.addArrangedSubview(row)
|
||||||
row.snp.makeConstraints { make in make.height.equalTo(55) }
|
row.snp.makeConstraints { make in rowHeights.append(make.height.equalTo(55).constraint) }
|
||||||
}
|
}
|
||||||
stackView.snp.makeConstraints { make in make.edges.equalToSuperview().inset(10) }
|
stackView.snp.makeConstraints { make in contentEdges = make.edges.equalToSuperview().inset(10).constraint }
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(*, unavailable)
|
@available(*, unavailable)
|
||||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
|
||||||
|
/// 固定任务页不增减状态提示行;小屏仅压缩格子间距与留白,六项参数位置保持稳定。
|
||||||
|
func configureFixedLayout(compact: Bool) {
|
||||||
|
usesFixedLayout = true
|
||||||
|
staleLabel.isHidden = true
|
||||||
|
rowHeights.forEach { $0.update(offset: compact ? 46 : 55) }
|
||||||
|
stackView.spacing = compact ? 4 : 6
|
||||||
|
contentEdges?.update(inset: compact ? 8 : 10)
|
||||||
|
}
|
||||||
|
|
||||||
/// 新快照覆盖全部读数;不保留断网前的值冒充有效数据。
|
/// 新快照覆盖全部读数;不保留断网前的值冒充有效数据。
|
||||||
func apply(telemetry: DroneDockTelemetry, isStale: Bool) {
|
func apply(telemetry: DroneDockTelemetry, isStale: Bool) {
|
||||||
staleLabel.isHidden = !isStale
|
apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText,
|
||||||
let values = isStale
|
telemetry.rainText, telemetry.signalText, telemetry.satelliteText], isStale: isStale)
|
||||||
? Array(repeating: "—", count: 6)
|
}
|
||||||
: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText, telemetry.rainText, telemetry.signalText, telemetry.satelliteText]
|
|
||||||
|
/// 展示后端已格式化的六项读数,保留单位;缺项与过期读数显示破折号。
|
||||||
|
func apply(values: [String], isStale: Bool, accessibilityPrefix: String? = nil) {
|
||||||
|
staleLabel.isHidden = usesFixedLayout || !isStale
|
||||||
|
let keys = ["battery", "temperature", "wind", "rain", "signal", "satellite"]
|
||||||
for (index, cell) in cells.enumerated() {
|
for (index, cell) in cells.enumerated() {
|
||||||
cell.apply(value: values[index], isStale: isStale)
|
let value = !isStale && values.indices.contains(index)
|
||||||
|
? DroneDockHomeMetric.usableText(values[index]) ?? "—" : "—"
|
||||||
|
cell.apply(value: value, isStale: isStale)
|
||||||
|
if let accessibilityPrefix { cell.accessibilityIdentifier = "\(accessibilityPrefix).\(keys[index])" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 验证朱工无人机状态请求、推荐设备与未知状态解析,不访问真实飞行接口。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockPlaneStatusAPITests: XCTestCase {
|
||||||
|
/// 只发送当前景区和实时电量参数,鉴权沿用统一 Token。
|
||||||
|
func testRequestUsesDocumentedPathLiveBatteryAndToken() async throws {
|
||||||
|
let session = MockURLSession(responses: [try envelope(Self.payload)])
|
||||||
|
let client = APIClient(environment: .testing, session: session)
|
||||||
|
client.bindAuthTokenProvider { "plane-status-test-token" }
|
||||||
|
|
||||||
|
let response = try await DroneDockPlaneStatusAPI(client: client).planeStatus(scenicID: 128)
|
||||||
|
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
let request = try XCTUnwrap(session.requests.first)
|
||||||
|
XCTAssertEqual(request.httpMethod, "GET")
|
||||||
|
XCTAssertEqual(request.url?.path, "/api/app/airport/plane-status")
|
||||||
|
XCTAssertEqual(request.url?.host, "api-test.zhifly.cn")
|
||||||
|
XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "plane-status-test-token")
|
||||||
|
XCTAssertNil(request.httpBody)
|
||||||
|
let url = try XCTUnwrap(request.url)
|
||||||
|
let query = try XCTUnwrap(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems)
|
||||||
|
XCTAssertEqual(Dictionary(uniqueKeysWithValues: query.map { ($0.name, $0.value ?? "") }),
|
||||||
|
["scenic_id": "128", "live_battery": "1"])
|
||||||
|
XCTAssertEqual(response.scenicID, 128)
|
||||||
|
XCTAssertEqual(response.connected, true)
|
||||||
|
XCTAssertEqual(response.hasIdle, true)
|
||||||
|
XCTAssertEqual(response.hasShooting, false)
|
||||||
|
XCTAssertEqual(response.pollHintMS, 5000)
|
||||||
|
XCTAssertEqual(response.recommend?.statusText, "空闲 · 电量 95%")
|
||||||
|
XCTAssertEqual(response.recommend?.batteryPercent, 95)
|
||||||
|
XCTAssertEqual(response.recommend?.canFly, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 缺少有效景区时不得发出范围不明的请求。
|
||||||
|
func testInvalidScenicIDIsRejectedBeforeRequest() async {
|
||||||
|
let session = MockURLSession(responses: [])
|
||||||
|
let api = DroneDockPlaneStatusAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
for id in [0, -1] {
|
||||||
|
do {
|
||||||
|
_ = try await api.planeStatus(scenicID: id)
|
||||||
|
XCTFail("无效景区必须在请求前拒绝")
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
XCTAssertTrue(session.requests.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 返回其他景区的数据不能显示在当前准备页。
|
||||||
|
func testMismatchedScenicResponseIsRejected() async throws {
|
||||||
|
var payload = Self.payload
|
||||||
|
payload["scenic_id"] = 129
|
||||||
|
let session = MockURLSession(responses: [try envelope(payload)])
|
||||||
|
do {
|
||||||
|
_ = try await DroneDockPlaneStatusAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
.planeStatus(scenicID: 128)
|
||||||
|
XCTFail("必须拒绝其他景区的状态")
|
||||||
|
} catch let APIError.decodeFailed(message) {
|
||||||
|
XCTAssertTrue(message.contains("景区不一致"))
|
||||||
|
}
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 后端业务失败保留原提示,不转换成离线或正常空设备。
|
||||||
|
func testBusinessFailurePreservesServerMessage() async throws {
|
||||||
|
let session = MockURLSession(responses: [try TestJSON.errorEnvelope(code: 160001, msg: "无权访问测试景区")])
|
||||||
|
do {
|
||||||
|
_ = try await DroneDockPlaneStatusAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
.planeStatus(scenicID: 128)
|
||||||
|
XCTFail("业务失败应抛出")
|
||||||
|
} catch let APIError.serverCode(code, message) {
|
||||||
|
XCTAssertEqual(code, 160001)
|
||||||
|
XCTAssertEqual(message, "无权访问测试景区")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 空设备和无推荐设备保持明确空态,布尔 false 不等同于字段缺失。
|
||||||
|
func testEmptyPlanesAndNullRecommendationRemainEmpty() throws {
|
||||||
|
let response = try decode([
|
||||||
|
"scenic_id": 128, "planes": [], "recommend": NSNull(),
|
||||||
|
"connected": false, "has_idle": false, "has_shooting": false, "poll_hint_ms": 5000
|
||||||
|
])
|
||||||
|
XCTAssertTrue(response.planes.isEmpty)
|
||||||
|
XCTAssertNil(response.recommend)
|
||||||
|
XCTAssertEqual(response.connected, false)
|
||||||
|
XCTAssertEqual(response.hasIdle, false)
|
||||||
|
XCTAssertEqual(response.hasShooting, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 数字字符串和真实零电量可解析,不把 0 当作缺失。
|
||||||
|
func testIntegerStringsAndZeroBatteryArePreserved() throws {
|
||||||
|
let plane: [String: Any] = [
|
||||||
|
"id": "501", "work_status": "0", "battery_percent": "0", "can_fly": false,
|
||||||
|
"battery_label": "电量 0%", "status_text": "离线 · 电量 0%"
|
||||||
|
]
|
||||||
|
let response = try decode(["scenic_id": "128", "planes": [plane], "recommend": plane, "poll_hint_ms": "5000"])
|
||||||
|
XCTAssertEqual(response.planes.first?.id, 501)
|
||||||
|
XCTAssertEqual(response.recommend?.workStatus, 0)
|
||||||
|
XCTAssertEqual(response.recommend?.batteryPercent, 0)
|
||||||
|
XCTAssertEqual(response.recommend?.canFly, false)
|
||||||
|
XCTAssertEqual(response.recommend?.statusText, "离线 · 电量 0%")
|
||||||
|
XCTAssertEqual(response.pollHintMS, 5000)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 缺失或 null 的可选字段保持未知,不补成空闲、离线或零电量。
|
||||||
|
func testMissingAndNullFieldsRemainUnknown() throws {
|
||||||
|
for plane: [String: Any] in [
|
||||||
|
["id": 501],
|
||||||
|
["id": 501, "sn_number": NSNull(), "name": NSNull(), "work_status": NSNull(),
|
||||||
|
"work_status_label": NSNull(), "battery_percent": NSNull(), "battery_label": NSNull(),
|
||||||
|
"can_fly": NSNull(), "status_text": NSNull()]
|
||||||
|
] {
|
||||||
|
let response = try decode(["scenic_id": 128, "planes": [plane], "recommend": plane])
|
||||||
|
let value = try XCTUnwrap(response.recommend)
|
||||||
|
XCTAssertNil(value.snNumber)
|
||||||
|
XCTAssertNil(value.name)
|
||||||
|
XCTAssertNil(value.workStatus)
|
||||||
|
XCTAssertNil(value.workStatusLabel)
|
||||||
|
XCTAssertNil(value.batteryPercent)
|
||||||
|
XCTAssertNil(value.batteryLabel)
|
||||||
|
XCTAssertNil(value.canFly)
|
||||||
|
XCTAssertNil(value.statusText)
|
||||||
|
XCTAssertNil(response.connected)
|
||||||
|
XCTAssertNil(response.hasIdle)
|
||||||
|
XCTAssertNil(response.hasShooting)
|
||||||
|
XCTAssertNil(response.pollHintMS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 未来状态和推荐顺序遵循服务端,客户端不按电量重新挑选设备。
|
||||||
|
func testUnknownStateAndServerRecommendationArePreserved() throws {
|
||||||
|
let preferred: [String: Any] = ["id": 502, "work_status": 99, "battery_percent": 20,
|
||||||
|
"work_status_label": "维护中", "status_text": "维护中 · 等待检查", "can_fly": false]
|
||||||
|
let response = try decode(["scenic_id": 128, "planes": [Self.plane, preferred], "recommend": preferred])
|
||||||
|
XCTAssertEqual(response.planes.map(\.id), [501, 502])
|
||||||
|
XCTAssertEqual(response.recommend?.id, 502)
|
||||||
|
XCTAssertEqual(response.recommend?.workStatus, 99)
|
||||||
|
XCTAssertEqual(response.recommend?.statusText, "维护中 · 等待检查")
|
||||||
|
XCTAssertEqual(response.recommend?.canFly, false)
|
||||||
|
let withoutRecommendation = try decode(["scenic_id": 128, "planes": [Self.plane]])
|
||||||
|
XCTAssertNil(withoutRecommendation.recommend)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 景区和设备身份必须正整数且设备列表唯一,错误列表不得冒充空态。
|
||||||
|
func testMalformedIdentitiesAndRequiredListsAreRejected() throws {
|
||||||
|
for id: Any in [0, -1, 1.5, true, "invalid"] {
|
||||||
|
XCTAssertThrowsError(try decode(["scenic_id": id, "planes": []]))
|
||||||
|
XCTAssertThrowsError(try decode(["scenic_id": 128, "planes": [["id": id]]]))
|
||||||
|
XCTAssertThrowsError(try decode(["scenic_id": 128, "planes": [], "recommend": ["id": id]]))
|
||||||
|
}
|
||||||
|
XCTAssertThrowsError(try decode(["scenic_id": 128]))
|
||||||
|
XCTAssertThrowsError(try decode(["planes": []]))
|
||||||
|
XCTAssertThrowsError(try decode(["scenic_id": 128, "planes": NSNull()]))
|
||||||
|
XCTAssertThrowsError(try decode(["scenic_id": 128, "planes": [:]]))
|
||||||
|
XCTAssertThrowsError(try decode(["scenic_id": 128, "planes": [Self.plane, Self.plane]]))
|
||||||
|
XCTAssertThrowsError(try decode(["scenic_id": 128, "planes": [], "recommend": [:]]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 错误类型不会被宽松转换成可飞、已连接或有效电量。
|
||||||
|
func testMalformedOptionalValuesAreRejected() throws {
|
||||||
|
for extra: [String: Any] in [
|
||||||
|
["work_status": "unknown"], ["battery_percent": true], ["battery_percent": 1.5],
|
||||||
|
["can_fly": "true"], ["status_text": 123], ["battery_label": false]
|
||||||
|
] {
|
||||||
|
var plane = Self.plane
|
||||||
|
plane.merge(extra) { _, new in new }
|
||||||
|
XCTAssertThrowsError(try decode(["scenic_id": 128, "planes": [plane]]))
|
||||||
|
}
|
||||||
|
for extra: [String: Any] in [["connected": 1], ["has_idle": "true"], ["has_shooting": "false"], ["poll_hint_ms": "invalid"]] {
|
||||||
|
var payload = Self.payload
|
||||||
|
payload.merge(extra) { _, new in new }
|
||||||
|
XCTAssertThrowsError(try decode(payload))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func decode(_ payload: [String: Any]) throws -> DroneDockPlaneStatusResponse {
|
||||||
|
try JSONDecoder().decode(DroneDockPlaneStatusResponse.self, from: JSONSerialization.data(withJSONObject: payload))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func envelope(_ payload: [String: Any]) throws -> Data {
|
||||||
|
try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": payload])
|
||||||
|
}
|
||||||
|
|
||||||
|
private static var plane: [String: Any] {
|
||||||
|
["id": 501, "sn_number": "TEST-PLANE-501", "name": "测试无人机", "work_status": 1,
|
||||||
|
"work_status_label": "空闲", "battery_percent": 95, "battery_label": "电量 95%",
|
||||||
|
"can_fly": true, "status_text": "空闲 · 电量 95%"]
|
||||||
|
}
|
||||||
|
|
||||||
|
private static var payload: [String: Any] {
|
||||||
|
["scenic_id": 128, "planes": [plane], "recommend": plane, "has_idle": true,
|
||||||
|
"has_shooting": false, "connected": true, "poll_hint_ms": 5000]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import Foundation
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 准备页测试共用的脱敏无人机响应,不访问真实设备或保存账号凭证。
|
||||||
|
enum DroneDockPlaneStatusTestData {
|
||||||
|
/// 构造当前景区快照,空列表与无推荐分别保留接口语义。
|
||||||
|
static func response(scenicID: Int = 128, planes: [[String: Any]] = [],
|
||||||
|
recommend: [String: Any]? = nil, connected: Bool? = nil,
|
||||||
|
pollHintMS: Int? = nil) throws -> DroneDockPlaneStatusResponse {
|
||||||
|
var payload: [String: Any] = ["scenic_id": scenicID, "planes": planes]
|
||||||
|
payload["recommend"] = recommend
|
||||||
|
payload["connected"] = connected
|
||||||
|
payload["poll_hint_ms"] = pollHintMS
|
||||||
|
return try JSONDecoder().decode(DroneDockPlaneStatusResponse.self,
|
||||||
|
from: JSONSerialization.data(withJSONObject: payload))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 使用明确测试名称与序列号,状态文案可按场景置空。
|
||||||
|
static func plane(id: Int = 1, status: Int = 1, text: String? = "空闲 · 电量 95%",
|
||||||
|
battery: Int? = 95) -> [String: Any] {
|
||||||
|
var value: [String: Any] = ["id": id, "sn_number": "TEST-PLANE-\(id)", "name": "测试无人机 \(id)",
|
||||||
|
"work_status": status, "can_fly": status == 1]
|
||||||
|
value["status_text"] = text
|
||||||
|
value["battery_percent"] = battery
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 可更换返回值并记录请求景区的即时服务,用于页面与状态测试。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockPlaneStatusTestService: DroneDockPlaneStatusServing {
|
||||||
|
/// 每次读取使用当前结果,支持恢复与业务错误场景。
|
||||||
|
var result: Result<DroneDockPlaneStatusResponse, Error>
|
||||||
|
/// 已读取的景区列表,便于验证独立轮询频率与身份。
|
||||||
|
private(set) var requests: [Int] = []
|
||||||
|
|
||||||
|
/// 默认提供无设备的合法空态,不默认推断设备已连接。
|
||||||
|
init(response: DroneDockPlaneStatusResponse? = nil) throws {
|
||||||
|
result = .success(try response ?? DroneDockPlaneStatusTestData.response())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 仅记录读取请求,不提供任务创建或飞行指令。
|
||||||
|
func planeStatus(scenicID: Int) async throws -> DroneDockPlaneStatusResponse {
|
||||||
|
requests.append(scenicID)
|
||||||
|
return try result.get()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@ import Foundation
|
|||||||
import XCTest
|
import XCTest
|
||||||
@testable import suixinkan
|
@testable import suixinkan
|
||||||
|
|
||||||
/// 验证准备页只读取购买配置、选择约束及异步身份隔离。
|
/// 验证准备页购买配置、独立无人机状态、选择约束及异步身份隔离。
|
||||||
@MainActor
|
@MainActor
|
||||||
final class DroneDockPreparationViewModelTests: XCTestCase {
|
final class DroneDockPreparationViewModelTests: XCTestCase {
|
||||||
/// 次数和配置来自购买快照,首页旧额度不会覆盖五次套餐。
|
/// 次数和配置来自购买快照,首页旧额度不会覆盖五次套餐。
|
||||||
@@ -44,8 +44,8 @@ final class DroneDockPreparationViewModelTests: XCTestCase {
|
|||||||
XCTAssertNil(model.errorMessage)
|
XCTAssertNil(model.errorMessage)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 已购配置不包含实时设备与定位数据,展示保持未知且不开放召唤。
|
/// 仅完成购买读取时设备仍未知,必须由独立无人机状态请求更新。
|
||||||
func testValidPurchaseKeepsDeviceAndLocationUnknown() async throws {
|
func testPurchaseAloneKeepsDeviceUnknownAndSummonUnavailable() async throws {
|
||||||
let model = try makeModel(service: ImmediatePreparationService())
|
let model = try makeModel(service: ImmediatePreparationService())
|
||||||
await model.refresh()
|
await model.refresh()
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ final class DroneDockPreparationViewModelTests: XCTestCase {
|
|||||||
XCTAssertEqual(model.deviceStatusText, "状态待确认")
|
XCTAssertEqual(model.deviceStatusText, "状态待确认")
|
||||||
XCTAssertEqual(model.deviceTone, .gray)
|
XCTAssertEqual(model.deviceTone, .gray)
|
||||||
XCTAssertEqual(model.primaryButtonTitle, "确认并召唤")
|
XCTAssertEqual(model.primaryButtonTitle, "确认并召唤")
|
||||||
XCTAssertEqual(model.admissionMessage, "召唤功能暂未开放")
|
XCTAssertEqual(model.admissionMessage, "点击后创建任务并召唤无人机")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 点位切换重选所属航线,未知及不可用航线不能成为当前选择。
|
/// 点位切换重选所属航线,未知及不可用航线不能成为当前选择。
|
||||||
@@ -271,15 +271,280 @@ final class DroneDockPreparationViewModelTests: XCTestCase {
|
|||||||
XCTAssertTrue(service.projectRequests.isEmpty)
|
XCTAssertTrue(service.projectRequests.isEmpty)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 推荐结果与列表排序独立,刷新无人机不重读购买配置或改变用户选择。
|
||||||
|
func testPlaneStatusUsesRecommendationAndPreservesPurchaseSelection() async throws {
|
||||||
|
let project = try ImmediatePreparationService()
|
||||||
|
let first = DroneDockPlaneStatusTestData.plane(id: 1, text: "空闲 · 电量 99%", battery: 99)
|
||||||
|
let recommended = DroneDockPlaneStatusTestData.plane(id: 2, text: "后端推荐 · 电量 13%", battery: 13)
|
||||||
|
let planes = try DroneDockPlaneStatusTestService(response: DroneDockPlaneStatusTestData.response(
|
||||||
|
planes: [first, recommended], recommend: recommended, connected: true))
|
||||||
|
let model = try makeModel(service: project, planeService: planes)
|
||||||
|
await model.refresh()
|
||||||
|
model.selectSpot(id: 202)
|
||||||
|
model.selectRoute(id: 402)
|
||||||
|
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
|
||||||
|
XCTAssertEqual(model.deviceStatusText, "后端推荐 · 电量 13%")
|
||||||
|
XCTAssertEqual(model.deviceTone, .green)
|
||||||
|
XCTAssertEqual(model.connectionTitle, "机巢已连接")
|
||||||
|
XCTAssertEqual(model.connectionTone, .green)
|
||||||
|
XCTAssertEqual(model.selectedSpotID, 202)
|
||||||
|
XCTAssertEqual(model.selectedRouteID, 402)
|
||||||
|
XCTAssertEqual(model.projectInfo?.order.shotRemain, 5)
|
||||||
|
XCTAssertEqual(project.projectRequests.count, 1)
|
||||||
|
XCTAssertEqual(planes.requests, [128])
|
||||||
|
XCTAssertEqual(model.primaryButtonTitle, "确认并召唤")
|
||||||
|
XCTAssertEqual(model.admissionMessage, "点击后创建任务并召唤无人机")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 已知工作状态只决定标签颜色,连接必须依赖独立 connected 字段。
|
||||||
|
func testPlaneStatusColorsAndConnectionUseExplicitFields() async throws {
|
||||||
|
let planes = try DroneDockPlaneStatusTestService()
|
||||||
|
let model = try makeModel(service: ImmediatePreparationService(), planeService: planes)
|
||||||
|
let cases: [(Int, Bool?, DroneDockStatusTone, String, String)] = [
|
||||||
|
(0, false, .gray, "离线", "机巢未连接"),
|
||||||
|
(1, true, .green, "空闲", "机巢已连接"),
|
||||||
|
(2, true, .orange, "拍摄中", "机巢已连接"),
|
||||||
|
(99, nil, .gray, "维护中", "机巢连接待确认")
|
||||||
|
]
|
||||||
|
for (status, connected, tone, label, connection) in cases {
|
||||||
|
let plane = DroneDockPlaneStatusTestData.plane(status: status, text: label)
|
||||||
|
planes.result = .success(try DroneDockPlaneStatusTestData.response(planes: [plane], recommend: plane, connected: connected))
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
XCTAssertEqual(model.deviceStatusText, label)
|
||||||
|
XCTAssertEqual(model.deviceTone, tone)
|
||||||
|
XCTAssertEqual(model.connectionTitle, connection)
|
||||||
|
XCTAssertEqual(model.connectionTone, connected == true ? .green : .gray)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 缺失完整文案时组合后端标签,缺失电量不伪造成零,真实零标签仍保留。
|
||||||
|
func testPlaneStatusFallbackLabelsPreserveUnknownAndRealZero() async throws {
|
||||||
|
let planes = try DroneDockPlaneStatusTestService()
|
||||||
|
let model = try makeModel(service: ImmediatePreparationService(), planeService: planes)
|
||||||
|
var plane = DroneDockPlaneStatusTestData.plane(text: " ", battery: nil)
|
||||||
|
plane["work_status_label"] = "空闲"
|
||||||
|
planes.result = .success(try DroneDockPlaneStatusTestData.response(planes: [plane], recommend: plane))
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
XCTAssertEqual(model.deviceStatusText, "空闲")
|
||||||
|
plane["battery_label"] = "电量 0%"
|
||||||
|
planes.result = .success(try DroneDockPlaneStatusTestData.response(planes: [plane], recommend: plane))
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
XCTAssertEqual(model.deviceStatusText, "空闲 · 电量 0%")
|
||||||
|
plane.removeValue(forKey: "work_status_label")
|
||||||
|
plane.removeValue(forKey: "battery_label")
|
||||||
|
planes.result = .success(try DroneDockPlaneStatusTestData.response(planes: [plane], recommend: plane))
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
XCTAssertEqual(model.deviceStatusText, "状态待确认")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 无设备与尚无推荐分别展示,不能自行拿列表第一架作为推荐。
|
||||||
|
func testEmptyPlanesAndMissingRecommendationRemainDistinct() async throws {
|
||||||
|
let planes = try DroneDockPlaneStatusTestService()
|
||||||
|
let model = try makeModel(service: ImmediatePreparationService(), planeService: planes)
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
XCTAssertEqual(model.deviceStatusText, "暂无无人机")
|
||||||
|
XCTAssertEqual(model.deviceTone, .gray)
|
||||||
|
planes.result = .success(try DroneDockPlaneStatusTestData.response(planes: [DroneDockPlaneStatusTestData.plane()], connected: true))
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
XCTAssertEqual(model.deviceStatusText, "状态待确认")
|
||||||
|
XCTAssertEqual(model.deviceTone, .gray)
|
||||||
|
XCTAssertEqual(model.connectionTitle, "机巢已连接")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 状态失败立刻撤下旧的空闲和电量,但保留购买点位、航线和额度。
|
||||||
|
func testPlaneFailureClearsOldStatusWithoutClearingProjectAndRecovers() async throws {
|
||||||
|
let plane = DroneDockPlaneStatusTestData.plane()
|
||||||
|
let value = try DroneDockPlaneStatusTestData.response(planes: [plane], recommend: plane, connected: true)
|
||||||
|
let planes = try DroneDockPlaneStatusTestService(response: value)
|
||||||
|
let project = try ImmediatePreparationService()
|
||||||
|
let model = try makeModel(service: project, planeService: planes)
|
||||||
|
await model.refresh()
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
model.selectRoute(id: 302)
|
||||||
|
planes.result = .failure(APIError.networkFailed("测试无人机状态暂不可用"))
|
||||||
|
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
|
||||||
|
XCTAssertNil(model.planeStatus)
|
||||||
|
XCTAssertEqual(model.deviceStatusText, "状态待确认")
|
||||||
|
XCTAssertEqual(model.connectionTitle, "机巢连接待确认")
|
||||||
|
XCTAssertTrue(model.planeStatusErrorMessage?.contains("测试无人机状态暂不可用") == true)
|
||||||
|
XCTAssertEqual(model.selectedRouteID, 302)
|
||||||
|
XCTAssertEqual(model.projectInfo?.order.shotRemain, 5)
|
||||||
|
XCTAssertNil(model.errorMessage)
|
||||||
|
planes.result = .success(value)
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
XCTAssertEqual(model.deviceStatusText, "空闲 · 电量 95%")
|
||||||
|
XCTAssertNil(model.planeStatusErrorMessage)
|
||||||
|
XCTAssertEqual(project.projectRequests.count, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 购买接口失败不抹去已成功获取的无人机状态,两个接口可以独立重试。
|
||||||
|
func testProjectFailureDoesNotClearPlaneStatus() async throws {
|
||||||
|
let plane = DroneDockPlaneStatusTestData.plane()
|
||||||
|
let planes = try DroneDockPlaneStatusTestService(response: DroneDockPlaneStatusTestData.response(planes: [plane], recommend: plane))
|
||||||
|
let project = try ImmediatePreparationService()
|
||||||
|
let model = try makeModel(service: project, planeService: planes)
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
project.projectResult = .failure(APIError.networkFailed("测试购买失败"))
|
||||||
|
await model.refresh()
|
||||||
|
XCTAssertNotNil(model.errorMessage)
|
||||||
|
XCTAssertEqual(model.deviceStatusText, "空闲 · 电量 95%")
|
||||||
|
XCTAssertNil(model.planeStatusErrorMessage)
|
||||||
|
XCTAssertEqual(planes.requests.count, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 即使测试替身绕过 API 校验,其他景区的无人机响应也不能填入页面。
|
||||||
|
func testPlaneResponseFromOtherScenicIsRejected() async throws {
|
||||||
|
let planes = try DroneDockPlaneStatusTestService(response: DroneDockPlaneStatusTestData.response(scenicID: 999))
|
||||||
|
let model = try makeModel(service: ImmediatePreparationService(), planeService: planes)
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
XCTAssertNil(model.planeStatus)
|
||||||
|
XCTAssertNotNil(model.planeStatusErrorMessage)
|
||||||
|
XCTAssertEqual(model.deviceStatusText, "状态待确认")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 无人机请求期间不会锁住点位选择,同一时刻的重复轮询不会再发请求。
|
||||||
|
func testPlaneRefreshDeduplicatesRequestsWithoutBlockingSelection() async throws {
|
||||||
|
let planes = SuspendedPlaneStatusService()
|
||||||
|
let started = expectation(description: "无人机读取挂起")
|
||||||
|
planes.requestStarted = { _ in started.fulfill() }
|
||||||
|
defer { planes.cancelAll() }
|
||||||
|
let model = try makeModel(service: ImmediatePreparationService(), planeService: planes)
|
||||||
|
await model.refresh()
|
||||||
|
let pending = Task { await model.refreshPlaneStatus() }
|
||||||
|
await fulfillment(of: [started], timeout: 2)
|
||||||
|
XCTAssertTrue(model.isLoadingPlaneStatus)
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
model.selectSpot(id: 202)
|
||||||
|
model.selectRoute(id: 402)
|
||||||
|
XCTAssertEqual(planes.requests, [128])
|
||||||
|
XCTAssertEqual(model.selectedRouteID, 402)
|
||||||
|
try planes.finish(index: 0)
|
||||||
|
await pending.value
|
||||||
|
XCTAssertFalse(model.isLoadingPlaneStatus)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 暂停无人机读取清除其快照,但不会清空购买配置或当前选择。
|
||||||
|
func testInvalidatePlaneStatusPreservesPurchasedSnapshot() async throws {
|
||||||
|
let model = try makeModel(service: ImmediatePreparationService())
|
||||||
|
await model.refresh()
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
model.selectRoute(id: 302)
|
||||||
|
model.invalidatePlaneStatus()
|
||||||
|
XCTAssertNil(model.planeStatus)
|
||||||
|
XCTAssertFalse(model.isLoadingPlaneStatus)
|
||||||
|
XCTAssertNil(model.planeStatusErrorMessage)
|
||||||
|
XCTAssertEqual(model.selectedRouteID, 302)
|
||||||
|
XCTAssertNotNil(model.projectInfo)
|
||||||
|
model.invalidate()
|
||||||
|
XCTAssertNil(model.projectInfo)
|
||||||
|
XCTAssertNil(model.selectedRouteID)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 页面取消或主动停止后,网络替身迟到返回也不能恢复旧无人机状态。
|
||||||
|
func testPlaneCancellationAndInvalidationRejectLateResponse() async throws {
|
||||||
|
for invalidate in [false, true] {
|
||||||
|
let planes = SuspendedPlaneStatusService()
|
||||||
|
let started = expectation(description: "待取消无人机读取")
|
||||||
|
planes.requestStarted = { _ in started.fulfill() }
|
||||||
|
defer { planes.cancelAll() }
|
||||||
|
let model = try makeModel(service: ImmediatePreparationService(), planeService: planes)
|
||||||
|
let pending = Task { await model.refreshPlaneStatus() }
|
||||||
|
await fulfillment(of: [started], timeout: 2)
|
||||||
|
if invalidate { model.invalidatePlaneStatus() } else { pending.cancel() }
|
||||||
|
try planes.finish(index: 0)
|
||||||
|
await pending.value
|
||||||
|
XCTAssertNil(model.planeStatus)
|
||||||
|
XCTAssertFalse(model.isLoadingPlaneStatus)
|
||||||
|
XCTAssertNil(model.planeStatusErrorMessage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 暂停后重启读取时,旧代次的响应不能盖掉新状态或结束新请求。
|
||||||
|
func testNewPlaneRequestAfterInvalidationRejectsOlderResponse() async throws {
|
||||||
|
let planes = SuspendedPlaneStatusService()
|
||||||
|
let firstStarted = expectation(description: "旧无人机请求")
|
||||||
|
let secondStarted = expectation(description: "新无人机请求")
|
||||||
|
planes.requestStarted = { if $0 == 0 { firstStarted.fulfill() } else { secondStarted.fulfill() } }
|
||||||
|
defer { planes.cancelAll() }
|
||||||
|
let model = try makeModel(service: ImmediatePreparationService(), planeService: planes)
|
||||||
|
let first = Task { await model.refreshPlaneStatus() }
|
||||||
|
await fulfillment(of: [firstStarted], timeout: 2)
|
||||||
|
model.invalidatePlaneStatus()
|
||||||
|
let second = Task { await model.refreshPlaneStatus() }
|
||||||
|
await fulfillment(of: [secondStarted], timeout: 2)
|
||||||
|
try planes.finish(index: 0)
|
||||||
|
await first.value
|
||||||
|
XCTAssertNil(model.planeStatus)
|
||||||
|
XCTAssertTrue(model.isLoadingPlaneStatus)
|
||||||
|
let busy = DroneDockPlaneStatusTestData.plane(status: 2, text: "拍摄中 · 电量 50%", battery: 50)
|
||||||
|
try planes.finish(index: 1, response: DroneDockPlaneStatusTestData.response(planes: [busy], recommend: busy))
|
||||||
|
await second.value
|
||||||
|
XCTAssertEqual(model.deviceStatusText, "拍摄中 · 电量 50%")
|
||||||
|
XCTAssertFalse(model.isLoadingPlaneStatus)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 登录账号、凭证、门店或景区变化时,购买和无人机状态都不能继续显示。
|
||||||
|
func testPlaneIdentityChangesRejectInFlightResponse() async throws {
|
||||||
|
for changed in [context(userID: "other"), context(scenicID: 129), context(storeID: 38), context(token: "other-token")] {
|
||||||
|
let scope = PreparationContextBox(context())
|
||||||
|
let planes = SuspendedPlaneStatusService()
|
||||||
|
let started = expectation(description: "无人机身份校验")
|
||||||
|
planes.requestStarted = { _ in started.fulfill() }
|
||||||
|
defer { planes.cancelAll() }
|
||||||
|
let model = try makeModel(service: ImmediatePreparationService(), scope: scope, planeService: planes)
|
||||||
|
await model.refresh()
|
||||||
|
let pending = Task { await model.refreshPlaneStatus() }
|
||||||
|
await fulfillment(of: [started], timeout: 2)
|
||||||
|
scope.value = changed
|
||||||
|
try planes.finish(index: 0)
|
||||||
|
await pending.value
|
||||||
|
XCTAssertNil(model.planeStatus)
|
||||||
|
XCTAssertNil(model.projectInfo)
|
||||||
|
XCTAssertNotNil(model.errorMessage)
|
||||||
|
XCTAssertNotNil(model.planeStatusErrorMessage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 轮询建议缺失或过小使用五秒,较长值保留但最多一分钟。
|
||||||
|
func testPlanePollIntervalUsesSafeBounds() async throws {
|
||||||
|
let planes = try DroneDockPlaneStatusTestService()
|
||||||
|
let model = try makeModel(service: ImmediatePreparationService(), planeService: planes)
|
||||||
|
XCTAssertEqual(model.pollIntervalNanoseconds, 5_000_000_000)
|
||||||
|
for (hint, seconds) in [(nil, 5), (Optional(-1), 5), (0, 5), (1000, 5), (7000, 7), (120000, 60)] {
|
||||||
|
planes.result = .success(try DroneDockPlaneStatusTestData.response(pollHintMS: hint))
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
XCTAssertEqual(model.pollIntervalNanoseconds, UInt64(seconds) * 1_000_000_000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 缺少登录会话时在本地拦截无人机读取,不让后台轮询发出无身份请求。
|
||||||
|
func testMissingSessionSkipsPlaneRequest() async throws {
|
||||||
|
let planes = try DroneDockPlaneStatusTestService()
|
||||||
|
let model = try makeModel(service: ImmediatePreparationService(),
|
||||||
|
scope: PreparationContextBox(context(token: "")), planeService: planes)
|
||||||
|
await model.refreshPlaneStatus()
|
||||||
|
XCTAssertTrue(planes.requests.isEmpty)
|
||||||
|
XCTAssertNil(model.planeStatus)
|
||||||
|
XCTAssertNotNil(model.planeStatusErrorMessage)
|
||||||
|
XCTAssertFalse(model.isLoadingPlaneStatus)
|
||||||
|
}
|
||||||
|
|
||||||
/// 每例使用内存订单和会话,不接触真实账号。
|
/// 每例使用内存订单和会话,不接触真实账号。
|
||||||
private func makeModel(service: any DroneDockPreparationServing, scope: PreparationContextBox? = nil,
|
private func makeModel(service: any DroneDockPreparationServing, scope: PreparationContextBox? = nil,
|
||||||
projectID: Int? = 101) throws -> DroneDockPreparationViewModel {
|
projectID: Int? = 101, planeService: (any DroneDockPlaneStatusServing)? = nil) throws -> DroneDockPreparationViewModel {
|
||||||
let scope = scope ?? PreparationContextBox(context())
|
let scope = scope ?? PreparationContextBox(context())
|
||||||
var order: [String: Any] = ["order_number": "TEST-PREPARATION-001", "project_name": "旧列表套餐",
|
var order: [String: Any] = ["order_number": "TEST-PREPARATION-001", "project_name": "旧列表套餐",
|
||||||
"shoot_count": 9, "shot_count": 2, "remaining_count": 7]
|
"shoot_count": 9, "shot_count": 2, "remaining_count": 7]
|
||||||
order["project_id"] = projectID
|
order["project_id"] = projectID
|
||||||
let decoded = try JSONDecoder().decode(DroneDockHomeOrder.self, from: JSONSerialization.data(withJSONObject: order))
|
let decoded = try JSONDecoder().decode(DroneDockHomeOrder.self, from: JSONSerialization.data(withJSONObject: order))
|
||||||
return DroneDockPreparationViewModel(context: scope.value, order: decoded, service: service,
|
return DroneDockPreparationViewModel(context: scope.value, order: decoded, service: service,
|
||||||
|
planeStatusService: try planeService ?? DroneDockPlaneStatusTestService(),
|
||||||
|
taskCreationService: DroneDockTaskCreationTestService(),
|
||||||
|
shootService: DroneDockShootTestService(),
|
||||||
currentContext: { scope.value })
|
currentContext: { scope.value })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -365,3 +630,34 @@ private final class SuspendedPreparationService: DroneDockPreparationServing {
|
|||||||
projects = []
|
projects = []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 精确控制无人机状态完成次序,验证轮询取消、重入和身份变化。
|
||||||
|
@MainActor
|
||||||
|
private final class SuspendedPlaneStatusService: DroneDockPlaneStatusServing {
|
||||||
|
var requestStarted: ((Int) -> Void)?
|
||||||
|
private(set) var requests: [Int] = []
|
||||||
|
private var pending: [CheckedContinuation<DroneDockPlaneStatusResponse, Error>?] = []
|
||||||
|
|
||||||
|
/// 挂起每个读取,测试负责明确返回或取消。
|
||||||
|
func planeStatus(scenicID: Int) async throws -> DroneDockPlaneStatusResponse {
|
||||||
|
requests.append(scenicID)
|
||||||
|
return try await withCheckedThrowingContinuation { continuation in
|
||||||
|
pending.append(continuation)
|
||||||
|
requestStarted?(pending.count - 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 默认返回测试空态,也可指定不同工作状态核对乱序。
|
||||||
|
func finish(index: Int, response: DroneDockPlaneStatusResponse? = nil) throws {
|
||||||
|
let result = try response ?? DroneDockPlaneStatusTestData.response()
|
||||||
|
let continuation = pending[index]
|
||||||
|
pending[index] = nil
|
||||||
|
continuation?.resume(returning: result)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 测试退出时恢复全部等待者,防止 continuation 泄漏。
|
||||||
|
func cancelAll() {
|
||||||
|
pending.forEach { $0?.resume(throwing: CancellationError()) }
|
||||||
|
pending = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ import UIKit
|
|||||||
import XCTest
|
import XCTest
|
||||||
@testable import suixinkan
|
@testable import suixinkan
|
||||||
|
|
||||||
/// 验证准备页仅请求购买快照,以及点位航线选择、刷新和错误状态。
|
/// 验证准备页购买快照、独立设备状态、点位航线选择与错误恢复。
|
||||||
@MainActor
|
@MainActor
|
||||||
final class DroneDockPreparationViewTests: XCTestCase {
|
final class DroneDockPreparationViewTests: XCTestCase {
|
||||||
private weak var previousKeyWindow: UIWindow?
|
private weak var previousKeyWindow: UIWindow?
|
||||||
|
|
||||||
/// 页面显示后仅请求项目购买快照,额度和配置来自真实接口字段,召唤仍禁用。
|
/// 页面只读取准备信息,有效购买配置允许明确点击创建任务,出现时不自动写入。
|
||||||
func testProjectSnapshotDisplaysOrderPointsRoutesAfterPageAppears() async throws {
|
func testProjectSnapshotDisplaysOrderPointsRoutesAfterPageAppears() async throws {
|
||||||
let (controller, session) = try makeController(responses: [DroneDockPreparationViewFixtures.projectEnvelope()])
|
let (controller, session) = try makeController(responses: [DroneDockPreparationViewFixtures.projectEnvelope()])
|
||||||
XCTAssertTrue(session.requests.isEmpty, "准备页尚未显示时不预先请求或创建任务")
|
XCTAssertTrue(session.requests.isEmpty, "准备页尚未显示时不预先请求或创建任务")
|
||||||
@@ -29,13 +29,12 @@ final class DroneDockPreparationViewTests: XCTestCase {
|
|||||||
XCTAssertFalse(texts.contains("位置待确认"))
|
XCTAssertFalse(texts.contains("位置待确认"))
|
||||||
XCTAssertFalse(texts.contains("机巢未连接"))
|
XCTAssertFalse(texts.contains("机巢未连接"))
|
||||||
XCTAssertFalse(texts.contains("在拍摄范围内"))
|
XCTAssertFalse(texts.contains("在拍摄范围内"))
|
||||||
XCTAssertTrue(texts.contains("召唤功能暂未开放"))
|
XCTAssertTrue(texts.contains("点击后创建任务并召唤无人机"))
|
||||||
XCTAssertEqual(list.numberOfItems(inSection: 1), 2)
|
XCTAssertEqual(list.numberOfItems(inSection: 1), 2)
|
||||||
XCTAssertNil(controller.navigationItem.rightBarButtonItem, "真实准备页不显示演示状态菜单")
|
XCTAssertNil(controller.navigationItem.rightBarButtonItem, "真实准备页不显示演示状态菜单")
|
||||||
let summon = try button(in: controller.view, id: "drone.preparation.summon")
|
let summon = try button(in: controller.view, id: "drone.preparation.summon")
|
||||||
XCTAssertFalse(summon.isEnabled)
|
XCTAssertTrue(summon.isEnabled)
|
||||||
XCTAssertEqual(summon.title(for: .normal), "确认并召唤")
|
XCTAssertEqual(summon.title(for: .normal), "确认并召唤")
|
||||||
summon.sendActions(for: .touchUpInside)
|
|
||||||
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
|
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
|
||||||
XCTAssertNil(controller.presentedViewController)
|
XCTAssertNil(controller.presentedViewController)
|
||||||
XCTAssertEqual(session.requests.count, 1)
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
@@ -198,10 +197,369 @@ final class DroneDockPreparationViewTests: XCTestCase {
|
|||||||
XCTAssertEqual(controller.viewModel.selectedRouteID, 202)
|
XCTAssertEqual(controller.viewModel.selectedRouteID, 202)
|
||||||
XCTAssertEqual(controller.viewModel.selectedSpotID, 101)
|
XCTAssertEqual(controller.viewModel.selectedSpotID, 101)
|
||||||
XCTAssertTrue(visibleTexts(in: controller.view).contains { $0.contains("航线暂停使用") })
|
XCTAssertTrue(visibleTexts(in: controller.view).contains { $0.contains("航线暂停使用") })
|
||||||
XCTAssertFalse(try button(in: controller.view, id: "drone.preparation.summon").isEnabled)
|
XCTAssertTrue(try button(in: controller.view, id: "drone.preparation.summon").isEnabled)
|
||||||
assertOnlyPreparationReads(session)
|
assertOnlyPreparationReads(session)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 底栏从朱工接口展示推荐状态和连接状态,创建待飞任务按购买配置开放。
|
||||||
|
func testPlaneStatusAPIUpdatesFooterIndependently() async throws {
|
||||||
|
let plane = DroneDockPlaneStatusTestData.plane()
|
||||||
|
let payload = try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": [
|
||||||
|
"scenic_id": 128, "planes": [plane], "recommend": plane, "connected": true, "poll_hint_ms": 5000
|
||||||
|
]])
|
||||||
|
let planeSession = MockURLSession(responses: [payload])
|
||||||
|
let planeAPI = DroneDockPlaneStatusAPI(client: APIClient(environment: .testing, session: planeSession))
|
||||||
|
let (controller, projectSession) = try DroneDockPreparationViewFixtures.controller(
|
||||||
|
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
|
||||||
|
planeService: planeAPI)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
try await settle(window) { self.visibleTexts(in: controller.view).contains("空闲 · 电量 95%") }
|
||||||
|
XCTAssertTrue(visibleTexts(in: controller.view).contains("机巢已连接"))
|
||||||
|
XCTAssertEqual(planeSession.requests.count, 1)
|
||||||
|
XCTAssertEqual(planeSession.requests.first?.url?.path, "/api/app/airport/plane-status")
|
||||||
|
XCTAssertEqual(projectSession.requests.count, 1)
|
||||||
|
XCTAssertTrue(try button(in: controller.view, id: "drone.preparation.summon").isEnabled)
|
||||||
|
assertUnambiguousLayout(in: controller.view)
|
||||||
|
capture(window, name: "准备页-无人机状态与电量")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 轮询只更新设备底栏,前后台切换和离开页面均停止,并保留购买配置选择。
|
||||||
|
func testPlanePollingStopsOutsideForegroundAndPreservesSelection() async throws {
|
||||||
|
let idle = DroneDockPlaneStatusTestData.plane()
|
||||||
|
let service = try DroneDockPlaneStatusTestService(response: DroneDockPlaneStatusTestData.response(
|
||||||
|
planes: [idle], recommend: idle, connected: true))
|
||||||
|
let project = try DroneDockPreparationViewFixtures.projectEnvelope()
|
||||||
|
let (controller, projectSession) = try DroneDockPreparationViewFixtures.controller(
|
||||||
|
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
|
||||||
|
responses: [project, project], planeService: service,
|
||||||
|
pollDelay: { _ in try await Task.sleep(nanoseconds: 40_000_000) })
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
let list = try collection(in: controller)
|
||||||
|
try await settle(window) { service.requests.count >= 2 && controller.viewModel.selectedSpotID == 101 }
|
||||||
|
try select(IndexPath(item: 1, section: 1), in: list)
|
||||||
|
let shooting = DroneDockPlaneStatusTestData.plane(status: 2, text: "拍摄中 · 电量 72%", battery: 72)
|
||||||
|
service.result = .success(try DroneDockPlaneStatusTestData.response(planes: [shooting], recommend: shooting, connected: true))
|
||||||
|
try await settle(window) { self.visibleTexts(in: controller.view).contains("拍摄中 · 电量 72%") }
|
||||||
|
XCTAssertEqual(controller.viewModel.selectedSpotID, 102)
|
||||||
|
XCTAssertEqual(controller.viewModel.selectedRouteID, 301)
|
||||||
|
XCTAssertEqual(projectSession.requests.count, 1)
|
||||||
|
|
||||||
|
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
|
||||||
|
let pausedCount = service.requests.count
|
||||||
|
try await Task.sleep(nanoseconds: 150_000_000)
|
||||||
|
XCTAssertEqual(service.requests.count, pausedCount)
|
||||||
|
XCTAssertNil(controller.viewModel.planeStatus)
|
||||||
|
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
|
try await settle(window) { service.requests.count > pausedCount && controller.viewModel.planeStatus != nil }
|
||||||
|
XCTAssertEqual(controller.viewModel.selectedSpotID, 102)
|
||||||
|
XCTAssertEqual(projectSession.requests.count, 1)
|
||||||
|
|
||||||
|
let navigation = try XCTUnwrap(controller.navigationController)
|
||||||
|
navigation.pushViewController(UIViewController(), animated: false)
|
||||||
|
// UIKit 的 appearance 回调可能晚于 push 返回,先确认页面已实际离开。
|
||||||
|
try await settle(window) { controller.viewModel.projectInfo == nil }
|
||||||
|
let departedCount = service.requests.count
|
||||||
|
try await Task.sleep(nanoseconds: 150_000_000)
|
||||||
|
XCTAssertEqual(service.requests.count, departedCount)
|
||||||
|
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
|
try await Task.sleep(nanoseconds: 100_000_000)
|
||||||
|
XCTAssertEqual(service.requests.count, departedCount)
|
||||||
|
navigation.popViewController(animated: false)
|
||||||
|
try await settle(window) { service.requests.count > departedCount && controller.viewModel.projectInfo != nil }
|
||||||
|
XCTAssertEqual(projectSession.requests.count, 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 轮询发现会话变化时,旧点位与航线同步从页面撤下,不能只更新底栏。
|
||||||
|
func testPollingScopeChangeRemovesOldPurchaseCards() async throws {
|
||||||
|
let context = DroneDockPreparationViewFixtures.context()
|
||||||
|
let scope = PreparationViewContextBox(context)
|
||||||
|
let idle = DroneDockPlaneStatusTestData.plane()
|
||||||
|
let service = try DroneDockPlaneStatusTestService(response: DroneDockPlaneStatusTestData.response(
|
||||||
|
planes: [idle], recommend: idle, connected: true))
|
||||||
|
let (controller, _) = try DroneDockPreparationViewFixtures.controller(
|
||||||
|
context: context, order: DroneDockPreparationViewFixtures.order(), planeService: service,
|
||||||
|
pollDelay: { _ in try await Task.sleep(nanoseconds: 40_000_000) }, currentContext: { scope.value })
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
let list = try collection(in: controller)
|
||||||
|
try await settle(window) { controller.viewModel.projectInfo != nil && controller.viewModel.planeStatus != nil }
|
||||||
|
scope.value = DroneDockHomeContext(userID: context.userID, accountType: context.accountType,
|
||||||
|
scenicID: 129, scenicName: "另一测试景区", storeID: context.storeID,
|
||||||
|
photographerName: context.photographerName, token: "preparation-test-token")
|
||||||
|
try await settle(window) { self.visibleTexts(in: controller.view).contains("准备信息加载失败") }
|
||||||
|
XCTAssertNil(controller.viewModel.projectInfo)
|
||||||
|
XCTAssertNil(controller.viewModel.planeStatus)
|
||||||
|
XCTAssertEqual(list.numberOfItems(inSection: 1), 0)
|
||||||
|
XCTAssertEqual(list.numberOfItems(inSection: 2), 0)
|
||||||
|
XCTAssertFalse(visibleTexts(in: controller.view).contains("测试航线甲"))
|
||||||
|
XCTAssertFalse(try button(in: controller.view, id: "drone.preparation.summon").isEnabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 设备读取失败不清空点位和航线,手动刷新可从未知状态恢复到离线状态。
|
||||||
|
func testPlaneFailureKeepsProjectAndRefreshRecovers() async throws {
|
||||||
|
let service = try DroneDockPlaneStatusTestService()
|
||||||
|
service.result = .failure(APIError.networkFailed("测试设备状态暂不可用"))
|
||||||
|
let project = try DroneDockPreparationViewFixtures.projectEnvelope()
|
||||||
|
let (controller, projectSession) = try DroneDockPreparationViewFixtures.controller(
|
||||||
|
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
|
||||||
|
responses: [project, project], planeService: service)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
try await settle(window) { controller.viewModel.projectInfo != nil && controller.viewModel.planeStatusErrorMessage != nil }
|
||||||
|
XCTAssertTrue(visibleTexts(in: controller.view).contains("状态待确认"))
|
||||||
|
XCTAssertTrue(visibleTexts(in: controller.view).contains { $0.contains("测试设备状态暂不可用") })
|
||||||
|
XCTAssertTrue(visibleTexts(in: controller.view).contains("测试航线甲"))
|
||||||
|
let offline = DroneDockPlaneStatusTestData.plane(status: 0, text: "离线 · 电量未知", battery: nil)
|
||||||
|
service.result = .success(try DroneDockPlaneStatusTestData.response(planes: [offline], recommend: offline, connected: false))
|
||||||
|
try button(in: controller.view, id: "drone.preparation.refreshSummon").sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { self.visibleTexts(in: controller.view).contains("离线 · 电量未知") }
|
||||||
|
XCTAssertTrue(visibleTexts(in: controller.view).contains("机巢未连接"))
|
||||||
|
XCTAssertNil(controller.viewModel.planeStatusErrorMessage)
|
||||||
|
XCTAssertEqual(projectSession.requests.count, 2)
|
||||||
|
XCTAssertEqual(service.requests.count, 2)
|
||||||
|
XCTAssertTrue(try button(in: controller.view, id: "drone.preparation.summon").isEnabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 连续点击只创建和召唤一次,成功后导航;返回准备页可查看原任务而不再次 POST。
|
||||||
|
func testCreateAndShootSuccessOpensSameTaskOnlyOnce() async throws {
|
||||||
|
let receipt = try DroneDockTaskCreationTestData.response(remaining: 1)
|
||||||
|
let data = try JSONSerialization.jsonObject(with: Data(receipt.dataJSON.utf8))
|
||||||
|
let envelope = try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": data])
|
||||||
|
let creationSession = MockURLSession(responses: [envelope])
|
||||||
|
let api = DroneDockTaskCreationAPI(client: APIClient(environment: .testing, session: creationSession))
|
||||||
|
let shootEnvelope = try JSONSerialization.data(withJSONObject: ["code": 100000, "data": ["test_ack": true]])
|
||||||
|
let shootSession = MockURLSession(responses: [shootEnvelope])
|
||||||
|
let shootAPI = DroneDockShootAPI(client: APIClient(environment: .testing, session: shootSession))
|
||||||
|
let project = try DroneDockPreparationViewFixtures.projectEnvelope()
|
||||||
|
let (controller, projectSession) = try DroneDockPreparationViewFixtures.controller(
|
||||||
|
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
|
||||||
|
responses: [project, project, project], creationService: api, shootService: shootAPI)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
let list = try collection(in: controller)
|
||||||
|
let summon = try button(in: controller.view, id: "drone.preparation.summon")
|
||||||
|
let navigation = try XCTUnwrap(controller.navigationController)
|
||||||
|
try await settle(window) { summon.isEnabled }
|
||||||
|
try select(IndexPath(item: 1, section: 2), in: list)
|
||||||
|
summon.sendActions(for: .touchUpInside)
|
||||||
|
summon.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { navigation.topViewController is DroneDockPreparationTaskDestinationStub }
|
||||||
|
let destination = try XCTUnwrap(navigation.topViewController as? DroneDockPreparationTaskDestinationStub)
|
||||||
|
XCTAssertEqual(destination.taskID, 501)
|
||||||
|
XCTAssertEqual(navigation.viewControllers.count, 2)
|
||||||
|
XCTAssertNil(controller.presentedViewController)
|
||||||
|
XCTAssertEqual(shootSession.requests.count, 1)
|
||||||
|
let shoot = try XCTUnwrap(shootSession.requests.first)
|
||||||
|
XCTAssertEqual(shoot.httpMethod, "POST")
|
||||||
|
XCTAssertEqual(shoot.url?.path, "/api/app/airport/shoot")
|
||||||
|
let shootBody = try XCTUnwrap(JSONSerialization.jsonObject(with: XCTUnwrap(shoot.httpBody)) as? [String: Any])
|
||||||
|
XCTAssertTrue(NSDictionary(dictionary: shootBody).isEqual(to: ["id": 501, "restart": false]))
|
||||||
|
XCTAssertNil(shootBody["plane_id"])
|
||||||
|
XCTAssertEqual(creationSession.requests.count, 1)
|
||||||
|
let request = try XCTUnwrap(creationSession.requests.first)
|
||||||
|
let body = try XCTUnwrap(JSONSerialization.jsonObject(with: XCTUnwrap(request.httpBody)) as? [String: Any])
|
||||||
|
XCTAssertTrue(NSDictionary(dictionary: body).isEqual(to: [
|
||||||
|
"scenic_id": 128, "order_number": "TEST-PREPARATION-001", "scenic_spot_id": 101, "air_line_id": 202
|
||||||
|
]))
|
||||||
|
XCTAssertEqual(projectSession.requests.count, 2)
|
||||||
|
navigation.popViewController(animated: false)
|
||||||
|
try await settle(window) { navigation.topViewController === controller && projectSession.requests.count == 3 && summon.isEnabled }
|
||||||
|
XCTAssertEqual(summon.title(for: .normal), "查看拍摄任务")
|
||||||
|
XCTAssertEqual(navigation.viewControllers.count, 1, "返回不会自动再次跳转")
|
||||||
|
summon.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { navigation.topViewController is DroneDockPreparationTaskDestinationStub }
|
||||||
|
XCTAssertEqual((navigation.topViewController as? DroneDockPreparationTaskDestinationStub)?.taskID, 501)
|
||||||
|
XCTAssertEqual(creationSession.requests.count, 1)
|
||||||
|
XCTAssertEqual(shootSession.requests.count, 1)
|
||||||
|
assertOnlyPreparationReads(projectSession)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 完整导航后才 GET 同一任务,读取失败与重试不会触发第二次创建或召唤。
|
||||||
|
func testSummonNavigationReadsSameTaskAndRetriesOnlyShooting() async throws {
|
||||||
|
let creation = DroneDockTaskCreationTestService(result: .success(try DroneDockTaskCreationTestData.response()))
|
||||||
|
let shoot = DroneDockShootTestService(result: .success(DroneDockShootResponse(dataJSON: nil)))
|
||||||
|
var payload = DroneDockShootingTaskTestData.payload()
|
||||||
|
payload["order_flight_task"] = ["id": 501, "order_number": "TEST-PREPARATION-001", "scenic_id": 128]
|
||||||
|
payload["header"] = ["order_number": "TEST-PREPARATION-001", "title": "创建后读取的任务"]
|
||||||
|
let success = try JSONSerialization.data(withJSONObject: ["code": 100000, "data": payload])
|
||||||
|
let readSession = MockURLSession(responses: [try TestJSON.errorEnvelope(code: 100099, msg: "测试任务暂不可读"), success])
|
||||||
|
let readAPI = DroneDockShootingAPI(client: APIClient(environment: .testing, session: readSession))
|
||||||
|
let project = try DroneDockPreparationViewFixtures.projectEnvelope()
|
||||||
|
let (controller, _) = try DroneDockPreparationViewFixtures.controller(
|
||||||
|
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
|
||||||
|
responses: [project, project], creationService: creation, shootService: shoot,
|
||||||
|
taskControllerFactory: { id, order, context in
|
||||||
|
XCTAssertEqual(id, 501)
|
||||||
|
XCTAssertEqual(shoot.requests, [501], "必须先确认召唤成功,再构造任务页")
|
||||||
|
XCTAssertTrue(readSession.requests.isEmpty)
|
||||||
|
let destination = DroneDockShootingTaskViewController(viewModel: DroneDockShootingTaskViewModel(
|
||||||
|
context: context, taskID: id, order: order, service: readAPI, currentContext: { context }))
|
||||||
|
destination.loadViewIfNeeded()
|
||||||
|
XCTAssertTrue(readSession.requests.isEmpty, "构造和加载视图不得提前读取任务")
|
||||||
|
return destination
|
||||||
|
})
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
let primary = try button(in: controller.view, id: "drone.preparation.summon")
|
||||||
|
try await settle(window) { primary.isEnabled }
|
||||||
|
XCTAssertTrue(readSession.requests.isEmpty)
|
||||||
|
primary.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) {
|
||||||
|
(controller.navigationController?.topViewController as? DroneDockShootingTaskViewController)?.viewModel.errorMessage != nil
|
||||||
|
}
|
||||||
|
let destination = try XCTUnwrap(controller.navigationController?.topViewController as? DroneDockShootingTaskViewController)
|
||||||
|
XCTAssertEqual(destination.viewModel.taskID, 501)
|
||||||
|
try button(in: destination.view, id: "drone.task.remote.refresh").sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { destination.viewModel.response != nil }
|
||||||
|
XCTAssertEqual(destination.viewModel.title, "创建后读取的任务")
|
||||||
|
XCTAssertEqual(readSession.requests.count, 2)
|
||||||
|
for request in readSession.requests {
|
||||||
|
XCTAssertEqual(request.httpMethod, "GET")
|
||||||
|
XCTAssertEqual(request.url?.path, "/api/app/airport/shooting")
|
||||||
|
let query = URLComponents(url: try XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems ?? []
|
||||||
|
XCTAssertEqual(Dictionary(uniqueKeysWithValues: query.map { ($0.name, $0.value ?? "") }), ["id": "501", "live_battery": "1"])
|
||||||
|
XCTAssertNil(request.httpBody)
|
||||||
|
}
|
||||||
|
XCTAssertEqual(creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(shoot.requests, [501])
|
||||||
|
XCTAssertEqual(controller.navigationController?.viewControllers.count, 2)
|
||||||
|
capture(window, name: "召唤成功后-同任务读取与失败重试")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 明确业务失败展示后端提示并允许再次点击,界面不离开准备页。
|
||||||
|
func testCreationBusinessFailureIsShownAndAllowsExplicitRetry() async throws {
|
||||||
|
let creation = DroneDockTaskCreationTestService(result: .failure(APIError.serverCode(160001, "测试航线暂不可用")))
|
||||||
|
let project = try DroneDockPreparationViewFixtures.projectEnvelope()
|
||||||
|
let (controller, _) = try DroneDockPreparationViewFixtures.controller(
|
||||||
|
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
|
||||||
|
responses: [project, project, project], creationService: creation)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
let summon = try button(in: controller.view, id: "drone.preparation.summon")
|
||||||
|
try await settle(window) { summon.isEnabled }
|
||||||
|
summon.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { self.visibleTexts(in: controller.view).contains("任务创建未成功") && summon.isEnabled }
|
||||||
|
let response = try XCTUnwrap(find(in: controller.view, id: "drone.preparation.creationResponse") as? UITextView)
|
||||||
|
XCTAssertEqual(response.text, "测试航线暂不可用")
|
||||||
|
XCTAssertEqual(creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
|
||||||
|
creation.result = .success(try DroneDockTaskCreationTestData.response())
|
||||||
|
summon.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { controller.viewModel.createdTask?.taskID == 501 && summon.isEnabled }
|
||||||
|
XCTAssertEqual(summon.title(for: .normal), "重试召唤")
|
||||||
|
XCTAssertEqual(creation.requests.count, 2)
|
||||||
|
XCTAssertNil(controller.presentedViewController)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 明确业务拒绝可对原任务重试召唤,不重新创建;购买刷新失败不能隐藏回执。
|
||||||
|
func testShootBusinessRejectionRetriesSameTaskWithoutCreatingAgain() async throws {
|
||||||
|
let creation = DroneDockTaskCreationTestService(result: .success(try DroneDockTaskCreationTestData.response()))
|
||||||
|
let shoot = DroneDockShootTestService(result: .failure(APIError.serverCode(100099, "测试无人机忙碌")))
|
||||||
|
let project = try DroneDockPreparationViewFixtures.projectEnvelope()
|
||||||
|
let projectFailure = try TestJSON.errorEnvelope(code: 160001, msg: "测试购买信息暂不可读")
|
||||||
|
let (controller, projects) = try DroneDockPreparationViewFixtures.controller(
|
||||||
|
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
|
||||||
|
responses: [project, project, projectFailure], creationService: creation, shootService: shoot)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
let primary = try button(in: controller.view, id: "drone.preparation.summon")
|
||||||
|
try await settle(window) { primary.isEnabled }
|
||||||
|
primary.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { controller.viewModel.shootErrorMessage != nil && primary.isEnabled }
|
||||||
|
XCTAssertEqual(primary.title(for: .normal), "重试召唤")
|
||||||
|
XCTAssertEqual(controller.viewModel.createdTask?.taskID, 501)
|
||||||
|
let failedText = try XCTUnwrap(find(in: controller.view, id: "drone.preparation.shootResponse") as? UITextView)
|
||||||
|
XCTAssertEqual(failedText.text, "测试无人机忙碌")
|
||||||
|
try button(in: controller.view, id: "drone.preparation.refreshSummon").sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { controller.viewModel.errorMessage != nil && primary.isEnabled }
|
||||||
|
shoot.result = .success(try DroneDockShootTestData.response())
|
||||||
|
primary.sendActions(for: .touchUpInside)
|
||||||
|
primary.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { controller.navigationController?.topViewController is DroneDockPreparationTaskDestinationStub }
|
||||||
|
XCTAssertEqual((controller.navigationController?.topViewController as? DroneDockPreparationTaskDestinationStub)?.taskID, 501)
|
||||||
|
XCTAssertEqual(shoot.requests, [501, 501])
|
||||||
|
XCTAssertEqual(creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(projects.requests.count, 3)
|
||||||
|
XCTAssertNotNil(controller.viewModel.shootResponse)
|
||||||
|
XCTAssertEqual(controller.navigationController?.viewControllers.count, 2)
|
||||||
|
XCTAssertNil(controller.presentedViewController)
|
||||||
|
XCTAssertFalse(visibleTexts(in: controller.view).contains("无人机已到达"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 接口业务成功但没有 data 时仍携创建所得 ID 导航,不依赖未约定的成功字段。
|
||||||
|
func testEmptyShootSuccessStillOpensCreatedTask() async throws {
|
||||||
|
let creation = DroneDockTaskCreationTestService(result: .success(try DroneDockTaskCreationTestData.response()))
|
||||||
|
let shoot = DroneDockShootTestService(result: .success(DroneDockShootResponse(dataJSON: nil)))
|
||||||
|
let project = try DroneDockPreparationViewFixtures.projectEnvelope()
|
||||||
|
let (controller, _) = try DroneDockPreparationViewFixtures.controller(
|
||||||
|
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
|
||||||
|
responses: [project, project], creationService: creation, shootService: shoot)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
let primary = try button(in: controller.view, id: "drone.preparation.summon")
|
||||||
|
try await settle(window) { primary.isEnabled }
|
||||||
|
primary.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { controller.navigationController?.topViewController is DroneDockPreparationTaskDestinationStub }
|
||||||
|
XCTAssertEqual((controller.navigationController?.topViewController as? DroneDockPreparationTaskDestinationStub)?.taskID, 501)
|
||||||
|
XCTAssertNotNil(controller.viewModel.shootResponse)
|
||||||
|
XCTAssertNil(controller.viewModel.shootDataJSON)
|
||||||
|
XCTAssertFalse(controller.viewModel.summonOutcomeUnknown)
|
||||||
|
XCTAssertEqual(shoot.requests, [501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 召唤请求超时后不能直接重发,保留任务并提示核对结果。
|
||||||
|
func testUnknownShootResultLocksRetryEvenAfterRefresh() async throws {
|
||||||
|
let creation = DroneDockTaskCreationTestService(result: .success(try DroneDockTaskCreationTestData.response()))
|
||||||
|
let shoot = DroneDockShootTestService(result: .failure(APIError.networkFailed("测试召唤超时")))
|
||||||
|
let project = try DroneDockPreparationViewFixtures.projectEnvelope()
|
||||||
|
let (controller, projects) = try DroneDockPreparationViewFixtures.controller(
|
||||||
|
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
|
||||||
|
responses: [project, project, project], creationService: creation, shootService: shoot)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
let primary = try button(in: controller.view, id: "drone.preparation.summon")
|
||||||
|
try await settle(window) { primary.isEnabled }
|
||||||
|
primary.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { controller.viewModel.summonOutcomeUnknown && !primary.isEnabled }
|
||||||
|
XCTAssertEqual(primary.title(for: .normal), "召唤结果待核对")
|
||||||
|
XCTAssertEqual(controller.viewModel.createdTask?.taskID, 501)
|
||||||
|
XCTAssertNotNil(find(in: controller.view, id: "drone.preparation.shootResponse"))
|
||||||
|
try button(in: controller.view, id: "drone.preparation.refreshSummon").sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { projects.requests.count == 3 && !controller.viewModel.isLoading }
|
||||||
|
primary.sendActions(for: .touchUpInside)
|
||||||
|
XCTAssertEqual(shoot.requests, [501])
|
||||||
|
XCTAssertEqual(creation.requests.count, 1)
|
||||||
|
XCTAssertFalse(primary.isEnabled)
|
||||||
|
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 请求超时不能推断创建失败,原页说明待核对并阻止刷新后重复提交。
|
||||||
|
func testAmbiguousCreationFailureStaysLockedOnPage() async throws {
|
||||||
|
let session = MockURLSession(results: [.failure(URLError(.timedOut))])
|
||||||
|
let api = DroneDockTaskCreationAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
let project = try DroneDockPreparationViewFixtures.projectEnvelope()
|
||||||
|
let (controller, projects) = try DroneDockPreparationViewFixtures.controller(
|
||||||
|
context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(),
|
||||||
|
responses: [project, project, project], creationService: api)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
let summon = try button(in: controller.view, id: "drone.preparation.summon")
|
||||||
|
try await settle(window) { summon.isEnabled }
|
||||||
|
summon.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { controller.viewModel.taskCreationOutcomeUnknown && summon.title(for: .normal) == "结果待核对" }
|
||||||
|
XCTAssertFalse(summon.isEnabled)
|
||||||
|
XCTAssertNotNil(find(in: controller.view, id: "drone.preparation.creationResponse"))
|
||||||
|
try button(in: controller.view, id: "drone.preparation.refreshSummon").sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { projects.requests.count == 3 && !controller.viewModel.isLoading }
|
||||||
|
summon.sendActions(for: .touchUpInside)
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
XCTAssertFalse(summon.isEnabled)
|
||||||
|
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
|
||||||
|
XCTAssertNil(controller.presentedViewController)
|
||||||
|
}
|
||||||
|
|
||||||
/// 创建固定身份和只使用匿名替身的准备页。
|
/// 创建固定身份和只使用匿名替身的准备页。
|
||||||
private func makeController(responses: [Data]) throws -> (DroneDockRemotePreparationViewController, MockURLSession) {
|
private func makeController(responses: [Data]) throws -> (DroneDockRemotePreparationViewController, MockURLSession) {
|
||||||
try DroneDockPreparationViewFixtures.controller(context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(), responses: responses)
|
try DroneDockPreparationViewFixtures.controller(context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(), responses: responses)
|
||||||
@@ -269,7 +627,7 @@ final class DroneDockPreparationViewTests: XCTestCase {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 所有准备页网络请求只能是 project-info GET,且携带本次订单与项目身份。
|
/// 购买配置服务只请求 project-info,设备状态通过独立替身验证。
|
||||||
private func assertOnlyPreparationReads(_ session: MockURLSession, file: StaticString = #filePath, line: UInt = #line) {
|
private func assertOnlyPreparationReads(_ session: MockURLSession, file: StaticString = #filePath, line: UInt = #line) {
|
||||||
XCTAssertFalse(session.requests.isEmpty, file: file, line: line)
|
XCTAssertFalse(session.requests.isEmpty, file: file, line: line)
|
||||||
XCTAssertTrue(session.requests.allSatisfy { $0.httpMethod == "GET" && $0.url?.path == "/api/yf-handset-app/photog/multi-plane/project-info" && $0.httpBody == nil }, file: file, line: line)
|
XCTAssertTrue(session.requests.allSatisfy { $0.httpMethod == "GET" && $0.url?.path == "/api/yf-handset-app/photog/multi-plane/project-info" && $0.httpBody == nil }, file: file, line: line)
|
||||||
@@ -339,15 +697,44 @@ enum DroneDockPreparationViewFixtures {
|
|||||||
return try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": data])
|
return try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": data])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 创建只请求项目购买快照的准备页,替身记录所有请求以发现额外接口调用。
|
/// 购买与设备各使用独立替身,避免响应顺序影响测试。
|
||||||
static func controller(context: DroneDockHomeContext, order: DroneDockHomeOrder,
|
static func controller(context: DroneDockHomeContext, order: DroneDockHomeOrder,
|
||||||
responses: [Data]? = nil) throws -> (DroneDockRemotePreparationViewController, MockURLSession) {
|
responses: [Data]? = nil,
|
||||||
|
planeService: (any DroneDockPlaneStatusServing)? = nil,
|
||||||
|
creationService: (any DroneDockTaskCreating)? = nil,
|
||||||
|
shootService: (any DroneDockShootServing)? = nil,
|
||||||
|
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) {
|
||||||
let payloads = try responses ?? [projectEnvelope(orderNumber: order.orderNumber ?? "", projectID: order.projectID ?? 101)]
|
let payloads = try responses ?? [projectEnvelope(orderNumber: order.orderNumber ?? "", projectID: order.projectID ?? 101)]
|
||||||
let session = MockURLSession(responses: payloads)
|
let session = MockURLSession(responses: payloads)
|
||||||
let client = APIClient(environment: .testing, session: session, notificationCenter: NotificationCenter())
|
let client = APIClient(environment: .testing, session: session, notificationCenter: NotificationCenter())
|
||||||
client.bindAuthTokenProvider { "preparation-test-token" }
|
client.bindAuthTokenProvider { "preparation-test-token" }
|
||||||
let model = DroneDockPreparationViewModel(context: context, order: order,
|
let model = DroneDockPreparationViewModel(context: context, order: order,
|
||||||
service: DroneDockPreparationAPI(client: client), currentContext: { context })
|
service: DroneDockPreparationAPI(client: client),
|
||||||
return (DroneDockRemotePreparationViewController(viewModel: model), session)
|
planeStatusService: try planeService ?? DroneDockPlaneStatusTestService(),
|
||||||
|
taskCreationService: creationService ?? DroneDockTaskCreationTestService(),
|
||||||
|
shootService: shootService ?? DroneDockShootTestService(),
|
||||||
|
currentContext: currentContext ?? { context })
|
||||||
|
let factory = taskControllerFactory ?? { taskID, _, _ in DroneDockPreparationTaskDestinationStub(taskID: taskID) }
|
||||||
|
return (DroneDockRemotePreparationViewController(viewModel: model, taskControllerFactory: factory,
|
||||||
|
planeStatusPollDelay: pollDelay), session)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 测试中在主线程切换景区,避免并发闭包捕获可变局部变量。
|
||||||
|
@MainActor
|
||||||
|
private final class PreparationViewContextBox {
|
||||||
|
var value: DroneDockHomeContext
|
||||||
|
init(_ value: DroneDockHomeContext) { self.value = value }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 导航替身只记录所传任务身份,避免准备页测试意外使用真实查询服务。
|
||||||
|
@MainActor
|
||||||
|
private final class DroneDockPreparationTaskDestinationStub: UIViewController {
|
||||||
|
let taskID: Int
|
||||||
|
init(taskID: Int) { self.taskID = taskID; super.init(nibName: nil, bundle: nil) }
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||||
|
override func viewDidLoad() { super.viewDidLoad(); view.backgroundColor = .white; title = "拍摄任务" }
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 验证召唤只使用已有任务,成功回执保留原 JSON,所有写请求均通过网络替身验证。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockShootAPITests: XCTestCase {
|
||||||
|
/// 按本轮联调要求只发送任务与非重启标记,完全省略 plane_id。
|
||||||
|
func testShootSendsOneAuthenticatedPOSTWithOnlyTaskIDAndRestart() async throws {
|
||||||
|
let session = MockURLSession(responses: [try envelope(data: [:])])
|
||||||
|
let client = APIClient(environment: .testing, session: session)
|
||||||
|
client.bindAuthTokenProvider { "shoot-test-token" }
|
||||||
|
_ = try await DroneDockShootAPI(client: client).shoot(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/shoot")
|
||||||
|
XCTAssertNil(request.url?.query)
|
||||||
|
XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "shoot-test-token")
|
||||||
|
let body = try XCTUnwrap(JSONSerialization.jsonObject(with: XCTUnwrap(request.httpBody)) as? [String: Any])
|
||||||
|
XCTAssertEqual(Set(body.keys), ["id", "restart"])
|
||||||
|
XCTAssertEqual(body["id"] as? Int, 501)
|
||||||
|
XCTAssertNil(body["plane_id"])
|
||||||
|
XCTAssertEqual(body["restart"] as? Bool, false)
|
||||||
|
let typedBody = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: XCTUnwrap(request.httpBody))
|
||||||
|
guard case .object(let values) = typedBody else { return XCTFail("请求必须是 JSON 对象") }
|
||||||
|
XCTAssertEqual(values["restart"], .bool(false))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 无效任务身份不发送召唤,也不尝试创建任务或选机。
|
||||||
|
func testInvalidTaskIDIsRejectedBeforeSending() async throws {
|
||||||
|
let session = MockURLSession(responses: [])
|
||||||
|
let api = DroneDockShootAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
for taskID in [0, -1] {
|
||||||
|
do {
|
||||||
|
_ = try await api.shoot(taskID: taskID)
|
||||||
|
XCTFail("无效任务 ID 不应发送")
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
XCTAssertTrue(session.requests.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 调用前已取消的任务不会向服务端提交召唤。
|
||||||
|
func testCancelledTaskDoesNotSendPOST() async throws {
|
||||||
|
let session = MockURLSession(responses: [])
|
||||||
|
let api = DroneDockShootAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
let pending = Task { @MainActor in try await api.shoot(taskID: 501) }
|
||||||
|
pending.cancel()
|
||||||
|
do {
|
||||||
|
_ = try await pending.value
|
||||||
|
XCTFail("已取消任务不应发送召唤")
|
||||||
|
} catch is CancellationError {}
|
||||||
|
XCTAssertTrue(session.requests.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 只有 100000 算业务成功,失败码的 null 或空数据不能被 emptyData 适配误判成功。
|
||||||
|
func testBusinessFailureWithEmptyDataPreservesCodeAndMessage() async throws {
|
||||||
|
for data: Any in [NSNull(), [:] as [String: Any], [] as [Any]] {
|
||||||
|
let session = MockURLSession(responses: [try envelope(data: data, code: 100099, message: "暂无可用无人机")])
|
||||||
|
let api = DroneDockShootAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
do {
|
||||||
|
_ = try await api.shoot(taskID: 501)
|
||||||
|
XCTFail("业务拒绝不能当作成功")
|
||||||
|
} catch let APIError.serverCode(code, message) {
|
||||||
|
XCTAssertEqual(code, 100099)
|
||||||
|
XCTAssertEqual(message, "暂无可用无人机")
|
||||||
|
}
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 超时结果不明确时接口层不重试同一写请求。
|
||||||
|
func testTimeoutIsNotAutomaticallyRetried() async throws {
|
||||||
|
let session = MockURLSession(results: [.failure(URLError(.timedOut))])
|
||||||
|
let api = DroneDockShootAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
do {
|
||||||
|
_ = try await api.shoot(taskID: 501)
|
||||||
|
XCTFail("超时不能当作成功")
|
||||||
|
} catch let APIError.networkFailed(message) {
|
||||||
|
XCTAssertFalse(message.isEmpty)
|
||||||
|
}
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
XCTAssertEqual(session.requests.first?.url?.path, "/api/app/airport/shoot")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// HTTP 失败即使携带成功业务码也不能转为召唤业务成功。
|
||||||
|
func testHTTPFailureIsNotConvertedIntoEmptySuccess() async throws {
|
||||||
|
let session = MockURLSession(responses: [try envelope(data: NSNull())], statusCode: 500)
|
||||||
|
let api = DroneDockShootAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
do {
|
||||||
|
_ = try await api.shoot(taskID: 501)
|
||||||
|
XCTFail("HTTP 失败不应成功")
|
||||||
|
} catch let APIError.httpStatus(code, _) {
|
||||||
|
XCTAssertEqual(code, 500)
|
||||||
|
}
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 畸形响应仍是解析错误,不被成功空 data 的兼容分支吞掉。
|
||||||
|
func testMalformedJSONRemainsDecodeFailureWithoutRetry() async throws {
|
||||||
|
let session = MockURLSession(responses: [Data("{\"code\":100000,\"data\":".utf8)])
|
||||||
|
let api = DroneDockShootAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
do {
|
||||||
|
_ = try await api.shoot(taskID: 501)
|
||||||
|
XCTFail("畸形 JSON 不应成功")
|
||||||
|
} catch let APIError.decodeFailed(message) {
|
||||||
|
XCTAssertFalse(message.isEmpty)
|
||||||
|
}
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 已确认业务成功的 null 或缺失 data 仍算成功,但不伪造可展示 JSON。
|
||||||
|
func testBusinessSuccessWithNullOrMissingDataHasNoFabricatedJSON() async throws {
|
||||||
|
let missing = try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success"])
|
||||||
|
for response in [try envelope(data: NSNull()), missing] {
|
||||||
|
let session = MockURLSession(responses: [response])
|
||||||
|
let result = try await DroneDockShootAPI(client: APIClient(environment: .testing, session: session)).shoot(taskID: 501)
|
||||||
|
XCTAssertNil(result.dataJSON)
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 成功 data 的未知对象、空数组、数字和 false 均保留,不要求未约定的任务身份字段。
|
||||||
|
func testSuccessDataPreservesArbitraryJSONIncludingEmptyAndFalse() async throws {
|
||||||
|
let object: [String: Any] = ["future": ["flag": false, "value": NSNull()],
|
||||||
|
"items": ["001", 0, 12.5, NSNull()], "url": "https://example.invalid/test"]
|
||||||
|
for data: Any in [object, [:] as [String: Any], [] as [Any], false, 0, "accepted"] {
|
||||||
|
let session = MockURLSession(responses: [try envelope(data: data)])
|
||||||
|
let result = try await DroneDockShootAPI(client: APIClient(environment: .testing, session: session)).shoot(taskID: 501)
|
||||||
|
let text = try XCTUnwrap(result.dataJSON)
|
||||||
|
let displayed = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: Data(text.utf8))
|
||||||
|
let originalData = try JSONSerialization.data(withJSONObject: data, options: [.fragmentsAllowed])
|
||||||
|
let original = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: originalData)
|
||||||
|
XCTAssertEqual(displayed, original)
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
if case .object(let fields) = displayed {
|
||||||
|
XCTAssertNil(fields["task_id"])
|
||||||
|
XCTAssertNil(fields["plane_id"])
|
||||||
|
XCTAssertNil(fields["code"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func envelope(data: Any, code: Int = 100000, message: String = "success") throws -> Data {
|
||||||
|
try JSONSerialization.data(withJSONObject: ["code": code, "msg": message, "data": data])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import Foundation
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 召唤请求的匿名回执,仅用于验证真实 data 保留,不模拟飞行完成。
|
||||||
|
enum DroneDockShootTestData {
|
||||||
|
/// 返回匿名成功 data;字段只是测试替身,不作为后端合同或实测响应。
|
||||||
|
static func response() throws -> DroneDockShootResponse {
|
||||||
|
try JSONDecoder().decode(DroneDockShootResponse.self,
|
||||||
|
from: Data(#"{"test_receipt":"TEST-SHOOT-501","extra":null}"#.utf8))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 单次召唤测试服务,只记录接收的任务 ID,不创建任务或读取 shooting。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockShootTestService: DroneDockShootServing {
|
||||||
|
/// 本次返回结果,可模拟明确业务拒绝后恢复。
|
||||||
|
var result: Result<DroneDockShootResponse, Error>
|
||||||
|
/// 已接收的任务 ID,供检查重试始终复用同一任务。
|
||||||
|
private(set) var requests: [Int] = []
|
||||||
|
/// 在调用时观察创建和召唤顺序。
|
||||||
|
var onRequest: (() -> Void)?
|
||||||
|
|
||||||
|
/// 默认明确拒绝,使不关注召唤的旧测试无需构造回执。
|
||||||
|
init(result: Result<DroneDockShootResponse, Error>? = nil) {
|
||||||
|
self.result = result ?? .failure(APIError.serverCode(160001, "测试召唤未配置"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 记录一次召唤请求,返回当前配置,不自动重试。
|
||||||
|
func shoot(taskID: Int) async throws -> DroneDockShootResponse {
|
||||||
|
requests.append(taskID)
|
||||||
|
onRequest?()
|
||||||
|
return try result.get()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 验证创建后复用任务召唤,以及成功、拒绝、未知结果与生命周期防重复规则。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockShootViewModelTests: XCTestCase {
|
||||||
|
/// 只有拿到张工创建的任务 ID 后才召唤,成功仅表示请求被接受。
|
||||||
|
func testFirstActionCreatesThenSummonsSameTask() async throws {
|
||||||
|
let fixture = try ShootFlowFixture()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
var observedRequest = false
|
||||||
|
var observedSubmitting = false
|
||||||
|
fixture.shoot.onRequest = {
|
||||||
|
observedRequest = true
|
||||||
|
XCTAssertEqual(fixture.model.createdTask?.taskID, 501)
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
}
|
||||||
|
await fixture.model.prepareAndSummon {
|
||||||
|
if fixture.model.isSummoning {
|
||||||
|
observedSubmitting = true
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
XCTAssertTrue(observedRequest)
|
||||||
|
XCTAssertTrue(observedSubmitting)
|
||||||
|
XCTAssertEqual(fixture.projects.requests, 2)
|
||||||
|
XCTAssertEqual(fixture.shoot.requests, [501])
|
||||||
|
XCTAssertNotNil(fixture.model.creationDataJSON)
|
||||||
|
XCTAssertNotNil(fixture.model.shootDataJSON)
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
XCTAssertEqual(fixture.model.primaryButtonTitle, "查看拍摄任务")
|
||||||
|
XCTAssertEqual(fixture.model.admissionMessage, "任务 501 的召唤请求已提交,请等待任务状态更新")
|
||||||
|
XCTAssertFalse(fixture.model.admissionMessage.contains("已起飞"))
|
||||||
|
XCTAssertFalse(fixture.model.admissionMessage.contains("已到达"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 业务明确成功但无 data 时仍锁定成功,不伪造 JSON 或误开放重试。
|
||||||
|
func testSuccessWithoutDataLocksSubmission() async throws {
|
||||||
|
let fixture = try ShootFlowFixture()
|
||||||
|
fixture.shoot.result = .success(DroneDockShootResponse(dataJSON: nil))
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertNotNil(fixture.model.shootResponse)
|
||||||
|
XCTAssertNil(fixture.model.shootDataJSON)
|
||||||
|
XCTAssertFalse(fixture.model.summonOutcomeUnknown)
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(fixture.shoot.requests, [501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 成功回执跨购买刷新、设备轮询和同实例返回保留,绝不再次提交。
|
||||||
|
func testSuccessfulSummonSurvivesRefreshAndInvalidation() async throws {
|
||||||
|
let fixture = try ShootFlowFixture()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
let receipt = fixture.model.shootDataJSON
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.refreshPlaneStatus()
|
||||||
|
fixture.model.invalidatePlaneStatus()
|
||||||
|
fixture.model.invalidate()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertEqual(fixture.model.createdTask?.taskID, 501)
|
||||||
|
XCTAssertEqual(fixture.model.shootDataJSON, receipt)
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(fixture.shoot.requests, [501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 召唤明确业务拒绝可手动重试,同任务直接召唤,不重复创建或购买预检。
|
||||||
|
func testBusinessFailureRetriesSameTaskWithoutCreatingAgain() async throws {
|
||||||
|
let fixture = try ShootFlowFixture()
|
||||||
|
fixture.shoot.result = .failure(APIError.serverCode(100099, "测试无人机暂不可用"))
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
let receipt = fixture.model.creationDataJSON
|
||||||
|
XCTAssertEqual(fixture.model.createdTask?.taskID, 501)
|
||||||
|
XCTAssertEqual(fixture.model.shootErrorMessage, "测试无人机暂不可用")
|
||||||
|
XCTAssertFalse(fixture.model.summonOutcomeUnknown)
|
||||||
|
XCTAssertTrue(fixture.model.isPrimaryActionEnabled)
|
||||||
|
XCTAssertEqual(fixture.model.primaryButtonTitle, "重试召唤")
|
||||||
|
fixture.shoot.result = .success(try DroneDockShootTestData.response())
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertEqual(fixture.model.creationDataJSON, receipt)
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(fixture.projects.requests, 2)
|
||||||
|
XCTAssertEqual(fixture.shoot.requests, [501, 501])
|
||||||
|
XCTAssertNil(fixture.model.shootErrorMessage)
|
||||||
|
XCTAssertNotNil(fixture.model.shootResponse)
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 召唤 POST 无法确认结果时保留未知锁,刷新和同实例返回均不能重发。
|
||||||
|
func testAmbiguousFailureRemainsLockedAfterRefreshAndReturn() async throws {
|
||||||
|
let errors: [Error] = [APIError.networkFailed("测试超时"), APIError.httpStatus(500, "测试异常"),
|
||||||
|
APIError.decodeFailed("测试响应无效"), APIError.invalidResponse, CancellationError()]
|
||||||
|
for error in errors {
|
||||||
|
let fixture = try ShootFlowFixture()
|
||||||
|
fixture.shoot.result = .failure(error)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertTrue(fixture.model.summonOutcomeUnknown)
|
||||||
|
XCTAssertFalse(fixture.model.taskCreationOutcomeUnknown)
|
||||||
|
XCTAssertNil(fixture.model.shootResponse)
|
||||||
|
XCTAssertEqual(fixture.model.createdTask?.taskID, 501)
|
||||||
|
XCTAssertEqual(fixture.model.primaryButtonTitle, "召唤结果待核对")
|
||||||
|
XCTAssertTrue(fixture.model.shootErrorMessage?.contains("勿重复提交") == true)
|
||||||
|
fixture.model.invalidate()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.refreshPlaneStatus()
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(fixture.shoot.requests, [501])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建明确失败或结果未知,都不能把缺失任务 ID 交给召唤接口。
|
||||||
|
func testCreationFailureNeverSummons() async throws {
|
||||||
|
for error in [APIError.serverCode(160001, "测试拒绝创建"), APIError.networkFailed("测试创建超时")] {
|
||||||
|
let fixture = try ShootFlowFixture()
|
||||||
|
fixture.creation.result = .failure(error)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertTrue(fixture.shoot.requests.isEmpty)
|
||||||
|
XCTAssertNil(fixture.model.createdTask)
|
||||||
|
XCTAssertNil(fixture.model.shootResponse)
|
||||||
|
XCTAssertFalse(fixture.model.summonOutcomeUnknown)
|
||||||
|
XCTAssertEqual(fixture.model.isPrimaryActionEnabled, !fixture.model.taskCreationOutcomeUnknown)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 最新购买权限不允许创建时,两个写接口都不触发。
|
||||||
|
func testPreflightRejectionStopsBothWrites() async throws {
|
||||||
|
let fixture = try ShootFlowFixture()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
fixture.projects.allowCreation = false
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertTrue(fixture.creation.requests.isEmpty)
|
||||||
|
XCTAssertTrue(fixture.shoot.requests.isEmpty)
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 已有低层创建回执时主按钮直接复用,不做第二次任务创建。
|
||||||
|
func testExistingCreatedTaskCanBeSummonedOnce() async throws {
|
||||||
|
let fixture = try ShootFlowFixture()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertTrue(fixture.shoot.requests.isEmpty)
|
||||||
|
XCTAssertEqual(fixture.model.admissionMessage, "任务 501 已创建,等待召唤")
|
||||||
|
XCTAssertTrue(fixture.model.isPrimaryActionEnabled)
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertEqual(fixture.projects.requests, 2)
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(fixture.shoot.requests, [501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 召唤进行中重复点击、切点和刷新不会产生并发写请求。
|
||||||
|
func testPendingSummonRejectsRepeatedActions() async throws {
|
||||||
|
let service = SuspendedShootFlowService()
|
||||||
|
let fixture = try ShootFlowFixture(shootService: service)
|
||||||
|
let started = expectation(description: "召唤已发送")
|
||||||
|
service.started = { started.fulfill() }
|
||||||
|
defer { service.cancelAll() }
|
||||||
|
await fixture.model.refresh()
|
||||||
|
let pending = Task { await fixture.model.prepareAndSummon() }
|
||||||
|
await fulfillment(of: [started], timeout: 2)
|
||||||
|
XCTAssertTrue(fixture.model.isSummoning)
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
XCTAssertTrue(fixture.model.isTaskSelectionLocked)
|
||||||
|
XCTAssertEqual(fixture.model.primaryButtonTitle, "正在召唤无人机…")
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
fixture.model.selectSpot(id: 202)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertEqual(fixture.model.selectedSpotID, 201)
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
try service.finish()
|
||||||
|
await pending.value
|
||||||
|
XCTAssertNotNil(fixture.model.shootResponse)
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 召唤发送后取消或离开,即便随后有成功回执,也保持待核对且不自动重发。
|
||||||
|
func testCancellationOrInvalidationAfterPostLocksUnknown() async throws {
|
||||||
|
for invalidate in [false, true] {
|
||||||
|
let service = SuspendedShootFlowService()
|
||||||
|
let fixture = try ShootFlowFixture(shootService: service)
|
||||||
|
let started = expectation(description: "待取消召唤")
|
||||||
|
service.started = { started.fulfill() }
|
||||||
|
defer { service.cancelAll() }
|
||||||
|
await fixture.model.refresh()
|
||||||
|
let pending = Task { await fixture.model.prepareAndSummon() }
|
||||||
|
await fulfillment(of: [started], timeout: 2)
|
||||||
|
if invalidate { fixture.model.invalidate() } else { pending.cancel() }
|
||||||
|
try service.finish()
|
||||||
|
await pending.value
|
||||||
|
XCTAssertEqual(fixture.model.createdTask?.taskID, 501)
|
||||||
|
XCTAssertNil(fixture.model.shootResponse)
|
||||||
|
XCTAssertTrue(fixture.model.summonOutcomeUnknown)
|
||||||
|
XCTAssertFalse(fixture.model.taskCreationOutcomeUnknown)
|
||||||
|
XCTAssertFalse(fixture.model.isSummoning)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建成功但召唤尚未发出时取消,不误记召唤未知;下次只召唤已有任务。
|
||||||
|
func testCancellationBeforeShootDoesNotMarkUnknown() async throws {
|
||||||
|
let fixture = try ShootFlowFixture()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
let pending = Task {
|
||||||
|
await fixture.model.prepareAndSummon {
|
||||||
|
if fixture.model.isSummoning { withUnsafeCurrentTask { $0?.cancel() } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await pending.value
|
||||||
|
XCTAssertEqual(fixture.model.createdTask?.taskID, 501)
|
||||||
|
XCTAssertTrue(fixture.shoot.requests.isEmpty)
|
||||||
|
XCTAssertFalse(fixture.model.summonOutcomeUnknown)
|
||||||
|
XCTAssertTrue(fixture.model.isPrimaryActionEnabled)
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(fixture.shoot.requests, [501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 召唤期间切换身份,迟到响应不展示,旧实例不能恢复写入入口。
|
||||||
|
func testContextChangeRejectsLateSummon() async throws {
|
||||||
|
let service = SuspendedShootFlowService()
|
||||||
|
let fixture = try ShootFlowFixture(shootService: service)
|
||||||
|
let started = expectation(description: "会话切换中的召唤")
|
||||||
|
service.started = { started.fulfill() }
|
||||||
|
defer { service.cancelAll() }
|
||||||
|
await fixture.model.refresh()
|
||||||
|
let pending = Task { await fixture.model.prepareAndSummon() }
|
||||||
|
await fulfillment(of: [started], timeout: 2)
|
||||||
|
fixture.scope.scenicID = 129
|
||||||
|
try service.finish()
|
||||||
|
await pending.value
|
||||||
|
XCTAssertNil(fixture.model.createdTask)
|
||||||
|
XCTAssertNil(fixture.model.shootResponse)
|
||||||
|
XCTAssertTrue(fixture.model.summonOutcomeUnknown)
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
fixture.scope.scenicID = 128
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 已成功后由设备轮询发现身份变化,也撤下旧回执而不释放成功防重复锁。
|
||||||
|
func testIdentityChangeRemovesSuccessfulReceipt() async throws {
|
||||||
|
let fixture = try ShootFlowFixture()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
fixture.scope.scenicID = 129
|
||||||
|
await fixture.model.refreshPlaneStatus()
|
||||||
|
XCTAssertNil(fixture.model.createdTask)
|
||||||
|
XCTAssertNil(fixture.model.shootResponse)
|
||||||
|
XCTAssertFalse(fixture.model.isPrimaryActionEnabled)
|
||||||
|
fixture.scope.scenicID = 128
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.prepareAndSummon()
|
||||||
|
XCTAssertEqual(fixture.shoot.requests, [501])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 独立内存数据源,所有写入由测试替身处理,不接触真实任务或设备。
|
||||||
|
@MainActor
|
||||||
|
private final class ShootFlowFixture {
|
||||||
|
let projects = ShootFlowProjectService()
|
||||||
|
let creation: DroneDockTaskCreationTestService
|
||||||
|
let shoot: DroneDockShootTestService
|
||||||
|
let scope = ShootFlowContext()
|
||||||
|
let model: DroneDockPreparationViewModel
|
||||||
|
|
||||||
|
init(shootService: (any DroneDockShootServing)? = nil) throws {
|
||||||
|
creation = DroneDockTaskCreationTestService(result: .success(try DroneDockTaskCreationTestData.response()))
|
||||||
|
shoot = DroneDockShootTestService(result: .success(try DroneDockShootTestData.response()))
|
||||||
|
let currentScope = scope
|
||||||
|
let order = try JSONDecoder().decode(DroneDockHomeOrder.self,
|
||||||
|
from: Data(#"{"order_number":"TEST-PREPARATION-001","project_id":101}"#.utf8))
|
||||||
|
model = DroneDockPreparationViewModel(context: scope.value, order: order, service: projects,
|
||||||
|
planeStatusService: try DroneDockPlaneStatusTestService(),
|
||||||
|
taskCreationService: creation, shootService: shootService ?? shoot,
|
||||||
|
currentContext: { currentScope.value })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 返回已购点位和航线,可在点击前模拟权限变更。
|
||||||
|
@MainActor
|
||||||
|
private final class ShootFlowProjectService: DroneDockPreparationServing {
|
||||||
|
var allowCreation = true
|
||||||
|
private(set) var requests = 0
|
||||||
|
|
||||||
|
func projectInfo(scenicID: Int, projectID: Int, orderNumber: String) async throws -> DroneDockProjectInfoResponse {
|
||||||
|
requests += 1
|
||||||
|
let data: [String: Any] = ["order_number": "TEST-PREPARATION-001", "project_id": 101,
|
||||||
|
"shoot_count": 5, "shot_count": 0, "remaining_count": 5,
|
||||||
|
"can_create_task": allowCreation,
|
||||||
|
"spot": [["scenic_spot_id": 201, "scenic_spot_name": "测试点位", "available": true,
|
||||||
|
"air_lines": [["air_line_id": 301, "air_line_name": "测试航线", "available": true, "samples": []]]]]]
|
||||||
|
return try JSONDecoder().decode(DroneDockProjectInfoResponse.self, from: JSONSerialization.data(withJSONObject: data))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 可改变景区的主线程会话替身。
|
||||||
|
@MainActor
|
||||||
|
private final class ShootFlowContext {
|
||||||
|
var scenicID = 128
|
||||||
|
var value: DroneDockHomeContext {
|
||||||
|
DroneDockHomeContext(userID: "shoot-test-user", accountType: "store_user", scenicID: scenicID,
|
||||||
|
scenicName: "测试景区", storeID: 37, photographerName: "测试人员", token: "shoot-test-token")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 挂起单次召唤 POST,精确控制取消和迟到回执场景。
|
||||||
|
@MainActor
|
||||||
|
private final class SuspendedShootFlowService: DroneDockShootServing {
|
||||||
|
var started: (() -> Void)?
|
||||||
|
private(set) var requests: [Int] = []
|
||||||
|
private var continuation: CheckedContinuation<DroneDockShootResponse, Error>?
|
||||||
|
|
||||||
|
func shoot(taskID: Int) async throws -> DroneDockShootResponse {
|
||||||
|
requests.append(taskID)
|
||||||
|
return try await withCheckedThrowingContinuation { continuation in
|
||||||
|
self.continuation = continuation
|
||||||
|
started?()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func finish() throws {
|
||||||
|
let response = try DroneDockShootTestData.response()
|
||||||
|
let pending = continuation
|
||||||
|
continuation = nil
|
||||||
|
pending?.resume(returning: response)
|
||||||
|
}
|
||||||
|
|
||||||
|
func cancelAll() {
|
||||||
|
continuation?.resume(throwing: CancellationError())
|
||||||
|
continuation = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 验证 shooting 仅按已有任务读取状态,完整展示响应且不发送创建或飞控请求。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockShootingAPITests: XCTestCase {
|
||||||
|
/// 正式读取只包含任务 ID 和实时电量查询项,复用统一登录 Token。
|
||||||
|
func testShootingUsesAuthenticatedGETWithExactQueryAndNoBody() async throws {
|
||||||
|
let session = MockURLSession(responses: [try envelope(payload())])
|
||||||
|
let client = APIClient(environment: .testing, session: session)
|
||||||
|
client.bindAuthTokenProvider { "shooting-test-token" }
|
||||||
|
let result = try await DroneDockShootingAPI(client: client).shooting(taskID: 501)
|
||||||
|
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
let request = try XCTUnwrap(session.requests.first)
|
||||||
|
XCTAssertEqual(request.httpMethod, "GET")
|
||||||
|
XCTAssertEqual(request.url?.path, "/api/app/airport/shooting")
|
||||||
|
XCTAssertNil(request.httpBody)
|
||||||
|
XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "shooting-test-token")
|
||||||
|
let components = try XCTUnwrap(URLComponents(url: XCTUnwrap(request.url), resolvingAgainstBaseURL: false))
|
||||||
|
XCTAssertEqual(components.queryItems, [URLQueryItem(name: "id", value: "501"),
|
||||||
|
URLQueryItem(name: "live_battery", value: "1")])
|
||||||
|
XCTAssertEqual(result.orderNumber, "TEST-SHOOTING-001")
|
||||||
|
XCTAssertEqual(result.scenic?.id, 128)
|
||||||
|
XCTAssertEqual(result.scenicSpot?.id, 201)
|
||||||
|
XCTAssertEqual(result.airLine?.scenicSpotID, 201)
|
||||||
|
XCTAssertEqual(result.header?.title, "测试点位 · 测试航线")
|
||||||
|
XCTAssertEqual(result.currentPlane?.statusText, "状态待确认")
|
||||||
|
XCTAssertEqual(result.executeGate?.canExecute, false)
|
||||||
|
XCTAssertEqual(result.executeGate?.code, "wayline_missing")
|
||||||
|
XCTAssertEqual(result.ui?.phase, "pending")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 明确关闭实时电量时仍是同一只读接口,不产生替代写请求。
|
||||||
|
func testLiveBatteryFalseIsAnExplicitQueryValue() async throws {
|
||||||
|
let session = MockURLSession(responses: [try envelope([:])])
|
||||||
|
_ = try await DroneDockShootingAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
.shooting(taskID: 502, liveBattery: false)
|
||||||
|
let request = try XCTUnwrap(session.requests.first)
|
||||||
|
XCTAssertEqual(request.httpMethod, "GET")
|
||||||
|
XCTAssertNil(request.httpBody)
|
||||||
|
let query = URLComponents(url: try XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems
|
||||||
|
XCTAssertEqual(query, [URLQueryItem(name: "id", value: "502"), URLQueryItem(name: "live_battery", value: "0")])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 非正整数任务 ID 在发送前拒绝,不尝试根据订单新建任务。
|
||||||
|
func testInvalidTaskIDDoesNotSendAnyRequest() async throws {
|
||||||
|
let session = MockURLSession(responses: [])
|
||||||
|
let api = DroneDockShootingAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
for taskID in [0, -1] {
|
||||||
|
do {
|
||||||
|
_ = try await api.shooting(taskID: taskID)
|
||||||
|
XCTFail("应拒绝无效任务 ID")
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
XCTAssertTrue(session.requests.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 后端业务拒绝保留原业务码和文案,不能改为本地拍摄成功状态。
|
||||||
|
func testBusinessFailurePreservesBackendCodeAndMessage() async throws {
|
||||||
|
let session = MockURLSession(responses: [try TestJSON.errorEnvelope(code: 160002, msg: "任务不存在")])
|
||||||
|
let api = DroneDockShootingAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
do {
|
||||||
|
_ = try await api.shooting(taskID: 501)
|
||||||
|
XCTFail("应保留业务错误")
|
||||||
|
} catch let APIError.serverCode(code, message) {
|
||||||
|
XCTAssertEqual(code, 160002)
|
||||||
|
XCTAssertEqual(message, "任务不存在")
|
||||||
|
}
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
XCTAssertEqual(session.requests.first?.httpMethod, "GET")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 失败不会自动发请求,显式再读仍使用同一任务 ID 且全程没有 POST。
|
||||||
|
func testFailedReadCanBeRetriedForSameTaskWithoutCreatingAnotherTask() async throws {
|
||||||
|
let httpResponse = try XCTUnwrap(HTTPURLResponse(url: URL(string: "https://api-test.zhifly.cn/mock")!,
|
||||||
|
statusCode: 200, httpVersion: nil, headerFields: nil))
|
||||||
|
let session = MockURLSession(results: [.failure(URLError(.timedOut)), .success((try envelope(payload()), httpResponse))])
|
||||||
|
let api = DroneDockShootingAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
do {
|
||||||
|
_ = try await api.shooting(taskID: 501)
|
||||||
|
XCTFail("首个读取应超时")
|
||||||
|
} catch {}
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
let result = try await api.shooting(taskID: 501)
|
||||||
|
XCTAssertEqual(result.executeGate?.canExecute, false)
|
||||||
|
XCTAssertEqual(session.requests.count, 2)
|
||||||
|
for request in session.requests {
|
||||||
|
XCTAssertEqual(request.httpMethod, "GET")
|
||||||
|
XCTAssertEqual(request.url?.path, "/api/app/airport/shooting")
|
||||||
|
XCTAssertNil(request.httpBody)
|
||||||
|
let query = URLComponents(url: try XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems
|
||||||
|
XCTAssertEqual(query?.first(where: { $0.name == "id" })?.value, "501")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 未建模设备读数、未知任务字段和空值完整显示,不伪造已校验的响应任务身份。
|
||||||
|
func testDataJSONPreservesUnknownFieldsAndOriginalTypes() throws {
|
||||||
|
var value = payload()
|
||||||
|
value["task"] = ["id": 999, "future_flag": false]
|
||||||
|
value["future"] = ["missing": NSNull(), "values": ["001", false, 0, 12.5]] as [String: Any]
|
||||||
|
value["metrics"] = [["key": "battery", "value": "0%"], ["key": "satellite", "value": NSNull()]]
|
||||||
|
value["plane_status"] = ["connected": false, "planes": [], "recommend": NSNull()] as [String: Any]
|
||||||
|
let response = try decode(value)
|
||||||
|
let displayed = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(response.dataJSON.utf8)) as? [String: Any])
|
||||||
|
XCTAssertTrue(NSDictionary(dictionary: displayed).isEqual(to: value))
|
||||||
|
XCTAssertTrue(response.dataJSON.contains("\n"))
|
||||||
|
XCTAssertNil(displayed["code"])
|
||||||
|
XCTAssertNil(displayed["msg"])
|
||||||
|
XCTAssertNil(displayed["time"])
|
||||||
|
XCTAssertNil(displayed["task_id"])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 真实 false、null 和缺失三种响应均可展示,不把未知门禁补成 true 或 false。
|
||||||
|
func testOptionalObjectsAndExecutionGatePreserveUnknownAndFalse() throws {
|
||||||
|
let empty = try decode([:])
|
||||||
|
XCTAssertNil(empty.scenic)
|
||||||
|
XCTAssertNil(empty.currentPlane)
|
||||||
|
XCTAssertNil(empty.executeGate)
|
||||||
|
|
||||||
|
let emptyObjects = try decode(["scenic": [:], "scenic_spot": [:], "air_line": [:],
|
||||||
|
"header": [:], "current_plane": [:], "execute_gate": [:], "ui": [:]])
|
||||||
|
XCTAssertNil(emptyObjects.scenic?.id)
|
||||||
|
XCTAssertNil(emptyObjects.executeGate?.canExecute)
|
||||||
|
|
||||||
|
let nulls = try decode(["current_plane": NSNull(), "execute_gate": ["can_execute": NSNull()]])
|
||||||
|
XCTAssertNil(nulls.currentPlane)
|
||||||
|
XCTAssertNil(nulls.executeGate?.canExecute)
|
||||||
|
let denied = try decode(["execute_gate": ["can_execute": false]])
|
||||||
|
XCTAssertEqual(denied.executeGate?.canExecute, false)
|
||||||
|
let allowed = try decode(["execute_gate": ["can_execute": true]])
|
||||||
|
XCTAssertEqual(allowed.executeGate?.canExecute, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 文案和数字不强转成执行许可,错误的已知字段类型不能展示为可信门禁。
|
||||||
|
func testMalformedKnownFieldsAreRejectedWithoutBooleanCoercion() throws {
|
||||||
|
for value: Any in ["false", "true", 0, 1] {
|
||||||
|
XCTAssertThrowsError(try decode(["execute_gate": ["can_execute": value]]))
|
||||||
|
}
|
||||||
|
XCTAssertThrowsError(try decode(["scenic": "128"]))
|
||||||
|
XCTAssertThrowsError(try decode(["header": ["title": false]]))
|
||||||
|
XCTAssertThrowsError(try JSONDecoder().decode(DroneDockShootingResponse.self, from: Data("[]".utf8)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 实测嵌套任务身份、摘要订单号和阶段说明均可解码,供任务页逐项核对。
|
||||||
|
func testNestedTaskIdentitiesHeaderAndStatusMessageAreDecoded() throws {
|
||||||
|
let response = try DroneDockShootingTaskTestData.response()
|
||||||
|
XCTAssertEqual(response.orderFlightTask?.id, 501)
|
||||||
|
XCTAssertEqual(response.orderFlightTask?.orderNumber, "TEST-TASK-PAGE-001")
|
||||||
|
XCTAssertEqual(response.orderFlightTask?.scenicID, 128)
|
||||||
|
XCTAssertEqual(response.task?.id, 501)
|
||||||
|
XCTAssertEqual(response.task?.status, 10)
|
||||||
|
XCTAssertEqual(response.task?.statusLabel, "待执行")
|
||||||
|
XCTAssertEqual(response.header?.orderNumber, "TEST-TASK-PAGE-001")
|
||||||
|
XCTAssertEqual(response.ui?.message, "测试阶段说明")
|
||||||
|
XCTAssertEqual(response.planeStatus?.scenicID, 128)
|
||||||
|
XCTAssertEqual(response.planeStatus?.pollHintMS, 5000)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 六项格式化零值保持可见,连接 false 与缺失/null 不混淆,未知读数仍完整保留。
|
||||||
|
func testTelemetryAndPlaneStatusPreserveZeroFalseNullAndUnknownFields() throws {
|
||||||
|
let value: [String: Any] = [
|
||||||
|
"metrics": [["key": "battery", "value": "0%", "raw": 0],
|
||||||
|
["key": "wind_speed", "value": "0m/s"],
|
||||||
|
["key": "rainfall", "value": NSNull()],
|
||||||
|
["key": "future_metric", "value": "测试新读数"]],
|
||||||
|
"plane_status": ["scenic_id": 128, "connected": false, "poll_hint_ms": 0,
|
||||||
|
"recommend": NSNull(), "future": ["flag": true]] as [String: Any]
|
||||||
|
]
|
||||||
|
let response = try decode(value)
|
||||||
|
XCTAssertEqual(response.metrics[0].displayText, "0%")
|
||||||
|
XCTAssertEqual(response.metrics[0].raw, .number(0))
|
||||||
|
XCTAssertEqual(response.metrics[1].displayText, "0m/s")
|
||||||
|
XCTAssertEqual(response.metrics[2].displayText, "—")
|
||||||
|
XCTAssertEqual(response.planeStatus?.connected, false)
|
||||||
|
XCTAssertEqual(response.planeStatus?.pollHintMS, 0)
|
||||||
|
let unknown = try decode(["plane_status": ["connected": NSNull(), "poll_hint_ms": NSNull()]])
|
||||||
|
XCTAssertNil(unknown.planeStatus?.connected)
|
||||||
|
XCTAssertNil(unknown.planeStatus?.pollHintMS)
|
||||||
|
let displayed = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(response.dataJSON.utf8)) as? [String: Any])
|
||||||
|
XCTAssertTrue(NSDictionary(dictionary: displayed).isEqual(to: value))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 格式化读数和连接状态不强转错误类型,避免把接口异常显示为可信设备状态。
|
||||||
|
func testMalformedTelemetryAndPlaneStatusAreRejected() throws {
|
||||||
|
XCTAssertThrowsError(try decode(["metrics": [["key": "battery", "value": false]]]))
|
||||||
|
XCTAssertThrowsError(try decode(["plane_status": ["connected": "false"]]))
|
||||||
|
XCTAssertThrowsError(try decode(["plane_status": ["poll_hint_ms": true]]))
|
||||||
|
XCTAssertThrowsError(try decode(["order_flight_task": ["id": true]]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 航线执行失败与订单任务执行中分别保留,未知新增字段不因展示模型扩展而丢失。
|
||||||
|
func testWaylineStatusIsDecodedSeparatelyFromOrderTaskStatus() throws {
|
||||||
|
let payload: [String: Any] = ["task": ["id": 501, "status": 20, "status_label": "执行中",
|
||||||
|
"wayline_status": 91, "wayline_status_label": "执行失败", "future": NSNull()]]
|
||||||
|
let response = try decode(payload)
|
||||||
|
XCTAssertEqual(response.task?.status, 20)
|
||||||
|
XCTAssertEqual(response.task?.waylineStatus, 91)
|
||||||
|
XCTAssertEqual(response.task?.waylineStatusLabel, "执行失败")
|
||||||
|
let displayed = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(response.dataJSON.utf8)) as? [String: Any])
|
||||||
|
XCTAssertTrue(NSDictionary(dictionary: displayed).isEqual(to: payload))
|
||||||
|
XCTAssertThrowsError(try decode(["task": ["wayline_status": true]]))
|
||||||
|
XCTAssertNil(try decode(["task": ["wayline_status": NSNull()]]).task?.waylineStatus)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 夹具只使用测试身份与文案,读取成功不等同于无人机已召唤。
|
||||||
|
private func payload() -> [String: Any] {
|
||||||
|
["order_number": "TEST-SHOOTING-001",
|
||||||
|
"scenic": ["id": 128, "name": "测试景区"],
|
||||||
|
"scenic_spot": ["id": 201, "name": "测试点位"],
|
||||||
|
"air_line": ["id": 301, "name": "测试航线", "scenic_spot_id": 201],
|
||||||
|
"header": ["title": "测试点位 · 测试航线", "tourist_label": "测试游客", "package_name": "测试套餐"],
|
||||||
|
"current_plane": ["id": 58, "sn_number": "TEST-PLANE-058", "work_status_label": "待确认", "status_text": "状态待确认"],
|
||||||
|
"execute_gate": ["can_execute": false, "code": "wayline_missing", "message": "尚未绑定飞行任务",
|
||||||
|
"primary_action": "blocked", "primary_action_label": "等待飞行任务"],
|
||||||
|
"ui": ["phase": "pending", "title": "任务信息已获取"]]
|
||||||
|
}
|
||||||
|
|
||||||
|
private func envelope(_ value: [String: Any]) throws -> Data {
|
||||||
|
try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": value])
|
||||||
|
}
|
||||||
|
|
||||||
|
private func decode(_ value: [String: Any]) throws -> DroneDockShootingResponse {
|
||||||
|
try JSONDecoder().decode(DroneDockShootingResponse.self, from: JSONSerialization.data(withJSONObject: value))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import Foundation
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 真实拍摄任务页测试共享的匿名任务、订单和设备快照。
|
||||||
|
enum DroneDockShootingTaskTestData {
|
||||||
|
/// 固定测试登录范围,参数可模拟切换景区或凭证。
|
||||||
|
static func context(scenicID: Int = 128, token: String = "task-read-test-token") -> DroneDockHomeContext {
|
||||||
|
DroneDockHomeContext(userID: "task-read-user", accountType: "store_user", scenicID: scenicID,
|
||||||
|
scenicName: "测试景区", storeID: 38, photographerName: "测试员工", token: token)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 进入页面时的订单摘要与 shooting 套餐名故意不同,验证服务端展示优先级。
|
||||||
|
static func order() throws -> DroneDockHomeOrder {
|
||||||
|
try JSONDecoder().decode(DroneDockHomeOrder.self, from: Data(#"{"order_number":"TEST-TASK-PAGE-001","project_id":101,"project_name":"原订单五次套餐","user_phone":"测试游客","shoot_count":5,"shot_count":0,"remaining_count":5}"#.utf8))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 使用已确认的后端字段结构,测试数据不代表真实飞行结果。
|
||||||
|
static func payload() -> [String: Any] {
|
||||||
|
["order_flight_task": ["id": 501, "order_number": "TEST-TASK-PAGE-001", "scenic_id": 128,
|
||||||
|
"status": 10, "status_label": "待执行"],
|
||||||
|
"task": ["id": 501, "status": 10, "status_label": "待执行"],
|
||||||
|
"scenic": ["id": 128, "name": "测试景区"],
|
||||||
|
"scenic_spot": ["id": 201, "name": "测试点位"],
|
||||||
|
"air_line": ["id": 301, "name": "测试航线", "scenic_spot_id": 201],
|
||||||
|
"header": ["order_number": "TEST-TASK-PAGE-001", "title": "测试点位 · 测试航线",
|
||||||
|
"tourist_label": "测试游客", "package_name": "接口返回单次套餐"],
|
||||||
|
"current_plane": ["id": 58, "sn_number": "TEST-PLANE-058", "status_text": "空闲 · 电量 0%"],
|
||||||
|
"plane_status": ["scenic_id": 128, "connected": true, "poll_hint_ms": 5000],
|
||||||
|
"metrics": [["key": "battery", "value": "0%", "raw": 0], ["key": "env_temp", "value": "0°C"],
|
||||||
|
["key": "wind_speed", "value": "0m/s"], ["key": "rainfall", "value": NSNull()],
|
||||||
|
["key": "signal", "value": "—"], ["key": "satellite", "value": "0颗"]],
|
||||||
|
"execute_gate": ["can_execute": false, "code": "wayline_missing", "message": "测试门禁原因"],
|
||||||
|
"ui": ["phase": "blocked", "title": "任务尚未关联航线", "message": "测试阶段说明"]]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 可覆盖顶层字段以测试缺失、未知状态与身份错误。
|
||||||
|
static func response(changes: [String: Any] = [:]) throws -> DroneDockShootingResponse {
|
||||||
|
try decode(payload().merging(changes) { _, new in new })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 从任意匿名 data 对象构造真实 DTO。
|
||||||
|
static func decode(_ payload: [String: Any]) throws -> DroneDockShootingResponse {
|
||||||
|
try JSONDecoder().decode(DroneDockShootingResponse.self, from: JSONSerialization.data(withJSONObject: payload))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 可配置返回值的只读 shooting 替身,只记录任务 ID 与实时电量参数。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockShootingTaskTestService: DroneDockShootingServing {
|
||||||
|
/// 当前读取结果,测试可模拟失败后恢复。
|
||||||
|
var result: Result<DroneDockShootingResponse, Error>
|
||||||
|
/// 所有读取记录,不提供任何创建或飞控能力。
|
||||||
|
private(set) var requests: [(taskID: Int, liveBattery: Bool)] = []
|
||||||
|
|
||||||
|
/// 注入匿名快照或读取错误。
|
||||||
|
init(result: Result<DroneDockShootingResponse, Error>) { self.result = result }
|
||||||
|
|
||||||
|
/// 返回配置结果,不自动重读或发送其他请求。
|
||||||
|
func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse {
|
||||||
|
requests.append((taskID, liveBattery))
|
||||||
|
return try result.get()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 验证真实任务页只读、同任务重入、身份检查及过期快照清除,不接入飞控。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockShootingTaskViewModelTests: XCTestCase {
|
||||||
|
/// 进入、刷新和返回始终读取传入的同一任务,构造本身不发请求。
|
||||||
|
func testRefreshAndReturnReadSameTaskWithLiveBattery() async throws {
|
||||||
|
let fixture = try ShootingTaskFixture()
|
||||||
|
XCTAssertTrue(fixture.service.requests.isEmpty)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
fixture.model.invalidate()
|
||||||
|
XCTAssertNil(fixture.model.response)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertEqual(fixture.service.requests.map(\.taskID), [501, 501, 501])
|
||||||
|
XCTAssertTrue(fixture.service.requests.allSatisfy(\.liveBattery))
|
||||||
|
XCTAssertNotNil(fixture.model.dataJSON)
|
||||||
|
XCTAssertFalse(fixture.model.isLoading)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 展示当前 shooting 文案,GET 成功不替换阻止状态,也不以原订单套餐掩盖后端差异。
|
||||||
|
func testDisplayUsesServerTaskStatePackageAndZeroTelemetry() async throws {
|
||||||
|
let fixture = try ShootingTaskFixture()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertEqual(fixture.model.title, "测试点位 · 测试航线")
|
||||||
|
XCTAssertEqual(fixture.model.subtitle, "测试游客 · 接口返回单次套餐")
|
||||||
|
XCTAssertEqual(fixture.model.statusTitle, "任务尚未关联航线")
|
||||||
|
XCTAssertEqual(fixture.model.statusMessage, "测试阶段说明")
|
||||||
|
XCTAssertEqual(fixture.model.deviceStatusText, "空闲 · 电量 0%")
|
||||||
|
XCTAssertEqual(fixture.model.response?.executeGate?.canExecute, false)
|
||||||
|
XCTAssertEqual(fixture.model.telemetry.batteryText, "0%")
|
||||||
|
XCTAssertEqual(fixture.model.telemetry.temperatureText, "0°C")
|
||||||
|
XCTAssertEqual(fixture.model.telemetry.windText, "0m/s")
|
||||||
|
XCTAssertEqual(fixture.model.telemetry.satelliteText, "0颗")
|
||||||
|
XCTAssertEqual(fixture.model.telemetry.rainText, "—")
|
||||||
|
XCTAssertEqual(fixture.model.telemetry.signalText, "—")
|
||||||
|
XCTAssertFalse(fixture.model.isTelemetryStale)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 未返回任务阶段和读数时显示未知,不从成功响应或 execute_gate=true 编造到达。
|
||||||
|
func testMissingFieldsStayUnknownWithoutInferringFlightPhase() async throws {
|
||||||
|
let fixture = try ShootingTaskFixture(response: DroneDockShootingTaskTestData.decode(["execute_gate": ["can_execute": true]]))
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertEqual(fixture.model.title, "拍摄任务")
|
||||||
|
XCTAssertEqual(fixture.model.statusTitle, "状态待确认")
|
||||||
|
XCTAssertEqual(fixture.model.statusMessage, "—")
|
||||||
|
XCTAssertEqual(fixture.model.deviceStatusText, "—")
|
||||||
|
XCTAssertEqual(fixture.model.telemetry, DroneDockShootingTelemetry(batteryText: "—", temperatureText: "—",
|
||||||
|
windText: "—", rainText: "—", signalText: "—", satelliteText: "—"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 最近读取失败后不能继续展示上次的允许执行标记或设备读数。
|
||||||
|
func testFailureClearsPreviousResponseAndCanRecoverSameTask() async throws {
|
||||||
|
let fixture = try ShootingTaskFixture(response: DroneDockShootingTaskTestData.response(changes: ["execute_gate": ["can_execute": true]]))
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertEqual(fixture.model.response?.executeGate?.canExecute, true)
|
||||||
|
fixture.service.result = .failure(APIError.networkFailed("测试断网"))
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertNil(fixture.model.response)
|
||||||
|
XCTAssertNil(fixture.model.dataJSON)
|
||||||
|
XCTAssertTrue(fixture.model.isTelemetryStale)
|
||||||
|
XCTAssertEqual(fixture.model.telemetry.batteryText, "—")
|
||||||
|
XCTAssertEqual(fixture.model.errorMessage, "网络请求失败:测试断网")
|
||||||
|
fixture.service.result = .success(try DroneDockShootingTaskTestData.response())
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertEqual(fixture.service.requests.map(\.taskID), [501, 501, 501])
|
||||||
|
XCTAssertNil(fixture.model.errorMessage)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 所有实际返回的任务、订单及景区身份都必须一致,不能只校验根层订单号。
|
||||||
|
func testAnyMismatchedReturnedIdentityIsRejected() async throws {
|
||||||
|
let cases: [[String: Any]] = [
|
||||||
|
["order_number": "OTHER"], ["order_flight_task": ["id": 502]], ["task": ["id": 502]],
|
||||||
|
["order_flight_task": ["order_number": "OTHER"]], ["task": ["order_number": "OTHER"]],
|
||||||
|
["header": ["order_number": "OTHER"]], ["scenic": ["id": 129]],
|
||||||
|
["order_flight_task": ["scenic_id": 129]], ["task": ["scenic_id": 129]],
|
||||||
|
["plane_status": ["scenic_id": 129]]
|
||||||
|
]
|
||||||
|
for changes in cases {
|
||||||
|
let fixture = try ShootingTaskFixture(response: DroneDockShootingTaskTestData.response(changes: changes))
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertNil(fixture.model.response)
|
||||||
|
XCTAssertTrue(fixture.model.errorMessage?.contains("不一致") == true)
|
||||||
|
XCTAssertEqual(fixture.service.requests.count, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 缺失任务或登录范围时不发送请求;当前账号切换也在发送前终止。
|
||||||
|
func testInvalidInputOrChangedContextDoesNotRequest() async throws {
|
||||||
|
for taskID in [0, -1] {
|
||||||
|
let fixture = try ShootingTaskFixture(taskID: taskID)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertTrue(fixture.service.requests.isEmpty)
|
||||||
|
XCTAssertNotNil(fixture.model.errorMessage)
|
||||||
|
}
|
||||||
|
let invalid = try ShootingTaskFixture(context: DroneDockShootingTaskTestData.context(token: ""))
|
||||||
|
await invalid.model.refresh()
|
||||||
|
XCTAssertTrue(invalid.service.requests.isEmpty)
|
||||||
|
let changed = try ShootingTaskFixture()
|
||||||
|
changed.scope.context = DroneDockShootingTaskTestData.context(token: "new-token")
|
||||||
|
await changed.model.refresh()
|
||||||
|
XCTAssertTrue(changed.service.requests.isEmpty)
|
||||||
|
XCTAssertTrue(changed.model.errorMessage?.contains("账号或景区已变化") == true)
|
||||||
|
changed.scope.context = DroneDockShootingTaskTestData.context()
|
||||||
|
await changed.model.refresh()
|
||||||
|
XCTAssertTrue(changed.service.requests.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 读取未结束时额外刷新不产生第二个请求。
|
||||||
|
func testOverlappingRefreshIsIgnored() async throws {
|
||||||
|
let service = DeferredShootingTaskService()
|
||||||
|
let fixture = try ShootingTaskFixture(service: service)
|
||||||
|
defer { service.cancelAll() }
|
||||||
|
let first = Task { await fixture.model.refresh() }
|
||||||
|
await waitForRequests(1, service: service)
|
||||||
|
XCTAssertTrue(fixture.model.isLoading)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
service.resolve(0, with: .success(try DroneDockShootingTaskTestData.response()))
|
||||||
|
await first.value
|
||||||
|
XCTAssertFalse(fixture.model.isLoading)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 离开后迟到回包不能覆盖重新进入后的新快照,读取仍使用同一任务。
|
||||||
|
func testInvalidatedOldResponseCannotOverwriteNewRead() async throws {
|
||||||
|
let service = DeferredShootingTaskService()
|
||||||
|
let fixture = try ShootingTaskFixture(service: service)
|
||||||
|
defer { service.cancelAll() }
|
||||||
|
let first = Task { await fixture.model.refresh() }
|
||||||
|
await waitForRequests(1, service: service)
|
||||||
|
fixture.model.invalidate()
|
||||||
|
let second = Task { await fixture.model.refresh() }
|
||||||
|
await waitForRequests(2, service: service)
|
||||||
|
service.resolve(1, with: .success(try DroneDockShootingTaskTestData.response(changes: ["ui": ["title": "最新状态"]])))
|
||||||
|
await second.value
|
||||||
|
service.resolve(0, with: .success(try DroneDockShootingTaskTestData.response(changes: ["ui": ["title": "过期状态"]])))
|
||||||
|
await first.value
|
||||||
|
XCTAssertEqual(fixture.model.statusTitle, "最新状态")
|
||||||
|
XCTAssertEqual(service.requests, [501, 501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 取消后的成功回包也不恢复设备与执行门禁快照。
|
||||||
|
func testCancelledResponseIsDiscarded() async throws {
|
||||||
|
let service = DeferredShootingTaskService()
|
||||||
|
let fixture = try ShootingTaskFixture(service: service)
|
||||||
|
defer { service.cancelAll() }
|
||||||
|
let pending = Task { await fixture.model.refresh() }
|
||||||
|
await waitForRequests(1, service: service)
|
||||||
|
pending.cancel()
|
||||||
|
service.resolve(0, with: .success(try DroneDockShootingTaskTestData.response()))
|
||||||
|
await pending.value
|
||||||
|
XCTAssertNil(fixture.model.response)
|
||||||
|
XCTAssertFalse(fixture.model.isLoading)
|
||||||
|
XCTAssertTrue(fixture.model.isTelemetryStale)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 在请求途中换景区,迟到响应被丢弃,后续不再用旧任务发请求。
|
||||||
|
func testContextChangeRejectsLateResponseAndFurtherReads() async throws {
|
||||||
|
let service = DeferredShootingTaskService()
|
||||||
|
let fixture = try ShootingTaskFixture(service: service)
|
||||||
|
defer { service.cancelAll() }
|
||||||
|
let pending = Task { await fixture.model.refresh() }
|
||||||
|
await waitForRequests(1, service: service)
|
||||||
|
fixture.scope.context = DroneDockShootingTaskTestData.context(scenicID: 129)
|
||||||
|
service.resolve(0, with: .success(try DroneDockShootingTaskTestData.response()))
|
||||||
|
await pending.value
|
||||||
|
XCTAssertNil(fixture.model.response)
|
||||||
|
XCTAssertTrue(fixture.model.errorMessage?.contains("账号或景区已变化") == true)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
}
|
||||||
|
|
||||||
|
private func waitForRequests(_ count: Int, service: DeferredShootingTaskService) async {
|
||||||
|
for _ in 0..<100 where service.requests.count < count { await Task.yield() }
|
||||||
|
XCTAssertEqual(service.requests.count, count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 每项测试隔离订单、会话和读取服务,避免共享可变全局状态。
|
||||||
|
@MainActor
|
||||||
|
private final class ShootingTaskFixture {
|
||||||
|
let service: DroneDockShootingTaskTestService
|
||||||
|
let scope: ShootingTaskScope
|
||||||
|
let model: DroneDockShootingTaskViewModel
|
||||||
|
|
||||||
|
init(taskID: Int = 501, context: DroneDockHomeContext = DroneDockShootingTaskTestData.context(),
|
||||||
|
response: DroneDockShootingResponse? = nil, service customService: (any DroneDockShootingServing)? = nil) throws {
|
||||||
|
service = DroneDockShootingTaskTestService(result: .success(try response ?? DroneDockShootingTaskTestData.response()))
|
||||||
|
scope = ShootingTaskScope(context: context)
|
||||||
|
let currentScope = scope
|
||||||
|
model = DroneDockShootingTaskViewModel(context: context, taskID: taskID, order: try DroneDockShootingTaskTestData.order(),
|
||||||
|
service: customService ?? service, currentContext: { currentScope.context })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前会话可独立变更,验证页面冻结身份不随外部切换漂移。
|
||||||
|
@MainActor
|
||||||
|
private final class ShootingTaskScope {
|
||||||
|
var context: DroneDockHomeContext
|
||||||
|
init(context: DroneDockHomeContext) { self.context = context }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 可按任意顺序完成的只读请求替身,用于验证取消与旧响应隔离。
|
||||||
|
@MainActor
|
||||||
|
private final class DeferredShootingTaskService: DroneDockShootingServing {
|
||||||
|
private(set) var requests: [Int] = []
|
||||||
|
private var pending: [Int: CheckedContinuation<DroneDockShootingResponse, Error>] = [:]
|
||||||
|
|
||||||
|
func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse {
|
||||||
|
let index = requests.count
|
||||||
|
requests.append(taskID)
|
||||||
|
return try await withCheckedThrowingContinuation { pending[index] = $0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolve(_ index: Int, with result: Result<DroneDockShootingResponse, Error>) {
|
||||||
|
pending.removeValue(forKey: index)?.resume(with: result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func cancelAll() {
|
||||||
|
let values = Array(pending.values)
|
||||||
|
pending.removeAll()
|
||||||
|
values.forEach { $0.resume(throwing: CancellationError()) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,432 @@
|
|||||||
|
import UIKit
|
||||||
|
import XCTest
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 验证真实任务页按进入、恢复前台和手动操作单次读取,不定时轮询或自动重试。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockShootingTaskViewTests: XCTestCase {
|
||||||
|
private weak var previousKeyWindow: UIWindow?
|
||||||
|
|
||||||
|
/// 构造和加载视图不请求,完整出现后才使用传入的同一任务 ID 读取。
|
||||||
|
func testFirstRequestWaitsUntilPageAppears() async throws {
|
||||||
|
let service = try TaskViewReadService()
|
||||||
|
let controller = try makeController(service: service)
|
||||||
|
XCTAssertTrue(service.requests.isEmpty)
|
||||||
|
controller.loadViewIfNeeded()
|
||||||
|
XCTAssertTrue(service.requests.isEmpty)
|
||||||
|
XCTAssertNil(controller.viewModel.response)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
try await settle(window) { controller.viewModel.response != nil }
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
XCTAssertEqual(controller.viewModel.taskID, 501)
|
||||||
|
XCTAssertEqual(controller.title, "拍摄任务")
|
||||||
|
XCTAssertEqual(controller.navigationItem.rightBarButtonItem?.accessibilityIdentifier, "drone.task.remote.navigationRefresh")
|
||||||
|
XCTAssertFalse(controller.navigationItem.hidesBackButton)
|
||||||
|
// 超过历史默认五秒间隔,停留本页仍只能保留首次 GET。
|
||||||
|
try await Task.sleep(nanoseconds: 5_300_000_000)
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 展示后端标题、套餐和六项带单位读数,不沿用演示值或假控制。
|
||||||
|
func testServerSummaryMetricsAndStatusUseRealTaskLayout() async throws {
|
||||||
|
let service = try TaskViewReadService()
|
||||||
|
let controller = try makeController(service: service)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
try await settle(window) { controller.viewModel.response != nil }
|
||||||
|
let texts = visibleTexts(in: controller.view)
|
||||||
|
XCTAssertTrue(texts.contains("测试点位 · 测试航线"))
|
||||||
|
XCTAssertTrue(texts.contains { $0.contains("单次航拍 · 含1次拍摄") })
|
||||||
|
XCTAssertFalse(texts.contains { $0.contains("入口五次套餐") })
|
||||||
|
XCTAssertTrue(texts.contains("航线任务未关联"))
|
||||||
|
XCTAssertTrue(texts.contains("测试任务需要等待服务端准备完成"))
|
||||||
|
XCTAssertTrue(texts.contains("空闲 · 电量93%"))
|
||||||
|
XCTAssertTrue(texts.contains("图传暂未接入"))
|
||||||
|
let values = ["battery": "93%", "temperature": "—", "wind": "0m/s",
|
||||||
|
"rain": "—", "signal": "—", "satellite": "32颗"]
|
||||||
|
for (key, value) in values {
|
||||||
|
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.\(key)")?.accessibilityValue, value)
|
||||||
|
}
|
||||||
|
XCTAssertNil(find(in: controller.view, id: "drone.task.primary"))
|
||||||
|
XCTAssertNil(find(in: controller.view, id: "drone.task.pause"))
|
||||||
|
XCTAssertNil(find(in: controller.view, id: "drone.task.return"))
|
||||||
|
for key in ["pause", "return"] {
|
||||||
|
let control = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.\(key)") as? UIControl)
|
||||||
|
XCTAssertFalse(control.isEnabled)
|
||||||
|
XCTAssertFalse(hidden(control))
|
||||||
|
}
|
||||||
|
XCTAssertFalse(texts.contains { $0.contains("本地界面演示") })
|
||||||
|
let feed = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.feedPlaceholder"))
|
||||||
|
XCTAssertEqual(feed.bounds.height, feed.bounds.width * 9 / 16, accuracy: 0.5)
|
||||||
|
assertUnambiguousLayout(in: controller.view)
|
||||||
|
capture(window, name: "真实拍摄任务-服务端状态与六项读数")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 业务错误留在本页,重新加载只 GET 同一任务,不产生任何写请求。
|
||||||
|
func testFailureAndRetryOnlyReadSameTask() async throws {
|
||||||
|
let session = MockURLSession(responses: [
|
||||||
|
try TestJSON.errorEnvelope(code: 100099, msg: "测试任务暂不可读取"),
|
||||||
|
try TaskViewData.envelope()
|
||||||
|
])
|
||||||
|
let service = DroneDockShootingAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
let controller = try makeController(service: service)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
try await settle(window) { controller.viewModel.errorMessage != nil }
|
||||||
|
XCTAssertTrue(visibleTexts(in: controller.view).contains("任务状态读取失败"))
|
||||||
|
XCTAssertTrue(visibleTexts(in: controller.view).contains("测试任务暂不可读取"))
|
||||||
|
XCTAssertEqual(try button(in: controller.view).title(for: .normal), "重新读取")
|
||||||
|
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "—")
|
||||||
|
try await Task.sleep(nanoseconds: 140_000_000)
|
||||||
|
XCTAssertEqual(session.requests.count, 1, "失败后等待明确点击,不自动重试")
|
||||||
|
try button(in: controller.view).sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { controller.viewModel.response != nil && session.requests.count == 2 }
|
||||||
|
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
|
||||||
|
for request in session.requests {
|
||||||
|
XCTAssertEqual(request.httpMethod, "GET")
|
||||||
|
XCTAssertEqual(request.url?.path, "/api/app/airport/shooting")
|
||||||
|
XCTAssertNil(request.httpBody)
|
||||||
|
let query = URLComponents(url: try XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems
|
||||||
|
XCTAssertEqual(query, [URLQueryItem(name: "id", value: "501"), URLQueryItem(name: "live_battery", value: "1")])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 恢复前台及重新进入各读取一次,重复前台通知和不可见期间均不追加 GET。
|
||||||
|
func testForegroundAndReentryEachReadSameTaskOnce() async throws {
|
||||||
|
let service = try TaskViewReadService()
|
||||||
|
let controller = try makeController(service: service)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
try await settle(window) { service.requests.count == 1 && controller.viewModel.response != nil }
|
||||||
|
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
|
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
|
try await Task.sleep(nanoseconds: 140_000_000)
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
|
||||||
|
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
|
||||||
|
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
|
||||||
|
try await Task.sleep(nanoseconds: 140_000_000)
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
XCTAssertNil(controller.viewModel.response)
|
||||||
|
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
|
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
|
try await settle(window) { service.requests.count == 2 && controller.viewModel.response != nil }
|
||||||
|
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
|
try await Task.sleep(nanoseconds: 140_000_000)
|
||||||
|
XCTAssertEqual(service.requests, [501, 501])
|
||||||
|
|
||||||
|
let navigation = try XCTUnwrap(controller.navigationController)
|
||||||
|
navigation.pushViewController(UIViewController(), animated: false)
|
||||||
|
try await settle(window) { controller.viewModel.response == nil && navigation.topViewController !== controller }
|
||||||
|
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
|
||||||
|
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
|
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
|
try await Task.sleep(nanoseconds: 140_000_000)
|
||||||
|
XCTAssertEqual(service.requests, [501, 501])
|
||||||
|
navigation.popViewController(animated: false)
|
||||||
|
try await settle(window) { service.requests.count == 3 && controller.viewModel.response != nil }
|
||||||
|
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
|
try await Task.sleep(nanoseconds: 140_000_000)
|
||||||
|
XCTAssertEqual(service.requests, [501, 501, 501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 中间按钮与导航栏刷新各追加一次 GET,固定页面不再包含滚动容器。
|
||||||
|
func testButtonAndNavigationRefreshEachReadOnce() async throws {
|
||||||
|
let service = try TaskViewReadService()
|
||||||
|
let controller = try makeController(service: service)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
try await settle(window) { service.requests.count == 1 && controller.viewModel.response != nil }
|
||||||
|
try button(in: controller.view).sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { service.requests.count == 2 && controller.viewModel.response != nil }
|
||||||
|
|
||||||
|
XCTAssertFalse(views(in: controller.view).contains { $0 is UIScrollView })
|
||||||
|
try tapNavigationRefresh(controller)
|
||||||
|
try await settle(window) { service.requests.count == 3 && controller.viewModel.response != nil }
|
||||||
|
try await Task.sleep(nanoseconds: 140_000_000)
|
||||||
|
XCTAssertEqual(service.requests, [501, 501, 501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 新请求期间撤下旧状态与读数,连续刷新不会形成并发请求。
|
||||||
|
func testPendingRefreshShowsUnknownReadingsAndRejectsDoubleTap() async throws {
|
||||||
|
let service = try TaskViewReadService()
|
||||||
|
let controller = try makeController(service: service)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { service.cancelAll(); close(window) }
|
||||||
|
try await settle(window) { controller.viewModel.response != nil }
|
||||||
|
service.suspendNext = true
|
||||||
|
let refreshButton = try button(in: controller.view)
|
||||||
|
refreshButton.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { controller.viewModel.isLoading && service.requests.count == 2 }
|
||||||
|
XCTAssertTrue(visibleTexts(in: controller.view).contains("正在获取任务状态"))
|
||||||
|
XCTAssertFalse(visibleTexts(in: controller.view).contains("空闲 · 电量93%"))
|
||||||
|
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "—")
|
||||||
|
XCTAssertFalse(refreshButton.isEnabled)
|
||||||
|
XCTAssertEqual(controller.navigationItem.rightBarButtonItem?.isEnabled, false)
|
||||||
|
refreshButton.sendActions(for: .touchUpInside)
|
||||||
|
try tapNavigationRefresh(controller)
|
||||||
|
XCTAssertEqual(service.requests.count, 2)
|
||||||
|
service.finish()
|
||||||
|
try await settle(window) { controller.viewModel.response != nil && !controller.viewModel.isLoading }
|
||||||
|
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "93%")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 后台取消后迟到回执不重新展示当前设备或遥测。
|
||||||
|
func testLateResponseAfterBackgroundDoesNotRepopulatePage() async throws {
|
||||||
|
let service = try TaskViewReadService()
|
||||||
|
service.suspendNext = true
|
||||||
|
let controller = try makeController(service: service)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { service.cancelAll(); close(window) }
|
||||||
|
try await settle(window) { service.requests.count == 1 && controller.viewModel.isLoading }
|
||||||
|
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
|
||||||
|
service.finish()
|
||||||
|
try await Task.sleep(nanoseconds: 120_000_000)
|
||||||
|
window.layoutIfNeeded()
|
||||||
|
XCTAssertNil(controller.viewModel.response)
|
||||||
|
XCTAssertFalse(visibleTexts(in: controller.view).contains("空闲 · 电量93%"))
|
||||||
|
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.satellite")?.accessibilityValue, "—")
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 身份变化后重新读取撤下旧响应,不显示原账号的执行门禁或设备读数。
|
||||||
|
func testContextChangeRemovesPreviousTaskState() async throws {
|
||||||
|
let service = try TaskViewReadService()
|
||||||
|
let scope = TaskViewScope()
|
||||||
|
let controller = try makeController(service: service, scope: scope)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
try await settle(window) { controller.viewModel.response != nil }
|
||||||
|
scope.scenicID = 129
|
||||||
|
try button(in: controller.view).sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { controller.viewModel.errorMessage != nil && controller.viewModel.response == nil }
|
||||||
|
XCTAssertTrue(visibleTexts(in: controller.view).contains("账号或景区已变化,请返回工作台重新进入"))
|
||||||
|
XCTAssertFalse(visibleTexts(in: controller.view).contains("空闲 · 电量93%"))
|
||||||
|
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "—")
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 缺失所有动态字段时六项均为未知,不显示已到达、已拍摄或假设备连接。
|
||||||
|
func testMissingFieldsStayUnknownWithoutDemoValues() async throws {
|
||||||
|
let service = try TaskViewReadService(response: JSONDecoder().decode(DroneDockShootingResponse.self, from: Data("{}".utf8)))
|
||||||
|
let controller = try makeController(service: service)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
try await settle(window) { controller.viewModel.response != nil }
|
||||||
|
for key in ["battery", "temperature", "wind", "rain", "signal", "satellite"] {
|
||||||
|
XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.\(key)")?.accessibilityValue, "—")
|
||||||
|
}
|
||||||
|
XCTAssertTrue(visibleTexts(in: controller.view).contains("状态待确认"))
|
||||||
|
XCTAssertNil(find(in: controller.view, id: "drone.task.primary"))
|
||||||
|
assertUnambiguousLayout(in: controller.view)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 从旧状态到加载再到长文案异常,固定顶部与底部始终保留相同位置。
|
||||||
|
func testRefreshingAndLongStatusDoNotMoveFixedRegions() async throws {
|
||||||
|
let service = try TaskViewReadService()
|
||||||
|
let controller = try makeController(service: service)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { service.cancelAll(); close(window) }
|
||||||
|
try await settle(window) { controller.viewModel.response != nil }
|
||||||
|
let ids = ["top", "summary", "feedPlaceholder", "telemetry", "stateContainer", "safety"]
|
||||||
|
let regions = try ids.map { try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.\($0)")) }
|
||||||
|
let frames = regions.map { $0.convert($0.bounds, to: controller.view) }
|
||||||
|
var payload = TaskViewData.payload()
|
||||||
|
payload["ui"] = ["phase": "failed", "title": "任务执行失败", "message": String(repeating: "测试长状态说明,请查看完整详情。", count: 20)]
|
||||||
|
service.response = try JSONDecoder().decode(DroneDockShootingResponse.self, from: JSONSerialization.data(withJSONObject: payload))
|
||||||
|
service.suspendNext = true
|
||||||
|
try tapNavigationRefresh(controller)
|
||||||
|
try await settle(window) { controller.viewModel.isLoading }
|
||||||
|
XCTAssertEqual(regions.map { $0.convert($0.bounds, to: controller.view) }, frames)
|
||||||
|
service.finish()
|
||||||
|
try await settle(window) { controller.viewModel.presentation.phase == .failed }
|
||||||
|
XCTAssertEqual(regions.map { $0.convert($0.bounds, to: controller.view) }, frames)
|
||||||
|
XCTAssertFalse(views(in: controller.view).contains { $0 is UIScrollView })
|
||||||
|
XCTAssertEqual(service.requests, [501, 501])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 详情展示完整文案,展开本身不会发起任何读取或控制请求。
|
||||||
|
func testDetailsKeepFullServerMessageWithoutRequestingAgain() async throws {
|
||||||
|
let message = String(repeating: "测试任务等待后端处理,完整原因应在详情保留。", count: 20)
|
||||||
|
var payload = TaskViewData.payload()
|
||||||
|
payload["ui"] = ["phase": "blocked", "title": "任务暂不可执行", "message": message]
|
||||||
|
let response = try JSONDecoder().decode(DroneDockShootingResponse.self, from: JSONSerialization.data(withJSONObject: payload))
|
||||||
|
let service = try TaskViewReadService(response: response)
|
||||||
|
let controller = try makeController(service: service)
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
try await settle(window) { controller.viewModel.response != nil }
|
||||||
|
let details = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.details") as? UIButton)
|
||||||
|
details.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { controller.presentedViewController is UIAlertController }
|
||||||
|
let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController)
|
||||||
|
XCTAssertTrue(alert.message?.contains(message) == true)
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
controller.dismiss(animated: false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 明确完成后素材入口沿用当前订单和景区,只跳转一次,不再次创建或召唤。
|
||||||
|
func testCompletedActionOpensMaterialsForCurrentOrder() async throws {
|
||||||
|
var payload = TaskViewData.payload()
|
||||||
|
payload["order_flight_task"] = ["id": 501, "status": 30, "order_number": "TEST-TASK-501", "scenic_id": 128]
|
||||||
|
payload["ui"] = ["phase": "completed", "title": "拍摄完成", "message": "测试任务已完成"]
|
||||||
|
let response = try JSONDecoder().decode(DroneDockShootingResponse.self, from: JSONSerialization.data(withJSONObject: payload))
|
||||||
|
let service = try TaskViewReadService(response: response)
|
||||||
|
let destination = UIViewController()
|
||||||
|
var factoryCalls = 0
|
||||||
|
let controller = try makeController(service: service, materialsFactory: { order, context in
|
||||||
|
factoryCalls += 1
|
||||||
|
XCTAssertEqual(order.orderNumber, "TEST-TASK-501")
|
||||||
|
XCTAssertEqual(context.scenicID, 128)
|
||||||
|
return destination
|
||||||
|
})
|
||||||
|
let window = makeWindow(root: controller)
|
||||||
|
defer { close(window) }
|
||||||
|
try await settle(window) { controller.viewModel.presentation.phase == .completed }
|
||||||
|
let primary = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary") as? UIButton)
|
||||||
|
XCTAssertTrue(primary.isEnabled)
|
||||||
|
XCTAssertEqual(primary.title(for: .normal), "查看素材")
|
||||||
|
primary.sendActions(for: .touchUpInside)
|
||||||
|
primary.sendActions(for: .touchUpInside)
|
||||||
|
try await settle(window) { controller.navigationController?.topViewController === destination }
|
||||||
|
XCTAssertEqual(factoryCalls, 1)
|
||||||
|
XCTAssertEqual(service.requests, [501])
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeController(service: any DroneDockShootingServing, scope: TaskViewScope? = nil,
|
||||||
|
materialsFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) throws -> DroneDockShootingTaskViewController {
|
||||||
|
let scope = scope ?? TaskViewScope()
|
||||||
|
let order = try JSONDecoder().decode(DroneDockHomeOrder.self, from: Data(#"{"order_number":"TEST-TASK-501","project_id":101,"project_name":"入口五次套餐","user_phone":"130****0501"}"#.utf8))
|
||||||
|
let model = DroneDockShootingTaskViewModel(context: scope.value, taskID: 501, order: order,
|
||||||
|
service: service, currentContext: { scope.value })
|
||||||
|
return DroneDockShootingTaskViewController(viewModel: model, materialsControllerFactory: materialsFactory)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeWindow(root: UIViewController) -> UIWindow {
|
||||||
|
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
|
||||||
|
let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
|
||||||
|
previousKeyWindow = scene?.windows.first { $0.isKeyWindow }
|
||||||
|
let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds)
|
||||||
|
window.frame = scene?.coordinateSpace.bounds ?? UIScreen.main.bounds
|
||||||
|
window.overrideUserInterfaceStyle = .light
|
||||||
|
window.rootViewController = UINavigationController(rootViewController: root)
|
||||||
|
window.makeKeyAndVisible()
|
||||||
|
window.layoutIfNeeded()
|
||||||
|
return window
|
||||||
|
}
|
||||||
|
|
||||||
|
private func close(_ window: UIWindow) {
|
||||||
|
window.isHidden = true
|
||||||
|
window.rootViewController = nil
|
||||||
|
previousKeyWindow?.makeKeyAndVisible()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func settle(_ window: UIWindow, until condition: () -> Bool) async throws {
|
||||||
|
for _ in 0..<160 {
|
||||||
|
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: "DroneDockShootingTaskViewTests", code: 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func views(in root: UIView) -> [UIView] { [root] + root.subviews.flatMap { views(in: $0) } }
|
||||||
|
private func hidden(_ view: UIView) -> Bool { view.isHidden || view.alpha < 0.01 || (view.superview.map(hidden) ?? false) }
|
||||||
|
private func find(in root: UIView, id: String) -> UIView? { views(in: root).first { $0.accessibilityIdentifier == id } }
|
||||||
|
private func visibleTexts(in root: UIView) -> [String] {
|
||||||
|
views(in: root).compactMap { view in
|
||||||
|
guard let label = view as? UILabel, !hidden(label), !label.bounds.isEmpty else { return nil }
|
||||||
|
return label.text
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private func button(in root: UIView) throws -> UIButton {
|
||||||
|
try XCTUnwrap(find(in: root, id: "drone.task.remote.refresh") as? UIButton)
|
||||||
|
}
|
||||||
|
private func tapNavigationRefresh(_ controller: UIViewController) throws {
|
||||||
|
let item = try XCTUnwrap(controller.navigationItem.rightBarButtonItem)
|
||||||
|
let action = try XCTUnwrap(item.action)
|
||||||
|
_ = UIApplication.shared.sendAction(action, to: item.target, from: item, for: nil)
|
||||||
|
}
|
||||||
|
private func assertUnambiguousLayout(in root: UIView, file: StaticString = #filePath, line: UInt = #line) {
|
||||||
|
let ambiguous = views(in: root).filter { !hidden($0) && !$0.bounds.isEmpty && $0.hasAmbiguousLayout }
|
||||||
|
XCTAssertTrue(ambiguous.isEmpty, "可见布局存在歧义:\(ambiguous.map { String(describing: type(of: $0)) })", file: file, line: line)
|
||||||
|
}
|
||||||
|
private func capture(_ window: UIWindow, name: String) {
|
||||||
|
let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) }
|
||||||
|
let attachment = XCTAttachment(image: image)
|
||||||
|
attachment.name = name
|
||||||
|
attachment.lifetime = .keepAlways
|
||||||
|
add(attachment)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 独立任务页 JSON 数据,所有设备、订单和摘要均为匿名测试值。
|
||||||
|
private enum TaskViewData {
|
||||||
|
static func payload() -> [String: Any] {
|
||||||
|
["order_number": "TEST-TASK-501", "scenic": ["id": 128, "name": "测试景区"],
|
||||||
|
"order_flight_task": ["id": 501, "order_number": "TEST-TASK-501", "scenic_id": 128],
|
||||||
|
"header": ["title": "测试点位 · 测试航线", "tourist_label": "游客130****0501", "package_name": "单次航拍 · 含1次拍摄"],
|
||||||
|
"current_plane": ["id": 1, "status_text": "空闲 · 电量93%"],
|
||||||
|
"ui": ["phase": "blocked", "title": "航线任务未关联", "message": "测试任务需要等待服务端准备完成"],
|
||||||
|
"execute_gate": ["can_execute": false, "message": "测试门禁原因"],
|
||||||
|
"metrics": [["key": "battery", "value": "93%"], ["key": "env_temp", "value": "—"],
|
||||||
|
["key": "wind_speed", "value": "0m/s"], ["key": "rainfall", "value": "—"],
|
||||||
|
["key": "signal", "value": "—"], ["key": "satellite", "value": "32颗"]],
|
||||||
|
"plane_status": ["scenic_id": 128, "connected": true, "poll_hint_ms": 5000]]
|
||||||
|
}
|
||||||
|
|
||||||
|
static func response() throws -> DroneDockShootingResponse {
|
||||||
|
try JSONDecoder().decode(DroneDockShootingResponse.self, from: JSONSerialization.data(withJSONObject: payload()))
|
||||||
|
}
|
||||||
|
|
||||||
|
static func envelope() throws -> Data {
|
||||||
|
try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": payload()])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 可挂起下一次读取,验证 UI 不并发查询和不接收迟到数据。
|
||||||
|
@MainActor
|
||||||
|
private final class TaskViewReadService: DroneDockShootingServing {
|
||||||
|
var response: DroneDockShootingResponse
|
||||||
|
var suspendNext = false
|
||||||
|
private(set) var requests: [Int] = []
|
||||||
|
private var continuation: CheckedContinuation<DroneDockShootingResponse, Error>?
|
||||||
|
|
||||||
|
init(response: DroneDockShootingResponse? = nil) throws { self.response = try response ?? TaskViewData.response() }
|
||||||
|
|
||||||
|
func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse {
|
||||||
|
XCTAssertTrue(liveBattery)
|
||||||
|
requests.append(taskID)
|
||||||
|
if suspendNext {
|
||||||
|
suspendNext = false
|
||||||
|
return try await withCheckedThrowingContinuation { continuation = $0 }
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
func finish() {
|
||||||
|
continuation?.resume(returning: response)
|
||||||
|
continuation = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func cancelAll() {
|
||||||
|
continuation?.resume(throwing: CancellationError())
|
||||||
|
continuation = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 可切换景区的测试会话,不涉及真实登录状态。
|
||||||
|
@MainActor
|
||||||
|
private final class TaskViewScope {
|
||||||
|
var scenicID = 128
|
||||||
|
var value: DroneDockHomeContext {
|
||||||
|
DroneDockHomeContext(userID: "task-ui-user", accountType: "store_user", scenicID: scenicID,
|
||||||
|
scenicName: "测试景区", storeID: 37, photographerName: "测试人员", token: "task-ui-token")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 验证创建待飞任务的参数、身份与完整 data 回执,不调用任何飞控接口。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockTaskCreationAPITests: XCTestCase {
|
||||||
|
/// 按张工合同只提交四项字段,登录 Token 沿用统一客户端。
|
||||||
|
func testCreateSendsOnlyDocumentedBodyAndPreservesOrderSummary() async throws {
|
||||||
|
let session = MockURLSession(responses: [try envelope(payload())])
|
||||||
|
let client = APIClient(environment: .testing, session: session)
|
||||||
|
client.bindAuthTokenProvider { "create-task-test-token" }
|
||||||
|
let result = try await DroneDockTaskCreationAPI(client: client).createTask(
|
||||||
|
scenicID: 128, orderNumber: "TEST-TASK-001", spotID: 201, airLineID: 301)
|
||||||
|
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
let request = try XCTUnwrap(session.requests.first)
|
||||||
|
XCTAssertEqual(request.httpMethod, "POST")
|
||||||
|
XCTAssertEqual(request.url?.path, "/api/yf-handset-app/photog/multi-plane/tasks/create")
|
||||||
|
XCTAssertNil(request.url?.query)
|
||||||
|
XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "create-task-test-token")
|
||||||
|
let body = try XCTUnwrap(JSONSerialization.jsonObject(with: XCTUnwrap(request.httpBody)) as? [String: Any])
|
||||||
|
XCTAssertEqual(Set(body.keys), ["scenic_id", "order_number", "scenic_spot_id", "air_line_id"])
|
||||||
|
XCTAssertEqual(body["scenic_id"] as? Int, 128)
|
||||||
|
XCTAssertEqual(body["order_number"] as? String, "TEST-TASK-001")
|
||||||
|
XCTAssertEqual(body["scenic_spot_id"] as? Int, 201)
|
||||||
|
XCTAssertEqual(body["air_line_id"] as? Int, 301)
|
||||||
|
XCTAssertEqual(result.taskID, 501)
|
||||||
|
XCTAssertEqual(result.order.shotUsed, 0)
|
||||||
|
XCTAssertEqual(result.order.shotRemain, 3)
|
||||||
|
XCTAssertEqual(result.order.shootStatus, "processing")
|
||||||
|
XCTAssertTrue(result.order.canUploadFilm == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 无效身份和超长订单号在发送前拒绝,不创建空参数任务。
|
||||||
|
func testInvalidParametersNeverReachNetwork() async throws {
|
||||||
|
let session = MockURLSession(responses: [])
|
||||||
|
let api = DroneDockTaskCreationAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
for (scenic, spot, line) in [(0, 201, 301), (-1, 201, 301), (128, 0, 301), (128, 201, -1)] {
|
||||||
|
await assertFailure { _ = try await api.createTask(scenicID: scenic, orderNumber: "TEST", spotID: spot, airLineID: line) }
|
||||||
|
}
|
||||||
|
for number in ["", " ", " TEST", "TEST ", "TEST\nORDER", String(repeating: "a", count: 129)] {
|
||||||
|
await assertFailure { _ = try await api.createTask(scenicID: 128, orderNumber: number, spotID: 201, airLineID: 301) }
|
||||||
|
}
|
||||||
|
XCTAssertTrue(session.requests.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 已发送请求若返回其他订单,应报结果不一致而不是自动再次创建。
|
||||||
|
func testMismatchedOrderIsRejectedWithoutAnotherWrite() async throws {
|
||||||
|
var value = payload()
|
||||||
|
value["order_number"] = "TEST-OTHER-ORDER"
|
||||||
|
let session = MockURLSession(responses: [try envelope(value)])
|
||||||
|
let api = DroneDockTaskCreationAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
do {
|
||||||
|
_ = try await api.createTask(scenicID: 128, orderNumber: "TEST-TASK-001", spotID: 201, airLineID: 301)
|
||||||
|
XCTFail("不能接受其他订单的任务")
|
||||||
|
} catch let APIError.decodeFailed(message) {
|
||||||
|
XCTAssertTrue(message.contains("订单不一致"))
|
||||||
|
}
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 后端业务拒绝保留业务码和原提示,便于页面区分明确失败和结果未知。
|
||||||
|
func testBusinessFailurePreservesCodeAndMessage() async throws {
|
||||||
|
let session = MockURLSession(responses: [try TestJSON.errorEnvelope(code: 160001, msg: "拍摄次数已用完")])
|
||||||
|
let api = DroneDockTaskCreationAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
do {
|
||||||
|
_ = try await api.createTask(scenicID: 128, orderNumber: "TEST-TASK-001", spotID: 201, airLineID: 301)
|
||||||
|
XCTFail("应保留业务失败")
|
||||||
|
} catch let APIError.serverCode(code, message) {
|
||||||
|
XCTAssertEqual(code, 160001)
|
||||||
|
XCTAssertEqual(message, "拍摄次数已用完")
|
||||||
|
}
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 超时不在接口层重试,以免无去重参数的创建请求产生第二条任务。
|
||||||
|
func testTransportFailureIsNotAutomaticallyRetried() async throws {
|
||||||
|
let session = MockURLSession(results: [.failure(URLError(.timedOut))])
|
||||||
|
let api = DroneDockTaskCreationAPI(client: APIClient(environment: .testing, session: session))
|
||||||
|
await assertFailure { _ = try await api.createTask(scenicID: 128, orderNumber: "TEST-TASK-001", spotID: 201, airLineID: 301) }
|
||||||
|
XCTAssertEqual(session.requests.count, 1)
|
||||||
|
XCTAssertEqual(session.requests.first?.url?.path, "/api/yf-handset-app/photog/multi-plane/tasks/create")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 数字字符串任务身份可使用,但展示 JSON 保留原始字符串类型。
|
||||||
|
func testStringTaskIDRemainsAStringInDisplayedData() throws {
|
||||||
|
var value = payload()
|
||||||
|
value["task_id"] = "501"
|
||||||
|
let result = try decode(value)
|
||||||
|
XCTAssertEqual(result.taskID, 501)
|
||||||
|
let displayed = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(result.dataJSON.utf8)) as? [String: Any])
|
||||||
|
XCTAssertEqual(displayed["task_id"] as? String, "501")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 完整 data 的未知字段、嵌套结构、空值、布尔和小数不被 DTO 投影丢弃。
|
||||||
|
func testDisplayedDataPreservesAllReturnedFieldsWithoutInventingEnvelope() throws {
|
||||||
|
var value = payload()
|
||||||
|
value["future"] = ["enabled": true, "optional": NSNull(), "items": ["001", false, 0, 12.5]] as [String: Any]
|
||||||
|
value["file_url"] = "https://example.invalid/样片.mp4"
|
||||||
|
let result = try decode(value)
|
||||||
|
let displayed = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(result.dataJSON.utf8)) as? [String: Any])
|
||||||
|
XCTAssertTrue(NSDictionary(dictionary: displayed).isEqual(to: value))
|
||||||
|
XCTAssertTrue(result.dataJSON.contains("\n"))
|
||||||
|
XCTAssertNil(displayed["code"])
|
||||||
|
XCTAssertNil(displayed["msg"])
|
||||||
|
XCTAssertNil(displayed["time"])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 没有有效任务 ID 不能标记为创建成功,订单身份与已用次数也需合法。
|
||||||
|
func testInvalidTaskIdentityAndMalformedOrderSummaryAreRejected() throws {
|
||||||
|
for id: Any in [0, -1, 1.5, true, "bad", "1.5", NSNull()] {
|
||||||
|
var value = payload(); value["task_id"] = id
|
||||||
|
XCTAssertThrowsError(try decode(value))
|
||||||
|
}
|
||||||
|
var missingID = payload(); missingID.removeValue(forKey: "task_id")
|
||||||
|
XCTAssertThrowsError(try decode(missingID))
|
||||||
|
for changes in [["order_number": " "], ["shot_count": -1], ["can_create_task": "true"]] as [[String: Any]] {
|
||||||
|
XCTAssertThrowsError(try decode(payload().merging(changes) { _, new in new }))
|
||||||
|
}
|
||||||
|
var missingOrder = payload(); missingOrder.removeValue(forKey: "order_number")
|
||||||
|
XCTAssertThrowsError(try decode(missingOrder))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建回执夹具仅使用测试订单,不包含真实游客或设备信息。
|
||||||
|
private func payload() -> [String: Any] {
|
||||||
|
["task_id": 501, "order_number": "TEST-TASK-001", "project_id": 101,
|
||||||
|
"project_name": "测试三次套餐", "shoot_count": 3, "shot_count": 0, "remaining_count": 3,
|
||||||
|
"shoot_status": "processing", "order_status": 20, "can_create_task": true,
|
||||||
|
"can_upload_film": true, "confirmed_at": NSNull()]
|
||||||
|
}
|
||||||
|
|
||||||
|
private func envelope(_ value: [String: Any]) throws -> Data {
|
||||||
|
try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": value])
|
||||||
|
}
|
||||||
|
|
||||||
|
private func decode(_ value: [String: Any]) throws -> DroneDockCreatedTask {
|
||||||
|
try JSONDecoder().decode(DroneDockCreatedTask.self, from: JSONSerialization.data(withJSONObject: value))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func assertFailure(_ action: () async throws -> Void, file: StaticString = #filePath, line: UInt = #line) async {
|
||||||
|
do { try await action(); XCTFail("应拒绝无效创建请求或响应", file: file, line: line) } catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import Foundation
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 创建任务测试共用的匿名回执,保留原始 data 字段供页面核对。
|
||||||
|
enum DroneDockTaskCreationTestData {
|
||||||
|
/// 返回最新订单摘要及稳定测试任务 ID,不附加模拟飞行结果。
|
||||||
|
static func response(taskID: Int = 501, orderNumber: String = "TEST-PREPARATION-001",
|
||||||
|
projectID: Int = 101, remaining: Int = 5) throws -> DroneDockCreatedTask {
|
||||||
|
let data: [String: Any] = ["task_id": taskID, "order_number": orderNumber, "project_id": projectID,
|
||||||
|
"project_name": "测试五次套餐", "shoot_count": 5, "shot_count": 0,
|
||||||
|
"remaining_count": remaining, "shoot_status": "processing", "order_status": 20,
|
||||||
|
"can_create_task": true, "can_upload_film": true, "can_confirm": false,
|
||||||
|
"film_count": 0, "user_phone": "130****0001"]
|
||||||
|
return try JSONDecoder().decode(DroneDockCreatedTask.self, from: JSONSerialization.data(withJSONObject: data))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 可注入明确成功或业务拒绝的任务创建服务,默认不创建任何测试任务。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockTaskCreationTestService: DroneDockTaskCreating {
|
||||||
|
/// 请求参数稳定记录,供验证一键只发送一次 POST。
|
||||||
|
struct Request: Equatable {
|
||||||
|
let scenicID: Int
|
||||||
|
let orderNumber: String
|
||||||
|
let spotID: Int
|
||||||
|
let airLineID: Int
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前返回结果,允许测试模拟明确拒绝后恢复。
|
||||||
|
var result: Result<DroneDockCreatedTask, Error>
|
||||||
|
/// 已收到的创建参数。
|
||||||
|
private(set) var requests: [Request] = []
|
||||||
|
|
||||||
|
/// 默认拒绝用于未关注创建动作的既有准备页测试。
|
||||||
|
init(result: Result<DroneDockCreatedTask, Error>? = nil) {
|
||||||
|
self.result = result ?? .failure(APIError.serverCode(160001, "测试任务创建未配置"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 仅记录任务创建调用,不实现召唤或其他飞行动作。
|
||||||
|
func createTask(scenicID: Int, orderNumber: String, spotID: Int, airLineID: Int) async throws -> DroneDockCreatedTask {
|
||||||
|
requests.append(Request(scenicID: scenicID, orderNumber: orderNumber, spotID: spotID, airLineID: airLineID))
|
||||||
|
return try result.get()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,363 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 验证准备页只创建待飞任务、保留真实回执,并阻止重复提交不确定请求。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockTaskCreationViewModelTests: XCTestCase {
|
||||||
|
/// 单独建任务只受购买条件约束,不因无设备状态或离线而错误拦截。
|
||||||
|
func testValidPurchaseAllowsCreationWithoutPlanePermission() async throws {
|
||||||
|
let fixture = try TaskCreationFixture()
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertTrue(fixture.model.canCreateTask)
|
||||||
|
XCTAssertNil(fixture.model.planeStatus)
|
||||||
|
fixture.planes.result = .success(try DroneDockPlaneStatusTestData.response(connected: false))
|
||||||
|
await fixture.model.refreshPlaneStatus()
|
||||||
|
XCTAssertTrue(fixture.model.canCreateTask)
|
||||||
|
XCTAssertEqual(fixture.model.admissionMessage, "点击后创建任务并召唤无人机")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建前重读购买配置,提交当前点位航线;任务成功不自行扣减拍摄次数。
|
||||||
|
func testCreationUsesSelectedIDsAndKeepsReturnedJSON() async throws {
|
||||||
|
let fixture = try TaskCreationFixture()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
fixture.model.selectSpot(id: 202)
|
||||||
|
fixture.model.selectRoute(id: 402)
|
||||||
|
var states: [Bool] = []
|
||||||
|
await fixture.model.createTask { states.append(fixture.model.isCreatingTask) }
|
||||||
|
XCTAssertEqual(states, [true, false])
|
||||||
|
XCTAssertEqual(fixture.projects.requests.count, 2)
|
||||||
|
XCTAssertEqual(fixture.creation.requests, [.init(scenicID: 128, orderNumber: "TEST-PREPARATION-001", spotID: 202, airLineID: 402)])
|
||||||
|
XCTAssertEqual(fixture.model.createdTask?.taskID, 501)
|
||||||
|
XCTAssertEqual(fixture.model.latestOrderSummary?.shotUsed, 0)
|
||||||
|
XCTAssertEqual(fixture.model.latestOrderSummary?.shotRemain, 5)
|
||||||
|
XCTAssertEqual(fixture.model.primaryButtonTitle, "确认并召唤")
|
||||||
|
XCTAssertTrue(fixture.model.admissionMessage.contains("等待召唤"))
|
||||||
|
let json = try XCTUnwrap(fixture.model.creationDataJSON?.data(using: .utf8))
|
||||||
|
let object = try XCTUnwrap(JSONSerialization.jsonObject(with: json) as? [String: Any])
|
||||||
|
XCTAssertEqual(object["task_id"] as? Int, 501)
|
||||||
|
XCTAssertEqual(object["remaining_count"] as? Int, 5)
|
||||||
|
XCTAssertNil(object["code"], "展示 data 原文,不伪造外层响应")
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 无额度、无权限、点位或航线不可用均在本地阻止提交。
|
||||||
|
func testInvalidPurchaseConditionsNeverCreateTask() async throws {
|
||||||
|
for payload in [
|
||||||
|
try TaskCreationFixtureData.project(remaining: 0),
|
||||||
|
try TaskCreationFixtureData.project(remaining: nil),
|
||||||
|
try TaskCreationFixtureData.project(total: 0),
|
||||||
|
try TaskCreationFixtureData.project(total: nil),
|
||||||
|
try TaskCreationFixtureData.project(canCreate: false),
|
||||||
|
try TaskCreationFixtureData.project(spots: []),
|
||||||
|
try TaskCreationFixtureData.project(spots: [TaskCreationFixtureData.point(201, available: false)]),
|
||||||
|
try TaskCreationFixtureData.project(spots: [TaskCreationFixtureData.point(201, routes: [], available: true)])
|
||||||
|
] {
|
||||||
|
let fixture = try TaskCreationFixture()
|
||||||
|
fixture.projects.result = .success(payload)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertTrue(fixture.creation.requests.isEmpty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 点选后权限发生变化,预检响应能阻止旧按钮状态触发 POST。
|
||||||
|
func testPreflightRejectsChangedPurchasePermission() async throws {
|
||||||
|
let fixture = try TaskCreationFixture()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
fixture.projects.result = .success(try TaskCreationFixtureData.project(remaining: 0, canCreate: false))
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertTrue(fixture.creation.requests.isEmpty)
|
||||||
|
XCTAssertEqual(fixture.model.projectInfo?.order.shotRemain, 0)
|
||||||
|
XCTAssertNotNil(fixture.model.taskCreationErrorMessage)
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 原航线失效时要求重新选择,不将旧点击默默发给另一航线。
|
||||||
|
func testPreflightDoesNotSubstituteAnotherRoute() async throws {
|
||||||
|
let fixture = try TaskCreationFixture()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
fixture.model.selectRoute(id: 302)
|
||||||
|
fixture.projects.result = .success(try TaskCreationFixtureData.project(spots: [TaskCreationFixtureData.point(201, routes: [301])]))
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertTrue(fixture.creation.requests.isEmpty)
|
||||||
|
XCTAssertEqual(fixture.model.selectedRouteID, 301)
|
||||||
|
XCTAssertTrue(fixture.model.taskCreationErrorMessage?.contains("重新选择") == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 提交中重复点击、选择及购买刷新均不产生第二次创建或改变归属。
|
||||||
|
func testPendingCreateLocksSelectionAndDuplicateClicks() async throws {
|
||||||
|
let service = SuspendedTaskCreationService()
|
||||||
|
let fixture = try TaskCreationFixture(creationService: service)
|
||||||
|
let started = expectation(description: "创建已发出")
|
||||||
|
service.started = { started.fulfill() }
|
||||||
|
defer { service.cancelAll() }
|
||||||
|
await fixture.model.refresh()
|
||||||
|
let pending = Task { await fixture.model.createTask() }
|
||||||
|
await fulfillment(of: [started], timeout: 2)
|
||||||
|
XCTAssertTrue(fixture.model.isCreatingTask)
|
||||||
|
XCTAssertTrue(fixture.model.isTaskSelectionLocked)
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
await fixture.model.createTask()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
fixture.model.selectSpot(id: 202)
|
||||||
|
fixture.model.selectRoute(id: 302)
|
||||||
|
XCTAssertEqual(fixture.model.selectedSpotID, 201)
|
||||||
|
XCTAssertEqual(fixture.model.selectedRouteID, 301)
|
||||||
|
XCTAssertEqual(fixture.projects.requests.count, 2)
|
||||||
|
XCTAssertEqual(service.requests.count, 1)
|
||||||
|
try service.finish()
|
||||||
|
await pending.value
|
||||||
|
XCTAssertEqual(fixture.model.createdTask?.taskID, 501)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 明确业务拒绝可由用户再次点击重试,错误文案保留后端语义。
|
||||||
|
func testBusinessRejectionAllowsExplicitRetry() async throws {
|
||||||
|
let fixture = try TaskCreationFixture()
|
||||||
|
fixture.creation.result = .failure(APIError.serverCode(160001, "测试航线临时不可用"))
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertEqual(fixture.model.taskCreationErrorMessage, "测试航线临时不可用")
|
||||||
|
XCTAssertFalse(fixture.model.taskCreationOutcomeUnknown)
|
||||||
|
XCTAssertTrue(fixture.model.canCreateTask)
|
||||||
|
fixture.creation.result = .success(try DroneDockTaskCreationTestData.response())
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 2)
|
||||||
|
XCTAssertEqual(fixture.model.createdTask?.taskID, 501)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 网络、HTTP、解码或空数据无法确定是否已创建,刷新也不能解锁重复 POST。
|
||||||
|
func testAmbiguousPostFailureRemainsLockedAfterRefresh() async throws {
|
||||||
|
let errors: [Error] = [APIError.networkFailed("测试超时"), APIError.httpStatus(500, "测试异常"),
|
||||||
|
APIError.decodeFailed("测试响应无效"), APIError.emptyData]
|
||||||
|
for error in errors {
|
||||||
|
let fixture = try TaskCreationFixture()
|
||||||
|
fixture.creation.result = .failure(error)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertTrue(fixture.model.taskCreationOutcomeUnknown)
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
XCTAssertNil(fixture.model.createdTask)
|
||||||
|
XCTAssertEqual(fixture.model.primaryButtonTitle, "结果待核对")
|
||||||
|
await fixture.model.refresh()
|
||||||
|
fixture.model.selectSpot(id: 202)
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
XCTAssertEqual(fixture.model.selectedSpotID, 201)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 仅购买预检失败时尚未发出写入,可恢复后重新提交。
|
||||||
|
func testPreflightNetworkFailureDoesNotMarkOutcomeUnknown() async throws {
|
||||||
|
let fixture = try TaskCreationFixture()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
fixture.projects.result = .failure(APIError.networkFailed("测试购买读取失败"))
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertTrue(fixture.creation.requests.isEmpty)
|
||||||
|
XCTAssertFalse(fixture.model.taskCreationOutcomeUnknown)
|
||||||
|
XCTAssertTrue(fixture.model.canCreateTask)
|
||||||
|
fixture.projects.result = .success(try TaskCreationFixtureData.project())
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
XCTAssertNotNil(fixture.model.createdTask)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST 发出后取消或离开,迟到回执不覆盖页面,结果按待核对处理。
|
||||||
|
func testCancellationOrInvalidationAfterPostPreservesUnknownLock() async throws {
|
||||||
|
for invalidate in [false, true] {
|
||||||
|
let service = SuspendedTaskCreationService()
|
||||||
|
let fixture = try TaskCreationFixture(creationService: service)
|
||||||
|
let started = expectation(description: "待取消创建")
|
||||||
|
service.started = { started.fulfill() }
|
||||||
|
defer { service.cancelAll() }
|
||||||
|
await fixture.model.refresh()
|
||||||
|
let pending = Task { await fixture.model.createTask() }
|
||||||
|
await fulfillment(of: [started], timeout: 2)
|
||||||
|
if invalidate { fixture.model.invalidate() } else { pending.cancel() }
|
||||||
|
try service.finish()
|
||||||
|
await pending.value
|
||||||
|
XCTAssertTrue(fixture.model.taskCreationOutcomeUnknown)
|
||||||
|
XCTAssertNil(fixture.model.createdTask)
|
||||||
|
XCTAssertFalse(fixture.model.isCreatingTask)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertEqual(service.requests.count, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建响应属于其他订单或项目时锁定未知结果,不能宣告成功或自动补建。
|
||||||
|
func testMismatchedReceiptRequiresReconciliation() async throws {
|
||||||
|
for response in [try DroneDockTaskCreationTestData.response(orderNumber: "TEST-OTHER"),
|
||||||
|
try DroneDockTaskCreationTestData.response(projectID: 202)] {
|
||||||
|
let fixture = try TaskCreationFixture()
|
||||||
|
fixture.creation.result = .success(response)
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertNil(fixture.model.createdTask)
|
||||||
|
XCTAssertTrue(fixture.model.taskCreationOutcomeUnknown)
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建期间切换景区,迟到响应不显示,旧实例不可恢复创建入口。
|
||||||
|
func testContextChangeDuringCreateRejectsReceipt() async throws {
|
||||||
|
let service = SuspendedTaskCreationService()
|
||||||
|
let fixture = try TaskCreationFixture(creationService: service)
|
||||||
|
let started = expectation(description: "创建身份切换")
|
||||||
|
service.started = { started.fulfill() }
|
||||||
|
defer { service.cancelAll() }
|
||||||
|
await fixture.model.refresh()
|
||||||
|
let pending = Task { await fixture.model.createTask() }
|
||||||
|
await fulfillment(of: [started], timeout: 2)
|
||||||
|
fixture.scope.value = TaskCreationFixtureData.context(scenicID: 129)
|
||||||
|
try service.finish()
|
||||||
|
await pending.value
|
||||||
|
XCTAssertNil(fixture.model.createdTask)
|
||||||
|
XCTAssertNil(fixture.model.projectInfo)
|
||||||
|
XCTAssertTrue(fixture.model.taskCreationOutcomeUnknown)
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
fixture.scope.value = TaskCreationFixtureData.context()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 成功或结果未知后,刷新及同实例离开返回不得把已提交选择改到另一点位。
|
||||||
|
func testSubmittedSelectionDoesNotMoveWhenPurchaseRefreshes() async throws {
|
||||||
|
for unknown in [false, true] {
|
||||||
|
let fixture = try TaskCreationFixture()
|
||||||
|
if unknown { fixture.creation.result = .failure(APIError.networkFailed("测试超时")) }
|
||||||
|
await fixture.model.refresh()
|
||||||
|
fixture.model.selectSpot(id: 202)
|
||||||
|
fixture.model.selectRoute(id: 402)
|
||||||
|
await fixture.model.createTask()
|
||||||
|
fixture.model.invalidate()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertEqual(fixture.model.selectedSpotID, 202)
|
||||||
|
XCTAssertEqual(fixture.model.selectedRouteID, 402)
|
||||||
|
fixture.projects.result = .success(try TaskCreationFixtureData.project(spots: [TaskCreationFixtureData.point(201)]))
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertEqual(fixture.model.selectedSpotID, 202)
|
||||||
|
XCTAssertEqual(fixture.model.selectedRouteID, 402)
|
||||||
|
XCTAssertNil(fixture.model.selectedSpot, "已提交点位被移除时不错误展示另一个点位")
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 普通刷新、设备暂停和同实例离开返回,都保留成功回执与防重复创建锁。
|
||||||
|
func testSuccessfulReceiptSurvivesRefreshAndPageInvalidation() async throws {
|
||||||
|
let fixture = try TaskCreationFixture()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
await fixture.model.createTask()
|
||||||
|
fixture.model.invalidatePlaneStatus()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
fixture.model.selectSpot(id: 202)
|
||||||
|
XCTAssertEqual(fixture.model.selectedSpotID, 201)
|
||||||
|
XCTAssertEqual(fixture.model.createdTask?.taskID, 501)
|
||||||
|
fixture.model.invalidate()
|
||||||
|
await fixture.model.refresh()
|
||||||
|
XCTAssertEqual(fixture.model.createdTask?.taskID, 501)
|
||||||
|
XCTAssertFalse(fixture.model.canCreateTask)
|
||||||
|
await fixture.model.createTask()
|
||||||
|
XCTAssertEqual(fixture.creation.requests.count, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 每例独立构造购买、设备、创建服务与会话;无真实账号和网络。
|
||||||
|
@MainActor
|
||||||
|
private final class TaskCreationFixture {
|
||||||
|
let projects: TaskCreationProjectService
|
||||||
|
let planes: DroneDockPlaneStatusTestService
|
||||||
|
let creation: DroneDockTaskCreationTestService
|
||||||
|
let scope: TaskCreationContextBox
|
||||||
|
let model: DroneDockPreparationViewModel
|
||||||
|
|
||||||
|
init(creationService: (any DroneDockTaskCreating)? = nil) throws {
|
||||||
|
projects = try TaskCreationProjectService()
|
||||||
|
planes = try DroneDockPlaneStatusTestService()
|
||||||
|
creation = DroneDockTaskCreationTestService(result: .success(try DroneDockTaskCreationTestData.response()))
|
||||||
|
scope = TaskCreationContextBox(TaskCreationFixtureData.context())
|
||||||
|
let currentScope = scope
|
||||||
|
let order = try JSONDecoder().decode(DroneDockHomeOrder.self, from: Data(#"{"order_number":"TEST-PREPARATION-001","project_id":101}"#.utf8))
|
||||||
|
model = DroneDockPreparationViewModel(context: scope.value, order: order, service: projects,
|
||||||
|
planeStatusService: planes, taskCreationService: creationService ?? creation,
|
||||||
|
shootService: DroneDockShootTestService(),
|
||||||
|
currentContext: { currentScope.value })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 创建前购买配置夹具,仅包含任务所需的有效点位与航线。
|
||||||
|
private enum TaskCreationFixtureData {
|
||||||
|
static func context(scenicID: Int = 128) -> DroneDockHomeContext {
|
||||||
|
DroneDockHomeContext(userID: "task-creation-test-user", accountType: "store_user", scenicID: scenicID,
|
||||||
|
scenicName: "测试景区", storeID: 37, photographerName: "测试工作人员", token: "task-creation-test-token")
|
||||||
|
}
|
||||||
|
|
||||||
|
static func project(remaining: Int? = 5, total: Int? = 5, canCreate: Bool = true,
|
||||||
|
spots: [[String: Any]]? = nil) throws -> DroneDockProjectInfoResponse {
|
||||||
|
var data: [String: Any] = ["order_number": "TEST-PREPARATION-001", "project_id": 101,
|
||||||
|
"shot_count": 0, "can_create_task": canCreate,
|
||||||
|
"spot": spots ?? [point(201), point(202, routes: [401, 402])]]
|
||||||
|
data["remaining_count"] = remaining
|
||||||
|
data["shoot_count"] = total
|
||||||
|
return try JSONDecoder().decode(DroneDockProjectInfoResponse.self, from: JSONSerialization.data(withJSONObject: data))
|
||||||
|
}
|
||||||
|
|
||||||
|
static func point(_ id: Int, routes: [Int] = [301, 302], available: Bool = true) -> [String: Any] {
|
||||||
|
["scenic_spot_id": id, "scenic_spot_name": "测试点位 \(id)", "available": available,
|
||||||
|
"air_lines": routes.map { ["air_line_id": $0, "air_line_name": "测试航线 \($0)", "available": true, "samples": []] as [String: Any] }]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 可更换结果的购买预检替身,记录读取次数以防自动重建。
|
||||||
|
@MainActor
|
||||||
|
private final class TaskCreationProjectService: DroneDockPreparationServing {
|
||||||
|
var result: Result<DroneDockProjectInfoResponse, Error>
|
||||||
|
private(set) var requests: [String] = []
|
||||||
|
|
||||||
|
init() throws { result = .success(try TaskCreationFixtureData.project()) }
|
||||||
|
func projectInfo(scenicID: Int, projectID: Int, orderNumber: String) async throws -> DroneDockProjectInfoResponse {
|
||||||
|
requests.append(orderNumber)
|
||||||
|
return try result.get()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 主线程切换身份,避免可发送闭包捕获可变局部变量。
|
||||||
|
@MainActor
|
||||||
|
private final class TaskCreationContextBox {
|
||||||
|
var value: DroneDockHomeContext
|
||||||
|
init(_ value: DroneDockHomeContext) { self.value = value }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 挂起单次创建请求,精确验证重复点击、取消和会话变更。
|
||||||
|
@MainActor
|
||||||
|
private final class SuspendedTaskCreationService: DroneDockTaskCreating {
|
||||||
|
var started: (() -> Void)?
|
||||||
|
private(set) var requests: [Int] = []
|
||||||
|
private var continuation: CheckedContinuation<DroneDockCreatedTask, Error>?
|
||||||
|
|
||||||
|
func createTask(scenicID: Int, orderNumber: String, spotID: Int, airLineID: Int) async throws -> DroneDockCreatedTask {
|
||||||
|
requests.append(spotID)
|
||||||
|
return try await withCheckedThrowingContinuation { continuation in
|
||||||
|
self.continuation = continuation
|
||||||
|
started?()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func finish() throws {
|
||||||
|
let response = try DroneDockTaskCreationTestData.response()
|
||||||
|
let pending = continuation
|
||||||
|
continuation = nil
|
||||||
|
pending?.resume(returning: response)
|
||||||
|
}
|
||||||
|
|
||||||
|
func cancelAll() {
|
||||||
|
continuation?.resume(throwing: CancellationError())
|
||||||
|
continuation = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
import UIKit
|
||||||
|
import XCTest
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 验证真实任务页三区固定,中间状态在有限高度内保持可读、可点击且不产生滚动。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockTaskFixedLayoutTests: XCTestCase {
|
||||||
|
private let compactSize = CGSize(width: 375, height: 146)
|
||||||
|
private let regularSize = CGSize(width: 402, height: 220)
|
||||||
|
private let phases: [DroneDockTaskDisplayPhase] = [
|
||||||
|
.loading, .navigating, .ready, .shooting, .paused, .returning,
|
||||||
|
.completed, .failed, .blocked, .unknown, .readError
|
||||||
|
]
|
||||||
|
|
||||||
|
/// 紧凑屏逐一显示全部业务阶段,控件始终留在固定中间区域内。
|
||||||
|
func testAllPhasesFitCompactStatusArea() throws {
|
||||||
|
let status = makeStatus(size: compactSize)
|
||||||
|
for phase in phases {
|
||||||
|
apply(presentation(phase), to: status)
|
||||||
|
XCTAssertTrue(status.usesCompactLayout, "\(phase)")
|
||||||
|
XCTAssertEqual(status.bounds.size, compactSize)
|
||||||
|
try assertReadableContainedContent(in: status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 常规屏支持全部阶段,并保留完整设备状态行而不放大外部容器。
|
||||||
|
func testAllPhasesFitRegularStatusArea() throws {
|
||||||
|
let status = makeStatus(size: regularSize)
|
||||||
|
for phase in phases {
|
||||||
|
apply(presentation(phase), to: status)
|
||||||
|
XCTAssertFalse(status.usesCompactLayout, "\(phase)")
|
||||||
|
XCTAssertEqual(status.bounds.size, regularSize)
|
||||||
|
let device = try XCTUnwrap(find(in: status, suffix: "deviceStatus") as? UILabel)
|
||||||
|
XCTAssertFalse(isHidden(device))
|
||||||
|
XCTAssertEqual(device.text, "空闲 · 电量 93%")
|
||||||
|
try assertReadableContainedContent(in: status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 任一阶段的超长后端文案不会挤出容器、压缩点击区域或依赖整体 transform。
|
||||||
|
func testLongCopyAcrossAllPhasesKeepsControlsReadableAndContained() throws {
|
||||||
|
for size in [compactSize, regularSize] {
|
||||||
|
let status = makeStatus(size: size)
|
||||||
|
for phase in phases {
|
||||||
|
let value = presentation(phase, longCopy: true)
|
||||||
|
apply(value, to: status)
|
||||||
|
XCTAssertEqual(status.bounds.size, size)
|
||||||
|
XCTAssertEqual(status.transform, .identity)
|
||||||
|
let title = try XCTUnwrap(find(in: status, suffix: "statusTitle") as? UILabel)
|
||||||
|
let message = try XCTUnwrap(find(in: status, suffix: "statusMessage") as? UILabel)
|
||||||
|
XCTAssertEqual(title.text, value.title, "视觉截断不能丢弃原始详情")
|
||||||
|
XCTAssertEqual(message.text, value.message)
|
||||||
|
try assertReadableContainedContent(in: status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 长文案可通过至少 44 点高的详情入口查看,截断不影响命中与回调。
|
||||||
|
func testCompactLongErrorDetailsRemainTappable() throws {
|
||||||
|
let status = makeStatus(size: compactSize)
|
||||||
|
apply(presentation(.readError, longCopy: true), to: status)
|
||||||
|
var detailsCalls = 0
|
||||||
|
status.onDetails = { detailsCalls += 1 }
|
||||||
|
let details = try XCTUnwrap(find(in: status, suffix: "details") as? UIButton)
|
||||||
|
XCTAssertTrue(details.isEnabled)
|
||||||
|
XCTAssertFalse(isHidden(details))
|
||||||
|
XCTAssertGreaterThanOrEqual(details.bounds.height, 44)
|
||||||
|
XCTAssertGreaterThanOrEqual(details.bounds.width, 44)
|
||||||
|
let center = details.convert(CGPoint(x: details.bounds.midX, y: details.bounds.midY), to: status)
|
||||||
|
let hit = status.hitTest(center, with: nil)
|
||||||
|
XCTAssertTrue(hit === details || hit?.isDescendant(of: details) == true)
|
||||||
|
details.sendActions(for: .touchUpInside)
|
||||||
|
XCTAssertEqual(detailsCalls, 1)
|
||||||
|
try assertReadableContainedContent(in: status)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 状态区只转发已允许的主操作,未接通的开始拍摄按钮不能借布局切换被启用。
|
||||||
|
func testActionAvailabilitySurvivesLayoutChanges() throws {
|
||||||
|
let status = makeStatus(size: compactSize)
|
||||||
|
var actionCalls = 0
|
||||||
|
status.onPrimaryAction = { actionCalls += 1 }
|
||||||
|
apply(presentation(.ready), to: status)
|
||||||
|
let start = try XCTUnwrap(find(in: status, suffix: "primary") as? UIButton)
|
||||||
|
XCTAssertFalse(start.isEnabled)
|
||||||
|
start.sendActions(for: .touchUpInside)
|
||||||
|
XCTAssertEqual(actionCalls, 0)
|
||||||
|
|
||||||
|
status.frame.size = regularSize
|
||||||
|
apply(presentation(.readError), to: status)
|
||||||
|
let refresh = try XCTUnwrap(find(in: status, suffix: "refresh") as? UIButton)
|
||||||
|
XCTAssertTrue(refresh.isEnabled)
|
||||||
|
refresh.sendActions(for: .touchUpInside)
|
||||||
|
XCTAssertEqual(actionCalls, 1)
|
||||||
|
try assertReadableContainedContent(in: status)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 以扣除系统栏后的内容尺寸切换状态,验证真实剩余中间高度及三区稳定性。
|
||||||
|
func testPageRegionsRemainFixedAcrossStatesAndStaleTelemetry() throws {
|
||||||
|
// 离线视图没有系统 safe area:小屏扣除状态栏 20 + 导航栏 44,大屏扣除顶部 106 + 底部 34。
|
||||||
|
let viewports: [(size: CGSize, expectedStatusHeight: CGFloat, screen: String)] = [
|
||||||
|
(CGSize(width: 375, height: 603), 146.0625, "375x667"),
|
||||||
|
(CGSize(width: 402, height: 734), 207.875, "402x874")
|
||||||
|
]
|
||||||
|
for viewport in viewports {
|
||||||
|
let size = viewport.size
|
||||||
|
let service = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.response()))
|
||||||
|
let controller = try makeController(service: service, size: size)
|
||||||
|
let root = try XCTUnwrap(controller.view)
|
||||||
|
let top = try XCTUnwrap(find(in: root, suffix: "top"))
|
||||||
|
let status = try XCTUnwrap(find(in: root, suffix: "stateContainer") as? DroneDockTaskStatusView)
|
||||||
|
let footer = try XCTUnwrap(find(in: root, suffix: "safety"))
|
||||||
|
let telemetry = try XCTUnwrap(find(in: root, suffix: "telemetry") as? DroneShootingTaskTelemetryView)
|
||||||
|
let feed = try XCTUnwrap(find(in: root, suffix: "feedPlaceholder"))
|
||||||
|
XCTAssertTrue(top.superview === root)
|
||||||
|
XCTAssertTrue(status.superview === root)
|
||||||
|
XCTAssertTrue(footer.superview === root)
|
||||||
|
XCTAssertTrue(allViews(in: root).allSatisfy { !($0 is UIScrollView) })
|
||||||
|
let stableIDs = ["top", "summary", "feedPlaceholder", "telemetry", "stateContainer", "safety"]
|
||||||
|
let initial = try regionFrames(in: root, suffixes: stableIDs)
|
||||||
|
XCTAssertEqual(status.bounds.height, viewport.expectedStatusHeight, accuracy: 0.5)
|
||||||
|
XCTAssertEqual(top.frame.maxY, status.frame.minY, accuracy: 0.5)
|
||||||
|
XCTAssertEqual(status.frame.maxY, footer.frame.minY, accuracy: 0.5)
|
||||||
|
XCTAssertEqual(feed.bounds.height, feed.bounds.width * 9 / 16, accuracy: 0.5)
|
||||||
|
assertContained(top, in: root)
|
||||||
|
assertContained(status, in: root)
|
||||||
|
assertContained(footer, in: root)
|
||||||
|
for suffix in ["summary", "feedPlaceholder", "telemetry"] {
|
||||||
|
assertContained(try XCTUnwrap(find(in: root, suffix: suffix)), in: top)
|
||||||
|
}
|
||||||
|
for suffix in ["pause", "return"] {
|
||||||
|
let button = try XCTUnwrap(find(in: footer, suffix: suffix) as? UIButton)
|
||||||
|
XCTAssertFalse(button.isEnabled)
|
||||||
|
XCTAssertGreaterThanOrEqual(button.bounds.height, 44)
|
||||||
|
XCTAssertGreaterThanOrEqual(button.bounds.width, 44)
|
||||||
|
assertContained(button, in: footer)
|
||||||
|
}
|
||||||
|
|
||||||
|
for phase in phases {
|
||||||
|
apply(presentation(phase, longCopy: phase == .readError), to: status)
|
||||||
|
UIView.performWithoutAnimation {
|
||||||
|
telemetry.apply(values: ["93%", "10.3℃", "0m/s", "无雨", "信号良好", "32颗"],
|
||||||
|
isStale: phase == .loading || phase == .readError,
|
||||||
|
accessibilityPrefix: "drone.task.remote.metric")
|
||||||
|
layoutHierarchy(root)
|
||||||
|
}
|
||||||
|
let current = try regionFrames(in: root, suffixes: stableIDs)
|
||||||
|
for suffix in stableIDs {
|
||||||
|
assertEqual(try XCTUnwrap(current[suffix]), try XCTUnwrap(initial[suffix]),
|
||||||
|
message: "\(Int(size.width))×\(Int(size.height)) \(phase) \(suffix)")
|
||||||
|
}
|
||||||
|
try assertReadableContainedContent(in: status)
|
||||||
|
}
|
||||||
|
XCTAssertTrue(service.requests.isEmpty, "仅布局测试不得触发网络读取")
|
||||||
|
capture(root, name: "任务固定三区-内容\(Int(size.width))x\(Int(size.height))-屏幕\(viewport.screen)-长错误文案")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 将常规、紧凑及长错误文案保存为 XCTest 图片附件供模拟器视觉复核。
|
||||||
|
func testCaptureRegularCompactAndLongErrorAttachments() throws {
|
||||||
|
let samples: [(CGSize, DroneDockTaskPresentation, String)] = [
|
||||||
|
(regularSize, presentation(.ready), "状态区-常规402x220-准备就绪"),
|
||||||
|
(compactSize, presentation(.shooting), "状态区-紧凑375x146-拍摄中"),
|
||||||
|
(compactSize, presentation(.readError, longCopy: true), "状态区-紧凑375x146-超长错误")
|
||||||
|
]
|
||||||
|
for (size, value, name) in samples {
|
||||||
|
let status = makeStatus(size: size)
|
||||||
|
apply(value, to: status)
|
||||||
|
try assertReadableContainedContent(in: status)
|
||||||
|
capture(status, name: name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeStatus(size: CGSize) -> DroneDockTaskStatusView {
|
||||||
|
let status = DroneDockTaskStatusView(frame: CGRect(origin: .zero, size: size))
|
||||||
|
status.overrideUserInterfaceStyle = .light
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
|
||||||
|
private func apply(_ presentation: DroneDockTaskPresentation, to status: DroneDockTaskStatusView) {
|
||||||
|
UIView.performWithoutAnimation {
|
||||||
|
status.apply(presentation)
|
||||||
|
layoutHierarchy(status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func presentation(_ phase: DroneDockTaskDisplayPhase, longCopy: Bool = false) -> DroneDockTaskPresentation {
|
||||||
|
let title: String
|
||||||
|
let action: DroneDockTaskDisplayAction
|
||||||
|
let actionTitle: String?
|
||||||
|
let enabled: Bool
|
||||||
|
switch phase {
|
||||||
|
case .loading: (title, action, actionTitle, enabled) = ("正在获取任务状态", .none, nil, false)
|
||||||
|
case .navigating: (title, action, actionTitle, enabled) = ("无人机正在前往点位", .refresh, "刷新任务状态", true)
|
||||||
|
case .ready: (title, action, actionTitle, enabled) = ("无人机已到达", .start, "开始拍摄", false)
|
||||||
|
case .shooting: (title, action, actionTitle, enabled) = ("正在拍摄", .refresh, "刷新任务状态", true)
|
||||||
|
case .paused: (title, action, actionTitle, enabled) = ("拍摄已暂停", .resume, "继续拍摄", false)
|
||||||
|
case .returning: (title, action, actionTitle, enabled) = ("无人机正在返航", .refresh, "刷新任务状态", true)
|
||||||
|
case .completed: (title, action, actionTitle, enabled) = ("本次拍摄已完成", .materials, "查看素材", true)
|
||||||
|
case .failed: (title, action, actionTitle, enabled) = ("航线任务执行失败", .refresh, "刷新任务状态", true)
|
||||||
|
case .blocked: (title, action, actionTitle, enabled) = ("当前无法继续拍摄", .refresh, "刷新任务状态", true)
|
||||||
|
case .unknown: (title, action, actionTitle, enabled) = ("状态待确认", .refresh, "刷新任务状态", true)
|
||||||
|
case .readError: (title, action, actionTitle, enabled) = ("任务状态读取失败", .refresh, "重新加载", true)
|
||||||
|
}
|
||||||
|
let longTitle = String(repeating: "航线任务状态需要确认,", count: 8)
|
||||||
|
let longMessage = String(repeating: "服务端返回的完整错误说明需要保留供工作人员查看,请检查任务和设备状态。", count: 12)
|
||||||
|
return DroneDockTaskPresentation(phase: phase, title: longCopy ? longTitle : title,
|
||||||
|
message: longCopy ? longMessage : "请确认当前状态后继续操作。", deviceStatus: "空闲 · 电量 93%",
|
||||||
|
action: action, actionTitle: actionTitle, isActionEnabled: enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeController(service: any DroneDockShootingServing, size: CGSize) throws -> DroneDockShootingTaskViewController {
|
||||||
|
let context = DroneDockShootingTaskTestData.context()
|
||||||
|
let model = DroneDockShootingTaskViewModel(context: context, taskID: 501,
|
||||||
|
order: try DroneDockShootingTaskTestData.order(), service: service, currentContext: { context })
|
||||||
|
let controller = DroneDockShootingTaskViewController(viewModel: model)
|
||||||
|
UIView.performWithoutAnimation {
|
||||||
|
controller.loadViewIfNeeded()
|
||||||
|
controller.view.frame = CGRect(origin: .zero, size: size)
|
||||||
|
layoutHierarchy(controller.view)
|
||||||
|
controller.viewDidLayoutSubviews()
|
||||||
|
layoutHierarchy(controller.view)
|
||||||
|
}
|
||||||
|
return controller
|
||||||
|
}
|
||||||
|
|
||||||
|
private func assertReadableContainedContent(in status: DroneDockTaskStatusView,
|
||||||
|
file: StaticString = #filePath, line: UInt = #line) throws {
|
||||||
|
XCTAssertEqual(status.transform, .identity, file: file, line: line)
|
||||||
|
XCTAssertGreaterThanOrEqual(status.effectiveScale, 0.8, file: file, line: line)
|
||||||
|
XCTAssertLessThanOrEqual(status.effectiveScale, 1, file: file, line: line)
|
||||||
|
XCTAssertTrue(allViews(in: status).allSatisfy { !($0 is UIScrollView) }, file: file, line: line)
|
||||||
|
for view in allViews(in: status) where view !== status && !isHidden(view) && !view.bounds.isEmpty {
|
||||||
|
assertContained(view, in: status, file: file, line: line)
|
||||||
|
if let label = view as? UILabel {
|
||||||
|
XCTAssertGreaterThanOrEqual(label.font.pointSize, 12, file: file, line: line)
|
||||||
|
if label.adjustsFontSizeToFitWidth {
|
||||||
|
XCTAssertGreaterThanOrEqual(label.font.pointSize * label.minimumScaleFactor, 12, file: file, line: line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let button = view as? UIButton {
|
||||||
|
XCTAssertGreaterThanOrEqual(button.bounds.height, 44, file: file, line: line)
|
||||||
|
XCTAssertGreaterThanOrEqual(button.bounds.width, 44, file: file, line: line)
|
||||||
|
if let title = button.currentTitle, !title.isEmpty {
|
||||||
|
let label = try XCTUnwrap(button.titleLabel, file: file, line: line)
|
||||||
|
XCTAssertEqual(label.text, title, file: file, line: line)
|
||||||
|
XCTAssertFalse(label.bounds.isEmpty, file: file, line: line)
|
||||||
|
XCTAssertFalse(isHidden(label), file: file, line: line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let details = try XCTUnwrap(find(in: status, suffix: "details") as? UIButton, file: file, line: line)
|
||||||
|
XCTAssertFalse(isHidden(details), file: file, line: line)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func assertContained(_ view: UIView, in container: UIView,
|
||||||
|
file: StaticString = #filePath, line: UInt = #line) {
|
||||||
|
let frame = view.convert(view.bounds, to: container)
|
||||||
|
XCTAssertTrue(container.bounds.insetBy(dx: -0.5, dy: -0.5).contains(frame),
|
||||||
|
"\(view.accessibilityIdentifier ?? String(describing: type(of: view))) 越界:\(frame),容器:\(container.bounds)",
|
||||||
|
file: file, line: line)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func assertEqual(_ lhs: CGRect, _ rhs: CGRect, message: String,
|
||||||
|
file: StaticString = #filePath, line: UInt = #line) {
|
||||||
|
XCTAssertEqual(lhs.origin.x, rhs.origin.x, accuracy: 0.5, message, file: file, line: line)
|
||||||
|
XCTAssertEqual(lhs.origin.y, rhs.origin.y, accuracy: 0.5, message, file: file, line: line)
|
||||||
|
XCTAssertEqual(lhs.size.width, rhs.size.width, accuracy: 0.5, message, file: file, line: line)
|
||||||
|
XCTAssertEqual(lhs.size.height, rhs.size.height, accuracy: 0.5, message, file: file, line: line)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func regionFrames(in root: UIView, suffixes: [String]) throws -> [String: CGRect] {
|
||||||
|
var frames: [String: CGRect] = [:]
|
||||||
|
for suffix in suffixes {
|
||||||
|
let view = try XCTUnwrap(find(in: root, suffix: suffix), "缺少固定区域 \(suffix)")
|
||||||
|
frames[suffix] = view.convert(view.bounds, to: root)
|
||||||
|
}
|
||||||
|
return frames
|
||||||
|
}
|
||||||
|
|
||||||
|
private func allViews(in root: UIView) -> [UIView] { [root] + root.subviews.flatMap { allViews(in: $0) } }
|
||||||
|
private func isHidden(_ view: UIView) -> Bool { view.isHidden || view.alpha < 0.01 || (view.superview.map(isHidden) ?? false) }
|
||||||
|
private func find(in root: UIView, suffix: String) -> UIView? {
|
||||||
|
allViews(in: root).first { $0.accessibilityIdentifier == "drone.task.remote.\(suffix)" }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 离线布局完成后显式刷新按钮标题图层,避免截图落在标题切换的过渡帧。
|
||||||
|
private func layoutHierarchy(_ view: UIView) {
|
||||||
|
view.setNeedsLayout()
|
||||||
|
view.layoutIfNeeded()
|
||||||
|
for child in view.subviews { layoutHierarchy(child) }
|
||||||
|
if let button = view as? UIButton {
|
||||||
|
button.layoutIfNeeded()
|
||||||
|
button.titleLabel?.setNeedsLayout()
|
||||||
|
button.titleLabel?.layoutIfNeeded()
|
||||||
|
button.titleLabel?.layer.setNeedsDisplay()
|
||||||
|
button.titleLabel?.layer.displayIfNeeded()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func capture(_ view: UIView, name: String) {
|
||||||
|
UIView.performWithoutAnimation { layoutHierarchy(view) }
|
||||||
|
let image = UIGraphicsImageRenderer(bounds: view.bounds).image { context in
|
||||||
|
view.layer.render(in: context.cgContext)
|
||||||
|
}
|
||||||
|
let attachment = XCTAttachment(image: image)
|
||||||
|
attachment.name = name
|
||||||
|
attachment.lifetime = .keepAlways
|
||||||
|
add(attachment)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 验证任务页展示阶段和动作的保守映射;阶段夹具用于显示测试,不代表全部状态已经后端实测。
|
||||||
|
@MainActor
|
||||||
|
final class DroneDockTaskPresentationTests: XCTestCase {
|
||||||
|
/// 显式阶段提供显示语义,保留后端标题和说明,不编造飞行百分比。
|
||||||
|
func testExplicitDisplayPhaseFixturesPreserveBackendText() async throws {
|
||||||
|
let phases: [(String, DroneDockTaskDisplayPhase)] = [
|
||||||
|
("navigating", .navigating), ("shooting", .shooting), ("paused", .paused),
|
||||||
|
("returning", .returning), ("failed", .failed), ("blocked", .blocked)
|
||||||
|
]
|
||||||
|
for (phase, expected) in phases {
|
||||||
|
let result = try await presentation([
|
||||||
|
"ui": ["phase": phase, "title": "服务端阶段标题", "message": "服务端完整阶段说明"],
|
||||||
|
"current_plane": ["status_text": "服务端设备文案"]
|
||||||
|
])
|
||||||
|
XCTAssertEqual(result.phase, expected)
|
||||||
|
XCTAssertEqual(result.title, "服务端阶段标题")
|
||||||
|
XCTAssertEqual(result.message, "服务端完整阶段说明")
|
||||||
|
XCTAssertEqual(result.deviceStatus, "服务端设备文案")
|
||||||
|
XCTAssertEqual(result.action, .refresh)
|
||||||
|
XCTAssertTrue(result.isActionEnabled)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 后端明确允许开始或恢复时本轮仍禁用,因为尚未对接相应飞控接口。
|
||||||
|
func testStartAndResumeRemainDisabledEvenWithPermission() async throws {
|
||||||
|
let ready = try await presentation([
|
||||||
|
"ui": ["phase": "arrived_pending_start", "title": "无人机已到达"],
|
||||||
|
"execute_gate": ["can_execute": true, "primary_action": "start_shoot", "primary_action_label": "开始拍摄"]
|
||||||
|
])
|
||||||
|
XCTAssertEqual(ready.phase, .ready)
|
||||||
|
XCTAssertEqual(ready.action, .start)
|
||||||
|
XCTAssertEqual(ready.actionTitle, "开始拍摄")
|
||||||
|
XCTAssertFalse(ready.isActionEnabled)
|
||||||
|
let paused = try await presentation([
|
||||||
|
"ui": ["phase": "paused"],
|
||||||
|
"execute_gate": ["can_execute": true, "primary_action": "flighttask_recovery", "primary_action_label": "继续执行"]
|
||||||
|
])
|
||||||
|
XCTAssertEqual(paused.phase, .paused)
|
||||||
|
XCTAssertEqual(paused.action, .resume)
|
||||||
|
XCTAssertEqual(paused.actionTitle, "继续执行")
|
||||||
|
XCTAssertFalse(paused.isActionEnabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 门禁拒绝覆盖到达提示,不出现开始按钮;暂停时门禁拒绝也不出现恢复动作。
|
||||||
|
func testDeniedGateNeverProducesStartOrResumeAction() async throws {
|
||||||
|
let denied = try await presentation([
|
||||||
|
"ui": ["phase": "arrived_pending_start", "title": "无人机已到达 是否开始拍摄?"],
|
||||||
|
"execute_gate": ["can_execute": false, "message": "电量不足", "primary_action": "start_shoot"]
|
||||||
|
])
|
||||||
|
XCTAssertEqual(denied.phase, .blocked)
|
||||||
|
XCTAssertEqual(denied.title, "暂不可开始拍摄")
|
||||||
|
XCTAssertEqual(denied.message, "电量不足")
|
||||||
|
XCTAssertEqual(denied.action, .refresh)
|
||||||
|
let paused = try await presentation(["ui": ["phase": "paused"], "execute_gate": ["can_execute": false]])
|
||||||
|
XCTAssertEqual(paused.action, .refresh)
|
||||||
|
XCTAssertTrue(paused.isActionEnabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 实测任务 6 的结构:航线 91 执行失败优先于订单任务 20 执行中,指令列表不等于可操作。
|
||||||
|
func testObservedWaylineFailureWinsOverExecutingTaskAndBlockedUI() async throws {
|
||||||
|
let reason = "航线任务状态不可拍摄(当前:执行失败)"
|
||||||
|
let result = try await presentation([
|
||||||
|
"task": ["id": 501, "status": 20, "status_label": "执行中", "wayline_status": 91, "wayline_status_label": "执行失败"],
|
||||||
|
"order_flight_task": ["id": 501, "status": 20, "status_label": "执行中"],
|
||||||
|
"execute_gate": ["can_execute": false, "code": "wayline_not_shooting", "message": reason, "primary_action": "blocked"],
|
||||||
|
"ui": ["phase": "blocked", "title": reason, "message": reason,
|
||||||
|
"commands": [["command": "flighttask_pause", "label": "紧急暂停"], ["command": "return_home", "label": "立即返航"]]]
|
||||||
|
])
|
||||||
|
XCTAssertEqual(result.phase, .failed)
|
||||||
|
XCTAssertEqual(result.title, "执行失败")
|
||||||
|
XCTAssertEqual(result.message, reason)
|
||||||
|
XCTAssertEqual(result.action, .refresh)
|
||||||
|
XCTAssertTrue(result.isActionEnabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 仅明确完成且无活动阶段冲突时开放素材入口;完成后仍返航时继续展示返航。
|
||||||
|
func testMaterialsRequiresExplicitUnconflictedCompletion() async throws {
|
||||||
|
for payload: [String: Any] in [
|
||||||
|
["task": ["id": 501, "status": 30, "status_label": "拍摄成功"]],
|
||||||
|
["ui": ["phase": "completed", "title": "本次拍摄已完成"]]
|
||||||
|
] {
|
||||||
|
let result = try await presentation(payload)
|
||||||
|
XCTAssertEqual(result.phase, .completed)
|
||||||
|
XCTAssertEqual(result.action, .materials)
|
||||||
|
XCTAssertEqual(result.actionTitle, "查看素材")
|
||||||
|
XCTAssertTrue(result.isActionEnabled)
|
||||||
|
}
|
||||||
|
let returning = try await presentation(["task": ["status": 30], "ui": ["phase": "returning"]])
|
||||||
|
XCTAssertEqual(returning.phase, .returning)
|
||||||
|
XCTAssertEqual(returning.action, .refresh)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 未知阶段、执行中摘要及矛盾字段不转换成到达、拍摄中或完成。
|
||||||
|
func testUnknownAndConflictingStatesUseRefreshOnly() async throws {
|
||||||
|
let payloads: [[String: Any]] = [
|
||||||
|
[:], ["task": ["status": 20, "status_label": "执行中"]],
|
||||||
|
["ui": ["phase": "future_phase", "title": "未知阶段"], "task": ["status": 30]],
|
||||||
|
["task": ["status": 20], "order_flight_task": ["status": 30]],
|
||||||
|
["task": ["status": 20], "ui": ["phase": "completed"]],
|
||||||
|
["task": ["status": 30], "ui": ["phase": "shooting"]],
|
||||||
|
["ui": ["phase": "arrived_pending_start"]],
|
||||||
|
["ui": ["phase": "arrived_pending_start"], "execute_gate": ["can_execute": true, "primary_action": "blocked"]],
|
||||||
|
["ui": ["phase": "paused"], "execute_gate": ["can_execute": true, "primary_action": "blocked"]]
|
||||||
|
]
|
||||||
|
for payload in payloads {
|
||||||
|
let result = try await presentation(payload)
|
||||||
|
XCTAssertEqual(result.phase, .unknown)
|
||||||
|
XCTAssertEqual(result.title, "状态待确认")
|
||||||
|
XCTAssertEqual(result.action, .refresh)
|
||||||
|
XCTAssertTrue(result.isActionEnabled)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 明确失败或取消不受笼统阶段文案覆盖,更不能开放素材完成入口。
|
||||||
|
func testFailedAndCancelledTaskStatesOverrideOptimisticUI() async throws {
|
||||||
|
let failed = try await presentation(["task": ["status": 40, "status_label": "执行失败"], "ui": ["phase": "completed"]])
|
||||||
|
XCTAssertEqual(failed.phase, .failed)
|
||||||
|
XCTAssertEqual(failed.title, "执行失败")
|
||||||
|
XCTAssertEqual(failed.action, .refresh)
|
||||||
|
let cancelled = try await presentation(["task": ["status": 50, "status_label": "任务已取消"], "ui": ["phase": "shooting"]])
|
||||||
|
XCTAssertEqual(cancelled.phase, .blocked)
|
||||||
|
XCTAssertEqual(cancelled.title, "任务已取消")
|
||||||
|
XCTAssertEqual(cancelled.action, .refresh)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前请求失败后覆盖旧完成态,清除素材入口并提供只读重试。
|
||||||
|
func testReadErrorOverridesPreviousCompletedPresentation() async throws {
|
||||||
|
let service = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.decode(["task": ["status": 30]])))
|
||||||
|
let model = try makeModel(service: service)
|
||||||
|
await model.refresh()
|
||||||
|
XCTAssertEqual(model.presentation.action, .materials)
|
||||||
|
let readError = APIError.networkFailed("测试读取失败")
|
||||||
|
service.result = .failure(readError)
|
||||||
|
await model.refresh()
|
||||||
|
XCTAssertEqual(model.presentation.phase, .readError)
|
||||||
|
XCTAssertEqual(model.presentation.message, readError.localizedDescription)
|
||||||
|
XCTAssertEqual(model.presentation.action, .refresh)
|
||||||
|
XCTAssertTrue(model.presentation.isActionEnabled)
|
||||||
|
XCTAssertEqual(model.presentation.deviceStatus, "—")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 请求进行中仅显示加载,无可执行主动作,也不保留前一次完成入口。
|
||||||
|
func testLoadingOverridesPreviousCompletedPresentation() async throws {
|
||||||
|
let service = PresentationPendingService(response: try DroneDockShootingTaskTestData.decode(["task": ["status": 30]]))
|
||||||
|
let model = try makeModel(service: service)
|
||||||
|
await model.refresh()
|
||||||
|
service.shouldHold = true
|
||||||
|
let pending = Task { await model.refresh() }
|
||||||
|
for _ in 0..<100 where !service.isPending { await Task.yield() }
|
||||||
|
XCTAssertTrue(service.isPending)
|
||||||
|
XCTAssertEqual(model.presentation.phase, .loading)
|
||||||
|
XCTAssertEqual(model.presentation.action, .none)
|
||||||
|
XCTAssertNil(model.presentation.actionTitle)
|
||||||
|
XCTAssertFalse(model.presentation.isActionEnabled)
|
||||||
|
service.finish()
|
||||||
|
await pending.value
|
||||||
|
XCTAssertEqual(model.presentation.phase, .completed)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func presentation(_ payload: [String: Any]) async throws -> DroneDockTaskPresentation {
|
||||||
|
let service = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.decode(payload)))
|
||||||
|
let model = try makeModel(service: service)
|
||||||
|
await model.refresh()
|
||||||
|
return model.presentation
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeModel(service: any DroneDockShootingServing) throws -> DroneDockShootingTaskViewModel {
|
||||||
|
let context = DroneDockShootingTaskTestData.context()
|
||||||
|
return DroneDockShootingTaskViewModel(context: context, taskID: 501, order: try DroneDockShootingTaskTestData.order(),
|
||||||
|
service: service, currentContext: { context })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 手动挂起一次读取,验证加载状态优先级,不访问真实网络。
|
||||||
|
@MainActor
|
||||||
|
private final class PresentationPendingService: DroneDockShootingServing {
|
||||||
|
var shouldHold = false
|
||||||
|
private let response: DroneDockShootingResponse
|
||||||
|
private var continuation: CheckedContinuation<DroneDockShootingResponse, Error>?
|
||||||
|
var isPending: Bool { continuation != nil }
|
||||||
|
|
||||||
|
init(response: DroneDockShootingResponse) { self.response = response }
|
||||||
|
|
||||||
|
func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse {
|
||||||
|
if shouldHold { return try await withCheckedThrowingContinuation { continuation = $0 } }
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
func finish() {
|
||||||
|
continuation?.resume(returning: response)
|
||||||
|
continuation = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
+414
-24
@@ -1,7 +1,7 @@
|
|||||||
# 机巢工作台页面接口对接记录
|
# 机巢工作台页面接口对接记录
|
||||||
|
|
||||||
> 更新日期:2026-10-29
|
> 更新日期:2026-10-29
|
||||||
> 核对范围:当前工作区,新增共用交付成片页与云端上传流程,从“我的拍摄订单”和“订单素材库”进入;真实上传待有效任务数据。准备页仅调用 `project-info`,已停用 `workbench` 及其定位请求。
|
> 核对范围:当前工作区。准备页使用张工 `project-info` 和朱工 `plane-status`;“确认并召唤”按 `project-info → tasks/create → shoot` 执行,召唤业务成功后进入任务页;按用户最新要求,`shooting` 已取消定时轮询,仅在进入页面、页面可见时返回前台或手动刷新时各读取一次同一任务。准备页 `plane-status` 保持轮询。2026-10-29 16:03 按用户明确要求新建任务 6,再以 `{id:6,restart:false}` 召唤,两个接口均业务成功并绑定飞机 61、航线任务 1926;但 16:04:52 只读回查显示航线“执行失败”、禁止拍摄,当前待排查 1926 失败原因及飞机 61 在线状态。召唤回执的“已到达”不是物理验证,本轮未调用开始拍摄或控制接口。任务 2 的参数、订单类型及机场状态失败保留为历史,原因不因新任务成功而作推断。`workbench`、定位请求已停用;图传、`start-shoot/command` 尚未接入,真实成片上传仍待联调。
|
||||||
> 用途:记录每个页面实际调用的接口、提供人、调用时机、请求参数和返回 JSON,供 iOS 与后端持续联调。
|
> 用途:记录每个页面实际调用的接口、提供人、调用时机、请求参数和返回 JSON,供 iOS 与后端持续联调。
|
||||||
|
|
||||||
## 1. 阅读说明
|
## 1. 阅读说明
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
|
|
||||||
## 2. 页面与接口总览
|
## 2. 页面与接口总览
|
||||||
|
|
||||||
当前机巢功能共 **7 个正式页面,涉及 10 个业务接口及 1 个通用 STS 接口**;其中成片保存与 STS 上传流程已实现,尚待真实任务数据联调。独立订单页复用首页已使用的 `orders`。
|
当前机巢模块共 **8 个正式页面,已实现 14 个业务接口及 1 个通用 STS 接口**。新增拍摄任务页复用已实现的 `shooting` API,接口总数不增加;它由任务页读取,准备页不直接调用。`shooting` 已取得类型 25 的真实响应;`tasks/create → shoot` 对任务 6 业务成功,但随后回查显示航线执行失败、禁止拍摄。任务页成功导航仍有网络替身测试覆盖;成片保存与 STS 上传流程仍待真实联调。独立订单页复用首页已使用的 `orders`。
|
||||||
|
|
||||||
| 页面/区域 | 提供人 | 方法与完整路径 | 当前状态 |
|
| 页面/区域 | 提供人 | 方法与完整路径 | 当前状态 |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
@@ -29,6 +29,10 @@
|
|||||||
| 机巢套餐收款页:生成小程序收款码 | 张工 | `POST /api/yf-handset-app/photog/multi-plane/pay-code` | 已接入 |
|
| 机巢套餐收款页:生成小程序收款码 | 张工 | `POST /api/yf-handset-app/photog/multi-plane/pay-code` | 已接入 |
|
||||||
| 收款记录页 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/receipts` | 已接入,支持分页 |
|
| 收款记录页 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/receipts` | 已接入,支持分页 |
|
||||||
| 拍摄准备页:已购套餐、点位、航线、次数 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/project-info` | 已接入 |
|
| 拍摄准备页:已购套餐、点位、航线、次数 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/project-info` | 已接入 |
|
||||||
|
| 拍摄准备页:机巢连接、推荐无人机状态与电量 | 朱工 | `GET /api/app/airport/plane-status` | 已接入,页面可见且 App 活跃时轮询 |
|
||||||
|
| 拍摄准备页:创建待飞任务并展示回执 | 张工 | `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 的航线执行失败、门禁阻止拍摄 |
|
||||||
| 订单素材库:整单摘要与点位标签 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/orders/detail` | 已接入 |
|
| 订单素材库:整单摘要与点位标签 | 张工 | `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/tasks` | 已接入,不分页 |
|
||||||
| 交付成片:订单权限与购买点位 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/orders/detail` | 复用已接入接口 |
|
| 交付成片:订单权限与购买点位 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/orders/detail` | 复用已接入接口 |
|
||||||
@@ -36,7 +40,7 @@
|
|||||||
| 交付成片:上传凭证 | 既有通用接口,张工文档指定复用 | `GET /api/app/config/get-sts-token` | 已实现,待本页真实上传联调 |
|
| 交付成片:上传凭证 | 既有通用接口,张工文档指定复用 | `GET /api/app/config/get-sts-token` | 已实现,待本页真实上传联调 |
|
||||||
| 交付成片:保存或替换成片 | 张工 | `POST /api/yf-handset-app/photog/multi-plane/tasks/film` | 已实现,待真实联调 |
|
| 交付成片:保存或替换成片 | 张工 | `POST /api/yf-handset-app/photog/multi-plane/tasks/film` | 已实现,待真实联调 |
|
||||||
|
|
||||||
准备页已停用朱工 `workbench`,历史响应保留在第 7.3 节。订单素材库见第 8 节;交付成片见第 9 节。飞行控制、批量下载和游客交付确认尚未接入,见第 10 节。
|
准备页已停用朱工 `workbench`,历史响应保留在第 7.3 节;召唤 `shoot` 见第 7.7 节。订单素材库见第 8 节;交付成片见第 9 节。到达后开始拍摄、暂停、返航、批量下载和游客交付确认尚未接入,见第 10 节。
|
||||||
|
|
||||||
## 3. 公共约定
|
## 3. 公共约定
|
||||||
|
|
||||||
@@ -286,7 +290,7 @@ API:[DroneDockAPI.swift](suixinkan/Features/DroneDock/API/DroneDockAPI.swift)
|
|||||||
|
|
||||||
切换分类从第 1 页重新请求,不在当前已加载页上做本地筛选。翻页继续传相同 `status`。数量取服务端 `total`,不以当前页条数替代;下一页失败保留已有订单并重试同一页。分类、账号、景区或门店变化后拒绝旧请求回填。
|
切换分类从第 1 页重新请求,不在当前已加载页上做本地筛选。翻页继续传相同 `status`。数量取服务端 `total`,不以当前页条数替代;下一页失败保留已有订单并重试同一页。分类、账号、景区或门店变化后拒绝旧请求回填。
|
||||||
|
|
||||||
卡片展示游客手机号、订单号、创建时间、套餐、已拍/总次数、剩余次数、进度条、素材与交付/确认摘要。状态取 `shoot_status`,次数取 `shoot_count/shot_count/remaining_count`;剩余 0 不自行判为已完成。未知次数显示“—”,不填 0。`can_create_task=true` 时进入现有真实准备页,跳转前不请求 `workbench`,也不创建任务;进入准备页后仅请求 `project-info`。“查看素材”进入真实订单素材库(第 8 节),页面出现后请求摘要与任务;“交付成片”已进入第 9 节共用页,交付确认入口仍提示暂未开放。
|
卡片展示游客手机号、订单号、创建时间、套餐、已拍/总次数、剩余次数、进度条、素材与交付/确认摘要。状态取 `shoot_status`,次数取 `shoot_count/shot_count/remaining_count`;剩余 0 不自行判为已完成。未知次数显示“—”,不填 0。`can_create_task=true` 时进入现有真实准备页,跳转前不请求 `workbench`,也不创建任务;进入准备页后读取 `project-info` 和 `plane-status`。“查看素材”进入真实订单素材库(第 8 节),页面出现后请求摘要与任务;“交付成片”已进入第 9 节共用页,交付确认入口仍提示暂未开放。
|
||||||
|
|
||||||
以下为本轮模拟器通过当前登录账号、景区 `271` 实际请求的脱敏响应;`pending` 的两条订单结构与 `all` 相同,完整样本见下方存档链接。
|
以下为本轮模拟器通过当前登录账号、景区 `271` 实际请求的脱敏响应;`pending` 的两条订单结构与 `all` 相同,完整样本见下方存档链接。
|
||||||
|
|
||||||
@@ -571,22 +575,35 @@ Debug 联调参数 `--dock-payment-probe` 下存在自动选首套餐生成码
|
|||||||
|
|
||||||
页面:[DroneDockRemotePreparationViewController.swift](suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift)
|
页面:[DroneDockRemotePreparationViewController.swift](suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift)
|
||||||
API:[DroneDockPreparationAPI.swift](suixinkan/Features/DroneDock/API/DroneDockPreparationAPI.swift)
|
API:[DroneDockPreparationAPI.swift](suixinkan/Features/DroneDock/API/DroneDockPreparationAPI.swift)
|
||||||
|
任务创建:[DroneDockTaskCreationAPI.swift](suixinkan/Features/DroneDock/API/DroneDockTaskCreationAPI.swift)
|
||||||
|
|
||||||
|
确认召唤:[DroneDockShootAPI.swift](suixinkan/Features/DroneDock/API/DroneDockShootAPI.swift)
|
||||||
|
|
||||||
|
任务状态(准备页不再调用):[DroneDockShootingAPI.swift](suixinkan/Features/DroneDock/API/DroneDockShootingAPI.swift)
|
||||||
购买模型:[DroneDockProjectInfoModels.swift](suixinkan/Features/DroneDock/Models/DroneDockProjectInfoModels.swift)
|
购买模型:[DroneDockProjectInfoModels.swift](suixinkan/Features/DroneDock/Models/DroneDockProjectInfoModels.swift)
|
||||||
状态:[DroneDockPreparationViewModel.swift](suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift)
|
状态:[DroneDockPreparationViewModel.swift](suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift)
|
||||||
|
|
||||||
### 7.1 调用顺序与数据归属
|
### 7.1 调用顺序与数据归属
|
||||||
|
|
||||||
1. 首页点击“开始拍摄”,先跳转到准备页。
|
1. 首页点击“开始拍摄”,先跳转到准备页。
|
||||||
2. 准备页出现后仅请求张工 `project-info`,读取已购配置;不请求定位,也不调用 `workbench`。
|
2. 准备页出现后分别请求张工 `project-info` 和朱工 `plane-status`,购买配置与设备状态独立更新;不请求定位,也不调用 `workbench`。
|
||||||
3. 请求结束后刷新 UI。页面下拉或点击“刷新状态”仅重新读取 `project-info`。
|
3. 页面下拉或点击“刷新状态”重新读取两个接口。无人机状态还在页面可见且 App 活跃时持续轮询,每次响应完成后等待 `poll_hint_ms` 建议间隔再请求,默认 5 秒并限制在 5~60 秒;不叠加未完成请求。
|
||||||
|
4. 离开页面或 App 失去活跃状态时取消状态请求与轮询,返回前台且页面可见时重新读取。状态接口失败会清除旧设备状态并显示未知,不清空已购配置或改变所选点位、航线。
|
||||||
|
5. 用户首次明确点击“确认并召唤”后,先重新请求 `project-info` 复核权限、次数和所选点位航线,再发送一次 `tasks/create`;创建成功后自动以返回的 `task_id` 作为朱工 `shoot.id` 提交召唤。召唤业务成功后自动跳转到拍摄任务页,传递同一个任务 ID、订单和景区身份。准备页仍保留两份回执。详见第 7.5~7.7 节。
|
||||||
|
6. 已有创建回执时保留该任务 ID。`shoot` 明确业务拒绝后允许“重试召唤”,只重试同任务的 `shoot`,不重建任务;召唤成功或结果未知时锁定再次提交。从任务页返回后,准备页按钮显示“查看拍摄任务”,再次点击只进入该任务,不重复创建或召唤。进入准备页、购买刷新和无人机轮询均不自动创建任务或发送召唤;`shooting` 由任务页出现后读取。
|
||||||
|
|
||||||
| 页面内容 | 权威数据来源 |
|
| 页面内容 | 权威数据来源 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 套餐名称、总次数、已拍次数、剩余次数、订单操作权限 | 张工 `project-info` 的根级订单摘要 |
|
| 套餐名称、总次数、已拍次数、剩余次数、订单操作权限 | 张工 `project-info` 的根级订单摘要;创建成功后优先使用 `tasks/create` 返回的最新订单摘要 |
|
||||||
| 可选点位、可选航线及可用性 | 张工 `project-info.spot` |
|
| 可选点位、可选航线及可用性 | 张工 `project-info.spot` |
|
||||||
| 点位封面 | `spot[].cover_url`;为空时使用中性占位 |
|
| 点位封面 | `spot[].cover_url`;为空时使用中性占位 |
|
||||||
| 样片元数据 | `air_lines[].samples` 已解析保留,当前准备页尚未新增样片播放入口 |
|
| 样片元数据 | `air_lines[].samples` 已解析保留,当前准备页尚未新增样片播放入口 |
|
||||||
| 机巢连接、工作状态、召唤门禁 | 实时读取入口尚待接入,保持未知,不据此允许召唤 |
|
| 机巢连接 | 朱工 `plane-status.connected`;true 已连接、false 未连接、缺失或请求失败待确认 |
|
||||||
|
| 无人机工作状态与电量 | 优先使用朱工 `plane-status.recommend.status_text`;不按设备列表自行重选推荐设备 |
|
||||||
|
| 待飞任务 ID 与创建结果 | 张工 `tasks/create.task_id` 及完整 `data` JSON;仅明确点击后创建 |
|
||||||
|
| 召唤提交结果 | 朱工 `shoot` 的业务成功/错误及实际 `data` JSON;已取得任务 6 成功样本,订单飞行任务 ID 读取 `order_flight_task.id`,见 7.7.2 |
|
||||||
|
| 任务状态与后续飞行阶段 | 拍摄任务页读取朱工 `shooting` 的任务摘要、`ui/execute_gate`、`current_plane` 和六项读数;准备页不直接读取,见 7.6 |
|
||||||
|
| 实际飞行执行 | 当前只接召唤提交,不执行 `start-shoot/command`;连接成功、空闲、`can_fly=true` 或召唤受理均不能表示已到达、已起飞或拍摄完成 |
|
||||||
| 距离、位置与范围 | 2026-10-29 产品确认移除相关展示,包括点位卡范围/米数/定位图标和底部范围状态,不保留“距离待确认”“位置待确认”占位 |
|
| 距离、位置与范围 | 2026-10-29 产品确认移除相关展示,包括点位卡范围/米数/定位图标和底部范围状态,不保留“距离待确认”“位置待确认”占位 |
|
||||||
| 点位已拍信息 | `project-info` 未提供;不使用历史 workbench 响应补充,缺失值保持未知 |
|
| 点位已拍信息 | `project-info` 未提供;不使用历史 workbench 响应补充,缺失值保持未知 |
|
||||||
|
|
||||||
@@ -745,9 +762,9 @@ API:[DroneDockPreparationAPI.swift](suixinkan/Features/DroneDock/API/DroneDock
|
|||||||
|
|
||||||
响应来源:[本地联调存档](docs/9.9.1/project-info-integration-2026-10-28/workbench-response.json)。
|
响应来源:[本地联调存档](docs/9.9.1/project-info-integration-2026-10-28/workbench-response.json)。
|
||||||
|
|
||||||
当前页面显示 `project-info` 返回的已购套餐、点位和航线;设备状态保持未知,距离与范围模块已移除,不再展示这次历史业务失败作为当前请求错误。
|
此前停用 `workbench` 后,页面使用 `project-info` 返回的已购套餐、点位和航线,设备状态保持未知。2026-10-29 已改由第 7.4 节 `plane-status` 提供实时设备状态;距离与范围模块仍已移除,不再展示这次历史业务失败作为当前请求错误。
|
||||||
|
|
||||||
**待朱工与张工确认:**类型 25 的实时设备、距离和召唤条件读取入口尚待接入。`project-info` 本身不提供这些实时设备字段,不能据此判断起飞条件满足。
|
**当前衔接:**按朱工 14:50 版合同,张工 `tasks/create` 的 `task_id` 作为朱工 `shoot` 的 `id`,见第 7.5、7.7 节;准备页不再调用 `shooting`。实时设备展示继续使用 `plane-status`,购买权限、设备展示状态或召唤请求被接受都不能据此判断实际起飞已经发生。
|
||||||
|
|
||||||
下面为**此前另一笔订单的历史成功响应节选**(2026-10-28 14:47:44),只用于说明旧 workbench 结构,不代表当前多点位订单已经支持。设备数组和点位数组各保留一项:
|
下面为**此前另一笔订单的历史成功响应节选**(2026-10-28 14:47:44),只用于说明旧 workbench 结构,不代表当前多点位订单已经支持。设备数组和点位数组各保留一项:
|
||||||
|
|
||||||
@@ -855,17 +872,385 @@ API:[DroneDockPreparationAPI.swift](suixinkan/Features/DroneDock/API/DroneDock
|
|||||||
|
|
||||||
这次历史请求未传经纬度,却返回约 3311 公里及 `in_range=false`。当前准备页不再读取或使用这类 workbench 距离/范围结果。后续对接实时入口时,需明确无定位的未知值语义,以及坐标系和范围校验规则。
|
这次历史请求未传经纬度,却返回约 3311 公里及 `in_range=false`。当前准备页不再读取或使用这类 workbench 距离/范围结果。后续对接实时入口时,需明确无定位的未知值语义,以及坐标系和范围校验规则。
|
||||||
|
|
||||||
### 7.4 “确认并召唤”的当前边界
|
### 7.4 底部无人机状态:朱工 plane-status
|
||||||
|
|
||||||
准备页目前只完成信息读取和本地选择,**“确认并召唤”按钮仍禁用**,没有发送以下请求:
|
API:[DroneDockPlaneStatusAPI.swift](suixinkan/Features/DroneDock/API/DroneDockPlaneStatusAPI.swift)
|
||||||
|
|
||||||
- 张工 `POST /api/yf-handset-app/photog/multi-plane/tasks/create`。
|
模型:[DroneDockPlaneStatusModels.swift](suixinkan/Features/DroneDock/Models/DroneDockPlaneStatusModels.swift)
|
||||||
- 朱工 `POST /api/app/airport/shoot`。
|
|
||||||
- 朱工 `POST /api/app/airport/start-shoot`。
|
|
||||||
|
|
||||||
后续先统一任务创建与绑定:张工 `tasks/create` 创建待飞任务并要求飞行模块复用 `task_id`;朱工文档的 `shoot` 仍描述自行创建任务。不能直接把两者串接而重复创建。`start-shoot` 属于到达后的开始拍摄,不应在进入准备页时调用。
|
`GET /api/app/airport/plane-status?scenic_id=271&live_battery=1`
|
||||||
|
|
||||||
以上接口尚无本轮真实成功 JSON,本记录不编造召唤响应。
|
| 参数 | 当前使用 |
|
||||||
|
| --- | --- |
|
||||||
|
| `scenic_id` | 当前景区,必须为正整数;响应景区必须一致 |
|
||||||
|
| `live_battery` | 显式传 `1`,请求实时电量 |
|
||||||
|
|
||||||
|
不传订单号、项目 ID、门店 ID、经纬度或任务 ID。底栏使用服务端推荐设备的 `recommend.status_text`;该文案缺失时仅组合后端的 `work_status_label` 和 `battery_label`,不把缺失电量补为 0。无设备显示“暂无无人机”,有设备但没有推荐设备时显示“状态待确认”。`work_status` 的 1 显示绿色、2 显示橙色、0 或未知显示灰色;此枚举使用本接口约定,不套用首页状态。
|
||||||
|
|
||||||
|
**实测响应:2026-10-29 11:06:12,HTTP 200、业务码 100000。** 景区 271 返回三台设备:58 空闲、电量 93%,61 和 57 离线且电量未知;推荐设备为 58,`connected=true`。模拟器底栏已显示“机巢已连接”和“空闲 · 电量 93%”。以下截取推荐设备及整体状态,`planes` 完整三条记录见脱敏存档:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 100000,
|
||||||
|
"data": {
|
||||||
|
"connected": true,
|
||||||
|
"has_idle": true,
|
||||||
|
"has_shooting": false,
|
||||||
|
"poll_hint_ms": 5000,
|
||||||
|
"recommend": {
|
||||||
|
"battery_label": "电量 93%",
|
||||||
|
"battery_percent": 93,
|
||||||
|
"can_fly": true,
|
||||||
|
"id": 58,
|
||||||
|
"is_receive_order": 1,
|
||||||
|
"name": "测试设备 58",
|
||||||
|
"online_status": 1,
|
||||||
|
"sn_number": "TEST-PLANE-58",
|
||||||
|
"status_text": "空闲 · 电量 93%",
|
||||||
|
"task_type": null,
|
||||||
|
"work_status": 1,
|
||||||
|
"work_status_label": "空闲"
|
||||||
|
},
|
||||||
|
"scenic_id": 271
|
||||||
|
},
|
||||||
|
"msg": "success",
|
||||||
|
"time": "2026-10-29 11:06:12"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
完整响应来源:[plane-status-redacted.json](docs/9.9.1/plane-status-integration-2026-10-29/plane-status-redacted.json)。仅将设备名称和序列号替换为测试值,其余字段、顺序、类型、空串与 null 保持实测内容。请求仅用于只读展示,不恢复定位、`workbench` 或召唤写入。
|
||||||
|
|
||||||
|
验证:模拟器构建、真实响应显示通过,相关 **49 项不同测试通过**(plane-status API/Model 10、准备页 ViewModel 28、页面 11)。覆盖推荐状态与电量、连接/离线/未知、错误恢复、轮询与手动刷新、前后台及离开取消、购买配置独立更新,以及账号/景区变化时撤下旧点位和航线。
|
||||||
|
|
||||||
|
### 7.5 “确认并召唤”:张工 tasks/create,创建后调用召唤
|
||||||
|
|
||||||
|
`POST /api/yf-handset-app/photog/multi-plane/tasks/create`
|
||||||
|
|
||||||
|
**创建已实测成功:11:56:26 创建任务 1;16:03:01 按用户明确要求重新创建一次,返回任务 6。** 当前流程使用创建回执 ID 调用朱工 `shoot`;任务 6 于 16:03:31 的召唤接口业务成功,16:04:52 回查显示航线执行失败,详见 7.7.2。成功后自动进入拍摄任务页的客户端流程由网络替身验证;准备页保留两份回执,返回后可查看原任务。新任务 6 是用户明确要求的一次新建,不是对任务 2 失败的自动重建或重试。本轮未调用 `start-shoot/command`。
|
||||||
|
|
||||||
|
| 参数 | 必填 | 当前来源 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `scenic_id` | 是 | 当前景区 ID |
|
||||||
|
| `order_number` | 是 | 进入准备页时选中的订单号,最长 128 字符 |
|
||||||
|
| `scenic_spot_id` | 是 | 当前选择的已购可用点位 ID |
|
||||||
|
| `air_line_id` | 是 | 当前点位下选择的已购可用航线 ID |
|
||||||
|
|
||||||
|
ID 必须为正整数。请求仅包含上述四项,不传 `project_id`、无人机 ID、门店 ID、经纬度或起飞控制参数。
|
||||||
|
|
||||||
|
**实测请求(景区 271,订单号已脱敏):**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"scenic_id": 271,
|
||||||
|
"order_number": "TEST-ORDER-004",
|
||||||
|
"scenic_spot_id": 412,
|
||||||
|
"air_line_id": 302
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
创建流程与按钮条件:
|
||||||
|
|
||||||
|
1. 已成功加载当前订单购买配置,身份和订单项目对应;`can_create_task=true`、总次数有效且大于 0、剩余次数大于 0;所选点位与航线的 `available` 均明确为 true 时,允许首次点击。先创建待飞任务再提交召唤,不以 `plane-status` 的连接、电量或 `can_fly` 作为创建门槛。
|
||||||
|
2. 点击后立即禁用重复提交并冻结点位航线,重新读取张工 `project-info`。如权限或次数已失效,则不发送 POST;原选择已失效时提示重新选择,不把此次点击自动转交给另一条航线。
|
||||||
|
3. 预检通过后只发送一次 `tasks/create`。响应校验任务 ID 及订单归属,页面展示返回的 `data`,保留未建模字段;不拼造 `code/msg/time` 或飞行状态。创建后的次数以返回的最新订单摘要为准,客户端不自行扣次。
|
||||||
|
4. 创建成功后自动以同一个 `task_id` 请求 `shoot`,提交期间显示“正在召唤无人机…”并禁用重复点击。已创建任务始终保留创建回执及防重建锁;召唤重试也不会再发送 `tasks/create`。普通购买刷新、设备轮询、同实例离开返回均不清除此锁。
|
||||||
|
5. 创建被后端明确业务拒绝时展示其错误,允许用户再次点击;购买预检失败尚未发出 POST,可重试。创建 POST 超时、网络/HTTP/解码错误,以及提交后取消或离开而结果未知时,显示“结果待核对”并保留防重复锁,不自动重发,也不继续调用 `shoot`。需先核对订单任务,再决定后续处理;本轮不增加未知创建结果的自动核对接口或任务重建流程。
|
||||||
|
6. 账号、Token、景区或门店变化后拒绝迟到回执,旧页面实例不能恢复创建入口。
|
||||||
|
|
||||||
|
**实测完整响应:HTTP 200,业务码 100000。仅订单号和手机号脱敏。**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 100000,
|
||||||
|
"data": {
|
||||||
|
"can_confirm": false,
|
||||||
|
"can_create_task": true,
|
||||||
|
"can_upload_film": true,
|
||||||
|
"confirm_status": 0,
|
||||||
|
"confirmed_at": null,
|
||||||
|
"created_at": "2026-10-27 17:39:10",
|
||||||
|
"film_count": 0,
|
||||||
|
"material_status": 0,
|
||||||
|
"order_number": "TEST-ORDER-004",
|
||||||
|
"order_status": 20,
|
||||||
|
"project_id": 386,
|
||||||
|
"project_name": "多点位航拍",
|
||||||
|
"remaining_count": 5,
|
||||||
|
"shoot_count": 5,
|
||||||
|
"shoot_status": "processing",
|
||||||
|
"shot_count": 0,
|
||||||
|
"task_id": 1,
|
||||||
|
"user_phone": "130****0004"
|
||||||
|
},
|
||||||
|
"msg": "success",
|
||||||
|
"time": "2026-10-29 11:56:26"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
张工约定:待飞任务不预占额度、不增加已成功拍摄次数;没有请求去重参数。返回的 `task_id` 是订单飞行任务 ID,飞行模块复用并更新该任务,不能再新建另一条订单任务。当前将该 ID 传给朱工 `shoot` 提交召唤;`start-shoot` 属于到达后的开始拍摄,当前不调用。
|
||||||
|
|
||||||
|
**此前单独创建阶段的实测记录:**完整响应见 [tasks-create-redacted.json](docs/9.9.1/task-create-integration-2026-10-29/tasks-create-redacted.json)。实际返回 `task_id=1`,订单进入 `processing`,已拍摄仍为 0、剩余 5,`can_upload_film=true`。创建时没有扣减次数。当时日志确认仅发出一次 `tasks/create` 写请求,没有朱工飞行接口调用;页面原位展示完整 data,按钮当时为“任务已创建”。随后曾改为同任务 `shooting` 读取,现已按上述规则改为同任务 `shoot` 召唤;未将历史创建响应写成新的创建记录。
|
||||||
|
|
||||||
|
此前创建阶段验证:模拟器构建及真实请求通过;相关 **64 项不同测试全部通过**(创建 API/Model 8、创建 ViewModel 14、准备页 ViewModel 28、页面 14)。覆盖提交参数、创建前复核、完整 JSON、成功/错误回显、单次 POST、重复点击锁、业务拒绝重试、未知结果锁及不跳页。真实环境只创建一次,未用真实订单重复执行成功测试。此前读取串接验证见第 7.6 节;当前召唤串接说明见第 7.7 节。
|
||||||
|
|
||||||
|
**任务 6 最新创建记录(2026-10-29 16:03:01):**先通过 `orders/detail` 与 `project-info` 确认同订单 `TEST-ORDER-004`、项目 386 的剩余次数为 5、`can_create_task=true`,点位 412 和航线 302 均可用,再发送上述四字段请求。返回 `code=100000`、`task_id=6`、`shoot_count=5`、`shot_count=0`、`remaining_count=5`,未因创建扣次。完整脱敏响应:[create-task6-redacted.json](docs/9.9.1/task-create-integration-2026-10-29/create-task6-redacted.json)。
|
||||||
|
|
||||||
|
### 7.6 拍摄任务页:朱工 shooting(含历史联调记录)
|
||||||
|
|
||||||
|
页面:[DroneDockShootingTaskViewController.swift](suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift)
|
||||||
|
|
||||||
|
状态:[DroneDockShootingTaskViewModel.swift](suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift)
|
||||||
|
|
||||||
|
API:[DroneDockShootingAPI.swift](suixinkan/Features/DroneDock/API/DroneDockShootingAPI.swift)
|
||||||
|
|
||||||
|
`GET /api/app/airport/shooting?id=<tasks/create 返回的 task_id>&live_battery=1`
|
||||||
|
|
||||||
|
**当前状态:真实拍摄任务页已接入,类型 25 已读取成功;最新任务 6 的召唤后回查显示航线执行失败、禁止拍摄,见 7.7.2。** 朱工 2026-10-29 14:50 版文档约定根据外部已创建的 `order_flight_task.id` 反查任务、航线、点位、景区及飞机信息;该接口只读任务,不创建或召唤。准备页在 `shoot` 业务成功后自动进入此页,首次 GET 在任务页实际出现后发送;任务 ID 始终来自同次创建回执。DEBUG 只读入口还可读取明确已存在的测试任务,不代表已执行召唤。
|
||||||
|
|
||||||
|
| 参数 | 必填 | 当前来源 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `id` | 是 | 已明确创建成功的 `tasks/create.data.task_id`,不是订单号、点位 ID 或航线 ID |
|
||||||
|
| `live_battery` | 否 | 当前显式发送 `1`;布尔查询使用 `1/0` 编码 |
|
||||||
|
|
||||||
|
该 GET 不发送 JSON body,不额外传景区、订单、点位、航线或经纬度参数。任务页只注入查询服务,没有创建、召唤或飞行控制依赖。
|
||||||
|
|
||||||
|
**当前布局与状态动作:**顶部固定显示订单摘要、16:9 图传占位和六项读数,底部固定保留安全控制;加载、错误或业务状态变化不改变这两块区域的位置。中间占用剩余高度,按加载、前往、就绪、拍摄、暂停、返航、完成、失败、阻止、未知或读取错误组合图标、标题、说明、设备状态和主操作,没有滚动容器,也不使用整体 transform 缩放。
|
||||||
|
|
||||||
|
空间不足时收紧间距、图标和字号,正文不小于 12 点,操作点击高度不小于 44 点;紧凑布局可隐藏设备摘要、截断长文案,通过“详情”查看完整说明。未确认或冲突状态显示待确认,不补造进度。开始/恢复拍摄及底部暂停/返航仍是禁用状态,不调用控制接口;只有明确完成态提供“查看素材”,进入当前订单的真实订单素材库。
|
||||||
|
|
||||||
|
2026-10-29 16:56 模拟器重新运行此固定布局页面,只读 `shooting?id=6&live_battery=1` 一次。真实回执仍显示航线执行失败、当前设备离线,页面如实展示错误原因与当前六项读数;没有调用创建、召唤或飞行控制。本地截图(不纳入 Git):`docs/9.9.1/shooting-integration-2026-10-29/task6-fixed-layout-real.jpg`。
|
||||||
|
|
||||||
|
固定布局阶段验证:模拟器构建成功,相关 **52 项不同测试通过**(任务 API 12、任务 ViewModel 10、任务页面 12、布局 7、阶段展示 9、准备页串接 1、共用遥测旧页面回归 1)。首轮错误文案用例遗漏通用网络错误前缀,修正测试预期后阶段展示 9 项复跑通过;实际内容区域 `375×603`、`402×734` 的布局 7 项再次通过。覆盖 11 种展示状态、长文案与详情、固定区域不随加载/状态/遥测变化、最小点击尺寸、完成态素材导航、单次 GET 及无轮询。阶段组合使用匿名替身验证;真实任务仍处于失败态,没有模拟飞控执行成功。
|
||||||
|
|
||||||
|
**当前刷新与生命周期(按用户要求取消任务页定时轮询):**
|
||||||
|
|
||||||
|
1. 每次进入任务页且 App 活跃时读取一次;返回前台且任务页仍可见时读取一次。不设定时器,不按 5 秒或 `plane_status.poll_hint_ms` 自动重复请求,不叠加未完成请求。
|
||||||
|
2. 已移除下拉刷新;点击导航栏刷新按钮、中间状态区的“刷新状态”或错误后的“重新读取”,各只 GET 同一个任务 ID 一次。读取失败撤下旧任务状态、执行门禁和读数,显示错误,不自动重试;后续进入页面、返回前台或手动刷新仍只读,不重建任务或重新召唤。
|
||||||
|
3. 离开任务页或 App 失去活跃状态时取消进行中的请求,清除旧快照并拒绝迟到响应;不在后台或页面不可见时读取。
|
||||||
|
4. 响应内提供的任务 ID、订单号、景区 ID 均与页面身份核对;账号、Token、景区或门店变化后不再使用旧页面读取。
|
||||||
|
5. 返回同一个准备页实例后保留创建和召唤回执,按钮为“查看拍摄任务”;再次点击仅导航到原任务,没有第二次 `tasks/create` 或 `shoot`。自动跳转对同一任务只触发一次。
|
||||||
|
|
||||||
|
**文档字段结构与页面使用:**以下字段来自朱工合同及 15:07 的真实响应,未返回的展示值保持未知;完整 `data` 保留原始 JSON,当前页面按字段展示,不额外铺开 JSON 文本。
|
||||||
|
|
||||||
|
| 返回字段 | 当前解析与展示 |
|
||||||
|
| --- | --- |
|
||||||
|
| `order_type/order_type_label`、`order_flight_task`、`task` | 保留订单类型、任务 ID、状态、航线任务关联等;合同任务状态为 10 待执行、20 执行中、30 成功、40 失败、50 取消、60 待确认,不从 GET 成功推导飞行完成 |
|
||||||
|
| `header.title` | 顶部标题;缺失时组合当前响应的点位和航线名称,仍缺失则显示“拍摄任务” |
|
||||||
|
| `header.tourist_label/package_name` | 顶部游客与套餐;仅缺失时使用入口订单摘要,不覆盖后端已返回文案;当前套餐口径冲突见下文 |
|
||||||
|
| `scenic`、`scenic_spot`、`air_line` | 解析景区、点位与航线摘要;用于身份核对和缺失标题的备用文本 |
|
||||||
|
| `current_plane.status_text/work_status_label` | 展示接口返回的任务设备状态;不使用准备页或 `plane_status.recommend` 自行替换 |
|
||||||
|
| `metrics[]` | 展示 `battery/env_temp/wind_speed/rainfall/signal/satellite` 六项,使用服务端文案及单位,0 为有效值,缺失显示“—” |
|
||||||
|
| `plane_status` | 保留设备列表、推荐设备、连接状态及原始 `poll_hint_ms`;任务页不再使用该建议间隔驱动请求,不作为派机或起飞许可 |
|
||||||
|
| `ui.title/message` | 结合任务、航线状态与门禁确定当前显示阶段;保留后端说明,缺失时使用 execute_gate.message。长文案在固定中间区域省略,详情可查看完整文字;不将任务总状态 20 直接当作正在拍摄 |
|
||||||
|
| `execute_gate`、`ui.primary_action/commands` | 保留门禁、原因及建议动作;开始/恢复拍摄和底部暂停/返航禁用,不发控制请求;明确完成态提供“查看素材”进入当前订单素材库,其余可读状态提供单次刷新 |
|
||||||
|
| 图传区域 | 显示“图传暂未接入”的中性占位;未调用 `/airport/live`,不填充演示画面 |
|
||||||
|
|
||||||
|
**真实成功响应:2026-10-29 15:07:25,HTTP 200、业务码 100000。** 只读已存在的 `task_id=1`,没有新的 `tasks/create` 或真实 `shoot` POST。完整响应见 [shooting-success-redacted.json](docs/9.9.1/shooting-integration-2026-10-29/shooting-success-redacted.json);以下为关键字段节选,省略字段不表示原响应缺失:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 100000,
|
||||||
|
"data": {
|
||||||
|
"order_type": 25,
|
||||||
|
"order_type_label": "多点位航拍",
|
||||||
|
"order_flight_task": {
|
||||||
|
"id": 1,
|
||||||
|
"order_number": "TEST-ORDER-004",
|
||||||
|
"scenic_id": 271,
|
||||||
|
"scenic_spot_id": 412,
|
||||||
|
"air_line_id": 302,
|
||||||
|
"status": 10,
|
||||||
|
"status_label": "待执行",
|
||||||
|
"plane_id": 0,
|
||||||
|
"airport_sn": "",
|
||||||
|
"wayline_task_id": 0
|
||||||
|
},
|
||||||
|
"header": {
|
||||||
|
"order_number": "TEST-ORDER-004",
|
||||||
|
"title": "天门寻梦 · 天门寻梦",
|
||||||
|
"tourist_label": "游客 130****0004",
|
||||||
|
"package_name": "单次航拍 · 含 1 次拍摄",
|
||||||
|
"shot_total": 1,
|
||||||
|
"shot_remain": 1
|
||||||
|
},
|
||||||
|
"current_plane": {
|
||||||
|
"id": 58,
|
||||||
|
"name": "测试设备 58",
|
||||||
|
"sn_number": "TEST-PLANE-58",
|
||||||
|
"status_text": "空闲 · 电量 93%"
|
||||||
|
},
|
||||||
|
"metrics": [
|
||||||
|
{ "key": "battery", "value": "93%", "raw": 93 },
|
||||||
|
{ "key": "env_temp", "value": "—", "raw": null },
|
||||||
|
{ "key": "wind_speed", "value": "0m/s", "raw": 0 },
|
||||||
|
{ "key": "rainfall", "value": "—", "raw": null },
|
||||||
|
{ "key": "signal", "value": "—", "raw": null },
|
||||||
|
{ "key": "satellite", "value": "32颗", "raw": 32 }
|
||||||
|
],
|
||||||
|
"plane_status": { "scenic_id": 271, "connected": true, "poll_hint_ms": 5000 },
|
||||||
|
"execute_gate": {
|
||||||
|
"can_execute": false,
|
||||||
|
"code": "wayline_missing",
|
||||||
|
"message": "航线任务未关联,请先完成召唤起飞",
|
||||||
|
"primary_action": "blocked"
|
||||||
|
},
|
||||||
|
"ui": {
|
||||||
|
"phase": "blocked",
|
||||||
|
"title": "航线任务未关联,请先完成召唤起飞",
|
||||||
|
"message": "航线任务未关联,请先完成召唤起飞",
|
||||||
|
"primary_action": "blocked"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"msg": "success",
|
||||||
|
"time": "2026-10-29 15:07:25"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
任务 1 在 15:07:25 采样时为**待执行**,`plane_id=0`、`airport_sn=""`、`wayline_task_id=0`,`execute_gate.can_execute=false`。这是未实发 `shoot` 时的只读结果;`current_plane` 返回空闲 93% 不能证明任务已锁定飞机、已经召唤或正在飞行。响应中的暂停、返航 `ui.commands` 仍不执行;当前底部安全控制仅保留禁用占位。
|
||||||
|
|
||||||
|
**待两位后端核对:**同一响应根级为 `order_type=25`“多点位航拍”,但 `header.package_name` 为“单次航拍 · 含 1 次拍摄”,`shot_total/shot_remain=1`;张工同订单购买/创建摘要为“多点位航拍”、总次数 5、剩余 5。请朱工与张工统一任务页 header 的套餐和次数来源。客户端目前按 `header` 展示任务页文案,不用它覆盖张工购买权限或整单次数,也不把该差异解释成已扣 4 次。
|
||||||
|
|
||||||
|
历史任务页接入阶段验证(当时含定时轮询,现已取消):模拟器构建、运行及任务 1 真实读取通过,**61 项不同相关测试全部通过**。首轮 60 项通过,1 项因错误文案断言漏掉统一前缀失败;修正断言后重跑任务页 ViewModel 全部 11 项通过,其余 50 项对应代码未改动。覆盖创建/召唤后同任务导航、返回查看不重复 POST、只读刷新、轮询前后台与离页取消、身份核对及失败撤下旧数据。模拟器实际显示六项“93%、—、0m/s、—、—、32颗”和待召唤的阻止原因;实点刷新仍只 GET `id=1&live_battery=1`。真实页面截图保留本地(不纳入 Git):`docs/9.9.1/shooting-integration-2026-10-29/shooting-task-real.jpg`。该阶段没有真实召唤或飞行控制 POST;写入和成功导航用网络替身验证。之后任务 2 的真实召唤拒绝记录见第 7.7 节。
|
||||||
|
|
||||||
|
此前取消任务页定时轮询阶段验证(当时仍有下拉刷新,现已移除):模拟器构建及 **21 项相关测试全部通过**(任务页页面 9、任务页 ViewModel 10、准备页跳转与同任务读取 2)。覆盖停留超过原五秒周期仍仅一次 GET、进入/恢复前台各一次、重复前台通知不重复读取、按钮与下拉刷新、并发抑制、离开取消与迟到响应隔离。准备页 `plane-status` 的原有轮询规则见 7.1、7.4,继续保留。
|
||||||
|
|
||||||
|
#### 7.6.1 历史:准备页直接读取及类型 25 失败
|
||||||
|
|
||||||
|
此前准备页的调用与重试规则(已停用):
|
||||||
|
|
||||||
|
1. 首次主按钮按 `project-info → tasks/create → shooting` 顺序执行;`shooting.id` 必须来自该次创建成功回执。
|
||||||
|
2. 读取成功后按钮为“刷新任务状态”,再次点击只 GET 同一个 ID;读取失败则保留创建回执,按钮为“重试读取任务”,同样只 GET 同一个 ID。读取失败不会设置“创建结果未知”,也不会补发创建请求。
|
||||||
|
3. 串接与读取期间禁用主按钮,点位航线保持原创建归属;页面进入、购买刷新、无人机轮询均不触发额外 `shooting` 请求,也没有自动重试。
|
||||||
|
4. 页面离开或任务取消后拒绝迟到读取响应,已创建 ID 保留用于同实例后续重读;账号、Token、景区或门店变化时撤下旧回执并禁止旧页面继续操作。
|
||||||
|
5. GET 成功只代表任务信息已读取,不能宣告已召唤、已起飞或拍摄完成。当时不调用 `shoot`、`start-shoot`、`command`,不导航至拍摄任务页。
|
||||||
|
|
||||||
|
**实测请求与失败响应:2026-10-29 14:14:42。** 对上轮已创建的 `task_id=1` 读取,未再次创建任务。第一次发送 `live_battery=true`,后端返回 `code=100099` 和 `The live battery field must be true or false`;改为 `1/0` 编码后发送以下请求,参数校验通过后仍被类型 25 业务校验拒绝。
|
||||||
|
|
||||||
|
`GET /api/app/airport/shooting?id=1&live_battery=1`
|
||||||
|
|
||||||
|
HTTP 200,完整业务响应:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 100099,
|
||||||
|
"data": [],
|
||||||
|
"msg": "多点位航拍请使用专用订单接口",
|
||||||
|
"time": "2026-10-29 14:14:42"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
该轮真实验证只有上述两次 GET,没有 `tasks/create` POST 或飞行控制调用。随后朱工 14:50 版合同明确类型 25 支持,15:07:25 对同一任务的新 GET 已真实成功,见上文。保留这份旧失败供追溯,不表示新版仍拒绝类型 25,也不将历史 HTTP 200 记为业务成功。真实失败响应文件:[shooting-rejected.json](docs/9.9.1/shooting-integration-2026-10-29/shooting-rejected.json)。
|
||||||
|
|
||||||
|
此前读取串接阶段验证:模拟器构建通过;相关 **83 项不同测试全部通过**(shooting API/Model 8、shooting 串接 ViewModel 10、创建 API/Model 8、创建 ViewModel 14、准备页 ViewModel 28、页面 15)。包括创建后携同一 ID 读取、GET 失败后不重建、并发点击、取消/身份切换、原始 JSON 回显、购买读取失败仍保留任务回执。该阶段测试中的成功回执均为匿名替身,当时尚无真实成功响应;后续 15:07 的真实成功记录单列于上文。
|
||||||
|
|
||||||
|
### 7.7 “确认并召唤”:朱工 shoot,复用已创建任务
|
||||||
|
|
||||||
|
API:[DroneDockShootAPI.swift](suixinkan/Features/DroneDock/API/DroneDockShootAPI.swift)
|
||||||
|
|
||||||
|
回执:[DroneDockShootModels.swift](suixinkan/Features/DroneDock/Models/DroneDockShootModels.swift)
|
||||||
|
|
||||||
|
`POST /api/app/airport/shoot`
|
||||||
|
|
||||||
|
**当前省略 `plane_id`,请求仅发送 `id/restart`;任务 6 于 16:03:31 返回真实业务成功,完整 JSON 见 7.7.2。** 此接口提交召唤,不是任务页的状态查询。准备页当前顺序为:用户明确点击 → `project-info` 复核 → 张工 `tasks/create` → 朱工 `shoot`。创建失败或创建结果未知时不继续召唤。最初按朱工 14:50 文档发送 `plane_id=0` 的实现和仅网络替身验证属于历史阶段,真实联调结果见下文。
|
||||||
|
|
||||||
|
| 参数 | 当前 App 发送 | 来源与含义 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `id` | 必填,正整数 | 同次张工 `tasks/create` 成功回执的 `task_id`,即已建 `order_flight_task.id` |
|
||||||
|
| `plane_id` | 省略 | 按用户最终指示不传该字段;不发送 `0`、`null` 或 `recommend.id` |
|
||||||
|
| `restart` | 固定 `false` | 本轮不发重新开始指令 |
|
||||||
|
| `air_line_id` | 省略 | 复用已创建任务上绑定的航线;不发送文档示例中的 `0` 覆盖值 |
|
||||||
|
|
||||||
|
**当前客户端请求格式及最新成功请求(2026-10-29 16:03:31):**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"restart": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
请求不额外传 `plane_id`、`order_number`、`scenic_id`、`scenic_spot_id` 或经纬度。朱工 14:50 合同原约定 `plane_id=0` 时按任务景区派机,并将 `plane_id/airport_sn` 写回任务占位;已有锁定时复用。该参数约定与 15:26 的真实校验不一致;当前省略字段已在任务 6 的真实成功回执中返回飞机 61,仍需朱工将文档与实际参数约定统一。召唤成功后的任务使用唯一锁定飞机,后续 `shooting/start-shoot/command` 以该任务飞机为准;本轮客户端已接任务页 `shooting` 查询,尚不接 `start-shoot/command` 控制动作。
|
||||||
|
|
||||||
|
提交、回显与重试规则:
|
||||||
|
|
||||||
|
1. 创建与召唤提交期间禁用重复点击并冻结点位航线;创建回执一旦成功保留任务 ID,后续不能重新调用 `tasks/create`。
|
||||||
|
2. 准备页保留张工创建回执和朱工召唤的成功状态、实际 `data` 或错误;召唤成功且页面仍可见、App 活跃时,自动跳转到同一任务的拍摄任务页,由该页开始 GET `shooting`。返回后按钮为“查看拍摄任务”,只重新进入同一任务;不调用 `start-shoot/command`。
|
||||||
|
3. `shoot` 返回 HTTP 成功且业务 `code=100000` 时,记录“召唤请求已提交”,锁定再次发送并开放任务查看入口。此成功仅表示接口受理,不推断已起飞、已到达、正在拍摄或拍摄完成。
|
||||||
|
4. 朱工明确业务拒绝时保留创建任务,允许用户点击“重试召唤”;只对同一个任务 ID 重试 `shoot`,不重新预检购买配置或重建任务。
|
||||||
|
5. `shoot` 的网络、HTTP、解码错误,或请求发出后取消、离开等导致结果未知时,显示“召唤结果待核对”并锁定重发。成功与未知结果均不会因普通刷新、轮询或同页面实例返回而重新发送。需先核对任务实际状态,再决定后续处理;本轮没有实现未知结果的自动查询或重发流程。
|
||||||
|
6. 账号、Token、景区、门店变化后拒绝迟到回执,撤下旧回执并禁止旧页面继续操作。页面出现、刷新购买配置和设备轮询本身不触发召唤写入。
|
||||||
|
|
||||||
|
**返回 JSON 处理:**朱工当前文档没有提供 `shoot` 成功 `data` 的确定字段结构,因此保留实际返回的任意 JSON 值(对象、数组、字符串、数值、布尔或 null),不预设 `task_uuid`、飞机、到达状态等字段,也不补造外层 `code/msg/time`。业务明确成功但 `data` 为 null 或缺失时,仍可记为召唤提交成功,并说明无返回数据;不生成假 `{}`、假任务详情或假飞行状态。最新任务 6 已返回对象型成功 `data`,结构与 ID 含义见 7.7.2;客户端仍保留完整实际 JSON,不假设每次都具有相同字段。
|
||||||
|
|
||||||
|
#### 7.7.1 历史真实召唤拒绝:任务 2
|
||||||
|
|
||||||
|
**2026-10-29 15:26:18,用户提供的真实日志:**请求 `POST /api/app/airport/shoot`,body 为:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"plane_id": 0,
|
||||||
|
"restart": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
响应 HTTP 200、业务 `code=100099`,`msg="The plane id must be at least 1."`。这表明当时后端校验拒绝 `plane_id=0`,不能视作召唤成功。用户最初提出改用 `recommend.id`,随后明确改为“不传 plane_id 试一下”;当前以最后指示为准,未采用推荐设备 ID 方案。
|
||||||
|
|
||||||
|
**2026-10-29 15:34:31,按最终指示实测省略 `plane_id`:**使用当前模拟器账号,先只读确认已有任务 2 为待执行、`plane_id=0`、`wayline_task_id=0`,随后只发送一次上方 `{"id":2,"restart":false}` 的真实 POST,没有新建任务或自动重试。HTTP 200,完整业务响应如下:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 100099,
|
||||||
|
"msg": "不支持的订单类型",
|
||||||
|
"data": [],
|
||||||
|
"time": "2026-10-29 15:34:31"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
原响应文件:[shoot-without-plane-rejected.json](docs/9.9.1/shooting-integration-2026-10-29/shoot-without-plane-rejected.json),不含需要脱敏的身份字段,保留原文。省略字段后得到订单类型拒绝,说明本次仍未成功召唤;不能据此认定派机、锁定飞机或后续导航已在真实环境成功。
|
||||||
|
|
||||||
|
**15:34 阶段记录的待朱工修改/确认事项(保留历史):**`shoot` 需要支持张工 `tasks/create` 已创建的类型 25 `order_flight_task.id`,复用该任务及已选航线;当时需修复“不支持的订单类型”,并明确省略 `plane_id` 时的服务端派机规则。此问题发生在 `shoot`,与 15:07 已读取成功的 `shooting` 不同。后端修改后再按同任务核对,不因该拒绝重新创建任务或自动连续重发。
|
||||||
|
|
||||||
|
**2026-10-29 15:41:41,后端告知已修改后的再次验证:**按用户指示,先 GET 确认任务 2 仍为待执行、`plane_id=0`、`wayline_task_id=0`,再只发送一次 `POST /api/app/airport/shoot`,body 仍为 `{"id":2,"restart":false}`。HTTP 200,业务返回仍为 `code=100099`、`msg="不支持的订单类型"`、`data=[]`,尚未召唤成功;没有创建新任务或自动重试。完整响应见 [shoot-without-plane-retry-rejected-154141.json](docs/9.9.1/shooting-integration-2026-10-29/shoot-without-plane-retry-rejected-154141.json)。需后端核对测试环境实际生效版本及类型 25 处理路径;仅凭本次响应不能确定是否部署问题。
|
||||||
|
|
||||||
|
**2026-10-29 15:58:52,用户再次明确要求验证后的结果:**15:58:27 先 GET 确认已有任务 2 仍为待执行、`plane_id=0`、`wayline_task_id=0`,随后仅发送一次 `POST /api/app/airport/shoot`,body 为 `{"id":2,"restart":false}`,未传 `plane_id`。HTTP 200,完整业务响应如下:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 180031,
|
||||||
|
"msg": "无法获取机场状态,暂时不可起飞",
|
||||||
|
"data": [],
|
||||||
|
"time": "2026-10-29 15:58:52"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
原响应文件:[shoot-airport-state-rejected-155852.json](docs/9.9.1/shooting-integration-2026-10-29/shoot-airport-state-rejected-155852.json),不含需要脱敏的身份字段,按原文保存。本次没有新建任务或自动重试,没有召唤成功 JSON。错误已从之前的订单类型拒绝变为机场状态获取失败;这只能说明本次返回的阻止原因变化,不能据此断言类型 25 的所有处理路径、派机或飞机锁定已经打通。
|
||||||
|
|
||||||
|
**任务 2 历史待核对:**参数、类型和机场状态失败均保留;后续新任务 6 成功不能证明任务 2 的失败原因,仍需朱工结合服务端日志解释其 `180031`。这不是客户端收到错误后自动重建任务的依据。
|
||||||
|
|
||||||
|
此前省略 `plane_id` 的模拟器构建和 **27 项相关测试全部通过**(shoot API/Model 9、准备页页面 18)。测试明确验证请求体仅有 `id/restart`、不存在 `plane_id`,并回归同任务导航、防重复提交及错误重试。该阶段真实请求为上述明确业务拒绝;后续任务 6 的成功记录见下节。
|
||||||
|
|
||||||
|
此前召唤原页回执阶段验证:模拟器构建通过,**89 项相关测试全部通过**(shoot API/Model 9、shoot 串接 ViewModel 13、创建 API/Model 8、创建 ViewModel 14、准备页 ViewModel 28、页面 17)。覆盖准确 POST 参数与鉴权、create→shoot 同任务次序、并发点击、明确拒绝重试、不确定结果锁、取消/身份变化、空 data 成功、原页两份回执及购买刷新失败后仍可展示回执。全部召唤请求由网络替身接收;未对真实无人机发送召唤。
|
||||||
|
|
||||||
|
#### 7.7.2 任务 6:创建与召唤业务成功,回查航线执行失败
|
||||||
|
|
||||||
|
用户明确要求“新建任务再召唤”。本次先复核原订单购买配置,只发送一次 `tasks/create` 并取得 `task_id=6`,再只发送一次 `shoot {"id":6,"restart":false}`,省略 `plane_id/air_line_id`;无自动重试。`shoot` 于 **2026-10-29 16:03:31** 返回 HTTP 200、`code=100000`、`msg="success"`。完整脱敏响应:[shoot-task6-success-redacted.json](docs/9.9.1/shooting-integration-2026-10-29/shoot-task6-success-redacted.json)。
|
||||||
|
|
||||||
|
| 成功回执字段 | 真实值及客户端含义 |
|
||||||
|
| --- | --- |
|
||||||
|
| `order_flight_task.id` | `6`,订单飞行任务 ID;后续 `shooting?id=6` 始终使用它 |
|
||||||
|
| `order_flight_task.status/status_label` | `20 / 执行中`,按服务端返回展示,不视为拍摄完成 |
|
||||||
|
| `order_flight_task.plane_id/airport_sn` | `61 / TEST-PLANE-61`(序列号已脱敏),本次回执已绑定设备 |
|
||||||
|
| `order_flight_task.wayline_task_id` 与根级 `data.task_id` | 均为 `1926`,是航线任务 ID;**不能拿 1926 替换 shooting 的入参 6** |
|
||||||
|
| `ui.phase/title` | `arrived_pending_start / 无人机已到达`,是后端返回的阶段提示 |
|
||||||
|
| `ui.primary_action/commands` | 返回开始拍摄、暂停和返航建议;本轮没有发送 `start-shoot/command` |
|
||||||
|
| `order_progress` | “单次航拍 · 含 1 次拍摄”、总/剩余 1,与本次创建摘要“多点位航拍”、总/剩余 5 仍不一致,待朱工和张工统一 |
|
||||||
|
|
||||||
|
**召唤后只读回查(2026-10-29 16:04:52):**`GET /api/app/airport/shooting?id=6&live_battery=1` 返回 `code=100000`,但 `task.wayline_task_id=1926`、`wayline_status=91`“执行失败”,`execute_gate.can_execute=false`、`code=wayline_not_shooting`,说明为“航线任务状态不可拍摄(当前:执行失败)”,`ui.phase=blocked`。`order_flight_task/task.status` 仍为 20“执行中”:订单飞行任务状态与航线状态是不同层次,应同时保留,不能仅凭这一差异认定前后端错误。完整响应:[shooting-task6-after-shoot-redacted.json](docs/9.9.1/shooting-integration-2026-10-29/shooting-task6-after-shoot-redacted.json)。
|
||||||
|
|
||||||
|
同一回查的 `current_plane.id=61`、`work_status=0`、`online_status=2`、`can_fly=false`,显示“离线 · 电量 94%”;`plane_status.connected=true` 是景区整体连接状态,不能替代该任务飞机的在线状态。请朱工排查航线任务 1926 的失败原因,并核对分配飞机 61 的在线状态和派机条件;现有响应不足以确定两者因果。`shoot.ui` 的“已到达”只是先前回执文案,不作为飞机物理到达的实证。
|
||||||
|
|
||||||
|
本轮仅创建 1 次、召唤 POST 1 次、随后任务 GET 1 次,无自动重试或任何 `start-shoot/command`。接口业务成功不等于航线执行成功,当前被阻止继续拍摄;不据此解释旧任务 2 的失败原因,也不自动重建或重发召唤。
|
||||||
|
|
||||||
## 8. 订单素材库
|
## 8. 订单素材库
|
||||||
|
|
||||||
@@ -1091,12 +1476,12 @@ GET /api/yf-handset-app/photog/multi-plane/tasks?scenic_id=271&order_number=TEST
|
|||||||
|
|
||||||
## 10. 其他页面与尚未接入的功能
|
## 10. 其他页面与尚未接入的功能
|
||||||
|
|
||||||
以下是模块已有演示页面和后端文档候选接口,不代表已完成正式接入。
|
以下区分已接入页面与仍保留的演示流程、后端候选能力;候选接口不代表已完成接入。
|
||||||
|
|
||||||
| 页面/功能 | 当前实现状态 | 文档中的后续候选接口与提供人 | 返回 JSON 记录 |
|
| 页面/功能 | 当前实现状态 | 文档中的后续候选接口与提供人 | 返回 JSON 记录 |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| 历史演示订单页 `DroneShootingOrdersViewController` | 仅演示流程继续使用本地数据;正式首页“查看全部”已进入真实 `DroneDockOrdersViewController` | 正式页张工 `GET /orders` 已接入,见 4.4 | 演示数据不能作为接口实测证据 |
|
| 历史演示订单页 `DroneShootingOrdersViewController` | 仅演示流程继续使用本地数据;正式首页“查看全部”已进入真实 `DroneDockOrdersViewController` | 正式页张工 `GET /orders` 已接入,见 4.4 | 演示数据不能作为接口实测证据 |
|
||||||
| 拍摄任务页 `DroneShootingTaskViewController` | 召唤、到达、拍摄、暂停、返航仍为演示流程 | 朱工 `/airport/shooting`、`/airport/status`、`/airport/live`、`/airport/start-shoot`、`/airport/command` | 暂无本页真实响应,不填模拟 JSON 冒充实测 |
|
| 拍摄任务页 `DroneDockShootingTaskViewController` | 顶部和底部固定,中间按状态组合且无滚动;进入、可见时返回前台或导航栏/中间刷新各只读一次,无下拉刷新或定时轮询;明确完成态可查看订单素材 | 朱工 `/airport/shooting` 已接入;图传 `/airport/live`、开始拍摄 `/airport/start-shoot`、控制 `/airport/command` 尚未接入,当前不另调 `/airport/status` | 类型 25 真实读取成功见 7.6;任务 6 已有真实召唤成功回执,尚无开始拍摄或控制成功记录 |
|
||||||
| 历史素材演示/下载 `DroneMaterialsViewController`、`DroneMaterialPreviewViewController` | 仅演示流程保留;正式入口已切换真实素材库,尚未接入批量下载或保存相册 | 下载可使用张工返回的有效文件 URL;当前正式页面只支持查看与预览 | 正式页面响应见第 8 节 |
|
| 历史素材演示/下载 `DroneMaterialsViewController`、`DroneMaterialPreviewViewController` | 仅演示流程保留;正式入口已切换真实素材库,尚未接入批量下载或保存相册 | 下载可使用张工返回的有效文件 URL;当前正式页面只支持查看与预览 | 正式页面响应见第 8 节 |
|
||||||
| 历史交付演示 `DroneDeliveryUploadViewController`、`DroneDeliveryReviewViewController` | 仅演示流程保留;正式上传使用第 9 节新共用页,游客确认尚未接入 | 后续张工 `POST /orders/confirm-code`、`GET /orders/detail` | 正式上传记录见第 9 节;暂无游客确认实测响应 |
|
| 历史交付演示 `DroneDeliveryUploadViewController`、`DroneDeliveryReviewViewController` | 仅演示流程保留;正式上传使用第 9 节新共用页,游客确认尚未接入 | 后续张工 `POST /orders/confirm-code`、`GET /orders/detail` | 正式上传记录见第 9 节;暂无游客确认实测响应 |
|
||||||
| 收款页“线下收款” | 跳转既有 `OfflineCollectionRegistrationViewController` | 复用原通用线下收款模块,不属于本次机巢类型 25 专用接口接入 | 本文未审计该旧模块 JSON,不将它记为新接口已打通 |
|
| 收款页“线下收款” | 跳转既有 `OfflineCollectionRegistrationViewController` | 复用原通用线下收款模块,不属于本次机巢类型 25 专用接口接入 | 本文未审计该旧模块 JSON,不将它记为新接口已打通 |
|
||||||
@@ -1107,13 +1492,15 @@ GET /api/yf-handset-app/photog/multi-plane/tasks?scenic_id=271&order_number=TEST
|
|||||||
|
|
||||||
| 事项 | 当前证据/约定 | 责任归属/后续 |
|
| 事项 | 当前证据/约定 | 责任归属/后续 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 多点位订单实时准备信息 | 当前仅请求 `project-info`;`workbench` 已停用,其业务码 100099 响应仅为历史记录 | 朱工、张工确认类型 25 的设备/距离/门禁读取入口,后续再接入 |
|
| 多点位订单实时准备信息 | 购买配置读取张工 `project-info`,设备状态读取朱工 `plane-status`,后者已实测显示“空闲 · 电量 93%”;`workbench` 的 100099 响应仅为历史记录 | 已完成创建后调用 shoot 的客户端衔接,当前按用户指示省略 plane_id;设备展示不作为起飞许可 |
|
||||||
| 任务创建和召唤衔接 | 一个接口要求绑定已有任务,另一个文档仍自行建任务 | 两位统一同一订单飞行任务 ID、类型 25 支持、失败重试及去重规则 |
|
| 任务创建后召唤 | 16:03:01 新建任务 6,16:03:31 省略 plane_id 的召唤接口业务成功;回执绑定飞机 61、航线任务 1926,后续 shooting 仍传 6 | 已取得成功样本;请朱工统一省略 plane_id 的文档约定。任务 2 的失败历史保留,原因不能由任务 6 成功反推;未调用开始拍摄或控制接口 |
|
||||||
|
| 任务状态读取与航线失败 | 16:04:52 shooting?id=6 读取成功:航线 1926 状态 91“执行失败”,任务总状态 20“执行中”,execute_gate=false、ui=blocked;任务飞机 61 显示离线且 can_fly=false,景区 connected=true | 朱工排查 1926 失败原因及飞机 61 在线状态、派机条件;区分任务/航线/景区状态层次,现有响应不足以确认故障因果;当前不继续拍摄 |
|
||||||
|
| 任务页套餐与次数 | shooting.header 及任务 6 的 shoot.order_progress 均为“单次航拍 · 含 1 次拍摄”、总/剩余 1;张工同单最新创建摘要为多点位航拍、总/剩余 5 | 朱工与张工统一 header/order_progress 来源;客户端不据此扣次或覆盖购买权限、整单次数 |
|
||||||
| 权威次数 | 类型 25 以张工订单摘要为准;仅有效成功任务计次 | 不回退朱工旧 `project_count/capture_num` 口径 |
|
| 权威次数 | 类型 25 以张工订单摘要为准;仅有效成功任务计次 | 不回退朱工旧 `project_count/capture_num` 口径 |
|
||||||
| 位置与范围 | 准备页已移除仅服务 workbench 的定位请求;产品确认不再展示距离、范围或定位占位 | 此次仅调整显示;后续召唤接口的服务端校验仍需按正式约定接入 |
|
| 位置与范围 | 准备页已移除仅服务 workbench 的定位请求;产品确认不再展示距离、范围或定位占位 | 此次仅调整显示;后续召唤接口的服务端校验仍需按正式约定接入 |
|
||||||
| 付款码返回语义 | 新返回为小程序码图片 URL,旧支付链接存档已过时 | 按最新图片合同展示,不能重新编码 URL |
|
| 付款码返回语义 | 新返回为小程序码图片 URL,旧支付链接存档已过时 | 按最新图片合同展示,不能重新编码 URL |
|
||||||
| 素材真实非空样本 | 当前订单摘要有 2 个点位,但全部与两个点位的任务均为空 | 后续飞行模块回写任务、原素材或成片后继续验证真实预览 |
|
| 素材真实非空样本 | 10 月 28 日素材采样时两个点位任务均为空;10 月 29 日 11:56 已创建任务 1,但尚无本页真实原素材或成片非空样本 | 后续飞行模块回写素材后继续验证真实预览,不将旧空态当成当前任务永远为空 |
|
||||||
| 成片上传真实数据 | 10 月 29 日仍无任务且 `can_upload_film=false`;用户确认先跳过真实上传联调 | 张工后续提供允许交付的有效任务后,验证真实 STS、OSS、保存及回读;当前代码与模拟器测试不等同于真实联调成功 |
|
| 成片上传真实数据 | 10 月 29 日 09:57 采样时无任务且 `can_upload_film=false`;11:56 创建响应已为 `can_upload_film=true`,用户此前确认先跳过真实上传联调 | 尚未验证真实 STS、OSS、保存及回读;已有创建响应不等于上传成功,后续按安排继续联调 |
|
||||||
| 空收款记录样本 | 本地有 10 月 27 日空态响应 | 后续取得非空真实响应时补充;当前非空 JSON 仅引用后端文档 |
|
| 空收款记录样本 | 本地有 10 月 27 日空态响应 | 后续取得非空真实响应时补充;当前非空 JSON 仅引用后端文档 |
|
||||||
|
|
||||||
## 12. 维护与证据索引
|
## 12. 维护与证据索引
|
||||||
@@ -1128,13 +1515,16 @@ GET /api/yf-handset-app/photog/multi-plane/tasks?scenic_id=271&order_number=TEST
|
|||||||
### 12.1 本文依据
|
### 12.1 本文依据
|
||||||
|
|
||||||
- 张工提供:`multi-plane-app-integration.md`,本机输入文件位于 Desktop;以用户最新确认的接口分工为准。
|
- 张工提供:`multi-plane-app-integration.md`,本机输入文件位于 Desktop;以用户最新确认的接口分工为准。
|
||||||
- 朱工提供:`随心瞰9.9.1-App机巢与素材库接口.md`,本机输入文件位于 Desktop。
|
- 朱工提供:`随心瞰9.9.1-App机巢与素材库接口.md`,本机输入文件位于 Desktop;召唤衔接最初依据 2026-10-29 14:50 更新版,当前省略 `plane_id` 以用户随后明确指示为准,真实拒绝记录见 7.7.1。
|
||||||
- 当前 App 的 API、ViewModel 与正式页面代码,正文各节已附项目内链接。
|
- 当前 App 的 API、ViewModel 与正式页面代码,正文各节已附项目内链接。
|
||||||
|
|
||||||
### 12.2 本地响应目录
|
### 12.2 本地响应目录
|
||||||
|
|
||||||
| 目录 | 内容 |
|
| 目录 | 内容 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
|
| [task-create-integration-2026-10-29](docs/9.9.1/task-create-integration-2026-10-29/) | 张工 tasks/create 的任务 1 历史成功响应,以及 16:03:01 按用户明确要求新建任务 6 的完整脱敏成功响应 |
|
||||||
|
| [shooting-integration-2026-10-29](docs/9.9.1/shooting-integration-2026-10-29/) | shooting 的历史失败与任务 1 成功响应;任务 2 各次 shoot 失败历史;16:03:31 任务 6 的 shoot 成功响应及 16:04:52 shooting 回查航线执行失败的完整脱敏响应 |
|
||||||
|
| [plane-status-integration-2026-10-29](docs/9.9.1/plane-status-integration-2026-10-29/) | 准备页无人机状态的完整脱敏实测响应,含三台设备、推荐状态与轮询间隔 |
|
||||||
| [delivery-integration-2026-10-29](docs/9.9.1/delivery-integration-2026-10-29/) | 交付前订单摘要、任务空态的真实脱敏响应;模拟器验证状态见第 9 节 |
|
| [delivery-integration-2026-10-29](docs/9.9.1/delivery-integration-2026-10-29/) | 交付前订单摘要、任务空态的真实脱敏响应;模拟器验证状态见第 9 节 |
|
||||||
| [materials-integration-2026-10-28](docs/9.9.1/materials-integration-2026-10-28/) | 订单摘要、全部任务与两个点位筛选的脱敏响应;真实截图仅留本地 |
|
| [materials-integration-2026-10-28](docs/9.9.1/materials-integration-2026-10-28/) | 订单摘要、全部任务与两个点位筛选的脱敏响应;真实截图仅留本地 |
|
||||||
| [orders-integration-2026-10-28](docs/9.9.1/orders-integration-2026-10-28/) | 我的拍摄订单四种状态的脱敏响应 |
|
| [orders-integration-2026-10-28](docs/9.9.1/orders-integration-2026-10-28/) | 我的拍摄订单四种状态的脱敏响应 |
|
||||||
|
|||||||
Reference in New Issue
Block a user