25-7-26-1
This commit is contained in:
85
lib/constant/api_key.dart
Normal file
85
lib/constant/api_key.dart
Normal file
@@ -0,0 +1,85 @@
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:secure_string_operations/secure_string_operations.dart';
|
||||
|
||||
import '../env/env.dart';
|
||||
import 'char_map.dart';
|
||||
|
||||
class AK {
|
||||
static final String publishableKey =
|
||||
X.r(X.r(X.r(Env.stripePublishableKe, cn), cC), cs);
|
||||
static final String sss_pass = X.r(X.r(X.r(Env.sss_pass, cn), cC), cs);
|
||||
static final String allowed = Env.allowed;
|
||||
static final String passnpassenger = X
|
||||
.r(X.r(X.r(Env.passnpassenger, cn), cC), cs)
|
||||
.toString()
|
||||
.split(Env.addd)[0];
|
||||
static final String newId = Env.newId;
|
||||
static final String sss_encryptionSalt =
|
||||
X.r(X.r(X.r(Env.sss_encryptionSalt, cn), cC), cs);
|
||||
static final String secretKey = X.r(X.r(X.r(Env.secretKey, cn), cC), cs);
|
||||
static final String basicAuthCredentials =
|
||||
X.r(X.r(X.r(Env.basicAuthCredentials, cn), cC), cs);
|
||||
static final String accountSIDTwillo =
|
||||
X.r(X.r(X.r(Env.accountSIDTwillo, cn), cC), cs);
|
||||
static final String serverAPI = X.r(X.r(X.r(Env.serverAPI, cn), cC), cs);
|
||||
static final String mapAPIKEY = Env.mapAPIKEY;
|
||||
static final String mapAPIKEYIOS = Env.mapAPIKEYIOS;
|
||||
static final String twilloRecoveryCode =
|
||||
X.r(X.r(X.r(Env.twilloRecoveryCode, cn), cC), cs);
|
||||
static final String authTokenTwillo =
|
||||
X.r(X.r(X.r(Env.authTokenTwillo, cn), cC), cs);
|
||||
static final String chatGPTkey = X.r(X.r(X.r(Env.chatGPTkey, cn), cC), cs);
|
||||
static final String transactionCloude =
|
||||
X.r(X.r(X.r(Env.transactionCloude, cn), cC), cs);
|
||||
static final String visionApi = X.r(X.r(X.r(Env.visionApi, cn), cC), cs);
|
||||
static final String chatGPTkeySefer =
|
||||
X.r(X.r(X.r(Env.chatGPTkeySefer, cn), cC), cs);
|
||||
static final String chatGPTkeySeferNew =
|
||||
X.r(X.r(X.r(Env.chatGPTkeySeferNew, cn), cC), cs);
|
||||
static final String serverPHP = Env.serverPHP;
|
||||
static final String llamaKey = X.r(X.r(X.r(Env.llamaKey, cn), cC), cs);
|
||||
static final String cohere = X.r(X.r(X.r(Env.cohere, cn), cC), cs);
|
||||
static final String claudeAiAPI = X.r(X.r(X.r(Env.claudeAiAPI, cn), cC), cs);
|
||||
static final String payPalClientId =
|
||||
X.r(X.r(X.r(Env.payPalClientId, cn), cC), cs);
|
||||
static final String payPalSecret =
|
||||
X.r(X.r(X.r(Env.payPalSecret, cn), cC), cs);
|
||||
static final String geminiApi = X.r(X.r(X.r(Env.geminiApi, cn), cC), cs);
|
||||
static final String agoraAppId = X.r(X.r(X.r(Env.agoraAppId, cn), cC), cs);
|
||||
static final String agoraAppCertificate =
|
||||
X.r(X.r(X.r(Env.agoraAppCertificate, cn), cC), cs);
|
||||
static final String payPalClientIdLive =
|
||||
X.r(X.r(X.r(Env.payPalClientIdLive, cn), cC), cs);
|
||||
static final String payPalSecretLive =
|
||||
X.r(X.r(X.r(Env.payPalSecretLive, cn), cC), cs);
|
||||
static final String integrationIdPayMob =
|
||||
X.r(X.r(X.r(Env.integrationIdPayMob, cn), cC), cs);
|
||||
static final String passwordPayMob =
|
||||
X.r(X.r(X.r(Env.passwordPayMob, cn), cC), cs);
|
||||
static final String usernamePayMob =
|
||||
X.r(X.r(X.r(Env.usernamePayMob, cn), cC), cs);
|
||||
static final String payMobApikey =
|
||||
X.r(X.r(X.r(Env.payMobApikey, cn), cC), cs);
|
||||
static final String integrationIdPayMobWallet =
|
||||
X.r(X.r(X.r(Env.integrationIdPayMobWallet, cn), cC), cs);
|
||||
static final String apiKeyHere = Env.apiKeyHere;
|
||||
static final String smsPasswordEgypt =
|
||||
X.r(X.r(X.r(Env.smsPasswordEgypt, cn), cC), cs);
|
||||
static final String ocpApimSubscriptionKey = Env.ocpApimSubscriptionKey;
|
||||
static final String chatGPTkeySeferNew4 =
|
||||
X.r(X.r(X.r(Env.chatGPTkeySeferNew4, cn), cC), cs);
|
||||
static final String anthropicAIkeySeferNew =
|
||||
X.r(X.r(X.r(Env.anthropicAIkeySeferNew, cn), cC), cs);
|
||||
static final String llama3Key = X.r(X.r(X.r(Env.llama3Key, cn), cC), cs);
|
||||
static final String payMobOutClientSecrret =
|
||||
X.r(X.r(X.r(Env.payMobOutClientSecrret, cn), cC), cs);
|
||||
static final String payMobOutClient_id =
|
||||
X.r(X.r(X.r(Env.payMobOutClient_id, cn), cC), cs);
|
||||
static final String payMobOutPassword =
|
||||
X.r(X.r(X.r(Env.payMobOutPassword, cn), cC), cs);
|
||||
static final String payMobOutUserName =
|
||||
X.r(X.r(X.r(Env.payMobOutUserName, cn), cC), cs);
|
||||
|
||||
///////////
|
||||
static final String keyOfApp = X.r(X.r(X.r(Env.keyOfApp, cn), cC), cs);
|
||||
}
|
||||
105
lib/constant/box_name.dart
Normal file
105
lib/constant/box_name.dart
Normal file
@@ -0,0 +1,105 @@
|
||||
class BoxName {
|
||||
static const String driverID = "driverID";
|
||||
static const String countryCode = "countryCode";
|
||||
static const String googlaMapApp = "googlaMapApp";
|
||||
|
||||
static const String tokenParent = "tokenParent";
|
||||
static const String lang = "lang";
|
||||
static const String serverChosen = "serverChosen";
|
||||
static const String gender = "gender";
|
||||
static const String jwt = "jwt";
|
||||
static const String lastName = "lastName";
|
||||
static const String fingerPrint = "fingerPrint";
|
||||
static const String payMobApikey = "payMobApikey";
|
||||
static const String refreshToken = "refreshToken";
|
||||
static const String serverLocations = "serverLocations";
|
||||
static const String carType = "carType";
|
||||
static const String carPlate = "carPlate";
|
||||
static const String basicLink = "basicLink";
|
||||
static const String packagInfo = "packagInfo";
|
||||
static const String paymentLink = "paymentLink";
|
||||
static const String locationName = "locationName";
|
||||
static const String isVerified = 'isVerified';
|
||||
static const String isFirstTime = 'isFirstTime';
|
||||
static const String firstTimeLoadKey = 'firstTimeLoadKey';
|
||||
static const String isSavedPhones = 'isSavedPhones';
|
||||
static const String statusDriverLocation = "statusDriverLocation";
|
||||
static const String isTest = "isTest";
|
||||
static const String hmac = "hmac";
|
||||
static const String password = "password";
|
||||
static const String validity = "validity";
|
||||
static const String promo = "promo";
|
||||
static const String discount = "discount";
|
||||
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 placesDestination = 'placesDestination';
|
||||
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 package = "package";
|
||||
static const String isInstall = "isInstall";
|
||||
static const String isGiftToken = "isGiftToken";
|
||||
static const String inviteCode = "inviteCode";
|
||||
static const String phoneWallet = "phoneWallet";
|
||||
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 locationPermission = "locationPermission";
|
||||
static const String nameDriver = "nameDriver";
|
||||
static const String driverPhotoUrl = "driverPhotoUrl";
|
||||
static const String passengerPhotoUrl = "passengerPhotoUrl";
|
||||
static const String email = "email";
|
||||
static const String emailDriver = "emailDriver";
|
||||
static const String tokens = "tokens";
|
||||
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 keyOfApp = 'keyOfApp';
|
||||
static const String initializationVector = 'initializationVector';
|
||||
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 isvibrate = "isvibrate";
|
||||
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';
|
||||
static const String parentTripSelected = 'parentTripSelected';
|
||||
}
|
||||
75
lib/constant/char_map.dart
Normal file
75
lib/constant/char_map.dart
Normal file
@@ -0,0 +1,75 @@
|
||||
import '../env/env.dart';
|
||||
|
||||
Map<String, String> cs = {
|
||||
"a": Env.a,
|
||||
"b": Env.b,
|
||||
"c": Env.c,
|
||||
"d": Env.d,
|
||||
"e": Env.e,
|
||||
"f": Env.f,
|
||||
"g": Env.g,
|
||||
"h": Env.h,
|
||||
"i": Env.i,
|
||||
"j": Env.j,
|
||||
"k": Env.k,
|
||||
"l": Env.l,
|
||||
"m": Env.m,
|
||||
"n": Env.n,
|
||||
"o": Env.o,
|
||||
"p": Env.p,
|
||||
"q": Env.q,
|
||||
"r": Env.r,
|
||||
"s": Env.s,
|
||||
"t": Env.t,
|
||||
"u": Env.u,
|
||||
"v": Env.v,
|
||||
"w": Env.w,
|
||||
"x": Env.x,
|
||||
"y": Env.y,
|
||||
"z": Env.z,
|
||||
};
|
||||
Map<String, String> cC = {
|
||||
"A": Env.A,
|
||||
"B": Env.B,
|
||||
"C": Env.C,
|
||||
"D": Env.D,
|
||||
"E": Env.E,
|
||||
"F": Env.F,
|
||||
"G": Env.G,
|
||||
"H": Env.H,
|
||||
"I": Env.I,
|
||||
"J": Env.J,
|
||||
"K": Env.K,
|
||||
"L": Env.L,
|
||||
"M": Env.M,
|
||||
"N": Env.N,
|
||||
"O": Env.O,
|
||||
"P": Env.P,
|
||||
"Q": Env.Q,
|
||||
"R": Env.R,
|
||||
"S": Env.S,
|
||||
"T": Env.T,
|
||||
"U": Env.U,
|
||||
"V": Env.V,
|
||||
"W": Env.W,
|
||||
"X": Env.X,
|
||||
"Y": Env.Y,
|
||||
"Z": Env.Z
|
||||
};
|
||||
|
||||
//
|
||||
|
||||
//
|
||||
|
||||
Map<String, String> cn = {
|
||||
"0": "3",
|
||||
"1": "7",
|
||||
"2": "1",
|
||||
"3": "9",
|
||||
"4": "0",
|
||||
"5": "5",
|
||||
"6": "2",
|
||||
"7": "6",
|
||||
"8": "4",
|
||||
"9": "8"
|
||||
};
|
||||
61
lib/constant/colors.dart
Normal file
61
lib/constant/colors.dart
Normal file
@@ -0,0 +1,61 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// A class that holds the color palette for the 'Intaleq' app.
|
||||
/// The palette is professionally designed to be modern, cohesive, and culturally
|
||||
/// relevant, inspired by the Syrian flag and the app's brand identity.
|
||||
class AppColor {
|
||||
// --- Core Brand Colors (Inspired by the Syrian Flag) ---
|
||||
|
||||
/// **Primary Color:** A strong, modern green representing growth, safety, and movement.
|
||||
/// Ideal for app bars, primary buttons, and major UI elements.
|
||||
static const Color primaryColor = Color(0xFF108942);
|
||||
|
||||
/// **Text/Write Color:** A very dark, near-black color for main text.
|
||||
/// It's softer on the eyes than pure black, improving readability.
|
||||
/// The variable name `writeColor` is kept as requested.
|
||||
static const Color writeColor = Color(0xFF1A1A1A);
|
||||
|
||||
/// **Secondary Color:** Pure white, used for backgrounds to create a clean
|
||||
/// and spacious look, ensuring content stands out.
|
||||
static const Color secondaryColor = Colors.white;
|
||||
|
||||
/// **Accent Color:** A vibrant, energetic red from the Syrian flag.
|
||||
/// Perfect for calls-to-action, highlights, icons, and notifications.
|
||||
static const Color accentColor = Color.fromARGB(255, 148, 140, 141);
|
||||
|
||||
// --- Neutral & Status Colors ---
|
||||
|
||||
/// **Grey Color:** A neutral grey for secondary text, borders, dividers,
|
||||
/// and disabled states.
|
||||
static const Color greyColor = Color(0xFF8E8E93);
|
||||
|
||||
/// **Red Color (Error):** A clear, attention-grabbing red for error messages and alerts.
|
||||
static const Color redColor = Color(0xFFD32F2F);
|
||||
|
||||
/// **Green Color (Success):** A positive green for success messages and confirmations.
|
||||
static const Color greenColor = Color(0xFF388E3C);
|
||||
|
||||
/// **Blue Color (Info):** A standard blue for informational text, links, or icons.
|
||||
static const Color blueColor = Color(0xFF108942);
|
||||
|
||||
/// **Yellow Color (Warning):** A warm yellow for warning messages or important highlights.
|
||||
static const Color yellowColor = Color(0xFFFFA000);
|
||||
|
||||
// --- Tier & Social Colors ---
|
||||
|
||||
/// **Gold Tier:** A bright gold for premium features, user ranks, or rewards.
|
||||
static const Color gold = Color(0xFFFFD700);
|
||||
|
||||
/// **Bronze Tiers:** Classic bronze colors for other user tiers or levels.
|
||||
static const Color bronze = Color(0xFFCD7F32);
|
||||
static const Color goldenBronze = Color(0xFFB87333); // Kept from original
|
||||
|
||||
/// **Twitter/X Color:** The official brand color for social login buttons.
|
||||
|
||||
// --- Utility Colors ---
|
||||
|
||||
/// **Accent Tint:** A transparent version of the red accent color.
|
||||
/// Useful for subtle backgrounds on selected items or highlighted areas.
|
||||
/// Replaces the old `deepPurpleAccent` to match the new brand palette.
|
||||
static Color deepPurpleAccent = const Color(0xFFCE1126).withOpacity(0.1);
|
||||
}
|
||||
144
lib/constant/credential.dart
Normal file
144
lib/constant/credential.dart
Normal 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;
|
||||
}
|
||||
}
|
||||
4767
lib/constant/info.dart
Normal file
4767
lib/constant/info.dart
Normal file
File diff suppressed because one or more lines are too long
351
lib/constant/links.dart
Normal file
351
lib/constant/links.dart
Normal file
@@ -0,0 +1,351 @@
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/env/env.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
|
||||
class AppLink {
|
||||
// static final String seferPaymentServer0 = Env.seferPaymentServer;
|
||||
// static final String seferPaymentServer = '${Env.seferPaymentServer}/ride';
|
||||
// static final String seferAlexandriaServer = Env.seferAlexandriaServer;
|
||||
// static final String seferCairoServer = Env.seferCairoServer;
|
||||
static String serverPHP = box.read('serverPHP');
|
||||
// static String seferCairoServer =
|
||||
// box.read(BoxName.locationName)[0]['server_link'];
|
||||
// static String seferGizaServer = box.read(BoxName.serverChosen);
|
||||
// static String seferAlexandriaServer = box.read(BoxName.serverChosen);
|
||||
// static String seferPaymentServer = box.read('seferPaymentServer');
|
||||
|
||||
static String seferPaymentServer =
|
||||
// box.read(BoxName.paymentLink);
|
||||
'https://walletintaleq.intaleq.xyz/v1/main';
|
||||
static String seferPaymentServer0 = box.read('seferPaymentServer');
|
||||
// static const String seferGizaServer = 'https://gizasefer.online/sefer';
|
||||
// static final String seferGizaServer = Env.seferGizaServer;
|
||||
// static final String endPoint = box.read(BoxName.serverChosen);
|
||||
// static final String server = endPoint;
|
||||
// static final String server = Env.serverPHP;
|
||||
|
||||
static final String endPoint = 'https://intaleq.xyz/intaleq';
|
||||
// box.read(BoxName.serverChosen) ?? box.read(BoxName.basicLink);
|
||||
// 'https://server.sefer.click/sefer.click/sefer';
|
||||
static final String server = endPoint;
|
||||
static String IntaleqCairoServer = endPoint;
|
||||
static String IntaleqGizaServer = box.read('Giza');
|
||||
static String IntaleqAlexandriaServer = box.read('Alexandria');
|
||||
|
||||
static String googleMapsLink = 'https://maps.googleapis.com/maps/api/';
|
||||
static String searcMaps =
|
||||
'https://autosuggest.search.hereapi.com/v1/autosuggest';
|
||||
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 getTokenParent = "$server/ride/firebase/getTokenParent.php";
|
||||
static String addTokens = "$server/ride/firebase/add.php";
|
||||
static String addFingerPrint = "$seferPaymentServer/ride/firebase/add.php";
|
||||
static String addTokensDriver = "$server/ride/firebase/addDriver.php";
|
||||
static String packageInfo = "$server/auth/packageInfo.php";
|
||||
|
||||
//=======================Wallet===================
|
||||
static String wallet = '$seferPaymentServer/ride/passengerWallet';
|
||||
static String walletDriver = '$seferPaymentServer/ride/driverWallet';
|
||||
static String getAllPassengerTransaction =
|
||||
"$wallet/getAllPassengerTransaction.php";
|
||||
static String getWalletByPassenger = "$wallet/getWalletByPassenger.php";
|
||||
static String getPassengersWallet = "$wallet/get.php";
|
||||
static String payWithPayMobWalletPasenger =
|
||||
'$seferPaymentServer/ride/payMob/wallet/payWithPayMob.php';
|
||||
static String payWithPayMobCardPassenger =
|
||||
'$seferPaymentServer/ride/payMob/payWithPayMob.php';
|
||||
static String payWithEcash = "$seferPaymentServer/ecash/payWithEcash.php";
|
||||
|
||||
static String paymetVerifyPassenger =
|
||||
"$seferPaymentServer/ride/payMob/paymet_verfy.php";
|
||||
static String getPassengerWalletArchive =
|
||||
"$wallet/getPassengerWalletArchive.php";
|
||||
|
||||
static String addDrivePayment = "$seferPaymentServer/ride/payment/add.php";
|
||||
static String addSeferWallet = "$seferPaymentServer/ride/seferWallet/add.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 getPromoFirst = "$promo/getPromoFirst.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";
|
||||
|
||||
//===============contact==========================
|
||||
static String savePhones = "$server/ride/egyptPhones/add.php";
|
||||
static String getPhones = "$server/ride/egyptPhones/get.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 = "$endPoint/ride/rides/get.php";
|
||||
static String getRideOrderID = "$endPoint/ride/rides/getRideOrderID.php";
|
||||
static String getRideStatus = "$endPoint/ride/rides/getRideStatus.php";
|
||||
static String getRideStatusBegin =
|
||||
"$endPoint/ride/rides/getRideStatusBegin.php";
|
||||
static String getRideStatusFromStartApp =
|
||||
"$ride/rides/getRideStatusFromStartApp.php";
|
||||
static String updateRides = "$server/ride/rides/update.php";
|
||||
static String updateStausFromSpeed =
|
||||
"$server/ride/rides/updateStausFromSpeed.php";
|
||||
static String deleteRides = "$server/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 = "$seferPaymentServer/ride/payment/add.php";
|
||||
static String addDriverPaymentPoints =
|
||||
"$seferPaymentServer/ride/driverPayment/add.php";
|
||||
static String addPaymentTokenPassenger =
|
||||
"$seferPaymentServer/ride/passengerWallet/addPaymentTokenPassenger.php";
|
||||
static String addPaymentTokenDriver =
|
||||
"$seferPaymentServer/ride/driverWallet/addPaymentToken.php";
|
||||
static String getDriverPaymentPoints =
|
||||
"$seferPaymentServer/ride/driverWallet/get.php";
|
||||
static String payWithEcashPassenger =
|
||||
"$seferPaymentServer/ride/ecash/passenger/payWithEcash.php";
|
||||
static String payWithMTNConfirm =
|
||||
"$seferPaymentServer/ride/mtn/passenger/mtn_confirm.php";
|
||||
static String payWithMTNStart =
|
||||
"$seferPaymentServer/ride/mtn/passenger/mtn_start.php";
|
||||
static String getDriverpaymentToday =
|
||||
"$seferPaymentServer/ride/payment/get.php";
|
||||
static String getCountRide =
|
||||
"$seferPaymentServer/ride/payment/getCountRide.php";
|
||||
static String getAllPaymentFromRide =
|
||||
"$seferPaymentServer/ride/payment/getAllPayment.php";
|
||||
static String getAllPaymentVisa =
|
||||
"$seferPaymentServer/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 =
|
||||
"$server/ride/notificationCaptain/addWaitingRide.php";
|
||||
static String updateWaitingTrip =
|
||||
"$server/ride/notificationCaptain/updateWaitingTrip.php";
|
||||
static String getRideWaiting =
|
||||
"$endPoint/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";
|
||||
//-----------------invitor------------------
|
||||
|
||||
static String addInviteDriver = "$server/ride/invitor/add.php";
|
||||
static String addInvitationPassenger =
|
||||
"$server/ride/invitor/addInvitationPassenger.php";
|
||||
static String getInviteDriver = "$server/ride/invitor/get.php";
|
||||
static String getDriverInvitationToPassengers =
|
||||
"$server/ride/invitor/getDriverInvitationToPassengers.php";
|
||||
static String updateInviteDriver = "$server/ride/invitor/update.php";
|
||||
static String updatePassengerGift =
|
||||
"$server/ride/invitor/updatePassengerGift.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";
|
||||
static String getPlacesSyria = "$ride/places_syria/get.php";
|
||||
|
||||
//-----------------Feed Back------------------
|
||||
static String addFeedBack = "$ride/feedBack/add.php";
|
||||
static String uploadAudio = "$ride/feedBack/upload_audio.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 =
|
||||
"${box.read(BoxName.serverChosen)}/ride/RegisrationCar/get.php";
|
||||
static String selectDriverAndCarForMishwariTrip =
|
||||
"$ride/RegisrationCar/selectDriverAndCarForMishwariTrip.php";
|
||||
static String updateRegisrationCar = "$ride/RegisrationCar/update.php";
|
||||
|
||||
//-----------------mishwari------------------
|
||||
|
||||
static String addMishwari = "$ride/mishwari/add.php";
|
||||
static String cancelMishwari = "$ride/mishwari/cancel.php";
|
||||
static String getMishwari = "$ride/mishwari/get.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 savePlacesServer = "$ride/places/add.php";
|
||||
static String getapiKey = "$ride/apiKey/get.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 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 = '${box.read(BoxName.serverChosen)}/ride/location';
|
||||
static String getCarsLocationByPassenger = "$location/get.php";
|
||||
|
||||
static String getLocationAreaLinks =
|
||||
'$ride/location/get_location_area_links.php';
|
||||
static String addpassengerLocation = "$location/addpassengerLocation.php";
|
||||
static String getCarsLocationByPassengerSpeed = "$location/getSpeed.php";
|
||||
static String getCarsLocationByPassengerComfort = "$location/getComfort.php";
|
||||
static String getCarsLocationByPassengerBalash = "$location/getBalash.php";
|
||||
static String getCarsLocationByPassengerPinkBike =
|
||||
"$location/getPinkBike.php";
|
||||
static String getCarsLocationByPassengerDelivery =
|
||||
"$location/getDelivery.php";
|
||||
static String getLocationParents = "$location/getLocationParents.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 loginJwtRider = "$server/login.php";
|
||||
static String loginJwtWalletRider = "$seferPaymentServer/loginWallet.php";
|
||||
static String loginFirstTime = "$server/loginFirstTime.php";
|
||||
static String getTesterApp = "$auth/Tester/getTesterApp.php";
|
||||
static String updateTesterApp = "$auth/Tester/updateTesterApp.php";
|
||||
static String signUp = "$auth/signup.php";
|
||||
static String sendVerifyEmail = "$auth/sendVerifyEmail.php";
|
||||
static String loginFromGooglePassenger = "$auth/loginFromGooglePassenger.php";
|
||||
static String checkPhoneNumberISVerfiedPassenger =
|
||||
"$auth/checkPhoneNumberISVerfiedPassenger.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 loginFromGoogleCaptin = "$authCaptin/loginFromGoogle.php";
|
||||
static String signUpCaptin = "$authCaptin/register.php";
|
||||
static String sendVerifyEmailCaptin = "$authCaptin/sendVerifyEmail.php";
|
||||
static String sendVerifyOtpMessage = "$server/auth/otpmessage.php";
|
||||
static String verifyOtpMessage = "$server/auth/verifyOtpMessage.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";
|
||||
static String updatePassengersInvitation =
|
||||
"$server/ride/invitor/updatePassengersInvitation.php";
|
||||
static String updateDriverInvitationDirectly =
|
||||
"$server/ride/invitor/updateDriverInvitationDirectly.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 getAdminUser = "$server/Admin/adminUser/get.php";
|
||||
static String addError = "$server/Admin/errorApp.php";
|
||||
static String getCaptainDetailsByEmailOrIDOrPhone =
|
||||
"$server/Admin/AdminCaptain/getCaptainDetailsByEmailOrIDOrPhone.php";
|
||||
static String getCaptainDetails = "$server/Admin/AdminCaptain/get.php";
|
||||
static String getRidesPerMonth =
|
||||
"$server/Admin/AdminRide/getRidesPerMonth.php";
|
||||
static String getRidesDetails = "$server/Admin/AdminRide/get.php";
|
||||
|
||||
//////////Sms egypt///////////
|
||||
static String sendSms = "https://sms.kazumi.me/api/sms/send-sms";
|
||||
static String sendSmsFromPHP =
|
||||
'$server/auth/sms_new_backend/sendOtpPassenger.php';
|
||||
static String verifyOtpPassenger =
|
||||
'$server/auth/passengerOTP/verifyOtpPassenger.php';
|
||||
static String senddlr = "https://sms.kazumi.me/api/sms/send-dlr";
|
||||
static String sendvalidity = "https://sms.kazumi.me/api/sms/send-validity";
|
||||
static String sendmany = "https://sms.kazumi.me/api/sms/send-many";
|
||||
static String checkCredit = "https://sms.kazumi.me/api/sms/check-credit";
|
||||
static String getSender = "$server/auth/sms/getSender.php";
|
||||
static String checkStatus = "https://sms.kazumi.me/api/sms/check-status";
|
||||
static String updatePhoneInvalidSMSPassenger =
|
||||
"$server/auth/sms/updatePhoneInvalidSMSPassenger.php";
|
||||
}
|
||||
22
lib/constant/notification.dart
Normal file
22
lib/constant/notification.dart
Normal file
@@ -0,0 +1,22 @@
|
||||
List<String> messages = [
|
||||
"🚗 عروض مميزة: استمتع بأقل الأسعار وأفضل العروض! افتح تطبيق انطلق الآن لتحصل على المزيد من الخيارات. 🌟",
|
||||
"💸 وفر الآن: وفر مع تطبيق انطلق! عروض مستمرة وخيارات متعددة تناسب احتياجاتك. 🔥",
|
||||
"🔒 أمان وراحة: مع تطبيق انطلق، احصل على أمان وراحة بأفضل الأسعار! 🚕",
|
||||
"💼 خيارات متنوعة: استفد من خيارات متنوعة وأسعار تنافسية على تطبيق انطلق، الأفضل دائماً. 🌐",
|
||||
"💵 توفير مضمون: حافظ على ميزانيتك وسافر بأمان مع تطبيق انطلق – العروض لا تتوقف! 🎉",
|
||||
"🌍 وجهات مميزة: أفضل وجهات الانطلق، بأقل الأسعار مع تطبيق انطلق – تابعنا الآن! 🛤️",
|
||||
"🛣️ سهولة وراحة: رحلاتك أصبحت أسهل وأرخص – سافر معنا وتمتع بأفضل التجارب. 🎊",
|
||||
"📲 حجز سهل: احجز رحلتك بسهولة وأمان مع انطلق – المزيد من الخصومات في انتظارك! 🎁",
|
||||
"👑 فئة مميزة: خليك من الفئة المميزة واستفد بأفضل الأسعار مع تطبيق انطلق. 💯",
|
||||
"💡 خيارات متعددة: نوفر لك خيارات متعددة وسعر مناسب – جرب تطبيق انطلق الآن! 🚖",
|
||||
"✨ عروض متجددة: العروض لا تتوقف على تطبيق انطلق – احجز رحلتك الآن وتمتع بالمزيد! 📅",
|
||||
"🚀 سهولة الوصول: الانطلق أصبح أسهل وأسرع مع تطبيق انطلق – كن مستعدًا لأفضل التجارب! 🌠",
|
||||
"🧳 راحة وأمان: تطبيق انطلق يقدم لك أمان وراحة بأقل الأسعار! 📉",
|
||||
"🔥 عروض فورية: احجز الآن واستمتع بعروض لا تُفوّت على تطبيق انطلق! 🚘",
|
||||
"🚖 أسعار تنافسية: اختر رحلتك الآن بأسعار تنافسية وتمتع بالراحة والأمان مع تطبيق انطلق. ✅",
|
||||
"💥 أسعار خاصة: أسعار خاصة بانتظارك على تطبيق انطلق! افتح التطبيق الآن واحجز رحلتك. 🌐",
|
||||
"🌟 راحة البال: انطلق بأمان وراحة مع تطبيق انطلق – استمتع بأفضل الأسعار. 💸",
|
||||
"📍 خصومات حصرية: استفد من الخصومات الحصرية والعروض المستمرة على تطبيق انطلق! 🛤️",
|
||||
"🛫 تجربة سهلة: رحلاتك أصبحت أفضل وأسهل مع تطبيق انطلق – افتح التطبيق واستمتع بالتجربة. ✨",
|
||||
"🔔 عروض لا مثيل لها: كن جاهزًا لعروض لا مثيل لها! تطبيق انطلق يقدم لك أفضل الخيارات بأقل الأسعار. 🎉",
|
||||
];
|
||||
198
lib/constant/sefer cairo server.php
Normal file
198
lib/constant/sefer cairo server.php
Normal file
@@ -0,0 +1,198 @@
|
||||
sefer cairo server
|
||||
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
{{ssl_certificate_key}}
|
||||
{{ssl_certificate}}
|
||||
server_name www.sefer.click;
|
||||
return 301 https://sefer.click$request_uri;
|
||||
}
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
{{ssl_certificate_key}}
|
||||
{{ssl_certificate}}
|
||||
server_name sefer.click www1.sefer.click;
|
||||
{{root}}
|
||||
{{nginx_access_log}}
|
||||
{{nginx_error_log}}
|
||||
# Set the maximum request body size
|
||||
client_max_body_size 10m;
|
||||
if ($scheme != "https") {
|
||||
rewrite ^ https://$host$uri permanent;
|
||||
}
|
||||
location ~ /.well-known {
|
||||
auth_basic off;
|
||||
allow all;
|
||||
}
|
||||
# Security headers
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline';" always;
|
||||
add_header Referrer-Policy "no-referrer-when-downgrade" always;
|
||||
add_header Permissions-Policy "geolocation=(), microphone=()" always;
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
|
||||
{{settings}}
|
||||
location / {
|
||||
{{varnish_proxy_pass}}
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Forwarded-Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_hide_header X-Varnish;
|
||||
proxy_redirect off;
|
||||
proxy_max_temp_file_size 0;
|
||||
proxy_connect_timeout 720;
|
||||
proxy_send_timeout 720;
|
||||
proxy_read_timeout 720;
|
||||
proxy_buffer_size 128k;
|
||||
proxy_buffers 4 256k;
|
||||
proxy_busy_buffers_size 256k;
|
||||
proxy_temp_file_write_size 256k;
|
||||
}
|
||||
location ~* ^.+\.(css|js|jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|woff2|eot|mp4|ogg|ogv|webm|webp|zip|swf|map|mjs)$ {
|
||||
add_header Access-Control-Allow-Origin "*";
|
||||
expires max;
|
||||
access_log off;
|
||||
}
|
||||
location ~ /\.(ht|svn|git) {
|
||||
deny all;
|
||||
}
|
||||
if (-f $request_filename) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
server {
|
||||
listen 8080;
|
||||
listen [::]:8080;
|
||||
server_name sefer.click www1.sefer.click;
|
||||
{{root}}
|
||||
try_files $uri $uri/ /index.php?$args;
|
||||
index index.php index.html;
|
||||
location ~ \.php$ {
|
||||
include fastcgi_params;
|
||||
fastcgi_intercept_errors on;
|
||||
fastcgi_index index.php;
|
||||
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
|
||||
try_files $uri =404;
|
||||
fastcgi_read_timeout 3600;
|
||||
fastcgi_send_timeout 3600;
|
||||
proxy_read_timeout 3600;
|
||||
proxy_send_timeout 3600;
|
||||
fastcgi_param HTTPS "on";
|
||||
fastcgi_param SERVER_PORT 443;
|
||||
fastcgi_pass 127.0.0.1:{{php_fpm_port}};
|
||||
fastcgi_param PHP_VALUE "{{php_settings}}";
|
||||
}
|
||||
if (-f $request_filename) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
wallet server
|
||||
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
{{ssl_certificate_key}}
|
||||
{{ssl_certificate}}
|
||||
server_name www.seferpw.shop;
|
||||
return 301 https://seferpw.shop$request_uri;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
{{ssl_certificate_key}}
|
||||
{{ssl_certificate}}
|
||||
server_name seferpw.shop www1.seferpw.shop 156.67.82.188;
|
||||
{{root}}
|
||||
{{nginx_access_log}}
|
||||
{{nginx_error_log}}
|
||||
# Set the maximum request body size
|
||||
client_max_body_size 10m;
|
||||
if ($scheme != "https") {
|
||||
rewrite ^ https://$host$uri permanent;
|
||||
}
|
||||
location ~ /.well-known {
|
||||
auth_basic off;
|
||||
allow all;
|
||||
}
|
||||
# Security headers
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline';" always;
|
||||
add_header Referrer-Policy "no-referrer-when-downgrade" always;
|
||||
add_header Permissions-Policy "geolocation=(), microphone=()" always;
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
|
||||
{{settings}}
|
||||
location / {
|
||||
{{varnish_proxy_pass}}
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Forwarded-Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_hide_header X-Varnish;
|
||||
proxy_redirect off;
|
||||
proxy_max_temp_file_size 0;
|
||||
proxy_connect_timeout 720;
|
||||
proxy_send_timeout 720;
|
||||
proxy_read_timeout 720;
|
||||
proxy_buffer_size 128k;
|
||||
proxy_buffers 4 256k;
|
||||
proxy_busy_buffers_size 256k;
|
||||
proxy_temp_file_write_size 256k;
|
||||
}
|
||||
location ~* ^.+\.(css|js|jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|woff2|eot|mp4|ogg|ogv|webm|webp|zip|swf|map|mjs)$ {
|
||||
add_header Access-Control-Allow-Origin "*";
|
||||
expires max;
|
||||
access_log off;
|
||||
}
|
||||
location ~ /\.(ht|svn|git) {
|
||||
deny all;
|
||||
}
|
||||
if (-f $request_filename) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
listen [::]:8080;
|
||||
server_name seferpw.shop www1.seferpw.shop 156.67.82.188;
|
||||
{{root}}
|
||||
try_files $uri $uri/ /index.php?$args;
|
||||
index index.php index.html;
|
||||
location ~ \.php$ {
|
||||
include fastcgi_params;
|
||||
fastcgi_intercept_errors on;
|
||||
fastcgi_index index.php;
|
||||
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
|
||||
try_files $uri =404;
|
||||
fastcgi_read_timeout 3600;
|
||||
fastcgi_send_timeout 3600;
|
||||
proxy_read_timeout 3600;
|
||||
proxy_send_timeout 3600;
|
||||
fastcgi_param HTTPS "on";
|
||||
fastcgi_param SERVER_PORT 443;
|
||||
fastcgi_pass 127.0.0.1:{{php_fpm_port}};
|
||||
fastcgi_param PHP_VALUE "{{php_settings}}";
|
||||
}
|
||||
if (-f $request_filename) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
70
lib/constant/style.dart
Normal file
70
lib/constant/style.dart
Normal file
@@ -0,0 +1,70 @@
|
||||
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: 36,
|
||||
color: AppColor.accentColor,
|
||||
fontFamily: box.read(BoxName.lang) == 'ar'
|
||||
// ?GoogleFonts.markaziText().fontFamily
|
||||
? GoogleFonts.markaziText().fontFamily
|
||||
: GoogleFonts.inter().fontFamily);
|
||||
static TextStyle headTitle2 = TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 24,
|
||||
color: AppColor.writeColor,
|
||||
fontFamily: box.read(BoxName.lang) == 'ar'
|
||||
? GoogleFonts.markaziText().fontFamily
|
||||
: GoogleFonts.inter().fontFamily);
|
||||
static TextStyle title = TextStyle(
|
||||
fontWeight: FontWeight.normal,
|
||||
fontSize: 16,
|
||||
color: AppColor.writeColor,
|
||||
fontFamily: box.read(BoxName.lang) == 'ar'
|
||||
? GoogleFonts.markaziText().fontFamily
|
||||
: GoogleFonts.inter().fontFamily);
|
||||
static TextStyle subtitle = TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 12,
|
||||
color: AppColor.writeColor,
|
||||
fontFamily: box.read(BoxName.lang) == 'ar'
|
||||
? GoogleFonts.markaziText().fontFamily
|
||||
: GoogleFonts.inter().fontFamily);
|
||||
static TextStyle number = const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 14,
|
||||
color: AppColor.writeColor,
|
||||
fontFamily: 'digit');
|
||||
|
||||
static BoxDecoration boxDecoration = 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),
|
||||
));
|
||||
static BoxDecoration boxDecoration1 = const BoxDecoration(
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Color.fromARGB(255, 237, 230, 230),
|
||||
blurRadius: 5,
|
||||
offset: Offset(2, 4)),
|
||||
BoxShadow(
|
||||
color: Color.fromARGB(255, 242, 237, 237),
|
||||
blurRadius: 5,
|
||||
offset: Offset(-2, -2))
|
||||
],
|
||||
color: AppColor.secondaryColor,
|
||||
borderRadius: BorderRadius.all(
|
||||
Radius.elliptical(15, 30),
|
||||
),
|
||||
);
|
||||
}
|
||||
19
lib/constant/table_names.dart
Normal file
19
lib/constant/table_names.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
import 'package:Intaleq/env/env.dart';
|
||||
|
||||
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";
|
||||
}
|
||||
|
||||
class Pasenger {
|
||||
static const String pasengerpas = 'MG6DEJZSczBT6Rx0jOlehQ==';
|
||||
static const String payMobApikey = 'payMobApikey';
|
||||
static const String initializationVector = 'initializationVector';
|
||||
static const String keyOfApp = 'keyOfApp';
|
||||
static const String FCM_PRIVATE_KEY_INTALEQ = 'FCM_PRIVATE_KEY_INTALEQ';
|
||||
}
|
||||
83
lib/constant/univeries_polygon.dart
Normal file
83
lib/constant/univeries_polygon.dart
Normal file
@@ -0,0 +1,83 @@
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
|
||||
class UniversitiesPolygons {
|
||||
// AUC polygon points
|
||||
static const List<List<LatLng>> universityPolygons = [
|
||||
// AUC Polygon
|
||||
[
|
||||
LatLng(30.013431, 31.502572),
|
||||
LatLng(30.018469, 31.497478),
|
||||
LatLng(30.023158, 31.495870),
|
||||
LatLng(30.025084, 31.496781),
|
||||
LatLng(30.018701, 31.511393),
|
||||
LatLng(30.015312, 31.508310),
|
||||
],
|
||||
// Example polygon for University 'German University in Cairo (GUC)'
|
||||
[
|
||||
LatLng(29.984554, 31.437829),
|
||||
LatLng(29.990363, 31.438390),
|
||||
LatLng(29.990560, 31.445643),
|
||||
LatLng(29.984436, 31.445825),
|
||||
],
|
||||
//Future University in Egypt (FUE)
|
||||
[
|
||||
LatLng(30.025794, 31.490946),
|
||||
LatLng(30.028341, 31.491014),
|
||||
LatLng(30.028341, 31.492586),
|
||||
LatLng(30.025844, 31.492491),
|
||||
],
|
||||
//'British University in Egypt (BUE)'
|
||||
[
|
||||
LatLng(30.117423, 31.605834),
|
||||
LatLng(30.118224, 31.605543),
|
||||
LatLng(30.118649, 31.607361),
|
||||
LatLng(30.118932, 31.608033),
|
||||
LatLng(30.119592, 31.612159),
|
||||
LatLng(30.119372, 31.612958),
|
||||
LatLng(30.120017, 31.617102),
|
||||
LatLng(30.119435, 31.617193),
|
||||
],
|
||||
//Misr International University (MIU)
|
||||
[
|
||||
LatLng(30.166498, 31.491663),
|
||||
LatLng(30.171956, 31.491060),
|
||||
LatLng(30.172212, 31.495754),
|
||||
LatLng(30.167112, 31.496108),
|
||||
],
|
||||
// Canadian International College (CIC)
|
||||
[
|
||||
LatLng(30.034312, 31.428963),
|
||||
LatLng(30.035661, 31.429037),
|
||||
LatLng(30.036074, 31.430522),
|
||||
LatLng(30.036017, 31.431146),
|
||||
LatLng(30.034580, 31.431117),
|
||||
],
|
||||
// October 6 University (O6U)
|
||||
[
|
||||
LatLng(29.974102, 30.946934),
|
||||
LatLng(29.976620, 30.944925),
|
||||
LatLng(29.979848, 30.949832),
|
||||
LatLng(29.977372, 30.951950),
|
||||
],
|
||||
[
|
||||
LatLng(30.029312, 31.210046),
|
||||
LatLng(30.027124, 31.201393),
|
||||
LatLng(30.014523, 31.205087),
|
||||
LatLng(30.015416, 31.212218),
|
||||
LatLng(30.027325, 31.210661),
|
||||
],
|
||||
// Add polygons for 8 more universities...
|
||||
];
|
||||
|
||||
static const List<String> universityNames = [
|
||||
"American University in Cairo (AUC)",
|
||||
'German University in Cairo (GUC)',
|
||||
'Future University in Egypt (FUE)',
|
||||
'British University in Egypt (BUE)',
|
||||
'Misr International University (MIU)',
|
||||
'Canadian International College (CIC)',
|
||||
'October 6 University (O6U)',
|
||||
"Cairo University",
|
||||
// Add names for 8 more universities...
|
||||
];
|
||||
}
|
||||
57
lib/controller/Widget/home_widget_provider.dart
Normal file
57
lib/controller/Widget/home_widget_provider.dart
Normal file
@@ -0,0 +1,57 @@
|
||||
// import 'package:home_widget/home_widget.dart';
|
||||
|
||||
// class TripzHomeWidgetProvider {
|
||||
// static const String widgetName = 'TripzHomeWidget';
|
||||
|
||||
// // Initialize Home Widget
|
||||
// static Future<void> initHomeWidget() async {
|
||||
// await HomeWidget.registerInteractivityCallback(backgroundCallback);
|
||||
// }
|
||||
|
||||
// // Background Callback for Widget Updates
|
||||
// static Future<void> backgroundCallback(Uri? uri) async {
|
||||
// if (uri?.host == 'updateWidget') {
|
||||
// // Logic to update widget data
|
||||
// await updateWidgetData();
|
||||
// }
|
||||
// }
|
||||
|
||||
// // Update Widget Data Method
|
||||
// static Future<void> updateWidgetData() async {
|
||||
// // Fetch current ride details
|
||||
// final rideData = await _fetchCurrentRideDetails();
|
||||
|
||||
// // Update Widget with Ride Information
|
||||
// await HomeWidget.saveWidgetData<String>(
|
||||
// 'ride_destination', rideData.destination);
|
||||
// await HomeWidget.saveWidgetData<String>(
|
||||
// 'ride_estimated_time', rideData.estimatedTime);
|
||||
// await HomeWidget.saveWidgetData<double>('ride_fare', rideData.fare);
|
||||
|
||||
// // Trigger Widget Update
|
||||
// await HomeWidget.updateWidget(
|
||||
// name: widgetName,
|
||||
// iOSName: 'TripzWidgetProvider',
|
||||
// androidName: 'com.mobileapp.store.ride.HomeWidgetProvider',
|
||||
// );
|
||||
// }
|
||||
|
||||
// // Mock method to fetch ride details (replace with actual implementation)
|
||||
// static Future<RideData> _fetchCurrentRideDetails() async {
|
||||
// // Implement actual data fetching logic
|
||||
// return RideData(
|
||||
// destination: 'Downtown Office', estimatedTime: '25 mins', fare: 15.50);
|
||||
// }
|
||||
// }
|
||||
|
||||
// // Ride Data Model
|
||||
// class RideData {
|
||||
// final String destination;
|
||||
// final String estimatedTime;
|
||||
// final double fare;
|
||||
|
||||
// RideData(
|
||||
// {required this.destination,
|
||||
// required this.estimatedTime,
|
||||
// required this.fare});
|
||||
// }
|
||||
37
lib/controller/auth/apple_signin_controller.dart
Normal file
37
lib/controller/auth/apple_signin_controller.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
|
||||
|
||||
class AuthController extends GetxController {
|
||||
final FirebaseAuth _auth = FirebaseAuth.instance;
|
||||
|
||||
Future<User?> signInWithApple() async {
|
||||
try {
|
||||
final appleCredential = await SignInWithApple.getAppleIDCredential(
|
||||
scopes: [
|
||||
AppleIDAuthorizationScopes.email,
|
||||
AppleIDAuthorizationScopes.fullName,
|
||||
],
|
||||
);
|
||||
|
||||
final oAuthProvider = OAuthProvider('apple.com');
|
||||
final credential = oAuthProvider.credential(
|
||||
idToken: appleCredential.identityToken,
|
||||
accessToken: appleCredential.authorizationCode,
|
||||
);
|
||||
|
||||
UserCredential userCredential =
|
||||
await _auth.signInWithCredential(credential);
|
||||
|
||||
return userCredential.user;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> signOut() async {
|
||||
try {
|
||||
await _auth.signOut();
|
||||
} catch (error) {}
|
||||
}
|
||||
}
|
||||
204
lib/controller/auth/google_sign.dart
Normal file
204
lib/controller/auth/google_sign.dart
Normal file
@@ -0,0 +1,204 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/controller/auth/login_controller.dart';
|
||||
import 'package:Intaleq/controller/functions/encrypt_decrypt.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:google_sign_in/google_sign_in.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../constant/links.dart';
|
||||
import '../../onbording_page.dart';
|
||||
import '../../print.dart';
|
||||
import '../functions/crud.dart';
|
||||
|
||||
class GoogleSignInHelper {
|
||||
static final GoogleSignIn _googleSignIn = GoogleSignIn(
|
||||
scopes: [
|
||||
'email',
|
||||
'profile',
|
||||
],
|
||||
);
|
||||
|
||||
// Method to handle Google Sign-In
|
||||
static Future<GoogleSignInAccount?> signIn() async {
|
||||
try {
|
||||
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
|
||||
if (googleUser != null) {
|
||||
await _handleSignUp(googleUser);
|
||||
// if (box.read(BoxName.countryCode) == 'Egypt') {
|
||||
// Get.to(() => EgyptCardAI());
|
||||
// } else if (box.read(BoxName.countryCode) == 'Jordan') {
|
||||
// Get.to(() => AiPage());
|
||||
// }
|
||||
}
|
||||
return googleUser;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<GoogleSignInAccount?> signInFromLogin() async {
|
||||
try {
|
||||
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
|
||||
if (googleUser != null) {
|
||||
await _handleSignUp(googleUser);
|
||||
await Get.put(LoginController()).loginUsingCredentials(
|
||||
box.read(BoxName.passengerID).toString(),
|
||||
box.read(BoxName.email).toString(),
|
||||
);
|
||||
}
|
||||
return googleUser;
|
||||
} catch (error) {
|
||||
// if (error is GoogleSignInAuthenticationException) {
|
||||
// // Handle authentication errors from Google Sign-In
|
||||
// addError("Google sign-in authentication error: ${error.message}",
|
||||
// '<GoogleSignInAccount?> signInFromLogin()');
|
||||
// } else if (error is GoogleSignInAccountNotFoundException) {
|
||||
// // Handle the case where the user is not found (if applicable)
|
||||
// addError("Google sign-in account not found error: ${error.message}",
|
||||
// '<GoogleSignInAccount?> signInFromLogin()');
|
||||
// }
|
||||
// else
|
||||
if (error is SocketException) {
|
||||
// Handle network issues, like SSL certificate issues
|
||||
addError("Network error (SSL certificate issue): ${error.message}",
|
||||
'<GoogleSignInAccount?> signInFromLogin()');
|
||||
} else if (error is PlatformException) {
|
||||
// Handle platform-specific errors, like Google Play Services issues
|
||||
if (error.code == 'sign_in_required') {
|
||||
// Google Play Services are required but not installed or outdated
|
||||
showGooglePlayServicesError();
|
||||
} else {
|
||||
addError("Platform error: ${error.message}",
|
||||
'<GoogleSignInAccount?> signInFromLogin()');
|
||||
}
|
||||
} else {
|
||||
// Catch all other unknown errors
|
||||
addError("Unknown error: ${error.toString()}",
|
||||
'<GoogleSignInAccount?> signInFromLogin()');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void showGooglePlayServicesError() async {
|
||||
const playStoreUrl =
|
||||
'https://play.google.com/store/apps/details?id=com.google.android.gms&hl=en_US';
|
||||
|
||||
if (await canLaunchUrl(Uri.parse(playStoreUrl))) {
|
||||
await launchUrl(Uri.parse(playStoreUrl));
|
||||
} else {
|
||||
// Fallback if the URL can't be opened
|
||||
showDialog(
|
||||
context: Get.context!,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: Text('Error'.tr),
|
||||
content: Text(
|
||||
'Could not open the Google Play Store. Please update Google Play Services manually.'
|
||||
.tr),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: Text('Close'.tr),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Future<GoogleSignInAccount?> signInFromLogin() async {
|
||||
// try {
|
||||
// final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
|
||||
// if (googleUser != null) {
|
||||
// await _handleSignUp(googleUser);
|
||||
// // if (box.read(BoxName.countryCode) == 'Egypt') {
|
||||
// await Get.put(LoginController()).loginUsingCredentials(
|
||||
// box.read(BoxName.passengerID).toString(),
|
||||
// box.read(BoxName.email).toString(),
|
||||
// );
|
||||
// // } else if (box.read(BoxName.countryCode) == 'Jordan') {
|
||||
// // // Get.to(() => AiPage());
|
||||
// // }
|
||||
// }
|
||||
// return googleUser;
|
||||
// } catch (error) {
|
||||
// addError(error.toString(), '<GoogleSignInAccount?> signInFromLogin()');
|
||||
// return null;
|
||||
// }
|
||||
// }
|
||||
|
||||
addError(String error, where) async {
|
||||
CRUD().post(link: AppLink.addError, payload: {
|
||||
'error': error.toString(), // Example error description
|
||||
'userId': box.read(BoxName.driverID) ??
|
||||
box.read(BoxName.passengerID), // Example user ID
|
||||
'userType': box.read(BoxName.driverID) != null
|
||||
? 'Driver'
|
||||
: 'passenger', // Example user type
|
||||
'phone': box.read(BoxName.phone) ??
|
||||
box.read(BoxName.phoneDriver), // Example phone number
|
||||
|
||||
'device': where
|
||||
});
|
||||
}
|
||||
|
||||
// Method to handle Google Sign-Out
|
||||
static Future<void> signOut() async {
|
||||
try {
|
||||
await _googleSignIn.signOut();
|
||||
await _handleSignOut();
|
||||
} catch (error) {}
|
||||
}
|
||||
|
||||
// Method to get the current signed-in user
|
||||
static GoogleSignInAccount? getCurrentUser() {
|
||||
return _googleSignIn.currentUser;
|
||||
}
|
||||
|
||||
// Method to handle sign-up process
|
||||
static Future<void> _handleSignUp(GoogleSignInAccount user) async {
|
||||
// Store driver information
|
||||
|
||||
box.write(BoxName.passengerID, user.id);
|
||||
box.write(BoxName.email, (user.email));
|
||||
box.write(BoxName.name, (user.displayName.toString()));
|
||||
box.write(BoxName.passengerPhotoUrl, (user.photoUrl.toString()));
|
||||
|
||||
// Perform any additional sign-up tasks or API calls here
|
||||
// For example, you can send the user data to your server for registration
|
||||
}
|
||||
|
||||
// Method to handle sign-out process
|
||||
static Future<void> _handleSignOut() async {
|
||||
// Clear stored driver information
|
||||
box.erase();
|
||||
// box.remove(BoxName.passengerPhotoUrl);
|
||||
// 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);
|
||||
// box.remove(BoxName.isVerified);
|
||||
// box.remove(BoxName.firstTimeLoadKey);
|
||||
Get.offAll(() => OnBoardingPage());
|
||||
// Perform any additional sign-out tasks or API calls here
|
||||
// For example, you can notify your server about the user sign-out
|
||||
}
|
||||
}
|
||||
406
lib/controller/auth/login_controller.dart
Normal file
406
lib/controller/auth/login_controller.dart
Normal file
@@ -0,0 +1,406 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
import 'package:Intaleq/constant/api_key.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import 'package:Intaleq/constant/info.dart';
|
||||
import 'package:Intaleq/controller/functions/add_error.dart';
|
||||
import 'package:Intaleq/views/auth/login_page.dart';
|
||||
import 'package:Intaleq/views/auth/sms_verfy_page.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:Intaleq/views/home/map_page_passenger.dart';
|
||||
import 'package:jwt_decoder/jwt_decoder.dart';
|
||||
import 'package:location/location.dart';
|
||||
import 'package:secure_string_operations/secure_string_operations.dart';
|
||||
|
||||
import '../../constant/char_map.dart';
|
||||
import '../../print.dart';
|
||||
import '../../views/auth/otp_token_page.dart';
|
||||
import '../functions/encrypt_decrypt.dart';
|
||||
import '../functions/package_info.dart';
|
||||
import '../functions/secure_storage.dart';
|
||||
import '../functions/securty_check.dart';
|
||||
|
||||
class LoginController extends GetxController {
|
||||
final formKey = GlobalKey<FormState>();
|
||||
final formKeyAdmin = GlobalKey<FormState>();
|
||||
TextEditingController emailController = TextEditingController();
|
||||
TextEditingController phoneController = TextEditingController();
|
||||
TextEditingController passwordController = TextEditingController();
|
||||
TextEditingController adminPasswordController = TextEditingController();
|
||||
TextEditingController adminNameController = TextEditingController();
|
||||
bool isAgreeTerms = false;
|
||||
bool isloading = false;
|
||||
late int isTest = 1;
|
||||
void changeAgreeTerm() {
|
||||
isAgreeTerms = !isAgreeTerms;
|
||||
update();
|
||||
}
|
||||
|
||||
var dev = '';
|
||||
@override
|
||||
void onInit() async {
|
||||
await getAppTester();
|
||||
Log.print('box.read(BoxName.isTest): ${box.read(BoxName.isTest)}');
|
||||
box.write(BoxName.countryCode, 'Syria');
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
getAppTester() async {
|
||||
var res = await CRUD().get(
|
||||
link: AppLink.getTesterApp,
|
||||
payload: {'appPlatform': AppInformation.appName});
|
||||
if (res != 'failure') {
|
||||
var d = jsonDecode(res);
|
||||
|
||||
isTest = int.parse(d['message'][0]['isTest'].toString());
|
||||
box.write(BoxName.isTest, isTest);
|
||||
update();
|
||||
} else {
|
||||
box.write(BoxName.isTest, '1');
|
||||
update();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
updateAppTester(String appPlatform) async {
|
||||
await CRUD().post(
|
||||
link: AppLink.updateTesterApp, payload: {'appPlatform': appPlatform});
|
||||
}
|
||||
|
||||
void saveAgreementTerms() {
|
||||
box.write(BoxName.agreeTerms, 'agreed');
|
||||
update();
|
||||
}
|
||||
|
||||
void saveCountryCode(String countryCode) {
|
||||
box.write(BoxName.countryCode, countryCode);
|
||||
update();
|
||||
}
|
||||
|
||||
getJwtWallet() async {
|
||||
final random = Random();
|
||||
|
||||
if (random.nextBool()) {
|
||||
await SecurityHelper.performSecurityChecks();
|
||||
} else {
|
||||
await SecurityChecks.isDeviceRootedFromNative(Get.context!);
|
||||
}
|
||||
|
||||
String fingerPrint = await DeviceHelper.getDeviceFingerprint();
|
||||
// print('fingerPrint: ${fingerPrint}');
|
||||
dev = Platform.isAndroid ? 'android' : 'ios';
|
||||
var payload = {
|
||||
'id': box.read(BoxName.passengerID),
|
||||
'password': AK.passnpassenger,
|
||||
'aud': '${AK.allowed}$dev',
|
||||
'fingerPrint': fingerPrint
|
||||
};
|
||||
var response1 = await http.post(
|
||||
Uri.parse(AppLink.loginJwtWalletRider),
|
||||
body: payload,
|
||||
);
|
||||
await box.write(BoxName.hmac, jsonDecode(response1.body)['hmac']);
|
||||
// Log.print('jsonDecoeded[hmac]: ${jsonDecoeded['hmac']}');
|
||||
// Log.print('req: ${response1.request}');
|
||||
// Log.print('response: ${response1.body}');
|
||||
// Log.print('payload: ${payload}');
|
||||
return jsonDecode(response1.body)['jwt'].toString();
|
||||
}
|
||||
|
||||
getJWT() async {
|
||||
// print(Pasenger.pasengerpas);
|
||||
// await SecurityHelper.performSecurityChecks();
|
||||
Log.print('firstTimeLoadKey: ${box.read(BoxName.firstTimeLoadKey)}');
|
||||
dev = Platform.isAndroid ? 'android' : 'ios';
|
||||
if (box.read(BoxName.firstTimeLoadKey).toString() != 'false') {
|
||||
var payload = {
|
||||
'id': box.read(BoxName.passengerID) ?? AK.newId,
|
||||
'password': AK.passnpassenger,
|
||||
'aud': '${AK.allowed}$dev',
|
||||
};
|
||||
// Log.print('payload: ${payload}');
|
||||
var response0 = await http.post(
|
||||
Uri.parse(AppLink.loginFirstTime),
|
||||
body: payload,
|
||||
);
|
||||
if (response0.statusCode == 200) {
|
||||
final decodedResponse1 = jsonDecode(response0.body);
|
||||
|
||||
final jwt = decodedResponse1['jwt'];
|
||||
final refreshToken = decodedResponse1['refresh_token'];
|
||||
box.write(BoxName.jwt, c(jwt));
|
||||
// Sss.write(BoxName.jwt, jwt);
|
||||
await storage.write(key: BoxName.refreshToken, value: refreshToken);
|
||||
|
||||
// await AppInitializer().getAIKey(Pasenger.keyOfApp);
|
||||
// await AppInitializer().getAIKey(Pasenger.initializationVector);
|
||||
// await Future.delayed(Duration.zero);
|
||||
await EncryptionHelper.initialize();
|
||||
|
||||
await AppInitializer().getKey();
|
||||
} else {}
|
||||
} else {
|
||||
await EncryptionHelper.initialize();
|
||||
|
||||
var payload = {
|
||||
'id': box.read(BoxName.passengerID),
|
||||
'password': box.read(BoxName.email),
|
||||
'aud': '${AK.allowed}$dev',
|
||||
};
|
||||
// Log.print('payload: ${payload}');
|
||||
var response1 = await http.post(
|
||||
Uri.parse(AppLink.loginJwtRider),
|
||||
body: payload,
|
||||
);
|
||||
// Log.print('req: ${response1.request}');
|
||||
// Log.print('response: ${response1.body}');
|
||||
// Log.print('payload: ${payload}');
|
||||
// Log.print('decodedResponse1: ${jsonDecode(response1.body)}');
|
||||
|
||||
if (response1.statusCode == 200) {
|
||||
final decodedResponse1 = jsonDecode(response1.body);
|
||||
// Log.print('decodedResponse1: ${decodedResponse1}');
|
||||
|
||||
final jwt = decodedResponse1['jwt'];
|
||||
await box.write(BoxName.jwt, c(jwt));
|
||||
|
||||
await AppInitializer().getKey();
|
||||
|
||||
final refreshToken = decodedResponse1['refresh_token'];
|
||||
await storage.write(key: BoxName.refreshToken, value: refreshToken);
|
||||
} else {}
|
||||
}
|
||||
}
|
||||
|
||||
loginUsingCredentials(String passengerID, email) async {
|
||||
isloading = true;
|
||||
update();
|
||||
bool isTokenExpired = JwtDecoder.isExpired(
|
||||
r(box.read(BoxName.jwt)).toString().split(AppInformation.addd)[0]);
|
||||
|
||||
if (isTokenExpired) {
|
||||
// Log.print('isTokenExpired loginUsingCredentials: ${isTokenExpired}');
|
||||
await getJWT();
|
||||
}
|
||||
|
||||
var res =
|
||||
await CRUD().get(link: AppLink.loginFromGooglePassenger, payload: {
|
||||
'email': email.toString(),
|
||||
'id': passengerID.toString(),
|
||||
"platform": Platform.isAndroid ? 'android' : 'ios',
|
||||
"appName": AppInformation.appName,
|
||||
});
|
||||
if (res == 'Failure') {
|
||||
// Get.offAll(SmsSignupEgypt());
|
||||
isloading = false;
|
||||
update();
|
||||
Get.snackbar("User does not exist.".tr, '', backgroundColor: Colors.red);
|
||||
} else {
|
||||
// Log.print('res: ${res}');
|
||||
var jsonDecoeded = jsonDecode(res);
|
||||
|
||||
if (jsonDecoeded.isNotEmpty) {
|
||||
var d = jsonDecoeded['data'][0];
|
||||
if (jsonDecoeded['status'] == 'success' &&
|
||||
d['verified'].toString() == '1') {
|
||||
//
|
||||
|
||||
box.write(BoxName.isVerified, '1');
|
||||
box.write(BoxName.email, d['email']);
|
||||
box.write(BoxName.phone, d['phone']);
|
||||
box.write(BoxName.name, d['first_name']);
|
||||
box.write(BoxName.isTest, '1');
|
||||
box.write(BoxName.package, d['package']);
|
||||
box.write(BoxName.promo, d['promo']);
|
||||
box.write(BoxName.discount, d['discount']);
|
||||
box.write(BoxName.validity, d['validity']);
|
||||
box.write(BoxName.isInstall, d['isInstall'] ?? 'none');
|
||||
box.write(BoxName.isGiftToken, d['isGiftToken'] ?? 'none');
|
||||
box.write(BoxName.firstTimeLoadKey, 'false');
|
||||
d['inviteCode'] != null
|
||||
? box.write(
|
||||
BoxName.inviteCode, (d['inviteCode'].toString()) ?? 'none')
|
||||
: null;
|
||||
|
||||
var token = await CRUD().get(link: AppLink.getTokens, payload: {
|
||||
'passengerID': box.read(BoxName.passengerID).toString()
|
||||
});
|
||||
var fingerPrint = await DeviceHelper.getDeviceFingerprint();
|
||||
Log.print('fingerPrint 0: ${fingerPrint}');
|
||||
await storage.write(key: BoxName.fingerPrint, value: fingerPrint);
|
||||
|
||||
if (email == '962798583052@intaleqapp.com') {
|
||||
} else {
|
||||
if (token != 'failure') {
|
||||
if ((jsonDecode(token)['message']['token'].toString()) !=
|
||||
box.read(BoxName.tokenFCM)) {
|
||||
await Get.defaultDialog(
|
||||
title: 'Device Change Detected'.tr,
|
||||
middleText: 'Please verify your identity'.tr,
|
||||
textConfirm: 'Verify'.tr,
|
||||
confirmTextColor: Colors.white,
|
||||
onConfirm: () {
|
||||
// Get.back();
|
||||
// انتقل لصفحة OTP الجديدة
|
||||
Get.to(
|
||||
() => OtpVerificationPage(
|
||||
phone: d['phone'].toString(),
|
||||
deviceToken: fingerPrint.toString(),
|
||||
token: token.toString(),
|
||||
ptoken:
|
||||
jsonDecode(token)['message']['token'].toString(),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
} // Logging to check if inviteCode is written correctly
|
||||
|
||||
if (d['inviteCode'] != 'none' &&
|
||||
d['inviteCode'] != null &&
|
||||
// box.read(BoxName.inviteCode).toString() != 'none' &&
|
||||
box.read(BoxName.isInstall).toString() != '1') {
|
||||
await CRUD()
|
||||
.post(link: AppLink.updatePassengersInvitation, payload: {
|
||||
"inviteCode": (box.read(BoxName.inviteCode).toString()),
|
||||
"passengerID": box.read(BoxName.passengerID).toString(),
|
||||
});
|
||||
Get.defaultDialog(
|
||||
title: 'Invitation Used'
|
||||
.tr, // Automatically translates based on the current locale
|
||||
middleText: "Your invite code was successfully applied!"
|
||||
.tr, // Automatically translates based on the current locale
|
||||
onConfirm: () {
|
||||
try {
|
||||
CRUD().post(link: AppLink.addPassengersPromo, payload: {
|
||||
"promoCode":
|
||||
'S-${(box.read(BoxName.name)).toString().split(' ')[0]}',
|
||||
"amount": '25',
|
||||
"passengerID": box.read(BoxName.passengerID).toString(),
|
||||
"description": 'promo first'
|
||||
});
|
||||
} catch (e) {
|
||||
addError(e.toString(),
|
||||
'passenger Invitation Used dialogu as promo line 185 login_controller');
|
||||
} finally {
|
||||
// Continue with the rest of your flow, regardless of errors
|
||||
// For example, navigate to the next page
|
||||
Get.offAll(() => const MapPagePassenger());
|
||||
}
|
||||
},
|
||||
textConfirm: "OK".tr, // Confirm button text
|
||||
);
|
||||
} else {
|
||||
Get.offAll(() => const MapPagePassenger());
|
||||
}
|
||||
} else {
|
||||
Get.offAll(() => SmsSignupEgypt());
|
||||
// Get.snackbar(jsonDecoeded['status'], jsonDecoeded['data'],
|
||||
// backgroundColor: Colors.redAccent);
|
||||
isloading = false;
|
||||
update();
|
||||
}
|
||||
} else {
|
||||
isloading = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void login() async {
|
||||
isloading = true;
|
||||
update();
|
||||
var res =
|
||||
await CRUD().get(link: AppLink.loginFromGooglePassenger, payload: {
|
||||
'email': (emailController.text),
|
||||
'id': passwordController.text,
|
||||
"platform": Platform.isAndroid ? 'android' : 'ios',
|
||||
"appName": AppInformation.appName,
|
||||
});
|
||||
|
||||
isloading = false;
|
||||
update();
|
||||
if (res == 'Failure') {
|
||||
//Failure
|
||||
Get.offAll(() => LoginPage());
|
||||
isloading = false;
|
||||
update();
|
||||
// Get.snackbar("User does not exist.".tr, '', backgroundColor: Colors.red);
|
||||
} else {
|
||||
var jsonDecoeded = jsonDecode(res);
|
||||
if (jsonDecoeded.isNotEmpty) {
|
||||
if (jsonDecoeded['status'] == 'success' &&
|
||||
jsonDecoeded['data'][0]['verified'].toString() == '1') {
|
||||
//
|
||||
box.write(BoxName.isVerified, '1');
|
||||
box.write(BoxName.email, jsonDecoeded['data'][0]['email']);
|
||||
box.write(BoxName.name, jsonDecoeded['data'][0]['first_name']);
|
||||
box.write(BoxName.phone, jsonDecoeded['data'][0]['phone']);
|
||||
box.write(BoxName.passengerID, passwordController.text);
|
||||
// var token = await CRUD().get(link: AppLink.getTokens, payload: {
|
||||
// 'passengerID': box.read(BoxName.passengerID).toString()
|
||||
// });
|
||||
await updateAppTester(AppInformation.appName);
|
||||
|
||||
Get.offAll(() => const MapPagePassenger());
|
||||
} else {
|
||||
// Get.offAll(() => SmsSignupEgypt());
|
||||
// Get.snackbar(jsonDecoeded['status'], jsonDecoeded['data'],
|
||||
// backgroundColor: Colors.redAccent);
|
||||
isloading = false;
|
||||
update();
|
||||
}
|
||||
} else {
|
||||
isloading = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
goToMapPage() {
|
||||
if (box.read(BoxName.email) != null) {
|
||||
Get.offAll(() => const MapPagePassenger());
|
||||
}
|
||||
}
|
||||
|
||||
final location = Location();
|
||||
|
||||
// late PermissionStatus permissionGranted = PermissionStatus.denied;
|
||||
Future<void> getLocationPermission() async {
|
||||
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
|
||||
permissionGranted = await location.requestPermission();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (permissionGranted.toString() == 'PermissionStatus.granted') {
|
||||
box.write(BoxName.locationPermission, 'true');
|
||||
}
|
||||
update();
|
||||
}
|
||||
}
|
||||
43
lib/controller/auth/onboarding_controller.dart
Normal file
43
lib/controller/auth/onboarding_controller.dart
Normal file
@@ -0,0 +1,43 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:Intaleq/views/auth/login_page.dart';
|
||||
|
||||
import '../../models/model/onboarding_model.dart';
|
||||
|
||||
abstract class OnBoardingController extends GetxController {
|
||||
next();
|
||||
onPageChanged(int index);
|
||||
}
|
||||
|
||||
class OnBoardingControllerImp extends OnBoardingController {
|
||||
late PageController pageController;
|
||||
|
||||
int currentPage = 0;
|
||||
|
||||
@override
|
||||
next() {
|
||||
currentPage++;
|
||||
|
||||
if (currentPage > onBoardingList.length - 1) {
|
||||
box.write(BoxName.onBoarding, 'yes');
|
||||
Get.offAll(() => LoginPage());
|
||||
} else {
|
||||
pageController.animateToPage(currentPage,
|
||||
duration: const Duration(milliseconds: 900), curve: Curves.easeInOut);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
onPageChanged(int index) {
|
||||
currentPage = index;
|
||||
update();
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
pageController = PageController();
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
133
lib/controller/auth/otp_controller.dart
Normal file
133
lib/controller/auth/otp_controller.dart
Normal file
@@ -0,0 +1,133 @@
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/views/home/map_page_passenger.dart';
|
||||
import 'package:get/get.dart';
|
||||
import '../../../constant/box_name.dart';
|
||||
import '../../../main.dart';
|
||||
import '../../../print.dart';
|
||||
import '../../views/auth/otp_page.dart';
|
||||
import '../../views/widgets/error_snakbar.dart';
|
||||
import '../functions/crud.dart';
|
||||
import 'login_controller.dart';
|
||||
|
||||
// --- Helper Class for Phone Authentication ---
|
||||
|
||||
class PhoneAuthHelper {
|
||||
// Define your server URLs
|
||||
static final String _baseUrl = '${AppLink.server}/auth/syria/';
|
||||
static final String _sendOtpUrl = '${_baseUrl}sendWhatsOpt.php';
|
||||
static final String _verifyOtpUrl = '${_baseUrl}verifyOtp.php';
|
||||
static final String _registerUrl = '${_baseUrl}register_passenger.php';
|
||||
|
||||
/// Sends an OTP to the provided phone number.
|
||||
static Future<bool> sendOtp(String phoneNumber) async {
|
||||
try {
|
||||
final response = await CRUD().post(
|
||||
link: _sendOtpUrl,
|
||||
payload: {'receiver': phoneNumber},
|
||||
);
|
||||
// Log.print('response: ${response}');
|
||||
if (response != 'failure') {
|
||||
final data = (response);
|
||||
// if (data['status'] == 'success') {
|
||||
mySnackbarSuccess('An OTP has been sent to your WhatsApp number.'.tr);
|
||||
return true;
|
||||
// } else {
|
||||
// mySnackeBarError(data['message'] ?? 'Failed to send OTP.');
|
||||
// return false;
|
||||
// }
|
||||
} else {
|
||||
mySnackeBarError('Server error. Please try again.'.tr);
|
||||
return false;
|
||||
}
|
||||
} catch (e) {
|
||||
Log.print('e: ${e}');
|
||||
// mySnackeBarError('An error occurred: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Verifies the OTP and logs the user in.
|
||||
|
||||
static Future<void> verifyOtp(String phoneNumber, String otp) async {
|
||||
try {
|
||||
final response = await CRUD().post(
|
||||
link: _verifyOtpUrl,
|
||||
payload: {'phone_number': phoneNumber, 'otp': otp},
|
||||
);
|
||||
|
||||
if (response != 'failure') {
|
||||
final data = (response);
|
||||
// Log.print('data: ${data}');
|
||||
|
||||
if (data['status'] == 'success') {
|
||||
final isRegistered = data['message']['isRegistered'] ?? false;
|
||||
// Log.print('isRegistered: ${isRegistered}');
|
||||
|
||||
if (isRegistered) {
|
||||
// ✅ المستخدم موجود مسبقاً -> تسجيل دخول مباشر
|
||||
await _handleSuccessfulLogin(data['message']['passenger']);
|
||||
} else {
|
||||
// ✅ مستخدم جديد -> الذهاب لصفحة التسجيل
|
||||
mySnackbarSuccess(
|
||||
'Phone verified. Please complete registration.'.tr);
|
||||
Get.to(() => RegistrationScreen(phoneNumber: phoneNumber));
|
||||
}
|
||||
} else {
|
||||
mySnackeBarError(data['message']);
|
||||
}
|
||||
} else {
|
||||
mySnackeBarError('Server error. Please try again.'.tr);
|
||||
}
|
||||
} catch (e) {
|
||||
mySnackeBarError('An error occurred: $e');
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> registerUser({
|
||||
required String phoneNumber,
|
||||
required String firstName,
|
||||
required String lastName,
|
||||
String? email,
|
||||
}) async {
|
||||
try {
|
||||
final response = await CRUD().post(
|
||||
link: _registerUrl,
|
||||
payload: {
|
||||
'phone_number': phoneNumber,
|
||||
'first_name': firstName,
|
||||
'last_name': lastName,
|
||||
'email': email ?? '', // Send empty string if null
|
||||
},
|
||||
);
|
||||
final data = (response);
|
||||
if (data != 'failure') {
|
||||
// Registration successful, log user in
|
||||
await _handleSuccessfulLogin(data['message']['data']);
|
||||
} else {
|
||||
mySnackeBarError(
|
||||
"User with this phone number or email already exists.".tr);
|
||||
}
|
||||
} catch (e) {
|
||||
Log.print('e: ${e}');
|
||||
mySnackeBarError('An error occurred: $e');
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> _handleSuccessfulLogin(
|
||||
Map<String, dynamic> userData) async {
|
||||
mySnackbarSuccess('Welcome, ${userData['first_name']}!');
|
||||
|
||||
// Save user data to local storage (Hive box) using new keys
|
||||
box.write(BoxName.passengerID, userData['id']);
|
||||
box.write(BoxName.name, userData['first_name']);
|
||||
box.write(BoxName.lastName, userData['last_name']);
|
||||
box.write(BoxName.email, userData['email']);
|
||||
box.write(BoxName.phone, userData['phone']);
|
||||
box.write(BoxName.isVerified, '1');
|
||||
|
||||
await Get.put(LoginController()).loginUsingCredentials(
|
||||
box.read(BoxName.passengerID).toString(),
|
||||
box.read(BoxName.email).toString(),
|
||||
); // Navigate to home
|
||||
}
|
||||
}
|
||||
381
lib/controller/auth/register_controller.dart
Normal file
381
lib/controller/auth/register_controller.dart
Normal file
@@ -0,0 +1,381 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:Intaleq/constant/colors.dart';
|
||||
import 'package:Intaleq/controller/auth/login_controller.dart';
|
||||
import 'package:Intaleq/controller/functions/add_error.dart';
|
||||
import 'package:Intaleq/controller/functions/encrypt_decrypt.dart';
|
||||
import 'package:Intaleq/views/home/map_page_passenger.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/constant/style.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/views/auth/login_page.dart';
|
||||
import 'package:Intaleq/views/widgets/elevated_btn.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.dart';
|
||||
import '../../views/auth/verify_email_page.dart';
|
||||
import '../../views/widgets/mydialoug.dart';
|
||||
import '../functions/sms_controller.dart';
|
||||
|
||||
class RegisterController extends GetxController {
|
||||
final formKey = GlobalKey<FormState>();
|
||||
final formKey3 = GlobalKey<FormState>();
|
||||
|
||||
TextEditingController firstNameController = TextEditingController();
|
||||
TextEditingController lastNameController = TextEditingController();
|
||||
TextEditingController emailController = TextEditingController();
|
||||
TextEditingController phoneController = TextEditingController();
|
||||
TextEditingController passwordController = TextEditingController();
|
||||
TextEditingController siteController = TextEditingController();
|
||||
// TextEditingController verfyCode = TextEditingController();
|
||||
TextEditingController verifyCode = TextEditingController();
|
||||
int remainingTime = 300; // 5 minutes in seconds
|
||||
bool isSent = false;
|
||||
bool isLoading = false;
|
||||
Timer? _timer;
|
||||
String birthDate = 'Birth Date'.tr;
|
||||
String gender = 'Male'.tr;
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
void startTimer() {
|
||||
_timer?.cancel(); // Cancel any existing timer
|
||||
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
if (remainingTime > 0) {
|
||||
remainingTime--;
|
||||
} else {
|
||||
timer.cancel();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
getBirthDate() {
|
||||
Get.defaultDialog(
|
||||
title: 'Select Date'.tr,
|
||||
titleStyle: AppStyle.title,
|
||||
content: SizedBox(
|
||||
width: 300,
|
||||
child: CalendarDatePicker(
|
||||
initialDate:
|
||||
DateTime.now().subtract(const Duration(days: 14 * 365)),
|
||||
firstDate: DateTime.parse('1940-06-01'),
|
||||
lastDate: DateTime.now().subtract(const Duration(days: 14 * 365)),
|
||||
onDateChanged: (date) {
|
||||
// Get the selected date and convert it to a DateTime object
|
||||
DateTime dateTime = date;
|
||||
// Call the getOrders() function from the controller
|
||||
birthDate = dateTime.toString().split(' ')[0];
|
||||
update();
|
||||
},
|
||||
|
||||
// onDateChanged: (DateTime value) {},
|
||||
),
|
||||
),
|
||||
confirm: MyElevatedButton(title: 'Ok'.tr, onPressed: () => Get.back()));
|
||||
}
|
||||
|
||||
void changeGender(String value) {
|
||||
gender = value;
|
||||
update();
|
||||
}
|
||||
|
||||
bool isValidEgyptianPhoneNumber(String phoneNumber) {
|
||||
// Remove any whitespace from the phone number
|
||||
phoneNumber = phoneNumber.replaceAll(RegExp(r'\s+'), '');
|
||||
|
||||
// Check if the phone number has exactly 11 digits
|
||||
if (phoneNumber.length != 11) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if the phone number starts with 010, 011, 012, or 015
|
||||
RegExp validPrefixes = RegExp(r'^01[0125]\d{8}$');
|
||||
|
||||
return validPrefixes.hasMatch(phoneNumber);
|
||||
}
|
||||
|
||||
bool isValidPhoneNumber(String phoneNumber) {
|
||||
// Remove any whitespace from the phone number
|
||||
phoneNumber = phoneNumber.replaceAll(RegExp(r'\s+'), '');
|
||||
|
||||
// Check if the phone number has at least 10 digits
|
||||
if (phoneNumber.length < 10) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for valid prefixes (modify this to match your use case)
|
||||
RegExp validPrefixes = RegExp(r'^[0-9]+$');
|
||||
|
||||
// Check if the phone number contains only digits
|
||||
return validPrefixes.hasMatch(phoneNumber);
|
||||
}
|
||||
|
||||
sendOtpMessage() async {
|
||||
SmsEgyptController smsEgyptController;
|
||||
isLoading = true;
|
||||
update();
|
||||
try {
|
||||
// Initialize SmsEgyptController
|
||||
smsEgyptController = Get.put(SmsEgyptController());
|
||||
|
||||
isLoading = true;
|
||||
update();
|
||||
|
||||
// Get phone number from controller
|
||||
String phoneNumber = phoneController.text;
|
||||
|
||||
// Check if the phone number is from Egypt (Assuming Egyptian numbers start with +20)
|
||||
|
||||
if (phoneController.text.isNotEmpty) {
|
||||
bool isEgyptianNumber = phoneNumber.startsWith('+20');
|
||||
if (isEgyptianNumber && phoneNumber.length == 13) {
|
||||
// Check if the phone number is already verified
|
||||
var responseChecker = await CRUD().post(
|
||||
link: AppLink.checkPhoneNumberISVerfiedPassenger,
|
||||
payload: {
|
||||
'phone_number': (phoneNumber),
|
||||
'email': box.read(BoxName.email),
|
||||
},
|
||||
);
|
||||
|
||||
if (responseChecker != 'failure') {
|
||||
var data = jsonDecode(responseChecker);
|
||||
|
||||
// If the phone number is already verified
|
||||
if (data['message'][0]['verified'].toString() == '1') {
|
||||
Get.snackbar('Phone number is verified before'.tr, '',
|
||||
backgroundColor: AppColor.greenColor);
|
||||
box.write(BoxName.isVerified, '1');
|
||||
box.write(BoxName.phone, (phoneNumber));
|
||||
Get.offAll(const MapPagePassenger());
|
||||
} else {
|
||||
await sendOtp(phoneNumber, isEgyptianNumber, smsEgyptController);
|
||||
}
|
||||
} else {
|
||||
await sendOtp(phoneNumber, isEgyptianNumber, smsEgyptController);
|
||||
}
|
||||
} else if (phoneNumber.length > 9) {
|
||||
sendOtp(phoneNumber, isEgyptianNumber, smsEgyptController);
|
||||
}
|
||||
} else {
|
||||
MyDialog().getDialog(
|
||||
'Error'.tr, 'Phone number must be exactly 11 digits long'.tr, () {
|
||||
Get.back();
|
||||
});
|
||||
// sendOtp(
|
||||
// phoneNumber, randomNumber, isEgyptianNumber, smsEgyptController);
|
||||
}
|
||||
} catch (e) {
|
||||
// Handle error
|
||||
} finally {
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to send OTP or WhatsApp message based on phone number location
|
||||
Future<void> sendOtp(String phoneNumber, bool isEgyptian,
|
||||
SmsEgyptController controller) async {
|
||||
// Trim any leading or trailing whitespace from the phone number
|
||||
phoneNumber = phoneNumber.trim();
|
||||
var dd = await CRUD().post(link: AppLink.sendVerifyOtpMessage, payload: {
|
||||
'phone_number': (phoneNumber),
|
||||
});
|
||||
Log.print('dd: ${dd}');
|
||||
|
||||
// Common Registration Logic (extracted for reuse)
|
||||
Future<void> registerUser() async {
|
||||
await CRUD().post(link: AppLink.updatePhoneInvalidSMSPassenger, payload: {
|
||||
"phone_number": (Get.find<RegisterController>().phoneController.text)
|
||||
});
|
||||
|
||||
box.write(BoxName.phone, (phoneController.text));
|
||||
|
||||
var nameParts = (box.read(BoxName.name)).toString().split(' ');
|
||||
var firstName = nameParts.isNotEmpty ? nameParts[0] : 'unknown';
|
||||
var lastName = nameParts.length > 1 ? nameParts[1] : 'unknown';
|
||||
|
||||
var payload = {
|
||||
'id': box.read(BoxName.passengerID),
|
||||
'phone': (phoneController.text),
|
||||
'email': box.read(BoxName.email),
|
||||
'password':
|
||||
('unknown'), //Consider if you *really* want to store 'unknown' passwords
|
||||
'gender': ('unknown'),
|
||||
'birthdate': ('2002-01-01'),
|
||||
'site': box.read(BoxName.passengerPhotoUrl) ?? 'unknown',
|
||||
'first_name': (firstName),
|
||||
'last_name': (lastName),
|
||||
};
|
||||
|
||||
var res1 = await CRUD().post(
|
||||
link: AppLink.signUp,
|
||||
payload: payload,
|
||||
);
|
||||
|
||||
if (res1 != 'failure') {
|
||||
//Multi-server signup (moved inside the successful registration check)
|
||||
if (AppLink.IntaleqAlexandriaServer != AppLink.IntaleqCairoServer) {
|
||||
List<Future> signUp = [
|
||||
CRUD().post(
|
||||
link: '${AppLink.IntaleqAlexandriaServer}/auth/signup.php',
|
||||
payload: payload,
|
||||
),
|
||||
CRUD().post(
|
||||
link: '${AppLink.IntaleqGizaServer}/auth/signup.php',
|
||||
payload: payload,
|
||||
)
|
||||
];
|
||||
await Future.wait(signUp); // Wait for both sign-ups to complete.
|
||||
}
|
||||
|
||||
box.write(BoxName.isVerified, '1');
|
||||
box.write(
|
||||
BoxName.isFirstTime, '0'); //Double-check the logic for isFirstTime
|
||||
box.write(BoxName.phone, (phoneController.text));
|
||||
|
||||
Get.put(LoginController()).loginUsingCredentials(
|
||||
box.read(BoxName.passengerID).toString(),
|
||||
box.read(BoxName.email).toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (isEgyptian) {
|
||||
// verifySMSCode();
|
||||
// await registerUser(); // Use the common registration logic
|
||||
// await controller.sendSmsEgypt(phoneNumber, otp.toString()); // Optional: Send SMS if Egyptian
|
||||
} else if (phoneController.text.toString().length >= 10) {
|
||||
await registerUser(); // Use the common registration logic for non-Egyptian users as well.
|
||||
// this for whatsapp messsage // Optional: Send WhatsApp message
|
||||
// await CRUD().sendWhatsAppAuth(phoneNumber, otp.toString());
|
||||
}
|
||||
|
||||
isLoading = false;
|
||||
isSent = true;
|
||||
remainingTime = 300;
|
||||
update(); // Reset to 5 minutes
|
||||
// startTimer(); // Consider whether you need a timer here, or if it's handled elsewhere.
|
||||
}
|
||||
|
||||
verifySMSCode() async {
|
||||
try {
|
||||
if (formKey3.currentState!.validate()) {
|
||||
var res = await CRUD().post(link: AppLink.verifyOtpPassenger, payload: {
|
||||
'phone_number': phoneController.text,
|
||||
'token': verifyCode.text,
|
||||
});
|
||||
|
||||
if (res != 'failure') {
|
||||
box.write(BoxName.phone, (phoneController.text));
|
||||
var nameParts = (box.read(BoxName.name)).toString().split(' ');
|
||||
var firstName = nameParts.isNotEmpty ? nameParts[0] : 'unknown';
|
||||
var lastName = nameParts.length > 1 ? nameParts[1] : 'unknown';
|
||||
|
||||
var payload = {
|
||||
'id': box.read(BoxName.passengerID),
|
||||
'phone': (phoneController.text),
|
||||
'email': box.read(BoxName.email),
|
||||
'password': 'unknown',
|
||||
'gender': 'unknown',
|
||||
'birthdate': '2002-01-01',
|
||||
'site': box.read(BoxName.passengerPhotoUrl) ?? 'unknown',
|
||||
'first_name': firstName,
|
||||
'last_name': lastName,
|
||||
};
|
||||
|
||||
var res1 = await CRUD().post(
|
||||
link: AppLink.signUp,
|
||||
payload: payload,
|
||||
);
|
||||
|
||||
if (res1 != 'failure') {
|
||||
if (AppLink.IntaleqAlexandriaServer != AppLink.IntaleqCairoServer) {
|
||||
List<Future> signUp = [
|
||||
CRUD().post(
|
||||
link: '${AppLink.IntaleqAlexandriaServer}/auth/signup.php',
|
||||
payload: payload,
|
||||
),
|
||||
CRUD().post(
|
||||
link: '${AppLink.IntaleqGizaServer}/auth/signup.php',
|
||||
payload: payload,
|
||||
)
|
||||
];
|
||||
await Future.wait(signUp);
|
||||
}
|
||||
|
||||
box.write(BoxName.isVerified, '1');
|
||||
box.write(BoxName.isFirstTime, '0');
|
||||
box.write(BoxName.phone, (phoneController.text));
|
||||
|
||||
Get.put(LoginController()).loginUsingCredentials(
|
||||
box.read(BoxName.passengerID).toString(),
|
||||
box.read(BoxName.email).toString(),
|
||||
);
|
||||
} else {
|
||||
Get.snackbar('Error'.tr,
|
||||
"The email or phone number is already registered.".tr,
|
||||
backgroundColor: Colors.redAccent);
|
||||
}
|
||||
} else {
|
||||
Get.snackbar('Error'.tr, "phone not verified".tr,
|
||||
backgroundColor: Colors.redAccent);
|
||||
}
|
||||
} else {
|
||||
Get.snackbar('Error'.tr, "you must insert token code".tr,
|
||||
backgroundColor: AppColor.redColor);
|
||||
}
|
||||
} catch (e) {
|
||||
addError(e.toString(), 'passenger sign up ');
|
||||
Get.snackbar('Error'.tr, "Something went wrong. Please try again.".tr,
|
||||
backgroundColor: Colors.redAccent);
|
||||
}
|
||||
}
|
||||
|
||||
sendVerifications() async {
|
||||
var res = await CRUD().post(link: AppLink.verifyEmail, payload: {
|
||||
'email': emailController.text,
|
||||
'token': verifyCode.text,
|
||||
});
|
||||
var dec = jsonDecode(res);
|
||||
if (dec['status'] == 'success') {
|
||||
Get.offAll(() => LoginPage());
|
||||
}
|
||||
}
|
||||
|
||||
void register() async {
|
||||
if (formKey.currentState!.validate()) {
|
||||
var res = await CRUD().post(link: AppLink.signUp, payload: {
|
||||
'first_name': firstNameController.text.toString(),
|
||||
'last_name': lastNameController.text.toString(),
|
||||
'email': emailController.text.toString(),
|
||||
'phone': phoneController.text.toString(),
|
||||
'password': passwordController.text.toString(),
|
||||
'gender': 'yet',
|
||||
'site': siteController.text,
|
||||
'birthdate': birthDate,
|
||||
});
|
||||
if (jsonDecode(res)['status'] == 'success') {
|
||||
int randomNumber = Random().nextInt(100000) + 1;
|
||||
await CRUD().post(link: AppLink.sendVerifyEmail, payload: {
|
||||
'email': emailController.text,
|
||||
'token': randomNumber.toString(),
|
||||
});
|
||||
Get.to(() => const VerifyEmailPage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_timer?.cancel();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
107
lib/controller/auth/token_otp_change_controller.dart
Normal file
107
lib/controller/auth/token_otp_change_controller.dart
Normal file
@@ -0,0 +1,107 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../print.dart';
|
||||
import '../../views/home/map_page_passenger.dart';
|
||||
import '../firebase/firbase_messge.dart';
|
||||
|
||||
class OtpVerificationController extends GetxController {
|
||||
final String phone;
|
||||
final String deviceToken;
|
||||
final String token;
|
||||
final otpCode = ''.obs;
|
||||
final isLoading = false.obs;
|
||||
final isVerifying = false.obs;
|
||||
var canResend = false.obs;
|
||||
var countdown = 120.obs;
|
||||
Timer? _timer;
|
||||
|
||||
OtpVerificationController({
|
||||
required this.phone,
|
||||
required this.deviceToken,
|
||||
required this.token,
|
||||
});
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
sendOtp(); // ترسل تلقائيًا عند فتح الصفحة
|
||||
startCountdown();
|
||||
}
|
||||
|
||||
void startCountdown() {
|
||||
canResend.value = false;
|
||||
countdown.value = 120;
|
||||
_timer?.cancel();
|
||||
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
if (countdown.value > 0) {
|
||||
countdown.value--;
|
||||
} else {
|
||||
canResend.value = true;
|
||||
timer.cancel();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> sendOtp() async {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
final response = await CRUD().post(
|
||||
link: '${AppLink.server}/auth/token_passenger/send_otp.php',
|
||||
payload: {
|
||||
'receiver': phone,
|
||||
// 'device_token': deviceToken,
|
||||
},
|
||||
);
|
||||
|
||||
if (response != 'failure') {
|
||||
// بإمكانك عرض رسالة نجاح هنا
|
||||
} else {
|
||||
// Get.snackbar('Error', 'Failed to send OTP');
|
||||
}
|
||||
} catch (e) {
|
||||
Get.snackbar('Error', e.toString());
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> verifyOtp(String ptoken) async {
|
||||
isVerifying.value = true;
|
||||
var finger = await storage.read(key: BoxName.fingerPrint);
|
||||
try {
|
||||
final response = await CRUD().post(
|
||||
link: '${AppLink.server}/auth/token_passenger/verify_otp.php',
|
||||
payload: {
|
||||
'phone_number': phone,
|
||||
'otp': otpCode.value,
|
||||
'token': box.read(BoxName.tokenFCM).toString(),
|
||||
'fingerPrint': finger.toString(),
|
||||
},
|
||||
);
|
||||
|
||||
if (response != 'failure' && response['status'] == 'success') {
|
||||
Get.back(); // توجه إلى الصفحة التالية
|
||||
await Get.put(FirebaseMessagesController()).sendNotificationToDriverMAP(
|
||||
'token change',
|
||||
'change device'.tr,
|
||||
ptoken.toString(),
|
||||
[],
|
||||
'cancel.wav',
|
||||
);
|
||||
Get.offAll(() => const MapPagePassenger());
|
||||
} else {
|
||||
Get.snackbar('Verification Failed', 'OTP is incorrect or expired');
|
||||
}
|
||||
} catch (e) {
|
||||
Get.snackbar('Error', e.toString());
|
||||
} finally {
|
||||
isVerifying.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
38
lib/controller/auth/tokens_controller.dart
Normal file
38
lib/controller/auth/tokens_controller.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../main.dart';
|
||||
import '../functions/encrypt_decrypt.dart';
|
||||
|
||||
class TokenController extends GetxController {
|
||||
bool isloading = false;
|
||||
|
||||
Future addToken() async {
|
||||
String? basicAuthCredentials =
|
||||
await storage.read(key: BoxName.basicAuthCredentials);
|
||||
isloading = true;
|
||||
update();
|
||||
var res = await http.post(
|
||||
Uri.parse(AppLink.addTokens),
|
||||
headers: {
|
||||
'Authorization':
|
||||
'Basic ${base64Encode(utf8.encode(basicAuthCredentials.toString()))}',
|
||||
},
|
||||
body: {
|
||||
'token': (box.read(BoxName.tokenFCM.toString())),
|
||||
'passengerID': box.read(BoxName.passengerID).toString()
|
||||
},
|
||||
);
|
||||
|
||||
isloading = false;
|
||||
update();
|
||||
var jsonToken = jsonDecode(res.body);
|
||||
if (jsonToken['status'] == 'The token has been updated successfully.') {
|
||||
Get.snackbar('token updated'.tr, '');
|
||||
}
|
||||
}
|
||||
}
|
||||
16
lib/controller/auth/verify_email_controller.dart
Normal file
16
lib/controller/auth/verify_email_controller.dart
Normal file
@@ -0,0 +1,16 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
|
||||
class VerifyEmailController extends GetxController {
|
||||
TextEditingController verfyCode = TextEditingController();
|
||||
@override
|
||||
void onInit() async {
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
sendverfications() async {
|
||||
await CRUD().post(link: AppLink.sendVerifyEmail);
|
||||
}
|
||||
}
|
||||
50
lib/controller/firebase/access_token.dart
Normal file
50
lib/controller/firebase/access_token.dart
Normal file
@@ -0,0 +1,50 @@
|
||||
import 'dart:convert';
|
||||
import 'package:googleapis_auth/auth_io.dart';
|
||||
|
||||
class AccessTokenManager {
|
||||
static final AccessTokenManager _instance = AccessTokenManager._internal();
|
||||
late final String serviceAccountJsonKey;
|
||||
AccessToken? _accessToken;
|
||||
DateTime? _expiryDate;
|
||||
|
||||
AccessTokenManager._internal();
|
||||
|
||||
factory AccessTokenManager(String jsonKey) {
|
||||
if (_instance._isServiceAccountKeyInitialized()) {
|
||||
// Prevent re-initialization
|
||||
return _instance;
|
||||
}
|
||||
_instance.serviceAccountJsonKey = jsonKey;
|
||||
return _instance;
|
||||
}
|
||||
|
||||
bool _isServiceAccountKeyInitialized() {
|
||||
try {
|
||||
serviceAccountJsonKey; // Access to check if initialized
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> getAccessToken() async {
|
||||
if (_accessToken != null && DateTime.now().isBefore(_expiryDate!)) {
|
||||
return _accessToken!.data;
|
||||
}
|
||||
try {
|
||||
final serviceAccountCredentials = ServiceAccountCredentials.fromJson(
|
||||
json.decode(serviceAccountJsonKey));
|
||||
final client = await clientViaServiceAccount(
|
||||
serviceAccountCredentials,
|
||||
['https://www.googleapis.com/auth/firebase.messaging'],
|
||||
);
|
||||
|
||||
_accessToken = client.credentials.accessToken;
|
||||
_expiryDate = client.credentials.accessToken.expiry;
|
||||
client.close();
|
||||
return _accessToken!.data;
|
||||
} catch (e) {
|
||||
throw Exception('Failed to obtain access token');
|
||||
}
|
||||
}
|
||||
}
|
||||
853
lib/controller/firebase/firbase_messge.dart
Normal file
853
lib/controller/firebase/firbase_messge.dart
Normal file
@@ -0,0 +1,853 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:Intaleq/controller/functions/encrypt_decrypt.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:Intaleq/controller/functions/toast.dart';
|
||||
import 'package:Intaleq/views/widgets/elevated_btn.dart';
|
||||
|
||||
import '../../constant/api_key.dart';
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/colors.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../constant/style.dart';
|
||||
import '../../constant/table_names.dart';
|
||||
import '../../env/env.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.dart';
|
||||
import '../../views/Rate/rate_captain.dart';
|
||||
import '../../views/home/map_page_passenger.dart';
|
||||
import '../../views/home/profile/promos_passenger_page.dart';
|
||||
import '../auth/google_sign.dart';
|
||||
import '../functions/audio_record1.dart';
|
||||
import '../home/map_passenger_controller.dart';
|
||||
import 'access_token.dart';
|
||||
import 'local_notification.dart';
|
||||
|
||||
class FirebaseMessagesController extends GetxController {
|
||||
final fcmToken = FirebaseMessaging.instance;
|
||||
|
||||
List<String> tokens = [];
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
NotificationController notificationController =
|
||||
Get.put(NotificationController());
|
||||
|
||||
Future getTokens() async {
|
||||
String? basicAuthCredentials =
|
||||
await storage.read(key: BoxName.basicAuthCredentials);
|
||||
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 getToken() async {
|
||||
fcmToken.getToken().then((token) {
|
||||
Log.print('fcmToken: ${token}');
|
||||
box.write(BoxName.tokenFCM, (token.toString()));
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
});
|
||||
FirebaseMessaging.onBackgroundMessage((RemoteMessage message) async {
|
||||
// Handle background message
|
||||
if (message.data.isNotEmpty && message.notification != null) {
|
||||
fireBaseTitles(message);
|
||||
}
|
||||
});
|
||||
|
||||
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
|
||||
if (message.data.isNotEmpty && message.notification != null) {
|
||||
fireBaseTitles(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> fireBaseTitles(RemoteMessage message) async {
|
||||
if (message.notification!.title! == 'Order'.tr) {
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'Order', message.notification!.body!, 'Order');
|
||||
}
|
||||
} else if (message.notification!.title! == 'Accepted Ride') {
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'Accepted Ride'.tr, 'Driver Accepted the Ride for You'.tr, 'ding');
|
||||
}
|
||||
var passengerList = message.data['passengerList'];
|
||||
|
||||
var myList = jsonDecode(passengerList) as List<dynamic>;
|
||||
Log.print('myList: ${myList}');
|
||||
final controller = Get.find<MapPassengerController>();
|
||||
controller.driverId = myList[0].toString();
|
||||
// assume rideId lives at index 2 in your list:
|
||||
controller.rideId = myList[3].toString();
|
||||
|
||||
controller
|
||||
..statusRide = 'Apply'
|
||||
..isSearchingWindow = false
|
||||
..update();
|
||||
await controller.rideAppliedFromDriver(true);
|
||||
|
||||
// driverAppliedTripSnakBar();
|
||||
} else if (message.notification!.title! == 'Promo'.tr) {
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'Promo', 'Show latest promo'.tr, 'promo');
|
||||
}
|
||||
Get.to(const PromosPassengerPage());
|
||||
} else if (message.notification!.title! == 'Trip Monitoring'.tr) {
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'Trip Monitoring'.tr, '', 'iphone_ringtone');
|
||||
}
|
||||
var myListString = message.data['passengerList'];
|
||||
var myList = jsonDecode(myListString) as List<dynamic>;
|
||||
Get.toNamed('/tripmonitor', arguments: {
|
||||
'rideId': myList[0].toString(),
|
||||
'driverId': myList[1].toString(),
|
||||
});
|
||||
} else if (message.notification!.title! == 'token change'.tr) {
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'token change'.tr, 'token change'.tr, 'cancel');
|
||||
}
|
||||
GoogleSignInHelper.signOut();
|
||||
} else if (message.notification!.title! ==
|
||||
'Driver Is Going To Passenger'.tr) {
|
||||
Get.find<MapPassengerController>().isDriverInPassengerWay = true;
|
||||
Get.find<MapPassengerController>().update();
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification('Driver is Going To You'.tr,
|
||||
'Please stay on the picked point.'.tr, 'tone1');
|
||||
}
|
||||
// Get.snackbar('Driver is Going To Passenger', '',
|
||||
// backgroundColor: AppColor.greenColor);
|
||||
} else if (message.notification!.title! == 'message From passenger') {
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'message From passenger'.tr, ''.tr, 'ding');
|
||||
}
|
||||
passengerDialog(message.notification!.body!);
|
||||
|
||||
update();
|
||||
} else if (message.notification!.title! == 'message From Driver') {
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'message From Driver'.tr, ''.tr, 'ding');
|
||||
}
|
||||
passengerDialog(message.notification!.body!);
|
||||
|
||||
update();
|
||||
} else if (message.notification!.title! == 'Trip is Begin'.tr) {
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'Trip is Begin'.tr, ''.tr, 'start');
|
||||
}
|
||||
Get.find<MapPassengerController>().getBeginRideFromDriver();
|
||||
// Get.snackbar('RideIsBegin', '', backgroundColor: AppColor.greenColor);
|
||||
box.write(BoxName.passengerWalletTotal, '0');
|
||||
update();
|
||||
} else if (message.notification!.title! == 'Hi ,I will go now'.tr) {
|
||||
// Get.snackbar('Hi ,I will go now', '',
|
||||
// backgroundColor: AppColor.greenColor);
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'Passenger come to you'.tr, 'Hi ,I will go now'.tr, 'ding');
|
||||
}
|
||||
update();
|
||||
} else if (message.notification!.title! == 'Hi ,I Arrive your site') {
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'Hi ,I Arrive your site'.tr, ''.tr, 'ding');
|
||||
}
|
||||
driverArrivePassengerDialoge();
|
||||
|
||||
update();
|
||||
} else if (message.notification!.title! == "Cancel Trip from driver") {
|
||||
Get.back();
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification("Cancel Trip from driver".tr,
|
||||
"We will look for a new driver.\nPlease wait.".tr, 'cancel');
|
||||
}
|
||||
Get.defaultDialog(
|
||||
title: "The driver canceled your ride.".tr,
|
||||
middleText: "We will look for a new driver.\nPlease wait.".tr,
|
||||
confirm: MyElevatedButton(
|
||||
kolor: AppColor.greenColor,
|
||||
title: 'Ok'.tr,
|
||||
onPressed: () async {
|
||||
Get.back();
|
||||
await Get.find<MapPassengerController>()
|
||||
.reSearchAfterCanceledFromDriver();
|
||||
},
|
||||
),
|
||||
cancel: MyElevatedButton(
|
||||
title: 'Cancel'.tr,
|
||||
kolor: AppColor.redColor,
|
||||
onPressed: () {
|
||||
Get.offAll(() => const MapPagePassenger());
|
||||
},
|
||||
)
|
||||
// Get.find<MapPassengerController>()
|
||||
// .searchNewDriverAfterRejectingFromDriver();
|
||||
);
|
||||
} else if (message.notification!.title! == 'Driver Finish Trip'.tr) {
|
||||
var myListString = message.data['DriverList'];
|
||||
Log.print('myListString: ${myListString}');
|
||||
var driverList = jsonDecode(myListString) as List<dynamic>;
|
||||
Log.print('driverList: ${driverList}');
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
"Driver Finish Trip".tr,
|
||||
'you will pay to Driver'.tr + ' ${driverList[3].toString()} \$'.tr,
|
||||
'tone1');
|
||||
}
|
||||
Get.find<AudioRecorderController>().stopRecording();
|
||||
if (double.parse(box.read(BoxName.passengerWalletTotal)) < 0) {
|
||||
box.write(BoxName.passengerWalletTotal, 0);
|
||||
}
|
||||
print(333);
|
||||
Get.find<MapPassengerController>().tripFinishedFromDriver();
|
||||
NotificationController().showNotification(
|
||||
'Don’t forget your personal belongings.'.tr,
|
||||
'Please make sure you have all your personal belongings and that any remaining fare, if applicable, has been added to your wallet before leaving. Thank you for choosing the Intaleq app'
|
||||
.tr,
|
||||
'ding');
|
||||
print(267);
|
||||
Get.to(() => RateDriverFromPassenger(), arguments: {
|
||||
'driverId': driverList[0].toString(),
|
||||
'rideId': driverList[1].toString(),
|
||||
'price': driverList[3].toString()
|
||||
});
|
||||
} else if (message.notification!.title! == "Finish Monitor".tr) {
|
||||
Get.defaultDialog(
|
||||
titleStyle: AppStyle.title,
|
||||
title: 'Trip finished '.tr,
|
||||
middleText: '',
|
||||
confirm: MyElevatedButton(
|
||||
title: 'Ok'.tr,
|
||||
onPressed: () {
|
||||
Get.offAll(() => const MapPagePassenger());
|
||||
}));
|
||||
}
|
||||
// else if (message.notification!.title! == "Trip Monitoring".tr) {
|
||||
// Get.to(() => const TripMonitor());
|
||||
// }
|
||||
else if (message.notification!.title! == 'Call Income') {
|
||||
try {
|
||||
var myListString = message.data['passengerList'];
|
||||
var driverList = jsonDecode(myListString) as List<dynamic>;
|
||||
// if (Platform.isAndroid) {
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'Call Income'.tr,
|
||||
message.notification!.body!,
|
||||
'iphone_ringtone',
|
||||
);
|
||||
}
|
||||
// }
|
||||
// Assuming GetMaterialApp is initialized and context is valid for navigation
|
||||
// Get.to(() => PassengerCallPage(
|
||||
// channelName: driverList[1].toString(),
|
||||
// token: driverList[0].toString(),
|
||||
// remoteID: driverList[2].toString(),
|
||||
// ));
|
||||
} catch (e) {}
|
||||
} else if (message.notification!.title! == 'Call Income from Driver'.tr) {
|
||||
try {
|
||||
var myListString = message.data['passengerList'];
|
||||
var driverList = jsonDecode(myListString) as List<dynamic>;
|
||||
// if (Platform.isAndroid) {
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'Call Income'.tr,
|
||||
message.notification!.body!,
|
||||
'iphone_ringtone',
|
||||
);
|
||||
}
|
||||
// Assuming GetMaterialApp is initialized and context is valid for navigation
|
||||
// Get.to(() => PassengerCallPage(
|
||||
// channelName: driverList[1].toString(),
|
||||
// token: driverList[0].toString(),
|
||||
// remoteID: driverList[2].toString(),
|
||||
// ));
|
||||
} catch (e) {}
|
||||
} else if (message.notification!.title! == 'Call End'.tr) {
|
||||
try {
|
||||
var myListString = message.data['passengerList'];
|
||||
var driverList = jsonDecode(myListString) as List<dynamic>;
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'Call End'.tr,
|
||||
message.notification!.body!,
|
||||
'ding',
|
||||
);
|
||||
}
|
||||
// Assuming GetMaterialApp is initialized and context is valid for navigation
|
||||
// Get.off(const CallPage());
|
||||
} catch (e) {}
|
||||
} else if (message.notification!.title! == 'Driver Cancelled Your Trip') {
|
||||
// Get.snackbar(
|
||||
// 'You will be pay the cost to driver or we will get it from you on next trip'
|
||||
// .tr,
|
||||
// 'message',
|
||||
// backgroundColor: AppColor.redColor);
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'Driver Cancelled Your Trip'.tr,
|
||||
'you will pay to Driver you will be pay the cost of driver time look to your Intaleq Wallet'
|
||||
.tr,
|
||||
'cancel');
|
||||
}
|
||||
box.write(BoxName.parentTripSelected, false);
|
||||
box.remove(BoxName.tokenParent);
|
||||
|
||||
Get.find<MapPassengerController>().restCounter();
|
||||
Get.offAll(() => const MapPagePassenger());
|
||||
}
|
||||
// else if (message.notification!.title! == 'Order Applied') {
|
||||
// Get.snackbar(
|
||||
// "The order has been accepted by another driver."
|
||||
// .tr, // Corrected grammar
|
||||
// "Be more mindful next time to avoid dropping orders."
|
||||
// .tr, // Improved sentence structure
|
||||
// backgroundColor: AppColor.yellowColor,
|
||||
// snackPosition: SnackPosition.BOTTOM,
|
||||
// );
|
||||
// }
|
||||
|
||||
else if (message.notification!.title! == 'Order Applied'.tr) {
|
||||
if (Platform.isAndroid) {
|
||||
notificationController.showNotification(
|
||||
'The order Accepted by another Driver'.tr,
|
||||
'We regret to inform you that another driver has accepted this order.'
|
||||
.tr,
|
||||
'order');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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> driverArrivePassengerDialoge() {
|
||||
return Get.defaultDialog(
|
||||
barrierDismissible: false,
|
||||
title: 'Hi ,I Arrive your site'.tr,
|
||||
titleStyle: AppStyle.title,
|
||||
middleText: 'Please go to Car Driver'.tr,
|
||||
middleTextStyle: AppStyle.title,
|
||||
confirm: MyElevatedButton(
|
||||
title: 'Ok I will go now.'.tr,
|
||||
onPressed: () {
|
||||
sendNotificationToPassengerToken(
|
||||
'Hi ,I will go now',
|
||||
'I will go now'.tr,
|
||||
Get.find<MapPassengerController>().driverToken,
|
||||
[],
|
||||
'ding.wav');
|
||||
Get.find<MapPassengerController>()
|
||||
.startTimerDriverWaitPassenger5Minute();
|
||||
|
||||
Get.back();
|
||||
Get.find<MapPassengerController>().remainingTime = 0;
|
||||
Get.find<MapPassengerController>().update();
|
||||
}));
|
||||
}
|
||||
|
||||
Future<dynamic> passengerDialog(String message) {
|
||||
return Get.defaultDialog(
|
||||
barrierDismissible: false,
|
||||
title: 'message From Driver'.tr,
|
||||
titleStyle: AppStyle.title,
|
||||
middleTextStyle: AppStyle.title,
|
||||
middleText: message.tr,
|
||||
confirm: MyElevatedButton(
|
||||
title: 'Ok'.tr,
|
||||
onPressed: () {
|
||||
// Get.find<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 {
|
||||
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, tone) async {
|
||||
// Get the token you want to subtract.
|
||||
String token = box.read(BoxName.tokenFCM);
|
||||
tokens = box.read(BoxName.tokens);
|
||||
// Subtract the token from the list of tokens.
|
||||
tokens.remove(token);
|
||||
|
||||
// Save the list of tokens back to the box.
|
||||
// box.write(BoxName.tokens, tokens);
|
||||
tokens = box.read(BoxName.tokens);
|
||||
for (var i = 0; i < tokens.length; i++) {
|
||||
http
|
||||
.post(
|
||||
Uri.parse('https://fcm.googleapis.com/fcm/send'),
|
||||
headers: <String, String>{
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'key=${AK.serverAPI}'
|
||||
},
|
||||
body: jsonEncode({
|
||||
'message': {
|
||||
'token': token,
|
||||
'notification': {
|
||||
'title': title,
|
||||
'body': body,
|
||||
},
|
||||
// 'data': {
|
||||
// 'DriverList': jsonEncode(data),
|
||||
// },
|
||||
'android': {
|
||||
'priority': 'high', // Set priority to high
|
||||
'notification': {
|
||||
'sound': tone,
|
||||
},
|
||||
},
|
||||
'apns': {
|
||||
'headers': {
|
||||
'apns-priority': '10', // Set APNs priority to 10
|
||||
},
|
||||
'payload': {
|
||||
'aps': {
|
||||
'sound': tone,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
.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) {
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
|
||||
late String serviceAccountKeyJson;
|
||||
// '{"type": "service_account", "project_id": "intaleq-d48a7", "private_key_id": "d63a627dad96d0050c08a76c2920b1e48ddc4d38", "private_key": "-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHgHWUIlGskFWT\\nkjBvSiAYzXz51NbyMtqlvq1rZaiokd/yzqcEsjgxcAEGap93gRu72cuJ7QzDOpec\\nXSmhQwaGrdDyGyuS5x8nBa9ea3QEUGKjk975OhgIDoaIX2YHjah+jf/p3CPvwovC\\n+qypLsErv5DtcFfKtHkL+Z8gKJojU3p0gP2cVLHlhodGG4767w1f70fIv5LmQRHh\\nE0x5GgjO7MfA1CJewgHDWzj9GTuTd9o3G5nF6ojn8H1EOWminNDrsHAagsplY7iV\\nNmdvGoIAg2kRt66y5k4Li7EiH3e2ILvomGvUe3ahxBTcyFAt7UuAC5aPTmB0OCtN\\n39vMkJGtAgMBAAECggEAQ/FoWcBMX4AyXNUzQJuWjcvhzbXiVE7kbwEez44qH+q6\\nQdeGQw+tGo0iFDzYvVrPhqzYaEs+hvib7Kk/xcdtYA2vNNzy/I9Q6TnC7V2b/+Ie\\njcYM8IUL7SaBQ811kon4gc07hDowVPXFImy7w8yEBjGyGmMhywumk+D6A/o/8Fph\\n3lGRzgYZ7K7+mXxDpJVFp8DwX+uqP/3wOzcITXE12GZpvB+re7TQTs01qjsSTJ3/\\nCZMC6CvwYr3BvJzvgrn2TNZ6N6yowHE2iJo/HnoY/DutiB1V0B2EAMgcy05ZUouH\\nnTTOMAyV5LdcxgCtzlz+meCuhV5SUtfSz27bnUluMwKBgQDz+qJM38NhUpW7tmxZ\\nQsYwlo3Zp2a38UV8VC4mNDM9jjsft9QRHShos7potlIvmn9ryxP87SGNZrW9xy/k\\ngvTbDXu65/TwCUa3HYFCC+eJ5S4bBK/ctFwn1sr5AFjxavY2VV6YHUIzGezo8Bsj\\n1R5IGy3UHreTWngDapJYpA3JQwKBgQDRVNK7UP/Qt4qovrTVlNJ5mHjpwk7VoKBC\\nV0yrfbYVjYETFRFMrsKkcwCTQ3uk3lEl/UzAt2vV6o4Ql8KDzYJ/8ZHHXp9Z2eK9\\nTgR2fOIaEh2JJUjyVAUtuJo7RFl61K3a080+ZGWuZCY6K+prGneFqGuJ7XTtveGy\\njIsZTUhSTwKBgQCS0n5/Qp1iYP+IsjQr1zpLnR6KH+p5wXEua75F8V3wqjo8UTUG\\ng4SA1b/VKfr1eMU7ij9iExYA8RFnvom8u248sLWH+fT1yq9KnS/fHijdXBTN35kx\\neTyIIQOOqz3bMqIuelttsRXYiL6AQ5Yhjywk+m4u27lfrK7SZ3zgaQF+3wKBgEBy\\nfgKfmHLY3z6+oAwVqos3LxrA8OaCcnSaTgeKR5HxI+kNFmtmbpSUt3ufTiTfMVqh\\n1oyKrA+LDDv9jSxpDCF57SjVb/gIxe8EYwlbv3zJUQCVUxUQWxvNduaCT44qhnAV\\nv13TKR78xGwqcxyQZHXo+VrYmaRMTn1bGcQrb/WvAoGAIWUnnGQsvf6SwPQ/7gXC\\nVAq4i3E+coLStVyPK552HVorKa7J+TQnNBGHjCaQhxfCgp59/4qeT5AizzQaMhuS\\noGiUwGeo4RY4A1EEGoUpUk3zWZfC+bAjHVDyIjfN0YfxobL6Sh/97N68PMzb6ppq\\nybvddSGGsqZgucSxkEhIdTw=\\n-----END PRIVATE KEY-----\\n", "client_email": "firebase-adminsdk-fbsvc@intaleq-d48a7.iam.gserviceaccount.com", "client_id": "100558924056484926665", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40intaleq-d48a7.iam.gserviceaccount.com", "universe_domain": "googleapis.com"}';
|
||||
@override
|
||||
Future<void> onInit() async {
|
||||
super.onInit();
|
||||
try {
|
||||
var encryptedKey = Env.privateKeyFCM;
|
||||
// Log.print('encryptedKey: ${encryptedKey}');
|
||||
serviceAccountKeyJson =
|
||||
EncryptionHelper.instance.decryptData(encryptedKey);
|
||||
// Log.print('serviceAccountKeyJson: ${serviceAccountKeyJson}');
|
||||
} catch (e) {
|
||||
print('🔴 Error decrypting FCM key: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> sendNotificationToDriverMAP(
|
||||
String title, String body, String token, List<String> data, String tone,
|
||||
{int retryCount = 2}) async {
|
||||
try {
|
||||
if (serviceAccountKeyJson.isEmpty) {
|
||||
print("🔴 Error: Service Account Key is empty");
|
||||
return;
|
||||
}
|
||||
|
||||
// Initialize AccessTokenManager
|
||||
final accessTokenManager = AccessTokenManager(serviceAccountKeyJson);
|
||||
Log.print(
|
||||
'accessTokenManager: ${accessTokenManager.serviceAccountJsonKey}');
|
||||
|
||||
// Obtain an OAuth 2.0 access token
|
||||
final accessToken = await accessTokenManager.getAccessToken();
|
||||
// Log.print('accessToken: ${accessToken}');
|
||||
|
||||
// Send the notification
|
||||
final response = await http.post(
|
||||
Uri.parse(
|
||||
'https://fcm.googleapis.com/v1/projects/intaleq-d48a7/messages:send'),
|
||||
headers: <String, String>{
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer $accessToken',
|
||||
},
|
||||
body: jsonEncode({
|
||||
'message': {
|
||||
'token': token,
|
||||
'notification': {
|
||||
'title': title,
|
||||
'body': body,
|
||||
},
|
||||
'data': {
|
||||
'DriverList': jsonEncode(data),
|
||||
},
|
||||
'android': {
|
||||
'priority': 'high', // Set priority to high
|
||||
'notification': {
|
||||
'sound': tone,
|
||||
},
|
||||
},
|
||||
'apns': {
|
||||
'headers': {
|
||||
'apns-priority': '10', // Set APNs priority to 10
|
||||
},
|
||||
'payload': {
|
||||
'aps': {
|
||||
'sound': tone,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
print(
|
||||
'Notification sent successfully. Status code: ${response.statusCode}');
|
||||
// print('Response token: ${token}');
|
||||
} else {
|
||||
print(
|
||||
'Failed to send notification. Status code: ${response.statusCode}');
|
||||
print('Response body: ${response.body}');
|
||||
if (retryCount > 0) {
|
||||
print('Retrying... Attempts remaining: $retryCount');
|
||||
await Future.delayed(
|
||||
Duration(seconds: 2)); // Optional delay before retrying
|
||||
return sendNotificationToDriverMAP(title, body, token, data, tone,
|
||||
retryCount: retryCount - 1);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print('Error sending notification: $e');
|
||||
if (retryCount > 0) {
|
||||
print('Retrying... Attempts remaining: $retryCount');
|
||||
await Future.delayed(
|
||||
Duration(seconds: 2)); // Optional delay before retrying
|
||||
return sendNotificationToDriverMAP(title, body, token, data, tone,
|
||||
retryCount: retryCount - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void sendNotificationToPassengerToken(
|
||||
String title, body, token, List<String> map, String tone) async {
|
||||
try {
|
||||
if (serviceAccountKeyJson.isEmpty) {
|
||||
print("🔴 Error: Service Account Key is empty");
|
||||
return;
|
||||
}
|
||||
// Initialize AccessTokenManager
|
||||
final accessTokenManager = AccessTokenManager(serviceAccountKeyJson);
|
||||
|
||||
// Obtain an OAuth 2.0 access token
|
||||
final accessToken = await accessTokenManager.getAccessToken();
|
||||
// Log.print('accessToken: ${accessToken}');
|
||||
|
||||
// Send the notification
|
||||
final response = await http.post(
|
||||
Uri.parse(
|
||||
'https://fcm.googleapis.com/v1/projects/intaleq-d48a7/messages:send'),
|
||||
headers: <String, String>{
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer $accessToken',
|
||||
},
|
||||
body: jsonEncode({
|
||||
'message': {
|
||||
'token': token,
|
||||
'notification': {
|
||||
'title': title,
|
||||
'body': body,
|
||||
},
|
||||
'android': {
|
||||
'priority': 'high', // Set priority to high
|
||||
'notification': {
|
||||
'sound': tone,
|
||||
},
|
||||
},
|
||||
'apns': {
|
||||
'headers': {
|
||||
'apns-priority': '10', // Set APNs priority to 10
|
||||
},
|
||||
'payload': {
|
||||
'aps': {
|
||||
'sound': tone,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
print('✅ Notification sent successfully!');
|
||||
} else {
|
||||
print(
|
||||
'🔴 Failed to send notification. Status code: ${response.statusCode}');
|
||||
print('Response body: ${response.body}');
|
||||
}
|
||||
} catch (e) {
|
||||
print('🔴 Error sending notification: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DriverTipWidget extends StatelessWidget {
|
||||
const DriverTipWidget({
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GetBuilder<MapPassengerController>(builder: (controller) {
|
||||
return Column(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
// Text(
|
||||
// '${'Your fee is '.tr}${Get.find<MapPassengerController>().totalPassenger.toStringAsFixed(2)}'),
|
||||
Text(
|
||||
'Do you want to pay Tips for this Driver'.tr,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
InkWell(
|
||||
onTap: () {
|
||||
box.write(BoxName.tipPercentage, '0.05');
|
||||
|
||||
Toast.show(
|
||||
context,
|
||||
'${'Tip is '.tr}${(controller.totalPassenger) * (double.parse(box.read(BoxName.tipPercentage.toString())))}',
|
||||
AppColor.blueColor);
|
||||
controller.update();
|
||||
},
|
||||
child: Container(
|
||||
decoration: BoxDecoration(border: Border.all()),
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.all(4),
|
||||
child: Center(
|
||||
child: Text('5%'),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
InkWell(
|
||||
onTap: () {
|
||||
box.write(BoxName.tipPercentage, '0.10');
|
||||
Toast.show(
|
||||
context,
|
||||
'${'Tip is'.tr} ${(controller.totalPassenger) * (double.parse(box.read(BoxName.tipPercentage.toString())))}',
|
||||
AppColor.blueColor);
|
||||
controller.update();
|
||||
},
|
||||
child: Container(
|
||||
decoration: BoxDecoration(border: Border.all()),
|
||||
child: const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(5),
|
||||
child: Text('10%'),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
InkWell(
|
||||
onTap: () {
|
||||
box.write(BoxName.tipPercentage, '0.15');
|
||||
Toast.show(
|
||||
context,
|
||||
'${'Tip is'.tr} ${(controller.totalPassenger) * (double.parse(box.read(BoxName.tipPercentage.toString())))}',
|
||||
AppColor.blueColor);
|
||||
controller.update();
|
||||
},
|
||||
child: Container(
|
||||
decoration: BoxDecoration(border: Border.all()),
|
||||
child: const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(5),
|
||||
child: Text('15%'),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
InkWell(
|
||||
onTap: () {
|
||||
box.write(BoxName.tipPercentage, '0.20');
|
||||
Toast.show(
|
||||
context,
|
||||
'${'Tip is'.tr} ${(controller.totalPassenger) * (double.parse(box.read(BoxName.tipPercentage.toString())))}',
|
||||
AppColor.blueColor);
|
||||
controller.update();
|
||||
},
|
||||
child: Container(
|
||||
decoration: BoxDecoration(border: Border.all()),
|
||||
child: const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(5),
|
||||
child: Text('20%'),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
MyElevatedButton(
|
||||
kolor: AppColor.redColor,
|
||||
title: 'No i want'.tr,
|
||||
onPressed: () {
|
||||
box.write(BoxName.tipPercentage, '0');
|
||||
controller.update();
|
||||
}),
|
||||
Container(
|
||||
decoration: AppStyle.boxDecoration1,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(6),
|
||||
child: Text(
|
||||
'${(controller.totalPassenger) * (double.parse(box.read(BoxName.tipPercentage.toString())))} ${box.read(BoxName.countryCode) == 'Egypt' ? 'LE'.tr : 'JOD'.tr}',
|
||||
style: AppStyle.title,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
],
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
59
lib/controller/firebase/live_activity.dart
Normal file
59
lib/controller/firebase/live_activity.dart
Normal file
@@ -0,0 +1,59 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
class LiveActivityScreen extends StatefulWidget {
|
||||
@override
|
||||
_LiveActivityScreenState createState() => _LiveActivityScreenState();
|
||||
}
|
||||
|
||||
class _LiveActivityScreenState extends State<LiveActivityScreen> {
|
||||
static const platform = MethodChannel('live_activity_channel');
|
||||
|
||||
Future<void> _startLiveActivity() async {
|
||||
try {
|
||||
await platform.invokeMethod('startLiveActivity');
|
||||
} on PlatformException catch (e) {
|
||||
print("Failed to start Live Activity: '${e.message}'.");
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _updateLiveActivity(double progress) async {
|
||||
try {
|
||||
await platform.invokeMethod('updateLiveActivity', {"progress": progress});
|
||||
} on PlatformException catch (e) {
|
||||
print("Failed to update Live Activity: '${e.message}'.");
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _endLiveActivity() async {
|
||||
try {
|
||||
await platform.invokeMethod('endLiveActivity');
|
||||
} on PlatformException catch (e) {
|
||||
print("Failed to end Live Activity: '${e.message}'.");
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text("Live Activity Test")),
|
||||
body: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
ElevatedButton(
|
||||
onPressed: _startLiveActivity,
|
||||
child: Text("Start Live Activity"),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () => _updateLiveActivity(0.5),
|
||||
child: Text("Update Progress to 50%"),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: _endLiveActivity,
|
||||
child: Text("End Live Activity"),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
331
lib/controller/firebase/local_notification.dart
Normal file
331
lib/controller/firebase/local_notification.dart
Normal file
@@ -0,0 +1,331 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
import 'package:timezone/data/latest.dart' as tz;
|
||||
import 'package:timezone/timezone.dart' as tz;
|
||||
|
||||
import '../../main.dart';
|
||||
|
||||
class NotificationController extends GetxController {
|
||||
final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
|
||||
FlutterLocalNotificationsPlugin();
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
initNotifications();
|
||||
}
|
||||
|
||||
// Initializes the local notifications plugin
|
||||
Future<void> initNotifications() async {
|
||||
const AndroidInitializationSettings android =
|
||||
AndroidInitializationSettings('@mipmap/launcher_icon');
|
||||
DarwinInitializationSettings ios = DarwinInitializationSettings(
|
||||
requestAlertPermission: true,
|
||||
requestBadgePermission: true,
|
||||
requestSoundPermission: true,
|
||||
// onDidReceiveLocalNotification:
|
||||
// (int id, String? title, String? body, String? payload) async {},
|
||||
);
|
||||
InitializationSettings initializationSettings =
|
||||
InitializationSettings(android: android, iOS: ios);
|
||||
await _flutterLocalNotificationsPlugin.initialize(initializationSettings);
|
||||
|
||||
tz.initializeTimeZones();
|
||||
print('Notifications initialized');
|
||||
}
|
||||
|
||||
// Displays a notification with the given title and message
|
||||
void showNotification(String title, String message, String tone) async {
|
||||
final AndroidNotificationDetails android = AndroidNotificationDetails(
|
||||
'high_importance_channel',
|
||||
'High Importance Notifications',
|
||||
importance: Importance.max,
|
||||
priority: Priority.high,
|
||||
showWhen: false,
|
||||
sound: RawResourceAndroidNotificationSound(tone),
|
||||
);
|
||||
|
||||
const DarwinNotificationDetails ios = DarwinNotificationDetails(
|
||||
sound: 'default',
|
||||
presentAlert: true,
|
||||
presentBadge: true,
|
||||
presentSound: true,
|
||||
);
|
||||
|
||||
final NotificationDetails details =
|
||||
NotificationDetails(android: android, iOS: ios);
|
||||
await _flutterLocalNotificationsPlugin.show(0, title, message, details);
|
||||
print('Notification shown: $title - $message');
|
||||
}
|
||||
// /Users/hamzaaleghwairyeen/development/App/ride 2/lib/controller/firebase/local_notification.dart
|
||||
|
||||
// Assume _flutterLocalNotificationsPlugin is initialized somewhere in your code
|
||||
|
||||
// void scheduleNotificationsForSevenDays(
|
||||
// String title, String message, String tone) async {
|
||||
// final AndroidNotificationDetails android = AndroidNotificationDetails(
|
||||
// 'high_importance_channel',
|
||||
// 'High Importance Notifications',
|
||||
// importance: Importance.max,
|
||||
// priority: Priority.high,
|
||||
// sound: RawResourceAndroidNotificationSound(tone),
|
||||
// );
|
||||
|
||||
// const DarwinNotificationDetails ios = DarwinNotificationDetails(
|
||||
// sound: 'default',
|
||||
// presentAlert: true,
|
||||
// presentBadge: true,
|
||||
// presentSound: true,
|
||||
// );
|
||||
|
||||
// final NotificationDetails details =
|
||||
// NotificationDetails(android: android, iOS: ios);
|
||||
|
||||
// // Check for the exact alarm permission on Android 12 and above
|
||||
// if (Platform.isAndroid) {
|
||||
// if (await Permission.scheduleExactAlarm.isDenied) {
|
||||
// if (await Permission.scheduleExactAlarm.request().isGranted) {
|
||||
// print('SCHEDULE_EXACT_ALARM permission granted');
|
||||
// } else {
|
||||
// print('SCHEDULE_EXACT_ALARM permission denied');
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// // Schedule notifications for the next 7 days
|
||||
// for (int day = 0; day < 7; day++) {
|
||||
// // Schedule for 8:00 AM
|
||||
// await _scheduleNotificationForTime(
|
||||
// day, 8, 0, title, message, details, day * 1000 + 1);
|
||||
|
||||
// // Schedule for 3:00 PM
|
||||
// await _scheduleNotificationForTime(
|
||||
// day, 15, 0, title, message, details, day * 1000 + 2); // Unique ID
|
||||
|
||||
// // Schedule for 8:00 PM
|
||||
// await _scheduleNotificationForTime(
|
||||
// day, 20, 0, title, message, details, day * 1000 + 3); // Unique ID
|
||||
// }
|
||||
|
||||
// print('Notifications scheduled successfully for the next 7 days');
|
||||
// }
|
||||
void scheduleNotificationsForSevenDays(
|
||||
String title, String message, String tone) async {
|
||||
final AndroidNotificationDetails android = AndroidNotificationDetails(
|
||||
'high_importance_channel',
|
||||
'High Importance Notifications',
|
||||
importance: Importance.max,
|
||||
priority: Priority.high,
|
||||
sound: RawResourceAndroidNotificationSound(tone),
|
||||
);
|
||||
|
||||
const DarwinNotificationDetails ios = DarwinNotificationDetails(
|
||||
sound: 'default',
|
||||
presentAlert: true,
|
||||
presentBadge: true,
|
||||
presentSound: true,
|
||||
);
|
||||
|
||||
final NotificationDetails details =
|
||||
NotificationDetails(android: android, iOS: ios);
|
||||
|
||||
// Check for the exact alarm permission on Android 12 and above
|
||||
if (Platform.isAndroid) {
|
||||
if (await Permission.scheduleExactAlarm.isDenied) {
|
||||
if (await Permission.scheduleExactAlarm.request().isGranted) {
|
||||
print('SCHEDULE_EXACT_ALARM permission granted');
|
||||
} else {
|
||||
print('SCHEDULE_EXACT_ALARM permission denied');
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Schedule notifications for the next 7 days
|
||||
for (int day = 0; day < 7; day++) {
|
||||
// List of notification times
|
||||
final notificationTimes = [
|
||||
{'hour': 8, 'minute': 0, 'id': day * 1000 + 1}, // 8:00 AM
|
||||
{'hour': 15, 'minute': 0, 'id': day * 1000 + 2}, // 3:00 PM
|
||||
{'hour': 20, 'minute': 0, 'id': day * 1000 + 3}, // 8:00 PM
|
||||
];
|
||||
|
||||
for (var time in notificationTimes) {
|
||||
final notificationId = time['id'] as int;
|
||||
|
||||
// Check if this notification ID is already stored
|
||||
bool isScheduled = box.read('notification_$notificationId') ?? false;
|
||||
|
||||
if (!isScheduled) {
|
||||
// Schedule the notification if not already scheduled
|
||||
await _scheduleNotificationForTime(
|
||||
day,
|
||||
time['hour'] as int,
|
||||
time['minute'] as int,
|
||||
title,
|
||||
message,
|
||||
details,
|
||||
notificationId,
|
||||
);
|
||||
|
||||
// Mark this notification ID as scheduled in GetStorage
|
||||
box.write('notification_$notificationId', true);
|
||||
} else {
|
||||
print('Notification with ID $notificationId is already scheduled.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
print('Notifications scheduled successfully for the next 7 days');
|
||||
}
|
||||
|
||||
void scheduleNotificationsForTimeSelected(
|
||||
String title, String message, String tone, DateTime timeSelected) async {
|
||||
final AndroidNotificationDetails android = AndroidNotificationDetails(
|
||||
'high_importance_channel',
|
||||
'High Importance Notifications',
|
||||
importance: Importance.max,
|
||||
priority: Priority.high,
|
||||
sound: RawResourceAndroidNotificationSound(tone),
|
||||
);
|
||||
|
||||
const DarwinNotificationDetails ios = DarwinNotificationDetails(
|
||||
sound: 'default',
|
||||
presentAlert: true,
|
||||
presentBadge: true,
|
||||
presentSound: true,
|
||||
);
|
||||
|
||||
final NotificationDetails details =
|
||||
NotificationDetails(android: android, iOS: ios);
|
||||
|
||||
// Check for the exact alarm permission on Android 12 and above
|
||||
if (Platform.isAndroid) {
|
||||
if (await Permission.scheduleExactAlarm.isDenied) {
|
||||
if (await Permission.scheduleExactAlarm.request().isGranted) {
|
||||
print('SCHEDULE_EXACT_ALARM permission granted');
|
||||
} else {
|
||||
print('SCHEDULE_EXACT_ALARM permission denied');
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Schedule notifications for 10 and 30 minutes before the timeSelected
|
||||
await _scheduleNotificationForTimeVIP(
|
||||
timeSelected.subtract(const Duration(minutes: 10)), // 10 minutes before
|
||||
title,
|
||||
message,
|
||||
details,
|
||||
1, // Unique ID for 10-minute before notification
|
||||
);
|
||||
|
||||
await _scheduleNotificationForTimeVIP(
|
||||
timeSelected.subtract(const Duration(minutes: 30)), // 30 minutes before
|
||||
title,
|
||||
message,
|
||||
details,
|
||||
2, // Unique ID for 30-minute before notification
|
||||
);
|
||||
|
||||
print('Notifications scheduled successfully for the time selected');
|
||||
}
|
||||
|
||||
Future<void> _scheduleNotificationForTimeVIP(
|
||||
DateTime scheduledDate,
|
||||
String title,
|
||||
String message,
|
||||
NotificationDetails details,
|
||||
int notificationId,
|
||||
) async {
|
||||
// Initialize and set Cairo timezone
|
||||
tz.initializeTimeZones();
|
||||
var cairoLocation = tz.getLocation('Africa/Cairo');
|
||||
|
||||
final now = tz.TZDateTime.now(cairoLocation);
|
||||
|
||||
// Convert to Cairo time
|
||||
tz.TZDateTime scheduledTZDateTime =
|
||||
tz.TZDateTime.from(scheduledDate, cairoLocation);
|
||||
|
||||
// Check if 10 minutes before the scheduled time is in the past
|
||||
if (scheduledTZDateTime
|
||||
.subtract(const Duration(minutes: 10))
|
||||
.isBefore(now)) {
|
||||
// If the 10 minutes before the scheduled time is in the past, don't schedule
|
||||
print(
|
||||
'Scheduled time minus 10 minutes is in the past. Skipping notification.');
|
||||
return; // Skip this notification
|
||||
}
|
||||
|
||||
print('Current time (Cairo): $now');
|
||||
print('Scheduling notification for: $scheduledTZDateTime');
|
||||
|
||||
await _flutterLocalNotificationsPlugin.zonedSchedule(
|
||||
notificationId, // Unique ID for each notification
|
||||
title,
|
||||
message,
|
||||
scheduledTZDateTime,
|
||||
details,
|
||||
androidScheduleMode: AndroidScheduleMode.exact,
|
||||
uiLocalNotificationDateInterpretation:
|
||||
UILocalNotificationDateInterpretation.absoluteTime,
|
||||
matchDateTimeComponents:
|
||||
null, // Don't repeat automatically; we handle manually
|
||||
);
|
||||
|
||||
print('Notification scheduled successfully for: $scheduledTZDateTime');
|
||||
}
|
||||
|
||||
Future<void> _scheduleNotificationForTime(
|
||||
int dayOffset,
|
||||
int hour,
|
||||
int minute,
|
||||
String title,
|
||||
String message,
|
||||
NotificationDetails details,
|
||||
int notificationId,
|
||||
) async {
|
||||
// Initialize and set Cairo timezone
|
||||
tz.initializeTimeZones();
|
||||
var cairoLocation = tz.getLocation('Africa/Cairo');
|
||||
|
||||
final now = tz.TZDateTime.now(cairoLocation);
|
||||
tz.TZDateTime scheduledDate = tz.TZDateTime(
|
||||
cairoLocation,
|
||||
now.year,
|
||||
now.month,
|
||||
now.day + dayOffset, // Add offset to schedule for the next days
|
||||
hour,
|
||||
minute,
|
||||
);
|
||||
|
||||
// If the scheduled time is in the past, move it to the next day
|
||||
if (scheduledDate.isBefore(now)) {
|
||||
scheduledDate = scheduledDate.add(const Duration(days: 1));
|
||||
}
|
||||
|
||||
print('Current time (Cairo): $now');
|
||||
print('Scheduling notification for: $scheduledDate');
|
||||
|
||||
await _flutterLocalNotificationsPlugin.zonedSchedule(
|
||||
notificationId, // Unique ID for each notification
|
||||
title,
|
||||
message,
|
||||
scheduledDate,
|
||||
details,
|
||||
androidScheduleMode: AndroidScheduleMode.exact,
|
||||
uiLocalNotificationDateInterpretation:
|
||||
UILocalNotificationDateInterpretation.absoluteTime,
|
||||
matchDateTimeComponents:
|
||||
null, // Don't repeat automatically; we handle 7 days manually
|
||||
);
|
||||
|
||||
print('Notification scheduled successfully for: $scheduledDate');
|
||||
}
|
||||
}
|
||||
19
lib/controller/functions/add_error.dart
Normal file
19
lib/controller/functions/add_error.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../main.dart';
|
||||
import 'crud.dart';
|
||||
|
||||
addError(String error, where) async {
|
||||
CRUD().post(link: AppLink.addError, payload: {
|
||||
'error': error.toString(), // Example error description
|
||||
'userId': box.read(BoxName.driverID) ??
|
||||
box.read(BoxName.passengerID), // Example user ID
|
||||
'userType': box.read(BoxName.driverID) != null
|
||||
? 'Driver'
|
||||
: 'passenger', // Example user type
|
||||
'phone': box.read(BoxName.phone) ??
|
||||
box.read(BoxName.phoneDriver), // Example phone number
|
||||
|
||||
'device': where
|
||||
});
|
||||
}
|
||||
166
lib/controller/functions/audio_record1.dart
Normal file
166
lib/controller/functions/audio_record1.dart
Normal file
@@ -0,0 +1,166 @@
|
||||
import 'dart:io';
|
||||
|
||||
// import 'package:flutter_sound/flutter_sound.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
import 'package:record/record.dart';
|
||||
|
||||
class AudioRecorderController extends GetxController {
|
||||
AudioPlayer audioPlayer = AudioPlayer();
|
||||
AudioRecorder recorder = AudioRecorder();
|
||||
|
||||
bool isRecording = false;
|
||||
bool isPlaying = false;
|
||||
bool isPaused = false;
|
||||
String filePath = '';
|
||||
String? selectedFilePath;
|
||||
double currentPosition = 0;
|
||||
double totalDuration = 0;
|
||||
|
||||
Future<void> playSoundFromAssets(String sound) async {
|
||||
try {
|
||||
await audioPlayer.setAsset(sound);
|
||||
audioPlayer.play();
|
||||
} catch (e) {
|
||||
print("Error playing sound: $e");
|
||||
}
|
||||
}
|
||||
|
||||
// Start recording
|
||||
Future<void> startRecording() async {
|
||||
final bool isPermissionGranted = await recorder.hasPermission();
|
||||
if (!isPermissionGranted) {
|
||||
// RecordingPermissionException('l');
|
||||
return;
|
||||
}
|
||||
|
||||
final directory = await getApplicationDocumentsDirectory();
|
||||
// Generate a unique file name using the current timestamp
|
||||
String fileName =
|
||||
// '${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day}_${Get.find<MapPassengerController>().rideId}.m4a';
|
||||
'${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day}.m4a';
|
||||
filePath = '${directory.path}/$fileName';
|
||||
|
||||
// Define the configuration for the recording
|
||||
const config = RecordConfig(
|
||||
// Specify the format, encoder, sample rate, etc., as needed
|
||||
encoder: AudioEncoder.aacLc, // For example, using AAC codec
|
||||
sampleRate: 44100, // Sample rate
|
||||
bitRate: 128000, // Bit rate
|
||||
);
|
||||
|
||||
// Start recording to file with the specified configuration
|
||||
await recorder.start(config, path: filePath);
|
||||
|
||||
isRecording = true;
|
||||
update();
|
||||
}
|
||||
|
||||
// Pause recording
|
||||
Future<void> pauseRecording() async {
|
||||
if (isRecording && !isPaused) {
|
||||
await recorder.pause();
|
||||
isPaused = true;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
// Resume recording
|
||||
Future<void> resumeRecording() async {
|
||||
if (isRecording && isPaused) {
|
||||
await recorder.resume();
|
||||
isPaused = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
// Stop recording
|
||||
Future<void> stopRecording() async {
|
||||
await recorder.stop();
|
||||
isRecording = false;
|
||||
isPaused = false;
|
||||
update();
|
||||
}
|
||||
|
||||
// Play the selected recorded file
|
||||
Future<void> playRecordedFile(String filePath) async {
|
||||
await audioPlayer.setFilePath(filePath);
|
||||
totalDuration = audioPlayer.duration?.inSeconds.toDouble() ?? 0;
|
||||
audioPlayer.play();
|
||||
|
||||
isPlaying = true;
|
||||
isPaused = false;
|
||||
audioPlayer.positionStream.listen((position) {
|
||||
currentPosition = position.inSeconds.toDouble();
|
||||
update();
|
||||
});
|
||||
selectedFilePath = filePath;
|
||||
update();
|
||||
}
|
||||
|
||||
// Pause playback
|
||||
Future<void> pausePlayback() async {
|
||||
if (isPlaying && !isPaused) {
|
||||
await audioPlayer.pause();
|
||||
isPaused = true;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
// Resume playback
|
||||
Future<void> resumePlayback() async {
|
||||
if (isPlaying && isPaused) {
|
||||
await audioPlayer.play();
|
||||
isPaused = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
// Stop playback
|
||||
Future<void> stopPlayback() async {
|
||||
await audioPlayer.stop();
|
||||
isPlaying = false;
|
||||
isPaused = false;
|
||||
currentPosition = 0;
|
||||
update();
|
||||
}
|
||||
|
||||
// Get a list of recorded files
|
||||
Future<List<String>> getRecordedFiles() async {
|
||||
final directory = await getApplicationDocumentsDirectory();
|
||||
final files = await directory.list().toList();
|
||||
return files
|
||||
.map((file) => file.path)
|
||||
.where((path) => path.endsWith('.m4a'))
|
||||
.toList();
|
||||
}
|
||||
|
||||
// Delete a specific recorded file
|
||||
Future<void> deleteRecordedFile(String filePath) async {
|
||||
final file = File(filePath);
|
||||
if (await file.exists()) {
|
||||
await file.delete();
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
// Delete all recorded files
|
||||
Future<void> deleteAllRecordedFiles() async {
|
||||
final directory = await getApplicationDocumentsDirectory();
|
||||
final files = await directory.list().toList();
|
||||
for (final file in files) {
|
||||
if (file.path.endsWith('.m4a')) {
|
||||
await deleteRecordedFile(file.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
audioPlayer.dispose();
|
||||
recorder.dispose();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
134
lib/controller/functions/call_controller.dart
Normal file
134
lib/controller/functions/call_controller.dart
Normal file
@@ -0,0 +1,134 @@
|
||||
// import 'package:SEFER/constant/api_key.dart';
|
||||
// import 'package:SEFER/controller/functions/crud.dart';
|
||||
// import 'package:SEFER/controller/home/map_passenger_controller.dart';
|
||||
// import 'package:agora_rtc_engine/agora_rtc_engine.dart';
|
||||
// import 'package:get/get.dart';
|
||||
// import 'package:permission_handler/permission_handler.dart';
|
||||
|
||||
// import '../../constant/box_name.dart';
|
||||
// import '../firebase/firbase_messge.dart';
|
||||
// import '../../main.dart';
|
||||
|
||||
// class CallController extends GetxController {
|
||||
// String channelName = ''; // Get.find<MapDriverController>().rideId;
|
||||
// String token = '';
|
||||
// // int uid = int.parse(box.read(BoxName.phoneDriver)); // uid of the local user
|
||||
// int uid = 0;
|
||||
// int? remoteUid; // uid of the remote user
|
||||
// bool _isJoined = false; // Indicates if the local user has joined the channel
|
||||
// String status = '';
|
||||
// late RtcEngine agoraEngine; // Agora engine instance
|
||||
|
||||
// @override
|
||||
// void onInit() {
|
||||
// super.onInit();
|
||||
// // if (box.read(BoxName.passengerID) != null) {
|
||||
// channelName = Get.find<MapPassengerController>().rideId; // 'sefer300'; //
|
||||
// remoteUid = int.parse(Get.find<MapPassengerController>().driverPhone);
|
||||
// uid = int.parse(box.read(BoxName.phone));
|
||||
// // } else {
|
||||
// // channelName = Get.find<MapDriverController>().rideId; // 'sefer300'; //
|
||||
// // remoteUid = int.parse(Get.find<MapDriverController>().passengerPhone);
|
||||
// // uid = int.parse(box.read(BoxName.phoneDriver));
|
||||
// // }
|
||||
|
||||
// initAgoraFull();
|
||||
// }
|
||||
|
||||
// initAgoraFull() async {
|
||||
// await fetchToken();
|
||||
// // Set up an instance of Agora engine
|
||||
// setupVoiceSDKEngine();
|
||||
// // join();
|
||||
// FirebaseMessagesController().sendNotificationToPassengerToken(
|
||||
// 'Call Income from Passenger',
|
||||
// '${'You have call from Passenger'.tr} ${box.read(BoxName.name)}',
|
||||
// Get.find<MapPassengerController>().driverToken,
|
||||
// [
|
||||
// token,
|
||||
// channelName,
|
||||
// uid.toString(),
|
||||
// remoteUid.toString(),
|
||||
// ],
|
||||
// 'iphone_ringtone.wav',
|
||||
// );
|
||||
// join();
|
||||
// }
|
||||
|
||||
// @override
|
||||
// void onClose() {
|
||||
// agoraEngine.leaveChannel();
|
||||
// super.onClose();
|
||||
// }
|
||||
|
||||
// Future<void> setupVoiceSDKEngine() async {
|
||||
// // retrieve or request microphone permission
|
||||
// await [Permission.microphone].request();
|
||||
|
||||
// //create an instance of the Agora engine
|
||||
// agoraEngine = createAgoraRtcEngine();
|
||||
// await agoraEngine.initialize(RtcEngineContext(appId: AK.agoraAppId));
|
||||
// // Register the event handler
|
||||
// agoraEngine.registerEventHandler(
|
||||
// RtcEngineEventHandler(
|
||||
// onJoinChannelSuccess: (RtcConnection connection, int elapsed) {
|
||||
// // Get.snackbar(
|
||||
// // "Local user uid:${connection.localUid} joined the channel", '');
|
||||
// status = 'joined'.tr;
|
||||
// _isJoined = true;
|
||||
// update();
|
||||
// },
|
||||
// onUserJoined: (RtcConnection connection, int remoteUid, int elapsed) {
|
||||
// // Get.snackbar("Remote user uid:$remoteUid joined the channel", '');
|
||||
// status = Get.find<MapPassengerController>().driverName.toString();
|
||||
// ' joined'.tr;
|
||||
// remoteUid = remoteUid;
|
||||
// update();
|
||||
// },
|
||||
// onUserOffline: (RtcConnection connection, int? remoteUid,
|
||||
// UserOfflineReasonType reason) {
|
||||
// // Get.snackbar("Remote user uid:$remoteUid left the channel", '');
|
||||
// status = 'Call left'.tr;
|
||||
// remoteUid = null;
|
||||
// update();
|
||||
// },
|
||||
// ),
|
||||
// );
|
||||
// }
|
||||
|
||||
// void join() async {
|
||||
// // Set channel options including the client role and channel profile
|
||||
// ChannelMediaOptions options = const ChannelMediaOptions(
|
||||
// clientRoleType: ClientRoleType.clientRoleBroadcaster,
|
||||
// channelProfile: ChannelProfileType.channelProfileCommunication,
|
||||
// );
|
||||
|
||||
// await agoraEngine.joinChannel(
|
||||
// token: token,
|
||||
// channelId: channelName,
|
||||
// options: options,
|
||||
// uid: uid,
|
||||
// );
|
||||
// }
|
||||
|
||||
// void leave() {
|
||||
// _isJoined = false;
|
||||
// remoteUid = null;
|
||||
// update();
|
||||
// agoraEngine.leaveChannel();
|
||||
// }
|
||||
|
||||
// // Clean up the resources when you leave
|
||||
// @override
|
||||
// void dispose() async {
|
||||
// await agoraEngine.leaveChannel();
|
||||
// super.dispose();
|
||||
// }
|
||||
|
||||
// fetchToken() async {
|
||||
// var res = await CRUD()
|
||||
// .getAgoraToken(channelName: channelName, uid: uid.toString());
|
||||
// token = res;
|
||||
// update();
|
||||
// }
|
||||
// }
|
||||
709
lib/controller/functions/crud.dart
Normal file
709
lib/controller/functions/crud.dart
Normal file
@@ -0,0 +1,709 @@
|
||||
import 'dart:convert';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/auth/login_controller.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:Intaleq/env/env.dart';
|
||||
|
||||
import '../../constant/api_key.dart';
|
||||
|
||||
import '../../print.dart';
|
||||
import '../../views/widgets/elevated_btn.dart';
|
||||
import '../../views/widgets/error_snakbar.dart';
|
||||
import 'add_error.dart';
|
||||
import 'encrypt_decrypt.dart';
|
||||
import 'upload_image.dart';
|
||||
|
||||
class CRUD {
|
||||
Future<dynamic> get({
|
||||
required String link,
|
||||
Map<String, dynamic>? payload,
|
||||
}) async {
|
||||
// print(r(box.read(BoxName.jwt)).toString().split(Env.addd)[0]);
|
||||
var url = Uri.parse(
|
||||
link,
|
||||
);
|
||||
var response = await http.post(
|
||||
url,
|
||||
body: payload,
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
'Authorization':
|
||||
'Bearer ${r(box.read(BoxName.jwt)).toString().split(Env.addd)[0]}'
|
||||
},
|
||||
);
|
||||
// print('req: ${response.request}');
|
||||
// Log.print('response: ${response.body}');
|
||||
// Log.print('payload: ${payload}');
|
||||
if (response.statusCode == 200) {
|
||||
var jsonData = jsonDecode(response.body);
|
||||
if (jsonData['status'] == 'success') {
|
||||
return response.body;
|
||||
}
|
||||
|
||||
return jsonData['status'];
|
||||
} else if (response.statusCode == 401) {
|
||||
// Specifically handle 401 Unauthorized
|
||||
var jsonData = jsonDecode(response.body);
|
||||
|
||||
if (jsonData['error'] == 'Token expired') {
|
||||
// Show snackbar prompting to re-login
|
||||
await Get.put(LoginController()).getJWT();
|
||||
mySnackbarSuccess('please order now'.tr);
|
||||
return 'token_expired'; // Return a specific value for token expiration
|
||||
} else {
|
||||
// Other 401 errors
|
||||
addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
|
||||
return 'failure';
|
||||
}
|
||||
} else {
|
||||
addError('Non-200 response code: ${response.statusCode}',
|
||||
'crud().post - Other');
|
||||
return 'failure';
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> getWallet({
|
||||
required String link,
|
||||
Map<String, dynamic>? payload,
|
||||
}) async {
|
||||
var s = await LoginController().getJwtWallet();
|
||||
final hmac = box.read(BoxName.hmac);
|
||||
// Log.print('hmac: ${hmac}');
|
||||
var url = Uri.parse(
|
||||
link,
|
||||
);
|
||||
var response = await http.post(
|
||||
url,
|
||||
body: payload,
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
'Authorization': 'Bearer $s',
|
||||
'X-HMAC-Auth': hmac.toString(),
|
||||
},
|
||||
);
|
||||
// print('req: ${response.request}');
|
||||
// Log.print('response: ${response.body}');
|
||||
// Log.print('payload: ${payload}');
|
||||
if (response.statusCode == 200) {
|
||||
var jsonData = jsonDecode(response.body);
|
||||
Log.print('jsonData: $jsonData');
|
||||
if (jsonData['status'] == 'success') {
|
||||
return response.body;
|
||||
}
|
||||
|
||||
return jsonData['status'];
|
||||
} else if (response.statusCode == 401) {
|
||||
// Specifically handle 401 Unauthorized
|
||||
var jsonData = jsonDecode(response.body);
|
||||
|
||||
if (jsonData['error'] == 'Token expired') {
|
||||
// Show snackbar prompting to re-login
|
||||
await Get.put(LoginController()).getJwtWallet();
|
||||
|
||||
return 'token_expired'; // Return a specific value for token expiration
|
||||
} else {
|
||||
// Other 401 errors
|
||||
addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
|
||||
return 'failure';
|
||||
}
|
||||
} else {
|
||||
addError('Non-200 response code: ${response.statusCode}',
|
||||
'crud().post - Other');
|
||||
return 'failure';
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> post(
|
||||
{required String link, Map<String, dynamic>? payload}) async {
|
||||
var url = Uri.parse(link);
|
||||
try {
|
||||
var response = await http.post(
|
||||
url,
|
||||
body: payload,
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
'Authorization':
|
||||
'Bearer ${r(box.read(BoxName.jwt)).toString().split(Env.addd)[0]}'
|
||||
},
|
||||
);
|
||||
// Log.print('req: ${response.request}');
|
||||
// Log.print('response: ${response.body}');
|
||||
// Log.print('payload: ${payload}');
|
||||
if (response.statusCode == 200) {
|
||||
try {
|
||||
var jsonData = jsonDecode(response.body);
|
||||
if (jsonData['status'] == 'success') {
|
||||
return jsonData;
|
||||
} else {
|
||||
return jsonData['status'];
|
||||
}
|
||||
} catch (e) {
|
||||
// addError(e.toString(), 'crud().post - JSON decoding');
|
||||
return 'failure';
|
||||
}
|
||||
} else if (response.statusCode == 401) {
|
||||
// Specifically handle 401 Unauthorized
|
||||
var jsonData = jsonDecode(response.body);
|
||||
|
||||
if (jsonData['error'] == 'Token expired') {
|
||||
// Show snackbar prompting to re-login
|
||||
await Get.put(LoginController()).getJWT();
|
||||
// MyDialog().getDialog(
|
||||
// 'Session expired. Please log in again.'.tr,
|
||||
// '',
|
||||
// () {
|
||||
// Get.put(LoginController()).loginUsingCredentials(
|
||||
// box.read(BoxName.passengerID), box.read(BoxName.email));
|
||||
// Get.back();
|
||||
// },
|
||||
// );
|
||||
|
||||
return 'token_expired'; // Return a specific value for token expiration
|
||||
} else {
|
||||
// Other 401 errors
|
||||
// addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
|
||||
return 'failure';
|
||||
}
|
||||
} else {
|
||||
// addError('Non-200 response code: ${response.statusCode}',
|
||||
// 'crud().post - Other');
|
||||
return 'failure';
|
||||
}
|
||||
} catch (e) {
|
||||
// addError('HTTP request error: $e', 'crud().post - HTTP');
|
||||
return 'failure';
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> postWallet(
|
||||
{required String link, Map<String, dynamic>? payload}) async {
|
||||
var s = await LoginController().getJwtWallet();
|
||||
|
||||
final hmac = box.read(BoxName.hmac);
|
||||
|
||||
var url = Uri.parse(link);
|
||||
try {
|
||||
var response = await http.post(
|
||||
url,
|
||||
body: payload,
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
'Authorization': 'Bearer $s',
|
||||
'X-HMAC-Auth': hmac.toString(),
|
||||
},
|
||||
);
|
||||
// print('req: ${response.request}');
|
||||
// Log.print('response: ${response.body}');
|
||||
// Log.print('payload: ${payload}');
|
||||
if (response.statusCode == 200) {
|
||||
try {
|
||||
var jsonData = jsonDecode(response.body);
|
||||
if (jsonData['status'] == 'success') {
|
||||
return jsonData;
|
||||
} else {
|
||||
return jsonData['status'];
|
||||
}
|
||||
} catch (e) {
|
||||
addError(e.toString(), 'crud().post - JSON decoding');
|
||||
return 'failure';
|
||||
}
|
||||
} else if (response.statusCode == 401) {
|
||||
// Specifically handle 401 Unauthorized
|
||||
var jsonData = jsonDecode(response.body);
|
||||
|
||||
if (jsonData['error'] == 'Token expired') {
|
||||
// Show snackbar prompting to re-login
|
||||
await Get.put(LoginController()).getJWT();
|
||||
// MyDialog().getDialog(
|
||||
// 'Session expired. Please log in again.'.tr,
|
||||
// '',
|
||||
// () {
|
||||
// Get.put(LoginController()).loginUsingCredentials(
|
||||
// box.read(BoxName.passengerID), box.read(BoxName.email));
|
||||
// Get.back();
|
||||
// },
|
||||
// );
|
||||
|
||||
return 'token_expired'; // Return a specific value for token expiration
|
||||
} else {
|
||||
// Other 401 errors
|
||||
// addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
|
||||
return 'failure';
|
||||
}
|
||||
} else {
|
||||
// addError('Non-200 response code: ${response.statusCode}',
|
||||
// 'crud().post - Other');
|
||||
return 'failure';
|
||||
}
|
||||
} catch (e) {
|
||||
// addError('HTTP request error: $e', 'crud().post - HTTP');
|
||||
return 'failure';
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> getTokenParent({
|
||||
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 jsonData;
|
||||
// }
|
||||
|
||||
// return jsonData['status'];
|
||||
}
|
||||
}
|
||||
|
||||
Future sendWhatsAppAuth(String to, String token) async {
|
||||
var res = await CRUD()
|
||||
.get(link: AppLink.getApiKey, payload: {'keyName': 'whatsapp_key'});
|
||||
var accesstoken = jsonDecode(res)['message']['whatsapp_key'];
|
||||
var headers = {
|
||||
'Authorization': 'Bearer $accesstoken',
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
|
||||
var url = 'https://graph.facebook.com/v20.0/${Env.whatappID}/messages';
|
||||
var request = http.Request('POST', Uri.parse(url));
|
||||
|
||||
var body = json.encode({
|
||||
"messaging_product": "whatsapp",
|
||||
"to": to,
|
||||
"type": "template",
|
||||
"template": {
|
||||
"name": "sefer1",
|
||||
"language": {"code": "en"},
|
||||
"components": [
|
||||
{
|
||||
"type": "body",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": token,
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
request.body = body;
|
||||
request.headers.addAll(headers);
|
||||
|
||||
try {
|
||||
http.StreamedResponse response = await request.send();
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
String responseBody = await response.stream.bytesToString();
|
||||
|
||||
Get.defaultDialog(
|
||||
title: 'You will receive a code in WhatsApp Messenger'.tr,
|
||||
middleText: 'wait 1 minute to recive message'.tr,
|
||||
confirm: MyElevatedButton(
|
||||
title: 'OK'.tr,
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
},
|
||||
),
|
||||
);
|
||||
} else {
|
||||
String errorBody = await response.stream.bytesToString();
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
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'),
|
||||
'https://orca-app-b2i85.ondigitalocean.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));
|
||||
String extracted =
|
||||
await arabicTextExtractByVisionAndAI(imagePath: imagePath);
|
||||
// await AI().geminiAiExtraction(prompt, extracted);
|
||||
}
|
||||
|
||||
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) ?? box.read(BoxName.passengerID)}.jpg';
|
||||
|
||||
var requestBody = {"url": imagePathFull};
|
||||
var response = await http.post(
|
||||
url,
|
||||
body: jsonEncode(requestBody), // Encode the JSON object to a string
|
||||
headers: headers,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
var responseBody = jsonDecode(response.body);
|
||||
return responseBody.toString();
|
||||
}
|
||||
return response.statusCode;
|
||||
}
|
||||
|
||||
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> 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
|
||||
final 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,
|
||||
);
|
||||
// Log.print('req: ${response.request}');
|
||||
// Log.print('response: ${response.body}');
|
||||
// Log.print('payload: ${payload}');
|
||||
var jsonData = jsonDecode(response.body);
|
||||
if (jsonData['status'] == 'OK') {
|
||||
return jsonData;
|
||||
}
|
||||
return (jsonData['status']);
|
||||
}
|
||||
|
||||
Future<dynamic> getHereMap({
|
||||
required String link,
|
||||
}) async {
|
||||
var url = Uri.parse(link);
|
||||
try {
|
||||
var response = await http.get(url);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
// Ensure the response body is decoded as UTF-8
|
||||
var decodedBody = utf8.decode(response.bodyBytes);
|
||||
var data = jsonDecode(decodedBody);
|
||||
return data;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
26
lib/controller/functions/custom_pant.dart
Normal file
26
lib/controller/functions/custom_pant.dart
Normal 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;
|
||||
}
|
||||
92
lib/controller/functions/device_info.dart
Normal file
92
lib/controller/functions/device_info.dart
Normal file
@@ -0,0 +1,92 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
|
||||
import '../../print.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,
|
||||
};
|
||||
// Log.print('deviceData: ${deviceData}');
|
||||
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'}';
|
||||
}
|
||||
}
|
||||
}
|
||||
42
lib/controller/functions/digit_obsecur_formate.dart
Normal file
42
lib/controller/functions/digit_obsecur_formate.dart
Normal 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);
|
||||
// }
|
||||
// }
|
||||
78
lib/controller/functions/encrypt_decrypt.dart
Normal file
78
lib/controller/functions/encrypt_decrypt.dart
Normal file
@@ -0,0 +1,78 @@
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/env/env.dart';
|
||||
import 'package:encrypt/encrypt.dart' as encrypt;
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:secure_string_operations/secure_string_operations.dart';
|
||||
|
||||
import '../../constant/char_map.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.dart';
|
||||
|
||||
class EncryptionHelper {
|
||||
static EncryptionHelper? _instance;
|
||||
|
||||
late final encrypt.Key key;
|
||||
late final encrypt.IV iv;
|
||||
|
||||
EncryptionHelper._(this.key, this.iv);
|
||||
static EncryptionHelper get instance {
|
||||
if (_instance == null) {
|
||||
throw Exception(
|
||||
"EncryptionHelper is not initialized. Call `await EncryptionHelper.initialize()` in main.");
|
||||
}
|
||||
return _instance!;
|
||||
}
|
||||
|
||||
/// Initializes and stores the instance globally
|
||||
static Future<void> initialize() async {
|
||||
if (_instance != null) {
|
||||
debugPrint("EncryptionHelper is already initialized.");
|
||||
return; // Prevent re-initialization
|
||||
}
|
||||
debugPrint("Initializing EncryptionHelper...");
|
||||
var keyOfApp = r(Env.keyOfApp).toString().split(Env.addd)[0];
|
||||
var initializationVector =
|
||||
r(Env.initializationVector).toString().split(Env.addd)[0];
|
||||
|
||||
// Set the global instance
|
||||
_instance = EncryptionHelper._(
|
||||
encrypt.Key.fromUtf8(keyOfApp!),
|
||||
encrypt.IV.fromUtf8(initializationVector!),
|
||||
);
|
||||
debugPrint("EncryptionHelper initialized successfully.");
|
||||
}
|
||||
|
||||
/// Encrypts a string
|
||||
String encryptData(String plainText) {
|
||||
try {
|
||||
final encrypter =
|
||||
encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
|
||||
final encrypted = encrypter.encrypt(plainText, iv: iv);
|
||||
return encrypted.base64;
|
||||
} catch (e) {
|
||||
debugPrint('Encryption Error: $e');
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/// Decrypts a string
|
||||
String decryptData(String encryptedText) {
|
||||
try {
|
||||
final encrypter =
|
||||
encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
|
||||
final encrypted = encrypt.Encrypted.fromBase64(encryptedText);
|
||||
return encrypter.decrypt(encrypted, iv: iv);
|
||||
} catch (e) {
|
||||
debugPrint('Decryption Error: $e');
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
r(String string) {
|
||||
return X.r(X.r(X.r(string, cn), cC), cs).toString();
|
||||
}
|
||||
|
||||
c(String string) {
|
||||
return X.c(X.c(X.c(string, cn), cC), cs).toString();
|
||||
}
|
||||
34
lib/controller/functions/geolocation.dart
Normal file
34
lib/controller/functions/geolocation.dart
Normal file
@@ -0,0 +1,34 @@
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
|
||||
class GeoLocation {
|
||||
Future<Position> getCurrentLocation() async {
|
||||
bool serviceEnabled;
|
||||
LocationPermission permission;
|
||||
|
||||
// Check if location services are enabled.
|
||||
serviceEnabled = await Geolocator.isLocationServiceEnabled();
|
||||
if (!serviceEnabled) {
|
||||
// Location services are not enabled, so we request the user to enable it.
|
||||
return Future.error('Location services are disabled.');
|
||||
}
|
||||
|
||||
permission = await Geolocator.checkPermission();
|
||||
if (permission == LocationPermission.denied) {
|
||||
permission = await Geolocator.requestPermission();
|
||||
if (permission == LocationPermission.denied) {
|
||||
// Permissions are denied, we cannot fetch the location.
|
||||
return Future.error('Location permissions are denied');
|
||||
}
|
||||
}
|
||||
|
||||
if (permission == LocationPermission.deniedForever) {
|
||||
// Permissions are denied forever, we cannot request permissions.
|
||||
return Future.error(
|
||||
'Location permissions are permanently denied, we cannot request permissions.');
|
||||
}
|
||||
|
||||
// When we reach here, permissions are granted and we can fetch the location.
|
||||
return await Geolocator.getCurrentPosition(
|
||||
desiredAccuracy: LocationAccuracy.high);
|
||||
}
|
||||
}
|
||||
77
lib/controller/functions/launch.dart
Normal file
77
lib/controller/functions/launch.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'dart:io';
|
||||
|
||||
void showInBrowser(String url) async {
|
||||
if (await canLaunchUrl(Uri.parse(url))) {
|
||||
launchUrl(Uri.parse(url));
|
||||
} else {}
|
||||
}
|
||||
|
||||
Future<void> makePhoneCall(String phoneNumber) async {
|
||||
final Uri launchUri = Uri(
|
||||
scheme: 'tel',
|
||||
path: phoneNumber,
|
||||
);
|
||||
await launchUrl(launchUri);
|
||||
}
|
||||
|
||||
void launchCommunication(
|
||||
String method, String contactInfo, String message) async {
|
||||
String url;
|
||||
|
||||
if (Platform.isIOS) {
|
||||
switch (method) {
|
||||
case 'phone':
|
||||
url = 'tel:$contactInfo';
|
||||
break;
|
||||
case 'sms':
|
||||
url = 'sms:$contactInfo?body=${Uri.encodeComponent(message)}';
|
||||
break;
|
||||
case 'whatsapp':
|
||||
url =
|
||||
'https://api.whatsapp.com/send?phone=$contactInfo&text=${Uri.encodeComponent(message)}';
|
||||
break;
|
||||
case 'email':
|
||||
url =
|
||||
'mailto:$contactInfo?subject=Subject&body=${Uri.encodeComponent(message)}';
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
} else if (Platform.isAndroid) {
|
||||
switch (method) {
|
||||
case 'phone':
|
||||
url = 'tel:$contactInfo';
|
||||
break;
|
||||
|
||||
case 'sms':
|
||||
url = 'sms:$contactInfo?body=${Uri.encodeComponent(message)}';
|
||||
break;
|
||||
case 'whatsapp':
|
||||
// Check if WhatsApp is installed
|
||||
final bool whatsappInstalled =
|
||||
await canLaunchUrl(Uri.parse('whatsapp://'));
|
||||
if (whatsappInstalled) {
|
||||
url =
|
||||
'whatsapp://send?phone=$contactInfo&text=${Uri.encodeComponent(message)}';
|
||||
} else {
|
||||
// Provide an alternative action, such as opening the WhatsApp Web API
|
||||
url =
|
||||
'https://api.whatsapp.com/send?phone=$contactInfo&text=${Uri.encodeComponent(message)}';
|
||||
}
|
||||
break;
|
||||
case 'email':
|
||||
url =
|
||||
'mailto:$contactInfo?subject=Subject&body=${Uri.encodeComponent(message)}';
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if (await canLaunchUrl(Uri.parse(url))) {
|
||||
await launchUrl(Uri.parse(url));
|
||||
} else {}
|
||||
}
|
||||
148
lib/controller/functions/location_controller.dart
Normal file
148
lib/controller/functions/location_controller.dart
Normal file
@@ -0,0 +1,148 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'package:location/location.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/controller/home/payment/captain_wallet_controller.dart';
|
||||
import 'package:Intaleq/main.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();
|
||||
|
||||
totalPoints = Get.put(CaptainWalletController()).totalPoints;
|
||||
}
|
||||
|
||||
Future<void> startLocationUpdates() async {
|
||||
if (box.read(BoxName.driverID) != null) {
|
||||
_locationTimer =
|
||||
Timer.periodic(const Duration(seconds: 5), (timer) async {
|
||||
try {
|
||||
totalPoints = Get.find<CaptainWalletController>().totalPoints;
|
||||
|
||||
// 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!;
|
||||
// Calculate the distance between the current location and the previous location
|
||||
// if (Get.find<HomeCaptainController>().rideId == 'rideId') {
|
||||
// if (previousTime > 0) {
|
||||
// double distance = calculateDistanceInKmPerHour(
|
||||
// previousTime, _locationData.time, speed);
|
||||
// totalDistance += distance;
|
||||
// }
|
||||
|
||||
// previousTime = _locationData.time!;
|
||||
// }
|
||||
// Print location details
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
16
lib/controller/functions/location_permission.dart
Normal file
16
lib/controller/functions/location_permission.dart
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
184
lib/controller/functions/log_out.dart
Normal file
184
lib/controller/functions/log_out.dart
Normal file
@@ -0,0 +1,184 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/colors.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:Intaleq/onbording_page.dart';
|
||||
import 'package:Intaleq/views/widgets/elevated_btn.dart';
|
||||
import 'package:Intaleq/views/widgets/my_textField.dart';
|
||||
|
||||
import '../../constant/style.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.passengerPhotoUrl);
|
||||
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);
|
||||
box.remove(BoxName.isVerified);
|
||||
Get.offAll(OnBoardingPage());
|
||||
},
|
||||
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(OnBoardingPage());
|
||||
},
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
351
lib/controller/functions/package_info.dart
Normal file
351
lib/controller/functions/package_info.dart
Normal file
@@ -0,0 +1,351 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:ui';
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:jailbreak_root_detection/jailbreak_root_detection.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/colors.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.dart';
|
||||
import 'encrypt_decrypt.dart';
|
||||
|
||||
Future<void> checkForUpdate(BuildContext context) async {
|
||||
final packageInfo = await PackageInfo.fromPlatform();
|
||||
final currentVersion = packageInfo.buildNumber;
|
||||
final version = packageInfo.version;
|
||||
print('currentVersion is : $currentVersion');
|
||||
// Fetch the latest version from your server
|
||||
String latestVersion = box.read(BoxName.package);
|
||||
box.write(BoxName.packagInfo, version);
|
||||
|
||||
if (latestVersion.isNotEmpty && latestVersion != currentVersion) {
|
||||
showUpdateDialog(context);
|
||||
}
|
||||
}
|
||||
|
||||
checkForBounusInvitation() {
|
||||
if (box.read(BoxName.inviteCode) != null) {}
|
||||
}
|
||||
|
||||
// Future<String> getPackageInfo() async {
|
||||
// final response = await CRUD().get(link: AppLink.packageInfo, payload: {
|
||||
// "platform": Platform.isAndroid ? 'android' : 'ios',
|
||||
// "appName": AppInformation.appName,
|
||||
// });
|
||||
|
||||
// if (response != 'failure') {
|
||||
// return jsonDecode(response)['message'][0]['version'];
|
||||
// }
|
||||
// return '';
|
||||
// }
|
||||
// getDeviceFingerprint() async {
|
||||
// final deviceInfo = await DeviceInfoPlugin().deviceInfo;
|
||||
// var deviceData;
|
||||
|
||||
// if (Platform.isAndroid) {
|
||||
// deviceData = deviceInfo.data;
|
||||
// Log.print('deviceData: ${jsonEncode(deviceData)}');
|
||||
// } else if (Platform.isIOS) {
|
||||
// deviceData = deviceInfo.data;
|
||||
// }
|
||||
|
||||
// final String deviceId =
|
||||
// deviceData['device'] ?? deviceData['identifierForVendor'];
|
||||
// final String deviceModel = deviceData['model'];
|
||||
// final String osVersion = deviceData['systemVersion'];
|
||||
|
||||
// Log.print('fingr: ${'${deviceId}_${deviceModel}_$osVersion'}');
|
||||
// Log.print('deviceModel: ${deviceModel}');
|
||||
// Log.print('osVersion: ${osVersion}');
|
||||
// return EncryptionHelper.instance
|
||||
// .encryptData('${deviceId}_${deviceModel}_$osVersion');
|
||||
// }
|
||||
|
||||
void showUpdateDialog(BuildContext context) {
|
||||
final String storeUrl = Platform.isAndroid
|
||||
? 'https://play.google.com/store/apps/details?id=com.Intaleq.intaleq'
|
||||
: 'https://apps.apple.com/jo/app/intaleq-rider/id6748075179';
|
||||
showGeneralDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
barrierColor: Colors.black.withOpacity(0.5),
|
||||
pageBuilder: (_, __, ___) {
|
||||
return BackdropFilter(
|
||||
filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
|
||||
child: Center(
|
||||
child: AlertDialog(
|
||||
// Using AlertDialog for a more Material Design look
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius:
|
||||
BorderRadius.circular(16)), // More rounded corners
|
||||
elevation: 4, // Add a bit more elevation
|
||||
contentPadding: EdgeInsets.zero, // Remove default content padding
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 20.0),
|
||||
child: Image.asset(
|
||||
'assets/images/logo.png',
|
||||
height: 72, // Slightly larger logo
|
||||
width: 72,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24.0),
|
||||
child: Text(
|
||||
'Update Available'.tr,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
// Use theme's title style
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Text(
|
||||
'A new version of the app is available. Please update to the latest version.'
|
||||
.tr, // More encouraging message
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
// Use theme's body style
|
||||
color: Colors.black87,
|
||||
),
|
||||
),
|
||||
),
|
||||
const Divider(height: 0),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextButton(
|
||||
// Using TextButton for "Cancel"
|
||||
onPressed: () => Navigator.pop(context),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Colors.grey,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.only(
|
||||
bottomLeft: Radius.circular(16),
|
||||
),
|
||||
),
|
||||
),
|
||||
child: Text('Cancel'.tr),
|
||||
),
|
||||
),
|
||||
const SizedBox(
|
||||
height: 48,
|
||||
child: VerticalDivider(width: 0), // Using VerticalDivider
|
||||
),
|
||||
Expanded(
|
||||
child: ElevatedButton(
|
||||
// Using ElevatedButton for "Update"
|
||||
onPressed: () async {
|
||||
if (await canLaunchUrl(Uri.parse(storeUrl))) {
|
||||
await launchUrl(Uri.parse(storeUrl));
|
||||
}
|
||||
if (context.mounted) Navigator.pop(context);
|
||||
},
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColor
|
||||
.primaryColor, // Use theme's primary color
|
||||
foregroundColor: Theme.of(context)
|
||||
.colorScheme
|
||||
.onPrimary, // Use theme's onPrimary color
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.only(
|
||||
bottomRight: Radius.circular(16),
|
||||
),
|
||||
),
|
||||
),
|
||||
child: Text('Update'.tr),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
transitionBuilder: (_, animation, __, child) {
|
||||
return ScaleTransition(
|
||||
scale: CurvedAnimation(
|
||||
parent: animation,
|
||||
curve: Curves.easeOutCubic, // More natural curve
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class SecurityHelper {
|
||||
/// Performs security checks and handles potential risks
|
||||
static Future<void> performSecurityChecks() async {
|
||||
bool isNotTrust = false;
|
||||
bool isJailBroken = false;
|
||||
bool isRealDevice = true;
|
||||
bool isOnExternalStorage = false;
|
||||
bool checkForIssues = false;
|
||||
bool isDevMode = false;
|
||||
bool isTampered = false;
|
||||
String bundleId = "";
|
||||
|
||||
try {
|
||||
isNotTrust = await JailbreakRootDetection.instance.isNotTrust;
|
||||
isJailBroken = await JailbreakRootDetection.instance.isJailBroken;
|
||||
isRealDevice = await JailbreakRootDetection.instance.isRealDevice;
|
||||
isOnExternalStorage =
|
||||
await JailbreakRootDetection.instance.isOnExternalStorage;
|
||||
|
||||
List<JailbreakIssue> issues =
|
||||
await JailbreakRootDetection.instance.checkForIssues;
|
||||
checkForIssues = issues.isNotEmpty;
|
||||
|
||||
isDevMode = await JailbreakRootDetection.instance.isDevMode;
|
||||
|
||||
// Get Bundle ID
|
||||
PackageInfo packageInfo = await PackageInfo.fromPlatform();
|
||||
bundleId = packageInfo.packageName;
|
||||
if (bundleId.isNotEmpty) {
|
||||
// Pass the CORRECT bundle ID to isTampered
|
||||
isTampered = await JailbreakRootDetection.instance.isTampered(bundleId);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint("Error during security checks: $e");
|
||||
// Consider handling specific exceptions, not just general errors.
|
||||
}
|
||||
|
||||
// Save values to storage (using GetStorage)
|
||||
await box.write('isNotTrust', isNotTrust); // Use await for write operations
|
||||
await box.write('isTampered', isTampered); // Use await
|
||||
await box.write('isJailBroken', isJailBroken); // Use await
|
||||
|
||||
debugPrint("Security Check Results:");
|
||||
debugPrint("isNotTrust: $isNotTrust");
|
||||
debugPrint("isJailBroken: $isJailBroken");
|
||||
debugPrint("isRealDevice: $isRealDevice");
|
||||
debugPrint("isOnExternalStorage: $isOnExternalStorage");
|
||||
debugPrint("checkForIssues: $checkForIssues");
|
||||
debugPrint("isDevMode: $isDevMode");
|
||||
debugPrint("isTampered: $isTampered");
|
||||
debugPrint("Bundle ID: $bundleId"); // Print the bundle ID
|
||||
|
||||
// Check for security risks and potentially show a warning
|
||||
if (isJailBroken || isRealDevice == false || isTampered) {
|
||||
// print("security_warning".tr); //using easy_localization
|
||||
// Use a more robust approach to show a warning, like a dialog:
|
||||
_showSecurityWarning();
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes all app data
|
||||
static void _showSecurityWarning() {
|
||||
// Use an RxInt to track the remaining seconds. This is the KEY!
|
||||
RxInt secondsRemaining = 10.obs;
|
||||
|
||||
Get.dialog(
|
||||
CupertinoAlertDialog(
|
||||
title: Text("Security Warning".tr),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Obx(() => Text(
|
||||
"Potential security risks detected. The application will close in @seconds seconds."
|
||||
.trParams({
|
||||
// Use trParams for placeholders
|
||||
'seconds': secondsRemaining.value.toString(),
|
||||
}),
|
||||
// Wrap the Text widget in Obx
|
||||
)),
|
||||
SizedBox(height: 24), // More spacing before the progress bar
|
||||
Obx(() => SizedBox(
|
||||
width: double.infinity, // Make progress bar full width
|
||||
child: CupertinoActivityIndicator(
|
||||
// in case of loading
|
||||
radius: 15,
|
||||
animating: true,
|
||||
))),
|
||||
SizedBox(height: 8),
|
||||
Obx(() => ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8), // Rounded corners
|
||||
child: LinearProgressIndicator(
|
||||
value: secondsRemaining.value / 10,
|
||||
backgroundColor: Colors.grey.shade300, // Lighter background
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
CupertinoColors.systemRed), // iOS-style red
|
||||
minHeight: 8, // Slightly thicker progress bar
|
||||
),
|
||||
)),
|
||||
],
|
||||
),
|
||||
),
|
||||
barrierDismissible: false,
|
||||
);
|
||||
|
||||
Timer.periodic(Duration(seconds: 1), (timer) {
|
||||
secondsRemaining.value--;
|
||||
if (secondsRemaining.value <= 0) {
|
||||
timer.cancel();
|
||||
// Get.back();
|
||||
_clearDataAndExit();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static Future<void> _clearDataAndExit() async {
|
||||
await storage.deleteAll();
|
||||
await box.erase();
|
||||
exit(0); // Exit the app
|
||||
print('exit');
|
||||
}
|
||||
}
|
||||
|
||||
class DeviceHelper {
|
||||
static Future<String> getDeviceFingerprint() async {
|
||||
final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
|
||||
var deviceData;
|
||||
|
||||
try {
|
||||
if (Platform.isAndroid) {
|
||||
// Fetch Android-specific device information
|
||||
AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
|
||||
deviceData = androidInfo.toMap(); // Convert to a map for easier access
|
||||
// Log.print('deviceData: ${jsonEncode(deviceData)}');
|
||||
} else if (Platform.isIOS) {
|
||||
// Fetch iOS-specific device information
|
||||
IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
|
||||
deviceData = iosInfo.toMap(); // Convert to a map for easier access
|
||||
} else {
|
||||
throw UnsupportedError('Unsupported platform');
|
||||
}
|
||||
|
||||
// Extract relevant device information
|
||||
final String deviceId = Platform.isAndroid
|
||||
? deviceData['androidId'] ?? deviceData['serialNumber'] ?? 'unknown'
|
||||
: deviceData['identifierForVendor'] ?? 'unknown';
|
||||
|
||||
final String deviceModel = deviceData['model'] ?? 'unknown';
|
||||
final String osVersion = Platform.isAndroid
|
||||
? deviceData['version']['release'] ?? 'unknown'
|
||||
: deviceData['systemVersion'] ?? 'unknown';
|
||||
|
||||
// Log the extracted information
|
||||
|
||||
// Generate and return the encrypted fingerprint
|
||||
final String fingerprint = '${deviceId}_${deviceModel}_$osVersion';
|
||||
// print(EncryptionHelper.instance.encryptData(fingerprint));
|
||||
return EncryptionHelper.instance.encryptData(fingerprint);
|
||||
} catch (e) {
|
||||
throw Exception('Failed to generate device fingerprint');
|
||||
}
|
||||
}
|
||||
}
|
||||
8
lib/controller/functions/remove_account.dart
Normal file
8
lib/controller/functions/remove_account.dart
Normal file
@@ -0,0 +1,8 @@
|
||||
// import 'package:ride/controller/functions/crud.dart';
|
||||
|
||||
// class RemoveAccount {
|
||||
|
||||
// void removeAccount()async{
|
||||
// var res=await CRUD().post(link: link)
|
||||
// }
|
||||
// }
|
||||
25
lib/controller/functions/scan_id_card.dart
Normal file
25
lib/controller/functions/scan_id_card.dart
Normal 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();
|
||||
// }
|
||||
// }
|
||||
85
lib/controller/functions/secure_storage.dart
Normal file
85
lib/controller/functions/secure_storage.dart
Normal file
@@ -0,0 +1,85 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/info.dart';
|
||||
import 'package:Intaleq/controller/auth/login_controller.dart';
|
||||
import 'package:jwt_decoder/jwt_decoder.dart';
|
||||
import 'package:secure_string_operations/secure_string_operations.dart';
|
||||
|
||||
import '../../constant/char_map.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.dart';
|
||||
import 'crud.dart';
|
||||
import 'encrypt_decrypt.dart';
|
||||
|
||||
class SecureStorage {
|
||||
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.toString();
|
||||
}
|
||||
}
|
||||
|
||||
const List<String> keysToFetch = [
|
||||
'serverPHP',
|
||||
'seferAlexandriaServer',
|
||||
'seferPaymentServer',
|
||||
'seferCairoServer',
|
||||
'seferGizaServer',
|
||||
];
|
||||
|
||||
class AppInitializer {
|
||||
List<Map<String, dynamic>> links = [];
|
||||
|
||||
Future<void> initializeApp() async {
|
||||
if (box.read(BoxName.jwt) == null) {
|
||||
await LoginController().getJWT();
|
||||
} else {
|
||||
bool isTokenExpired = JwtDecoder.isExpired(X
|
||||
.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
|
||||
.toString()
|
||||
.split(AppInformation.addd)[0]);
|
||||
if (isTokenExpired) {
|
||||
await LoginController().getJWT();
|
||||
}
|
||||
}
|
||||
|
||||
// await getKey();
|
||||
}
|
||||
|
||||
getAIKey(String key1) async {
|
||||
if (box.read(BoxName.firstTimeLoadKey) == null) {
|
||||
var res =
|
||||
await CRUD().get(link: AppLink.getapiKey, payload: {"keyName": key1});
|
||||
if (res != 'failure') {
|
||||
var d = jsonDecode(res)['message'];
|
||||
storage.write(key: key1, value: d[key1].toString());
|
||||
} else {}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> getKey() async {
|
||||
try {
|
||||
var res =
|
||||
await CRUD().get(link: AppLink.getLocationAreaLinks, payload: {});
|
||||
if (res != 'failure') {
|
||||
links = List<Map<String, dynamic>>.from(jsonDecode(res)['message']);
|
||||
await box.remove(BoxName.locationName);
|
||||
await box.remove(BoxName.basicLink);
|
||||
await box.remove(links[4]['name']);
|
||||
await box.remove(links[1]['name']);
|
||||
await box.remove(links[2]['name']);
|
||||
await box.write(BoxName.locationName, links);
|
||||
await box.write(BoxName.basicLink, (links[0]['server_link']));
|
||||
await box.write(links[2]['name'], (links[2]['server_link']));
|
||||
await box.write(links[1]['name'], (links[3]['server_link']));
|
||||
await box.write(links[3]['name'], (links[1]['server_link']));
|
||||
await box.write(BoxName.paymentLink, (links[4]['server_link']));
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
46
lib/controller/functions/securty_check.dart
Normal file
46
lib/controller/functions/securty_check.dart
Normal file
@@ -0,0 +1,46 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class SecurityChecks {
|
||||
static const platform = MethodChannel(
|
||||
'com.Intaleq.intaleq/security'); // Choose a unique channel name
|
||||
|
||||
static Future<bool> isDeviceCompromised() async {
|
||||
try {
|
||||
final bool result = await platform
|
||||
.invokeMethod('isNativeRooted'); // Invoke the native method
|
||||
return result;
|
||||
} on PlatformException catch (e) {
|
||||
print("Failed to check security status: ${e.message}");
|
||||
return true; // Treat platform errors as a compromised device (for safety)
|
||||
}
|
||||
}
|
||||
|
||||
static isDeviceRootedFromNative(BuildContext context) async {
|
||||
bool compromised = await isDeviceCompromised();
|
||||
if (compromised) {
|
||||
showDialog(
|
||||
barrierDismissible: false,
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text("Security Warning".tr),
|
||||
content: Text(
|
||||
"Your device appears to be compromised. The app will now close."
|
||||
.tr),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
SystemNavigator.pop(); // Close the app
|
||||
},
|
||||
child: Text("OK"),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Continue with normal app flow
|
||||
print("Device is secure.");
|
||||
}
|
||||
}
|
||||
}
|
||||
168
lib/controller/functions/sms_controller.dart
Normal file
168
lib/controller/functions/sms_controller.dart
Normal file
@@ -0,0 +1,168 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:Intaleq/constant/api_key.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/info.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/auth/login_controller.dart';
|
||||
import 'package:Intaleq/env/env.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:Intaleq/views/widgets/elevated_btn.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../../print.dart';
|
||||
import '../auth/register_controller.dart';
|
||||
import 'crud.dart';
|
||||
|
||||
class SmsEgyptController extends GetxController {
|
||||
var headers = {'Content-Type': 'application/json'};
|
||||
Future<String> getSender() async {
|
||||
var res = await CRUD().get(link: AppLink.getSender, payload: {});
|
||||
if (res != 'failure') {
|
||||
var d = jsonDecode(res)['message'][0]['senderId'].toString();
|
||||
return d;
|
||||
} else {
|
||||
return "Sefer Egy";
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> sendSmsEgypt(String phone, otp) async {
|
||||
// String sender = await getSender();
|
||||
// var body = jsonEncode({
|
||||
// "username": 'Sefer',
|
||||
// "password": AK.smsPasswordEgypt,
|
||||
// "message": "${AppInformation.appName} app code is $otp\ncopy it to app",
|
||||
// "language": box.read(BoxName.lang) == 'en' ? "e" : 'r',
|
||||
// "sender": sender, //"Sefer Egy",
|
||||
// "receiver": phone
|
||||
// });
|
||||
|
||||
var res = await CRUD().post(link: AppLink.sendSmsFromPHP, payload: {
|
||||
"language": box.read(BoxName.lang) == 'en' ? "e" : 'r',
|
||||
"receiver": phone,
|
||||
});
|
||||
if (res != 'failure') {
|
||||
// var res = await http.post(
|
||||
// Uri.parse(AppLink.sendSms),
|
||||
// body: body,
|
||||
// headers: headers,
|
||||
// );
|
||||
|
||||
// else if (jsonDecode(res)['message'].toString() ==
|
||||
// "Invalid Sender with Connection") {
|
||||
//
|
||||
// }
|
||||
// else {
|
||||
Get.defaultDialog(
|
||||
title: 'You will receive a code in SMS message'.tr,
|
||||
middleText: '',
|
||||
confirm: MyElevatedButton(
|
||||
title: 'OK'.tr,
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
}));
|
||||
} else {
|
||||
await CRUD().post(link: AppLink.updatePhoneInvalidSMSPassenger, payload: {
|
||||
"phone_number":
|
||||
'+2${Get.find<RegisterController>().phoneController.text}'
|
||||
});
|
||||
box.write(BoxName.phoneDriver,
|
||||
'+2${Get.find<RegisterController>().phoneController.text}');
|
||||
box.write(BoxName.isVerified, '1');
|
||||
|
||||
await Get.put(LoginController()).loginUsingCredentials(
|
||||
box.read(BoxName.driverID).toString(),
|
||||
box.read(BoxName.emailDriver).toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future checkCredit(String phone, otp) async {
|
||||
var res = await http.post(
|
||||
Uri.parse(AppLink.checkCredit),
|
||||
body: {
|
||||
"username": AppInformation.appName,
|
||||
"password": AK.smsPasswordEgypt,
|
||||
},
|
||||
headers: headers,
|
||||
);
|
||||
}
|
||||
|
||||
Future sendSmsWithValidaty(String phone, otp) async {
|
||||
var res = await http.post(
|
||||
Uri.parse(AppLink.checkCredit),
|
||||
body: {
|
||||
"username": AppInformation.appName,
|
||||
"password": AK.smsPasswordEgypt,
|
||||
"message": "This is an example SMS message.",
|
||||
"language": box.read(BoxName.lang) == 'en' ? "e" : 'r',
|
||||
"sender": "Kazumi", // todo add sefer sender name
|
||||
"receiver": "2$phone",
|
||||
"validity": "10",
|
||||
"StartTime": DateTime.now().toString() // "1/1/2024 10:00:00"
|
||||
},
|
||||
headers: headers,
|
||||
);
|
||||
}
|
||||
|
||||
Future sendSmsStatus(String smsid) async {
|
||||
var res = await http.post(
|
||||
Uri.parse(AppLink.checkCredit),
|
||||
body: {
|
||||
"username": AppInformation.appName,
|
||||
"password": AK.smsPasswordEgypt,
|
||||
"smsid": smsid //"00b77dfc-5b8f-474d-9def-9f0158b70f98"
|
||||
},
|
||||
headers: headers,
|
||||
);
|
||||
}
|
||||
|
||||
Future sendWhatsAppAuth(String to, String token) async {
|
||||
var headers = {
|
||||
'Authorization': 'Bearer ${Env.whatsapp}',
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
var request = http.Request(
|
||||
'POST',
|
||||
Uri.parse(
|
||||
'https://graph.facebook.com/v20.0/${Env.whatappID}/messages'));
|
||||
request.body = json.encode({
|
||||
"messaging_product": "whatsapp",
|
||||
"to": to, //"962798583052",
|
||||
"type": "template",
|
||||
"template": {
|
||||
"name": "sefer1",
|
||||
"language": {"code": "en"},
|
||||
"components": [
|
||||
{
|
||||
"type": "body",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": token,
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
request.headers.addAll(headers);
|
||||
|
||||
http.StreamedResponse response = await request.send();
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
print(await response.stream.bytesToString());
|
||||
Get.defaultDialog(
|
||||
title: 'You will receive a code in WhatsApp Messenger'.tr,
|
||||
middleText: '',
|
||||
confirm: MyElevatedButton(
|
||||
title: 'OK'.tr,
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
}));
|
||||
} else {
|
||||
print(response.reasonPhrase);
|
||||
}
|
||||
}
|
||||
}
|
||||
18
lib/controller/functions/sss.dart
Normal file
18
lib/controller/functions/sss.dart
Normal file
@@ -0,0 +1,18 @@
|
||||
import 'package:secure_string_operations/secure_string_operations.dart';
|
||||
|
||||
import '../../constant/char_map.dart';
|
||||
import '../../main.dart';
|
||||
|
||||
class Sss {
|
||||
static read(String boxname) async {
|
||||
return box.read(X.r(X.r(X.r(boxname, cn), cC), cs));
|
||||
}
|
||||
|
||||
static write(String boxname, value) async {
|
||||
return box.write(boxname, X.c(X.c(X.c(value, cn), cC), cs));
|
||||
}
|
||||
|
||||
static delete(String boxname) async {
|
||||
return box.remove(boxname);
|
||||
}
|
||||
}
|
||||
35
lib/controller/functions/toast.dart
Normal file
35
lib/controller/functions/toast.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/colors.dart';
|
||||
import 'package:Intaleq/constant/style.dart';
|
||||
|
||||
class Toast {
|
||||
static void show(BuildContext context, String message, Color color) {
|
||||
final snackBar = SnackBar(
|
||||
clipBehavior: Clip.antiAliasWithSaveLayer,
|
||||
backgroundColor: color,
|
||||
elevation: 3,
|
||||
content: Text(
|
||||
message,
|
||||
style: AppStyle.title.copyWith(color: AppColor.secondaryColor),
|
||||
),
|
||||
behavior: SnackBarBehavior.floating,
|
||||
animation: const AlwaysStoppedAnimation(1.0),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10.0), // Custom border radius
|
||||
),
|
||||
width: Get.width * .8,
|
||||
// shape: const StadiumBorder(
|
||||
// side: BorderSide(
|
||||
// color: AppColor.secondaryColor,
|
||||
// width: 1.0,
|
||||
// style: BorderStyle.solid,
|
||||
// )),
|
||||
duration: const Duration(seconds: 2),
|
||||
);
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
snackBar,
|
||||
);
|
||||
}
|
||||
}
|
||||
51
lib/controller/functions/tts.dart
Normal file
51
lib/controller/functions/tts.dart
Normal file
@@ -0,0 +1,51 @@
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_tts/flutter_tts.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../main.dart';
|
||||
|
||||
class TextToSpeechController extends GetxController {
|
||||
final flutterTts = FlutterTts();
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
initTts();
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
flutterTts.stop(); // Stop any ongoing TTS
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
// Initialize TTS engine with language check
|
||||
Future<void> initTts() async {
|
||||
try {
|
||||
String langCode = box.read(BoxName.lang) ?? 'en-US';
|
||||
bool isAvailable = await flutterTts.isLanguageAvailable(langCode);
|
||||
|
||||
// If language is unavailable, default to 'en-US'
|
||||
if (!isAvailable) {
|
||||
langCode = 'en-US';
|
||||
}
|
||||
|
||||
await flutterTts.setLanguage(langCode);
|
||||
await flutterTts.setSpeechRate(0.5); // Adjust speech rate
|
||||
await flutterTts.setVolume(1.0); // Set volume
|
||||
} catch (error) {
|
||||
Get.snackbar('Error', 'Failed to initialize TTS: $error');
|
||||
}
|
||||
}
|
||||
|
||||
// Function to speak the given text
|
||||
Future<void> speakText(String text) async {
|
||||
try {
|
||||
await flutterTts.awaitSpeakCompletion(true);
|
||||
await flutterTts.speak(text);
|
||||
} catch (error) {
|
||||
Get.snackbar('Error', 'Failed to speak text: $error');
|
||||
}
|
||||
}
|
||||
}
|
||||
22
lib/controller/functions/twilio_service.dart
Normal file
22
lib/controller/functions/twilio_service.dart
Normal file
@@ -0,0 +1,22 @@
|
||||
// import 'package:ride/constant/credential.dart';
|
||||
// import 'package:twilio_flutter/twilio_flutter.dart';
|
||||
//
|
||||
// class TwilioSMS {
|
||||
// TwilioFlutter twilioFlutter = TwilioFlutter(
|
||||
// accountSid: AppCredintials.accountSIDTwillo,
|
||||
// authToken: AppCredintials.authTokenTwillo,
|
||||
// twilioNumber: '+962 7 9858 3052');
|
||||
//
|
||||
// Future<void> sendSMS({
|
||||
// required String recipientPhoneNumber,
|
||||
// required String message,
|
||||
// }) async {
|
||||
// try {
|
||||
// await twilioFlutter.sendSMS(
|
||||
// toNumber: recipientPhoneNumber,
|
||||
// messageBody: message,
|
||||
// );
|
||||
// } catch (e) {
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
104
lib/controller/functions/upload_image.dart
Normal file
104
lib/controller/functions/upload_image.dart
Normal file
@@ -0,0 +1,104 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:Intaleq/constant/api_key.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:image_cropper/image_cropper.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:path/path.dart';
|
||||
import 'package:secure_string_operations/secure_string_operations.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/char_map.dart';
|
||||
import '../../constant/colors.dart';
|
||||
import '../../constant/info.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,
|
||||
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':
|
||||
'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
|
||||
});
|
||||
// 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}');
|
||||
}
|
||||
}
|
||||
}
|
||||
91
lib/controller/home/blinking_promo_controller.dart.dart
Normal file
91
lib/controller/home/blinking_promo_controller.dart.dart
Normal file
@@ -0,0 +1,91 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../constant/links.dart';
|
||||
import '../../views/widgets/elevated_btn.dart';
|
||||
import '../functions/crud.dart';
|
||||
|
||||
class BlinkingController extends GetxController {
|
||||
final promoFormKey = GlobalKey<FormState>();
|
||||
|
||||
final promo = TextEditingController();
|
||||
bool promoTaken = false;
|
||||
void applyPromoCodeToPassenger() async {
|
||||
//TAWJIHI
|
||||
if (promoFormKey.currentState!.validate()) {
|
||||
CRUD().get(link: AppLink.getPassengersPromo, payload: {
|
||||
'promo_code': promo.text,
|
||||
}).then((value) {
|
||||
if (value == 'failure') {
|
||||
Get.defaultDialog(
|
||||
title: 'Promo End !'.tr,
|
||||
confirm: MyElevatedButton(
|
||||
title: 'Back',
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
Get.back();
|
||||
},
|
||||
));
|
||||
}
|
||||
var decode = jsonDecode(value);
|
||||
|
||||
// if (decode["status"] == "success") {
|
||||
// var firstElement = decode["message"][0];
|
||||
// if (double.parse(box.read(BoxName.passengerWalletTotal)) < 0) {
|
||||
// totalPassenger = totalCostPassenger -
|
||||
// (totalCostPassenger * int.parse(firstElement['amount']) / 100);
|
||||
// update();
|
||||
// } else {
|
||||
// totalPassenger = totalCostPassenger -
|
||||
// (totalCostPassenger * int.parse(firstElement['amount']) / 100);
|
||||
// update();
|
||||
// }
|
||||
|
||||
// totalDriver = totalDriver -
|
||||
// (totalDriver * int.parse(firstElement['amount']) / 100);
|
||||
// promoTaken = true;
|
||||
// update();
|
||||
// Get.back();
|
||||
// }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Reactive variable for blinking (on/off)
|
||||
var isLightOn = false.obs;
|
||||
|
||||
// To animate the border color
|
||||
var borderColor = Colors.black.obs;
|
||||
|
||||
Timer? _blinkingTimer;
|
||||
|
||||
// Method to start blinking for 5 seconds
|
||||
void startBlinking() {
|
||||
int count = 0;
|
||||
|
||||
_blinkingTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
// Toggle light on/off
|
||||
isLightOn.value = !isLightOn.value;
|
||||
borderColor.value = isLightOn.value
|
||||
? Colors.yellow
|
||||
: Colors.black; // Animate border color
|
||||
|
||||
count++;
|
||||
|
||||
// Stop blinking after 5 seconds
|
||||
if (count >= 35) {
|
||||
timer.cancel();
|
||||
isLightOn.value = false; // Ensure light turns off
|
||||
borderColor.value = Colors.black; // Reset the border color
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_blinkingTimer?.cancel();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
78
lib/controller/home/contact_us_controller.dart
Normal file
78
lib/controller/home/contact_us_controller.dart
Normal file
@@ -0,0 +1,78 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_font_icons/flutter_font_icons.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../constant/colors.dart';
|
||||
import '../functions/launch.dart';
|
||||
|
||||
class ContactUsController extends GetxController {
|
||||
final String phone1 = '+201018805430';
|
||||
final String phone2 = '+201080182934';
|
||||
final TimeOfDay workStartTime = const TimeOfDay(hour: 12, minute: 0);
|
||||
final TimeOfDay workEndTime = const TimeOfDay(hour: 19, minute: 0);
|
||||
|
||||
bool _isWithinWorkTime(TimeOfDay now) {
|
||||
return (now.hour > workStartTime.hour ||
|
||||
(now.hour == workStartTime.hour &&
|
||||
now.minute >= workStartTime.minute)) &&
|
||||
(now.hour < workEndTime.hour ||
|
||||
(now.hour == workEndTime.hour && now.minute <= workEndTime.minute));
|
||||
}
|
||||
|
||||
void showContactDialog(BuildContext context) {
|
||||
TimeOfDay now = TimeOfDay.now();
|
||||
|
||||
showCupertinoModalPopup(
|
||||
context: context,
|
||||
builder: (context) => CupertinoActionSheet(
|
||||
title: Text('Contact Us'.tr),
|
||||
message: Text('Choose a contact option'.tr),
|
||||
actions: <Widget>[
|
||||
if (_isWithinWorkTime(now))
|
||||
CupertinoActionSheetAction(
|
||||
child: Text(phone1),
|
||||
onPressed: () => makePhoneCall(
|
||||
phone1,
|
||||
),
|
||||
),
|
||||
if (_isWithinWorkTime(now))
|
||||
CupertinoActionSheetAction(
|
||||
child: Text(phone2),
|
||||
onPressed: () => makePhoneCall(phone2),
|
||||
),
|
||||
if (!_isWithinWorkTime(now))
|
||||
CupertinoActionSheetAction(
|
||||
child: Text(
|
||||
'Work time is from 12:00 - 19:00.\nYou can send a WhatsApp message or email.'
|
||||
.tr),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
CupertinoActionSheetAction(
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
const Icon(
|
||||
FontAwesome.whatsapp,
|
||||
color: AppColor.greenColor,
|
||||
),
|
||||
Text('Send WhatsApp Message'.tr),
|
||||
],
|
||||
),
|
||||
onPressed: () =>
|
||||
launchCommunication('whatsapp', phone1, 'Hello'.tr),
|
||||
),
|
||||
CupertinoActionSheetAction(
|
||||
child: Text('Send Email'.tr),
|
||||
onPressed: () =>
|
||||
launchCommunication('email', 'support@sefer.live', 'Hello'.tr),
|
||||
),
|
||||
],
|
||||
cancelButton: CupertinoActionSheetAction(
|
||||
child: Text('Cancel'.tr),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
15
lib/controller/home/home_page_controller.dart
Normal file
15
lib/controller/home/home_page_controller.dart
Normal file
@@ -0,0 +1,15 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../main.dart';
|
||||
|
||||
class HomePageController extends GetxController {
|
||||
late bool isVibrate = box.read(BoxName.isvibrate) ?? true;
|
||||
|
||||
void changeVibrateOption(bool value) {
|
||||
isVibrate = box.read(BoxName.isvibrate) ?? true;
|
||||
isVibrate = value;
|
||||
box.write(BoxName.isvibrate, value);
|
||||
update();
|
||||
}
|
||||
}
|
||||
5669
lib/controller/home/map_passenger_controller.dart
Normal file
5669
lib/controller/home/map_passenger_controller.dart
Normal file
File diff suppressed because it is too large
Load Diff
14
lib/controller/home/menu_controller.dart
Normal file
14
lib/controller/home/menu_controller.dart
Normal file
@@ -0,0 +1,14 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class MyMenuController extends GetxController {
|
||||
bool isDrawerOpen = true;
|
||||
|
||||
void getDrawerMenu() {
|
||||
if (isDrawerOpen == true) {
|
||||
isDrawerOpen = false;
|
||||
} else {
|
||||
isDrawerOpen = true;
|
||||
}
|
||||
update();
|
||||
}
|
||||
}
|
||||
129
lib/controller/home/payment/captain_wallet_controller.dart
Normal file
129
lib/controller/home/payment/captain_wallet_controller.dart
Normal file
@@ -0,0 +1,129 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
|
||||
class CaptainWalletController extends GetxController {
|
||||
bool isLoading = false;
|
||||
Map walletDate = {};
|
||||
Map walletDateVisa = {};
|
||||
Map walletDriverPointsDate = {};
|
||||
final formKey = GlobalKey<FormState>();
|
||||
String totalAmount = '0';
|
||||
String totalAmountVisa = '0';
|
||||
String totalPoints = '0';
|
||||
final amountFromBudgetController = TextEditingController();
|
||||
|
||||
payFromBudget() async {
|
||||
if (formKey.currentState!.validate()) {
|
||||
var pointFromBudget = box.read(BoxName.countryCode) == 'Jordan'
|
||||
? int.parse((amountFromBudgetController.text)) * 100
|
||||
: int.parse((amountFromBudgetController.text));
|
||||
|
||||
await addDriverPayment('fromBudgetToPoints',
|
||||
int.parse((amountFromBudgetController.text)) * -1);
|
||||
Future.delayed(const Duration(seconds: 2));
|
||||
await addDriverWallet('fromBudget', pointFromBudget.toString());
|
||||
update();
|
||||
Get.back();
|
||||
// getCaptainWalletFromRide();
|
||||
// getCaptainWalletFromBuyPoints();
|
||||
// checkAccountCaptainBank();
|
||||
}
|
||||
}
|
||||
|
||||
// Future getCaptainWalletFromRide() async {
|
||||
// isLoading = true;
|
||||
// update();
|
||||
// var res = await CRUD().get(
|
||||
// link: AppLink.getAllPaymentFromRide,
|
||||
// payload: {'driverID': box.read(BoxName.driverID)},
|
||||
// );
|
||||
// walletDate = jsonDecode(res);
|
||||
// totalAmount = walletDate['message'][0]['total_amount'].toString() == null
|
||||
// ? '0'
|
||||
// : walletDate['message'][0]['total_amount'];
|
||||
|
||||
// var res1 = await CRUD().get(
|
||||
// link: AppLink.getAllPaymentVisa,
|
||||
// payload: {'driverID': box.read(BoxName.driverID)});
|
||||
// walletDateVisa = jsonDecode(res1);
|
||||
// totalAmountVisa = walletDateVisa['message'][0]['diff'].toString() == null
|
||||
// ? '0'
|
||||
// : walletDateVisa['message'][0]['diff'];
|
||||
// isLoading = false;
|
||||
// update();
|
||||
// }
|
||||
|
||||
// Future getCaptainWalletFromBuyPoints() async {
|
||||
// isLoading = true;
|
||||
// update();
|
||||
// var res = await CRUD().get(
|
||||
// link: AppLink.getDriverPaymentPoints,
|
||||
// payload: {'driverID': box.read(BoxName.driverID)},
|
||||
// );
|
||||
// walletDriverPointsDate = jsonDecode(res);
|
||||
// if (walletDriverPointsDate['message'][0]['driverID'].toString() ==
|
||||
// box.read(BoxName.driverID)) {
|
||||
// double totalPointsDouble = double.parse(
|
||||
// walletDriverPointsDate['message'][0]['total_amount'].toString());
|
||||
// totalPoints = totalPointsDouble.toStringAsFixed(0);
|
||||
// } else {
|
||||
// totalPoints = '0';
|
||||
// }
|
||||
|
||||
// isLoading = false;
|
||||
// update();
|
||||
// }
|
||||
|
||||
late String paymentID;
|
||||
Future addDriverPayment(String paymentMethod, amount) async {
|
||||
var res =
|
||||
await CRUD().postWallet(link: AppLink.addDriverPaymentPoints, payload: {
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
'amount': amount.toString(),
|
||||
'payment_method': paymentMethod.toString(),
|
||||
});
|
||||
var d = jsonDecode(res);
|
||||
paymentID = d['message'].toString();
|
||||
}
|
||||
|
||||
Future addDriverWallet(String paymentMethod, point) async {
|
||||
await CRUD().postWallet(link: AppLink.addDriversWalletPoints, payload: {
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
'paymentID': paymentID.toString(),
|
||||
'amount': point,
|
||||
'paymentMethod': paymentMethod.toString(),
|
||||
});
|
||||
}
|
||||
|
||||
//check if account bank is created or not
|
||||
Future checkAccountCaptainBank() async {
|
||||
isLoading = false;
|
||||
update();
|
||||
if (box.read(BoxName.accountIdStripeConnect).toString().isEmpty) {
|
||||
var res = await CRUD().getWallet(link: AppLink.getAccount, payload: {
|
||||
'id': box.read(BoxName.driverID).toString(),
|
||||
});
|
||||
var d = jsonDecode(res);
|
||||
if (d['status'] != 'failure') {
|
||||
box.write(BoxName.accountIdStripeConnect,
|
||||
d['message'][0]['accountBank'].toString());
|
||||
}
|
||||
}
|
||||
isLoading = true;
|
||||
update();
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
// getCaptainWalletFromRide();
|
||||
// getCaptainWalletFromBuyPoints();
|
||||
// checkAccountCaptainBank();
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
75
lib/controller/home/payment/credit_card_Controller.dart
Normal file
75
lib/controller/home/payment/credit_card_Controller.dart
Normal file
@@ -0,0 +1,75 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../constant/box_name.dart';
|
||||
import '../../functions/digit_obsecur_formate.dart';
|
||||
import '../../functions/secure_storage.dart';
|
||||
|
||||
class CreditCardController extends GetxController {
|
||||
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
|
||||
final TextEditingController cardNumberController = TextEditingController();
|
||||
final TextEditingController cardHolderNameController =
|
||||
TextEditingController();
|
||||
final TextEditingController expiryDateController = TextEditingController();
|
||||
final TextEditingController cvvCodeController = TextEditingController();
|
||||
openPayment() async {
|
||||
String? cardNumber = await SecureStorage().readData(BoxName.cardNumber);
|
||||
String? cardHolderName =
|
||||
await SecureStorage().readData(BoxName.cardHolderName);
|
||||
String? expiryDate = await SecureStorage().readData(BoxName.expiryDate);
|
||||
String? cvvCode = await SecureStorage().readData(BoxName.cvvCode);
|
||||
|
||||
// if (cvvCode != null && cvvCode.isNotEmpty) {
|
||||
// final maskedCardNumber = DigitObscuringFormatter()
|
||||
// .formatEditUpdate(
|
||||
// TextEditingValue.empty,
|
||||
// TextEditingValue(text: cardNumber ?? ''),
|
||||
// )
|
||||
// .text;
|
||||
|
||||
// cardNumberController.text = maskedCardNumber;
|
||||
// cardHolderNameController.text = cardHolderName ?? '';
|
||||
// expiryDateController.text = expiryDate ?? '';
|
||||
// cvvCodeController.text = cvvCode;
|
||||
// }
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() async {
|
||||
super.onInit();
|
||||
openPayment();
|
||||
// String? cardNumber = await SecureStorage().readData(BoxName.cardNumber);
|
||||
// String? cardHolderName =
|
||||
// await SecureStorage().readData(BoxName.cardHolderName);
|
||||
// String? expiryDate = await SecureStorage().readData(BoxName.expiryDate);
|
||||
// String? cvvCode = await SecureStorage().readData(BoxName.cvvCode);
|
||||
|
||||
// if (cvvCode != null && cvvCode.isNotEmpty) {
|
||||
// final maskedCardNumber = DigitObscuringFormatter()
|
||||
// .formatEditUpdate(
|
||||
// TextEditingValue.empty,
|
||||
// TextEditingValue(text: cardNumber ?? ''),
|
||||
// )
|
||||
// .text;
|
||||
|
||||
// cardNumberController.text = maskedCardNumber;
|
||||
// cardHolderNameController.text = cardHolderName ?? '';
|
||||
// expiryDateController.text = expiryDate ?? '';
|
||||
// cvvCodeController.text = cvvCode;
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
class CreditCardModel {
|
||||
String cardNumber;
|
||||
String cardHolderName;
|
||||
String expiryDate;
|
||||
String cvvCode;
|
||||
|
||||
CreditCardModel({
|
||||
required this.cardNumber,
|
||||
required this.cardHolderName,
|
||||
required this.expiryDate,
|
||||
required this.cvvCode,
|
||||
});
|
||||
}
|
||||
148
lib/controller/home/points_for_rider_controller.dart
Normal file
148
lib/controller/home/points_for_rider_controller.dart
Normal file
@@ -0,0 +1,148 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'package:Intaleq/constant/style.dart';
|
||||
import 'package:Intaleq/controller/home/map_passenger_controller.dart';
|
||||
|
||||
import '../../constant/api_key.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../functions/crud.dart';
|
||||
import '../functions/location_controller.dart';
|
||||
|
||||
class PointsForRiderController extends GetxController {
|
||||
List<String> locations = [];
|
||||
String hintTextDestinationPoint = 'Search for your destination'.tr;
|
||||
TextEditingController placeStartController = TextEditingController();
|
||||
|
||||
void addLocation(String location) {
|
||||
locations.add(location);
|
||||
update();
|
||||
}
|
||||
|
||||
void getTextFromList(String location) {
|
||||
locations.add(location);
|
||||
update();
|
||||
Get.back();
|
||||
}
|
||||
|
||||
void removeLocation(int index) {
|
||||
locations.removeAt(index);
|
||||
update();
|
||||
}
|
||||
|
||||
void onReorder(int oldIndex, int newIndex) {
|
||||
if (newIndex > oldIndex) {
|
||||
newIndex -= 1;
|
||||
update();
|
||||
}
|
||||
|
||||
final item = locations.removeAt(oldIndex);
|
||||
locations.insert(newIndex, item);
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
class LocationModel {
|
||||
String name;
|
||||
double lat, lon;
|
||||
|
||||
LocationModel({required this.name, required this.lat, required this.lon});
|
||||
}
|
||||
|
||||
class WayPointController extends GetxController {
|
||||
// A list of text editing controllers for each text field
|
||||
// final textFields = [TextEditingController()].obs;
|
||||
List<String> wayPoints = [];
|
||||
List<List<dynamic>> placeListResponse = [];
|
||||
double wayPointHeight = 400;
|
||||
String hintTextDestinationPoint = 'Search for your destination'.tr;
|
||||
TextEditingController textSearchCotroller = TextEditingController();
|
||||
// A list of places corresponding to each text field
|
||||
final places = <String>[];
|
||||
|
||||
final hintTextPointList = <String>[];
|
||||
late LatLng myLocation;
|
||||
|
||||
void addWayPoints() {
|
||||
String wayPoint = 'Add a Stop'.tr;
|
||||
|
||||
if (wayPoints.length < 5) {
|
||||
wayPoints.add(wayPoint);
|
||||
update();
|
||||
} else {
|
||||
Get.defaultDialog(
|
||||
title: 'This is most WayPoints',
|
||||
titleStyle: AppStyle.title,
|
||||
middleText: '');
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
void removeTextField(int index) {
|
||||
wayPoints.removeAt(index);
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
// A method to reorder the text fields and the places
|
||||
void reorderTextFields(int oldIndex, int newIndex) {
|
||||
if (newIndex > oldIndex) {
|
||||
newIndex -= 1;
|
||||
}
|
||||
final wayPoint = wayPoints.removeAt(oldIndex);
|
||||
wayPoints.insert(newIndex, wayPoint);
|
||||
update();
|
||||
}
|
||||
|
||||
void updatePlace(int index, String input) async {
|
||||
var url =
|
||||
'${AppLink.googleMapsLink}place/nearbysearch/json?keyword=$input&location=${myLocation.latitude},${myLocation.longitude}&radius=50000&language=en&key=${AK.mapAPIKEY.toString()}';
|
||||
var response = await CRUD().getGoogleApi(link: url, payload: {});
|
||||
// final place = input;
|
||||
// if (index == 0) {
|
||||
List<dynamic> newList = [];
|
||||
placeListResponse.add(newList);
|
||||
newList = response['results'];
|
||||
placeListResponse[index].add(newList);
|
||||
update();
|
||||
// }
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
Get.put(LocationController());
|
||||
addWayPoints();
|
||||
myLocation = Get.find<MapPassengerController>().passengerLocation;
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
|
||||
class PlaceList extends StatelessWidget {
|
||||
// Get the controller instance
|
||||
final controller = Get.put(WayPointController());
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Use the Obx widget to rebuild the widget when the controller changes
|
||||
return Obx(() {
|
||||
// Use the ListView widget to display the list of places
|
||||
return ListView(
|
||||
// The children of the list are the places
|
||||
children: [
|
||||
// Loop through the places in the controller
|
||||
for (final place in controller.places)
|
||||
// Create a text widget for each place
|
||||
Text(
|
||||
// Use the place as the text
|
||||
place,
|
||||
|
||||
// Add some style and padding
|
||||
style: const TextStyle(fontSize: 18.0),
|
||||
),
|
||||
],
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
238
lib/controller/home/profile/complaint_controller.dart
Normal file
238
lib/controller/home/profile/complaint_controller.dart
Normal file
@@ -0,0 +1,238 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/colors.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/constant/style.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:Intaleq/views/widgets/elevated_btn.dart';
|
||||
import 'package:http_parser/http_parser.dart';
|
||||
import 'package:mime/mime.dart';
|
||||
|
||||
import '../../../constant/api_key.dart';
|
||||
import '../../../print.dart';
|
||||
import '../../../views/widgets/mydialoug.dart';
|
||||
|
||||
class ComplaintController extends GetxController {
|
||||
bool isLoading = false;
|
||||
final formKey = GlobalKey<FormState>();
|
||||
final complaintController = TextEditingController();
|
||||
final suggestionController = TextEditingController();
|
||||
List feedBack = [];
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
getLatestRidesForPassengers();
|
||||
}
|
||||
|
||||
getLatestRidesForPassengers() async {
|
||||
isLoading = true;
|
||||
update();
|
||||
var res = await CRUD().get(link: AppLink.getFeedBack, payload: {
|
||||
'passengerId': box.read(BoxName.passengerID).toString(),
|
||||
});
|
||||
if (res != 'failure') {
|
||||
var d = jsonDecode(res)['message'];
|
||||
feedBack = d;
|
||||
}
|
||||
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
void addComplaint() async {
|
||||
isLoading = true;
|
||||
update();
|
||||
var res = await CRUD().post(link: AppLink.addFeedBack, payload: {
|
||||
'passengerId': box.read(BoxName.passengerID).toString(),
|
||||
'feedBack': complaintController.text
|
||||
});
|
||||
// var d = jsonDecode(res);
|
||||
if (res != 'failure') {
|
||||
Get.defaultDialog(
|
||||
title: 'Success'.tr,
|
||||
titleStyle: AppStyle.title,
|
||||
middleText: 'Complaint data saved successfully'.tr,
|
||||
middleTextStyle: AppStyle.title,
|
||||
confirm: MyElevatedButton(
|
||||
kolor: AppColor.greenColor,
|
||||
title: 'Ok'.tr,
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
// Get.back();
|
||||
}));
|
||||
}
|
||||
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
var isUploading = false.obs;
|
||||
var uploadSuccess = false.obs;
|
||||
late String audioLink = '';
|
||||
Future<void> uploadAudioFile(File audioFile) async {
|
||||
try {
|
||||
isUploading.value = true;
|
||||
|
||||
// Prepare the file upload
|
||||
var uri = Uri.parse('${AppLink.IntaleqCairoServer}/upload_audio.php');
|
||||
var request = http.MultipartRequest('POST', uri);
|
||||
|
||||
// Add the file to the request with MIME type
|
||||
var mimeType = lookupMimeType(audioFile.path);
|
||||
request.headers.addAll({
|
||||
'Authorization':
|
||||
'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials.toString()))}',
|
||||
});
|
||||
request.files.add(
|
||||
await http.MultipartFile.fromPath(
|
||||
'audio',
|
||||
audioFile.path,
|
||||
contentType: mimeType != null ? MediaType.parse(mimeType) : null,
|
||||
),
|
||||
);
|
||||
|
||||
// Send the request
|
||||
var response = await request.send();
|
||||
|
||||
// Convert response to string for parsing
|
||||
var responseBody = await http.Response.fromStream(response);
|
||||
|
||||
// After the upload request
|
||||
if (response.statusCode == 200) {
|
||||
var jsonResponse = jsonDecode(responseBody.body);
|
||||
|
||||
if (jsonResponse['status'] == 'Audio file uploaded successfully.') {
|
||||
uploadSuccess.value = true;
|
||||
audioLink = jsonResponse['link']; // Get the audio link
|
||||
Get.back();
|
||||
Get.snackbar('Success'.tr, 'Audio uploaded successfully.'.tr,
|
||||
backgroundColor: const Color.fromARGB(255, 89, 185, 115));
|
||||
} else {
|
||||
uploadSuccess.value = false;
|
||||
}
|
||||
} else {
|
||||
uploadSuccess.value = false;
|
||||
}
|
||||
} catch (e) {
|
||||
uploadSuccess.value = false;
|
||||
} finally {
|
||||
isUploading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
var customerServiceSolutions;
|
||||
var passengerReport;
|
||||
var driverReport;
|
||||
var isloading = false;
|
||||
Future<void> geminiAudio(payload, String audioLink, String complain) async {
|
||||
String prompt = '''
|
||||
Analyze the following complaint between a passenger and driver in a ride-hailing service. The complaint includes an audio link for reference. Provide two possible solutions for customer service to resolve the issue, and generate a detailed report for both the passenger and the driver.
|
||||
|
||||
Complaint details:
|
||||
- Passenger: $complain
|
||||
- Driver: [Driver's complaint]
|
||||
- Ride Information: {ride details such as start_location, end_location, date, price, status, and rating details}
|
||||
- Audio Link: [$audioLink]
|
||||
|
||||
Output the result in JSON format with the following structure:
|
||||
{
|
||||
"customerServiceSolutions": [
|
||||
"solution1",
|
||||
"solution2"
|
||||
],
|
||||
"passengerReport": {
|
||||
"solution": "Passenger's solution" if passenger right,
|
||||
"complaint": "Passenger's complaint",
|
||||
"rideDetails": {detailed ride info}
|
||||
},
|
||||
"driverReport": {
|
||||
"complaint": "Driver's complaint",
|
||||
"rideDetails": {detailed ride info}
|
||||
}
|
||||
} the response in arabic language with egypt
|
||||
''';
|
||||
|
||||
var requestBody = jsonEncode({
|
||||
"contents": [
|
||||
{
|
||||
"parts": [
|
||||
{"text": "$payload $prompt"}
|
||||
]
|
||||
}
|
||||
],
|
||||
"generationConfig": {
|
||||
"temperature": 1,
|
||||
"topK": 64,
|
||||
"topP": 0.95,
|
||||
"maxOutputTokens": 8192,
|
||||
"stopSequences": []
|
||||
},
|
||||
"safetySettings": [
|
||||
{
|
||||
"category": "HARM_CATEGORY_HARASSMENT",
|
||||
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
||||
},
|
||||
{
|
||||
"category": "HARM_CATEGORY_HATE_SPEECH",
|
||||
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
||||
},
|
||||
{
|
||||
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
|
||||
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
||||
},
|
||||
{
|
||||
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
|
||||
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
final response = await http.post(
|
||||
Uri.parse(
|
||||
'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro:generateContent?key=${AK.geminiApi}'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: requestBody,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
var responseData = jsonDecode(response.body);
|
||||
var result = responseData['candidates'][0]['content']['parts'][0]['text'];
|
||||
Log.print('result: ${result}');
|
||||
|
||||
// Clean up the result by removing surrounding backticks if they exist
|
||||
result = result.replaceAll(RegExp(r'^```json\s*|\s*```$'), '');
|
||||
|
||||
// Attempt to decode the cleaned result as JSON
|
||||
try {
|
||||
var jsonResult = jsonDecode(result);
|
||||
|
||||
// Access customer service solutions and reports for both passenger and driver
|
||||
customerServiceSolutions = jsonResult['customerServiceSolutions'];
|
||||
passengerReport = jsonResult['passengerReport'];
|
||||
driverReport = jsonResult['driverReport'];
|
||||
update();
|
||||
// Use the data accordingly
|
||||
// For example, log the reports or display them in a UI dialog
|
||||
|
||||
update();
|
||||
} catch (e) {
|
||||
MyDialog().getDialog(
|
||||
'Error'.tr,
|
||||
'Unable to parse the response as JSON. Please check the format and try again.'
|
||||
.tr, () {
|
||||
Get.back();
|
||||
});
|
||||
}
|
||||
} else {
|
||||
Get.snackbar(
|
||||
'Error', "Request failed with status: ${response.statusCode}",
|
||||
backgroundColor: AppColor.redColor);
|
||||
}
|
||||
}
|
||||
}
|
||||
314
lib/controller/home/profile/invit_controller.dart
Normal file
314
lib/controller/home/profile/invit_controller.dart
Normal file
@@ -0,0 +1,314 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/colors.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/controller/functions/encrypt_decrypt.dart';
|
||||
import 'package:Intaleq/controller/payment/payment_controller.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_contacts/flutter_contacts.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:share/share.dart';
|
||||
|
||||
import '../../../main.dart';
|
||||
import '../../../print.dart';
|
||||
import '../../../views/widgets/error_snakbar.dart';
|
||||
import '../../../views/widgets/mydialoug.dart';
|
||||
import '../../functions/launch.dart';
|
||||
import '../../notification/notification_captain_controller.dart';
|
||||
|
||||
class InviteController extends GetxController {
|
||||
final TextEditingController invitePhoneController = TextEditingController();
|
||||
List driverInvitationData = [];
|
||||
List driverInvitationDataToPassengers = [];
|
||||
String? couponCode;
|
||||
String? driverCouponCode;
|
||||
|
||||
int selectedTab = 0;
|
||||
PassengerStats passengerStats = PassengerStats();
|
||||
void updateSelectedTab(int index) {
|
||||
selectedTab = index;
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> shareCouponCode() async {
|
||||
// TODO: Implement sharing functionality
|
||||
// You can use share_plus package to share the coupon code
|
||||
}
|
||||
Future<void> shareDriverCode() async {
|
||||
if (driverCouponCode != null) {
|
||||
final String shareText = '''
|
||||
Join Intaleq as a driver using my referral code!
|
||||
Use code: $driverCouponCode
|
||||
Download the Intaleq Driver app now and earn rewards!
|
||||
''';
|
||||
await Share.share(shareText);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> sharePassengerCode() async {
|
||||
if (couponCode != null) {
|
||||
final String shareText = '''
|
||||
Get a discount on your first Intaleq ride!
|
||||
Use my referral code: $couponCode
|
||||
Download the Intaleq app now and enjoy your ride!
|
||||
''';
|
||||
await Share.share(shareText);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
// fetchDriverStats();
|
||||
}
|
||||
|
||||
void fetchDriverStats() async {
|
||||
try {
|
||||
var response = await CRUD().get(link: AppLink.getInviteDriver, payload: {
|
||||
"driverId": box.read(BoxName.driverID),
|
||||
});
|
||||
if (response != 'failure') {
|
||||
var data = jsonDecode(response);
|
||||
driverInvitationData = data['message'];
|
||||
update();
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
void fetchDriverStatsPassengers() async {
|
||||
try {
|
||||
var response = await CRUD()
|
||||
.get(link: AppLink.getDriverInvitationToPassengers, payload: {
|
||||
"driverId": box.read(BoxName.passengerID),
|
||||
});
|
||||
if (response != 'failure') {
|
||||
var data = jsonDecode(response);
|
||||
driverInvitationDataToPassengers = data['message'];
|
||||
update();
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
void selectPhone(String phone) {
|
||||
if (box.read(BoxName.countryCode) == 'Egypt') {
|
||||
invitePhoneController.text = phone;
|
||||
update();
|
||||
Get.back();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> saveContactsToServer() async {
|
||||
try {
|
||||
// TODO: Implement the actual server upload logic here
|
||||
// Simulating a server request
|
||||
await Future.delayed(Duration(seconds: 2));
|
||||
Get.snackbar('Success'.tr,
|
||||
'${selectedContacts.length} contacts saved to server'.tr);
|
||||
} catch (e) {
|
||||
Get.snackbar('Error'.tr,
|
||||
'An error occurred while saving contacts to server: $e'.tr);
|
||||
}
|
||||
}
|
||||
|
||||
List<Contact> contacts = <Contact>[];
|
||||
List<Contact> selectedContacts = <Contact>[];
|
||||
RxList<Map<String, dynamic>> contactMaps = <Map<String, dynamic>>[].obs;
|
||||
|
||||
Future<void> pickContacts() async {
|
||||
try {
|
||||
// Request contacts permission
|
||||
if (await FlutterContacts.requestPermission(readonly: true)) {
|
||||
// Fetch all contacts with full properties
|
||||
final List<Contact> allContacts = await FlutterContacts.getContacts(
|
||||
withProperties: true,
|
||||
withThumbnail: false,
|
||||
withPhoto: true,
|
||||
);
|
||||
|
||||
// Check if contacts are available
|
||||
if (allContacts.isNotEmpty) {
|
||||
// Store the contacts
|
||||
contacts = allContacts;
|
||||
Log.print('contacts: $contacts');
|
||||
|
||||
// Convert contacts to a list of maps
|
||||
contactMaps.value = await Future.wait(contacts.map((contact) async {
|
||||
Log.print('Contact name: ${contact.displayName}');
|
||||
|
||||
// Fetch phone numbers separately
|
||||
final phones = await contact.phones;
|
||||
Log.print('Contact phones: $phones');
|
||||
|
||||
// Fetch email addresses separately
|
||||
final emails = await contact.emails;
|
||||
Log.print('Contact emails: $emails');
|
||||
|
||||
// Handle empty or null values
|
||||
return {
|
||||
'name': contact.displayName ?? '',
|
||||
'phones': phones
|
||||
.where((phone) => phone.normalizedNumber != null)
|
||||
.map((phone) => phone.normalizedNumber ?? 'No number')
|
||||
.toList(),
|
||||
'emails': emails
|
||||
.where((email) => email.address != null)
|
||||
.map((email) => email.address ?? 'No email')
|
||||
.toList(),
|
||||
};
|
||||
}).toList());
|
||||
|
||||
update();
|
||||
} else {
|
||||
Get.snackbar('No contacts available'.tr,
|
||||
'Please add contacts to your phone.'.tr);
|
||||
}
|
||||
} else {
|
||||
Get.snackbar('Permission denied'.tr,
|
||||
'Contact permission is required to pick contacts'.tr);
|
||||
}
|
||||
} catch (e) {
|
||||
Get.snackbar(
|
||||
'Error'.tr, 'An error occurred while picking contacts: $e'.tr);
|
||||
}
|
||||
}
|
||||
|
||||
void onSelectPassengerInvitation(int index) async {
|
||||
MyDialog().getDialog(
|
||||
int.parse(driverInvitationDataToPassengers[index]['countOfInvitDriver']
|
||||
.toString()) <
|
||||
2
|
||||
? '${'When'.tr} ${(driverInvitationDataToPassengers[index]['passengerName'].toString())} ${"complete, you can claim your gift".tr} '
|
||||
: 'You deserve the gift'.tr,
|
||||
'${(driverInvitationDataToPassengers[index]['passengerName'].toString())} ${driverInvitationDataToPassengers[index]['countOfInvitDriver'].toString()} / 2 ${'Trip'.tr}',
|
||||
() async {
|
||||
if (int.parse(driverInvitationDataToPassengers[index]
|
||||
['countOfInvitDriver']
|
||||
.toString()) <
|
||||
2) {
|
||||
Get.back();
|
||||
} else {
|
||||
// Claim the gift if 100 trips are completed
|
||||
if (driverInvitationDataToPassengers[index]['isGiftToken']
|
||||
.toString() ==
|
||||
'0') {
|
||||
Get.back();
|
||||
// Add wallet to the inviter
|
||||
await Get.find<PaymentController>().addPassengersWallet('20');
|
||||
// add for invitor too
|
||||
// await Get.find<CaptainWalletController>().addDriverWalletToInvitor(
|
||||
// 'paymentMethod',
|
||||
// driverInvitationData[index]['driverInviterId'],
|
||||
// '50');
|
||||
// Update invitation as claimed
|
||||
await CRUD().post(
|
||||
link: AppLink.updatePassengerGift,
|
||||
payload: {'id': driverInvitationDataToPassengers[index]['id']},
|
||||
);
|
||||
// Notify the inviter
|
||||
NotificationCaptainController().addNotificationCaptain(
|
||||
driverInvitationDataToPassengers[index]['passengerInviterId']
|
||||
.toString(),
|
||||
"You have got a gift for invitation".tr,
|
||||
'${"You have 20".tr} ${'LE'}',
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
Get.back();
|
||||
MyDialog().getDialog(
|
||||
"You have got a gift".tr,
|
||||
"Share the app with another new passenger".tr,
|
||||
() {
|
||||
Get.back();
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
savePhoneToServer() async {
|
||||
for (var i = 0; i < contactMaps.length; i++) {
|
||||
var phones = contactMaps[i]['phones'];
|
||||
if (phones != null && phones.isNotEmpty && phones[0].isNotEmpty) {
|
||||
var res = await CRUD().post(link: AppLink.savePhones, payload: {
|
||||
"name": contactMaps[i]['name'] ?? 'none',
|
||||
"phones": phones[0] ?? 'none',
|
||||
"phones2": phones.join(', ') ??
|
||||
'none', // Convert List<String> to a comma-separated string
|
||||
});
|
||||
if (res != 'failure') {}
|
||||
} else {}
|
||||
}
|
||||
}
|
||||
|
||||
String formatPhoneNumber(String input) {
|
||||
// Remove any non-digit characters
|
||||
String digitsOnly = input.replaceAll(RegExp(r'\D'), '');
|
||||
|
||||
// Ensure the number starts with the country code
|
||||
if (digitsOnly.startsWith('20')) {
|
||||
digitsOnly = digitsOnly.substring(1);
|
||||
}
|
||||
|
||||
return digitsOnly;
|
||||
}
|
||||
|
||||
void sendInviteToPassenger() async {
|
||||
if (invitePhoneController.text.isEmpty ||
|
||||
invitePhoneController.text.length < 11) {
|
||||
mySnackeBarError('Please enter a correct phone'.tr);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// try {
|
||||
String phoneNumber = formatPhoneNumber(invitePhoneController.text);
|
||||
|
||||
var response =
|
||||
await CRUD().post(link: AppLink.addInvitationPassenger, payload: {
|
||||
"driverId": box.read(BoxName.passengerID),
|
||||
"inviterPassengerPhone": ('+2$phoneNumber')
|
||||
});
|
||||
|
||||
if (response != 'failure') {
|
||||
var d = response;
|
||||
Get.snackbar('Success', 'Invite sent successfully'.tr);
|
||||
|
||||
String message = '${'*Intaleq APP CODE*'.tr}\n\n'
|
||||
'${"Use this code in registration".tr}\n'
|
||||
'${"To get a gift for both".tr}\n\n'
|
||||
'${"The period of this code is 1 hour".tr}\n\n'
|
||||
'${'before'.tr} *${d['message']['expirationTime'].toString()}*\n\n'
|
||||
'_*${d['message']['inviteCode'].toString()}*_\n\n'
|
||||
'${"Install our app:".tr}\n'
|
||||
'*Android:* https://play.google.com/store/apps/details?id=com.mobileapp.store.ride\n\n\n'
|
||||
'*iOS:* https://apps.apple.com/us/app/sefer/id6458734951';
|
||||
|
||||
launchCommunication('whatsapp', '+2$phoneNumber', message);
|
||||
|
||||
invitePhoneController.clear();
|
||||
} else {
|
||||
Get.snackbar('Error'.tr, "Invite code already used".tr,
|
||||
backgroundColor: AppColor.redColor,
|
||||
duration: const Duration(seconds: 4));
|
||||
}
|
||||
// } catch (e) {
|
||||
// Get.snackbar('Error', 'An error occurred'.tr);
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
class PassengerStats {
|
||||
final int totalInvites;
|
||||
final int activeUsers;
|
||||
final double totalEarnings;
|
||||
|
||||
PassengerStats({
|
||||
this.totalInvites = 0,
|
||||
this.activeUsers = 0,
|
||||
this.totalEarnings = 0.0,
|
||||
});
|
||||
}
|
||||
35
lib/controller/home/profile/order_history_controller.dart
Normal file
35
lib/controller/home/profile/order_history_controller.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
|
||||
class OrderHistoryController extends GetxController {
|
||||
List<dynamic> orderHistoryListPassenger = [];
|
||||
bool isloading = true;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
getOrderHistoryByPassenger();
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
Future getOrderHistoryByPassenger() async {
|
||||
var res = await CRUD().get(link: AppLink.getRides, payload: {
|
||||
'passenger_id': box.read(BoxName.passengerID).toString(),
|
||||
});
|
||||
if (res.toString() == 'failure') {
|
||||
// Get.snackbar('failure', 'message');
|
||||
isloading = false;
|
||||
update();
|
||||
} else {
|
||||
var jsonDecoded = jsonDecode(res);
|
||||
|
||||
orderHistoryListPassenger = jsonDecoded['data'];
|
||||
isloading = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
}
|
||||
45
lib/controller/home/profile/promos_controller.dart
Normal file
45
lib/controller/home/profile/promos_controller.dart
Normal file
@@ -0,0 +1,45 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
|
||||
import '../../../main.dart';
|
||||
|
||||
class PromosController extends GetxController {
|
||||
List<dynamic> promoList = [];
|
||||
bool isLoading = true;
|
||||
late String promos;
|
||||
@override
|
||||
void onInit() {
|
||||
getPromoByToday();
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
Future getPromoByToday() async {
|
||||
var res = await CRUD().get(link: AppLink.getPromoBytody, payload: {
|
||||
'passengerID': box.read(BoxName.passengerID).toString(),
|
||||
});
|
||||
if (res.toString() == 'failure') {
|
||||
// Get.defaultDialog(
|
||||
// title: 'No Promo for today .'.tr,
|
||||
// middleText: '',
|
||||
// titleStyle: AppStyle.title,
|
||||
// confirm: MyElevatedButton(
|
||||
// title: 'Back'.tr,
|
||||
// onPressed: () {
|
||||
// Get.back();
|
||||
// Get.back();
|
||||
// }));
|
||||
isLoading = false;
|
||||
update();
|
||||
} else {
|
||||
var jsonDecoded = jsonDecode(res);
|
||||
|
||||
promoList = jsonDecoded['message'];
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
}
|
||||
152
lib/controller/home/splash_screen_controlle.dart
Normal file
152
lib/controller/home/splash_screen_controlle.dart
Normal file
@@ -0,0 +1,152 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:Intaleq/constant/style.dart';
|
||||
import 'package:Intaleq/controller/functions/secure_storage.dart';
|
||||
import 'package:Intaleq/views/widgets/my_scafold.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/views/auth/login_page.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
// import 'package:uni_links/uni_links.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../main.dart';
|
||||
import '../../onbording_page.dart';
|
||||
import '../../views/auth/otp_page.dart';
|
||||
import '../auth/login_controller.dart';
|
||||
|
||||
class SplashScreenController extends GetxController
|
||||
with GetTickerProviderStateMixin {
|
||||
late AnimationController _animationController;
|
||||
late Animation<double> animation;
|
||||
final progress = 0.0.obs;
|
||||
Timer? _progressTimer;
|
||||
|
||||
String packageInfo = '';
|
||||
|
||||
Future<void> _getPackageInfo() async {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
packageInfo = info.version;
|
||||
box.write(BoxName.packagInfo, packageInfo);
|
||||
update();
|
||||
}
|
||||
|
||||
String iss = '';
|
||||
@override
|
||||
Future<void> onInit() async {
|
||||
super.onInit();
|
||||
|
||||
// storage.read(key: 'iss').then((s) {
|
||||
// // print(s);
|
||||
// iss = s!;
|
||||
// });
|
||||
// if (iss == null) {
|
||||
SecureStorage().saveData('iss', 'mobile-app:');
|
||||
// }
|
||||
|
||||
_getPackageInfo();
|
||||
_animationController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 1500), // Reduced duration
|
||||
)..forward();
|
||||
|
||||
animation =
|
||||
CurvedAnimation(parent: _animationController, curve: Curves.easeOut);
|
||||
|
||||
startTimer();
|
||||
_startProgressTimer();
|
||||
}
|
||||
|
||||
void _startProgressTimer() {
|
||||
const totalTime = 2000; // 5 seconds in milliseconds
|
||||
const interval = 50; // Update every 50ms
|
||||
int elapsed = 0;
|
||||
|
||||
_progressTimer =
|
||||
Timer.periodic(const Duration(milliseconds: interval), (timer) async {
|
||||
elapsed += interval;
|
||||
progress.value = (elapsed / totalTime).clamp(0.0, 1.0);
|
||||
|
||||
if (elapsed >= totalTime) {
|
||||
timer.cancel();
|
||||
// await SecurityHelper.performSecurityChecks();
|
||||
// if (box.read('isNotTrust') ||
|
||||
// box.read('isJailBroken') ||
|
||||
// box.read('isTampered')) {
|
||||
// Get.to(() => SecurityPage());
|
||||
// } else {
|
||||
box.read(BoxName.onBoarding) == null
|
||||
? Get.off(() => OnBoardingPage())
|
||||
: box.read(BoxName.email) != null &&
|
||||
box.read(BoxName.phone) != null &&
|
||||
box.read(BoxName.isVerified) == '1'
|
||||
// ? Get.off(() => const MapPagePassenger())
|
||||
? await Get.put(LoginController()).loginUsingCredentials(
|
||||
box.read(BoxName.passengerID).toString(),
|
||||
box.read(BoxName.email).toString(),
|
||||
)
|
||||
: Get.off(() => LoginPage());
|
||||
}
|
||||
// }
|
||||
});
|
||||
}
|
||||
|
||||
void startTimer() async {
|
||||
Timer(const Duration(seconds: 5), () async {
|
||||
// box.read(BoxName.onBoarding) == null
|
||||
// ? Get.off(() => OnBoardingPage())
|
||||
// : box.read(BoxName.email) != null &&
|
||||
// box.read(BoxName.phone) != null &&
|
||||
// box.read(BoxName.isVerified) == '1'
|
||||
// // ? Get.off(() => const MapPagePassenger())
|
||||
// ? await Get.put(LoginController()).loginUsingCredentials(
|
||||
// box.read(BoxName.passengerID).toString(),
|
||||
// box.read(BoxName.email).toString(),
|
||||
// )
|
||||
// : Get.off(() => LoginPage());
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_progressTimer?.cancel();
|
||||
_animationController.dispose();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
|
||||
class SecurityPage extends StatelessWidget {
|
||||
const SecurityPage({
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MyScafolld(
|
||||
title: "security_warning".tr,
|
||||
body: [
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
"security_message".tr,
|
||||
style: AppStyle.headTitle2,
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
// await SecurityHelper.clearAllData();
|
||||
},
|
||||
child: Text(
|
||||
"security_warning".tr,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
],
|
||||
isleading: false);
|
||||
}
|
||||
}
|
||||
113
lib/controller/home/trip_monitor_controller.dart
Normal file
113
lib/controller/home/trip_monitor_controller.dart
Normal file
@@ -0,0 +1,113 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
|
||||
class TripMonitorController extends GetxController {
|
||||
bool isLoading = false;
|
||||
Map tripData = {};
|
||||
late String rideId;
|
||||
late String driverId;
|
||||
GoogleMapController? mapController;
|
||||
List myListString = [];
|
||||
late Timer timer;
|
||||
late LatLng parentLocation;
|
||||
BitmapDescriptor carIcon = BitmapDescriptor.defaultMarker;
|
||||
BitmapDescriptor motoIcon = BitmapDescriptor.defaultMarker;
|
||||
BitmapDescriptor ladyIcon = BitmapDescriptor.defaultMarker;
|
||||
double rotation = 0;
|
||||
double speed = 0;
|
||||
|
||||
getLocationParent() async {
|
||||
var res = await CRUD().get(
|
||||
link: AppLink.getLocationParents, payload: {"driver_id": driverId});
|
||||
if (res != 'failure') {
|
||||
tripData = jsonDecode(res);
|
||||
parentLocation = LatLng(
|
||||
double.parse(tripData['message'][0]['latitude'].toString()),
|
||||
double.parse(tripData['message'][0]['longitude'].toString()));
|
||||
rotation = double.parse(tripData['message'][0]['heading'].toString());
|
||||
speed = double.parse(tripData['message'][0]['speed'].toString());
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
void onMapCreated(GoogleMapController controller) async {
|
||||
mapController = controller;
|
||||
controller.getVisibleRegion();
|
||||
controller.animateCamera(
|
||||
CameraUpdate.newLatLng(parentLocation),
|
||||
);
|
||||
update();
|
||||
// Set up a timer or interval to trigger the marker update every 3 seconds.
|
||||
timer = Timer.periodic(const Duration(seconds: 10), (_) async {
|
||||
await getLocationParent();
|
||||
mapController?.animateCamera(CameraUpdate.newLatLng(parentLocation));
|
||||
update();
|
||||
});
|
||||
}
|
||||
|
||||
// init() async {
|
||||
// final arguments = Get.arguments;
|
||||
// driverId = arguments['driverId'];
|
||||
// rideId = arguments['rideId'];
|
||||
// await getLocationParent();
|
||||
// }
|
||||
|
||||
Future<void> init({String? rideId, String? driverId}) async {
|
||||
this.driverId = driverId!;
|
||||
this.rideId = rideId!;
|
||||
await getLocationParent();
|
||||
update();
|
||||
}
|
||||
|
||||
void addCustomCarIcon() {
|
||||
ImageConfiguration config = ImageConfiguration(
|
||||
size: const Size(30, 30), devicePixelRatio: Get.pixelRatio);
|
||||
BitmapDescriptor.fromAssetImage(config, 'assets/images/car.png',
|
||||
mipmaps: false)
|
||||
.then((value) {
|
||||
carIcon = value;
|
||||
update();
|
||||
});
|
||||
void addCustomMotoIcon() {
|
||||
ImageConfiguration config = ImageConfiguration(
|
||||
size: const Size(30, 30), devicePixelRatio: Get.pixelRatio);
|
||||
BitmapDescriptor.fromAssetImage(config, 'assets/images/moto1.png',
|
||||
mipmaps: false)
|
||||
.then((value) {
|
||||
motoIcon = value;
|
||||
update();
|
||||
});
|
||||
}
|
||||
|
||||
void addCustomLadyIcon() {
|
||||
ImageConfiguration config = ImageConfiguration(
|
||||
size: const Size(30, 30), devicePixelRatio: Get.pixelRatio);
|
||||
BitmapDescriptor.fromAssetImage(config, 'assets/images/lady1.png',
|
||||
mipmaps: false)
|
||||
.then((value) {
|
||||
ladyIcon = value;
|
||||
update();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
addCustomCarIcon();
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
timer.cancel();
|
||||
mapController?.dispose();
|
||||
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
324
lib/controller/home/vip_waitting_page.dart
Normal file
324
lib/controller/home/vip_waitting_page.dart
Normal file
@@ -0,0 +1,324 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/colors.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/constant/style.dart';
|
||||
import 'package:Intaleq/controller/home/map_passenger_controller.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:Intaleq/views/widgets/elevated_btn.dart';
|
||||
import 'package:Intaleq/views/widgets/my_scafold.dart';
|
||||
import 'package:Intaleq/views/widgets/mycircular.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_font_icons/flutter_font_icons.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import '../functions/crud.dart';
|
||||
import '../functions/encrypt_decrypt.dart';
|
||||
|
||||
class VipOrderController extends GetxController {
|
||||
RxBool isLoading = false.obs;
|
||||
final arguments = Get.arguments;
|
||||
RxList<dynamic> tripData = <dynamic>[].obs;
|
||||
RxBool isButtonVisible = false.obs;
|
||||
RxInt countdown = 60.obs;
|
||||
Timer? _countdownTimer;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
fetchOrder();
|
||||
startCountdown();
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_countdownTimer?.cancel();
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
Future<void> fetchOrder() async {
|
||||
try {
|
||||
isLoading.value = true;
|
||||
var mapPassengerController = Get.find<MapPassengerController>();
|
||||
|
||||
var res = await CRUD().get(
|
||||
link: AppLink.getMishwari,
|
||||
payload: {
|
||||
// 'driverId': mapPassengerController.driverIdVip.toString(),
|
||||
'driverId': box.read(BoxName.passengerID).toString(),
|
||||
},
|
||||
);
|
||||
|
||||
if (res != 'failure') {
|
||||
var decodedResponse = jsonDecode(res);
|
||||
if (decodedResponse['message'] is List) {
|
||||
tripData.value = decodedResponse['message'];
|
||||
} else {
|
||||
tripData.clear(); // Ensure empty list if no data
|
||||
// mySnackeBarError('No trip data found');
|
||||
}
|
||||
} else {
|
||||
tripData.clear();
|
||||
// mySnackeBarError('Failed to fetch trip data');
|
||||
}
|
||||
} catch (e) {
|
||||
tripData.clear();
|
||||
// mySnackeBarError('An error occurred: $e');
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
void startCountdown() {
|
||||
_countdownTimer?.cancel(); // Cancel any existing timer
|
||||
countdown.value = 60;
|
||||
|
||||
_countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
if (countdown.value > 0) {
|
||||
countdown.value--;
|
||||
} else {
|
||||
timer.cancel();
|
||||
isButtonVisible.value = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void sendToDriverAgain() {
|
||||
// Reset states
|
||||
isButtonVisible.value = false;
|
||||
fetchOrder(); // Refresh order
|
||||
startCountdown(); // Restart countdown
|
||||
}
|
||||
}
|
||||
|
||||
class VipWaittingPage extends StatelessWidget {
|
||||
VipWaittingPage({super.key});
|
||||
final VipOrderController vipOrderController = Get.put(VipOrderController());
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MyScafolld(
|
||||
title: "Waiting VIP".tr,
|
||||
body: [
|
||||
Obx(() {
|
||||
// Loading state
|
||||
if (vipOrderController.isLoading.value) {
|
||||
return const Center(child: MyCircularProgressIndicator());
|
||||
}
|
||||
|
||||
// No data state
|
||||
if (vipOrderController.tripData.isEmpty) {
|
||||
return Center(
|
||||
child: Text(
|
||||
'No trip data available'.tr,
|
||||
style: AppStyle.title,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Data available
|
||||
var data = vipOrderController.tripData[0];
|
||||
|
||||
// Function to get the localized status string
|
||||
String getLocalizedStatus(String status) {
|
||||
switch (status) {
|
||||
case 'pending':
|
||||
return 'pending'.tr;
|
||||
case 'accepted':
|
||||
return 'accepted'.tr;
|
||||
case 'begin':
|
||||
return 'begin'.tr;
|
||||
case 'rejected':
|
||||
return 'rejected'.tr;
|
||||
case 'cancelled':
|
||||
return 'cancelled'.tr;
|
||||
default:
|
||||
return 'unknown'.tr;
|
||||
}
|
||||
}
|
||||
|
||||
// Function to get the appropriate status color
|
||||
Color getStatusColor(String status) {
|
||||
switch (status) {
|
||||
case 'pending':
|
||||
return Colors.yellow;
|
||||
case 'accepted':
|
||||
return Colors.green;
|
||||
case 'begin':
|
||||
return Colors.green;
|
||||
case 'rejected':
|
||||
return Colors.red;
|
||||
case 'cancelled':
|
||||
return Colors.red;
|
||||
default:
|
||||
return Colors.grey;
|
||||
}
|
||||
}
|
||||
|
||||
return Card(
|
||||
elevation: 4,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
margin: const EdgeInsets.all(16),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
"${'Driver Name:'.tr} ${data['name']}",
|
||||
style: AppStyle.title,
|
||||
),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
"${'Car Plate:'.tr} ${data['car_plate']}",
|
||||
style: AppStyle.title,
|
||||
),
|
||||
Text(
|
||||
"${'Car Make:'.tr} ${data['make']}",
|
||||
style: AppStyle.title,
|
||||
),
|
||||
Text(
|
||||
"${'Car Model:'.tr} ${data['model']}",
|
||||
style: AppStyle.title,
|
||||
),
|
||||
Text(
|
||||
"${"Car Color:".tr} ${data['color']}",
|
||||
style: AppStyle.title,
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(
|
||||
width: 100,
|
||||
height: 100,
|
||||
child: Icon(
|
||||
Fontisto.car,
|
||||
size: 80,
|
||||
color: Color(
|
||||
int.parse(
|
||||
data['color_hex'].replaceFirst('#', '0xff'),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
const Divider(),
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
color: getStatusColor(data['status']),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Text(
|
||||
"${'Trip Status:'.tr} ${getLocalizedStatus(data['status'])}",
|
||||
style: const TextStyle(fontSize: 16),
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
"${'Scheduled Time:'.tr} ${DateFormat('yyyy-MM-dd hh:mm a').format(DateTime.parse(data['timeSelected']))}",
|
||||
style: const TextStyle(fontSize: 16),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
data['status'].toString() != 'begin'
|
||||
? MyElevatedButton(
|
||||
title: "Cancel Trip".tr,
|
||||
kolor: AppColor.redColor,
|
||||
onPressed: () {
|
||||
Get.find<MapPassengerController>().cancelVip(
|
||||
data['token'].toString(),
|
||||
data['id'].toString(),
|
||||
);
|
||||
},
|
||||
)
|
||||
: const SizedBox(),
|
||||
Obx(() {
|
||||
// If countdown is still running, show countdown
|
||||
if (!vipOrderController.isButtonVisible.value) {
|
||||
return Column(
|
||||
children: [
|
||||
CircularProgressIndicator(
|
||||
value: 1 -
|
||||
(vipOrderController.countdown.value / 60),
|
||||
strokeWidth: 6.0,
|
||||
color: AppColor.greenColor,
|
||||
backgroundColor: AppColor.accentColor,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
"${vipOrderController.countdown.value}s ${'remaining'.tr}",
|
||||
style: const TextStyle(fontSize: 16),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Once countdown is complete, show "Send to Driver Again" button
|
||||
return MyElevatedButton(
|
||||
title: "Send to Driver Again".tr,
|
||||
kolor: AppColor.greenColor,
|
||||
onPressed: () {
|
||||
Get.find<MapPassengerController>()
|
||||
.sendToDriverAgain(data['token']);
|
||||
vipOrderController.fetchOrder();
|
||||
},
|
||||
);
|
||||
}),
|
||||
],
|
||||
),
|
||||
const SizedBox(
|
||||
height: 30,
|
||||
),
|
||||
data['status'].toString() == 'begin'
|
||||
? MyElevatedButton(
|
||||
title: "Click here to begin your trip\n\nGood luck, "
|
||||
.tr +
|
||||
(box.read(BoxName.name).toString().split(' ')[0])
|
||||
.toString(),
|
||||
kolor: AppColor.greenColor,
|
||||
onPressed: () {
|
||||
final mapPassengerController =
|
||||
Get.find<MapPassengerController>();
|
||||
mapPassengerController.make = data['make'];
|
||||
mapPassengerController.licensePlate =
|
||||
data['car_plate'];
|
||||
mapPassengerController.model = data['model'];
|
||||
mapPassengerController.driverId = data['driverId'];
|
||||
mapPassengerController.carColor = data['color'];
|
||||
mapPassengerController.driverRate = data['rating'];
|
||||
mapPassengerController.colorHex = data['color_hex'];
|
||||
mapPassengerController.driverPhone = data['phone'];
|
||||
mapPassengerController.driverToken = data['token'];
|
||||
mapPassengerController.driverName =
|
||||
data['name'].toString().split(' ')[0];
|
||||
|
||||
Get.back();
|
||||
|
||||
mapPassengerController.begiVIPTripFromPassenger();
|
||||
},
|
||||
)
|
||||
: const SizedBox()
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
],
|
||||
isleading: true,
|
||||
);
|
||||
}
|
||||
}
|
||||
205
lib/controller/local/local_controller.dart
Normal file
205
lib/controller/local/local_controller.dart
Normal file
@@ -0,0 +1,205 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../main.dart';
|
||||
import '../themes/themes.dart';
|
||||
|
||||
class LocaleController extends GetxController {
|
||||
Locale? language;
|
||||
String countryCode = '';
|
||||
|
||||
ThemeData appTheme = lightThemeEnglish;
|
||||
|
||||
void changeLang(String langcode) {
|
||||
Locale locale;
|
||||
switch (langcode) {
|
||||
case "ar":
|
||||
locale = const Locale("ar");
|
||||
appTheme = lightThemeArabic;
|
||||
box.write(BoxName.lang, 'ar');
|
||||
break;
|
||||
case "ar-main":
|
||||
locale = const Locale("ar-main");
|
||||
appTheme = lightThemeArabic;
|
||||
box.write(BoxName.lang, 'ar-main');
|
||||
break;
|
||||
case "en":
|
||||
locale = const Locale("en");
|
||||
appTheme = lightThemeEnglish;
|
||||
box.write(BoxName.lang, 'en');
|
||||
break;
|
||||
case "tr":
|
||||
locale = const Locale("tr");
|
||||
appTheme = lightThemeEnglish;
|
||||
box.write(BoxName.lang, 'tr');
|
||||
break;
|
||||
case "fr":
|
||||
locale = const Locale("fr");
|
||||
appTheme = lightThemeEnglish;
|
||||
box.write(BoxName.lang, 'fr');
|
||||
break;
|
||||
case "it":
|
||||
locale = const Locale("it");
|
||||
appTheme = lightThemeEnglish;
|
||||
box.write(BoxName.lang, 'it');
|
||||
break;
|
||||
case "de":
|
||||
locale = const Locale("de");
|
||||
appTheme = lightThemeEnglish;
|
||||
box.write(BoxName.lang, 'de');
|
||||
break;
|
||||
case "el":
|
||||
locale = const Locale("el");
|
||||
appTheme = lightThemeEnglish;
|
||||
box.write(BoxName.lang, 'el');
|
||||
break;
|
||||
case "es":
|
||||
locale = const Locale("es");
|
||||
appTheme = lightThemeEnglish;
|
||||
box.write(BoxName.lang, 'es');
|
||||
break;
|
||||
case "fa":
|
||||
locale = const Locale("fa");
|
||||
appTheme = lightThemeEnglish;
|
||||
box.write(BoxName.lang, 'fa');
|
||||
break;
|
||||
case "zh":
|
||||
locale = const Locale("zh");
|
||||
appTheme = lightThemeEnglish;
|
||||
box.write(BoxName.lang, 'zh');
|
||||
break;
|
||||
case "ru":
|
||||
locale = const Locale("ru");
|
||||
appTheme = lightThemeEnglish;
|
||||
box.write(BoxName.lang, 'ru');
|
||||
break;
|
||||
case "hi":
|
||||
locale = const Locale("hi");
|
||||
appTheme = lightThemeEnglish;
|
||||
box.write(BoxName.lang, 'hi');
|
||||
break;
|
||||
case "ar-ma":
|
||||
locale = const Locale("ar-ma");
|
||||
appTheme = lightThemeArabic;
|
||||
box.write(BoxName.lang, 'ar-ma');
|
||||
break;
|
||||
case "ar-gulf":
|
||||
locale = const Locale("ar-gulf");
|
||||
appTheme = lightThemeArabic;
|
||||
box.write(BoxName.lang, 'ar-gulf');
|
||||
break;
|
||||
default:
|
||||
locale = Locale(Get.deviceLocale!.languageCode);
|
||||
box.write(BoxName.lang, Get.deviceLocale!.languageCode);
|
||||
appTheme = lightThemeEnglish;
|
||||
break;
|
||||
}
|
||||
|
||||
box.write(BoxName.lang, langcode);
|
||||
Get.changeTheme(appTheme);
|
||||
Get.updateLocale(locale);
|
||||
update();
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
String? storedLang = box.read(BoxName.lang);
|
||||
if (storedLang == null) {
|
||||
// Use device language if no language is stored
|
||||
storedLang = Get.deviceLocale!.languageCode;
|
||||
box.write(BoxName.lang, storedLang);
|
||||
}
|
||||
|
||||
changeLang(storedLang);
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
|
||||
// class LocaleController extends GetxController {
|
||||
// Locale? language;
|
||||
// String countryCode = '';
|
||||
// void restartApp() {
|
||||
// runApp(const MyApp());
|
||||
// }
|
||||
|
||||
// ThemeData appTheme = themeEnglish;
|
||||
|
||||
// changeLang(String langcode) {
|
||||
// Locale locale;
|
||||
// switch (langcode) {
|
||||
// case "ar":
|
||||
// locale = const Locale("ar");
|
||||
// appTheme = themeArabic;
|
||||
// break;
|
||||
// case "en":
|
||||
// locale = const Locale("en");
|
||||
// appTheme = themeEnglish;
|
||||
// break;
|
||||
// case "tr":
|
||||
// locale = const Locale("tr");
|
||||
// appTheme = themeEnglish;
|
||||
// break;
|
||||
// case "fr":
|
||||
// locale = const Locale("fr");
|
||||
// appTheme = themeEnglish;
|
||||
// break;
|
||||
// case "it":
|
||||
// locale = const Locale("it");
|
||||
// appTheme = themeEnglish;
|
||||
// break;
|
||||
// case "de":
|
||||
// locale = const Locale("de");
|
||||
// appTheme = themeEnglish;
|
||||
// break;
|
||||
// case "el":
|
||||
// locale = const Locale("el");
|
||||
// appTheme = themeEnglish;
|
||||
// break;
|
||||
// case "es":
|
||||
// locale = const Locale("es");
|
||||
// appTheme = themeEnglish;
|
||||
// break;
|
||||
// case "fa":
|
||||
// locale = const Locale("fa");
|
||||
// appTheme = themeArabic;
|
||||
// break;
|
||||
// case "zh":
|
||||
// locale = const Locale("zh");
|
||||
// appTheme = themeEnglish;
|
||||
// break;
|
||||
// case "ru":
|
||||
// locale = const Locale("ru");
|
||||
// appTheme = themeEnglish;
|
||||
// break;
|
||||
// case "hi":
|
||||
// locale = const Locale("hi");
|
||||
// appTheme = themeEnglish;
|
||||
// break;
|
||||
// default:
|
||||
// locale = Locale(Get.deviceLocale!.languageCode);
|
||||
// appTheme = themeEnglish;
|
||||
// break;
|
||||
// }
|
||||
|
||||
// box.write(BoxName.lang, langcode);
|
||||
// Get.changeTheme(appTheme);
|
||||
// Get.updateLocale(locale);
|
||||
// restartApp();
|
||||
// update();
|
||||
// }
|
||||
|
||||
// @override
|
||||
// void onInit() {
|
||||
// String? storedLang = box.read(BoxName.lang);
|
||||
// if (storedLang == null) {
|
||||
// // Use device language if no language is stored
|
||||
// storedLang = Get.deviceLocale!.languageCode;
|
||||
// box.write(BoxName.lang, storedLang);
|
||||
// }
|
||||
|
||||
// changeLang(storedLang);
|
||||
|
||||
// super.onInit();
|
||||
// }
|
||||
// }
|
||||
7574
lib/controller/local/phone_intel/countries.dart
Normal file
7574
lib/controller/local/phone_intel/countries.dart
Normal file
File diff suppressed because it is too large
Load Diff
168
lib/controller/local/phone_intel/country_picker_dialog.dart
Normal file
168
lib/controller/local/phone_intel/country_picker_dialog.dart
Normal file
@@ -0,0 +1,168 @@
|
||||
import 'package:Intaleq/controller/local/phone_intel/helpers.dart';
|
||||
import 'package:flutter/foundation.dart' show kIsWeb;
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'countries.dart';
|
||||
|
||||
class PickerDialogStyle {
|
||||
final Color? backgroundColor;
|
||||
|
||||
final TextStyle? countryCodeStyle;
|
||||
|
||||
final TextStyle? countryNameStyle;
|
||||
|
||||
final Widget? listTileDivider;
|
||||
|
||||
final EdgeInsets? listTilePadding;
|
||||
|
||||
final EdgeInsets? padding;
|
||||
|
||||
final Color? searchFieldCursorColor;
|
||||
|
||||
final InputDecoration? searchFieldInputDecoration;
|
||||
|
||||
final EdgeInsets? searchFieldPadding;
|
||||
|
||||
final double? width;
|
||||
|
||||
PickerDialogStyle({
|
||||
this.backgroundColor,
|
||||
this.countryCodeStyle,
|
||||
this.countryNameStyle,
|
||||
this.listTileDivider,
|
||||
this.listTilePadding,
|
||||
this.padding,
|
||||
this.searchFieldCursorColor,
|
||||
this.searchFieldInputDecoration,
|
||||
this.searchFieldPadding,
|
||||
this.width,
|
||||
});
|
||||
}
|
||||
|
||||
class CountryPickerDialog extends StatefulWidget {
|
||||
final List<Country> countryList;
|
||||
final Country selectedCountry;
|
||||
final ValueChanged<Country> onCountryChanged;
|
||||
final String searchText;
|
||||
final List<Country> filteredCountries;
|
||||
final PickerDialogStyle? style;
|
||||
final String languageCode;
|
||||
|
||||
const CountryPickerDialog({
|
||||
Key? key,
|
||||
required this.searchText,
|
||||
required this.languageCode,
|
||||
required this.countryList,
|
||||
required this.onCountryChanged,
|
||||
required this.selectedCountry,
|
||||
required this.filteredCountries,
|
||||
this.style,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<CountryPickerDialog> createState() => _CountryPickerDialogState();
|
||||
}
|
||||
|
||||
class _CountryPickerDialogState extends State<CountryPickerDialog> {
|
||||
late List<Country> _filteredCountries;
|
||||
late Country _selectedCountry;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
_selectedCountry = widget.selectedCountry;
|
||||
_filteredCountries = widget.filteredCountries.toList()
|
||||
..sort(
|
||||
(a, b) => a
|
||||
.localizedName(widget.languageCode)
|
||||
.compareTo(b.localizedName(widget.languageCode)),
|
||||
);
|
||||
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final mediaWidth = MediaQuery.of(context).size.width;
|
||||
final width = widget.style?.width ?? mediaWidth;
|
||||
const defaultHorizontalPadding = 40.0;
|
||||
const defaultVerticalPadding = 24.0;
|
||||
return Dialog(
|
||||
insetPadding: EdgeInsets.symmetric(
|
||||
vertical: defaultVerticalPadding,
|
||||
horizontal: mediaWidth > (width + defaultHorizontalPadding * 2)
|
||||
? (mediaWidth - width) / 2
|
||||
: defaultHorizontalPadding),
|
||||
backgroundColor: widget.style?.backgroundColor,
|
||||
child: Container(
|
||||
padding: widget.style?.padding ?? const EdgeInsets.all(10),
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Padding(
|
||||
padding:
|
||||
widget.style?.searchFieldPadding ?? const EdgeInsets.all(0),
|
||||
child: TextField(
|
||||
cursorColor: widget.style?.searchFieldCursorColor,
|
||||
decoration: widget.style?.searchFieldInputDecoration ??
|
||||
InputDecoration(
|
||||
suffixIcon: const Icon(Icons.search),
|
||||
labelText: widget.searchText,
|
||||
),
|
||||
onChanged: (value) {
|
||||
_filteredCountries = widget.countryList.stringSearch(value)
|
||||
..sort(
|
||||
(a, b) => a
|
||||
.localizedName(widget.languageCode)
|
||||
.compareTo(b.localizedName(widget.languageCode)),
|
||||
);
|
||||
if (mounted) setState(() {});
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: _filteredCountries.length,
|
||||
itemBuilder: (ctx, index) => Column(
|
||||
children: <Widget>[
|
||||
ListTile(
|
||||
leading: kIsWeb
|
||||
? Image.asset(
|
||||
'assets/flags/${_filteredCountries[index].code.toLowerCase()}.png',
|
||||
package: 'intl_phone_field',
|
||||
width: 32,
|
||||
)
|
||||
: Text(
|
||||
_filteredCountries[index].flag,
|
||||
style: const TextStyle(fontSize: 18),
|
||||
),
|
||||
contentPadding: widget.style?.listTilePadding,
|
||||
title: Text(
|
||||
_filteredCountries[index]
|
||||
.localizedName(widget.languageCode),
|
||||
style: widget.style?.countryNameStyle ??
|
||||
const TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
trailing: Text(
|
||||
'+${_filteredCountries[index].dialCode}',
|
||||
style: widget.style?.countryCodeStyle ??
|
||||
const TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
onTap: () {
|
||||
_selectedCountry = _filteredCountries[index];
|
||||
widget.onCountryChanged(_selectedCountry);
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
),
|
||||
widget.style?.listTileDivider ??
|
||||
const Divider(thickness: 1),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
31
lib/controller/local/phone_intel/helpers.dart
Normal file
31
lib/controller/local/phone_intel/helpers.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
import 'countries.dart';
|
||||
|
||||
bool isNumeric(String s) =>
|
||||
s.isNotEmpty && int.tryParse(s.replaceAll("+", "")) != null;
|
||||
|
||||
String removeDiacritics(String str) {
|
||||
var withDia =
|
||||
'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
|
||||
var withoutDia =
|
||||
'AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz';
|
||||
|
||||
for (int i = 0; i < withDia.length; i++) {
|
||||
str = str.replaceAll(withDia[i], withoutDia[i]);
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
extension CountryExtensions on List<Country> {
|
||||
List<Country> stringSearch(String search) {
|
||||
search = removeDiacritics(search.toLowerCase());
|
||||
return where(
|
||||
(country) => isNumeric(search) || search.startsWith("+")
|
||||
? country.dialCode.contains(search)
|
||||
: removeDiacritics(country.name.replaceAll("+", "").toLowerCase())
|
||||
.contains(search) ||
|
||||
country.nameTranslations.values.any((element) =>
|
||||
removeDiacritics(element.toLowerCase()).contains(search)),
|
||||
).toList();
|
||||
}
|
||||
}
|
||||
521
lib/controller/local/phone_intel/intl_phone_field.dart
Normal file
521
lib/controller/local/phone_intel/intl_phone_field.dart
Normal file
@@ -0,0 +1,521 @@
|
||||
library intl_phone_field;
|
||||
|
||||
import 'dart:async';
|
||||
import 'package:flutter/foundation.dart' show kIsWeb;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import './countries.dart';
|
||||
import './phone_number.dart';
|
||||
import 'country_picker_dialog.dart';
|
||||
import 'helpers.dart';
|
||||
|
||||
class IntlPhoneField extends StatefulWidget {
|
||||
/// The TextFormField key.
|
||||
final GlobalKey<FormFieldState>? formFieldKey;
|
||||
|
||||
/// Whether to hide the text being edited (e.g., for passwords).
|
||||
final bool obscureText;
|
||||
|
||||
/// How the text should be aligned horizontally.
|
||||
final TextAlign textAlign;
|
||||
|
||||
/// How the text should be aligned vertically.
|
||||
final TextAlignVertical? textAlignVertical;
|
||||
final VoidCallback? onTap;
|
||||
|
||||
/// {@macro flutter.widgets.editableText.readOnly}
|
||||
final bool readOnly;
|
||||
final FormFieldSetter<PhoneNumber>? onSaved;
|
||||
|
||||
/// {@macro flutter.widgets.editableText.onChanged}
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [inputFormatters], which are called before [onChanged]
|
||||
/// runs and can validate and change ("format") the input value.
|
||||
/// * [onEditingComplete], [onSubmitted], [onSelectionChanged]:
|
||||
/// which are more specialized input change notifications.
|
||||
final ValueChanged<PhoneNumber>? onChanged;
|
||||
|
||||
final ValueChanged<Country>? onCountryChanged;
|
||||
|
||||
/// An optional method that validates an input. Returns an error string to display if the input is invalid, or null otherwise.
|
||||
///
|
||||
/// A [PhoneNumber] is passed to the validator as argument.
|
||||
/// The validator can handle asynchronous validation when declared as a [Future].
|
||||
/// Or run synchronously when declared as a [Function].
|
||||
///
|
||||
/// By default, the validator checks whether the input number length is between selected country's phone numbers min and max length.
|
||||
/// If `disableLengthCheck` is not set to `true`, your validator returned value will be overwritten by the default validator.
|
||||
/// But, if `disableLengthCheck` is set to `true`, your validator will have to check phone number length itself.
|
||||
final FutureOr<String?> Function(PhoneNumber?)? validator;
|
||||
|
||||
/// {@macro flutter.widgets.editableText.keyboardType}
|
||||
final TextInputType keyboardType;
|
||||
|
||||
/// Controls the text being edited.
|
||||
///
|
||||
/// If null, this widget will create its own [TextEditingController].
|
||||
final TextEditingController? controller;
|
||||
|
||||
/// Defines the keyboard focus for this widget.
|
||||
///
|
||||
/// The [focusNode] is a long-lived object that's typically managed by a
|
||||
/// [StatefulWidget] parent. See [FocusNode] for more information.
|
||||
///
|
||||
/// To give the keyboard focus to this widget, provide a [focusNode] and then
|
||||
/// use the current [FocusScope] to request the focus:
|
||||
///
|
||||
/// ```dart
|
||||
/// FocusScope.of(context).requestFocus(myFocusNode);
|
||||
/// ```
|
||||
///
|
||||
/// This happens automatically when the widget is tapped.
|
||||
///
|
||||
/// To be notified when the widget gains or loses the focus, add a listener
|
||||
/// to the [focusNode]:
|
||||
///
|
||||
/// ```dart
|
||||
/// focusNode.addListener(() { print(myFocusNode.hasFocus); });
|
||||
/// ```
|
||||
///
|
||||
/// If null, this widget will create its own [FocusNode].
|
||||
///
|
||||
/// ## Keyboard
|
||||
///
|
||||
/// Requesting the focus will typically cause the keyboard to be shown
|
||||
/// if it's not showing already.
|
||||
///
|
||||
/// On Android, the user can hide the keyboard - without changing the focus -
|
||||
/// with the system back button. They can restore the keyboard's visibility
|
||||
/// by tapping on a text field. The user might hide the keyboard and
|
||||
/// switch to a physical keyboard, or they might just need to get it
|
||||
/// out of the way for a moment, to expose something it's
|
||||
/// obscuring. In this case requesting the focus again will not
|
||||
/// cause the focus to change, and will not make the keyboard visible.
|
||||
///
|
||||
/// This widget builds an [EditableText] and will ensure that the keyboard is
|
||||
/// showing when it is tapped by calling [EditableTextState.requestKeyboard()].
|
||||
final FocusNode? focusNode;
|
||||
|
||||
/// {@macro flutter.widgets.editableText.onSubmitted}
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [EditableText.onSubmitted] for an example of how to handle moving to
|
||||
/// the next/previous field when using [TextInputAction.next] and
|
||||
/// [TextInputAction.previous] for [textInputAction].
|
||||
final void Function(String)? onSubmitted;
|
||||
|
||||
/// If false the widget is "disabled": it ignores taps, the [TextFormField]'s
|
||||
/// [decoration] is rendered in grey,
|
||||
/// [decoration]'s [InputDecoration.counterText] is set to `""`,
|
||||
/// and the drop down icon is hidden no matter [showDropdownIcon] value.
|
||||
///
|
||||
/// If non-null this property overrides the [decoration]'s
|
||||
/// [Decoration.enabled] property.
|
||||
final bool enabled;
|
||||
|
||||
/// The appearance of the keyboard.
|
||||
///
|
||||
/// This setting is only honored on iOS devices.
|
||||
///
|
||||
/// If unset, defaults to the brightness of [ThemeData.brightness].
|
||||
final Brightness? keyboardAppearance;
|
||||
|
||||
/// Initial Value for the field.
|
||||
/// This property can be used to pre-fill the field.
|
||||
final String? initialValue;
|
||||
|
||||
final String languageCode;
|
||||
|
||||
/// 2 letter ISO Code or country dial code.
|
||||
///
|
||||
/// ```dart
|
||||
/// initialCountryCode: 'IN', // India
|
||||
/// initialCountryCode: '+225', // Côte d'Ivoire
|
||||
/// ```
|
||||
final String? initialCountryCode;
|
||||
|
||||
/// List of Country to display see countries.dart for format
|
||||
final List<Country>? countries;
|
||||
|
||||
/// The decoration to show around the text field.
|
||||
///
|
||||
/// By default, draws a horizontal line under the text field but can be
|
||||
/// configured to show an icon, label, hint text, and error text.
|
||||
///
|
||||
/// Specify null to remove the decoration entirely (including the
|
||||
/// extra padding introduced by the decoration to save space for the labels).
|
||||
final InputDecoration decoration;
|
||||
|
||||
/// The style to use for the text being edited.
|
||||
///
|
||||
/// This text style is also used as the base style for the [decoration].
|
||||
///
|
||||
/// If null, defaults to the `subtitle1` text style from the current [Theme].
|
||||
final TextStyle? style;
|
||||
|
||||
/// Disable view Min/Max Length check
|
||||
final bool disableLengthCheck;
|
||||
|
||||
/// Won't work if [enabled] is set to `false`.
|
||||
final bool showDropdownIcon;
|
||||
|
||||
final BoxDecoration dropdownDecoration;
|
||||
|
||||
/// The style use for the country dial code.
|
||||
final TextStyle? dropdownTextStyle;
|
||||
|
||||
/// {@macro flutter.widgets.editableText.inputFormatters}
|
||||
final List<TextInputFormatter>? inputFormatters;
|
||||
|
||||
/// The text that describes the search input field.
|
||||
///
|
||||
/// When the input field is empty and unfocused, the label is displayed on top of the input field (i.e., at the same location on the screen where text may be entered in the input field).
|
||||
/// When the input field receives focus (or if the field is non-empty), the label moves above (i.e., vertically adjacent to) the input field.
|
||||
final String searchText;
|
||||
|
||||
/// Position of an icon [leading, trailing]
|
||||
final IconPosition dropdownIconPosition;
|
||||
|
||||
/// Icon of the drop down button.
|
||||
///
|
||||
/// Default is [Icon(Icons.arrow_drop_down)]
|
||||
final Icon dropdownIcon;
|
||||
|
||||
/// Whether this text field should focus itself if nothing else is already focused.
|
||||
final bool autofocus;
|
||||
|
||||
/// Autovalidate mode for text form field.
|
||||
///
|
||||
/// If [AutovalidateMode.onUserInteraction], this FormField will only auto-validate after its content changes.
|
||||
/// If [AutovalidateMode.always], it will auto-validate even without user interaction.
|
||||
/// If [AutovalidateMode.disabled], auto-validation will be disabled.
|
||||
///
|
||||
/// Defaults to [AutovalidateMode.onUserInteraction].
|
||||
final AutovalidateMode? autovalidateMode;
|
||||
|
||||
/// Whether to show or hide country flag.
|
||||
///
|
||||
/// Default value is `true`.
|
||||
final bool showCountryFlag;
|
||||
|
||||
/// Message to be displayed on autoValidate error
|
||||
///
|
||||
/// Default value is `Invalid Mobile Number`.
|
||||
final String? invalidNumberMessage;
|
||||
|
||||
/// The color of the cursor.
|
||||
final Color? cursorColor;
|
||||
|
||||
/// How tall the cursor will be.
|
||||
final double? cursorHeight;
|
||||
|
||||
/// How rounded the corners of the cursor should be.
|
||||
final Radius? cursorRadius;
|
||||
|
||||
/// How thick the cursor will be.
|
||||
final double cursorWidth;
|
||||
|
||||
/// Whether to show cursor.
|
||||
final bool? showCursor;
|
||||
|
||||
/// The padding of the Flags Button.
|
||||
///
|
||||
/// The amount of insets that are applied to the Flags Button.
|
||||
///
|
||||
/// If unset, defaults to [EdgeInsets.zero].
|
||||
final EdgeInsetsGeometry flagsButtonPadding;
|
||||
|
||||
/// The type of action button to use for the keyboard.
|
||||
final TextInputAction? textInputAction;
|
||||
|
||||
/// Optional set of styles to allow for customizing the country search
|
||||
/// & pick dialog
|
||||
final PickerDialogStyle? pickerDialogStyle;
|
||||
|
||||
/// The margin of the country selector button.
|
||||
///
|
||||
/// The amount of space to surround the country selector button.
|
||||
///
|
||||
/// If unset, defaults to [EdgeInsets.zero].
|
||||
final EdgeInsets flagsButtonMargin;
|
||||
|
||||
/// Enable the autofill hint for phone number.
|
||||
final bool disableAutoFillHints;
|
||||
|
||||
/// If null, default magnification configuration will be used.
|
||||
final TextMagnifierConfiguration? magnifierConfiguration;
|
||||
|
||||
const IntlPhoneField({
|
||||
Key? key,
|
||||
this.formFieldKey,
|
||||
this.initialCountryCode,
|
||||
this.languageCode = 'en',
|
||||
this.disableAutoFillHints = false,
|
||||
this.obscureText = false,
|
||||
this.textAlign = TextAlign.left,
|
||||
this.textAlignVertical,
|
||||
this.onTap,
|
||||
this.readOnly = false,
|
||||
this.initialValue,
|
||||
this.keyboardType = TextInputType.phone,
|
||||
this.controller,
|
||||
this.focusNode,
|
||||
this.decoration = const InputDecoration(),
|
||||
this.style,
|
||||
this.dropdownTextStyle,
|
||||
this.onSubmitted,
|
||||
this.validator,
|
||||
this.onChanged,
|
||||
this.countries,
|
||||
this.onCountryChanged,
|
||||
this.onSaved,
|
||||
this.showDropdownIcon = true,
|
||||
this.dropdownDecoration = const BoxDecoration(),
|
||||
this.inputFormatters,
|
||||
this.enabled = true,
|
||||
this.keyboardAppearance,
|
||||
@Deprecated('Use searchFieldInputDecoration of PickerDialogStyle instead')
|
||||
this.searchText = 'Search country',
|
||||
this.dropdownIconPosition = IconPosition.leading,
|
||||
this.dropdownIcon = const Icon(Icons.arrow_drop_down),
|
||||
this.autofocus = false,
|
||||
this.textInputAction,
|
||||
this.autovalidateMode = AutovalidateMode.onUserInteraction,
|
||||
this.showCountryFlag = true,
|
||||
this.cursorColor,
|
||||
this.disableLengthCheck = false,
|
||||
this.flagsButtonPadding = EdgeInsets.zero,
|
||||
this.invalidNumberMessage = 'Invalid Mobile Number',
|
||||
this.cursorHeight,
|
||||
this.cursorRadius = Radius.zero,
|
||||
this.cursorWidth = 2.0,
|
||||
this.showCursor = true,
|
||||
this.pickerDialogStyle,
|
||||
this.flagsButtonMargin = EdgeInsets.zero,
|
||||
this.magnifierConfiguration,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<IntlPhoneField> createState() => _IntlPhoneFieldState();
|
||||
}
|
||||
|
||||
class _IntlPhoneFieldState extends State<IntlPhoneField> {
|
||||
late List<Country> _countryList;
|
||||
late Country _selectedCountry;
|
||||
late List<Country> filteredCountries;
|
||||
late String number;
|
||||
|
||||
String? validatorMessage;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_countryList = widget.countries ?? countries;
|
||||
filteredCountries = _countryList;
|
||||
number = widget.initialValue ?? '';
|
||||
if (widget.initialCountryCode == null && number.startsWith('+')) {
|
||||
number = number.substring(1);
|
||||
// parse initial value
|
||||
_selectedCountry = countries.firstWhere(
|
||||
(country) => number.startsWith(country.fullCountryCode),
|
||||
orElse: () => _countryList.first);
|
||||
|
||||
// remove country code from the initial number value
|
||||
number = number.replaceFirst(
|
||||
RegExp("^${_selectedCountry.fullCountryCode}"), "");
|
||||
} else {
|
||||
_selectedCountry = _countryList.firstWhere(
|
||||
(item) => item.code == (widget.initialCountryCode ?? 'US'),
|
||||
orElse: () => _countryList.first);
|
||||
|
||||
// remove country code from the initial number value
|
||||
if (number.startsWith('+')) {
|
||||
number = number.replaceFirst(
|
||||
RegExp("^\\+${_selectedCountry.fullCountryCode}"), "");
|
||||
} else {
|
||||
number = number.replaceFirst(
|
||||
RegExp("^${_selectedCountry.fullCountryCode}"), "");
|
||||
}
|
||||
}
|
||||
|
||||
if (widget.autovalidateMode == AutovalidateMode.always) {
|
||||
final initialPhoneNumber = PhoneNumber(
|
||||
countryISOCode: _selectedCountry.code,
|
||||
countryCode: '+${_selectedCountry.dialCode}',
|
||||
number: widget.initialValue ?? '',
|
||||
);
|
||||
|
||||
final value = widget.validator?.call(initialPhoneNumber);
|
||||
|
||||
if (value is String) {
|
||||
validatorMessage = value;
|
||||
} else {
|
||||
(value as Future).then((msg) {
|
||||
validatorMessage = msg;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _changeCountry() async {
|
||||
filteredCountries = _countryList;
|
||||
await showDialog(
|
||||
context: context,
|
||||
useRootNavigator: false,
|
||||
builder: (context) => StatefulBuilder(
|
||||
builder: (ctx, setState) => CountryPickerDialog(
|
||||
languageCode: widget.languageCode.toLowerCase(),
|
||||
style: widget.pickerDialogStyle,
|
||||
filteredCountries: filteredCountries,
|
||||
searchText: widget.searchText,
|
||||
countryList: _countryList,
|
||||
selectedCountry: _selectedCountry,
|
||||
onCountryChanged: (Country country) {
|
||||
_selectedCountry = country;
|
||||
widget.onCountryChanged?.call(country);
|
||||
setState(() {});
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return TextFormField(
|
||||
key: widget.formFieldKey,
|
||||
initialValue: (widget.controller == null) ? number : null,
|
||||
autofillHints: widget.disableAutoFillHints
|
||||
? null
|
||||
: [AutofillHints.telephoneNumberNational],
|
||||
readOnly: widget.readOnly,
|
||||
obscureText: widget.obscureText,
|
||||
textAlign: widget.textAlign,
|
||||
textAlignVertical: widget.textAlignVertical,
|
||||
cursorColor: widget.cursorColor,
|
||||
onTap: widget.onTap,
|
||||
controller: widget.controller,
|
||||
focusNode: widget.focusNode,
|
||||
cursorHeight: widget.cursorHeight,
|
||||
cursorRadius: widget.cursorRadius,
|
||||
cursorWidth: widget.cursorWidth,
|
||||
showCursor: widget.showCursor,
|
||||
onFieldSubmitted: widget.onSubmitted,
|
||||
magnifierConfiguration: widget.magnifierConfiguration,
|
||||
decoration: widget.decoration.copyWith(
|
||||
prefixIcon: _buildFlagsButton(),
|
||||
counterText: !widget.enabled ? '' : null,
|
||||
),
|
||||
style: widget.style,
|
||||
onSaved: (value) {
|
||||
widget.onSaved?.call(
|
||||
PhoneNumber(
|
||||
countryISOCode: _selectedCountry.code,
|
||||
countryCode:
|
||||
'+${_selectedCountry.dialCode}${_selectedCountry.regionCode}',
|
||||
number: value!,
|
||||
),
|
||||
);
|
||||
},
|
||||
onChanged: (value) async {
|
||||
final phoneNumber = PhoneNumber(
|
||||
countryISOCode: _selectedCountry.code,
|
||||
countryCode: '+${_selectedCountry.fullCountryCode}',
|
||||
number: value,
|
||||
);
|
||||
|
||||
if (widget.autovalidateMode != AutovalidateMode.disabled) {
|
||||
validatorMessage = await widget.validator?.call(phoneNumber);
|
||||
}
|
||||
|
||||
widget.onChanged?.call(phoneNumber);
|
||||
},
|
||||
validator: (value) {
|
||||
if (value == null || !isNumeric(value)) return validatorMessage;
|
||||
if (!widget.disableLengthCheck) {
|
||||
return value.length >= _selectedCountry.minLength &&
|
||||
value.length <= _selectedCountry.maxLength
|
||||
? null
|
||||
: widget.invalidNumberMessage;
|
||||
}
|
||||
|
||||
return validatorMessage;
|
||||
},
|
||||
maxLength: widget.disableLengthCheck ? null : _selectedCountry.maxLength,
|
||||
keyboardType: widget.keyboardType,
|
||||
inputFormatters: widget.inputFormatters,
|
||||
enabled: widget.enabled,
|
||||
keyboardAppearance: widget.keyboardAppearance,
|
||||
autofocus: widget.autofocus,
|
||||
textInputAction: widget.textInputAction,
|
||||
autovalidateMode: widget.autovalidateMode,
|
||||
);
|
||||
}
|
||||
|
||||
Container _buildFlagsButton() {
|
||||
return Container(
|
||||
margin: widget.flagsButtonMargin,
|
||||
child: DecoratedBox(
|
||||
decoration: widget.dropdownDecoration,
|
||||
child: InkWell(
|
||||
borderRadius: widget.dropdownDecoration.borderRadius as BorderRadius?,
|
||||
onTap: widget.enabled ? _changeCountry : null,
|
||||
child: Padding(
|
||||
padding: widget.flagsButtonPadding,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
const SizedBox(
|
||||
width: 4,
|
||||
),
|
||||
if (widget.enabled &&
|
||||
widget.showDropdownIcon &&
|
||||
widget.dropdownIconPosition == IconPosition.leading) ...[
|
||||
widget.dropdownIcon,
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
if (widget.showCountryFlag) ...[
|
||||
kIsWeb
|
||||
? Image.asset(
|
||||
'assets/flags/${_selectedCountry.code.toLowerCase()}.png',
|
||||
package: 'intl_phone_field',
|
||||
width: 32,
|
||||
)
|
||||
: Text(
|
||||
_selectedCountry.flag,
|
||||
style: const TextStyle(fontSize: 18),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
],
|
||||
FittedBox(
|
||||
child: Text(
|
||||
'+${_selectedCountry.dialCode}',
|
||||
style: widget.dropdownTextStyle,
|
||||
),
|
||||
),
|
||||
if (widget.enabled &&
|
||||
widget.showDropdownIcon &&
|
||||
widget.dropdownIconPosition == IconPosition.trailing) ...[
|
||||
const SizedBox(width: 4),
|
||||
widget.dropdownIcon,
|
||||
],
|
||||
const SizedBox(width: 8),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum IconPosition {
|
||||
leading,
|
||||
trailing,
|
||||
}
|
||||
79
lib/controller/local/phone_intel/phone_number.dart
Normal file
79
lib/controller/local/phone_intel/phone_number.dart
Normal file
@@ -0,0 +1,79 @@
|
||||
import 'countries.dart';
|
||||
|
||||
class NumberTooLongException implements Exception {}
|
||||
|
||||
class NumberTooShortException implements Exception {}
|
||||
|
||||
class InvalidCharactersException implements Exception {}
|
||||
|
||||
class PhoneNumber {
|
||||
String countryISOCode;
|
||||
String countryCode;
|
||||
String number;
|
||||
|
||||
PhoneNumber({
|
||||
required this.countryISOCode,
|
||||
required this.countryCode,
|
||||
required this.number,
|
||||
});
|
||||
|
||||
factory PhoneNumber.fromCompleteNumber({required String completeNumber}) {
|
||||
if (completeNumber == "") {
|
||||
return PhoneNumber(countryISOCode: "", countryCode: "", number: "");
|
||||
}
|
||||
|
||||
try {
|
||||
Country country = getCountry(completeNumber);
|
||||
String number;
|
||||
if (completeNumber.startsWith('+')) {
|
||||
number = completeNumber.substring(1 + country.dialCode.length + country.regionCode.length);
|
||||
} else {
|
||||
number = completeNumber.substring(country.dialCode.length + country.regionCode.length);
|
||||
}
|
||||
return PhoneNumber(
|
||||
countryISOCode: country.code, countryCode: country.dialCode + country.regionCode, number: number);
|
||||
} on InvalidCharactersException {
|
||||
rethrow;
|
||||
// ignore: unused_catch_clause
|
||||
} on Exception catch (e) {
|
||||
return PhoneNumber(countryISOCode: "", countryCode: "", number: "");
|
||||
}
|
||||
}
|
||||
|
||||
bool isValidNumber() {
|
||||
Country country = getCountry(completeNumber);
|
||||
if (number.length < country.minLength) {
|
||||
throw NumberTooShortException();
|
||||
}
|
||||
|
||||
if (number.length > country.maxLength) {
|
||||
throw NumberTooLongException();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
String get completeNumber {
|
||||
return countryCode + number;
|
||||
}
|
||||
|
||||
static Country getCountry(String phoneNumber) {
|
||||
if (phoneNumber == "") {
|
||||
throw NumberTooShortException();
|
||||
}
|
||||
|
||||
final validPhoneNumber = RegExp(r'^[+0-9]*[0-9]*$');
|
||||
|
||||
if (!validPhoneNumber.hasMatch(phoneNumber)) {
|
||||
throw InvalidCharactersException();
|
||||
}
|
||||
|
||||
if (phoneNumber.startsWith('+')) {
|
||||
return countries
|
||||
.firstWhere((country) => phoneNumber.substring(1).startsWith(country.dialCode + country.regionCode));
|
||||
}
|
||||
return countries.firstWhere((country) => phoneNumber.startsWith(country.dialCode + country.regionCode));
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() => 'PhoneNumber(countryISOCode: $countryISOCode, countryCode: $countryCode, number: $number)';
|
||||
}
|
||||
19372
lib/controller/local/translations.dart
Normal file
19372
lib/controller/local/translations.dart
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,62 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/style.dart';
|
||||
import 'package:Intaleq/views/widgets/elevated_btn.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../main.dart';
|
||||
import '../functions/crud.dart';
|
||||
|
||||
class NotificationCaptainController extends GetxController {
|
||||
bool isLoading = false;
|
||||
Map notificationData = {};
|
||||
|
||||
getNotifications() async {
|
||||
isLoading = true;
|
||||
update();
|
||||
var res = await CRUD().get(
|
||||
link: AppLink.getNotificationCaptain,
|
||||
payload: {'driverID': box.read(BoxName.driverID)});
|
||||
if (res == "failure") {
|
||||
Get.defaultDialog(
|
||||
title: 'There is no notification yet'.tr,
|
||||
titleStyle: AppStyle.title,
|
||||
middleText: '',
|
||||
confirm: MyElevatedButton(
|
||||
title: 'Back',
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
Get.back();
|
||||
}));
|
||||
}
|
||||
notificationData = jsonDecode(res);
|
||||
// sql.insertData(notificationData['message'], TableName.captainNotification);
|
||||
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
updateNotification(String id) async {
|
||||
await CRUD().post(
|
||||
link: AppLink.updateNotificationCaptain,
|
||||
payload: {'isShown': true, 'id': id},
|
||||
);
|
||||
}
|
||||
|
||||
addNotificationCaptain(String driverId, title, body, isPin) async {
|
||||
await CRUD().post(link: AppLink.addNotificationCaptain, payload: {
|
||||
'driverID': driverId,
|
||||
'title': title,
|
||||
'body': body,
|
||||
'isPin': isPin
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
getNotifications();
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/controller/firebase/firbase_messge.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../main.dart';
|
||||
import '../../views/widgets/mydialoug.dart';
|
||||
import '../functions/crud.dart';
|
||||
|
||||
class PassengerNotificationController extends GetxController {
|
||||
bool isloading = false;
|
||||
Map notificationData = {};
|
||||
|
||||
getNotifications() async {
|
||||
isloading = true;
|
||||
update();
|
||||
var res = await CRUD().get(
|
||||
link: AppLink.getNotificationPassenger,
|
||||
payload: {'passenger_id': box.read(BoxName.passengerID)});
|
||||
if (res == "failure") {
|
||||
MyDialog().getDialog('There is no notification yet'.tr, '', () {
|
||||
Get.back();
|
||||
Get.back();
|
||||
});
|
||||
} else {
|
||||
notificationData = jsonDecode(res);
|
||||
isloading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
// sql.insertData(notificationData['message'], TableName.captainNotification);
|
||||
}
|
||||
|
||||
updateNotification(String id) async {
|
||||
await CRUD().post(
|
||||
link: AppLink.updateNotificationPassenger,
|
||||
payload: {'isShown': 'true', 'id': id},
|
||||
);
|
||||
Get.back();
|
||||
getNotifications();
|
||||
}
|
||||
|
||||
addNotificationToPassenger(String title, body) async {
|
||||
var res = CRUD().post(link: AppLink.addNotificationPassenger, payload: {
|
||||
'title': title,
|
||||
'body': body,
|
||||
});
|
||||
Get.find<FirebaseMessagesController>().sendNotificationToPassengerToken(
|
||||
title,
|
||||
body,
|
||||
'token',
|
||||
[],
|
||||
'iphone_ringtone.wav',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
getNotifications();
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
39
lib/controller/notification/ride_available_controller.dart
Normal file
39
lib/controller/notification/ride_available_controller.dart
Normal file
@@ -0,0 +1,39 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:Intaleq/constant/style.dart';
|
||||
import 'package:Intaleq/views/widgets/elevated_btn.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../constant/links.dart';
|
||||
import '../functions/crud.dart';
|
||||
|
||||
class RideAvailableController extends GetxController {
|
||||
bool isLoading = false;
|
||||
Map rideAvailableMap = {};
|
||||
getRideAvailable() async {
|
||||
isLoading = true;
|
||||
var res = await CRUD().get(link: AppLink.getRideWaiting, payload: {});
|
||||
if (res != 'failure') {
|
||||
rideAvailableMap = jsonDecode(res);
|
||||
isLoading = false;
|
||||
update();
|
||||
} else {
|
||||
Get.defaultDialog(
|
||||
title: 'No Rides now!'.tr,
|
||||
middleText: '',
|
||||
titleStyle: AppStyle.title,
|
||||
confirm: MyElevatedButton(
|
||||
title: 'Ok'.tr,
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
Get.back();
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
getRideAvailable();
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
43
lib/controller/payment/driver_payment_controller.dart
Normal file
43
lib/controller/payment/driver_payment_controller.dart
Normal file
@@ -0,0 +1,43 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:Intaleq/views/widgets/elevated_btn.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
|
||||
class DriverWalletHistoryController extends GetxController {
|
||||
bool isLoading = false;
|
||||
List archive = [];
|
||||
|
||||
getArchivePayment() async {
|
||||
isLoading = true;
|
||||
update();
|
||||
var res = await CRUD().getWallet(
|
||||
link: AppLink.getWalletByDriver,
|
||||
payload: {'driverID': box.read(BoxName.driverID)});
|
||||
if (res == 'failure') {
|
||||
Get.defaultDialog(
|
||||
barrierDismissible: false,
|
||||
title: 'There is no data yet.'.tr,
|
||||
middleText: '',
|
||||
confirm: MyElevatedButton(
|
||||
title: 'Back'.tr,
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
Get.back();
|
||||
},
|
||||
));
|
||||
}
|
||||
archive = jsonDecode(res)['message'];
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
getArchivePayment();
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
|
||||
import '../../views/widgets/mydialoug.dart';
|
||||
|
||||
class PassengerWalletHistoryController extends GetxController {
|
||||
bool isLoading = false;
|
||||
List archive = [];
|
||||
|
||||
Future<void> getArchivePayment() async {
|
||||
try {
|
||||
isLoading = true;
|
||||
update();
|
||||
|
||||
var res = await CRUD().getWallet(
|
||||
link: AppLink.getPassengerWalletArchive,
|
||||
payload: {'passenger_id': box.read(BoxName.passengerID)},
|
||||
);
|
||||
|
||||
if (res != 'failure') {
|
||||
archive = jsonDecode(res)['message'];
|
||||
} else {
|
||||
MyDialog().getDialog('No wallet record found'.tr, '', () {
|
||||
Get.back();
|
||||
Get.back();
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
MyDialog().getDialog('An error occurred'.tr, e.toString(), () {
|
||||
Get.back();
|
||||
});
|
||||
} finally {
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
getArchivePayment();
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
926
lib/controller/payment/payment_controller.dart
Normal file
926
lib/controller/payment/payment_controller.dart
Normal file
@@ -0,0 +1,926 @@
|
||||
import 'dart:convert';
|
||||
import 'package:Intaleq/constant/api_key.dart';
|
||||
import 'package:Intaleq/constant/style.dart';
|
||||
import 'package:Intaleq/controller/firebase/firbase_messge.dart';
|
||||
import 'package:Intaleq/controller/payment/paymob/paymob_response.dart';
|
||||
import 'package:Intaleq/views/home/map_page_passenger.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_paypal/flutter_paypal.dart';
|
||||
import 'package:flutter_stripe/flutter_stripe.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:local_auth/local_auth.dart';
|
||||
import 'package:Intaleq/controller/home/map_passenger_controller.dart';
|
||||
import 'package:webview_flutter/webview_flutter.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../constant/colors.dart';
|
||||
import '../../constant/info.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.dart';
|
||||
import '../functions/crud.dart';
|
||||
import '../functions/encrypt_decrypt.dart';
|
||||
import '../functions/toast.dart';
|
||||
import 'paymob/e_cash_screen.dart';
|
||||
|
||||
class PaymentController extends GetxController {
|
||||
bool isLoading = false;
|
||||
bool isWalletChecked = true;
|
||||
bool isCashChecked = false;
|
||||
bool isWalletFound = false;
|
||||
bool isPromoSheetDialogue = false;
|
||||
final formKey = GlobalKey<FormState>();
|
||||
final promo = TextEditingController();
|
||||
final walletphoneController = TextEditingController();
|
||||
double totalPassenger = Get.find<MapPassengerController>().totalPassenger;
|
||||
int? selectedAmount = 0;
|
||||
List<dynamic> totalPassengerWalletDetails = [];
|
||||
String passengerTotalWalletAmount = '';
|
||||
String ip = '1';
|
||||
DateTime now = DateTime.now();
|
||||
late int timestamp;
|
||||
|
||||
void updateSelectedAmount(int value) {
|
||||
selectedAmount = value;
|
||||
update();
|
||||
}
|
||||
|
||||
void changePromoSheetDialogue() {
|
||||
isPromoSheetDialogue = !isPromoSheetDialogue;
|
||||
update();
|
||||
}
|
||||
|
||||
getPassengerWallet() async {
|
||||
isLoading = true;
|
||||
update();
|
||||
|
||||
await CRUD().getWallet(
|
||||
link: AppLink.getWalletByPassenger,
|
||||
payload: {'passenger_id': box.read(BoxName.passengerID)}).then((value) {
|
||||
box.write(BoxName.passengerWalletTotal,
|
||||
jsonDecode(value)['message'][0]['total'].toString());
|
||||
});
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
String paymentToken = '';
|
||||
Future<String> generateTokenPassenger(String amount) async {
|
||||
var res =
|
||||
await CRUD().post(link: AppLink.addPaymentTokenPassenger, payload: {
|
||||
'passengerId': box.read(BoxName.passengerID).toString(),
|
||||
'amount': amount.toString(),
|
||||
});
|
||||
var d = jsonDecode(res);
|
||||
return d['message'];
|
||||
}
|
||||
|
||||
Future<String> generateTokenDriver(String amount) async {
|
||||
var res = await CRUD().post(link: AppLink.addPaymentTokenDriver, payload: {
|
||||
'driverID': Get.find<MapPassengerController>().driverId,
|
||||
'amount': amount.toString(),
|
||||
});
|
||||
var d = jsonDecode(res);
|
||||
return d['message'];
|
||||
}
|
||||
|
||||
Future addSeferWallet(String paymentMethod, point) async {
|
||||
var seferToken = await generateTokenPassenger(point);
|
||||
await CRUD().postWallet(link: AppLink.addSeferWallet, payload: {
|
||||
'amount': point.toString(),
|
||||
'paymentMethod': paymentMethod,
|
||||
'passengerId': box.read(BoxName.passengerID).toString(),
|
||||
'token': seferToken,
|
||||
'driverId': 'passenger',
|
||||
});
|
||||
}
|
||||
|
||||
Future addPassengersWallet(String point) async {
|
||||
var token = await generateTokenPassenger(point);
|
||||
await CRUD().postWallet(link: AppLink.addPassengersWallet, payload: {
|
||||
'passenger_id': box.read(BoxName.passengerID).toString(),
|
||||
'balance': point,
|
||||
'token': token,
|
||||
});
|
||||
}
|
||||
|
||||
payToDriverForCancelAfterAppliedAndHeNearYou(String rideId) async {
|
||||
{
|
||||
double costOfWaiting5Minute = box.read(BoxName.countryCode) == 'Egypt'
|
||||
? (4 * .08) + (5 * 1)
|
||||
// 4 indicate foe 4 km ditance from driver start move to passenger
|
||||
: (4 * .06) + (5 * .06); //for Eygpt other like jordan .06 per minute
|
||||
var paymentTokenWait =
|
||||
await generateTokenDriver(costOfWaiting5Minute.toString());
|
||||
var res =
|
||||
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
|
||||
'rideId': rideId,
|
||||
'amount': costOfWaiting5Minute.toString(),
|
||||
'payment_method': 'cancel-from-near',
|
||||
'passengerID': box.read(BoxName.passengerID).toString(),
|
||||
'token': paymentTokenWait,
|
||||
'driverID': Get.find<MapPassengerController>().driverId.toString(),
|
||||
});
|
||||
var paymentTokenWait1 =
|
||||
await generateTokenDriver(costOfWaiting5Minute.toString());
|
||||
var res1 = await CRUD()
|
||||
.postWallet(link: AppLink.addDriversWalletPoints, payload: {
|
||||
'paymentID': 'rideId$rideId',
|
||||
'amount': (costOfWaiting5Minute).toStringAsFixed(0),
|
||||
'paymentMethod': 'cancel-from-near',
|
||||
'token': paymentTokenWait1,
|
||||
'driverID': Get.find<MapPassengerController>().driverId.toString(),
|
||||
});
|
||||
|
||||
if (res != 'failure') {
|
||||
Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
|
||||
'Cancel',
|
||||
'Trip Cancelled. The cost of the trip will be added to your wallet.'
|
||||
.tr,
|
||||
Get.find<MapPassengerController>().driverToken,
|
||||
[],
|
||||
'cancel.wav',
|
||||
);
|
||||
}
|
||||
var paymentTokenWaitPassenger1 =
|
||||
await generateTokenPassenger((costOfWaiting5Minute * -1).toString());
|
||||
await CRUD().post(link: AppLink.addPassengersWallet, payload: {
|
||||
'passenger_id': box.read(BoxName.passengerID).toString(),
|
||||
'balance': (costOfWaiting5Minute * -1).toString(),
|
||||
'token': paymentTokenWaitPassenger1,
|
||||
});
|
||||
Get.offAll(const MapPagePassenger());
|
||||
}
|
||||
}
|
||||
|
||||
addPassengerWallet() async {
|
||||
isLoading = true;
|
||||
update();
|
||||
|
||||
await addSeferWallet('visa-in', selectedAmount.toString());
|
||||
await addPassengersWallet(selectedAmount == 100
|
||||
? '100'
|
||||
: selectedAmount == 200
|
||||
? '215'
|
||||
: selectedAmount == 400
|
||||
? '450'
|
||||
: selectedAmount == 1000
|
||||
? '1140'
|
||||
: '0');
|
||||
|
||||
// getPassengerWallet();
|
||||
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
void onChangedPaymentMethodWallet(bool? value) {
|
||||
if (box.read(BoxName.passengerWalletTotal) == null ||
|
||||
double.parse(box.read(BoxName.passengerWalletTotal).toString()) <
|
||||
totalPassenger) {
|
||||
isWalletChecked = false;
|
||||
isWalletChecked ? isCashChecked = true : isCashChecked = true;
|
||||
update();
|
||||
} else {
|
||||
isWalletChecked = !isWalletChecked;
|
||||
isWalletChecked ? isCashChecked = false : isCashChecked = true;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
void onChangedPaymentMethodCash(bool? value) {
|
||||
if (box.read(BoxName.passengerWalletTotal) == null ||
|
||||
double.parse(box.read(BoxName.passengerWalletTotal)) < totalPassenger) {
|
||||
isWalletChecked = false;
|
||||
isCashChecked = !isCashChecked;
|
||||
isCashChecked ? isWalletChecked = false : isWalletChecked = false;
|
||||
update();
|
||||
} else {
|
||||
isCashChecked = !isCashChecked;
|
||||
isCashChecked ? isWalletChecked = false : isWalletChecked = true;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
void applyPromoCodeToPassenger() async {
|
||||
//TAWJIHI
|
||||
CRUD().get(link: AppLink.getPassengersPromo, payload: {
|
||||
'promo_code': promo.text,
|
||||
}).then((value) {
|
||||
var decod = jsonDecode(value);
|
||||
|
||||
if (decod["status"] == "success") {
|
||||
var firstElement = decod["message"][0];
|
||||
totalPassenger = totalPassenger -
|
||||
(totalPassenger * int.parse(firstElement['amount']));
|
||||
MapPassengerController().promoTaken = true;
|
||||
update();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
late String clientSecret;
|
||||
|
||||
Future<void> makePaymentStripe(
|
||||
double amount, String currency, Function method) async {
|
||||
var newAmount = (amount * 100).toInt();
|
||||
|
||||
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
|
||||
clientSecret = await getClientSecret(newAmount.toString(), currency);
|
||||
await initializePaymentSheet(clientSecret);
|
||||
await Stripe.instance.presentPaymentSheet();
|
||||
method();
|
||||
} else {
|
||||
// Authentication failed, handle accordingly
|
||||
}
|
||||
} else {
|
||||
// Local authentication not available, proceed with payment without authentication
|
||||
clientSecret = await getClientSecret(newAmount.toString(), currency);
|
||||
await initializePaymentSheet(clientSecret);
|
||||
await Stripe.instance.presentPaymentSheet();
|
||||
method();
|
||||
}
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> initializePaymentSheet(String clientSecret) async {
|
||||
await Stripe.instance.initPaymentSheet(
|
||||
paymentSheetParameters: SetupPaymentSheetParameters(
|
||||
// intentConfiguration: IntentConfiguration.fromJson({}),
|
||||
// applePay: const PaymentSheetApplePay(merchantCountryCode: 'US'),
|
||||
// googlePay: const PaymentSheetGooglePay(merchantCountryCode: 'US'),
|
||||
paymentIntentClientSecret: clientSecret,
|
||||
merchantDisplayName: AppInformation.appName,
|
||||
billingDetails: BillingDetails(
|
||||
name: box.read(BoxName.nameDriver) == null
|
||||
? (box.read(BoxName.name).toString().split(' ')[0]).toString()
|
||||
: box.read(BoxName.nameDriver).toString(),
|
||||
email: box.read(BoxName.emailDriver) == null
|
||||
? box.read(BoxName.email).toString()
|
||||
: box.read(BoxName.emailDriver).toString(),
|
||||
phone: box.read(BoxName.phoneDriver) == null
|
||||
? box.read(BoxName.phone).toString()
|
||||
: box.read(BoxName.phoneDriver).toString(),
|
||||
address: Address(
|
||||
city: 'city',
|
||||
country: box.read(BoxName.countryCode), //'United States'
|
||||
line1: '',
|
||||
line2: '',
|
||||
postalCode: '12345',
|
||||
state: box.read(BoxName.countryCode) // 'Boston'
|
||||
)),
|
||||
allowsDelayedPaymentMethods: true,
|
||||
customerEphemeralKeySecret: Stripe.merchantIdentifier,
|
||||
appearance: const PaymentSheetAppearance(
|
||||
shapes: PaymentSheetShape(borderRadius: 12),
|
||||
colors: PaymentSheetAppearanceColors(
|
||||
background: AppColor.secondaryColor,
|
||||
),
|
||||
),
|
||||
billingDetailsCollectionConfiguration:
|
||||
const BillingDetailsCollectionConfiguration(
|
||||
name: CollectionMode.automatic,
|
||||
phone: CollectionMode.automatic,
|
||||
email: CollectionMode.automatic,
|
||||
// address: CollectionMode.automatic,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<String> getClientSecret(String amount, currency) async {
|
||||
var res = await CRUD().postStripe(
|
||||
link: 'https://api.stripe.com/v1/payment_intents',
|
||||
payload: {
|
||||
'amount': amount,
|
||||
'currency': currency,
|
||||
'payment_method_types[0]': 'card'
|
||||
},
|
||||
);
|
||||
|
||||
// Convert the res object to a JSON object
|
||||
final jsonResponse = jsonDecode(res);
|
||||
// Check if the client_secret property exists and is not null
|
||||
if (jsonResponse.containsKey('client_secret') &&
|
||||
jsonResponse['client_secret'] != null) {
|
||||
// Return the client_secret property
|
||||
return jsonResponse['client_secret'] as String;
|
||||
} else {
|
||||
throw Exception('Failed to fetch client secret');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> configure3dSecureFuture() async {
|
||||
await Stripe.instance.openApplePaySetup();
|
||||
}
|
||||
|
||||
Future<void> makePaymentPayPal(BuildContext context) 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
|
||||
|
||||
if (selectedAmount != 0) {
|
||||
changePromoSheetDialogue();
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (BuildContext context) => UsePaypal(
|
||||
sandboxMode: true,
|
||||
clientId: AK.payPalClientId,
|
||||
secretKey: AK.payPalSecret,
|
||||
returnURL: AppInformation.website,
|
||||
cancelURL: "${AppInformation.website}/cancel",
|
||||
transactions: [
|
||||
{
|
||||
"amount": {
|
||||
//sb-opsju26682403@personal.example.com
|
||||
"total": '$selectedAmount',
|
||||
"currency": box.read(BoxName.countryCode) == 'Egypt'
|
||||
? 'EGP'
|
||||
: "JOD",
|
||||
"details": {
|
||||
"subtotal": '$selectedAmount',
|
||||
"shipping": '0',
|
||||
"shipping_discount": 0
|
||||
}
|
||||
},
|
||||
"description": "The payment transaction description.",
|
||||
"payment_options": const {
|
||||
"allowed_payment_method": "INSTANT_FUNDING_SOURCE"
|
||||
},
|
||||
"item_list": {
|
||||
"items": [
|
||||
{
|
||||
"name": "${AppInformation.appName} Wallet ",
|
||||
"quantity": 1,
|
||||
"price": '$selectedAmount',
|
||||
"currency": "USD"
|
||||
}
|
||||
],
|
||||
|
||||
// shipping address is not required though
|
||||
"shipping_address": const {
|
||||
"recipient_name":
|
||||
"${AppInformation.appName} Wallet",
|
||||
"line1": "Shafa Badran",
|
||||
"line2": "",
|
||||
"city": "Amman",
|
||||
"country_code": "JO",
|
||||
"postal_code": "13112",
|
||||
"phone": "+962798583052",
|
||||
"state": "Amman"
|
||||
},
|
||||
}
|
||||
}
|
||||
],
|
||||
note: "Contact us for any questions on your order.".tr,
|
||||
onSuccess: (Map params) async {
|
||||
addPassengerWallet();
|
||||
changePromoSheetDialogue();
|
||||
await getPassengerWallet();
|
||||
},
|
||||
onError: (error) {
|
||||
Toast.show(context, ' $error'.tr, AppColor.redColor);
|
||||
},
|
||||
onCancel: (params) {
|
||||
Toast.show(context, 'Pyament Cancelled .'.tr,
|
||||
AppColor.yellowColor);
|
||||
}),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
Toast.show(context, 'You will choose one of above !'.tr,
|
||||
AppColor.redColor);
|
||||
}
|
||||
} else {
|
||||
// Authentication failed, handle accordingly
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Map licenseDetailsMap = {};
|
||||
Future getLicenseInfo() async {
|
||||
var res = await CRUD().get(
|
||||
link: AppLink.getLicense,
|
||||
payload: {'driverID': box.read(BoxName.driverID)});
|
||||
licenseDetailsMap = jsonDecode(res);
|
||||
}
|
||||
|
||||
Future createConnectAccount() async {
|
||||
String url = 'https://api.stripe.com/v1/accounts';
|
||||
await getLicenseInfo();
|
||||
DateTime dob =
|
||||
DateTime.parse(licenseDetailsMap['message'][0]['dateOfBirth']);
|
||||
int currentTimestamp =
|
||||
(DateTime.now().millisecondsSinceEpoch / 1000).round();
|
||||
int day = dob.day;
|
||||
int month = dob.month;
|
||||
int year = dob.year;
|
||||
await getIpAddress();
|
||||
final body = {
|
||||
"type": "custom",
|
||||
"business_profile[name]": box.read(BoxName.nameDriver),
|
||||
"business_profile[product_description]": "Captain",
|
||||
"business_profile[support_address][city]": "San Francisco",
|
||||
"business_profile[support_address][country]": 'US',
|
||||
"business_profile[support_address][line1]":
|
||||
licenseDetailsMap['message'][0]['address'].toString().trim()[0],
|
||||
"business_profile[support_address][postal_code]":
|
||||
licenseDetailsMap['message'][0]['postalCode'],
|
||||
"business_profile[support_address][state]": "MA",
|
||||
"business_profile[support_email]": "support@sefer.live",
|
||||
"business_profile[support_phone]": "555-123-4567",
|
||||
"business_profile[url]": "https://sefer.live",
|
||||
"business_type": "individual",
|
||||
"capabilities[card_payments][requested]": "true",
|
||||
"capabilities[transfers][requested]": "true",
|
||||
"company[address][city]": "ATTLEBORO",
|
||||
"company[address][country]": "US",
|
||||
"company[address][line1]": "1249 NEWPORT AVE",
|
||||
"company[address][postal_code]": "02703 ",
|
||||
"company[address][state]": "MA",
|
||||
"company[name]": AppInformation.companyName,
|
||||
"country": "us",
|
||||
"default_currency": "usd",
|
||||
"email": "support@sefer.live",
|
||||
// "individual[ssn]": "123-45-6789", //
|
||||
"individual[id_number]": licenseDetailsMap['message'][0]['documentNo'],
|
||||
// "individual[id_type]": "drivers_license", //
|
||||
"individual[address][city]": "ATTLEBORO",
|
||||
"individual[address][country]": "US",
|
||||
"individual[address][line1]": licenseDetailsMap['message'][0]['address'],
|
||||
// "individual[address][postal_code]": licenseDetailsMap['message'][0]
|
||||
// ['postalCode'],
|
||||
"individual[address][state]": "MA",
|
||||
// "individual[ssn_last_4]": '1111', ////////
|
||||
"individual[dob][day]": day.toString(),
|
||||
"individual[dob][month]": month.toString(),
|
||||
"individual[dob][year]": year.toString(),
|
||||
"individual[email]": box.read(BoxName.emailDriver),
|
||||
"individual[first_name]":
|
||||
licenseDetailsMap['message'][0]['name'].toString().split(' ')[0],
|
||||
"individual[gender]":
|
||||
licenseDetailsMap['message'][0]['sex'] == 'M' ? 'male' : 'female',
|
||||
"individual[last_name]":
|
||||
licenseDetailsMap['message'][0]['name'].toString().split(' ')[1],
|
||||
// "individual[phone]": box.read(BoxName.phoneDriver),////////////
|
||||
"tos_acceptance[date]": currentTimestamp.toString(),
|
||||
"tos_acceptance[ip]": ip.toString()
|
||||
};
|
||||
|
||||
final response = await CRUD().postStripe(
|
||||
link: url,
|
||||
payload: body,
|
||||
);
|
||||
final responseData = jsonDecode(response);
|
||||
final accountId = responseData['id'];
|
||||
box.write(BoxName.accountIdStripeConnect, accountId);
|
||||
await updateCaptainAccountBank();
|
||||
return accountId;
|
||||
}
|
||||
|
||||
Future updateCaptainAccountBank() async {
|
||||
var res = await CRUD().post(link: AppLink.updateAccountBank, payload: {
|
||||
'id': box.read(BoxName.driverID),
|
||||
'accountBank': box.read(BoxName.accountIdStripeConnect),
|
||||
});
|
||||
if (jsonDecode(res)['status'] == 'success') {
|
||||
Get.snackbar('Account Updated', '');
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> createTransactionToCaptain(
|
||||
String amount, String account) async {
|
||||
String url = 'https://api.stripe.com/v1/transfers';
|
||||
|
||||
final body = {
|
||||
'amount': amount, //amount
|
||||
'currency': 'usd',
|
||||
'destination': account //'acct_1OKIjQRgcWrsdyDT' //account id
|
||||
};
|
||||
|
||||
final response = await CRUD().postStripe(
|
||||
link: url,
|
||||
payload: body,
|
||||
);
|
||||
final responseData = jsonDecode(response);
|
||||
final transactionId = responseData['id'];
|
||||
|
||||
return transactionId;
|
||||
}
|
||||
|
||||
Future getIpAddress() async {
|
||||
var url = Uri.parse('https://api.ipify.org?format=json');
|
||||
|
||||
var response = await http.get(url);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
ip = jsonDecode(response.body)['ip'];
|
||||
} else {}
|
||||
}
|
||||
|
||||
// 'https://accept.paymob.com/unifiedcheckout/?publicKey=egy_pk_live_mbjDC9Ni6FSHKmsz8sOHiVk2xd7oWRve&clientSecret=egy_sk_live_c0904e9cf04506ae64f818d4e075b4a957e3713fdf7a22cb7da30a29e72442b5'
|
||||
// أضف هذا الرابط إلى ملف AppLink الخاص بك
|
||||
|
||||
// هذه هي الدالة الجديدة التي ستستخدمها لبدء الدفع
|
||||
Future<void> payWithEcash(BuildContext context, String amount) async {
|
||||
try {
|
||||
// 1. يمكنك استخدام نفس طريقة التحقق بالبصمة إذا أردت
|
||||
bool isAvailable = await LocalAuthentication().isDeviceSupported();
|
||||
if (isAvailable) {
|
||||
bool didAuthenticate = await LocalAuthentication().authenticate(
|
||||
localizedReason: 'Use Touch ID or Face ID to confirm payment',
|
||||
);
|
||||
|
||||
if (didAuthenticate) {
|
||||
// 2. استدعاء الـ Endpoint الجديد على السيرفر الخاص بك
|
||||
var res = await CRUD().postWallet(
|
||||
link: AppLink.payWithEcashPassenger,
|
||||
payload: {
|
||||
// ✅ أرسل البيانات التي يحتاجها السيرفر الخاص بـ ecash
|
||||
"amount": amount,
|
||||
"passengerId": box.read(BoxName.passengerID),
|
||||
},
|
||||
);
|
||||
|
||||
// 3. التأكد من أن السيرفر أعاد رابط الدفع بنجاح
|
||||
if (res != null &&
|
||||
res['status'] == 'success' &&
|
||||
res['message'] != null) {
|
||||
final String paymentUrl = res['message'];
|
||||
// 4. الانتقال إلى شاشة الدفع الجديدة الخاصة بـ ecash
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) =>
|
||||
EcashPaymentScreen(paymentUrl: paymentUrl),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// عرض رسالة خطأ في حال فشل السيرفر في إنشاء الرابط
|
||||
Get.defaultDialog(
|
||||
title: 'Error'.tr,
|
||||
content: Text(
|
||||
'Failed to initiate payment. Please try again.'.tr,
|
||||
style: AppStyle.title,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
Get.defaultDialog(
|
||||
title: 'Error'.tr,
|
||||
content: Text(
|
||||
'An error occurred during the payment process.'.tr,
|
||||
style: AppStyle.title,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Future<void> payWithEcashDriver(BuildContext context, String amount) async {
|
||||
// try {
|
||||
// // يمكنك استخدام نفس طريقة التحقق بالبصمة إذا أردت
|
||||
// bool isAvailable = await LocalAuthentication().isDeviceSupported();
|
||||
// if (isAvailable) {
|
||||
// bool didAuthenticate = await LocalAuthentication().authenticate(
|
||||
// localizedReason: 'Use Touch ID or Face ID to confirm payment'.tr,
|
||||
// );
|
||||
|
||||
// if (didAuthenticate) {
|
||||
// // استدعاء الـ Endpoint الجديد على السيرفر الخاص بك
|
||||
// var res = await CRUD().postWallet(
|
||||
// link: AppLink.payWithEcashPassenger,
|
||||
// // link:
|
||||
// // 'https://wl.tripz-egypt.com/v1/main/ride/ecash/driver/payWithEcash.php',
|
||||
// payload: {
|
||||
// // أرسل البيانات التي يحتاجها السيرفر
|
||||
// "amount": amount,
|
||||
// // "driverId": box.read(BoxName.driverID), // تأكد من وجود هذا المتغير
|
||||
// "passengerId":
|
||||
// box.read(BoxName.passengerID), // تأكد من وجود هذا المتغير
|
||||
// },
|
||||
// );
|
||||
|
||||
// // التأكد من أن السيرفر أعاد رابط الدفع بنجاح
|
||||
// if (res != null &&
|
||||
// res['status'] == 'success' &&
|
||||
// res['message'] != null) {
|
||||
// final String paymentUrl = res['message'];
|
||||
// // الانتقال إلى شاشة الدفع الجديدة الخاصة بـ ecash للسائق
|
||||
// Navigator.push(
|
||||
// context,
|
||||
// MaterialPageRoute(
|
||||
// builder: (context) =>
|
||||
// EcashDriverPaymentScreen(paymentUrl: paymentUrl),
|
||||
// ),
|
||||
// );
|
||||
// } else {
|
||||
// // عرض رسالة خطأ في حال فشل السيرفر في إنشاء الرابط
|
||||
// Get.defaultDialog(
|
||||
// title: 'Error'.tr,
|
||||
// content: Text(
|
||||
// 'Failed to initiate payment. Please try again.'.tr,
|
||||
// style: AppStyle.title,
|
||||
// ),
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// } catch (e) {
|
||||
// Get.defaultDialog(
|
||||
// title: 'Error'.tr,
|
||||
// content: Text(
|
||||
// 'An error occurred during the payment process.'.tr,
|
||||
// style: AppStyle.title,
|
||||
// ),
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
|
||||
/// شاشة جديدة ومبسطة خاصة بدفع السائقين عبر ecash
|
||||
|
||||
Future<void> payWithMTNWallet(
|
||||
BuildContext context, String amount, String currency) async {
|
||||
// استخدام مؤشر تحميل لتجربة مستخدم أفضل
|
||||
Get.dialog(const Center(child: CircularProgressIndicator()),
|
||||
barrierDismissible: false);
|
||||
|
||||
try {
|
||||
String phone = box.read(BoxName.phoneWallet);
|
||||
String passengerID = box.read(BoxName.passengerID).toString();
|
||||
String formattedAmount = double.parse(amount).toStringAsFixed(0);
|
||||
|
||||
print("🚀 بدء عملية دفع MTN");
|
||||
print(
|
||||
"📦 Payload: passengerID: $passengerID, amount: $formattedAmount, phone: $phone");
|
||||
|
||||
// التحقق من البصمة (اختياري)
|
||||
bool isAuthSupported = await LocalAuthentication().isDeviceSupported();
|
||||
if (isAuthSupported) {
|
||||
bool didAuthenticate = await LocalAuthentication().authenticate(
|
||||
localizedReason: 'استخدم بصمة الإصبع أو الوجه لتأكيد الدفع',
|
||||
);
|
||||
if (!didAuthenticate) {
|
||||
if (Get.isDialogOpen ?? false) Get.back();
|
||||
print("❌ المستخدم لم يؤكد بالبصمة/الوجه");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 1️⃣ استدعاء mtn_start_payment.php (الملف الجديد)
|
||||
var responseData = await CRUD().postWallet(
|
||||
link: AppLink.payWithMTNStart,
|
||||
payload: {
|
||||
"amount": formattedAmount,
|
||||
"passengerId": passengerID,
|
||||
"phone": phone,
|
||||
},
|
||||
);
|
||||
|
||||
print("✅ استجابة الخادم (mtn_start_payment.php):");
|
||||
print(responseData);
|
||||
|
||||
// --- بداية التعديل المهم ---
|
||||
// التحقق القوي من الاستجابة لتجنب الأخطاء
|
||||
Map<String, dynamic> startRes;
|
||||
|
||||
if (responseData is Map<String, dynamic>) {
|
||||
// إذا كانت الاستجابة بالفعل Map، استخدمها مباشرة
|
||||
startRes = responseData;
|
||||
} else if (responseData is String) {
|
||||
// إذا كانت نص، حاول تحليلها كـ JSON
|
||||
try {
|
||||
startRes = json.decode(responseData);
|
||||
} catch (e) {
|
||||
throw Exception(
|
||||
"فشل في تحليل استجابة الخادم. الاستجابة: $responseData");
|
||||
}
|
||||
} else {
|
||||
// نوع غير متوقع
|
||||
throw Exception("تم استلام نوع بيانات غير متوقع من الخادم.");
|
||||
}
|
||||
|
||||
if (startRes['status'] != 'success') {
|
||||
String errorMsg = startRes['message']?.toString() ??
|
||||
"فشل بدء عملية الدفع. حاول مرة أخرى.";
|
||||
throw Exception(errorMsg);
|
||||
}
|
||||
// --- نهاية التعديل المهم ---
|
||||
|
||||
// استخراج البيانات بأمان
|
||||
final messageData = startRes["message"];
|
||||
final invoiceNumber = messageData["invoiceNumber"].toString();
|
||||
final operationNumber = messageData["operationNumber"].toString();
|
||||
final guid = messageData["guid"].toString();
|
||||
|
||||
print(
|
||||
"📄 invoiceNumber: $invoiceNumber, 🔢 operationNumber: $operationNumber, 🧭 guid: $guid");
|
||||
|
||||
if (Get.isDialogOpen ?? false)
|
||||
Get.back(); // إغلاق مؤشر التحميل قبل عرض حوار OTP
|
||||
|
||||
// 2️⃣ عرض واجهة إدخال OTP
|
||||
String? otp = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
String input = "";
|
||||
return AlertDialog(
|
||||
title: const Text("أدخل كود التحقق"),
|
||||
content: TextField(
|
||||
keyboardType: TextInputType.number,
|
||||
decoration: const InputDecoration(hintText: "كود OTP"),
|
||||
onChanged: (val) => input = val,
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
child: const Text("تأكيد"),
|
||||
onPressed: () => Navigator.of(context).pop(input),
|
||||
),
|
||||
TextButton(
|
||||
child: const Text("إلغاء"),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (otp == null || otp.isEmpty) {
|
||||
print("❌ لم يتم إدخال OTP");
|
||||
return;
|
||||
}
|
||||
print("🔐 تم إدخال OTP: $otp");
|
||||
|
||||
Get.dialog(const Center(child: CircularProgressIndicator()),
|
||||
barrierDismissible: false);
|
||||
|
||||
// 3️⃣ استدعاء mtn_confirm.php
|
||||
var confirmRes = await CRUD().postWallet(
|
||||
link: AppLink.payWithMTNConfirm,
|
||||
payload: {
|
||||
"invoiceNumber": invoiceNumber,
|
||||
"operationNumber": operationNumber,
|
||||
"guid": guid,
|
||||
"otp": otp,
|
||||
"phone": phone,
|
||||
},
|
||||
);
|
||||
|
||||
if (Get.isDialogOpen ?? false) Get.back();
|
||||
|
||||
print("✅ استجابة mtn_confirm.php:");
|
||||
print(confirmRes);
|
||||
|
||||
if (confirmRes != null && confirmRes['status'] == 'success') {
|
||||
Get.defaultDialog(
|
||||
title: "✅ نجاح",
|
||||
content: const Text("تمت عملية الدفع وإضافة الرصيد إلى محفظتك."),
|
||||
);
|
||||
} else {
|
||||
String errorMsg =
|
||||
confirmRes?['message']?.toString() ?? "فشل في تأكيد الدفع";
|
||||
Get.defaultDialog(
|
||||
title: "❌ فشل",
|
||||
content: Text(errorMsg),
|
||||
);
|
||||
}
|
||||
} catch (e, s) {
|
||||
print("🔥 خطأ أثناء الدفع عبر MTN:");
|
||||
print(e);
|
||||
print(s);
|
||||
if (Get.isDialogOpen ?? false) Get.back();
|
||||
Get.defaultDialog(
|
||||
title: 'حدث خطأ',
|
||||
content: Text(e.toString().replaceFirst("Exception: ", "")),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
timestamp = now.millisecondsSinceEpoch;
|
||||
if (box.read(BoxName.passengerWalletTotal) == null) {
|
||||
box.write(BoxName.passengerWalletTotal, '0');
|
||||
}
|
||||
getPassengerWallet();
|
||||
final localAuth = LocalAuthentication();
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
|
||||
class EcashDriverPaymentScreen extends StatefulWidget {
|
||||
final String paymentUrl;
|
||||
|
||||
const EcashDriverPaymentScreen({required this.paymentUrl, Key? key})
|
||||
: super(key: key);
|
||||
|
||||
@override
|
||||
State<EcashDriverPaymentScreen> createState() =>
|
||||
_EcashDriverPaymentScreenState();
|
||||
}
|
||||
|
||||
class _EcashDriverPaymentScreenState extends State<EcashDriverPaymentScreen> {
|
||||
late final WebViewController _controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = WebViewController()
|
||||
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
||||
..setNavigationDelegate(NavigationDelegate(
|
||||
onPageFinished: (url) async {
|
||||
print('Ecash Driver WebView URL Finished: $url');
|
||||
await Get.find<PaymentController>().getPassengerWallet();
|
||||
// هنا نتحقق فقط من أن المستخدم عاد إلى صفحة النجاح
|
||||
// لا حاجة لاستدعاء أي API هنا، فالـ Webhook يقوم بكل العمل
|
||||
if (url.contains("success.php")) {
|
||||
showProcessingDialog();
|
||||
}
|
||||
},
|
||||
))
|
||||
..loadRequest(Uri.parse(widget.paymentUrl));
|
||||
}
|
||||
|
||||
// دالة لعرض رسالة "العملية قيد المعالجة"
|
||||
void showProcessingDialog() {
|
||||
showDialog(
|
||||
barrierDismissible: false,
|
||||
context: Get.context!,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12.0),
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
Icon(Icons.check_circle, color: Colors.green),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
"Payment Successful".tr,
|
||||
style: TextStyle(
|
||||
color: Colors.green,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: Text(
|
||||
"Your payment is being processed and your wallet will be updated shortly."
|
||||
.tr,
|
||||
style: const TextStyle(fontSize: 16),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
// أغلق مربع الحوار، ثم أغلق شاشة الدفع
|
||||
Navigator.pop(context); // Close the dialog
|
||||
Navigator.pop(context); // Close the payment screen
|
||||
},
|
||||
style: TextButton.styleFrom(
|
||||
backgroundColor: Colors.green,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
"OK".tr,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text('Complete Payment'.tr)),
|
||||
body: WebViewWidget(controller: _controller),
|
||||
);
|
||||
}
|
||||
}
|
||||
158
lib/controller/payment/paymob.dart
Normal file
158
lib/controller/payment/paymob.dart
Normal file
@@ -0,0 +1,158 @@
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:dio/dio.dart' as dio;
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../constant/api_key.dart';
|
||||
import '../../main.dart';
|
||||
import '../../print.dart';
|
||||
import '../functions/encrypt_decrypt.dart';
|
||||
|
||||
class PaymobManager extends GetxController {
|
||||
String authanticationToken1 = "";
|
||||
String orderId1 = "";
|
||||
|
||||
Future<String> getPaymentKey(int amount, String currency) async {
|
||||
try {
|
||||
String authanticationToken = await _getAuthanticationToken();
|
||||
|
||||
int orderId = await _getOrderId(
|
||||
authanticationToken: authanticationToken,
|
||||
amount: (100 * amount).toString(),
|
||||
currency: currency,
|
||||
);
|
||||
|
||||
String paymentKey = await _getPaymentKey(
|
||||
authanticationToken: authanticationToken,
|
||||
amount: (100 * amount).toString(),
|
||||
currency: currency,
|
||||
orderId: orderId.toString(),
|
||||
);
|
||||
authanticationToken1 = authanticationToken.toString();
|
||||
orderId1 = orderId.toString();
|
||||
update();
|
||||
return paymentKey;
|
||||
} catch (e) {
|
||||
throw Exception();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> payWithPayMob(int amount, String currency) async {
|
||||
// 1. Fetch Payment Key (Assuming PaymobManager is a custom class)
|
||||
String paymentToken;
|
||||
try {
|
||||
paymentToken = await PaymobManager().getPaymentKey(amount, currency);
|
||||
} on Exception catch (e) {
|
||||
// Handle errors gracefully, e.g., display error message to user
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Prepare Payment Data Payload
|
||||
final Map<String, dynamic> data = {
|
||||
"source": {
|
||||
"identifier": box.read(BoxName.phone), //"01010101010"
|
||||
"subtype": "WALLET",
|
||||
},
|
||||
"payment_token": paymentToken,
|
||||
};
|
||||
|
||||
// 3. Make Payment Request using Dio
|
||||
final dio = Dio();
|
||||
try {
|
||||
final response = await dio.post(
|
||||
'https://accept.paymobsolutions.com/api/acceptance/payments/pay',
|
||||
data: data,
|
||||
);
|
||||
|
||||
// 4. Handle Payment Response
|
||||
if (response.statusCode == 200) {
|
||||
final paymentData = response.data; // Assuming JSON response
|
||||
|
||||
// Navigate to success screen or display success message
|
||||
launchUrl(Uri.parse(paymentData['iframe_redirection_url']));
|
||||
} else {
|
||||
// Payment failed: Handle errors (e.g., display error message)
|
||||
}
|
||||
} on DioError catch (e) {
|
||||
// Handle network or Dio-related errors
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> _getStatusAfterPaid() async {
|
||||
final dio.Response response = await Dio().post(
|
||||
"https://accept.paymob.com/api/ecommerce/orders/transaction_inquiry",
|
||||
data: {
|
||||
"auth_token": authanticationToken1,
|
||||
"merchant_order_id": "970960",
|
||||
"order_id": orderId1
|
||||
});
|
||||
return response.data["success"];
|
||||
}
|
||||
|
||||
Future<String> _getAuthanticationToken() async {
|
||||
final dio.Response response =
|
||||
await Dio().post("https://accept.paymob.com/api/auth/tokens", data: {
|
||||
"api_key": AK.payMobApikey,
|
||||
'username': AK.usernamePayMob,
|
||||
"password": AK.passwordPayMob,
|
||||
});
|
||||
Log.print('token: ${response}');
|
||||
return response.data["token"];
|
||||
}
|
||||
|
||||
Future<int> _getOrderId({
|
||||
required String authanticationToken,
|
||||
required String amount,
|
||||
required String currency,
|
||||
}) async {
|
||||
final dio.Response response = await Dio()
|
||||
.post("https://accept.paymob.com/api/ecommerce/orders", data: {
|
||||
"auth_token": authanticationToken,
|
||||
"amount_cents": amount,
|
||||
"currency": currency,
|
||||
"delivery_needed": "false",
|
||||
"items": [],
|
||||
});
|
||||
Log.print('id: ${response}');
|
||||
return response.data["id"];
|
||||
}
|
||||
|
||||
Future<String> _getPaymentKey({
|
||||
required String authanticationToken,
|
||||
required String orderId,
|
||||
required String amount,
|
||||
required String currency,
|
||||
}) async {
|
||||
final dio.Response response = await Dio()
|
||||
.post("https://accept.paymob.com/api/acceptance/payment_keys", data: {
|
||||
"expiration": 200,
|
||||
"auth_token": authanticationToken.toString(),
|
||||
"order_id": orderId.toString(),
|
||||
"integration_id":
|
||||
4601103, ////todo wallet or online card int.parse(AK.integrationIdPayMob),
|
||||
"lock_order_when_paid": "false",
|
||||
"amount_cents": amount,
|
||||
"currency": currency,
|
||||
"billing_data": {
|
||||
"first_name":
|
||||
(box.read(BoxName.name).toString().split(' ')[0]).toString(),
|
||||
"last_name":
|
||||
(box.read(BoxName.name).toString().split(' ')[1]).toString(),
|
||||
"email": (box.read(BoxName.email)),
|
||||
"phone_number": (box.read(BoxName.phone)),
|
||||
"apartment": "NA",
|
||||
"floor": "NA",
|
||||
"street": "NA",
|
||||
"building": "NA",
|
||||
"shipping_method": "NA",
|
||||
"postal_code": "NA",
|
||||
"city": "NA",
|
||||
"country": box.read(BoxName.countryCode),
|
||||
"state": "NA"
|
||||
},
|
||||
});
|
||||
Log.print('token: ${response}');
|
||||
return response.data["token"];
|
||||
}
|
||||
}
|
||||
99
lib/controller/payment/paymob/e_cash_screen.dart
Normal file
99
lib/controller/payment/paymob/e_cash_screen.dart
Normal file
@@ -0,0 +1,99 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:webview_flutter/webview_flutter.dart';
|
||||
|
||||
// ✅ شاشة جديدة ومبسطة خاصة بـ ecash
|
||||
class EcashPaymentScreen extends StatefulWidget {
|
||||
final String paymentUrl;
|
||||
|
||||
const EcashPaymentScreen({required this.paymentUrl, Key? key})
|
||||
: super(key: key);
|
||||
|
||||
@override
|
||||
State<EcashPaymentScreen> createState() => _EcashPaymentScreenState();
|
||||
}
|
||||
|
||||
class _EcashPaymentScreenState extends State<EcashPaymentScreen> {
|
||||
late final WebViewController _controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = WebViewController()
|
||||
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
||||
..setNavigationDelegate(NavigationDelegate(
|
||||
onPageFinished: (url) {
|
||||
print('Ecash WebView URL Finished: $url');
|
||||
|
||||
// ✅ هنا نتحقق فقط من أن المستخدم عاد إلى صفحة النجاح
|
||||
// هذه الصفحة هي التي حددناها في `APP_REDIRECT_URL_SUCCESS` في ملف PHP
|
||||
if (url.contains("success.php")) {
|
||||
// لا نستدعي أي API هنا. الـ Webhook على السيرفر يقوم بكل العمل.
|
||||
// فقط نعرض للمستخدم رسالة بأن العملية قيد المراجعة ونغلق الشاشة.
|
||||
showProcessingDialog();
|
||||
}
|
||||
},
|
||||
))
|
||||
..loadRequest(Uri.parse(widget.paymentUrl));
|
||||
}
|
||||
|
||||
// دالة لعرض رسالة "العملية قيد المعالجة"
|
||||
void showProcessingDialog() {
|
||||
showDialog(
|
||||
barrierDismissible: false,
|
||||
context: Get.context!,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12.0),
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
Icon(Icons.check_circle, color: Colors.green),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
"Payment Successful".tr,
|
||||
style: TextStyle(
|
||||
color: Colors.green,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: Text(
|
||||
"Your payment is being processed and your wallet will be updated shortly."
|
||||
.tr,
|
||||
style: const TextStyle(fontSize: 16),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
// أغلق مربع الحوار، ثم أغلق شاشة الدفع
|
||||
Navigator.pop(context); // Close the dialog
|
||||
Navigator.pop(context); // Close the payment screen
|
||||
},
|
||||
style: TextButton.styleFrom(
|
||||
backgroundColor: Colors.green,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
"OK".tr,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text('Complete Payment'.tr)),
|
||||
body: WebViewWidget(controller: _controller),
|
||||
);
|
||||
}
|
||||
}
|
||||
487
lib/controller/payment/paymob/paymob_response.dart
Normal file
487
lib/controller/payment/paymob/paymob_response.dart
Normal file
@@ -0,0 +1,487 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:webview_flutter/webview_flutter.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../../../print.dart';
|
||||
import '../../functions/encrypt_decrypt.dart';
|
||||
|
||||
class PaymobResponse {
|
||||
bool success;
|
||||
String? transactionID;
|
||||
String? responseCode;
|
||||
String? message;
|
||||
|
||||
PaymobResponse({
|
||||
this.transactionID,
|
||||
required this.success,
|
||||
this.responseCode,
|
||||
this.message,
|
||||
});
|
||||
|
||||
factory PaymobResponse.fromJson(Map<String, dynamic> json) {
|
||||
return PaymobResponse(
|
||||
success: json['success'] == 'true',
|
||||
transactionID: json['id'],
|
||||
message: json['message'],
|
||||
responseCode: json['txn_response_code'],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class PaymobPayment {
|
||||
static PaymobPayment instance = PaymobPayment();
|
||||
|
||||
bool _isInitialized = false;
|
||||
|
||||
final Dio _dio = Dio();
|
||||
final _baseURL = 'https://accept.paymob.com/api/';
|
||||
late String _apiKey;
|
||||
late int _integrationID;
|
||||
late int _iFrameID;
|
||||
late String _iFrameURL;
|
||||
late int _userTokenExpiration;
|
||||
|
||||
/// Initializing PaymobPayment instance.
|
||||
Future<bool> initialize({
|
||||
/// It is a unique identifier for the merchant which used to authenticate your requests calling any of Accept's API.
|
||||
/// from dashboard Select Settings -> Account Info -> API Key
|
||||
required String apiKey,
|
||||
|
||||
/// from dashboard Select Developers -> Payment Integrations -> Online Card ID
|
||||
required int integrationID,
|
||||
|
||||
/// from paymob Select Developers -> iframes
|
||||
required int iFrameID,
|
||||
|
||||
/// The expiration time of this payment token in seconds. (The maximum is 3600 seconds which is an hour)
|
||||
int userTokenExpiration = 300,
|
||||
}) async {
|
||||
if (_isInitialized) {
|
||||
return true;
|
||||
}
|
||||
_dio.options.baseUrl = _baseURL;
|
||||
_dio.options.validateStatus = (status) => true;
|
||||
_apiKey = apiKey;
|
||||
_integrationID = integrationID;
|
||||
_iFrameID = iFrameID;
|
||||
_iFrameURL =
|
||||
'https://accept.paymobsolutions.com/api/acceptance/iframes/$_iFrameID?payment_token=';
|
||||
_isInitialized = true;
|
||||
_userTokenExpiration = userTokenExpiration;
|
||||
return _isInitialized;
|
||||
}
|
||||
|
||||
/// Get authentication token, which is valid for one hour from the creation time.
|
||||
Future<String> _getAuthToken() async {
|
||||
try {
|
||||
final response = await _dio.post(
|
||||
'auth/tokens',
|
||||
data: {
|
||||
'api_key': _apiKey,
|
||||
},
|
||||
);
|
||||
|
||||
return response.data['token'];
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// At this step, you will register an order to Accept's database, so that you can pay for it later using a transaction
|
||||
Future<int> _addOrder({
|
||||
required String authToken,
|
||||
required String currency,
|
||||
required String amount,
|
||||
required List items,
|
||||
}) async {
|
||||
try {
|
||||
final response = await _dio.post(
|
||||
'ecommerce/orders',
|
||||
data: {
|
||||
"auth_token": authToken,
|
||||
"delivery_needed": "false",
|
||||
"amount_cents": amount,
|
||||
"currency": currency,
|
||||
"items": items,
|
||||
},
|
||||
);
|
||||
|
||||
return response.data['id'];
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// At this step, you will obtain a payment_key token. This key will be used to authenticate your payment request. It will be also used for verifying your transaction request metadata.
|
||||
Future<String> _getPurchaseToken({
|
||||
required String authToken,
|
||||
required String currency,
|
||||
required int orderID,
|
||||
required String amount,
|
||||
required PaymobBillingData billingData,
|
||||
}) async {
|
||||
final response = await _dio.post(
|
||||
'acceptance/payment_keys',
|
||||
data: {
|
||||
"auth_token": authToken,
|
||||
"amount_cents": amount,
|
||||
"expiration": _userTokenExpiration,
|
||||
"order_id": orderID,
|
||||
"billing_data": billingData,
|
||||
"currency": currency,
|
||||
"integration_id": _integrationID,
|
||||
"lock_order_when_paid": "false"
|
||||
},
|
||||
);
|
||||
final message = response.data['message'];
|
||||
if (message != null) {
|
||||
throw Exception(message);
|
||||
}
|
||||
return response.data['token'];
|
||||
}
|
||||
|
||||
/// Proceed to pay with only calling this function.
|
||||
/// Opens a WebView at Paymob redirectedURL to accept user payment info.
|
||||
Future<PaymobResponse?> pay(
|
||||
{
|
||||
/// BuildContext for navigation to WebView
|
||||
required BuildContext context,
|
||||
|
||||
/// Which Currency you would pay in.
|
||||
required String currency,
|
||||
|
||||
/// Payment amount in cents EX: 20000 is an 200 EGP
|
||||
required String amountInCents,
|
||||
|
||||
/// Optional Callback if you can use return result of pay function or use this callback
|
||||
void Function(PaymobResponse response)? onPayment,
|
||||
|
||||
/// list of json objects contains the contents of the purchase.
|
||||
List? items,
|
||||
|
||||
/// The billing data related to the customer related to this payment.
|
||||
PaymobBillingData? billingData}) async {
|
||||
if (!_isInitialized) {
|
||||
throw Exception(
|
||||
'PaymobPayment is not initialized call:`PaymobPayment.instance.initialize`');
|
||||
}
|
||||
final authToken = await _getAuthToken();
|
||||
final orderID = await _addOrder(
|
||||
authToken: authToken,
|
||||
currency: currency,
|
||||
amount: amountInCents,
|
||||
items: items ?? [],
|
||||
);
|
||||
final purchaseToken = await _getPurchaseToken(
|
||||
authToken: authToken,
|
||||
currency: currency,
|
||||
orderID: orderID,
|
||||
amount: amountInCents,
|
||||
billingData: billingData ?? PaymobBillingData(),
|
||||
);
|
||||
if (context.mounted) {
|
||||
final response = await PaymobIFrame.show(
|
||||
context: context,
|
||||
redirectURL: _iFrameURL + purchaseToken,
|
||||
onPayment: onPayment,
|
||||
);
|
||||
return response;
|
||||
}
|
||||
return null;
|
||||
} //51624
|
||||
}
|
||||
|
||||
class PaymobBillingData {
|
||||
String? email;
|
||||
String? firstName;
|
||||
String? lastName;
|
||||
String? phoneNumber;
|
||||
String? apartment;
|
||||
String? floor;
|
||||
String? street;
|
||||
String? building;
|
||||
String? postalCode;
|
||||
String? city;
|
||||
String? state;
|
||||
String? country;
|
||||
String? shippingMethod;
|
||||
|
||||
PaymobBillingData({
|
||||
this.email,
|
||||
this.firstName,
|
||||
this.lastName,
|
||||
this.phoneNumber,
|
||||
this.apartment,
|
||||
this.floor,
|
||||
this.street,
|
||||
this.building,
|
||||
this.postalCode,
|
||||
this.city,
|
||||
this.state,
|
||||
this.country,
|
||||
this.shippingMethod,
|
||||
});
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
"email": box.read(BoxName.email) ?? box.read(BoxName.emailDriver),
|
||||
"first_name":
|
||||
(box.read(BoxName.name).toString().split(' ')[0]).toString(),
|
||||
"last_name": (box.read(BoxName.name).toString().split(' ')[1]).toString(),
|
||||
"phone_number": (box.read(BoxName.phone)),
|
||||
"apartment": apartment ?? "NA",
|
||||
"floor": floor ?? "NA",
|
||||
"building": building ?? "NA",
|
||||
"street": street ?? "NA",
|
||||
"postal_code": postalCode ?? "NA",
|
||||
"city": city ?? "NA",
|
||||
"state": state ?? "NA",
|
||||
"country": country ?? "NA",
|
||||
"shipping_method": box.read(BoxName.passengerID) ?? "NA",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class PaymobIFrame extends StatefulWidget {
|
||||
const PaymobIFrame({
|
||||
Key? key,
|
||||
required this.redirectURL,
|
||||
this.onPayment,
|
||||
}) : super(key: key);
|
||||
|
||||
final String redirectURL;
|
||||
final void Function(PaymobResponse)? onPayment;
|
||||
|
||||
static Future<PaymobResponse?> show({
|
||||
required BuildContext context,
|
||||
required String redirectURL,
|
||||
void Function(PaymobResponse)? onPayment,
|
||||
}) =>
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (context) {
|
||||
return PaymobIFrame(
|
||||
onPayment: onPayment,
|
||||
redirectURL: redirectURL,
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
State<PaymobIFrame> createState() => _PaymobIFrameState();
|
||||
}
|
||||
|
||||
class _PaymobIFrameState extends State<PaymobIFrame> {
|
||||
WebViewController? controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
controller = WebViewController()
|
||||
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
||||
..setNavigationDelegate(
|
||||
NavigationDelegate(
|
||||
onNavigationRequest: (NavigationRequest request) {
|
||||
if (request.url.contains('txn_response_code') &&
|
||||
request.url.contains('success') &&
|
||||
request.url.contains('id')) {
|
||||
final params = _getParamFromURL(request.url);
|
||||
final response = PaymobResponse.fromJson(params);
|
||||
if (widget.onPayment != null) {
|
||||
widget.onPayment!(response);
|
||||
}
|
||||
Navigator.pop(context, response);
|
||||
return NavigationDecision.prevent;
|
||||
}
|
||||
return NavigationDecision.navigate;
|
||||
},
|
||||
),
|
||||
)
|
||||
..loadRequest(Uri.parse(widget.redirectURL));
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: controller == null
|
||||
? const Center(
|
||||
child: CircularProgressIndicator.adaptive(),
|
||||
)
|
||||
: SafeArea(
|
||||
child: WebViewWidget(
|
||||
controller: controller!,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _getParamFromURL(String url) {
|
||||
final uri = Uri.parse(url);
|
||||
Map<String, dynamic> data = {};
|
||||
uri.queryParameters.forEach((key, value) {
|
||||
data[key] = value;
|
||||
});
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
class PaymentScreen extends StatefulWidget {
|
||||
final String iframeUrl;
|
||||
|
||||
const PaymentScreen({required this.iframeUrl, Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<PaymentScreen> createState() => _PaymentScreenState();
|
||||
}
|
||||
|
||||
class _PaymentScreenState extends State<PaymentScreen> {
|
||||
late final WebViewController _controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = WebViewController()
|
||||
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
||||
..setNavigationDelegate(NavigationDelegate(
|
||||
onPageFinished: (url) {
|
||||
Log.print('url onPageFinished : ${url}');
|
||||
if (url.contains("success")) {
|
||||
_fetchPaymentStatus(); // ✅ استدعاء الويب هوك بعد نجاح الدفع
|
||||
} else if (url.contains("failed")) {
|
||||
showCustomDialog(
|
||||
title: "Error".tr,
|
||||
message: 'Payment Failed'.tr, // يتم جلب رسالة الخطأ من الخادم
|
||||
isSuccess: false,
|
||||
);
|
||||
}
|
||||
},
|
||||
))
|
||||
..loadRequest(Uri.parse(widget.iframeUrl));
|
||||
}
|
||||
|
||||
// ✅ استدعاء الويب هوك بعد انتهاء الدفع
|
||||
Future<void> _fetchPaymentStatus() async {
|
||||
final String userId = (box.read(BoxName.phoneWallet)); // ضع user_id الحقيقي
|
||||
final String apiUrl = AppLink.paymetVerifyPassenger;
|
||||
|
||||
try {
|
||||
final response = await CRUD().getWallet(link: apiUrl, payload: {
|
||||
'user_id': userId,
|
||||
'passengerId': box.read(BoxName.passengerID),
|
||||
'paymentMethod': 'visa-in',
|
||||
});
|
||||
|
||||
if (response != 'failure' && response != 'token_expired') {
|
||||
try {
|
||||
final jsonData = jsonDecode(response);
|
||||
|
||||
if (jsonData['status'] == 'success') {
|
||||
// تأكد أن 'message' هو String وليس Map
|
||||
// final message = jsonData['message'];
|
||||
showCustomDialog(
|
||||
title: "Payment Status",
|
||||
message: jsonData['message'], // يتم جلب الرسالة من الخادم
|
||||
isSuccess: true,
|
||||
);
|
||||
} else {
|
||||
showCustomDialog(
|
||||
title: "Error",
|
||||
message: jsonData['message'], // يتم جلب رسالة الخطأ من الخادم
|
||||
isSuccess: false,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
showCustomDialog(
|
||||
title: "Error",
|
||||
message: response, // يتم جلب رسالة الخطأ من الخادم
|
||||
isSuccess: false,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
showCustomDialog(
|
||||
title: "Error".tr,
|
||||
message: response, // يتم جلب رسالة الخطأ من الخادم
|
||||
isSuccess: false,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
showCustomDialog(
|
||||
title: "Error".tr,
|
||||
message: 'Server error'.tr, // يتم جلب رسالة الخطأ من الخادم
|
||||
isSuccess: false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void showCustomDialog({
|
||||
required String title,
|
||||
required String message,
|
||||
required bool isSuccess,
|
||||
}) {
|
||||
showDialog(
|
||||
barrierDismissible: false,
|
||||
context: Get.context!,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12.0),
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
Icon(
|
||||
isSuccess ? Icons.check_circle : Icons.error,
|
||||
color: isSuccess ? Colors.green : Colors.red,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
color: isSuccess ? Colors.green : Colors.red,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: Text(
|
||||
message,
|
||||
style: const TextStyle(fontSize: 16),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
Navigator.pop(context);
|
||||
},
|
||||
style: TextButton.styleFrom(
|
||||
backgroundColor: isSuccess ? Colors.green : Colors.red,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
"OK",
|
||||
style: const TextStyle(color: Colors.white),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('إتمام الدفع')),
|
||||
body: WebViewWidget(controller: _controller),
|
||||
);
|
||||
}
|
||||
}
|
||||
382
lib/controller/payment/paymob/paymob_wallet.dart
Normal file
382
lib/controller/payment/paymob/paymob_wallet.dart
Normal file
@@ -0,0 +1,382 @@
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:webview_flutter/webview_flutter.dart';
|
||||
|
||||
import '../../../print.dart';
|
||||
import '../../functions/encrypt_decrypt.dart';
|
||||
|
||||
class PaymobResponseWallet {
|
||||
final bool success;
|
||||
final String? transactionID;
|
||||
final String? responseCode;
|
||||
final String? message;
|
||||
|
||||
PaymobResponseWallet({
|
||||
required this.success,
|
||||
this.transactionID,
|
||||
this.responseCode,
|
||||
this.message,
|
||||
});
|
||||
|
||||
factory PaymobResponseWallet.fromJson(Map<String, dynamic> json) {
|
||||
return PaymobResponseWallet(
|
||||
success: json['success'] == 'true',
|
||||
transactionID: json['id'],
|
||||
responseCode: json['txn_response_code'],
|
||||
message: json['data']['message'],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class PaymobPaymentWallet {
|
||||
static PaymobPaymentWallet instance = PaymobPaymentWallet();
|
||||
|
||||
bool _isInitializedWallet = false;
|
||||
|
||||
final Dio _dio = Dio();
|
||||
final _baseURL = 'https://accept.paymob.com/api/';
|
||||
late String _apiKey;
|
||||
late int _integrationID;
|
||||
late int _iFrameID;
|
||||
late String _iFrameURL;
|
||||
late int _userTokenExpiration;
|
||||
|
||||
/// Initializing PaymobPayment instance.
|
||||
Future<bool> initialize({
|
||||
/// It is a unique identifier for the merchant which used to authenticate your requests calling any of Accept's API.
|
||||
/// from dashboard Select Settings -> Account Info -> API Key
|
||||
required String apiKey,
|
||||
|
||||
/// from dashboard Select Developers -> Payment Integrations -> Online Card ID
|
||||
required int integrationID,
|
||||
|
||||
/// from paymob Select Developers -> iframes
|
||||
required int iFrameID,
|
||||
|
||||
/// The expiration time of this payment token in seconds. (The maximum is 3600 seconds which is an hour)
|
||||
int userTokenExpiration = 300,
|
||||
}) async {
|
||||
if (_isInitializedWallet) {
|
||||
return true;
|
||||
}
|
||||
_dio.options.baseUrl = _baseURL;
|
||||
_dio.options.validateStatus = (status) => true;
|
||||
_apiKey = apiKey;
|
||||
_integrationID = integrationID;
|
||||
_iFrameID = iFrameID;
|
||||
_iFrameURL =
|
||||
'https://accept.paymobsolutions.com/api/acceptance/iframes/$_iFrameID?payment_token=';
|
||||
_isInitializedWallet = true;
|
||||
_userTokenExpiration = userTokenExpiration;
|
||||
return _isInitializedWallet;
|
||||
}
|
||||
|
||||
/// Get authentication token, which is valid for one hour from the creation time.
|
||||
Future<String> _getAuthToken() async {
|
||||
try {
|
||||
final response = await _dio.post(
|
||||
'auth/tokens',
|
||||
data: {
|
||||
'api_key': _apiKey,
|
||||
},
|
||||
);
|
||||
return response.data['token'];
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// At this step, you will register an order to Accept's database, so that you can pay for it later using a transaction
|
||||
Future<int> _addOrder({
|
||||
required String authToken,
|
||||
required String currency,
|
||||
required String amount,
|
||||
required List items,
|
||||
}) async {
|
||||
try {
|
||||
final response = await _dio.post(
|
||||
'ecommerce/orders',
|
||||
data: {
|
||||
"auth_token": authToken,
|
||||
"delivery_needed": "false",
|
||||
"amount_cents": amount,
|
||||
"currency": currency,
|
||||
"items": items,
|
||||
},
|
||||
);
|
||||
return response.data['id'];
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// At this step, you will obtain a payment_key token. This key will be used to authenticate your payment request. It will be also used for verifying your transaction request metadata.
|
||||
Future<String> _getPurchaseToken({
|
||||
required String authToken,
|
||||
required String currency,
|
||||
required int orderID,
|
||||
required String amount,
|
||||
required PaymobBillingDataWallet billingData,
|
||||
}) async {
|
||||
final response = await _dio.post(
|
||||
'acceptance/payment_keys',
|
||||
data: {
|
||||
"auth_token": authToken,
|
||||
"amount_cents": amount,
|
||||
"expiration": _userTokenExpiration,
|
||||
"order_id": orderID,
|
||||
"billing_data": billingData,
|
||||
"currency": currency,
|
||||
"integration_id": _integrationID,
|
||||
"lock_order_when_paid": "false"
|
||||
},
|
||||
);
|
||||
// final message = response.data['message'];
|
||||
// if (message != null) {
|
||||
// throw Exception(message);
|
||||
// }
|
||||
return response.data['token'];
|
||||
}
|
||||
|
||||
Future<String> _getWalletUrl({
|
||||
required String paymentToken,
|
||||
}) async {
|
||||
final Map<String, dynamic> data = {
|
||||
"source": {
|
||||
"identifier": (box.read(BoxName.phoneWallet).toString()),
|
||||
"subtype": "WALLET",
|
||||
},
|
||||
"payment_token": paymentToken,
|
||||
};
|
||||
final dio = Dio();
|
||||
try {
|
||||
final response = await dio.post(
|
||||
'https://accept.paymobsolutions.com/api/acceptance/payments/pay',
|
||||
data: data,
|
||||
);
|
||||
|
||||
// 4. Handle Payment Response
|
||||
if (response.statusCode == 200) {
|
||||
final paymentData = response.data; // Assuming JSON response
|
||||
|
||||
return paymentData['iframe_redirection_url'];
|
||||
// Navigate to success screen or display success message
|
||||
} else {
|
||||
// Payment failed: Handle errors (e.g., display error message)
|
||||
}
|
||||
} on DioError catch (e) {
|
||||
// Handle network or Dio-related errors
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/// Proceed to pay with only calling this function.
|
||||
/// Opens a WebView at Paymob redirectedURL to accept user payment info.
|
||||
Future<PaymobResponseWallet?> pay(
|
||||
{
|
||||
/// BuildContext for navigation to WebView
|
||||
required BuildContext context,
|
||||
|
||||
/// Which Currency you would pay in.
|
||||
required String currency,
|
||||
|
||||
/// Payment amount in cents EX: 20000 is an 200 EGP
|
||||
required String amountInCents,
|
||||
|
||||
/// Optional Callback if you can use return result of pay function or use this callback
|
||||
void Function(PaymobResponseWallet response)? onPayment,
|
||||
|
||||
/// list of json objects contains the contents of the purchase.
|
||||
List? items,
|
||||
|
||||
/// The billing data related to the customer related to this payment.
|
||||
PaymobBillingDataWallet? billingData}) async {
|
||||
if (!_isInitializedWallet) {
|
||||
throw Exception(
|
||||
'PaymobPayment is not initialized call:`PaymobPayment.instance.initialize`');
|
||||
}
|
||||
final authToken = await _getAuthToken();
|
||||
final orderID = await _addOrder(
|
||||
authToken: authToken,
|
||||
currency: currency,
|
||||
amount: amountInCents,
|
||||
items: items ?? [],
|
||||
);
|
||||
final purchaseToken = await _getPurchaseToken(
|
||||
authToken: authToken,
|
||||
currency: currency,
|
||||
orderID: orderID,
|
||||
amount: amountInCents,
|
||||
billingData: billingData ??
|
||||
PaymobBillingDataWallet(
|
||||
// email: box.read(BoxName.email) ?? box.read(BoxName.emailDriver),
|
||||
// firstName: box.read(BoxName.name) ?? box.read(BoxName.nameDriver),
|
||||
// lastName:
|
||||
// box.read(BoxName.lastNameDriver) ?? box.read(BoxName.name),
|
||||
// phoneNumber:
|
||||
// box.read(BoxName.phone) ?? box.read(BoxName.phoneDriver),
|
||||
),
|
||||
);
|
||||
final urlWallet = await _getWalletUrl(paymentToken: purchaseToken);
|
||||
Log.print('urlWallet: ${urlWallet}');
|
||||
|
||||
if (context.mounted) {
|
||||
final response = await PaymobIFrameWallet.show(
|
||||
context: context,
|
||||
redirectURL: urlWallet,
|
||||
onPayment: onPayment,
|
||||
);
|
||||
return response;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class PaymobBillingDataWallet {
|
||||
String? email;
|
||||
String? firstName;
|
||||
String? lastName;
|
||||
String? phoneNumber;
|
||||
String? apartment;
|
||||
String? floor;
|
||||
String? street;
|
||||
String? building;
|
||||
String? postalCode;
|
||||
String? city;
|
||||
String? state;
|
||||
String? country;
|
||||
String? shippingMethod;
|
||||
|
||||
PaymobBillingDataWallet({
|
||||
this.email,
|
||||
this.firstName,
|
||||
this.lastName,
|
||||
this.phoneNumber,
|
||||
this.apartment,
|
||||
this.floor,
|
||||
this.street,
|
||||
this.building,
|
||||
this.postalCode,
|
||||
this.city,
|
||||
this.state,
|
||||
this.country,
|
||||
this.shippingMethod,
|
||||
});
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
"email": (box.read(BoxName.email)),
|
||||
"first_name":
|
||||
(box.read(BoxName.name).toString().split(' ')[0]).toString(),
|
||||
"last_name":
|
||||
(box.read(BoxName.name).toString().split(' ')[1]).toString() ??
|
||||
'Intaleq',
|
||||
"phone_number": (box.read(BoxName.phoneWallet)),
|
||||
"apartment": apartment ?? "NA",
|
||||
"floor": floor ?? "NA",
|
||||
"building": building ?? "NA",
|
||||
"street": street ?? "NA",
|
||||
"postal_code": postalCode ?? "NA",
|
||||
"city": city ?? "NA",
|
||||
"state": state ?? "NA",
|
||||
"country": country ?? "NA",
|
||||
"shipping_method": shippingMethod ?? "NA",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class PaymobIFrameWallet extends StatefulWidget {
|
||||
const PaymobIFrameWallet({
|
||||
Key? key,
|
||||
required this.redirectURL,
|
||||
this.onPayment,
|
||||
}) : super(key: key);
|
||||
|
||||
final String redirectURL;
|
||||
final void Function(PaymobResponseWallet)? onPayment;
|
||||
|
||||
static Future<PaymobResponseWallet?> show({
|
||||
required BuildContext context,
|
||||
required String redirectURL,
|
||||
void Function(PaymobResponseWallet)? onPayment,
|
||||
}) =>
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (context) {
|
||||
return PaymobIFrameWallet(
|
||||
onPayment: onPayment,
|
||||
redirectURL: redirectURL,
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
State<PaymobIFrameWallet> createState() => _PaymobIFrameState();
|
||||
}
|
||||
|
||||
class _PaymobIFrameState extends State<PaymobIFrameWallet> {
|
||||
WebViewController? controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
controller = WebViewController()
|
||||
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
||||
..setNavigationDelegate(
|
||||
NavigationDelegate(
|
||||
onNavigationRequest: (NavigationRequest request) {
|
||||
if (request.url.contains('txn_response_code') &&
|
||||
// request.url.contains('successfully') &&
|
||||
request.url.contains('success') &&
|
||||
request.url.contains('id')) {
|
||||
final params = _getParamFromURL(request.url);
|
||||
final response = PaymobResponseWallet.fromJson(params);
|
||||
if (widget.onPayment != null) {
|
||||
widget.onPayment!(response);
|
||||
}
|
||||
Navigator.pop(context, response);
|
||||
return NavigationDecision.prevent;
|
||||
}
|
||||
return NavigationDecision.navigate;
|
||||
},
|
||||
),
|
||||
)
|
||||
..loadRequest(Uri.parse(widget.redirectURL));
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: controller == null
|
||||
? const Center(
|
||||
child: CircularProgressIndicator.adaptive(),
|
||||
)
|
||||
: SafeArea(
|
||||
child: WebViewWidget(
|
||||
controller: controller!,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _getParamFromURL(String url) {
|
||||
final uri = Uri.parse(url);
|
||||
final queryParams = uri.queryParameters;
|
||||
final data = <String, dynamic>{};
|
||||
|
||||
queryParams.forEach((key, value) {
|
||||
if (key.contains('.')) {
|
||||
final parts = key.split('.');
|
||||
data.putIfAbsent(parts.first, () => <String, dynamic>{});
|
||||
(data[parts.first] as Map<String, dynamic>)[parts.last] = value;
|
||||
} else {
|
||||
data[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
0
lib/controller/payment/stripe.dart
Normal file
0
lib/controller/payment/stripe.dart
Normal file
95
lib/controller/profile/captain_profile_controller.dart
Normal file
95
lib/controller/profile/captain_profile_controller.dart
Normal file
@@ -0,0 +1,95 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
|
||||
class CaptainProfileController extends GetxController {
|
||||
bool isLoading = false;
|
||||
TextEditingController vin = TextEditingController();
|
||||
TextEditingController color = TextEditingController();
|
||||
TextEditingController make = TextEditingController();
|
||||
TextEditingController model = TextEditingController();
|
||||
TextEditingController year = TextEditingController();
|
||||
TextEditingController expirationDate = TextEditingController();
|
||||
|
||||
Future updateFields() async {
|
||||
var payload = {
|
||||
'driverID': box.read(BoxName.driverID),
|
||||
};
|
||||
|
||||
if (vin.text.isNotEmpty) {
|
||||
payload['vin'] = vin.text;
|
||||
}
|
||||
|
||||
if (color.text.isNotEmpty) {
|
||||
payload['color'] = color.text;
|
||||
}
|
||||
|
||||
if (model.text.isNotEmpty) {
|
||||
payload['model'] = model.text;
|
||||
}
|
||||
|
||||
if (make.text.isNotEmpty) {
|
||||
payload['make'] = make.text;
|
||||
}
|
||||
|
||||
if (year.text.isNotEmpty) {
|
||||
payload['year'] = year.text;
|
||||
}
|
||||
|
||||
if (expirationDate.text.isNotEmpty) {
|
||||
payload['expiration_date'] = expirationDate.text;
|
||||
}
|
||||
|
||||
var res =
|
||||
await CRUD().post(link: AppLink.updateRegisrationCar, payload: payload);
|
||||
|
||||
if (jsonDecode(res)['status'] == 'success') {
|
||||
box.write(BoxName.vin, vin.text);
|
||||
box.write(BoxName.color, color.text);
|
||||
box.write(BoxName.model, model.text);
|
||||
box.write(BoxName.make, make.text);
|
||||
box.write(BoxName.year, year.text);
|
||||
box.write(BoxName.expirationDate, expirationDate.text);
|
||||
update();
|
||||
Get.back();
|
||||
}
|
||||
}
|
||||
|
||||
Map captainProfileData = {};
|
||||
Future getProfileData() async {
|
||||
var res = await CRUD().get(
|
||||
link: AppLink.getCaptainProfile,
|
||||
payload: {'id': box.read(BoxName.driverID)});
|
||||
if (res != 'failure') {
|
||||
var d = jsonDecode(res);
|
||||
captainProfileData = d['message'];
|
||||
update();
|
||||
box.write(BoxName.sexDriver, d['message']['gender']);
|
||||
box.write(BoxName.dobDriver, d['message']['birthdate']);
|
||||
box.write(BoxName.vin, d['message']['vin']);
|
||||
box.write(BoxName.color, d['message']['color']);
|
||||
box.write(BoxName.model, d['message']['model']);
|
||||
box.write(BoxName.carPlate, d['message']['car_plate']);
|
||||
box.write(BoxName.make, d['message']['make']);
|
||||
box.write(BoxName.year, d['message']['year']);
|
||||
box.write(BoxName.expirationDate, d['message']['expiration_date']);
|
||||
// box.write(BoxName.acc, d['message']['accountBank']);
|
||||
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
// if (box.read(BoxName.dobDriver) == null) {
|
||||
getProfileData();
|
||||
// }
|
||||
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
117
lib/controller/profile/profile_controller.dart
Normal file
117
lib/controller/profile/profile_controller.dart
Normal file
@@ -0,0 +1,117 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:Intaleq/constant/colors.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
|
||||
class ProfileController extends GetxController {
|
||||
bool isloading = false;
|
||||
Map prfoileData = {};
|
||||
TextEditingController txtController = TextEditingController();
|
||||
List genders = ['Male', 'Female', 'Other'];
|
||||
|
||||
String gender = 'Male';
|
||||
|
||||
void setGender(String value) {
|
||||
gender = value;
|
||||
update();
|
||||
}
|
||||
|
||||
String? selectedDegree;
|
||||
|
||||
void setDegree(String? degree) {
|
||||
selectedDegree = degree;
|
||||
update();
|
||||
}
|
||||
|
||||
String? selectedCountry;
|
||||
|
||||
void setCountry(String? country) {
|
||||
selectedCountry = country;
|
||||
// box.write(BoxName.countryCode, country);
|
||||
update();
|
||||
}
|
||||
|
||||
updateColumn(Map<String, dynamic> payload) async {
|
||||
isloading = true;
|
||||
update();
|
||||
await CRUD().post(link: AppLink.updateprofile, payload: payload);
|
||||
await getProfile();
|
||||
isloading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
updatField(String columnName, TextInputType type) async {
|
||||
Get.dialog(
|
||||
CupertinoAlertDialog(
|
||||
title: Text('${'Update'.tr} $columnName'),
|
||||
content: Column(
|
||||
children: [
|
||||
const SizedBox(height: 16), // Add spacing between title and input
|
||||
CupertinoTextField(
|
||||
controller: txtController,
|
||||
placeholder: 'type here'.tr,
|
||||
keyboardType: type,
|
||||
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: CupertinoColors.lightBackgroundGray),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
CupertinoButton(
|
||||
color: AppColor.blueColor,
|
||||
onPressed: () async {
|
||||
Get.back();
|
||||
await updateColumn({
|
||||
'id': box.read(BoxName.passengerID),
|
||||
columnName: (txtController.text),
|
||||
});
|
||||
if (columnName == 'first_name') {
|
||||
box.write(BoxName.name, (txtController.text));
|
||||
}
|
||||
|
||||
txtController.clear();
|
||||
},
|
||||
child: Text('Update'.tr),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
getProfile() async {
|
||||
isloading = true;
|
||||
update();
|
||||
var res = await CRUD().get(link: AppLink.getprofile, payload: {
|
||||
'id': box.read(BoxName.passengerID).toString(),
|
||||
});
|
||||
|
||||
if (res.toString() == 'failure') {
|
||||
// Get.snackbar('failure', 'message');
|
||||
isloading = false;
|
||||
update();
|
||||
} else {
|
||||
var jsonDecoded = jsonDecode(res);
|
||||
prfoileData = jsonDecoded['data'];
|
||||
box.write(BoxName.sosPhonePassenger, prfoileData['sosPhone'].toString());
|
||||
box.write(BoxName.gender, prfoileData['gender'].toString());
|
||||
box.write(BoxName.name,
|
||||
'${prfoileData['first_name']} ${prfoileData['last_name']}');
|
||||
isloading = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
getProfile();
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
28
lib/controller/profile/setting_controller.dart
Normal file
28
lib/controller/profile/setting_controller.dart
Normal file
@@ -0,0 +1,28 @@
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class SettingController extends GetxController {
|
||||
bool isGoogleMapsEnabled = false;
|
||||
|
||||
void onChangMapApp() {
|
||||
if (!isGoogleMapsEnabled) {
|
||||
isGoogleMapsEnabled = true;
|
||||
box.write(BoxName.googlaMapApp, true);
|
||||
update();
|
||||
} else {
|
||||
isGoogleMapsEnabled = false;
|
||||
box.write(BoxName.googlaMapApp, false);
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
if (box.read(BoxName.googlaMapApp) != null) {
|
||||
isGoogleMapsEnabled = box.read(BoxName.googlaMapApp);
|
||||
}
|
||||
update();
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
108
lib/controller/rate/rate_conroller.dart
Normal file
108
lib/controller/rate/rate_conroller.dart
Normal file
@@ -0,0 +1,108 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/constant/links.dart';
|
||||
import 'package:Intaleq/constant/style.dart';
|
||||
import 'package:Intaleq/controller/functions/crud.dart';
|
||||
import 'package:Intaleq/controller/home/map_passenger_controller.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:Intaleq/views/home/map_page_passenger.dart';
|
||||
import 'package:Intaleq/views/widgets/elevated_btn.dart';
|
||||
|
||||
import '../firebase/firbase_messge.dart';
|
||||
import '../payment/payment_controller.dart';
|
||||
|
||||
// import '../home/captin/home_captain_controller.dart';
|
||||
|
||||
class RateController extends GetxController {
|
||||
double selectedRateItemId = -1;
|
||||
TextEditingController comment = TextEditingController();
|
||||
String? rideId, passengerId, driverId, price;
|
||||
late GlobalKey<FormState> formKey;
|
||||
@override
|
||||
void onInit() {
|
||||
formKey = GlobalKey<FormState>();
|
||||
passengerId = Get.arguments['passengerId'];
|
||||
rideId = Get.arguments['rideId'];
|
||||
driverId = Get.arguments['driverId'];
|
||||
price = Get.arguments['price'];
|
||||
box.write(BoxName.tipPercentage, '0');
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
void selectRateItem(double id) {
|
||||
selectedRateItemId = id;
|
||||
update();
|
||||
}
|
||||
|
||||
void addRateToDriver() async {
|
||||
if (selectedRateItemId < 1) {
|
||||
Get.defaultDialog(
|
||||
title: 'You Should choose rate figure'.tr,
|
||||
titleStyle: AppStyle.title,
|
||||
middleText: '',
|
||||
confirm: MyElevatedButton(title: 'Ok', onPressed: () => Get.back()));
|
||||
} else if (Get.find<PaymentController>().isWalletChecked == true) {
|
||||
double tip = 0;
|
||||
tip = (Get.find<MapPassengerController>().totalPassenger) *
|
||||
(double.parse(box.read(BoxName.tipPercentage).toString()));
|
||||
|
||||
if (tip > 0) {
|
||||
var res = await CRUD().post(link: AppLink.addTips, payload: {
|
||||
'passengerID': box.read(BoxName.passengerID),
|
||||
'driverID': Get.find<MapPassengerController>().driverId.toString(),
|
||||
'rideID': Get.find<MapPassengerController>().rideId.toString(),
|
||||
'tipAmount': tip.toString(),
|
||||
});
|
||||
await Get.find<PaymentController>()
|
||||
.addPassengersWallet(((-1) * tip).toString());
|
||||
var token1 = await Get.find<PaymentController>().generateTokenDriver(
|
||||
box.read(BoxName.countryCode) == 'Egypt'
|
||||
? tip.toStringAsFixed(0)
|
||||
: (tip * 100).toString());
|
||||
await CRUD().post(link: AppLink.addDriversWalletPoints, payload: {
|
||||
'driverID': Get.find<MapPassengerController>().driverId.toString(),
|
||||
'paymentID': '${Get.find<MapPassengerController>().rideId}tip',
|
||||
'amount': box.read(BoxName.countryCode) == 'Egypt'
|
||||
? tip.toStringAsFixed(0)
|
||||
: (tip * 100).toString(),
|
||||
'paymentMethod': 'visa-tip',
|
||||
'token': token1,
|
||||
});
|
||||
if (res != 'failure') {
|
||||
Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
|
||||
'You Have Tips'.tr,
|
||||
'${'${tip.toString()}\$${' tips\nTotal is'.tr}'} ${tip + (Get.find<MapPassengerController>().totalPassenger)}',
|
||||
Get.find<MapPassengerController>().driverToken.toString(),
|
||||
[],
|
||||
'ding.wav',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
await CRUD().post(
|
||||
link: "${AppLink.IntaleqCairoServer}/ride/rate/addRateToDriver.php",
|
||||
payload: {
|
||||
'passenger_id': box.read(BoxName.passengerID).toString(),
|
||||
'driver_id': driverId.toString(),
|
||||
'ride_id': rideId.toString(),
|
||||
'rating': selectedRateItemId.toString(),
|
||||
'comment': comment.text,
|
||||
});
|
||||
|
||||
if (AppLink.endPoint != AppLink.IntaleqCairoServer) {
|
||||
CRUD().post(
|
||||
link: "${AppLink.endPoint}/ride/rate/addRateToDriver.php",
|
||||
payload: {
|
||||
'passenger_id': box.read(BoxName.passengerID).toString(),
|
||||
'driver_id': driverId.toString(),
|
||||
'ride_id': rideId.toString(),
|
||||
'rating': selectedRateItemId.toString(),
|
||||
'comment': comment.text,
|
||||
});
|
||||
}
|
||||
|
||||
Get.find<MapPassengerController>().restCounter();
|
||||
Get.offAll(const MapPagePassenger());
|
||||
}
|
||||
}
|
||||
148
lib/controller/themes/themes.dart
Normal file
148
lib/controller/themes/themes.dart
Normal file
@@ -0,0 +1,148 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:Intaleq/constant/style.dart';
|
||||
|
||||
import '../../constant/colors.dart';
|
||||
|
||||
ThemeData lightThemeEnglish = ThemeData(
|
||||
brightness: Brightness.light,
|
||||
fontFamily: "SFPro",
|
||||
textTheme: TextTheme(
|
||||
displaySmall: AppStyle.title,
|
||||
displayLarge: AppStyle.headTitle,
|
||||
displayMedium: AppStyle.headTitle2,
|
||||
bodyLarge: AppStyle.title,
|
||||
bodyMedium: AppStyle.subtitle,
|
||||
),
|
||||
primarySwatch: Colors.blue,
|
||||
dialogTheme: DialogTheme(
|
||||
backgroundColor: AppColor.secondaryColor,
|
||||
contentTextStyle: AppStyle.title,
|
||||
titleTextStyle: AppStyle.headTitle2,
|
||||
),
|
||||
appBarTheme: AppBarTheme(
|
||||
elevation: 0,
|
||||
color: AppColor.secondaryColor,
|
||||
centerTitle: true,
|
||||
iconTheme: const IconThemeData(
|
||||
color: AppColor.primaryColor,
|
||||
),
|
||||
toolbarTextStyle: TextTheme(
|
||||
titleSmall: AppStyle.subtitle,
|
||||
headlineSmall: AppStyle.title,
|
||||
titleLarge: AppStyle.headTitle2,
|
||||
).bodyMedium,
|
||||
titleTextStyle: TextTheme(
|
||||
titleSmall: AppStyle.subtitle,
|
||||
headlineSmall: AppStyle.title,
|
||||
titleLarge: AppStyle.headTitle2,
|
||||
).titleLarge,
|
||||
),
|
||||
);
|
||||
|
||||
ThemeData darkThemeEnglish = ThemeData(
|
||||
brightness: Brightness.dark,
|
||||
fontFamily: "SFPro",
|
||||
textTheme: TextTheme(
|
||||
displaySmall: AppStyle.title,
|
||||
displayLarge: AppStyle.headTitle,
|
||||
displayMedium: AppStyle.headTitle2,
|
||||
bodyLarge: AppStyle.title,
|
||||
bodyMedium: AppStyle.subtitle,
|
||||
),
|
||||
primarySwatch: Colors.blue,
|
||||
dialogTheme: DialogTheme(
|
||||
backgroundColor: AppColor.secondaryColor,
|
||||
contentTextStyle: AppStyle.title,
|
||||
titleTextStyle: AppStyle.headTitle2,
|
||||
),
|
||||
appBarTheme: AppBarTheme(
|
||||
elevation: 0,
|
||||
color: AppColor.secondaryColor,
|
||||
centerTitle: true,
|
||||
iconTheme: const IconThemeData(
|
||||
color: AppColor.primaryColor,
|
||||
),
|
||||
toolbarTextStyle: TextTheme(
|
||||
titleSmall: AppStyle.subtitle,
|
||||
headlineSmall: AppStyle.title,
|
||||
titleLarge: AppStyle.headTitle2,
|
||||
).bodyMedium,
|
||||
titleTextStyle: TextTheme(
|
||||
titleSmall: AppStyle.subtitle,
|
||||
headlineSmall: AppStyle.title,
|
||||
titleLarge: AppStyle.headTitle2,
|
||||
).titleLarge,
|
||||
),
|
||||
);
|
||||
|
||||
ThemeData lightThemeArabic = ThemeData(
|
||||
brightness: Brightness.light,
|
||||
fontFamily: 'SFArabic',
|
||||
textTheme: TextTheme(
|
||||
displaySmall: AppStyle.title,
|
||||
displayLarge: AppStyle.headTitle,
|
||||
displayMedium: AppStyle.headTitle2,
|
||||
bodyLarge: AppStyle.title,
|
||||
bodyMedium: AppStyle.subtitle,
|
||||
),
|
||||
primarySwatch: Colors.blue,
|
||||
dialogTheme: DialogTheme(
|
||||
backgroundColor: AppColor.secondaryColor,
|
||||
contentTextStyle: AppStyle.title,
|
||||
titleTextStyle: AppStyle.headTitle2,
|
||||
),
|
||||
appBarTheme: AppBarTheme(
|
||||
elevation: 0,
|
||||
color: AppColor.secondaryColor,
|
||||
centerTitle: true,
|
||||
iconTheme: const IconThemeData(
|
||||
color: AppColor.primaryColor,
|
||||
),
|
||||
toolbarTextStyle: TextTheme(
|
||||
titleSmall: AppStyle.subtitle,
|
||||
headlineSmall: AppStyle.title,
|
||||
titleLarge: AppStyle.headTitle2,
|
||||
).bodyMedium,
|
||||
titleTextStyle: TextTheme(
|
||||
titleSmall: AppStyle.subtitle,
|
||||
headlineSmall: AppStyle.title,
|
||||
titleLarge: AppStyle.headTitle2,
|
||||
).titleLarge,
|
||||
),
|
||||
);
|
||||
|
||||
ThemeData darkThemeArabic = ThemeData(
|
||||
brightness: Brightness.dark,
|
||||
fontFamily: 'SFArabic',
|
||||
textTheme: TextTheme(
|
||||
displaySmall: AppStyle.title,
|
||||
displayLarge: AppStyle.headTitle,
|
||||
displayMedium: AppStyle.headTitle2,
|
||||
bodyLarge: AppStyle.title,
|
||||
bodyMedium: AppStyle.subtitle,
|
||||
),
|
||||
primarySwatch: Colors.blue,
|
||||
dialogTheme: DialogTheme(
|
||||
backgroundColor: AppColor.secondaryColor,
|
||||
contentTextStyle: AppStyle.title,
|
||||
titleTextStyle: AppStyle.headTitle2,
|
||||
),
|
||||
appBarTheme: AppBarTheme(
|
||||
elevation: 0,
|
||||
color: AppColor.secondaryColor,
|
||||
centerTitle: true,
|
||||
iconTheme: const IconThemeData(
|
||||
color: AppColor.primaryColor,
|
||||
),
|
||||
toolbarTextStyle: TextTheme(
|
||||
titleSmall: AppStyle.subtitle,
|
||||
headlineSmall: AppStyle.title,
|
||||
titleLarge: AppStyle.headTitle2,
|
||||
).bodyMedium,
|
||||
titleTextStyle: TextTheme(
|
||||
titleSmall: AppStyle.subtitle,
|
||||
headlineSmall: AppStyle.title,
|
||||
titleLarge: AppStyle.headTitle2,
|
||||
).titleLarge,
|
||||
),
|
||||
);
|
||||
339
lib/env/env.dart
vendored
Normal file
339
lib/env/env.dart
vendored
Normal file
@@ -0,0 +1,339 @@
|
||||
import 'package:envied/envied.dart';
|
||||
|
||||
part 'env.g.dart';
|
||||
|
||||
@Envied()
|
||||
abstract class Env {
|
||||
@EnviedField(varName: 'basicAuthCredentials', obfuscate: true)
|
||||
static final String basicAuthCredentials = _Env.basicAuthCredentials;
|
||||
|
||||
@EnviedField(varName: 'basicCompareFaces', obfuscate: true)
|
||||
static final String basicCompareFaces = _Env.basicCompareFaces;
|
||||
|
||||
@EnviedField(varName: 'sss_encryptionSalt', obfuscate: true)
|
||||
static final String sss_encryptionSalt = _Env.sss_encryptionSalt;
|
||||
|
||||
@EnviedField(varName: 'sss_pass', obfuscate: true)
|
||||
static final String sss_pass = _Env.sss_pass;
|
||||
|
||||
@EnviedField(varName: 'addd', obfuscate: true)
|
||||
static final String addd = _Env.addd;
|
||||
|
||||
@EnviedField(varName: 'passnpassenger', obfuscate: true)
|
||||
static final String passnpassenger = _Env.passnpassenger;
|
||||
|
||||
@EnviedField(varName: 'newId', obfuscate: true)
|
||||
static final String newId = _Env.newId;
|
||||
|
||||
@EnviedField(varName: 'allowed', obfuscate: true)
|
||||
static final String allowed = _Env.allowed;
|
||||
|
||||
@EnviedField(varName: 'apiKeyHere', obfuscate: true)
|
||||
static final String apiKeyHere = _Env.apiKeyHere;
|
||||
|
||||
@EnviedField(varName: 'getLocationAreaLinks', obfuscate: true)
|
||||
static final String getLocationAreaLinks = _Env.getLocationAreaLinks;
|
||||
|
||||
@EnviedField(varName: 'initializationVector', obfuscate: true)
|
||||
static final String initializationVector = _Env.initializationVector;
|
||||
|
||||
@EnviedField(varName: 'basicCompareFacesURL', obfuscate: true)
|
||||
static final String basicCompareFacesURL = _Env.basicCompareFacesURL;
|
||||
|
||||
@EnviedField(varName: 'accountSIDTwillo', obfuscate: true)
|
||||
static final String accountSIDTwillo = _Env.accountSIDTwillo;
|
||||
|
||||
@EnviedField(varName: 'serverAPI', obfuscate: true)
|
||||
static final String serverAPI = _Env.serverAPI;
|
||||
|
||||
@EnviedField(varName: 'mapAPIKEY', obfuscate: true)
|
||||
static final String mapAPIKEY = _Env.mapAPIKEY;
|
||||
|
||||
@EnviedField(varName: 'mapAPIKEYIOS', obfuscate: true)
|
||||
static final String mapAPIKEYIOS = _Env.mapAPIKEYIOS;
|
||||
|
||||
@EnviedField(varName: 'twilloRecoveryCode', obfuscate: true)
|
||||
static final String twilloRecoveryCode = _Env.twilloRecoveryCode;
|
||||
|
||||
@EnviedField(varName: 'authTokenTwillo', obfuscate: true)
|
||||
static final String authTokenTwillo = _Env.authTokenTwillo;
|
||||
|
||||
@EnviedField(varName: 'chatGPTkey', obfuscate: true)
|
||||
static final String chatGPTkey = _Env.chatGPTkey;
|
||||
|
||||
@EnviedField(varName: 'transactionCloude', obfuscate: true)
|
||||
static final String transactionCloude = _Env.transactionCloude;
|
||||
|
||||
@EnviedField(varName: 'visionApi', obfuscate: true)
|
||||
static final String visionApi = _Env.visionApi;
|
||||
|
||||
@EnviedField(varName: 'secretKey', obfuscate: true)
|
||||
static final String secretKey = _Env.secretKey;
|
||||
|
||||
@EnviedField(varName: 'stripe_publishableKe', obfuscate: true)
|
||||
static final String stripePublishableKe = _Env.stripePublishableKe;
|
||||
|
||||
@EnviedField(varName: 'chatGPTkeySefer', obfuscate: true)
|
||||
static final String chatGPTkeySefer = _Env.chatGPTkeySefer;
|
||||
|
||||
@EnviedField(varName: 'llamaKey', obfuscate: true)
|
||||
static final String llamaKey = _Env.llamaKey;
|
||||
|
||||
@EnviedField(varName: 'privateKeyFCM', obfuscate: true)
|
||||
static final String privateKeyFCM = _Env.privateKeyFCM;
|
||||
|
||||
@EnviedField(varName: 'whatsapp', obfuscate: true)
|
||||
static final String whatsapp = _Env.whatsapp;
|
||||
|
||||
@EnviedField(varName: 'whatappID', obfuscate: true)
|
||||
static final String whatappID = _Env.whatappID;
|
||||
|
||||
@EnviedField(varName: 'serverPHP', obfuscate: true)
|
||||
static final String serverPHP = _Env.serverPHP;
|
||||
|
||||
@EnviedField(varName: 'seferAlexandriaServer', obfuscate: true)
|
||||
static final String seferAlexandriaServer = _Env.seferAlexandriaServer;
|
||||
|
||||
@EnviedField(varName: 'seferPaymentServer', obfuscate: true)
|
||||
static final String seferPaymentServer = _Env.seferPaymentServer;
|
||||
|
||||
@EnviedField(varName: 'seferCairoServer', obfuscate: true)
|
||||
static final String seferCairoServer = _Env.seferCairoServer;
|
||||
|
||||
@EnviedField(varName: 'seferGizaServer', obfuscate: true)
|
||||
static final String seferGizaServer = _Env.seferGizaServer;
|
||||
|
||||
@EnviedField(varName: 'chatGPTkeySeferNew', obfuscate: true)
|
||||
static final String chatGPTkeySeferNew = _Env.chatGPTkeySeferNew;
|
||||
|
||||
@EnviedField(varName: 'cohere', obfuscate: true)
|
||||
static final String cohere = _Env.cohere;
|
||||
|
||||
@EnviedField(varName: 'claudeAiAPI', obfuscate: true)
|
||||
static final String claudeAiAPI = _Env.claudeAiAPI;
|
||||
|
||||
@EnviedField(varName: 'payPalClientId', obfuscate: true)
|
||||
static final String payPalClientId = _Env.payPalClientId;
|
||||
|
||||
@EnviedField(varName: 'payPalSecret', obfuscate: true)
|
||||
static final String payPalSecret = _Env.payPalSecret;
|
||||
|
||||
@EnviedField(varName: 'geminiApi', obfuscate: true)
|
||||
static final String geminiApi = _Env.geminiApi;
|
||||
|
||||
@EnviedField(varName: 'geminiApiMasa', obfuscate: true)
|
||||
static final String geminiApiMasa = _Env.geminiApiMasa;
|
||||
|
||||
@EnviedField(varName: 'agoraAppId', obfuscate: true)
|
||||
static final String agoraAppId = _Env.agoraAppId;
|
||||
|
||||
@EnviedField(varName: 'agoraAppCertificate', obfuscate: true)
|
||||
static final String agoraAppCertificate = _Env.agoraAppCertificate;
|
||||
|
||||
@EnviedField(varName: 'payPalClientIdLive', obfuscate: true)
|
||||
static final String payPalClientIdLive = _Env.payPalClientIdLive;
|
||||
|
||||
@EnviedField(varName: 'payPalSecretLive', obfuscate: true)
|
||||
static final String payPalSecretLive = _Env.payPalSecretLive;
|
||||
|
||||
@EnviedField(varName: 'integrationIdPayMob', obfuscate: true)
|
||||
static final String integrationIdPayMob = _Env.integrationIdPayMob;
|
||||
|
||||
@EnviedField(varName: 'passwordPayMob', obfuscate: true)
|
||||
static final String passwordPayMob = _Env.passwordPayMob;
|
||||
|
||||
@EnviedField(varName: 'usernamePayMob', obfuscate: true)
|
||||
static final String usernamePayMob = _Env.usernamePayMob;
|
||||
|
||||
@EnviedField(varName: 'payMobApikey', obfuscate: true)
|
||||
static final String payMobApikey = _Env.payMobApikey;
|
||||
|
||||
@EnviedField(varName: 'integrationIdPayMobWallet', obfuscate: true)
|
||||
static final String integrationIdPayMobWallet =
|
||||
_Env.integrationIdPayMobWallet;
|
||||
|
||||
@EnviedField(varName: 'smsPasswordEgypt', obfuscate: true)
|
||||
static final String smsPasswordEgypt = _Env.smsPasswordEgypt;
|
||||
|
||||
@EnviedField(varName: 'ocpApimSubscriptionKey', obfuscate: true)
|
||||
static final String ocpApimSubscriptionKey = _Env.ocpApimSubscriptionKey;
|
||||
|
||||
@EnviedField(varName: 'chatGPTkeySeferNew4', obfuscate: true)
|
||||
static final String chatGPTkeySeferNew4 = _Env.chatGPTkeySeferNew4;
|
||||
|
||||
@EnviedField(varName: 'anthropicAIkeySeferNew', obfuscate: true)
|
||||
static final String anthropicAIkeySeferNew = _Env.anthropicAIkeySeferNew;
|
||||
|
||||
@EnviedField(varName: 'llama3Key', obfuscate: true)
|
||||
static final String llama3Key = _Env.llama3Key;
|
||||
|
||||
@EnviedField(varName: 'payMobOutClientSecrret', obfuscate: true)
|
||||
static final String payMobOutClientSecrret = _Env.payMobOutClientSecrret;
|
||||
|
||||
@EnviedField(varName: 'payMobOutClient_id', obfuscate: true)
|
||||
static final String payMobOutClient_id = _Env.payMobOutClient_id;
|
||||
|
||||
@EnviedField(varName: 'payMobOutPassword', obfuscate: true)
|
||||
static final String payMobOutPassword = _Env.payMobOutPassword;
|
||||
|
||||
@EnviedField(varName: 'payMobOutUserName', obfuscate: true)
|
||||
static final String payMobOutUserName = _Env.payMobOutUserName;
|
||||
|
||||
@EnviedField(varName: 'A', obfuscate: true)
|
||||
static final String A = _Env.A;
|
||||
|
||||
@EnviedField(varName: 'B', obfuscate: true)
|
||||
static final String B = _Env.B;
|
||||
|
||||
@EnviedField(varName: 'C', obfuscate: true)
|
||||
static final String C = _Env.C;
|
||||
|
||||
@EnviedField(varName: 'D', obfuscate: true)
|
||||
static final String D = _Env.D;
|
||||
|
||||
@EnviedField(varName: 'E', obfuscate: true)
|
||||
static final String E = _Env.E;
|
||||
|
||||
@EnviedField(varName: 'F', obfuscate: true)
|
||||
static final String F = _Env.F;
|
||||
|
||||
@EnviedField(varName: 'G', obfuscate: true)
|
||||
static final String G = _Env.G;
|
||||
|
||||
@EnviedField(varName: 'H', obfuscate: true)
|
||||
static final String H = _Env.H;
|
||||
|
||||
@EnviedField(varName: 'I', obfuscate: true)
|
||||
static final String I = _Env.I;
|
||||
|
||||
@EnviedField(varName: 'J', obfuscate: true)
|
||||
static final String J = _Env.J;
|
||||
|
||||
@EnviedField(varName: 'K', obfuscate: true)
|
||||
static final String K = _Env.K;
|
||||
|
||||
@EnviedField(varName: 'L', obfuscate: true)
|
||||
static final String L = _Env.L;
|
||||
|
||||
@EnviedField(varName: 'M', obfuscate: true)
|
||||
static final String M = _Env.M;
|
||||
|
||||
@EnviedField(varName: 'N', obfuscate: true)
|
||||
static final String N = _Env.N;
|
||||
|
||||
@EnviedField(varName: 'O', obfuscate: true)
|
||||
static final String O = _Env.O;
|
||||
|
||||
@EnviedField(varName: 'P', obfuscate: true)
|
||||
static final String P = _Env.P;
|
||||
|
||||
@EnviedField(varName: 'Q', obfuscate: true)
|
||||
static final String Q = _Env.Q;
|
||||
|
||||
@EnviedField(varName: 'R', obfuscate: true)
|
||||
static final String R = _Env.R;
|
||||
|
||||
@EnviedField(varName: 'S', obfuscate: true)
|
||||
static final String S = _Env.S;
|
||||
|
||||
@EnviedField(varName: 'T', obfuscate: true)
|
||||
static final String T = _Env.T;
|
||||
|
||||
@EnviedField(varName: 'U', obfuscate: true)
|
||||
static final String U = _Env.U;
|
||||
|
||||
@EnviedField(varName: 'V', obfuscate: true)
|
||||
static final String V = _Env.V;
|
||||
|
||||
@EnviedField(varName: 'W', obfuscate: true)
|
||||
static final String W = _Env.W;
|
||||
|
||||
@EnviedField(varName: 'X', obfuscate: true)
|
||||
static final String X = _Env.X;
|
||||
|
||||
@EnviedField(varName: 'Y', obfuscate: true)
|
||||
static final String Y = _Env.Y;
|
||||
|
||||
@EnviedField(varName: 'Z', obfuscate: true)
|
||||
static final String Z = _Env.Z;
|
||||
@EnviedField(varName: 'a', obfuscate: true)
|
||||
static final String a = _Env.a;
|
||||
|
||||
@EnviedField(varName: 'b', obfuscate: true)
|
||||
static final String b = _Env.b;
|
||||
|
||||
@EnviedField(varName: 'c', obfuscate: true)
|
||||
static final String c = _Env.c;
|
||||
|
||||
@EnviedField(varName: 'd', obfuscate: true)
|
||||
static final String d = _Env.d;
|
||||
|
||||
@EnviedField(varName: 'e', obfuscate: true)
|
||||
static final String e = _Env.e;
|
||||
|
||||
@EnviedField(varName: 'f', obfuscate: true)
|
||||
static final String f = _Env.f;
|
||||
|
||||
@EnviedField(varName: 'g', obfuscate: true)
|
||||
static final String g = _Env.g;
|
||||
|
||||
@EnviedField(varName: 'h', obfuscate: true)
|
||||
static final String h = _Env.h;
|
||||
|
||||
@EnviedField(varName: 'i', obfuscate: true)
|
||||
static final String i = _Env.i;
|
||||
|
||||
@EnviedField(varName: 'j', obfuscate: true)
|
||||
static final String j = _Env.j;
|
||||
|
||||
@EnviedField(varName: 'k', obfuscate: true)
|
||||
static final String k = _Env.k;
|
||||
|
||||
@EnviedField(varName: 'l', obfuscate: true)
|
||||
static final String l = _Env.l;
|
||||
|
||||
@EnviedField(varName: 'm', obfuscate: true)
|
||||
static final String m = _Env.m;
|
||||
|
||||
@EnviedField(varName: 'n', obfuscate: true)
|
||||
static final String n = _Env.n;
|
||||
|
||||
@EnviedField(varName: 'o', obfuscate: true)
|
||||
static final String o = _Env.o;
|
||||
|
||||
@EnviedField(varName: 'p', obfuscate: true)
|
||||
static final String p = _Env.p;
|
||||
|
||||
@EnviedField(varName: 'q', obfuscate: true)
|
||||
static final String q = _Env.q;
|
||||
|
||||
@EnviedField(varName: 'r', obfuscate: true)
|
||||
static final String r = _Env.r;
|
||||
|
||||
@EnviedField(varName: 's', obfuscate: true)
|
||||
static final String s = _Env.s;
|
||||
|
||||
@EnviedField(varName: 't', obfuscate: true)
|
||||
static final String t = _Env.t;
|
||||
|
||||
@EnviedField(varName: 'u', obfuscate: true)
|
||||
static final String u = _Env.u;
|
||||
|
||||
@EnviedField(varName: 'v', obfuscate: true)
|
||||
static final String v = _Env.v;
|
||||
|
||||
@EnviedField(varName: 'w', obfuscate: true)
|
||||
static final String w = _Env.w;
|
||||
|
||||
@EnviedField(varName: 'x', obfuscate: true)
|
||||
static final String x = _Env.x;
|
||||
|
||||
@EnviedField(varName: 'y', obfuscate: true)
|
||||
static final String y = _Env.y;
|
||||
|
||||
@EnviedField(varName: 'z', obfuscate: true)
|
||||
static final String z = _Env.z;
|
||||
|
||||
@EnviedField(varName: 'keyOfApp', obfuscate: true)
|
||||
static final String keyOfApp = _Env.keyOfApp;
|
||||
}
|
||||
14260
lib/env/env.g.dart
vendored
Normal file
14260
lib/env/env.g.dart
vendored
Normal file
File diff suppressed because it is too large
Load Diff
71
lib/firebase_options.dart
Normal file
71
lib/firebase_options.dart
Normal file
@@ -0,0 +1,71 @@
|
||||
// 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: 'AIzaSyCFsWBqvkXzk1Gb-bCGxwqTwJQKIeHjH64',
|
||||
appId: '1:1086900987150:android:b7231956aa6d3b3377a35f',
|
||||
messagingSenderId: '1086900987150',
|
||||
projectId: 'intaleq-d48a7',
|
||||
storageBucket: 'intaleq-d48a7.firebasestorage.app',
|
||||
);
|
||||
|
||||
static const FirebaseOptions ios = FirebaseOptions(
|
||||
apiKey: 'AIzaSyDzGO9a-1IDMLD2FxhmOO9ONL1gMssFa9g',
|
||||
appId: '1:1086900987150:ios:a60973accd7f3dc777a35f',
|
||||
messagingSenderId: '1086900987150',
|
||||
projectId: 'intaleq-d48a7',
|
||||
storageBucket: 'intaleq-d48a7.firebasestorage.app',
|
||||
androidClientId: '1086900987150-060srlmdjocdcav377rbur4ka14m90b7.apps.googleusercontent.com',
|
||||
iosClientId: '1086900987150-9jv4oa8l3t23d54lrf27c1d22tbt9i6d.apps.googleusercontent.com',
|
||||
iosBundleId: 'com.Intaleq.intaleq',
|
||||
);
|
||||
|
||||
}
|
||||
18
lib/homw_widget.dart
Normal file
18
lib/homw_widget.dart
Normal file
@@ -0,0 +1,18 @@
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
class WidgetManager {
|
||||
static const platform = MethodChannel('com.mobileapp.store.ride/widget');
|
||||
|
||||
static Future<void> updateWidget() async {
|
||||
try {
|
||||
await platform.invokeMethod('updateWidget');
|
||||
} on PlatformException catch (e) {
|
||||
print("Failed to update widget: '${e.message}'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Example usage:
|
||||
void updateHomeScreenWidget() {
|
||||
WidgetManager.updateWidget();
|
||||
}
|
||||
169
lib/main.dart
Normal file
169
lib/main.dart
Normal file
@@ -0,0 +1,169 @@
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:Intaleq/controller/payment/paymob/paymob_response.dart';
|
||||
import 'package:Intaleq/views/home/HomePage/contact_us.dart';
|
||||
import 'package:Intaleq/views/home/HomePage/share_app_page.dart';
|
||||
import 'package:Intaleq/views/home/my_wallet/passenger_wallet.dart';
|
||||
import 'package:Intaleq/views/home/profile/passenger_profile_page.dart';
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:flutter_stripe/flutter_stripe.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:get_storage/get_storage.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:quick_actions/quick_actions.dart';
|
||||
import 'package:wakelock_plus/wakelock_plus.dart';
|
||||
import 'constant/api_key.dart';
|
||||
import 'constant/info.dart';
|
||||
import 'constant/notification.dart';
|
||||
import 'controller/firebase/firbase_messge.dart';
|
||||
import 'controller/firebase/local_notification.dart';
|
||||
import 'controller/functions/encrypt_decrypt.dart';
|
||||
import 'controller/functions/secure_storage.dart';
|
||||
import 'controller/local/local_controller.dart';
|
||||
import 'controller/local/translations.dart';
|
||||
import 'controller/payment/paymob/paymob_wallet.dart';
|
||||
import 'firebase_options.dart';
|
||||
import 'models/db_sql.dart';
|
||||
import 'splash_screen_page.dart';
|
||||
|
||||
final box = GetStorage();
|
||||
final storage = FlutterSecureStorage();
|
||||
// final PaymobPayment paymobPayment = PaymobPayment();
|
||||
final PaymobPayment paymobPayment = PaymobPayment();
|
||||
final PaymobPaymentWallet paymobPaymentWallet = PaymobPaymentWallet();
|
||||
|
||||
DbSql sql = DbSql.instance;
|
||||
// EncryptionHelper encryptionHelper = EncryptionHelper.instance;
|
||||
@pragma('vm:entry-point')
|
||||
Future<void> backgroundMessageHandler(RemoteMessage message) async {
|
||||
await Firebase.initializeApp();
|
||||
|
||||
FirebaseMessagesController().fireBaseTitles(message);
|
||||
}
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
WakelockPlus.enable();
|
||||
|
||||
await GetStorage.init();
|
||||
|
||||
final AppInitializer initializer = AppInitializer();
|
||||
|
||||
await initializer.initializeApp();
|
||||
await EncryptionHelper.initialize();
|
||||
|
||||
NotificationController notificationController =
|
||||
Get.put(NotificationController());
|
||||
|
||||
Stripe.publishableKey = AK.publishableKey;
|
||||
// if (box.read(BoxName.driverID) != null) {}
|
||||
|
||||
if (Platform.isAndroid || Platform.isIOS) {
|
||||
await Firebase.initializeApp(
|
||||
options: DefaultFirebaseOptions.currentPlatform,
|
||||
);
|
||||
await FirebaseMessagesController().requestFirebaseMessagingPermission();
|
||||
|
||||
FirebaseMessaging.onBackgroundMessage(backgroundMessageHandler);
|
||||
|
||||
List<Future> initializationTasks = [
|
||||
FirebaseMessagesController().getNotificationSettings(),
|
||||
FirebaseMessagesController().getToken(),
|
||||
];
|
||||
// cameras = await availableCameras();
|
||||
await Future.wait(initializationTasks);
|
||||
SystemChrome.setPreferredOrientations([
|
||||
DeviceOrientation.portraitUp,
|
||||
DeviceOrientation.portraitDown,
|
||||
]);
|
||||
}
|
||||
|
||||
await notificationController.initNotifications();
|
||||
|
||||
// Generate a random index to pick a message
|
||||
final random = Random();
|
||||
final randomMessage = messages[random.nextInt(messages.length)];
|
||||
|
||||
// Schedule the notification with the random message
|
||||
notificationController.scheduleNotificationsForSevenDays(
|
||||
randomMessage.split(':')[0],
|
||||
randomMessage.split(':')[1],
|
||||
"tone1",
|
||||
);
|
||||
// final encryptionHelper = await EncryptionHelper.initialize();
|
||||
|
||||
final QuickActions quickActions = QuickActions();
|
||||
|
||||
quickActions.initialize((String shortcutType) {
|
||||
// print('Activated shortcut: $shortcutType');
|
||||
if (shortcutType == 'share_app') {
|
||||
Get.toNamed('/shareApp');
|
||||
} else if (shortcutType == 'wallet') {
|
||||
Get.toNamed('/wallet');
|
||||
} else if (shortcutType == 'profile') {
|
||||
Get.toNamed('/profile');
|
||||
} else if (shortcutType == 'contact_support') {
|
||||
Get.toNamed('/contactSupport');
|
||||
}
|
||||
});
|
||||
quickActions.setShortcutItems(<ShortcutItem>[
|
||||
ShortcutItem(
|
||||
type: 'share_app',
|
||||
localizedTitle: 'Share App'.tr,
|
||||
icon: 'icon_share',
|
||||
),
|
||||
ShortcutItem(
|
||||
type: 'wallet',
|
||||
localizedTitle: 'Wallet'.tr,
|
||||
icon: 'icon_wallet',
|
||||
),
|
||||
ShortcutItem(
|
||||
type: 'profile',
|
||||
localizedTitle: 'Profile'.tr,
|
||||
icon: 'icon_user',
|
||||
),
|
||||
ShortcutItem(
|
||||
type: 'contact_support',
|
||||
localizedTitle: 'Contact Support'.tr,
|
||||
icon: 'icon_support',
|
||||
),
|
||||
]);
|
||||
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
// This widget is the root of your application.
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
LocaleController localController = Get.put(LocaleController());
|
||||
|
||||
return GetMaterialApp(
|
||||
title: AppInformation.appName,
|
||||
translations: MyTranslation(),
|
||||
debugShowCheckedModeBanner: false,
|
||||
locale: localController.language,
|
||||
theme: localController.appTheme,
|
||||
key: UniqueKey(),
|
||||
|
||||
// routes: {'/':const HomePage()},
|
||||
// home: LoginCaptin());
|
||||
initialRoute: '/',
|
||||
getPages: [
|
||||
GetPage(name: '/', page: () => SplashScreen()),
|
||||
GetPage(name: '/shareApp', page: () => ShareAppPage()),
|
||||
GetPage(name: '/wallet', page: () => PassengerWallet()),
|
||||
GetPage(name: '/profile', page: () => PassengerProfilePage()),
|
||||
GetPage(name: '/contactSupport', page: () => ContactUsPage()),
|
||||
],
|
||||
// home: SplashScreen()
|
||||
);
|
||||
}
|
||||
}
|
||||
146
lib/models/db_sql.dart
Normal file
146
lib/models/db_sql.dart
Normal file
@@ -0,0 +1,146 @@
|
||||
import 'package:Intaleq/constant/table_names.dart';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:path/path.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,
|
||||
createdAt TEXT
|
||||
)
|
||||
''');
|
||||
// await db.execute('DROP TABLE IF EXISTS ${TableName.recentLocations}');
|
||||
await db.execute('''
|
||||
CREATE TABLE ${TableName.recentLocations}(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
latitude REAL,
|
||||
longitude REAL,
|
||||
name TEXT,
|
||||
rate TEXT,
|
||||
createdAt 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> insertMapLocation(Map<String, dynamic> map, String table) async {
|
||||
Database db = await instance.database;
|
||||
|
||||
// Check if the record already exists (based on latitude, longitude, and name)
|
||||
var existing = await db.query(
|
||||
table,
|
||||
where: 'latitude = ? AND longitude = ? AND name = ?',
|
||||
whereArgs: [map['latitude'], map['longitude'], map['name']],
|
||||
);
|
||||
|
||||
if (existing.isNotEmpty) {
|
||||
// If record exists, update the createdAt field with the current timestamp
|
||||
var updatedMap = Map<String, dynamic>.from(map);
|
||||
updatedMap['createdAt'] =
|
||||
DateTime.now().toIso8601String(); // Update timestamp
|
||||
return await db.update(
|
||||
table,
|
||||
updatedMap,
|
||||
where: 'id = ?',
|
||||
whereArgs: [existing.first['id']], // Update the existing row
|
||||
);
|
||||
} else {
|
||||
// If record doesn't exist, insert new record with the current timestamp
|
||||
map['createdAt'] = DateTime.now().toIso8601String();
|
||||
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);
|
||||
}
|
||||
}
|
||||
21
lib/models/model/admin/monthly_ride.dart
Normal file
21
lib/models/model/admin/monthly_ride.dart
Normal 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,
|
||||
);
|
||||
}
|
||||
79
lib/models/model/admin/passenger_model.dart
Normal file
79
lib/models/model/admin/passenger_model.dart
Normal 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'],
|
||||
);
|
||||
}
|
||||
}
|
||||
12
lib/models/model/driver/rides_summary_model.dart
Normal file
12
lib/models/model/driver/rides_summary_model.dart
Normal 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]));
|
||||
}
|
||||
34
lib/models/model/locations.dart
Normal file
34
lib/models/model/locations.dart
Normal 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']),
|
||||
);
|
||||
}
|
||||
}
|
||||
30
lib/models/model/onboarding_model.dart
Normal file
30
lib/models/model/onboarding_model.dart
Normal file
@@ -0,0 +1,30 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
List<OnBoardingModel> onBoardingList = [
|
||||
OnBoardingModel(
|
||||
title: 'Welcome to Intaleq!'.tr,
|
||||
image: 'assets/images/on1.png',
|
||||
body:
|
||||
'Intaleq 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 Intaleq, 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:
|
||||
'Intaleq 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});
|
||||
}
|
||||
272
lib/models/model/painter_copoun.dart
Normal file
272
lib/models/model/painter_copoun.dart
Normal file
@@ -0,0 +1,272 @@
|
||||
import 'dart:math' as math;
|
||||
import 'package:Intaleq/constant/box_name.dart';
|
||||
import 'package:Intaleq/main.dart';
|
||||
import 'package:Intaleq/splash_screen_page.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class CouponPainter extends CustomPainter {
|
||||
final Color primaryColor;
|
||||
final Color secondaryColor;
|
||||
|
||||
CouponPainter({
|
||||
required this.primaryColor,
|
||||
required this.secondaryColor,
|
||||
});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final Paint primaryPaint = Paint()
|
||||
..color = primaryColor
|
||||
..style = PaintingStyle.fill; //
|
||||
|
||||
final Paint secondaryPaint = Paint()
|
||||
..color = secondaryColor
|
||||
..style = PaintingStyle.fill;
|
||||
|
||||
final Path path = Path();
|
||||
|
||||
// Draw the main ticket shape
|
||||
path.moveTo(0, size.height * 0.1);
|
||||
path.lineTo(size.width * 0.93, size.height * 0.1);
|
||||
path.arcToPoint(
|
||||
Offset(size.width, size.height * 0.2),
|
||||
radius: const Radius.circular(20),
|
||||
clockwise: false,
|
||||
);
|
||||
path.lineTo(size.width, size.height * 0.8);
|
||||
path.arcToPoint(
|
||||
Offset(size.width * 0.93, size.height * 0.9),
|
||||
radius: const Radius.circular(20),
|
||||
clockwise: false,
|
||||
);
|
||||
path.lineTo(0, size.height * 0.9);
|
||||
path.close();
|
||||
|
||||
canvas.drawPath(path, primaryPaint);
|
||||
|
||||
// Draw decorative circles on the left side
|
||||
for (int i = 0; i < 5; i++) {
|
||||
canvas.drawCircle(
|
||||
Offset(0, size.height * (0.2 + i * 0.15)),
|
||||
10,
|
||||
secondaryPaint,
|
||||
);
|
||||
}
|
||||
|
||||
// Draw a wavy pattern on the right side
|
||||
final wavePaint = Paint()
|
||||
..color = secondaryColor.withOpacity(0.3)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 2;
|
||||
|
||||
for (int i = 0; i < 20; i++) {
|
||||
canvas.drawLine(
|
||||
Offset(size.width * 0.8, i * 10.0),
|
||||
Offset(
|
||||
size.width,
|
||||
i * 10.0 + math.sin(i * 0.5) * 10,
|
||||
),
|
||||
wavePaint,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(CustomPainter oldDelegate) => false;
|
||||
}
|
||||
|
||||
class PromoBanner extends StatelessWidget {
|
||||
final String promoCode;
|
||||
final String discountPercentage;
|
||||
final String validity;
|
||||
|
||||
const PromoBanner({
|
||||
Key? key,
|
||||
required this.promoCode,
|
||||
required this.discountPercentage,
|
||||
required this.validity,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomPaint(
|
||||
painter: CouponPainter(
|
||||
primaryColor: Colors.blue[800]!,
|
||||
secondaryColor: Colors.white,
|
||||
),
|
||||
child: Container(
|
||||
width: 320,
|
||||
height: 240,
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
const SizedBox(
|
||||
height: 10,
|
||||
),
|
||||
Text(
|
||||
'Enter the promo code and get'.tr,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
Text(
|
||||
'${'DISCOUNT'.tr} $discountPercentage ${'for'.tr} $validity'
|
||||
.toUpperCase(),
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.1),
|
||||
blurRadius: 4,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
|
||||
child: Text(
|
||||
promoCode,
|
||||
style: TextStyle(
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.blue[800],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
// Copy promo code to clipboard
|
||||
Clipboard.setData(ClipboardData(text: promoCode));
|
||||
// Show a Snackbar or other feedback to the user
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Promo code copied to clipboard!'.tr)),
|
||||
);
|
||||
box.write(BoxName.isGiftToken, '1');
|
||||
box.write(BoxName.isFirstTime, '1');
|
||||
Get.back();
|
||||
},
|
||||
style: ElevatedButton.styleFrom(
|
||||
foregroundColor: Colors.blue[800], // Customize the color
|
||||
backgroundColor: Colors.white, // Customize the background color
|
||||
),
|
||||
child: Text('Copy Code'.tr),
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// import 'package:Intaleq/constant/colors.dart';
|
||||
// import 'package:flutter/cupertino.dart';
|
||||
// import 'package:flutter/material.dart';
|
||||
|
||||
// class CouponPainter extends CustomPainter {
|
||||
// @override
|
||||
// void paint(Canvas canvas, Size size) {
|
||||
// final Paint paint = Paint()
|
||||
// ..color = AppColor.blueColor
|
||||
// ..style = PaintingStyle.fill;
|
||||
|
||||
// final Path path = Path();
|
||||
|
||||
// // Draw the ticket shape (like the image)
|
||||
// path.moveTo(0, 0);
|
||||
// path.lineTo(size.width * 0.7, 0); // top left to top right edge
|
||||
|
||||
// // Draw curve for the cut on the right side (ticket look)
|
||||
// path.arcToPoint(Offset(size.width, size.height * 0.15),
|
||||
// radius: const Radius.circular(15), clockwise: false);
|
||||
// path.lineTo(size.width, size.height * 0.85);
|
||||
// path.arcToPoint(Offset(size.width * 0.7, size.height),
|
||||
// radius: const Radius.circular(15), clockwise: false);
|
||||
// path.lineTo(0, size.height);
|
||||
|
||||
// canvas.drawPath(path, paint);
|
||||
// }
|
||||
|
||||
// @override
|
||||
// bool shouldRepaint(CustomPainter oldDelegate) {
|
||||
// return false;
|
||||
// }
|
||||
// }
|
||||
|
||||
// class PromoBanner extends StatelessWidget {
|
||||
// final String promoCode;
|
||||
// final String discountPercentage;
|
||||
// final String validity;
|
||||
|
||||
// const PromoBanner({
|
||||
// required this.promoCode,
|
||||
// required this.discountPercentage,
|
||||
// required this.validity,
|
||||
// });
|
||||
|
||||
// @override
|
||||
// Widget build(BuildContext context) {
|
||||
// return CustomPaint(
|
||||
// painter: CouponPainter(),
|
||||
// child: Container(
|
||||
// width: 300, // Fixed width for the promo banner
|
||||
// height: 180, // Set the desired height for your banner
|
||||
// padding: const EdgeInsets.all(16),
|
||||
// child: Column(
|
||||
// mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
// children: [
|
||||
// Text(
|
||||
// 'Enter the promo code and get'.toUpperCase(),
|
||||
// style: const TextStyle(
|
||||
// fontSize: 16,
|
||||
// fontWeight: FontWeight.bold,
|
||||
// color: Colors.white,
|
||||
// ),
|
||||
// textAlign: TextAlign.center,
|
||||
// ),
|
||||
// Text(
|
||||
// '$discountPercentage OFF for $validity'.toUpperCase(),
|
||||
// style: const TextStyle(
|
||||
// fontSize: 18,
|
||||
// fontWeight: FontWeight.bold,
|
||||
// color: Colors.white,
|
||||
// ),
|
||||
// textAlign: TextAlign.center,
|
||||
// ),
|
||||
// const SizedBox(height: 10),
|
||||
// Container(
|
||||
// decoration: BoxDecoration(
|
||||
// color: Colors.white,
|
||||
// borderRadius: BorderRadius.circular(10),
|
||||
// ),
|
||||
// padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
|
||||
// child: Text(
|
||||
// promoCode,
|
||||
// style: TextStyle(
|
||||
// fontSize: 20,
|
||||
// fontWeight: FontWeight.bold,
|
||||
// color: Colors.blue[800],
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
// ),
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user