Update: 2026-08-08 12:58:16

This commit is contained in:
Hamza-Ayed
2026-08-08 12:58:17 +03:00
parent 611b5e616d
commit fae0e4a38a
55 changed files with 5771 additions and 1820 deletions
@@ -299,7 +299,7 @@ class HomeCaptainController extends GetxController {
void goToWalletFromConnect() {
Get.back();
Get.back();
Get.to(() => WalletCaptainRefactored());
Get.to(() => const WalletCaptainRefactored());
}
void changeRideId() {
@@ -0,0 +1,176 @@
// earnings_controller.dart — مصدر واحد لأرقام شاشة الأرباح
//
// ‏كانت الأرقام تُبنى من أربعة نداءات مستقلة، فيصل كلٌّ منها في لحظة
// ‏مختلفة وتظهر أرقام لا تتفق. هنا نداء واحد بختم زمني واحد.
//
// ‏والأهم: **الفشل لا يُترجم أصفاراً**. الكود السابق كان عند فشل الشبكة
// ‏يولّد سبعة أيام بأصفار ويعرضها كأنها أرباح السائق — وهو يرى دخله وقد
// ‏تبخّر. الحالتان هنا منفصلتان: `hasError` غير «كسبتَ صفراً».
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:siro_driver/constant/links.dart';
import 'package:siro_driver/controller/functions/crud.dart';
import 'package:siro_driver/main.dart';
import 'earnings_models.dart';
class EarningsController extends GetxController {
EarningsSummary? summary;
List<TripEarning> trips = [];
bool isLoading = false;
bool isLoadingTrips = false;
/// ‏سبب الفشل كنصّ للسائق، أو null. وجوده يعني «لا نعرف أرباحك الآن»
/// ‏لا «أرباحك صفر» — والفرق بينهما هو الفرق بين عطلٍ يُحتمل وثقةٍ تُفقد.
String? errorMessage;
/// ‏هل المعروض من الذاكرة المؤقتة؟ الشاشة تُظهر ذلك صراحةً مع وقت
/// ‏القياس، فلا يقرأ السائق رقماً عمره ساعات على أنه لحظته.
bool isStale = false;
DateTime? lastFetch;
/// ‏اليوم المختار لقائمة الرحلات (null = آخر سبعة أيام).
String? selectedDay;
static const _cacheKey = 'earnings_summary_cache';
static const _cacheAtKey = 'earnings_summary_cached_at';
/// ‏دقيقتان لا ثلاث ساعات. الكاش الطويل السابق كان سبب تناقض شاشة
/// ‏الأرباح مع شاشة الرصيد؛ ومدة قصيرة تكفي لمنع النداءات المتكررة
/// ‏عند التنقّل بين الشاشات بلا أن تُقدّم للسائق ماضياً على أنه حاضر.
static const _freshFor = Duration(minutes: 2);
@override
void onInit() {
super.onInit();
_loadFromCache();
load();
}
void _loadFromCache() {
try {
final raw = box.read(_cacheKey);
if (raw == null) return;
summary = EarningsSummary.fromJson(
Map<String, dynamic>.from(jsonDecode(raw)));
final at = box.read(_cacheAtKey);
if (at != null) lastFetch = DateTime.tryParse(at.toString());
isStale = true;
update();
} catch (e) {
debugPrint('[Earnings] تعذّرت قراءة الكاش: $e');
}
}
Future<void> load({bool force = false}) async {
if (!force && lastFetch != null && !isStale) {
if (DateTime.now().difference(lastFetch!) < _freshFor) return;
}
isLoading = summary == null; // ‏دوّار فقط حين لا يوجد ما يُعرض
errorMessage = null;
update();
final res = await CRUD().get(link: AppLink.getEarningsSummary);
// ‏الرسائل مفصّلة بحسب سبب الفشل: «تحقق من اتصالك» تُصلح بفعل،
// ‏و«حدث خطأ» تترك السائق بلا حيلة.
if (res == 'no_internet') {
_fail('تعذّر الوصول للخادم — تحقّق من اتصالك');
return;
}
if (res == 'token_expired') {
_fail('انتهت الجلسة، حاول مجدداً');
return;
}
if (res == 'failure' || res == null) {
_fail('تعذّر تحميل أرباحك الآن');
return;
}
try {
final data = jsonDecode(res);
if (data['status'] != 'success' || data['message'] is! Map) {
_fail('تعذّر تحميل أرباحك الآن');
return;
}
summary = EarningsSummary.fromJson(
Map<String, dynamic>.from(data['message']));
box.write(_cacheKey, jsonEncode(data['message']));
box.write(_cacheAtKey, DateTime.now().toIso8601String());
lastFetch = DateTime.now();
isStale = false;
errorMessage = null;
} catch (e) {
debugPrint('[Earnings] تعذّر تحليل الرد: $e');
_fail('تعذّر تحميل أرباحك الآن');
return;
} finally {
isLoading = false;
update();
}
await loadTrips();
}
/// ‏الفشل يُبقي آخر بيانات معروفة معروضة ومعلَّمة كقديمة، ولا يستبدلها
/// ‏بأصفار. رقم قديم صادق أنفع من رقم حاضر كاذب.
void _fail(String message) {
errorMessage = message;
isLoading = false;
if (summary != null) isStale = true;
update();
}
Future<void> loadTrips({String? day}) async {
selectedDay = day;
isLoadingTrips = true;
update();
final res = await CRUD().get(
link: AppLink.getEarningsTrips,
payload: {
if (day != null) 'date': day,
if (day == null) 'range': 'week',
},
);
try {
if (res is String && res != 'failure' && res != 'no_internet' && res != 'token_expired') {
final data = jsonDecode(res);
if (data['status'] == 'success' && data['message'] is Map) {
final list = data['message']['trips'];
trips = (list is List)
? list
.map((t) => TripEarning.fromJson(Map<String, dynamic>.from(t)))
.toList()
: <TripEarning>[];
}
}
} catch (e) {
debugPrint('[Earnings] تعذّر تحليل الرحلات: $e');
}
isLoadingTrips = false;
update();
}
/// ‏نصّ «آخر تحديث» بصيغة يفهمها السائق بلا حساب.
String get lastUpdatedLabel {
if (lastFetch == null) return '';
final diff = DateTime.now().difference(lastFetch!);
if (diff.inMinutes < 1) return 'الآن';
if (diff.inMinutes < 60) return 'قبل ${diff.inMinutes} دقيقة';
if (diff.inHours < 24) return 'قبل ${diff.inHours} ساعة';
return 'قبل ${diff.inDays} يوم';
}
}
@@ -0,0 +1,226 @@
// earnings_models.dart — نماذج شاشة الأرباح
//
// ‏كل الأرقام تصل من نقطة واحدة (`ride/earnings/summary.php`) بختم زمني
// ‏واحد، فلا مجال لأن يتناقض رقمان في الشاشة نفسها.
class PeriodEarnings {
final int trips;
/// ‏صافي السائق — حصته المثبَّتة لحظة عرض السعر، أي ما وُعد به قبل القبول.
final double net;
/// ‏إجمالي ما دفعه الركاب.
final double gross;
/// ‏عمولة المنصة. تُعرض صراحةً لا تُطرح بصمت: السائق الذي يرى تركيبة
/// ‏المبلغ يفهم، والذي يرى الصافي وحده يخمّن ويشكّ.
final double commission;
final double distance;
final int minutes;
PeriodEarnings({
required this.trips,
required this.net,
required this.gross,
required this.commission,
required this.distance,
required this.minutes,
});
double get hours => minutes / 60.0;
factory PeriodEarnings.fromJson(Map<String, dynamic> j) => PeriodEarnings(
trips: int.tryParse(j['trips']?.toString() ?? '0') ?? 0,
net: double.tryParse(j['net']?.toString() ?? '0') ?? 0,
gross: double.tryParse(j['gross']?.toString() ?? '0') ?? 0,
commission: double.tryParse(j['commission']?.toString() ?? '0') ?? 0,
distance: double.tryParse(j['distance']?.toString() ?? '0') ?? 0,
minutes: int.tryParse(j['minutes']?.toString() ?? '0') ?? 0,
);
static PeriodEarnings empty() => PeriodEarnings(
trips: 0, net: 0, gross: 0, commission: 0, distance: 0, minutes: 0);
}
class DayEarnings {
final String day;
final int trips;
final double net;
final int minutes;
DayEarnings(
{required this.day,
required this.trips,
required this.net,
required this.minutes});
factory DayEarnings.fromJson(Map<String, dynamic> j) => DayEarnings(
day: j['day']?.toString() ?? '',
trips: int.tryParse(j['trips']?.toString() ?? '0') ?? 0,
net: double.tryParse(j['net']?.toString() ?? '0') ?? 0,
minutes: int.tryParse(j['minutes']?.toString() ?? '0') ?? 0,
);
}
class DeductionItem {
final String product;
final String name;
final double outstanding;
DeductionItem(
{required this.product, required this.name, required this.outstanding});
factory DeductionItem.fromJson(Map<String, dynamic> j) => DeductionItem(
product: j['product']?.toString() ?? '',
name: j['name']?.toString() ?? '',
outstanding: double.tryParse(j['outstanding']?.toString() ?? '0') ?? 0,
);
}
/// ‏الاقتطاعات (تأمين، وقود) تُعرض بجانب الأرباح التي اقتُطعت منها.
/// ‏اقتطاعٌ لا يظهر في مكانه يُقرأ سرقةً مهما كان مشروعاً.
class Deductions {
final double today;
final double week;
final double month;
final double outstanding;
final List<DeductionItem> items;
Deductions({
required this.today,
required this.week,
required this.month,
required this.outstanding,
required this.items,
});
bool get hasAny => today > 0 || outstanding > 0;
factory Deductions.fromJson(Map<String, dynamic> j) => Deductions(
today: double.tryParse(j['today']?.toString() ?? '0') ?? 0,
week: double.tryParse(j['week']?.toString() ?? '0') ?? 0,
month: double.tryParse(j['month']?.toString() ?? '0') ?? 0,
outstanding: double.tryParse(j['outstanding']?.toString() ?? '0') ?? 0,
items: (j['items'] is List)
? (j['items'] as List)
.map((i) => DeductionItem.fromJson(Map<String, dynamic>.from(i)))
.toList()
: <DeductionItem>[],
);
}
class EarningsSummary {
final PeriodEarnings today;
final PeriodEarnings week;
final PeriodEarnings month;
final PeriodEarnings prevWeek;
/// ‏نسبة التغيّر عن الأسبوع الماضي، أو null إن لم يكن هناك ما يُقارَن به.
/// ‏المقارنة بالذات لا بالسائقين الآخرين: ترتيبٌ يُحبط أكثر من يحتاج
/// ‏التحفيز — فهو من سيقع في أسفله.
final double? trendPercent;
final List<DayEarnings> daily;
final DayEarnings? bestDay;
final Deductions deductions;
final String asOf;
EarningsSummary({
required this.today,
required this.week,
required this.month,
required this.prevWeek,
required this.daily,
required this.deductions,
required this.asOf,
this.trendPercent,
this.bestDay,
});
factory EarningsSummary.fromJson(Map<String, dynamic> j) => EarningsSummary(
today: PeriodEarnings.fromJson(Map<String, dynamic>.from(j['today'] ?? {})),
week: PeriodEarnings.fromJson(Map<String, dynamic>.from(j['week'] ?? {})),
month: PeriodEarnings.fromJson(Map<String, dynamic>.from(j['month'] ?? {})),
prevWeek:
PeriodEarnings.fromJson(Map<String, dynamic>.from(j['prev_week'] ?? {})),
trendPercent: j['trend_percent'] == null
? null
: double.tryParse(j['trend_percent'].toString()),
daily: (j['daily'] is List)
? (j['daily'] as List)
.map((d) => DayEarnings.fromJson(Map<String, dynamic>.from(d)))
.toList()
: <DayEarnings>[],
bestDay: j['best_day'] is Map
? DayEarnings.fromJson(Map<String, dynamic>.from(j['best_day']))
: null,
deductions:
Deductions.fromJson(Map<String, dynamic>.from(j['deductions'] ?? {})),
asOf: j['as_of']?.toString() ?? '',
);
}
class TripBreakdown {
final double gross;
final double commission;
final double bonus;
final double net;
/// ‏إعفاء العمولة (سلسلة ٠٪) — هدية تدفع المنصة ثمنها ولم تكن تظهر
/// ‏للسائق في أي شاشة. نميّزها لتُعرض مكسباً لا سطراً فارغاً.
final bool zeroCommission;
TripBreakdown({
required this.gross,
required this.commission,
required this.bonus,
required this.net,
required this.zeroCommission,
});
factory TripBreakdown.fromJson(Map<String, dynamic> j) => TripBreakdown(
gross: double.tryParse(j['gross']?.toString() ?? '0') ?? 0,
commission: double.tryParse(j['commission']?.toString() ?? '0') ?? 0,
bonus: double.tryParse(j['bonus']?.toString() ?? '0') ?? 0,
net: double.tryParse(j['net']?.toString() ?? '0') ?? 0,
zeroCommission: j['zero_commission'] == true,
);
}
class TripEarning {
final int rideId;
final String at;
final String from;
final String to;
final String carType;
final String paymentMethod;
final double distanceKm;
final int minutes;
final TripBreakdown breakdown;
TripEarning({
required this.rideId,
required this.at,
required this.from,
required this.to,
required this.carType,
required this.paymentMethod,
required this.distanceKm,
required this.minutes,
required this.breakdown,
});
factory TripEarning.fromJson(Map<String, dynamic> j) => TripEarning(
rideId: int.tryParse(j['ride_id']?.toString() ?? '0') ?? 0,
at: j['at']?.toString() ?? '',
from: j['from']?.toString() ?? '',
to: j['to']?.toString() ?? '',
carType: j['car_type']?.toString() ?? '',
paymentMethod: j['payment_method']?.toString() ?? '',
distanceKm: double.tryParse(j['distance_km']?.toString() ?? '0') ?? 0,
minutes: int.tryParse(j['minutes']?.toString() ?? '0') ?? 0,
breakdown:
TripBreakdown.fromJson(Map<String, dynamic>.from(j['breakdown'] ?? {})),
);
}
@@ -1,293 +0,0 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:siro_driver/constant/box_name.dart';
import 'package:siro_driver/constant/links.dart';
import 'package:siro_driver/controller/functions/crud.dart';
import 'package:siro_driver/models/model/driver/rides_summary_model.dart';
import '../../../main.dart';
class StatisticsController extends GetxController {
bool isLoading = false;
// ═══ Weekly Data ═══
List<DayStat> weeklyStats = [];
double weeklyEarnings = 0;
int weeklyTrips = 0;
double weeklyHours = 0;
// ═══ Monthly Data ═══
List<MonthlyPriceDriverModel> monthlyEarnings = [];
List<MonthlyRideModel> monthlyRides = [];
List<MonthlyDataModel> monthlyDuration = [];
double monthlyTotalEarnings = 0;
int monthlyTotalTrips = 0;
double monthlyTotalHours = 0;
String bestDay = '--';
double bestDayEarnings = 0;
// ═══ Tab State ═══
int selectedTab = 0; // 0=weekly, 1=monthly
@override
void onInit() {
super.onInit();
reloadData();
}
void changeTab(int tab) {
selectedTab = tab;
update();
}
// ═══════ جلب البيانات الأسبوعية ═══════
Future<void> fetchWeeklyData() async {
isLoading = true;
update();
try {
var res = await CRUD().get(
link: AppLink.getWeeklyAggregate,
payload: {
'driver_id': box.read(BoxName.driverID).toString(),
},
);
if (res != null && res != 'failure') {
box.write('stats_weekly_cache', res);
var data = jsonDecode(res);
if (data['message'] is List) {
weeklyStats = (data['message'] as List)
.map((e) => DayStat.fromJson(e))
.toList();
weeklyEarnings = weeklyStats.fold(0, (s, d) => s + d.earnings);
weeklyTrips = weeklyStats.fold(0, (s, d) => s + d.trips);
weeklyHours = weeklyStats.fold(0, (s, d) => s + d.hours);
}
}
} catch (e) {
debugPrint('❌ [Stats] Weekly fetch error: $e');
// Fallback: generate from local data
_generateLocalWeeklyData();
}
isLoading = false;
update();
}
// ═══════ جلب البيانات الشهرية ═══════
Future<void> fetchMonthlyData() async {
try {
// 1. أرباح شهرية
var earningsRes = await CRUD().getWallet(
link: AppLink.getAllPaymentFromRide,
payload: {'driverID': box.read(BoxName.driverID).toString()},
);
if (earningsRes != null && earningsRes != 'failure') {
box.write('stats_monthly_earnings_cache', earningsRes);
var data = jsonDecode(earningsRes);
if (data['message'] is List) {
monthlyEarnings = (data['message'] as List)
.map((e) => MonthlyPriceDriverModel.fromJson(e))
.toList();
monthlyTotalEarnings =
monthlyEarnings.fold(0, (s, d) => s + d.pricePerDay);
// أفضل يوم
if (monthlyEarnings.isNotEmpty) {
var best = monthlyEarnings
.reduce((a, b) => a.pricePerDay > b.pricePerDay ? a : b);
bestDay = best.day.toString();
bestDayEarnings = best.pricePerDay;
}
}
}
// 2. رحلات شهرية
var ridesRes = await CRUD().get(
link: AppLink.getRidesDriverByDay,
payload: {'driver_id': box.read(BoxName.driverID).toString()},
);
if (ridesRes != null && ridesRes != 'failure') {
box.write('stats_monthly_rides_cache', ridesRes);
var data = jsonDecode(ridesRes);
if (data['message'] is List) {
monthlyRides = (data['message'] as List)
.map((e) => MonthlyRideModel.fromJson(e))
.toList();
monthlyTotalTrips = monthlyRides.fold(0, (s, d) => s + d.countRide);
}
}
// 3. ساعات شهرية
var durationRes = await CRUD().get(
link: AppLink.getTotalDriverDuration,
payload: {'driver_id': box.read(BoxName.driverID).toString()},
);
if (durationRes != null && durationRes != 'failure') {
box.write('stats_monthly_duration_cache', durationRes);
var data = jsonDecode(durationRes);
if (data['message'] is List) {
monthlyDuration = (data['message'] as List)
.map((e) => MonthlyDataModel.fromJson(e))
.toList();
monthlyTotalHours =
monthlyDuration.fold(0, (s, d) => s + d.totalDuration.toDouble());
}
}
} catch (e) {
debugPrint('❌ [Stats] Monthly fetch error: $e');
}
update();
}
void _generateLocalWeeklyData() {
// Fallback بيانات محلية عند عدم توفر الـ API
final now = DateTime.now();
weeklyStats = List.generate(7, (i) {
final day = now.subtract(Duration(days: 6 - i));
return DayStat(
date: day,
dayName: _getDayName(day.weekday),
earnings: 0,
trips: 0,
hours: 0,
);
});
}
String _getDayName(int weekday) {
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
return days[weekday - 1];
}
bool _isFetching = false;
Future<void> reloadData({bool force = false}) async {
if (_isFetching) return;
_isFetching = true;
// التحقق من التخزين المؤقت (3 ساعات)
String? lastFetchStr = box.read('stats_last_fetch');
if (!force && lastFetchStr != null) {
try {
DateTime lastFetch = DateTime.parse(lastFetchStr);
if (DateTime.now().difference(lastFetch).inHours < 3) {
debugPrint('ℹ️ [Statistics] Loading cached statistics (last fetch: $lastFetchStr)');
// تحميل الكاش الأسبوعي
String? weeklyCache = box.read('stats_weekly_cache');
if (weeklyCache != null) {
var data = jsonDecode(weeklyCache);
if (data['message'] is List) {
weeklyStats = (data['message'] as List)
.map((e) => DayStat.fromJson(e))
.toList();
weeklyEarnings = weeklyStats.fold(0, (s, d) => s + d.earnings);
weeklyTrips = weeklyStats.fold(0, (s, d) => s + d.trips);
weeklyHours = weeklyStats.fold(0, (s, d) => s + d.hours);
}
}
// تحميل الكاش الشهري (الأرباح)
String? earningsCache = box.read('stats_monthly_earnings_cache');
if (earningsCache != null) {
var data = jsonDecode(earningsCache);
if (data['message'] is List) {
monthlyEarnings = (data['message'] as List)
.map((e) => MonthlyPriceDriverModel.fromJson(e))
.toList();
monthlyTotalEarnings =
monthlyEarnings.fold(0, (s, d) => s + d.pricePerDay);
if (monthlyEarnings.isNotEmpty) {
var best = monthlyEarnings
.reduce((a, b) => a.pricePerDay > b.pricePerDay ? a : b);
bestDay = best.day.toString();
bestDayEarnings = best.pricePerDay;
}
}
}
// تحميل الكاش الشهري (الرحلات)
String? ridesCache = box.read('stats_monthly_rides_cache');
if (ridesCache != null) {
var data = jsonDecode(ridesCache);
if (data['message'] is List) {
monthlyRides = (data['message'] as List)
.map((e) => MonthlyRideModel.fromJson(e))
.toList();
monthlyTotalTrips = monthlyRides.fold(0, (s, d) => s + d.countRide);
}
}
// تحميل الكاش الشهري (المدد)
String? durationCache = box.read('stats_monthly_duration_cache');
if (durationCache != null) {
var data = jsonDecode(durationCache);
if (data['message'] is List) {
monthlyDuration = (data['message'] as List)
.map((e) => MonthlyDataModel.fromJson(e))
.toList();
monthlyTotalHours =
monthlyDuration.fold(0, (s, d) => s + d.totalDuration.toDouble());
}
}
_isFetching = false;
update();
return;
}
} catch (e) {
debugPrint('⚠️ [Statistics] Failed to load cached statistics: $e');
}
}
isLoading = true;
update();
try {
debugPrint('📊 [Statistics] Reloading data from server...');
await fetchWeeklyData();
await fetchMonthlyData();
box.write('stats_last_fetch', DateTime.now().toIso8601String());
debugPrint('📊 [Statistics] Data reload complete.');
} catch (e) {
debugPrint('❌ [Statistics] Error reloading data: $e');
} finally {
_isFetching = false;
isLoading = false;
update();
}
}
}
// ═══════ نموذج إحصائية اليوم ═══════
class DayStat {
final DateTime date;
final String dayName;
final double earnings;
final int trips;
final double hours;
DayStat({
required this.date,
required this.dayName,
required this.earnings,
required this.trips,
required this.hours,
});
factory DayStat.fromJson(Map<String, dynamic> json) {
final date =
DateTime.tryParse(json['day']?.toString() ?? '') ?? DateTime.now();
const dayNames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
return DayStat(
date: date,
dayName: dayNames[date.weekday - 1],
earnings: double.tryParse(json['earnings']?.toString() ?? '0') ?? 0,
trips: int.tryParse(json['trips']?.toString() ?? '0') ?? 0,
hours: double.tryParse(json['hours']?.toString() ?? '0') ?? 0,
);
}
}