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
@@ -1,8 +1,12 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:driver/core/l10n/app_localizations.dart';
import '../cubit/auth_cubit.dart';
import '../cubit/auth_state.dart';
import '../../../core/ui/tripz_scaffold.dart';
import '../../../core/ui/tripz_button.dart';
import '../../../core/ui/tripz_text_field.dart';
class OtpScreen extends StatefulWidget {
const OtpScreen({super.key});
@@ -13,60 +17,61 @@ class OtpScreen extends StatefulWidget {
class _OtpScreenState extends State<OtpScreen> {
final _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_forward),
onPressed: () => context.go('/phone'),
),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24),
child: BlocConsumer<AuthCubit, AuthState>(
listener: (context, state) {
if (state.status == AuthStatus.error && state.error != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(state.error!)),
);
}
},
builder: (context, state) {
final loading = state.status == AuthStatus.authenticating;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 24),
Text('أدخل رمز التحقق',
style: Theme.of(context).textTheme.titleLarge),
const SizedBox(height: 8),
Text('أُرسل إلى ${state.phone}'),
const SizedBox(height: 28),
TextField(
controller: _controller,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
decoration: const InputDecoration(labelText: 'الرمز'),
),
const SizedBox(height: 20),
FilledButton(
onPressed: loading
? null
: () => context.read<AuthCubit>().verify(_controller.text),
child: loading
? const SizedBox(
height: 22, width: 22,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('تأكيد'),
),
],
);
},
),
),
final l10n = AppLocalizations.of(context)!;
return TripzScaffold(
showBackButton: true,
onBack: () => context.go('/phone'),
child: BlocConsumer<AuthCubit, AuthState>(
listener: (context, state) {
if (state.status == AuthStatus.error && state.error != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(state.error!)),
);
}
},
builder: (context, state) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 24),
Text(
l10n.otpTitle,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
l10n.otpSentTo(state.phone),
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 28),
TripzTextField(
controller: _controller,
label: l10n.otpLabel,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
maxLength: 6,
),
const SizedBox(height: 20),
TripzButton(
label: l10n.confirm,
loading: state.status == AuthStatus.authenticating,
onPressed: () =>
context.read<AuthCubit>().verify(_controller.text),
),
],
);
},
),
);
}
@@ -1,7 +1,11 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:driver/core/l10n/app_localizations.dart';
import '../cubit/auth_cubit.dart';
import '../cubit/auth_state.dart';
import '../../../core/ui/tripz_scaffold.dart';
import '../../../core/ui/tripz_button.dart';
import '../../../core/ui/tripz_text_field.dart';
class PhoneScreen extends StatefulWidget {
const PhoneScreen({super.key});
@@ -12,55 +16,61 @@ class PhoneScreen extends StatefulWidget {
class _PhoneScreenState extends State<PhoneScreen> {
final _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 40),
Text('Tripz', style: Theme.of(context).textTheme.headlineMedium),
const SizedBox(height: 8),
const Text('أدخل رقم هاتفك للمتابعة'),
const SizedBox(height: 32),
TextField(
controller: _controller,
keyboardType: TextInputType.phone,
decoration: const InputDecoration(
labelText: 'رقم الهاتف',
hintText: '07XXXXXXXX',
),
),
const SizedBox(height: 20),
BlocConsumer<AuthCubit, AuthState>(
listener: (context, state) {
if (state.status == AuthStatus.error && state.error != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(state.error!)),
);
}
},
builder: (context, state) {
final loading = state.status == AuthStatus.authenticating;
return FilledButton(
onPressed: loading
? null
: () => context.read<AuthCubit>().sendOtp(_controller.text),
child: loading
? const SizedBox(
height: 22, width: 22,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('إرسال الرمز'),
);
},
),
],
final l10n = AppLocalizations.of(context)!;
return TripzScaffold(
safeAreaTop: true,
padding: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Spacer(flex: 2),
Text(
l10n.appName,
style: Theme.of(context).textTheme.headlineLarge,
),
),
const SizedBox(height: 8),
Text(
l10n.phoneTitle,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const Spacer(),
TripzTextField(
controller: _controller,
label: l10n.phoneLabel,
hint: l10n.phoneHint,
keyboardType: TextInputType.phone,
),
const SizedBox(height: 20),
BlocConsumer<AuthCubit, AuthState>(
listener: (context, state) {
if (state.status == AuthStatus.error && state.error != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(state.error!)),
);
}
},
builder: (context, state) {
return TripzButton(
label: l10n.sendCode,
loading: state.status == AuthStatus.authenticating,
onPressed: () =>
context.read<AuthCubit>().sendOtp(_controller.text),
);
},
),
const Spacer(flex: 2),
],
),
);
}
@@ -0,0 +1,118 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../data/driver_repository.dart';
import '../data/driver_location_service.dart';
import '../data/models/driver_profile_model.dart';
/// حالة DriverCubit.
class DriverState extends Equatable {
final DriverProfileModel? profile;
final bool loading;
final bool online;
final String? error;
const DriverState({
this.profile,
this.loading = true,
this.online = false,
this.error,
});
DriverState copyWith({
DriverProfileModel? profile,
bool? loading,
bool? online,
String? error,
bool clearError = false,
}) {
return DriverState(
profile: profile ?? this.profile,
loading: loading ?? this.loading,
online: online ?? this.online,
error: clearError ? null : (error ?? this.error),
);
}
@override
List<Object?> get props => [profile, loading, online, error];
}
/// Cubit مُتّصل/مُنقطع — يدير ملف السائق وتبديل الحالة وموقع الخلفية.
///
/// يُقدّم:
/// - جلب الملف عند بدء التشغيل
/// - تبديل الحالة (online/offline)
/// - بدء/إيقاف تتبع الموقع عند التنشيط
class DriverCubit extends Cubit<DriverState> {
final DriverRepository _repo;
DriverLocationService? _locationService;
Timer? _heartbeatTimer;
DriverCubit(this._repo) : super(const DriverState(loading: true));
/// جلب ملف السائق وتحديد الحالة الأولية.
Future<void> loadProfile() async {
try {
final profile = await _repo.getProfile();
if (profile != null) {
emit(state.copyWith(
profile: profile,
online: profile.online,
loading: false,
));
// إذا كان مُتصلاً مسبقاً، أعد بدء التتبع.
if (profile.online) {
_startLocationTracking();
}
} else {
emit(state.copyWith(loading: false));
}
} catch (e) {
emit(state.copyWith(loading: false, error: e.toString()));
}
}
/// تبديل الحالة (مُتصل/مُنقطع).
Future<void> toggleOnline() async {
final newOnline = !state.online;
emit(state.copyWith(online: newOnline));
final result = await _repo.setOnline(newOnline);
if (!result) {
// فشل — أعد الحالة السابقة.
emit(state.copyWith(online: !newOnline));
return;
}
if (newOnline) {
_startLocationTracking();
} else {
_stopLocationTracking();
}
}
/// بدء تتبع الموقع.
void _startLocationTracking() {
if (_locationService?.isActive == true) return;
_locationService = DriverLocationService((lat, lng, {heading, speed}) async {
await _repo.sendLocation(lat: lat, lng: lng, heading: heading, speed: speed);
});
_locationService!.start();
}
/// إيقاف تتبع الموقع.
void _stopLocationTracking() {
_locationService?.stop();
_locationService = null;
_heartbeatTimer?.cancel();
_heartbeatTimer = null;
}
@override
Future<void> close() {
_stopLocationTracking();
return super.close();
}
}
@@ -0,0 +1,91 @@
import 'dart:async';
import 'package:geolocator/geolocator.dart';
/// خدمة موقع السائق — تتبع الموقع في الخلفية وإرساله للسيرفر.
///
/// تتبع 3 ثوانٍ عند التنشيط، ثم إرسال كل دقيقتين (docs/23 §10).
/// تراعي حالة البطارية وتتوقف عند انخفاضها.
class DriverLocationService {
final Future<void> Function(double lat, double lng, {double? heading, double? speed})
_onLocationUpdate;
StreamSubscription<Position>? _positionSub;
Timer? _heartbeatTimer;
bool _active = false;
DriverLocationService(this._onLocationUpdate);
bool get isActive => _active;
/// بدء التتبع.
Future<void> start() async {
if (_active) return;
// تحقق من صلاحية الموقع.
var permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) {
return;
}
}
_active = true;
// أرسل الموقع فوراً.
_sendCurrentLocation();
// استمع لتحديثات الموقع كل 3 ثوانٍ.
_positionSub = Geolocator.getPositionStream(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 15, // تحديث عند تغيير 15 متر
),
).listen((pos) {
_onLocationUpdate(
pos.latitude,
pos.longitude,
heading: pos.heading,
speed: pos.speed,
);
});
// دفعة كل دقيقتين كحد أقصى.
_heartbeatTimer = Timer.periodic(const Duration(minutes: 2), (_) {
_sendCurrentLocation();
});
}
/// إيقاف التتبع.
void stop() {
_active = false;
_positionSub?.cancel();
_positionSub = null;
_heartbeatTimer?.cancel();
_heartbeatTimer = null;
}
/// إرسال الموقع الحالي مرة واحدة.
Future<void> _sendCurrentLocation() async {
try {
final pos = await Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
),
);
await _onLocationUpdate(
pos.latitude,
pos.longitude,
heading: pos.heading,
speed: pos.speed,
);
} catch (_) {
// خطأ صامت — سيحاول مرة أخرى مع الدقيقة التالية.
}
}
void dispose() {
stop();
}
}
@@ -0,0 +1,50 @@
import '../../../core/api/api_client.dart';
import 'models/driver_profile_model.dart';
/// مستودع بيانات السائق — يُستخدم من DriverCubit.
class DriverRepository {
final ApiClient _api;
DriverRepository(this._api);
/// `GET /drivers/me` — جلب ملف السائق.
Future<DriverProfileModel?> getProfile() async {
try {
final r = await _api.dio.get('/drivers/me');
return DriverProfileModel.fromJson(r.data as Map<String, dynamic>);
} catch (_) {
return null;
}
}
/// `PATCH /drivers/status` — تبديل الحالة (مُتصل/مُنقطع).
Future<bool> setOnline(bool online) async {
try {
final r = await _api.dio.patch('/drivers/status', data: {'online': online});
return r.data['online'] as bool? ?? online;
} catch (_) {
return false;
}
}
/// `POST /drivers/location` — إرسال الموقع الحالي.
///
/// يُعيد `true` إذا كان الموقع "مُهماً" (تغيير كبير حسب السيرفر).
Future<bool> sendLocation({
required double lat,
required double lng,
double? heading,
double? speed,
}) async {
try {
final r = await _api.dio.post('/drivers/location', data: {
'lat': lat,
'lng': lng,
if (heading != null) 'heading': heading,
if (speed != null) 'speed': speed,
});
return r.data['significant'] as bool? ?? false;
} catch (_) {
return false;
}
}
}
@@ -0,0 +1,94 @@
import 'package:equatable/equatable.dart';
/// نموذج بيانات السائق — من `GET /drivers/me`.
class DriverProfileModel extends Equatable {
final String id;
final String phone;
final String? name;
final bool online;
final double? lat;
final double? lng;
final String? vehicleMake;
final String? vehicleModel;
final int? vehicleYear;
final String? vehicleColor;
final String? plateNumber;
final String? serviceClass;
final double? rating;
final int? totalTrips;
final int? creditBalance;
const DriverProfileModel({
required this.id,
required this.phone,
this.name,
this.online = false,
this.lat,
this.lng,
this.vehicleMake,
this.vehicleModel,
this.vehicleYear,
this.vehicleColor,
this.plateNumber,
this.serviceClass,
this.rating,
this.totalTrips,
this.creditBalance,
});
factory DriverProfileModel.fromJson(Map<String, dynamic> j) =>
DriverProfileModel(
id: j['id'] as String,
phone: (j['phone'] ?? '') as String,
name: j['name'] as String?,
online: j['online'] as bool? ?? false,
lat: (j['lat'] as num?)?.toDouble(),
lng: (j['lng'] as num?)?.toDouble(),
vehicleMake: j['vehicleMake'] as String?,
vehicleModel: j['vehicleModel'] as String?,
vehicleYear: j['vehicleYear'] as int?,
vehicleColor: j['vehicleColor'] as String?,
plateNumber: j['plateNumber'] as String?,
serviceClass: j['serviceClass'] as String?,
rating: (j['rating'] as num?)?.toDouble(),
totalTrips: j['totalTrips'] as int?,
creditBalance: j['creditBalance'] as int?,
);
DriverProfileModel copyWith({
String? name,
bool? online,
double? lat,
double? lng,
String? vehicleMake,
String? vehicleModel,
int? vehicleYear,
String? vehicleColor,
String? plateNumber,
String? serviceClass,
double? rating,
int? totalTrips,
int? creditBalance,
}) {
return DriverProfileModel(
id: id,
phone: phone,
name: name ?? this.name,
online: online ?? this.online,
lat: lat ?? this.lat,
lng: lng ?? this.lng,
vehicleMake: vehicleMake ?? this.vehicleMake,
vehicleModel: vehicleModel ?? this.vehicleModel,
vehicleYear: vehicleYear ?? this.vehicleYear,
vehicleColor: vehicleColor ?? this.vehicleColor,
plateNumber: plateNumber ?? this.plateNumber,
serviceClass: serviceClass ?? this.serviceClass,
rating: rating ?? this.rating,
totalTrips: totalTrips ?? this.totalTrips,
creditBalance: creditBalance ?? this.creditBalance,
);
}
@override
List<Object?> get props => [id, phone, name, online, vehicleMake, vehicleModel, plateNumber];
}
@@ -0,0 +1,62 @@
import 'package:equatable/equatable.dart';
/// عرض رحلة وارد — من `trip:offer` عبر WebSocket.
///
/// يحتوي على كل المعلومات التي يحتاجها السائق للقبول/الرفض.
/// المهلة الزمنية (`expiresAt`) تُدار من OffersBloc.
class TripOfferModel extends Equatable {
final String tripId;
final double pickupLat;
final double pickupLng;
final String? pickupAddress;
final double dropoffLat;
final double dropoffLng;
final String? dropoffAddress;
final double distance;
final num fare;
final String currency;
final int etaPickup;
final String vehicleClass;
final DateTime expiresAt;
const TripOfferModel({
required this.tripId,
required this.pickupLat,
required this.pickupLng,
this.pickupAddress,
required this.dropoffLat,
required this.dropoffLng,
this.dropoffAddress,
required this.distance,
required this.fare,
required this.currency,
required this.etaPickup,
required this.vehicleClass,
required this.expiresAt,
});
factory TripOfferModel.fromJson(Map<String, dynamic> j) => TripOfferModel(
tripId: j['tripId'] as String,
pickupLat: (j['pickup']?['lat'] ?? 0).toDouble(),
pickupLng: (j['pickup']?['lng'] ?? 0).toDouble(),
pickupAddress: j['pickup']?['address'] as String?,
dropoffLat: (j['dropoff']?['lat'] ?? 0).toDouble(),
dropoffLng: (j['dropoff']?['lng'] ?? 0).toDouble(),
dropoffAddress: j['dropoff']?['address'] as String?,
distance: (j['distance'] ?? 0).toDouble(),
fare: (j['fare'] ?? 0) as num,
currency: (j['currency'] ?? 'IQD') as String,
etaPickup: (j['etaPickup'] ?? 0) as int,
vehicleClass: (j['vehicleClass'] ?? '') as String,
expiresAt: DateTime.parse(j['expiresAt'] as String),
);
/// المسافة المنسقة (كم مع خانتين عشريتين).
String get formattedDistance => '${distance.toStringAsFixed(1)} km';
/// الأجرة المنسقة.
String get formattedFare => '$fare $currency';
@override
List<Object?> get props => [tripId, pickupLat, pickupLng, fare, expiresAt];
}
@@ -1,45 +1,189 @@
import 'package:flutter/material.dart';
import 'package:driver/core/l10n/app_localizations.dart';
import 'package:intaleq_maps/intaleq_maps.dart';
import 'package:driver/core/design/tokens.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../auth/cubit/auth_cubit.dart';
import '../../auth/cubit/auth_state.dart';
import 'package:driver/features/home/cubit/driver_cubit.dart';
import 'package:driver/features/offers/bloc/offers_bloc.dart';
import 'widgets/driver_status_indicator.dart';
import 'widgets/trip_offer_card.dart';
import 'dart:async';
/// شاشة السائق الرئيسية — هيكل مؤقّت (Q3).
///
/// ما سيُبنى هنا لاحقاً حسب docs/22 (المجموعة Q3): مفتاح الاتصال/الانقطاع ·
/// overlay العرض الوارد · widgets الرحلة · الرصيد والشحن. ولا يُعاد اختراع
/// **متحكّم الموقع**: نمط سيرو مثبت عملياً (تسجيل ٣ث · دفعات كل دقيقتين ·
/// وعي بالبطارية) — راجع docs/23 §10.
class HomeScreen extends StatelessWidget {
/// شاشة السائق الرئيسية — خريطة + مفتاح الاتصال/الانقطاع + overlay العروض.
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final Completer<IntaleqMapController> _mapController = Completer();
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final cs = Theme.of(context).colorScheme;
return Scaffold(
appBar: AppBar(
title: const Text('تطبيق السائق'),
actions: [
IconButton(
icon: const Icon(Icons.logout),
onPressed: () => context.read<AuthCubit>().logout(),
body: Stack(
children: [
// ── الخريطة ──
_buildMap(cs),
// ── شريط الحالة العلوي ──
Positioned(
top: MediaQuery.of(context).padding.top + T.s8,
left: T.s16,
right: T.s16,
child: _buildTopBar(context, l10n, cs),
),
// ── مؤشر حالة السائق ──
Positioned(
bottom: T.s24,
left: T.s16,
right: T.s16,
child: const DriverStatusIndicator(),
),
// ── overlay العروض الواردة ──
const _OffersOverlay(),
],
),
body: BlocBuilder<AuthCubit, AuthState>(
builder: (context, state) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.local_taxi, size: 72),
const SizedBox(height: 16),
Text('أهلاً ${state.user?.name ?? state.user?.phone ?? ''}'),
const SizedBox(height: 8),
const Text('لوحة السائق قيد البناء (Q3)'),
);
}
Widget _buildMap(ColorScheme cs) {
return BlocBuilder<DriverCubit, DriverState>(
builder: (context, state) {
final driverLat = state.profile?.lat ?? 33.3128;
final driverLng = state.profile?.lng ?? 44.3615;
return IntaleqMap(
apiKey: '',
initialCameraPosition: CameraPosition(
target: LatLng(driverLat, driverLng),
zoom: 14,
),
myLocationEnabled: true,
myLocationButtonEnabled: false,
zoomControlsEnabled: false,
onMapCreated: (controller) {
if (!_mapController.isCompleted) {
_mapController.complete(controller);
}
},
);
},
);
}
Widget _buildTopBar(BuildContext context, AppLocalizations l10n, ColorScheme cs) {
return SafeArea(
child: Row(
children: [
// زر القائمة
Container(
decoration: BoxDecoration(
color: cs.surface,
borderRadius: BorderRadius.circular(T.rCircle),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.08),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
);
},
child: IconButton(
icon: const Icon(Icons.menu_rounded),
onPressed: () {
// TODO: Q4 drawer
},
),
),
const Spacer(),
// معلومات السائق
Container(
padding: const EdgeInsets.symmetric(
horizontal: T.s12,
vertical: T.s8,
),
decoration: BoxDecoration(
color: cs.surface,
borderRadius: BorderRadius.circular(T.r12),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.08),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Row(
children: [
Icon(Icons.star_rounded, size: 18, color: Colors.amber[600]),
const SizedBox(width: T.s4),
Text(
'${context.read<DriverCubit>().state.profile?.rating?.toStringAsFixed(1) ?? "-"}',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
],
),
),
],
),
);
}
}
/// overlay يعرض العروض الواردة كبطاقات في أسفل الشاشة.
class _OffersOverlay extends StatelessWidget {
const _OffersOverlay();
@override
Widget build(BuildContext context) {
return BlocBuilder<OffersBloc, OffersState>(
builder: (context, state) {
if (!state.hasOffers) return const SizedBox.shrink();
return Positioned(
bottom: 100,
left: T.s16,
right: T.s16,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// عدد العروض
if (state.offers.length > 1)
Container(
margin: const EdgeInsets.only(bottom: T.s8),
padding: const EdgeInsets.symmetric(
horizontal: T.s12,
vertical: T.s4,
),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary,
borderRadius: BorderRadius.circular(T.rCircle),
),
child: Text(
'${state.offers.length} ${AppLocalizations.of(context)!.offersAvailable}',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onPrimary,
fontWeight: FontWeight.w600,
),
),
),
// العرض الأحدث
TripOfferCard(offer: state.offers.first),
],
),
);
},
);
}
}
@@ -0,0 +1,133 @@
import 'package:flutter/material.dart';
import 'package:driver/core/l10n/app_localizations.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:driver/core/design/tokens.dart';
import 'package:driver/core/design/tripz_colors.dart';
import 'package:driver/features/home/cubit/driver_cubit.dart';
/// مؤشر حالة السائق — يعرض "مُتصل" أو "مُنقطع" مع زر التبديل.
class DriverStatusIndicator extends StatelessWidget {
const DriverStatusIndicator({super.key});
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final cs = Theme.of(context).colorScheme;
return BlocBuilder<DriverCubit, DriverState>(
builder: (context, state) {
final isOnline = state.online;
return Container(
padding: const EdgeInsets.symmetric(
horizontal: T.s16,
vertical: T.s12,
),
decoration: BoxDecoration(
color: cs.surface,
borderRadius: BorderRadius.circular(T.r12),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.1),
blurRadius: 12,
offset: const Offset(0, -4),
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// معلومات السائق
if (state.profile != null)
Padding(
padding: const EdgeInsets.only(bottom: T.s8),
child: 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(
state.profile!.name ?? l10n.anonymous,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(
fontWeight: FontWeight.w600,
),
),
if (state.profile!.vehicleMake != null)
Text(
'${state.profile!.vehicleMake} ${state.profile!.vehicleModel ?? ""} · ${state.profile!.plateNumber ?? ""}',
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: cs.onSurfaceVariant,
),
),
],
),
),
],
),
),
// زر التبديل
SizedBox(
width: double.infinity,
height: T.buttonHeight,
child: ElevatedButton(
onPressed: state.loading
? null
: () => context.read<DriverCubit>().toggleOnline(),
style: ElevatedButton.styleFrom(
backgroundColor: isOnline
? context.tripzColors.danger
: cs.primary,
foregroundColor: isOnline ? Colors.white : cs.onPrimary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(T.r12),
),
elevation: 0,
),
child: state.loading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
isOnline
? Icons.stop_rounded
: Icons.play_arrow_rounded,
size: 24,
),
const SizedBox(width: T.s8),
Text(
isOnline ? l10n.goOffline : l10n.goOnline,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
],
),
);
},
);
}
}
@@ -0,0 +1,287 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:driver/core/l10n/app_localizations.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:driver/core/design/tokens.dart';
import 'package:driver/core/design/tripz_colors.dart';
import 'package:driver/features/home/data/models/trip_offer_model.dart';
import 'package:driver/features/offers/bloc/offers_bloc.dart';
/// بطاقة عرض الرحلة الواردة — تُعرض في overlay.
///
/// تتضمن:
/// - نقاط pickup/dropoff على الخريطة المصغرة
/// - معلومات المسافة والأجرة والوقت
/// - عداد تنازلي للمهلة
/// - أزرار قبول/رفض
class TripOfferCard extends StatefulWidget {
final TripOfferModel offer;
const TripOfferCard({super.key, required this.offer});
@override
State<TripOfferCard> createState() => _TripOfferCardState();
}
class _TripOfferCardState extends State<TripOfferCard> {
Timer? _countdownTimer;
int _remainingSeconds = 0;
@override
void initState() {
super.initState();
_remainingSeconds = widget.offer.expiresAt.difference(DateTime.now()).inSeconds;
_countdownTimer = Timer.periodic(const Duration(seconds: 1), (_) {
if (!mounted) return;
setState(() {
_remainingSeconds = widget.offer.expiresAt.difference(DateTime.now()).inSeconds;
if (_remainingSeconds <= 0) {
_countdownTimer?.cancel();
}
});
});
}
@override
void dispose() {
_countdownTimer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final cs = Theme.of(context).colorScheme;
final progress = _remainingSeconds > 0
? (_remainingSeconds / 30.0).clamp(0.0, 1.0)
: 0.0;
return Container(
constraints: const BoxConstraints(maxHeight: 280),
decoration: BoxDecoration(
color: cs.surface,
borderRadius: BorderRadius.circular(T.r12),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.12),
blurRadius: 16,
offset: const Offset(0, 4),
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// شريط التقدم (العد التنازلي)
LinearProgressIndicator(
value: progress,
backgroundColor: cs.surfaceContainerHighest,
valueColor: AlwaysStoppedAnimation<Color>(
_remainingSeconds > 10 ? cs.primary : context.tripzColors.danger,
),
minHeight: 4,
),
Padding(
padding: const EdgeInsets.all(T.s16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// الأجرة + العداد
Row(
children: [
Text(
widget.offer.formattedFare,
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.bold,
color: cs.primary,
),
),
const Spacer(),
Container(
padding: const EdgeInsets.symmetric(
horizontal: T.s8,
vertical: T.s4,
),
decoration: BoxDecoration(
color: _remainingSeconds > 10
? cs.primaryContainer
: context.tripzColors.danger.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(T.r8),
),
child: Text(
'${_remainingSeconds > 0 ? _remainingSeconds : 0}s',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontWeight: FontWeight.w600,
color: _remainingSeconds > 10
? cs.onPrimaryContainer
: context.tripzColors.danger,
),
),
),
],
),
const SizedBox(height: T.s12),
// المسافة والوقت
Row(
children: [
_InfoChip(
icon: Icons.straighten,
label: widget.offer.formattedDistance,
),
const SizedBox(width: T.s8),
_InfoChip(
icon: Icons.access_time,
label: '${widget.offer.etaPickup} ${l10n.min}',
),
const SizedBox(width: T.s8),
_InfoChip(
icon: Icons.local_taxi,
label: widget.offer.vehicleClass,
),
],
),
const SizedBox(height: T.s12),
// نقاط pickup وdropoff
_LocationDot(
color: const Color(0xFF4CAF50),
label: widget.offer.pickupAddress ?? l10n.pickupLocation,
),
Padding(
padding: const EdgeInsets.only(left: 7),
child: Container(
width: 2,
height: T.s16,
color: cs.outlineVariant,
),
),
_LocationDot(
color: const Color(0xFFF44336),
label: widget.offer.dropoffAddress ?? l10n.dropoffLocation,
),
const SizedBox(height: T.s16),
// أزرار القبول/الرفض
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () {
context.read<OffersBloc>().add(
OfferRejected(widget.offer.tripId),
);
},
style: OutlinedButton.styleFrom(
foregroundColor: cs.error,
side: BorderSide(color: cs.error),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(T.r12),
),
minimumSize: const Size(0, T.buttonHeight),
),
child: Text(l10n.reject),
),
),
const SizedBox(width: T.s12),
Expanded(
child: ElevatedButton(
onPressed: () {
context.read<OffersBloc>().add(
OfferAccepted(widget.offer.tripId),
);
},
style: ElevatedButton.styleFrom(
backgroundColor: cs.primary,
foregroundColor: cs.onPrimary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(T.r12),
),
minimumSize: const Size(0, T.buttonHeight),
elevation: 0,
),
child: Text(l10n.accept),
),
),
],
),
],
),
),
],
),
);
}
}
/// رقاقة معلومات صغيرة (مسافة / وقت / فئة).
class _InfoChip extends StatelessWidget {
final IconData icon;
final String label;
const _InfoChip({required this.icon, required this.label});
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return Container(
padding: const EdgeInsets.symmetric(horizontal: T.s8, vertical: T.s4),
decoration: BoxDecoration(
color: cs.surfaceContainerHighest,
borderRadius: BorderRadius.circular(T.r8),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 14, color: cs.onSurfaceVariant),
const SizedBox(width: 4),
Text(
label,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: cs.onSurfaceVariant,
),
),
],
),
);
}
}
/// نقطة موقع مع لون وعنوان.
class _LocationDot extends StatelessWidget {
final Color color;
final String label;
const _LocationDot({required this.color, required this.label});
@override
Widget build(BuildContext context) {
return Row(
children: [
Container(
width: 12,
height: 12,
decoration: BoxDecoration(
color: color,
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,235 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../data/offers_repository.dart';
import 'package:driver/features/home/data/models/trip_offer_model.dart';
import '../../trip/data/driver_socket_service.dart';
import '../../trip/data/trip_event_merger.dart';
// ─── أحداث ───
sealed class OffersEvent extends Equatable {
const OffersEvent();
@override
List<Object?> get props => [];
}
/// بدء الاستماع للعروض (بعد الاتصال بالـWebSocket).
class OffersStarted extends OffersEvent {
const OffersStarted();
}
/// عرض رحلة وارد (من WebSocket).
class OfferReceived extends OffersEvent {
final TripOfferModel offer;
const OfferReceived(this.offer);
@override
List<Object?> get props => [offer.tripId];
}
/// العرض تم قبوله من سائق آخر.
class OfferTaken extends OffersEvent {
final String tripId;
const OfferTaken(this.tripId);
@override
List<Object?> get props => [tripId];
}
/// العرض انتهت مهلته (من المؤقت).
class OfferExpired extends OffersEvent {
final String tripId;
const OfferExpired(this.tripId);
@override
List<Object?> get props => [tripId];
}
/// قبول العرض.
class OfferAccepted extends OffersEvent {
final String tripId;
const OfferAccepted(this.tripId);
@override
List<Object?> get props => [tripId];
}
/// رفض العرض يدوياً.
class OfferRejected extends OffersEvent {
final String tripId;
const OfferRejected(this.tripId);
@override
List<Object?> get props => [tripId];
}
/// مسح كل العروض (عند بدء رحلة نشطة).
class OffersClear extends OffersEvent {
const OffersClear();
}
// ─── حالة ───
class OffersState extends Equatable {
final List<TripOfferModel> offers;
final String? acceptedTripId;
final bool accepting;
final String? error;
const OffersState({
this.offers = const [],
this.acceptedTripId,
this.accepting = false,
this.error,
});
OffersState copyWith({
List<TripOfferModel>? offers,
String? acceptedTripId,
bool? accepting,
String? error,
bool clearError = false,
bool clearAccepted = false,
}) {
return OffersState(
offers: offers ?? this.offers,
acceptedTripId: clearAccepted ? null : (acceptedTripId ?? this.acceptedTripId),
accepting: accepting ?? this.accepting,
error: clearError ? null : (error ?? this.error),
);
}
/// هل هناك عرض واحد على الأقل؟
bool get hasOffers => offers.isNotEmpty;
@override
List<Object?> get props => [offers, acceptedTripId, accepting, error];
}
// ─── Bloc ───
/// OffersBloc — Bloc الثاني للسائق (docs/03 §14).
///
/// يستقبل عروض من WebSocket ويدير القبول/الرفض والمؤقت.
/// العروض تُعرض كـstack: الأحدث أولاً.
class OffersBloc extends Bloc<OffersEvent, OffersState> {
final OffersRepository _offersRepo;
final DriverSocketService _socket;
final DriverTripEventMerger _merger;
/// مؤقتات المهلة لكل عرض ( tripId → Timer ).
final Map<String, Timer> _expiryTimers = {};
OffersBloc({
required OffersRepository offersRepo,
required DriverSocketService socket,
DriverTripEventMerger? merger,
}) : _offersRepo = offersRepo,
_socket = socket,
_merger = merger ?? DriverTripEventMerger(),
super(const OffersState()) {
on<OffersStarted>(_onStarted);
on<OfferReceived>(_onOfferReceived);
on<OfferTaken>(_onOfferTaken);
on<OfferExpired>(_onOfferExpired);
on<OfferAccepted>(_onOfferAccepted);
on<OfferRejected>(_onOfferRejected);
on<OffersClear>(_onClear);
// استمع لتحديثات Merger.
_merger.offerStream.listen((offer) {
add(OfferReceived(offer));
});
_merger.offerTakenStream.listen((tripId) {
add(OfferTaken(tripId));
});
}
Future<void> _onStarted(OffersStarted event, Emitter<OffersState> emit) async {
_socket.connect();
}
void _onOfferReceived(OfferReceived event, Emitter<OffersState> emit) {
// لا تضف عروضاً مكررة.
final exists = state.offers.any((o) => o.tripId == event.offer.tripId);
if (exists) return;
final updated = [event.offer, ...state.offers];
emit(state.copyWith(offers: updated, clearError: true));
// ابدأ مؤقت المهلة.
_startExpiryTimer(event.offer);
}
void _onOfferTaken(OfferTaken event, Emitter<OffersState> emit) {
final updated = state.offers.where((o) => o.tripId != event.tripId).toList();
_cancelExpiryTimer(event.tripId);
emit(state.copyWith(offers: updated));
}
void _onOfferExpired(OfferExpired event, Emitter<OffersState> emit) {
final updated = state.offers.where((o) => o.tripId != event.tripId).toList();
_cancelExpiryTimer(event.tripId);
emit(state.copyWith(offers: updated));
}
Future<void> _onOfferAccepted(OfferAccepted event, Emitter<OffersState> emit) async {
emit(state.copyWith(accepting: true, clearError: true));
final trip = await _offersRepo.acceptTrip(event.tripId);
if (trip == null) {
emit(state.copyWith(accepting: false, error: 'Failed to accept trip'));
return;
}
// أزل كل العروض المتبقية (تم اختيار سائق).
_cancelAllTimers();
emit(state.copyWith(
offers: [],
accepting: false,
acceptedTripId: event.tripId,
));
}
void _onOfferRejected(OfferRejected event, Emitter<OffersState> emit) {
final updated = state.offers.where((o) => o.tripId != event.tripId).toList();
_cancelExpiryTimer(event.tripId);
emit(state.copyWith(offers: updated));
}
void _onClear(OffersClear event, Emitter<OffersState> emit) {
_cancelAllTimers();
emit(const OffersState());
}
// ─── مساعدات المؤقتات ───
void _startExpiryTimer(TripOfferModel offer) {
final remaining = offer.expiresAt.difference(DateTime.now());
if (remaining.isNegative) {
add(OfferExpired(offer.tripId));
return;
}
_expiryTimers[offer.tripId]?.cancel();
_expiryTimers[offer.tripId] = Timer(remaining, () {
add(OfferExpired(offer.tripId));
});
}
void _cancelExpiryTimer(String tripId) {
_expiryTimers[tripId]?.cancel();
_expiryTimers.remove(tripId);
}
void _cancelAllTimers() {
for (final timer in _expiryTimers.values) {
timer.cancel();
}
_expiryTimers.clear();
}
@override
Future<void> close() {
_cancelAllTimers();
_merger.dispose();
return super.close();
}
}
@@ -0,0 +1,41 @@
import 'package:driver/core/api/api_client.dart';
import 'package:driver/features/trip/data/models/driver_trip_model.dart';
/// مستودع عروض ورحلات السائق — يُستخدم من OffersBloc وDriverTripBloc.
class OffersRepository {
final ApiClient _api;
OffersRepository(this._api);
/// `GET /trips/available` — جلب الرحلات المتاحة.
Future<List<DriverTripModel>> getAvailableTrips() async {
try {
final r = await _api.dio.get('/trips/available');
final items = (r.data['items'] ?? r.data) as List;
return items
.map((j) => DriverTripModel.fromJson(j as Map<String, dynamic>))
.toList();
} catch (_) {
return [];
}
}
/// `POST /trips/:id/accept` — قبول عرض الرحلة.
Future<DriverTripModel?> acceptTrip(String tripId) async {
try {
final r = await _api.dio.post('/trips/$tripId/accept');
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;
}
}
}
@@ -0,0 +1,38 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'settings_state.dart';
/// الإعدادات العامة: الثيم + اللغة.
/// يُحفظ محلياً عبر SharedPreferences (ليس سراً — docs/26 §4).
class SettingsCubit extends Cubit<SettingsState> {
static const _kThemeKey = 'settings_theme_mode';
static const _kLocaleKey = 'settings_locale';
SettingsCubit() : super(const SettingsState()) {
_load();
}
Future<void> _load() async {
final prefs = await SharedPreferences.getInstance();
final themeIndex = prefs.getInt(_kThemeKey) ?? 0;
final localeCode = prefs.getString(_kLocaleKey) ?? 'ar';
emit(state.copyWith(
themeMode: ThemeMode.values[themeIndex],
locale: Locale(localeCode),
));
}
Future<void> setThemeMode(ThemeMode mode) async {
emit(state.copyWith(themeMode: mode));
final prefs = await SharedPreferences.getInstance();
await prefs.setInt(_kThemeKey, mode.index);
}
Future<void> setLocale(Locale locale) async {
emit(state.copyWith(locale: locale));
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_kLocaleKey, locale.languageCode);
}
}
@@ -0,0 +1,31 @@
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
enum SettingsStatus { loaded, error }
class SettingsState extends Equatable {
final SettingsStatus status;
final ThemeMode themeMode;
final Locale locale;
const SettingsState({
this.status = SettingsStatus.loaded,
this.themeMode = ThemeMode.system,
this.locale = const Locale('ar'),
});
SettingsState copyWith({
SettingsStatus? status,
ThemeMode? themeMode,
Locale? locale,
}) {
return SettingsState(
status: status ?? this.status,
themeMode: themeMode ?? this.themeMode,
locale: locale ?? this.locale,
);
}
@override
List<Object?> get props => [status, themeMode, locale];
}
@@ -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),
],
),
);
}
}