Food delivery driver module + masked calls + TURN
This commit is contained in:
@@ -15,8 +15,13 @@ import '../../constant/box_name.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../main.dart'; // للوصول لـ box
|
||||
import '../../print.dart';
|
||||
import '../../views/food_delivery/food_delivery_home_page.dart';
|
||||
import '../../views/food_delivery/food_offer_page.dart';
|
||||
import '../../views/food_delivery/food_task_details_page.dart';
|
||||
import '../../views/home/Captin/driver_map_page.dart';
|
||||
import '../../views/home/Captin/orderCaptin/order_request_page.dart';
|
||||
import '../food_delivery/food_delivery_controller.dart';
|
||||
import '../food_delivery/food_notification_service.dart';
|
||||
import '../functions/crud.dart';
|
||||
import '../home/captin/home_captain_controller.dart';
|
||||
|
||||
@@ -213,6 +218,14 @@ class NotificationController extends GetxController {
|
||||
if (payload == null) return;
|
||||
|
||||
final payloadData = jsonDecode(payload) as Map<String, dynamic>;
|
||||
|
||||
// إشعارات وحدة التوصيل لها حمولة وأزرار خاصة بها — نفرزها قبل أي شيء
|
||||
// لأن باقي هذه الدالة يفترض حمولة رحلة (مصفوفة add_ride.php).
|
||||
if (payloadData.containsKey('food_event')) {
|
||||
await _handleFoodNotificationResponse(response, payloadData);
|
||||
return;
|
||||
}
|
||||
|
||||
final rawData = payloadData['data'];
|
||||
|
||||
List<dynamic> listData = [];
|
||||
@@ -248,6 +261,38 @@ class NotificationController extends GetxController {
|
||||
}
|
||||
}
|
||||
|
||||
// ── فرع وحدة التوصيل — مسار مستقل تماماً عن مسار الرحلات أعلاه ──────────
|
||||
Future<void> _handleFoodNotificationResponse(
|
||||
NotificationResponse response, Map<String, dynamic> payloadData) async {
|
||||
final orderId = int.tryParse(payloadData['order_id']?.toString() ?? '') ?? 0;
|
||||
if (orderId == 0) return;
|
||||
|
||||
await FoodNotificationService.instance.cancelOfferNotification();
|
||||
|
||||
// الكنترولر قد لا يكون مسجَّلاً (الضغط على الإشعار والتطبيق مغلق)، فنسجّله
|
||||
// ليعيد بناء حالته من الخادم قبل عرض أي شاشة.
|
||||
final controller = Get.isRegistered<FoodDeliveryController>()
|
||||
? Get.find<FoodDeliveryController>()
|
||||
: Get.put(FoodDeliveryController());
|
||||
|
||||
if (response.actionId == 'FOOD_ACCEPT') {
|
||||
await controller.respondToOffer(orderId, true);
|
||||
Get.to(() => FoodTaskDetailsPage(orderId: orderId));
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.actionId == 'FOOD_REJECT') {
|
||||
await controller.respondToOffer(orderId, false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (payloadData['food_event'] == 'offer') {
|
||||
Get.to(() => const FoodOfferPage(), fullscreenDialog: true);
|
||||
} else {
|
||||
Get.to(() => const FoodDeliveryHomePage());
|
||||
}
|
||||
}
|
||||
|
||||
// ==============================================================================
|
||||
// 4. منطق القبول الآمن (Safe Accept Logic)
|
||||
// ==============================================================================
|
||||
|
||||
@@ -1,37 +1,87 @@
|
||||
// food_delivery_controller.dart — حالة تبويب التوصيل (وضع التوصيل، العروض، المهام النشطة)
|
||||
//
|
||||
// مصادر الأحداث ثلاثة، مرتّبة بالأولوية:
|
||||
// 1) سوكيت الطعام المستقل (FoodSocketService) — المسار اللحظي الأساسي.
|
||||
// 2) polling لـ pending_offers.php — يعمل فقط حين ينقطع السوكيت (لا نُحمّل
|
||||
// الخادم نداءً كل 4 ثوانٍ بينما القناة الحية شغّالة).
|
||||
// 3) active.php — مصدر الحقيقة لحالة المهام، يُصحّح أي فارق بعد أي انقطاع.
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.dart';
|
||||
import '../../views/food_delivery/food_offer_page.dart';
|
||||
import '../../views/widgets/error_snakbar.dart';
|
||||
import '../voice_call_controller.dart';
|
||||
import 'food_delivery_models.dart';
|
||||
import 'food_delivery_service.dart';
|
||||
import 'food_notification_service.dart';
|
||||
import 'food_socket_service.dart';
|
||||
|
||||
class FoodDeliveryController extends GetxController {
|
||||
bool isDeliveryModeEnabled = false;
|
||||
bool isTogglingMode = false;
|
||||
bool isSocketConnected = false;
|
||||
|
||||
List<FoodDeliveryOffer> pendingOffers = [];
|
||||
List<FoodDeliveryTask> activeTasks = [];
|
||||
bool isLoadingTasks = false;
|
||||
|
||||
int todayOrdersCount = 0;
|
||||
int todayEarnings = 0;
|
||||
|
||||
final Set<int> _respondingOfferIds = {};
|
||||
final Set<int> _busyTaskIds = {};
|
||||
// معرّفات عروض عُرضت أو انتهت — يمنع تكرار فتح الشاشة حين يصل نفس العرض
|
||||
// من السوكيت ومن polling معاً.
|
||||
final Set<int> _handledOfferIds = {};
|
||||
|
||||
Timer? _pollTimer;
|
||||
Timer? _countdownTimer;
|
||||
final AudioPlayer _audioPlayer = AudioPlayer();
|
||||
bool _isOfferScreenOpen = false;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
_refreshAll();
|
||||
_pollTimer = Timer.periodic(const Duration(seconds: 4), (_) => _refreshAll());
|
||||
FoodNotificationService.instance.ensureChannels();
|
||||
_bindSocketHandlers();
|
||||
_bootstrap();
|
||||
|
||||
// نبضة خفيفة: المهام دائماً، والعروض فقط إذا كان السوكيت مقطوعاً
|
||||
_pollTimer = Timer.periodic(const Duration(seconds: 8), (_) => _pollTick());
|
||||
_countdownTimer = Timer.periodic(const Duration(seconds: 1), (_) => _tickOffers());
|
||||
}
|
||||
|
||||
Future<void> _refreshAll() async {
|
||||
if (isDeliveryModeEnabled) {
|
||||
await _fetchPendingOffers();
|
||||
}
|
||||
Future<void> _bootstrap() async {
|
||||
await refreshStatus();
|
||||
await fetchActiveTasks();
|
||||
}
|
||||
|
||||
// ── وضع التوصيل ────────────────────────────────────────────────────────
|
||||
Future<void> refreshStatus() async {
|
||||
final res = await FoodDeliveryService.getStatus();
|
||||
if (!res.success || res.data == null) return;
|
||||
|
||||
final s = res.data!;
|
||||
isDeliveryModeEnabled = s.deliveryModeEnabled;
|
||||
todayOrdersCount = s.todayOrdersCount;
|
||||
todayEarnings = s.todayEarnings;
|
||||
|
||||
// الخادم هو مرجع الوضع — نوصل/نقطع السوكيت تبعاً له لا تبعاً لحالة الشاشة
|
||||
if (isDeliveryModeEnabled) {
|
||||
await FoodSocketService.instance.connect();
|
||||
} else {
|
||||
FoodSocketService.instance.disconnect();
|
||||
pendingOffers.clear();
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> toggleDeliveryMode(bool enable) async {
|
||||
isTogglingMode = true;
|
||||
update();
|
||||
@@ -41,23 +91,165 @@ class FoodDeliveryController extends GetxController {
|
||||
|
||||
if (res.success) {
|
||||
isDeliveryModeEnabled = enable;
|
||||
if (!enable) pendingOffers = [];
|
||||
if (enable) {
|
||||
await FoodSocketService.instance.connect();
|
||||
} else {
|
||||
FoodSocketService.instance.disconnect();
|
||||
pendingOffers.clear();
|
||||
FoodNotificationService.instance.cancelOfferNotification();
|
||||
}
|
||||
} else {
|
||||
mySnackbarWarning(res.message);
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> _fetchPendingOffers() async {
|
||||
final res = await FoodDeliveryService.getPendingOffers();
|
||||
if (res.success) {
|
||||
pendingOffers = res.data ?? [];
|
||||
// ── السوكيت ────────────────────────────────────────────────────────────
|
||||
void _bindSocketHandlers() {
|
||||
final socket = FoodSocketService.instance;
|
||||
socket.onOffer = (payload) => _handleIncomingOffer(FoodDeliveryOffer.fromJson(payload));
|
||||
socket.onOrderUpdate = _handleOrderUpdate;
|
||||
socket.onIncomingCall = _handleIncomingCall;
|
||||
socket.onConnectionChanged = (connected) {
|
||||
isSocketConnected = connected;
|
||||
// بعد أي إعادة اتصال نسحب الحالة من الخادم — السوكيت ناقل لا مخزن حالة
|
||||
if (connected) {
|
||||
fetchActiveTasks();
|
||||
_fetchPendingOffers();
|
||||
}
|
||||
update();
|
||||
};
|
||||
}
|
||||
|
||||
void _handleOrderUpdate(Map<String, dynamic> payload) {
|
||||
final status = payload['status']?.toString() ?? '';
|
||||
final orderId = int.tryParse(payload['order_id']?.toString() ?? '') ?? 0;
|
||||
|
||||
if (status.startsWith('cancelled') && orderId != 0) {
|
||||
FoodNotificationService.instance.showStatusNotification(
|
||||
orderId: orderId,
|
||||
title: 'أُلغي طلب التوصيل',
|
||||
body: 'الطلب #$orderId أُلغي — لا حاجة لمتابعته',
|
||||
);
|
||||
mySnackbarWarning('أُلغي طلب التوصيل #$orderId');
|
||||
}
|
||||
fetchActiveTasks();
|
||||
}
|
||||
|
||||
// ── المكالمة المقنّعة ───────────────────────────────────────────────────
|
||||
// الزبون بادر بالاتصال: الحمولة لا تحمل رقماً ولا اسماً حقيقياً، فقط
|
||||
// session_id ننضم به لنفس خادم الإشارات المستعمل في مكالمات الرحلات.
|
||||
void _handleIncomingCall(Map<String, dynamic> payload) {
|
||||
final sessionId = payload['session_id']?.toString() ?? '';
|
||||
final orderId = payload['order_id']?.toString() ?? '';
|
||||
if (sessionId.isEmpty || orderId.isEmpty) return;
|
||||
|
||||
// مسجَّل عالمياً بـ lazyPut(fenix) في main — والـ put احتياط لو أُزيل
|
||||
final callController = _voiceCall();
|
||||
|
||||
callController.receiveCall(
|
||||
sessionIdVal: sessionId,
|
||||
remoteNameVal: payload['caller_name']?.toString() ?? 'زبون الطلب',
|
||||
rideIdVal: 'food_$orderId',
|
||||
);
|
||||
}
|
||||
|
||||
/// السائق يتصل بالزبون — لا يرى رقمه ولا يُخزَّن عنده
|
||||
Future<void> callCustomer(int orderId) async {
|
||||
// مسجَّل عالمياً بـ lazyPut(fenix) في main — والـ put احتياط لو أُزيل
|
||||
final callController = _voiceCall();
|
||||
|
||||
await callController.startCall(
|
||||
rideIdVal: 'food_$orderId',
|
||||
driverId: box.read(BoxName.driverID).toString(),
|
||||
passengerId: '', // هوية الزبون لا تصل التطبيق — الخادم يحلّها من الطلب
|
||||
remoteNameVal: 'زبون الطلب',
|
||||
sessionEndpoint: '${AppLink.server}/food/courier/call_customer.php',
|
||||
sessionPayload: {'order_id': orderId.toString()},
|
||||
);
|
||||
}
|
||||
|
||||
VoiceCallController _voiceCall() {
|
||||
try {
|
||||
return Get.find<VoiceCallController>();
|
||||
} catch (_) {
|
||||
return Get.put(VoiceCallController());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fetchActiveTasks() async {
|
||||
isLoadingTasks = true;
|
||||
// ── العروض ─────────────────────────────────────────────────────────────
|
||||
void _handleIncomingOffer(FoodDeliveryOffer offer) {
|
||||
if (offer.orderId == 0 || offer.isExpired) return;
|
||||
if (_handledOfferIds.contains(offer.orderId)) return;
|
||||
if (pendingOffers.any((o) => o.orderId == offer.orderId)) return;
|
||||
|
||||
_handledOfferIds.add(offer.orderId);
|
||||
pendingOffers.add(offer);
|
||||
update();
|
||||
|
||||
_playOfferSound();
|
||||
|
||||
final isForeground = box.read(BoxName.isAppInForeground) ?? false;
|
||||
if (isForeground == true) {
|
||||
_openOfferScreen();
|
||||
} else {
|
||||
// التطبيق في الخلفية — إشعار ملء شاشة بقناة التوصيل الخاصة
|
||||
FoodNotificationService.instance.showOfferNotification(offer);
|
||||
}
|
||||
}
|
||||
|
||||
void _openOfferScreen() {
|
||||
if (_isOfferScreenOpen) return;
|
||||
_isOfferScreenOpen = true;
|
||||
Get.to(() => const FoodOfferPage(), fullscreenDialog: true)?.whenComplete(() {
|
||||
_isOfferScreenOpen = false;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _playOfferSound() async {
|
||||
try {
|
||||
await _audioPlayer.setAsset('assets/order1.wav');
|
||||
await _audioPlayer.play();
|
||||
} catch (e) {
|
||||
Log.print('🍔 [FoodDelivery] تعذّر تشغيل نغمة العرض: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// انتهاء المهلة يُدار محلياً للعرض فقط — الخادم يرفض أي قبول متأخر أصلاً
|
||||
void _tickOffers() {
|
||||
if (pendingOffers.isEmpty) return;
|
||||
final before = pendingOffers.length;
|
||||
pendingOffers.removeWhere((o) => o.isExpired);
|
||||
if (pendingOffers.isEmpty && before > 0) {
|
||||
FoodNotificationService.instance.cancelOfferNotification();
|
||||
if (_isOfferScreenOpen && Get.currentRoute.contains('FoodOfferPage')) {
|
||||
Get.back();
|
||||
}
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> _pollTick() async {
|
||||
// العروض عبر polling فقط عند انقطاع السوكيت — احتياط لا مسار أساسي
|
||||
if (isDeliveryModeEnabled && !FoodSocketService.instance.isConnected) {
|
||||
await _fetchPendingOffers();
|
||||
}
|
||||
await fetchActiveTasks(silent: true);
|
||||
}
|
||||
|
||||
Future<void> _fetchPendingOffers() async {
|
||||
final res = await FoodDeliveryService.getPendingOffers();
|
||||
if (!res.success) return;
|
||||
for (final offer in res.data ?? <FoodDeliveryOffer>[]) {
|
||||
_handleIncomingOffer(offer);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fetchActiveTasks({bool silent = false}) async {
|
||||
if (!silent) {
|
||||
isLoadingTasks = true;
|
||||
update();
|
||||
}
|
||||
final res = await FoodDeliveryService.getActiveTasks();
|
||||
isLoadingTasks = false;
|
||||
if (res.success) activeTasks = res.data ?? [];
|
||||
@@ -76,6 +268,7 @@ class FoodDeliveryController extends GetxController {
|
||||
|
||||
_respondingOfferIds.remove(orderId);
|
||||
pendingOffers.removeWhere((o) => o.orderId == orderId);
|
||||
FoodNotificationService.instance.cancelOfferNotification();
|
||||
|
||||
if (!res.success) {
|
||||
mySnackbarWarning(res.message);
|
||||
@@ -83,10 +276,15 @@ class FoodDeliveryController extends GetxController {
|
||||
mySnackbarSuccess('تم قبول طلب التوصيل');
|
||||
}
|
||||
|
||||
if (pendingOffers.isEmpty && _isOfferScreenOpen && Get.currentRoute.contains('FoodOfferPage')) {
|
||||
Get.back();
|
||||
}
|
||||
|
||||
update();
|
||||
await fetchActiveTasks();
|
||||
}
|
||||
|
||||
// ── خطوات المهمة ───────────────────────────────────────────────────────
|
||||
Future<void> markPickedUp(int orderId) async {
|
||||
if (_busyTaskIds.contains(orderId)) return;
|
||||
_busyTaskIds.add(orderId);
|
||||
@@ -115,6 +313,7 @@ class FoodDeliveryController extends GetxController {
|
||||
if (res.success) {
|
||||
mySnackbarSuccess('تم تسليم الطلب بنجاح');
|
||||
await fetchActiveTasks();
|
||||
await refreshStatus(); // تحديث عدّاد أرباح اليوم فوراً بعد التسليم
|
||||
} else {
|
||||
mySnackbarWarning(res.message);
|
||||
}
|
||||
@@ -124,6 +323,10 @@ class FoodDeliveryController extends GetxController {
|
||||
@override
|
||||
void onClose() {
|
||||
_pollTimer?.cancel();
|
||||
_countdownTimer?.cancel();
|
||||
_audioPlayer.dispose();
|
||||
// لا نقطع السوكيت هنا: وضع التوصيل قد يبقى مفعّلاً بعد إغلاق الشاشة،
|
||||
// والقطع يتم فقط عند إطفاء الوضع صراحةً من التبديل.
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
// food_delivery_models.dart — نماذج بيانات وحدة التوصيل (جهة السائق)
|
||||
|
||||
int _int(dynamic v) => int.tryParse(v?.toString() ?? '') ?? 0;
|
||||
double? _doubleOrNull(dynamic v) => double.tryParse(v?.toString() ?? '');
|
||||
double _double(dynamic v) => double.tryParse(v?.toString() ?? '') ?? 0;
|
||||
DateTime? _date(dynamic v) => DateTime.tryParse(v?.toString() ?? '');
|
||||
|
||||
class FoodDeliveryTask {
|
||||
final int id;
|
||||
final String status; // courier_assigned | picked_up
|
||||
@@ -9,10 +14,22 @@ class FoodDeliveryTask {
|
||||
final double? merchantLng;
|
||||
final String? merchantAddress;
|
||||
final int deliveryFee;
|
||||
final int itemsTotal;
|
||||
final int serviceFee;
|
||||
final int discount;
|
||||
final int grandTotal;
|
||||
final String paymentMethod; // wallet | cash
|
||||
final int cashToCollect;
|
||||
final int courierOwes;
|
||||
final int itemsCount;
|
||||
final String? customerNote;
|
||||
final String? deliveryAddress;
|
||||
final double deliveryLat;
|
||||
final double deliveryLng;
|
||||
final DateTime? createdAt;
|
||||
final DateTime? readyAt;
|
||||
final DateTime? courierAssignedAt;
|
||||
final DateTime? pickedUpAt;
|
||||
|
||||
FoodDeliveryTask({
|
||||
required this.id,
|
||||
@@ -22,37 +39,73 @@ class FoodDeliveryTask {
|
||||
required this.deliveryFee,
|
||||
required this.deliveryLat,
|
||||
required this.deliveryLng,
|
||||
this.itemsTotal = 0,
|
||||
this.serviceFee = 0,
|
||||
this.discount = 0,
|
||||
this.grandTotal = 0,
|
||||
this.paymentMethod = 'wallet',
|
||||
this.cashToCollect = 0,
|
||||
this.courierOwes = 0,
|
||||
this.itemsCount = 0,
|
||||
this.customerNote,
|
||||
this.merchantLat,
|
||||
this.merchantLng,
|
||||
this.merchantAddress,
|
||||
this.deliveryAddress,
|
||||
this.createdAt,
|
||||
this.readyAt,
|
||||
this.courierAssignedAt,
|
||||
this.pickedUpAt,
|
||||
});
|
||||
|
||||
bool get isPickedUp => status == 'picked_up';
|
||||
bool get isCash => paymentMethod == 'cash';
|
||||
|
||||
factory FoodDeliveryTask.fromJson(Map<String, dynamic> j) => FoodDeliveryTask(
|
||||
id: int.tryParse(j['id'].toString()) ?? 0,
|
||||
id: _int(j['id']),
|
||||
status: j['status']?.toString() ?? '',
|
||||
merchantId: int.tryParse(j['merchant_id'].toString()) ?? 0,
|
||||
merchantId: _int(j['merchant_id']),
|
||||
merchantNameAr: j['merchant_name_ar']?.toString() ?? '',
|
||||
merchantLat: double.tryParse(j['merchant_lat']?.toString() ?? ''),
|
||||
merchantLng: double.tryParse(j['merchant_lng']?.toString() ?? ''),
|
||||
merchantLat: _doubleOrNull(j['merchant_lat']),
|
||||
merchantLng: _doubleOrNull(j['merchant_lng']),
|
||||
merchantAddress: j['merchant_address']?.toString(),
|
||||
deliveryFee: int.tryParse(j['delivery_fee']?.toString() ?? '0') ?? 0,
|
||||
deliveryFee: _int(j['delivery_fee']),
|
||||
itemsTotal: _int(j['items_total']),
|
||||
serviceFee: _int(j['service_fee']),
|
||||
discount: _int(j['discount']),
|
||||
grandTotal: _int(j['grand_total']),
|
||||
paymentMethod: j['payment_method']?.toString() ?? 'wallet',
|
||||
cashToCollect: _int(j['cash_to_collect']),
|
||||
courierOwes: _int(j['courier_owes']),
|
||||
itemsCount: _int(j['items_count']),
|
||||
customerNote: j['customer_note']?.toString(),
|
||||
deliveryAddress: j['delivery_address']?.toString(),
|
||||
deliveryLat: double.tryParse(j['delivery_lat']?.toString() ?? '0') ?? 0,
|
||||
deliveryLng: double.tryParse(j['delivery_lng']?.toString() ?? '0') ?? 0,
|
||||
createdAt: DateTime.tryParse(j['created_at']?.toString() ?? ''),
|
||||
deliveryLat: _double(j['delivery_lat']),
|
||||
deliveryLng: _double(j['delivery_lng']),
|
||||
createdAt: _date(j['created_at']),
|
||||
readyAt: _date(j['ready_at']),
|
||||
courierAssignedAt: _date(j['courier_assigned_at']),
|
||||
pickedUpAt: _date(j['picked_up_at']),
|
||||
);
|
||||
}
|
||||
|
||||
// عرض توصيل وارد — من polling على food/courier/pending_offers.php
|
||||
// عرض توصيل وارد — يصل عبر سوكيت الطعام ('food_delivery_offer') وبنفس الحقول
|
||||
// من courier/pending_offers.php عند انقطاع السوكيت (foodBuildCourierOfferPayload).
|
||||
class FoodDeliveryOffer {
|
||||
final int orderId;
|
||||
final int merchantId;
|
||||
final String merchantNameAr;
|
||||
final String? merchantAddress;
|
||||
final double? merchantLat;
|
||||
final double? merchantLng;
|
||||
final double deliveryLat;
|
||||
final double deliveryLng;
|
||||
final int deliveryFee;
|
||||
final int itemsCount;
|
||||
final String paymentMethod;
|
||||
final int cashToCollect;
|
||||
final int ttlSeconds;
|
||||
final DateTime receivedAt;
|
||||
final DateTime? offeredAt;
|
||||
|
||||
FoodDeliveryOffer({
|
||||
@@ -60,28 +113,206 @@ class FoodDeliveryOffer {
|
||||
required this.merchantId,
|
||||
required this.merchantNameAr,
|
||||
required this.deliveryFee,
|
||||
this.merchantAddress,
|
||||
this.merchantLat,
|
||||
this.merchantLng,
|
||||
this.deliveryLat = 0,
|
||||
this.deliveryLng = 0,
|
||||
this.itemsCount = 0,
|
||||
this.paymentMethod = 'wallet',
|
||||
this.cashToCollect = 0,
|
||||
this.ttlSeconds = 20,
|
||||
DateTime? receivedAt,
|
||||
this.offeredAt,
|
||||
});
|
||||
}) : receivedAt = receivedAt ?? DateTime.now();
|
||||
|
||||
bool get isCash => paymentMethod == 'cash';
|
||||
|
||||
factory FoodDeliveryOffer.fromJson(Map<String, dynamic> j) => FoodDeliveryOffer(
|
||||
orderId: int.tryParse(j['order_id'].toString()) ?? 0,
|
||||
merchantId: int.tryParse(j['merchant_id'].toString()) ?? 0,
|
||||
orderId: _int(j['order_id']),
|
||||
merchantId: _int(j['merchant_id']),
|
||||
merchantNameAr: j['merchant_name_ar']?.toString() ?? '',
|
||||
merchantLat: double.tryParse(j['merchant_lat']?.toString() ?? ''),
|
||||
merchantLng: double.tryParse(j['merchant_lng']?.toString() ?? ''),
|
||||
deliveryFee: int.tryParse(j['delivery_fee']?.toString() ?? '0') ?? 0,
|
||||
offeredAt: DateTime.tryParse(j['offered_at']?.toString() ?? ''),
|
||||
merchantAddress: j['merchant_address']?.toString(),
|
||||
merchantLat: _doubleOrNull(j['merchant_lat']),
|
||||
merchantLng: _doubleOrNull(j['merchant_lng']),
|
||||
deliveryLat: _double(j['delivery_lat']),
|
||||
deliveryLng: _double(j['delivery_lng']),
|
||||
deliveryFee: _int(j['delivery_fee']),
|
||||
itemsCount: _int(j['items_count']),
|
||||
paymentMethod: j['payment_method']?.toString() ?? 'wallet',
|
||||
cashToCollect: _int(j['cash_to_collect']),
|
||||
ttlSeconds: _int(j['offer_ttl_seconds']) == 0 ? 20 : _int(j['offer_ttl_seconds']),
|
||||
offeredAt: _date(j['offered_at']),
|
||||
);
|
||||
|
||||
// مهلة العرض 20 ثانية من الخادم (SET NX EX 20) — عدّاد تقريبي للعرض فقط،
|
||||
// الخادم هو الحكم الفعلي (رفض offer_respond إن انتهت المهلة فعلاً).
|
||||
// العدّاد للعرض فقط — الخادم هو الحكم الفعلي ويرفض offer_respond بعد المهلة.
|
||||
// نبدأ من offered_at إن جاءت (مسار polling)، وإلا من لحظة الاستلام (مسار السوكيت).
|
||||
int get secondsRemaining {
|
||||
if (offeredAt == null) return 20;
|
||||
final elapsed = DateTime.now().difference(offeredAt!).inSeconds;
|
||||
return (20 - elapsed).clamp(0, 20);
|
||||
final start = offeredAt ?? receivedAt;
|
||||
final elapsed = DateTime.now().difference(start).inSeconds;
|
||||
return (ttlSeconds - elapsed).clamp(0, ttlSeconds);
|
||||
}
|
||||
|
||||
bool get isExpired => secondsRemaining <= 0;
|
||||
}
|
||||
|
||||
// صنف داخل الطلب — يراه السائق ليتأكد من محتوى الكيس عند الاستلام من المطعم
|
||||
class FoodOrderItem {
|
||||
final String nameAr;
|
||||
final int quantity;
|
||||
final int unitPrice;
|
||||
final int lineTotal;
|
||||
|
||||
FoodOrderItem({
|
||||
required this.nameAr,
|
||||
required this.quantity,
|
||||
required this.unitPrice,
|
||||
required this.lineTotal,
|
||||
});
|
||||
|
||||
factory FoodOrderItem.fromJson(Map<String, dynamic> j) => FoodOrderItem(
|
||||
nameAr: j['name_ar']?.toString() ?? '',
|
||||
quantity: _int(j['quantity']),
|
||||
unitPrice: _int(j['unit_price']),
|
||||
lineTotal: _int(j['line_total']),
|
||||
);
|
||||
}
|
||||
|
||||
class FoodOrderDetails {
|
||||
final FoodDeliveryTask task;
|
||||
final List<FoodOrderItem> items;
|
||||
final String? merchantPhone;
|
||||
|
||||
FoodOrderDetails({required this.task, required this.items, this.merchantPhone});
|
||||
|
||||
factory FoodOrderDetails.fromJson(Map<String, dynamic> j) => FoodOrderDetails(
|
||||
task: FoodDeliveryTask.fromJson(j),
|
||||
items: (j['items'] is List)
|
||||
? (j['items'] as List)
|
||||
.map((i) => FoodOrderItem.fromJson(Map<String, dynamic>.from(i)))
|
||||
.toList()
|
||||
: <FoodOrderItem>[],
|
||||
merchantPhone: j['merchant_phone']?.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
class FoodCourierStatus {
|
||||
final bool deliveryModeEnabled;
|
||||
final int activeOrdersCount;
|
||||
final int todayOrdersCount;
|
||||
final int todayEarnings;
|
||||
|
||||
FoodCourierStatus({
|
||||
required this.deliveryModeEnabled,
|
||||
this.activeOrdersCount = 0,
|
||||
this.todayOrdersCount = 0,
|
||||
this.todayEarnings = 0,
|
||||
});
|
||||
|
||||
factory FoodCourierStatus.fromJson(Map<String, dynamic> j) => FoodCourierStatus(
|
||||
deliveryModeEnabled: j['delivery_mode_enabled'] == true ||
|
||||
j['delivery_mode_enabled']?.toString() == '1' ||
|
||||
j['delivery_mode_enabled']?.toString() == 'true',
|
||||
activeOrdersCount: _int(j['active_orders_count']),
|
||||
todayOrdersCount: _int(j['today_orders_count']),
|
||||
todayEarnings: _int(j['today_earnings']),
|
||||
);
|
||||
}
|
||||
|
||||
class FoodEarningsDay {
|
||||
final String day;
|
||||
final int ordersCount;
|
||||
final int earnings;
|
||||
|
||||
FoodEarningsDay({required this.day, required this.ordersCount, required this.earnings});
|
||||
|
||||
factory FoodEarningsDay.fromJson(Map<String, dynamic> j) => FoodEarningsDay(
|
||||
day: j['day']?.toString() ?? '',
|
||||
ordersCount: _int(j['orders_count']),
|
||||
earnings: _int(j['earnings']),
|
||||
);
|
||||
}
|
||||
|
||||
class FoodEarnings {
|
||||
final int todayEarnings;
|
||||
final int todayOrders;
|
||||
final int weekEarnings;
|
||||
final int weekOrders;
|
||||
final int monthEarnings;
|
||||
final int monthOrders;
|
||||
final int totalEarnings;
|
||||
final int totalOrders;
|
||||
final int pendingCashOwed;
|
||||
final List<FoodEarningsDay> daily;
|
||||
|
||||
FoodEarnings({
|
||||
required this.todayEarnings,
|
||||
required this.todayOrders,
|
||||
required this.weekEarnings,
|
||||
required this.weekOrders,
|
||||
required this.monthEarnings,
|
||||
required this.monthOrders,
|
||||
required this.totalEarnings,
|
||||
required this.totalOrders,
|
||||
required this.pendingCashOwed,
|
||||
required this.daily,
|
||||
});
|
||||
|
||||
factory FoodEarnings.fromJson(Map<String, dynamic> j) => FoodEarnings(
|
||||
todayEarnings: _int(j['today_earnings']),
|
||||
todayOrders: _int(j['today_orders']),
|
||||
weekEarnings: _int(j['week_earnings']),
|
||||
weekOrders: _int(j['week_orders']),
|
||||
monthEarnings: _int(j['month_earnings']),
|
||||
monthOrders: _int(j['month_orders']),
|
||||
totalEarnings: _int(j['total_earnings']),
|
||||
totalOrders: _int(j['total_orders']),
|
||||
pendingCashOwed: _int(j['pending_cash_owed']),
|
||||
daily: (j['daily'] is List)
|
||||
? (j['daily'] as List)
|
||||
.map((d) => FoodEarningsDay.fromJson(Map<String, dynamic>.from(d)))
|
||||
.toList()
|
||||
: <FoodEarningsDay>[],
|
||||
);
|
||||
}
|
||||
|
||||
class FoodHistoryEntry {
|
||||
final int id;
|
||||
final String merchantNameAr;
|
||||
final String? merchantAddress;
|
||||
final int deliveryFee;
|
||||
final int grandTotal;
|
||||
final String paymentMethod;
|
||||
final int itemsCount;
|
||||
final int? rating;
|
||||
final int? durationMinutes;
|
||||
final DateTime? deliveredAt;
|
||||
|
||||
FoodHistoryEntry({
|
||||
required this.id,
|
||||
required this.merchantNameAr,
|
||||
required this.deliveryFee,
|
||||
this.merchantAddress,
|
||||
this.grandTotal = 0,
|
||||
this.paymentMethod = 'wallet',
|
||||
this.itemsCount = 0,
|
||||
this.rating,
|
||||
this.durationMinutes,
|
||||
this.deliveredAt,
|
||||
});
|
||||
|
||||
factory FoodHistoryEntry.fromJson(Map<String, dynamic> j) => FoodHistoryEntry(
|
||||
id: _int(j['id']),
|
||||
merchantNameAr: j['merchant_name_ar']?.toString() ?? '',
|
||||
merchantAddress: j['merchant_address']?.toString(),
|
||||
deliveryFee: _int(j['delivery_fee']),
|
||||
grandTotal: _int(j['grand_total']),
|
||||
paymentMethod: j['payment_method']?.toString() ?? 'wallet',
|
||||
itemsCount: _int(j['items_count']),
|
||||
rating: j['rating'] == null ? null : _int(j['rating']),
|
||||
durationMinutes: j['duration_minutes'] == null ? null : _int(j['duration_minutes']),
|
||||
deliveredAt: _date(j['delivered_at']),
|
||||
);
|
||||
}
|
||||
|
||||
const int foodCurrencyDivisor = 1000;
|
||||
|
||||
@@ -22,30 +22,66 @@ class FoodDeliveryService {
|
||||
return FoodDeliveryApiResult(false, null, _errMsg(res));
|
||||
}
|
||||
|
||||
/// حالة السائق عند فتح التبويب — وضع التوصيل مخزَّن في Redis على الخادم،
|
||||
/// فلا يجوز افتراض "مغلق" محلياً وإلا ظهر التبديل مطفأً والعروض تصل فعلاً.
|
||||
static Future<FoodDeliveryApiResult<FoodCourierStatus>> getStatus() async {
|
||||
final res = await CRUD().post(link: '$_base/courier/status.php');
|
||||
final msg = _payload(res);
|
||||
if (msg != null) {
|
||||
return FoodDeliveryApiResult(true, FoodCourierStatus.fromJson(msg), 'ok');
|
||||
}
|
||||
return FoodDeliveryApiResult(false, null, _errMsg(res));
|
||||
}
|
||||
|
||||
static Future<FoodDeliveryApiResult<List<FoodDeliveryTask>>> getActiveTasks() async {
|
||||
final res = await CRUD().post(link: '$_base/courier/active.php');
|
||||
if (res is Map && res['status'] == 'success') {
|
||||
final msg = res['message'];
|
||||
final list = (msg is Map && msg['orders'] is List)
|
||||
? (msg['orders'] as List)
|
||||
.map((o) => FoodDeliveryTask.fromJson(Map<String, dynamic>.from(o)))
|
||||
.toList()
|
||||
: <FoodDeliveryTask>[];
|
||||
return FoodDeliveryApiResult(true, list, 'ok');
|
||||
final msg = _payload(res);
|
||||
if (msg != null) {
|
||||
return FoodDeliveryApiResult(true, _list(msg['orders'], FoodDeliveryTask.fromJson), 'ok');
|
||||
}
|
||||
return FoodDeliveryApiResult(false, null, _errMsg(res));
|
||||
}
|
||||
|
||||
static Future<FoodDeliveryApiResult<List<FoodDeliveryOffer>>> getPendingOffers() async {
|
||||
final res = await CRUD().post(link: '$_base/courier/pending_offers.php');
|
||||
if (res is Map && res['status'] == 'success') {
|
||||
final msg = res['message'];
|
||||
final list = (msg is Map && msg['offers'] is List)
|
||||
? (msg['offers'] as List)
|
||||
.map((o) => FoodDeliveryOffer.fromJson(Map<String, dynamic>.from(o)))
|
||||
.toList()
|
||||
: <FoodDeliveryOffer>[];
|
||||
return FoodDeliveryApiResult(true, list, 'ok');
|
||||
final msg = _payload(res);
|
||||
if (msg != null) {
|
||||
return FoodDeliveryApiResult(true, _list(msg['offers'], FoodDeliveryOffer.fromJson), 'ok');
|
||||
}
|
||||
return FoodDeliveryApiResult(false, null, _errMsg(res));
|
||||
}
|
||||
|
||||
static Future<FoodDeliveryApiResult<FoodOrderDetails>> getOrderDetails(int orderId) async {
|
||||
final res = await CRUD().post(
|
||||
link: '$_base/courier/order_details.php',
|
||||
payload: {'order_id': orderId.toString()},
|
||||
);
|
||||
final msg = _payload(res);
|
||||
if (msg != null && msg['order'] is Map) {
|
||||
return FoodDeliveryApiResult(
|
||||
true, FoodOrderDetails.fromJson(Map<String, dynamic>.from(msg['order'])), 'ok');
|
||||
}
|
||||
return FoodDeliveryApiResult(false, null, _errMsg(res));
|
||||
}
|
||||
|
||||
static Future<FoodDeliveryApiResult<FoodEarnings>> getEarnings() async {
|
||||
final res = await CRUD().post(link: '$_base/courier/earnings.php');
|
||||
final msg = _payload(res);
|
||||
if (msg != null) return FoodDeliveryApiResult(true, FoodEarnings.fromJson(msg), 'ok');
|
||||
return FoodDeliveryApiResult(false, null, _errMsg(res));
|
||||
}
|
||||
|
||||
static Future<FoodDeliveryApiResult<List<FoodHistoryEntry>>> getHistory({
|
||||
int limit = 20,
|
||||
int offset = 0,
|
||||
}) async {
|
||||
final res = await CRUD().post(
|
||||
link: '$_base/courier/history.php',
|
||||
payload: {'limit': limit.toString(), 'offset': offset.toString()},
|
||||
);
|
||||
final msg = _payload(res);
|
||||
if (msg != null) {
|
||||
return FoodDeliveryApiResult(true, _list(msg['orders'], FoodHistoryEntry.fromJson), 'ok');
|
||||
}
|
||||
return FoodDeliveryApiResult(false, null, _errMsg(res));
|
||||
}
|
||||
@@ -55,9 +91,9 @@ class FoodDeliveryService {
|
||||
link: '$_base/courier/offer_respond.php',
|
||||
payload: {'order_id': orderId.toString(), 'response': accept ? 'accept' : 'reject'},
|
||||
);
|
||||
if (res is Map && res['status'] == 'success') {
|
||||
final msg = res['message'];
|
||||
return FoodDeliveryApiResult(true, (msg is Map ? msg['response']?.toString() : null) ?? '', 'ok');
|
||||
final msg = _payload(res);
|
||||
if (msg != null) {
|
||||
return FoodDeliveryApiResult(true, msg['response']?.toString() ?? '', 'ok');
|
||||
}
|
||||
return FoodDeliveryApiResult(false, null, _errMsg(res));
|
||||
}
|
||||
@@ -80,6 +116,19 @@ class FoodDeliveryService {
|
||||
return FoodDeliveryApiResult(false, null, _errMsg(res));
|
||||
}
|
||||
|
||||
// كل ردود backend/food تأتي بغلاف {status, message:{...}} — نستخرج المحتوى مرة واحدة
|
||||
static Map<String, dynamic>? _payload(dynamic res) {
|
||||
if (res is Map && res['status'] == 'success' && res['message'] is Map) {
|
||||
return Map<String, dynamic>.from(res['message']);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static List<T> _list<T>(dynamic raw, T Function(Map<String, dynamic>) fromJson) {
|
||||
if (raw is! List) return <T>[];
|
||||
return raw.map((e) => fromJson(Map<String, dynamic>.from(e))).toList();
|
||||
}
|
||||
|
||||
static String _errMsg(dynamic res) {
|
||||
if (res == 'no_internet') return 'تحقق من اتصالك بالإنترنت';
|
||||
if (res == 'token_expired') return 'انتهت الجلسة، حاول مجدداً';
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
// food_notification_service.dart — إشعارات وحدة التوصيل، منفصلة كلياً عن إشعارات الرحلات
|
||||
//
|
||||
// الفصل مقصود على ثلاثة مستويات:
|
||||
// 1) قناتان أندرويد خاصتان (food_delivery_offer_channel / food_delivery_status_channel)
|
||||
// غير 'high_importance_channel' الخاص بالرحلات — فيقدر السائق يكتم أو يغيّر
|
||||
// نغمة التوصيل من إعدادات النظام دون أن يمسّ تنبيه الرحلات إطلاقاً.
|
||||
// 2) معرّفات إشعارات مستقلة (7001/7002) فلا يستبدل إشعار توصيل إشعارَ رحلة.
|
||||
// 3) أزرار وحمولة خاصة ('FOOD_ACCEPT'/'FOOD_REJECT' + {"food_event": ...})
|
||||
// يلتقطها فرع مستقل في handleNotificationResponse.
|
||||
import 'dart:convert';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
|
||||
import 'food_delivery_models.dart';
|
||||
|
||||
class FoodNotificationService {
|
||||
FoodNotificationService._();
|
||||
static final FoodNotificationService instance = FoodNotificationService._();
|
||||
|
||||
// نفس نسخة الإضافة المستخدمة في NotificationController (singleton داخل الحزمة)،
|
||||
// لكن بقنوات ومعرّفات خاصة بنا — لا نستدعي initialize هنا إطلاقاً حتى لا
|
||||
// نستبدل معالِج النقر العام الذي هيّأه تطبيق الرحلات عند الإقلاع.
|
||||
final FlutterLocalNotificationsPlugin _plugin = FlutterLocalNotificationsPlugin();
|
||||
|
||||
static const String offerChannelId = 'food_delivery_offer_channel';
|
||||
static const String statusChannelId = 'food_delivery_status_channel';
|
||||
static const int offerNotificationId = 7001;
|
||||
static const int statusNotificationId = 7002;
|
||||
|
||||
bool _channelsReady = false;
|
||||
|
||||
Future<void> ensureChannels() async {
|
||||
if (_channelsReady) return;
|
||||
|
||||
final android = _plugin.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin>();
|
||||
if (android == null) {
|
||||
_channelsReady = true; // iOS — لا قنوات
|
||||
return;
|
||||
}
|
||||
|
||||
const offerChannel = AndroidNotificationChannel(
|
||||
offerChannelId,
|
||||
'عروض التوصيل',
|
||||
description: 'تنبيه وصول عرض توصيل طلب طعام جديد',
|
||||
importance: Importance.max,
|
||||
playSound: true,
|
||||
sound: RawResourceAndroidNotificationSound('order1'),
|
||||
enableVibration: true,
|
||||
);
|
||||
|
||||
const statusChannel = AndroidNotificationChannel(
|
||||
statusChannelId,
|
||||
'تحديثات طلبات التوصيل',
|
||||
description: 'تغيّر حالة طلب توصيل قائم (جاهز، ملغى، إلخ)',
|
||||
importance: Importance.high,
|
||||
playSound: true,
|
||||
);
|
||||
|
||||
await android.createNotificationChannel(offerChannel);
|
||||
await android.createNotificationChannel(statusChannel);
|
||||
_channelsReady = true;
|
||||
}
|
||||
|
||||
/// إشعار عرض توصيل — ملء الشاشة (fullScreenIntent) كإشعار المكالمة، لأن مهلة
|
||||
/// العرض 20 ثانية ولا تحتمل أن يمرّ السائق على شريط الإشعارات لاحقاً.
|
||||
Future<void> showOfferNotification(FoodDeliveryOffer offer) async {
|
||||
await ensureChannels();
|
||||
|
||||
final body = '${offer.merchantNameAr}\n'
|
||||
'💰 أجرة التوصيل: ${foodFormatPrice(offer.deliveryFee)}'
|
||||
'${offer.itemsCount > 0 ? ' | 🧾 ${offer.itemsCount} صنف' : ''}'
|
||||
'${offer.cashToCollect > 0 ? '\n💵 تحصيل نقدي: ${foodFormatPrice(offer.cashToCollect)}' : ''}';
|
||||
|
||||
final androidDetails = AndroidNotificationDetails(
|
||||
offerChannelId,
|
||||
'عروض التوصيل',
|
||||
importance: Importance.max,
|
||||
priority: Priority.max,
|
||||
fullScreenIntent: true,
|
||||
category: AndroidNotificationCategory.call,
|
||||
visibility: NotificationVisibility.public,
|
||||
timeoutAfter: 20000, // يختفي مع انتهاء مهلة العرض نفسها
|
||||
sound: const RawResourceAndroidNotificationSound('order1'),
|
||||
audioAttributesUsage: AudioAttributesUsage.alarm,
|
||||
color: const Color(0xFFFF6B35),
|
||||
styleInformation: BigTextStyleInformation(
|
||||
body,
|
||||
contentTitle: '🍔 عرض توصيل جديد',
|
||||
summaryText: foodFormatPrice(offer.deliveryFee),
|
||||
),
|
||||
actions: const <AndroidNotificationAction>[
|
||||
AndroidNotificationAction('FOOD_ACCEPT', '✅ قبول',
|
||||
showsUserInterface: true, titleColor: Color(0xFF4CAF50)),
|
||||
AndroidNotificationAction('FOOD_REJECT', '❌ رفض',
|
||||
cancelNotification: true, titleColor: Color(0xFFE53935)),
|
||||
],
|
||||
);
|
||||
|
||||
const iosDetails = DarwinNotificationDetails(
|
||||
sound: 'order1.wav',
|
||||
presentAlert: true,
|
||||
presentBadge: true,
|
||||
presentSound: true,
|
||||
categoryIdentifier: 'FOOD_OFFER_CATEGORY',
|
||||
interruptionLevel: InterruptionLevel.timeSensitive,
|
||||
);
|
||||
|
||||
await _plugin.show(
|
||||
id: offerNotificationId,
|
||||
title: '🍔 عرض توصيل جديد',
|
||||
body: '${offer.merchantNameAr} — ${foodFormatPrice(offer.deliveryFee)}',
|
||||
notificationDetails:
|
||||
NotificationDetails(android: androidDetails, iOS: iosDetails),
|
||||
payload: jsonEncode({
|
||||
'food_event': 'offer',
|
||||
'order_id': offer.orderId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> cancelOfferNotification() async {
|
||||
await _plugin.cancel(id: offerNotificationId);
|
||||
}
|
||||
|
||||
/// تحديث حالة مهمة قائمة (مثلاً إلغاء من النظام) — قناة أهدأ، بلا ملء شاشة
|
||||
Future<void> showStatusNotification({
|
||||
required int orderId,
|
||||
required String title,
|
||||
required String body,
|
||||
}) async {
|
||||
await ensureChannels();
|
||||
|
||||
const androidDetails = AndroidNotificationDetails(
|
||||
statusChannelId,
|
||||
'تحديثات طلبات التوصيل',
|
||||
importance: Importance.high,
|
||||
priority: Priority.high,
|
||||
color: Color(0xFFFF6B35),
|
||||
);
|
||||
const iosDetails = DarwinNotificationDetails(
|
||||
presentAlert: true,
|
||||
presentSound: true,
|
||||
);
|
||||
|
||||
await _plugin.show(
|
||||
id: statusNotificationId,
|
||||
title: title,
|
||||
body: body,
|
||||
notificationDetails:
|
||||
const NotificationDetails(android: androidDetails, iOS: iosDetails),
|
||||
payload: jsonEncode({'food_event': 'status', 'order_id': orderId}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
// food_socket_service.dart — قناة سوكيت مستقلة تماماً لوحدة التوصيل
|
||||
//
|
||||
// لماذا سوكيت منفصل ولا نركب على سوكيت الرحلات (LocationController.socket)؟
|
||||
// • خادمان منفصلان فعلاً: food_socket.php (4040) مقابل driver_socket (2020)،
|
||||
// وغرفة السائق هناك courier_food_{id} بمصادقة JWT مختلفة الاستعلام.
|
||||
// • عزل الأعطال: سقوط سوكيت الطعام لا يقطع توزيع الرحلات، وهو المسار الحرج.
|
||||
// • دورة حياة مختلفة: نتصل فقط أثناء «وضع التوصيل» وننفصل عند إطفائه،
|
||||
// بينما سوكيت الرحلات يبقى حياً طوال مناوبة السائق.
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:socket_io_client/socket_io_client.dart' as IO;
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.dart';
|
||||
|
||||
typedef FoodOfferHandler = void Function(Map<String, dynamic> payload);
|
||||
typedef FoodOrderUpdateHandler = void Function(Map<String, dynamic> payload);
|
||||
|
||||
class FoodSocketService {
|
||||
FoodSocketService._();
|
||||
static final FoodSocketService instance = FoodSocketService._();
|
||||
|
||||
IO.Socket? _socket;
|
||||
bool _isConnecting = false;
|
||||
Timer? _heartbeat;
|
||||
|
||||
FoodOfferHandler? onOffer;
|
||||
FoodOrderUpdateHandler? onOrderUpdate;
|
||||
FoodOrderUpdateHandler? onIncomingCall;
|
||||
void Function(bool connected)? onConnectionChanged;
|
||||
|
||||
bool get isConnected => _socket?.connected == true;
|
||||
|
||||
Future<void> connect() async {
|
||||
if (isConnected || _isConnecting) return;
|
||||
|
||||
final driverId = box.read(BoxName.driverID)?.toString() ?? '';
|
||||
final token = box.read(BoxName.tokenDriver)?.toString() ?? '';
|
||||
if (driverId.isEmpty || token.isEmpty) {
|
||||
Log.print('🍔 [FoodSocket] لا يوجد driverID/token — تخطّي الاتصال');
|
||||
return;
|
||||
}
|
||||
|
||||
_isConnecting = true;
|
||||
_disposeSocket();
|
||||
|
||||
try {
|
||||
_socket = IO.io(
|
||||
AppLink.foodSocketUrl,
|
||||
IO.OptionBuilder()
|
||||
.setTransports(['websocket'])
|
||||
// food_socket.php يتحقق: role=driver ويطابق user_id داخل الـ JWT مع id
|
||||
.setQuery({
|
||||
'role': 'driver',
|
||||
'id': driverId,
|
||||
'jwt': token,
|
||||
'platform': Platform.isIOS ? 'ios' : 'android',
|
||||
})
|
||||
.enableForceNew()
|
||||
.enableReconnection()
|
||||
.setReconnectionDelay(2000)
|
||||
.build(),
|
||||
);
|
||||
|
||||
_bindListeners();
|
||||
_socket!.connect();
|
||||
} catch (e) {
|
||||
_isConnecting = false;
|
||||
Log.print('❌ [FoodSocket] فشل التهيئة: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void _bindListeners() {
|
||||
final s = _socket;
|
||||
if (s == null) return;
|
||||
|
||||
s.onConnect((_) {
|
||||
_isConnecting = false;
|
||||
Log.print('✅ [FoodSocket] متصل — غرفة courier_food');
|
||||
onConnectionChanged?.call(true);
|
||||
_startHeartbeat();
|
||||
});
|
||||
|
||||
s.onDisconnect((_) {
|
||||
Log.print('⚠️ [FoodSocket] انقطع الاتصال');
|
||||
onConnectionChanged?.call(false);
|
||||
_stopHeartbeat();
|
||||
});
|
||||
|
||||
s.onConnectError((e) {
|
||||
_isConnecting = false;
|
||||
Log.print('❌ [FoodSocket] خطأ اتصال: $e');
|
||||
onConnectionChanged?.call(false);
|
||||
});
|
||||
|
||||
s.onError((e) => Log.print('❌ [FoodSocket] خطأ: $e'));
|
||||
|
||||
// عرض توصيل جديد — الحمولة كاملة من foodBuildCourierOfferPayload،
|
||||
// فشاشة العرض تُبنى فوراً بلا نداء HTTP إضافي (المهلة 20 ثانية فقط).
|
||||
s.on('food_delivery_offer', (data) {
|
||||
final map = _asMap(data);
|
||||
if (map == null) return;
|
||||
Log.print('🍔 [FoodSocket] عرض توصيل #${map['order_id']}');
|
||||
onOffer?.call(map);
|
||||
});
|
||||
|
||||
// مكالمة واردة من الزبون عبر القناة المقنّعة — لا رقم هاتف في الحمولة،
|
||||
// فقط session_id ينضم به الطرفان لخادم الإشارات.
|
||||
s.on('food_incoming_call', (data) {
|
||||
final map = _asMap(data);
|
||||
if (map == null) return;
|
||||
Log.print('🍔 [FoodSocket] مكالمة واردة على الطلب #${map['order_id']}');
|
||||
onIncomingCall?.call(map);
|
||||
});
|
||||
|
||||
// تحديث حالة طلب قائم (المطعم ألغى، النظام ألغى، إلخ)
|
||||
s.on('food_order_update', (data) {
|
||||
final map = _asMap(data);
|
||||
if (map == null) return;
|
||||
Log.print('🍔 [FoodSocket] تحديث طلب #${map['order_id']} → ${map['status']}');
|
||||
onOrderUpdate?.call(map);
|
||||
});
|
||||
}
|
||||
|
||||
// السوكيت ناقل إشعار لا مخزن حالة — أي حمولة غير مفهومة تُهمَل بصمت
|
||||
// ويصحّح التطبيق نفسه من courier/active.php.
|
||||
Map<String, dynamic>? _asMap(dynamic data) {
|
||||
try {
|
||||
if (data is Map) return Map<String, dynamic>.from(data);
|
||||
if (data is List && data.isNotEmpty && data.first is Map) {
|
||||
return Map<String, dynamic>.from(data.first as Map);
|
||||
}
|
||||
} catch (e) {
|
||||
Log.print('❌ [FoodSocket] حمولة غير صالحة: $e');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void _startHeartbeat() {
|
||||
_stopHeartbeat();
|
||||
_heartbeat = Timer.periodic(const Duration(seconds: 25), (_) {
|
||||
if (isConnected) _socket!.emit('heartbeat', {});
|
||||
});
|
||||
}
|
||||
|
||||
void _stopHeartbeat() {
|
||||
_heartbeat?.cancel();
|
||||
_heartbeat = null;
|
||||
}
|
||||
|
||||
void _disposeSocket() {
|
||||
if (_socket == null) return;
|
||||
_socket!.clearListeners();
|
||||
_socket!.dispose();
|
||||
_socket = null;
|
||||
}
|
||||
|
||||
void disconnect() {
|
||||
_stopHeartbeat();
|
||||
_isConnecting = false;
|
||||
_socket?.disconnect();
|
||||
_disposeSocket();
|
||||
onConnectionChanged?.call(false);
|
||||
Log.print('🍔 [FoodSocket] تم قطع الاتصال (وضع التوصيل مطفأ)');
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import '../../constant/links.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.dart';
|
||||
import '../../services/signaling_service.dart';
|
||||
import '../../services/turn_credentials_service.dart';
|
||||
import '../../views/widgets/voice_call_bottom_sheet.dart';
|
||||
import 'functions/crud.dart';
|
||||
|
||||
@@ -229,11 +230,16 @@ class VoiceCallController extends GetxController with WidgetsBindingObserver {
|
||||
|
||||
// EN: Initiates an outgoing call.
|
||||
// AR: يبدأ مكالمة صادرة.
|
||||
/// [sessionEndpoint] و [sessionPayload] يسمحان لوحدات أخرى (توصيل الطعام)
|
||||
/// بإعادة استخدام نفس قناة WebRTC المقنّعة بواجهة إنشاء جلسة خاصة بها،
|
||||
/// بدل تكرار منطق الإشارات والصوت. القيمة الافتراضية هي مكالمة الرحلة.
|
||||
Future<void> startCall({
|
||||
required String rideIdVal,
|
||||
required String driverId,
|
||||
required String passengerId,
|
||||
required String remoteNameVal,
|
||||
String? sessionEndpoint,
|
||||
Map<String, String>? sessionPayload,
|
||||
}) async {
|
||||
if (state.value != VoiceCallState.idle) return;
|
||||
|
||||
@@ -268,8 +274,9 @@ class VoiceCallController extends GetxController with WidgetsBindingObserver {
|
||||
// 2. EN: Call PHP Backend to create Node.js session & notify Passenger via FCM.
|
||||
// AR: استدعاء واجهة PHP لإنشاء الجلسة على Node.js وإشعار الراكب عبر FCM.
|
||||
final response = await CRUD().post(
|
||||
link: "${AppLink.server}/ride/call/driver/create_call_session.php",
|
||||
payload: {'ride_id': rideIdVal},
|
||||
link: sessionEndpoint ??
|
||||
"${AppLink.server}/ride/call/driver/create_call_session.php",
|
||||
payload: sessionPayload ?? {'ride_id': rideIdVal},
|
||||
);
|
||||
|
||||
if (response == null ||
|
||||
@@ -281,8 +288,16 @@ class VoiceCallController extends GetxController with WidgetsBindingObserver {
|
||||
return;
|
||||
}
|
||||
|
||||
final data = response['data'];
|
||||
sessionId.value = data['session_id'];
|
||||
// واجهات الرحلات تُعيد الجلسة في 'data'، وواجهات وحدة الطعام تُعيدها في
|
||||
// 'message' (غلاف jsonSuccess الموحّد) — نقبل الشكلين.
|
||||
final data = response['data'] ?? response['message'];
|
||||
if (data is! Map || data['session_id'] == null) {
|
||||
errorMessage.value =
|
||||
"Failed to initiate call session. Please try again.".tr;
|
||||
_endCallInternal("session_creation_failed");
|
||||
return;
|
||||
}
|
||||
sessionId.value = data['session_id'].toString();
|
||||
|
||||
// 3. EN: Connect to WebRTC signaling server / AR: الاتصال بخادم الإشارات
|
||||
await _signaling.connect(sessionId.value, currentUserId);
|
||||
@@ -492,8 +507,16 @@ class VoiceCallController extends GetxController with WidgetsBindingObserver {
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// EN: Fallback STUN servers / AR: خوام STUN الاحتياطية
|
||||
}
|
||||
|
||||
// خوادم TURN من الباك إند — بيانات اعتماد مؤقتة. بلا TURN تفشل المكالمة
|
||||
// صامتةً حين يكون الطرفان خلف CGNAT (شبكة الجوال)، وهي الحالة الغالبة.
|
||||
// نُضيفها قبل خوادم الإشارات: STUN يبقى أولاً في الترتيب داخل القائمة.
|
||||
final turnServers = await TurnCredentialsService.getIceServers();
|
||||
iceServers.addAll(turnServers);
|
||||
|
||||
if (iceServers.isEmpty) {
|
||||
// EN: Fallback STUN servers / AR: خوادم STUN الاحتياطية
|
||||
iceServers.addAll([
|
||||
{"urls": "stun:stun.l.google.com:19302"},
|
||||
{"urls": "stun:stun1.l.google.com:19302"},
|
||||
|
||||
Reference in New Issue
Block a user