You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mohemm-flutter-app/lib/ui/login/login_screen.dart

1172 lines
46 KiB
Dart

import 'dart:io';
3 weeks ago
import 'dart:ui' as ui;
import 'package:easy_localization/easy_localization.dart';
4 years ago
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
// import 'package:huawei_hmsavailability/huawei_hmsavailability.dart';
import 'package:mohem_flutter_app/api/login_api_client.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/consts.dart';
4 years ago
import 'package:mohem_flutter_app/classes/notifications.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/config/routes.dart';
import 'package:mohem_flutter_app/dialogs/otp_dialog.dart';
import 'package:mohem_flutter_app/widgets/bottom_sheets/confirm_bottom_sheet.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
3 weeks ago
import 'package:mohem_flutter_app/ui/profile/mazaya_access_result_screen.dart';
import 'package:mohem_flutter_app/models/basic_member_information_model.dart';
import 'package:mohem_flutter_app/models/check_mobile_app_version_model.dart';
import 'package:mohem_flutter_app/models/generic_response_model.dart';
import 'package:mohem_flutter_app/models/get_mobile_login_info_list_model.dart';
3 weeks ago
import 'package:mohem_flutter_app/models/dependent/get_mobile_login_info_dependent_model.dart';
import 'package:mohem_flutter_app/models/member_information_list_model.dart';
import 'package:mohem_flutter_app/models/member_login_list_model.dart';
import 'package:mohem_flutter_app/models/privilege_list_model.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/input_widget.dart';
import 'package:safe_device/safe_device.dart';
// import 'package:safe_device/safe_device.dart';
import 'package:wifi_iot/wifi_iot.dart';
class LoginScreen extends StatefulWidget {
LoginScreen({Key? key}) : super(key: key);
@override
_LoginScreenState createState() {
return _LoginScreenState();
}
}
class _LoginScreenState extends State<LoginScreen> {
TextEditingController username = TextEditingController();
TextEditingController password = TextEditingController();
TextEditingController nationalId = TextEditingController();
TextEditingController dobController = TextEditingController();
DateTime? selectedDob;
3 weeks ago
// ignore: unused_field
CheckMobileAppVersionModel? _checkMobileAppVersion;
MemberLoginListModel? _memberLoginList;
4 years ago
late final FirebaseMessaging _firebaseMessaging;
bool _autoLogin = false;
4 years ago
bool? isAppOpenBySystem;
bool isJailBroken = false;
bool isRealDevice = true;
bool isDevelopmentModeEnable = false;
BasicMemberInformationModel? _basicMemberInformation;
GenericResponseModel? genericResponseModel;
// late HmsApiAvailability hmsApiAvailability;
4 years ago
@override
void initState() {
super.initState();
ApiConsts.selectedMemberType = MemberType.employee;
ApiConsts.ISDependetLogin = false;
3 weeks ago
nationalId.addListener(_onCredentialsChanged);
dobController.addListener(_onCredentialsChanged);
checkDependentPrefs();
// hmsApiAvailability = HmsApiAvailability();
// checkFirebaseToken();
if (kReleaseMode) {
checkDeviceSafety();
}
}
3 weeks ago
void _onCredentialsChanged() {
if (mounted && ApiConsts.ISDependetLogin) {
setState(() {});
}
}
void checkDeviceSafety() {
try {
SafeDevice.isJailBroken.then((bool value) {
isJailBroken = value;
});
SafeDevice.isRealDevice.then((value) {
isRealDevice = value;
});
if (Platform.isAndroid) {
// isOnExternalStorage = await SafeDevice.isOnExternalStorage;
2 years ago
// SafeDevice.isDevelopmentModeEnable.then((value) {
// isDevelopmentModeEnable = value;
// });
}
} catch (error) {
print(error);
}
}
@override
void dispose() {
3 weeks ago
nationalId.removeListener(_onCredentialsChanged);
dobController.removeListener(_onCredentialsChanged);
dobController.dispose();
super.dispose();
}
String? firebaseToken;
GetMobileLoginInfoListModel? loginInfo;
3 weeks ago
GetMobileLoginInfoDependentModel? dependentLoginInfo;
Future<void> checkFirebaseToken() async {
try {
3 years ago
await checkPrefs();
Utils.showLoading(context);
4 years ago
if (Platform.isAndroid) {
try {
if (!(await Utils.isGoogleServicesAvailable())) {
print("HUAWEI APPPP GALLERYYYY!!!!");
3 years ago
AppNotifications().init(firebaseToken, context);
AppState().setIsHuawei = true;
AppNotifications().initHuaweiPush(checkLoginInfo);
} else {
print("GOOGLE PLAY STOREEEE!!!!");
await Firebase.initializeApp();
_firebaseMessaging = FirebaseMessaging.instance;
try {
firebaseToken = await _firebaseMessaging.getToken();
3 weeks ago
if (firebaseToken != null && firebaseToken!.isNotEmpty) {
AppState().setDeviceToken = firebaseToken;
Utils.saveStringFromPrefs("P_DEP_DEVICE_TOKEN", firebaseToken!);
}
} catch (ex) {
firebaseToken = "";
}
AppNotifications().init(firebaseToken, context);
2 years ago
if (isJailBroken || !isRealDevice) {
Utils.hideLoading(context);
Navigator.pushNamedAndRemoveUntil(context, AppRoutes.unsafeDeviceScreen, (_) => false);
} else {
checkLoginInfo();
}
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
}
// });
4 years ago
} catch (ex) {}
} else {
4 years ago
await Firebase.initializeApp();
_firebaseMessaging = FirebaseMessaging.instance;
firebaseToken = await _firebaseMessaging.getToken();
3 weeks ago
if (firebaseToken != null && firebaseToken!.isNotEmpty) {
AppState().setDeviceToken = firebaseToken;
Utils.saveStringFromPrefs("P_DEP_DEVICE_TOKEN", firebaseToken!);
}
3 years ago
String? firebaseAPNSToken = await _firebaseMessaging.getAPNSToken();
print("Firebase Token: $firebaseToken");
print("Firebase APNS Token: $firebaseAPNSToken");
AppNotifications().init(firebaseToken, context);
4 years ago
checkLoginInfo();
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
}
} catch (ex) {
Utils.hideLoading(context);
Utils.handleException(ex, context, null);
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
}
}
4 years ago
void checkLoginInfo() async {
3 years ago
try {
3 weeks ago
String devToken = AppState().getIsHuawei ? AppState().getHuaweiPushToken : (firebaseToken ?? "");
if (devToken.isEmpty && !AppState().getIsHuawei) {
if (AppState().getDeviceToken != null && AppState().getDeviceToken!.isNotEmpty) {
devToken = AppState().getDeviceToken!;
firebaseToken = devToken;
} else {
String saved = await Utils.getStringFromPrefs("P_DEP_DEVICE_TOKEN");
if (saved.isNotEmpty) {
devToken = saved;
firebaseToken = devToken;
} else {
try {
await Firebase.initializeApp();
String? tok = await FirebaseMessaging.instance.getToken();
if (tok != null && tok.isNotEmpty) {
devToken = tok;
firebaseToken = tok;
AppState().setDeviceToken = tok;
Utils.saveStringFromPrefs("P_DEP_DEVICE_TOKEN", tok);
}
} catch (e) {
if (kDebugMode) print("Error fetching FCM token in checkLoginInfo: $e");
}
}
}
}
String devType = Platform.isAndroid ? "android" : "ios";
// if (ApiConsts.selectedMemberType.isDependent) {
// dependentLoginInfo = await LoginApiClient().getMobileLoginInfoNEWDependent(devToken, devType, memberType: MemberType.dependent.value);
// Utils.hideLoading(context);
// if (dependentLoginInfo != null) {
// _handleDependentLoginInfo(dependentLoginInfo!);
// }
// return;
// }
loginInfo = await LoginApiClient().getMobileLoginInfoNEW(devToken, devType, memberType: ApiConsts.selectedMemberType.value);
bool isEmpLast = AppState().isEmpLastLoginToDevice ?? true;
if (!isEmpLast) {
// Dependent login flow
ApiConsts.selectedMemberType = MemberType.dependent;
ApiConsts.ISDependetLogin = true;
if (mounted) {
setState(() {
ApiConsts.selectedMemberType = MemberType.dependent;
ApiConsts.ISDependetLogin = true;
});
}
bool autoLoggedIn = await _tryDependentAutoLogin();
if (autoLoggedIn) {
return;
3 weeks ago
} else {
dependentLoginInfo = await LoginApiClient().getMobileLoginInfoNEWDependent(devToken, devType, memberType: MemberType.dependent.value);
Utils.hideLoading(context);
if (dependentLoginInfo != null) {
_handleDependentLoginInfo(dependentLoginInfo!);
}
if (mounted) {
setState(() {});
}
return;
3 weeks ago
}
}
3 weeks ago
// Employee login flow
ApiConsts.selectedMemberType = MemberType.employee;
ApiConsts.ISDependetLogin = false;
if (mounted) {
setState(() {
ApiConsts.selectedMemberType = MemberType.employee;
ApiConsts.ISDependetLogin = false;
});
}
3 years ago
if (loginInfo == null) {
await checkPrefs();
_autoLogin = false;
Utils.hideLoading(context);
return;
} else {
loginInfo!.deviceToken = firebaseToken;
await checkPrefs();
Utils.hideLoading(context);
performLogin();
}
} catch (ex) {
4 years ago
Utils.hideLoading(context);
}
}
3 weeks ago
void _handleDependentLoginInfo(GetMobileLoginInfoDependentModel info) {
if (info.nationalId != null && info.nationalId!.isNotEmpty) {
nationalId.text = info.nationalId!;
} else if (info.dependentID != null && info.dependentID!.isNotEmpty) {
nationalId.text = info.dependentID!;
}
3 weeks ago
String? rawDob = (info.birthDate != null && info.birthDate!.isNotEmpty) ? info.birthDate : ((info.dob != null && info.dob!.isNotEmpty) ? info.dob : null);
3 weeks ago
if (rawDob != null && rawDob.isNotEmpty) {
DateTime? parsed = _parseBirthDate(rawDob);
if (parsed != null) {
selectedDob = parsed;
3 weeks ago
dobController.text = DateFormat('dd-MM-yyyy').format(parsed);
3 weeks ago
} else {
dobController.text = rawDob;
}
}
if (info.dependentName != null && info.dependentName!.isNotEmpty) {
2 weeks ago
String cleanedName = info.dependentName!.replaceAll(RegExp(r'\s*-\s*'), ' ').replaceAll(RegExp(r'\s+'), ' ').trim();
AppState().setDependentName = cleanedName;
Utils.saveStringFromPrefs("P_DEPENDENT_NAME", cleanedName);
3 weeks ago
}
}
DateTime? _parseBirthDate(String? dateStr) {
if (dateStr == null || dateStr.trim().isEmpty) return null;
String s = dateStr.trim();
// 1. Handle Microsoft WCF JSON Date format: /Date(889401600000)/ or /Date(889401600000+0300)/
RegExp dateRegex = RegExp(r'/?Date\((-?\d+)(?:[+-]\d+)?\)/?');
Match? match = dateRegex.firstMatch(s);
if (match != null) {
try {
int millis = int.parse(match.group(1)!);
DateTime dtUtc = DateTime.fromMillisecondsSinceEpoch(millis, isUtc: true);
return DateTime(dtUtc.year, dtUtc.month, dtUtc.day);
} catch (_) {}
}
// 2. Handle pure epoch milliseconds string e.g. "889401600000"
if (RegExp(r'^-?\d{10,14}$').hasMatch(s)) {
try {
int millis = int.parse(s);
DateTime dtUtc = DateTime.fromMillisecondsSinceEpoch(millis, isUtc: true);
return DateTime(dtUtc.year, dtUtc.month, dtUtc.day);
} catch (_) {}
}
// 3. Try standard ISO-8601 (yyyy-MM-dd, yyyy-MM-ddTHH:mm:ss, etc.)
DateTime? dt = DateTime.tryParse(s);
if (dt != null) return DateTime(dt.year, dt.month, dt.day);
// 4. Try standard custom date patterns
3 weeks ago
List<String> formats = ['dd-MM-yyyy', 'yyyy-MM-dd', 'dd/MM/yyyy', 'MM/dd/yyyy', 'yyyy/MM/dd'];
3 weeks ago
for (String fmt in formats) {
try {
DateTime parsed = DateFormat(fmt).parseStrict(s);
return DateTime(parsed.year, parsed.month, parsed.day);
} catch (_) {}
}
return null;
}
Future<void> checkDependentPrefs() async {
if (nationalId.text.isEmpty) {
String savedNid = await Utils.getStringFromPrefs("P_DEP_NATIONAL_ID");
if (savedNid.isNotEmpty) nationalId.text = savedNid;
}
if (dobController.text.isEmpty) {
String savedDob = await Utils.getStringFromPrefs("P_DEP_BIRTH_DATE");
if (savedDob.isNotEmpty) {
DateTime? parsed = _parseBirthDate(savedDob);
if (parsed != null) {
selectedDob = parsed;
3 weeks ago
dobController.text = DateFormat('dd-MM-yyyy').format(parsed);
3 weeks ago
} else {
dobController.text = savedDob;
}
}
} else {
// If dobController already has raw /Date(...) text, parse and format it cleanly
DateTime? parsed = _parseBirthDate(dobController.text);
if (parsed != null) {
selectedDob = parsed;
3 weeks ago
dobController.text = DateFormat('dd-MM-yyyy').format(parsed);
3 weeks ago
}
}
}
4 years ago
Future<void> checkPrefs() async {
String username = await Utils.getStringFromPrefs(SharedPrefsConsts.username);
4 years ago
if (username.isNotEmpty) {
String password = await Utils.getStringFromPrefs(SharedPrefsConsts.password);
4 years ago
// String firebaseToken = await Utils.getStringFromPrefs(SharedPrefsConsts.firebaseToken);
// print("firebaseToken:$firebaseToken");
this.username.text = username;
this.password.text = password;
_autoLogin = true;
}
}
void performLogin() async {
Utils.showLoading(context);
try {
_checkMobileAppVersion = await LoginApiClient().checkMobileAppVersion();
_memberLoginList = await LoginApiClient().memberLogin(username.text, password.text);
AppState().setMemberLoginListModel = _memberLoginList;
AppState().setUserName = username.text;
AppState().password = password.text;
if (_autoLogin) {
AppState().setMemberInformationListModel = (await MemberInformationListModel.getFromPrefs()).first;
AppState().setPrivilegeListModel = await PrivilegeListModel.getFromPrefs();
String mohemmWifiSSID = await Utils.getStringFromPrefs(SharedPrefsConsts.mohemmWifiSSID);
String mohemmWifiPassword = await Utils.getStringFromPrefs(SharedPrefsConsts.mohemmWifiPassword);
4 years ago
AppState().setMohemmWifiSSID = mohemmWifiSSID;
AppState().setMohemmWifiPassword = mohemmWifiPassword;
}
Utils.hideLoading(context);
if (firebaseToken == null || firebaseToken!.isEmpty || firebaseToken == "null") {
if (AppState().getDeviceToken != null && AppState().getDeviceToken!.isNotEmpty && AppState().getDeviceToken != "null") {
firebaseToken = AppState().getDeviceToken;
} else {
String saved = await Utils.getStringFromPrefs("P_DEP_DEVICE_TOKEN");
if (saved.isNotEmpty && saved != "null") {
firebaseToken = saved;
}
}
}
String effectiveTokenArg = (firebaseToken != null && firebaseToken!.isNotEmpty && firebaseToken != "null")
? firebaseToken!
: (AppState().getDeviceToken ?? "");
if (_autoLogin && loginInfo != null) {
if (loginInfo!.deviceToken == null || loginInfo!.deviceToken!.isEmpty || loginInfo!.deviceToken == "null") {
loginInfo!.deviceToken = effectiveTokenArg;
}
Navigator.pushReplacementNamed(context, AppRoutes.verifyLastLogin, arguments: loginInfo);
} else {
Navigator.pushNamed(context, AppRoutes.verifyLogin, arguments: effectiveTokenArg);
}
4 years ago
Utils.saveStringFromPrefs(SharedPrefsConsts.password, password.text);
} catch (ex) {
print(ex);
print(ex.toString());
Utils.hideLoading(context);
Utils.handleException(ex, context, (msg) {
if (msg.toLowerCase().contains("password has expired")) {
// Sends an OTP/activation code via performForgotPassword() - requires an explicit
// tap, not an auto-firing toast, since it's a real side effect, not just navigation.
ConfirmBottomSheet.show(
context,
message: msg,
confirmText: LocaleKeys.forgotPassword.tr(),
showCancelButton: false,
onConfirm: () {
performForgotPassword();
},
);
} else {
2 weeks ago
Utils.showToast(msg);
}
});
}
}
void performForgotPassword() async {
// if (username.text.isEmpty) {
// return;
// }
Utils.showLoading(context);
try {
_basicMemberInformation = await LoginApiClient().getBasicUserInformation("CS", username.text);
genericResponseModel = await LoginApiClient().sendPublicActivationCode(_basicMemberInformation?.pMOBILENUMBER, username.text);
Utils.hideLoading(context);
OtpDialog(
context,
1,
int.tryParse(_basicMemberInformation?.pMOBILENUMBER ?? ""),
(value, TextEditingController _pinPutController) async {
Utils.showLoading(context);
try {
GenericResponseModel? genericResponseModel = await LoginApiClient().checkPublicActivationCode(value, username.text);
if (genericResponseModel?.errorMessage != null) {
Utils.showToast(genericResponseModel?.errorMessage ?? "");
return;
}
Utils.hideLoading(context);
await Navigator.pushNamed(context, AppRoutes.newPassword, arguments: username.text);
Navigator.pop(context);
// Navigator.pop(context);
} catch (ex) {
print(ex);
_pinPutController.clear();
otpFieldClear.value = "";
Utils.hideLoading(context);
Utils.handleException(ex, context, null);
}
},
3 weeks ago
() => {Navigator.pop(context)},
onResendCode: () {
performForgotPassword();
},
).displayDialog(context);
} catch (ex) {
print(ex);
Utils.hideLoading(context);
Utils.handleException(ex, context, null);
}
}
3 weeks ago
void _switchToMode(MemberType type) async {
if (ApiConsts.selectedMemberType != type) {
AppState().setIsEmpLastLoginToDevice = (type == MemberType.employee);
setState(() {
ApiConsts.selectedMemberType = type;
3 weeks ago
ApiConsts.ISDependetLogin = (type == MemberType.dependent);
});
3 weeks ago
if (type == MemberType.dependent) {
await checkDependentPrefs();
} else {
await checkPrefs();
3 weeks ago
}
if (firebaseToken == null || firebaseToken!.isEmpty) {
String saved = await Utils.getStringFromPrefs("P_DEP_DEVICE_TOKEN");
if (saved.isNotEmpty) {
firebaseToken = saved;
}
}
}
}
Widget _buildCtaCard({bool isSVG = false, required String iconPath, required BuildContext context, required String title, required String subtitle, required VoidCallback onTap}) {
3 weeks ago
bool isRtl = Directionality.of(context) == ui.TextDirection.rtl || AppState().isArabic(context);
return InkWell(
borderRadius: BorderRadius.circular(14),
onTap: onTap,
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(14),
3 weeks ago
decoration: BoxDecoration(color: const Color(0xFFEAF8F4), borderRadius: BorderRadius.circular(14), border: Border.all(color: const Color(0xFFB8E8DB), width: 1.0)),
3 weeks ago
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
3 weeks ago
children: <Widget>[
Container(
width: 40,
height: 40,
decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(10)),
alignment: Alignment.center,
child: isSVG ? SvgPicture.asset(iconPath, height: 22, width: 22).paddingOnly(top: 2, left: 3, right: 3) : Image.asset(iconPath, height: 22, width: 22).paddingOnly(top: 2),
3 weeks ago
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
3 weeks ago
title.toText14(isBold: true, color: const Color(0xFF1E293B), textAlign: isRtl ? TextAlign.right : TextAlign.left),
3 weeks ago
const SizedBox(height: 4),
3 weeks ago
subtitle.toText12(color: const Color(0xFF64748B)),
3 weeks ago
],
),
3 weeks ago
),
const SizedBox(width: 8),
3 weeks ago
Icon(isRtl ? Icons.chevron_left_rounded : Icons.chevron_right_rounded, color: const Color(0xFF64748B), size: 20),
3 weeks ago
],
),
),
);
}
3 weeks ago
Widget _buildDependentCtaCard(BuildContext context) {
return _buildCtaCard(
context: context,
2 weeks ago
isSVG: false,
iconPath: 'assets/images/mazaya.png',
3 weeks ago
title: LocaleKeys.joinMazaya.tr(),
subtitle: LocaleKeys.joinMazayaSubtitle.tr(),
onTap: () => _switchToMode(MemberType.dependent),
);
}
Widget _buildEmployeeCtaCard(BuildContext context) {
return _buildCtaCard(
context: context,
2 weeks ago
iconPath: 'assets/images/mohem.png',
3 weeks ago
title: LocaleKeys.continueAsEmployee.tr(),
subtitle: LocaleKeys.continueAsEmployeeSubtitle.tr(),
onTap: () => _switchToMode(MemberType.employee),
);
}
Future<void> _selectDateOfBirth(BuildContext context) async {
DateTime initialDate = selectedDob ?? DateTime(2000, 1, 1);
DateTime firstDate = DateTime(1920, 1, 1);
DateTime lastDate = DateTime.now();
DateTime? picked = await showDatePicker(
context: context,
initialDate: initialDate.isAfter(lastDate) ? lastDate : initialDate,
firstDate: firstDate,
lastDate: lastDate,
builder: (context, child) {
3 weeks ago
return Theme(data: Theme.of(context).copyWith(colorScheme: const ColorScheme.light(primary: MyColors.textMixColor, onPrimary: Colors.white, onSurface: MyColors.darkTextColor)), child: child!);
},
);
if (picked != null) {
setState(() {
selectedDob = picked;
3 weeks ago
dobController.text = DateFormat('dd-MM-yyyy', 'en_US').format(picked);
});
}
}
String getFormattedBirthDate() {
3 weeks ago
DateTime? date = selectedDob ?? _parseBirthDate(dobController.text.trim());
if (date != null) {
int utcMillis = DateTime.utc(date.year, date.month, date.day).millisecondsSinceEpoch;
return "/Date($utcMillis)/";
}
return "";
}
2 weeks ago
void _navigateToMazayaAccessRevoked([String? depName, String? message]) async {
2 weeks ago
await Utils.removeStringFromPrefs("P_DEP_IS_LOGGED_IN");
await Utils.removeStringFromPrefs("P_DEP_NATIONAL_ID");
await Utils.removeStringFromPrefs("P_DEP_BIRTH_DATE");
await Utils.removeStringFromPrefs("P_DEP_TOKEN_ID");
await Utils.removeStringFromPrefs("P_DEP_LOGIN_TOKEN_ID");
await Utils.removeStringFromPrefs("P_DEP_AUTHENTICATION_TOKEN_ID");
await Utils.removeStringFromPrefs("P_DEP_MOBILE_NUMBER");
await Utils.removeStringFromPrefs("P_DEPENDENT_NAME");
await Utils.removeStringFromPrefs("P_DEP_LOGIN_TYPE");
3 weeks ago
ApiConsts.selectedMemberType = MemberType.employee;
ApiConsts.ISDependetLogin = false;
AppState().setDependentName = null;
AppState().setDependentDob = null;
AppState().setDependentLoginType = null;
AppState().setWalaplusDepInfoModel = null;
AppState().setPostParamsInitConfig();
3 weeks ago
String name = depName ?? AppState().dependentName ?? "";
if (name.isEmpty) {
name = await Utils.getStringFromPrefs("P_DEPENDENT_NAME");
}
if (!mounted) return;
2 weeks ago
Navigator.push(context, MaterialPageRoute(builder: (_) => MazayaAccessResultScreen(isGranted: false, dependentName: name, message: message)));
3 weeks ago
}
void performDependentLogin() async {
if (nationalId.text.trim().isEmpty) {
3 weeks ago
Utils.showToast(LocaleKeys.pleaseEnterNationalId.tr());
return;
}
String birthDateStr = getFormattedBirthDate();
if (birthDateStr.isEmpty) {
3 weeks ago
Utils.showToast(LocaleKeys.pleaseSelectDob.tr());
return;
}
Utils.showLoading(context);
try {
3 weeks ago
String devToken = AppState().getIsHuawei ? AppState().getHuaweiPushToken : (firebaseToken ?? "");
if (devToken.isEmpty && !AppState().getIsHuawei) {
if (AppState().getDeviceToken != null && AppState().getDeviceToken!.isNotEmpty) {
devToken = AppState().getDeviceToken!;
} else {
String saved = await Utils.getStringFromPrefs("P_DEP_DEVICE_TOKEN");
if (saved.isNotEmpty) {
devToken = saved;
}
}
}
String devType = Platform.isAndroid ? "android" : "ios";
GenericResponseModel? depLoginResponse = await LoginApiClient().memberLoginDependent(
nationalId: nationalId.text.trim(),
birthDate: birthDateStr,
3 weeks ago
deviceToken: devToken,
deviceType: devType,
context: context,
);
if (depLoginResponse?.errorMessage != null && depLoginResponse!.errorMessage!.isNotEmpty) {
Utils.hideLoading(context);
3 weeks ago
if (Utils.isMazayaAccessRevoked(depLoginResponse.errorMessage)) {
_navigateToMazayaAccessRevoked();
return;
}
Utils.showToast(depLoginResponse.errorMessage!);
return;
}
3 weeks ago
if (depLoginResponse?.getWalaplusDepInfoModel != null) {
AppState().setWalaplusDepInfoModel = depLoginResponse!.getWalaplusDepInfoModel;
String? depName = depLoginResponse.getWalaplusDepInfoModel?.pDependentName;
if (depName != null && depName.trim().isNotEmpty) {
2 weeks ago
String cleanedName = depName.replaceAll(RegExp(r'\s*-\s*'), ' ').replaceAll(RegExp(r'\s+'), ' ').trim();
AppState().setDependentName = cleanedName;
Utils.saveStringFromPrefs("P_DEPENDENT_NAME", cleanedName);
3 weeks ago
}
}
3 weeks ago
String? authToken = (depLoginResponse?.authenticationTokenID != null && depLoginResponse!.authenticationTokenID!.trim().isNotEmpty) ? depLoginResponse.authenticationTokenID!.trim() : null;
3 weeks ago
String? logInTokenID = depLoginResponse?.logInTokenID;
String? mobileNumber = depLoginResponse?.getWalaplusDepInfoModel?.pEmpMobileNumber;
3 weeks ago
// If AuthenticationTokenID is present in MemberLogin_Dependent response:
// No need to show OTP screen, direct move to dashboard and use AuthenticationTokenID as TokenID for all other requests
if (authToken != null && authToken.isNotEmpty) {
Utils.hideLoading(context);
3 weeks ago
_completeDependentLogin(depLoginResponse, logInTokenID ?? authToken, mobileNumber ?? "", loginType: 1, navigateToDashboard: true);
3 weeks ago
return;
}
// Step 2: Send OTP if no previous login found on this device
if (logInTokenID == null || logInTokenID.isEmpty || mobileNumber == null || mobileNumber.isEmpty) {
Utils.hideLoading(context);
3 weeks ago
Utils.showToast(LocaleKeys.unableToRetrieveDependentInfo.tr());
return;
}
GenericResponseModel? sendOtpResponse = await LoginApiClient().mohemmSendOTPDependent(
nationalId: nationalId.text.trim(),
mobileNumber: mobileNumber,
logInTokenID: logInTokenID,
context: context,
);
Utils.hideLoading(context);
if (sendOtpResponse?.messageStatus == 1) {
// Step 3: Open OTP Dialog
_showDependentOtpDialog(logInTokenID, mobileNumber);
} else {
3 weeks ago
Utils.showToast(sendOtpResponse?.errorMessage ?? LocaleKeys.failedToSendOtp.tr());
}
} catch (ex) {
3 weeks ago
if (kDebugMode) print(ex);
Utils.hideLoading(context);
3 weeks ago
if (Utils.isMazayaAccessRevoked(ex)) {
_navigateToMazayaAccessRevoked();
return;
}
Utils.handleException(ex, context, null);
}
}
void _showDependentOtpDialog(String logInTokenID, String mobileNumber) {
OtpDialog(
context,
1,
int.tryParse(mobileNumber),
(value, TextEditingController _pinPutController) async {
Utils.showLoading(context);
try {
GenericResponseModel? checkOtpResponse = await LoginApiClient().mohemmCheckOTPDependent(
logInTokenID: logInTokenID,
activationCode: value,
nationalId: nationalId.text.trim(),
mobileNumber: mobileNumber,
context: context,
);
Utils.hideLoading(context);
if (checkOtpResponse?.errorMessage != null && checkOtpResponse!.errorMessage!.isNotEmpty) {
3 weeks ago
if (Utils.isMazayaAccessRevoked(checkOtpResponse.errorMessage)) {
Navigator.pop(context);
_navigateToMazayaAccessRevoked();
return;
}
Utils.showToast(checkOtpResponse.errorMessage!);
_pinPutController.clear();
otpFieldClear.value = "";
return;
}
Navigator.pop(context);
3 weeks ago
3 weeks ago
_completeDependentLogin(checkOtpResponse, logInTokenID, mobileNumber, loginType: 1, navigateToDashboard: true);
} catch (ex) {
3 weeks ago
if (kDebugMode) print(ex);
_pinPutController.clear();
otpFieldClear.value = "";
Utils.hideLoading(context);
3 weeks ago
if (Utils.isMazayaAccessRevoked(ex)) {
Navigator.pop(context);
_navigateToMazayaAccessRevoked();
return;
}
Utils.handleException(ex, context, null);
}
},
() {
Navigator.pop(context);
},
onResendCode: () async {
Utils.showLoading(context);
try {
3 weeks ago
await LoginApiClient().mohemmSendOTPDependent(nationalId: nationalId.text.trim(), mobileNumber: mobileNumber, logInTokenID: logInTokenID, context: context);
Utils.hideLoading(context);
2 weeks ago
Utils.showToast(LocaleKeys.verificationCodeResent.tr(), isSuccess: true);
3 weeks ago
_showDependentOtpDialog(logInTokenID, mobileNumber);
} catch (ex) {
Utils.hideLoading(context);
3 weeks ago
if (Utils.isMazayaAccessRevoked(ex)) {
Navigator.pop(context);
_navigateToMazayaAccessRevoked();
return;
}
Utils.handleException(ex, context, null);
}
},
).displayDialog(context);
}
bool _isAutoLoggingInDependent = false;
Future<bool> _tryDependentAutoLogin() async {
if (_isAutoLoggingInDependent) return true;
_isAutoLoggingInDependent = true;
try {
String isDepLoggedIn = await Utils.getStringFromPrefs("P_DEP_IS_LOGGED_IN");
if (isDepLoggedIn != "true") {
return false;
}
String savedNid = await Utils.getStringFromPrefs("P_DEP_NATIONAL_ID");
if (savedNid.isEmpty) {
return false;
}
String savedDob = await Utils.getStringFromPrefs("P_DEP_BIRTH_DATE");
String savedToken = await Utils.getStringFromPrefs("P_DEP_TOKEN_ID");
String savedLoginToken = await Utils.getStringFromPrefs("P_DEP_LOGIN_TOKEN_ID");
String savedAuthToken = await Utils.getStringFromPrefs("P_DEP_AUTHENTICATION_TOKEN_ID");
String savedMobile = await Utils.getStringFromPrefs("P_DEP_MOBILE_NUMBER");
String savedName = await Utils.getStringFromPrefs("P_DEPENDENT_NAME");
String savedLoginType = await Utils.getStringFromPrefs("P_DEP_LOGIN_TYPE");
int loginType = int.tryParse(savedLoginType) ?? 1;
3 weeks ago
String effectiveToken = savedAuthToken.isNotEmpty ? savedAuthToken : (savedToken.isNotEmpty ? savedToken : savedLoginToken);
if (nationalId.text.isEmpty) {
nationalId.text = savedNid;
}
if (savedDob.isNotEmpty && dobController.text.isEmpty) {
DateTime? parsed = _parseBirthDate(savedDob);
if (parsed != null) {
selectedDob = parsed;
dobController.text = DateFormat('dd-MM-yyyy').format(parsed);
} else {
dobController.text = savedDob;
}
}
if (AppState().postParamsObject == null) {
AppState().setPostParamsInitConfig();
}
ApiConsts.selectedMemberType = MemberType.dependent;
ApiConsts.ISDependetLogin = true;
AppState().postParamsObject?.setTokenID = effectiveToken;
AppState().setAuthenticationTokenID = effectiveToken;
AppState().postParamsObject?.setLogInTokenID = savedLoginToken.isNotEmpty ? savedLoginToken : effectiveToken;
AppState().postParamsObject?.setUserName = savedNid;
AppState().postParamsObject?.setPUserName = savedNid;
if (savedMobile.isNotEmpty) {
AppState().postParamsObject?.setMobileNumer = savedMobile;
}
AppState().postParamsObject?.channel = 31;
AppState().postParamsObject?.versionID = 20;
AppState().setUserName = savedNid;
AppState().isAuthenticated = true;
AppState().setLogged = true;
if (savedName.isNotEmpty) {
AppState().setDependentName = savedName;
}
if (savedDob.isNotEmpty) {
AppState().setDependentDob = savedDob;
}
AppState().setDependentLoginType = loginType;
if (savedDob.isNotEmpty) {
String devToken = AppState().getIsHuawei ? AppState().getHuaweiPushToken : (firebaseToken ?? "");
if (devToken.isEmpty && !AppState().getIsHuawei) {
if (AppState().getDeviceToken != null && AppState().getDeviceToken!.isNotEmpty) {
devToken = AppState().getDeviceToken!;
} else {
devToken = await Utils.getStringFromPrefs("P_DEP_DEVICE_TOKEN");
}
}
String devType = Platform.isAndroid ? "android" : "ios";
try {
3 weeks ago
GenericResponseModel? depLoginResponse = await LoginApiClient().memberLoginDependent(nationalId: savedNid, birthDate: savedDob, deviceToken: devToken, deviceType: devType, context: context);
if (depLoginResponse?.errorMessage != null && depLoginResponse!.errorMessage!.isNotEmpty) {
if (Utils.isMazayaAccessRevoked(depLoginResponse.errorMessage)) {
if (mounted) {
Utils.hideLoading(context);
_navigateToMazayaAccessRevoked(savedName);
}
return true;
}
}
if (depLoginResponse != null) {
3 weeks ago
String? authToken = (depLoginResponse.authenticationTokenID != null && depLoginResponse.authenticationTokenID!.trim().isNotEmpty) ? depLoginResponse.authenticationTokenID!.trim() : null;
String? logInTokenID = depLoginResponse.logInTokenID;
String? mobileNumber = depLoginResponse.getWalaplusDepInfoModel?.pEmpMobileNumber ?? savedMobile;
if (authToken != null && authToken.isNotEmpty) {
if (mounted) {
Utils.hideLoading(context);
3 weeks ago
_completeDependentLogin(depLoginResponse, logInTokenID ?? authToken, mobileNumber, loginType: loginType, navigateToDashboard: true);
}
return true;
}
}
} catch (ex) {
if (Utils.isMazayaAccessRevoked(ex)) {
if (mounted) {
Utils.hideLoading(context);
_navigateToMazayaAccessRevoked(savedName);
}
return true;
}
if (kDebugMode) print("Error in memberLoginDependent auto-login: $ex");
}
}
if (effectiveToken.isNotEmpty && mounted) {
Utils.hideLoading(context);
2 weeks ago
Navigator.pushNamedAndRemoveUntil(context, AppRoutes.mazayaDiscover, (Route<dynamic> route) => false);
return true;
}
} catch (e) {
if (kDebugMode) print("Error in _tryDependentAutoLogin: $e");
} finally {
_isAutoLoggingInDependent = false;
}
return false;
}
3 weeks ago
void _completeDependentLogin(GenericResponseModel? checkOtpResponse, String logInTokenID, String mobileNumber, {int loginType = 1, bool navigateToDashboard = true}) {
3 weeks ago
String effectiveToken =
(checkOtpResponse?.authenticationTokenID != null && checkOtpResponse!.authenticationTokenID!.trim().isNotEmpty)
? checkOtpResponse.authenticationTokenID!.trim()
: ((checkOtpResponse?.tokenID != null && checkOtpResponse!.tokenID!.isNotEmpty)
? checkOtpResponse.tokenID!
: ((checkOtpResponse?.logInTokenID != null && checkOtpResponse!.logInTokenID!.isNotEmpty) ? checkOtpResponse.logInTokenID! : logInTokenID));
3 weeks ago
String effectiveNationalId = nationalId.text.trim().isNotEmpty ? nationalId.text.trim() : (AppState().getUserName ?? "");
String effectiveDob = getFormattedBirthDate().isNotEmpty ? getFormattedBirthDate() : (AppState().dependentDob ?? "");
3 weeks ago
AppState().postParamsObject?.setTokenID = effectiveToken;
AppState().setAuthenticationTokenID = effectiveToken;
3 weeks ago
AppState().postParamsObject?.setLogInTokenID = (checkOtpResponse?.logInTokenID != null && checkOtpResponse!.logInTokenID!.isNotEmpty) ? checkOtpResponse.logInTokenID! : logInTokenID;
AppState().postParamsObject?.setUserName = effectiveNationalId;
AppState().postParamsObject?.setPUserName = effectiveNationalId;
3 weeks ago
3 weeks ago
String resolvedMobile = mobileNumber.isNotEmpty ? mobileNumber : (checkOtpResponse?.getWalaplusDepInfoModel?.pEmpMobileNumber ?? "");
3 weeks ago
if (resolvedMobile.isNotEmpty) {
AppState().postParamsObject?.setMobileNumer = resolvedMobile;
Utils.saveStringFromPrefs("P_DEP_MOBILE_NUMBER", resolvedMobile);
}
AppState().setUserName = effectiveNationalId;
3 weeks ago
AppState().isAuthenticated = true;
AppState().setLogged = true;
if (checkOtpResponse?.getWalaplusDepInfoModel != null) {
AppState().setWalaplusDepInfoModel = checkOtpResponse!.getWalaplusDepInfoModel;
String? depName = checkOtpResponse.getWalaplusDepInfoModel?.pDependentName;
if (depName != null && depName.trim().isNotEmpty) {
AppState().setDependentName = depName.trim();
Utils.saveStringFromPrefs("P_DEPENDENT_NAME", depName.trim());
}
}
AppState().setDependentLoginType = loginType;
AppState().setDependentDob = effectiveDob;
3 weeks ago
Utils.saveStringFromPrefs("P_DEP_IS_LOGGED_IN", "true");
Utils.saveStringFromPrefs("P_DEP_NATIONAL_ID", effectiveNationalId);
Utils.saveStringFromPrefs("P_DEP_BIRTH_DATE", effectiveDob);
3 weeks ago
Utils.saveStringFromPrefs("P_DEP_LOGIN_TOKEN_ID", AppState().postParamsObject?.logInTokenID ?? logInTokenID);
Utils.saveStringFromPrefs("P_DEP_TOKEN_ID", effectiveToken);
if (checkOtpResponse?.authenticationTokenID != null && checkOtpResponse!.authenticationTokenID!.trim().isNotEmpty) {
Utils.saveStringFromPrefs("P_DEP_AUTHENTICATION_TOKEN_ID", checkOtpResponse.authenticationTokenID!.trim());
}
String tokenToSave = AppState().getIsHuawei
? AppState().getHuaweiPushToken
: ((firebaseToken != null && firebaseToken!.isNotEmpty && firebaseToken != "null")
? firebaseToken!
: (AppState().getDeviceToken ?? ""));
if (tokenToSave.isNotEmpty && tokenToSave != "null") {
Utils.saveStringFromPrefs("P_DEP_DEVICE_TOKEN", tokenToSave);
}
3 weeks ago
Utils.saveStringFromPrefs("P_DEP_LOGIN_TYPE", loginType.toString());
if (navigateToDashboard && ApiConsts.ISDependetLogin) {
2 weeks ago
Navigator.pushNamedAndRemoveUntil(context, AppRoutes.mazayaDiscover, (Route<dynamic> route) => false);
3 weeks ago
}
}
void _ensureDeviceTokenLoaded() async {
if (firebaseToken == null || firebaseToken!.isEmpty || firebaseToken == "null") {
if (AppState().getDeviceToken != null && AppState().getDeviceToken!.isNotEmpty && AppState().getDeviceToken != "null") {
firebaseToken = AppState().getDeviceToken;
} else {
String saved = await Utils.getStringFromPrefs("P_DEP_DEVICE_TOKEN");
if (saved.isNotEmpty && saved != "null") {
firebaseToken = saved;
AppState().setDeviceToken = saved;
} else if (!AppState().getIsHuawei) {
try {
await Firebase.initializeApp();
String? tok = await FirebaseMessaging.instance.getToken();
if (tok != null && tok.isNotEmpty) {
firebaseToken = tok;
AppState().setDeviceToken = tok;
Utils.saveStringFromPrefs("P_DEP_DEVICE_TOKEN", tok);
}
} catch (_) {}
}
}
}
}
@override
Widget build(BuildContext context) {
4 years ago
if (isAppOpenBySystem == null) {
isAppOpenBySystem = (ModalRoute.of(context)!.settings.arguments ?? true) as bool;
if (!kReleaseMode) {
// username.text = "15444"; // Maha User
4 years ago
// username.text = "15153"; // Tamer User
// password.text = "Abcd@12345";
4 years ago
// username.text = "206535"; // Hashim User
// password.text = "Namira786";
// 13777
// Ab12345cd
}
if (isAppOpenBySystem!) {
checkFirebaseToken();
} else {
_ensureDeviceTokenLoaded();
}
4 years ago
}
// username.text = "15444";
return Scaffold(
body: Column(
children: [
const SizedBox(height: 23),
Expanded(
child: Padding(
padding: const EdgeInsets.all(21.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Row(
children: [
LocaleKeys.english.tr().toText14(color: AppState().isArabic(context) ? null : MyColors.textMixColor).onPress(() {
context.setLocale(const Locale("en", "US"));
_ensureDeviceTokenLoaded();
}),
3 weeks ago
Container(width: 1, color: MyColors.darkWhiteColor, height: 16, margin: const EdgeInsets.only(left: 10, right: 10)),
LocaleKeys.arabic.tr().toText14(color: !AppState().isArabic(context) ? null : MyColors.textMixColor).onPress(() {
context.setLocale(const Locale("ar", "SA"));
_ensureDeviceTokenLoaded();
}),
],
),
],
),
Expanded(
3 weeks ago
child: LayoutBuilder(
builder: (context, constraints) {
return SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: ConstrainedBox(
3 weeks ago
constraints: BoxConstraints(minHeight: constraints.maxHeight),
3 weeks ago
child: IntrinsicHeight(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
LocaleKeys.login.tr().toText24(isBold: true),
LocaleKeys.pleaseEnterLoginDetails.tr().toText16(),
16.height,
if (ApiConsts.selectedMemberType == MemberType.employee) ...[
InputWidget(LocaleKeys.username.tr(), "123456", username),
12.height,
InputWidget(LocaleKeys.password.tr(), "xxxxxx", password, isTextIsPassword: true),
9.height,
Align(
alignment: AlignmentDirectional.centerEnd,
3 weeks ago
child: LocaleKeys.forgotPassword.tr().toText12(isUnderLine: true, color: MyColors.textMixColor).onPress(() {
performForgotPassword();
}),
3 weeks ago
),
20.height,
_buildDependentCtaCard(context),
] else ...[
3 weeks ago
InputWidget(LocaleKeys.nationalIdOrIqamaNumber.tr(), "1234567890", nationalId, isInputTypeNum: true),
3 weeks ago
12.height,
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => _selectDateOfBirth(context),
child: Stack(
alignment: AlignmentDirectional.centerEnd,
children: [
3 weeks ago
IgnorePointer(child: InputWidget(LocaleKeys.dateOfBirth.tr(), "DD-MM-YYYY", dobController)),
3 weeks ago
Positioned.directional(
textDirection: Directionality.of(context),
end: 16,
3 weeks ago
child: const Icon(Icons.calendar_today_outlined, size: 20, color: MyColors.grey70Color),
3 weeks ago
),
],
),
),
20.height,
_buildEmployeeCtaCard(context),
],
],
),
),
),
3 weeks ago
);
},
),
3 weeks ago
),
],
),
),
),
3 weeks ago
DefaultButton(LocaleKeys.login.tr(), () async {
SystemChannels.textInput.invokeMethod('TextInput.hide');
if (ApiConsts.ISDependetLogin) {
performDependentLogin();
} else {
performLogin();
}
}).insideContainer,
],
),
);
}
void connectWithHmgNetwork() async {
try {
bool isConnected = await WiFiForIoTPlugin.connect("MOHEMM-CONNECT", password: "0987654321", joinOnce: Platform.isIOS ? false : true, security: NetworkSecurity.WPA, withInternet: false);
if (isConnected) {
await WiFiForIoTPlugin.forceWifiUsage(true);
// if (Platform.isIOS) {
// await closeWifiRequest();
// await Future.delayed(Duration(seconds: 6));
// } else {
// await WiFiForIoTPlugin.forceWifiUsage(true);
// }
}
} catch (e) {
print("----------------o----");
print(e);
}
}
Future<bool> closeWifiRequest() async {
if (Platform.isAndroid) {
await WiFiForIoTPlugin.forceWifiUsage(false);
}
return await WiFiForIoTPlugin.disconnect();
}
}