From ee7f01f422f547bbf5c9ba65a4f50f2063356f00 Mon Sep 17 00:00:00 2001 From: awei Date: Thu, 23 Jul 2026 07:55:36 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(app):=20=E5=BB=BA=E5=96=AE=E5=89=8D?= =?UTF-8?q?=E8=BB=8A=E8=B3=87=E9=A0=90=E4=BC=B0=EF=BC=88=E6=87=B8=E8=80=8C?= =?UTF-8?q?=E6=9C=AA=E6=B1=BA=20#1=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 叫車表單顯示預估車資:地圖選目的地(單點)或停靠點填完(多停靠點)時自動算、 車種變更時重算。是預估不是定價——實際依行駛路線於行程結束時結算,卡片明確標示。 後端對應 dispatch 的 POST /api/customer/rides/estimate(以全程規劃路線試算, 與完成計費共用 FeeSettings.Quote)。 - FareEstimate 模型+CustomerApiClient.estimateFare。 - CustomerController 加預估狀態:dropoff 座標存 controller 才能在車種變更時重算; 多停靠點由 stops 推導不需 GPS,單點需上車 GPS(優先用已取得定位,8 秒逾時)。 - _FareEstimateCard:有清潔費時拆「車資+寵物車清潔費=預估合計」,否則單一金額; 附「約 X 公里・Y 分鐘」與「實際車資依行駛路線可能不同,於行程結束時結算」。 - 失敗一律靜默清空——預估只是輔助資訊,不擋叫車、不彈錯誤(與 P5 查費率同原則)。 - 送出叫車/登出時清掉預估狀態,不留到下一趟。 驗收:flutter analyze 無 issue、flutter test 197 passed(新增 customer_fare_estimate_test 7 案:多停靠點帶 stops 不需 GPS/車種變更重算含清潔費/失敗靜默/clear/移除乘客清空/模型解析)。 尚未做:模擬器實跑 E2E(需後端 docker)。 Co-Authored-By: Claude Opus 4.8 --- README.md | 11 +- docs/TODO.md | 47 +++++- lib/core/api/customer_api_client.dart | 34 ++++ lib/core/models/models.dart | 36 +++++ lib/customer/customer_controller.dart | 94 +++++++++++ lib/customer/widgets/ride_phase_content.dart | 85 ++++++++++ test/customer_fare_estimate_test.dart | 162 +++++++++++++++++++ 7 files changed, 459 insertions(+), 10 deletions(-) create mode 100644 test/customer_fare_estimate_test.dart diff --git a/README.md b/README.md index e1f0af4..678abc3 100644 --- a/README.md +++ b/README.md @@ -177,15 +177,20 @@ FCM data 的值一律是字串,App 端 `fleetEventFromPushData()` 會把座標 已核准→首頁;能不能接單以後端 `can_accept` 為準(App 不自行推導)。 admin 端在司機管理頁核准/退回(退回須附原因)。 -**目前**:`flutter analyze` 無 issue、`flutter test` **179 passed**。 +- **建單前車資預估(懸而未決 #1,2026-07-23)**:叫車表單顯示**預估車資**, + 地圖選目的地(單點)或停靠點填完(多停靠點)時自動算、車種變更時重算。 + 後端新開 `POST /api/customer/rides/estimate`(以全程規劃路線試算,與完成計費共用 + `FeeSettings.Quote`)。**是預估不是定價**——實際依行駛路線於行程結束時結算,卡片明確標示; + 失敗靜默不擋叫車。詳見 [`docs/TODO.md`](docs/TODO.md)「💰 建單前車資預估」。 + +**目前**:`flutter analyze` 無 issue、`flutter test` **197 passed**。 ## 規劃中(尚未實作) > 完整規格與待拍板事項見 [`docs/TODO.md`](docs/TODO.md) 與後端 > [line-fleet-dispatch/docs/TODO.md](../line-fleet-dispatch/docs/TODO.md)。 -- **待產品拍板**(見 TODO「懸而未決」):多停靠點的**建單前車資預估** - (需後端新開報價 API;要嘛接受「先搭後知價」,要嘛投資一支 API)。 +- 依賴外部資源/實機的項目(A2 真裝置推播、A5 iOS 實機部署與 iOS 推播)——見 TODO。 ## 相關文件 diff --git a/docs/TODO.md b/docs/TODO.md index 433233a..85ec904 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -295,18 +295,51 @@ **且要先想清楚產品要的是停用、隱藏、還是照選但提示可能配不到**。等產品定方向。 - **admin 代司機改車牌**(可選):目前車牌只能司機自己改(改完回 pending 等審核)。 代改要處理「代改要不要重審」「誰負責填錯的責任」,**在有客服實際卡住的案例前不做**。 -- **車資預估報價 API**:見下方「懸而未決」第 1 項——後端根本沒有這支 API,需先拍板。 +- ~~**車資預估報價 API**~~ ✅ 已做(2026-07-23,見下方「💰 建單前車資預估」)。 ## 🔮 懸而未決(需產品拍板) > **等使用者拍板,未拍板前不要做**(2026-07-19 使用者:其他等我拍板)。 -1. **N 的衍生風險:乘客看不到預估車資** +1. [x] **N 的衍生風險:乘客看不到預估車資 ✅ 已解(2026-07-23,拍板投資報價 API)** N5 拍板「車資=全程實際路線(含繞路)」+ 多停靠點 → **繞路越多車資越高**, - 但乘客建單時**完全看不到預估**(後端只在完成時定格計費,**沒有報價 API**)。 - 多停靠點會放大這個問題:乘客排了 5 位乘客 10 個停靠點,卻要到行程結束才知道多少錢。 - **要解需要後端新開一支報價 API**(以全程路線試算),App 端才能在建單前顯示預估。 - **這是產品決策**:要嘛接受「先搭後知價」,要嘛投資一支報價 API。 + 舊狀況乘客建單時**完全看不到預估**(後端只在完成時定格計費,沒有報價 API)。 + **決策:投資一支報價 API**(非「先搭後知價」)。詳見下方「💰 建單前車資預估」段。 + +--- + +## 💰 建單前車資預估(懸而未決 #1,2026-07-23) + +> 拍板投資報價 API:乘客在**建單前**就看到預估車資,不必到行程結束才知道多少錢。 +> 多停靠點行程放大了「先搭後知價」的痛點(排一堆繞路卻看不到金額),這是本題的主因。 +> **是預估不是定價**——後端仍於行程完成時依**實際行駛路線**定格計費,兩者可能不同。 + +**後端**(dispatch,分支 `claude/quote-fare-estimate-api`): +- 新 `POST /api/customer/rides/estimate`(customer JWT,純唯讀、不建單、不寫 DB)。 +- `service.EstimateService`:以全程規劃路線(起點 → 各停靠點 → 終點,**含繞路**)算里程, + 與完成計費**共用同一份 `FeeSettings.Quote`**——預估與實收落在同一套費率規則, + 差異只來自「規劃路線 vs 實際行駛路線」。距離走 `RouteVia`(與 N5 計費同一支多點 API), + OSRM 掛掉時內部退回逐段 haversine,故**預估永遠算得出一個數**(近似),不會卡住乘客。 +- 輸入形狀與建單相同(沿用 `validateStops`/座標驗證),**目的地座標必填**(沒終點無法路由); + 車種選填(寵物車含清潔費)。回傳白名單欄位:`fare_cents`/`cleaning_fee_cents`/`total_cents`/ + `distance_m`/`duration_sec`——**不回手續費/實得等內部費率**(比照 `CustomerJSON`)。 +- 測試:service 8 案(單點/多停靠點全程入路線/寵物清潔費/缺目的地 400/非法車種/ + min_fare 下限/未成對停靠點/未就緒)+ handler 2 案(授權 401/403、綁定 400、未就緒 503)。 + +**App**(fleet-app,本分支): +- `FareEstimate` 模型 + `CustomerApiClient.estimateFare`;`CustomerController` 加預估狀態, + **地圖選點目的地時**(單點)或**停靠點填完時**(多停靠點)自動算,**車種變更時重算** + (寵物車加清潔費要即時反映)。dropoff 座標存在 controller 才能在車種變更時重算。 +- 叫車表單顯示 `_FareEstimateCard`:有清潔費時拆「車資 + 寵物車清潔費 = 預估合計」, + 否則單一預估金額;附「約 X 公里・Y 分鐘」與**「實際車資依行駛路線可能不同,於行程結束時結算」**。 +- **失敗一律靜默清空**——預估只是輔助資訊,不擋叫車、不彈錯誤(與 P5 查費率同一原則); + 單點模式需要上車 GPS(優先用已取得的定位,8 秒逾時),多停靠點由 stops 推導不需 GPS。 +- 測試:`customer_fare_estimate_test` 7 案(多停靠點帶 stops 不需 GPS/車種變更重算含清潔費/ + 失敗靜默/clearEstimate/移除乘客清空/模型解析);`flutter analyze` 無 issue、`flutter test` 197 passed。 + +**驗收**:三端(此處為兩端)各自 build/lint/test 綠——dispatch service+handler 單元測試綠、 +app `flutter test` 197 passed。**尚未做**:模擬器實跑 E2E(選目的地→看到預估→叫車→完成對帳 +「預估 vs 實收」的差異合理);需後端 docker 起服務,留待下次。 --- @@ -639,7 +672,7 @@ admin 月報表頁 UI 亦渲染相同數字(NT$85.00/NT$12.75/NT$3,012.75 ### App 端待拍板 - 停靠點編輯的 UX:一次填滿 5 位很繁瑣,是否預設 1 位、按「+ 新增乘客」漸進展開? -- 車資預估:乘客建單時要不要先顯示預估車資?(後端目前只在完成時定格計費,無報價 API) +- ~~車資預估:乘客建單時要不要先顯示預估車資?~~ ✅ 已做(2026-07-23,報價 API,見下方「💰 建單前車資預估」)。 --- diff --git a/lib/core/api/customer_api_client.dart b/lib/core/api/customer_api_client.dart index c5f5ed6..36df2b5 100644 --- a/lib/core/api/customer_api_client.dart +++ b/lib/core/api/customer_api_client.dart @@ -98,6 +98,40 @@ class CustomerApiClient { } } + /// 建單**前**預估車資(懸而未決 #1,對齊 POST /api/customer/rides/estimate)。 + /// + /// 單點行程:pickup(GPS)+ dropoff 座標必填(沒終點無法算路線)。 + /// 多停靠點行程:帶 stops,後端由它推導起訖,pickup/dropoff 會被忽略(照樣送 pickup 佔位)。 + /// 指定寵物車時預估會含清潔費。 + Future estimateFare({ + required double pickupLat, + required double pickupLng, + double? dropoffLat, + double? dropoffLng, + String? requiredVehicleType, + List stops = const [], + }) async { + try { + final res = await _dio.post>( + '/customer/rides/estimate', + data: { + 'pickup_lat': pickupLat, + 'pickup_lng': pickupLng, + if (dropoffLat != null && dropoffLng != null) ...{ + 'dropoff_lat': dropoffLat, + 'dropoff_lng': dropoffLng, + }, + if (requiredVehicleType != null && requiredVehicleType.isNotEmpty) + 'required_vehicle_type': requiredVehicleType, + if (stops.isNotEmpty) 'stops': [for (final s in stops) s.toJson()], + }, + ); + return FareEstimate.fromJson(res.data!); + } on DioException catch (e) { + throw _wrap(e); + } + } + /// 查乘客可讀的費率(對齊 GET /api/customer/fees,P5)。 /// /// 後端是**白名單輸出**,目前只回 pet_cleaning_fee_bps——不會有手續費/月會費。 diff --git a/lib/core/models/models.dart b/lib/core/models/models.dart index 0451ee7..f946b30 100644 --- a/lib/core/models/models.dart +++ b/lib/core/models/models.dart @@ -168,6 +168,42 @@ class CompletedRideSummary { fareAmountCents == null ? null : fareAmountCents! + (cleaningFeeCents ?? 0); } +/// 建單**前**的車資預估(懸而未決 #1)。金額皆為「分」(整數元)。 +/// +/// 來自後端 `POST /api/customer/rides/estimate`:以全程規劃路線試算,讓乘客在多停靠點 +/// 排一堆繞路之前就先看到大概金額。**是預估不是定價**——實際依行駛路線(繞路、跳過站、 +/// 路況)於行程完成時才定格,兩者可能不同,UI 必須標明。 +/// 只含乘客該知道的欄位:車資、清潔費、合計、距離、時間——不含手續費/實得等內部費率。 +class FareEstimate { + const FareEstimate({ + required this.fareCents, + required this.cleaningFeeCents, + required this.totalCents, + required this.distanceM, + required this.durationSec, + }); + + final int fareCents; + + /// 寵物車清潔費(分);只有指定寵物車時 > 0。 + final int cleaningFeeCents; + + /// 乘客實付總額(分)=車資 + 清潔費。 + final int totalCents; + final int distanceM; + final int durationSec; + + bool get hasCleaningFee => cleaningFeeCents > 0; + + factory FareEstimate.fromJson(Map json) => FareEstimate( + fareCents: (json['fare_cents'] as num?)?.toInt() ?? 0, + cleaningFeeCents: (json['cleaning_fee_cents'] as num?)?.toInt() ?? 0, + totalCents: (json['total_cents'] as num?)?.toInt() ?? 0, + distanceM: (json['distance_m'] as num?)?.toInt() ?? 0, + durationSec: (json['duration_sec'] as num?)?.toInt() ?? 0, + ); +} + /// 司機資訊(ride.accepted payload,O4/O7)。 /// /// 車種/車牌來自 ride 快照(司機換車後歷史不變),電話為 drivers 即時值 diff --git a/lib/customer/customer_controller.dart b/lib/customer/customer_controller.dart index a76040d..81412f3 100644 --- a/lib/customer/customer_controller.dart +++ b/lib/customer/customer_controller.dart @@ -54,6 +54,13 @@ class CustomerController extends ChangeNotifier { int? _petCleaningFeeBps; // 多乘客行程的編輯狀態(N3);空 = 單點訂單。 final List _passengers = []; + // 建單前的車資預估(懸而未決 #1);null =尚無預估(未選目的地/預估失敗)。 + FareEstimate? _estimate; + bool _estimating = false; + // 單點模式下地圖選點得到的目的地座標——存在 controller 才能在車種變更時重算預估 + // (地址欄的座標在 widget,但價格會受車種影響,預估的權威輸入放這裡才同步得了)。 + double? _estDropoffLat; + double? _estDropoffLng; int? _liveEtaSec; int? _liveDistM; double? _liveDriverLat; @@ -82,6 +89,8 @@ class CustomerController extends ChangeNotifier { bool get busy => _busy; bool get wsConnected => _wsConnected; Position? get lastPosition => _lastPosition; + FareEstimate? get fareEstimate => _estimate; + bool get estimating => _estimating; CustomerRide? get activeRide => _activeRide; /// 司機姓名。優先來自 ride.accepted WS 事件,錯過事件時由 GET active 還原 @@ -145,6 +154,7 @@ class CustomerController extends ChangeNotifier { void disableMultiStop() { _passengers.clear(); notifyListeners(); + _refreshEstimate(); } /// 新增一位乘客(標籤自動給 A/B/C…,與司機端看到的一致)。 @@ -167,6 +177,7 @@ class CustomerController extends ChangeNotifier { ); } notifyListeners(); + _refreshEstimate(); } /// 設定某位乘客的上車/下車點。 @@ -175,6 +186,7 @@ class CustomerController extends ChangeNotifier { if (pickup != null) _passengers[index].pickup = pickup; if (dropoff != null) _passengers[index].dropoff = dropoff; notifyListeners(); + _refreshEstimate(); } static String _labelFor(int index) => @@ -184,11 +196,84 @@ class CustomerController extends ChangeNotifier { Future setRequiredVehicleType(VehicleType? type) async { _requiredVehicleType = type; notifyListeners(); + // 車種影響價格(寵物車加清潔費)→ 重算預估,讓金額與選擇同步。 + _refreshEstimate(); if (type == VehicleType.pet && _petCleaningFeeBps == null) { await refreshPetCleaningFee(); } } + /// 記住地圖選點的目的地座標並算一次預估(懸而未決 #1,單點模式)。 + void setEstimateDropoff(double lat, double lng) { + _estDropoffLat = lat; + _estDropoffLng = lng; + _refreshEstimate(); + } + + /// 清掉目的地座標與預估(手動改地址、或收合表單時)。 + void clearEstimate() { + _estDropoffLat = null; + _estDropoffLng = null; + if (_estimate != null || _estimating) { + _estimate = null; + _estimating = false; + notifyListeners(); + } + } + + /// 依目前輸入(單點座標或多停靠點 stops + 指定車種)重算車資預估。 + /// + /// **失敗一律靜默清空**——預估只是輔助資訊,不可擋叫車、不彈錯誤(與 P5 查費率同一原則)。 + /// 單點模式需要目的地座標與上車 GPS;多停靠點模式由 stops 推導,不需 GPS。 + Future _refreshEstimate() async { + if (_session == null) return; + final stops = buildStops(_passengers); + final hasStops = stops.isNotEmpty; + if (!hasStops && (_estDropoffLat == null || _estDropoffLng == null)) { + // 沒有可預估的輸入(未選地圖目的地,也非多停靠點)→ 清空。 + if (_estimate != null || _estimating) { + _estimate = null; + _estimating = false; + notifyListeners(); + } + return; + } + _estimating = true; + notifyListeners(); + try { + var pickupLat = 0.0; + var pickupLng = 0.0; + if (!hasStops) { + // 單點模式需要上車座標;優先用已取得的定位,否則現取(8 秒逾時,見 _acquirePosition)。 + final pos = _lastPosition ?? await _acquirePosition(); + if (pos == null) { + _estimate = null; + _estimating = false; + notifyListeners(); + return; + } + _lastPosition = pos; + pickupLat = pos.latitude; + pickupLng = pos.longitude; + } + final est = await _api.estimateFare( + pickupLat: pickupLat, + pickupLng: pickupLng, + dropoffLat: hasStops ? null : _estDropoffLat, + dropoffLng: hasStops ? null : _estDropoffLng, + requiredVehicleType: _requiredVehicleType?.code, + stops: stops, + ); + _estimate = est; + } catch (_) { + // 任何失敗(網路、權限、路線)都不顯示預估,也不擋叫車。 + _estimate = null; + } finally { + _estimating = false; + notifyListeners(); + } + } + /// 查乘客可讀的清潔費率(P5)。失敗**不設值也不擋叫車**—— /// UI 會降級顯示「將加收清潔費(上限 30%)」,總比因為查費率失敗而不能叫車好。 Future refreshPetCleaningFee() async { @@ -336,6 +421,10 @@ class CustomerController extends ChangeNotifier { _rideCancelled = false; _requiredVehicleType = null; _passengers.clear(); + _estimate = null; + _estimating = false; + _estDropoffLat = null; + _estDropoffLng = null; _liveEtaSec = null; _liveDistM = null; _liveDriverLat = null; @@ -639,6 +728,11 @@ class CustomerController extends ChangeNotifier { _lastActiveRide = ride; // 這趟已送出,編輯狀態不該留到下一趟。 _passengers.clear(); + // 預估屬於「建單前」的輔助資訊,送出後就該收掉,不留到下一趟。 + _estimate = null; + _estimating = false; + _estDropoffLat = null; + _estDropoffLng = null; _driverName = null; _driverInfo = null; // 新的一趟開始 → 上一趟的取消原因不該還掛著。 diff --git a/lib/customer/widgets/ride_phase_content.dart b/lib/customer/widgets/ride_phase_content.dart index e787eeb..84c548f 100644 --- a/lib/customer/widgets/ride_phase_content.dart +++ b/lib/customer/widgets/ride_phase_content.dart @@ -336,6 +336,8 @@ class _OrderFormContentState extends State { _dropoffLat = null; _dropoffLng = null; }); + // 沒有座標就算不出預估(地址字串無法路由)→ 收掉預估。 + widget.ctrl.clearEstimate(); } }, decoration: const InputDecoration( @@ -366,6 +368,11 @@ class _OrderFormContentState extends State { const SizedBox(height: 12), // P2:指定車種。預設「不指定」=維持現行行為(任何車種都可派)。 VehicleTypePicker(ctrl: ctrl), + // 懸而未決 #1:建單前車資預估。有輸入才顯示(選了地圖目的地或多停靠點)。 + if (ctrl.estimating || ctrl.fareEstimate != null) ...[ + const SizedBox(height: 12), + _FareEstimateCard(ctrl: ctrl), + ], const SizedBox(height: 16), FilledButton.icon( onPressed: ctrl.busy ? null : () => _submit(context), @@ -392,6 +399,8 @@ class _OrderFormContentState extends State { _dropoffLat = picked.lat; _dropoffLng = picked.lng; }); + // 有了目的地座標即可預估車資(懸而未決 #1)——不擋叫車,失敗靜默。 + widget.ctrl.setEstimateDropoff(picked.lat, picked.lng); } } @@ -470,6 +479,82 @@ class _CancelNoticeCard extends StatelessWidget { } } +/// 建單前的車資預估卡(懸而未決 #1)。 +/// +/// **明確標示是預估、不是定價**:後端於行程完成時才依實際行駛路線定格計費, +/// 繞路/跳過站/路況都會讓實收與此預估不同。有清潔費時比照完成卡拆分項 +/// (車資 + 寵物車清潔費 = 合計),沒有時只顯示單一預估金額。 +class _FareEstimateCard extends StatelessWidget { + const _FareEstimateCard({required this.ctrl}); + + final CustomerController ctrl; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final est = ctrl.fareEstimate; + return Card( + margin: EdgeInsets.zero, + color: scheme.secondaryContainer, + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Icon(Icons.receipt_long, size: 20, color: scheme.onSecondaryContainer), + const SizedBox(width: 8), + Text('預估車資', + style: theme.textTheme.titleSmall + ?.copyWith(color: scheme.onSecondaryContainer)), + const Spacer(), + if (ctrl.estimating) + const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ], + ), + if (est != null) ...[ + const SizedBox(height: 8), + if (est.hasCleaningFee) ...[ + _FareRow(label: '車資', cents: est.fareCents), + const SizedBox(height: 4), + _FareRow(label: '寵物車清潔費', cents: est.cleaningFeeCents), + const Divider(height: 16), + _FareRow(label: '預估合計', cents: est.totalCents, emphasize: true), + ] else + _FareRow(label: '預估合計', cents: est.totalCents, emphasize: true), + const SizedBox(height: 6), + Text( + '約 ${_km(est.distanceM)} 公里・${_min(est.durationSec)} 分鐘', + style: theme.textTheme.bodySmall + ?.copyWith(color: scheme.onSecondaryContainer), + ), + const SizedBox(height: 4), + Text( + '實際車資依行駛路線可能不同,於行程結束時結算。', + style: theme.textTheme.bodySmall?.copyWith( + color: scheme.onSecondaryContainer.withValues(alpha: 0.75), + ), + ), + ], + ], + ), + ), + ); + } + + // 公尺 → 一位小數的公里字串(4823 → "4.8")。 + String _km(int meters) => (meters / 1000).toStringAsFixed(1); + + // 秒 → 分鐘(無條件進位,至少 1 分鐘,避免顯示 0 分鐘)。 + int _min(int seconds) => seconds <= 0 ? 1 : ((seconds + 59) ~/ 60); +} + /// 完成卡的費用列(O6 分項用)。 class _FareRow extends StatelessWidget { const _FareRow({ diff --git a/test/customer_fare_estimate_test.dart b/test/customer_fare_estimate_test.dart new file mode 100644 index 0000000..755163b --- /dev/null +++ b/test/customer_fare_estimate_test.dart @@ -0,0 +1,162 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:line_fleet_app/core/api/customer_api_client.dart'; +import 'package:line_fleet_app/core/api/fleet_api_client.dart' show ApiException; +import 'package:line_fleet_app/core/models/models.dart'; +import 'package:line_fleet_app/customer/customer_controller.dart'; + +/// 記錄 estimateFare 收到的參數,回一筆可控的預估;可設定為丟例外(測靜默失敗)。 +class _FakeEstimateApi extends CustomerApiClient { + _FakeEstimateApi(); + + int calls = 0; + List lastStops = const []; + String? lastVehicleType; + bool shouldThrow = false; + FareEstimate result = const FareEstimate( + fareCents: 18500, + cleaningFeeCents: 0, + totalCents: 18500, + distanceM: 5000, + durationSec: 600, + ); + + @override + Future estimateFare({ + required double pickupLat, + required double pickupLng, + double? dropoffLat, + double? dropoffLng, + String? requiredVehicleType, + List stops = const [], + }) async { + calls++; + lastStops = stops; + lastVehicleType = requiredVehicleType; + if (shouldThrow) { + throw ApiException('boom'); + } + return result; + } + + // 選寵物車時 controller 會查費率,避免打真網路。 + @override + Future fetchPetCleaningFeeBps() async => 2000; +} + +void main() { + StopPoint p(double v) => StopPoint(lat: v, lng: v, address: '地點$v'); + + // _refreshEstimate 是 fire-and-forget 的 async,flush 幾輪微任務讓它跑完。 + Future flush() async { + for (var i = 0; i < 3; i++) { + await Future.delayed(Duration.zero); + } + } + + group('建單前車資預估(懸而未決 #1)', () { + late _FakeEstimateApi api; + late CustomerController ctrl; + + setUp(() { + api = _FakeEstimateApi(); + ctrl = CustomerController(api: api); + ctrl.setSessionForTest( + const CustomerSession(customerId: 1, token: 'tok', name: '小美'), + ); + }); + + tearDown(() => ctrl.dispose()); + + test('多停靠點填完 → 帶 stops 預估,不需 GPS', () async { + ctrl.addPassenger(); + ctrl.setPassengerPoint(0, pickup: p(1), dropoff: p(2)); + await flush(); + + expect(api.calls, greaterThan(0)); + expect(api.lastStops, isNotEmpty, reason: '多停靠點模式應帶 stops'); + expect(ctrl.fareEstimate, isNotNull); + expect(ctrl.fareEstimate!.totalCents, 18500); + expect(ctrl.estimating, isFalse); + }); + + test('車種改寵物車 → 重算預估並帶新車種(含清潔費)', () async { + ctrl.addPassenger(); + ctrl.setPassengerPoint(0, pickup: p(1), dropoff: p(2)); + await flush(); + final before = api.calls; + + // 寵物車的預估含清潔費。 + api.result = const FareEstimate( + fareCents: 18500, + cleaningFeeCents: 3700, + totalCents: 22200, + distanceM: 5000, + durationSec: 600, + ); + await ctrl.setRequiredVehicleType(VehicleType.pet); + await flush(); + + expect(api.calls, greaterThan(before), reason: '車種變更要觸發重算'); + expect(api.lastVehicleType, VehicleType.pet.code); + expect(ctrl.fareEstimate!.hasCleaningFee, isTrue); + expect(ctrl.fareEstimate!.totalCents, 22200); + }); + + test('預估失敗 → 靜默清空,不擋叫車、不丟例外', () async { + api.shouldThrow = true; + ctrl.addPassenger(); + ctrl.setPassengerPoint(0, pickup: p(1), dropoff: p(2)); + await flush(); + + expect(api.calls, greaterThan(0)); + expect(ctrl.fareEstimate, isNull, reason: '失敗時不顯示預估'); + expect(ctrl.estimating, isFalse); + }); + + test('clearEstimate 清掉預估與座標', () async { + ctrl.addPassenger(); + ctrl.setPassengerPoint(0, pickup: p(1), dropoff: p(2)); + await flush(); + expect(ctrl.fareEstimate, isNotNull); + + ctrl.clearEstimate(); + expect(ctrl.fareEstimate, isNull); + expect(ctrl.estimating, isFalse); + }); + + test('移除全部乘客且無單點目的地 → 沒有可預估輸入,清空', () async { + ctrl.addPassenger(); + ctrl.setPassengerPoint(0, pickup: p(1), dropoff: p(2)); + await flush(); + expect(ctrl.fareEstimate, isNotNull); + + ctrl.disableMultiStop(); // 清空乘客 + await flush(); + expect(ctrl.fareEstimate, isNull, reason: '無 stops 又無單點座標 → 無預估'); + }); + }); + + group('FareEstimate 模型', () { + test('fromJson 解析後端欄位', () { + final e = FareEstimate.fromJson(const { + 'fare_cents': 18500, + 'cleaning_fee_cents': 3700, + 'total_cents': 22200, + 'distance_m': 5000, + 'duration_sec': 600, + }); + expect(e.fareCents, 18500); + expect(e.cleaningFeeCents, 3700); + expect(e.totalCents, 22200); + expect(e.hasCleaningFee, isTrue); + }); + + test('缺鍵時歸零、無清潔費', () { + final e = FareEstimate.fromJson(const {'total_cents': 8500}); + expect(e.fareCents, 0); + expect(e.cleaningFeeCents, 0); + expect(e.hasCleaningFee, isFalse); + expect(e.totalCents, 8500); + }); + }); +} From f794095297db3cace4e93c1d248b2d1b4a9e29f5 Mon Sep 17 00:00:00 2001 From: awei Date: Thu, 23 Jul 2026 08:24:33 +0800 Subject: [PATCH 2/2] =?UTF-8?q?docs:=20=E5=BB=BA=E5=96=AE=E5=89=8D?= =?UTF-8?q?=E8=BB=8A=E8=B3=87=E9=A0=90=E4=BC=B0=E6=A8=A1=E6=93=AC=E5=99=A8?= =?UTF-8?q?=20E2E=20=E5=B0=8D=E5=B8=B3=E7=B5=90=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit App 建單 ride #24 完成卡「車資 NT$94」=同座標預估 NT$94;API 層單點與寵物車 (清潔費 20%)預估皆與完成實收完全一致(共用 FeeSettings.Quote+同一 OSRM 路線)。 Co-Authored-By: Claude Opus 4.8 --- README.md | 3 ++- docs/TODO.md | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 678abc3..03912d4 100644 --- a/README.md +++ b/README.md @@ -181,7 +181,8 @@ FCM data 的值一律是字串,App 端 `fleetEventFromPushData()` 會把座標 地圖選目的地(單點)或停靠點填完(多停靠點)時自動算、車種變更時重算。 後端新開 `POST /api/customer/rides/estimate`(以全程規劃路線試算,與完成計費共用 `FeeSettings.Quote`)。**是預估不是定價**——實際依行駛路線於行程結束時結算,卡片明確標示; - 失敗靜默不擋叫車。詳見 [`docs/TODO.md`](docs/TODO.md)「💰 建單前車資預估」。 + 失敗靜默不擋叫車。**已模擬器實跑對帳**:App 建單→完成,完成卡車資與預估完全一致 + (不繞路時實收=預估)。詳見 [`docs/TODO.md`](docs/TODO.md)「💰 建單前車資預估」。 **目前**:`flutter analyze` 無 issue、`flutter test` **197 passed**。 diff --git a/docs/TODO.md b/docs/TODO.md index 85ec904..0ec16b1 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -338,8 +338,19 @@ 失敗靜默/clearEstimate/移除乘客清空/模型解析);`flutter analyze` 無 issue、`flutter test` 197 passed。 **驗收**:三端(此處為兩端)各自 build/lint/test 綠——dispatch service+handler 單元測試綠、 -app `flutter test` 197 passed。**尚未做**:模擬器實跑 E2E(選目的地→看到預估→叫車→完成對帳 -「預估 vs 實收」的差異合理);需後端 docker 起服務,留待下次。 +app `flutter test` 197 passed。 + +**✅ 模擬器實跑 E2E 對帳(2026-07-23,`m6_pixel` + 後端 quote-api worktree 本機起服務)**: +- **App UI 實跑**:地圖選目的地 → 叫車表單出現「預估車資」卡(**預估合計 NT$221・約 6.8 公里・ + 10 分鐘**+「實際車資依行駛路線可能不同,於行程結束時結算」免責文案);GPS 上車點以模擬器 + `geo fix` 帶入,目的地由地圖選點(`geocoding` 反查)→ `setEstimateDropoff` 觸發預估。 +- **完整鏈路對帳**:App 叫車建 ride #24(429m)→ 司機 API 接單→上車→完成(不補軌跡)→ + **App 完成卡顯示「車資 NT$94」**,與同座標 estimate 回的預估 **NT$94(9400 分)完全一致**。 +- **API 層對帳(決定性,同一後端)**:預估與完成共用 `FeeSettings.Quote`+同一 OSRM 路線 → + 單點(6811m)預估 fare 22100 = 完成實收 22100;**寵物車**(清潔費率設 20%)預估 + fare 22100+清潔費 4400 = 完成實收 22100+4400(**車資與清潔費皆一致**)。 +- 結論:不繞路時**實收=預估**(同路線同費率);繞路時走 N5 既有 `max(軌跡, 路線)` 邏輯, + 故免責文案「實際依行駛路線可能不同」成立。 ---