feat: implement core architecture, design system, localization, and trip features for both driver and rider apps.

This commit is contained in:
Hamza-Ayed
2026-07-19 16:21:58 +03:00
parent 959e2fa758
commit c4dfeb4c6f
207 changed files with 14017 additions and 5567 deletions
@@ -0,0 +1,285 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../data/driver_trip_repository.dart';
import '../data/driver_socket_service.dart';
import '../data/trip_event_merger.dart';
import 'package:driver/features/trip/data/models/driver_trip_model.dart';
// ─── أحداث ───
sealed class DriverTripEvent extends Equatable {
const DriverTripEvent();
@override
List<Object?> get props => [];
}
/// فحص رحلة نشطة عند بدء التشغيل.
class DriverTripCheckActive extends DriverTripEvent {
const DriverTripCheckActive();
}
/// تم قبول رحلة (من OffersBloc).
class DriverTripAccepted extends DriverTripEvent {
final DriverTripModel trip;
const DriverTripAccepted(this.trip);
@override
List<Object?> get props => [trip.id];
}
/// تحديث حالة من WebSocket أو FCM.
class DriverTripUpdateReceived extends DriverTripEvent {
final String tripId;
final String status;
final Map<String, dynamic> extra;
const DriverTripUpdateReceived({
required this.tripId,
required this.status,
this.extra = const {},
});
@override
List<Object?> get props => [tripId, status];
}
/// تغيير الحالة يدوياً (من زر السائق).
class DriverTripStatusChanged extends DriverTripEvent {
final String status;
const DriverTripStatusChanged(this.status);
@override
List<Object?> get props => [status];
}
/// إلغاء الرحلة من السائق.
class DriverTripCancelRequested extends DriverTripEvent {
const DriverTripCancelRequested();
}
/// مسح الرحلة من الذاكرة.
class DriverTripClear extends DriverTripEvent {
const DriverTripClear();
}
// ─── حالة ───
class DriverTripState extends Equatable {
final DriverTripModel? trip;
final bool loading;
final String? error;
final bool cancelled;
const DriverTripState({
this.trip,
this.loading = false,
this.error,
this.cancelled = false,
});
DriverTripState copyWith({
DriverTripModel? trip,
bool? loading,
String? error,
bool? cancelled,
bool clearError = false,
}) {
return DriverTripState(
trip: trip ?? this.trip,
loading: loading ?? this.loading,
error: clearError ? null : (error ?? this.error),
cancelled: cancelled ?? this.cancelled,
);
}
/// هل هناك رحلة نشطة؟
bool get hasActiveTrip {
if (trip == null) return false;
return !['completed', 'paid', 'cancelled', 'expired']
.contains(trip!.status);
}
/// الحالة التالية المتوقعة للسائق.
String? get nextStatus {
if (trip == null) return null;
switch (trip!.status) {
case 'assigned':
return 'driver_arriving';
case 'driver_arriving':
return 'driver_arrived';
case 'driver_arrived':
return 'in_progress';
case 'in_progress':
return 'completed';
default:
return null;
}
}
/// هل يمكن للسائق إلغاء الرحلة حالياً؟
bool get canCancel {
if (trip == null) return false;
return ['assigned', 'driver_arriving'].contains(trip!.status);
}
@override
List<Object?> get props => [trip, loading, error, cancelled];
}
// ─── Bloc ───
/// DriverTripBloc — يدير دورة حياة الرحلة من وجهة نظر السائق.
///
/// الحالات: assigned → driver_arriving → driver_arrived → in_progress → completed
class DriverTripBloc extends Bloc<DriverTripEvent, DriverTripState> {
final DriverTripRepository _tripRepo;
final DriverSocketService _socket;
final DriverTripEventMerger _merger;
Timer? _reconciliationTimer;
DriverTripBloc({
required DriverTripRepository tripRepo,
required DriverSocketService socket,
DriverTripEventMerger? merger,
}) : _tripRepo = tripRepo,
_socket = socket,
_merger = merger ?? DriverTripEventMerger(),
super(const DriverTripState()) {
on<DriverTripCheckActive>(_onCheckActive);
on<DriverTripAccepted>(_onAccepted);
on<DriverTripUpdateReceived>(_onUpdateReceived);
on<DriverTripStatusChanged>(_onStatusChanged);
on<DriverTripCancelRequested>(_onCancel);
on<DriverTripClear>(_onClear);
// استمع لتحديثات Merger.
_merger.updateStream.listen((update) {
add(DriverTripUpdateReceived(
tripId: update.tripId,
status: update.status,
extra: update.extra,
));
});
}
Future<void> _onCheckActive(
DriverTripCheckActive event, Emitter<DriverTripState> emit) async {
emit(state.copyWith(loading: true));
try {
final trip = await _tripRepo.getTrip('me'); // backend يُعيد الرحلة النشطة للسائق
if (trip != null && trip.status != 'completed' && trip.status != 'paid') {
emit(state.copyWith(trip: trip, loading: false));
_joinTripRoom(trip.id);
_startReconciliation(trip.id);
} else {
emit(state.copyWith(loading: false));
}
} catch (_) {
emit(state.copyWith(loading: false));
}
}
void _onAccepted(DriverTripAccepted event, Emitter<DriverTripState> emit) {
emit(state.copyWith(trip: event.trip));
_joinTripRoom(event.trip.id);
_startReconciliation(event.trip.id);
}
void _onUpdateReceived(
DriverTripUpdateReceived event, Emitter<DriverTripState> emit) {
final currentTrip = state.trip;
if (currentTrip == null || currentTrip.id != event.tripId) return;
// تصفية صامتة: تجاهل الحالات القديمة.
if (isTerminalStatus(event.status)) {
emit(state.copyWith(
trip: currentTrip.copyWith(status: event.status),
));
_stopReconciliation();
_socket.leaveTrip(event.tripId);
return;
}
emit(state.copyWith(
trip: currentTrip.copyWith(status: event.status),
clearError: true,
));
}
Future<void> _onStatusChanged(
DriverTripStatusChanged event, Emitter<DriverTripState> emit) async {
if (state.trip == null) return;
emit(state.copyWith(loading: true, clearError: true));
final trip = await _tripRepo.updateStatus(state.trip!.id, event.status);
if (trip == null) {
emit(state.copyWith(loading: false, error: 'Failed to update status'));
return;
}
emit(state.copyWith(trip: trip, loading: false));
if (isTerminalStatus(trip.status)) {
_stopReconciliation();
_socket.leaveTrip(trip.id);
}
}
Future<void> _onCancel(
DriverTripCancelRequested event, Emitter<DriverTripState> emit) async {
if (state.trip == null) return;
emit(state.copyWith(loading: true, clearError: true));
final trip = await _tripRepo.cancelTrip(state.trip!.id);
if (trip == null) {
emit(state.copyWith(loading: false, error: 'Failed to cancel trip'));
return;
}
emit(state.copyWith(trip: trip, cancelled: true, loading: false));
_stopReconciliation();
_socket.leaveTrip(trip.id);
}
void _onClear(DriverTripClear event, Emitter<DriverTripState> emit) {
_stopReconciliation();
emit(const DriverTripState());
}
// ─── مساعدات ───
void _joinTripRoom(String tripId) {
_socket.joinTrip(tripId);
}
void _startReconciliation(String tripId) {
_stopReconciliation();
_reconciliationTimer = Timer.periodic(const Duration(seconds: 25), (_) async {
try {
final trip = await _tripRepo.getTrip(tripId);
if (trip != null) {
add(DriverTripUpdateReceived(
tripId: trip.id,
status: trip.status,
));
}
} catch (_) {}
});
}
void _stopReconciliation() {
_reconciliationTimer?.cancel();
_reconciliationTimer = null;
}
@override
Future<void> close() {
_stopReconciliation();
_merger.dispose();
return super.close();
}
}
/// هل هذه الحالة نهائية؟
bool isTerminalStatus(String status) {
return status == 'cancelled' || status == 'expired' || status == 'paid' || status == 'completed';
}
@@ -0,0 +1,117 @@
import 'dart:async';
import 'package:socket_io_client/socket_io_client.dart' as io;
import '../../../core/config.dart';
import '../../../core/storage/token_store.dart';
import '../../home/data/models/trip_offer_model.dart';
import 'trip_event_merger.dart';
/// خدمة WebSocket للسائق — تتصل بالسيرفر وتستقبل:
/// - `trip:offer` — عرض رحلة وارد
/// - `trip:offer_taken` — تم قبول العرض (من سائق آخر)
/// - `trip:update` — تحديث حالة الرحلة النشطة
/// - `trip:new` — رحلة جديدة متاحة
class DriverSocketService {
final TokenStore _tokenStore;
final DriverTripEventMerger _merger;
io.Socket? _socket;
bool _connected = false;
String? _currentTripId;
DriverSocketService(this._tokenStore, this._merger);
/// الاتصال بالخادم.
Future<void> connect() async {
if (_connected) return;
final token = await _tokenStore.access();
if (token == null || token.isEmpty) return;
_socket = io.io(
AppConfig.baseUrl.replaceAll('/api', ''),
io.OptionBuilder()
.setTransports(['websocket'])
.enableAutoConnect()
.enableReconnection()
.setReconnectionDelay(2000)
.setReconnectionAttempts(10)
.setAuth({'token': token})
.build(),
);
_socket!.onConnect((_) {
_connected = true;
});
_socket!.onDisconnect((_) {
_connected = false;
});
_socket!.onReconnect((_) {
if (_currentTripId != null) {
joinTrip(_currentTripId!);
}
});
// استقبال عروض الرحلات الواردة.
_socket!.on('trip:offer', (data) {
if (data is! Map) return;
final map = Map<String, dynamic>.from(data);
_merger.addOffer(TripOfferModel.fromJson(map));
});
// العرض تم قبوله من سائق آخر.
_socket!.on('trip:offer_taken', (data) {
if (data is! Map) return;
final map = Map<String, dynamic>.from(data);
final tripId = map['tripId'] as String?;
if (tripId != null) {
_merger.addOfferTaken(tripId);
}
});
// تحديث حالة الرحلة النشطة.
_socket!.on('trip:update', (data) {
if (data is! Map) return;
final map = Map<String, dynamic>.from(data);
_merger.addUpdate(DriverTripUpdate(
tripId: map['tripId'] as String? ?? '',
status: map['status'] as String? ?? '',
extra: map..remove('tripId')..remove('status'),
));
});
// رحلة جديدة متاحة (إشعار عام).
_socket!.on('trip:new', (data) {
if (data is! Map) return;
final map = Map<String, dynamic>.from(data);
final tripId = map['tripId'] as String?;
if (tripId != null) {
_merger.addNewTrip(tripId);
}
});
_socket!.connect();
}
/// الانضمام لغرفة الرحلة.
void joinTrip(String tripId) {
_currentTripId = tripId;
_socket?.emit('trip:join', {'tripId': tripId});
}
/// مغادرة غرفة الرحلة.
void leaveTrip(String tripId) {
_currentTripId = null;
}
/// قطع الاتصال.
void disconnect() {
_socket?.disconnect();
_socket?.dispose();
_socket = null;
_connected = false;
}
bool get isConnected => _connected;
}
@@ -0,0 +1,75 @@
import '../../../core/api/api_client.dart';
import 'models/driver_trip_model.dart';
import 'models/chat_message_model.dart';
/// مستودع رحلة السائق — يُستخدم من DriverTripBloc.
///
/// يشمل تغييرات الحالة ودردشة الرحلة.
class DriverTripRepository {
final ApiClient _api;
DriverTripRepository(this._api);
/// `GET /trips/:id` — جلب رحلة محددة.
Future<DriverTripModel?> getTrip(String tripId) async {
try {
final r = await _api.dio.get('/trips/$tripId');
return DriverTripModel.fromJson(r.data as Map<String, dynamic>);
} catch (_) {
return null;
}
}
/// `PATCH /trips/:id/status` — تغيير حالة الرحلة (status machine).
///
/// الحالات المسموحة للسائق: `driver_arriving`, `driver_arrived`, `in_progress`, `completed`.
Future<DriverTripModel?> updateStatus(String tripId, String status) async {
try {
final r = await _api.dio.patch('/trips/$tripId/status', data: {
'status': status,
});
return DriverTripModel.fromJson(r.data as Map<String, dynamic>);
} catch (_) {
return null;
}
}
/// `POST /trips/:id/cancel` — إلغاء الرحلة من السائق.
Future<DriverTripModel?> cancelTrip(String tripId) async {
try {
final r = await _api.dio.post('/trips/$tripId/cancel');
return DriverTripModel.fromJson(r.data as Map<String, dynamic>);
} catch (_) {
return null;
}
}
/// `GET /chat/:tripId/messages` — جلب سجل الرسائل.
Future<List<ChatMessageModel>> getMessages(String tripId, {String? currentUserId}) async {
try {
final r = await _api.dio.get('/chat/$tripId/messages');
final items = (r.data['items'] ?? r.data) as List;
return items
.map((j) => ChatMessageModel.fromJson(
j as Map<String, dynamic>,
currentUserId: currentUserId,
))
.toList();
} catch (_) {
return [];
}
}
/// `POST /chat/:tripId/send` — إرسال رسالة.
Future<ChatMessageModel?> sendMessage(String tripId, String text,
{String? currentUserId}) async {
try {
final r = await _api.dio.post('/chat/$tripId/send', data: {'text': text});
return ChatMessageModel.fromJson(
r.data as Map<String, dynamic>,
currentUserId: currentUserId,
);
} catch (_) {
return null;
}
}
}
@@ -0,0 +1,89 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:firebase_messaging/firebase_messaging.dart';
import '../../../core/api/api_client.dart';
import '../../../core/di.dart';
import 'trip_event_merger.dart';
/// القناة الثانية للزمن الحقيقي — FCM data-message (docs/23 §15).
///
/// للسائق: يستقبل عروض الرحلات (trip:offer) وتحديثات الحالة
/// عبر FCM كطبقة احتياطية للسوكت. أيّهما يسبق يفوز —
/// الـ merger يتكفّل بالتصفية الصامتة.
class DriverFcmService {
final DriverTripEventMerger _merger;
StreamSubscription<RemoteMessage>? _onMessageSub;
StreamSubscription<RemoteMessage>? _onOpenSub;
DriverFcmService(this._merger);
Future<void> init() async {
final messaging = FirebaseMessaging.instance;
await messaging.requestPermission(
alert: false,
badge: false,
sound: false,
provisional: false,
);
final token = await messaging.getToken();
if (token != null) {
_registerToken(token);
}
messaging.onTokenRefresh.listen(_registerToken);
_onMessageSub = FirebaseMessaging.onMessage.listen(_handleMessage);
_onOpenSub = FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
}
void dispose() {
_onMessageSub?.cancel();
_onOpenSub?.cancel();
}
void _handleMessage(RemoteMessage message) {
final data = message.data;
final type = data['type'] as String?;
final tripId = data['tripId'] as String?;
if (type == null || tripId == null || tripId.isEmpty) return;
switch (type) {
case 'trip_offer':
// عرض رحلة وارد — سيُعالج عبر OffersBloc.
_merger.addNewTrip(tripId);
break;
case 'trip_offer_taken':
// العرض تم قبوله من سائق آخر.
_merger.addOfferTaken(tripId);
break;
default:
// تحديث حالة رحلة نشطة.
final status = type.startsWith('trip_') ? type.substring(5) : null;
if (status == null) return;
final extra = Map<String, dynamic>.from(data)
..remove('type')
..remove('tripId')
..remove('title')
..remove('body');
_merger.addUpdate(DriverTripUpdate(
tripId: tripId,
status: status,
extra: extra,
));
}
}
static Future<void> _registerToken(String token) async {
try {
final api = getIt<ApiClient>();
await api.dio.post('/notifications/token', data: {
'token': token,
'platform': Platform.isIOS ? 'ios' : 'android',
});
} catch (_) {}
}
}
@@ -0,0 +1,33 @@
import 'package:equatable/equatable.dart';
/// نموذج رسالة الدردشة — من `GET /chat/:tripId/messages` و`POST /chat/:tripId/send`.
class ChatMessageModel extends Equatable {
final String id;
final String tripId;
final String senderId;
final String text;
final DateTime createdAt;
final bool isMe;
const ChatMessageModel({
required this.id,
required this.tripId,
required this.senderId,
required this.text,
required this.createdAt,
required this.isMe,
});
factory ChatMessageModel.fromJson(Map<String, dynamic> j, {String? currentUserId}) =>
ChatMessageModel(
id: j['id'] as String,
tripId: (j['tripId'] ?? '') as String,
senderId: j['senderId'] as String,
text: j['text'] as String,
createdAt: DateTime.parse(j['createdAt'] as String),
isMe: j['senderId'] == currentUserId,
);
@override
List<Object?> get props => [id, tripId, senderId, text, createdAt];
}
@@ -0,0 +1,93 @@
import 'package:equatable/equatable.dart';
/// نموذج الرحلة من وجهة نظر السائق — من `GET /trips/available` وتحديثات WebSocket.
class DriverTripModel extends Equatable {
final String id;
final String status;
final String? clientId;
final String? clientName;
final String? clientPhone;
final double pickupLat;
final double pickupLng;
final String? pickupAddress;
final double dropoffLat;
final double dropoffLng;
final String? dropoffAddress;
final String vehicleClass;
final num? fare;
final String? currency;
final String? paymentMethod;
final DateTime? createdAt;
final DateTime? updatedAt;
const DriverTripModel({
required this.id,
required this.status,
this.clientId,
this.clientName,
this.clientPhone,
required this.pickupLat,
required this.pickupLng,
this.pickupAddress,
required this.dropoffLat,
required this.dropoffLng,
this.dropoffAddress,
required this.vehicleClass,
this.fare,
this.currency,
this.paymentMethod,
this.createdAt,
this.updatedAt,
});
factory DriverTripModel.fromJson(Map<String, dynamic> j) => DriverTripModel(
id: j['id'] as String,
status: j['status'] as String,
clientId: j['clientId'] as String?,
clientName: j['clientName'] as String?,
clientPhone: j['clientPhone'] as String?,
pickupLat: (j['pickup']?['lat'] ?? j['pickupLat'] ?? 0).toDouble(),
pickupLng: (j['pickup']?['lng'] ?? j['pickupLng'] ?? 0).toDouble(),
pickupAddress: (j['pickup']?['address'] ?? j['pickupAddress']) as String?,
dropoffLat: (j['dropoff']?['lat'] ?? j['dropoffLat'] ?? 0).toDouble(),
dropoffLng: (j['dropoff']?['lng'] ?? j['dropoffLng'] ?? 0).toDouble(),
dropoffAddress: (j['dropoff']?['address'] ?? j['dropoffAddress']) as String?,
vehicleClass: (j['vehicleClass'] ?? '') as String,
fare: (j['fare'] as num?),
currency: j['currency'] as String?,
paymentMethod: j['paymentMethod'] as String?,
createdAt: j['createdAt'] != null ? DateTime.tryParse(j['createdAt'] as String) : null,
updatedAt: j['updatedAt'] != null ? DateTime.tryParse(j['updatedAt'] as String) : null,
);
DriverTripModel copyWith({
String? status,
String? clientName,
String? clientPhone,
num? fare,
String? currency,
}) {
return DriverTripModel(
id: id,
status: status ?? this.status,
clientId: clientId,
clientName: clientName ?? this.clientName,
clientPhone: clientPhone ?? this.clientPhone,
pickupLat: pickupLat,
pickupLng: pickupLng,
pickupAddress: pickupAddress,
dropoffLat: dropoffLat,
dropoffLng: dropoffLng,
dropoffAddress: dropoffAddress,
vehicleClass: vehicleClass,
fare: fare ?? this.fare,
currency: currency ?? this.currency,
paymentMethod: paymentMethod,
createdAt: createdAt,
updatedAt: DateTime.now(),
);
}
@override
List<Object?> get props => [id, status, clientId, vehicleClass, fare];
}
@@ -0,0 +1,92 @@
import 'dart:async';
import '../../home/data/models/trip_offer_model.dart';
/// تحديث حالة رحلة من WebSocket (للسائق).
class DriverTripUpdate {
final String tripId;
final String status;
final Map<String, dynamic> extra;
const DriverTripUpdate({
required this.tripId,
required this.status,
this.extra = const {},
});
}
/// محول أحداث WebSocket للسائق — يدعم:
/// - عروض الرحلات (`trip:offer`)
/// - إلغاء العروض (`trip:offer_taken`)
/// - تحديثات الحالة (`trip:update`)
/// - رحلات جديدة (`trip:new`)
///
/// التصفية الصامتة تتم بترتيب الحالات (docs/23 §15).
int _statusOrder(String s) {
switch (s) {
case 'assigned':
return 0;
case 'driver_arriving':
return 1;
case 'driver_arrived':
return 2;
case 'in_progress':
return 3;
case 'completed':
return 4;
case 'paid':
return 5;
default:
return -1; // cancelled, expired
}
}
class DriverTripEventMerger {
final _offerController = StreamController<TripOfferModel>.broadcast();
final _offerTakenController = StreamController<String>.broadcast();
final _updateController = StreamController<DriverTripUpdate>.broadcast();
final _newTripController = StreamController<String>.broadcast();
/// الحالة المعروضة حالياً لكل رحلة.
final Map<String, int> _currentOrder = {};
Stream<TripOfferModel> get offerStream => _offerController.stream;
Stream<String> get offerTakenStream => _offerTakenController.stream;
Stream<DriverTripUpdate> get updateStream => _updateController.stream;
Stream<String> get newTripStream => _newTripController.stream;
/// استقبال عرض رحلة وارد.
void addOffer(TripOfferModel offer) {
_offerController.add(offer);
}
/// العرض تم قبوله من سائق آخر.
void addOfferTaken(String tripId) {
_offerTakenController.add(tripId);
}
/// تحديث حالة رحلة نشطة.
void addUpdate(DriverTripUpdate update) {
final newOrder = _statusOrder(update.status);
final currentOrder = _currentOrder[update.tripId] ?? -1;
if (newOrder >= 0 && newOrder <= currentOrder) return;
if (newOrder >= 0) {
_currentOrder[update.tripId] = newOrder;
}
_updateController.add(update);
}
/// إشعار برحلة جديدة متاحة.
void addNewTrip(String tripId) {
_newTripController.add(tripId);
}
void dispose() {
_offerController.close();
_offerTakenController.close();
_updateController.close();
_newTripController.close();
}
}
@@ -0,0 +1,212 @@
import 'package:flutter/material.dart';
import 'package:driver/core/l10n/app_localizations.dart';
import '../../../core/design/tokens.dart';
import '../../../core/ui/tripz_text_field.dart';
import '../../trip/data/driver_trip_repository.dart';
import '../../trip/data/models/chat_message_model.dart';
import '../../../core/storage/token_store.dart';
import '../../../core/di.dart';
/// شاشة دردشة السائق مع العميل داخل الرحلة.
///
/// تُستخدم من شاشة تنفيذ الرحلة (Q4).
class DriverChatScreen extends StatefulWidget {
final String tripId;
const DriverChatScreen({super.key, required this.tripId});
@override
State<DriverChatScreen> createState() => _DriverChatScreenState();
}
class _DriverChatScreenState extends State<DriverChatScreen> {
final TextEditingController _controller = TextEditingController();
final ScrollController _scrollController = ScrollController();
late final DriverTripRepository _repo;
List<ChatMessageModel> _messages = [];
bool _loading = true;
bool _sending = false;
@override
void initState() {
super.initState();
_repo = DriverTripRepository(getIt());
_loadMessages();
}
Future<void> _loadMessages() async {
final userId = await getIt<TokenStore>().access();
final messages = await _repo.getMessages(widget.tripId, currentUserId: userId);
if (mounted) {
setState(() {
_messages = messages;
_loading = false;
});
_scrollToBottom();
}
}
Future<void> _sendMessage() async {
final text = _controller.text.trim();
if (text.isEmpty || _sending) return;
setState(() => _sending = true);
_controller.clear();
final userId = await getIt<TokenStore>().access();
final msg = await _repo.sendMessage(widget.tripId, text, currentUserId: userId);
if (msg != null && mounted) {
setState(() => _messages.add(msg));
_scrollToBottom();
}
if (mounted) setState(() => _sending = false);
}
void _scrollToBottom() {
Future.delayed(const Duration(milliseconds: 100), () {
if (_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
}
});
}
@override
void dispose() {
_controller.dispose();
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final cs = Theme.of(context).colorScheme;
return Scaffold(
appBar: AppBar(
title: Text(l10n.chat),
),
body: Column(
children: [
// الرسائل
Expanded(
child: _loading
? const Center(child: CircularProgressIndicator())
: _messages.isEmpty
? Center(
child: Text(
l10n.noMessagesYet,
style: TextStyle(color: cs.onSurfaceVariant),
),
)
: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(T.s16),
itemCount: _messages.length,
itemBuilder: (context, index) {
final msg = _messages[index];
return _MessageBubble(message: msg);
},
),
),
// حقل الإرسال
Container(
padding: const EdgeInsets.all(T.s12),
decoration: BoxDecoration(
color: cs.surface,
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 8,
offset: const Offset(0, -2),
),
],
),
child: SafeArea(
child: Row(
children: [
Expanded(
child: TripzTextField(
controller: _controller,
hint: l10n.typeMessage,
onSubmitted: (_) => _sendMessage(),
),
),
const SizedBox(width: T.s8),
IconButton(
onPressed: _sending ? null : _sendMessage,
icon: _sending
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Icon(Icons.send, color: cs.primary),
),
],
),
),
),
],
),
);
}
}
class _MessageBubble extends StatelessWidget {
final ChatMessageModel message;
const _MessageBubble({required this.message});
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return Align(
alignment: message.isMe ? Alignment.centerRight : Alignment.centerLeft,
child: Container(
margin: const EdgeInsets.only(bottom: T.s8),
padding: const EdgeInsets.symmetric(
horizontal: T.s12,
vertical: T.s8,
),
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.75,
),
decoration: BoxDecoration(
color: message.isMe ? cs.primary : cs.surfaceContainerHighest,
borderRadius: BorderRadius.circular(T.r12).copyWith(
bottomRight: message.isMe ? const Radius.circular(4) : null,
bottomLeft: !message.isMe ? const Radius.circular(4) : null,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
message.text,
style: TextStyle(
color: message.isMe ? cs.onPrimary : cs.onSurface,
),
),
const SizedBox(height: 2),
Text(
'${message.createdAt.hour.toString().padLeft(2, '0')}:${message.createdAt.minute.toString().padLeft(2, '0')}',
style: TextStyle(
fontSize: 10,
color: message.isMe
? cs.onPrimary.withValues(alpha: 0.7)
: cs.onSurfaceVariant,
),
),
],
),
),
);
}
}
@@ -0,0 +1,260 @@
import 'package:flutter/material.dart';
import 'package:driver/core/l10n/app_localizations.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intaleq_maps/intaleq_maps.dart';
import '../../../core/design/tokens.dart';
import '../../trip/bloc/driver_trip_bloc.dart';
import 'widgets/trip_action_button.dart';
/// شاشة تنفيذ الرحلة — تتبع السائق أثناء تنفيذ الرحلة.
///
/// الحالات:
/// - `assigned`: عرض pickup + زر "في الطريق"
/// - `driver_arriving`: تتبع المسار إلى العميل
/// - `driver_arrived`: انتظار العميل + زر "بدء الرحلة"
/// - `in_progress`: تتبع المسار إلى dropoff + زر "إتمام"
class DriverTripScreen extends StatelessWidget {
const DriverTripScreen({super.key});
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final cs = Theme.of(context).colorScheme;
return BlocBuilder<DriverTripBloc, DriverTripState>(
builder: (context, state) {
if (state.trip == null) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
final trip = state.trip!;
final statusLabel = _statusLabel(l10n, trip.status);
return Scaffold(
appBar: AppBar(
title: Text(statusLabel),
centerTitle: true,
automaticallyImplyLeading: false,
actions: [
if (state.canCancel)
TextButton(
onPressed: () => _showCancelDialog(context, l10n),
child: Text(
l10n.cancel,
style: TextStyle(color: cs.error),
),
),
],
),
body: Column(
children: [
// ── الخريطة ──
Expanded(
flex: 3,
child: _buildMap(context, trip),
),
// ── معلومات + زر ──
Expanded(
flex: 2,
child: Container(
padding: const EdgeInsets.all(T.s16),
decoration: BoxDecoration(
color: cs.surface,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(T.r24),
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.08),
blurRadius: 12,
offset: const Offset(0, -4),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// معلومات العميل
if (trip.clientName != null)
Row(
children: [
CircleAvatar(
radius: 20,
backgroundColor: cs.primaryContainer,
child: Icon(Icons.person, color: cs.onPrimaryContainer),
),
const SizedBox(width: T.s12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
trip.clientName!,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
fontWeight: FontWeight.w600,
),
),
if (trip.clientPhone != null)
Text(
trip.clientPhone!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: cs.onSurfaceVariant,
),
),
],
),
),
],
),
const SizedBox(height: T.s12),
// نقاط pickup/dropoff
_InfoRow(
dotColor: const Color(0xFF4CAF50),
label: trip.pickupAddress ?? l10n.pickupLocation,
),
const SizedBox(height: T.s4),
_InfoRow(
dotColor: const Color(0xFFF44336),
label: trip.dropoffAddress ?? l10n.dropoffLocation,
),
if (trip.fare != null) ...[
const SizedBox(height: T.s8),
Text(
'${l10n.tripFare}: ${trip.fare} ${trip.currency ?? ""}',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
color: cs.primary,
),
),
],
const Spacer(),
// زر الإجراء التالي
TripActionButton(trip: trip),
if (state.error != null) ...[
const SizedBox(height: T.s8),
Text(
state.error!,
style: TextStyle(color: cs.error, fontSize: 12),
textAlign: TextAlign.center,
),
],
],
),
),
),
],
),
);
},
);
}
Widget _buildMap(BuildContext context, dynamic trip) {
return IntaleqMap(
apiKey: '',
initialCameraPosition: CameraPosition(
target: LatLng(trip.pickupLat, trip.pickupLng),
zoom: 14,
),
myLocationEnabled: true,
myLocationButtonEnabled: false,
zoomControlsEnabled: false,
markers: {
Marker(
markerId: const MarkerId('pickup'),
position: LatLng(trip.pickupLat, trip.pickupLng),
infoWindow: InfoWindow(title: AppLocalizations.of(context)!.pickupLocation),
),
if (trip.dropoffLat != 0 && trip.dropoffLng != 0)
Marker(
markerId: const MarkerId('dropoff'),
position: LatLng(trip.dropoffLat, trip.dropoffLng),
infoWindow: InfoWindow(title: AppLocalizations.of(context)!.dropoffLocation),
),
},
);
}
String _statusLabel(AppLocalizations l10n, String status) {
switch (status) {
case 'assigned':
return l10n.tripAssigned;
case 'driver_arriving':
return l10n.onTheWay;
case 'driver_arrived':
return l10n.arrivedAtPickup;
case 'in_progress':
return l10n.tripInProgress;
case 'completed':
return l10n.tripCompleted;
default:
return l10n.trip;
}
}
void _showCancelDialog(BuildContext context, AppLocalizations l10n) {
final cs = Theme.of(context).colorScheme;
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text(l10n.cancelTrip),
content: Text(l10n.cancelTripConfirm),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: Text(l10n.no),
),
TextButton(
onPressed: () {
Navigator.pop(ctx);
context.read<DriverTripBloc>().add(const DriverTripCancelRequested());
},
style: TextButton.styleFrom(foregroundColor: cs.error),
child: Text(l10n.yes),
),
],
),
);
}
}
class _InfoRow extends StatelessWidget {
final Color dotColor;
final String label;
const _InfoRow({required this.dotColor, required this.label});
@override
Widget build(BuildContext context) {
return Row(
children: [
Container(
width: 10,
height: 10,
decoration: BoxDecoration(
color: dotColor,
shape: BoxShape.circle,
),
),
const SizedBox(width: T.s8),
Expanded(
child: Text(
label,
style: Theme.of(context).textTheme.bodyMedium,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
);
}
}
@@ -0,0 +1,161 @@
import 'package:flutter/material.dart';
import 'package:driver/core/l10n/app_localizations.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:driver/core/design/tokens.dart';
import 'package:driver/core/design/tripz_colors.dart';
import 'package:driver/features/trip/bloc/driver_trip_bloc.dart';
/// زر الإجراء التالي في شاشة تنفيذ الرحلة.
///
/// الحالة → الزر:
/// - assigned → "في الطريق" (driver_arriving)
/// - driver_arriving → "وصلت" (driver_arrived)
/// - driver_arrived → "بدء الرحلة" (in_progress)
/// - in_progress → "إتمام" (completed)
class TripActionButton extends StatelessWidget {
final dynamic trip;
const TripActionButton({super.key, required this.trip});
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final cs = Theme.of(context).colorScheme;
final bloc = context.watch<DriverTripBloc>();
final state = bloc.state;
final nextStatus = state.nextStatus;
if (nextStatus == null) return const SizedBox.shrink();
final label = _buttonLabel(l10n, nextStatus);
final color = nextStatus == 'completed'
? context.tripzColors.success
: cs.primary;
return Column(
mainAxisSize: MainAxisSize.min,
children: [
// أزرار ثانوية
Row(
children: [
if (trip.clientPhone != null) ...[
Expanded(
child: _SecondaryButton(
icon: Icons.phone,
label: l10n.callClient,
onTap: () => _launchPhone(trip.clientPhone!),
),
),
const SizedBox(width: T.s8),
],
Expanded(
child: _SecondaryButton(
icon: Icons.chat_bubble_outline,
label: l10n.chat,
onTap: () {
// TODO: Q4 chat screen
},
),
),
],
),
const SizedBox(height: T.s12),
// زر الإجراء الرئيسي
SizedBox(
width: double.infinity,
height: T.buttonHeight,
child: ElevatedButton(
onPressed: state.loading
? null
: () {
bloc.add(DriverTripStatusChanged(nextStatus));
},
style: ElevatedButton.styleFrom(
backgroundColor: color,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(T.r12),
),
elevation: 0,
),
child: state.loading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: Text(
label,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
),
],
);
}
String _buttonLabel(AppLocalizations l10n, String status) {
switch (status) {
case 'driver_arriving':
return l10n.onTheWay;
case 'driver_arrived':
return l10n.arrivedAtPickup;
case 'in_progress':
return l10n.startTrip;
case 'completed':
return l10n.completeTrip;
default:
return status;
}
}
void _launchPhone(String phone) async {
final uri = Uri(scheme: 'tel', path: phone);
if (await canLaunchUrl(uri)) {
await launchUrl(uri);
}
}
}
/// زر ثانوي صغير.
class _SecondaryButton extends StatelessWidget {
final IconData icon;
final String label;
final VoidCallback onTap;
const _SecondaryButton({
required this.icon,
required this.label,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return OutlinedButton(
onPressed: onTap,
style: OutlinedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(T.r12),
),
minimumSize: const Size(0, T.buttonHeight),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 18),
const SizedBox(width: T.s4),
Text(label),
],
),
);
}
}