first commit

This commit is contained in:
Hamza-Ayed
2024-06-22 16:34:02 +03:00
commit 0a71a194b9
205 changed files with 17401 additions and 0 deletions

72
lib/constant/api_key.dart Normal file
View File

@@ -0,0 +1,72 @@
import '../env/env.dart';
import 'char_map.dart';
import 'credential.dart';
class AK {
static final AC a = AC();
static final String publishableKey =
AC().r(AC().r(AC().r(Env.stripePublishableKe, cn), cC), cs);
static final String secretKey = a.r(a.r(a.r(Env.secretKey, cn), cC), cs);
static final String basicAuthCredentials =
a.r(a.r(a.r(Env.basicAuthCredentials, cn), cC), cs);
static final String accountSIDTwillo =
a.r(a.r(a.r(Env.accountSIDTwillo, cn), cC), cs);
static final String serverAPI = a.r(a.r(a.r(Env.serverAPI, cn), cC), cs);
static final String mapAPIKEY = a.r(a.r(a.r(Env.mapAPIKEY, cn), cC), cs);
static final String twilloRecoveryCode =
a.r(a.r(a.r(Env.twilloRecoveryCode, cn), cC), cs);
static final String authTokenTwillo =
a.r(a.r(a.r(Env.authTokenTwillo, cn), cC), cs);
static final String chatGPTkey = a.r(a.r(a.r(Env.chatGPTkey, cn), cC), cs);
static final String transactionCloude =
a.r(a.r(a.r(Env.transactionCloude, cn), cC), cs);
static final String visionApi = a.r(a.r(a.r(Env.visionApi, cn), cC), cs);
static final String chatGPTkeySefer =
a.r(a.r(a.r(Env.chatGPTkeySefer, cn), cC), cs);
static final String chatGPTkeySeferNew =
a.r(a.r(a.r(Env.chatGPTkeySeferNew, cn), cC), cs);
static final String serverPHP = Env.serverPHP;
static final String llamaKey = a.r(a.r(a.r(Env.llamaKey, cn), cC), cs);
static final String cohere = a.r(a.r(a.r(Env.cohere, cn), cC), cs);
static final String claudeAiAPI = a.r(a.r(a.r(Env.claudeAiAPI, cn), cC), cs);
static final String payPalClientId =
a.r(a.r(a.r(Env.payPalClientId, cn), cC), cs);
static final String payPalSecret =
a.r(a.r(a.r(Env.payPalSecret, cn), cC), cs);
static final String geminiApi = a.r(a.r(a.r(Env.geminiApi, cn), cC), cs);
static final String agoraAppId = a.r(a.r(a.r(Env.agoraAppId, cn), cC), cs);
static final String agoraAppCertificate =
a.r(a.r(a.r(Env.agoraAppCertificate, cn), cC), cs);
static final String payPalClientIdLive =
a.r(a.r(a.r(Env.payPalClientIdLive, cn), cC), cs);
static final String payPalSecretLive =
a.r(a.r(a.r(Env.payPalSecretLive, cn), cC), cs);
static final String integrationIdPayMob =
a.r(a.r(a.r(Env.integrationIdPayMob, cn), cC), cs);
static final String passwordPayMob =
a.r(a.r(a.r(Env.passwordPayMob, cn), cC), cs);
static final String usernamePayMob =
a.r(a.r(a.r(Env.usernamePayMob, cn), cC), cs);
static final String payMobApikey =
a.r(a.r(a.r(Env.payMobApikey, cn), cC), cs);
static final String integrationIdPayMobWallet =
a.r(a.r(a.r(Env.integrationIdPayMobWallet, cn), cC), cs);
static final String smsPasswordEgypt =
a.r(a.r(a.r(Env.smsPasswordEgypt, cn), cC), cs);
static final String ocpApimSubscriptionKey =
a.r(a.r(a.r(Env.ocpApimSubscriptionKey, cn), cC), cs);
static final String chatGPTkeySeferNew4 =
a.r(a.r(a.r(Env.chatGPTkeySeferNew4, cn), cC), cs);
static final String anthropicAIkeySeferNew =
a.r(a.r(a.r(Env.anthropicAIkeySeferNew, cn), cC), cs);
static final String llama3Key = a.r(a.r(a.r(Env.llama3Key, cn), cC), cs);
static final String payMobOutClientSecrret =
a.r(a.r(a.r(Env.payMobOutClientSecrret, cn), cC), cs);
static final String payMobOutClient_id =
a.r(a.r(a.r(Env.payMobOutClient_id, cn), cC), cs);
static final String payMobOutPassword =
a.r(a.r(a.r(Env.payMobOutPassword, cn), cC), cs);
static final String payMobOutUserName =
a.r(a.r(a.r(Env.payMobOutUserName, cn), cC), cs);
}

View File

@@ -0,0 +1,73 @@
class BoxName {
static const String driverID = "driverID";
static const String countryCode = "countryCode";
static const String googlaMapApp = "googlaMapApp";
static const String lang = "lang";
static const String carType = "carType";
static const String carPlate = "carPlate";
static const String statusDriverLocation = "statusDriverLocation";
static const String password = "password";
static const String arrivalTime = "arrivalTime";
static const String passwordDriver = "passwordDriver";
static const String agreeTerms = "agreeTerms";
static const String addWork = 'addWork';
static const String addHome = 'addHome';
static const String tipPercentage = 'tipPercentage';
static const String accountIdStripeConnect = "accountIdStripeConnect";
static const String faceDetectTimes = "faceDetectTimes";
static const String sosPhonePassenger = "sosPhonePassenger";
static const String sosPhoneDriver = "sosPhoneDriver";
static const String passengerID = "pasengerID";
static const String phone = "phone";
static const String phoneDriver = "phoneDriver";
static const String dobDriver = "dobDriver";
static const String sexDriver = "sexDriver";
static const String lastNameDriver = "lastNameDriver";
static const String name = "name";
static const String nameDriver = "nameDriver";
static const String driverPhotoUrl = "driverPhotoUrl";
static const String email = "email";
static const String emailDriver = "emailDriver";
static const String tokens = "tokens";
static const String tokensDrivers = "tokensDrivers";
static const String tokensPassengers = "tokensPassengers";
static const String tokenFCM = "tokenFCM";
static const String tokenDriver = "tokenDriver";
static const String cardNumber = "cardNumber";
static const String cardNumberDriver = "cardNumberDriver";
static const String cardHolderName = "cardHolderName";
static const String cardHolderNameDriver = "cardHolderNameDriver";
static const String expiryDate = "expiryDate";
static const String expiryDateDriver = "expiryDateDriver";
static const String cvvCode = "cvvCode";
static const String cvvCodeDriver = "cvvCodeDriver";
static const String passengerWalletDetails = "passengerWalletDetails";
static const String passengerWalletTotal = "passengerWalletTotal";
static const String passengerWalletFound = "passengerWalletFound";
static const String periods = 'periods';
static const String onBoarding = 'onBoarding';
static const String stripePublishableKey = 'stripe_publishableKe';
static const String apiKeyRun = 'apiKeyRun';
static const String serverAPI = 'serverAPI';
static const String secretKey = 'secretKey';
static const String basicAuthCredentials = 'basicAuthCredentials';
static const String mapAPIKEY = 'mapAPIKEY';
static const String twilloRecoveryCode = 'twilloRecoveryCode';
static const String accountSIDTwillo = 'accountSIDTwillo';
static const String authTokenTwillo = 'authTokenTwillo';
static const String chatGPTkey = 'chatGPTkey';
static const String chatGPTkeySefer = 'chatGPTkeySefer';
static const String transactionCloude = 'transactionCloude';
static const String visionApi = 'visionApi';
static const String vin = "vin";
static const String make = "make";
static const String model = "model";
static const String year = "year";
static const String expirationDate = "expirationDate";
static const String color = "color";
static const String owner = "owner";
static const String registrationDate = "registrationDate";
static const String recentLocations = 'recentLocations';
static const String tripData = 'tripData';
}

View File

@@ -0,0 +1,68 @@
Map<String, String> cn = {
"0": "3",
"1": "7",
"2": "1",
"3": "9",
"4": "0",
"5": "5",
"6": "2",
"7": "6",
"8": "4",
"9": "8"
};
Map<String, String> cs = {
"a": "q",
"b": "x",
"c": "f",
"d": "y",
"e": "j",
"f": "u",
"g": "k",
"h": "w",
"i": "o",
"j": "e",
"k": "g",
"l": "r",
"m": "n",
"n": "b",
"o": "i",
"p": "v",
"q": "a",
"r": "l",
"s": "z",
"t": "c",
"u": "h",
"v": "p",
"w": "t",
"x": "d",
"y": "s",
"z": "m"
};
Map<String, String> cC = {
"A": "Q",
"B": "X",
"C": "F",
"D": "Y",
"E": "J",
"F": "U",
"G": "K",
"H": "W",
"I": "O",
"J": "E",
"K": "G",
"L": "R",
"M": "N",
"N": "B",
"O": "I",
"P": "V",
"Q": "A",
"R": "L",
"S": "Z",
"T": "C",
"U": "H",
"V": "P",
"W": "T",
"X": "D",
"Y": "S",
"Z": "M"
};

14
lib/constant/colors.dart Normal file
View File

@@ -0,0 +1,14 @@
import 'package:flutter/material.dart';
class AppColor {
static const Color primaryColor = Colors.black;
static const Color secondaryColor = Colors.white;
static const Color accentColor = Colors.grey;
static const Color redColor = Color(0xFFEA4335); // Google Red
static const Color greenColor = Color(0xFF34A853); // Google Green
static const Color blueColor =
Color.fromARGB(255, 66, 135, 246); // Google Blue
static const Color yellowColor = Color(0xFFFBBC05); // Google Yellow
static Color deepPurpleAccent =
const Color.fromARGB(255, 123, 76, 254).withOpacity(0.3);
}

View File

@@ -0,0 +1,144 @@
import 'dart:convert';
import 'package:crypto/crypto.dart';
import '../controller/functions/crud.dart';
import '../main.dart';
import 'box_name.dart';
import 'char_map.dart';
import 'links.dart';
class AC {
gAK() async {
if (box.read(BoxName.apiKeyRun).toString() != 'run') {
var res = await CRUD().get(link: AppLink.getApiKey, payload: {});
var decod = jsonDecode(res);
print(decod);
Map<String, dynamic> jsonData = {};
for (var i = 0; i < decod['message'].length; i++) {
String h = decod['message'][i]['hashed_key'].toString();
String retrievedString = r(r(r(h, cn), cC), cs);
await storage.write(
key: decod['message'][i]['name'].toString(),
value: retrievedString.toString(),
);
//
String name = decod['message'][i]['name'].toString();
String value = decod['message'][i]['hashed_key'].toString();
jsonData[name] = value;
}
String jsonString = json.encode(jsonData);
print(jsonString);
box.write(BoxName.apiKeyRun, 'run');
}
}
String q(String b, String c) {
final d = utf8.encode(c);
final e = utf8.encode(b);
final f = Hmac(sha256, d);
final g = f.convert(e);
final h = g.bytes;
final i = base64Url.encode(h);
return i;
}
String j(String k, String l) {
final m = utf8.encode(l);
final n = base64Url.decode(k);
final o = Hmac(sha256, m);
final p = o.convert(n);
final q = utf8.decode(p.bytes);
return q;
}
String a(String b, String c) {
int d = b.length;
int e = d ~/ 4;
List<String> f = [];
for (int g = 0; g < d; g += e) {
int h = g + e;
if (h > d) {
h = d;
}
String i = b.substring(g, h);
f.add(i);
}
print(f);
Map<String, String> j = {};
j['birinci'] = f[4];
j['ikinci'] = f[2];
j['üçüncü'] = c + f[1];
j['dördüncü'] = f[0];
j['beş'] = f[3];
String k = '';
j.forEach((l, m) {
k += m;
});
return k;
}
Map<String, String> n(String o, String c) {
String p = o.replaceAll(c, '');
Map<String, String> q = {};
q['birinci'] = p[p.length - 5] + p[p.length - 3];
q['ikinci'] = p[p.length - 1] + p[p.length - 15];
q['üçüncü'] = p[p.length - 9] + p[p.length - 12];
q['dördüncü'] = p[p.length - 11] + p[p.length - 6];
q['beş'] = p[p.length - 2] + p[p.length - 8];
return q;
}
String c(String a, Map<String, String> b) {
StringBuffer c = StringBuffer();
c.write(a);
String d = "Bl";
c.write(b[d] ?? d);
StringBuffer e = StringBuffer();
String f = c.toString();
for (int g = 0; g < f.length; g++) {
String h = f[g];
e.write(b[h] ?? h);
}
return e.toString();
}
String r(String a, Map<String, String> b) {
StringBuffer c = StringBuffer();
String d = "Bl";
int e = d.length;
for (int f = 0; f < a.length; f++) {
String g = a[f];
String h = b.keys.firstWhere(
(i) => b[i] == g,
orElse: () => g,
);
c.write(h);
}
String j = c.toString();
if (j.endsWith(d)) {
j = j.substring(0, j.length - e);
}
return j;
}
}

4469
lib/constant/info.dart Normal file

File diff suppressed because one or more lines are too long

225
lib/constant/links.dart Normal file
View File

@@ -0,0 +1,225 @@
import '../env/env.dart';
class AppLink {
static final String server = Env.serverPHP;
static String googleMapsLink = 'https://maps.googleapis.com/maps/api/';
static String llama = 'https://api.llama-api.com/chat/completions';
static String gemini =
'https://generativelanguage.googleapis.com/v1beta3/models/text-bison-001:generateText';
static String test = "$server/test.php";
//===============firebase==========================
static String getTokens = "$server/ride/firebase/get.php";
static String getAllTokenDrivers =
"$server/ride/firebase/getALlTokenDrivers.php";
static String getAllTokenPassengers =
"$server/ride/firebase/getAllTokenPassengers.php";
static String addTokens = "$server/ride/firebase/add.php";
static String addTokensDriver = "$server/ride/firebase/addDriver.php";
//=======================Wallet===================
static String addPaymentTokenDriver =
"$ride/driverWallet/addPaymentToken.php";
static String addSeferWallet = "$ride/seferWallet/add.php";
static String getSeferWallet = "$ride/seferWallet/get.php";
static String addDrivePayment = "$ride/payment/add.php";
static String updatePaymetToPaid = "$ride/payment/updatePaymetToPaid.php";
static String wallet = '$server/ride/passengerWallet';
static String walletDriver = '$server/ride/driverWallet';
static String getAllPassengerTransaction =
"$wallet/getAllPassengerTransaction.php";
static String getWalletByPassenger = "$wallet/getWalletByPassenger.php";
static String getPassengersWallet = "$wallet/get.php";
static String getPassengerWalletArchive =
"$wallet/getPassengerWalletArchive.php";
static String addPassengersWallet = "$wallet/add.php";
static String deletePassengersWallet = "$wallet/delete.php";
static String updatePassengersWallet = "$wallet/update.php";
static String getWalletByDriver = "$walletDriver/getWalletByDriver.php";
static String getDriversWallet = "$walletDriver/get.php";
static String addDriversWalletPoints = "$walletDriver/add.php";
static String deleteDriversWallet = "$walletDriver/delete.php";
static String updateDriversWallet = "$walletDriver/update.php";
//=======================promo===================ride.mobile-app.store/ride/promo/get.php
static String promo = '$server/ride/promo';
static String getPassengersPromo = "$promo/get.php";
static String getPromoBytody = "$promo/getPromoBytody.php";
static String addPassengersPromo = "$promo/add.php";
static String deletePassengersPromo = "$promo/delete.php";
static String updatePassengersPromo = "$promo/update.php";
////=======================cancelRide===================
static String ride = '$server/ride';
static String addCancelRideFromPassenger = "$server/ride/cancelRide/add.php";
static String cancelRide = "$server/ride/cancelRide/get.php";
//-----------------ridessss------------------
static String addRides = "$ride/rides/add.php";
static String getRides = "$ride/rides/get.php";
static String getRideOrderID = "$ride/rides/getRideOrderID.php";
static String getRideStatus = "$ride/rides/getRideStatus.php";
static String getRideStatusBegin = "$ride/rides/getRideStatusBegin.php";
static String getRideStatusFromStartApp =
"$ride/rides/getRideStatusFromStartApp.php";
static String updateRides = "$ride/rides/update.php";
static String updateStausFromSpeed = "$ride/rides/updateStausFromSpeed.php";
static String deleteRides = "$ride/rides/delete.php";
//-----------------DriverPayment------------------
static String adddriverScam = "$ride/driver_scam/add.php";
static String getdriverScam = "$ride/driver_scam/get.php";
/////////---getKazanPercent===////////////
static String getKazanPercent = "$ride/kazan/get.php";
static String addKazanPercent = "$ride/kazan/add.php";
////-----------------DriverPayment------------------
static String addDriverpayment = "$ride/payment/add.php";
static String addDriverPaymentPoints = "$ride/driverPayment/add.php";
static String getDriverPaymentPoints = "$ride/driverWallet/get.php";
static String getDriverpaymentToday = "$ride/payment/get.php";
static String getCountRide = "$ride/payment/getCountRide.php";
static String getAllPaymentFromRide = "$ride/payment/getAllPayment.php";
static String getAllPaymentVisa = "$ride/payment/getAllPaymentVisa.php";
//-----------------Passenger NotificationCaptain------------------
static String addNotificationPassenger =
"$ride/notificationPassenger/add.php";
static String getNotificationPassenger =
"$ride/notificationPassenger/get.php";
static String updateNotificationPassenger =
"$ride/notificationPassenger/update.php";
//-----------------Driver NotificationCaptain------------------
static String addNotificationCaptain = "$ride/notificationCaptain/add.php";
static String addWaitingRide = "$ride/notificationCaptain/addWaitingRide.php";
static String getRideWaiting = "$ride/notificationCaptain/getRideWaiting.php";
static String getNotificationCaptain = "$ride/notificationCaptain/get.php";
static String updateNotificationCaptain =
"$ride/notificationCaptain/update.php";
static String deleteNotificationCaptain =
"$ride/notificationCaptain/delete.php";
//-----------------Api Key------------------
static String addApiKey = "$ride/apiKey/add.php";
static String getApiKey = "$ride/apiKey/get.php";
static String getCnMap = "$server/auth/cnMap.php";
static String updateApiKey = "$ride/apiKey/update.php";
static String deleteApiKey = "$ride/apiKey/delete.php";
//-----------------Feed Back------------------
static String addFeedBack = "$ride/feedBack/add.php";
static String getFeedBack = "$ride/feedBack/get.php";
static String updateFeedBack = "$ride/feedBack/updateFeedBack.php";
//-----------------Tips------------------
static String addTips = "$ride/tips/add.php";
static String getTips = "$ride/tips/get.php";
static String updateTips = "$ride/tips/update.php";
//-----------------Help Center------------------
static String addhelpCenter = "$ride/helpCenter/add.php";
static String gethelpCenter = "$ride/helpCenter/get.php";
static String getByIdhelpCenter = "$ride/helpCenter/getById.php";
static String updatehelpCenter = "$ride/helpCenter/update.php";
static String deletehelpCenter = "$ride/helpCenter/delete.php";
//-----------------license------------------
static String addLicense = "$ride/license/add.php";
static String getLicense = "$ride/license/get.php";
static String updateLicense = "$ride/license/updateFeedBack.php";
//-----------------RegisrationCar------------------
static String addRegisrationCar = "$ride/RegisrationCar/add.php";
static String getRegisrationCar = "$ride/RegisrationCar/get.php";
static String updateRegisrationCar = "$ride/RegisrationCar/update.php";
//-----------------DriverOrder------------------
static String addDriverOrder = "$ride/driver_order/add.php";
static String getDriverOrder = "$ride/driver_order/get.php";
static String getOrderCancelStatus =
"$ride/driver_order/getOrderCancelStatus.php";
static String updateDriverOrder = "$ride/driver_order/update.php";
static String deleteDriverOrder = "$ride/driver_order/delete.php";
// =====================================
static String addRateToPassenger = "$ride/rate/add.php";
static String addRateToDriver = "$ride/rate/addRateToDriver.php";
static String getDriverRate = "$ride/rate/getDriverRate.php";
static String getPassengerRate = "$ride/rate/getPassengerRate.php";
////////////////emails ============//
static String sendEmailToPassengerForTripDetails =
"$ride/rides/emailToPassengerTripDetail.php";
static String sendEmailToDrivertransaction =
"https://api.sefer.live/sefer/Admin/sendEmailToDrivertransaction.php";
// ===========================================
static String pathImage = "$server/upload/types/";
static String uploadImage = "$server/uploadImage.php";
static String uploadImage1 = "$server/uploadImage1.php";
static String uploadImagePortrate = "$server/uploadImagePortrate.php";
static String uploadImageType = "$server/uploadImageType.php";
//=============egypt documents ==============
static String uploadEgyptidFront =
"$server/EgyptDocuments/uploadEgyptidFront.php";
static String uploadEgypt = "$server/uploadEgypt.php";
//==================certifcate==========
static String location = '$server/ride/location';
static String getCarsLocationByPassenger = "$location/get.php";
static String getFemalDriverLocationByPassenger =
"$location/getFemalDriver.php";
static String getDriverCarsLocationToPassengerAfterApplied =
"$location/getDriverCarsLocationToPassengerAfterApplied.php";
static String addCarsLocationByPassenger = "$location/add.php";
static String deleteCarsLocationByPassenger = "$location/delete.php";
static String updateCarsLocationByPassenger = "$location/update.php";
static String getTotalDriverDuration = "$location/getTotalDriverDuration.php";
static String getTotalDriverDurationToday =
"$location/getTotalDriverDurationToday.php";
//==================Blog=============
static String profile = '$server/ride/profile';
static String getprofile = "$profile/get.php";
static String getCaptainProfile = "$profile/getCaptainProfile.php";
static String addprofile = "$profile/add.php";
static String deleteprofile = "$profile/delete.php";
static String updateprofile = "$profile/update.php";
//===================Auth============
static String auth = '$server/auth';
static String login = "$auth/login.php";
static String signUp = "$auth/signup.php";
static String sendVerifyEmail = "$auth/sendVerifyEmail.php";
static String passengerRemovedAccountEmail =
"$auth/passengerRemovedAccountEmail.php";
static String verifyEmail = "$auth/verifyEmail.php";
//===================Auth Captin============
static String authCaptin = '$server/auth/captin';
static String loginCaptin = "$authCaptin/login.php";
static String signUpCaptin = "$authCaptin/register.php";
static String sendVerifyEmailCaptin = "$authCaptin/sendVerifyEmail.php";
static String verifyEmailCaptin = "$authCaptin/verifyEmail.php";
static String removeUser = "$authCaptin/removeAccount.php";
static String deletecaptainAccounr = "$authCaptin/deletecaptainAccounr.php";
static String updateAccountBank = "$authCaptin/updateAccountBank.php";
static String getAccount = "$authCaptin/getAccount.php";
//===================Admin Captin============
static String getPassengerDetailsByPassengerID =
"$server/Admin/getPassengerDetailsByPassengerID.php";
static String getPassengerDetails = "$server/Admin/getPassengerDetails.php";
static String getPassengerbyEmail = "$server/Admin/getPassengerbyEmail.php";
static String addAdminUser = "$server/Admin/adminUser/add.php";
static String getdashbord = "$server/Admin/dashbord.php";
static String getAdminUser = "$server/Admin/adminUser/get.php";
static String getCaptainDetailsByEmailOrIDOrPhone =
"$server/Admin/AdminCaptain/getCaptainDetailsByEmailOrIDOrPhone.php";
static String getCaptainDetails = "$server/Admin/AdminCaptain/get.php";
static String getVisaForEachDriver = "$server/Admin/getVisaForEachDriver.php";
static String getRidesPerMonth =
"$server/Admin/AdminRide/getRidesPerMonth.php";
static String getRidesDetails = "$server/Admin/AdminRide/get.php";
}

80
lib/constant/style.dart Normal file
View File

@@ -0,0 +1,80 @@
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../main.dart';
import 'box_name.dart';
import 'colors.dart';
class AppStyle {
static TextStyle headTitle = TextStyle(
fontWeight: FontWeight.bold,
fontSize: 40,
color: AppColor.accentColor,
fontFamily: box.read(BoxName.lang) == 'en'
? GoogleFonts.josefinSans().fontFamily
: box.read(BoxName.lang) == 'ar'
? GoogleFonts.habibi().fontFamily
: GoogleFonts.josefinSans().fontFamily);
static TextStyle headTitle2 = TextStyle(
fontWeight: FontWeight.bold,
fontSize: 26,
color: AppColor.primaryColor,
fontFamily: box.read(BoxName.lang) == 'en'
? GoogleFonts.josefinSans().fontFamily
: box.read(BoxName.lang) == 'ar'
? GoogleFonts.amiri().fontFamily
: GoogleFonts.josefinSans().fontFamily);
static TextStyle title = TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: AppColor.primaryColor,
fontFamily: box.read(BoxName.lang) == 'en'
? GoogleFonts.josefinSans().fontFamily
: box.read(BoxName.lang) == 'ar'
? GoogleFonts.amiri().fontFamily
: GoogleFonts.josefinSans().fontFamily);
static TextStyle subtitle = TextStyle(
fontWeight: FontWeight.bold,
fontSize: 13,
color: AppColor.primaryColor,
fontFamily: box.read(BoxName.lang) == 'en'
? GoogleFonts.josefinSans().fontFamily
: box.read(BoxName.lang) == 'ar'
? GoogleFonts.amiri().fontFamily
: GoogleFonts.josefinSans().fontFamily);
static TextStyle number = TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14,
color: AppColor.primaryColor,
fontFamily: GoogleFonts.averiaSansLibre().fontFamily);
static BoxDecoration boxDecoration = const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(12)),
color: AppColor.secondaryColor,
boxShadow: [
BoxShadow(
color: AppColor.accentColor,
offset: Offset(-3, -3),
blurRadius: 0,
spreadRadius: 0,
blurStyle: BlurStyle.outer),
BoxShadow(
color: AppColor.accentColor,
offset: Offset(3, 3),
blurRadius: 0,
spreadRadius: 0,
blurStyle: BlurStyle.outer)
]);
static BoxDecoration boxDecoration1 = const BoxDecoration(
boxShadow: [
BoxShadow(
color: AppColor.accentColor, blurRadius: 5, offset: Offset(2, 4)),
BoxShadow(
color: AppColor.accentColor, blurRadius: 5, offset: Offset(-2, -2))
],
color: AppColor.secondaryColor,
borderRadius: BorderRadius.all(
Radius.elliptical(15, 30),
),
);
}

View File

@@ -0,0 +1,9 @@
class TableName {
static const String placesFavorite = "placesFavorite";
static const String recentLocations = "recentLocations";
static const String carLocations = "carLocations";
static const String driverOrdersRefuse = "driverOrdersRefuse";
static const String rideLocation = "rideLocation";
static const String faceDetectTimes = "faceDetectTimes";
static const String captainNotification = "captainNotification";
}

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,38 @@
import 'dart:convert';
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';
class DashboardController extends GetxController {
bool isLoading = false;
List dashbord = [];
int creditSMS = 0;
Future getDashBoard() async {
isLoading = true;
update();
var res = await CRUD().get(link: AppLink.getdashbord, payload: {});
if (res != 'failure') {
var d = jsonDecode(res);
dashbord = d['message'];
isLoading = false;
update();
}
var res2 = await CRUD().kazumiSMS(
link: 'https://sms.kazumi.me/api/sms/check-credit',
payload: {"username": "Sefer", "password": AK.smsPasswordEgypt},
);
creditSMS = res2['credit'];
update();
}
@override
void onInit() {
getDashBoard();
super.onInit();
}
}

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,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,189 @@
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().get(link: AppLink.getVisaForEachDriver, payload: {});
var d = jsonDecode(res);
driversWalletPoints = d['message'];
isLoading = false;
update();
}
}

View File

@@ -0,0 +1,116 @@
import 'dart:convert';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import '../../../constant/links.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': 'sefer_api_checker',
'password': '#c3pSwbUxOKpQnr5hHZAgpkSW',
'client_id': 'kmNWU5gKsL8LKVhsJFbOGTEb3YQ5sQhvBoB8pqoW',
'client_secret':
'htV6nFANLDd658ueTEuMrIqwjcXsocMXmBLAYof7FuutBcSxdTdoNqFl3EAvO6zrOgGPLdiMrofNp2V9ASVRpjoSlFjDNRzY7hfPunAJEgf2N5ZUuknN4QniaqIZvaNt'
};
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;
}
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://stagingpayouts.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': 'myself',
'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://stagingpayouts.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,461 @@
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 '../../constant/api_key.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 'local_notification.dart';
class FirebaseMessagesController extends GetxController {
final fcmToken = FirebaseMessaging.instance;
List<String> tokens = [];
List<String> tokensPassengers = [];
List dataTokens = [];
late String driverID;
late String driverToken;
NotificationSettings? notificationSettings;
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");
}
}
Future getAllTokenDrivers() async {
var res = await http.post(
Uri.parse(AppLink.getAllTokenDrivers),
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.tokensDrivers, tokens);
} else {
Get.defaultDialog(title: "Warning", middleText: "Server Error");
}
}
Future getAllTokenPassengers() async {
var res = await http.post(
Uri.parse(AppLink.getAllTokenPassengers),
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++) {
tokensPassengers.add(jsonResponse['data'][i]['token']);
}
box.write(BoxName.tokensPassengers, tokensPassengers);
} 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.tokensDrivers);
// 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++) {
http
.post(Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=${AK.serverAPI}'
},
body: jsonEncode({
'notification': <String, dynamic>{
'title': title,
'body': body,
'sound': 'start.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) {
// });
// }
// }
void sendNotificationToPassengerToken(
String title, body, token, List<String> map) async {
try {
final response = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=${AK.serverAPI}'
},
body: jsonEncode({
'notification': <String, dynamic>{
'title': title,
'body': body,
'sound': 'tone2.wav'
},
'data': {
'passengerList': map,
},
'priority': 'high',
'to': token,
}),
);
if (response.statusCode == 200) {
// Notification sent successfully
} else {
// Handle error response
'Failed to send notification. Status code: ${response.statusCode}';
}
} catch (e) {
// Handle other exceptions
}
}
void sendNotificationToAnyWithoutData(
String title, String body, String token) async {
try {
final response = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=${AK.serverAPI}'
},
body: jsonEncode({
'notification': <String, dynamic>{
'title': title,
'body': body,
'sound': 'notify.wav'
},
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done'
},
'priority': 'high',
'to': token,
}),
);
if (response.statusCode == 200) {
// Notification sent successfully
} else {
// Handle error response
'Failed to send notification. Status code: ${response.statusCode}';
}
} catch (e) {
// Handle other exceptions
}
}
void sendNotificationToDriverMAP(
String title, String body, String token, List<String> data) async {
try {
final response = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=${AK.serverAPI}'
},
body: jsonEncode({
'notification': <String, dynamic>{
'title': title,
'body': body,
// 'sound': 'tone2.wav',
'sound': 'order.wav'
},
'data': {
'DriverList': data,
},
'priority': 'high',
'to': token,
}),
);
if (response.statusCode == 200) {
// Notification sent successfully
} else {
// Handle error response
'Failed to send notification. Status code: ${response.statusCode}';
}
} catch (e) {
// Handle other exceptions
}
}
void sendNotificationToDriverMapPolyline(String title, String body,
String token, List<String> data, String polylineJson) async {
try {
final response = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=${AK.serverAPI}'
},
body: jsonEncode({
'notification': <String, dynamic>{
'title': title,
'body': body,
// 'sound': 'tone2.wav',
'sound': 'order.wav'
},
'data': {
'DriverList': data,
'PolylineJson': polylineJson,
},
'priority': 'high',
'to': token,
}),
);
if (response.statusCode == 200) {
// Notification sent successfully
} else {
// Handle error response
'Failed to send notification. Status code: ${response.statusCode}';
}
} catch (e) {
// Handle other exceptions
}
}
}

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,484 @@
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 '../../env/env.dart';
import '../../main.dart';
import 'gemeni.dart';
import 'llama_ai.dart';
import 'upload_image.dart';
class CRUD {
Future<dynamic> get({
required String link,
Map<String, dynamic>? payload,
}) async {
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials.toString()))}',
},
);
// if (response.statusCode == 200) {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return response.body;
}
return jsonData['status'];
}
// }
Future<dynamic> getAgoraToken({
required String channelName,
required String uid,
}) async {
var uid = box.read(BoxName.phone) ?? box.read(BoxName.phoneDriver);
var res = await http.get(
Uri.parse(
'https://repulsive-pig-rugby-shirt.cyclic.app/token?channelName=$channelName'),
headers: {'Authorization': 'Bearer ${AK.agoraAppCertificate}'});
if (res.statusCode == 200) {
var response = jsonDecode(res.body);
return response['token'];
} else {}
}
Future<dynamic> getLlama({
required String link,
required String payload,
required String prompt,
}) async {
var url = Uri.parse(
link,
);
var headers = {
'Content-Type': 'application/json',
'Authorization':
'Bearer LL-X5lJ0Px9CzKK0HTuVZ3u2u4v3tGWkImLTG7okGRk4t25zrsLqJ0qNoUzZ2x4ciPy'
// 'Authorization': 'Bearer ${Env.llamaKey}'
};
var data = json.encode({
"model": "Llama-3-70b-Inst-FW",
// "model": "llama-13b-chat",
"messages": [
{
"role": "user",
"content":
"Extract the desired information from the following passage as json decoded like $prompt just in this:\n\n$payload"
}
],
"temperature": 0.9
});
var response = await http.post(
url,
body: data,
headers: headers,
);
if (response.statusCode == 200) {
return response.body;
}
return response.statusCode;
}
Future allMethodForAI(String prompt, linkPHP, imagePath) async {
// await ImageController().choosImage(linkPHP, imagePath);
Future.delayed(const Duration(seconds: 2));
var extractedString =
await arabicTextExtractByVisionAndAI(imagePath: imagePath);
var json = jsonDecode(extractedString);
var textValues = getAllTextValuesWithLineNumbers(json);
// List<String> textValues = getAllTextValues(json);
// await AI().geminiAiExtraction(prompt, textValues);
}
Map<String, List<Map<String, String>>> getAllTextValuesWithLineNumbers(
Map json) {
Map<String, List<Map<String, String>>> output = {};
int lineNumber = 1;
if (json.containsKey('regions')) {
List<dynamic> regions = json['regions'];
for (Map<String, dynamic> region in regions) {
if (region.containsKey('lines')) {
List<dynamic> lines = region['lines'];
List<Map<String, String>> linesWithText = [];
for (Map<String, dynamic> line in lines) {
if (line.containsKey('words')) {
List<dynamic> words = line['words'];
String lineText = "";
for (Map<String, dynamic> word in words) {
if (word.containsKey('text')) {
lineText += word['text'] + " ";
}
}
lineText = lineText.trim();
linesWithText.add(
{"line_number": lineNumber.toString(), "text": lineText});
lineNumber++;
}
}
output["region_${region.hashCode}"] = linesWithText;
}
}
}
return output;
}
// List<String> getAllTextValues(Map json) {
// List<String> textValues = [];
// if (json.containsKey('regions')) {
// List<dynamic> regions = json['regions'];
// for (Map<String, dynamic> region in regions) {
// if (region.containsKey('lines')) {
// List<dynamic> lines = region['lines'];
// for (Map<String, dynamic> line in lines) {
// if (line.containsKey('words')) {
// List<dynamic> words = line['words'];
// for (Map<String, dynamic> word in words) {
// if (word.containsKey('text')) {
// textValues.add(word['text']);
// }
// }
// }
// }
// }
// }
// }
// return textValues;
// }
Future<dynamic> arabicTextExtractByVisionAndAI({
required String imagePath,
}) async {
var headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '21010e54b50f41a4904708c526e102df'
};
// var url = Uri.parse(
// 'https://ocrhamza.cognitiveservices.azure.com/vision/v2.1/ocr?language=ar',
// );
String imagePathFull =
'${AppLink.server}card_image/$imagePath-${box.read(BoxName.driverID)}.jpg';
var request = http.Request(
'POST',
Uri.parse(
'https://ocrhamza.cognitiveservices.azure.com/vision/v2.1/ocr?language=ar'));
request.body = json.encode({"url": imagePathFull});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
return await response.stream.bytesToString();
} else {}
}
Future<dynamic> getChatGPT({
required String link,
required String payload,
}) async {
var url = Uri.parse(
link,
);
var headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ${Env.chatGPTkeySeferNew}'
};
var data = json.encode({
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content":
"Extract the desired information from the following passage as json decoded like vin,make,made,year,expiration_date,color,owner,registration_date just in this:\n\n$payload"
}
],
"temperature": 0.9
});
var response = await http.post(
url,
body: data,
headers: headers,
);
if (response.statusCode == 200) {
return response.body;
}
return response.statusCode;
}
Future<dynamic> postStripe({
required String link,
Map<String, dynamic>? payload,
}) async {
// String? secretKey = await storage.read(key: BoxName.secretKey);
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer ${AK.secretKey}',
},
);
if (response.statusCode == 200) {
return response.body;
} else {}
}
Future<dynamic> post({
required String link,
Map<String, dynamic>? payload,
}) async {
// String? basicAuthCredentials =
// await storage.read(key: BoxName.basicAuthCredentials);
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
},
);
var jsonData = jsonDecode(response.body);
if (response.statusCode == 200) {
if (jsonData['status'] == 'success') {
return response.body;
} else {
return (jsonData['status']);
}
} else {
return response.statusCode;
}
}
Future<dynamic> kazumiSMS({
required String link,
Map<String, dynamic>? payload,
}) async {
var url = Uri.parse(
link,
);
var headers = {'Content-Type': 'application/json'};
var request = http.Request('POST', url);
request.body = json.encode({
"username": "Sefer",
"password": AK.smsPasswordEgypt,
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
var responseBody = await response.stream.bytesToString();
var data = json.decode(responseBody);
return data;
} else {}
}
Future<dynamic> postPayMob({
required String link,
Map<String, dynamic>? payload,
}) async {
// String? basicAuthCredentials =
// await storage.read(key: BoxName.basicAuthCredentials);
var url = Uri.parse(
link,
);
var response = await http.post(url,
body: payload, headers: {'Content-Type': 'application/json'});
var jsonData = jsonDecode(response.body);
if (response.statusCode == 200) {
if (jsonData['status'] == 'success') {
return response.body;
} else {
return (jsonData['status']);
}
} else {
return response.statusCode;
}
}
sendEmail(
String link,
Map<String, String>? payload,
) async {
var headers = {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
};
var request = http.Request('POST', Uri.parse(link));
request.bodyFields = payload!;
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
} else {}
}
Future<dynamic> postFromDialogue({
required String link,
Map<String, dynamic>? payload,
}) async {
// String? basicAuthCredentials =
// await storage.read(key: BoxName.basicAuthCredentials);
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
},
);
if (response.body.isNotEmpty) {
var jsonData = jsonDecode(response.body);
if (response.statusCode == 200) {
if (jsonData['status'] == 'success') {
Get.back();
// Get.snackbar(
// jsonData['status'],
// jsonData['message'],
// );
return response.body;
}
}
return (jsonData['status']);
}
}
Future<void> sendVerificationRequest(String phoneNumber) async {
final accountSid = AK.accountSIDTwillo;
final authToken = AK.authTokenTwillo;
final verifySid = AK.twilloRecoveryCode;
final Uri verificationUri = Uri.parse(
'https://verify.twilio.com/v2/Services/$verifySid/Verifications');
// Send the verification request
final response = await http.post(
verificationUri,
headers: {
'Authorization':
'Basic ${base64Encode(utf8.encode('$accountSid:$authToken'))}',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
'To': phoneNumber,
'Channel': 'sms',
},
);
if (response.statusCode == 201) {
} else {}
// Prompt the user to enter the OTP
const otpCode = "123456"; // Replace with user input
// Check the verification code
final checkUri = Uri.parse(
'https://verify.twilio.com/v2/Services/$verifySid/VerificationCheck');
final checkResponse = await http.post(
checkUri,
headers: {
'Authorization':
'Basic ${base64Encode(utf8.encode('$accountSid:$authToken'))}',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
'To': phoneNumber,
'Code': otpCode,
},
);
if (checkResponse.statusCode == 201) {
} else {}
}
Future<dynamic> getGoogleApi({
required String link,
Map<String, dynamic>? payload,
}) async {
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
);
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'OK') {
return jsonData;
}
return (jsonData['status']);
}
Future<dynamic> update({
required String endpoint,
required Map<String, dynamic> data,
required String id,
}) async {
// String? basicAuthCredentials =
// await storage.read(key: BoxName.basicAuthCredentials);
var url = Uri.parse('$endpoint/$id');
var response = await http.put(
url,
body: json.encode(data),
headers: {
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
},
);
return json.decode(response.body);
}
Future<dynamic> delete({
required String endpoint,
required String id,
}) async {
// String? basicAuthCredentials =
// await storage.read(key: BoxName.basicAuthCredentials);
var url = Uri.parse('$endpoint/$id');
var response = await http.delete(
url,
headers: {
'Authorization':
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
},
);
return json.decode(response.body);
}
}

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,90 @@
// import 'dart:io';
// import 'package:device_info_plus/device_info_plus.dart';
// 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,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,63 @@
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 {}
}
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,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,115 @@
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sefer_admin1/constant/box_name.dart';
import 'package:sefer_admin1/controller/firebase/firbase_messge.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';
class NotificationController extends GetxController {
final formKey = GlobalKey<FormState>();
final title = TextEditingController();
final body = TextEditingController();
List<String> tokensDriver = [];
List<String> tokensPassengers = [];
getTokensDrivers() async {
await FirebaseMessagesController().getAllTokenDrivers();
}
getTokensPassengers() async {
await FirebaseMessagesController().getAllTokenPassengers();
}
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);
if (formKey.currentState!.validate()) {
for (var i = 0; i < tokensDriver.length; i++) {
FirebaseMessagesController().sendNotificationToAnyWithoutData(
title.text, body.text, tokensDriver[i]);
}
}
}),
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);
for (var i = 0; i < tokensPassengers.length; i++) {
if (formKey.currentState!.validate()) {
FirebaseMessagesController().sendNotificationToAnyWithoutData(
title.text, body.text, tokensPassengers[i]);
}
}
}),
cancel: MyElevatedButton(
title: 'cancel',
onPressed: () {
Get.back();
}));
}
}

70
lib/firebase_options.dart Normal file
View File

@@ -0,0 +1,70 @@
// File generated by FlutterFire CLI.
// ignore_for_file: type=lint
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show defaultTargetPlatform, kIsWeb, TargetPlatform;
/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
if (kIsWeb) {
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for web - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
return ios;
case TargetPlatform.macOS:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for macos - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.windows:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for windows - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.linux:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for linux - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions android = FirebaseOptions(
apiKey: 'AIzaSyCyfwRXTwSTLOFQSQgN5p7QZgGJVZnEKq0',
appId: '1:594687661098:android:8ec72f5f8b0b0ab8595f53',
messagingSenderId: '594687661098',
projectId: 'ride-b1bd8',
storageBucket: 'ride-b1bd8.appspot.com',
);
static const FirebaseOptions ios = FirebaseOptions(
apiKey: 'AIzaSyCf2mW2h0HD8ZYjwh4VOa2ladw6MJkCDTM',
appId: '1:594687661098:ios:9f46a169fad13752595f53',
messagingSenderId: '594687661098',
projectId: 'ride-b1bd8',
storageBucket: 'ride-b1bd8.appspot.com',
androidClientId: '594687661098-2dhoogl7be9phobfbu8bbg1sj567iv88.apps.googleusercontent.com',
iosClientId: '594687661098-aj48k038fjst4k8jiprfbq8895b11cci.apps.googleusercontent.com',
iosBundleId: 'com.example.seferAdmin1',
);
}

64
lib/main.dart Normal file
View File

@@ -0,0 +1,64 @@
import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'controller/firebase/firbase_messge.dart';
import 'firebase_options.dart';
import 'models/db_sql.dart';
import 'views/admin/admin_home_page.dart';
final box = GetStorage();
const storage = FlutterSecureStorage();
@pragma('vm:entry-point')
Future<void> backgroundMessageHandler(RemoteMessage message) async {
await Firebase.initializeApp();
if (message.data.isNotEmpty && message.notification != null) {
FirebaseMessagesController().fireBaseTitles(message);
}
}
DbSql sql = DbSql.instance;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await GetStorage.init();
if (Platform.isAndroid || Platform.isIOS) {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await FirebaseMessagesController().requestFirebaseMessagingPermission();
FirebaseMessaging.onBackgroundMessage(backgroundMessageHandler);
List<Future> initializationTasks = [
FirebaseMessagesController().getNotificationSettings(),
FirebaseMessagesController().getToken(),
];
await Future.wait(initializationTasks);
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
runApp(const MainApp());
}
class MainApp extends StatelessWidget {
const MainApp({super.key});
@override
Widget build(BuildContext context) {
return const GetMaterialApp(
debugShowCheckedModeBanner: false,
home: AdminHomePage(),
);
}
}

116
lib/models/db_sql.dart Normal file
View File

@@ -0,0 +1,116 @@
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import '../constant/table_names.dart';
class DbSql {
static final DbSql instance = DbSql._();
static Database? _database;
DbSql._();
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
Future<Database> _initDatabase() async {
String path = join(await getDatabasesPath(), 'my_database.db');
return await openDatabase(
path,
version: 1,
onCreate: (db, version) async {
await db.execute('''
CREATE TABLE IF NOT EXISTS ${TableName.carLocations}(
id INTEGER PRIMARY KEY AUTOINCREMENT,
driver_id TEXT,
latitude REAL,
longitude REAL,
created_at TEXT,
updated_at TEXT
)
''');
await db.execute('''
CREATE TABLE IF NOT EXISTS ${TableName.placesFavorite}(
id INTEGER PRIMARY KEY AUTOINCREMENT,
latitude REAL,
longitude REAL,
name TEXT UNIQUE,
rate TEXT
)
''');
await db.execute('''
CREATE TABLE IF NOT EXISTS ${TableName.recentLocations}(
id INTEGER PRIMARY KEY AUTOINCREMENT,
latitude REAL,
longitude REAL,
name TEXT ,
rate TEXT
)
''');
await db.execute('''
CREATE TABLE IF NOT EXISTS ${TableName.driverOrdersRefuse}(
id INTEGER PRIMARY KEY AUTOINCREMENT,
order_id TEXT UNIQUE,
created_at TEXT,
driver_id TEXT
)
''');
await db.execute('''
CREATE TABLE IF NOT EXISTS ${TableName.rideLocation}(
id INTEGER PRIMARY KEY AUTOINCREMENT,
order_id TEXT ,
created_at TEXT,
lat TEXT,
lng TEXT
)
''');
await db.execute('''
CREATE TABLE IF NOT EXISTS ${TableName.faceDetectTimes}(
id INTEGER PRIMARY KEY AUTOINCREMENT,
faceDetectTimes INTEGER
)
''');
await db.execute('''
CREATE TABLE IF NOT EXISTS ${TableName.captainNotification}(
id INTEGER PRIMARY KEY AUTOINCREMENT,
faceDetectTimes INTEGER
)
''');
},
);
}
Future<List<Map<String, dynamic>>> getAllData(String table) async {
Database db = await instance.database;
return await db.query(table);
}
Future<List<Map<String, dynamic>>> getCustomQuery(String query) async {
Database db = await instance.database;
return await db.rawQuery(query);
}
Future<int> insertData(Map<String, dynamic> map, String table) async {
Database db = await instance.database;
return await db.insert(table, map);
}
Future<int> updateData(Map<String, dynamic> map, String table, int id) async {
Database db = await instance.database;
return await db.update(table, map, where: 'id = ?', whereArgs: [id]);
}
Future<int> deleteData(String table, int id) async {
Database db = await instance.database;
return await db.delete(table, where: 'id = ?', whereArgs: [id]);
}
Future<int> deleteAllData(String table) async {
Database db = await instance.database;
return await db.delete(table);
}
}

View File

@@ -0,0 +1,40 @@
-- Frequent Complaint Passengers
SELECT
passengers.id AS passenger_id,
passengers.first_name,
passengers.last_name,
passengers.phone,
COUNT(`feedBack`.id) AS complaint_count
FROM
passengers
JOIN `feedBack` ON passengers.id = `feedBack`.`passengerId`
GROUP BY
passengers.id
ORDER BY
complaint_count
DESC
LIMIT 10;
--==========
-- to get all driver payment to pay to them
SELECT
p.driverID,
COALESCE(SUM(p.amount), 0) AS total_amount,
COALESCE(SUM(p.amount), 0) + COALESCE(pd.total_points, 0) AS diff
FROM
payments p
JOIN (
SELECT
driverID,
SUM(amount) AS total_points
FROM
paymentsDriverPoints
WHERE
payment_method = 'fromBudgetToPoints'
GROUP BY
driverID
) pd ON p.driverID = pd.driverID
WHERE
p.isGiven = 'waiting'
AND p.payment_method IN ('visa-in', 'visa', 'visaRide', 'TransferFrom', 'payout', 'TransferTo')
GROUP BY
p.driverID;

View File

@@ -0,0 +1,21 @@
class MonthlyDataModel {
final int year;
final int month;
final int day;
final int ridesCount;
MonthlyDataModel({
required this.year,
required this.month,
required this.day,
required this.ridesCount,
});
factory MonthlyDataModel.fromJson(Map<String, dynamic> json) =>
MonthlyDataModel(
year: json['year'] as int,
month: json['month'] as int,
day: json['day'] as int,
ridesCount: json['rides_count'] as int,
);
}

View File

@@ -0,0 +1,79 @@
class Passenger {
String id;
String phone;
String email;
String gender;
String status;
String birthdate;
String site;
String firstName;
String lastName;
String sosPhone;
String education;
String employmentType;
String maritalStatus;
String createdAt;
String updatedAt;
int countPassenger;
int countFeedback;
double ratingPassenger;
int countDriverRate;
int countPassengerCancel;
double passengerAverageRating;
int countPassengerRate;
int countPassengerRide;
Passenger({
required this.id,
required this.phone,
required this.email,
required this.gender,
required this.status,
required this.birthdate,
required this.site,
required this.firstName,
required this.lastName,
required this.sosPhone,
required this.education,
required this.employmentType,
required this.maritalStatus,
required this.createdAt,
required this.updatedAt,
required this.countPassenger,
required this.countFeedback,
required this.ratingPassenger,
required this.countDriverRate,
required this.countPassengerCancel,
required this.passengerAverageRating,
required this.countPassengerRate,
required this.countPassengerRide,
});
factory Passenger.fromJson(Map<String, dynamic> json) {
return Passenger(
id: json['id'],
phone: json['phone'],
email: json['email'],
gender: json['gender'],
status: json['status'],
birthdate: json['birthdate'],
site: json['site'],
firstName: json['first_name'],
lastName: json['last_name'],
sosPhone: json['sosPhone'],
education: json['education'],
employmentType: json['employmentType'],
maritalStatus: json['maritalStatus'],
createdAt: json['created_at'],
updatedAt: json['updated_at'],
countPassenger: json['countPassenger'],
countFeedback: json['countFeedback'],
ratingPassenger: json['ratingPassenger'].toDouble(),
countDriverRate: json['countDriverRate'],
countPassengerCancel: json['countPassengerCancel'],
passengerAverageRating: json['passengerAverageRating'].toDouble(),
countPassengerRate: json['countPassengerRate'],
countPassengerRide: json['countPassengerRide'],
);
}
}

View File

@@ -0,0 +1,12 @@
class MonthlyDataModel {
int day;
int totalDuration;
MonthlyDataModel({required this.day, required this.totalDuration});
factory MonthlyDataModel.fromJson(Map<String, dynamic> json) =>
MonthlyDataModel(
day: int.parse(json['day'].toString().split('-')[2]),
totalDuration:
int.parse(json['total_duration'].toString().split(':')[0]));
}

View File

@@ -0,0 +1,34 @@
class CarLocationModel {
String id;
String driverId;
double latitude;
double heading;
double speed;
double longitude;
DateTime createdAt;
DateTime updatedAt;
CarLocationModel({
required this.id,
required this.driverId,
required this.latitude,
required this.longitude,
required this.heading,
required this.speed,
required this.createdAt,
required this.updatedAt,
});
factory CarLocationModel.fromJson(Map<String, dynamic> json) {
return CarLocationModel(
id: json['id'],
driverId: json['driver_id'],
latitude: double.parse(json['latitude'].toString()),
longitude: double.parse(json['longitude'].toString()),
heading: double.parse(json['heading'].toString()),
speed: double.parse(json['speed'].toString()),
createdAt: DateTime.parse(json['created_at']),
updatedAt: DateTime.parse(json['updated_at']),
);
}
}

View File

@@ -0,0 +1,30 @@
import 'package:get/get.dart';
List<OnBoardingModel> onBoardingList = [
OnBoardingModel(
title: 'Welcome to Sefer!'.tr,
image: 'assets/images/on1.png',
body:
'Sefer is the ride-hailing app that is safe, reliable, and accessible.'
.tr,
),
OnBoardingModel(
title: 'Get to your destination quickly and easily.'.tr,
image: 'assets/images/on2.png',
body: 'With Sefer, you can get a ride to your destination in minutes.'.tr,
),
OnBoardingModel(
title: 'Enjoy a safe and comfortable ride.'.tr,
image: 'assets/images/on3.png',
body:
'Sefer is committed to safety, and all of our captains are carefully screened and background checked.'
.tr,
),
];
class OnBoardingModel {
final String? title;
final String? image;
final String? body;
OnBoardingModel({this.body, this.title, this.image});
}

13
lib/print.dart Normal file
View File

@@ -0,0 +1,13 @@
import 'dart:developer' as developer;
class Log {
Log._();
static void print(String value, {StackTrace? stackTrace}) {
developer.log(value, name: 'LOG', stackTrace: stackTrace);
}
static Object? inspect(Object? object) {
return developer.inspect(object);
}
}

View File

@@ -0,0 +1,393 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/src/rx_typedefs/rx_typedefs.dart';
import 'package:sefer_admin1/controller/admin/dashboard_controller.dart';
import 'package:sefer_admin1/controller/notification_controller.dart';
import 'package:sefer_admin1/views/widgets/mycircular.dart';
import '../../constant/links.dart';
import '../../constant/style.dart';
import '../../controller/functions/crud.dart';
import '../../controller/functions/gemeni.dart';
import '../widgets/my_scafold.dart';
import 'captain/captain.dart';
import 'passenger/passenger.dart';
import 'rides/rides.dart';
import 'static/static.dart';
import 'wallet/wallet.dart';
class AdminHomePage extends StatelessWidget {
const AdminHomePage({super.key});
@override
Widget build(BuildContext context) {
Get.put(DashboardController());
return MyScafolld(
title: 'Admin Home Page',
body: [
GetBuilder<DashboardController>(builder: (dashboardController) {
return dashboardController.dashbord.isEmpty
? const MyCircularProgressIndicator()
: Padding(
padding: const EdgeInsets.all(8.0),
child: ListView(
// crossAxisAlignment: WrapCrossAlignment.center,
// alignment: WrapAlignment.center,
children: [
Container(
width: Get.width,
height: Get.height * .6,
decoration: AppStyle.boxDecoration1,
child: Wrap(
spacing: 6,
alignment: WrapAlignment.spaceBetween,
runAlignment: WrapAlignment.spaceBetween,
children: [
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'Sms',
style: AppStyle.title,
),
Text(dashboardController.creditSMS
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'Passengers',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['countPassengers']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'Drivers',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['countDriver']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'Rides this month',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['countRideThisMonth']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'avg costs',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['avg_passenger_price']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'completed ride',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['completed_rides']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'cancelled ride',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['cancelled_rides']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'payments to driver',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['payments']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'sefer wallet',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['seferWallet']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'count of transfer',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['transfer_from_count']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'Morning',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['morning_ride_count']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'evening',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['evening_ride_count']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'night',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['night_ride_count']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'comfort',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['comfort']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'Speed',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['speed']
.toString()),
],
),
)),
Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'Lady',
style: AppStyle.title,
),
Text(dashboardController.dashbord[0]
['lady']
.toString()),
],
),
)),
],
)),
AdminWidgetsDashBoard(
title: 'Passengers',
onPressed: () => Get.to(() => Passengrs(),
transition: Transition.topLevel)),
AdminWidgetsDashBoard(
title: 'Captains',
onPressed: () => Get.to(() => Captain(),
transition: Transition.size)),
AdminWidgetsDashBoard(
title: 'Wallet',
onPressed: () => Get.to(() => Wallet(),
transition: Transition.fade)),
AdminWidgetsDashBoard(
title: 'Rides',
onPressed: () => Get.to(() => Rides(),
transition: Transition.downToUp)),
AdminWidgetsDashBoard(
title: 'Static',
onPressed: () => Get.to(() => const StaticDash())),
AdminWidgetsDashBoard(
title: 'send notification Drivers',
onPressed: () async {
await Get.put(NotificationController())
.getTokensDrivers();
NotificationController()
.sendNotificationDrivers();
}),
AdminWidgetsDashBoard(
title: 'send notification Passengers',
onPressed: () async {
await Get.put(NotificationController())
.getTokensPassengers();
NotificationController()
.sendNotificationPassengers();
}),
// AdminWidgetsDashBoard(
// title: 'JordanID', onPressed: () => AI().jordanID()),
// AdminWidgetsDashBoard(
// title: 'Llama',
// onPressed: () =>
// CarRegistrationRecognizerController().scanText()),
AdminWidgetsDashBoard(
title: 'Add device to be Admin',
onPressed: () async {
// Map device = DeviceInfoPlus.deviceData;
await CRUD()
.post(link: AppLink.addAdminUser, payload: {
// 'deviceNumber': device['serialNumber'].toString(),
'name': 'b',
});
}),
],
),
);
})
],
isleading: false);
}
}
class AdminWidgetsDashBoard extends StatelessWidget {
const AdminWidgetsDashBoard({
super.key,
required this.title,
required this.onPressed,
});
final String title;
final Callback onPressed;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: onPressed,
child: Container(
decoration: AppStyle.boxDecoration,
height: 50,
width: Get.width * .4,
child: Center(
child: Text(
title.tr,
style: AppStyle.title,
),
),
),
),
);
}
}

View File

@@ -0,0 +1,222 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/admin/captain_admin_controller.dart';
import '../../widgets/elevated_btn.dart';
import '../../widgets/my_scafold.dart';
import '../../widgets/my_textField.dart';
import '../../widgets/mycircular.dart';
import 'captain_details.dart';
import 'form_captain.dart';
class Captain extends StatelessWidget {
Captain({super.key});
final CaptainAdminController captainAdminController =
Get.put(CaptainAdminController());
@override
Widget build(BuildContext context) {
return MyScafolld(
title: 'Captain'.tr,
body: [
GetBuilder<CaptainAdminController>(
builder: (captainAdminController) => Column(
children: [
captainAdminController.isLoading
? const MyCircularProgressIndicator()
: Column(
children: [
Padding(
padding: const EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
captainAdmin(
captainAdminController,
'Captains Count',
'countPassenger',
),
MyElevatedButton(
title: 'Add Prize to Gold Captains',
onPressed: () {
var date = DateTime.now();
var day = date.weekday;
if (day == 6) {
// Saturday is 6
Get.defaultDialog(
title:
'Add Prize to Gold Captains',
titleStyle: AppStyle.title,
content: Column(
children: [
Text(
'Add Points to their wallet as prize'
.tr,
style: AppStyle.title,
),
Form(
key: captainAdminController
.formCaptainPrizeKey,
child: MyTextForm(
controller:
captainAdminController
.captainPrizeController,
label:
'Count of prize'
.tr,
hint: 'Count of prize'
.tr,
type: TextInputType
.number))
],
),
confirm: MyElevatedButton(
title: 'Add',
onPressed: () async {
if (captainAdminController
.formCaptainPrizeKey
.currentState!
.validate()) {
captainAdminController
.addCaptainsPrizeToWalletSecure();
}
},
),
);
} else {
Get.defaultDialog(
title:
'This day is not allowed',
titleStyle: AppStyle.title,
middleText:
'Saturday only Allowed day',
middleTextStyle: AppStyle.title,
confirm: MyElevatedButton(
title: 'Ok'.tr,
onPressed: () {
Get.back();
}));
}
})
],
),
),
const SizedBox(
height: 10,
),
InkWell(
onTap: () {
//todo search
},
child: Padding(
padding: const EdgeInsets.all(3),
child: Container(
width: Get.width,
height: 110,
decoration: BoxDecoration(
border: Border.all(
width: 2,
color: AppColor.greenColor)),
child: formSearchCaptain()
// ],
// ),
),
),
),
SizedBox(
height: Get.height * .5,
child: ListView.builder(
itemCount: captainAdminController
.captainData['message'].length,
itemBuilder: (context, index) {
final user = captainAdminController
.captainData['message'][index];
return InkWell(
onTap: () {
Get.to(const CaptainsDetailsPage(),
arguments: {
'data': user,
});
},
child: Padding(
padding: const EdgeInsets.all(3),
child: Container(
decoration: BoxDecoration(
border: Border.all(width: 2)),
child: ListTile(
title: Row(
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
Text(
'Name : ${user['first_name']} ${user['last_name']}',
style: AppStyle.title,
),
Text(
'Rating : ${user['ratingPassenger']}',
style: AppStyle.title,
),
],
),
subtitle: Row(
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
Text(
'Count Trip : ${user['countPassengerRide']}',
style: AppStyle.title,
),
Text(
'Count Driver Rate : ${user['countDriverRate']}',
style: AppStyle.title,
),
],
),
),
),
),
);
},
),
),
],
),
],
))
],
isleading: true,
);
}
Container captainAdmin(CaptainAdminController captainAdminController,
String title, String jsonField) {
return Container(
height: Get.height * .1,
decoration: BoxDecoration(border: Border.all(width: 2)),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {},
child: Column(
children: [
Text(
title.tr,
style: AppStyle.title,
),
Text(
captainAdminController.captainData['message'][0][jsonField]
.toString(),
style: AppStyle.title,
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,167 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/admin/captain_admin_controller.dart';
import '../../../controller/firebase/firbase_messge.dart';
import '../../widgets/elevated_btn.dart';
import '../../widgets/my_scafold.dart';
import '../../widgets/my_textField.dart';
class CaptainsDetailsPage extends StatelessWidget {
const CaptainsDetailsPage({super.key});
@override
Widget build(BuildContext context) {
final arguments = Get.arguments;
final Map<String, dynamic> data = arguments['data'];
var key = Get.find<CaptainAdminController>().formCaptainPrizeKey;
var titleNotify = Get.find<CaptainAdminController>().titleNotify;
var bodyNotify = Get.find<CaptainAdminController>().bodyNotify;
return MyScafolld(
title: data['first_name'] + ' ' + data['last_name'],
body: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Email is ${data['email']}',
style: AppStyle.title,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Phone is ${data['phone']}',
style: AppStyle.title,
),
Text(
'gender is ${data['gender']}',
style: AppStyle.title,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'status is ${data['status']}',
style: AppStyle.title,
),
Text(
'birthdate is ${data['birthdate']}',
style: AppStyle.title,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'site is ${data['site']}',
style: AppStyle.title,
),
// Text(
// 'sosPhone is ${data['sosPhone']}',
// style: AppStyle.title,
// ),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Count Feedback is ${data['countFeedback']}',
style: AppStyle.title,
),
Text(
'Count Driver Rate is ${data['countDriverRate']}',
style: AppStyle.title,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Count Cancel is ${data['countPassengerCancel']}',
style: AppStyle.title,
),
Text(
'Count Ride is ${data['countPassengerRide']}',
style: AppStyle.title,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Rating Captain Avarage is ${data['passengerAverageRating']}',
style: AppStyle.title,
),
Text(
'Rating is ${data['ratingPassenger']}',
style: AppStyle.title,
),
],
),
Container(
decoration: BoxDecoration(
border: Border.all(width: 3, color: AppColor.yellowColor)),
child: TextButton(
onPressed: () async {
Get.defaultDialog(
title: 'Send Notification'.tr,
titleStyle: AppStyle.title,
content: Form(
key: key,
child: Column(
children: [
MyTextForm(
controller: titleNotify,
label: 'title'.tr,
hint: 'title notificaton'.tr,
type: TextInputType.name),
const SizedBox(
height: 10,
),
MyTextForm(
controller: bodyNotify,
label: 'body'.tr,
hint: 'body notificaton'.tr,
type: TextInputType.name)
],
),
),
confirm: MyElevatedButton(
title: 'Send',
onPressed: () {
if (key.currentState!.validate()) {
FirebaseMessagesController()
.sendNotificationToAnyWithoutData(
titleNotify.text,
bodyNotify.text,
data['passengerToken'],
);
Get.back();
}
}));
},
child: Text(
"Send Notificaion to Captains ".tr,
style: AppStyle.title,
),
),
)
],
),
)
],
isleading: true,
);
}
}

View File

@@ -0,0 +1,84 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/admin/captain_admin_controller.dart';
import '../../widgets/elevated_btn.dart';
import 'captain_details.dart';
GetBuilder<CaptainAdminController> formSearchCaptain() {
// DbSql sql = DbSql.instance;
return GetBuilder<CaptainAdminController>(
builder: (controller) => Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Container(
decoration:
const BoxDecoration(color: AppColor.secondaryColor),
child: TextField(
decoration: InputDecoration(
border: const OutlineInputBorder(
borderRadius: BorderRadius.only(),
gapPadding: 4,
borderSide: BorderSide(
color: AppColor.redColor,
width: 2,
)),
suffixIcon: InkWell(
onTap: () async {
if (controller.captainController.text.length > 4) {
await controller.getCaptains();
Get.defaultDialog(
title: controller.captain['message'][0]
['email'],
titleStyle: AppStyle.title,
content: Column(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
'Name is ${controller.captain['message'][0]['first_name']} ${controller.captain['message'][0]['last_name']}',
style: AppStyle.title,
),
Text(
'phone is ${controller.captain['message'][0]['phone']}',
style: AppStyle.title,
),
],
),
confirm: MyElevatedButton(
title: 'Go To Details'.tr,
onPressed: () {
Get.to(
() => const CaptainsDetailsPage(),
arguments: {
'data': controller
.captain['message'][0],
});
}));
}
},
child: const Icon(Icons.search)),
hintText: 'Search for Passenger'.tr,
hintStyle: AppStyle.title,
hintMaxLines: 1,
prefixIcon: IconButton(
onPressed: () async {
controller.captainController.clear();
// controller.clearPlaces();
},
icon: Icon(
Icons.clear,
color: Colors.red[300],
),
),
),
controller: controller.captainController,
),
),
)
],
));
}

View File

@@ -0,0 +1,86 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/admin/passenger_admin_controller.dart';
import '../../widgets/elevated_btn.dart';
import 'passenger_details_page.dart';
GetBuilder<PassengerAdminController> formSearchPassengers() {
// DbSql sql = DbSql.instance;
return GetBuilder<PassengerAdminController>(
builder: (controller) => Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Container(
decoration:
const BoxDecoration(color: AppColor.secondaryColor),
child: TextField(
decoration: InputDecoration(
border: const OutlineInputBorder(
borderRadius: BorderRadius.only(),
gapPadding: 4,
borderSide: BorderSide(
color: AppColor.redColor,
width: 2,
)),
suffixIcon: InkWell(
onTap: () async {
if (controller.passengerController.text.length >
4) {
await controller.getPassengers();
Get.defaultDialog(
title: controller.passengers['message'][0]
['email'],
titleStyle: AppStyle.title,
content: Column(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
'Name is ${controller.passengers['message'][0]['first_name']} ${controller.passengers['message'][0]['last_name']}',
style: AppStyle.title,
),
Text(
'phone is ${controller.passengers['message'][0]['phone']}',
style: AppStyle.title,
),
],
),
confirm: MyElevatedButton(
title: 'Go To Details'.tr,
onPressed: () {
Get.to(
() => const PassengerDetailsPage(),
arguments: {
'data': controller
.passengers['message'][0],
});
}));
}
},
child: const Icon(Icons.search)),
hintText: 'Search for Passenger'.tr,
hintStyle: AppStyle.title,
hintMaxLines: 1,
prefixIcon: IconButton(
onPressed: () async {
controller.passengerController.clear();
controller.clearPlaces();
},
icon: Icon(
Icons.clear,
color: Colors.red[300],
),
),
),
controller: controller.passengerController,
),
),
)
],
));
}

View File

@@ -0,0 +1,204 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../constant/style.dart';
import '../../../controller/admin/passenger_admin_controller.dart';
import '../../widgets/elevated_btn.dart';
import '../../widgets/my_scafold.dart';
import '../../widgets/my_textField.dart';
import '../../widgets/mycircular.dart';
import 'form_passenger.dart';
import 'passenger_details_page.dart';
class Passengrs extends StatelessWidget {
Passengrs({super.key});
final PassengerAdminController passengerAdminController =
Get.put(PassengerAdminController());
@override
Widget build(BuildContext context) {
return MyScafolld(
title: 'Passengrs'.tr,
isleading: true,
body: [
GetBuilder<PassengerAdminController>(
builder: (passengerAdminController) => Column(
children: [
passengerAdminController.isLoading
? const MyCircularProgressIndicator()
: Column(
children: [
Padding(
padding: const EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
passengerAdmin(
passengerAdminController,
'Passengers Count',
'countPassenger',
),
MyElevatedButton(
title: 'Add Prize to Gold Passengers',
onPressed: () {
var date = DateTime.now();
var day = date.weekday;
if (day == 6) {
// Saturday is 6
Get.defaultDialog(
title:
'Add Prize to Gold Passengers',
titleStyle: AppStyle.title,
content: Column(
children: [
Text(
'Add Points to their wallet as prize'
.tr,
style: AppStyle.title,
),
Form(
key:
passengerAdminController
.formPrizeKey,
child: MyTextForm(
controller:
passengerAdminController
.passengerPrizeController,
label:
'Count of prize'
.tr,
hint: 'Count of prize'
.tr,
type: TextInputType
.number))
],
),
confirm: MyElevatedButton(
title: 'Add',
onPressed: () async {
if (passengerAdminController
.formPrizeKey
.currentState!
.validate()) {
passengerAdminController
.addPassengerPrizeToWalletSecure();
}
},
),
);
} else {
Get.defaultDialog(
title:
'This day is not allowed',
titleStyle: AppStyle.title,
middleText:
'Saturday only Allowed day',
middleTextStyle: AppStyle.title,
confirm: MyElevatedButton(
title: 'Ok'.tr,
onPressed: () {
Get.back();
}));
}
})
],
),
),
const SizedBox(
height: 10,
),
formSearchPassengers(),
SizedBox(
height: Get.height * .5,
child: ListView.builder(
itemCount: passengerAdminController
.passengersData['message'].length,
itemBuilder: (context, index) {
final user = passengerAdminController
.passengersData['message'][index];
return InkWell(
onTap: () {
Get.to(const PassengerDetailsPage(),
arguments: {
'data': user,
});
},
child: Padding(
padding: const EdgeInsets.all(3),
child: Container(
decoration: BoxDecoration(
border: Border.all(width: 2)),
child: ListTile(
title: Row(
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
Text(
'Name : ${user['first_name']} ${user['last_name']}',
style: AppStyle.title,
),
Text(
'Rating : ${user['ratingPassenger']}',
style: AppStyle.title,
),
],
),
subtitle: Row(
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
Text(
'Count Trip : ${user['countPassengerRide']}',
style: AppStyle.title,
),
Text(
'Count Driver Rate : ${user['countDriverRate']}',
style: AppStyle.title,
),
],
),
),
),
),
);
},
),
),
],
),
],
))
],
);
}
Container passengerAdmin(PassengerAdminController passengerAdminController,
String title, String jsonField) {
return Container(
height: Get.height * .1,
decoration: BoxDecoration(border: Border.all(width: 2)),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {},
child: Column(
children: [
Text(
title.tr,
style: AppStyle.title,
),
Text(
passengerAdminController.passengersData['message'][0][jsonField]
.toString(),
style: AppStyle.title,
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,167 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/admin/passenger_admin_controller.dart';
import '../../../controller/firebase/firbase_messge.dart';
import '../../widgets/elevated_btn.dart';
import '../../widgets/my_scafold.dart';
import '../../widgets/my_textField.dart';
class PassengerDetailsPage extends StatelessWidget {
const PassengerDetailsPage({super.key});
@override
Widget build(BuildContext context) {
final arguments = Get.arguments;
final Map<String, dynamic> data = arguments['data'];
var key = Get.find<PassengerAdminController>().formPrizeKey;
var titleNotify = Get.find<PassengerAdminController>().titleNotify;
var bodyNotify = Get.find<PassengerAdminController>().bodyNotify;
return MyScafolld(
title: data['first_name'],
body: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Email is ${data['email']}',
style: AppStyle.title,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Phone is ${data['phone']}',
style: AppStyle.title,
),
Text(
'gender is ${data['gender']}',
style: AppStyle.title,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'status is ${data['status']}',
style: AppStyle.title,
),
Text(
'birthdate is ${data['birthdate']}',
style: AppStyle.title,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'site is ${data['site']}',
style: AppStyle.title,
),
Text(
'sosPhone is ${data['sosPhone']}',
style: AppStyle.title,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Count Feedback is ${data['countFeedback']}',
style: AppStyle.title,
),
Text(
'Count Driver Rate is ${data['countDriverRate']}',
style: AppStyle.title,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Count Cancel is ${data['countPassengerCancel']}',
style: AppStyle.title,
),
Text(
'Count Ride is ${data['countPassengerRide']}',
style: AppStyle.title,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Rating Captain Avarage is ${data['passengerAverageRating']}',
style: AppStyle.title,
),
Text(
'Rating is ${data['ratingPassenger']}',
style: AppStyle.title,
),
],
),
Container(
decoration: BoxDecoration(
border: Border.all(width: 3, color: AppColor.yellowColor)),
child: TextButton(
onPressed: () async {
Get.defaultDialog(
title: 'Send Notification'.tr,
titleStyle: AppStyle.title,
content: Form(
key: key,
child: Column(
children: [
MyTextForm(
controller: titleNotify,
label: 'title'.tr,
hint: 'title notificaton'.tr,
type: TextInputType.name),
const SizedBox(
height: 10,
),
MyTextForm(
controller: bodyNotify,
label: 'body'.tr,
hint: 'body notificaton'.tr,
type: TextInputType.name)
],
),
),
confirm: MyElevatedButton(
title: 'Send',
onPressed: () {
if (key.currentState!.validate()) {
FirebaseMessagesController()
.sendNotificationToAnyWithoutData(
titleNotify.text,
bodyNotify.text,
data['passengerToken'],
);
Get.back();
}
}));
},
child: Text(
"Send Notificaion to Passenger ".tr,
style: AppStyle.title,
),
),
)
],
),
)
],
isleading: true,
);
}
}

View File

@@ -0,0 +1,236 @@
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/admin/ride_admin_controller.dart';
import '../../widgets/my_scafold.dart';
import '../../widgets/mycircular.dart';
class Rides extends StatelessWidget {
Rides({super.key});
RideAdminController rideAdminController = Get.put(RideAdminController());
@override
Widget build(BuildContext context) {
return MyScafolld(title: 'Rides'.tr, isleading: true, body: [
GetBuilder<RideAdminController>(
builder: (rideAdminController) => rideAdminController.isLoading
? const Center(child: MyCircularProgressIndicator())
: Column(
children: [
SizedBox(
height: Get.height * .4,
child: LineChart(
duration: const Duration(milliseconds: 150),
curve: Curves.ease,
LineChartData(
lineBarsData: [
LineChartBarData(
spots: rideAdminController.chartData,
isCurved: true,
color: Colors.deepPurpleAccent, // Custom color
barWidth: 3, // Thinner line
dotData: const FlDotData(
show: true), // Show dots on each point
belowBarData: BarAreaData(
// Add gradient fill below the line
show: true,
color: AppColor.deepPurpleAccent,
),
isStrokeJoinRound: true,
shadow: const BoxShadow(
color: AppColor.yellowColor,
blurRadius: 4,
offset: Offset(2, 2),
),
),
],
showingTooltipIndicators: const [],
titlesData: FlTitlesData(
show: true,
topTitles: AxisTitles(
axisNameWidget: Text(
'Days',
style: AppStyle.title,
),
axisNameSize: 30,
sideTitles: const SideTitles(
reservedSize: 30, showTitles: true)),
bottomTitles: AxisTitles(
axisNameWidget: Text(
'Total Trips on month'.tr,
style: AppStyle.title,
),
axisNameSize: 30,
sideTitles: const SideTitles(
reservedSize: 30, showTitles: true)),
leftTitles: AxisTitles(
axisNameWidget: Text(
'Counts of Trips on month'.tr,
style: AppStyle.title,
),
axisNameSize: 30,
sideTitles: const SideTitles(
reservedSize: 30, showTitles: true)),
),
gridData: const FlGridData(
show: true,
),
borderData: FlBorderData(
show: true,
border: const Border(
bottom: BorderSide(color: AppColor.accentColor),
left: BorderSide(color: AppColor.accentColor),
),
),
),
),
),
// SizedBox(
// height: Get.height * .4,
// child: PieChart(
// PieChartData(
// sectionsSpace: 4, // Adjust spacing between sections
// centerSpaceRadius:
// 40, // Adjust radius of center space
// sections: [
// for (final rideData in rideAdminController.rideData)
// PieChartSectionData(
// value: rideData.ridesCount.toDouble(),
// title: '${rideData.day}', showTitle: true,
// titleStyle:
// AppStyle.subtitle, // Display day as title
// radius: 60, // Adjust radius of each section
// color:
// AppColor.deepPurpleAccent, // Custom color
// ),
// ],
// ),
// ),
// ),
// SizedBox(
// // height: 400,
// child: SfCartesianChart(
// legend: const Legend(
// isVisible: true,
// position: LegendPosition.bottom,
// overflowMode: LegendItemOverflowMode.wrap,
// textStyle: TextStyle(
// color: Colors.white,
// fontSize: 12,
// fontWeight: FontWeight.bold,
// ),
// ),
// borderWidth: 2,
// borderColor: AppColor.blueColor,
// plotAreaBorderColor: AppColor.deepPurpleAccent,
// enableAxisAnimation: true,
// primaryXAxis: CategoryAxis(
// borderColor: AppColor.accentColor, borderWidth: 2,
// title: AxisTitle(
// text: 'Total Trips on month'.tr,
// textStyle: AppStyle.title,
// ),
// // labelRotation: 45,
// majorGridLines: const MajorGridLines(width: 0),
// ),
// primaryYAxis: const NumericAxis(isVisible: false),
// series: <LineSeries<ChartDataS, String>>[
// LineSeries<ChartDataS, String>(
// dataSource: rideAdminController.chartDatasync,
// xValueMapper: (ChartDataS data, _) => '${data.day}',
// yValueMapper: (ChartDataS data, _) =>
// data.ridesCount,
// dataLabelSettings:
// const DataLabelSettings(isVisible: true),
// ),
// ],
// ),
// ),
const SizedBox(
height: 20,
),
Card(
elevation: 4,
color: AppColor.deepPurpleAccent,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Total Trips on this Month is ${rideAdminController.jsonResponse['message'][0]['current_month_rides_count']}',
style: AppStyle.title,
),
),
),
const SizedBox(
height: 20,
),
Card(
elevation: 4,
color: AppColor.yellowColor,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
'Driver Average Duration: ${rideAdminController.ridesDetails[0]['driver_avg_duration']}',
style: AppStyle.subtitle,
),
Text(
'Number of Drivers: ${rideAdminController.ridesDetails[0]['num_Driver']}',
style: AppStyle.subtitle,
),
Text(
'Total Rides: ${rideAdminController.ridesDetails[0]['total_rides']}',
style: AppStyle.subtitle,
),
Text(
'Ongoing Rides: ${rideAdminController.ridesDetails[0]['ongoing_rides']}',
style: AppStyle.subtitle,
),
Text(
'Completed Rides: ${rideAdminController.ridesDetails[0]['completed_rides']}',
style: AppStyle.subtitle,
),
Text(
'Cancelled Rides: ${rideAdminController.ridesDetails[0]['cancelled_rides']}',
style: AppStyle.subtitle,
),
Text(
'Longest Duration: ${rideAdminController.ridesDetails[0]['longest_duration']}',
style: AppStyle.subtitle,
),
Text(
'Total Distance: ${rideAdminController.ridesDetails[0]['total_distance']} km',
style: AppStyle.subtitle,
),
Text(
'Average Distance: ${rideAdminController.ridesDetails[0]['average_distance']} km',
style: AppStyle.subtitle,
),
Text(
'Longest Distance: ${rideAdminController.ridesDetails[0]['longest_distance']} km',
style: AppStyle.subtitle,
),
Text(
'Total Driver Earnings: \$${rideAdminController.ridesDetails[0]['total_driver_earnings']}',
style: AppStyle.subtitle,
),
Text(
'Total Company Earnings: \$${rideAdminController.ridesDetails[0]['total_company_earnings']}',
style: AppStyle.subtitle,
),
Text(
'Company Percentage: ${rideAdminController.ridesDetails[0]['companyPercent']} %',
style: AppStyle.subtitle,
),
],
),
),
)
],
))
]);
}
}

View File

@@ -0,0 +1,13 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../widgets/my_scafold.dart';
class StaticDash extends StatelessWidget {
const StaticDash({super.key});
@override
Widget build(BuildContext context) {
return MyScafolld(title: 'Static Dash'.tr, body: [], isleading: true);
}
}

View File

@@ -0,0 +1,83 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_admin1/constant/style.dart';
import 'package:sefer_admin1/views/widgets/elevated_btn.dart';
import 'package:sefer_admin1/views/widgets/mycircular.dart';
import '../../../controller/admin/wallet_admin_controller.dart';
import '../../widgets/my_scafold.dart';
class Wallet extends StatelessWidget {
Wallet({super.key});
WalletAdminController walletAdminController =
Get.put(WalletAdminController());
@override
Widget build(BuildContext context) {
return MyScafolld(
title: 'Wallet'.tr,
body: [
GetBuilder<WalletAdminController>(builder: (walletAdminController) {
return Center(
child: walletAdminController.isLoading
? const MyCircularProgressIndicator()
: Column(
children: [
MyElevatedButton(
title: 'Pay to them to banks'.tr,
onPressed: () async {
await walletAdminController.payToBankDriverAll();
}),
SizedBox(
height: Get.height * .8,
child: ListView.builder(
itemCount:
walletAdminController.driversWalletPoints.length,
itemBuilder: (BuildContext context, int index) {
var res = walletAdminController
.driversWalletPoints[index];
if (res != null && res['name_arabic'] != null) {
return Padding(
padding: const EdgeInsets.all(4.0),
child: Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
'driver name: ${res['name_arabic'].toString()}'),
Text(
'Amount: ${res['total_amount'].toString()}'),
],
),
),
),
);
} else {
return Container(); // Return an empty container if the data is null
}
},
),
)
],
),
);
})
],
isleading: true,
action: IconButton(
onPressed: () async {
walletAdminController.getWalletForEachDriverToPay();
},
icon: const Icon(
Icons.refresh,
color: Colors.black,
),
),
);
}
}

View File

@@ -0,0 +1,63 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../constant/colors.dart';
class MyCircleContainer extends StatelessWidget {
final Widget child;
final Color backgroundColor;
final Color borderColor;
MyCircleContainer({
Key? key,
required this.child,
this.backgroundColor = AppColor.secondaryColor,
this.borderColor = AppColor.accentColor,
}) : super(key: key);
final controller = Get.put(CircleController());
@override
Widget build(BuildContext context) {
return GetBuilder<CircleController>(
builder: ((controller) => GestureDetector(
onTap: () {
controller.changeColor();
},
child: AnimatedContainer(
onEnd: () {
controller.onEnd();
},
duration: const Duration(milliseconds: 300),
width: controller.size,
height: controller.size,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: controller.backgroundColor,
border: Border.all(
color: borderColor,
width: 1,
),
),
child: Center(child: child),
),
)));
}
}
class CircleController extends GetxController {
Color backgroundColor = AppColor.secondaryColor;
double size = 40;
void changeColor() {
backgroundColor = backgroundColor == AppColor.secondaryColor
? AppColor.accentColor
: AppColor.secondaryColor;
size = 60;
update();
}
void onEnd() {
size = 40;
update();
}
}

View File

@@ -0,0 +1,47 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../constant/colors.dart';
import '../../constant/style.dart';
class MyElevatedButton extends StatelessWidget {
final String title;
final VoidCallback onPressed;
final Color kolor;
final int vibrateDuration;
const MyElevatedButton({
Key? key,
required this.title,
required this.onPressed,
this.kolor = AppColor.primaryColor,
this.vibrateDuration = 100,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(kolor),
),
onPressed: () async {
// Handle haptic feedback for both iOS and Android
if (Platform.isIOS) {
HapticFeedback.selectionClick();
} else {
// Vibration.vibrate(duration: 100);
// Vibrate.vibrateWithPauses(pauses);
}
// Ensure the onPressed callback is called after haptic feedback
onPressed();
},
child: Text(
title,
textAlign: TextAlign.center,
style: AppStyle.title.copyWith(color: AppColor.secondaryColor),
),
);
}
}

View File

@@ -0,0 +1,66 @@
import 'package:flutter/material.dart';
import '../../constant/colors.dart';
import '../../constant/style.dart';
class IconWidgetMenu extends StatelessWidget {
const IconWidgetMenu({
Key? key,
required this.onpressed,
required this.icon,
required this.title,
}) : super(key: key);
final VoidCallback onpressed;
final IconData icon;
final String title;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onpressed,
child: Padding(
padding: const EdgeInsets.only(top: 25),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 50,
decoration: const BoxDecoration(
color: AppColor.secondaryColor,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: AppColor.secondaryColor,
offset: Offset(-2, -2),
blurRadius: 0,
spreadRadius: 0,
blurStyle: BlurStyle.outer,
),
BoxShadow(
color: AppColor.accentColor,
offset: Offset(3, 3),
blurRadius: 0,
spreadRadius: 0,
blurStyle: BlurStyle.outer,
),
],
),
child: Center(
child: Icon(
icon,
size: 30,
color: AppColor.primaryColor,
),
),
),
Text(
title,
style: AppStyle.subtitle,
)
],
),
),
);
}
}

View File

@@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../constant/colors.dart';
import '../../constant/style.dart';
class MyScafolld extends StatelessWidget {
const MyScafolld({
super.key,
required this.title,
required this.body,
this.action = const Icon(
Icons.clear,
color: AppColor.secondaryColor,
),
required this.isleading,
});
final String title;
final List<Widget> body;
final Widget action;
final bool isleading;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColor.secondaryColor,
appBar: AppBar(
backgroundColor: AppColor.secondaryColor,
elevation: 0,
leading: isleading
? IconButton(
onPressed: () {
Get.back();
},
icon: const Icon(
Icons.arrow_back_ios_new,
color: AppColor.primaryColor,
),
)
: const SizedBox(),
actions: [action],
title: Text(
title,
style: AppStyle.title.copyWith(fontSize: 30),
),
),
body: SafeArea(child: Stack(children: body)));
}
}

View File

@@ -0,0 +1,65 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import '../../constant/colors.dart';
class MyTextForm extends StatelessWidget {
const MyTextForm({
super.key,
required this.controller,
required this.label,
required this.hint,
required this.type,
});
final TextEditingController controller;
final String label, hint;
final TextInputType type;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: SizedBox(
width: Get.width * .8,
child: TextFormField(
keyboardType: type,
cursorColor: AppColor.accentColor,
controller: controller,
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: AppColor.primaryColor,
width: 2.0,
),
borderRadius: BorderRadius.circular(10),
),
focusColor: AppColor.accentColor,
fillColor: AppColor.accentColor,
border: const OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12))),
labelText: label.tr,
hintText: hint.tr,
),
validator: (value) {
if (value!.isEmpty) {
return 'Please enter $label.'.tr;
}
if (type == TextInputType.emailAddress) {
if (!value.contains('@')) {
return 'Please enter a valid email.'.tr;
}
} else if (type == TextInputType.phone) {
if (value.length != 10) {
return 'Please enter a valid phone number.'.tr;
}
}
return null;
},
),
),
);
}
}

View File

@@ -0,0 +1,37 @@
import 'package:flutter/material.dart';
class MyCircularProgressIndicator extends StatelessWidget {
final Color backgroundColor;
const MyCircularProgressIndicator({
super.key,
this.backgroundColor = Colors.transparent,
});
@override
Widget build(BuildContext context) {
return Center(
child: Container(
width: 110,
height: 110,
decoration: BoxDecoration(
color: backgroundColor,
shape: BoxShape.circle,
),
child: Stack(
children: [
const Center(child: CircularProgressIndicator()),
Column(
children: [
Align(
alignment: Alignment.center,
child: Image.asset('assets/images/logo.png'),
),
],
),
],
),
),
);
}
}