Update: 2026-08-07 19:01:00

This commit is contained in:
Hamza-Ayed
2026-08-07 19:01:00 +03:00
parent cdd36d4777
commit 0db59647eb
31 changed files with 1974 additions and 2 deletions
+9
View File
@@ -681,4 +681,13 @@ class AppLink {
// ================= Scheduled Rides =================
static String get scheduledList => "$server/ride/scheduled/list.php";
// ================= Driver Insurance =================
// ملاحظة: addHealthInsuranceProvider/getHealthInsuranceProvider أعلاه هما
// المسار القديم على جدول driver_health_assurance. هذه هي نقاط الخطط
// والأقساط الجديدة، وتعمل على جداول insurance_* المنفصلة.
static String get insurancePlans => "$server/driver_assurance/plans.php";
static String get insuranceSubscribe =>
"$server/driver_assurance/subscribe.php";
static String get insuranceCancel => "$server/driver_assurance/cancel.php";
}
@@ -0,0 +1,156 @@
import 'dart:convert';
import 'package:get/get.dart';
import '../../constant/links.dart';
import '../../views/widgets/error_snakbar.dart';
import '../functions/crud.dart';
/// حالة تأمين السائق: الوثيقة النشطة، ودفتر الأقساط، والخطط المتاحة.
///
/// الخطط والحالة نداءان منفصلان في الخادم (plans.php و get.php)، لكنهما
/// شاشة واحدة عند السائق — فنجلبهما معاً ونعرض ما اكتمل. فشل أحدهما لا
/// يُفرغ الشاشة من الآخر.
class DriverInsuranceController extends GetxController {
final CRUD _crud = CRUD();
final isLoading = false.obs;
final isSubmitting = false.obs;
/// الوثيقة النشطة، أو null إن لم يكن مشتركاً.
final policy = Rxn<Map<String, dynamic>>();
/// ملخّص الدفتر: المستحق والمسدَّد.
final ledger = <String, dynamic>{}.obs;
/// آخر القيود — السائق الذي يُخصم من أرباحه يجب أن يرى مقابل ماذا.
final entries = <Map<String, dynamic>>[].obs;
/// كل الخطط، لا المؤهَّل لها فقط: إخفاء ما لا يستحقه بعد يجعل التأمين
/// مجهولاً عنده، وإظهاره مع «ينقصك كذا رحلة» يحوّله إلى هدف.
final plans = <Map<String, dynamic>>[].obs;
@override
void onInit() {
super.onInit();
refreshAll();
}
Future<void> refreshAll() async {
isLoading.value = true;
await Future.wait([_fetchStatus(), _fetchPlans()]);
isLoading.value = false;
}
Future<void> _fetchStatus() async {
try {
final data = _extract(await _crud.post(
link: AppLink.getHealthInsuranceProvider,
payload: const {},
));
if (data == null) return;
policy.value = data['policy'] is Map
? Map<String, dynamic>.from(data['policy'] as Map)
: null;
ledger.assignAll(data['ledger'] is Map
? Map<String, dynamic>.from(data['ledger'] as Map)
: <String, dynamic>{});
entries.assignAll(((data['entries'] as List?) ?? [])
.map((e) => Map<String, dynamic>.from(e as Map))
.toList());
} catch (_) {
mySnackbarError('Failed to load insurance status'.tr);
}
}
Future<void> _fetchPlans() async {
try {
final data = _extract(await _crud.post(
link: AppLink.insurancePlans,
payload: const {},
));
if (data == null) return;
plans.assignAll(((data['plans'] as List?) ?? [])
.map((e) => Map<String, dynamic>.from(e as Map))
.toList());
} catch (_) {
mySnackbarError('Failed to load insurance plans'.tr);
}
}
/// يشترك في خطة. الخادم يعيد فحص الأهلية بنفسه — الشاشة قد تكون
/// مفتوحة منذ ساعة، فما عرضناه ليس حجة.
Future<bool> subscribe(int planId) async {
if (isSubmitting.value) return false;
isSubmitting.value = true;
try {
final res = await _crud.post(
link: AppLink.insuranceSubscribe,
payload: {'plan_id': planId.toString()},
);
final decoded = res is String ? jsonDecode(res) : res;
if (decoded is Map && decoded['status'] == 'success') {
await refreshAll();
return true;
}
// رسالة الخادم تحمل سبب الرفض بالتفصيل (ما ينقص السائق تحديداً)،
// فنعرضها كما هي بدل رسالة عامة لا تدلّه على شيء.
mySnackbarError(_errorOf(decoded) ?? 'Subscription failed'.tr);
return false;
} catch (_) {
mySnackbarError('Subscription failed'.tr);
return false;
} finally {
isSubmitting.value = false;
}
}
Future<bool> cancel({String reason = ''}) async {
if (isSubmitting.value) return false;
isSubmitting.value = true;
try {
final res = await _crud.post(
link: AppLink.insuranceCancel,
payload: {'reason': reason},
);
final decoded = res is String ? jsonDecode(res) : res;
if (decoded is Map && decoded['status'] == 'success') {
await refreshAll();
return true;
}
mySnackbarError(_errorOf(decoded) ?? 'Cancellation failed'.tr);
return false;
} catch (_) {
mySnackbarError('Cancellation failed'.tr);
return false;
} finally {
isSubmitting.value = false;
}
}
bool get hasPolicy => policy.value != null;
double get pendingTotal =>
double.tryParse('${ledger['pending_total'] ?? 0}') ?? 0;
String get currency => '${ledger['currency'] ?? policy.value?['currency'] ?? ''}';
Map<String, dynamic>? _extract(dynamic res) {
final decoded = res is String ? jsonDecode(res) : res;
if (decoded is! Map || decoded['status'] != 'success') return null;
final data = decoded['message'] ?? decoded['data'];
return data is Map ? Map<String, dynamic>.from(data) : <String, dynamic>{};
}
String? _errorOf(dynamic decoded) {
if (decoded is! Map) return null;
final m = decoded['message'] ?? decoded['error'];
return m is String && m.isNotEmpty ? m : null;
}
}
+20 -1
View File
@@ -949,5 +949,24 @@
"Destination": "وجهة الوصول",
"Failed to fetch scheduled rides": "تعذّر جلب الرحلات المجدولة",
"Passenger offline — call them": "راكب بلا إنترنت — اتصل به",
"No internet — call": "بلا إنترنت — اتصل"
"No internet — call": "بلا إنترنت — اتصل",
"Insurance": "التأمين",
"Premium": "القسط",
"Monthly": "شهري",
"Daily": "يومي",
"Started on": "بدأت في",
"Policy number": "رقم الوثيقة",
"Premium ledger": "دفتر الأقساط",
"Outstanding": "المستحق",
"Settled": "المسدَّد",
"Cancel policy": "إلغاء الوثيقة",
"Subscribe": "اشترك",
"Not eligible yet": "غير مؤهَّل بعد",
"rides": "رحلة",
"No insurance plans available yet": "لا توجد خطط تأمين متاحة بعد",
"Failed to load insurance status": "تعذّر تحميل حالة التأمين",
"Failed to load insurance plans": "تعذّر تحميل خطط التأمين",
"Subscription failed": "تعذّر الاشتراك",
"Cancellation failed": "تعذّر الإلغاء",
"Cancelling stops future premiums. Outstanding dues remain payable.": "الإلغاء يوقف الأقساط القادمة، ويبقى المستحق السابق واجب السداد."
}
+20 -1
View File
@@ -907,5 +907,24 @@
"Destination": "Destination",
"Failed to fetch scheduled rides": "Failed to fetch scheduled rides",
"Passenger offline — call them": "Passenger offline — call them",
"No internet — call": "No internet — call"
"No internet — call": "No internet — call",
"Insurance": "Insurance",
"Premium": "Premium",
"Monthly": "Monthly",
"Daily": "Daily",
"Started on": "Started on",
"Policy number": "Policy number",
"Premium ledger": "Premium ledger",
"Outstanding": "Outstanding",
"Settled": "Settled",
"Cancel policy": "Cancel policy",
"Subscribe": "Subscribe",
"Not eligible yet": "Not eligible yet",
"rides": "rides",
"No insurance plans available yet": "No insurance plans available yet",
"Failed to load insurance status": "Failed to load insurance status",
"Failed to load insurance plans": "Failed to load insurance plans",
"Subscription failed": "Subscription failed",
"Cancellation failed": "Cancellation failed",
"Cancelling stops future premiums. Outstanding dues remain payable.": "Cancelling stops future premiums. Outstanding dues remain payable."
}
@@ -29,6 +29,7 @@ import '../../../../constant/colors.dart';
import '../About Us/video_page.dart';
import '../../../food_delivery/food_delivery_home_page.dart';
import '../../journal/driver_scheduled_rides_page.dart';
import '../../journal/driver_insurance_page.dart';
// 1. إنشاء Class لتعريف بيانات كل عنصر في القائمة
class DrawerItem {
@@ -87,6 +88,11 @@ class AppDrawer extends StatelessWidget {
icon: Icons.edit_calendar_rounded,
color: Colors.orangeAccent,
onTap: () => Get.to(() => const DriverScheduledRidesPage())),
DrawerItem(
title: 'Insurance'.tr,
icon: Icons.health_and_safety_rounded,
color: Colors.indigo,
onTap: () => Get.to(() => const DriverInsurancePage())),
DrawerItem(
title: 'Leaderboard'.tr,
icon: Icons.leaderboard_rounded,
@@ -0,0 +1,285 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../constant/colors.dart';
import '../../../controller/insurance/driver_insurance_controller.dart';
/// شاشة التأمين: الوثيقة النشطة ودفترها، أو الخطط المتاحة.
///
/// الحالتان لا تظهران معاً — من له وثيقة يرى وثيقته، ومن لا وثيقة له
/// يرى الخطط. عرض الاثنين كان سيوحي أن الاشتراك في ثانية ممكن، وهو
/// ليس كذلك: تبديل الخطة يمرّ بإلغاء صريح ليبقى في السجل أثر.
class DriverInsurancePage extends StatelessWidget {
const DriverInsurancePage({super.key});
@override
Widget build(BuildContext context) {
final c = Get.put(DriverInsuranceController());
return Scaffold(
appBar: AppBar(title: Text('Insurance'.tr), centerTitle: true),
body: Obx(() {
if (c.isLoading.value) {
return const Center(child: CircularProgressIndicator());
}
return RefreshIndicator(
onRefresh: c.refreshAll,
child: ListView(
padding: const EdgeInsets.all(16),
children: c.hasPolicy ? _policyView(context, c) : _plansView(context, c),
),
);
}),
);
}
// ── الوثيقة النشطة ─────────────────────────────────────────
List<Widget> _policyView(BuildContext context, DriverInsuranceController c) {
final p = c.policy.value!;
return [
Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.verified_user, color: Colors.green),
const SizedBox(width: 8),
Expanded(
child: Text(
'${p['plan'] ?? ''}',
style: const TextStyle(
fontSize: 18, fontWeight: FontWeight.bold),
),
),
],
),
const SizedBox(height: 4),
Text('${p['provider'] ?? ''}',
style: TextStyle(color: Colors.grey.shade600)),
const Divider(height: 24),
_row('Premium'.tr,
'${p['premium']} ${p['currency']} / '
'${p['billing_cycle'] == 'monthly' ? 'Monthly'.tr : 'Daily'.tr}'),
_row('Started on'.tr, '${p['started_at'] ?? '—'}'),
if ((p['policy_number'] ?? '').toString().isNotEmpty)
_row('Policy number'.tr, '${p['policy_number']}'),
if ((p['coverage'] ?? '').toString().isNotEmpty) ...[
const SizedBox(height: 12),
Text('${p['coverage']}',
style: TextStyle(color: Colors.grey.shade700)),
],
],
),
),
),
const SizedBox(height: 16),
// ── دفتر الأقساط ──
// يظهر في نفس الشاشة لا في أخرى: الخصم الذي لا يرى السائق مقابله
// مفاجأة تُفقد الثقة، مهما كان مشروحاً في مكان آخر.
Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Premium ledger'.tr,
style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.bold)),
const SizedBox(height: 12),
_row('Outstanding'.tr,
'${c.pendingTotal.toStringAsFixed(2)} ${c.currency}'),
_row('Settled'.tr,
'${ledgerNum(c.ledger['settled_total'])} ${c.currency}'),
if (c.entries.isNotEmpty) ...[
const Divider(height: 24),
...c.entries.take(10).map((e) => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('${e['charge_date']}',
style: TextStyle(color: Colors.grey.shade700)),
Text('${e['amount']} ${e['currency']}',
style: TextStyle(
color: e['status'] == 'settled'
? Colors.green
: Colors.orange.shade800,
fontWeight: FontWeight.w600,
)),
],
),
)),
],
],
),
),
),
const SizedBox(height: 24),
OutlinedButton.icon(
onPressed: c.isSubmitting.value ? null : () => _confirmCancel(context, c),
icon: const Icon(Icons.cancel_outlined, color: Colors.red),
label: Text('Cancel policy'.tr,
style: const TextStyle(color: Colors.red)),
style: OutlinedButton.styleFrom(
side: const BorderSide(color: Colors.red),
minimumSize: const Size.fromHeight(48),
),
),
];
}
// ── الخطط المتاحة ──────────────────────────────────────────
List<Widget> _plansView(BuildContext context, DriverInsuranceController c) {
if (c.plans.isEmpty) {
return [
const SizedBox(height: 80),
Icon(Icons.health_and_safety_outlined,
size: 80, color: Colors.grey.shade400),
const SizedBox(height: 16),
Text('No insurance plans available yet'.tr,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 18, color: Colors.grey)),
];
}
return c.plans.map((plan) {
final eligible = plan['eligible'] == true;
final missing = (plan['missing'] as List?) ?? [];
final progress = (plan['progress_rides'] ?? 0) as num;
final required = (plan['required_rides'] ?? 0) as num;
return Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
margin: const EdgeInsets.only(bottom: 16),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('${plan['name'] ?? ''}',
style: const TextStyle(
fontSize: 18, fontWeight: FontWeight.bold)),
Text('${plan['provider'] ?? ''}',
style: TextStyle(color: Colors.grey.shade600)),
const SizedBox(height: 8),
Text(
'${plan['premium']} ${plan['currency']} / '
'${plan['billing_cycle'] == 'monthly' ? 'Monthly'.tr : 'Daily'.tr}',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: AppColor.primaryColor),
),
if ((plan['coverage'] ?? '').toString().isNotEmpty) ...[
const SizedBox(height: 8),
Text('${plan['coverage']}',
style: TextStyle(color: Colors.grey.shade700)),
],
// شريط التقدّم نحو الشرط — الرقم وحده لا يحرّك أحداً،
// ورؤية القرب من الهدف تفعل.
if (!eligible && required > 0) ...[
const SizedBox(height: 12),
LinearProgressIndicator(
value: required == 0 ? 0 : (progress / required).clamp(0, 1),
backgroundColor: Colors.grey.shade300,
),
const SizedBox(height: 6),
Text('$progress / $required ${'rides'.tr}',
style: TextStyle(
fontSize: 12, color: Colors.grey.shade600)),
],
if (!eligible && missing.isNotEmpty) ...[
const SizedBox(height: 8),
...missing.map((m) => Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.lock_outline,
size: 14, color: Colors.orange),
const SizedBox(width: 6),
Expanded(
child: Text('$m',
style: TextStyle(
fontSize: 12,
color: Colors.orange.shade900)),
),
],
)),
],
const SizedBox(height: 12),
ElevatedButton(
onPressed: (!eligible || c.isSubmitting.value)
? null
: () => c.subscribe(plan['id'] as int),
style: ElevatedButton.styleFrom(
backgroundColor: AppColor.primaryColor,
foregroundColor: Colors.white,
minimumSize: const Size.fromHeight(44),
),
child: Text(eligible ? 'Subscribe'.tr : 'Not eligible yet'.tr),
),
],
),
),
);
}).toList();
}
void _confirmCancel(BuildContext context, DriverInsuranceController c) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('Cancel policy'.tr),
// نصرّح بأن المستحق السابق يبقى: الإلغاء يوقف القادم ولا يمحو
// أياماً استُفيد من تغطيتها فعلاً.
content: Text(c.pendingTotal > 0
? '${'Cancelling stops future premiums. Outstanding dues remain payable.'.tr}\n\n'
'${'Outstanding'.tr}: ${c.pendingTotal.toStringAsFixed(2)} ${c.currency}'
: 'Cancelling stops future premiums. Outstanding dues remain payable.'.tr),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: Text('Back'.tr),
),
TextButton(
onPressed: () {
Navigator.pop(ctx);
c.cancel();
},
child: Text('Confirm'.tr,
style: const TextStyle(color: Colors.red)),
),
],
),
);
}
static String ledgerNum(dynamic v) =>
(double.tryParse('${v ?? 0}') ?? 0).toStringAsFixed(2);
Widget _row(String label, String value) => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label, style: TextStyle(color: Colors.grey.shade700)),
Flexible(
child: Text(value,
textAlign: TextAlign.end,
style: const TextStyle(fontWeight: FontWeight.w600)),
),
],
),
);
}