This commit is contained in:
Hamza-Ayed
2024-09-30 09:37:26 +03:00
parent f5b7307f86
commit 659f178737
21 changed files with 416 additions and 151 deletions

View File

@@ -281,6 +281,7 @@ class AppLink {
static String getPassengerDetails = "$server/Admin/getPassengerDetails.php";
static String getPassengerbyEmail = "$server/Admin/getPassengerbyEmail.php";
static String addAdminUser = "$server/Admin/adminUser/add.php";
static String addError = "$server/Admin/errorApp.php";
static String getAdminUser = "$server/Admin/adminUser/get.php";
static String getCaptainDetailsByEmailOrIDOrPhone =
"$server/Admin/AdminCaptain/getCaptainDetailsByEmailOrIDOrPhone.php";

View File

@@ -4,6 +4,7 @@ import 'package:SEFER/constant/colors.dart';
import 'package:SEFER/controller/functions/location_background_controller.dart';
import 'package:SEFER/print.dart';
import 'package:SEFER/views/auth/captin/cards/sms_signup.dart';
import 'package:SEFER/views/auth/captin/login_captin.dart';
import 'package:SEFER/views/widgets/elevated_btn.dart';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
@@ -134,6 +135,7 @@ class LoginDriverController extends GetxController {
}
Get.off(() => HomeCaptain());
// Get.off(() => LoginCaptin());
} else {
Get.offAll(() => SmsSignupEgypt());
// Get.snackbar(jsonDecoeded['status'], jsonDecoeded['data'],

View File

@@ -160,83 +160,124 @@ class RegisterCaptainController extends GetxController {
// isLoading = false;
// update();
// }
DateTime? lastOtpSentTime; // Store the last OTP sent time
int otpResendInterval = 300; // 5 minutes in seconds
// Main function to handle OTP sending
sendOtpMessage() async {
SmsEgyptController smsEgyptController = Get.put(SmsEgyptController());
isLoading = true;
update();
int randomNumber = Random().nextInt(100000) + 1;
isLoading = true;
update();
// Get the current time and the last OTP time (if it exists)
DateTime currentTime = DateTime.now();
DateTime? lastOtpTime = box.read(BoxName.lastOtpTime);
// Check if the last OTP was sent within 5 minutes (300 seconds)
if (lastOtpTime != null &&
currentTime.difference(lastOtpTime).inSeconds < 300) {
Get.snackbar(
'Please wait'.tr, 'You can send another OTP after 5 minutes.'.tr,
backgroundColor: AppColor.redColor);
isLoading = false;
if (_isOtpResendAllowed()) {
isLoading = true;
update();
return;
}
if (formKey3.currentState!.validate()) {
if (box.read(BoxName.countryCode) == 'Egypt') {
if (isValidEgyptianPhoneNumber(phoneController.text)) {
var responseCheker = await CRUD()
.post(link: AppLink.checkPhoneNumberISVerfiedDriver, payload: {
'phone_number': '+2${phoneController.text}',
});
if (formKey3.currentState!.validate()) {
String countryCode = box.read(BoxName.countryCode);
String phoneNumber = phoneController.text;
if (responseCheker != 'failure') {
var d = jsonDecode(responseCheker);
if (d['message'][0]['is_verified'].toString() == '1') {
Get.snackbar('Phone number is verified before'.tr, '',
backgroundColor: AppColor.greenColor);
box.write(BoxName.phoneVerified, '1');
box.write(BoxName.phone, '+2${phoneController.text}');
await Get.put(LoginDriverController()).loginUsingCredentials(
box.read(BoxName.driverID).toString(),
box.read(BoxName.emailDriver).toString(),
);
} else {
await _sendOtp(randomNumber, smsEgyptController);
}
} else {
await _sendOtp(randomNumber, smsEgyptController);
}
if (countryCode == 'Egypt' && isValidEgyptianPhoneNumber(phoneNumber)) {
await _checkAndSendOtp(phoneNumber);
} else {
Get.snackbar('Phone Number wrong'.tr, '',
backgroundColor: AppColor.redColor);
_showErrorMessage('Phone Number is not Egypt phone '.tr);
}
}
isLoading = false;
update();
} else {
_showCooldownMessage();
}
}
// Check if the resend OTP request is allowed (5 minutes cooldown)
bool _isOtpResendAllowed() {
if (lastOtpSentTime == null) return true;
final int elapsedTime =
DateTime.now().difference(lastOtpSentTime!).inSeconds;
return elapsedTime >= otpResendInterval;
}
// Show message when user tries to resend OTP too soon
void _showCooldownMessage() {
int remainingTime = otpResendInterval -
DateTime.now().difference(lastOtpSentTime!).inSeconds;
Get.snackbar(
'Please wait ${remainingTime ~/ 60}:${(remainingTime % 60).toString().padLeft(2, '0')} minutes before requesting again',
'',
backgroundColor: AppColor.redColor,
);
}
// Check if the phone number has been verified, and send OTP if not verified
_checkAndSendOtp(String phoneNumber) async {
var responseChecker = await CRUD().post(
link: AppLink.checkPhoneNumberISVerfiedDriver,
payload: {
'phone_number': '+2$phoneNumber',
},
);
if (responseChecker != 'failure') {
var responseData = jsonDecode(responseChecker);
if (_isPhoneVerified(responseData)) {
_handleAlreadyVerified();
} else {
await _sendOtpAndSms(phoneNumber);
}
} else {
await _sendOtpAndSms(phoneNumber);
}
}
// Check if the phone number is already verified
bool _isPhoneVerified(dynamic responseData) {
return responseData['message'][0]['is_verified'].toString() == '1';
}
// Handle case where phone number is already verified
_handleAlreadyVerified() {
Get.snackbar(
'Phone number is already verified'.tr,
'',
backgroundColor: AppColor.greenColor,
);
box.write(BoxName.phoneVerified, '1');
box.write(BoxName.phone, '+2${phoneController.text}');
Get.put(LoginDriverController()).loginUsingCredentials(
box.read(BoxName.driverID).toString(),
box.read(BoxName.emailDriver).toString(),
);
}
// Send OTP and SMS
_sendOtpAndSms(String phoneNumber) async {
SmsEgyptController smsEgyptController = Get.put(SmsEgyptController());
int randomNumber = Random().nextInt(100000) + 1;
await CRUD().post(
link: AppLink.sendVerifyOtpMessage,
payload: {
'phone_number': '+2$phoneNumber',
'token_code': randomNumber.toString(),
'driverId': box.read(BoxName.driverID),
'email': box.read(BoxName.emailDriver),
},
);
// Get.snackbar('', '');
// await smsEgyptController.sendSmsEgypt(phoneNumber, randomNumber.toString());
lastOtpSentTime = DateTime.now(); // Update the last OTP sent time
isSent = true;
isLoading = false;
update();
}
_sendOtp(int randomNumber, SmsEgyptController smsEgyptController) async {
await CRUD().post(link: AppLink.sendVerifyOtpMessage, payload: {
'phone_number': '+2${phoneController.text}',
'token_code': randomNumber.toString(),
"driverId": box.read(BoxName.driverID),
"email": box.read(BoxName.emailDriver),
});
await smsEgyptController.sendSmsEgypt(
phoneController.text.toString(), randomNumber.toString());
// Save the current time as the last OTP time
box.write(BoxName.lastOtpTime, DateTime.now());
isSent = true;
isLoading = false;
update();
// Show error message in case of invalid phone number
void _showErrorMessage(String message) {
Get.snackbar(
message.tr,
'',
backgroundColor: AppColor.redColor,
);
}
verifySMSCode() async {

View File

@@ -0,0 +1,30 @@
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
class FacebookSignIn {
Future<UserCredential?> signInWithFacebook() async {
final LoginResult result = await FacebookAuth.instance.login();
if (result.status == LoginStatus.success) {
// Create a credential from the access token
final OAuthCredential credential =
FacebookAuthProvider.credential(result.accessToken!.tokenString);
// Once signed in, return the UserCredential
return await FirebaseAuth.instance.signInWithCredential(credential);
}
return null;
}
Future<void> signOut() async {
try {
await FacebookAuth.instance.logOut();
print('Facebook Sign Out Successful');
} catch (e) {
print('Error during Facebook Sign Out: $e');
}
}
Future<bool> isSignedIn() async {
final accessToken = await FacebookAuth.instance.accessToken;
return accessToken != null;
}
}

View File

@@ -1,6 +1,8 @@
import 'package:SEFER/constant/box_name.dart';
import 'package:SEFER/constant/colors.dart';
import 'package:SEFER/constant/links.dart';
import 'package:SEFER/controller/auth/captin/login_captin_controller.dart';
import 'package:SEFER/controller/functions/crud.dart';
import 'package:SEFER/main.dart';
import 'package:SEFER/views/auth/captin/cards/sms_signup.dart';
import 'package:SEFER/views/home/on_boarding_page.dart';
@@ -83,7 +85,7 @@ class GoogleSignInHelper {
// return null;
// }
// }
static Future<GoogleSignInAccount?> signInFromLogin() async {
Future<GoogleSignInAccount?> signInFromLogin() async {
try {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
@@ -106,11 +108,27 @@ class GoogleSignInHelper {
} catch (error) {
Get.snackbar('Google Sign-In error', '$error',
backgroundColor: AppColor.redColor);
addError(error.toString(), 'GoogleSignInAccount?> signInFromLogin()');
print('Google Sign-In error: $error');
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 {

View File

@@ -135,7 +135,7 @@ class FirebaseMessagesController extends GetxController {
});
} else if (message.notification!.title == 'Cancel Trip') {
if (Platform.isAndroid) {
NotificationController().showNotification(
NotificationController1().showNotification(
'Cancel Trip'.tr, 'Passenger Cancel Trip'.tr, 'cancel', '');
}
cancelTripDialog();
@@ -143,7 +143,7 @@ class FirebaseMessagesController extends GetxController {
var myListString = message.data['DriverList'];
var driverList = jsonDecode(myListString) as List<dynamic>;
if (Platform.isAndroid) {
NotificationController()
NotificationController1()
.showNotification('VIP Order'.tr, '', 'order', '');
}
MyDialog().getDialog('VIP Order'.tr, 'midTitle', () {
@@ -159,13 +159,13 @@ class FirebaseMessagesController extends GetxController {
} else if (message.notification!.title == 'Cancel') {
cancelTripDialog1();
} else if (message.notification!.title! == 'token change') {
// NotificationController()
// .showNotification('token change'.tr, 'token change', 'cancel');
NotificationController1()
.showNotification('token change'.tr, 'token change', 'cancel', '');
// GoogleSignInHelper.signOut();
GoogleSignInHelper.signOut();
} else if (message.notification!.title! == 'message From passenger') {
if (Platform.isAndroid) {
NotificationController()
NotificationController1()
.showNotification('message From passenger'.tr, ''.tr, 'tone2', '');
}
passengerDialog(message.notification!.body!);

View File

@@ -61,7 +61,7 @@ class NotificationController extends GetxController {
priority: Priority.high,
styleInformation: bigTextStyleInformation,
playSound: true,
sound: RawResourceAndroidNotificationSound(tone),
sound: RawResourceAndroidNotificationSound(tone == '' ? 'ding' : tone),
// audioAttributesUsage: AudioAttributesUsage.alarm,
visibility: NotificationVisibility.public,
autoCancel: false,

View File

@@ -16,6 +16,7 @@ import '../../constant/colors.dart';
import '../../constant/info.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../../print.dart';
import '../functions/crud.dart';
import '../functions/toast.dart';
import 'paymob/paymob_wallet.dart';
@@ -588,25 +589,31 @@ class PaymentController extends GetxController {
billingData: PaymobBillingDataWallet(),
onPayment: (PaymobResponseWallet response) {},
);
if (response!.success == true && response.responseCode == '200') {
Get.defaultDialog(
barrierDismissible: false,
title: 'Payment Successful'.tr,
titleStyle: AppStyle.title,
content: Text(
'The payment was approved.'.tr,
style: AppStyle.title,
),
confirm: MyElevatedButton(
title: 'OK'.tr,
kolor: AppColor.greenColor,
onPressed: () async {
Get.back();
method();
},
),
);
// Log.print('message: ${response!.message}');
// Log.print('responseCode: ${response.responseCode}');
// Log.print('success: ${response.success}');
// Log.print('transactionID: ${response.transactionID}');
if (response!.responseCode == '200' && response.success == true) {
// Log.print('transactionID wewer: ${response.transactionID}');
Toast.show(context, 'Payment Successful'.tr, AppColor.greenColor);
method();
// Get.defaultDialog(
// barrierDismissible: false,
// title: 'Payment Successful'.tr,
// titleStyle: AppStyle.title,
// content: Text(
// 'The payment was approved.'.tr,
// style: AppStyle.title,
// ),
// confirm: MyElevatedButton(
// title: 'OK'.tr,
// kolor: AppColor.greenColor,
// onPressed: () async {
// Get.back();
// method();
// },
// ),
// );
} else {
Get.defaultDialog(
barrierDismissible: false,

View File

@@ -313,6 +313,70 @@ class PaymobIFrameWallet extends StatefulWidget {
State<PaymobIFrameWallet> createState() => _PaymobIFrameState();
}
// class _PaymobIFrameState extends State<PaymobIFrameWallet> {
// WebViewController? controller;
// @override
// void initState() {
// controller = WebViewController()
// ..setJavaScriptMode(JavaScriptMode.unrestricted)
// ..setNavigationDelegate(
// NavigationDelegate(
// onNavigationRequest: (NavigationRequest request) {
// Log.print('request.url: ${request.url}');
// if (request.url.contains('txn_response_code') &&
// 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;
// }
// }
class _PaymobIFrameState extends State<PaymobIFrameWallet> {
WebViewController? controller;
@@ -323,16 +387,23 @@ class _PaymobIFrameState extends State<PaymobIFrameWallet> {
..setNavigationDelegate(
NavigationDelegate(
onNavigationRequest: (NavigationRequest request) {
Log.print('request.url: ${request.url}');
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);
// Show a dialog after successful payment
// _showSuccessDialog(response);
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
@@ -375,4 +446,24 @@ class _PaymobIFrameState extends State<PaymobIFrameWallet> {
return data;
}
void _showSuccessDialog(PaymobResponseWallet response) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Payment Successful'),
content: Text('Transaction ID: EGP'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop(); // Close the dialog
},
child: Text('OK'),
),
],
);
},
);
}
}

View File

@@ -7,6 +7,7 @@ import 'package:SEFER/views/home/Captin/orderCaptin/order_request_page.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
@@ -129,14 +130,14 @@ void main() async {
await FirebaseMessagesController().requestFirebaseMessagingPermission();
FirebaseMessaging.onBackgroundMessage(backgroundMessageHandler);
// NotificationController1().initNotifications();
NotificationController().initNotifications();
NotificationController1().initNotifications();
await Future.wait([
FirebaseMessagesController().getNotificationSettings(),
FirebaseMessagesController().getToken(),
]);
// await FacebookAuth.instance.init();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
@@ -145,6 +146,7 @@ void main() async {
PaymobPayment.instance.initialize(
apiKey: AK.payMobApikey,
// integrationID: 4556055,
integrationID: int.parse(AK.integrationIdPayMob),
userTokenExpiration: 200,
iFrameID: 837992,
@@ -152,6 +154,7 @@ void main() async {
PaymobPaymentWallet.instance.initialize(
apiKey: AK.payMobApikey,
integrationID: int.parse(AK.integrationIdPayMobWallet),
// integrationID: 4556056,
userTokenExpiration: 200,
iFrameID: 837992,
);

View File

@@ -1,5 +1,6 @@
import 'dart:io';
import 'package:SEFER/controller/auth/facebook_login.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
@@ -210,10 +211,20 @@ class LoginCaptin extends StatelessWidget {
MyElevatedButton(
title: 'Sign In by Google'.tr,
onPressed: () async {
await GoogleSignInHelper.signInFromLogin();
await GoogleSignInHelper().signInFromLogin();
},
kolor: AppColor.redColor,
),
// Platform.isAndroid
// ? MyElevatedButton(
// title: 'Sign In by Facebook'.tr,
// onPressed: () async {
// await FacebookSignIn()
// .signInWithFacebook();
// },
// kolor: AppColor.blueColor,
// )
// : const SizedBox(),
!Platform.isAndroid
? MyElevatedButton(
title: 'Sign In by Apple'.tr,

View File

@@ -3,6 +3,7 @@ import 'package:SEFER/controller/firebase/local_notification.dart';
import 'package:SEFER/main.dart';
import 'package:SEFER/views/auth/captin/cards/egypt_card_a_i.dart';
import 'package:SEFER/views/auth/captin/cards/sms_signup.dart';
import 'package:SEFER/views/auth/captin/login_captin.dart';
import 'package:flutter/material.dart';
import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:bubble_head/bubble.dart';
@@ -276,20 +277,20 @@ GetBuilder<HomeCaptainController> leftMainMenuCaptainIcons() {
// return IconButton(
// onPressed: () async {
// // FirebaseMessagesController().sendNotificationToAnyWithoutData(
// // 'Order'.tr,
// // 'from: ',
// // // jsonDecode(value)['message'].toString(),
// // 'dqK5wNrPTr20HQ8qa5KsgL:APA91bHwPW_XzCIxQtg_IkJmHg1JRd8NRMquvsgedBaHAIgErTs6Uzpw1IX0EIJqkTaZq5dxd1u2z7NVdLlvcmEzrpjjWt1pUsZaa5UU7Cpx6hUzJMUdXvhNlAYFGklM8bWUG4ZXSRf1',
// // 'order.wav');
// // NotificationController().showNotification(
// // 'Order'.tr,
// // 'We regret to inform you that another driver has accepted this order.'
// // .tr,
// // 'order',
// // '');
// // requestLocationPermission();
// // Get.to(SmsSignupEgypt());
// // print(box.read(BoxName.tokenDriver));
// 'Order'.tr,
// 'from: ',
// // jsonDecode(value)['message'].toString(),
// 'dqK5wNrPTr20HQ8qa5KsgL:APA91bHwPW_XzCIxQtg_IkJmHg1JRd8NRMquvsgedBaHAIgErTs6Uzpw1IX0EIJqkTaZq5dxd1u2z7NVdLlvcmEzrpjjWt1pUsZaa5UU7Cpx6hUzJMUdXvhNlAYFGklM8bWUG4ZXSRf1',
// 'order.wav');
// NotificationController1().showNotification(
// 'sdf'.tr,
// 'We regret to inform you that another driver has accepted this order.'
// .tr,
// '',
// '');
// requestLocationPermission();
// Get.to(() => LoginCaptin());
// print(box.read(BoxName.tokenDriver));
// },
// icon: const Icon(
// FontAwesome5.closed_captioning,

View File

@@ -437,8 +437,12 @@ class PassengerInfoWindow extends StatelessWidget {
title: 'I arrive you'.tr,
kolor: AppColor.yellowColor,
onPressed: () async {
if (controller
.calculateDistanceBetweenDriverAndPassengerLocation() <
// Await the result of the distance calculation
double distanceToArrive =
await controller
.calculateDistanceBetweenDriverAndPassengerLocation();
if (distanceToArrive <
40) {
FirebaseMessagesController()
.sendNotificationToPassengerToken(

View File

@@ -106,7 +106,7 @@ class PointsCaptain extends StatelessWidget {
.getCaptainWalletFromBuyPoints();
});
}
Get.back();
// Get.back();
}));
},
),