diff --git a/README.md b/README.md index 7df374a..5286fdf 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,9 @@ FCM data 的值一律是字串,App 端 `fleetEventFromPushData()` 會把座標 (該趟車資×%,建單快照)→ 與司機對話 → 司機尋獲後支付處理費 → 歸還結案; 司機端 AppBar「遺失物協尋」工作清單(已找到/已歸還/未尋獲結案)。 處理費% 由 admin 費率設定頁調整(後端 `lost_item_fee_bps`)。 +- **我的行程歷史(2026-07-19)**:乘客首頁右上「我的行程」→ 列出過去行程 + (狀態/路線/時間/車資);**有司機的行程可事後「聯絡司機」**開對話 + (沿用 `RideChatScreen`)。後端 `GET /customer/rides`(只回本人,LEFT JOIN 司機名)。 - **司機端概覽地圖(2026-07-16)**:接單後行程卡內嵌地圖(flutter_map + OSM,免 key)—— 自己(綠色計程車)+目標(前往上車點=紅釘/行程中=藍旗)+兩點連線,相機自動框住兩點。 **只做「看位置」,不做導航**——turn-by-turn 仍由「導航」按鈕跳外部 Google Maps/Waze。 @@ -133,8 +136,6 @@ FCM data 的值一律是字串,App 端 `fleetEventFromPushData()` 會把座標 > 完整規格與待拍板事項見 [`docs/TODO.md`](docs/TODO.md) 與後端 > [line-fleet-dispatch/docs/TODO.md](../line-fleet-dispatch/docs/TODO.md)。 -- **留言板入口補遺**:沿用既有 `RideChatScreen`(本來就有 REST 歷史+WS 即時), - 補上「歷史行程也能進入對話」的入口,讓乘客事後(例如找遺失物)仍能聯絡司機。 - **待產品拍板**(見 TODO「懸而未決」):O5 admin 車輛審核(會讓司機端三態變四態)、 多停靠點的**建單前車資預估**(需後端新開報價 API)。 diff --git a/docs/TODO.md b/docs/TODO.md index a142a12..fdd3378 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -546,9 +546,14 @@ admin 月報表頁 UI 亦渲染相同數字(NT$85.00/NT$12.75/NT$3,012.75 未指定時完成卡不該出現清潔費欄位。 `CompletedRideSummary` 目前只有 `fareAmountCents`,要加 `cleaningFeeCents`。 沿用 `money.dart` 的整數元格式(M 已定案)。 -- [ ] **留言板**:沿用既有 `RideChatScreen`(H1,已有 REST 歷史+WS 即時)。 - 需確認「行程完成很久之後仍能進入對話」的入口——目前入口綁在進行中行程/協尋單上, - 歷史行程沒有對話入口(**可能要加**)。 +- [x] **留言板入口補遺** ✅ 2026-07-19:加「我的行程」歷史畫面 + (`CustomerRideHistoryScreen`,首頁右上 receipt FAB 進入),列出過去行程 + (狀態/路線/時間/車資),**有派到司機的行程**給「聯絡司機」開 `RideChatScreen` + (派單前取消的無對象可聯絡)。後端新增 `GET /customer/rides` + (dispatch PR #39:`ListRecentByCustomer`,LEFT JOIN drivers 取司機名,只回本人)。 + 沿用既有聊天,`RideChatScreen` 已按 `rideId` 過濾,重用 `ctrl.chatStream` 安全。 + **模擬器實跑驗過**:完成 ride #9 → 歷史畫面顯示(NT$212/司機名)→ 聯絡司機 + → 發訊右靠綠泡 → 後端持久化、司機端 `GET /rides/9/messages` 讀到 `customer:...`。 ### 乘客指定車種(✅ 2026-07-16 拍板採此方案,依賴後端 P1–P5) diff --git a/lib/core/api/customer_api_client.dart b/lib/core/api/customer_api_client.dart index e2f602a..c5f5ed6 100644 --- a/lib/core/api/customer_api_client.dart +++ b/lib/core/api/customer_api_client.dart @@ -134,6 +134,24 @@ class CustomerApiClient { } } + /// 我的行程歷史(新到舊)。供「事後聯絡司機」的入口。 + Future> fetchRideHistory({int limit = 20}) async { + try { + final res = await _dio.get>( + '/customer/rides', + queryParameters: {'limit': limit}, + ); + final raw = res.data?['rides']; + if (raw is! List) return const []; + return raw + .whereType() + .map((m) => CustomerRideSummary.fromJson(Map.from(m))) + .toList(); + } on DioException catch (e) { + throw _wrap(e); + } + } + /// 行程內對話歷史(afterId > 0 時做增量補讀,WS 斷線重連後補漏)。 Future> fetchMessages(int rideId, {int afterId = 0}) async { try { diff --git a/lib/core/models/models.dart b/lib/core/models/models.dart index 572a41a..cb3e4d9 100644 --- a/lib/core/models/models.dart +++ b/lib/core/models/models.dart @@ -269,6 +269,26 @@ abstract final class RideStatus { status == completed || status == cancelled; } +/// 訂單狀態的中文標籤(乘客端共用)。 +String rideStatusLabel(int status) { + switch (status) { + case RideStatus.requested: + return '尋找司機中'; + case RideStatus.assigned: + return '派單中'; + case RideStatus.accepted: + return '司機前往上車點'; + case RideStatus.pickedUp: + return '行程中'; + case RideStatus.completed: + return '已完成'; + case RideStatus.cancelled: + return '已取消'; + default: + return '狀態 $status'; + } +} + /// 乘客端當前訂單。狀態碼對齊後端 constants.RideStatus*。 /// 來源可能是下單回應(snake key: ride_id/status)或查詢 model.Ride /// (無 json tag → PascalCase key: ID/Status),故解析時兩者皆容。 @@ -302,24 +322,7 @@ class CustomerRide { return '約 ${(etaPickupSec! / 60).ceil()} 分鐘抵達'; } - String get statusLabel { - switch (status) { - case RideStatus.requested: - return '尋找司機中'; - case RideStatus.assigned: - return '派單中'; - case RideStatus.accepted: - return '司機前往上車點'; - case RideStatus.pickedUp: - return '行程中'; - case RideStatus.completed: - return '已完成'; - case RideStatus.cancelled: - return '已取消'; - default: - return '狀態 $status'; - } - } + String get statusLabel => rideStatusLabel(status); /// 乘客端分階段文案。`driverArrived` 來自 WS `driver.arrived` ///(後端狀態仍為 Accepted,不另存 DB flag)。 @@ -353,6 +356,58 @@ class CustomerRide { } } +/// 乘客端「我的行程」歷史列表的單筆(後端 GET /customer/rides 的 CustomerRideRow)。 +/// 夠渲染清單與開對話即可;`driverName` 只在有派到司機時非空 → 決定是否顯示「聯絡司機」。 +class CustomerRideSummary { + const CustomerRideSummary({ + required this.rideId, + required this.status, + required this.pickupAddress, + this.dropoffAddress, + this.requestedAt, + this.completedAt, + this.fareAmountCents, + this.driverId, + this.driverName, + }); + + final int rideId; + final int status; + final String pickupAddress; + final String? dropoffAddress; + final DateTime? requestedAt; + final DateTime? completedAt; + final int? fareAmountCents; + final int? driverId; + final String? driverName; + + /// 有派到司機才給「聯絡司機」——取消於派單前的行程沒有對象可聯絡。 + bool get hasDriver => driverId != null; + + String get statusLabel => rideStatusLabel(status); + + static DateTime? _parseTime(Object? v) { + if (v is! String || v.isEmpty) return null; + return DateTime.tryParse(v); + } + + factory CustomerRideSummary.fromJson(Map json) { + return CustomerRideSummary( + rideId: (json['id'] as num).toInt(), + status: (json['status'] as num?)?.toInt() ?? 0, + pickupAddress: json['pickup_address'] as String? ?? '', + dropoffAddress: (json['dropoff_address'] as String?)?.isNotEmpty == true + ? json['dropoff_address'] as String + : null, + requestedAt: _parseTime(json['requested_at']), + completedAt: _parseTime(json['completed_at']), + fareAmountCents: (json['fare_amount_cents'] as num?)?.toInt(), + driverId: (json['driver_id'] as num?)?.toInt(), + driverName: json['driver_name'] as String?, + ); + } +} + /// 行程內對話訊息(乘客↔司機)。來源:REST 歷史查詢或 WS `chat.message` payload, /// 兩者欄位相同(後端 rideMessagePayload 與 model JSON 對齊)。 class RideMessage { diff --git a/lib/customer/customer_controller.dart b/lib/customer/customer_controller.dart index ad5f25f..d5d1258 100644 --- a/lib/customer/customer_controller.dart +++ b/lib/customer/customer_controller.dart @@ -70,6 +70,11 @@ class CustomerController extends ChangeNotifier { // 遺失物:未結案協尋單(WS lost_item.* 即時更新)。 List _lostItems = []; + // 歷史行程(我的行程列表;進畫面時才載入)。 + List _rideHistory = []; + bool _historyLoading = false; + String? _historyError; + CustomerSession? get session => _session; bool get isLoggedIn => _session != null; bool get loading => _loading; @@ -217,6 +222,27 @@ class CustomerController extends ChangeNotifier { /// 未結案遺失物協尋單。 List get lostItems => _lostItems; + /// 歷史行程(我的行程列表)。 + List get rideHistory => List.unmodifiable(_rideHistory); + bool get historyLoading => _historyLoading; + String? get historyError => _historyError; + + /// 載入歷史行程(進「我的行程」畫面時呼叫)。 + Future loadRideHistory() async { + if (_session == null) return; + _historyLoading = true; + _historyError = null; + notifyListeners(); + try { + _rideHistory = await _api.fetchRideHistory(); + } on ApiException catch (e) { + _historyError = e.message; + } finally { + _historyLoading = false; + notifyListeners(); + } + } + /// 聊天室開啟/關閉;開啟時清未讀並停止累計。 void setChatVisible(bool visible) { _chatVisible = visible; diff --git a/lib/customer/screens/customer_map_home_screen.dart b/lib/customer/screens/customer_map_home_screen.dart index 95bad7e..c6d26ab 100644 --- a/lib/customer/screens/customer_map_home_screen.dart +++ b/lib/customer/screens/customer_map_home_screen.dart @@ -7,6 +7,7 @@ import '../../core/models/models.dart'; import '../../core/util/map_tiles.dart'; import '../customer_controller.dart'; import '../widgets/ride_phase_content.dart'; +import 'ride_history_screen.dart'; /// 地圖為底+Bottom Sheet 主畫面(spec §2.1)。 /// 圖磚走 OpenStreetMap(flutter_map),不需任何 API key。 @@ -47,10 +48,26 @@ class _CustomerMapHomeScreenState extends State { Positioned( top: MediaQuery.of(context).padding.top + 12, right: 16, - child: FloatingActionButton.small( - heroTag: 'logout', - onPressed: ctrl.loading ? null : () => ctrl.logout(), - child: const Icon(Icons.logout), + child: Column( + children: [ + FloatingActionButton.small( + heroTag: 'history', + tooltip: '我的行程', + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => const CustomerRideHistoryScreen(), + ), + ), + child: const Icon(Icons.receipt_long), + ), + const SizedBox(height: 12), + FloatingActionButton.small( + heroTag: 'logout', + tooltip: '登出', + onPressed: ctrl.loading ? null : () => ctrl.logout(), + child: const Icon(Icons.logout), + ), + ], ), ), DraggableScrollableSheet( diff --git a/lib/customer/screens/ride_history_screen.dart b/lib/customer/screens/ride_history_screen.dart new file mode 100644 index 0000000..5ed451e --- /dev/null +++ b/lib/customer/screens/ride_history_screen.dart @@ -0,0 +1,228 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../../core/models/models.dart'; +import '../../core/util/money.dart'; +import '../../shared/screens/ride_chat_screen.dart'; +import '../customer_controller.dart'; + +/// 「我的行程」歷史列表(留言板入口補遺)。 +/// +/// 過去行程沒有其他對話入口——這裡讓乘客事後(例如想起有東西忘在車上、 +/// 或對車資有疑問)仍能聯絡當時的司機。**只有派到司機的行程**才給「聯絡司機」, +/// 派單前就取消的行程沒有對象可聯絡。 +class CustomerRideHistoryScreen extends StatefulWidget { + const CustomerRideHistoryScreen({super.key}); + + @override + State createState() => + _CustomerRideHistoryScreenState(); +} + +class _CustomerRideHistoryScreenState extends State { + @override + void initState() { + super.initState(); + // build 期間不可改 provider 狀態,排到下一影格。 + WidgetsBinding.instance.addPostFrameCallback((_) { + context.read().loadRideHistory(); + }); + } + + @override + Widget build(BuildContext context) { + final ctrl = context.watch(); + return Scaffold( + appBar: AppBar(title: const Text('我的行程')), + body: RefreshIndicator( + onRefresh: ctrl.loadRideHistory, + child: _body(context, ctrl), + ), + ); + } + + Widget _body(BuildContext context, CustomerController ctrl) { + if (ctrl.historyLoading && ctrl.rideHistory.isEmpty) { + return const Center(child: CircularProgressIndicator()); + } + if (ctrl.historyError != null && ctrl.rideHistory.isEmpty) { + return _ErrorState( + message: ctrl.historyError!, + onRetry: ctrl.loadRideHistory, + ); + } + if (ctrl.rideHistory.isEmpty) { + // ListView 而非 Center,讓下拉刷新在空清單也能觸發。 + return ListView( + children: [ + const SizedBox(height: 120), + Center( + child: Text( + '還沒有行程紀錄', + style: Theme.of(context).textTheme.bodyLarge, + ), + ), + ], + ); + } + return ListView.builder( + padding: const EdgeInsets.all(12), + itemCount: ctrl.rideHistory.length, + itemBuilder: (context, i) => + _RideHistoryCard(ctrl: ctrl, ride: ctrl.rideHistory[i]), + ); + } +} + +class _RideHistoryCard extends StatelessWidget { + const _RideHistoryCard({required this.ctrl, required this.ride}); + + final CustomerController ctrl; + final CustomerRideSummary ride; + + static const _months = [ + '', '1月', '2月', '3月', '4月', '5月', '6月', + '7月', '8月', '9月', '10月', '11月', '12月', + ]; + + String _dateLabel() { + final t = ride.completedAt ?? ride.requestedAt; + if (t == null) return ''; + final local = t.toLocal(); + final hh = local.hour.toString().padLeft(2, '0'); + final mm = local.minute.toString().padLeft(2, '0'); + return '${_months[local.month]}${local.day}日 $hh:$mm'; + } + + void _openChat(BuildContext context) { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => RideChatScreen( + rideId: ride.rideId, + selfRole: 'customer', + title: '聯絡司機(行程 #${ride.rideId})', + loadHistory: ctrl.fetchMessages, + send: ctrl.sendMessage, + incoming: ctrl.chatStream, + onVisibilityChanged: ctrl.setChatVisible, + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final date = _dateLabel(); + return Card( + margin: const EdgeInsets.only(bottom: 12), + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + '行程 #${ride.rideId}', + style: theme.textTheme.titleMedium, + ), + ), + Chip( + label: Text(ride.statusLabel), + visualDensity: VisualDensity.compact, + ), + ], + ), + if (date.isNotEmpty) ...[ + const SizedBox(height: 2), + Text(date, style: theme.textTheme.bodySmall), + ], + const SizedBox(height: 10), + _RouteRow( + icon: Icons.my_location, + label: ride.pickupAddress.isEmpty ? '上車點' : ride.pickupAddress, + ), + if (ride.dropoffAddress != null) ...[ + const SizedBox(height: 4), + _RouteRow(icon: Icons.place, label: ride.dropoffAddress!), + ], + if (ride.driverName != null) ...[ + const SizedBox(height: 8), + Text('司機:${ride.driverName}', style: theme.textTheme.bodyMedium), + ], + if (ride.fareAmountCents != null) ...[ + const SizedBox(height: 4), + Text( + '車資 ${formatCentsAsNtd(ride.fareAmountCents!)}', + style: theme.textTheme.bodyMedium, + ), + ], + // 有派到司機才給對話入口——這是本畫面存在的理由(事後聯絡)。 + if (ride.hasDriver) ...[ + const SizedBox(height: 8), + Align( + alignment: Alignment.centerLeft, + child: OutlinedButton.icon( + onPressed: () => _openChat(context), + icon: const Icon(Icons.chat_bubble_outline, size: 18), + label: const Text('聯絡司機'), + ), + ), + ], + ], + ), + ), + ); + } +} + +class _RouteRow extends StatelessWidget { + const _RouteRow({required this.icon, required this.label}); + + final IconData icon; + final String label; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, size: 18, color: theme.colorScheme.outline), + const SizedBox(width: 8), + Expanded( + child: Text(label, style: theme.textTheme.bodyMedium), + ), + ], + ); + } +} + +class _ErrorState extends StatelessWidget { + const _ErrorState({required this.message, required this.onRetry}); + + final String message; + final Future Function() onRetry; + + @override + Widget build(BuildContext context) { + return ListView( + children: [ + const SizedBox(height: 100), + const Center(child: Icon(Icons.cloud_off, size: 40)), + const SizedBox(height: 12), + Center(child: Text(message, textAlign: TextAlign.center)), + const SizedBox(height: 16), + Center( + child: FilledButton.icon( + onPressed: () => onRetry(), + icon: const Icon(Icons.refresh), + label: const Text('重試'), + ), + ), + ], + ); + } +} diff --git a/test/customer_ride_history_test.dart b/test/customer_ride_history_test.dart new file mode 100644 index 0000000..0f42a0c --- /dev/null +++ b/test/customer_ride_history_test.dart @@ -0,0 +1,137 @@ +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +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'; +import 'package:line_fleet_app/customer/screens/ride_history_screen.dart'; +import 'package:provider/provider.dart'; + +class _FakeApi extends CustomerApiClient { + _FakeApi() : super(dio: Dio(BaseOptions(baseUrl: 'http://test.invalid/api'))); + + List history = const []; + ApiException? historyError; + int fetchCount = 0; + + @override + Future> fetchRideHistory({int limit = 20}) async { + fetchCount++; + if (historyError != null) throw historyError!; + return history; + } +} + +CustomerController _loggedIn(_FakeApi api) { + final ctrl = CustomerController(api: api); + ctrl.setSessionForTest( + const CustomerSession(customerId: 1, token: 'tok', name: '小美'), + ); + return ctrl; +} + +void main() { + group('CustomerRideSummary 解析', () { + test('有司機 → hasDriver;車資/時間/狀態解析', () { + final s = CustomerRideSummary.fromJson(const { + 'id': 42, + 'status': 4, + 'pickup_address': '台北101', + 'dropoff_address': '台北車站', + 'requested_at': '2026-07-18T10:00:00Z', + 'completed_at': '2026-07-18T10:30:00Z', + 'fare_amount_cents': 21500, + 'driver_id': 7, + 'driver_name': '阿明', + }); + expect(s.hasDriver, isTrue); + expect(s.driverName, '阿明'); + expect(s.fareAmountCents, 21500); + expect(s.statusLabel, '已完成'); + expect(s.completedAt, isNotNull); + }); + + test('無司機(派單前取消)→ hasDriver=false、缺鍵容忍', () { + final s = CustomerRideSummary.fromJson(const { + 'id': 43, + 'status': 9, + 'pickup_address': '某處', + }); + expect(s.hasDriver, isFalse); + expect(s.driverName, isNull); + expect(s.dropoffAddress, isNull); + expect(s.fareAmountCents, isNull); + expect(s.statusLabel, '已取消'); + }); + }); + + group('loadRideHistory', () { + test('成功載入填入 rideHistory', () async { + final api = _FakeApi() + ..history = const [ + CustomerRideSummary(rideId: 2, status: 4, pickupAddress: 'B'), + CustomerRideSummary(rideId: 1, status: 9, pickupAddress: 'A'), + ]; + final ctrl = _loggedIn(api); + addTearDown(ctrl.dispose); + + await ctrl.loadRideHistory(); + expect(ctrl.rideHistory.length, 2); + expect(ctrl.historyError, isNull); + expect(ctrl.historyLoading, isFalse); + }); + + test('失敗設 historyError、不丟例外', () async { + final api = _FakeApi()..historyError = ApiException('壞了'); + final ctrl = _loggedIn(api); + addTearDown(ctrl.dispose); + + await ctrl.loadRideHistory(); + expect(ctrl.historyError, '壞了'); + expect(ctrl.rideHistory, isEmpty); + expect(ctrl.historyLoading, isFalse); + }); + }); + + group('歷史畫面', () { + Future pump(WidgetTester tester, CustomerController ctrl) { + return tester.pumpWidget( + ChangeNotifierProvider.value( + value: ctrl, + child: const MaterialApp(home: CustomerRideHistoryScreen()), + ), + ); + } + + testWidgets('有司機的行程顯示「聯絡司機」,無司機的不顯示', (tester) async { + final api = _FakeApi() + ..history = const [ + CustomerRideSummary( + rideId: 2, status: 4, pickupAddress: '台北101', + dropoffAddress: '台北車站', driverId: 7, driverName: '阿明', + ), + CustomerRideSummary(rideId: 1, status: 9, pickupAddress: '某處'), + ]; + final ctrl = _loggedIn(api); + addTearDown(ctrl.dispose); + + await pump(tester, ctrl); + await tester.pumpAndSettle(); + + expect(find.text('行程 #2'), findsOneWidget); + expect(find.text('行程 #1'), findsOneWidget); + // 兩筆行程、只有有司機那筆給「聯絡司機」。 + expect(find.text('聯絡司機'), findsOneWidget); + expect(find.textContaining('阿明'), findsOneWidget); + }); + + testWidgets('空清單顯示提示', (tester) async { + final ctrl = _loggedIn(_FakeApi()..history = const []); + addTearDown(ctrl.dispose); + await pump(tester, ctrl); + await tester.pumpAndSettle(); + expect(find.text('還沒有行程紀錄'), findsOneWidget); + }); + }); +}