From 1e34136fcde1c033032a39a9f5598e2237463f98 Mon Sep 17 00:00:00 2001 From: awei Date: Tue, 21 Jul 2026 22:13:45 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(driver):=20=E5=8F=B8=E6=A9=9F=E7=AB=AF?= =?UTF-8?q?=E8=81=AF=E7=B5=A1=E9=9B=BB=E8=A9=B1=E5=A1=AB=E5=AF=AB=E5=85=A5?= =?UTF-8?q?=E5=8F=A3=EF=BC=88=E8=AE=93=E4=B9=98=E5=AE=A2=E7=AB=AF=E6=92=A5?= =?UTF-8?q?=E8=99=9F=E6=8C=89=E9=88=95=E7=9C=9F=E7=9A=84=E6=9C=83=E5=87=BA?= =?UTF-8?q?=E7=8F=BE=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 乘客端「撥打司機電話」按鈕(O7)2026-07-17 就上線了,資料讀後端的 driver_phone。但 drivers.phone 沒有任何寫入路徑——註冊不收、沒有更新 端點、司機端沒有欄位——所以號碼恆為空字串、hasPhone 永遠 false, 這顆按鈕從來沒有真正出現過。 - DriverProfile 模型 + fetchProfile/updatePhone(PUT /api/driver/profile) - DriverController: phone/hasPhone/savePhone;載入失敗靜默降級,電話是 選填,不該擋住車輛設定流程,也不該掛一條與當前操作無關的錯誤 - 車輛資訊頁加獨立的電話區塊與獨立送出鈕:電話與車輛走不同端點, UI 若共用一顆「儲存」,司機改電話就會連帶把車輛重送審(O5) - 三個 Fake API 補上 profile 端點——init()/login() 觸碰的端點沒覆蓋, testWidgets 在 FakeAsync 下會永久卡住(既有坑) 需搭配 dispatch 的 PUT /api/driver/profile(分支 claude/driver-phone-profile)。 驗收:flutter analyze 無 issue、flutter test 182 passed(新增 9); 反向確認移除電話長度檢查後對應測試會 FAIL。 Co-Authored-By: Claude Opus 4.8 --- docs/TODO.md | 54 +++- lib/core/api/fleet_api_client.dart | 29 +++ lib/core/models/vehicle.dart | 30 +++ lib/driver/driver_controller.dart | 51 ++++ lib/driver/screens/driver_vehicle_screen.dart | 238 ++++++++++++------ test/driver_controller_test.dart | 17 ++ test/driver_home_widget_test.dart | 5 + test/driver_vehicle_test.dart | 133 +++++++++- 8 files changed, 469 insertions(+), 88 deletions(-) diff --git a/docs/TODO.md b/docs/TODO.md index 8da6e5d..b0c18a9 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -59,8 +59,9 @@ 兩個 shared scheme,bundle id 對齊 Android(`dev.linefleet.line_fleet_app.driver`/`.customer`), 顯示名走 xcconfig 變數;模擬器主畫面「司機端」「乘客端」**兩個 icon 並存不互相覆蓋**。 **✅ 階段 7 收尾**:README 補 iOS 段與 `API_BASE` 平台預設對照表; - CI 的 `build-ios` job(macos-latest,customer flavor 不簽名 build)**已寫好但推不上去**—— - token 缺 `workflow` scope,改動留在本機工作區,需 `gh auth refresh -h github.com -s workflow`。 + CI 的 `build-ios` job(macos-latest,customer flavor 不簽名 build)**已在 `origin/main`** + (`.github/workflows/flutter-ci.yml:31`;2026-07-21 覆核,先前記的「token 缺 workflow scope + 推不上去」已不成立)。 **➡️ 只剩階段 5 實機部署**(需使用者接上 iPhone+Xcode 選 Personal Team+手機信任憑證, 產出是 A1「鎖屏長跑背景定位」的 iOS 實機驗收)**與階段 6 推播**(卡在付費 Apple 帳號)。 **實機已有、Apple 帳號為免費 Personal Team**:階段 1–5(含實機部署與 A1 背景定位實機驗收) @@ -592,25 +593,60 @@ admin 月報表頁 UI 亦渲染相同數字(NT$85.00/NT$12.75/NT$3,012.75 ### 司機端 -- [ ] **車輛資訊設定頁**:車種**下拉選單**(轎車/休旅/七人座/無障礙/寵物用車, - 顯示名稱在 App 對應,送後端 code)+車牌輸入+**聯絡電話**(`drivers.phone` 欄位已存在,只是沒填寫入口), - 串 `GET/PUT /api/driver/vehicle`。 +- [x] **車輛資訊設定頁**:車種**下拉選單**+車牌輸入 ✅ 2026-07-17(見上方 O2/O3 段); + **聯絡電話 ✅ 2026-07-21**(見下方「司機聯絡電話」段)。 - [ ] **強制跳轉引導** ✅ 定案(2026-07-16):未填車輛資訊時**強制導向設定頁**, 填完才能回到首頁/上線。不是「提示」而是 gate—— 使用者明確要求「強迫司機必須填寫才能開始接單(用跳轉方式引導)」。 實作點:`driver/app.dart` 的 `_DriverRoot`(目前只有 `isLoggedIn ? Home : Login`), 加第三種狀態 `已登入但無車輛資訊 → VehicleSetupScreen`。 註:**後端也會擋**(O3),App 端跳轉只是提早給回饋、不能只靠 App。 -- [ ] **`DriverController` 狀態**:加 `vehicle`/`hasVehicle`;`init()`/`login()` 後載入。 - 注意 `hasVehicle` 未載入完成前不要誤判成「沒填」而閃跳轉(載入中要有明確狀態)。 +- [x] **`DriverController` 狀態** ✅ 2026-07-17:`vehicle`/`hasVehicle`/`vehicleChecked`/ + `vehicleLoadFailed`(見上方 O2/O3 段的三態說明)。 + +## 📞 司機聯絡電話(2026-07-21,三層都補) + +> **抓到的缺口**:乘客端「撥打司機電話」按鈕(O7)早就上線,資料讀 `drivers.phone`; +> 但那個欄位**沒有任何寫入路徑**——註冊不收、沒有更新端點、司機端沒有欄位, +> 只有後端測試碼直接寫 DB。正式流程下號碼恆為空字串,`hasPhone` 永遠 false, +> **撥號按鈕從來沒有真正出現過**。規劃早在「司機端/車輛資訊設定頁」寫過 +> 「`drivers.phone` 欄位已存在,只是沒填寫入口」,但一直沒人接。 + +- [x] **後端**(dispatch `claude/driver-phone-profile`,commit `eb46ce1`,**尚未開 PR**): + 新開 **`PUT /api/driver/profile`**(driver JWT,只改 phone)+ + `constants.NormalizePhone`/`IsValidPhone`(8–15 碼、允許開頭 `+`)。 + **刻意不併進 `PUT /driver/vehicle`**——那支的 `UpdateVehicle` 會把 + `vehicle_review_status` 原子地重置為 pending(O5),司機每改一次電話 + 就會被審核 gate 踢出接單池。空字串=清除號碼(司機可收回不公開)。 + 驗證格式比照車牌的取捨:不綁「09 開頭」,否則市話與國際號碼會被誤擋。 +- [x] **App 端**:`DriverProfile` 模型、`fetchProfile`/`updatePhone`、 + controller 的 `phone`/`hasPhone`/`savePhone`(載入失敗**靜默降級**, + 電話是選填,不能讓它擋住車輛設定流程或掛一條無關的紅字); + 車輛資訊頁加**獨立的電話區塊+獨立送出鈕**——兩者走不同端點,UI 若共用一顆 + 「儲存」,司機改電話就會連帶重送審。頁面明講「修改電話不會影響車輛審核狀態」。 + +**驗收**: +- 靜態:`flutter analyze` 無 issue、`flutter test` **182 passed**(原 173,新增 9); + 後端 `go build ./...` OK、`TestDriverSetPhone` 4 子測試+`TestNormalizePhone`/ + `TestIsValidPhone` 全綠。 +- **反向確認**(兩次,都真的跑過):讓 `UpdatePhone` 也重置審核 → 「改電話不影響車輛 + 審核狀態」FAIL;移除電話長度檢查 → 「太短的號碼在本地就擋下」FAIL;兩者皆已還原。 +- **後端 live 全鏈路**(新分支 docker):存 `0912-345-678` → 回 `0912345678`(正規化生效); + 存完再查車輛 → **`review_status:"approved"`、`can_accept:true`(審核沒被重置,這是關鍵斷言)**; + 存 `12345` → 400「電話格式錯誤」;存 `""` → 清除成功。 + 再走完整叫車鏈路(司機上線→乘客建單→接單),乘客端 `GET /customer/rides/active` + **首次真的帶出 `"driver_phone":"0912345678"`**——改動前此欄恆為空字串。 +- **UI**:以 golden 渲染車輛資訊頁確認版面(兩區塊分離、電話帶出既有值、兩顆獨立按鈕)。 + **模擬器互動實跑未完成**:本機 bash 能移動游標但送不出合成點擊事件(缺輔助使用權限), + `cliclick` 三種點法皆無效,非座標問題。**待補:由人在模擬器上實際操作一次**。 ### 乘客端 - [ ] **顯示司機車種車牌**:`ride.accepted` 後的「司機前往上車點」階段, sheet 目前只顯示「司機:{name}」+ETA,要加車種與車牌(醒目、方便路邊對車)。 `CustomerController` 的 `driverName` 旁加 `driverVehicleType`/`driverPlateNumber`。 -- [ ] **司機聯絡方式** ✅ 已拍板(2026-07-16):**明碼**顯示可撥打的電話(`tel:` 連結)+留言板入口。 - 僅該趟乘客可見(後端 MultiAuth 控管,App 只在行程/協尋畫面顯示,不做任何司機列表)。 +- [x] **司機聯絡方式** ✅ 2026-07-17 乘客端 UI 完成(`DriverVehicleCard` 的 `tel:` 撥號鈕); + **但號碼直到 2026-07-21 補上司機端填寫入口才真的會出現**(見上方「司機聯絡電話」段)。 - [ ] **清潔費分項顯示** ✅ 定案:完成卡不可只給總額,要拆「車資 NT$X + 清潔費 NT$Y」。 **只有乘客指定寵物車的行程才有清潔費**(依 `required_vehicle_type`,非司機車種); 未指定時完成卡不該出現清潔費欄位。 diff --git a/lib/core/api/fleet_api_client.dart b/lib/core/api/fleet_api_client.dart index d4319c2..39b5dd9 100644 --- a/lib/core/api/fleet_api_client.dart +++ b/lib/core/api/fleet_api_client.dart @@ -149,6 +149,35 @@ class FleetApiClient { } } + /// 查自己的個資(對齊 GET /api/driver/me)。目前只用 `phone`。 + Future fetchProfile() async { + try { + final res = await _dio.get>('/driver/me'); + return DriverProfile.fromJson(res.data ?? const {}); + } on DioException catch (e) { + throw _wrap(e); + } + } + + /// 設定聯絡電話(對齊 PUT /api/driver/profile)。 + /// + /// **刻意不走 `/driver/vehicle`**:那支會把車輛審核重置為 pending(O5), + /// 司機改一次電話就會被踢回「審核中」而無法接單。 + /// + /// 後端會正規化號碼(去空白與 `-`、`(`、`)`)並回傳正規化後的值——**以回傳值為準**。 + /// 傳空字串=清除號碼(乘客端撥號按鈕隨之消失)。 + Future updatePhone(String phone) async { + try { + final res = await _dio.put>( + '/driver/profile', + data: {'phone': phone}, + ); + return DriverProfile.fromJson(res.data ?? const {}); + } on DioException catch (e) { + throw _wrap(e); + } + } + /// 查自己的車輛資訊(對齊 GET /api/driver/vehicle,O2)。 /// 未設定時兩欄為空字串、hasVehicle=false,非錯誤。 Future fetchVehicle() async { diff --git a/lib/core/models/vehicle.dart b/lib/core/models/vehicle.dart index d7b93a0..2f84cbb 100644 --- a/lib/core/models/vehicle.dart +++ b/lib/core/models/vehicle.dart @@ -96,3 +96,33 @@ class DriverVehicle { static const empty = DriverVehicle(vehicleType: '', plateNumber: '', hasVehicle: false); } + +/// 司機個資(對齊後端 `driverPublic`:`GET /api/driver/me`、`PUT /api/driver/profile`)。 +/// +/// 目前 App 只用到 `phone`——乘客端在「司機前往上車點」階段用它撥號(O7), +/// 而司機端在此之前**沒有任何填寫入口**,號碼永遠是空的、撥號按鈕永遠不顯示。 +class DriverProfile { + const DriverProfile({ + required this.driverId, + required this.name, + required this.phone, + }); + + final int driverId; + final String name; + + /// 聯絡電話;'' =未填(乘客端整塊撥號按鈕不顯示)。後端已正規化(去空白與分隔符號)。 + final String phone; + + bool get hasPhone => phone.isNotEmpty; + + factory DriverProfile.fromJson(Map json) { + return DriverProfile( + driverId: (json['driver_id'] as num?)?.toInt() ?? 0, + name: json['name'] as String? ?? '', + phone: json['phone'] as String? ?? '', + ); + } + + static const empty = DriverProfile(driverId: 0, name: '', phone: ''); +} diff --git a/lib/driver/driver_controller.dart b/lib/driver/driver_controller.dart index 4bfc77a..fc36eb0 100644 --- a/lib/driver/driver_controller.dart +++ b/lib/driver/driver_controller.dart @@ -61,6 +61,11 @@ class DriverController extends ChangeNotifier { // 混為一談會讓 _DriverRoot 卡在無限 spinner,司機連登出都按不到。 bool _vehicleLoadFailed = false; + // 司機個資(目前只用聯絡電話)。null =尚未載入;載入失敗不阻擋任何流程—— + // 電話是選填,查不到就讓欄位留白,不能因此擋住車輛設定頁。 + DriverProfile? _profile; + bool _phoneSaving = false; + AuthSession? get session => _session; bool get isLoggedIn => _session != null; bool get loading => _loading; @@ -158,6 +163,50 @@ class DriverController extends ChangeNotifier { notifyListeners(); } + /// 目前的聯絡電話;'' =未填或尚未載入。 + String get phone => _profile?.phone ?? ''; + + /// 是否已填聯絡電話。未填時乘客端看不到撥號按鈕。 + bool get hasPhone => _profile?.hasPhone ?? false; + + /// 電話儲存中(UI 用來 disable 欄位與按鈕)。 + bool get phoneSaving => _phoneSaving; + + /// 載入司機個資(目前只為了聯絡電話)。 + /// + /// **失敗時刻意不設 _error**:電話是選填欄位,查不到就讓它留白即可; + /// 若在這裡設錯誤,車輛設定頁會掛著一條與當前操作無關的紅字, + /// 讓司機以為車輛沒存成功。 + Future refreshProfile() async { + if (_session == null) return; + try { + _profile = await _api.fetchProfile(); + notifyListeners(); + } on ApiException { + // 靜默降級:維持 _profile 原值(可能為 null),不擋任何流程。 + } + } + + /// 設定聯絡電話。成功回 true。 + /// + /// 以後端回傳值更新狀態(號碼已正規化),不要用送出去的字串。 + /// 傳空字串=清除號碼。 + Future savePhone(String phone) async { + _phoneSaving = true; + _error = null; + notifyListeners(); + try { + _profile = await _api.updatePhone(phone); + return true; + } on ApiException catch (e) { + _error = e.message; // 格式錯誤(400)等訊息已由 api_error 中文化 + return false; + } finally { + _phoneSaving = false; + notifyListeners(); + } + } + /// 設定車種與車牌(O2)。成功回 true。 /// 以後端回傳值更新狀態(車牌已正規化),不要用送出去的字串。 Future saveVehicle({ @@ -211,6 +260,7 @@ class DriverController extends ChangeNotifier { await refreshLostItems(); // O3 gate 的 App 端引導:一還原 session 就查車輛,_DriverRoot 才知道要不要跳設定頁。 await refreshVehicle(); + await refreshProfile(); } await _bindPushListener(); } @@ -275,6 +325,7 @@ class DriverController extends ChangeNotifier { await refreshLostItems(); // 登入後立刻查車輛:沒填的話 _DriverRoot 會直接導去設定頁(O3 gate 的 App 端引導)。 await refreshVehicle(); + await refreshProfile(); } on ApiException catch (e) { _error = e.message; } finally { diff --git a/lib/driver/screens/driver_vehicle_screen.dart b/lib/driver/screens/driver_vehicle_screen.dart index e8f63bf..de9e738 100644 --- a/lib/driver/screens/driver_vehicle_screen.dart +++ b/lib/driver/screens/driver_vehicle_screen.dart @@ -21,7 +21,9 @@ class DriverVehicleScreen extends StatefulWidget { class _DriverVehicleScreenState extends State { final _formKey = GlobalKey(); + final _phoneFormKey = GlobalKey(); final _plateCtrl = TextEditingController(); + final _phoneCtrl = TextEditingController(); VehicleType? _type; bool _initialised = false; @@ -30,20 +32,38 @@ class _DriverVehicleScreenState extends State { super.didChangeDependencies(); if (_initialised) return; // 帶入既有值(修改情境);未填時留空。 - final v = context.read().vehicle; + final ctrl = context.read(); + final v = ctrl.vehicle; if (v != null) { _type = v.type; _plateCtrl.text = v.plateNumber; } + _phoneCtrl.text = ctrl.phone; _initialised = true; } @override void dispose() { _plateCtrl.dispose(); + _phoneCtrl.dispose(); super.dispose(); } + Future _savePhone() async { + if (!(_phoneFormKey.currentState?.validate() ?? false)) return; + final ctrl = context.read(); + final ok = await ctrl.savePhone(_phoneCtrl.text); + if (!mounted) return; + if (ok) { + // 以後端正規化後的號碼回填,讓司機看到真正存進去的內容。 + _phoneCtrl.text = ctrl.phone; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(ctrl.hasPhone ? '聯絡電話已儲存' : '已清除聯絡電話')), + ); + } + // 失敗時錯誤訊息由 ctrl.error 顯示。 + } + Future _save() async { if (!(_formKey.currentState?.validate() ?? false)) return; if (_type == null) return; @@ -56,9 +76,9 @@ class _DriverVehicleScreenState extends State { if (ok) { // 強制情境:填完後 _DriverRoot 會自動換成首頁(hasVehicle 變 true),不必 pop。 if (!widget.mandatory) Navigator.of(context).pop(); - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('車輛資訊已儲存')), - ); + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('車輛資訊已儲存'))); } // 失敗時錯誤訊息由 ctrl.error 顯示(含車牌重複 409 的中文訊息)。 } @@ -77,89 +97,151 @@ class _DriverVehicleScreenState extends State { body: SafeArea( child: SingleChildScrollView( padding: const EdgeInsets.all(16), - child: Form( - key: _formKey, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - if (widget.mandatory) ...[ - Card( - color: Theme.of(context).colorScheme.errorContainer, - child: const Padding( - padding: EdgeInsets.all(12), - child: Row( - children: [ - Icon(Icons.info_outline), - SizedBox(width: 8), - Expanded( - child: Text('請先填寫車種與車牌,填完才能開始接單。'), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (widget.mandatory) ...[ + Card( + color: Theme.of(context).colorScheme.errorContainer, + child: const Padding( + padding: EdgeInsets.all(12), + child: Row( + children: [ + Icon(Icons.info_outline), + SizedBox(width: 8), + Expanded(child: Text('請先填寫車種與車牌,填完才能開始接單。')), + ], ), - ], + ), + ), + const SizedBox(height: 16), + ], + DropdownButtonFormField( + initialValue: _type, + decoration: const InputDecoration( + labelText: '車種', + border: OutlineInputBorder(), ), + items: [ + for (final v in VehicleType.values) + DropdownMenuItem(value: v, child: Text(v.label)), + ], + onChanged: ctrl.vehicleSaving + ? null + : (v) => setState(() => _type = v), + validator: (v) => v == null ? '請選擇車種' : null, + ), + const SizedBox(height: 16), + TextFormField( + controller: _plateCtrl, + enabled: !ctrl.vehicleSaving, + textCapitalization: TextCapitalization.characters, + decoration: const InputDecoration( + labelText: '車牌', + hintText: '例如 ABC-1234', + border: OutlineInputBorder(), + ), + // 只擋明顯的空值——格式由後端寬鬆驗證(台灣車牌多代並存, + // App 端硬綁樣式會誤擋真車牌)。 + validator: (v) => + (v == null || v.trim().isEmpty) ? '請輸入車牌' : null, + ), + if (_type == VehicleType.pet) ...[ + const SizedBox(height: 12), + Text( + '寵物用車:乘客指定此車種時會加收清潔費,該費用全額歸司機。', + style: Theme.of(context).textTheme.bodySmall, + ), + ], + const SizedBox(height: 24), + FilledButton( + onPressed: ctrl.vehicleSaving ? null : _save, + child: ctrl.vehicleSaving + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ) + : const Text('儲存車輛資訊'), ), - ), - const SizedBox(height: 16), - ], - DropdownButtonFormField( - initialValue: _type, - decoration: const InputDecoration( - labelText: '車種', - border: OutlineInputBorder(), - ), - items: [ - for (final v in VehicleType.values) - DropdownMenuItem(value: v, child: Text(v.label)), ], - onChanged: ctrl.vehicleSaving - ? null - : (v) => setState(() => _type = v), - validator: (v) => v == null ? '請選擇車種' : null, ), - const SizedBox(height: 16), - TextFormField( - controller: _plateCtrl, - enabled: !ctrl.vehicleSaving, - textCapitalization: TextCapitalization.characters, - decoration: const InputDecoration( - labelText: '車牌', - hintText: '例如 ABC-1234', - border: OutlineInputBorder(), - ), - // 只擋明顯的空值——格式由後端寬鬆驗證(台灣車牌多代並存, - // App 端硬綁樣式會誤擋真車牌)。 - validator: (v) => - (v == null || v.trim().isEmpty) ? '請輸入車牌' : null, - ), - if (_type == VehicleType.pet) ...[ - const SizedBox(height: 12), - Text( - '寵物用車:乘客指定此車種時會加收清潔費,該費用全額歸司機。', - style: Theme.of(context).textTheme.bodySmall, - ), - ], - if (ctrl.error != null) ...[ - const SizedBox(height: 16), - Card( - color: Theme.of(context).colorScheme.errorContainer, - child: Padding( - padding: const EdgeInsets.all(12), - child: Text(ctrl.error!), + ), + const SizedBox(height: 32), + const Divider(), + const SizedBox(height: 16), + // 電話**獨立一區、獨立送出**:改車輛會讓審核回到待審核(O5), + // 而改電話不該讓司機被鎖出接單,兩者因此走不同的後端端點。 + Form( + key: _phoneFormKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + '聯絡電話', + style: Theme.of(context).textTheme.titleMedium, ), + const SizedBox(height: 4), + Text( + '乘客在您前往上車點時可直接撥打。留空則乘客端不顯示撥號按鈕。' + '修改電話不會影響車輛審核狀態。', + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 12), + TextFormField( + controller: _phoneCtrl, + enabled: !ctrl.phoneSaving, + keyboardType: TextInputType.phone, + decoration: const InputDecoration( + labelText: '電話(選填)', + hintText: '例如 0912345678', + border: OutlineInputBorder(), + ), + // 留空是合法的(=清除號碼);只在有填時做最低限度的長度檢查, + // 格式仍以後端為準——市話、國際碼樣式太多,App 端硬綁會誤擋。 + validator: (v) { + final s = (v ?? '').trim(); + if (s.isEmpty) return null; + final digits = s.replaceAll(RegExp(r'[\s\-()]'), ''); + return digits.length < 8 ? '電話長度不足' : null; + }, + ), + const SizedBox(height: 16), + OutlinedButton( + onPressed: ctrl.phoneSaving ? null : _savePhone, + child: ctrl.phoneSaving + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ) + : const Text('儲存聯絡電話'), + ), + ], + ), + ), + // 共用一個錯誤區(controller 只有一個 error);訊息本身會說明是車牌 + // 重複還是電話格式,放在最下方兩區都看得到。 + if (ctrl.error != null) ...[ + const SizedBox(height: 16), + Card( + color: Theme.of(context).colorScheme.errorContainer, + child: Padding( + padding: const EdgeInsets.all(12), + child: Text(ctrl.error!), ), - ], - const SizedBox(height: 24), - FilledButton( - onPressed: ctrl.vehicleSaving ? null : _save, - child: ctrl.vehicleSaving - ? const SizedBox( - height: 20, - width: 20, - child: CircularProgressIndicator(strokeWidth: 2), - ) - : const Text('儲存'), ), ], - ), + ], ), ), ), diff --git a/test/driver_controller_test.dart b/test/driver_controller_test.dart index 49bac0f..0f7e2b3 100644 --- a/test/driver_controller_test.dart +++ b/test/driver_controller_test.dart @@ -421,6 +421,12 @@ class _FakeFleetApi extends FleetApiClient { plateNumber: 'ABC-1234', hasVehicle: true, ); + DriverProfile profile = const DriverProfile( + driverId: 1, + name: '測試司機', + phone: '', + ); + ApiException? phoneError; ApiException? vehicleError; final savedVehicles = []; DropoffInfo pickUpDropoff = const DropoffInfo(); @@ -456,6 +462,17 @@ class _FakeFleetApi extends FleetApiClient { return vehicle; } + // init()/login() 也會呼叫 fetchProfile,理由同上方 fetchVehicle 的註解。 + @override + Future fetchProfile() async => profile; + + @override + Future updatePhone(String phone) async { + if (phoneError != null) throw phoneError!; + profile = DriverProfile(driverId: 1, name: '測試司機', phone: phone.trim()); + return profile; + } + @override Future updateVehicle({ required String vehicleType, diff --git a/test/driver_home_widget_test.dart b/test/driver_home_widget_test.dart index 71f1480..a5d559a 100644 --- a/test/driver_home_widget_test.dart +++ b/test/driver_home_widget_test.dart @@ -220,6 +220,11 @@ class _FakeFleetApi extends FleetApiClient { hasVehicle: true, ); + // init() 也會呼叫 fetchProfile,Fake 沒覆蓋就會打真網路卡死 FakeAsync。 + @override + Future fetchProfile() async => + const DriverProfile(driverId: 1, name: '測試司機', phone: '0912345678'); + @override Future acceptRide(int rideId) async => '接單成功'; diff --git a/test/driver_vehicle_test.dart b/test/driver_vehicle_test.dart index 97fce8c..104994c 100644 --- a/test/driver_vehicle_test.dart +++ b/test/driver_vehicle_test.dart @@ -195,6 +195,118 @@ void main() { }); }); + group('聯絡電話(乘客端撥號按鈕的資料來源)', () { + testWidgets('儲存電話走 profile 端點,不動車輛審核狀態', (tester) async { + // 這是本功能存在的理由:改電話若走 PUT /driver/vehicle, + // 後端會把審核重置為 pending,司機每改一次號碼就被鎖出接單(O5 gate)。 + final api = _VehicleFakeApi() + ..vehicle = const DriverVehicle( + vehicleType: 'sedan', + plateNumber: 'ABC-1234', + hasVehicle: true, + reviewStatus: VehicleReviewStatus.approved, + canAccept: true, + ); + final ctrl = DriverController( + storage: MemoryDriverAuthStore(), + api: api, + wsFactory: FleetWsClient.silent, + ); + addTearDown(ctrl.dispose); + await ctrl.init(); + await ctrl.login(lineUserId: 'U', password: 'pw'); + expect(ctrl.canAcceptRides, isTrue, reason: '前置:這位司機原本已核准可接單'); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: ctrl, + child: const MaterialApp(home: DriverVehicleScreen()), + ), + ); + await tester.pump(); + + await tester.enterText( + find.widgetWithText(TextFormField, '電話(選填)'), + '0912-345-678', + ); + await tester.tap(find.text('儲存聯絡電話')); + await tester.pumpAndSettle(); + + expect(api.savedPhones, ['0912-345-678']); + // 沒有碰到車輛端點——否則審核會被重置。 + expect(api.savedVehicles, isEmpty); + expect(ctrl.vehicleReviewStatus, VehicleReviewStatus.approved); + expect(ctrl.canAcceptRides, isTrue); + expect(ctrl.hasPhone, isTrue); + }); + + testWidgets('留空代表清除號碼,不被必填擋下', (tester) async { + // 司機不想公開號碼時要有辦法收回;乘客端隨之不顯示撥號按鈕。 + final api = _VehicleFakeApi() + ..profile = const DriverProfile( + driverId: 1, + name: '測試司機', + phone: '0912345678', + ); + final ctrl = DriverController( + storage: MemoryDriverAuthStore(), + api: api, + wsFactory: FleetWsClient.silent, + ); + addTearDown(ctrl.dispose); + // 走正式路徑載入 profile(login 後會 refreshProfile),欄位才會帶出既有號碼。 + await ctrl.init(); + await ctrl.login(lineUserId: 'U', password: 'pw'); + expect(ctrl.hasPhone, isTrue, reason: '前置:欄位應帶出既有號碼'); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: ctrl, + child: const MaterialApp(home: DriverVehicleScreen()), + ), + ); + await tester.pump(); + + await tester.enterText( + find.widgetWithText(TextFormField, '電話(選填)'), + '', + ); + await tester.tap(find.text('儲存聯絡電話')); + await tester.pumpAndSettle(); + + expect(api.savedPhones, ['']); + expect(ctrl.hasPhone, isFalse); + }); + + testWidgets('太短的號碼在本地就擋下,不送出', (tester) async { + final api = _VehicleFakeApi(); + final ctrl = DriverController( + storage: MemoryDriverAuthStore(), + api: api, + wsFactory: FleetWsClient.silent, + ); + addTearDown(ctrl.dispose); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: ctrl, + child: const MaterialApp(home: DriverVehicleScreen()), + ), + ); + await tester.pump(); + + await tester.enterText( + find.widgetWithText(TextFormField, '電話(選填)'), + '12345', + ); + await tester.tap(find.text('儲存聯絡電話')); + await tester.pumpAndSettle(); + + expect(find.text('電話長度不足'), findsOneWidget); + expect(api.savedPhones, isEmpty); + }); + }); + group('DriverVehicleScreen(強制情境)', () { testWidgets('強制情境沒有返回鍵,且顯示提示', (tester) async { final api = _VehicleFakeApi() @@ -245,7 +357,7 @@ void main() { ); await tester.pump(); - await tester.tap(find.text('儲存')); + await tester.tap(find.text('儲存車輛資訊')); await tester.pump(); expect(find.text('請選擇車種'), findsOneWidget); @@ -263,6 +375,13 @@ class _VehicleFakeApi extends FleetApiClient { plateNumber: 'ABC-1234', hasVehicle: true, ); + DriverProfile profile = const DriverProfile( + driverId: 1, + name: '測試司機', + phone: '', + ); + ApiException? phoneError; + final List savedPhones = []; ApiException? vehicleError; final savedVehicles = []; @@ -288,6 +407,18 @@ class _VehicleFakeApi extends FleetApiClient { return vehicle; } + // init()/login() 也會呼叫 fetchProfile,Fake 沒覆蓋就會打真網路卡死 FakeAsync。 + @override + Future fetchProfile() async => profile; + + @override + Future updatePhone(String phone) async { + if (phoneError != null) throw phoneError!; + savedPhones.add(phone); + profile = DriverProfile(driverId: 1, name: '測試司機', phone: phone.trim()); + return profile; + } + @override Future updateVehicle({ required String vehicleType, From 02de3eb91226e899dd49c39ed5ebf371a513ec0e Mon Sep 17 00:00:00 2001 From: awei Date: Tue, 21 Jul 2026 22:25:46 +0800 Subject: [PATCH 2/3] =?UTF-8?q?test(driver):=20=E5=8A=A0=20integration=5Ft?= =?UTF-8?q?est=20=E5=9C=A8=E7=9C=9F=E6=A8=A1=E6=93=AC=E5=99=A8=E9=A9=97?= =?UTF-8?q?=E8=81=AF=E7=B5=A1=E9=9B=BB=E8=A9=B1=E7=AB=AF=E5=88=B0=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit widget test 用 Fake API,證明不了「App 真的把電話寫進後端、而且沒把車輛 審核狀態弄壞」。而系統層的合成滑鼠事件在本機 agent 環境送不進模擬器 (cliclick 移動游標正常但點擊靜默失效,Tab/方向鍵焦點也只能停在第一個 AppBar icon),所以互動必須改由 Flutter 自己派送。 integration_test 同時解掉兩件事:點擊不經系統事件,且能在斷言裡直接 向後端重查,不必相信 controller 的記憶體狀態。 實跑(iPhone 17 Pro + 後端 docker):輸入 0988-123-456 → 儲存 → SnackBar 出現 → 後端回正規化後的 0988123456 → 車輛仍 approved/can_accept。 外部 curl 交叉驗證 GET /driver/me 一致(操作前該欄為空字串)。 Co-Authored-By: Claude Opus 4.8 --- docs/TODO.md | 14 +++-- integration_test/driver_phone_test.dart | 72 +++++++++++++++++++++++++ pubspec.lock | 39 ++++++++++++++ pubspec.yaml | 3 ++ 4 files changed, 125 insertions(+), 3 deletions(-) create mode 100644 integration_test/driver_phone_test.dart diff --git a/docs/TODO.md b/docs/TODO.md index b0c18a9..a336fb9 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -636,9 +636,17 @@ admin 月報表頁 UI 亦渲染相同數字(NT$85.00/NT$12.75/NT$3,012.75 存 `12345` → 400「電話格式錯誤」;存 `""` → 清除成功。 再走完整叫車鏈路(司機上線→乘客建單→接單),乘客端 `GET /customer/rides/active` **首次真的帶出 `"driver_phone":"0912345678"`**——改動前此欄恆為空字串。 -- **UI**:以 golden 渲染車輛資訊頁確認版面(兩區塊分離、電話帶出既有值、兩顆獨立按鈕)。 - **模擬器互動實跑未完成**:本機 bash 能移動游標但送不出合成點擊事件(缺輔助使用權限), - `cliclick` 三種點法皆無效,非座標問題。**待補:由人在模擬器上實際操作一次**。 +- **UI 互動實跑 ✅(2026-07-21,iPhone 17 Pro 模擬器+後端 docker)**: + 新增 `integration_test/driver_phone_test.dart`——在**真模擬器上跑真 App、打真後端**, + 輸入 `0988-123-456` → 點「儲存聯絡電話」→ 斷言 SnackBar「聯絡電話已儲存」出現 → + **重新向後端查**(不信 controller 的記憶體狀態)得到正規化後的 `0988123456` → + 車輛仍 `approved`/`can_accept:true`。`All tests passed`。 + 外部 curl 交叉驗證:`GET /driver/me` 回 `"phone":"0988123456"`(操作前是空字串)。 +- **踩到的坑(已記進 [[ios-simulator-automation]])**:`cliclick` 的點擊在此環境**靜默失效** + ——`cliclick m:` 移動游標正常、`osascript` 的 keystroke 也有效,但合成滑鼠點擊完全到不了 + 模擬器(該執行檔缺輔助使用授權),Tab/方向鍵焦點導航又只能停在第一個 AppBar icon。 + **出路是 `integration_test`**:點擊由 Flutter 自己派送,不經過系統事件, + 同時還能斷言後端狀態。以後 iOS 的 UI 驗收優先走這條,別再跟座標纏鬥。 ### 乘客端 diff --git a/integration_test/driver_phone_test.dart b/integration_test/driver_phone_test.dart new file mode 100644 index 0000000..f88d6f3 --- /dev/null +++ b/integration_test/driver_phone_test.dart @@ -0,0 +1,72 @@ +// 司機聯絡電話的端到端驗收:在真模擬器上跑真 App、打真後端。 +// +// 為什麼需要這個檔:widget test 用的是 Fake API,證明不了「App 真的把電話寫進後端、 +// 而且沒有把車輛審核狀態弄壞」;而系統層的合成點擊事件在本機 CI/agent 環境送不進 +// 模擬器(見 docs/TODO.md 的說明),所以互動必須由 Flutter 自己派送。 +// +// 前置:後端要跑在 --dart-define 指定的 API_BASE,且該司機帳號存在、車輛已核准。 +// 跑法: +// flutter test integration_test/driver_phone_test.dart \ +// -d --flavor driver \ +// --dart-define=API_BASE=http://127.0.0.1:8080 +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:line_fleet_app/core/api/fleet_api_client.dart'; +import 'package:line_fleet_app/core/storage/token_storage.dart'; +import 'package:line_fleet_app/core/ws/fleet_ws_client.dart'; +import 'package:line_fleet_app/core/theme/app_theme.dart'; +import 'package:line_fleet_app/driver/driver_controller.dart'; +import 'package:line_fleet_app/driver/screens/driver_vehicle_screen.dart'; +import 'package:provider/provider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets('司機填聯絡電話 → 真的寫進後端,且車輛審核狀態不受影響', (tester) async { + final api = FleetApiClient(); + final ctrl = DriverController( + storage: MemoryDriverAuthStore(), + api: api, + // 這個案子與派單無關,靜默 WS 免得測試被連線時序干擾。 + wsFactory: FleetWsClient.silent, + ); + addTearDown(ctrl.dispose); + + await ctrl.init(); + await ctrl.login(lineUserId: 'sim-driver-001', password: 'password123'); + expect(ctrl.isLoggedIn, isTrue, reason: '前置:登入應成功(後端有跑嗎?)'); + expect(ctrl.canAcceptRides, isTrue, reason: '前置:這位司機的車輛應已核准'); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: ctrl, + child: MaterialApp( + theme: appLightTheme, + home: const DriverVehicleScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + + // 帶分隔符號輸入,順便驗後端正規化後有回填到欄位。 + await tester.enterText( + find.widgetWithText(TextFormField, '電話(選填)'), + '0988-123-456', + ); + await tester.tap(find.text('儲存聯絡電話')); + await tester.pumpAndSettle(const Duration(seconds: 3)); + + expect(find.text('聯絡電話已儲存'), findsOneWidget, reason: 'SnackBar 應出現'); + expect(ctrl.error, isNull, reason: '不應有錯誤'); + + // 以「重新向後端查一次」為準,而不是相信 controller 的記憶體狀態。 + final fresh = await api.fetchProfile(); + expect(fresh.phone, '0988123456', reason: '後端應存下正規化後的號碼'); + + // 這是本功能存在的理由:改電話不可以把司機踢回審核中。 + final vehicle = await api.fetchVehicle(); + expect(vehicle.canAccept, isTrue, reason: '存電話後仍必須能接單'); + expect(vehicle.reviewStatus.name, 'approved'); + }); +} diff --git a/pubspec.lock b/pubspec.lock index 1a49b08..8dbb1fa 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -230,6 +230,11 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_driver: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" flutter_launcher_icons: dependency: "direct dev" description: @@ -312,6 +317,11 @@ packages: description: flutter source: sdk version: "0.0.0" + fuchsia_remote_debug_protocol: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" geoclue: dependency: transitive description: @@ -448,6 +458,11 @@ packages: url: "https://pub.dev" source: hosted version: "4.8.0" + integration_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" intl: dependency: transitive description: @@ -752,6 +767,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.5.0" + process: + dependency: transitive + description: + name: process + sha256: c6248e4526673988586e8c00bb22a49210c258dc91df5227d5da9748ecf79744 + url: "https://pub.dev" + source: hosted + version: "5.0.5" proj4dart: dependency: transitive description: @@ -885,6 +908,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" + sync_http: + dependency: transitive + description: + name: sync_http + sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961" + url: "https://pub.dev" + source: hosted + version: "0.3.1" term_glyph: dependency: transitive description: @@ -1029,6 +1060,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.3" + webdriver: + dependency: transitive + description: + name: webdriver + sha256: "2f3a14ca026957870cfd9c635b83507e0e51d8091568e90129fbf805aba7cade" + url: "https://pub.dev" + source: hosted + version: "3.1.0" win32: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index ff3842b..558e8e9 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -29,6 +29,9 @@ dependencies: dev_dependencies: flutter_test: sdk: flutter + # 在真模擬器/裝置上驅動 UI(點擊由 Flutter 自己派送,不需要系統層的合成滑鼠事件)。 + integration_test: + sdk: flutter flutter_lints: ^6.0.0 flutter_launcher_icons: ^0.14.4 From d34b4feb581557f386008cd6cd766d63129ffd75 Mon Sep 17 00:00:00 2001 From: awei Date: Tue, 21 Jul 2026 22:31:48 +0800 Subject: [PATCH 3/3] =?UTF-8?q?docs:=20=E6=94=B6=E5=B0=BE=E2=80=94?= =?UTF-8?q?=E2=80=94README=20=E8=A3=9C=E9=9B=BB=E8=A9=B1=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E8=88=87=E6=B8=AC=E8=A9=A6=E8=B7=91=E6=B3=95=EF=BC=8CTODO=20?= =?UTF-8?q?=E5=AF=AB=E6=98=8E=E4=B8=8B=E6=AC=A1=E4=BB=BB=E5=8B=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - README: 司機聯絡電話段(含「不可與 vehicle 端點共用」的理由)、 測試指令、iOS UI 驗收優先走 integration_test 的提醒 - TODO: 「下次任務」改成可直接接手的狀態——先合兩個相依 PR, 再做 A5 階段 5(iOS 實機)→ A1 鎖屏長跑背景定位實機驗收, 含 `-d ios` 免查 device-id、以及卡在哪三件人工操作 - tool/watch_driver_location.sh: A1 驗收腳本從 scratchpad 收進 repo (每 5 秒讀 Redis driver::loc 的 updated_at 判斷背景定位有沒有斷; 後端沒掛 gin.Logger(),請求層不印 log,所以看 Redis 不看 log) Co-Authored-By: Claude Opus 4.8 --- README.md | 23 ++++++++- docs/TODO.md | 24 ++++++++++ tool/watch_driver_location.sh | 87 +++++++++++++++++++++++++++++++++++ 3 files changed, 133 insertions(+), 1 deletion(-) create mode 100755 tool/watch_driver_location.sh diff --git a/README.md b/README.md index f3d85ee..7ddd0ce 100644 --- a/README.md +++ b/README.md @@ -171,7 +171,28 @@ FCM data 的值一律是字串,App 端 `fleetEventFromPushData()` 會把座標 已核准→首頁;能不能接單以後端 `can_accept` 為準(App 不自行推導)。 admin 端在司機管理頁核准/退回(退回須附原因)。 -**目前**:`flutter analyze` 無 issue、`flutter test` **179 passed**。 +- **司機聯絡電話(2026-07-21)**:司機端車輛資訊頁加**獨立的電話區塊+獨立送出鈕**, + 串後端 `PUT /api/driver/profile`。**不可與 `PUT /driver/vehicle` 共用**——那支會把 + 車輛審核重置為待審核(O5),司機改一次電話就會被踢出接單池。留空=清除號碼。 + 在此之前 `drivers.phone` 沒有任何寫入路徑,乘客端的撥號按鈕從未真正出現過。 + +**目前**:`flutter analyze` 無 issue、`flutter test` **182 passed**。 + +### 測試怎麼跑 + +```bash +flutter analyze +flutter test # 單元/widget(不含 integration_test/) + +# 在真模擬器上跑真 App、打真後端(需先起後端 docker) +flutter test integration_test/driver_phone_test.dart \ + -d --flavor driver \ + --dart-define=API_BASE=http://127.0.0.1:8080 +``` + +> **iOS 的 UI 驗收優先走 `integration_test`**:它的點擊由 Flutter 自己派送, +> 不經過系統合成事件——`cliclick` 那類工具在無輔助使用授權的環境會**靜默失效** +> (游標會動、點擊卻到不了模擬器),別再跟座標纏鬥。 ## 規劃中(尚未實作) diff --git a/docs/TODO.md b/docs/TODO.md index a336fb9..50f785b 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -253,6 +253,30 @@ ## 下次任務 +> **⬅️ 從這裡開始(2026-07-21 收工時的狀態)** +> +> **0. 先合兩個待審 PR**(電話功能,三層都有實證,合併順序有相依): +> 1. [fleet-dispatch#42](https://github.com/thothawei/fleet-dispatch/pull/42)(`PUT /api/driver/profile`)**要先合** +> 2. [fleet-app#40](https://github.com/thothawei/fleet-app/pull/40)(司機端填寫入口)——後端未合前會 404 +> +> **1. A5 階段 5:iOS 實機部署 → 產出 A1「鎖屏長跑背景定位」實機驗收**(最高優先) +> 這是掛最久且唯一沒有實機證據的核心功能;背景定位失效=司機靜默收不到派單,測試補不上。 +> 阻塞**不是技術問題**,是三件需要人操作的事:接上 iPhone/Xcode 登入 Apple ID +> (`security find-identity` 目前 **0 valid identities**)/Runner target 選 Personal Team。 +> 做完就跑:`flutter run -d ios -t lib/main_driver.dart --flavor driver --dart-define=API_BASE=http://<區網IP>:8080` +> ——**不用查 device-id,`-d ios` 會自動選唯一的 iOS 實機**。 +> 驗收腳本已寫好:每 5 秒讀 Redis `driver::loc` 的 `updated_at`,輸出更新次數/ +> 最大空窗/PASS-FAIL(後端沒掛 `gin.Logger()`,請求層不印 log,所以不看 log 看 Redis)。 +> 腳本已收進 repo:`tool/watch_driver_location.sh [監看秒數]`。 +> 已預先驗過:driver flavor 的 `flutter build ios --no-codesign` 可過(20.6MB)。 +> +> **2. 若當下不方便接實機**,可獨立完成的候選: +> - **B5 評分/付款**:卡後端 Phase C(未開工),需要先談後端 +> - **A2 FCM 推播**:需建 Firebase 專案 + `google-services.json` + 後端 FCM 實作(Android 可做,iOS 端卡付費帳號) +> - **WS 重連 jitter**:退避已上線但無抖動,後端重啟時所有司機會同時重連(量體大才有感) +> +> **3. 等你拍板才能動**:多停靠點的建單前車資預估(需後端新開報價 API,見「懸而未決」) + > **🎨 App icon(叫車系統圖示)✅ 已完成(2026-07-15,PR #15)**:品牌綠 LINE green #06C755 + 白色計程車, > 以 `flutter_launcher_icons` 產生 Android(含 adaptive icon)與 iOS 各尺寸,driver/customer 兩 flavor 共用。 diff --git a/tool/watch_driver_location.sh b/tool/watch_driver_location.sh new file mode 100755 index 0000000..396366d --- /dev/null +++ b/tool/watch_driver_location.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# A1 背景定位實機驗收(iOS 階段 5-4):監看司機位置在鎖屏期間是否持續更新。 +# +# 資料來源:後端把每次 POST /api/driver/location 寫進 Redis hash +# driver::loc(lat/lng/updated_at,見 internal/redis/store.go)。 +# 後端沒有掛 gin.Logger(),請求層不印 log,所以用 Redis 當真相來源。 +# +# 用法:watch_driver_location.sh [監看秒數,預設 660=11 分鐘] + +set -u + +DRIVER_ID="${1:?請給 driver_id}" +DURATION="${2:-660}" +DISPATCH_DIR="/Users/mac/Documents/line-fleet-dispatch" +POLL_SEC=5 + +# App 端每 8 秒回報一次(AppConfig.locationIntervalSec), +# 容忍網路抖動與 iOS 的 distanceFilter,超過 60 秒沒更新就算「背景被系統凍結」。 +STALE_THRESHOLD=60 + +cd "$DISPATCH_DIR" || exit 1 + +redis_get() { + docker compose exec -T redis redis-cli HGET "driver:${DRIVER_ID}:loc" updated_at 2>/dev/null | tr -d '\r' +} + +first_ts="" +last_ts="" +last_change_at=$(date +%s) +max_gap=0 +updates=0 +samples=0 +start_at=$(date +%s) +end_at=$((start_at + DURATION)) + +echo "監看 driver:${DRIVER_ID}:loc,共 ${DURATION} 秒(每 ${POLL_SEC} 秒取樣一次)" +echo "開始時間:$(date '+%H:%M:%S')" +echo + +while [ "$(date +%s)" -lt "$end_at" ]; do + ts=$(redis_get) + now=$(date +%s) + samples=$((samples + 1)) + + if [ -z "$ts" ]; then + echo "$(date '+%H:%M:%S') ⚠️ Redis 裡還沒有這位司機的位置(司機上線了嗎?)" + else + if [ -z "$first_ts" ]; then + first_ts="$ts" + last_ts="$ts" + last_change_at="$now" + echo "$(date '+%H:%M:%S') ✅ 首次取得位置 updated_at=${ts}" + elif [ "$ts" != "$last_ts" ]; then + gap=$((now - last_change_at)) + [ "$gap" -gt "$max_gap" ] && max_gap="$gap" + updates=$((updates + 1)) + last_ts="$ts" + last_change_at="$now" + echo "$(date '+%H:%M:%S') ✅ 位置更新(距上次 ${gap}s,累計 ${updates} 次)" + else + stale=$((now - last_change_at)) + if [ "$stale" -ge "$STALE_THRESHOLD" ]; then + echo "$(date '+%H:%M:%S') ❌ 已 ${stale}s 沒有新位置——背景定位可能被系統停掉" + fi + fi + fi + sleep "$POLL_SEC" +done + +# 收尾把最後一段靜止期也算進最大間隔,否則「結束前就斷掉」會被漏掉 +final_stale=$(( $(date +%s) - last_change_at )) +[ "$final_stale" -gt "$max_gap" ] && max_gap="$final_stale" + +echo +echo "==================== 驗收結果 ====================" +echo "監看時長 :${DURATION}s" +echo "取樣次數 :${samples}" +echo "位置更新次數 :${updates}" +echo "最大更新間隔 :${max_gap}s(門檻 ${STALE_THRESHOLD}s)" +if [ "$updates" -eq 0 ]; then + echo "判定 :❌ FAIL — 全程沒有任何位置更新" +elif [ "$max_gap" -ge "$STALE_THRESHOLD" ]; then + echo "判定 :❌ FAIL — 曾有 ${max_gap}s 的空窗,背景定位沒有持續" +else + echo "判定 :✅ PASS — 全程位置持續更新,無超過門檻的空窗" +fi +echo "=================================================="