first commit

This commit is contained in:
Hamza-Ayed
2025-07-30 10:24:53 +03:00
parent 0945095398
commit 0b17f93aaa
244 changed files with 40043 additions and 0 deletions

View File

@@ -0,0 +1,105 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:local_auth/local_auth.dart';
import '../../constant/colors.dart';
import '../../constant/links.dart';
import '../functions/crud.dart';
class CaptainAdminController extends GetxController {
bool isLoading = false;
Map captainData = {};
Map captain = {};
final captainController = TextEditingController();
final captainPrizeController = TextEditingController();
final titleNotify = TextEditingController();
final bodyNotify = TextEditingController();
final formCaptainKey = GlobalKey<FormState>();
final formCaptainPrizeKey = GlobalKey<FormState>();
Future getCaptainCount() async {
isLoading = true;
update();
var res = await CRUD().get(link: AppLink.getCaptainDetails, payload: {});
var d = jsonDecode(res);
if (d['status'] == 'success') {
captainData = d;
}
isLoading = false;
update();
}
Future addCaptainPrizeToWallet() async {
String? paymentId;
//todo link to add wallet to captain
for (var i = 0; i < captainData['message'].length; i++) {
await CRUD().post(link: AppLink.addDriverPaymentPoints, payload: {
'driverID': captainData['message'][i]['id'],
'amount': captainPrizeController.text,
'paymentMethod': 'Prize',
}).then((value) {
paymentId = value['message'].toString();
});
await CRUD().post(link: AppLink.addPassengersWallet, payload: {
'driverID': captainData['message'][i]['id'],
'amount': captainPrizeController.text,
'paymentMethod': 'Prize',
'paymentID': paymentId.toString(),
});
}
Get.back();
}
void addCaptainsPrizeToWalletSecure() async {
try {
// Check if local authentication is available
bool isAvailable = await LocalAuthentication().isDeviceSupported();
if (isAvailable) {
// Authenticate the user
bool didAuthenticate = await LocalAuthentication().authenticate(
localizedReason: 'Use Touch ID or Face ID to confirm payment',
);
if (didAuthenticate) {
// User authenticated successfully, proceed with payment
await addCaptainPrizeToWallet();
Get.snackbar('Prize Added', '', backgroundColor: AppColor.greenColor);
} else {
// Authentication failed, handle accordingly
Get.snackbar('Authentication failed', '',
backgroundColor: AppColor.redColor);
// 'Authentication failed');
}
} else {
// Local authentication not available, proceed with payment without authentication
await addCaptainPrizeToWallet();
Get.snackbar('Prize Added', '', backgroundColor: AppColor.greenColor);
}
} catch (e) {
rethrow;
}
}
Future getCaptains() async {
var res = await CRUD()
.get(link: AppLink.getCaptainDetailsByEmailOrIDOrPhone, payload: {
'driver_id': captainController.text,
'driverEmail': captainController.text,
'driverPhone': captainController.text,
});
var d = jsonDecode(res);
if (d['status'] == 'success') {
captain = d;
}
update();
}
@override
void onInit() {
getCaptainCount();
super.onInit();
}
}

View File

@@ -0,0 +1,86 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_admin1/constant/links.dart';
import 'package:sefer_admin1/controller/functions/crud.dart';
import '../../constant/api_key.dart';
import '../../constant/box_name.dart';
import '../../main.dart';
import '../../print.dart';
class DashboardController extends GetxController {
bool isLoading = false;
List dashbord = [];
String creditSMS = '0';
final formKey = GlobalKey<FormState>();
final smsText = TextEditingController();
Future getDashBoard() async {
isLoading = true;
update();
// الطلب من السيرفر الرئيسي
var res = await CRUD().get(link: AppLink.getdashbord, payload: {});
if (res != 'failure') {
var d = jsonDecode(res);
// Log.print('d: ${d}');
dashbord = d['message']; // هذا عبارة عن List<Map>
}
// الطلب من سيرفر المحافظ
var resPayments = await CRUD().postWallet(
link: AppLink.getPaymentsDashboard,
payload: {},
);
if (resPayments != 'failure') {
var p = resPayments;
// Log.print('p: ${p}');
// نتأكد أن الكل Map بداخل List
if (dashbord.isNotEmpty &&
p['message'] is List &&
p['message'].isNotEmpty) {
dashbord[0].addAll(p['message'][0]); // ندمج المعلومات داخل نفس الـ Map
}
}
// كريدت الرسائل
var res2 = await CRUD().kazumiSMS(
link: 'https://sms.kazumi.me/api/sms/check-credit',
payload: {"username": "Sefer", "password": AK.smsPasswordEgypt},
);
creditSMS = res2['credit'];
Log.print(' res2[credit]: ${res2['credit']}');
Log.print('creditSMS: ${creditSMS}');
isLoading = false;
update();
}
sendSMSMethod() async {
if (formKey.currentState!.validate()) {
for (var phoneNumber in box.read(BoxName.tokensDrivers)['message']) {
// for (var i = 0; i < 2; i++) {
await CRUD().sendSmsEgypt(
phoneNumber['phone'].toString(),
// box.read(BoxName.tokensDrivers)['message'][i]['phone'].toString(),
smsText.text,
);
// Log.print('CRUD().phoneDriversTest.: ${phoneNumber['phone']}');
Future.delayed(const Duration(microseconds: 20));
}
Get.back();
}
}
@override
void onInit() async {
getDashBoard();
super.onInit();
}
}

View File

@@ -0,0 +1,25 @@
class InvoiceModel {
final String invoiceNumber;
final String amount;
final String date;
final String name;
final String? imageLink;
InvoiceModel({
required this.invoiceNumber,
required this.amount,
required this.date,
required this.name,
this.imageLink,
});
factory InvoiceModel.fromJson(Map<String, dynamic> json) {
return InvoiceModel(
invoiceNumber: json['invoice_number'],
amount: json['amount'].toString(),
date: json['date'],
name: json['name'],
imageLink: json['image_link'],
);
}
}

View File

@@ -0,0 +1,108 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:local_auth/local_auth.dart';
import '../../constant/colors.dart';
import '../../constant/links.dart';
import '../functions/crud.dart';
class PassengerAdminController extends GetxController {
bool isLoading = false;
Map passengersData = {};
Map passengers = {};
double height = 150;
final formPassKey = GlobalKey<FormState>();
final formPrizeKey = GlobalKey<FormState>();
final titleNotify = TextEditingController();
final bodyNotify = TextEditingController();
final passengerController = TextEditingController();
final passengerPrizeController = TextEditingController();
Future getPassengerCount() async {
isLoading = true;
update();
var res = await CRUD().get(link: AppLink.getPassengerDetails, payload: {});
var d = jsonDecode(res);
if (d['status'] == 'success') {
passengersData = d;
}
isLoading = false;
update();
}
Future addPassengerPrizeToWallet() async {
for (var i = 0; i < passengersData['message'].length; i++) {
await CRUD().post(link: AppLink.addPassengersWallet, payload: {
'passenger_id': passengersData['message'][i]['id'],
'balance': passengerPrizeController.text,
});
}
Get.back();
}
void addPassengerPrizeToWalletSecure() async {
try {
// Check if local authentication is available
bool isAvailable = await LocalAuthentication().isDeviceSupported();
if (isAvailable) {
// Authenticate the user
bool didAuthenticate = await LocalAuthentication().authenticate(
localizedReason: 'Use Touch ID or Face ID to confirm payment',
);
if (didAuthenticate) {
// User authenticated successfully, proceed with payment
await addPassengerPrizeToWallet();
Get.snackbar('Prize Added', '', backgroundColor: AppColor.greenColor);
} else {
// Authentication failed, handle accordingly
Get.snackbar('Authentication failed', '',
backgroundColor: AppColor.redColor);
// 'Authentication failed');
}
} else {
// Local authentication not available, proceed with payment without authentication
await addPassengerPrizeToWallet();
Get.snackbar('Prize Added', '', backgroundColor: AppColor.greenColor);
}
} catch (e) {
rethrow;
}
}
Future getPassengers() async {
var res = await CRUD().get(link: AppLink.getPassengerbyEmail, payload: {
'passengerEmail': passengerController.text,
'passengerId': passengerController.text,
'passengerphone': passengerController.text,
});
var d = jsonDecode(res);
if (d['status'] == 'success') {
passengers = d;
}
update();
}
changeHeight() {
if (passengers.isEmpty) {
height = 0;
update();
}
height = 150;
update();
}
void clearPlaces() {
passengers = {};
update();
}
@override
void onInit() {
getPassengerCount();
super.onInit();
}
}

View File

@@ -0,0 +1,590 @@
import 'dart:convert';
import 'dart:ffi';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import '../../constant/api_key.dart';
import '../../constant/box_name.dart';
import '../../constant/colors.dart';
import '../../constant/info.dart';
import '../../constant/links.dart';
import '../../constant/style.dart';
import '../../main.dart';
import '../functions/crud.dart';
class RegisterCaptainController extends GetxController {
bool isDriverSaved = false;
bool isCarSaved = false;
Map<String, dynamic>? arguments;
String? driverId;
String? email;
String? phone;
@override
void onInit() {
super.onInit();
arguments = Get.arguments;
initArguments();
}
void driveInit() {
arguments = Get.arguments;
initArguments();
}
void initArguments() {
if (arguments != null) {
driverId = arguments!['driverId'];
email = arguments!['email'];
phone = arguments!['phone_number'];
} else {
print('Arguments are null');
}
}
Map<String, dynamic> responseMap = {};
Map<String, dynamic> responseCarLicenseMapJordan = {};
Map<String, dynamic> responseBackCarLicenseMap = {};
Map<String, dynamic> responseIdCardMap = {};
Map<String, dynamic> responseIdCardDriverEgyptBack = {};
Map<String, dynamic> responseForComplaint = {};
Map<String, dynamic> responseIdCardDriverEgyptFront = {};
Map<String, dynamic> responseIdEgyptFront = {};
Map<String, dynamic> responseCriminalRecordEgypt = {};
Map<String, dynamic> responseIdEgyptBack = {};
Map<String, dynamic> responseIdEgyptDriverLicense = {};
String? responseIdCardDriverEgypt1;
bool isloading = false;
var image;
DateTime now = DateTime.now();
bool isLoading = false;
Future allMethodForAI(String prompt, imagePath, driverID) async {
isLoading = true;
update();
var extractedString = await CRUD().arabicTextExtractByVisionAndAI(
imagePath: imagePath, driverID: driverID);
var json = jsonDecode(extractedString);
var textValues = extractTextFromLines(json);
// await Get.put(AI()).geminiAiExtraction(prompt, textValues, imagePath);
await Get.put(RegisterCaptainController())
.anthropicAI(textValues, prompt, imagePath);
isLoading = false;
update();
}
String extractTextFromLines(Map<String, dynamic> jsonData) {
final readResult = jsonData['readResult'];
final blocks = readResult['blocks'];
final StringBuffer buffer = StringBuffer();
for (final block in blocks) {
final lines = block['lines'];
for (final line in lines) {
final text = line['text'];
buffer.write(text);
buffer.write('\n');
}
}
return buffer.toString().trim();
}
List driverNotCompleteRegistration = [];
getDriverNotCompleteRegistration() async {
var res = await CRUD()
.get(link: AppLink.getDriverNotCompleteRegistration, payload: {});
if (res != 'failure') {
var d = jsonDecode(res)['message'];
driverNotCompleteRegistration = d;
update();
} else {
Get.snackbar(res, '');
}
}
final today = DateTime.now();
Future<void> addDriverAndCarEgypt() async {
final expiryDate = responseIdEgyptDriverLicense['expiry_date'];
final expiryDateTime = DateTime.tryParse(expiryDate);
final isExpired = expiryDateTime != null && expiryDateTime.isBefore(today);
final taxExpiryDate = responseIdCardDriverEgyptBack['tax_expiry'];
// Get the inspection date from the response
final inspectionDate = responseIdCardDriverEgyptBack['inspection_date'];
final year = int.parse(inspectionDate.split('-')[0]);
// Try parsing the tax expiry date. If it fails, set it to null.
final taxExpiryDateTime = DateTime.tryParse(taxExpiryDate ?? '');
final isExpiredCar =
taxExpiryDateTime != null && taxExpiryDateTime.isBefore(today);
// Check if the inspection date is before today
final inspectionDateTime = DateTime(year, 1, 1);
final isInspectionExpired = inspectionDateTime.isBefore(today);
if (isExpiredCar || isInspectionExpired) {
Get.defaultDialog(
title: 'Expired Drivers License'.tr,
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.warning, size: 48, color: Colors.red),
const SizedBox(height: 16),
Text(
'Your drivers license and/or car tax has expired. Please renew them before proceeding.'
.tr,
textAlign: TextAlign.center,
style: AppStyle.title,
),
const SizedBox(height: 16),
IconButton(
onPressed: () async {
// await Get.find<TextToSpeechController>().speakText(
// 'Your drivers license and/or car tax has expired. Please renew them before proceeding.'
// .tr,
// );
},
icon: const Icon(Icons.volume_up),
),
],
),
actions: [
TextButton(
onPressed: () {
Get.back();
},
child: const Text('OK'),
),
],
);
} else if (isExpired) {
Get.defaultDialog(
title: 'Expired Drivers License'.tr,
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.warning, size: 48, color: Colors.red),
const SizedBox(height: 16),
Text(
'Your drivers license has expired. Please renew it before proceeding.'
.tr,
textAlign: TextAlign.center,
style: AppStyle.title,
),
const SizedBox(height: 16),
IconButton(
onPressed: () async {
// await Get.find<TextToSpeechController>().speakText(
// 'Your drivers license has expired. Please renew it before proceeding.'
// .tr,
// );
},
icon: const Icon(Icons.volume_up),
),
],
),
actions: [
TextButton(
onPressed: () {
Get.back();
},
child: const Text('OK'),
),
],
);
} else if (responseIdEgyptDriverLicense['national_number']
.toString()
.substring(0, 12) !=
responseIdEgyptBack['nationalID'].toString().substring(0, 12)) {
Get.defaultDialog(
barrierDismissible: false,
title: 'ID Mismatch',
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.warning, size: 48, color: Colors.red),
const SizedBox(height: 16),
Text(
'The national number on your drivers license does not match the one on your ID document. Please verify and provide the correct documents.'
.tr,
textAlign: TextAlign.center,
style: AppStyle.title,
),
const SizedBox(height: 16),
IconButton(
onPressed: () async {
// await Get.find<TextToSpeechController>().speakText(
// 'The national number on your drivers license does not match the one on your ID document. Please verify and provide the correct documents.',
// );
},
icon: const Icon(Icons.volume_up),
),
],
),
actions: [
TextButton(
onPressed: () {
Get.back();
},
child: const Text('OK'),
),
],
);
}
// else if (responseCriminalRecordEgypt['FullName'] !=
// responseIdEgyptDriverLicense['name_arabic']) {
// Get.defaultDialog(
// barrierDismissible: false,
// title: 'Criminal Record Mismatch',
// content: Column(
// mainAxisSize: MainAxisSize.min,
// children: [
// const Icon(Icons.warning, size: 48, color: Colors.red),
// const SizedBox(height: 16),
// Text(
// 'The full name on your criminal record does not match the one on your drivers license. Please verify and provide the correct documents.'
// .tr,
// textAlign: TextAlign.center,
// style: AppStyle.title,
// ),
// const SizedBox(height: 16),
// IconButton(
// onPressed: () async {
// await Get.find<TextToSpeechController>().speakText(
// 'The full name on your criminal record does not match the one on your drivers license. Please verify and provide the correct documents.'
// .tr,
// );
// },
// icon: const Icon(Icons.volume_up),
// ),
// ],
// ),
// actions: [
// TextButton(
// onPressed: () {
// Get.back();
// },
// child: const Text('OK'),
// ),
// ],
// );
// }
else {
await addDriverEgypt();
await addRegistrationCarEgypt();
if (isCarSaved && isDriverSaved) {
Get.snackbar('added', '',
backgroundColor:
AppColor.greenColor); // Get.offAll(() => HomeCaptain());
// Get.offAll(() => HomeCaptain());
}
}
}
Future<void> addDriverEgypt() async {
isLoading = true;
update();
var payload = {
'first_name': responseIdEgyptDriverLicense['firstName']?.toString() ??
'Not specified',
'last_name': responseIdEgyptDriverLicense['lastName']?.toString() ??
'Not specified',
'email': email?.toString() ?? 'Not specified',
'phone': phone?.toString() ?? 'Not specified',
'id': driverId?.toString() ?? 'Not specified',
'password': '123456',
'gender': responseIdEgyptBack['gender']?.toString() ?? 'Not specified',
'license_type':
responseIdEgyptDriverLicense['license_type']?.toString() ??
'Not specified',
'national_number':
responseIdEgyptBack['nationalID']?.toString() ?? 'Not specified',
'name_arabic': responseIdEgyptDriverLicense['name_arabic']?.toString() ??
'Not specified',
'name_english':
responseIdEgyptDriverLicense['name_english']?.toString() ??
'Not specified',
'issue_date': responseIdEgyptDriverLicense['issue_date']?.toString() ??
'Not specified',
'expiry_date': responseIdEgyptDriverLicense['expiry_date']?.toString() ??
'Not specified',
'license_categories': responseIdEgyptDriverLicense['license_categories']
is List
? responseIdEgyptDriverLicense['license_categories'].join(', ')
: responseIdEgyptDriverLicense['license_categories']?.toString() ??
'Not specified',
'address': responseIdEgyptFront['address']?.toString() ?? 'Not specified',
'card_id': responseIdEgyptFront['card_id']?.toString() ?? 'Not specified',
'occupation':
responseIdEgyptBack['occupation']?.toString() ?? 'Not specified',
'education':
responseIdEgyptBack['occupation']?.toString() ?? 'Not specified',
'licenseIssueDate':
responseIdEgyptDriverLicense['issue_date']?.toString() ??
'Not specified',
'religion':
responseIdEgyptBack['religion']?.toString() ?? 'Not specified',
'status': 'yet',
'birthdate': responseIdEgyptFront['dob']?.toString() ?? 'Not specified',
'maritalStatus':
responseIdEgyptBack['maritalStatus']?.toString() ?? 'Not specified',
'site': responseIdEgyptDriverLicense['address']?.toString() ??
'Not specified',
'employmentType':
responseIdEgyptDriverLicense['employmentType']?.toString() ??
'Not specified',
};
var res = await CRUD().post(link: AppLink.signUpCaptin, payload: payload);
var status1 = jsonDecode(res);
isLoading = false;
update();
// Handle response
if (status1['status'] == 'success') {
isDriverSaved = true;
Get.snackbar('Success', 'Driver data saved successfully',
backgroundColor: AppColor.greenColor);
} else {
Get.snackbar('Error', 'Failed to save driver data',
backgroundColor: Colors.red);
}
}
addCriminalDeocuments() async {
var res = await CRUD().post(link: AppLink.addCriminalDocuments, payload: {
"driverId": box.read(BoxName.driverID),
"IssueDate": responseCriminalRecordEgypt['IssueDate'],
"InspectionResult": responseCriminalRecordEgypt['InspectionResult'],
});
if (res != 'failure') {
Get.snackbar('uploaded sucssefuly'.tr, '');
}
}
Future addRegistrationCarEgypt() async {
try {
isLoading = true;
update();
var res = await CRUD().post(link: AppLink.addRegisrationCar, payload: {
'driverID': driverId,
'vin': responseIdCardDriverEgyptBack['chassis'].toString(),
'car_plate': responseIdCardDriverEgyptFront['car_plate'].toString(),
'make': responseIdCardDriverEgyptBack['make'].toString(),
'model': responseIdCardDriverEgyptBack['model'],
'year': responseIdCardDriverEgyptBack['year'].toString(),
'expiration_date':
responseIdCardDriverEgyptFront['LicenseExpirationDate'].toString(),
'color': responseIdCardDriverEgyptBack['color'],
'owner': responseIdCardDriverEgyptFront['owner'],
'color_hex': responseIdCardDriverEgyptBack['color_hex'].toString(),
'address': responseIdCardDriverEgyptFront['address'].toString(),
'displacement': responseIdCardDriverEgyptBack['engine'].toString(),
'fuel': responseIdCardDriverEgyptBack['fuel'].toString(),
'registration_date':
'${responseIdCardDriverEgyptBack['inspection_date']}',
});
isLoading = false;
update();
var status = jsonDecode(res);
if (status['status'] == 'success') {
isCarSaved = true;
Get.snackbar('Success', 'message',
backgroundColor: AppColor.greenColor);
}
} catch (e) {}
}
Future getComplaintDataToAI() async {
var res = await CRUD().get(
link: AppLink.getComplaintAllDataForDriver,
payload: {'driver_id': driverId.toString()},
);
if (res != 'failure') {
var d = jsonDecode(res)['message'];
return d;
} else {
return [
{'data': 'no data'}
];
}
}
Future<dynamic> anthropicAIForComplaint() async {
var dataComplaint = await getComplaintDataToAI();
var messagesData = [
{
"role": "user",
"content": [
{
"type": "text",
"text": "$dataComplaint ${AppInformation.complaintPrompt} "
}
]
}
];
var requestBody = jsonEncode({
"model": "claude-3-haiku-20240307",
"max_tokens": 1024,
"temperature": 0,
"system": "Json output only without any additional ",
"messages": messagesData,
});
final response = await http.post(
Uri.parse('https://api.anthropic.com/v1/messages'),
headers: {
'x-api-key': AK.anthropicAIkeySeferNew,
'anthropic-version': '2023-06-01',
'content-type': 'application/json'
},
body: requestBody,
);
if (response.statusCode == 200) {
var responseData = jsonDecode(utf8.decode(response.bodyBytes));
// Process the responseData as needed
responseForComplaint = jsonDecode(responseData['content'][0]['text']);
}
}
Future<dynamic> anthropicAI(
String payload, String prompt, String idType) async {
var messagesData = [
{
"role": "user",
"content": [
{"type": "text", "text": "$payload $prompt"}
]
}
];
var requestBody = jsonEncode({
"model": "claude-3-haiku-20240307",
"max_tokens": 1024,
"temperature": 0,
"system": "Json output only without any additional ",
"messages": messagesData,
});
final response = await http.post(
Uri.parse('https://api.anthropic.com/v1/messages'),
headers: {
'x-api-key': AK.anthropicAIkeySeferNew,
'anthropic-version': '2023-06-01',
'content-type': 'application/json'
},
body: requestBody,
);
if (response.statusCode == 200) {
var responseData = jsonDecode(utf8.decode(response.bodyBytes));
// Process the responseData as needed
if (idType == 'car_back') {
responseIdCardDriverEgyptBack =
jsonDecode(responseData['content'][0]['text']);
} else if (idType == 'car_front') {
responseIdCardDriverEgyptFront =
jsonDecode(responseData['content'][0]['text']);
} else if (idType == 'id_front') {
responseIdEgyptFront = jsonDecode(responseData['content'][0]['text']);
} else if (idType == 'id_back') {
responseIdEgyptBack = jsonDecode(responseData['content'][0]['text']);
} else if (idType == 'driver_license') {
responseIdEgyptDriverLicense =
jsonDecode(responseData['content'][0]['text']);
} else if (idType == 'criminalRecord') {
responseCriminalRecordEgypt =
jsonDecode(responseData['content'][0]['text']);
}
update();
return responseData.toString();
}
return responseIdCardDriverEgyptBack.toString();
}
Future<void> geminiAiExtraction(String prompt, payload, String idType) async {
var requestBody = jsonEncode({
"contents": [
{
"parts": [
{"text": "$payload $prompt"}
]
}
],
"generationConfig": {
"temperature": 1,
"topK": 64,
"topP": 0.95,
"maxOutputTokens": 8192,
"stopSequences": []
},
"safetySettings": [
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
}
]
});
final response = await http.post(
Uri.parse(
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent?key=${AK.geminiApi}'),
'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro:generateContent?key=${AK.geminiApi}'),
headers: {'Content-Type': 'application/json'},
body: requestBody,
);
if (response.statusCode == 200) {
var responseData = jsonDecode(response.body);
// Process the responseData as needed
var result = responseData['candidates'][0]['content']['parts'][0]['text'];
RegExp regex = RegExp(r"```json([^`]*)```");
String? jsonString =
regex.firstMatch(responseData.toString())?.group(1)?.trim();
if (jsonString != null) {
// Convert the JSON object to a String
jsonString = jsonEncode(json.decode(jsonString));
if (idType == 'car_back') {
responseIdCardDriverEgyptBack = jsonDecode(jsonString);
} else if (idType == 'car_front') {
responseIdCardDriverEgyptFront = jsonDecode(jsonString);
} else if (idType == 'id_front') {
responseIdEgyptFront = jsonDecode(jsonString);
} else if (idType == 'id_back') {
responseIdEgyptBack = jsonDecode(jsonString);
} else if (idType == 'driver_license') {
responseIdEgyptDriverLicense = jsonDecode(jsonString);
}
update();
} else {
Get.snackbar('Error', "JSON string not found",
backgroundColor: AppColor.redColor);
}
// Rest of your code...
} else {}
}
}

View File

@@ -0,0 +1,73 @@
import 'dart:convert';
import 'package:fl_chart/fl_chart.dart';
import 'package:get/get.dart';
import '../../constant/links.dart';
import '../../models/model/admin/monthly_ride.dart';
import '../functions/crud.dart';
class RideAdminController extends GetxController {
bool isLoading = false;
late List<MonthlyDataModel> rideData;
late Map<String, dynamic> jsonResponse;
List<dynamic> ridesDetails = [];
var chartData;
// late List<ChartDataS> chartDatasync;
Future getRidesAdminDash() async {
isLoading = true;
update();
var res = await CRUD().get(link: AppLink.getRidesPerMonth, payload: {});
jsonResponse = jsonDecode(res);
rideData = (jsonResponse['message'] as List)
.map((item) => MonthlyDataModel.fromJson(item))
.toList();
chartData = rideData
.map((data) => FlSpot(data.day.toDouble(), data.ridesCount.toDouble()))
.toList();
// chartDatasync = (jsonResponse['message'] as List)
// .map((item) => ChartDataS(
// item['year'],
// item['month'],
// item['day'],
// item['rides_count'],
// ))
// .toList();
isLoading = false;
update();
}
Future getRidesDetails() async {
// isLoading = true;
// update();
var res = await CRUD().get(link: AppLink.getRidesDetails, payload: {});
var d = jsonDecode(res);
ridesDetails = d['message'];
// isLoading = false;
// update();
}
@override
void onInit() async {
List<Future> initializationTasks = [
getRidesAdminDash(),
getRidesDetails(),
];
// cameras = await availableCameras();
await Future.wait(initializationTasks);
super.onInit();
}
}
// class ChartDataS {
// ChartDataS(this.year, this.month, this.day, this.ridesCount);
// final int year;
// final int month;
// final int day;
// final int ridesCount;
// }

View File

@@ -0,0 +1,238 @@
import 'dart:convert';
import 'package:fl_chart/fl_chart.dart';
import 'package:get/get.dart';
import '../../constant/links.dart';
import '../../models/model/passengers_model.dart';
import '../../print.dart';
import '../functions/crud.dart';
class StaticController extends GetxController {
Map<String, dynamic> jsonData1 = {};
Map<String, dynamic> jsonData2 = {};
List staticList = [];
var chartDataPassengers;
var chartDataDrivers;
var chartDataDriversCalling;
var chartDataRides;
var chartDataEmployee;
var chartDataEmployeeMaryam;
var chartDataEmployeeRawda;
var chartDataEmployeeMena;
var chartDataEmployeeSefer4;
var chartDataDriversMatchingNotes;
bool isLoading = false;
String totalMonthlyPassengers = '';
String totalMonthlyRides = '';
String totalMonthlyEmployee = '';
String totalMonthlyDrivers = '';
late List<MonthlyPassengerInstall> passengersData;
late List<MonthlyRidesInstall> ridesData;
late List<MonthlyEmployeeData> employeeData;
late List<MonthlyDriverInstall> driversData;
Future<void> fetch() async {
isLoading = true;
update(); // Notify the observers about the loading state change
var res = await CRUD().get(
link: AppLink.getPassengersStatic,
payload: {},
);
jsonData1 = jsonDecode(res);
var jsonResponse = jsonDecode(res) as Map<String, dynamic>;
isLoading = false;
final List<dynamic> jsonData = jsonResponse['message'];
totalMonthlyPassengers = jsonData[0]['totalMonthly'].toString();
passengersData = jsonData.map<MonthlyPassengerInstall>((item) {
return MonthlyPassengerInstall.fromJson(item);
}).toList();
final List<FlSpot> spots = passengersData
.map((data) => FlSpot(
data.day.toDouble(),
data.totalPassengers.toDouble(),
))
.toList();
chartDataPassengers = spots;
update(); // Notify the observers about the data and loading state change
}
Future<void> fetchRides() async {
isLoading = true;
update(); // Notify the observers about the loading state change
var res = await CRUD().get(
link: AppLink.getRidesStatic,
payload: {},
);
jsonData1 = jsonDecode(res);
var jsonResponse = jsonDecode(res) as Map<String, dynamic>;
isLoading = false;
final List<dynamic> jsonData = jsonResponse['message'];
totalMonthlyRides = jsonData[0]['totalMonthly'].toString();
ridesData = jsonData.map<MonthlyRidesInstall>((item) {
return MonthlyRidesInstall.fromJson(item);
}).toList();
final List<FlSpot> spots = ridesData
.map((data) => FlSpot(
data.day.toDouble(),
data.totalRides.toDouble(),
))
.toList();
chartDataRides = spots;
update(); // Notify the observers about the data and loading state change
}
Future<void> fetchEmployee() async {
try {
isLoading = true;
update();
var res = await CRUD().get(link: AppLink.getEmployeeStatic, payload: {});
// First check if the response is valid JSON
if (res == 'failure') {
throw FormatException('Invalid response: $res');
}
var jsonResponse = jsonDecode(res) as Map<String, dynamic>;
// Initialize empty lists for all chart data
chartDataEmployeeMaryam = <FlSpot>[];
chartDataEmployeeRawda = <FlSpot>[];
chartDataEmployeeMena = <FlSpot>[];
chartDataEmployeeSefer4 = <FlSpot>[];
totalMonthlyRides = '0';
// Check for error response
if (jsonResponse['status'] == 'failure') {
isLoading = false;
update();
return;
}
final List<dynamic> jsonData = jsonResponse['message'];
if (jsonData.isEmpty) {
isLoading = false;
update();
return;
}
totalMonthlyRides = jsonData[0]['totalMonthly']?.toString() ?? '0';
// Group data by employee
Map<String, List<MonthlyEmployeeData>> employeeDataMap = {};
for (var item in jsonData) {
var employeeData = MonthlyEmployeeData.fromJson(item);
if (!employeeDataMap.containsKey(employeeData.name)) {
employeeDataMap[employeeData.name] = [];
}
employeeDataMap[employeeData.name]!.add(employeeData);
}
final today = DateTime.now().day;
// Create data for each employee
final employeeNames = {
'maryam': chartDataEmployeeMaryam,
'yasmine': chartDataEmployeeRawda,
'mena': chartDataEmployeeMena,
'ashjan': chartDataEmployeeSefer4,
};
employeeNames.forEach((name, chartData) {
var spots = <FlSpot>[];
for (int day = 1; day <= today; day++) {
spots.add(FlSpot(
day.toDouble(),
employeeDataMap[name]
?.firstWhere(
(e) => e.day == day,
orElse: () => MonthlyEmployeeData(
day: day,
totalEmployees: 0,
name: name,
),
)
.totalEmployees
.toDouble() ??
0,
));
}
// Explicitly cast to List<FlSpot>
if (name == 'maryam')
chartDataEmployeeMaryam = List<FlSpot>.from(spots);
if (name == 'yasmine')
chartDataEmployeeRawda = List<FlSpot>.from(spots);
if (name == 'mena') chartDataEmployeeMena = List<FlSpot>.from(spots);
if (name == 'ashjan')
chartDataEmployeeSefer4 = List<FlSpot>.from(spots);
});
} catch (e) {
Log.print('Error in fetchEmployee: $e');
// Set empty FlSpot lists in case of error
chartDataEmployeeMaryam = <FlSpot>[];
chartDataEmployeeRawda = <FlSpot>[];
chartDataEmployeeMena = <FlSpot>[];
chartDataEmployeeSefer4 = <FlSpot>[];
totalMonthlyRides = '0';
} finally {
isLoading = false;
update();
}
}
Future<void> fetchDrivers() async {
isLoading = true;
update(); // Notify the observers about the loading state change
var res = await CRUD().get(
link: AppLink.getdriverstotalMonthly,
payload: {},
);
jsonData2 = jsonDecode(res);
var jsonResponse = jsonDecode(res) as Map<String, dynamic>;
isLoading = false;
final List<dynamic> jsonData = jsonResponse['message'];
staticList = jsonData;
totalMonthlyDrivers = jsonData[0]['totalDrivers'].toString();
driversData = jsonData.map<MonthlyDriverInstall>((item) {
return MonthlyDriverInstall.fromJson(item);
}).toList();
final List<FlSpot> spots = driversData
.map((data) => FlSpot(
data.day.toDouble(),
data.dailyTotalDrivers.toDouble(),
))
.toList();
chartDataDrivers = spots;
final List<FlSpot> spotsCalling = driversData
.map((data) => FlSpot(
data.day.toDouble(),
data.dailyTotalCallingDrivers.toDouble(),
))
.toList();
chartDataDriversCalling = spotsCalling;
final List<FlSpot> spotsTotalMatchingNotes = driversData
.map((data) => FlSpot(
data.day.toDouble(),
data.dailyMatchingNotes.toDouble(),
))
.toList();
chartDataDriversMatchingNotes = spotsTotalMatchingNotes;
update(); // Notify the observers about the data and loading state change
}
Future getAll() async {
await fetch();
await fetchRides();
await fetchDrivers();
await fetchEmployee();
}
}

View File

@@ -0,0 +1,195 @@
import 'dart:async';
import 'dart:convert';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import '../../constant/api_key.dart';
import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../../print.dart';
import '../functions/crud.dart';
class WalletAdminController extends GetxController {
bool isLoading = false;
late Map<String, dynamic> jsonResponse;
List<dynamic> walletDetails = [];
List driversWalletPoints = [];
@override
void onInit() {
getWalletForEachDriverToPay();
super.onInit();
}
Future getWalletAdminDash() async {
isLoading = true;
update();
var res = await CRUD().get(link: AppLink.getRidesPerMonth, payload: {});
jsonResponse = jsonDecode(res);
}
Future payToBankDriverAll() async {
for (var i = 0; i < driversWalletPoints.length; i++) {
String token = await getToken();
await Future.delayed(const Duration(seconds: 1));
try {
await payToDriverBankAccount(
token,
driversWalletPoints[i]['total_amount'].toString(),
driversWalletPoints[i]['accountBank'].toString(),
driversWalletPoints[i]['bankCode'].toString(),
driversWalletPoints[i]['name_arabic'].toString(),
driversWalletPoints[i]['driverID'].toString(),
driversWalletPoints[i]['phone'].toString(),
driversWalletPoints[i]['email'].toString(),
);
await Future.delayed(const Duration(seconds: 3));
} on FormatException catch (e) {
// Handle the error or rethrow the exception as needed
}
}
}
Future<void> payToDriverBankAccount(
String token,
String amount,
String bankCardNumber,
String bankCode,
String name,
String driverId,
String phone,
String email) async {
var headers = {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
};
var body = jsonEncode({
"issuer": "bank_card",
"amount": amount,
"full_name": name,
"bank_card_number": bankCardNumber,
"bank_code": bankCode,
"bank_transaction_type": "cash_transfer"
});
var response = await http.post(
Uri.parse(
'https://stagingpayouts.paymobsolutions.com/api/secure/disburse/'),
headers: headers,
body: body);
if (response.statusCode == 200) {
var d = jsonDecode(response.body);
if (d['status_description'] ==
"Transaction received and validated successfully. Dispatched for being processed by the bank") {
await addPayment('payFromSeferToDriver', driverId,
((-1) * double.parse(amount)).toString());
await addSeferWallet('payFromSeferToDriver', driverId,
((-1) * double.parse(amount)).toString());
await updatePaymentToPaid(driverId);
await sendEmail(driverId, amount, phone, name, bankCardNumber, email);
}
} else {}
}
// String paymentToken = '';
Future<String> generateToken(String amount) async {
var res = await CRUD().post(link: AppLink.addPaymentTokenDriver, payload: {
'driverID': box.read(BoxName.driverID).toString(),
'amount': amount.toString(),
});
var d = jsonDecode(res);
return d['message'];
}
Future sendEmail(
String driverId, amount, phone, name, bankCardNumber, email) async {
await CRUD().sendEmail(AppLink.sendEmailToDrivertransaction, {
"driverID": driverId,
"total_amount": amount,
"phone": phone,
"name_arabic": name,
"accountBank": bankCardNumber,
"email": email
});
}
Future addSeferWallet(
String paymentMethod, String driverID, String point) async {
var seferToken = await generateToken(point.toString());
await CRUD().post(link: AppLink.addSeferWallet, payload: {
'amount': point.toString(),
'paymentMethod': paymentMethod,
'passengerId': 'driver',
'token': seferToken,
'driverId': driverID.toString(),
});
}
Future addPayment(
String paymentMethod, String driverID, String amount) async {
var paymentToken =
await generateToken(((double.parse(amount))).toStringAsFixed(0));
await CRUD().post(link: AppLink.addDrivePayment, payload: {
'rideId': DateTime.now().toIso8601String(),
'amount': ((double.parse(amount))).toStringAsFixed(0),
'payment_method': paymentMethod,
'passengerID': 'myself',
'token': paymentToken,
'driverID': driverID.toString(),
});
}
Future updatePaymentToPaid(String driverID) async {
await CRUD().post(link: AppLink.updatePaymetToPaid, payload: {
'driverID': driverID.toString(),
});
}
Future<String> getToken() async {
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
// 'Cookie':
// 'csrftoken=74iZJ8XYyuTm5WRq2W4tpWX5eqoJLZVK5QhuDrChWpDtzpgGA269bbCWuEcW85t4'
};
var body = {
'grant_type': 'password',
'username': AK.payMobOutUserName,
'password': AK.payMobOutPassword,
'client_id': AK.payMobOutClient_id,
'client_secret': AK.payMobOutClientSecrret
};
var res = await http.post(
Uri.parse(
'https://stagingpayouts.paymobsolutions.com/api/secure/o/token/'),
headers: headers,
body: body,
);
String token = '';
if (res.statusCode == 200) {
var decode = jsonDecode(res.body);
token = decode['access_token'];
}
return token;
}
Future getWalletForEachDriverToPay() async {
isLoading = true;
update();
var res = await CRUD()
.postWallet(link: AppLink.getVisaForEachDriver, payload: {});
var d = (res);
if (d != 'failure') {
driversWalletPoints = d['message'];
isLoading = false;
update();
}
driversWalletPoints = [];
isLoading = false;
update();
}
}

View File

@@ -0,0 +1,56 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'otp_helper.dart';
class OtpVerificationAdmin extends StatefulWidget {
final String phone;
const OtpVerificationAdmin({required this.phone});
@override
State<OtpVerificationAdmin> createState() => _OtpVerificationAdminState();
}
class _OtpVerificationAdminState extends State<OtpVerificationAdmin> {
final _otpController = TextEditingController();
bool _isLoading = false;
Future<void> _verifyOtp() async {
setState(() => _isLoading = true);
final otpHelper = OtpHelper();
await otpHelper.verifyOtp(widget.phone, _otpController.text.trim());
// if (success) {
// Get.offAllNamed('/admin-dashboard');
// } else {
// Get.snackbar('خطأ', 'رمز التحقق غير صحيح');
// }
setState(() => _isLoading = false);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('التحقق من الرمز')),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
TextFormField(
controller: _otpController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(labelText: 'رمز التحقق'),
),
const SizedBox(height: 20),
_isLoading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: _verifyOtp,
child: const Text('تحقق وأدخل'),
)
],
),
),
);
}
}

View File

@@ -0,0 +1,114 @@
import 'package:get/get.dart';
import 'package:sefer_admin1/controller/functions/device_info.dart';
import 'package:sefer_admin1/views/auth/login_page.dart';
import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../../print.dart';
import '../../views/admin/admin_home_page.dart';
import '../../views/widgets/snackbar.dart';
import '../functions/crud.dart';
class OtpHelper extends GetxController {
static final String _sendOtpUrl =
'${AppLink.server}/Admin/auth/send_otp_admin.php';
static final String _verifyOtpUrl =
'${AppLink.server}/Admin/auth/verify_otp_admin.php';
static final String _checkAdminLogin =
'${AppLink.server}/Admin/auth/login.php';
/// إرسال OTP
static Future<bool> sendOtp(String phoneNumber) async {
try {
final response = await CRUD().post(
link: _sendOtpUrl,
payload: {'receiver': phoneNumber},
);
if (response != 'failure') {
mySnackeBarError('تم إرسال رمز التحقق إلى رقمك عبر WhatsApp');
return true;
} else {
mySnackeBarError('حدث خطأ من الخادم. حاول مجددًا.');
return false;
}
} catch (e) {
Log.print('OTP SEND ERROR: $e');
mySnackeBarError('حدث خطأ أثناء الإرسال: $e');
return false;
}
}
/// التحقق من OTP
Future<void> verifyOtp(String phoneNumber, String otp) async {
try {
final response = await CRUD().post(
link: _verifyOtpUrl,
payload: {
'phone_number': phoneNumber,
'otp': otp,
'device_number': box.read(BoxName.fingerPrint)
},
);
if (response != 'failure') {
if (response['status'] == 'success') {
box.write(BoxName.phoneVerified, true);
box.write(BoxName.adminPhone, phoneNumber);
mySnackbarSuccess('تم التحقق من الرقم بنجاح');
await checkAdminLogin();
} else {
mySnackeBarError(response['message'] ?? 'فشل في التحقق.');
}
} else {
mySnackeBarError('فشل من الخادم. حاول مرة أخرى.');
}
} catch (e) {
Log.print('OTP VERIFY ERROR: $e');
mySnackeBarError('خطأ في التحقق: $e');
}
}
Future<void> checkAdminLogin() async {
final deviceNumber =
box.read(BoxName.fingerPrint); // خزّنه عند التشغيل أول مرة
final phoneNumber = box.read(BoxName.adminPhone); // عند التحقق من OTP
if (deviceNumber != null && phoneNumber != null) {
final response = await CRUD().post(
link: _checkAdminLogin,
payload: {
"device_number": deviceNumber,
"phone_number": phoneNumber,
},
);
if (response != "failure") {
Get.offAll(() => AdminHomePage());
} else {
Get.offAll(() => AdminLoginPage());
}
} else {
Get.offAll(() => AdminLoginPage());
}
}
@override
void onInit() {
super.onInit();
DeviceHelper.getDeviceFingerprint().then((deviceFingerprint) {
box.write(BoxName.fingerPrint, deviceFingerprint);
});
// تأجيل تنفيذ التنقل حتى تنتهي مرحلة البناء
Future.microtask(() {
if (box.read(BoxName.phoneVerified) == true &&
box.read(BoxName.adminPhone) != null) {
checkAdminLogin();
} else {
Get.offAll(() => AdminLoginPage());
}
});
}
}

View File

@@ -0,0 +1,113 @@
import 'dart:convert';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import '../../../constant/links.dart';
import '../../constant/api_key.dart';
import '../../constant/box_name.dart';
import '../../constant/colors.dart';
import '../../main.dart';
import '../functions/crud.dart';
class PaymobPayout extends GetxController {
bool isLoading = false;
String dropdownValue = 'etisalat';
Future<String> getToken() async {
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
// 'Cookie':
// 'csrftoken=74iZJ8XYyuTm5WRq2W4tpWX5eqoJLZVK5QhuDrChWpDtzpgGA269bbCWuEcW85t4'
};
var body = {
'grant_type': 'password',
'username': AK.payMobOutUserName,
'password': AK.payMobOutPassword,
'client_id': AK.payMobOutClient_id,
'client_secret': AK.payMobOutClientSecrret
};
var res = await http.post(
Uri.parse('https://payouts.paymobsolutions.com/api/secure/o/token/'),
headers: headers,
body: body,
);
String token = '';
if (res.statusCode == 200) {
var decode = jsonDecode(res.body);
token = decode['access_token'];
}
return token;
}
payToDriverWallet(
String token, String amount, String issuer, String msisdn) async {
var headers = {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
};
var body = json.encode({
"amount": amount, //"10.00",
"issuer": issuer, //"vodafone",
"msisdn": msisdn, // "01023456789"
});
var res = await http.post(
Uri.parse('https://payouts.paymobsolutions.com/api/secure/disburse/'),
headers: headers,
body: body,
);
var dec = jsonDecode(res.body);
if (dec['disbursement_status'] == 'successful') {
await CRUD().post(link: AppLink.addDriverpayment, payload: {
'rideId': DateTime.now().toIso8601String(),
'amount': ((-1) * (double.parse(dec['amount'])) + 5).toStringAsFixed(0),
'payment_method': 'payout',
'passengerID': 'admin',
'driverID': box.read(BoxName.driverID).toString(),
});
Get.snackbar('Transaction successful'.tr,
'${'Transaction successful'.tr} ${dec['amount']}',
backgroundColor: AppColor.greenColor);
// Get.find<CaptainWalletController>().getCaptainWalletFromRide();
} else if (dec['disbursement_status'] == 'failed') {
Get.snackbar('Transaction failed'.tr, 'Transaction failed'.tr,
backgroundColor: AppColor.redColor);
}
}
payToDriverBankAccount(String token, String amount, String bankCardNumber,
String bankCode) async {
var headers = {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
};
var body = {
"issuer": "bank_card",
"amount": amount, //9.0,
"full_name":
'${box.read(BoxName.nameDriver)} ${box.read(BoxName.lastNameDriver)}',
"bank_card_number": bankCardNumber, //"1111-2222-3333-4444",
"bank_code": bankCode, //"CIB",
"bank_transaction_type": "cash_transfer"
};
var res = await http
.post(
Uri.parse('https://payouts.paymobsolutions.com/api/secure/disburse/'),
headers: headers,
body: body,
)
.then((value) {});
}
Future payToWalletDriverAll(
String amount, String issuer, String msisdn) async {
String token = await getToken();
await payToDriverWallet(token, amount, issuer, msisdn);
}
Future payToBankDriverAll(
String amount, String bankCardNumber, String bankCode) async {
String token = await getToken();
await payToDriverBankAccount(token, amount, bankCardNumber, bankCode);
}
}

View File

@@ -0,0 +1,68 @@
import 'dart:convert';
import 'package:get/get.dart';
import '../../constant/colors.dart';
import '../../constant/links.dart';
import '../functions/crud.dart';
class Driverthebest extends GetxController {
bool isLoading = false;
List driver = [];
getBestDriver() async {
var res = await CRUD().get(link: AppLink.getBestDriver, payload: {});
if (res != 'failure') {
driver = jsonDecode(res)['message'];
update();
} else {
Get.snackbar('error', '', backgroundColor: AppColor.redColor);
}
}
@override
void onInit() {
getBestDriver();
super.onInit();
}
}
class DriverTheBestGizaController extends GetxController {
bool isLoading = false;
List driver = [];
getBestDriver() async {
var res = await CRUD().get(link: AppLink.getBestDriverGiza, payload: {});
if (res != 'failure') {
driver = jsonDecode(res)['message'];
update();
} else {
Get.snackbar('error', '', backgroundColor: AppColor.redColor);
}
}
@override
void onInit() {
getBestDriver();
super.onInit();
}
}
class DriverTheBestAlexandriaController extends GetxController {
bool isLoading = false;
List driver = [];
getBestDriver() async {
var res =
await CRUD().get(link: AppLink.getBestDriverAlexandria, payload: {});
if (res != 'failure') {
driver = jsonDecode(res)['message'];
update();
} else {
Get.snackbar('error', '', backgroundColor: AppColor.redColor);
}
}
@override
void onInit() {
getBestDriver();
super.onInit();
}
}

View File

@@ -0,0 +1,76 @@
import 'dart:convert';
import 'dart:math';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sefer_admin1/constant/colors.dart';
import 'package:sefer_admin1/constant/links.dart';
import 'package:sefer_admin1/controller/functions/crud.dart';
class EmployeeController extends GetxController {
List employee = [];
final name = TextEditingController();
final education = TextEditingController();
final site = TextEditingController();
final phone = TextEditingController();
final status = TextEditingController();
final formKey = GlobalKey<FormState>();
fetchEmployee() async {
var res = await CRUD().get(link: AppLink.getEmployee, payload: {});
if (res != 'failure') {
employee = jsonDecode(res)['message'];
update();
} else {
Get.snackbar('error', '', backgroundColor: AppColor.redColor);
}
}
late String id;
String generateRandomId(int length) {
const String chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
Random random = Random();
return String.fromCharCodes(Iterable.generate(
length,
(_) => chars.codeUnitAt(random.nextInt(chars.length)),
));
}
addEmployee() async {
// Create the payload with the employee data
var res = await CRUD().post(link: AppLink.addEmployee, payload: {
"id": id,
"name": name.text,
"education": education.text,
"site": site.text,
"phone": phone.text,
"status": status.text,
});
// Check the response from the API
if (res != 'failure') {
// You can handle the success case here, such as showing a success message
Get.back();
Get.snackbar('Success', 'Employee added successfully',
backgroundColor: AppColor.greenColor);
name.clear();
education.clear();
site.clear();
phone.clear();
status.clear();
fetchEmployee();
} else {
// Handle the error case by showing a snackbar with an error message
Get.snackbar('Error', 'Failed to add employee',
backgroundColor: AppColor.redColor);
}
}
@override
void onInit() {
fetchEmployee();
super.onInit();
}
}

View File

@@ -0,0 +1,517 @@
import 'dart:convert';
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:secure_string_operations/secure_string_operations.dart';
import 'package:sefer_admin1/constant/info.dart';
import 'package:sefer_admin1/env/env.dart';
import '../../constant/api_key.dart';
import '../../constant/box_name.dart';
import '../../constant/char_map.dart';
import '../../constant/colors.dart';
import '../../constant/links.dart';
import '../../constant/style.dart';
import '../../main.dart';
import '../../print.dart';
import '../../views/widgets/elevated_btn.dart';
import '../functions/encrypt_decrypt.dart';
import '../notification_controller.dart';
import 'local_notification.dart';
import 'token_access.dart';
class FirebaseMessagesController extends GetxController {
final fcmToken = FirebaseMessaging.instance;
List<String> tokens = [];
List<String> tokensPassengers = [];
List dataTokens = [];
List dataTokensPassenger = [];
late String driverID;
late String driverToken;
NotificationSettings? notificationSettings;
bool isLoading = false;
Future<void> getNotificationSettings() async {
// Get the current notification settings
NotificationSettings? notificationSettings =
await FirebaseMessaging.instance.getNotificationSettings();
'Notification authorization status: ${notificationSettings.authorizationStatus}';
// Call the update function if needed
update();
}
Future<void> requestFirebaseMessagingPermission() async {
FirebaseMessaging messaging = FirebaseMessaging.instance;
// Check if the platform is Android
if (Platform.isAndroid) {
// Request permission for Android
await messaging.requestPermission();
} else if (Platform.isIOS) {
// Request permission for iOS
NotificationSettings settings = await messaging.requestPermission(
alert: true,
announcement: true,
badge: true,
carPlay: true,
criticalAlert: true,
provisional: false,
sound: true,
);
messaging.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
}
}
Future getTokens() async {
var res = await http.post(
Uri.parse(AppLink.getTokens),
headers: {
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
},
body: {},
);
var jsonResponse = jsonDecode(res.body);
if (jsonResponse['status'] == 'success') {
dataTokens = jsonResponse['data'];
for (var i = 0; i < dataTokens.length; i++) {
tokens.add(jsonResponse['data'][i]['token']);
}
box.write(BoxName.tokens, tokens);
} else {
Get.defaultDialog(title: "Warning", middleText: "Server Error");
}
}
var currentPage = 1;
var totalPages = 1;
Future<void> getAllTokenDrivers() async {
isLoading = true;
try {
var res = await http.post(
Uri.parse(AppLink.getDriversPhonesAndTokens),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
// 'Authorization': 'Bearer ${box.read(BoxName.jwt)}'
},
body: {
// 'page': page.toString(),
},
);
var jsonResponse = jsonDecode(res.body);
Log.print('jsonResponse: ${jsonResponse}');
if (jsonResponse['status'] == 'success') {
// var newData = jsonResponse['data'] as List;
// Log.print('newData: ${newData}');
// // if (page == 1) {
// // dataTokens.clear();
// // tokens.clear();
// // }
// dataTokens.addAll(newData);
// for (var item in newData) {
// tokens.add(item['token']);
// }
// currentPage = int.parse(jsonResponse['currentPage']);
// totalPages = jsonResponse['totalPages'];
box.write(BoxName.tokensDrivers, jsonResponse);
Log.print(
'box.write(BoxName.tokensDrivers: ${box.read(BoxName.tokensDrivers)}');
} else {
Get.defaultDialog(
title: "Warning", middleText: "No more data available");
}
} catch (e) {
Get.defaultDialog(title: "Error", middleText: "Server Error: $e");
} finally {
isLoading = false;
}
}
var currentPagePassenger = 1;
var totalPagesPassenger = 1;
Future<void> getAllTokenPassenger({int page = 1}) async {
isLoading = true;
try {
var res = await http.post(
Uri.parse(AppLink.getAllTokenPassengers),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
},
body: {},
);
var jsonResponse = jsonDecode(res.body);
if (jsonResponse['status'] == 'success') {
box.write(BoxName.tokensPassengers, jsonResponse);
Log.print(
'box.write(BoxName.tokensPassenger: ${box.read(BoxName.tokensPassengers)}');
} else {
Get.defaultDialog(
title: "Warning", middleText: "No more data available");
}
} catch (e) {
Get.defaultDialog(title: "Error", middleText: "Server Error: $e");
} finally {
isLoading = false;
}
}
bool isSendingNotifications = false;
Future<void> loadAllPagesAndSendNotifications() async {
isSendingNotifications = true;
// currentPage = 1;
// while (currentPage <= totalPages) {
// await getAllTokenDrivers(page: currentPage);
await getAllTokenDrivers();
// Log.print('tokens: ${tokens}');
await NotificationController().sendNotificationDrivers();
// print(tokens);
// if (currentPage < totalPages) {
// await Future.delayed(const Duration(seconds: 3));
// }
// currentPage++;
// }
isSendingNotifications = false;
Get.snackbar("Success", "All notifications sent!");
}
bool isSendingNotificationsPassenger = false;
Future<void> loadAllPagesAndSendNotificationsPassengers() async {
isSendingNotificationsPassenger = true;
currentPage = 1;
// while (currentPagePassenger <= totalPagesPassenger) {
await getAllTokenPassenger();
await NotificationController().sendNotificationPassengers();
// print(tokensPassengers);
// if (currentPagePassenger < totalPagesPassenger) {
// await Future.delayed(const Duration(seconds: 3));
// }
// currentPagePassenger++;
// }
isSendingNotificationsPassenger = false;
Get.snackbar("Success", "All notifications sent!");
}
Future getAllTokenPassengers() async {
var res = await http.post(
Uri.parse(AppLink.getAllTokenPassengers),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
// 'Authorization': 'Bearer ${box.read(BoxName.jwt)}'
},
body: {},
);
var jsonResponse = jsonDecode(res.body);
if (jsonResponse['status'] == 'success') {
dataTokens = jsonResponse['data'];
for (var i = 0; i < dataTokens.length; i++) {
tokensPassengers.add(jsonResponse['data'][i]['token']);
}
box.write(BoxName.tokensPassengers, jsonResponse['data']);
} else {
Get.defaultDialog(title: "Warning", middleText: "Server Error");
}
}
Future getToken() async {
fcmToken.getToken().then((token) {
if (box.read(BoxName.email) == null) {
box.write(BoxName.tokenDriver, token);
} else {
box.write(BoxName.tokenFCM, token);
}
});
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
// If the app is in the background or terminated, show a system tray message
RemoteNotification? notification = message.notification;
AndroidNotification? android = notification?.android;
// if (notification != null && android != null) {
if (message.data.isNotEmpty && message.notification != null) {
fireBaseTitles(message);
}
});
}
void fireBaseTitles(RemoteMessage message) {
if (message.notification!.title! == 'Order') {
if (Platform.isAndroid) {
// NotificationController().showNotification('Order', '', 'order');
}
var myListString = message.data['DriverList'];
// var points = message.data['PolylineJson'];
var myList = jsonDecode(myListString) as List<dynamic>;
// var myPoints = jsonDecode(points) as List<dynamic>;
driverToken = myList[14].toString();
// This is for location using and uploading status
update();
}
}
SnackbarController driverAppliedTripSnakBar() {
return Get.snackbar(
'Driver Applied the Ride for You'.tr,
'',
colorText: AppColor.greenColor,
duration: const Duration(seconds: 3),
snackPosition: SnackPosition.TOP,
titleText: Text(
'Applied'.tr,
style: const TextStyle(color: AppColor.redColor),
),
messageText: Text(
'Driver Applied the Ride for You'.tr,
style: AppStyle.title,
),
icon: const Icon(Icons.approval),
shouldIconPulse: true,
margin: const EdgeInsets.all(16),
padding: const EdgeInsets.all(16),
);
}
Future<dynamic> passengerDialog(String message) {
return Get.defaultDialog(
barrierDismissible: false,
title: 'message From passenger'.tr,
titleStyle: AppStyle.title,
middleTextStyle: AppStyle.title,
middleText: message.tr,
confirm: MyElevatedButton(
title: 'Ok'.tr,
onPressed: () {
// FirebaseMessagesController().sendNotificationToPassengerToken(
// 'Hi ,I will go now'.tr,
// 'I will go now'.tr,
// Get.find<MapPassengerController>().driverToken, []);
// Get.find<MapPassengerController>()
// .startTimerDriverWaitPassenger5Minute();
Get.back();
}));
}
// Future<dynamic> driverFinishTripDialoge(List<dynamic> driverList) {
// return Get.defaultDialog(
// title: 'Driver Finish Trip'.tr,
// content: const DriverTipWidget(),
// confirm: MyElevatedButton(
// title: 'Yes'.tr,
// onPressed: () async {
// var tip = (Get.find<MapPassengerController>().totalPassenger) *
// (double.parse(box.read(BoxName.tipPercentage.toString())));
// var res = await CRUD().post(link: AppLink.addTips, payload: {
// 'passengerID': box.read(BoxName.passengerID),
// 'driverID': driverList[0].toString(),
// 'rideID': driverList[1].toString(),
// 'tipAmount': tip.toString(),
// });
// await CRUD().post(link: AppLink.addPassengersWallet, payload: {
// 'passenger_id': box.read(BoxName.passengerID).toString(),
// 'balance': ((-1) * tip).toString()
// });
// await CRUD().post(link: AppLink.addDriversWalletPoints, payload: {
// 'driverID': driverList[0].toString(),
// 'paymentID': '${Get.find<MapPassengerController>().rideId}tip',
// 'amount': (tip * 100).toString(),
// 'paymentMethod': 'visa-tip',
// });
// if (res != 'failure') {
// FirebaseMessagesController().sendNotificationToAnyWithoutData(
// 'You Have Tips',
// '${'${tip.toString()}\$${' tips\nTotal is'.tr}'} ${tip + (Get.find<MapPassengerController>().totalPassenger)}',
// driverList[2].toString(),
// );
// }
// Get.to(() => RateDriverFromPassenger(), arguments: {
// 'driverId': driverList[0].toString(),
// 'rideId': driverList[1].toString(),
// 'price': driverList[3].toString()
// });
// },
// kolor: AppColor.greenColor,
// ),
// cancel: MyElevatedButton(
// title: 'No,I want'.tr,
// onPressed: () {
// Get.to(() => RateDriverFromPassenger(), arguments: {
// 'driverId': driverList[0].toString(),
// 'rideId': driverList[1].toString(),
// 'price': driverList[3].toString()
// });
// },
// kolor: AppColor.redColor,
// ));
// }
void sendNotificationAll(String title, body) async {
// Get the token you want to subtract.
String token = box.read(BoxName.tokenFCM);
tokens = box.read(BoxName.tokens);
// Subtract the token from the list of tokens.
tokens.remove(token);
// Save the list of tokens back to the box.
// box.write(BoxName.tokens, tokens);
tokens = box.read(BoxName.tokens);
for (var i = 0; i < tokens.length; i++) {
String serviceAccountKeyJson = '''{
"type": "service_account",
"project_id": "ride-b1bd8",
"private_key_id": "75e817c0b902db2ef35edf2c2bd159dec1f13249",
"private_key": "-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQD0zH9TQGDQHUv3\\na3/JAD1UKPwAp3wNKT0a6fxiIzjI3JxQWI30QvZCcfl6CdMhIcydX1ncSaYTcEeC\\n/AdPVCPkqyJx1YIGGg6P/mRzCWeaN8fsp6z250m5vcObDCZc3dbJEkepbep+6FPY\\n21m3KO+AHh1glgsTGZOTm5xiU8NGXpdk2QEh8wpiIIlR/HuKwVw9g8urNe3Sno+U\\nDm3z37iFqvZdmpqO8aWTJu6beb3hsREK9XK2I9JqC2JUwiGQRo3idOvPP6hkqrWx\\nKSX96vglQFYfakvJdDp2ZATOlpBYPMtS/IWhJ985u58TSS+Kl8qpnpaZBSxgJirf\\nhWzhnKLfAgMBAAECggEAJP785SePGhS7ZN6ltspm+l+hSjYFrPWFCxq+rlQ1YkHZ\\nC9l+RqKSFhOkiPmQI2s4wbXl3kFxLHHlFNoi/q2wKQBmGb8TQfnRJpjjNHGA61Ev\\n0Ue7/6qPvVb9B2MsLw/FxKiTFPuMG3bgKR9pbSFuJLYoaW7zqITOhVnYphGTqwAY\\nBVVcvISSLvELDmH9VZcv/9DVqVlqbbESHWh1Z4W6XGPoEqeDH/upNTyQQ/46Msgm\\nTGE6VqLHpWuSf6SqHp+r0Y0lI3vIPM1vz5FAJDJbOE/enHa0fSup0OHSMxl0HVMn\\nnO1yrGF3vsIPOej5HKr5d71bEIckzk73/yjNC1/mDQKBgQD7RtUvc9omsSsFMJ6e\\nBASAn6Dktx/QY/XNJjFzHQj69cywLDe5t5AL2gUi3phQ2oqB5XJdwnd5bTIEPEPZ\\nDOuOai2802p6FJk6kjmZAMVGx5JtXBH+vs6jrmQQSMiKbjwN1TT6xIWakvLOonUi\\nX6ZvjYYjU/E0YJU3jSiXWEr76wKBgQD5Zn4SouJ6BCDZMbausJVMBkk3qxsYooip\\np89WakC6e7AZinpkRcqjGGV9GOvc8crJs6fyXAA9ORepGP47Mc0ZrDssOkstznsM\\npr8R0S6MKwEZaT9ixOHdOcLZ47ps+JzA2Wr4KN2OvFHksUkB/46ATD1j9WZVgB8M\\namsYp/Y73QKBgHOo+PvsoZ9psVmkNX6abtAdqdtdB0HOoRea2uwXk0ig12TIFaZg\\nfedWpUKVnxqoXVTJHklV99RmlL0qWDiSH+LfsMnXro0e6iDxqZ1po2Se/CFmXcoa\\nXdctsFVmixhdATuExewfhTfPKABA+xWlXWC/jdy5CK+JPWXijaqMM4edAoGAE5Bj\\nsWiPpYyvWvpYX0nA3G7dzX0hqgQN/mkIjbnWDArp3IcNZNJIvBSM2Yxb7EAXbU0n\\njo6DAkp5Pa2VO+WDNlFZbvW/sf8xjeOCt44WPa6d7nVgIIpbQXRngZoopKW3/jTP\\n/FmQT8McFXmGxZ5belsAsdetSGW9icbLUerTGQ0CgYEAmf/G8Ag3XxmqTXvvHuv2\\n14OP7WnrVqkEMnydrftEwn4peXd/Lz+/GYX5Zc4ZoNgbN8IvZ5z0+OmRsallsbiW\\nBw0/tc68CjzxXOvReWxDluUopqWVGj5tlGqE5xUDku9SWJSxbkiQ3rqutzBdPXpr\\noqHwPyDrmK/Zgqn+uiIm4Ck=\\n-----END PRIVATE KEY-----\\n",
"client_email": "firebase-adminsdk-o2wqi@ride-b1bd8.iam.gserviceaccount.com",
"client_id": "111210077025005706623",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-o2wqi%40ride-b1bd8.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}
'''; // As defined above
// Initialize AccessTokenManager
final accessTokenManager = AccessTokenManager(serviceAccountKeyJson);
// Obtain an OAuth 2.0 access token
final accessToken = await accessTokenManager.getAccessToken();
// Send the notification
final response = await http
.post(
Uri.parse(
'https://fcm.googleapis.com/v1/projects/ride-b1bd8/messages:send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'Bearer $accessToken',
},
body: jsonEncode({
'notification': <String, dynamic>{
'title': title,
'body': body,
'sound': 'ding.wav'
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done'
},
'to': tokens[i],
}))
.whenComplete(() {})
.catchError((e) {});
}
}
// for (var i = 0; i < tokens.length; i++) {
// http
// .post(Uri.parse('https://fcm.googleapis.com/fcm/send'),
// headers: <String, String>{
// 'Content-Type': 'application/json',
// 'Authorization': 'key=${storage.read(key: BoxName.serverAPI}'
// },
// body: jsonEncode({
// 'notification': <String, dynamic>{
// 'title': title,
// 'body': body,
// 'sound': 'true'
// },
// 'priority': 'high',
// 'data': <String, dynamic>{
// 'click_action': 'FLUTTER_NOTIFICATION_CLICK',
// 'id': '1',
// 'status': 'done'
// },
// 'to': tokens[i],
// }))
// .whenComplete(() {})
// .catchError((e) {
// });
// }
// }
//android/app/src/main/res/raw/iphone_ringtone.wav
late String serviceAccountKeyJson;
void sendNotificationToAnyWithoutData(
String title, String body, String token, String tone) async {
try {
var encryptedKey = Env.privateKeyFCM;
// Log.print('encryptedKey: ${encryptedKey}');
serviceAccountKeyJson =
EncryptionHelper.instance.decryptData(encryptedKey);
// As defined above
// Initialize AccessTokenManager
final accessTokenManager = AccessTokenManager(serviceAccountKeyJson);
// Obtain an OAuth 2.0 access token
final accessToken = await accessTokenManager.getAccessToken();
// Log.print('accessToken: ${accessToken}');
// Send the notification
final response = await http.post(
Uri.parse(
'https://fcm.googleapis.com/v1/projects/intaleq-d48a7/messages:send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'Bearer $accessToken',
},
body: jsonEncode({
'message': {
'token': token,
'notification': {
'title': title,
'body': body,
},
'android': {
'notification': {
'sound': tone,
},
},
'apns': {
'payload': {
'aps': {
'sound': tone,
},
},
},
},
}),
);
if (response.statusCode == 200) {
SnackBar(content: Text('${response.statusCode}'));
print(
'Notification sent successfully. Status code: ${response.statusCode}');
print('Response body: ${response.body}');
} else {
print(
'Failed to send notification. Status code: ${response.statusCode}');
print('Response body: ${response.body}');
}
} catch (e) {
print('Error sending notification: $e');
}
}
}

View File

@@ -0,0 +1,29 @@
// import 'package:flutter_local_notifications/flutter_local_notifications.dart';
// import 'package:get/get.dart';
// class NotificationController extends GetxController {
// final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
// FlutterLocalNotificationsPlugin();
// // Initializes the local notifications plugin
// Future<void> initNotifications() async {
// const AndroidInitializationSettings android =
// AndroidInitializationSettings('@mipmap/launcher_icon');
// const InitializationSettings initializationSettings =
// InitializationSettings(android: android);
// await _flutterLocalNotificationsPlugin.initialize(initializationSettings);
// }
// // Displays a notification with the given title and message
// void showNotification(String title, String message, String tone) async {
// AndroidNotificationDetails android = AndroidNotificationDetails(
// 'your channel id', 'your channel name',
// importance: Importance.max,
// priority: Priority.high,
// showWhen: false,
// sound: RawResourceAndroidNotificationSound(tone));
// NotificationDetails details = NotificationDetails(android: android);
// await _flutterLocalNotificationsPlugin.show(0, title, message, details);
// }
// }

View File

@@ -0,0 +1,53 @@
import 'dart:convert';
import 'package:googleapis_auth/auth_io.dart';
import '../../print.dart';
class AccessTokenManager {
static final AccessTokenManager _instance = AccessTokenManager._internal();
late final String serviceAccountJsonKey;
AccessToken? _accessToken;
DateTime? _expiryDate;
AccessTokenManager._internal();
factory AccessTokenManager(String jsonKey) {
if (_instance._isServiceAccountKeyInitialized()) {
// Prevent re-initialization
return _instance;
}
_instance.serviceAccountJsonKey = jsonKey;
return _instance;
}
bool _isServiceAccountKeyInitialized() {
try {
serviceAccountJsonKey; // Access to check if initialized
return true;
} catch (e) {
return false;
}
}
Future<String> getAccessToken() async {
if (_accessToken != null && DateTime.now().isBefore(_expiryDate!)) {
return _accessToken!.data;
}
try {
final serviceAccountCredentials = ServiceAccountCredentials.fromJson(
json.decode(serviceAccountJsonKey));
final client = await clientViaServiceAccount(
serviceAccountCredentials,
['https://www.googleapis.com/auth/firebase.messaging'],
);
_accessToken = client.credentials.accessToken;
_expiryDate = client.credentials.accessToken.expiry;
client.close();
Log.print('_accessToken!.data: ${_accessToken!.data}');
return _accessToken!.data;
} catch (e) {
throw Exception('Failed to obtain access token');
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,26 @@
import 'package:flutter/material.dart';
class LineChartPainter extends CustomPainter {
final List<double> data;
LineChartPainter(this.data);
@override
void paint(Canvas canvas, Size size) {
// Calculate the scale factor.
final scaleFactor = size.height / 240;
// Draw the line chart.
for (var i = 0; i < data.length - 1; i++) {
final x1 = i * size.width / data.length;
final y1 = data[i] * scaleFactor;
final x2 = (i + 1) * size.width / data.length;
final y2 = data[i + 1] * scaleFactor;
canvas.drawLine(Offset(x1, y1), Offset(x2, y2), Paint());
}
}
@override
bool shouldRepaint(LineChartPainter oldDelegate) => false;
}

View File

@@ -0,0 +1,295 @@
// import 'dart:io';
// import 'package:device_info_plus/device_info_plus.dart';
import 'dart:async';
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:device_info_plus/device_info_plus.dart';
import '../../main.dart';
class DeviceHelper {
static Future<String> getDeviceFingerprint() async {
final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
var deviceData;
try {
if (Platform.isAndroid) {
// Fetch Android-specific device information
AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
deviceData = androidInfo.toMap(); // Convert to a map for easier access
// Log.print('deviceData: ${jsonEncode(deviceData)}');
} else if (Platform.isIOS) {
// Fetch iOS-specific device information
IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
deviceData = iosInfo.toMap(); // Convert to a map for easier access
} else {
throw UnsupportedError('Unsupported platform');
}
// Extract relevant device information
final String deviceId = Platform.isAndroid
? deviceData['androidId'] ?? deviceData['serialNumber'] ?? 'unknown'
: deviceData['identifierForVendor'] ?? 'unknown';
final String deviceModel = deviceData['model'] ?? 'unknown';
final String osVersion = Platform.isAndroid
? deviceData['version']['release'] ?? 'unknown'
: deviceData['systemVersion'] ?? 'unknown';
// Log the extracted information
// Generate and return the encrypted fingerprint
final String fingerprint = '${deviceId}_${deviceModel}_$osVersion';
// print(EncryptionHelper.instance.encryptData(fingerprint));
return (fingerprint);
} catch (e) {
throw Exception('Failed to generate device fingerprint');
}
}
}
// class SecurityHelper {
// /// Performs security checks and handles potential risks
// static Future<void> performSecurityChecks() async {
// bool isNotTrust = false;
// bool isJailBroken = false;
// bool isRealDevice = true;
// bool isOnExternalStorage = false;
// bool checkForIssues = false;
// bool isDevMode = false;
// bool isTampered = false;
// String bundleId = "";
// try {
// isNotTrust = await JailbreakRootDetection.instance.isNotTrust;
// isJailBroken = await JailbreakRootDetection.instance.isJailBroken;
// isRealDevice = await JailbreakRootDetection.instance.isRealDevice;
// isOnExternalStorage =
// await JailbreakRootDetection.instance.isOnExternalStorage;
// List<JailbreakIssue> issues =
// await JailbreakRootDetection.instance.checkForIssues;
// checkForIssues = issues.isNotEmpty;
// isDevMode = await JailbreakRootDetection.instance.isDevMode;
// // Get Bundle ID
// PackageInfo packageInfo = await PackageInfo.fromPlatform();
// bundleId = packageInfo.packageName;
// if (bundleId.isNotEmpty) {
// // Pass the CORRECT bundle ID to isTampered
// isTampered = await JailbreakRootDetection.instance.isTampered(bundleId);
// }
// } catch (e) {
// debugPrint("Error during security checks: $e");
// // Consider handling specific exceptions, not just general errors.
// }
// // Save values to storage (using GetStorage)
// await box.write('isNotTrust', isNotTrust); // Use await for write operations
// await box.write('isTampered', isTampered); // Use await
// await box.write('isJailBroken', isJailBroken); // Use await
// // debugPrint("Security Check Results:");
// // debugPrint("isNotTrust: $isNotTrust");
// // debugPrint("isJailBroken: $isJailBroken");
// // debugPrint("isRealDevice: $isRealDevice");
// // debugPrint("isOnExternalStorage: $isOnExternalStorage");
// // debugPrint("checkForIssues: $checkForIssues");
// // debugPrint("isDevMode: $isDevMode");
// // debugPrint("isTampered: $isTampered");
// // debugPrint("Bundle ID: $bundleId"); // Print the bundle ID
// // Check for security risks and potentially show a warning
// if (isJailBroken || isRealDevice == false || isTampered) {
// // print("security_warning".tr); //using easy_localization
// // Use a more robust approach to show a warning, like a dialog:
// _showSecurityWarning();
// }
// }
// /// Deletes all app data
// static Future<void> clearAllData() async {
// //await storage.deleteAll(); // What's 'storage'? Be specific. Likely GetStorage as well.
// await box.erase(); // Clear GetStorage data
// exit(0); // This will terminate the app. Be VERY careful with this.
// }
// // static void _showSecurityWarning() {
// // // Show a dialog, navigate to an error screen, etc.
// // // Example using Get.dialog (if you use GetX):
// //
// // Get.dialog(
// // AlertDialog(
// // title: Text("Security Warning".tr), // Or use localized string
// // content: Text(
// // "Potential security risks detected. The application may not function correctly."
// // .tr), //Or use localized string
// // actions: [
// // TextButton(
// // onPressed: () async {
// // await storage.deleteAll();
// // await box.erase();
// // Get.back(); // Close the dialog
// // // Or, if you really must, exit the app (but give the user a chance!)
// // exit(0);
// // },
// // child: Text("OK"), // Or use a localized string
// // ),
// // ],
// // ),
// // barrierDismissible: false, // Prevent closing by tapping outside
// // );
// // }
// static void _showSecurityWarning() {
// // Use an RxInt to track the remaining seconds. This is the KEY!
// RxInt secondsRemaining = 10.obs;
// Get.dialog(
// CupertinoAlertDialog(
// title: Text("Security Warning".tr),
// content: Column(
// mainAxisSize: MainAxisSize.min,
// children: [
// Obx(() => Text(
// "Potential security risks detected. The application will close in @seconds seconds."
// .trParams({
// // Use trParams for placeholders
// 'seconds': secondsRemaining.value.toString(),
// }),
// // Wrap the Text widget in Obx
// )),
// SizedBox(height: 24), // More spacing before the progress bar
// Obx(() => SizedBox(
// width: double.infinity, // Make progress bar full width
// child: CupertinoActivityIndicator(
// // in case of loading
// radius: 15,
// animating: true,
// ))),
// SizedBox(height: 8),
// Obx(() => ClipRRect(
// borderRadius: BorderRadius.circular(8), // Rounded corners
// child: LinearProgressIndicator(
// value: secondsRemaining.value / 10,
// backgroundColor: Colors.grey.shade300, // Lighter background
// valueColor: AlwaysStoppedAnimation<Color>(
// CupertinoColors.systemRed), // iOS-style red
// minHeight: 8, // Slightly thicker progress bar
// ),
// )),
// ],
// ),
// ),
// barrierDismissible: false,
// );
// Timer.periodic(Duration(seconds: 1), (timer) {
// secondsRemaining.value--;
// if (secondsRemaining.value <= 0) {
// timer.cancel();
// // Get.back();
// _clearDataAndExit();
// }
// });
// }
// static Future<void> _clearDataAndExit() async {
// await storage.deleteAll();
// await box.erase();
// exit(0); // Exit the app
// print('exit');
// }
// }
// class DeviceInfoPlus {
// static List<Map<String, dynamic>> deviceDataList = [];
// static Future<List<Map<String, dynamic>>> getDeviceInfo() async {
// final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
// try {
// if (Platform.isAndroid) {
// AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
// Map<String, dynamic> deviceData = {
// 'platform': 'Android',
// 'brand': androidInfo.brand,
// 'model': androidInfo.model,
// 'androidId': androidInfo.device,
// 'versionRelease': androidInfo.version.release,
// 'sdkVersion': androidInfo.version.sdkInt,
// 'manufacturer': androidInfo.manufacturer,
// 'isPhysicalDevice': androidInfo.isPhysicalDevice,
// 'serialNumber': androidInfo.serialNumber,
// 'fingerprint': androidInfo.fingerprint,
// 'type': androidInfo.type,
// 'data': androidInfo.data,
// 'version': androidInfo.version,
// 'tags': androidInfo.tags,
// 'display': androidInfo.display,
// };
// deviceDataList.add(deviceData);
// } else if (Platform.isIOS) {
// IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
// Map<String, dynamic> deviceData = {
// 'brand': 'Apple',
// 'model': iosInfo.model,
// 'systemName': iosInfo.systemName,
// 'systemVersion': iosInfo.systemVersion,
// 'utsname': iosInfo.utsname,
// 'isPhysicalDevice': iosInfo.isPhysicalDevice,
// 'identifierForVendor': iosInfo.identifierForVendor,
// 'name': iosInfo.name,
// 'localizedModel': iosInfo.localizedModel,
// };
// deviceDataList.add(deviceData);
// } else if (Platform.isMacOS) {
// MacOsDeviceInfo macInfo = await deviceInfoPlugin.macOsInfo;
// Map<String, dynamic> deviceData = {
// 'platform': 'macOS',
// 'model': macInfo.model,
// 'version': macInfo.systemGUID,
// };
// deviceDataList.add(deviceData);
// } else if (Platform.isWindows) {
// WindowsDeviceInfo windowsInfo = await deviceInfoPlugin.windowsInfo;
// Map<String, dynamic> deviceData = {
// 'platform': 'Windows',
// 'manufacturer': windowsInfo.computerName,
// 'version': windowsInfo.majorVersion,
// 'deviceId': windowsInfo.deviceId,
// 'userName': windowsInfo.userName,
// 'productName': windowsInfo.productName,
// 'installDate': windowsInfo.installDate,
// 'productId': windowsInfo.productId,
// 'numberOfCores': windowsInfo.numberOfCores,
// 'systemMemoryInMegabytes': windowsInfo.systemMemoryInMegabytes,
// };
// deviceDataList.add(deviceData);
// } else if (Platform.isLinux) {
// LinuxDeviceInfo linuxInfo = await deviceInfoPlugin.linuxInfo;
// Map<String, dynamic> deviceData = {
// 'platform': 'Linux',
// 'manufacturer': linuxInfo.name,
// 'version': linuxInfo.version,
// };
// deviceDataList.add(deviceData);
// }
// } catch (e) {
// }
// return deviceDataList;
// }
// // Method to print all device data
// static void printDeviceInfo() {
// for (Map<String, dynamic> deviceData in deviceDataList) {
// 'Version: ${deviceData['version'] ?? deviceData['versionRelease'] ?? 'N/A'}');
// }
// }
// }

View File

@@ -0,0 +1,42 @@
import 'package:flutter/services.dart';
class DigitObscuringFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
final maskedText = maskDigits(newValue.text);
return newValue.copyWith(
text: maskedText,
selection: updateCursorPosition(maskedText, newValue.selection));
}
String maskDigits(String text) {
final totalDigits = text.length;
final visibleDigits = 4;
final hiddenDigits = totalDigits - visibleDigits * 2;
final firstVisibleDigits = text.substring(0, visibleDigits);
final lastVisibleDigits = text.substring(totalDigits - visibleDigits);
final maskedDigits = List.filled(hiddenDigits, '*').join();
return '$firstVisibleDigits$maskedDigits$lastVisibleDigits';
}
TextSelection updateCursorPosition(
String maskedText, TextSelection currentSelection) {
final cursorPosition = currentSelection.baseOffset;
final cursorOffset =
currentSelection.extentOffset - currentSelection.baseOffset;
final totalDigits = maskedText.length;
const visibleDigits = 4;
final hiddenDigits = totalDigits - visibleDigits * 2;
final updatedPosition = cursorPosition <= visibleDigits
? cursorPosition
: hiddenDigits + visibleDigits + (cursorPosition - visibleDigits);
return TextSelection.collapsed(
offset: updatedPosition, affinity: currentSelection.affinity);
}
}

View File

@@ -0,0 +1,41 @@
// import 'dart:io';
//
// import 'package:get/get.dart';
// import 'package:image_picker/image_picker.dart';
// import 'package:google_ml_kit/google_ml_kit.dart';
//
// class ImagePickerController extends GetxController {
// RxBool textScanning = false.obs;
// RxString scannedText = ''.obs;
//
// Future<void> getImage(ImageSource source) async {
// try {
// final pickedImage = await ImagePicker().pickImage(source: source);
// if (pickedImage != null) {
// textScanning.value = true;
// final imageFile = File(pickedImage.path);
// getRecognisedText(imageFile);
// }
// } catch (e) {
// textScanning.value = false;
// scannedText.value = "Error occurred while scanning";
// }
// }
//
// Future<void> getRecognisedText(File image) async {
// final inputImage = InputImage.fromFilePath(image.path);
// final textDetector = GoogleMlKit.vision.textRecognizer();
// final RecognizedText recognisedText =
// await textDetector.processImage(inputImage);
// await textDetector.close();
//
// scannedText.value = '';
// for (TextBlock block in recognisedText.blocks) {
// for (TextLine line in block.lines) {
// scannedText.value += line.text + '\n';
// }
// }
//
// textScanning.value = false;
// }
// }

View File

@@ -0,0 +1,79 @@
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter/foundation.dart';
import 'package:secure_string_operations/secure_string_operations.dart';
import '../../constant/char_map.dart';
import '../../env/env.dart';
import '../../main.dart';
import '../../print.dart';
class EncryptionHelper {
static EncryptionHelper? _instance;
late final encrypt.Key key;
late final encrypt.IV iv;
EncryptionHelper._(this.key, this.iv);
static EncryptionHelper get instance {
if (_instance == null) {
throw Exception(
"EncryptionHelper is not initialized. Call `await EncryptionHelper.initialize()` in main.");
}
return _instance!;
}
/// Initializes and stores the instance globally
static Future<void> initialize() async {
if (_instance != null) {
debugPrint("EncryptionHelper is already initialized.");
return; // Prevent re-initialization
}
debugPrint("Initializing EncryptionHelper...");
var keyOfApp = r(Env.keyOfApp).toString().split(Env.addd)[0];
Log.print('keyOfApp: ${keyOfApp}');
var initializationVector =
r(Env.initializationVector).toString().split(Env.addd)[0];
Log.print('initializationVector: ${initializationVector}');
// Set the global instance
_instance = EncryptionHelper._(
encrypt.Key.fromUtf8(keyOfApp),
encrypt.IV.fromUtf8(initializationVector),
);
debugPrint("EncryptionHelper initialized successfully.");
}
/// Encrypts a string
String encryptData(String plainText) {
try {
final encrypter =
encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
final encrypted = encrypter.encrypt(plainText, iv: iv);
return encrypted.base64;
} catch (e) {
debugPrint('Encryption Error: $e');
return '';
}
}
/// Decrypts a string
String decryptData(String encryptedText) {
try {
final encrypter =
encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
final encrypted = encrypt.Encrypted.fromBase64(encryptedText);
return encrypter.decrypt(encrypted, iv: iv);
} catch (e) {
debugPrint('Decryption Error: $e');
return '';
}
}
}
r(String string) {
return X.r(X.r(X.r(string, cn), cC), cs).toString();
}
c(String string) {
return X.c(X.c(X.c(string, cn), cC), cs).toString();
}

View File

@@ -0,0 +1,829 @@
// import 'dart:convert';
// import 'dart:io';
// import 'package:get/get.dart';
// import 'package:image_cropper/image_cropper.dart';
// import 'package:image_picker/image_picker.dart';
// import 'package:http/http.dart' as http;
// import 'package:image/image.dart' as img;
// import 'package:path_provider/path_provider.dart';
// import '../../constant/api_key.dart';
// import '../../constant/colors.dart';
// class AI extends GetxController {
// final picker = ImagePicker();
// Map<String, dynamic> responseMap = {};
// Map<String, dynamic> responseCarLicenseMap = {};
// Map<String, dynamic> responseBackCarLicenseMap = {};
// Map<String, dynamic> responseIdCardeMap = {};
// bool isloading = false;
// var image;
// CroppedFile? croppedFile;
// DateTime now = DateTime.now();
// Future<void> pickImage() async {
// final pickedImage = await picker.pickImage(source: ImageSource.gallery);
// if (pickedImage != null) {
// image = File(pickedImage.path);
// // Crop the image
// croppedFile = await ImageCropper().cropImage(
// sourcePath: image!.path,
// aspectRatioPresets: [
// CropAspectRatioPreset.square,
// CropAspectRatioPreset.ratio3x2,
// CropAspectRatioPreset.original,
// CropAspectRatioPreset.ratio4x3,
// CropAspectRatioPreset.ratio16x9
// ],
// uiSettings: [
// AndroidUiSettings(
// toolbarTitle: 'Cropper'.tr,
// toolbarColor: AppColor.blueColor,
// toolbarWidgetColor: AppColor.yellowColor,
// initAspectRatio: CropAspectRatioPreset.original,
// lockAspectRatio: false),
// IOSUiSettings(
// title: 'Cropper'.tr,
// ),
// ],
// );
// // image = croppedFile;
// // Resize the image
// final rawImage =
// img.decodeImage(File(croppedFile!.path).readAsBytesSync());
// final resizedImage =
// img.copyResize(rawImage!, width: 800); // Adjust the width as needed
// final appDir = await getTemporaryDirectory();
// final resizedImagePath = '${appDir.path}/resized_image.jpg';
// final resizedImageFile = File(resizedImagePath);
// resizedImageFile.writeAsBytesSync(
// img.encodeJpg(resizedImage)); // Save the resized image as JPEG
// image = resizedImageFile;
// update();
// }
// }
// Future<void> generateContent() async {
// await pickImage();
// if (image != null) {
// final imageBytes = await image.readAsBytes();
// final imageData = base64Encode(imageBytes);
// var requestBody = jsonEncode({
// 'contents': [
// {
// 'parts': [
// {
// 'inlineData': {
// 'mimeType': 'image/jpeg',
// 'data': imageData,
// },
// },
// {
// 'text':
// 'write json for all data as first name ,last name,dob,licenseID,expiration date,issued date asdress class type ,output json type',
// },
// ],
// },
// ],
// 'generationConfig': {
// 'temperature': 0.4,
// 'topK': 32,
// 'topP': 1,
// 'maxOutputTokens': 4096,
// 'stopSequences': [],
// },
// 'safetySettings': [
// {
// 'category': 'HARM_CATEGORY_HARASSMENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_HATE_SPEECH',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// ],
// });
// final response = await http.post(
// Uri.parse(
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
// headers: {'Content-Type': 'application/json'},
// body: requestBody,
// );
// if (response.statusCode == 200) {
// var responseData = jsonDecode(response.body);
// // Process the responseData as needed
// var result =
// responseData['candidates'][0]['content']['parts'][0]['text'];
// RegExp regex = RegExp(r"```json([^`]*)```");
// String? jsonString =
// regex.firstMatch(responseData.toString())?.group(1)?.trim();
// if (jsonString != null) {
// // Convert the JSON object to a String
// jsonString = jsonEncode(json.decode(jsonString));
// } else {
// }
// // Rest of your code...
// } else {
// }
// } else {
// }
// }
// Future<void> geminiAiExtraction(String prompt, payload) async {
// var requestBody = jsonEncode({
// 'contents': [
// {
// 'parts': [
// // {
// // 'inlineData': {
// // 'mimeType': 'image/jpeg',
// // 'data': imageData,
// // },
// // },
// {
// 'text':
// "Extract the desired information from the following passage as json decoded like $prompt .and look for this instruction first name in line 3or 2 ,fullname in line 4 from it written left to right but you modify it rtl,address in line 5 it written left to right but you modify it rtl and 6,dob,nationalid in the last line as just in this:\n\n$payload"
// },
// ],
// },
// ],
// 'generationConfig': {
// 'temperature': 0.4,
// 'topK': 32,
// 'topP': 1,
// 'maxOutputTokens': 4096,
// 'stopSequences': [],
// },
// 'safety_settings': [
// {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
// {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
// {
// "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
// "threshold": "BLOCK_NONE"
// },
// {
// "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
// "threshold": "BLOCK_NONE"
// },
// ]
// });
// final response = await http.post(
// Uri.parse(
// // 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent?key=AIzaSyCyoLcSkDzK5_SMe00nhut56SSXWPR074w'),
// headers: {'Content-Type': 'application/json'},
// body: requestBody,
// );
// if (response.statusCode == 200) {
// var responseData = jsonDecode(response.body);
// // Process the responseData as needed
// var result = responseData['candidates'][0]['content']['parts'][0]['text'];
// RegExp regex = RegExp(r"```json([^`]*)```");
// String? jsonString =
// regex.firstMatch(responseData.toString())?.group(1)?.trim();
// if (jsonString != null) {
// // Convert the JSON object to a String
// jsonString = jsonEncode(json.decode(jsonString));
// } else {
// }
// // Rest of your code...
// } else {
// }
// }
// Future<void> getDriverLicenseJordanContent() async {
// await pickImage();
// isloading = true;
// update();
// if (image != null) {
// final imageBytes = await image.readAsBytes();
// final imageData = base64Encode(imageBytes);
// var requestBody = jsonEncode({
// 'contents': [
// {
// 'parts': [
// {
// 'inlineData': {
// 'mimeType': 'image/jpeg',
// 'data': imageData,
// },
// },
// {
// 'text':
// 'write json for all data as first name ,last name,dob,id ,expiration date,issued date asdress class type,age in years ,output json type in arabic value and stay engish key and make date format like YYYY-MM-DD , for name please extract name in arabic in Name in json plus first_name ',
// },
// ],
// },
// ],
// 'generationConfig': {
// 'temperature': 0.4,
// 'topK': 32,
// 'topP': 1,
// 'maxOutputTokens': 4096,
// 'stopSequences': [],
// },
// 'safetySettings': [
// {
// 'category': 'HARM_CATEGORY_HARASSMENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_HATE_SPEECH',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// ],
// });
// final response = await http.post(
// Uri.parse(
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
// headers: {'Content-Type': 'application/json'},
// body: requestBody,
// );
// isloading = false;
// update();
// if (response.statusCode == 200) {
// var responseData = jsonDecode(response.body);
// // Process the responseData as needed
// var result =
// responseData['candidates'][0]['content']['parts'][0]['text'];
// RegExp regex = RegExp(r"```json([^`]*)```");
// String? jsonString =
// regex.firstMatch(responseData.toString())?.group(1)?.trim();
// if (jsonString != null) {
// // Convert the JSON object to a String
// jsonString = jsonEncode(json.decode(jsonString));
// responseMap = jsonDecode(jsonString);
// } else {
// }
// // Rest of your code...
// } else {
// }
// } else {
// }
// }
// Future<void> getCarLicenseJordanContent() async {
// await pickImage();
// isloading = true;
// update();
// if (image != null) {
// final imageBytes = await image.readAsBytes();
// final imageData = base64Encode(imageBytes);
// var requestBody = jsonEncode({
// 'contents': [
// {
// 'parts': [
// {
// 'inlineData': {
// 'mimeType': 'image/jpeg',
// 'data': imageData,
// },
// },
// {
// 'text':
// '''Extract the following information from the front face of the Jordanian ID card:
// Name
// National ID number
// Gender
// Date of birth
// Output the extracted information in the following JSON format''',
// },
// ],
// },
// ],
// 'generationConfig': {
// 'temperature': 0.4,
// 'topK': 32,
// 'topP': 1,
// 'maxOutputTokens': 4096,
// 'stopSequences': [],
// },
// 'safetySettings': [
// {
// 'category': 'HARM_CATEGORY_HARASSMENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_HATE_SPEECH',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// ],
// });
// final response = await http.post(
// Uri.parse(
// // 'https://${API_ENDPOINT}/v1/projects/${PROJECT_ID}/locations/${LOCATION_ID}/publishers/google/models/${MODEL_ID}:streamGenerateContent'),
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
// headers: {'Content-Type': 'application/json'},
// body: requestBody,
// );
// isloading = false;
// update();
// if (response.statusCode == 200) {
// var responseData = jsonDecode(response.body);
// // Process the responseData as needed
// var result =
// responseData['candidates'][0]['content']['parts'][0]['text'];
// RegExp regex = RegExp(r"```json([^`]*)```");
// String? jsonString =
// regex.firstMatch(responseData.toString())?.group(1)?.trim();
// if (jsonString != null) {
// // Convert the JSON object to a String
// jsonString = jsonEncode(json.decode(jsonString));
// responseCarLicenseMap = jsonDecode(jsonString);
// } else {
// }
// // Rest of your code...
// } else {
// }
// } else {
// }
// }
// Future<void> jordanID() async {
// await pickImage();
// isloading = true;
// update();
// if (image != null) {
// final imageBytes = await image.readAsBytes();
// final imageData = base64Encode(imageBytes);
// var requestBody = jsonEncode({
// 'contents': [
// {
// 'parts': [
// {
// 'inlineData': {
// 'mimeType': 'image/jpeg',
// 'data': imageData,
// },
// },
// {
// 'text':
// '''Extract the following information from the front face of the Jordanian ID card:
// Name
// National ID number
// Gender
// Date of birth
// Output the extracted information in the following JSON format''',
// },
// ],
// },
// ],
// 'generationConfig': {
// 'temperature': 0.4,
// 'topK': 32,
// 'topP': 1,
// 'maxOutputTokens': 4096,
// 'stopSequences': [],
// },
// 'safetySettings': [
// {
// 'category': 'HARM_CATEGORY_HARASSMENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_HATE_SPEECH',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// ],
// });
// final response = await http.post(
// Uri.parse(
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
// headers: {'Content-Type': 'application/json'},
// body: requestBody,
// );
// isloading = false;
// update();
// if (response.statusCode == 200) {
// var responseData = jsonDecode(response.body);
// // Process the responseData as needed
// var result =
// responseData['candidates'][0]['content']['parts'][0]['text'];
// RegExp regex = RegExp(r"```json([^`]*)```");
// String? jsonString =
// regex.firstMatch(responseData.toString())?.group(1)?.trim();
// if (jsonString != null) {
// // Convert the JSON object to a String
// jsonString = jsonEncode(json.decode(jsonString));
// responseCarLicenseMap = jsonDecode(jsonString);
// } else {
// }
// // Rest of your code...
// } else {
// }
// } else {
// }
// }
// Future<void> carLicenseJordan() async {
// await pickImage();
// isloading = true;
// update();
// if (image != null) {
// final imageBytes = await image.readAsBytes();
// final imageData = base64Encode(imageBytes);
// var requestBody = jsonEncode({
// 'contents': [
// {
// 'parts': [
// {
// 'inlineData': {
// 'mimeType': 'image/jpeg',
// 'data': imageData,
// },
// },
// {
// 'text':
// '''Extract the following information from the front face of the car license card in Jordan:
// * name
// * Address
// * Vehicle type
// * car_kind
// * car_color
// * Vehicle category
// * car_year
// * car_plate
// * Registration type
// * Usage type
// * expire_date_of_license
// Output the extracted information in the following JSON formate and make date format like YYYY-MM-DD''',
// },
// ],
// },
// ],
// 'generationConfig': {
// 'temperature': 0.4,
// 'topK': 32,
// 'topP': 1,
// 'maxOutputTokens': 4096,
// 'stopSequences': [],
// },
// 'safetySettings': [
// {
// 'category': 'HARM_CATEGORY_HARASSMENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_HATE_SPEECH',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// ],
// });
// final response = await http.post(
// Uri.parse(
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro-vision-latest:generateContent?key=${AK.geminiApi}'),
// headers: {'Content-Type': 'application/json'},
// body: requestBody,
// );
// isloading = false;
// update();
// if (response.statusCode == 200) {
// var responseData = jsonDecode(response.body);
// // Process the responseData as needed
// var result =
// responseData['candidates'][0]['content']['parts'][0]['text'];
// RegExp regex = RegExp(r"```json([^`]*)```");
// String? jsonString =
// regex.firstMatch(responseData.toString())?.group(1)?.trim();
// if (jsonString != null) {
// // Convert the JSON object to a String
// jsonString = jsonEncode(json.decode(jsonString));
// responseCarLicenseMap = jsonDecode(jsonString);
// } else {
// }
// // Rest of your code...
// } else {
// }
// } else {
// }
// }
// Future getTextFromCard(String prompt) async {
// await pickImage();
// isloading = true;
// update();
// if (image != null) {
// final imageBytes = await image.readAsBytes();
// final imageData = base64Encode(imageBytes);
// var requestBody = jsonEncode({
// 'contents': [
// {
// 'parts': [
// {
// 'inlineData': {
// 'mimeType': 'image/jpeg',
// 'data': imageData,
// },
// },
// {
// 'text': prompt,
// },
// ],
// },
// ],
// 'generationConfig': {
// "temperature": 1,
// "topK": 32,
// "topP": 0.1,
// "maxOutputTokens": 4096,
// "stopSequences": []
// },
// 'safetySettings': [
// {
// 'category': 'HARM_CATEGORY_HARASSMENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_HATE_SPEECH',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// ],
// });
// final response = await http.post(
// Uri.parse(
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro-vision-latest:generateContent?key=${AK.geminiApi}'),
// headers: {'Content-Type': 'application/json'},
// body: requestBody,
// );
// isloading = false;
// update();
// if (response.statusCode == 200) {
// var responseData = jsonDecode(response.body);
// // Process the responseData as needed
// var result =
// responseData['candidates'][0]['content']['parts'][0]['text'];
// RegExp regex = RegExp(r"```json([^`]*)```");
// String? jsonString =
// regex.firstMatch(responseData.toString())?.group(1)?.trim();
// if (jsonString != null) {
// // Convert the JSON object to a String
// jsonString = jsonEncode(json.decode(jsonString));
// responseBackCarLicenseMap = jsonDecode(jsonString);
// } else {
// }
// // Rest of your code...
// } else {
// }
// } else {
// }
// }
// Future<void> generateBackCarLicenseJordanContent() async {
// await pickImage();
// isloading = true;
// update();
// if (image != null) {
// final imageBytes = await image.readAsBytes();
// final imageData = base64Encode(imageBytes);
// var requestBody = jsonEncode({
// 'contents': [
// {
// 'parts': [
// {
// 'inlineData': {
// 'mimeType': 'image/jpeg',
// 'data': imageData,
// },
// },
// {
// 'text':
// 'write json output from extracting car license back face for these key ,vin,fuelType,passengerType,curbWeight,insuranceCompany,policyNumber,notes,insuranceType and output it json .dont add data else this image',
// },
// ],
// },
// ],
// 'generationConfig': {
// 'temperature': 0.4,
// 'topK': 343,
// 'topP': 1,
// 'maxOutputTokens': 4096,
// 'stopSequences': [],
// },
// 'safetySettings': [
// {
// 'category': 'HARM_CATEGORY_HARASSMENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_HATE_SPEECH',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// ],
// });
// final response = await http.post(
// Uri.parse(
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
// headers: {'Content-Type': 'application/json'},
// body: requestBody,
// );
// isloading = false;
// update();
// if (response.statusCode == 200) {
// var responseData = jsonDecode(response.body);
// // Process the responseData as needed
// var result =
// responseData['candidates'][0]['content']['parts'][0]['text'];
// RegExp regex = RegExp(r"```json([^`]*)```");
// String? jsonString =
// regex.firstMatch(responseData.toString())?.group(1)?.trim();
// if (jsonString != null) {
// // Convert the JSON object to a String
// jsonString = jsonEncode(json.decode(jsonString));
// responseBackCarLicenseMap = jsonDecode(jsonString);
// } else {
// }
// // Rest of your code...
// } else {
// }
// } else {
// }
// }
// Future<void> getFromCarRegistration() async {
// await pickImage();
// if (image != null) {
// final imageBytes = await image.readAsBytes();
// final imageData = base64Encode(imageBytes);
// var requestBody = jsonEncode({
// 'contents': [
// {
// 'parts': [
// {
// 'inlineData': {
// 'mimeType': 'image/jpeg',
// 'data': imageData,
// },
// },
// {
// 'text':
// 'write output json from image for[ vin, make, model, year, expiration_date, color, owner, registration_date ],output json type ',
// },
// ],
// },
// ],
// 'generationConfig': {
// 'temperature': 0.4,
// 'topK': 32,
// 'topP': 1,
// 'maxOutputTokens': 4096,
// 'stopSequences': [],
// },
// 'safetySettings': [
// {
// 'category': 'HARM_CATEGORY_HARASSMENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_HATE_SPEECH',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// {
// 'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
// 'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
// },
// ],
// });
// final response = await http.post(
// Uri.parse(
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
// headers: {'Content-Type': 'application/json'},
// body: requestBody,
// );
// if (response.statusCode == 200) {
// var responseData = jsonDecode(response.body);
// // Process the responseData as needed
// var result =
// responseData['candidates'][0]['content']['parts'][0]['text'];
// RegExp regex = RegExp(r"```json([^`]*)```");
// String? jsonString =
// regex.firstMatch(responseData.toString())?.group(1)?.trim();
// if (jsonString != null) {
// // Convert the JSON object to a String
// jsonString = jsonEncode(json.decode(jsonString));
// } else {
// }
// // Rest of your code...
// } else {
// }
// } else {
// }
// }
// @override
// void onInit() {
// // generateContent();
// super.onInit();
// }
// }

View File

@@ -0,0 +1,71 @@
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
void showInBrowser(String url) async {
if (await canLaunchUrl(Uri.parse(url))) {
launchUrl(Uri.parse(url));
} else {}
}
Future<void> makePhoneCall(String phoneNumber) async {
final Uri launchUri = Uri(
scheme: 'tel',
path: phoneNumber,
);
await launchUrl(launchUri);
}
void launchCommunication(
String method, String contactInfo, String message) async {
String url;
if (Platform.isIOS) {
switch (method) {
case 'phone':
url = 'tel:$contactInfo';
break;
case 'sms':
url = 'sms:$contactInfo?body=$message';
break;
case 'whatsapp':
url = 'https://api.whatsapp.com/send?phone=$contactInfo&text=$message';
break;
case 'email':
url = 'mailto:$contactInfo?subject=Subject&body=$message';
break;
default:
return;
}
} else if (Platform.isAndroid) {
switch (method) {
case 'phone':
url = 'tel:$contactInfo';
break;
case 'sms':
url = 'sms:$contactInfo?body=$message';
break;
case 'whatsapp':
url = 'whatsapp://send?phone=$contactInfo&text=$message';
break;
case 'email':
url = 'mailto:$contactInfo?subject=Subject&body=$message';
break;
default:
return;
}
} else {
return;
}
if (await canLaunchUrl(Uri.parse(url))) {
launchUrl(Uri.parse(url));
} else {}
}

View File

@@ -0,0 +1,36 @@
import 'dart:convert';
import '../../constant/links.dart';
import 'crud.dart';
class LlamaAi {
Future<Map> getCarRegistrationData(String input, prompt) async {
Map exrtatDataFinal = {};
String oneLine = input.replaceAll('\n', ' ');
// var res = await CRUD().getLlama(link: AppLink.gemini, payload: oneLine);
var res = await CRUD()
.getLlama(link: AppLink.llama, payload: oneLine, prompt: prompt);
var decod = jsonDecode(res.toString());
// exrtatDataFinal = jsonDecode(extractDataFromJsonString(decod['choices']));
extractDataFromJsonString(decod['choices'][0]['message']['content']);
return exrtatDataFinal;
}
String extractDataFromJsonString(String jsonString) {
// Remove any leading or trailing whitespace from the string
jsonString = jsonString.trim();
// Extract the JSON substring from the given string
final startIndex = jsonString.indexOf('{');
final endIndex = jsonString.lastIndexOf('}');
final jsonSubstring = jsonString.substring(startIndex, endIndex + 1);
// Parse the JSON substring into a Map
final jsonData = jsonDecode(jsonSubstring);
// Return the extracted data
return jsonEncode(jsonData);
}
}

View File

@@ -0,0 +1,133 @@
// import 'dart:async';
// import 'package:get/get.dart';
// import 'package:google_maps_flutter/google_maps_flutter.dart';
// import 'package:location/location.dart';
// import '../../constant/box_name.dart';
// import '../../constant/links.dart';
// import '../../main.dart';
// import 'crud.dart';
// // LocationController.dart
// class LocationController extends GetxController {
// LocationData? _currentLocation;
// late Location location;
// bool isLoading = false;
// late double heading = 0;
// late double accuracy = 0;
// late double previousTime = 0;
// late double latitude;
// late double totalDistance = 0;
// late double longitude;
// late DateTime time;
// late double speed = 0;
// late double speedAccuracy = 0;
// late double headingAccuracy = 0;
// bool isActive = false;
// late LatLng myLocation;
// String totalPoints = '0';
// LocationData? get currentLocation => _currentLocation;
// Timer? _locationTimer;
// @override
// void onInit() async {
// super.onInit();
// location = Location();
// getLocation();
// // startLocationUpdates();
// }
// Future<void> startLocationUpdates() async {
// if (box.read(BoxName.driverID) != null) {
// _locationTimer =
// Timer.periodic(const Duration(seconds: 5), (timer) async {
// try {
// // if (isActive) {
// if (double.parse(totalPoints) > -300) {
// await getLocation();
// // if (box.read(BoxName.driverID) != null) {
// await CRUD()
// .post(link: AppLink.addCarsLocationByPassenger, payload: {
// 'driver_id': box.read(BoxName.driverID).toString(),
// 'latitude': myLocation.latitude.toString(),
// 'longitude': myLocation.longitude.toString(),
// 'heading': heading.toString(),
// 'speed': (speed * 3.6).toStringAsFixed(1),
// 'distance': totalDistance == 0
// ? '0'
// : totalDistance < 1
// ? totalDistance.toStringAsFixed(3)
// : totalDistance.toStringAsFixed(1),
// 'status': box.read(BoxName.statusDriverLocation).toString()
// });
// }
// } catch (e) {
// // Handle the error gracefully
// }
// });
// }
// }
// void stopLocationUpdates() {
// _locationTimer?.cancel();
// }
// Future<void> getLocation() async {
// // isLoading = true;
// // update();
// bool serviceEnabled;
// PermissionStatus permissionGranted;
// // Check if location services are enabled
// serviceEnabled = await location.serviceEnabled();
// if (!serviceEnabled) {
// serviceEnabled = await location.requestService();
// if (!serviceEnabled) {
// // Location services are still not enabled, handle the error
// return;
// }
// }
// // Check if the app has permission to access location
// permissionGranted = await location.hasPermission();
// if (permissionGranted == PermissionStatus.denied) {
// permissionGranted = await location.requestPermission();
// if (permissionGranted != PermissionStatus.granted) {
// // Location permission is still not granted, handle the error
// return;
// }
// }
// // Configure location accuracy
// // LocationAccuracy desiredAccuracy = LocationAccuracy.high;
// // Get the current location
// LocationData _locationData = await location.getLocation();
// myLocation =
// (_locationData.latitude != null && _locationData.longitude != null
// ? LatLng(_locationData.latitude!, _locationData.longitude!)
// : null)!;
// speed = _locationData.speed!;
// heading = _locationData.heading!;
// // isLoading = false;
// update();
// }
// double calculateDistanceInKmPerHour(
// double? startTime, double? endTime, double speedInMetersPerSecond) {
// // Calculate the time difference in hours
// double timeDifferenceInHours = (endTime! - startTime!) / 1000 / 3600;
// // Convert speed to kilometers per hour
// double speedInKmPerHour = speedInMetersPerSecond * 3.6;
// // Calculate the distance in kilometers
// double distanceInKilometers = speedInKmPerHour * timeDifferenceInHours;
// return distanceInKilometers;
// }
// }

View File

@@ -0,0 +1,16 @@
// import 'package:location/location.dart';
// import 'package:get/get.dart';
// class LocationPermissions {
// late Location location;
// Future locationPermissions() async {
// location = Location();
// var permissionStatus = await location.requestPermission();
// if (permissionStatus == PermissionStatus.denied) {
// // The user denied the location permission.
// Get.defaultDialog(title: 'GPS Required Allow !.'.tr, middleText: '');
// return null;
// }
// }
// }

View File

@@ -0,0 +1,181 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../constant/box_name.dart';
import '../../constant/colors.dart';
import '../../constant/links.dart';
import '../../constant/style.dart';
import '../../main.dart';
import '../../views/widgets/elevated_btn.dart';
import '../../views/widgets/my_textField.dart';
import 'crud.dart';
class LogOutController extends GetxController {
TextEditingController checkTxtController = TextEditingController();
final formKey = GlobalKey<FormState>();
final formKey1 = GlobalKey<FormState>();
final emailTextController = TextEditingController();
Future deleteMyAccountDriver(String id) async {
await CRUD().post(link: AppLink.removeUser, payload: {'id': id}).then(
(value) => Get.snackbar('Deleted'.tr, 'Your Account is Deleted',
backgroundColor: AppColor.redColor));
}
checkBeforeDelete() async {
var res = await CRUD().post(
link: AppLink.deletecaptainAccounr,
payload: {'id': box.read(BoxName.driverID)}).then((value) => exit(0));
}
deletecaptainAccount() {
Get.defaultDialog(
backgroundColor: AppColor.yellowColor,
title: 'Are you sure to delete your account?'.tr,
middleText:
'Your data will be erased after 2 weeks\nAnd you will can\'t return to use app after 1 month ',
titleStyle: AppStyle.title,
content: Column(
children: [
Container(
width: Get.width,
decoration: AppStyle.boxDecoration,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Your data will be erased after 2 weeks\nAnd you will can\'t return to use app after 1 month'
.tr,
style: AppStyle.title.copyWith(color: AppColor.redColor),
),
),
),
const SizedBox(
height: 20,
),
Form(
key: formKey,
child: SizedBox(
width: Get.width,
child: MyTextForm(
controller: checkTxtController,
label: 'Enter Your First Name'.tr,
hint: 'Enter Your First Name'.tr,
type: TextInputType.name,
),
))
],
),
confirm: MyElevatedButton(
title: 'Delete'.tr,
onPressed: () {
if (checkTxtController.text == box.read(BoxName.nameDriver)) {
deletecaptainAccount();
}
}));
}
Future logOutPassenger() async {
Get.defaultDialog(
title: 'Are you Sure to LogOut?'.tr,
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
MyElevatedButton(
title: 'Cancel'.tr,
onPressed: () => Get.back(),
),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(AppColor.redColor),
),
onPressed: () {
// box.remove(BoxName.agreeTerms);
box.remove(BoxName.driverID);
box.remove(BoxName.email);
box.remove(BoxName.lang);
box.remove(BoxName.name);
box.remove(BoxName.passengerID);
box.remove(BoxName.phone);
box.remove(BoxName.tokenFCM);
box.remove(BoxName.tokens);
box.remove(BoxName.addHome);
box.remove(BoxName.addWork);
box.remove(BoxName.agreeTerms);
box.remove(BoxName.apiKeyRun);
box.remove(BoxName.countryCode);
box.remove(BoxName.accountIdStripeConnect);
box.remove(BoxName.passengerWalletTotal);
Get.offAll(const MainApp());
},
child: Text(
'Sign Out'.tr,
style:
AppStyle.title.copyWith(color: AppColor.secondaryColor),
))
],
));
}
Future logOutCaptain() async {
Get.defaultDialog(
title: 'Are you Sure to LogOut?'.tr,
titleStyle: AppStyle.title,
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
MyElevatedButton(
title: 'Cancel'.tr,
onPressed: () => Get.back(),
),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(AppColor.redColor),
),
onPressed: () {
// box.remove(BoxName.agreeTerms);
box.remove(BoxName.driverID);
box.remove(BoxName.sexDriver);
box.remove(BoxName.dobDriver);
box.remove(BoxName.nameDriver);
box.remove(BoxName.emailDriver);
box.remove(BoxName.phoneDriver);
box.remove(BoxName.statusDriverLocation);
box.remove(BoxName.cvvCodeDriver);
box.remove(BoxName.lastNameDriver);
box.remove(BoxName.passwordDriver);
box.remove(BoxName.cardNumberDriver);
box.remove(BoxName.expiryDateDriver);
box.remove(BoxName.cardHolderNameDriver);
box.remove(BoxName.vin);
box.remove(BoxName.make);
box.remove(BoxName.year);
box.remove(BoxName.owner);
box.remove(BoxName.onBoarding);
box.remove(BoxName.agreeTerms);
Get.offAll(const MainApp());
},
child: Text(
'Sign Out'.tr,
style:
AppStyle.title.copyWith(color: AppColor.secondaryColor),
))
],
));
}
deletePassengerAccount() async {
if (formKey1.currentState!.validate()) {
if (box.read(BoxName.email).toString() == emailTextController.text) {
await CRUD().post(link: AppLink.passengerRemovedAccountEmail, payload: {
'email': box.read(BoxName.email),
});
} else {
Get.snackbar('Email Wrong'.tr, 'Email you inserted is Wrong.'.tr,
snackPosition: SnackPosition.BOTTOM,
backgroundColor: AppColor.redColor);
}
}
}
}

View File

@@ -0,0 +1,25 @@
// import 'package:credit_card_scanner/credit_card_scanner.dart';
// import 'package:get/get.dart';
//
// class ScanIdCard extends GetxController {
// CardDetails? _cardDetails;
// CardScanOptions scanOptions = const CardScanOptions(
// scanCardHolderName: true,
// enableDebugLogs: true,
// validCardsToScanBeforeFinishingScan: 5,
// possibleCardHolderNamePositions: [
// CardHolderNameScanPosition.aboveCardNumber,
// ],
// );
//
// Future<void> scanCard() async {
// final CardDetails? cardDetails =
// await CardScanner.scanCard(scanOptions: scanOptions);
// if (cardDetails == null) {
// return;
// }
//
// _cardDetails = cardDetails;
// update();
// }
// }

View File

@@ -0,0 +1,14 @@
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class SecureStorage {
final FlutterSecureStorage _storage = const FlutterSecureStorage();
void saveData(String key, value) async {
await _storage.write(key: key, value: value);
}
Future<String?> readData(String boxName) async {
final String? value = await _storage.read(key: boxName);
return value;
}
}

View File

@@ -0,0 +1,50 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
class SecurityChecks {
static const platform = MethodChannel(
'com.intaleq.intaleq_admin/security'); // Choose a unique channel name
static Future<bool> isDeviceCompromised() async {
try {
final bool result = await platform
.invokeMethod('isNativeRooted'); // Invoke the native method
return result;
} on PlatformException catch (e) {
print("Failed to check security status: ${e.message}");
return true; // Treat platform errors as a compromised device (for safety)
}
}
static isDeviceRootedFromNative(BuildContext context) async {
bool compromised = await isDeviceCompromised();
if (compromised) {
showDialog(
barrierDismissible: false,
context: context,
builder: (context) => AlertDialog(
title: Text("Security Warning".tr),
content: Text(
"Your device appears to be compromised. The app will now close."
.tr),
actions: [
TextButton(
onPressed: () {
SystemNavigator.pop(); // Close the app
},
child: Text("OK"),
),
],
),
);
} else {
// Continue with normal app flow
print("Device is secure.");
}
}
}

View File

@@ -0,0 +1,446 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart';
import 'package:image/image.dart' as img;
import 'package:path_provider/path_provider.dart' as path_provider;
import '../../constant/api_key.dart';
import '../../constant/box_name.dart';
import '../../constant/colors.dart';
import '../../main.dart';
import '../../print.dart';
class ImageController extends GetxController {
File? myImage;
bool isloading = false;
CroppedFile? croppedFile;
final picker = ImagePicker();
var image;
Future<img.Image> detectAndCropDocument(File imageFile) async {
img.Image? image = img.decodeImage(await imageFile.readAsBytes());
if (image == null) throw Exception('Unable to decode image');
int left = image.width, top = image.height, right = 0, bottom = 0;
// Threshold for considering a pixel as part of the document (adjust as needed)
const int threshold = 240;
for (int y = 0; y < image.height; y++) {
for (int x = 0; x < image.width; x++) {
final pixel = image.getPixel(x, y);
final luminance = img.getLuminance(pixel);
if (luminance < threshold) {
left = x < left ? x : left;
top = y < top ? y : top;
right = x > right ? x : right;
bottom = y > bottom ? y : bottom;
}
}
}
// Add a small padding
left = (left - 5).clamp(0, image.width);
top = (top - 5).clamp(0, image.height);
right = (right + 5).clamp(0, image.width);
bottom = (bottom + 5).clamp(0, image.height);
return img.copyCrop(image,
x: left, y: top, width: right - left, height: bottom - top);
}
Future<File> rotateImageIfNeeded(File imageFile) async {
img.Image croppedDoc = await detectAndCropDocument(imageFile);
// Check if the document is in portrait orientation
bool isPortrait = croppedDoc.height > croppedDoc.width;
img.Image processedImage;
if (isPortrait) {
// Rotate the image by 90 degrees clockwise
processedImage = img.copyRotate(croppedDoc, angle: 90);
} else {
processedImage = croppedDoc;
}
// Get temporary directory
final tempDir = await path_provider.getTemporaryDirectory();
final tempPath = tempDir.path;
// Create the processed image file
File processedFile = File('$tempPath/processed_image.jpg');
await processedFile.writeAsBytes(img.encodeJpg(processedImage));
return processedFile;
}
Future<File> rotateImage(File imageFile) async {
// Read the image file
img.Image? image = img.decodeImage(await imageFile.readAsBytes());
if (image == null) return imageFile;
// Rotate the image by 90 degrees clockwise
img.Image rotatedImage = img.copyRotate(image, angle: 90);
// Get temporary directory
final tempDir = await path_provider.getTemporaryDirectory();
final tempPath = tempDir.path;
// Create the rotated image file
File rotatedFile = File('$tempPath/rotated_image.jpg');
await rotatedFile.writeAsBytes(img.encodeJpg(rotatedImage));
return rotatedFile;
}
choosImage(String link, String imageType, String id) async {
try {
final pickedImage = await picker.pickImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.rear,
);
if (pickedImage == null) return;
image = File(pickedImage.path);
croppedFile = await ImageCropper().cropImage(
sourcePath: image!.path,
uiSettings: [
AndroidUiSettings(
toolbarTitle: 'Cropper'.tr,
toolbarColor: AppColor.blueColor,
toolbarWidgetColor: AppColor.yellowColor,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false,
),
IOSUiSettings(
title: 'Cropper'.tr,
),
],
);
if (croppedFile == null) return;
myImage = File(croppedFile!.path);
isloading = true;
update();
// Rotate the compressed image
File processedImage = await rotateImageIfNeeded(File(croppedFile!.path));
File compressedImage = await compressImage(processedImage);
print('link =$link');
Log.print('link: ${link}');
await uploadImage(
compressedImage,
{
'driverID': id,
'imageType': imageType,
},
link,
);
} catch (e) {
print('Error in choosImage: $e');
Get.snackbar('Image Upload Failed'.tr, e.toString(),
backgroundColor: AppColor.primaryColor);
} finally {
isloading = false;
update();
}
}
// choosFaceFromDriverLicense(String link, String imageType) async {
// final pickedImage = await picker.pickImage(
// source: ImageSource.camera,
// preferredCameraDevice: CameraDevice.rear,
// );
// if (pickedImage == null) return;
// image = File(pickedImage.path);
// File? processedImage;
// // For face images, use face detection and cropping
// processedImage = await detectAndCropFace(image!);
// if (processedImage == null) {
// Get.snackbar('Face Detection Failed', 'No face detected in the image.');
// return;
// }
// isloading = true;
// update();
// File compressedImage = await compressImage(processedImage);
// try {
// await uploadImage(
// compressedImage,
// {
// 'driverID': box.read(BoxName.driverID).toString(),
// 'imageType': imageType
// },
// link,
// );
// } catch (e) {
// Get.snackbar('Image Upload Failed'.tr, e.toString(),
// backgroundColor: AppColor.redColor);
// } finally {
// isloading = false;
// update();
// }
// }
choosFace(String link, String imageType) async {
final pickedImage = await picker.pickImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front,
);
if (pickedImage != null) {
image = File(pickedImage.path);
isloading = true;
update();
// Compress the image
File compressedImage = await compressImage(File(pickedImage.path));
// Save the picked image directly
// File savedImage = File(pickedImage.path);
print('link =$link');
try {
await uploadImage(
compressedImage,
{
'driverID':
box.read(BoxName.driverID) ?? box.read(BoxName.passengerID),
'imageType': imageType
},
link,
);
} catch (e) {
Get.snackbar('Image Upload Failed'.tr, e.toString(),
backgroundColor: AppColor.redColor);
} finally {
isloading = false;
update();
}
}
}
uploadImage(File file, Map data, String link) async {
var request = http.MultipartRequest(
'POST',
Uri.parse(link),
);
var length = await file.length();
var stream = http.ByteStream(file.openRead());
var multipartFile = http.MultipartFile(
'image',
stream,
length,
filename: basename(file.path),
);
request.headers.addAll({
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials.toString()))}',
});
// Set the file name to the driverID
request.files.add(
http.MultipartFile(
'image',
stream,
length,
filename: '${box.read(BoxName.driverID)}.jpg',
),
);
data.forEach((key, value) {
request.fields[key] = value;
});
var myrequest = await request.send();
var res = await http.Response.fromStream(myrequest);
if (res.statusCode == 200) {
Log.print('jsonDecode(res.body): ${jsonDecode(res.body)}');
Get.snackbar('title', 'message', backgroundColor: AppColor.greenColor);
return jsonDecode(res.body);
} else {
throw Exception(
'Failed to upload image: ${res.statusCode} - ${res.body}');
}
}
choosImagePicture(String link, String imageType) async {
final pickedImage = await picker.pickImage(
source: ImageSource.gallery,
// preferredCameraDevice: CameraDevice.rear,
// maxHeight: Get.height * .3,
// maxWidth: Get.width * .9,
// imageQuality: 100,
);
image = File(pickedImage!.path);
croppedFile = await ImageCropper().cropImage(
sourcePath: image!.path,
uiSettings: [
AndroidUiSettings(
toolbarTitle: 'Cropper'.tr,
toolbarColor: AppColor.blueColor,
toolbarWidgetColor: AppColor.yellowColor,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
IOSUiSettings(
title: 'Cropper'.tr,
),
],
);
myImage = File(pickedImage.path);
isloading = true;
update();
// Save the cropped image
// File savedCroppedImage = File(croppedFile!.path);
File compressedImage = await compressImage(File(croppedFile!.path));
print('link =$link');
try {
await uploadImage(
compressedImage,
{
'driverID':
box.read(BoxName.driverID) ?? box.read(BoxName.passengerID),
'imageType': imageType
},
link,
);
} catch (e) {
Get.snackbar('Image Upload Failed'.tr, e.toString(),
backgroundColor: AppColor.redColor);
} finally {
isloading = false;
update();
}
}
uploadImagePicture(File file, Map data, String link) async {
var request = http.MultipartRequest(
'POST',
Uri.parse(link), //'https://ride.mobile-app.store/uploadImage1.php'
);
var length = await file.length();
var stream = http.ByteStream(file.openRead());
var multipartFile = http.MultipartFile(
'image',
stream,
length,
filename: basename(file.path),
);
request.headers.addAll({
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials.toString()))}',
});
// Set the file name to the driverID
request.files.add(
http.MultipartFile(
'image',
stream,
length,
filename: '${box.read(BoxName.driverID)}.jpg',
),
);
data.forEach((key, value) {
request.fields[key] = value;
});
var myrequest = await request.send();
var res = await http.Response.fromStream(myrequest);
if (res.statusCode == 200) {
return jsonDecode(res.body);
} else {
throw Exception(
'Failed to upload image: ${res.statusCode} - ${res.body}');
}
}
}
Future<File> compressImage(File file) async {
final dir = await path_provider.getTemporaryDirectory();
final targetPath = "${dir.absolute.path}/temp.jpg";
var result = await FlutterImageCompress.compressAndGetFile(
file.absolute.path,
targetPath,
quality: 70,
minWidth: 1024,
minHeight: 1024,
);
return File(result!.path);
}
// Future<File> detectAndCropFace(File imageFile) async {
// final inputImage = InputImage.fromFilePath(imageFile.path);
// final options = FaceDetectorOptions(
// enableClassification: false,
// enableLandmarks: false,
// enableTracking: false,
// minFaceSize: 0.15,
// performanceMode: FaceDetectorMode.accurate,
// );
// final faceDetector = FaceDetector(options: options);
// try {
// final List<Face> faces = await faceDetector.processImage(inputImage);
// final image = img.decodeImage(await imageFile.readAsBytes());
// if (image == null) throw Exception('Unable to decode image');
// int left, top, width, height;
// if (faces.isNotEmpty) {
// // Face detected, crop around the face
// final face = faces[0];
// double padding = 0.2; // 20% padding
// int paddingX = (face.boundingBox.width * padding).round();
// int paddingY = (face.boundingBox.height * padding).round();
// left = (face.boundingBox.left - paddingX).round();
// top = (face.boundingBox.top - paddingY).round();
// width = (face.boundingBox.width + 2 * paddingX).round();
// height = (face.boundingBox.height + 2 * paddingY).round();
// } else {
// // No face detected, crop the center of the image
// int size = min(image.width, image.height);
// left = (image.width - size) ~/ 2;
// top = (image.height - size) ~/ 2;
// width = size;
// height = size;
// }
// // Ensure dimensions are within image bounds
// left = left.clamp(0, image.width - 1);
// top = top.clamp(0, image.height - 1);
// width = width.clamp(1, image.width - left);
// height = height.clamp(1, image.height - top);
// final croppedImage =
// img.copyCrop(image, x: left, y: top, width: width, height: height);
// // Save the cropped image
// final tempDir = await path_provider.getTemporaryDirectory();
// final tempPath = tempDir.path;
// final croppedFile = File('$tempPath/cropped_image.jpg');
// await croppedFile.writeAsBytes(img.encodeJpg(croppedImage, quality: 100));
// return croppedFile;
// } finally {
// faceDetector.close();
// }
// }

View File

@@ -0,0 +1,108 @@
// import 'dart:convert';
// import 'dart:io';
// import 'package:get/get.dart';
// import 'package:http/http.dart' as http;
// import 'package:image_cropper/image_cropper.dart';
// import 'package:image_picker/image_picker.dart';
// import 'package:path/path.dart';
// import '../../constant/api_key.dart';
// import '../../constant/box_name.dart';
// import '../../constant/colors.dart';
// import '../../main.dart';
// class ImageController extends GetxController {
// File? myImage;
// bool isloading = false;
// CroppedFile? croppedFile;
// final picker = ImagePicker();
// var image;
// choosImage(String link, String imageType) async {
// final pickedImage = await picker.pickImage(source: ImageSource.gallery);
// image = File(pickedImage!.path);
// croppedFile = await ImageCropper().cropImage(
// sourcePath: image!.path,
// aspectRatioPresets: [
// CropAspectRatioPreset.square,
// CropAspectRatioPreset.ratio3x2,
// CropAspectRatioPreset.original,
// CropAspectRatioPreset.ratio4x3,
// CropAspectRatioPreset.ratio16x9
// ],
// uiSettings: [
// AndroidUiSettings(
// toolbarTitle: 'Cropper'.tr,
// toolbarColor: AppColor.blueColor,
// toolbarWidgetColor: AppColor.yellowColor,
// initAspectRatio: CropAspectRatioPreset.original,
// lockAspectRatio: false),
// IOSUiSettings(
// title: 'Cropper'.tr,
// ),
// ],
// );
// myImage = File(pickedImage.path);
// isloading = true;
// update();
// // Save the cropped image
// File savedCroppedImage = File(croppedFile!.path);
// try {
// await uploadImage(
// savedCroppedImage,
// {
// 'driverID':
// box.read(BoxName.driverID) ?? box.read(BoxName.passengerID),
// 'imageType': imageType
// },
// link,
// );
// } catch (e) {
// Get.snackbar('Image Upload Failed'.tr, e.toString(),
// backgroundColor: AppColor.redColor);
// } finally {
// isloading = false;
// update();
// }
// }
// uploadImage(File file, Map data, String link) async {
// var request = http.MultipartRequest(
// 'POST',
// Uri.parse(link), //'https://ride.mobile-app.store/uploadImage1.php'
// );
// var length = await file.length();
// var stream = http.ByteStream(file.openRead());
// var multipartFile = http.MultipartFile(
// 'image',
// stream,
// length,
// filename: basename(file.path),
// );
// request.headers.addAll({
// 'Authorization':
// 'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials.toString()))}',
// });
// // Set the file name to the driverID
// request.files.add(
// http.MultipartFile(
// 'image',
// stream,
// length,
// filename: '${box.read(BoxName.driverID)}.jpg',
// ),
// );
// data.forEach((key, value) {
// request.fields[key] = value;
// });
// var myrequest = await request.send();
// var res = await http.Response.fromStream(myrequest);
// if (res.statusCode == 200) {
// return jsonDecode(res.body);
// } else {
// throw Exception(
// 'Failed to upload image: ${res.statusCode} - ${res.body}');
// }
// }
// }

View File

@@ -0,0 +1,64 @@
import 'dart:convert';
import 'package:get/get.dart';
import 'package:sefer_admin1/constant/colors.dart';
import '../../constant/links.dart';
import '../firebase/firbase_messge.dart';
import 'crud.dart';
class WalletController extends GetxController {
String paymentToken = '';
Future<String> generateTokenDriver(String amount, driverID) async {
var res = await CRUD().post(link: AppLink.addPaymentTokenDriver, payload: {
'driverID': driverID.toString(),
'amount': amount.toString(),
});
var d = jsonDecode(res);
return d['message'];
}
addPaymentToDriver(String amount, driverID, token) async {
paymentToken = await generateTokenDriver(amount.toString(), driverID);
var res = await CRUD().post(link: AppLink.addDrivePayment, payload: {
'rideId': 'gift_$driverID _${DateTime.now().toIso8601String()}',
'amount': amount,
'payment_method': 'visaRide',
'passengerID': 'gift',
'token': paymentToken,
'driverID': driverID.toString(),
});
if (res != 'failure') {
FirebaseMessagesController().sendNotificationToAnyWithoutData(
"لديك هدية من سفَر".tr,
'لقد حصلت على هدية من سفر بقيمة $amount ',
token, // Access token correctly
'ding.wav',
);
Get.snackbar('success', 'addPaymentToDriver',
backgroundColor: AppColor.greenColor);
} else {
Get.snackbar('error', 'addPaymentToDriver',
backgroundColor: AppColor.redColor);
}
}
Future addSeferWallet(String point, driverID) async {
var amount = (int.parse(point) * -1).toStringAsFixed(0);
var seferToken = await generateTokenDriver(amount, driverID);
var res = await CRUD().post(link: AppLink.addSeferWallet, payload: {
'amount': amount.toString(),
'paymentMethod': 'visaRide',
'passengerId': 'gift$driverID',
'token': seferToken,
'driverId': driverID.toString(),
});
if (res != 'failure') {
Get.snackbar('success', 'addSeferWallet',
backgroundColor: AppColor.greenColor);
} else {
Get.snackbar('error', 'addSeferWallet',
backgroundColor: AppColor.redColor);
}
}
}

View File

@@ -0,0 +1,220 @@
import 'package:flutter/widgets.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';
class NotificationController extends GetxController {
final formKey = GlobalKey<FormState>();
final title = TextEditingController();
final body = TextEditingController();
List<String> tokensDriver = [];
List<String> tokensPassengers = [];
getTokensDrivers() async {
await FirebaseMessagesController().loadAllPagesAndSendNotifications();
}
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));
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();
}));
}
Future<dynamic> sendNotificationPassengers() {
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 {
// 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',
);
}
}
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%.”