2026-03-10-1

This commit is contained in:
Hamza-Ayed
2026-03-10 00:02:17 +03:00
parent c000d22ca3
commit cdda136006
28 changed files with 9912 additions and 3592 deletions

View File

@@ -21,6 +21,6 @@
<key>CFBundleVersion</key>
<string>1.0</string>
<key>MinimumOSVersion</key>
<string>12.0</string>
<string>13.0</string>
</dict>
</plist>

View File

@@ -163,10 +163,10 @@ PODS:
- PromisesObjC (2.4.0)
- PromisesSwift (2.4.0):
- PromisesObjC (= 2.4.0)
- SDWebImage (5.21.1):
- SDWebImage/Core (= 5.21.1)
- SDWebImage/Core (5.21.1)
- SDWebImageWebPCoder (0.14.6):
- SDWebImage (5.21.6):
- SDWebImage/Core (= 5.21.6)
- SDWebImage/Core (5.21.6)
- SDWebImageWebPCoder (0.15.0):
- libwebp (~> 1.0)
- SDWebImage/Core (~> 5.17)
- sqflite_darwin (0.0.4):
@@ -289,8 +289,8 @@ SPEC CHECKSUMS:
path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564
PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47
PromisesSwift: 9d77319bbe72ebf6d872900551f7eeba9bce2851
SDWebImage: f29024626962457f3470184232766516dee8dfea
SDWebImageWebPCoder: e38c0a70396191361d60c092933e22c20d5b1380
SDWebImage: 1bb6a1b84b6fe87b972a102bdc77dd589df33477
SDWebImageWebPCoder: 0e06e365080397465cc73a7a9b472d8a3bd0f377
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
TOCropViewController: 80b8985ad794298fb69d3341de183f33d1853654
url_launcher_ios: 694010445543906933d732453a59da0a173ae33d

View File

@@ -497,7 +497,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
@@ -628,7 +628,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
@@ -679,7 +679,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;

View File

@@ -1,7 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<dict>
<key>NSLocalNetworkUsageDescription</key>
<string>نحتاج إلى الوصول إلى الشبكة المحلية لاكتشاف الأجهزة القريبة.</string>
<key>NSBonjourServices</key>
<array>
<string>_http._tcp</string>
<string>_https._tcp</string>
</array>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
@@ -23,7 +31,7 @@
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<true />
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
@@ -42,8 +50,8 @@
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<true />
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
</dict>
<true />
</dict>
</plist>

View File

@@ -11,14 +11,27 @@ class AppLink {
// static final String endPoint = box.read(BoxName.serverChosen);
// static final String server = Env.seferCairoServer;
static final String server = 'https://api.intaleq.xyz/intaleq';
static final String server = 'https://api.intaleq.xyz/intaleq_v1';
static String loginJwtDriver =
"https://api.intaleq.xyz/intaleq/loginAdmin.php";
//=============================
//=============================
static final getAllFingerprints =
'$server/migration/get_all_fingerprints.php';
static final updateFingerprintAdmin =
'$server/migration/update_fingerprint_admin.php';
static final getAllDriverFingerprints =
'$server/migration/get_all_driver_fingerprints.php';
static final updateDriverFingerprintAdmin =
'$server/migration/update_driver_fingerprint_admin.php';
//=============================
//=============================
static String googleMapsLink = 'https://maps.googleapis.com/maps/api/';
static String llama = 'https://api.llama-api.com/chat/completions';
static String gemini =
'https://generativelanguage.googleapis.com/v1beta3/models/text-bison-001:generateText';
static String serverMonitor = "https://tripz-egypt.com/server/monitor.php";
static String test = "$server/test.php";
static String loginWalletAdmin = "$seferPaymentServer/loginWalletAdmin.php";

View File

@@ -53,7 +53,7 @@ class CaptainAdminController extends GetxController {
update();
var res = await CRUD().post(
link: AppLink.find_driver_by_phone,
payload: {'phone': phone},
payload: {'phone': "963$phone"},
);
var d = (res);
if (d != 'failure') {

View File

@@ -54,14 +54,14 @@ class DashboardController extends GetxController {
}
// 🔹 Check SMS credit
var res2 = await CRUD().kazumiSMS(
link: 'https://sms.kazumi.me/api/sms/check-credit',
payload: {"username": "Sefer", "password": AK.smsPasswordEgypt},
);
// var res2 = await CRUD().kazumiSMS(
// link: 'https://sms.kazumi.me/api/sms/check-credit',
// payload: {"username": "Sefer", "password": AK.smsPasswordEgypt},
// );
creditSMS = res2['credit'];
print('📱 SMS Credit Response: ${jsonEncode(res2)}');
print('💰 creditSMS: $creditSMS');
// creditSMS = res2['credit'];
// print('📱 SMS Credit Response: ${jsonEncode(res2)}');
// print('💰 creditSMS: $creditSMS');
isLoading = false;
update();

View File

@@ -1,5 +1,6 @@
import 'dart:convert';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
@@ -7,8 +8,72 @@ import '../../constant/links.dart';
import '../../print.dart';
import '../functions/crud.dart';
// ══════════════════════════════════════════════════════════════
// MODEL: Represents one employee's full data for a period
// ══════════════════════════════════════════════════════════════
class EmployeeChartData {
final String name;
final Color color;
final List<FlSpot> notesSpots;
final List<FlSpot> callsSpots;
const EmployeeChartData({
required this.name,
required this.color,
required this.notesSpots,
required this.callsSpots,
});
int get totalNotes => notesSpots.fold(0, (sum, s) => sum + s.y.toInt());
int get totalCalls => callsSpots.fold(0, (sum, s) => sum + s.y.toInt());
EmployeeChartData copyWith({
List<FlSpot>? notesSpots,
List<FlSpot>? callsSpots,
}) {
return EmployeeChartData(
name: name,
color: color,
notesSpots: notesSpots ?? this.notesSpots,
callsSpots: callsSpots ?? this.callsSpots,
);
}
}
// ══════════════════════════════════════════════════════════════
// MODEL: Employment activation stats per employee
// ══════════════════════════════════════════════════════════════
class EmploymentStat {
final String name;
final int count;
final Color color;
const EmploymentStat({
required this.name,
required this.count,
required this.color,
});
}
// ══════════════════════════════════════════════════════════════
// CONTROLLER
// ══════════════════════════════════════════════════════════════
class StaticController extends GetxController {
// --- Date & State Management ---
// ─── Color Palette for Dynamic Employees ───────────────────
static const List<Color> _employeeColors = [
Color(0xFF00D4AA), // teal
Color(0xFF82AAFF), // blue
Color(0xFFFFCB6B), // amber
Color(0xFFC792EA), // purple
Color(0xFFFF5370), // red
Color(0xFFC3E88D), // green
Color(0xFFF07178), // coral
Color(0xFF89DDFF), // cyan
];
Color _colorForIndex(int i) => _employeeColors[i % _employeeColors.length];
// ─── Date & State ───────────────────────────────────────────
DateTime? startDate = DateTime(DateTime.now().year, DateTime.now().month, 1);
DateTime? endDate =
DateTime(DateTime.now().year, DateTime.now().month + 1, 0);
@@ -19,56 +84,53 @@ class StaticController extends GetxController {
bool isComparing = false;
bool isLoading = false;
// --- Daily Notes State ---
// ─── Daily Notes State ─────────────────────────────────────
bool isLoadingNotes = false;
List<dynamic> dailyNotesList = [];
// --- Chart Data (Current Range) ---
// ─── Main Chart Data ───────────────────────────────────────
List<FlSpot> chartDataPassengers = [];
List<FlSpot> chartDataDrivers = [];
List<FlSpot> chartDataRides = [];
List<FlSpot> chartDataDriversMatchingNotes = [];
// Employee Data (Notes/General Stats)
List<FlSpot> chartDataEmployeerama1 = [];
List<FlSpot> chartDataEmployeeshahd = [];
List<FlSpot> chartDataEmployeeRama2 = [];
List<FlSpot> chartDataEmployeeSefer4 = [];
// Employee Data (Calls/Activations Stats)
List<FlSpot> chartDataCallsrama1 = [];
List<FlSpot> chartDataCallsShahd = [];
List<FlSpot> chartDataCallsRama2 = [];
List<FlSpot> chartDataCallsSefer4 = [];
// --- Chart Data (Comparison Range) ---
List<FlSpot> chartDataPassengersCompare = [];
List<FlSpot> chartDataDriversCompare = [];
List<FlSpot> chartDataRidesCompare = [];
List<FlSpot> chartDataDriversMatchingNotesCompare = [];
// Employee Comparison (Notes)
List<FlSpot> chartDataEmployeerama1Compare = [];
List<FlSpot> chartDataEmployeeshahdCompare = [];
List<FlSpot> chartDataEmployeeRama2Compare = [];
List<FlSpot> chartDataEmployeeSefer4Compare = [];
// ─── 🔥 DYNAMIC Employee Data ─────────────────────────────
// Key = employee name (from server), Value = their chart data
Map<String, EmployeeChartData> employeeData = {};
Map<String, EmployeeChartData> employeeDataCompare = {};
// Employee Comparison (Calls/Activations)
List<FlSpot> chartDataCallsrama1Compare = [];
List<FlSpot> chartDataCallsShahdCompare = [];
List<FlSpot> chartDataCallsRama2Compare = [];
List<FlSpot> chartDataCallsSefer4Compare = [];
// Set of all known employee names (union of current + compare)
Set<String> get allEmployeeNames => {
...employeeData.keys,
...employeeDataCompare.keys,
};
// --- Totals ---
// ─── Employment Stats ──────────────────────────────────────
List<EmploymentStat> employmentStatsList = [];
// ─── Totals ────────────────────────────────────────────────
String totalMonthlyPassengers = '0';
String totalMonthlyRides = '0';
String totalMonthlyDrivers = '0';
// --- Raw Lists ---
// ─── Raw Lists ─────────────────────────────────────────────
List staticList = [];
// --- Employment Type Stats List (Simple Count) ---
List<Map<String, dynamic>> employmentStatsList = [];
// ─── Color Registry (stable across rebuilds) ───────────────
final Map<String, Color> _employeeColorRegistry = {};
Color _getOrAssignColor(String name) {
if (!_employeeColorRegistry.containsKey(name)) {
_employeeColorRegistry[name] =
_colorForIndex(_employeeColorRegistry.length);
}
return _employeeColorRegistry[name]!;
}
@override
void onInit() {
@@ -76,7 +138,7 @@ class StaticController extends GetxController {
getAll();
}
// --- Helpers for View ---
// ─── Helpers ───────────────────────────────────────────────
double get daysInPeriod {
if (startDate == null || endDate == null) return 31;
return endDate!.difference(startDate!).inDays + 1.0;
@@ -84,10 +146,17 @@ class StaticController extends GetxController {
String get currentDateString {
if (startDate == null || endDate == null) return "";
return "${DateFormat('yyyy-MM-dd').format(startDate!)} : ${DateFormat('yyyy-MM-dd').format(endDate!)}";
return "${DateFormat('yyyy-MM-dd').format(startDate!)} : "
"${DateFormat('yyyy-MM-dd').format(endDate!)}";
}
// --- Date Actions ---
String get compareDateString {
if (compareStartDate == null || compareEndDate == null) return "";
return "${DateFormat('yyyy-MM-dd').format(compareStartDate!)} : "
"${DateFormat('yyyy-MM-dd').format(compareEndDate!)}";
}
// ─── Date Actions ──────────────────────────────────────────
void updateDateRange(DateTime start, DateTime end) {
startDate = start;
endDate = end;
@@ -120,29 +189,18 @@ class StaticController extends GetxController {
chartDataDriversCompare.clear();
chartDataRidesCompare.clear();
chartDataDriversMatchingNotesCompare.clear();
chartDataEmployeerama1Compare.clear();
chartDataEmployeeshahdCompare.clear();
chartDataEmployeeRama2Compare.clear();
chartDataEmployeeSefer4Compare.clear();
chartDataCallsrama1Compare.clear();
chartDataCallsShahdCompare.clear();
chartDataCallsRama2Compare.clear();
chartDataCallsSefer4Compare.clear();
employeeDataCompare.clear();
}
Map<String, dynamic> _getPayload(DateTime start, DateTime end) {
return {
Map<String, dynamic> _getPayload(DateTime start, DateTime end) => {
"start_date": DateFormat('yyyy-MM-dd').format(start),
"end_date": DateFormat('yyyy-MM-dd').format(end),
"month": start.month.toString(),
"year": start.year.toString(),
};
}
// --- Main Fetch Logic ---
Future getAll() async {
// ─── Main Fetch ────────────────────────────────────────────
Future<void> getAll() async {
if (startDate == null || endDate == null) return;
isLoading = true;
@@ -152,8 +210,8 @@ class StaticController extends GetxController {
fetchPassengers(isCompare: false),
fetchRides(isCompare: false),
fetchDrivers(isCompare: false),
fetchEmployee(isCompare: false),
fetchEditorCalls(isCompare: false),
fetchEmployeeDynamic(isCompare: false),
fetchEditorCallsDynamic(isCompare: false),
fetchEmploymentStats(),
]);
@@ -162,8 +220,8 @@ class StaticController extends GetxController {
fetchPassengers(isCompare: true),
fetchRides(isCompare: true),
fetchDrivers(isCompare: true),
fetchEmployee(isCompare: true),
fetchEditorCalls(isCompare: true),
fetchEmployeeDynamic(isCompare: true),
fetchEditorCallsDynamic(isCompare: true),
]);
}
@@ -171,90 +229,124 @@ class StaticController extends GetxController {
update();
}
// ... (Existing Functions _generateSpots, fetchPassengers, etc.) ...
List<FlSpot> _generateSpots(List<dynamic> data, String dateKey,
String valueKey, DateTime startOfRange) {
List<FlSpot> spots = [];
Map<String, double> dataMap = {};
for (var item in data) {
String dateStr = item[dateKey].toString();
double val = double.tryParse(item[valueKey].toString()) ?? 0.0;
dataMap[dateStr] = val;
}
DateTime rangeEnd =
(startOfRange == startDate) ? endDate! : compareEndDate!;
int totalDays = rangeEnd.difference(startOfRange).inDays + 1;
for (int i = 0; i < totalDays; i++) {
DateTime currentDate = startOfRange.add(Duration(days: i));
String dateKeyStr = DateFormat('yyyy-MM-dd').format(currentDate);
double value = dataMap[dateKeyStr] ?? 0.0;
spots.add(FlSpot((i + 1).toDouble(), value));
}
return spots;
// ─── Spot Generator ───────────────────────────────────────
List<FlSpot> _generateSpots(
List<dynamic> data,
String dateKey,
String valueKey,
DateTime startOfRange,
DateTime endOfRange,
) {
Map<String, double> dataMap = {
for (var item in data)
item[dateKey].toString():
double.tryParse(item[valueKey].toString()) ?? 0.0
};
int totalDays = endOfRange.difference(startOfRange).inDays + 1;
return List.generate(totalDays, (i) {
final date = startOfRange.add(Duration(days: i));
final key = DateFormat('yyyy-MM-dd').format(date);
return FlSpot((i + 1).toDouble(), dataMap[key] ?? 0.0);
});
}
Future<void> fetchPassengers({bool isCompare = false}) async {
DateTime start = isCompare ? compareStartDate! : startDate!;
DateTime end = isCompare ? compareEndDate! : endDate!;
var res = await CRUD().get(
link: AppLink.getPassengersStatic, payload: _getPayload(start, end));
var jsonResponse = jsonDecode(res);
if (jsonResponse['status'] == 'failure') return;
final List<dynamic> jsonData = jsonResponse['message'];
if (!isCompare &&
jsonData.isNotEmpty &&
jsonData[0]['totalMonthly'] != null) {
totalMonthlyPassengers = jsonData[0]['totalMonthly'].toString();
/// Generates spots map keyed by employee name from a date→name→value structure
Map<String, List<FlSpot>> _generateEmployeeSpots(
Map<String, Map<String, double>> dateNameMap,
DateTime start,
DateTime end,
) {
// Discover all employee names dynamically
final Set<String> names = {};
for (var dayData in dateNameMap.values) {
names.addAll(dayData.keys);
}
List<FlSpot> spots =
_generateSpots(jsonData, 'day', 'totalPassengers', start);
int totalDays = end.difference(start).inDays + 1;
final Map<String, List<FlSpot>> result = {};
for (final name in names) {
result[name] = List.generate(totalDays, (i) {
final date = start.add(Duration(days: i));
final dateStr = DateFormat('yyyy-MM-dd').format(date);
final value = dateNameMap[dateStr]?[name] ?? 0.0;
return FlSpot((i + 1).toDouble(), value);
});
}
return result;
}
/// Parses a list of {date/day, NAME, count} records into a dateNameMap
Map<String, Map<String, double>> _parseDateNameMap(List<dynamic> jsonData) {
final Map<String, Map<String, double>> result = {};
for (var item in jsonData) {
final dateStr = (item['date'] ?? item['day']).toString();
final name = item['NAME'].toString().toLowerCase().trim();
final count = double.tryParse(item['count'].toString()) ?? 0.0;
result.putIfAbsent(dateStr, () => {})[name] =
(result[dateStr]?[name] ?? 0) + count;
}
return result;
}
// ─── Passengers ───────────────────────────────────────────
Future<void> fetchPassengers({bool isCompare = false}) async {
final start = isCompare ? compareStartDate! : startDate!;
final end = isCompare ? compareEndDate! : endDate!;
final res = await CRUD().get(
link: AppLink.getPassengersStatic, payload: _getPayload(start, end));
final json = jsonDecode(res);
if (json['status'] == 'failure') return;
final List<dynamic> data = json['message'];
if (!isCompare && data.isNotEmpty && data[0]['totalMonthly'] != null) {
totalMonthlyPassengers = data[0]['totalMonthly'].toString();
}
final spots = _generateSpots(data, 'day', 'totalPassengers', start, end);
if (isCompare)
chartDataPassengersCompare = spots;
else
chartDataPassengers = spots;
}
// ─── Rides ────────────────────────────────────────────────
Future<void> fetchRides({bool isCompare = false}) async {
DateTime start = isCompare ? compareStartDate! : startDate!;
DateTime end = isCompare ? compareEndDate! : endDate!;
var res = await CRUD()
final start = isCompare ? compareStartDate! : startDate!;
final end = isCompare ? compareEndDate! : endDate!;
final res = await CRUD()
.get(link: AppLink.getRidesStatic, payload: _getPayload(start, end));
var jsonResponse = jsonDecode(res);
if (jsonResponse['status'] == 'failure') return;
final List<dynamic> jsonData = jsonResponse['message'];
if (!isCompare &&
jsonData.isNotEmpty &&
jsonData[0]['totalMonthly'] != null) {
totalMonthlyRides = jsonData[0]['totalMonthly'].toString();
final json = jsonDecode(res);
if (json['status'] == 'failure') return;
final List<dynamic> data = json['message'];
if (!isCompare && data.isNotEmpty && data[0]['totalMonthly'] != null) {
totalMonthlyRides = data[0]['totalMonthly'].toString();
}
List<FlSpot> spots = _generateSpots(jsonData, 'day', 'totalRides', start);
final spots = _generateSpots(data, 'day', 'totalRides', start, end);
if (isCompare)
chartDataRidesCompare = spots;
else
chartDataRides = spots;
}
// ─── Drivers ──────────────────────────────────────────────
Future<void> fetchDrivers({bool isCompare = false}) async {
DateTime start = isCompare ? compareStartDate! : startDate!;
DateTime end = isCompare ? compareEndDate! : endDate!;
var res = await CRUD().get(
final start = isCompare ? compareStartDate! : startDate!;
final end = isCompare ? compareEndDate! : endDate!;
final res = await CRUD().get(
link: AppLink.getdriverstotalMonthly, payload: _getPayload(start, end));
var jsonResponse = jsonDecode(res);
if (jsonResponse['status'] == 'failure') return;
final List<dynamic> jsonData = jsonResponse['message'];
final json = jsonDecode(res);
if (json['status'] == 'failure') return;
final List<dynamic> data = json['message'];
if (!isCompare &&
jsonData.isNotEmpty &&
jsonData[0]['totalMonthlyDrivers'] != null) {
totalMonthlyDrivers = jsonData[0]['totalMonthlyDrivers'].toString();
data.isNotEmpty &&
data[0]['totalMonthlyDrivers'] != null) {
totalMonthlyDrivers = data[0]['totalMonthlyDrivers'].toString();
staticList = data;
}
if (!isCompare) {
staticList = jsonData;
}
List<FlSpot> spotsDrivers =
_generateSpots(jsonData, 'day', 'dailyTotalDrivers', start);
List<FlSpot> spotsNotes =
_generateSpots(jsonData, 'day', 'dailyMatchingNotes', start);
final spotsDrivers =
_generateSpots(data, 'day', 'dailyTotalDrivers', start, end);
final spotsNotes =
_generateSpots(data, 'day', 'dailyMatchingNotes', start, end);
if (isCompare) {
chartDataDriversCompare = spotsDrivers;
chartDataDriversMatchingNotesCompare = spotsNotes;
@@ -264,237 +356,126 @@ class StaticController extends GetxController {
}
}
Future<void> fetchEmployee({bool isCompare = false}) async {
// ─── 🔥 DYNAMIC: Employee Notes ───────────────────────────
Future<void> fetchEmployeeDynamic({bool isCompare = false}) async {
try {
DateTime start = isCompare ? compareStartDate! : startDate!;
DateTime end = isCompare ? compareEndDate! : endDate!;
var res = await CRUD().get(
final start = isCompare ? compareStartDate! : startDate!;
final end = isCompare ? compareEndDate! : endDate!;
final res = await CRUD().get(
link: AppLink.getEmployeeStatic, payload: _getPayload(start, end));
if (isCompare) {
chartDataEmployeerama1Compare = [];
chartDataEmployeeshahdCompare = [];
chartDataEmployeeRama2Compare = [];
chartDataEmployeeSefer4Compare = [];
} else {
chartDataEmployeerama1 = [];
chartDataEmployeeshahd = [];
chartDataEmployeeRama2 = [];
chartDataEmployeeSefer4 = [];
}
if (res == 'failure') return;
var jsonResponse = jsonDecode(res) as Map<String, dynamic>;
if (jsonResponse['status'] == 'failure') return;
final List<dynamic> jsonData = jsonResponse['message'];
if (jsonData.isEmpty) return;
final json = jsonDecode(res) as Map<String, dynamic>;
if (json['status'] == 'failure') return;
final List<dynamic> data = json['message'];
if (data.isEmpty) return;
Map<String, Map<String, double>> dateNameMap = {};
for (var item in jsonData) {
String dateKeyStr = item['date'] ?? item['day'];
String name = item['NAME'].toString().toLowerCase().trim();
double count = double.tryParse(item['count'].toString()) ?? 0.0;
if (!dateNameMap.containsKey(dateKeyStr)) dateNameMap[dateKeyStr] = {};
if (dateNameMap[dateKeyStr]!.containsKey(name)) {
dateNameMap[dateKeyStr]![name] =
dateNameMap[dateKeyStr]![name]! + count;
final dateNameMap = _parseDateNameMap(data);
final spotsMap = _generateEmployeeSpots(dateNameMap, start, end);
// Merge into employee data map
final target = isCompare ? employeeDataCompare : employeeData;
spotsMap.forEach((name, spots) {
final color = _getOrAssignColor(name);
if (target.containsKey(name)) {
target[name] = target[name]!.copyWith(notesSpots: spots);
} else {
dateNameMap[dateKeyStr]![name] = count;
}
}
final targetLists = isCompare
? {
'rama1': chartDataEmployeerama1Compare,
'shahd': chartDataEmployeeshahdCompare,
'rama2': chartDataEmployeeRama2Compare,
'mayar': chartDataEmployeeSefer4Compare
}
: {
'rama1': chartDataEmployeerama1,
'shahd': chartDataEmployeeshahd,
'rama2': chartDataEmployeeRama2,
'mayar': chartDataEmployeeSefer4
};
int totalDays = end.difference(start).inDays + 1;
targetLists.forEach((key, listToFill) {
for (int i = 0; i < totalDays; i++) {
DateTime currentDate = start.add(Duration(days: i));
String currentDateStr = DateFormat('yyyy-MM-dd').format(currentDate);
double value = 0;
Map<String, double>? dayData = dateNameMap[currentDateStr];
if (dayData != null) {
// if (key == 'mayar') {
// value = (dayData['mayar'] ?? 0) +
// (dayData['rama1'] ?? 0) +
// (dayData['sefer4'] ?? 0);
// } else {
value = dayData[key] ?? 0;
// }
}
listToFill.add(FlSpot((i + 1).toDouble(), value));
target[name] = EmployeeChartData(
name: name,
color: color,
notesSpots: spots,
callsSpots: [],
);
}
});
} catch (e) {
Log.print('Error in fetchEmployee: $e');
Log.print('Error in fetchEmployeeDynamic: $e');
}
}
Future<void> fetchEditorCalls({bool isCompare = false}) async {
// ─── 🔥 DYNAMIC: Employee Calls ───────────────────────────
Future<void> fetchEditorCallsDynamic({bool isCompare = false}) async {
try {
DateTime start = isCompare ? compareStartDate! : startDate!;
DateTime end = isCompare ? compareEndDate! : endDate!;
var res = await CRUD().get(
final start = isCompare ? compareStartDate! : startDate!;
final end = isCompare ? compareEndDate! : endDate!;
final res = await CRUD().get(
link: AppLink.getEditorStatsCalls, payload: _getPayload(start, end));
if (isCompare) {
chartDataCallsrama1Compare = [];
chartDataCallsShahdCompare = [];
chartDataCallsRama2Compare = [];
chartDataCallsSefer4Compare = [];
} else {
chartDataCallsrama1 = [];
chartDataCallsShahd = [];
chartDataCallsRama2 = [];
chartDataCallsSefer4 = [];
}
if (res == 'failure') return;
final json = jsonDecode(res) as Map<String, dynamic>;
if (json['status'] == 'failure') return;
final List<dynamic> data = json['message'];
if (data.isEmpty) return;
var jsonResponse = jsonDecode(res) as Map<String, dynamic>;
if (jsonResponse['status'] == 'failure') return;
final dateNameMap = _parseDateNameMap(data);
final spotsMap = _generateEmployeeSpots(dateNameMap, start, end);
final List<dynamic> jsonData = jsonResponse['message'];
if (jsonData.isEmpty) return;
final target = isCompare ? employeeDataCompare : employeeData;
Map<String, Map<String, double>> dateNameMap = {};
for (var item in jsonData) {
String dateKeyStr = item['date'] ?? item['day'];
String name = item['NAME'].toString().toLowerCase().trim();
double count = double.tryParse(item['count'].toString()) ?? 0.0;
if (!dateNameMap.containsKey(dateKeyStr)) {
dateNameMap[dateKeyStr] = {};
}
if (dateNameMap[dateKeyStr]!.containsKey(name)) {
dateNameMap[dateKeyStr]![name] =
dateNameMap[dateKeyStr]![name]! + count;
spotsMap.forEach((name, spots) {
final color = _getOrAssignColor(name);
if (target.containsKey(name)) {
target[name] = target[name]!.copyWith(callsSpots: spots);
} else {
dateNameMap[dateKeyStr]![name] = count;
}
}
final targetLists = isCompare
? {
'rama1': chartDataCallsrama1Compare,
'shahd': chartDataCallsShahdCompare,
'rama2': chartDataCallsRama2Compare,
'mayar': chartDataCallsSefer4Compare,
}
: {
'rama1': chartDataCallsrama1,
'shahd': chartDataCallsShahd,
'rama2': chartDataCallsRama2,
'mayar': chartDataCallsSefer4,
};
int totalDays = end.difference(start).inDays + 1;
targetLists.forEach((key, listToFill) {
for (int i = 0; i < totalDays; i++) {
DateTime currentDate = start.add(Duration(days: i));
String currentDateStr = DateFormat('yyyy-MM-dd').format(currentDate);
double value = 0;
Map<String, double>? dayData = dateNameMap[currentDateStr];
if (dayData != null) {
// if (key == 'mayar_group') {
// value = (dayData['mayar'] ?? 0) +
// (dayData['rama1'] ?? 0) +
// (dayData['sefer4'] ?? 0);
// } else {
value = dayData[key] ?? 0;
// }
}
listToFill.add(FlSpot((i + 1).toDouble(), value));
target[name] = EmployeeChartData(
name: name,
color: color,
notesSpots: [],
callsSpots: spots,
);
}
});
} catch (e) {
Log.print('Error in fetchEditorCalls: $e');
Log.print('Error in fetchEditorCallsDynamic: $e');
}
}
// --- 🔴 FIXED: Fetch Employment Stats with Unique Check ---
// ─── Employment Stats ─────────────────────────────────────
Future<void> fetchEmploymentStats() async {
try {
// لا نستخدم .clear() هنا، سنقوم باستبدال القائمة بالكامل في النهاية
var res = await CRUD().get(
final res = await CRUD().get(
link: AppLink.getEmployeeDriverAfterCallingRegister,
payload: _getPayload(startDate!, endDate!));
if (res == 'failure') return;
final json = jsonDecode(res);
if (json['status'] != 'success') return;
final List<dynamic> data = json['message']?['data'] ?? [];
var jsonResponse = jsonDecode(res);
if (jsonResponse['status'] == 'success') {
if (jsonResponse['message'] != null &&
jsonResponse['message']['data'] != null) {
List<dynamic> data = jsonResponse['message']['data'];
List<String> allowedNames = ['shahd', 'mayar', 'rama1', 'rama2'];
// استخدام Map لضمان عدم تكرار الأسماء (تجميع القيم)
Map<String, int> uniqueMap = {};
// Aggregate by name (dynamic — no hardcoded allowed list)
final Map<String, int> aggregated = {};
for (var item in data) {
String name =
item['employmentType'].toString().toLowerCase().trim();
int count = int.tryParse(item['count'].toString()) ?? 0;
if (allowedNames.contains(name)) {
if (uniqueMap.containsKey(name)) {
uniqueMap[name] = uniqueMap[name]! + count;
} else {
uniqueMap[name] = count;
}
}
final name = item['employmentType'].toString().toLowerCase().trim();
final count = int.tryParse(item['count'].toString()) ?? 0;
aggregated[name] = (aggregated[name] ?? 0) + count;
}
// تحويل الـ Map إلى القائمة النهائية
List<Map<String, dynamic>> tempList = [];
uniqueMap.forEach((key, value) {
tempList.add({'name': key, 'count': value});
});
// استبدال القائمة القديمة بالقائمة الجديدة النظيفة
employmentStatsList = tempList;
}
}
employmentStatsList = aggregated.entries.map((e) {
return EmploymentStat(
name: e.key,
count: e.value,
color: _getOrAssignColor(e.key),
);
}).toList()
..sort((a, b) => b.count.compareTo(a.count)); // sort descending
} catch (e) {
Log.print("Error fetchEmploymentStats: $e");
}
}
// --- Fetch Daily Notes Log ---
// ─── Daily Notes ──────────────────────────────────────────
Future<void> fetchDailyNotes(DateTime date) async {
try {
isLoadingNotes = true;
dailyNotesList.clear();
update();
var res = await CRUD().post(
final res = await CRUD().post(
link: AppLink.getNotesForEmployee,
payload: {"date": DateFormat('yyyy-MM-dd').format(date)});
if (res != 'failure') {
var jsonResponse = (res);
if (jsonResponse['status'] == 'success') {
dailyNotesList = jsonResponse['message'];
final json = res;
if (json['status'] == 'success') {
dailyNotesList = json['message'];
}
}
} catch (e) {
@@ -504,4 +485,28 @@ class StaticController extends GetxController {
update();
}
}
// ─── Computed Summaries for UI ────────────────────────────
/// Returns sorted list of employees by total notes descending
List<EmployeeChartData> get employeesSortedByNotes {
final list = employeeData.values.toList();
list.sort((a, b) => b.totalNotes.compareTo(a.totalNotes));
return list;
}
/// Returns sorted list of employees by total calls descending
List<EmployeeChartData> get employeesSortedByCalls {
final list = employeeData.values.toList();
list.sort((a, b) => b.totalCalls.compareTo(a.totalCalls));
return list;
}
/// Grand total notes across all employees
int get grandTotalNotes =>
employeeData.values.fold(0, (s, e) => s + e.totalNotes);
/// Grand total calls across all employees
int get grandTotalCalls =>
employeeData.values.fold(0, (s, e) => s + e.totalCalls);
}

View File

@@ -56,19 +56,19 @@ class WalletController extends GetxController {
});
}
Future addDrivergift3000(String paymentMethod, driverID, point, phone) async {
Future addDrivergift300(String paymentMethod, driverID, point, phone) async {
// paymentToken = await generateToken(count);
// var paymentID = await getPaymentId(paymentMethod, point.toString());
var res = await CRUD().postWallet(link: AppLink.add300ToDriver, payload: {
'driverID': driverID.toString(),
'paymentID': paymentMethod,
'amount': point,
'token': 'gift_connect_30000',
'token': 'gift_connect_300',
'paymentMethod': paymentMethod,
'phone': phone,
});
if (res != 'failure') {
Get.snackbar('success', 'addDrivergift3000',
Get.snackbar('success', 'addDrivergift300',
backgroundColor: AppColor.greenColor);
} else {
Get.snackbar('error', res, backgroundColor: AppColor.redColor);

View File

@@ -1,234 +1,237 @@
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_admin1/constant/box_name.dart';
import 'package:sefer_admin1/constant/links.dart';
import 'package:sefer_admin1/controller/firebase/firbase_messge.dart';
import 'package:sefer_admin1/controller/functions/crud.dart';
import 'package:sefer_admin1/main.dart';
import 'package:sefer_admin1/views/widgets/elevated_btn.dart';
import 'package:sefer_admin1/views/widgets/my_textField.dart';
import '../constant/style.dart';
import '../print.dart';
import 'firebase/notification_service.dart';
class NotificationController extends GetxController {
final formKey = GlobalKey<FormState>();
final title = TextEditingController();
final body = TextEditingController();
List<String> tokensDriver = [];
List<String> tokensPassengers = [];
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
final TextEditingController titleController = TextEditingController();
final TextEditingController bodyController = TextEditingController();
// getTokensDrivers() async {
// await FirebaseMessagesController().loadAllPagesAndSendNotifications();
// }
// ألوان الثيم (متناسقة مع باقي الصفحات المحسنة)
final Color _dialogColor = const Color(0xFF1A1F3A);
final Color _inputColor = const Color(0xFF0A0E27);
final Color _primaryAccent = const Color(0xFF6366F1);
// getTokensPassengers() async {
// await FirebaseMessagesController()
// .loadAllPagesAndSendNotificationsPassengers();
// }
Future<dynamic> sendNotificationDrivers() {
return Get.defaultDialog(
title: 'send notification'.tr,
titleStyle: AppStyle.title,
content: Form(
key: formKey,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: MyTextForm(
controller: title,
label: 'title notification'.tr,
hint: 'title notification'.tr,
type: TextInputType.name),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: MyTextForm(
controller: body,
label: 'body notification'.tr,
hint: 'body notification'.tr,
type: TextInputType.name),
),
],
),
),
confirm: MyElevatedButton(
title: 'send'.tr,
onPressed: () async {
// tokensDriver = box.read(BoxName.tokensDrivers)['message'];
// Log.print('tokensDriver: ${tokensDriver}');
// if (formKey.currentState!.validate()) {
// box.read(BoxName.tokensDrivers)['message'].length;
// for (var i = 0;
// i < box.read(BoxName.tokensDrivers)['message'].length;
// i++) {
// // for (var i = 0; i < 2; i++) {
// // print(i);
// var res = await CRUD()
// .post(link: AppLink.addNotificationCaptain, payload: {
// "driverID": box
// .read(BoxName.tokensDrivers)['message'][i]['id']
// .toString(),
// "title": title.text,
// "body": body.text,
// "isPin": 'unPin',
// });
// Log.print(
// 'res: ${res}for ${box.read(BoxName.tokensDrivers)['message'][i]['id']}');
// // Log.print('tokensDriver[i]: ${tokensDriver[i]}');
// Future.delayed(const Duration(microseconds: 50));
NotificationService.sendNotification(
target: 'drivers', // الإرسال لجميع المشتركين في "service"
title: title.text,
body: body.text,
isTopic: true,
category: 'fromAdmin', // فئة توضح نوع الإشعار
);
// FirebaseMessagesController().sendNotificationToAnyWithoutData(
// title.text,
// body.text,
// box
// .read(BoxName.tokensDrivers)['message'][i]['token']
// .toString(),
// 'tone2.wav');
// }
Get.back();
// }
}),
cancel: MyElevatedButton(
title: 'cancel',
onPressed: () {
Get.back();
}));
@override
void onClose() {
titleController.dispose();
bodyController.dispose();
super.onClose();
}
Future<dynamic> sendNotificationPassengers() {
return Get.defaultDialog(
title: 'send notification'.tr,
titleStyle: AppStyle.title,
content: Form(
/// تنظيف الحقول
void _clearFields() {
titleController.clear();
bodyController.clear();
}
/// إرسال إشعار للسائقين
Future<void> sendNotificationDrivers() async {
_clearFields();
await _showCustomDialog(
dialogTitle: 'إشعار للسائقين',
targetAudience: 'drivers',
icon: Icons.drive_eta_rounded,
iconColor: Colors.orangeAccent,
);
}
/// إرسال إشعار للركاب
Future<void> sendNotificationPassengers() async {
_clearFields();
await _showCustomDialog(
dialogTitle: 'إشعار للركاب',
targetAudience: 'passengers',
icon: Icons.people_alt_rounded,
iconColor: Colors.blueAccent,
);
}
/// دالة عامة لإظهار نافذة الإرسال بتصميم عصري
Future<void> _showCustomDialog({
required String dialogTitle,
required String targetAudience,
required IconData icon,
required Color iconColor,
}) {
return Get.dialog(
Dialog(
backgroundColor: _dialogColor,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
elevation: 10,
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(24),
child: Form(
key: formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: MyTextForm(
controller: title,
label: 'title notification'.tr,
hint: 'title notification'.tr,
type: TextInputType.name),
// 1. أيقونة العنوان
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: iconColor.withOpacity(0.15),
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: iconColor.withOpacity(0.1),
blurRadius: 10,
offset: const Offset(0, 4),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: MyTextForm(
controller: body,
label: 'body notification'.tr,
hint: 'body notification'.tr,
type: TextInputType.name),
],
),
child: Icon(icon, color: iconColor, size: 32),
),
const SizedBox(height: 16),
// 2. العنوان
Text(
dialogTitle,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
fontFamily: 'Segoe UI',
),
),
const SizedBox(height: 24),
// 3. حقول الإدخال
_buildModernTextField(
controller: titleController,
hint: 'عنوان الإشعار',
icon: Icons.title_rounded,
),
const SizedBox(height: 16),
_buildModernTextField(
controller: bodyController,
hint: 'نص الرسالة',
icon: Icons.message_rounded,
maxLines: 3,
),
const SizedBox(height: 32),
// 4. الأزرار
Row(
children: [
Expanded(
child: TextButton(
onPressed: () => Get.back(),
style: TextButton.styleFrom(
foregroundColor: Colors.white54,
padding: const EdgeInsets.symmetric(vertical: 12),
),
child: const Text('إلغاء'),
),
),
const SizedBox(width: 12),
Expanded(
child: ElevatedButton(
onPressed: () async {
if (titleController.text.trim().isEmpty ||
bodyController.text.trim().isEmpty) {
Get.snackbar(
"تنبيه",
"الرجاء تعبئة جميع الحقول",
backgroundColor: Colors.amber.withOpacity(0.8),
colorText: Colors.white,
snackPosition: SnackPosition.TOP,
);
return;
}
Get.back(); // إغلاق النافذة
await _processSending(targetAudience);
},
style: ElevatedButton.styleFrom(
backgroundColor: _primaryAccent,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
elevation: 0,
),
child: const Text('إرسال'),
),
),
],
),
],
),
),
confirm: MyElevatedButton(
title: 'send'.tr,
onPressed: () async {
// tokensPassengers = box.read(BoxName.tokensPassengers);
// var tokensPassengersData =
// box.read(BoxName.tokensPassengers)['data'];
// // Debug print to check structure of the 'data' field
// print('Tokens Passengers Data: $tokensPassengersData');
// if (tokensPassengersData is List) {
// for (var i = 0; i < tokensPassengersData.length; i++) {
// if (formKey.currentState!.validate()) {
// var res = await CRUD()
// .post(link: AppLink.addNotificationPassenger, payload: {
// "passenger_id":
// tokensPassengersData[i]['passengerID'].toString(),
// "title": title.text,
// "body": body.text,
// });
// Log.print('res: ${res}');
// FirebaseMessagesController()
// .sendNotificationToAnyWithoutData(
// title.text,
// body.text,
// tokensPassengersData[i]['token']
// .toString(), // Access token correctly
// 'order.wav',
// );
// }
// }
NotificationService.sendNotification(
target: 'passengers', // الإرسال لجميع المشتركين في "service"
title: title.text,
body: body.text,
isTopic: true,
category: 'fromAdmin', // فئة توضح نوع الإشعار
),
),
),
barrierColor: Colors.black.withOpacity(0.7), // تعتيم الخلفية
);
}
/// تنفيذ عملية الإرسال الفعلية
Future<void> _processSending(String target) async {
// إظهار تنبيه بدء العملية
Get.snackbar(
"جاري الإرسال",
"يتم إرسال الإشعار لـ $target...",
backgroundColor: _primaryAccent.withOpacity(0.2),
colorText: Colors.white,
duration: const Duration(seconds: 2),
);
try {
// استدعاء خدمة الإرسال
await NotificationService.sendNotification(
target: target,
title: titleController.text,
body: bodyController.text,
isTopic: true,
category: 'fromAdmin',
);
Get.snackbar(
"نجاح",
"تم إرسال الإشعار بنجاح",
backgroundColor: Colors.green.withOpacity(0.5),
colorText: Colors.white,
);
} catch (e) {
Get.snackbar(
"خطأ",
"فشل إرسال الإشعار: $e",
backgroundColor: Colors.red.withOpacity(0.5),
colorText: Colors.white,
);
}
}
/// تصميم حقل الإدخال المخصص (Dark Input Field)
Widget _buildModernTextField({
required TextEditingController controller,
required String hint,
required IconData icon,
int maxLines = 1,
}) {
return Container(
decoration: BoxDecoration(
color: _inputColor,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.white.withOpacity(0.1)),
),
child: TextField(
controller: controller,
style: const TextStyle(color: Colors.white),
maxLines: maxLines,
decoration: InputDecoration(
hintText: hint,
hintStyle:
TextStyle(color: Colors.white.withOpacity(0.3), fontSize: 14),
prefixIcon: Icon(icon, color: Colors.white38, size: 20),
border: InputBorder.none,
contentPadding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
),
),
);
Get.back();
// } else {
// // Handle the case where 'data' is not a list
// print('Data is not a list: $tokensPassengersData');
// }
}),
cancel: MyElevatedButton(
title: 'cancel',
onPressed: () {
Get.back();
}));
}
}
// يلا دلوقتي! تطبيق سفر جاهز عشان تبدأ تستقبل الطلبات
// • افتح التطبيق دلوقتي، واستعد إنك تستقبل طلبات أكتر. كل ما تكون فاتح، فرصتك في الطلبات بتزيد!
// 2. خليك فاتح واستقبل طلبات أكتر مع تطبيق سفر
// • وجودك متصل في التطبيق هيخليك تستقبل طلبات أكتر. افتح التطبيق دلوقتي وما تفوتش الفرصة!
// 3. فرصتك لزيادة دخلك مع تطبيق سفر تبدأ من دلوقتي!
// • مجرد إنك تفتح التطبيق مش هيأثر عليك، بالعكس، هيزود فرصتك في طلبات أكتر. افتح التطبيق واشترك دلوقتي!
//sms
// link sefer driver is https://shorturl.at/IHJcm1.
// // ميزات الأمان بعد 500 رحلة:
// • “بعد 500 رحلة مع سفر، تحصل على مميزات أمان إضافية لضمان راحتك.”
// • “نوفر لك ميزات أمان متقدمة بعد 500 رحلة لتجربة قيادة أكثر أمانًا.”
// • “مع 500 رحلة، تحصل على دعم أمني متقدم لتوفير أفضل تجربة قيادة.”
// 2. ميزات الصيانة:
// • “احصل على خدمات صيانة مجانية بعد عدد معين من الرحلات مع سفر.”
// • “استمتع بخدمات صيانة حصرية عند الوصول إلى عدد محدد من الرحلات.”
// • “مع سفر، نقدم لك عروض صيانة مميزة لتحافظ على سيارتك في أفضل حال.”
// 3. ميزات فتح حسابات البنوك:
// • “مع سفر، يمكنك فتح حساب بنكي بسهولة واستفادة من عروض مميزة.”
// • “افتح حساب بنكي مع تطبيق سفر واستفد من خدمات مالية حصرية.”
// • “نساعدك على فتح حساب بنكي بأفضل العروض بالتعاون مع البنوك المحلية.”
// 4. ميزات ورود السيارات ومعارض السيارات الخاصة بنا:
// • “استمتع بعروض مميزة لشراء السيارات من معارض سفر الحصرية.”
// • “اختر سيارتك المثالية من معارض سفر بأسعار تنافسية وخدمات مميزة.”
// • “نقدم لك أفضل عروض السيارات من معارضنا لتسهيل امتلاك سيارتك الجديدة.”
// 5. ميزات أوفر كار:
// • “أوفر كار من سفر توفر لك سيارات اقتصادية لزيادة دخلك بكفاءة.”
// • “مع أوفر كار، يمكنك العمل بسيارات اقتصادية وتحقيق أرباح أكبر.”
// • “تطبيق سفر يقدم لك أوفر كار، الخيار الاقتصادي المثالي لزيادة دخلك.”
// 6. مستوى الدخل المحدود والطلبات الاقتصادية:
// • “لأصحاب الدخل المحدود، وفرنا طلبات اقتصادية تضمن لك زيادة دخلك.”
// • “الطلبات الاقتصادية من سفر تساعدك على زيادة دخلك بسهولة وفعالية.”
// • “استفد من طلبات اقتصادية تناسب أصحاب الدخل المحدود لزيادة أرباحك.”
// 7. طلبات الليل:
// • “مع طلبات الليل من سفر، زود دخلك واستفد من فرص إضافية في المساء.”
// • “لا تفوت فرصة طلبات الليل مع سفر، زود دخلك في أي وقت.”
// • “طلبات الليل من سفر توفر لك فرصًا إضافية لتحقيق دخل أعلى.”
// 8. طلبات الكمفورت الأكثر راحة والسيارات المكيفة:
// • “قدّم خدمة مريحة مع طلبات الكمفورت من سفر والسيارات المكيفة.”
// • “طلبات الكمفورت توفر تجربة راقية للركاب بسيارات مكيفة ومريحة.”
// • “مع سفر، سيارات الكمفورت المكيفة تضمن راحة الركاب وزيادة الطلبات.”
// 9. طلبات السبيد:
// • “استقبل طلبات السبيد مع سفر لتقديم رحلات أسرع وزيادة دخلك.”
// • “طلبات السبيد توفر لك فرصة إكمال المزيد من الرحلات في وقت أقل.”
// • “مع طلبات السبيد من سفر، تقدم خدمة سريعة وفعالة لزيادة الأرباح.”
// 10. الطلبات الثابتة والمعتدلة السعر والنسبة الثابتة 8%:
// • “مع نسبة ثابتة 8%، تحصل على أفضل عروض الأسعار مع سفر.”
// • “استمتع بنسبة ثابتة 8%، أقل نسبة بين المنافسين لزيادة دخلك.”
// • “طلبات سفر الثابتة تضمن لك دخلاً مستقراً بنسبة أقل من 8%.”

View File

@@ -0,0 +1,150 @@
import 'dart:async';
import 'package:get/get.dart';
import 'package:sefer_admin1/constant/links.dart';
import '../../print.dart';
// --- Models ---
class ServerData {
final CpuInfo cpu;
final MemoryInfo memory;
final DiskInfo disk;
final Map<String, String> services;
final List<ProcessInfo> topProcesses;
final NetworkInfo network;
final UptimeInfo uptime;
final String timestamp;
ServerData({
required this.cpu,
required this.memory,
required this.disk,
required this.services,
required this.topProcesses,
required this.network,
required this.uptime,
required this.timestamp,
});
factory ServerData.fromJson(Map<String, dynamic> json) {
return ServerData(
cpu: CpuInfo.fromJson(json['cpu']),
memory: MemoryInfo.fromJson(json['memory']),
disk: DiskInfo.fromJson(json['disk']),
services: Map<String, String>.from(json['services']),
topProcesses: (json['top_processes'] as List)
.map((i) => ProcessInfo.fromJson(i))
.toList(),
network: NetworkInfo.fromJson(json['network']),
uptime: UptimeInfo.fromJson(json['uptime']),
timestamp: json['timestamp'],
);
}
}
class CpuInfo {
final double percent;
final int cores;
final double load1m;
CpuInfo({required this.percent, required this.cores, required this.load1m});
factory CpuInfo.fromJson(Map<String, dynamic> json) => CpuInfo(
percent: json['percent'].toDouble(),
cores: json['cores'],
load1m: json['load_1m'].toDouble());
}
class MemoryInfo {
final double percent;
final double usedGb;
final double totalGb;
MemoryInfo(
{required this.percent, required this.usedGb, required this.totalGb});
factory MemoryInfo.fromJson(Map<String, dynamic> json) => MemoryInfo(
percent: json['percent'].toDouble(),
usedGb: json['used_gb'].toDouble(),
totalGb: json['total_gb'].toDouble());
}
class DiskInfo {
final double percent;
final double usedGb;
final double totalGb;
DiskInfo(
{required this.percent, required this.usedGb, required this.totalGb});
factory DiskInfo.fromJson(Map<String, dynamic> json) => DiskInfo(
percent: json['percent'].toDouble(),
usedGb: json['used_gb'].toDouble(),
totalGb: json['total_gb'].toDouble());
}
class ProcessInfo {
final String name;
final String usage;
ProcessInfo({required this.name, required this.usage});
factory ProcessInfo.fromJson(Map<String, dynamic> json) =>
ProcessInfo(name: json['name'], usage: json['usage']);
}
class NetworkInfo {
final double receivedMb;
final double sentMb;
NetworkInfo({required this.receivedMb, required this.sentMb});
factory NetworkInfo.fromJson(Map<String, dynamic> json) => NetworkInfo(
receivedMb: json['received_mb'].toDouble(),
sentMb: json['sent_mb'].toDouble());
}
class UptimeInfo {
final String formatted;
UptimeInfo({required this.formatted});
factory UptimeInfo.fromJson(Map<String, dynamic> json) =>
UptimeInfo(formatted: json['formatted']);
}
// --- Controller ---
class ServerMonitorController extends GetxController {
var isLoading = false.obs;
var serverData = Rxn<ServerData>();
var errorMessage = ''.obs;
Timer? _timer; // تخزين التايمر
@override
void onInit() {
super.onInit();
fetchServerData();
// تحديث تلقائي كل 60 ثانية
_timer = Timer.periodic(Duration(seconds: 60), (_) {
fetchServerData();
});
}
@override
void onClose() {
// إلغاء التحديث عند إغلاق الصفحة
_timer?.cancel();
super.onClose();
}
Future<void> fetchServerData() async {
try {
isLoading(true);
errorMessage('');
final response = await GetConnect().get(AppLink.serverMonitor);
if (response.status.hasError) {
errorMessage.value = 'خطأ في الاتصال: ${response.statusText}';
} else {
serverData.value = ServerData.fromJson(response.body);
}
} catch (e) {
errorMessage.value = 'حدث خطأ: $e';
} finally {
isLoading(false);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +1,10 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
// تأكد من استيراد مكتبة الاتصال إذا أردت تفعيل زر الاتصال فعلياً
// import 'package:url_launcher/url_launcher.dart';
import '../../../constant/box_name.dart';
import '../../../controller/functions/launch.dart';
import '../../../main.dart';
import '../../widgets/my_scafold.dart';
import '../../widgets/my_textField.dart';
import '../../widgets/mycircular.dart';
import '../../../constant/style.dart';
import '../../../controller/admin/captain_admin_controller.dart';
import 'captain_details.dart';
@@ -20,14 +15,9 @@ class CaptainsPage extends StatelessWidget {
Get.put(CaptainAdminController());
final TextEditingController searchController = TextEditingController();
// 🔴 هام جداً: قم بتغيير هذا المتغير بناءً على حالة تسجيل الدخول الحقيقية في تطبيقك
// مثال: bool isAdmin = Get.find<AuthController>().isAdmin;
// final bool isAdmin = true; // اجعلها false لتجربة وضع المستخدم العادي
String myPhone = box.read(BoxName.adminPhone).toString();
// 2. تحديد من هو "السوبر أدمن" الذي يرى كل شيء
// يمكنك إضافة المزيد من الأرقام هنا باستخدام || أو قائمة
bool isSuperAdmin = false;
@override
Widget build(BuildContext context) {
isSuperAdmin = myPhone == '963942542053' || myPhone == '963992952235';
@@ -37,44 +27,45 @@ class CaptainsPage extends StatelessWidget {
isleading: true,
body: [
Container(
height: MediaQuery.of(context).size.height, // لضمان أخذ المساحة
padding: const EdgeInsets.all(16.0),
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Theme.of(context).primaryColor.withOpacity(0.03),
Colors.white,
],
),
),
child: Column(
children: [
// --- شريط البحث المحسن ---
_buildSearchSection(context),
const SizedBox(height: 20),
// --- قائمة النتائج ---
_buildHeaderSection(context),
Expanded(
child: GetBuilder<CaptainAdminController>(
builder: (controller) {
if (controller.isLoading) {
return const Center(child: MyCircularProgressIndicator());
return _buildLoadingState();
}
if (controller.captainData['message'] == null ||
controller.captainData['message'].isEmpty) {
final message = controller.captainData['message'];
if (message == null) {
return _buildEmptyState();
}
return ListView.separated(
physics: const BouncingScrollPhysics(),
itemCount: controller.captainData['message'].length,
separatorBuilder: (context, index) =>
const SizedBox(height: 12),
itemBuilder: (context, index) {
final captain =
controller.captainData['message'][index];
return _buildCaptainCard(context, captain);
},
);
// 🔥 الحل هنا: توحيد الشكل إلى List
final List<dynamic> captains =
message is List ? message : [message];
if (captains.isEmpty) {
return _buildEmptyState();
}
return _buildResultsList(context, captains);
},
),
),
// مساحة إضافية في الأسفل لتجنب تداخل المحتوى مع الحواف
const SizedBox(height: 80),
],
),
),
@@ -82,53 +73,107 @@ class CaptainsPage extends StatelessWidget {
);
}
// --- ودجت البحث ---
Widget _buildSearchSection(BuildContext context) {
// ================= HEADER =================
Widget _buildHeaderSection(BuildContext context) {
return Container(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.1),
spreadRadius: 2,
color: Colors.black.withOpacity(0.04),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
),
child: Icon(
Icons.manage_search_rounded,
color: Theme.of(context).primaryColor,
size: 24,
),
),
const SizedBox(width: 12),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Find Captain'.tr,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
),
Text(
'Search by phone number'.tr,
style: TextStyle(
fontSize: 13,
color: Colors.grey[600],
),
),
],
),
],
),
const SizedBox(height: 20),
_buildModernSearchBar(context),
],
),
);
}
Widget _buildModernSearchBar(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.grey[50],
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.grey[200]!),
),
child: Row(
children: [
Expanded(
child: MyTextForm(
child: TextField(
controller: searchController,
label: 'Captain Phone Number'.tr,
hint: 'Enter phone number...'.tr,
type: TextInputType.phone,
// يمكنك إزالة الحواف من الـ TextField الأصلي إذا أردت ليتناسب مع الكونتينر
keyboardType: TextInputType.phone,
style: const TextStyle(fontSize: 15),
decoration: InputDecoration(
hintText: '0990000000'.tr,
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 14),
prefixIcon: Icon(Icons.phone_android_rounded,
color: Colors.grey[400], size: 22),
border: InputBorder.none,
contentPadding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
),
onSubmitted: (_) => _performSearch(),
),
),
Container(
decoration: BoxDecoration(
Padding(
padding: const EdgeInsets.all(6.0),
child: Material(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10),
borderRadius: BorderRadius.circular(12),
child: InkWell(
onTap: _performSearch,
borderRadius: BorderRadius.circular(12),
child: const Padding(
padding: EdgeInsets.all(12),
child: Icon(Icons.search, color: Colors.white, size: 24),
),
),
child: IconButton(
icon: const Icon(Icons.search, size: 28, color: Colors.white),
onPressed: () {
final phone = searchController.text;
if (phone.isNotEmpty) {
captainController.find_driver_by_phone(phone);
} else {
Get.snackbar(
'Error'.tr,
'Please enter a phone number to search.'.tr,
backgroundColor: Colors.red.withOpacity(0.8),
colorText: Colors.white,
);
}
},
),
),
],
@@ -136,128 +181,138 @@ class CaptainsPage extends StatelessWidget {
);
}
// --- بطاقة الكابتن المحسنة ---
Widget _buildCaptainCard(BuildContext context, dynamic captain) {
void _performSearch() {
final phone = searchController.text.trim();
if (phone.isNotEmpty) {
captainController.find_driver_by_phone(phone);
}
}
// ================= RESULTS =================
Widget _buildResultsList(BuildContext context, List<dynamic> captains) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 12),
child: Row(
children: [
Text(
'Search Results'.tr,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
color: Colors.black87,
),
),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
),
child: Text(
'${captains.length}',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.bold,
color: Theme.of(context).primaryColor,
),
),
),
],
),
),
Expanded(
child: ListView.separated(
physics: const BouncingScrollPhysics(),
padding: const EdgeInsets.fromLTRB(20, 0, 20, 80),
itemCount: captains.length,
separatorBuilder: (_, __) => const SizedBox(height: 12),
itemBuilder: (context, index) {
final captain = captains[index] as Map<String, dynamic>;
return _buildModernCaptainCard(context, captain);
},
),
),
],
);
}
// ================= CARD =================
Widget _buildModernCaptainCard(
BuildContext context, Map<String, dynamic> captain) {
final String fullName =
'${captain['first_name'] ?? ''} ${captain['last_name'] ?? ''}';
final String phone = captain['phone']?.toString() ?? '';
final String? email = captain['email']?.toString();
return Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.08),
spreadRadius: 1,
blurRadius: 8,
color: Colors.black.withOpacity(0.04),
blurRadius: 12,
offset: const Offset(0, 4),
),
],
border: Border.all(color: Colors.grey.withOpacity(0.1)),
),
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(16),
borderRadius: BorderRadius.circular(20),
onTap: () {
Get.to(() => const CaptainDetailsPage(),
arguments: {'data': captain});
},
child: Padding(
padding: const EdgeInsets.all(12.0),
padding: const EdgeInsets.all(16.0),
child: Row(
children: [
// صورة الكابتن أو أيقونة
CircleAvatar(
radius: 28,
backgroundColor:
Theme.of(context).primaryColor.withOpacity(0.1),
child: Icon(
Icons.person,
color: Theme.of(context).primaryColor,
size: 30,
Container(
width: 56,
height: 56,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Theme.of(context).primaryColor.withOpacity(0.8),
Theme.of(context).primaryColor,
],
),
borderRadius: BorderRadius.circular(16),
),
child: const Icon(
Icons.person_rounded,
color: Colors.white,
size: 28,
),
),
const SizedBox(width: 15),
// المعلومات النصية
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// الاسم
Text(
'${captain['first_name']} ${captain['last_name']}',
fullName,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.black87,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 6),
Text(phone),
if (isSuperAdmin && email != null) ...[
const SizedBox(height: 4),
// رقم الهاتف (مع المنطق)
Row(
children: [
Icon(Icons.phone_iphone,
size: 14, color: Colors.grey[600]),
const SizedBox(width: 4),
Text(
_formatPhoneNumber(captain['phone'].toString()),
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: Colors.grey[700],
fontFamily:
'monospace', // لجعل الأرقام والنجوم متناسقة
),
),
],
),
// الإيميل (يظهر فقط للأدمن)
if (isSuperAdmin && captain['email'] != null) ...[
const SizedBox(height: 4),
Row(
children: [
Icon(Icons.email_outlined,
size: 14, color: Colors.grey[600]),
const SizedBox(width: 4),
Expanded(
child: Text(
captain['email'],
style: TextStyle(
fontSize: 12,
color: Colors.grey[600],
),
overflow: TextOverflow.ellipsis,
),
),
],
),
Text(email),
],
],
),
),
// أزرار الإجراءات
Column(
children: [
// زر الاتصال (فقط للأدمن)
if (isSuperAdmin)
IconButton(
onPressed: () {
// منطق الاتصال
makePhoneCall('+' + captain['phone']);
// Get.snackbar(
// 'Call', 'Calling ${captain['phone']}...');
},
icon: const Icon(Icons.call, color: Colors.green),
tooltip: 'Call Captain',
),
if (!isSuperAdmin)
const Icon(Icons.arrow_forward_ios,
size: 16, color: Colors.grey),
],
),
],
),
),
@@ -266,37 +321,15 @@ class CaptainsPage extends StatelessWidget {
);
}
// --- دالة تنسيق الرقم (المنطق المطلوب) ---
String _formatPhoneNumber(String phone) {
if (isSuperAdmin) {
return phone; // للأدمن: إظهار الرقم كاملاً
} else {
// للمستخدم العادي: إظهار آخر 4 أرقام فقط
if (phone.length <= 4) return phone;
String lastFour = phone.substring(phone.length - 4);
String maskedPart = '*' * (phone.length - 4);
return '$maskedPart$lastFour'; // النتيجة: *******1234
}
// ================= STATES =================
Widget _buildLoadingState() {
return const Center(child: MyCircularProgressIndicator());
}
// --- تصميم الحالة الفارغة ---
Widget _buildEmptyState() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.search_off_rounded, size: 80, color: Colors.grey[300]),
const SizedBox(height: 10),
Text(
'No captains found.'.tr,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: Colors.grey[500],
),
),
],
),
return const Center(
child: Text("No captains found"),
);
}
}

View File

@@ -80,7 +80,7 @@ class DriverGiftCheckerController extends GetxController {
// } else {
// الخطوة 3: إضافة الهدية
statusLog.value += "\n🎁 الهدية غير موجودة. جاري الإضافة...";
await _addGiftToDriver(driverId, phoneInput, "30000");
await _addGiftToDriver(driverId, phoneInput, "300");
// }
} catch (e) {
statusLog.value = "حدث خطأ غير متوقع: $e";
@@ -95,7 +95,7 @@ class DriverGiftCheckerController extends GetxController {
final wallet = Get.put(WalletController());
// استخدام الدالة الموجودة في نظامك
await wallet.addDrivergift3000('new driver', driverId, amount, phone);
await wallet.addDrivergift300('new driver', driverId, amount, phone);
// statusLog.value += "\n✅ تمت إضافة مبلغ $amount ل.س بنجاح!";

View File

@@ -5,7 +5,8 @@ import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:http/http.dart' as http;
import 'package:url_launcher/url_launcher.dart'; // ضروري من أجل الاتصال
import 'package:sefer_admin1/constant/links.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../constant/box_name.dart';
import '../../../main.dart';
@@ -17,7 +18,8 @@ class IntaleqTrackerScreen extends StatefulWidget {
State<IntaleqTrackerScreen> createState() => _IntaleqTrackerScreenState();
}
class _IntaleqTrackerScreenState extends State<IntaleqTrackerScreen> {
class _IntaleqTrackerScreenState extends State<IntaleqTrackerScreen>
with TickerProviderStateMixin {
// === Map Controller ===
final MapController _mapController = MapController();
List<Marker> _markers = [];
@@ -32,58 +34,83 @@ class _IntaleqTrackerScreenState extends State<IntaleqTrackerScreen> {
int dayCount = 0;
Timer? _timer;
// === Animation Controllers ===
late AnimationController _fadeController;
late AnimationController _scaleController;
// === Admin Info ===
String myPhone = box.read(BoxName.adminPhone).toString();
bool get isSuperAdmin =>
myPhone == '963942542053' || myPhone == '963992952235';
// === URLs ===
final String _baseDir = "https://api.intaleq.xyz/intaleq/ride/location/";
final String _baseDir = "${AppLink.server}/ride/location/";
@override
void initState() {
super.initState();
_initAnimations();
fetchData();
// === تعديل 1: التحديث كل 5 دقائق بدلاً من 15 ثانية ===
_timer = Timer.periodic(const Duration(minutes: 5), (timer) {
if (mounted) fetchData();
});
}
void _initAnimations() {
_fadeController = AnimationController(
duration: const Duration(milliseconds: 800),
vsync: this,
);
_scaleController = AnimationController(
duration: const Duration(milliseconds: 600),
vsync: this,
);
_fadeController.forward();
_scaleController.forward();
}
@override
void dispose() {
_timer?.cancel();
_mapController.dispose();
_fadeController.dispose();
_scaleController.dispose();
super.dispose();
}
// === دالة إجراء الاتصال ===
Future<void> _makePhoneCall(String phoneNumber) async {
final Uri launchUri = Uri(scheme: 'tel', path: phoneNumber);
if (await canLaunchUrl(launchUri)) {
await launchUrl(launchUri);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text("لا يمكن إجراء الاتصال لهذا الرقم")),
);
_showSnackBar("لا يمكن إجراء الاتصال لهذا الرقم");
}
}
// === Fetch Data Function ===
void _showSnackBar(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: const Color(0xFF2C3E50),
behavior: SnackBarBehavior.floating,
margin: const EdgeInsets.all(16),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
);
}
Future<void> fetchData() async {
if (!mounted) return;
setState(() => isLoading = true);
try {
// 1. طلب التحديث من PHP
String updateUrl =
"${_baseDir}getUpdatedLocationForAdmin.php?mode=${isLiveMode ? 'live' : 'day'}";
await http.get(Uri.parse(updateUrl));
String v = DateTime.now().millisecondsSinceEpoch.toString();
// === Live Data ===
final responseLive =
await http.get(Uri.parse("${_baseDir}locations_live.json?v=$v"));
if (responseLive.statusCode == 200) {
@@ -98,7 +125,6 @@ class _IntaleqTrackerScreenState extends State<IntaleqTrackerScreen> {
});
}
// === Day Data ===
final responseDay =
await http.get(Uri.parse("${_baseDir}locations_day.json?v=$v"));
if (responseDay.statusCode == 200) {
@@ -124,7 +150,6 @@ class _IntaleqTrackerScreenState extends State<IntaleqTrackerScreen> {
}
}
// === Build Markers ===
void _buildMarkers(List<dynamic> drivers) {
List<Marker> newMarkers = [];
@@ -144,8 +169,8 @@ class _IntaleqTrackerScreenState extends State<IntaleqTrackerScreen> {
newMarkers.add(
Marker(
point: LatLng(lat, lon),
width: 50,
height: 50,
width: 60,
height: 60,
child: GestureDetector(
onTap: () {
_showDriverInfoDialog(
@@ -158,31 +183,7 @@ class _IntaleqTrackerScreenState extends State<IntaleqTrackerScreen> {
cancelled: cancelled,
);
},
child: Stack(
alignment: Alignment.center,
children: [
Container(
width: 32,
height: 32,
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.9),
shape: BoxShape.circle,
boxShadow: const [
BoxShadow(blurRadius: 3, color: Colors.black26)
]),
),
Transform.rotate(
angle: heading * (math.pi / 180),
child: Icon(
Icons.navigation,
color: isLiveMode
? const Color(0xFF27AE60)
: const Color(0xFF2980B9),
size: 28,
),
),
],
),
child: _buildMarkerWidget(heading),
),
),
);
@@ -193,7 +194,46 @@ class _IntaleqTrackerScreenState extends State<IntaleqTrackerScreen> {
});
}
// === Dialog Function ===
Widget _buildMarkerWidget(double heading) {
return Stack(
alignment: Alignment.center,
children: [
Container(
width: 44,
height: 44,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
colors: isLiveMode
? [const Color(0xFF27AE60), const Color(0xFF229954)]
: [const Color(0xFF3498DB), const Color(0xFF2980B9)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
boxShadow: [
BoxShadow(
color: (isLiveMode
? const Color(0xFF27AE60)
: const Color(0xFF3498DB))
.withOpacity(0.5),
blurRadius: 12,
spreadRadius: 2,
)
],
),
),
Transform.rotate(
angle: heading * (math.pi / 180),
child: Icon(
Icons.navigation,
color: Colors.white,
size: 26,
),
),
],
);
}
void _showDriverInfoDialog({
required String driverId,
required String name,
@@ -206,68 +246,68 @@ class _IntaleqTrackerScreenState extends State<IntaleqTrackerScreen> {
showDialog(
context: context,
builder: (_) => Dialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
backgroundColor: Colors.transparent,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.white, Colors.grey.shade50],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.15),
blurRadius: 30,
spreadRadius: 5,
)
],
),
child: Padding(
padding: const EdgeInsets.all(20),
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text("بيانات الكابتن",
Container(
padding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: isLiveMode
? [const Color(0xFF27AE60), const Color(0xFF229954)]
: [const Color(0xFF3498DB), const Color(0xFF2980B9)],
),
borderRadius: BorderRadius.circular(12),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.person_outline, color: Colors.white, size: 20),
const SizedBox(width: 8),
const Text(
"معلومات الكابتن",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Color(0xFF2C3E50))),
const Divider(thickness: 1, height: 25),
_infoRow(Icons.person, "الاسم", name),
_infoRow(Icons.badge, "المعرف (ID)", driverId),
_infoRow(Icons.speed, "السرعة", "$speed كم/س"),
const SizedBox(height: 10),
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.grey.shade50,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.grey.shade200)),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_statItem("مكتملة", completed, Colors.green),
Container(
width: 1, height: 30, color: Colors.grey.shade300),
_statItem("ملغاة", cancelled, Colors.red),
color: Colors.white,
),
),
],
),
),
// === تعديل 2: جعل رقم الهاتف قابلاً للنقر ===
const SizedBox(height: 20),
_buildInfoCard(Icons.person, "الاسم", name),
const SizedBox(height: 12),
_buildInfoCard(Icons.badge, "المعرف", driverId),
const SizedBox(height: 12),
_buildInfoCard(Icons.speed, "السرعة", "$speed كم/س"),
const SizedBox(height: 20),
_buildStatsContainer(completed, cancelled),
if (isSuperAdmin) ...[
const SizedBox(height: 15),
InkWell(
onTap: () {
if (phone.isNotEmpty) _makePhoneCall(phone);
},
borderRadius: BorderRadius.circular(8),
child: Container(
padding:
const EdgeInsets.symmetric(vertical: 8, horizontal: 10),
decoration: BoxDecoration(
color: const Color(0xFFFFF3CD),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: const Color(0xFFFFEEBA))),
child: Row(
children: [
Expanded(
child: _infoRow(Icons.phone, "الهاتف", phone,
isPrivate: true)),
const SizedBox(width: 5),
const Icon(Icons.call, color: Colors.green, size: 20),
const SizedBox(height: 16),
_buildPhoneButton(phone),
],
),
),
),
],
const SizedBox(height: 20),
SizedBox(
width: double.infinity,
@@ -276,173 +316,513 @@ class _IntaleqTrackerScreenState extends State<IntaleqTrackerScreen> {
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF2C3E50),
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
elevation: 0,
),
child: const Text(
"إغلاق",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
child: const Text("إغلاق"),
),
)
],
),
),
),
),
);
}
// Helper Widgets
Widget _infoRow(IconData icon, String label, String value,
{bool isPrivate = false}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
Widget _buildInfoCard(IconData icon, String label, String value) {
return Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.grey.shade200,
width: 1,
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 8,
)
],
),
child: Row(
children: [
Icon(icon,
size: 20,
color: isPrivate ? Colors.orange[800] : Colors.grey[600]),
const SizedBox(width: 8),
Text("$label: ",
style:
const TextStyle(fontWeight: FontWeight.bold, fontSize: 13)),
Expanded(
child: Text(value,
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.grey.shade100,
borderRadius: BorderRadius.circular(8),
),
child: Icon(icon, color: const Color(0xFF2C3E50), size: 20),
),
const SizedBox(width: 12),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: TextStyle(
fontSize: 14,
fontWeight:
isPrivate ? FontWeight.bold : FontWeight.normal),
textAlign: TextAlign.end)),
fontSize: 12,
color: Colors.grey.shade600,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 4),
Text(
value,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Color(0xFF2C3E50),
),
),
],
),
],
),
);
}
Widget _statItem(String label, String val, Color color) {
Widget _buildStatsContainer(String completed, String cancelled) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.grey.shade50, Colors.grey.shade100],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.grey.shade200),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildStatItem("✓ مكتملة", completed, const Color(0xFF27AE60)),
Container(
width: 1,
height: 40,
color: Colors.grey.shade300,
),
_buildStatItem("✕ ملغاة", cancelled, const Color(0xFFE74C3C)),
],
),
);
}
Widget _buildStatItem(String label, String value, Color color) {
return Column(
children: [
Text(val,
Text(
value,
style: TextStyle(
color: color, fontWeight: FontWeight.bold, fontSize: 16)),
Text(label, style: const TextStyle(fontSize: 11, color: Colors.grey)),
color: color,
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
const SizedBox(height: 4),
Text(
label,
style: TextStyle(
fontSize: 12,
color: Colors.grey.shade600,
fontWeight: FontWeight.w500,
),
),
],
);
}
Widget _buildPhoneButton(String phone) {
return InkWell(
onTap: () {
if (phone.isNotEmpty) _makePhoneCall(phone);
},
borderRadius: BorderRadius.circular(12),
child: Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 14),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [const Color(0xFFFFA500), const Color(0xFFFF8C00)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: const Color(0xFFFFA500).withOpacity(0.4),
blurRadius: 12,
spreadRadius: 2,
)
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.call, color: Colors.white, size: 20),
const SizedBox(width: 10),
Expanded(
child: Text(
phone,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 15,
),
textAlign: TextAlign.center,
),
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
title: const Text("نظام تتبع الكباتن"),
backgroundColor: const Color(0xFF2C3E50),
foregroundColor: Colors.white),
elevation: 0,
backgroundColor: Colors.transparent,
centerTitle: true,
title: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
color: const Color(0xFF2C3E50).withOpacity(0.9),
borderRadius: BorderRadius.circular(12),
// backdropFilter: const BackdropFilter(blur: 10),
),
child: const Text(
"نظام تتبع الكابتن",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
foregroundColor: Colors.white,
),
body: Stack(
children: [
FlutterMap(
mapController: _mapController,
options: const MapOptions(
initialCenter: LatLng(33.513, 36.276), initialZoom: 10.0),
initialCenter: LatLng(33.513, 36.276),
initialZoom: 10.0,
),
children: [
TileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'com.tripz.app'),
userAgentPackageName: 'com.tripz.app',
),
MarkerLayer(markers: _markers),
],
),
_buildDashboard(),
],
),
);
}
// === Dashboard ===
Positioned(
top: 20,
right: 15,
Widget _buildDashboard() {
return Positioned(
top: 100,
right: 16,
child: FadeTransition(
opacity: _fadeController,
child: ScaleTransition(
scale: _scaleController,
child: Container(
width: 260,
padding: const EdgeInsets.all(15),
width: 300,
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.95),
borderRadius: BorderRadius.circular(12),
boxShadow: const [
BoxShadow(color: Colors.black12, blurRadius: 10)
]),
color: Colors.white,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.15),
blurRadius: 30,
spreadRadius: 5,
)
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Column(
children: [
// Header
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
const Color(0xFF2C3E50),
const Color(0xFF34495E)
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Icon(Icons.dashboard,
color: Colors.white, size: 22),
const Text(
"لوحة التحكم",
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
const Text("لوحة التحكم",
style: TextStyle(fontWeight: FontWeight.bold)),
const Divider(),
// أزرار التبديل
// Mode Buttons
Row(
children: [
Expanded(
child: _modeBtn("أرشيف اليوم", !isLiveMode, () {
child: _buildModeButton(
"أرشيف اليوم",
!isLiveMode,
() {
setState(() => isLiveMode = false);
fetchData();
})),
const SizedBox(width: 8),
},
const Color(0xFF3498DB),
),
),
const SizedBox(width: 10),
Expanded(
child: _modeBtn("مباشر", isLiveMode, () {
child: _buildModeButton(
"مباشر",
isLiveMode,
() {
setState(() => isLiveMode = true);
fetchData();
})),
},
const Color(0xFF27AE60),
),
),
],
),
const SizedBox(height: 15),
const SizedBox(height: 16),
// === عرض العدادين معاً ===
Row(
// Stats
_buildStatRow(
icon: Icons.live_tv,
label: "نشط الآن (مباشر)",
value: liveCount.toString(),
color: const Color(0xFF27AE60),
),
const SizedBox(height: 12),
_buildStatRow(
icon: Icons.history,
label: "إجمالي اليوم",
value: dayCount.toString(),
color: const Color(0xFF3498DB),
),
const SizedBox(height: 14),
// Last Update
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.grey.shade50,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.grey.shade200),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("$liveCount",
style: const TextStyle(
color: Color(0xFF27AE60),
fontWeight: FontWeight.bold,
fontSize: 14)),
const Text("نشط الآن (مباشر):",
style: TextStyle(fontSize: 12)),
Text(
isLoading
? "جاري التحديث..."
: "تحديث: $lastUpdated",
style: TextStyle(
fontSize: 11,
color: Colors.grey.shade600,
fontWeight: FontWeight.w500,
),
),
Icon(
isLoading
? Icons.hourglass_bottom
: Icons.check_circle,
size: 14,
color: isLoading ? Colors.orange : Colors.green,
),
],
),
const SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("$dayCount",
style: const TextStyle(
color: Color(0xFF2980B9),
fontWeight: FontWeight.bold,
fontSize: 14)),
const Text("إجمالي اليوم:",
style: TextStyle(fontSize: 12)),
],
),
const SizedBox(height: 12),
const SizedBox(height: 10),
Text(isLoading ? "جاري التحديث..." : "تحديث: $lastUpdated",
style: const TextStyle(fontSize: 10, color: Colors.grey)),
const SizedBox(height: 8),
// Refresh Button
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: isLoading ? null : fetchData,
child: const Text("تحديث البيانات")))
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF2C3E50),
foregroundColor: Colors.white,
disabledBackgroundColor: Colors.grey.shade300,
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
elevation: 0,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (isLoading)
const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.white,
),
),
)
else
const Icon(Icons.refresh, size: 18),
const SizedBox(width: 8),
const Text(
"تحديث البيانات",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
],
),
),
),
],
),
),
],
),
),
),
),
),
);
}
Widget _modeBtn(String title, bool active, VoidCallback onTap) {
Widget _buildModeButton(
String title,
bool active,
VoidCallback onTap,
Color color,
) {
return InkWell(
onTap: onTap,
child: Container(
borderRadius: BorderRadius.circular(10),
child: AnimatedContainer(
duration: const Duration(milliseconds: 300),
padding: const EdgeInsets.symmetric(vertical: 10),
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(vertical: 8),
decoration: BoxDecoration(
color: active ? const Color(0xFF3498DB) : Colors.white,
borderRadius: BorderRadius.circular(6),
border: Border.all(color: const Color(0xFF3498DB))),
child: Text(title,
gradient: active
? LinearGradient(
colors: [color, color.withOpacity(0.8)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
)
: null,
color: active ? null : Colors.grey.shade100,
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: active ? color : Colors.grey.shade300,
width: 1.5,
),
boxShadow: active
? [
BoxShadow(
color: color.withOpacity(0.3),
blurRadius: 8,
spreadRadius: 1,
)
]
: null,
),
child: Text(
title,
style: TextStyle(
color: active ? Colors.white : const Color(0xFF3498DB),
fontWeight: active ? FontWeight.bold : FontWeight.normal)),
color: active ? Colors.white : Colors.grey.shade700,
fontWeight: active ? FontWeight.bold : FontWeight.w600,
fontSize: 13,
),
),
),
);
}
Widget _buildStatRow({
required IconData icon,
required String label,
required String value,
required Color color,
}) {
return Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: color.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(icon, color: color, size: 18),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: TextStyle(
fontSize: 12,
color: Colors.grey.shade600,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 2),
Text(
value,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: color,
),
),
],
),
),
],
);
}
}

View File

@@ -3,9 +3,9 @@ import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:sefer_admin1/constant/links.dart';
// Keep your specific imports
import 'package:sefer_admin1/controller/functions/crud.dart';
import 'package:sefer_admin1/print.dart';
/// --------------------------------------------------------------------------
/// 1. DATA MODELS
@@ -43,8 +43,7 @@ class DriverLocation {
class RideMonitorController extends GetxController {
// CONFIGURATION
final String apiUrl =
"https://api.intaleq.xyz/intaleq/Admin/rides/monitorRide.php";
final String apiUrl = "${AppLink.server}/Admin/rides/monitorRide.php";
// INPUT CONTROLLERS
final TextEditingController phoneInputController = TextEditingController();
@@ -81,7 +80,15 @@ class RideMonitorController extends GetxController {
void startSearch() {
if (phoneInputController.text.trim().isEmpty) {
Get.snackbar("Error", "Please enter a phone number");
Get.snackbar(
"تنبيه",
"يرجى إدخال رقم الهاتف أولاً",
backgroundColor: Colors.redAccent.withOpacity(0.9),
colorText: Colors.white,
snackPosition: SnackPosition.TOP,
margin: const EdgeInsets.all(15),
borderRadius: 15,
);
return;
}
@@ -92,8 +99,8 @@ class RideMonitorController extends GetxController {
startPoint.value = null;
endPoint.value = null;
routePolyline.clear();
driverName.value = "Loading...";
rideStatus.value = "Loading...";
driverName.value = "جاري التحميل...";
rideStatus.value = "جاري التحميل...";
_isFirstLoad = true;
// Switch UI
@@ -114,7 +121,7 @@ class RideMonitorController extends GetxController {
_timer?.cancel();
isTracking.value = false;
isLoading.value = false;
phoneInputController.clear();
// phoneInputController.clear(); // اختياري: يمكنك إبقائه لتسهيل البحث مرة أخرى
}
Future<void> fetchRideData() async {
@@ -124,11 +131,9 @@ class RideMonitorController extends GetxController {
try {
final response = await CRUD().post(
link: apiUrl,
payload: {"phone": phone},
payload: {"phone": "963$phone"},
);
// Log.print('response: ${response}');
if (response != 'failure') {
final jsonResponse = response;
@@ -140,12 +145,13 @@ class RideMonitorController extends GetxController {
// 1. Parse Driver Info
if (data['driver_details'] != null) {
driverName.value = data['driver_details']['fullname'] ?? "Unknown";
driverName.value =
data['driver_details']['fullname'] ?? "سائق غير معروف";
}
// 2. Parse Ride Info & Route
if (data['ride_details'] != null) {
rideStatus.value = data['ride_details']['status'] ?? "Unknown";
rideStatus.value = data['ride_details']['status'] ?? "غير معروف";
// Parse Start/End Locations (Format: "lat,lng")
String? startStr = data['ride_details']['start_location'];
@@ -174,21 +180,19 @@ class RideMonitorController extends GetxController {
if (startPoint.value != null && endPoint.value != null) {
_updateMapBounds();
}
print("No live location coordinates.");
}
hasError.value = false;
} else {
hasError.value = true;
errorMessage.value = jsonResponse['message'] ??
"Phone number not found or no active ride.";
"لم يتم العثور على رقم الهاتف أو لا توجد رحلة نشطة.";
}
} else {
hasError.value = true;
errorMessage.value = "Connection Failed";
errorMessage.value = "فشل الاتصال بالخادم";
}
} catch (e) {
print("Polling Error: $e");
if (isLoading.value) {
hasError.value = true;
errorMessage.value = e.toString();
@@ -207,14 +211,12 @@ class RideMonitorController extends GetxController {
final lng = double.parse(parts[1].trim());
return LatLng(lat, lng);
} catch (e) {
print("Error parsing location string '$str': $e");
return null;
}
}
// Logic to fit start, end, and driver on screen
void _updateMapBounds() {
// Only auto-fit on the first successful load to avoid fighting user pan/zoom
if (!_isFirstLoad) return;
List<LatLng> pointsToFit = [];
@@ -232,106 +234,184 @@ class RideMonitorController extends GetxController {
mapController.fitCamera(
CameraFit.bounds(
bounds: bounds,
padding:
const EdgeInsets.all(80.0), // Padding so markers aren't on edge
padding: const EdgeInsets.all(80.0),
),
);
_isFirstLoad = false; // Disable auto-fit after initial success
_isFirstLoad = false;
} catch (e) {
print("Map Controller not ready yet: $e");
// Map Controller not ready yet
}
}
}
}
/// --------------------------------------------------------------------------
/// 3. UI SCREEN
/// 3. UI SCREEN (Modern Light Theme)
/// --------------------------------------------------------------------------
class RideMonitorScreen extends StatelessWidget {
const RideMonitorScreen({super.key});
// 🎨 الألوان العصرية (Modern Palette)
final Color backgroundColor = const Color(0xFFF4F7FE);
final Color primaryColor = const Color(0xFF4318FF);
final Color textPrimary = const Color(0xFF2B3674);
final Color textSecondary = const Color(0xFFA3AED0);
@override
Widget build(BuildContext context) {
final RideMonitorController controller = Get.put(RideMonitorController());
return Scaffold(
appBar: AppBar(
title: const Text("Admin Ride Monitor"),
backgroundColor: Colors.blueAccent,
foregroundColor: Colors.white,
actions: [
Obx(() => controller.isTracking.value
? IconButton(
icon: const Icon(Icons.close),
onPressed: controller.stopTracking,
tooltip: "Stop Tracking",
)
: const SizedBox.shrink()),
],
backgroundColor: backgroundColor,
// الإبقاء على AppBar فقط في شاشة البحث
appBar: PreferredSize(
preferredSize: const Size.fromHeight(kToolbarHeight),
child: Obx(() {
if (controller.isTracking.value)
return const SizedBox
.shrink(); // إخفاء الـ AppBar في وضع التتبع للخريطة الكاملة
return AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
centerTitle: true,
iconTheme: IconThemeData(color: textPrimary),
title: Text(
"مراقبة الرحلات",
style: TextStyle(
color: textPrimary,
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
);
}),
),
body: Obx(() {
if (!controller.isTracking.value) {
return _buildSearchForm(context, controller);
}
return _buildMapTrackingView(controller);
return _buildMapTrackingView(context, controller);
}),
);
}
// ---------------------------------------------------------------------------
// واجهة البحث (Search View)
// ---------------------------------------------------------------------------
Widget _buildSearchForm(
BuildContext context, RideMonitorController controller) {
return Center(
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Padding(
padding: const EdgeInsets.all(24.0),
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: Container(
padding: const EdgeInsets.all(32.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(30),
boxShadow: [
BoxShadow(
color: primaryColor.withOpacity(0.08),
blurRadius: 24,
offset: const Offset(0, 10),
)
],
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.map_outlined, size: 80, color: Colors.blueAccent),
const SizedBox(height: 20),
const Text(
"Track Active Ride",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: primaryColor.withOpacity(0.1),
shape: BoxShape.circle,
),
const SizedBox(height: 10),
const Text(
"Enter Driver or Passenger Phone Number",
style: TextStyle(color: Colors.grey),
child:
Icon(Icons.radar_rounded, size: 60, color: primaryColor),
),
const SizedBox(height: 30),
TextField(
const SizedBox(height: 24),
Text(
"تتبع رحلة نشطة",
style: TextStyle(
color: textPrimary,
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
"أدخل رقم هاتف السائق أو الراكب للبدء",
style: TextStyle(
color: textSecondary,
fontSize: 14,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
Container(
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.white, width: 2),
),
child: TextField(
controller: controller.phoneInputController,
keyboardType: TextInputType.phone,
textDirection: TextDirection.ltr,
style: TextStyle(
color: textPrimary,
fontSize: 16,
fontWeight: FontWeight.w600,
),
decoration: InputDecoration(
labelText: "Phone Number",
hintText: "e.g. 9639...",
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
prefixIcon: const Icon(Icons.phone),
hintText: "مثال: 0992952235...",
hintStyle: TextStyle(color: textSecondary),
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(
vertical: 18, horizontal: 20),
prefixIcon:
Icon(Icons.phone_rounded, color: primaryColor),
),
),
const SizedBox(height: 20),
),
const SizedBox(height: 32),
SizedBox(
width: double.infinity,
height: 50,
height: 56,
child: ElevatedButton(
onPressed: controller.startSearch,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blueAccent,
backgroundColor: primaryColor,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
borderRadius: BorderRadius.circular(16),
),
),
child: const Text(
"بدء المراقبة",
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
child: const Text("Start Monitoring",
style: TextStyle(color: Colors.white, fontSize: 16)),
),
),
],
),
),
),
),
);
}
Widget _buildMapTrackingView(RideMonitorController controller) {
// ---------------------------------------------------------------------------
// واجهة الخريطة (Map View)
// ---------------------------------------------------------------------------
Widget _buildMapTrackingView(
BuildContext context, RideMonitorController controller) {
return Stack(
children: [
FlutterMap(
@@ -352,10 +432,12 @@ class RideMonitorScreen extends StatelessWidget {
polylines: [
Polyline(
points: controller.routePolyline.value,
strokeWidth: 5.0,
color: Colors.blueAccent.withOpacity(0.8),
strokeWidth: 6.0,
color: primaryColor.withOpacity(0.9),
borderStrokeWidth: 2.0,
borderColor: Colors.blue[900]!,
borderColor: primaryColor.withOpacity(0.3),
strokeCap: StrokeCap.round,
strokeJoin: StrokeJoin.round,
),
],
),
@@ -363,25 +445,22 @@ class RideMonitorScreen extends StatelessWidget {
// 2. START & END MARKERS
MarkerLayer(
markers: [
// Start Point (Green Flag)
// Start Point (Green Dot)
if (controller.startPoint.value != null)
Marker(
point: controller.startPoint.value!,
width: 40,
height: 40,
child:
const Icon(Icons.flag, color: Colors.green, size: 40),
alignment: Alignment.topCenter,
width: 30,
height: 30,
child: _buildPointMarker(const Color(0xFF10B981)),
),
// End Point (Red Flag)
// End Point (Red Dot)
if (controller.endPoint.value != null)
Marker(
point: controller.endPoint.value!,
width: 40,
height: 40,
child: const Icon(Icons.flag, color: Colors.red, size: 40),
alignment: Alignment.topCenter,
width: 30,
height: 30,
child: _buildPointMarker(const Color(0xFFEF4444)),
),
// Driver Car Marker
@@ -391,30 +470,49 @@ class RideMonitorScreen extends StatelessWidget {
controller.driverLocation.value!.latitude,
controller.driverLocation.value!.longitude,
),
width: 60,
height: 60,
width: 80,
height: 80,
child: Transform.rotate(
angle: (controller.driverLocation.value!.heading *
(3.14159 / 180)),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.directions_car_filled,
color: Colors
.black, // Dark car for visibility on blue line
size: 35,
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
blurRadius: 10,
spreadRadius: 2,
)
],
),
child: Icon(
Icons.directions_car_rounded,
color: primaryColor,
size: 28,
),
),
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 4, vertical: 1),
horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.8),
borderRadius: BorderRadius.circular(4),
color: textPrimary,
borderRadius: BorderRadius.circular(6),
),
child: Text(
"${controller.driverLocation.value!.speed.toInt()} km",
"${controller.driverLocation.value!.speed.toInt()} كم",
style: const TextStyle(
fontSize: 10, fontWeight: FontWeight.bold),
color: Colors.white,
fontSize: 10,
fontWeight: FontWeight.bold,
),
textDirection: TextDirection.rtl,
),
)
],
@@ -426,88 +524,196 @@ class RideMonitorScreen extends StatelessWidget {
],
),
// LOADING OVERLAY
// زر التراجع (إيقاف التتبع) أعلى الشاشة
Positioned(
top: MediaQuery.of(context).padding.top + 10,
right: 20, // أو left حسب لغة التطبيق
child: Container(
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 10,
offset: const Offset(0, 4),
)
],
),
child: IconButton(
icon: Icon(Icons.close_rounded, color: textPrimary, size: 24),
onPressed: controller.stopTracking,
tooltip: "إيقاف المراقبة",
),
),
),
// LOADING OVERLAY (Smooth Frosted Glass like)
if (controller.isLoading.value &&
controller.driverLocation.value == null &&
controller.startPoint.value == null)
Container(
color: Colors.black45,
child: const Center(
child: CircularProgressIndicator(color: Colors.white)),
color: Colors.white.withOpacity(0.8),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(
color: primaryColor, strokeWidth: 3),
const SizedBox(height: 16),
Text(
"جاري تحديد الموقع...",
style: TextStyle(
color: textPrimary,
fontWeight: FontWeight.bold,
fontSize: 16,
),
)
],
),
),
),
// ERROR OVERLAY
if (controller.hasError.value)
Center(
child: Container(
margin: const EdgeInsets.all(20),
padding: const EdgeInsets.all(20),
margin: const EdgeInsets.all(24),
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: const [
BoxShadow(blurRadius: 10, color: Colors.black26)
]),
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 20,
offset: const Offset(0, 10),
)
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.error_outline, color: Colors.red, size: 40),
const SizedBox(height: 10),
Text(controller.errorMessage.value,
textAlign: TextAlign.center),
const SizedBox(height: 10),
ElevatedButton(
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.red.withOpacity(0.1),
shape: BoxShape.circle,
),
child: const Icon(Icons.error_outline_rounded,
color: Colors.red, size: 40),
),
const SizedBox(height: 16),
Text(
"حدث خطأ",
style: TextStyle(
color: textPrimary,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
controller.errorMessage.value,
textAlign: TextAlign.center,
style: TextStyle(color: textSecondary, height: 1.5),
),
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: controller.stopTracking,
child: const Text("Back"))
style: ElevatedButton.styleFrom(
backgroundColor: backgroundColor,
foregroundColor: textPrimary,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
padding: const EdgeInsets.symmetric(vertical: 14),
),
child: const Text("رجوع للبحث",
style: TextStyle(fontWeight: FontWeight.bold)),
),
)
],
),
),
),
// INFO CARD
// INFO CARD (Bottom Floating Card)
if (!controller.hasError.value && !controller.isLoading.value)
Positioned(
bottom: 20,
bottom: 30,
left: 20,
right: 20,
child: Card(
elevation: 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.08),
blurRadius: 24,
offset: const Offset(0, 10),
)
],
),
child: Padding(
padding: const EdgeInsets.all(16.0),
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
const CircleAvatar(
backgroundColor: Colors.blueAccent,
child: Icon(Icons.person, color: Colors.white),
Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: primaryColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(15),
),
const SizedBox(width: 12),
child: Icon(Icons.person_rounded,
color: primaryColor, size: 28),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
controller.driverName.value,
style: const TextStyle(
fontSize: 18, fontWeight: FontWeight.bold),
style: TextStyle(
color: textPrimary,
fontSize: 18,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Row(
children: [
Icon(Icons.circle,
size: 10,
color:
controller.rideStatus.value == 'Begin'
? Colors.green
: Colors.grey),
const SizedBox(width: 5),
Text(controller.rideStatus.value,
style: const TextStyle(
fontWeight: FontWeight.w600)),
Container(
width: 8,
height: 8,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: controller.rideStatus.value
.toLowerCase() ==
'begin'
? const Color(0xFF10B981)
: const Color(0xFFF59E0B),
),
),
const SizedBox(width: 6),
Text(
controller.rideStatus.value,
style: TextStyle(
color: textSecondary,
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
],
),
],
@@ -515,25 +721,53 @@ class RideMonitorScreen extends StatelessWidget {
),
],
),
const Divider(),
const Padding(
padding: EdgeInsets.symmetric(vertical: 16),
child: Divider(height: 1, thickness: 1),
),
if (controller.driverLocation.value != null)
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildInfoBadge(Icons.speed,
"${controller.driverLocation.value!.speed.toStringAsFixed(1)} km/h"),
_buildInfoBadge(
Icons.access_time,
_buildModernInfoBadge(
Icons.speed_rounded,
"${controller.driverLocation.value!.speed.toStringAsFixed(1)} كم/س",
const Color(0xFF3B82F6),
),
Container(
width: 1,
height: 30,
color: Colors.grey.withOpacity(0.2)),
_buildModernInfoBadge(
Icons.access_time_rounded,
controller.driverLocation.value!.updatedAt
.split(' ')
.last),
.last,
const Color(0xFF8B5CF6),
),
],
)
else
const Text("Connecting to driver...",
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
color: primaryColor, strokeWidth: 2),
),
const SizedBox(width: 10),
Text(
"جاري الاتصال بالسائق...",
style: TextStyle(
color: Colors.orange,
fontStyle: FontStyle.italic)),
color: primaryColor,
fontWeight: FontWeight.w600,
fontSize: 13,
),
),
],
),
],
),
),
@@ -543,14 +777,56 @@ class RideMonitorScreen extends StatelessWidget {
);
}
Widget _buildInfoBadge(IconData icon, String text) {
// --- Helper Widgets ---
Widget _buildPointMarker(Color color) {
return Container(
decoration: BoxDecoration(
color: color.withOpacity(0.3),
shape: BoxShape.circle,
),
child: Center(
child: Container(
width: 12,
height: 12,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
border: Border.all(color: Colors.white, width: 2),
boxShadow: [
BoxShadow(
color: color.withOpacity(0.5),
blurRadius: 6,
spreadRadius: 1,
)
],
),
),
),
);
}
Widget _buildModernInfoBadge(IconData icon, String text, Color iconColor) {
return Row(
children: [
Icon(icon, size: 16, color: Colors.grey[600]),
const SizedBox(width: 4),
Text(text,
Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: iconColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(icon, size: 16, color: iconColor),
),
const SizedBox(width: 8),
Text(
text,
style: TextStyle(
color: Colors.grey[800], fontWeight: FontWeight.bold)),
color: textPrimary,
fontSize: 14,
fontWeight: FontWeight.bold,
),
textDirection: TextDirection.ltr, // للحفاظ على اتجاه الأرقام
),
],
);
}

View File

@@ -1,186 +1,564 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_admin1/constant/colors.dart';
import 'package:sefer_admin1/constant/style.dart';
import 'package:sefer_admin1/constant/links.dart';
import 'package:sefer_admin1/controller/employee_controller/employee_controller.dart';
import 'package:sefer_admin1/controller/functions/launch.dart';
import 'package:sefer_admin1/views/widgets/elevated_btn.dart';
import 'package:sefer_admin1/views/widgets/my_scafold.dart';
import 'package:sefer_admin1/views/widgets/my_textField.dart';
import '../../../constant/links.dart';
import '../../../controller/functions/upload_image copy.dart';
import 'package:sefer_admin1/controller/functions/upload_image copy.dart'; // تأكد من مسار الملف الصحيح
import 'package:url_launcher/url_launcher.dart';
class EmployeePage extends StatelessWidget {
const EmployeePage({super.key});
@override
Widget build(BuildContext context) {
// حقن الكنترولر
Get.put(EmployeeController());
return GetBuilder<EmployeeController>(builder: (employeeController) {
return Scaffold(
appBar: AppBar(
title: Text('Employee Page'.tr),
),
body: ListView.builder(
itemCount: employeeController
.employee.length, // Set the item count based on the employee list
itemBuilder: (context, index) {
// Get the employee data for the current index
var employee = employeeController.employee[index];
// Return a widget to display the employee information
return Padding(
padding: const EdgeInsets.all(3.0),
child: Container(
decoration: AppStyle.boxDecoration1,
child: ListTile(
trailing: IconButton(
onPressed: () {
Get.to(() => EmployeeDetails(
index: index,
));
},
icon: Icon(
Icons.shop_two,
color: employee['status'].toString().contains('ممتاز')
? AppColor.greenColor
: AppColor.accentColor,
),
),
title: Column(
// ألوان الثيم
const Color bgColor = Color(0xFF0A0E27);
const Color cardColor = Color(0xFF1A1F3A);
const Color primaryAccent = Color(0xFF6366F1);
return Scaffold(
backgroundColor: bgColor,
body: GetBuilder<EmployeeController>(
builder: (controller) {
return CustomScrollView(
physics: const BouncingScrollPhysics(),
slivers: [
// 1. App Bar
SliverAppBar(
expandedHeight: 100,
floating: true,
pinned: true,
backgroundColor: bgColor,
elevation: 0,
flexibleSpace: FlexibleSpaceBar(
titlePadding: const EdgeInsets.only(bottom: 16),
title: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(employee['name']),
Text(
'Phone: ${employee['phone']}\nEducation: ${employee['education']}'),
Text('Status: ${employee['status']}'),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: primaryAccent.withOpacity(0.2),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(Icons.badge_rounded,
color: Colors.white, size: 18),
),
const SizedBox(width: 10),
const Text(
'الموظفون',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: Colors.white,
fontFamily: 'Segoe UI',
),
),
],
), // Display employee name
onTap: () {
// Add any action you want when the employee is tapped
),
centerTitle: true,
background: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
primaryAccent.withOpacity(0.15),
bgColor,
],
),
),
),
),
),
// 2. قائمة الموظفين
if (controller.employee.isEmpty)
const SliverFillRemaining(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.people_outline,
size: 60, color: Colors.white24),
SizedBox(height: 16),
Text("لا يوجد موظفين حالياً",
style: TextStyle(color: Colors.white54)),
],
),
),
)
else
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final employee = controller.employee[index];
return _EmployeeCard(
employee: employee,
index: index,
cardColor: cardColor,
primaryAccent: primaryAccent,
);
},
leading: IconButton(
onPressed: () {
makePhoneCall(employee['phone'].toString());
// launchCommunication(
// 'phone', employee['phone'].toString(), '');
},
icon: const Icon(Icons.phone),
childCount: controller.employee.length,
),
),
),
],
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
employeeController.id = employeeController.generateRandomId(8);
Get.to(
employeeFields(employeeController),
);
}, // Icon to display
backgroundColor: Colors.blue, // Button color (optional)
tooltip: 'Add Employee',
child: const Icon(Icons.add), // Tooltip text when long-pressed
final controller = Get.find<EmployeeController>();
controller.id = controller.generateRandomId(8);
Get.to(() => _EmployeeFormScreen(controller: controller));
},
backgroundColor: primaryAccent,
child: const Icon(Icons.person_add_rounded, color: Colors.white),
),
);
});
}
}
Scaffold employeeFields(EmployeeController employeeController) {
return Scaffold(
appBar: AppBar(),
body: Form(
key: employeeController.formKey,
child: SizedBox(
height: 500,
child: ListView(
// === بطاقة الموظف (تصميم جديد ومحسن) ===
class _EmployeeCard extends StatelessWidget {
final Map<String, dynamic> employee;
final int index;
final Color cardColor;
final Color primaryAccent;
const _EmployeeCard({
required this.employee,
required this.index,
required this.cardColor,
required this.primaryAccent,
});
@override
Widget build(BuildContext context) {
bool isExcellent = employee['status'].toString().contains('ممتاز');
Color statusColor = isExcellent ? const Color(0xFF10B981) : Colors.amber;
return Container(
margin: const EdgeInsets.only(bottom: 16),
decoration: BoxDecoration(
color: cardColor,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.white.withOpacity(0.05)),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
blurRadius: 10,
offset: const Offset(0, 4),
),
],
),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: () => Get.to(() => EmployeeDetails(index: index)),
borderRadius: BorderRadius.circular(16),
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MyElevatedButton(
title: 'front id',
onPressed: () async {
await ImageController().choosImage(AppLink.uploadEgypt,
'idFrontEmployee', employeeController.id);
}),
MyElevatedButton(
title: 'back id',
onPressed: () async {
await ImageController().choosImage(AppLink.uploadEgypt,
'idbackEmployee', employeeController.id);
}),
MyTextForm(
controller: employeeController.name,
label: 'name',
hint: 'name',
type: TextInputType.name),
MyTextForm(
controller: employeeController.education,
label: 'education',
hint: 'education',
type: TextInputType.name),
MyTextForm(
controller: employeeController.site,
label: 'site',
hint: 'site',
type: TextInputType.name),
MyTextForm(
controller: employeeController.phone,
label: 'phone',
hint: 'phone',
type: TextInputType.phone),
MyTextForm(
controller: employeeController.status,
label: 'status',
hint: 'status',
type: TextInputType.name),
// الصف العلوي: الحالة + أيقونة
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.05),
shape: BoxShape.circle,
),
child: Icon(Icons.person,
color: Colors.white.withOpacity(0.7), size: 20),
),
Flexible(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: statusColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
border:
Border.all(color: statusColor.withOpacity(0.3)),
),
child: Text(
employee['status'] ?? 'Unknown',
style: TextStyle(
color: statusColor,
fontSize: 12,
fontWeight: FontWeight.bold,
height: 1.5,
),
textAlign: TextAlign.center,
),
),
),
],
),
const SizedBox(height: 12),
// الاسم في سطر كامل ومميز
Text(
employee['name'] ?? 'Unknown',
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
height: 1.3,
),
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 12),
child: Divider(height: 1, color: Colors.white10),
),
// تفاصيل التعليم والهاتف والموقع (مع دعم تعدد الأسطر)
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildInfoRow(Icons.phone_iphone_rounded,
employee['phone'] ?? '', Colors.white54),
const SizedBox(height: 12), // مسافة أكبر بين العناصر
_buildInfoRow(
Icons.school_outlined,
employee['education'] ?? 'غير محدد',
primaryAccent),
const SizedBox(height: 12), // مسافة أكبر
_buildInfoRow(Icons.location_on_outlined,
employee['site'] ?? 'غير محدد', Colors.blueGrey),
],
),
),
// زر الاتصال الجانبي
const SizedBox(width: 16),
Material(
color: Colors.green.withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
child: InkWell(
onTap: () =>
_makePhoneCall(employee['phone'].toString()),
borderRadius: BorderRadius.circular(12),
child: Container(
padding: const EdgeInsets.all(14),
child: const Icon(Icons.call,
color: Colors.green, size: 24),
),
),
),
],
),
],
),
),
),
bottomNavigationBar: MyElevatedButton(
title: 'upload',
onPressed: () async {
if (employeeController.formKey.currentState!.validate()) {
await employeeController.addEmployee();
),
);
}
Widget _buildInfoRow(IconData icon, String text, Color iconColor) {
return Row(
crossAxisAlignment:
CrossAxisAlignment.start, // محاذاة الأيقونة مع بداية النص
children: [
Padding(
padding: const EdgeInsets.only(top: 2), // ضبط بسيط لموقع الأيقونة
child: Icon(icon, size: 16, color: iconColor.withOpacity(0.8)),
),
const SizedBox(width: 10),
Expanded(
child: Text(
text,
style: TextStyle(
color: Colors.white.withOpacity(0.7),
fontSize: 13,
height: 1.5, // تباعد الأسطر لسهولة القراءة
),
// تم إزالة maxLines و overflow للسماح بالنص بالنزول لأسطر متعددة
),
),
],
);
}
Future<void> _makePhoneCall(String phoneNumber) async {
final Uri launchUri = Uri(scheme: 'tel', path: phoneNumber);
if (await canLaunchUrl(launchUri)) {
await launchUrl(launchUri);
}
}
}
// === شاشة إضافة موظف ===
class _EmployeeFormScreen extends StatelessWidget {
final EmployeeController controller;
const _EmployeeFormScreen({required this.controller});
@override
Widget build(BuildContext context) {
const Color bgColor = Color(0xFF0A0E27);
const Color inputColor = Color(0xFF1A1F3A);
return Scaffold(
backgroundColor: bgColor,
appBar: AppBar(
title: const Text("إضافة موظف جديد",
style: TextStyle(color: Colors.white)),
backgroundColor: bgColor,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Get.back(),
),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Form(
key: controller.formKey,
child: Column(
children: [
Row(
children: [
Expanded(
child: _UploadButton(
title: "الهوية (أمام)",
icon: Icons.credit_card,
onPressed: () async {
await ImageController().choosImage(AppLink.uploadEgypt,
'idFrontEmployee', controller.id);
},
),
),
const SizedBox(width: 16),
Expanded(
child: _UploadButton(
title: "الهوية (خلف)",
icon: Icons.credit_card_outlined,
onPressed: () async {
await ImageController().choosImage(AppLink.uploadEgypt,
'idbackEmployee', controller.id);
},
),
),
],
),
const SizedBox(height: 24),
_buildModernTextField(
controller.name, "الاسم الكامل", Icons.person, inputColor),
const SizedBox(height: 16),
_buildModernTextField(
controller.phone, "رقم الهاتف", Icons.phone, inputColor,
type: TextInputType.phone),
const SizedBox(height: 16),
_buildModernTextField(controller.education, "التعليم / الملاحظات",
Icons.school, inputColor),
const SizedBox(height: 16),
_buildModernTextField(controller.site, "الموقع / العنوان",
Icons.location_on, inputColor),
const SizedBox(height: 16),
_buildModernTextField(controller.status, "الحالة (مثال: ممتاز)",
Icons.star, inputColor),
const SizedBox(height: 32),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () async {
if (controller.formKey.currentState!.validate()) {
await controller.addEmployee();
Get.back();
}
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF6366F1),
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
),
child: const Text("حفظ البيانات",
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold)),
),
),
],
),
),
),
);
}
Widget _buildModernTextField(TextEditingController controller, String hint,
IconData icon, Color fillColor,
{TextInputType type = TextInputType.text}) {
return Container(
decoration: BoxDecoration(
color: fillColor,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.white.withOpacity(0.1)),
),
child: TextFormField(
controller: controller,
keyboardType: type,
style: const TextStyle(color: Colors.white),
maxLines: null, // السماح بتعدد الأسطر عند الإدخال أيضاً
decoration: InputDecoration(
labelText: hint,
labelStyle: TextStyle(color: Colors.white.withOpacity(0.5)),
prefixIcon: Icon(icon, color: Colors.white38, size: 20),
border: InputBorder.none,
contentPadding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
),
validator: (value) =>
value == null || value.isEmpty ? 'حقل مطلوب' : null,
),
);
}
}
class _UploadButton extends StatelessWidget {
final String title;
final IconData icon;
final VoidCallback onPressed;
const _UploadButton(
{required this.title, required this.icon, required this.onPressed});
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onPressed,
borderRadius: BorderRadius.circular(12),
child: Container(
padding: const EdgeInsets.symmetric(vertical: 20),
decoration: BoxDecoration(
color: const Color(0xFF1A1F3A),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: const Color(0xFF6366F1).withOpacity(0.3),
style: BorderStyle.solid),
),
child: Column(
children: [
Icon(icon, color: const Color(0xFF6366F1), size: 30),
const SizedBox(height: 8),
Text(title,
style: const TextStyle(color: Colors.white70, fontSize: 12)),
const SizedBox(height: 4),
const Text("اضغط للرفع",
style: TextStyle(color: Colors.white38, fontSize: 10)),
],
),
),
);
}
}
// === شاشة التفاصيل ===
class EmployeeDetails extends StatelessWidget {
final int index;
const EmployeeDetails({super.key, required this.index});
@override
Widget build(BuildContext context) {
const Color bgColor = Color(0xFF0A0E27);
return Scaffold(
backgroundColor: bgColor,
appBar: AppBar(
title:
const Text('تفاصيل الموظف', style: TextStyle(color: Colors.white)),
backgroundColor: bgColor,
iconTheme: const IconThemeData(color: Colors.white),
elevation: 0,
),
body: GetBuilder<EmployeeController>(
builder: (controller) {
final employeeId = controller.employee[index]['id'];
return SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text("الهوية الأمامية",
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold)),
const SizedBox(height: 10),
_buildImageViewer(
'${AppLink.server}/card_image/idFrontEmployee-$employeeId.jpg',
),
const SizedBox(height: 30),
const Text("الهوية الخلفية",
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold)),
const SizedBox(height: 10),
_buildImageViewer(
'${AppLink.server}/card_image/idbackEmployee-$employeeId.jpg',
),
],
),
);
},
),
);
}
}
class EmployeeDetails extends StatelessWidget {
const EmployeeDetails({super.key, required this.index});
final int index;
@override
Widget build(BuildContext context) {
return MyScafolld(
title: 'Details',
isleading: true,
body: [
GetBuilder<EmployeeController>(builder: (employeeController) {
return Column(
Widget _buildImageViewer(String url) {
return Container(
width: double.infinity,
height: 220,
decoration: BoxDecoration(
color: const Color(0xFF1A1F3A),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.white.withOpacity(0.1)),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image.network(
url,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return const Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
height: 200,
width: 400,
child: Image.network(
// https: //server.sefer.click/sefer.click/sefer/card_image/idFrontEmployee-GC15188P.jpg
'https://server.sefer.click/sefer.click/sefer/card_image/idFrontEmployee-${employeeController.employee[index]['id']}.jpg'),
),
const SizedBox(
height: 10,
),
SizedBox(
height: 200,
width: 400,
child: Image.network(
'https://server.sefer.click/sefer.click/sefer/card_image/idFrontEmployee-${employeeController.employee[index]['id']}.jpg'),
)
Icon(Icons.broken_image_rounded,
color: Colors.white24, size: 50),
SizedBox(height: 8),
Text("فشل تحميل الصورة",
style: TextStyle(color: Colors.white24)),
],
),
);
})
],
},
loadingBuilder: (context, child, loadingProgress) {
if (loadingProgress == null) return child;
return const Center(
child: CircularProgressIndicator(color: Color(0xFF6366F1)));
},
),
),
);
}
}

View File

@@ -0,0 +1,266 @@
// ═══════════════════════════════════════════════════════════════
// driver_fingerprint_migration.dart
// ───────────────────────────────────────────────────────────────
// المنطق ببساطة:
// 1. خذ البصمة كما هي من DB
// 2. split('_') → احذف آخر جزء (OS version)
// 3. join('_') → encrypt → رفع
//
// مثال:
// "abc123_SamsungA51_13" → "abc123_SamsungA51" → encrypt
// "TECNO_LH7n-GL_14" → "TECNO_LH7n-GL" → encrypt
// "unknown_2412DPC0AG_15" → "unknown_2412DPC0AG" → encrypt
// ═══════════════════════════════════════════════════════════════
import 'package:flutter/material.dart';
import '../../../constant/links.dart';
import '../../../controller/functions/crud.dart';
import '../../../controller/functions/encrypt_decrypt.dart';
import '../../../print.dart';
class DriverFingerprintMigrationTool extends StatefulWidget {
const DriverFingerprintMigrationTool({super.key});
@override
State<DriverFingerprintMigrationTool> createState() =>
_DriverFingerprintMigrationToolState();
}
class _DriverFingerprintMigrationToolState
extends State<DriverFingerprintMigrationTool> {
bool _isRunning = false;
bool _isDone = false;
int _total = 0;
int _processed = 0;
int _updated = 0;
int _failed = 0;
String _currentLog = '';
static const int _batchSize = 50;
// ─────────────────────────────────────────────────────────────
// المنطق الأساسي — حذف آخر جزء بعد "_"
// ─────────────────────────────────────────────────────────────
String _removeLastSegment(String raw) {
final parts = raw.split('_');
if (parts.length <= 1) return raw; // جزء واحد — ما في شيء نحذفه
parts.removeLast();
return parts.join('_');
}
Future<void> _startMigration() async {
setState(() {
_isRunning = true;
_isDone = false;
_processed = 0;
_updated = 0;
_failed = 0;
_currentLog = 'جارٍ جلب بصمات السائقين...';
});
try {
final records = await _fetchAll();
if (records == null) {
_log('❌ فشل في جلب البيانات');
setState(() => _isRunning = false);
return;
}
_total = records.length;
_log('✅ تم جلب $_total بصمة — بدء المعالجة...');
for (int i = 0; i < records.length; i += _batchSize) {
final batch = records.skip(i).take(_batchSize).toList();
_log('⚙️ معالجة ${i + 1}${i + batch.length} من $_total');
await Future.wait(batch.map(_processSingle));
if (i + _batchSize < records.length) {
await Future.delayed(const Duration(milliseconds: 300));
}
}
_log('🎉 اكتمل!\nمحدَّث: $_updated | فاشل: $_failed');
setState(() {
_isDone = true;
_isRunning = false;
});
} catch (e) {
_log('❌ خطأ: $e');
setState(() => _isRunning = false);
}
}
Future<List<Map<String, dynamic>>?> _fetchAll() async {
try {
final response = await CRUD().post(
link: AppLink.getAllDriverFingerprints,
payload: {'admin_key': 'iuyweiruinakjbfkajkjlkmalkcxnlahd'},
);
if (response == 'failure' || response == null) return null;
final data = response['data'];
if (data is! List) return null;
return List<Map<String, dynamic>>.from(data);
} catch (e) {
Log.print('fetchAll error: $e');
return null;
}
}
Future<void> _processSingle(Map<String, dynamic> record) async {
final captainId = record['captain_id']?.toString() ?? '';
final rawFp = record['fingerPrint']?.toString() ?? '';
if (captainId.isEmpty || rawFp.isEmpty) {
setState(() {
_failed++;
_processed++;
});
return;
}
try {
// ── حذف آخر جزء (OS version) ─────────────────────────────
final String newRaw = _removeLastSegment(rawFp);
final String encrypted = EncryptionHelper.instance.encryptData(newRaw);
Log.print('🔄 [$captainId] "$rawFp" → "$newRaw" → encrypted');
// ── رفع للسيرفر ──────────────────────────────────────────
final res = await CRUD().post(
link: AppLink.updateDriverFingerprintAdmin,
payload: {
'captain_id': captainId,
'fingerprint': encrypted,
'admin_key': 'iuyweiruinakjbfkajkjlkmalkcxnlahd',
},
);
if (res != 'failure' && res?['status'] == 'success') {
setState(() {
_updated++;
_processed++;
});
} else {
setState(() {
_failed++;
_processed++;
});
}
} catch (e) {
Log.print('❌ [$captainId]: $e');
setState(() {
_failed++;
_processed++;
});
}
}
void _log(String msg) {
Log.print(msg);
setState(() => _currentLog = msg);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Driver FP Migration')),
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.orange.shade50,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.orange.shade200),
),
child: const Text(
'⚠️ تُستخدم مرة واحدة فقط\n\n'
'"abc123_Samsung_13" → "abc123_Samsung" → encrypt\n'
'"TECNO_LH7n_14" → "TECNO_LH7n" → encrypt',
style:
TextStyle(fontSize: 13, height: 1.7, fontFamily: 'monospace'),
),
),
const SizedBox(height: 24),
if (_total > 0) ...[
Text('التقدم: $_processed / $_total',
style: const TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(height: 8),
LinearProgressIndicator(
value: _total > 0 ? _processed / _total : 0,
backgroundColor: Colors.grey.shade200,
color: _isDone ? Colors.green : Colors.blue,
minHeight: 8,
),
const SizedBox(height: 16),
],
if (_processed > 0)
Row(children: [
_chip('محدَّث', _updated, Colors.green),
const SizedBox(width: 8),
_chip('فاشل', _failed, Colors.red),
]),
const SizedBox(height: 16),
if (_currentLog.isNotEmpty)
Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.grey.shade100,
borderRadius: BorderRadius.circular(8),
),
child: Text(_currentLog,
style:
const TextStyle(fontFamily: 'monospace', fontSize: 12)),
),
const Spacer(),
SizedBox(
width: double.infinity,
height: 52,
child: ElevatedButton(
onPressed: (_isRunning || _isDone) ? null : _startMigration,
style: ElevatedButton.styleFrom(
backgroundColor: _isDone ? Colors.green : Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
),
child: _isRunning
? const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
color: Colors.white, strokeWidth: 2)),
SizedBox(width: 12),
Text('جارٍ الترحيل...',
style:
TextStyle(color: Colors.white, fontSize: 16)),
],
)
: Text(
_isDone ? '✅ اكتمل الترحيل' : 'بدء ترحيل بصمات السائقين',
style: const TextStyle(color: Colors.white, fontSize: 16),
),
),
),
]),
),
);
}
Widget _chip(String label, int value, Color color) => Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: color.withOpacity(0.1),
borderRadius: BorderRadius.circular(20),
border: Border.all(color: color.withOpacity(0.3)),
),
child: Text('$label: $value',
style: TextStyle(color: color, fontWeight: FontWeight.bold)),
);
}

View File

@@ -0,0 +1,855 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sefer_admin1/constant/links.dart';
import 'package:sefer_admin1/controller/functions/crud.dart';
import 'package:sefer_admin1/main.dart';
import '../../../constant/box_name.dart';
// ─── Custom Colors ────────────────────────────────────────────────────────────
class _AppColors {
static const bg = Color(0xFF0A0D14);
static const surface = Color(0xFF111622);
static const card = Color(0xFF161D2E);
static const border = Color(0xFF1F2D4A);
static const accent = Color(0xFF00E5FF);
static const accentDim = Color(0xFF0097A7);
static const accentGlow = Color(0x2200E5FF);
static const accentDecrypt = Color(0xFF7C4DFF);
static const accentDecryptDim = Color(0xFF512DA8);
static const accentDecryptGlow = Color(0x227C4DFF);
static const textPrimary = Color(0xFFE8F0FE);
static const textSec = Color(0xFF7A8BAA);
static const success = Color(0xFF00E676);
static const error = Color(0xFFFF5252);
}
class EncryptToolPage extends StatefulWidget {
final String adminToken;
const EncryptToolPage({Key? key, required this.adminToken}) : super(key: key);
@override
State<EncryptToolPage> createState() => _EncryptToolPageState();
}
class _EncryptToolPageState extends State<EncryptToolPage>
with SingleTickerProviderStateMixin {
final TextEditingController _inputController = TextEditingController();
final TextEditingController _outputController = TextEditingController();
String _output = '';
bool _loading = false;
String? _error;
bool _isInputCopied = false;
bool _isOutputCopied = false;
late final AnimationController _glowController;
late final Animation<double> _glowAnimation;
@override
void initState() {
super.initState();
_glowController = AnimationController(
vsync: this,
duration: const Duration(seconds: 3),
)..repeat(reverse: true);
_glowAnimation = Tween<double>(begin: 0.4, end: 1.0).animate(
CurvedAnimation(parent: _glowController, curve: Curves.easeInOut),
);
}
@override
void dispose() {
_inputController.dispose();
_outputController.dispose();
_glowController.dispose();
super.dispose();
}
// ─── Logic (unchanged) ──────────────────────────────────────────────────────
Future<void> _callTool(String action) async {
FocusScope.of(context).unfocus();
setState(() {
_loading = true;
_error = null;
_output = '';
_outputController.clear();
_isInputCopied = false;
_isOutputCopied = false;
});
try {
final response = await CRUD().post(
link: '${AppLink.server}/ggg.php',
payload: {
'action': action,
'text': _inputController.text,
'admin_phone': box.read(BoxName.adminPhone) ?? '',
},
);
if (response == 'failure') {
setState(() => _error = 'حدث خطأ في الاتصال بالخادم. حاول مرة أخرى.');
} else {
if (response['status'] == 'success') {
setState(() {
_output = (response['result'] ?? '').toString();
_outputController.text = _output;
});
} else {
setState(() =>
_error = response['message']?.toString() ?? 'حدث خطأ غير معروف.');
}
}
} catch (e) {
setState(() => _error = 'مشكلة في الشبكة: $e');
} finally {
setState(() => _loading = false);
}
}
void _showSnackBar(String message, {bool isError = false}) {
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Row(
children: [
Icon(isError ? Icons.error_outline : Icons.check_circle,
color: isError ? _AppColors.error : _AppColors.success),
const SizedBox(width: 12),
Text(
message,
style: const TextStyle(
fontFamily: 'Cairo',
fontWeight: FontWeight.bold,
color: _AppColors.textPrimary,
),
),
],
),
backgroundColor:
isError ? const Color(0xFF1A0808) : const Color(0xFF081A0F),
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
side: BorderSide(
color: isError ? _AppColors.error : _AppColors.success,
width: 1,
),
),
margin: const EdgeInsets.all(16),
duration: const Duration(seconds: 2),
),
);
}
Future<void> _copyText(bool isInput) async {
final textToCopy = isInput ? _inputController.text : _outputController.text;
if (textToCopy.isEmpty) {
_showSnackBar('لا يوجد نص لنسخه!', isError: true);
return;
}
await Clipboard.setData(ClipboardData(text: textToCopy));
if (isInput) {
setState(() => _isInputCopied = true);
Future.delayed(const Duration(seconds: 2), () {
if (mounted) setState(() => _isInputCopied = false);
});
} else {
setState(() => _isOutputCopied = true);
Future.delayed(const Duration(seconds: 2), () {
if (mounted) setState(() => _isOutputCopied = false);
});
}
_showSnackBar('تم النسخ بنجاح!');
}
Future<void> _pasteText(bool isInput) async {
final clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
final textToPaste = clipboardData?.text ?? '';
if (textToPaste.isEmpty) {
_showSnackBar('الحافظة فارغة!', isError: true);
return;
}
setState(() {
if (isInput) {
_inputController.text = textToPaste;
} else {
_output = textToPaste;
_outputController.text = textToPaste;
}
});
_showSnackBar('تم اللصق بنجاح!');
}
// ─── UI Helpers ─────────────────────────────────────────────────────────────
Widget _buildActionButtons({
required bool isInput,
required bool isCopied,
Color accentColor = _AppColors.accent,
}) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
_MiniIconButton(
label: 'لصق',
icon: Icons.content_paste_rounded,
color: accentColor,
onTap: () => _pasteText(isInput),
),
const SizedBox(width: 6),
_MiniIconButton(
label: isCopied ? 'تم!' : 'نسخ',
icon: isCopied ? Icons.check_circle_rounded : Icons.copy_rounded,
color: isCopied ? _AppColors.success : accentColor,
onTap: () => _copyText(isInput),
),
],
);
}
InputDecoration _buildInputDecoration(String hint) => InputDecoration(
hintText: hint,
hintStyle: const TextStyle(color: _AppColors.textSec, fontSize: 14),
filled: true,
fillColor: const Color(0xFF0C1120),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: BorderSide.none,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(color: _AppColors.border, width: 1),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(color: _AppColors.accent, width: 1.5),
),
contentPadding: const EdgeInsets.all(16),
);
// ─── Build ──────────────────────────────────────────────────────────────────
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: _AppColors.bg,
body: Stack(
children: [
// ── Ambient background glow ──────────────────────────────────────────
Positioned(
top: -120,
left: -80,
child: AnimatedBuilder(
animation: _glowAnimation,
builder: (_, __) => Opacity(
opacity: _glowAnimation.value * 0.25,
child: Container(
width: 380,
height: 380,
decoration: const BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(
colors: [Color(0xFF00E5FF), Colors.transparent],
),
),
),
),
),
),
Positioned(
bottom: -100,
right: -60,
child: AnimatedBuilder(
animation: _glowAnimation,
builder: (_, __) => Opacity(
opacity: (1 - _glowAnimation.value) * 0.2,
child: Container(
width: 320,
height: 320,
decoration: const BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(
colors: [Color(0xFF7C4DFF), Colors.transparent],
),
),
),
),
),
),
// ── Content ──────────────────────────────────────────────────────────
SafeArea(
child: Column(
children: [
// ── AppBar ─────────────────────────────────────────────────────
Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 16, 0),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back_ios_new_rounded,
color: _AppColors.textSec, size: 20),
onPressed: () => Navigator.pop(context),
),
const Spacer(),
Row(
children: [
Container(
width: 8,
height: 8,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: _AppColors.accent,
boxShadow: [
BoxShadow(
color: _AppColors.accentGlow,
blurRadius: 8,
spreadRadius: 2,
),
],
),
),
const SizedBox(width: 10),
const Text(
'أداة التشفير',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w700,
color: _AppColors.textPrimary,
letterSpacing: 0.5,
),
),
],
),
const Spacer(),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: _AppColors.accentGlow,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: _AppColors.accent.withOpacity(0.3)),
),
child: const Text(
'AES-256',
style: TextStyle(
color: _AppColors.accent,
fontSize: 11,
fontWeight: FontWeight.bold,
letterSpacing: 1.5,
),
),
),
],
),
),
// ── Scrollable body ───────────────────────────────────────────
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(20, 24, 20, 32),
physics: const BouncingScrollPhysics(),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 650),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// ─── Input Card ─────────────────────────────────────
_GlassCard(
borderColor: _AppColors.accent.withOpacity(0.2),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Header
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: _AppColors.accentGlow,
borderRadius:
BorderRadius.circular(10),
),
child: const Icon(
Icons.text_fields_rounded,
color: _AppColors.accent,
size: 18),
),
const SizedBox(width: 12),
const Text(
'النص الأصلي',
style: TextStyle(
color: _AppColors.textPrimary,
fontSize: 15,
fontWeight: FontWeight.w700,
),
),
],
),
_buildActionButtons(
isInput: true,
isCopied: _isInputCopied,
accentColor: _AppColors.accent,
),
],
),
const SizedBox(height: 16),
// Input field
TextField(
controller: _inputController,
maxLines: 5,
minLines: 3,
textDirection: TextDirection.ltr,
style: const TextStyle(
color: _AppColors.textPrimary,
fontSize: 15,
height: 1.6,
fontFamily: 'monospace',
),
onTap: () {
if (_inputController.text.isNotEmpty) {
_inputController.selection =
TextSelection(
baseOffset: 0,
extentOffset:
_inputController.text.length,
);
}
},
decoration: _buildInputDecoration(
'اكتب أو الصق النص هنا...'),
),
const SizedBox(height: 24),
// Action buttons row
Row(
children: [
// Encrypt
Expanded(
child: _ActionButton(
label: 'تشفير',
icon: Icons.lock_rounded,
isLoading: _loading,
onPressed: _loading
? null
: () => _callTool('encrypt'),
gradient: const LinearGradient(
colors: [
Color(0xFF00B4D8),
Color(0xFF00E5FF)
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
glowColor: _AppColors.accentGlow,
borderColor: _AppColors.accent,
),
),
const SizedBox(width: 14),
// Decrypt
Expanded(
child: _ActionButton(
label: 'فك التشفير',
icon: Icons.lock_open_rounded,
isLoading: _loading,
onPressed: _loading
? null
: () => _callTool('decrypt'),
gradient: const LinearGradient(
colors: [
Color(0xFF5B2EA6),
Color(0xFF7C4DFF)
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
glowColor:
_AppColors.accentDecryptGlow,
borderColor: _AppColors.accentDecrypt,
),
),
],
),
],
),
),
// ─── Error message ───────────────────────────────────
AnimatedSize(
duration: const Duration(milliseconds: 300),
child: _error != null
? Container(
margin: const EdgeInsets.only(top: 16),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: const Color(0xFF1A0808),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: _AppColors.error
.withOpacity(0.4)),
),
child: Row(
children: [
const Icon(
Icons.error_outline_rounded,
color: _AppColors.error,
size: 20),
const SizedBox(width: 12),
Expanded(
child: Text(
_error!,
style: const TextStyle(
color: _AppColors.error,
fontWeight: FontWeight.w600,
fontSize: 14,
),
),
),
],
),
)
: const SizedBox.shrink(),
),
// ─── Output Card ─────────────────────────────────────
const SizedBox(height: 20),
_GlassCard(
borderColor:
_AppColors.accentDecrypt.withOpacity(0.25),
headerWidget: Container(
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 14),
decoration: const BoxDecoration(
color: Color(0xFF16102A),
borderRadius: BorderRadius.vertical(
top: Radius.circular(20)),
),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: _AppColors.accentDecryptGlow,
borderRadius:
BorderRadius.circular(10),
),
child: const Icon(
Icons.shield_rounded,
color: _AppColors.accentDecrypt,
size: 18),
),
const SizedBox(width: 12),
const Text(
'النتيجة',
style: TextStyle(
color: _AppColors.textPrimary,
fontSize: 15,
fontWeight: FontWeight.w700,
),
),
],
),
_buildActionButtons(
isInput: false,
isCopied: _isOutputCopied,
accentColor: _AppColors.accentDecrypt,
),
],
),
),
child: Padding(
padding: const EdgeInsets.all(20),
child: TextField(
controller: _outputController,
readOnly: true,
maxLines: 5,
minLines: 3,
textDirection: TextDirection.ltr,
style: const TextStyle(
color: _AppColors.textPrimary,
fontSize: 15,
height: 1.6,
fontFamily: 'monospace',
letterSpacing: 0.5,
),
decoration: const InputDecoration(
hintText: 'ستظهر النتيجة هنا...',
hintStyle: TextStyle(
color: _AppColors.textSec,
fontSize: 14),
border: InputBorder.none,
isDense: true,
contentPadding: EdgeInsets.zero,
),
onTap: () {
if (_outputController.text.isNotEmpty) {
_outputController.selection =
TextSelection(
baseOffset: 0,
extentOffset:
_outputController.text.length,
);
}
},
),
),
),
// ─── Footer hint ─────────────────────────────────────
const SizedBox(height: 24),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.info_outline_rounded,
color: _AppColors.textSec, size: 13),
const SizedBox(width: 6),
const Text(
'البيانات مشفرة بالكامل ولا تُخزَّن على الخادم',
style: TextStyle(
color: _AppColors.textSec,
fontSize: 12,
),
),
],
),
],
),
),
),
),
),
],
),
),
],
),
);
}
}
// ─── Reusable Widgets ──────────────────────────────────────────────────────────
/// Glass card with optional custom header widget
class _GlassCard extends StatelessWidget {
final Widget child;
final Widget? headerWidget;
final Color borderColor;
const _GlassCard({
required this.child,
this.headerWidget,
this.borderColor = _AppColors.border,
});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: _AppColors.card,
borderRadius: BorderRadius.circular(22),
border: Border.all(color: borderColor, width: 1.2),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.35),
blurRadius: 24,
offset: const Offset(0, 8),
),
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(22),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (headerWidget != null) headerWidget!,
if (headerWidget == null)
Padding(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 0),
child: child,
)
else
child,
if (headerWidget == null) const SizedBox(height: 20),
],
),
),
);
}
}
/// Gradient action button with glow
class _ActionButton extends StatefulWidget {
final String label;
final IconData icon;
final bool isLoading;
final VoidCallback? onPressed;
final Gradient gradient;
final Color glowColor;
final Color borderColor;
const _ActionButton({
required this.label,
required this.icon,
required this.isLoading,
required this.onPressed,
required this.gradient,
required this.glowColor,
required this.borderColor,
});
@override
State<_ActionButton> createState() => _ActionButtonState();
}
class _ActionButtonState extends State<_ActionButton>
with SingleTickerProviderStateMixin {
late final AnimationController _ctrl;
late final Animation<double> _scale;
@override
void initState() {
super.initState();
_ctrl = AnimationController(
vsync: this, duration: const Duration(milliseconds: 120));
_scale = Tween<double>(begin: 1.0, end: 0.95)
.animate(CurvedAnimation(parent: _ctrl, curve: Curves.easeOut));
}
@override
void dispose() {
_ctrl.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTapDown: (_) => _ctrl.forward(),
onTapUp: (_) => _ctrl.reverse(),
onTapCancel: () => _ctrl.reverse(),
onTap: widget.onPressed,
child: AnimatedBuilder(
animation: _scale,
builder: (_, child) =>
Transform.scale(scale: _scale.value, child: child),
child: AnimatedOpacity(
opacity: widget.onPressed == null ? 0.4 : 1.0,
duration: const Duration(milliseconds: 200),
child: Container(
padding: const EdgeInsets.symmetric(vertical: 16),
decoration: BoxDecoration(
gradient: widget.gradient,
borderRadius: BorderRadius.circular(14),
boxShadow: [
BoxShadow(
color: widget.glowColor,
blurRadius: 16,
spreadRadius: 1,
offset: const Offset(0, 4),
),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: widget.isLoading
? [
const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
color: Colors.white, strokeWidth: 2),
),
]
: [
Icon(widget.icon, color: Colors.white, size: 18),
const SizedBox(width: 8),
Text(
widget.label,
style: const TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.w700,
letterSpacing: 0.3,
),
),
],
),
),
),
),
);
}
}
/// Small inline icon button (copy/paste)
class _MiniIconButton extends StatelessWidget {
final String label;
final IconData icon;
final Color color;
final VoidCallback onTap;
const _MiniIconButton({
required this.label,
required this.icon,
required this.color,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: color.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: color.withOpacity(0.25)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, color: color, size: 14),
const SizedBox(width: 5),
Text(
label,
style: TextStyle(
color: color,
fontWeight: FontWeight.bold,
fontSize: 12,
),
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,355 @@
// ═══════════════════════════════════════════════════════════════
// fingerprint_migration.dart
// ───────────────────────────────────────────────────────────────
// أداة ترحيل البصمات القديمة للنظام الجديد
// ───────────────────────────────────────────────────────────────
// المشكلة:
// البصمة القديمة = encrypt(androidId_model_osVersion)
// البصمة الجديدة = encrypt(androidId_model)
//
// الحل:
// 1. نجيب كل البصمات من السيرفر (batch 50 في المرة)
// 2. نفك تشفير كل بصمة بـ EncryptionHelper
// 3. نحذف آخر جزء (osVersion) مع الـ _ قبله
// 4. نعيد التشفير
// 5. نرفع البصمة المحدّثة للسيرفر
//
// يُستخدم مرة واحدة فقط ثم يُحذف من التطبيق
// ═══════════════════════════════════════════════════════════════
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../../../constant/links.dart';
import '../../../controller/functions/crud.dart';
import '../../../controller/functions/encrypt_decrypt.dart';
import '../../../print.dart';
class FingerprintMigrationTool extends StatefulWidget {
const FingerprintMigrationTool({super.key});
@override
State<FingerprintMigrationTool> createState() =>
_FingerprintMigrationToolState();
}
class _FingerprintMigrationToolState extends State<FingerprintMigrationTool> {
// ── حالة الترحيل ──────────────────────────────────────────
bool _isRunning = false;
bool _isDone = false;
int _total = 0;
int _processed = 0;
int _updated = 0; // بصمات تم تحديثها
int _skipped = 0; // بصمات كانت بالفعل بالنظام الجديد
int _failed = 0; // فشل في المعالجة
String _currentLog = '';
static const int _batchSize = 50;
// ─────────────────────────────────────────────────────────────
// الدالة الرئيسية للترحيل
// ─────────────────────────────────────────────────────────────
Future<void> _startMigration() async {
setState(() {
_isRunning = true;
_isDone = false;
_processed = 0;
_updated = 0;
_skipped = 0;
_failed = 0;
_currentLog = 'جارٍ جلب البصمات من السيرفر...';
});
try {
// ── 1. جلب كل البصمات من السيرفر ──────────────────────
final allFingerprints = await _fetchAllFingerprints();
if (allFingerprints == null) {
_log('❌ فشل في جلب البيانات من السيرفر');
setState(() => _isRunning = false);
return;
}
_total = allFingerprints.length;
_log('✅ تم جلب $_total بصمة — بدء المعالجة...');
// ── 2. معالجة على batches ──────────────────────────────
for (int i = 0; i < allFingerprints.length; i += _batchSize) {
final batch = allFingerprints.skip(i).take(_batchSize).toList();
_log('⚙️ معالجة ${i + 1}${i + batch.length} من $_total');
// معالجة الـ batch بالتوازي
await Future.wait(
batch.map((record) => _processSingleRecord(record)),
);
// استراحة قصيرة بين الـ batches لحماية السيرفر
if (i + _batchSize < allFingerprints.length) {
await Future.delayed(const Duration(milliseconds: 300));
}
}
_log('🎉 اكتمل الترحيل!\n'
'محدَّث: $_updated | متجاوز: $_skipped | فاشل: $_failed');
setState(() {
_isDone = true;
_isRunning = false;
});
} catch (e) {
_log('❌ خطأ عام: $e');
setState(() => _isRunning = false);
}
}
// ─────────────────────────────────────────────────────────────
// جلب كل البصمات من السيرفر
// ─────────────────────────────────────────────────────────────
Future<List<Map<String, dynamic>>?> _fetchAllFingerprints() async {
try {
final response = await CRUD().post(
link: AppLink.getAllFingerprints, // أضفه في AppLink
payload: {
'admin_key': 'iuyweiruinakjbfkajkjlkmalkcxnlahd'
}, // مفتاح أمان للـ endpoint
);
if (response == 'failure' || response == null) return null;
final data = response['data'];
if (data is! List) return null;
return List<Map<String, dynamic>>.from(data);
} catch (e) {
Log.print('fetchAllFingerprints error: $e');
return null;
}
}
// ─────────────────────────────────────────────────────────────
// معالجة بصمة واحدة
// ─────────────────────────────────────────────────────────────
Future<void> _processSingleRecord(Map<String, dynamic> record) async {
final String passengerID = record['passengerID']?.toString() ?? '';
final String encryptedFp = record['fingerPrint']?.toString() ?? '';
final String userType = record['userType']?.toString() ?? 'passenger';
if (passengerID.isEmpty || encryptedFp.isEmpty) {
setState(() {
_failed++;
_processed++;
});
return;
}
try {
// ── فك التشفير ────────────────────────────────────────
final String rawFp = EncryptionHelper.instance.decryptData(encryptedFp);
// ── تحليل البصمة ──────────────────────────────────────
// الشكل القديم: "androidId_model_osVersion" (3 أجزاء أو أكثر)
// الشكل الجديد: "androidId_model" (جزءان فقط)
final List<String> parts = rawFp.split('_');
if (parts.length <= 2) {
// البصمة بالفعل بالنظام الجديد — تجاوزها
setState(() {
_skipped++;
_processed++;
});
return;
}
// ── حذف آخر جزء (osVersion) ──────────────────────────
// مثال: "abc123_SamsungA51_13" → "abc123_SamsungA51"
// نأخذ أول جزأين فقط بغض النظر عن عدد الأجزاء
final String newRawFp = '${parts[0]}_${parts[1]}';
// ── إعادة التشفير ─────────────────────────────────────
final String newEncryptedFp =
EncryptionHelper.instance.encryptData(newRawFp);
// ── رفع البصمة الجديدة للسيرفر ───────────────────────
final response = await CRUD().post(
link: AppLink.updateFingerprintAdmin, // أضفه في AppLink
payload: {
'passengerID': passengerID,
'fingerprint': newEncryptedFp,
'userType': userType,
'admin_key': 'iuyweiruinakjbfkajkjlkmalkcxnlahd',
},
);
if (response != 'failure' && response?['status'] == 'success') {
setState(() {
_updated++;
_processed++;
});
Log.print('✅ Updated: $passengerID | $rawFp$newRawFp');
} else {
setState(() {
_failed++;
_processed++;
});
Log.print('❌ Failed update: $passengerID');
}
} catch (e) {
// فشل فك التشفير أو إعادة التشفير
setState(() {
_failed++;
_processed++;
});
Log.print('❌ Process error for $passengerID: $e');
}
}
void _log(String message) {
Log.print(message);
setState(() => _currentLog = message);
}
// ─────────────────────────────────────────────────────────────
// UI
// ─────────────────────────────────────────────────────────────
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Fingerprint Migration Tool')),
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// ── شرح الأداة ──────────────────────────────────
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.orange.shade50,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.orange.shade200),
),
child: const Text(
'⚠️ هذه الأداة تُستخدم مرة واحدة فقط\n'
'تقوم بتحديث بصمات الأجهزة القديمة\n'
'لتكون متوافقة مع النظام الجديد (بدون OS version)',
style: TextStyle(fontSize: 14, height: 1.6),
),
),
Container(
child: TextButton(
onPressed: () {
print(EncryptionHelper.instance.decryptData(
'dab40749cdecbfddf4696566448b384f0d272705b08b4ff779e085fbf3257026'));
},
child: Text(
"Decrypt Test",
),
),
),
Container(
child: TextButton(
onPressed: () {
print(EncryptionHelper.instance.encryptData(
'1B501143-C579-461C-B556-4E8B390EEFE1_iPhone'));
},
child: Text(
"Encrypt Test",
),
),
),
const SizedBox(height: 24),
// ── شريط التقدم ─────────────────────────────────
if (_total > 0) ...[
Text('التقدم: $_processed / $_total'),
const SizedBox(height: 8),
LinearProgressIndicator(
value: _total > 0 ? _processed / _total : 0,
backgroundColor: Colors.grey.shade200,
color: _isDone ? Colors.green : Colors.blue,
),
const SizedBox(height: 16),
],
// ── إحصائيات ────────────────────────────────────
if (_processed > 0)
Row(children: [
_statChip('محدَّث', _updated, Colors.green),
const SizedBox(width: 8),
_statChip('متجاوز', _skipped, Colors.blue),
const SizedBox(width: 8),
_statChip('فاشل', _failed, Colors.red),
]),
const SizedBox(height: 16),
// ── السجل الحالي ─────────────────────────────────
if (_currentLog.isNotEmpty)
Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.grey.shade100,
borderRadius: BorderRadius.circular(8),
),
child: Text(_currentLog,
style: const TextStyle(fontFamily: 'monospace')),
),
const Spacer(),
// ── زر التشغيل ──────────────────────────────────
SizedBox(
width: double.infinity,
height: 50,
child: ElevatedButton(
onPressed: (_isRunning || _isDone) ? null : _startMigration,
style: ElevatedButton.styleFrom(
backgroundColor: _isDone ? Colors.green : Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
),
child: _isRunning
? const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
color: Colors.white, strokeWidth: 2),
),
SizedBox(width: 12),
Text('جارٍ الترحيل...',
style: TextStyle(color: Colors.white)),
],
)
: Text(
_isDone ? '✅ اكتمل الترحيل' : 'بدء الترحيل',
style:
const TextStyle(color: Colors.white, fontSize: 16),
),
),
),
],
),
),
);
}
Widget _statChip(String label, int value, Color color) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: color.withOpacity(0.1),
borderRadius: BorderRadius.circular(20),
border: Border.all(color: color.withOpacity(0.3)),
),
child: Text('$label: $value',
style: TextStyle(color: color, fontWeight: FontWeight.bold)),
);
}
}

View File

@@ -128,14 +128,8 @@ class _ErrorListPageState extends State<ErrorListPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[100],
appBar: AppBar(
title: const Text('سجل الأخطاء'),
backgroundColor: Colors.white,
foregroundColor: Colors.black,
elevation: 1.0,
centerTitle: true,
),
backgroundColor: const Color(0xFFF0F4F8),
appBar: _buildAppBar(),
body: Column(
children: [
_SearchBar(
@@ -151,22 +145,84 @@ class _ErrorListPageState extends State<ErrorListPage> {
);
}
PreferredSizeWidget _buildAppBar() {
return AppBar(
elevation: 0,
backgroundColor: const Color(0xFF0F172A),
foregroundColor: Colors.white,
centerTitle: true,
title: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.white.withOpacity(0.2)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.error_outline, color: Colors.red, size: 22),
const SizedBox(width: 8),
const Text(
"سجل الأخطاء",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
],
),
),
);
}
Widget _buildBody() {
if (_loading) {
return const Center(child: CircularProgressIndicator());
return const Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF0F172A)),
),
);
}
if (_errorMsg != null) {
return Center(
child: Text(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error_outline, size: 64, color: Colors.red.shade300),
const SizedBox(height: 16),
Text(
_errorMsg!,
style: TextStyle(color: Colors.red[700]),
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.red.shade700,
fontSize: 14,
),
),
],
),
);
}
if (_items.isEmpty) {
return const Center(child: Text('لا توجد سجلات'));
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.check_circle_outline,
size: 64,
color: Colors.green.shade300,
),
const SizedBox(height: 16),
const Text(
'لا توجد سجلات أخطاء',
style: TextStyle(fontSize: 16, color: Colors.grey),
),
],
),
);
}
return RefreshIndicator(
@@ -177,19 +233,25 @@ class _ErrorListPageState extends State<ErrorListPage> {
await _fetchLast20();
}
},
color: const Color(0xFF0F172A),
child: ListView.builder(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
itemCount: _items.length,
itemBuilder: (context, index) {
final e = _items[index];
return _ErrorTile(e);
return _ErrorTile(_items[index], index);
},
),
);
}
@override
void dispose() {
_phoneCtrl.dispose();
super.dispose();
}
}
class _SearchBar extends StatelessWidget {
class _SearchBar extends StatefulWidget {
final TextEditingController controller;
final VoidCallback onSearch;
final VoidCallback onClear;
@@ -200,40 +262,132 @@ class _SearchBar extends StatelessWidget {
required this.onClear,
});
@override
State<_SearchBar> createState() => _SearchBarState();
}
class _SearchBarState extends State<_SearchBar> {
bool _isFocused = false;
@override
Widget build(BuildContext context) {
return Card(
margin: const EdgeInsets.all(12),
elevation: 2,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
child: Row(
return Container(
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.white, Colors.grey.shade50],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.08),
blurRadius: 16,
spreadRadius: 2,
)
],
),
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Focus(
onFocusChange: (focused) {
setState(() => _isFocused = focused);
},
child: TextField(
controller: controller,
controller: widget.controller,
keyboardType: TextInputType.phone,
onSubmitted: (_) => onSearch(),
decoration: const InputDecoration(
hintText: 'بحث برقم الهاتف...',
prefixIcon: Icon(Icons.search),
border: InputBorder.none,
textDirection: TextDirection.rtl,
onSubmitted: (_) => widget.onSearch(),
style: const TextStyle(fontSize: 15),
decoration: InputDecoration(
hintText: 'بحث برقم الهاتف',
hintStyle: TextStyle(color: Colors.grey.shade400),
prefixIcon: Icon(
Icons.search,
color: _isFocused
? const Color(0xFF0F172A)
: Colors.grey.shade400,
),
suffixIcon: widget.controller.text.isNotEmpty
? InkWell(
onTap: () {
widget.controller.clear();
setState(() {});
},
child: Icon(Icons.close,
color: Colors.grey.shade400, size: 20),
)
: null,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
BorderSide(color: Colors.grey.shade300, width: 1),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
BorderSide(color: Colors.grey.shade300, width: 1),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(
color: Color(0xFF0F172A),
width: 2,
),
),
filled: true,
fillColor: Colors.white,
contentPadding: const EdgeInsets.symmetric(vertical: 12),
),
onChanged: (_) => setState(() {}),
),
),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: onSearch,
child: const Text('بحث'),
onPressed: widget.onSearch,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF0F172A),
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(horizontal: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
elevation: 0,
),
child: const Row(
children: [
Icon(Icons.search, size: 18),
SizedBox(width: 6),
Text("بحث"),
],
),
),
const SizedBox(width: 8),
TextButton(
onPressed: onClear,
child: const Text('مسح'),
OutlinedButton(
onPressed: widget.onClear,
style: OutlinedButton.styleFrom(
foregroundColor: const Color(0xFF0F172A),
side: const BorderSide(
color: Color(0xFF0F172A),
width: 1.5,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
padding: const EdgeInsets.symmetric(horizontal: 12),
),
child: const Icon(Icons.refresh, size: 20),
),
],
),
],
),
);
}
@@ -241,112 +395,265 @@ class _SearchBar extends StatelessWidget {
class _ErrorTile extends StatelessWidget {
final ErrorLog item;
const _ErrorTile(this.item);
final int index;
const _ErrorTile(this.item, this.index);
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
// تحديد الألوان والأيقونات بناءً على نوع المستخدم
final isDriver = item.userType.toLowerCase().contains('driver') ||
item.userType.toLowerCase().contains('سائق');
// تحديد الألوان بناءً على نوع المستخدم
Color? typeBgColor;
Color? typeTextColor;
final userTypeColor =
isDriver ? const Color(0xFF10B981) : const Color(0xFFF59E0B);
final userTypeIcon = isDriver ? Icons.directions_car : Icons.person;
final userTypeLabel = isDriver ? "سائق" : "راكب";
final type = item.userType.toLowerCase();
if (type.contains('driver') || type.contains('سائق')) {
typeBgColor = Colors.green.shade100;
typeTextColor = Colors.green.shade800;
} else if (type.contains('passenger') || type.contains('راكب')) {
typeBgColor = Colors.amber.shade100; // لون ذهبي/أصفر
typeTextColor = Colors.amber.shade900;
}
final userTypeBgColor = isDriver
? const Color(0xFF10B981).withOpacity(0.1)
: const Color(0xFFF59E0B).withOpacity(0.1);
return Card(
return Container(
margin: const EdgeInsets.only(bottom: 12),
elevation: 2,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Padding(
padding: const EdgeInsets.all(12.0),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.white, Colors.grey.shade50],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.grey.shade200, width: 1),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.06),
blurRadius: 12,
spreadRadius: 1,
)
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Stack(
children: [
// خط علوي ملون
Positioned(
top: 0,
left: 0,
right: 0,
child: Container(
height: 4,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
const Color(0xFFEF4444),
Colors.red.shade400,
],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
),
),
),
),
Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
// السطر الأول: نص الخطأ (قابل للنسخ)
// الصف الأول: رقم الخطأ ونوع المستخدم
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 6,
),
decoration: BoxDecoration(
color: userTypeBgColor,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: userTypeColor, width: 1),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(userTypeIcon, size: 14, color: userTypeColor),
const SizedBox(width: 4),
Text(
userTypeLabel,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: userTypeColor,
),
),
],
),
),
Text(
'#${item.id}',
style: TextStyle(
fontSize: 12,
color: Colors.grey.shade500,
fontWeight: FontWeight.w500,
),
),
],
),
const SizedBox(height: 12),
// عنوان الخطأ (قابل للنسخ)
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.red.shade50,
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: Colors.red.shade200,
width: 1,
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.warning_amber_rounded,
size: 18, color: Colors.red.shade600),
const SizedBox(width: 8),
Expanded(
child: SelectableText(
item.error.isEmpty ? '(بدون عنوان)' : item.error,
style: theme.textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.bold,
color: Colors.red.shade900,
height: 1.4,
),
),
),
// تم إزالة _StatusPill (ويدجت الحالة New) من هنا
],
),
const SizedBox(height: 8),
// تفاصيل مختصرة (قابل للنسخ)
if (item.details.isNotEmpty)
SelectableText(
item.details,
style: theme.textTheme.bodyMedium
?.copyWith(color: Colors.grey[700]),
),
const SizedBox(height: 12),
// التفاصيل (إن وجدت)
if (item.details.isNotEmpty) ...[
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.grey.shade50,
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: Colors.grey.shade200,
width: 1,
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.info_outline,
size: 16, color: Colors.grey.shade600),
const SizedBox(width: 8),
Expanded(
child: SelectableText(
item.details,
style: TextStyle(
fontSize: 12,
color: Colors.grey.shade700,
height: 1.4,
),
),
),
],
),
),
const SizedBox(height: 12),
],
// معلومات تقنية
Wrap(
spacing: 8,
spacing: 6,
runSpacing: 6,
alignment: WrapAlignment.end,
children: [
_KV('الهاتف', item.phone),
_KV('المستخدم', item.userId),
// تمرير الألوان المخصصة لنوع المستخدم
_KV(
'النوع',
item.userType,
bgColor: typeBgColor,
textColor: typeTextColor,
_buildInfoBadge(
icon: Icons.phone,
label: 'الهاتف',
value: item.phone,
color: Colors.blue,
),
_buildInfoBadge(
icon: Icons.person_outline,
label: 'المعرف',
value: item.userId,
color: Colors.purple,
),
_buildInfoBadge(
icon: Icons.devices,
label: 'Path',
value: item.device,
color: Colors.orange,
),
_buildInfoBadge(
icon: Icons.schedule,
label: 'التاريخ',
value: item.createdAt,
color: Colors.teal,
),
_KV('الجهاز', item.device),
_KV('التاريخ', item.createdAt),
_KV('ID', item.id),
],
),
],
),
),
],
),
),
);
}
}
class _KV extends StatelessWidget {
final String k;
final String v;
final Color? bgColor;
final Color? textColor;
const _KV(this.k, this.v, {this.bgColor, this.textColor});
@override
Widget build(BuildContext context) {
Widget _buildInfoBadge({
required IconData icon,
required String label,
required String value,
required Color color,
}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: bgColor ?? Colors.grey[200],
color: color.withOpacity(0.08),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: color.withOpacity(0.3), width: 1),
),
child: Text.rich(TextSpan(
style: TextStyle(fontSize: 11, color: textColor ?? Colors.grey[600]),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
TextSpan(text: "$k: "),
Icon(icon, size: 13, color: color),
const SizedBox(width: 4),
Flexible(
child: Text.rich(
TextSpan(
text: v.isEmpty ? '' : v,
children: [
TextSpan(
text: "$label: ",
style: TextStyle(
fontSize: 10,
color: color.withOpacity(0.7),
fontWeight: FontWeight.w500,
),
),
TextSpan(
text: value.isEmpty ? '' : value,
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: textColor ?? Colors.grey[800],
color: color,
),
),
],
)),
),
),
),
],
),
);
}
}

View File

@@ -1,71 +1,529 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:sefer_admin1/constant/links.dart';
import 'package:sefer_admin1/controller/functions/crud.dart';
import 'package:sefer_admin1/views/widgets/my_textField.dart';
import '../../print.dart';
// ══════════════════════════════════════════════════════════════
// DESIGN TOKENS (same as AdminHomePage)
// ══════════════════════════════════════════════════════════════
const Color _bg = Color(0xFF0D1117);
const Color _surface = Color(0xFF161B22);
const Color _surfaceElevated = Color(0xFF1C2333);
const Color _accent = Color(0xFF00D4AA);
const Color _danger = Color(0xFFFF5370);
const Color _warning = Color(0xFFFFCB6B);
const Color _info = Color(0xFF82AAFF);
const Color _textPrimary = Color(0xFFE6EDF3);
const Color _textSecondary = Color(0xFF7D8590);
const Color _divider = Color(0xFF21262D);
class PackageUpdateScreen extends StatelessWidget {
PackageUpdateScreen({super.key});
final PackageController packageController = Get.put(PackageController());
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Package Update'),
),
body: GetBuilder<PackageController>(builder: (packageController) {
return Center(
child: ListView.builder(
itemCount: packageController.packages.length,
backgroundColor: _bg,
appBar: _buildAppBar(),
body: GetBuilder<PackageController>(
builder: (controller) {
if (controller.isLoading.value) {
return const Center(
child: CircularProgressIndicator(color: _accent, strokeWidth: 2),
);
}
if (controller.packages.isEmpty) {
return _buildEmptyState();
}
return ListView.separated(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 40),
itemCount: controller.packages.length,
separatorBuilder: (_, __) => const SizedBox(height: 10),
itemBuilder: (context, index) {
var package = packageController.packages[index];
return ListTile(
title: Text(package['appName']),
subtitle: Text(
'Platform: ${package['platform']} \nVersion: ${package['version']}'),
trailing: const Icon(Icons.update),
onTap: () {
Get.defaultDialog(
title: 'Update',
middleText: '',
content: Column(
final package = controller.packages[index];
return _buildPackageCard(context, package, controller);
},
);
},
),
);
}
// ─────────────────────────── APP BAR ───────────────────────────
PreferredSizeWidget _buildAppBar() {
return AppBar(
backgroundColor: _bg,
elevation: 0,
surfaceTintColor: Colors.transparent,
leading: GestureDetector(
onTap: () => Get.back(),
child: Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: _surface,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: _divider),
),
child: const Icon(Icons.arrow_back_ios_new_rounded,
color: _textSecondary, size: 16),
),
),
title: Row(
children: [
Text(package['appName']),
Text(package['platform']),
Text(package['version']),
MyTextForm(
controller: packageController.versionController,
label: package['version'].toString(),
hint: package['version'].toString(),
type: const TextInputType.numberWithOptions(
decimal: true),
Container(
padding: const EdgeInsets.all(7),
decoration: BoxDecoration(
color: _accent.withOpacity(0.12),
borderRadius: BorderRadius.circular(9),
border: Border.all(color: _accent.withOpacity(0.25)),
),
child: const Icon(Icons.system_update_rounded,
color: _accent, size: 16),
),
const SizedBox(width: 10),
const Text(
'تحديث التطبيق',
style: TextStyle(
color: _textPrimary,
fontSize: 17,
fontWeight: FontWeight.w600,
),
),
],
),
onConfirm: () async {
await packageController.updatePackages(
package['id'].toString(),
packageController.versionController.text.toString(),
);
},
onCancel: () {},
);
},
);
},
actions: [
GestureDetector(
onTap: () => packageController.fetchPackages(),
child: Container(
margin: const EdgeInsets.only(right: 16),
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: _surface,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: _divider),
),
child: const Icon(Icons.refresh_rounded,
color: _textSecondary, size: 18),
),
),
],
bottom: PreferredSize(
preferredSize: const Size.fromHeight(1),
child: Container(height: 1, color: _divider),
),
);
}),
}
// ─────────────────────────── PACKAGE CARD ───────────────────────────
Widget _buildPackageCard(
BuildContext context, dynamic package, PackageController controller) {
final platform = package['platform']?.toString() ?? '';
final isAndroid = platform.toLowerCase().contains('android');
final isIOS = platform.toLowerCase().contains('ios');
final Color platformColor = isAndroid
? const Color(0xFF4CAF50)
: isIOS
? _info
: _warning;
final IconData platformIcon = isAndroid
? Icons.android_rounded
: isIOS
? Icons.apple_rounded
: Icons.devices_rounded;
return Material(
color: Colors.transparent,
child: InkWell(
onTap: () => _showUpdateDialog(context, package, controller),
borderRadius: BorderRadius.circular(16),
splashColor: _accent.withOpacity(0.06),
highlightColor: Colors.transparent,
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: _surface,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: _divider),
),
child: Row(
children: [
// Platform Icon
Container(
width: 48,
height: 48,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
platformColor.withOpacity(0.20),
platformColor.withOpacity(0.06),
],
),
borderRadius: BorderRadius.circular(13),
border: Border.all(color: platformColor.withOpacity(0.25)),
),
child: Icon(platformIcon, color: platformColor, size: 22),
),
const SizedBox(width: 14),
// Info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
package['appName']?.toString() ?? '',
style: const TextStyle(
color: _textPrimary,
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 4),
Row(
children: [
_buildTag(platform, platformColor),
const SizedBox(width: 6),
_buildVersionBadge(
package['version']?.toString() ?? '?'),
],
),
],
),
),
// Update button
Container(
padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
decoration: BoxDecoration(
color: _accent.withOpacity(0.10),
borderRadius: BorderRadius.circular(10),
border: Border.all(color: _accent.withOpacity(0.25)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.edit_rounded, color: _accent, size: 13),
SizedBox(width: 5),
Text(
'تعديل',
style: TextStyle(
color: _accent,
fontSize: 11,
fontWeight: FontWeight.w600,
),
),
],
),
),
],
),
),
),
);
}
Widget _buildTag(String label, Color color) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: color.withOpacity(0.10),
borderRadius: BorderRadius.circular(6),
),
child: Text(
label,
style: TextStyle(
color: color,
fontSize: 10,
fontWeight: FontWeight.w600,
),
),
);
}
Widget _buildVersionBadge(String version) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: _divider,
borderRadius: BorderRadius.circular(6),
),
child: Text(
'v$version',
style: const TextStyle(
color: _textSecondary,
fontSize: 10,
fontWeight: FontWeight.w500,
fontFamily: 'monospace',
),
),
);
}
// ─────────────────────────── EMPTY STATE ───────────────────────────
Widget _buildEmptyState() {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: _surface,
shape: BoxShape.circle,
border: Border.all(color: _divider),
),
child: const Icon(Icons.inventory_2_outlined,
color: _textSecondary, size: 32),
),
const SizedBox(height: 16),
const Text('لا توجد حزم متاحة',
style: TextStyle(
color: _textPrimary,
fontSize: 15,
fontWeight: FontWeight.w600)),
const SizedBox(height: 6),
const Text('اسحب للأسفل لإعادة التحميل',
style: TextStyle(color: _textSecondary, fontSize: 12)),
],
),
);
}
// ─────────────────────────── UPDATE DIALOG ───────────────────────────
void _showUpdateDialog(
BuildContext context, dynamic package, PackageController controller) {
controller.versionController.clear();
Get.dialog(
Dialog(
backgroundColor: Colors.transparent,
child: Container(
decoration: BoxDecoration(
color: _surfaceElevated,
borderRadius: BorderRadius.circular(24),
border: Border.all(color: _divider),
boxShadow: const [
BoxShadow(
color: Colors.black54,
blurRadius: 30,
offset: Offset(0, 12),
),
],
),
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Header
Row(
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: _accent.withOpacity(0.12),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: _accent.withOpacity(0.25)),
),
child: const Icon(Icons.system_update_rounded,
color: _accent, size: 20),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'تحديث الإصدار',
style: TextStyle(
color: _textPrimary,
fontSize: 16,
fontWeight: FontWeight.w700,
),
),
Text(
package['appName']?.toString() ?? '',
style: const TextStyle(
color: _textSecondary, fontSize: 11),
),
],
),
),
],
),
const SizedBox(height: 20),
Container(height: 1, color: _divider),
const SizedBox(height: 20),
// Current info
Row(
children: [
_buildInfoChip(Icons.devices_rounded,
package['platform']?.toString() ?? '', _info),
const SizedBox(width: 8),
_buildInfoChip(Icons.tag_rounded,
'الحالي: ${package['version']}', _warning),
],
),
const SizedBox(height: 18),
// Input label
const Text(
'الإصدار الجديد',
style: TextStyle(
color: _textSecondary,
fontSize: 11,
fontWeight: FontWeight.w600,
letterSpacing: 0.8,
),
),
const SizedBox(height: 8),
// Text input
Container(
decoration: BoxDecoration(
color: _bg,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: _divider),
),
child: TextField(
controller: controller.versionController,
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
style: const TextStyle(
color: _textPrimary,
fontSize: 15,
fontFamily: 'monospace',
fontWeight: FontWeight.w600,
),
decoration: InputDecoration(
hintText: package['version'].toString(),
hintStyle: const TextStyle(
color: _textSecondary,
fontFamily: 'monospace',
),
prefixIcon:
const Icon(Icons.tag_rounded, color: _accent, size: 18),
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(
horizontal: 14, vertical: 14),
),
),
),
const SizedBox(height: 24),
// Actions
Row(
children: [
Expanded(
child: TextButton(
onPressed: () => Get.back(),
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(color: _divider),
),
),
child: const Text(
'إلغاء',
style: TextStyle(color: _textSecondary, fontSize: 13),
),
),
),
const SizedBox(width: 12),
Expanded(
child: Obx(() => ElevatedButton.icon(
icon: controller.isLoading.value
? const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 2,
),
)
: const Icon(Icons.check_rounded, size: 16),
label: Text(
controller.isLoading.value ? 'جاري...' : 'تحديث',
style: const TextStyle(fontSize: 13),
),
style: ElevatedButton.styleFrom(
backgroundColor: _accent,
foregroundColor: _bg,
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
elevation: 0,
),
onPressed: controller.isLoading.value
? null
: () async {
await controller.updatePackages(
package['id'].toString(),
controller.versionController.text,
);
},
)),
),
],
),
],
),
),
),
);
}
Widget _buildInfoChip(IconData icon, String label, Color color) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: color.withOpacity(0.08),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: color.withOpacity(0.2)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, color: color, size: 13),
const SizedBox(width: 5),
Text(
label,
style: TextStyle(
color: color,
fontSize: 11,
fontWeight: FontWeight.w600,
),
),
],
),
);
}
}
// ══════════════════════════════════════════════════════════════
// CONTROLLER
// ══════════════════════════════════════════════════════════════
class PackageController extends GetxController {
List packages = []; // Observable list to hold package info
List packages = [];
var isLoading = false.obs;
final versionController = TextEditingController();
final formKey = GlobalKey<FormState>();
@@ -76,32 +534,62 @@ class PackageController extends GetxController {
fetchPackages();
}
// Method to fetch package data from API
fetchPackages() async {
isLoading.value = true;
var response = await CRUD().get(link: AppLink.getPackages, payload: {});
if (response != 'failure') {
var jsonData = jsonDecode(response);
packages = jsonData['message'];
update();
Log.print('jsonData: ${jsonData}');
Log.print('jsonData: $jsonData');
}
isLoading.value = false;
}
updatePackages(String id, version) async {
updatePackages(String id, String version) async {
if (version.trim().isEmpty) {
Get.snackbar(
'تنبيه',
'يرجى إدخال رقم الإصدار',
backgroundColor: _warning.withOpacity(0.15),
colorText: _textPrimary,
borderRadius: 12,
margin: const EdgeInsets.all(16),
icon: const Icon(Icons.warning_rounded, color: _warning),
);
return;
}
isLoading.value = true;
var response = await CRUD().post(
link: AppLink.updatePackages,
payload: {
"id": id,
"version": version,
},
payload: {"id": id, "version": version},
);
Log.print('response: ${response}');
Log.print('response: $response');
isLoading.value = false;
if (response != 'failure') {
Get.back();
Get.snackbar(
'تم التحديث',
'تم تحديث الإصدار بنجاح',
backgroundColor: _accent.withOpacity(0.15),
colorText: _textPrimary,
borderRadius: 12,
margin: const EdgeInsets.all(16),
icon: const Icon(Icons.check_circle_rounded, color: _accent),
);
fetchPackages();
} else {
Get.snackbar('error', 'message');
Get.snackbar(
'خطأ',
'فشل التحديث، يرجى المحاولة مجدداً',
backgroundColor: _danger.withOpacity(0.15),
colorText: _textPrimary,
borderRadius: 12,
margin: const EdgeInsets.all(16),
icon: const Icon(Icons.error_rounded, color: _danger),
);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,669 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../controller/server/server_monitor_controller.dart';
class ServerMonitorPage extends StatelessWidget {
const ServerMonitorPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final controller = Get.put(ServerMonitorController());
final themeColor = const Color(0xFF6366F1);
return Scaffold(
backgroundColor: const Color(0xFF0A0E27),
body: RefreshIndicator(
onRefresh: controller.fetchServerData,
color: themeColor,
backgroundColor: const Color(0xFF1A1F3A),
child: CustomScrollView(
physics: const BouncingScrollPhysics(),
slivers: [
// === 1. App Bar المتجاوب ===
SliverAppBar(
expandedHeight: 100,
floating: true,
pinned: true,
backgroundColor: const Color(0xFF0A0E27),
elevation: 0,
flexibleSpace: FlexibleSpaceBar(
titlePadding: const EdgeInsets.only(bottom: 16),
title: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.dns_rounded,
color: Colors.white, size: 20),
const SizedBox(width: 8),
const Text(
'Server Monitor',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: Colors.white,
fontFamily: 'Segoe UI', // أو أي خط تفضله
),
),
],
),
centerTitle: true,
background: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
themeColor.withOpacity(0.3),
const Color(0xFF0A0E27),
],
),
),
),
),
actions: [
_buildRefreshButton(controller),
],
),
// === 2. المحتوى الرئيسي ===
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
sliver: Obx(() {
if (controller.isLoading.value &&
controller.serverData.value == null) {
return const SliverFillRemaining(child: _LoadingState());
}
if (controller.errorMessage.isNotEmpty) {
return SliverFillRemaining(
child: _ErrorState(controller: controller));
}
final data = controller.serverData.value!;
return SliverToBoxAdapter(
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
maxWidth:
1000), // لمنع التمدد الزائد في الشاشات الكبيرة
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// معلومات الوقت والتشغيل
_HeaderInfo(data: data),
const SizedBox(height: 20),
// بطاقات الأداء (CPU & RAM)
LayoutBuilder(builder: (context, constraints) {
return _buildCpuMemSection(
data, constraints.maxWidth > 600);
}),
const SizedBox(height: 20),
// القسم المتغير (خدمات + عمليات + تخزين)
LayoutBuilder(builder: (context, constraints) {
// إذا كانت الشاشة كبيرة (تابلت/ديسكتوب)
if (constraints.maxWidth > 800) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// العمود الأول: الخدمات والشبكة
Expanded(
flex: 4,
child: Column(
children: [
_ServicesCard(data: data),
const SizedBox(height: 20),
_StorageNetworkCard(data: data),
],
),
),
const SizedBox(width: 20),
// العمود الثاني: العمليات
Expanded(
flex: 6,
child: _TopProcessesCard(
data: data,
height:
600), // ارتفاع ثابت في وضع الكمبيوتر
),
],
);
}
// إذا كانت الشاشة موبايل
else {
return Column(
children: [
_ServicesCard(data: data),
const SizedBox(height: 16),
_StorageNetworkCard(data: data),
const SizedBox(height: 16),
_TopProcessesCard(
data: data), // ارتفاع ديناميكي
],
);
}
}),
const SizedBox(height: 40),
],
),
),
),
);
}),
),
],
),
),
);
}
Widget _buildRefreshButton(ServerMonitorController controller) {
return Obx(() => Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
),
child: IconButton(
icon: controller.isLoading.value
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2, color: Colors.white),
)
: const Icon(Icons.refresh_rounded, color: Colors.white),
onPressed: controller.fetchServerData,
),
));
}
// دمج بطاقات المعالج والذاكرة
Widget _buildCpuMemSection(dynamic data, bool isWide) {
List<Widget> cards = [
_MetricCard(
title: "المعالج (CPU)",
value: "${data.cpu.percent}%",
subtitle: "${data.cpu.cores} Cores",
icon: Icons.memory,
percent: data.cpu.percent.toDouble(),
color: const Color(0xFFFF6B6B),
),
SizedBox(width: isWide ? 20 : 0, height: isWide ? 0 : 16),
_MetricCard(
title: "الذاكرة (RAM)",
value: "${data.memory.percent}%",
subtitle: "${data.memory.usedGb}/${data.memory.totalGb} GB",
icon: Icons.sd_storage_rounded,
percent: data.memory.percent.toDouble(),
color: const Color(0xFF4E54C8),
),
];
return isWide
? Row(
children: cards
.map((e) => e is SizedBox ? e : Expanded(child: e))
.toList())
: Column(children: cards);
}
}
// === مكونات فرعية معاد استخدامها (Widgets) ===
class _HeaderInfo extends StatelessWidget {
final dynamic data;
const _HeaderInfo({required this.data});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.05),
borderRadius: BorderRadius.circular(50),
border: Border.all(color: Colors.white.withOpacity(0.1)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.timer_outlined,
size: 16, color: Colors.greenAccent.withOpacity(0.8)),
const SizedBox(width: 8),
Text(
"Uptime: ${data.uptime.formatted}",
style: const TextStyle(
color: Colors.white70,
fontSize: 12,
fontWeight: FontWeight.w500),
),
Container(
width: 1,
height: 12,
color: Colors.white24,
margin: const EdgeInsets.symmetric(horizontal: 12)),
Icon(Icons.update,
size: 16, color: Colors.blueAccent.withOpacity(0.8)),
const SizedBox(width: 8),
Text(
"Last Update: ${data.timestamp.split(' ')[1]}",
style: const TextStyle(color: Colors.white70, fontSize: 12),
),
],
),
);
}
}
class _MetricCard extends StatelessWidget {
final String title;
final String value;
final String subtitle;
final IconData icon;
final double percent;
final Color color;
const _MetricCard({
required this.title,
required this.value,
required this.subtitle,
required this.icon,
required this.percent,
required this.color,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [color.withOpacity(0.9), color.withOpacity(0.6)],
),
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: color.withOpacity(0.3),
blurRadius: 12,
offset: const Offset(0, 8),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.2),
borderRadius: BorderRadius.circular(12),
),
child: Icon(icon, color: Colors.white, size: 24),
),
Text(
value,
style: const TextStyle(
color: Colors.white,
fontSize: 28,
fontWeight: FontWeight.bold),
),
],
),
const SizedBox(height: 16),
Text(title,
style: const TextStyle(color: Colors.white70, fontSize: 14)),
const SizedBox(height: 4),
Text(subtitle,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600)),
const SizedBox(height: 12),
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value: percent / 100,
minHeight: 6,
backgroundColor: Colors.black12,
valueColor: const AlwaysStoppedAnimation(Colors.white),
),
),
],
),
);
}
}
class _ServicesCard extends StatelessWidget {
final dynamic data;
const _ServicesCard({required this.data});
@override
Widget build(BuildContext context) {
return _BaseCard(
title: "حالة الخدمات",
icon: Icons.security,
iconColor: Colors.tealAccent,
child: Column(
children: data.services.entries.map<Widget>((e) {
final isActive = e.value == 'active';
return Container(
margin: const EdgeInsets.only(bottom: 10),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: const Color(0xFF0F1629),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: isActive
? Colors.green.withOpacity(0.3)
: Colors.red.withOpacity(0.3),
),
),
child: Row(
children: [
CircleAvatar(
radius: 4,
backgroundColor:
isActive ? Colors.greenAccent : Colors.redAccent,
),
const SizedBox(width: 12),
Expanded(
child: Text(
e.key.toUpperCase(),
style: const TextStyle(
color: Colors.white, fontWeight: FontWeight.w600),
),
),
Container(
padding:
const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: isActive
? Colors.green.withOpacity(0.1)
: Colors.red.withOpacity(0.1),
borderRadius: BorderRadius.circular(6),
),
child: Text(
isActive ? "Running" : "Stopped",
style: TextStyle(
color: isActive ? Colors.greenAccent : Colors.redAccent,
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
),
],
),
);
}).toList(),
),
);
}
}
class _StorageNetworkCard extends StatelessWidget {
final dynamic data;
const _StorageNetworkCard({required this.data});
@override
Widget build(BuildContext context) {
return _BaseCard(
title: "التخزين والشبكة",
icon: Icons.cloud_queue_rounded,
iconColor: Colors.purpleAccent,
child: Column(
children: [
_buildRowItem(Icons.pie_chart_outline, "Storage",
"${data.disk.percent}%", "${data.disk.usedGb} GB Used"),
const Divider(color: Colors.white10, height: 24),
_buildRowItem(Icons.download_rounded, "Download",
"${data.network.receivedMb} MB", "In"),
const SizedBox(height: 16),
_buildRowItem(Icons.upload_rounded, "Upload",
"${data.network.sentMb} MB", "Out"),
],
),
);
}
Widget _buildRowItem(IconData icon, String label, String value, String sub) {
return Row(
children: [
Icon(icon, color: Colors.white54, size: 20),
const SizedBox(width: 12),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label,
style: const TextStyle(color: Colors.white60, fontSize: 12)),
Text(sub,
style: TextStyle(
color: Colors.white.withOpacity(0.4), fontSize: 10)),
],
),
const Spacer(),
Text(value,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 16)),
],
);
}
}
class _TopProcessesCard extends StatelessWidget {
final dynamic data;
final double? height;
const _TopProcessesCard({required this.data, this.height});
@override
Widget build(BuildContext context) {
return Container(
height: height, // إذا كان null سيأخذ الارتفاع بناءً على المحتوى
decoration: BoxDecoration(
color: const Color(0xFF1A1F3A),
borderRadius: BorderRadius.circular(24),
border: Border.all(color: Colors.white.withOpacity(0.05)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(20),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.orange.withOpacity(0.1),
borderRadius: BorderRadius.circular(8)),
child: const Icon(Icons.analytics_rounded,
color: Colors.orange, size: 18),
),
const SizedBox(width: 12),
const Text("Top Processes",
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold)),
],
),
),
const Divider(height: 1, color: Colors.white10),
// نستخدم ListView.builder داخل Expanded إذا كان هناك ارتفاع محدد، وإلا Column للموبايل
height != null
? Expanded(child: _buildList())
: _buildList(shrinkWrap: true),
],
),
);
}
Widget _buildList({bool shrinkWrap = false}) {
return ListView.separated(
padding: const EdgeInsets.all(16),
physics: shrinkWrap
? const NeverScrollableScrollPhysics()
: const BouncingScrollPhysics(),
shrinkWrap: shrinkWrap,
itemCount: data.topProcesses.length,
separatorBuilder: (_, __) => const SizedBox(height: 12),
itemBuilder: (context, index) {
final process = data.topProcesses[index];
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.03),
borderRadius: BorderRadius.circular(12),
),
child: Row(
children: [
Text("#${index + 1}",
style: const TextStyle(
color: Colors.white38, fontWeight: FontWeight.bold)),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(process.name,
style: const TextStyle(
color: Colors.white, fontWeight: FontWeight.w500),
overflow: TextOverflow.ellipsis),
],
),
),
Container(
padding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: Colors.orange.withOpacity(0.1),
borderRadius: BorderRadius.circular(20),
),
child: Text(
process.usage,
style: const TextStyle(
color: Colors.orangeAccent,
fontSize: 12,
fontWeight: FontWeight.bold),
),
),
],
),
);
},
);
}
}
class _BaseCard extends StatelessWidget {
final String title;
final IconData icon;
final Color iconColor;
final Widget child;
const _BaseCard({
required this.title,
required this.icon,
required this.iconColor,
required this.child,
});
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: const Color(0xFF1A1F3A),
borderRadius: BorderRadius.circular(24),
border: Border.all(color: Colors.white.withOpacity(0.05)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: iconColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(8)),
child: Icon(icon, color: iconColor, size: 18),
),
const SizedBox(width: 12),
Text(title,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold)),
],
),
const SizedBox(height: 20),
child,
],
),
);
}
}
class _LoadingState extends StatelessWidget {
const _LoadingState();
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(color: Color(0xFF6366F1)),
const SizedBox(height: 16),
Text("Connecting to server...",
style: TextStyle(color: Colors.white.withOpacity(0.5))),
],
),
);
}
}
class _ErrorState extends StatelessWidget {
final ServerMonitorController controller;
const _ErrorState({required this.controller});
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.cloud_off_rounded,
size: 60, color: Colors.redAccent),
const SizedBox(height: 16),
Text(controller.errorMessage.value,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white)),
const SizedBox(height: 24),
ElevatedButton(
onPressed: controller.fetchServerData,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF6366F1),
shape: const StadiumBorder(),
),
child: const Text("Try Again"),
)
],
),
),
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -7,16 +7,37 @@ import '../../controller/auth/otp_helper.dart';
import '../../controller/functions/crud.dart';
import '../../print.dart';
// ─── Colors (نفس نظام الألوان المستخدم في التطبيق) ──────────────────────────
class _C {
static const bg = Color(0xFF0A0D14);
static const card = Color(0xFF161D2E);
static const border = Color(0xFF1F2D4A);
static const accent = Color(0xFF00E5FF);
static const accentGlow = Color(0x2200E5FF);
static const accentDim = Color(0xFF0097A7);
static const textPrimary = Color(0xFFE8F0FE);
static const textSec = Color(0xFF7A8BAA);
static const error = Color(0xFFFF5252);
static const inputBg = Color(0xFF0C1120);
}
class AdminLoginPage extends StatefulWidget {
const AdminLoginPage({super.key});
@override
State<AdminLoginPage> createState() => _AdminLoginPageState();
}
class _AdminLoginPageState extends State<AdminLoginPage> {
class _AdminLoginPageState extends State<AdminLoginPage>
with SingleTickerProviderStateMixin {
final _phoneController = TextEditingController();
final _formKey = GlobalKey<FormState>();
bool _isLoading = false;
late final AnimationController _glowCtrl;
late final Animation<double> _glowAnim;
// ─── Logic (بدون تغيير) ────────────────────────────────────────────────────
Future<void> _submit() async {
final allowedPhones = Env.ALLOWED_ADMIN_PHONES;
Log.print('allowedPhones: ${allowedPhones}');
@@ -42,42 +63,207 @@ class _AdminLoginPageState extends State<AdminLoginPage> {
@override
void initState() {
super.initState();
_initializeToken(); // استدعاء دالة async بدون await
_initializeToken();
_glowCtrl = AnimationController(
vsync: this,
duration: const Duration(seconds: 4),
)..repeat(reverse: true);
_glowAnim = Tween<double>(begin: 0.3, end: 1.0).animate(
CurvedAnimation(parent: _glowCtrl, curve: Curves.easeInOut),
);
}
void _initializeToken() async {
await CRUD().getJWT();
}
@override
void dispose() {
_phoneController.dispose();
_glowCtrl.dispose();
super.dispose();
}
// ─── Build ─────────────────────────────────────────────────────────────────
@override
Widget build(BuildContext context) {
Get.put(OtpHelper());
return Scaffold(
appBar: AppBar(title: const Text('دخول الإدارة')),
body: Padding(
padding: const EdgeInsets.all(20.0),
backgroundColor: _C.bg,
body: Stack(
children: [
// ── Ambient glow top-right ──────────────────────────────────────────
Positioned(
top: -150,
right: -100,
child: AnimatedBuilder(
animation: _glowAnim,
builder: (_, __) => Opacity(
opacity: _glowAnim.value * 0.18,
child: Container(
width: 400,
height: 400,
decoration: const BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(
colors: [Color(0xFF00E5FF), Colors.transparent],
),
),
),
),
),
),
// ── Ambient glow bottom-left ────────────────────────────────────────
Positioned(
bottom: -120,
left: -80,
child: AnimatedBuilder(
animation: _glowAnim,
builder: (_, __) => Opacity(
opacity: (1 - _glowAnim.value) * 0.15,
child: Container(
width: 340,
height: 340,
decoration: const BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(
colors: [Color(0xFF7C4DFF), Colors.transparent],
),
),
),
),
),
),
// ── Main content ───────────────────────────────────────────────────
SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 28),
physics: const BouncingScrollPhysics(),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 440),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// IntlPhoneField(
// initialCountryCode: 'SY',
// decoration: const InputDecoration(labelText: 'رقم الهاتف'),
// onChanged: (phone) {
// _phoneController.text = phone.completeNumber;
// },
// validator: (phone) {
// if (phone == null || phone.completeNumber.isEmpty) {
// return 'الرجاء إدخال رقم الهاتف';
// }
// return null;
// },
// ),
const SizedBox(height: 24),
// ── Logo / Icon ─────────────────────────────────────
_buildLogo(),
const SizedBox(height: 32),
// ── Title ───────────────────────────────────────────
const Text(
'لوحة الإدارة',
style: TextStyle(
color: _C.textPrimary,
fontSize: 26,
fontWeight: FontWeight.w800,
letterSpacing: 0.5,
),
),
const SizedBox(height: 8),
const Text(
'أدخل رقم هاتفك للمتابعة',
style: TextStyle(
color: _C.textSec,
fontSize: 14,
),
),
const SizedBox(height: 40),
// ── Card ────────────────────────────────────────────
Container(
padding: const EdgeInsets.all(28),
decoration: BoxDecoration(
color: _C.card,
borderRadius: BorderRadius.circular(24),
border: Border.all(
color: _C.accent.withOpacity(0.18), width: 1.2),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.4),
blurRadius: 32,
offset: const Offset(0, 12),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// ── Field label ─────────────────────────────
const Row(
children: [
Icon(Icons.phone_android_rounded,
color: _C.accent, size: 16),
SizedBox(width: 8),
Text(
'رقم الهاتف',
style: TextStyle(
color: _C.textSec,
fontSize: 13,
fontWeight: FontWeight.w600,
letterSpacing: 0.3,
),
),
],
),
const SizedBox(height: 10),
// ── Phone field ─────────────────────────────
TextFormField(
controller: _phoneController,
keyboardType: TextInputType.phone,
decoration: const InputDecoration(labelText: 'رقم الهاتف'),
textDirection: TextDirection.ltr,
style: const TextStyle(
color: _C.textPrimary,
fontSize: 16,
fontFamily: 'monospace',
letterSpacing: 1.2,
),
decoration: InputDecoration(
hintText: '+963 XXX XXX XXX',
hintStyle: const TextStyle(
color: _C.textSec,
fontSize: 14,
letterSpacing: 0.5),
filled: true,
fillColor: _C.inputBg,
prefixIcon: const Icon(Icons.dialpad_rounded,
color: _C.accentDim, size: 20),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: BorderSide.none,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(
color: _C.border, width: 1),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(
color: _C.accent, width: 1.5),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(
color: _C.error, width: 1),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(
color: _C.error, width: 1.5),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 16),
errorStyle: const TextStyle(
color: _C.error, fontSize: 12),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'الرجاء إدخال رقم الهاتف';
@@ -85,13 +271,179 @@ class _AdminLoginPageState extends State<AdminLoginPage> {
return null;
},
),
const SizedBox(height: 20),
const SizedBox(height: 28),
// ── Submit button ────────────────────────────
_isLoading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: _submit,
child: const Text('إرسال رمز التحقق'),
? const Center(
child: SizedBox(
width: 32,
height: 32,
child: CircularProgressIndicator(
color: _C.accent,
strokeWidth: 2.5,
),
),
)
: _SubmitButton(onPressed: () {
if (_formKey.currentState!.validate()) {
_submit();
}
}),
],
),
),
const SizedBox(height: 32),
// ── Footer ──────────────────────────────────────────
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 6,
height: 6,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _C.accent,
boxShadow: [
BoxShadow(
color: _C.accentGlow,
blurRadius: 6,
spreadRadius: 1,
),
],
),
),
const SizedBox(width: 8),
const Text(
'وصول مقيّد للمشرفين فقط',
style: TextStyle(
color: _C.textSec,
fontSize: 12,
),
),
],
),
const SizedBox(height: 24),
],
),
),
),
),
),
),
],
),
);
}
// ─── Logo Widget ─────────────────────────────────────────────────────────
Widget _buildLogo() {
return AnimatedBuilder(
animation: _glowAnim,
builder: (_, child) => Container(
width: 90,
height: 90,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _C.card,
border: Border.all(
color: _C.accent.withOpacity(0.3 + _glowAnim.value * 0.3),
width: 1.5,
),
boxShadow: [
BoxShadow(
color: _C.accentGlow.withOpacity(_glowAnim.value * 0.6),
blurRadius: 30,
spreadRadius: 4,
),
],
),
child: child,
),
child: const Icon(
Icons.admin_panel_settings_rounded,
color: _C.accent,
size: 42,
),
);
}
}
// ─── Submit Button ─────────────────────────────────────────────────────────────
class _SubmitButton extends StatefulWidget {
final VoidCallback onPressed;
const _SubmitButton({required this.onPressed});
@override
State<_SubmitButton> createState() => _SubmitButtonState();
}
class _SubmitButtonState extends State<_SubmitButton>
with SingleTickerProviderStateMixin {
late final AnimationController _ctrl;
late final Animation<double> _scale;
@override
void initState() {
super.initState();
_ctrl = AnimationController(
vsync: this, duration: const Duration(milliseconds: 100));
_scale = Tween<double>(begin: 1.0, end: 0.96)
.animate(CurvedAnimation(parent: _ctrl, curve: Curves.easeOut));
}
@override
void dispose() {
_ctrl.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTapDown: (_) => _ctrl.forward(),
onTapUp: (_) => _ctrl.reverse(),
onTapCancel: () => _ctrl.reverse(),
onTap: widget.onPressed,
child: AnimatedBuilder(
animation: _scale,
builder: (_, child) =>
Transform.scale(scale: _scale.value, child: child),
child: Container(
padding: const EdgeInsets.symmetric(vertical: 17),
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFF00B4D8), Color(0xFF00E5FF)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(14),
boxShadow: [
BoxShadow(
color: const Color(0x3300E5FF),
blurRadius: 20,
spreadRadius: 1,
offset: const Offset(0, 6),
),
],
),
child: const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.send_rounded, color: Colors.white, size: 18),
SizedBox(width: 10),
Text(
'إرسال رمز التحقق',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w700,
letterSpacing: 0.3,
),
),
],
),
),

View File

@@ -4,10 +4,7 @@ import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:sefer_admin1/constant/colors.dart';
import 'package:sefer_admin1/constant/links.dart';
import 'package:sefer_admin1/views/widgets/my_scafold.dart';
import 'package:sefer_admin1/views/widgets/my_textField.dart';
import '../../constant/box_name.dart';
import '../../constant/info.dart';
@@ -28,6 +25,11 @@ class _AddInvoicePageState extends State<AddInvoicePage> {
File? _imageFile;
bool _isLoading = false;
// الألوان المستخدمة في الثيم
final Color primaryColor = const Color(0xFF4F46E5); // Indigo
final Color secondaryColor = const Color(0xFF818CF8); // Lighter Indigo
final Color bgColor = const Color(0xFFF3F4F6); // Light Gray Background
String generateInvoiceNumber() {
final now = DateTime.now();
return "INV-${now.year}${now.month.toString().padLeft(2, '0')}${now.day.toString().padLeft(2, '0')}-${now.microsecond}";
@@ -36,7 +38,7 @@ class _AddInvoicePageState extends State<AddInvoicePage> {
Future<void> uploadInvoice() async {
if (!_formKey.currentState!.validate()) return;
final driverID = '123'; // ← عدّله حسب نظامك
final driverID = '123'; // قيمة افتراضية أو يمكن جلبها من الكونترولر
final invoiceNumber = generateInvoiceNumber();
final amount = _amountController.text.trim();
final itemName = _itemNameController.text.trim();
@@ -45,11 +47,13 @@ class _AddInvoicePageState extends State<AddInvoicePage> {
setState(() => _isLoading = true);
try {
// إعداد الترويسة (Headers)
final headers = {
'Authorization':
'Bearer ${r(box.read(BoxName.jwt)).split(AppInformation.addd)[0]}',
'X-HMAC-Auth': '${box.read(BoxName.hmac)}',
};
final uri = Uri.parse(AppLink.addInvoice);
final request = http.MultipartRequest('POST', uri)
..fields['driverID'] = driverID
@@ -59,41 +63,62 @@ class _AddInvoicePageState extends State<AddInvoicePage> {
..fields['date'] = date
..headers.addAll(headers);
// إضافة الصورة إذا وجدت
if (_imageFile != null) {
final imageName = _imageFile!.path.split('/').last;
final imageStream = http.ByteStream(_imageFile!.openRead());
final imageLength = await _imageFile!.length();
request.files.add(http.MultipartFile(
final multipartFile = await http.MultipartFile.fromPath(
'image',
imageStream,
imageLength,
filename: imageName,
));
} else {}
_imageFile!.path,
);
request.files.add(multipartFile);
}
final response = await request.send();
final respStr = await response.stream.bytesToString();
final data = jsonDecode(respStr);
// محاولة تحليل الاستجابة
Map<String, dynamic> data;
try {
data = jsonDecode(respStr);
} catch (e) {
data = {'status': 'error', 'message': 'Invalid server response'};
}
if (data['status'] == 'success') {
Get.snackbar('تم الحفظ', 'تم حفظ الفاتورة بنجاح',
backgroundColor: Colors.green.shade100);
Get.snackbar(
'نجاح',
'تم حفظ الفاتورة بنجاح',
backgroundColor: Colors.green.withOpacity(0.1),
colorText: Colors.green[800],
snackPosition: SnackPosition.TOP,
margin: const EdgeInsets.all(10),
borderRadius: 20,
);
_itemNameController.clear();
_amountController.clear();
setState(() => _imageFile = null);
Get.back(); // العودة للصفحة السابقة
// تأخير بسيط قبل العودة لتحديث الصفحة السابقة
Future.delayed(const Duration(seconds: 1), () {
Get.back(result: true);
});
} else {
Get.snackbar('خطأ', data['message'],
backgroundColor: Colors.red.shade100);
Get.snackbar(
'تنبيه',
data['message'] ?? 'حدث خطأ غير معروف',
backgroundColor: Colors.red.withOpacity(0.1),
colorText: Colors.red[800],
);
}
} catch (e, stacktrace) {
Get.snackbar('فشل الإرسال', e.toString(),
backgroundColor: Colors.red.shade100);
} catch (e) {
Get.snackbar(
'خطأ في الاتصال',
e.toString(),
backgroundColor: Colors.red.withOpacity(0.1),
colorText: Colors.red[800],
);
} finally {
setState(() => _isLoading = false);
if (mounted) setState(() => _isLoading = false);
}
}
@@ -114,76 +139,263 @@ class _AddInvoicePageState extends State<AddInvoicePage> {
@override
Widget build(BuildContext context) {
return MyScafolld(
title: 'إضافة فاتورة جديدة',
body: [
Padding(
padding: const EdgeInsets.all(16.0),
return Scaffold(
backgroundColor: bgColor,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
centerTitle: true,
title: const Text(
'إضافة فاتورة جديدة',
style:
TextStyle(color: Color(0xFF1F2937), fontWeight: FontWeight.bold),
),
leading: IconButton(
icon: const Icon(Icons.arrow_back_ios_new, color: Color(0xFF1F2937)),
onPressed: () => Get.back(),
),
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.white, bgColor],
),
),
),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20.0),
child: Form(
key: _formKey,
child: ListView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
MyTextForm(
controller: _itemNameController,
label: 'اسم البضاعة',
hint: 'مثال: قطع غيار',
type: TextInputType.text,
// validator: (val) =>
// val!.isEmpty ? 'الرجاء إدخال اسم البضاعة' : null,
// قسم البيانات الأساسية
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 15,
offset: const Offset(0, 5),
),
const SizedBox(height: 16),
MyTextForm(
controller: _amountController,
label: 'قيمة الفاتورة',
hint: 'مثال: 150.75',
type: TextInputType.numberWithOptions(decimal: true),
// validator: (val) =>
// val!.isEmpty ? 'الرجاء إدخال المبلغ' : null,
],
),
child: Column(
children: [
_buildModernTextField(
controller: _itemNameController,
label: 'اسم البضاعة / الخدمة',
icon: Icons.inventory_2_outlined,
hint: 'مثال: صيانة سيارة',
),
const SizedBox(height: 20),
Text('صورة الفاتورة (اختياري)',
style: Theme.of(context).textTheme.titleMedium),
_buildModernTextField(
controller: _amountController,
label: 'قيمة الفاتورة (د.أ)',
icon: Icons.attach_money,
hint: '0.00',
isNumber: true,
),
],
),
),
const SizedBox(height: 25),
// قسم الصورة
Text(
'صورة الفاتورة',
style: TextStyle(
color: Colors.grey[700],
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
const SizedBox(height: 10),
Container(
height: 180,
InkWell(
onTap: pickInvoiceImage,
borderRadius: BorderRadius.circular(20),
child: Container(
height: 200,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.grey.shade200,
border: Border.all(color: Colors.grey.shade400),
borderRadius: BorderRadius.circular(10),
color: Colors.white,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: _imageFile != null
? primaryColor
: Colors.grey.shade300,
width: 2,
style: _imageFile != null
? BorderStyle.solid
: BorderStyle.solid,
),
child: _imageFile != null
? ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.file(_imageFile!, fit: BoxFit.cover),
image: _imageFile != null
? DecorationImage(
image: FileImage(_imageFile!),
fit: BoxFit.cover,
)
: const Center(child: Text('لم يتم اختيار صورة')),
: null,
),
const SizedBox(height: 12),
ElevatedButton.icon(
onPressed: pickInvoiceImage,
icon: const Icon(Icons.image),
label: const Text('اختيار صورة'),
child: _imageFile == null
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(15),
decoration: BoxDecoration(
color: primaryColor.withOpacity(0.05),
shape: BoxShape.circle,
),
const SizedBox(height: 30),
ElevatedButton(
child: Icon(Icons.add_a_photo_rounded,
size: 40, color: primaryColor),
),
const SizedBox(height: 10),
Text(
'اضغط لرفع صورة الفاتورة',
style: TextStyle(
color: Colors.grey[500],
fontWeight: FontWeight.w500,
),
),
],
)
: Stack(
children: [
Positioned(
top: 10,
right: 10,
child: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.9),
shape: BoxShape.circle,
),
child: Icon(Icons.edit,
color: primaryColor, size: 20),
),
),
],
),
),
),
const SizedBox(height: 40),
// زر الحفظ
SizedBox(
height: 55,
child: ElevatedButton(
onPressed: _isLoading ? null : uploadInvoice,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: AppColor.primaryColor,
backgroundColor: Colors.transparent,
shadowColor: Colors.transparent,
padding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
),
child: Ink(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: _isLoading
? [Colors.grey, Colors.grey]
: [primaryColor, secondaryColor],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
),
borderRadius: BorderRadius.circular(15),
boxShadow: [
if (!_isLoading)
BoxShadow(
color: primaryColor.withOpacity(0.4),
blurRadius: 10,
offset: const Offset(0, 4),
),
],
),
child: Container(
alignment: Alignment.center,
child: _isLoading
? const CircularProgressIndicator(color: Colors.white)
: const Text(
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 2,
),
)
: const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.save_rounded, color: Colors.white),
SizedBox(width: 10),
Text(
'حفظ الفاتورة',
style: TextStyle(color: Colors.white),
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
),
),
],
isleading: true,
),
),
),
);
}
Widget _buildModernTextField({
required TextEditingController controller,
required String label,
required IconData icon,
required String hint,
bool isNumber = false,
}) {
return TextFormField(
controller: controller,
keyboardType: isNumber
? const TextInputType.numberWithOptions(decimal: true)
: TextInputType.text,
validator: (val) {
if (val == null || val.isEmpty) {
return 'هذا الحقل مطلوب';
}
return null;
},
decoration: InputDecoration(
labelText: label,
hintText: hint,
prefixIcon: Icon(icon, color: primaryColor.withOpacity(0.7)),
filled: true,
fillColor: Colors.grey[50],
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.grey.shade200),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: primaryColor, width: 1.5),
),
contentPadding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
),
);
}
}

View File

@@ -1,24 +1,32 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import '../../constant/links.dart';
import '../../controller/admin/get_all_invoice_controller.dart';
import '../../controller/functions/crud.dart';
import '../../print.dart';
import 'add_invoice_page.dart';
// نفترض أن هذا الموديل موجود في مشروعك، إذا لم يكن موجوداً يرجى إضافته أو تعديل الاستيراد
// import '../../model/invoice_model.dart';
class InvoiceListPage extends StatefulWidget {
const InvoiceListPage({super.key});
@override
_InvoiceListPageState createState() => _InvoiceListPageState();
}
class _InvoiceListPageState extends State<InvoiceListPage> {
List<InvoiceModel> invoices = [];
List<dynamic> invoices = []; // استخدام dynamic لتجنب مشاكل الموديل إذا اختلف
int totalCount = 0;
double totalAmount = 0.0;
bool isLoading = true;
// الألوان "الإيجابية" للتصميم الجديد
final Color primaryColor = const Color(0xFF4F46E5); // Indigo
final Color secondaryColor = const Color(0xFF818CF8); // Lighter Indigo
final Color moneyColor = const Color(0xFF059669); // Emerald Green
final Color bgColor = const Color(0xFFF3F4F6); // Light Gray Background
@override
void initState() {
super.initState();
@@ -26,255 +34,423 @@ class _InvoiceListPageState extends State<InvoiceListPage> {
}
Future<void> fetchInvoices() async {
// لإظهار مؤشر التحديث بشكل جيد
if (!isLoading) {
setState(() {});
}
if (!mounted) return;
setState(() => isLoading = true);
final response = await CRUD().post(link: AppLink.getInvoices, payload: {});
final data = (response);
Log.print('data: $data');
try {
final response =
await CRUD().post(link: AppLink.getInvoices, payload: {});
if (response != 'failure' && response['status'] == 'success') {
final data = response;
if (mounted) {
if (data != 'failure' && data['status'] == 'success') {
setState(() {
invoices = List.from(data['data'])
.map((item) => InvoiceModel.fromJson(item))
.toList();
totalCount = data['summary']['count'];
invoices = data['data']; // استخدام البيانات مباشرة
totalCount = int.tryParse(data['summary']['count'].toString()) ?? 0;
totalAmount =
double.tryParse(data['summary']['total'].toString()) ?? 0.0;
isLoading = false;
});
} else {
setState(() {
isLoading = false;
});
Get.snackbar("خطأ", "فشل في تحميل الفواتير. حاول التحديث مرة أخرى.",
backgroundColor: Colors.red.withOpacity(0.8),
colorText: Colors.white);
}
} else {
if (mounted) {
setState(() => isLoading = false);
Get.snackbar("تنبيه", "لا توجد فواتير لعرضها أو حدث خطأ",
backgroundColor: Colors.orange.withOpacity(0.2),
colorText: Colors.orange[900]);
}
}
} catch (e) {
Log.print('Error fetching invoices: $e');
if (mounted) setState(() => isLoading = false);
}
}
// --- دالة لعرض الصورة في نافذة منبثقة ---
void _showImageDialog(BuildContext context, String imageUrl) {
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
builder: (_) => Dialog(
backgroundColor: Colors.transparent,
child: Stack(
alignment: Alignment.center,
children: [
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
),
child: GestureDetector(
// لإغلاق الصورة عند الضغط عليها
onTap: () => Navigator.of(context).pop(),
child: Container(
padding: EdgeInsets.all(12),
padding: const EdgeInsets.all(5),
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
child: InteractiveViewer(
// لإتاحة التكبير والتصغير
panEnabled: true,
minScale: 0.5,
maxScale: 4,
child: Image.network(
imageUrl,
fit: BoxFit.contain,
// إظهار مؤشر تحميل أثناء جلب الصورة
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
loadingBuilder: (context, child, loadingProgress) {
if (loadingProgress == null) return child;
return Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes!
: null,
return SizedBox(
height: 200,
width: 200,
child: Center(
child: CircularProgressIndicator(color: primaryColor),
),
);
},
// إظهار أيقونة خطأ في حال فشل تحميل الصورة
errorBuilder: (context, error, stackTrace) {
return Icon(Icons.broken_image,
size: 100, color: Colors.red);
},
),
),
),
),
return const SizedBox(
height: 150,
width: 150,
child: Icon(Icons.broken_image,
size: 60, color: Colors.grey),
);
},
),
),
),
),
Positioned(
top: 0,
right: 0,
child: CircleAvatar(
backgroundColor: Colors.white,
child: IconButton(
icon: const Icon(Icons.close, color: Colors.black),
onPressed: () => Navigator.pop(context),
),
),
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("قائمة الفواتير"),
centerTitle: true,
elevation: 2,
actions: [
IconButton(
icon: Icon(Icons.add_a_photo),
onPressed: () {
// يمكنك إضافة إجراء الطباعة هنا
backgroundColor: bgColor,
// زر عائم بتصميم متدرج
floatingActionButton: Container(
decoration: BoxDecoration(
gradient: LinearGradient(colors: [primaryColor, secondaryColor]),
borderRadius: BorderRadius.circular(30),
boxShadow: [
BoxShadow(
color: primaryColor.withOpacity(0.4),
blurRadius: 10,
offset: const Offset(0, 4))
],
),
child: FloatingActionButton.extended(
onPressed: () => Get.to(() => AddInvoicePage()),
label: const Text('إضافة فاتورة',
style: TextStyle(fontWeight: FontWeight.bold)),
icon: const Icon(Icons.add),
backgroundColor: Colors.transparent,
elevation: 0,
),
),
body: Column(
children: [
// 1. رأس الصفحة (Header & Summary)
_buildHeader(),
Get.to(() => AddInvoicePage());
// 2. قائمة الفواتير
Expanded(
child: isLoading
? Center(child: CircularProgressIndicator(color: primaryColor))
: invoices.isEmpty
? _buildEmptyState()
: RefreshIndicator(
onRefresh: fetchInvoices,
color: primaryColor,
child: ListView.builder(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 80),
itemCount: invoices.length,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
final invoice = invoices[index];
return _buildInvoiceCard(invoice);
},
),
),
),
],
),
);
}
// === تصميم الهيدر (رأس الصفحة) ===
Widget _buildHeader() {
return Container(
width: double.infinity,
padding: EdgeInsets.only(
top: MediaQuery.of(context).padding.top + 20,
bottom: 30,
left: 20,
right: 20,
),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [primaryColor, const Color(0xFF6366F1)],
),
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(30),
bottomRight: Radius.circular(30),
),
boxShadow: [
BoxShadow(
color: primaryColor.withOpacity(0.3),
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
body: isLoading
? Center(child: CircularProgressIndicator())
: RefreshIndicator(
onRefresh: fetchInvoices, // خاصية السحب للتحديث
child: Column(
children: [
Expanded(
child: ListView.builder(
padding:
EdgeInsets.symmetric(vertical: 8.0, horizontal: 12.0),
itemCount: invoices.length,
itemBuilder: (context, index) {
final invoice = invoices[index];
return Card(
elevation: 4,
margin: EdgeInsets.symmetric(vertical: 8.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
// العنوان وزر الرجوع
Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back_ios,
color: Colors.white, size: 20),
onPressed: () => Get.back(),
),
const Expanded(
child: Text(
"سجل الفواتير",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(width: 40), // للمحاذاة
],
),
const SizedBox(height: 25),
// بطاقات الملخص
Row(
children: [
Expanded(
child: _buildSummaryItem(
title: "الإجمالي",
value: "${totalAmount.toStringAsFixed(1)} د.أ",
icon: Icons.attach_money,
isMoney: true,
),
),
Container(width: 1, height: 40, color: Colors.white24),
Expanded(
child: _buildSummaryItem(
title: "عدد الفواتير",
value: "$totalCount",
icon: Icons.receipt_long,
isMoney: false,
),
),
],
),
],
),
);
}
Widget _buildSummaryItem(
{required String title,
required String value,
required IconData icon,
required bool isMoney}) {
return Column(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.2),
shape: BoxShape.circle,
),
child: Icon(icon, color: Colors.white, size: 20),
),
const SizedBox(height: 8),
Text(
value,
style: TextStyle(
color: isMoney ? const Color(0xFFD1FAE5) : Colors.white,
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
Text(
title,
style: TextStyle(color: Colors.white.withOpacity(0.8), fontSize: 12),
),
],
);
}
// === تصميم بطاقة الفاتورة ===
Widget _buildInvoiceCard(dynamic invoice) {
// استخراج البيانات بأمان
String name = invoice['name'] ?? 'بدون اسم';
String amount = invoice['amount']?.toString() ?? '0';
String date = invoice['date'] ?? '';
String invNumber = invoice['invoiceNumber']?.toString() ?? '#';
String? imageUrl = invoice['imageLink'];
return Container(
margin: const EdgeInsets.only(bottom: 16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.03),
blurRadius: 15,
offset: const Offset(0, 5),
),
],
),
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(15.0),
borderRadius: BorderRadius.circular(20),
onTap: () {
// التحقق من وجود رابط للصورة قبل محاولة عرضه
if (invoice.imageLink != null &&
invoice.imageLink!.isNotEmpty) {
_showImageDialog(context, invoice.imageLink!);
if (imageUrl != null && imageUrl.isNotEmpty) {
_showImageDialog(context, imageUrl);
} else {
Get.snackbar("لا توجد صورة",
"هذه الفاتورة لا تحتوي على صورة مرفقة.");
Get.snackbar("تنبيه", "لا توجد صورة مرفقة",
backgroundColor: Colors.grey[200], colorText: Colors.black);
}
},
child: Padding(
padding: const EdgeInsets.all(16.0),
padding: const EdgeInsets.all(16),
child: Row(
children: [
// أيقونة الفاتورة الرئيسية
Icon(Icons.receipt_long,
color: Theme.of(context).primaryColor,
size: 40),
SizedBox(width: 16),
// تفاصيل الفاتورة
// 1. أيقونة أو صورة مصغرة
Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: primaryColor.withOpacity(0.08),
borderRadius: BorderRadius.circular(15),
),
child: imageUrl != null && imageUrl.isNotEmpty
? ClipRRect(
borderRadius: BorderRadius.circular(15),
child: Image.network(
imageUrl,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) =>
Icon(Icons.receipt, color: primaryColor),
),
)
: Icon(Icons.receipt_outlined, color: primaryColor),
),
const SizedBox(width: 16),
// 2. التفاصيل
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"فاتورة رقم: ${invoice.invoiceNumber}",
style: TextStyle(
name,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: Color(0xFF1F2937),
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
SizedBox(height: 8),
Text(
"الاسم: ${invoice.name}",
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.circular(8),
),
child: Text(
"#$invNumber",
style: TextStyle(
color: Colors.green.shade700,
fontSize: 10,
color: Colors.grey[600],
fontWeight: FontWeight.bold),
),
),
],
),
const SizedBox(height: 6),
Text(
date,
style: TextStyle(color: Colors.grey[500], fontSize: 12),
),
],
),
),
const SizedBox(width: 12),
// 3. المبلغ
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
"$amount",
style: TextStyle(
color: moneyColor,
fontWeight: FontWeight.w900,
fontSize: 18,
),
),
Text(
"د.أ",
style: TextStyle(
color: moneyColor.withOpacity(0.7),
fontWeight: FontWeight.w500,
),
),
SizedBox(height: 8),
Text(
"المبلغ: ${invoice.amount} د.أ",
style: TextStyle(
color: Colors.green.shade700,
fontWeight: FontWeight.w500,
),
),
SizedBox(height: 4),
Text(
"التاريخ: ${invoice.date}",
style: TextStyle(
color: Colors.grey.shade600,
fontSize: 12,
),
),
],
),
),
// أيقونة توضح وجود صورة
if (invoice.imageLink != null &&
invoice.imageLink!.isNotEmpty)
Icon(Icons.image_outlined,
color: Colors.blueAccent, size: 30),
],
),
),
),
);
},
),
),
_buildSummaryCard(), // بطاقة الملخص السفلية
],
),
),
);
}
Widget _buildSummaryCard() {
return Card(
margin: EdgeInsets.all(0),
elevation: 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
child: Container(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
Widget _buildEmptyState() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.receipt_long_rounded, size: 80, color: Colors.grey[300]),
const SizedBox(height: 16),
Text(
"إجمالي الفواتير",
style: TextStyle(color: Colors.grey.shade600, fontSize: 14),
),
Text(
"$totalCount",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
"لا توجد فواتير حالياً",
style: TextStyle(color: Colors.grey[500], fontSize: 16),
),
const SizedBox(height: 8),
TextButton.icon(
onPressed: fetchInvoices,
icon: const Icon(Icons.refresh),
label: const Text("تحديث"),
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
"المبلغ الإجمالي",
style: TextStyle(color: Colors.grey.shade600, fontSize: 14),
),
Text(
"${totalAmount.toStringAsFixed(2)} د.أ",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.green.shade800,
),
),
],
),
],
),
),
);
}
}