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.
921 lines
36 KiB
Dart
921 lines
36 KiB
Dart
import 'dart:io';
|
|
import 'dart:ui' as ui;
|
|
|
|
import 'package:easy_localization/easy_localization.dart';
|
|
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: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';
|
|
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/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';
|
|
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';
|
|
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;
|
|
|
|
// ignore: unused_field
|
|
CheckMobileAppVersionModel? _checkMobileAppVersion;
|
|
MemberLoginListModel? _memberLoginList;
|
|
|
|
late final FirebaseMessaging _firebaseMessaging;
|
|
|
|
bool _autoLogin = false;
|
|
|
|
bool? isAppOpenBySystem;
|
|
|
|
bool isJailBroken = false;
|
|
bool isRealDevice = true;
|
|
bool isDevelopmentModeEnable = false;
|
|
|
|
BasicMemberInformationModel? _basicMemberInformation;
|
|
GenericResponseModel? genericResponseModel;
|
|
|
|
// late HmsApiAvailability hmsApiAvailability;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
ApiConsts.selectedMemberType = MemberType.employee;
|
|
ApiConsts.ISDependetLogin = false;
|
|
nationalId.addListener(_onCredentialsChanged);
|
|
dobController.addListener(_onCredentialsChanged);
|
|
checkDependentPrefs();
|
|
// hmsApiAvailability = HmsApiAvailability();
|
|
// checkFirebaseToken();
|
|
if (kReleaseMode) {
|
|
checkDeviceSafety();
|
|
}
|
|
}
|
|
|
|
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;
|
|
// SafeDevice.isDevelopmentModeEnable.then((value) {
|
|
// isDevelopmentModeEnable = value;
|
|
// });
|
|
}
|
|
} catch (error) {
|
|
print(error);
|
|
}
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
nationalId.removeListener(_onCredentialsChanged);
|
|
dobController.removeListener(_onCredentialsChanged);
|
|
dobController.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
String? firebaseToken;
|
|
GetMobileLoginInfoListModel? loginInfo;
|
|
GetMobileLoginInfoDependentModel? dependentLoginInfo;
|
|
|
|
Future<void> checkFirebaseToken() async {
|
|
try {
|
|
await checkPrefs();
|
|
Utils.showLoading(context);
|
|
if (Platform.isAndroid) {
|
|
try {
|
|
if (!(await Utils.isGoogleServicesAvailable())) {
|
|
print("HUAWEI APPPP GALLERYYYY!!!!");
|
|
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();
|
|
if (firebaseToken != null && firebaseToken!.isNotEmpty) {
|
|
AppState().setDeviceToken = firebaseToken;
|
|
Utils.saveStringFromPrefs("P_DEP_DEVICE_TOKEN", firebaseToken!);
|
|
}
|
|
} catch (ex) {
|
|
firebaseToken = "";
|
|
}
|
|
AppNotifications().init(firebaseToken, context);
|
|
|
|
if (isJailBroken || !isRealDevice) {
|
|
Utils.hideLoading(context);
|
|
Navigator.pushNamedAndRemoveUntil(context, AppRoutes.unsafeDeviceScreen, (_) => false);
|
|
} else {
|
|
checkLoginInfo();
|
|
}
|
|
|
|
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
|
|
}
|
|
// });
|
|
} catch (ex) {}
|
|
} else {
|
|
await Firebase.initializeApp();
|
|
_firebaseMessaging = FirebaseMessaging.instance;
|
|
firebaseToken = await _firebaseMessaging.getToken();
|
|
if (firebaseToken != null && firebaseToken!.isNotEmpty) {
|
|
AppState().setDeviceToken = firebaseToken;
|
|
Utils.saveStringFromPrefs("P_DEP_DEVICE_TOKEN", firebaseToken!);
|
|
}
|
|
String? firebaseAPNSToken = await _firebaseMessaging.getAPNSToken();
|
|
print("Firebase Token: $firebaseToken");
|
|
print("Firebase APNS Token: $firebaseAPNSToken");
|
|
AppNotifications().init(firebaseToken, context);
|
|
checkLoginInfo();
|
|
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
|
|
}
|
|
} catch (ex) {
|
|
Utils.hideLoading(context);
|
|
Utils.handleException(ex, context, null);
|
|
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
|
|
}
|
|
}
|
|
|
|
void checkLoginInfo() async {
|
|
try {
|
|
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);
|
|
if (loginInfo == null) {
|
|
await checkPrefs();
|
|
_autoLogin = false;
|
|
Utils.hideLoading(context);
|
|
return;
|
|
} else {
|
|
loginInfo!.deviceToken = firebaseToken;
|
|
await checkPrefs();
|
|
Utils.hideLoading(context);
|
|
performLogin();
|
|
}
|
|
} catch (ex) {
|
|
Utils.hideLoading(context);
|
|
}
|
|
}
|
|
|
|
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!;
|
|
}
|
|
|
|
String? rawDob = (info.birthDate != null && info.birthDate!.isNotEmpty) ? info.birthDate : ((info.dob != null && info.dob!.isNotEmpty) ? info.dob : null);
|
|
|
|
if (rawDob != null && rawDob.isNotEmpty) {
|
|
DateTime? parsed = _parseBirthDate(rawDob);
|
|
if (parsed != null) {
|
|
selectedDob = parsed;
|
|
dobController.text = DateFormat('dd-MM-yyyy').format(parsed);
|
|
} else {
|
|
dobController.text = rawDob;
|
|
}
|
|
}
|
|
|
|
if (info.dependentName != null && info.dependentName!.isNotEmpty) {
|
|
AppState().setDependentName = info.dependentName;
|
|
Utils.saveStringFromPrefs("P_DEPENDENT_NAME", info.dependentName!);
|
|
}
|
|
}
|
|
|
|
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
|
|
List<String> formats = ['dd-MM-yyyy', 'yyyy-MM-dd', 'dd/MM/yyyy', 'MM/dd/yyyy', 'yyyy/MM/dd'];
|
|
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;
|
|
dobController.text = DateFormat('dd-MM-yyyy').format(parsed);
|
|
} 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;
|
|
dobController.text = DateFormat('dd-MM-yyyy').format(parsed);
|
|
}
|
|
}
|
|
}
|
|
|
|
Future<void> checkPrefs() async {
|
|
String username = await Utils.getStringFromPrefs(SharedPrefsConsts.username);
|
|
if (username.isNotEmpty) {
|
|
String password = await Utils.getStringFromPrefs(SharedPrefsConsts.password);
|
|
// 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);
|
|
AppState().setMohemmWifiSSID = mohemmWifiSSID;
|
|
AppState().setMohemmWifiPassword = mohemmWifiPassword;
|
|
}
|
|
Utils.hideLoading(context);
|
|
if (_autoLogin) {
|
|
Navigator.pushReplacementNamed(context, AppRoutes.verifyLastLogin, arguments: loginInfo);
|
|
} else {
|
|
Navigator.pushNamed(context, AppRoutes.verifyLogin, arguments: "$firebaseToken");
|
|
}
|
|
Utils.saveStringFromPrefs(SharedPrefsConsts.password, password.text);
|
|
} catch (ex) {
|
|
print(ex);
|
|
print(ex.toString());
|
|
Utils.hideLoading(context);
|
|
Utils.handleException(ex, context, (msg) {
|
|
Utils.confirmDialog(
|
|
context,
|
|
msg,
|
|
onTap: () async {
|
|
if (msg.toLowerCase().contains("password has expired")) {
|
|
Navigator.pop(context);
|
|
// await Navigator.pushNamed(context, AppRoutes.newPassword, arguments: username.text);
|
|
performForgotPassword();
|
|
} else {
|
|
Navigator.pop(context);
|
|
}
|
|
},
|
|
);
|
|
});
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
},
|
|
() => {Navigator.pop(context)},
|
|
onResendCode: () {
|
|
performForgotPassword();
|
|
},
|
|
).displayDialog(context);
|
|
} catch (ex) {
|
|
print(ex);
|
|
Utils.hideLoading(context);
|
|
Utils.handleException(ex, context, null);
|
|
}
|
|
}
|
|
|
|
void _switchToMode(MemberType type) async {
|
|
if (ApiConsts.selectedMemberType != type) {
|
|
setState(() {
|
|
ApiConsts.selectedMemberType = type;
|
|
ApiConsts.ISDependetLogin = (type == MemberType.dependent);
|
|
});
|
|
if (type == MemberType.dependent) {
|
|
await checkDependentPrefs();
|
|
}
|
|
if (firebaseToken == null || firebaseToken!.isEmpty) {
|
|
String saved = await Utils.getStringFromPrefs("P_DEP_DEVICE_TOKEN");
|
|
if (saved.isNotEmpty) {
|
|
firebaseToken = saved;
|
|
}
|
|
}
|
|
checkLoginInfo();
|
|
}
|
|
}
|
|
|
|
Widget _buildCtaCard({required BuildContext context, required IconData icon, required String title, required String subtitle, required VoidCallback onTap}) {
|
|
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),
|
|
decoration: BoxDecoration(color: const Color(0xFFEAF8F4), borderRadius: BorderRadius.circular(14), border: Border.all(color: const Color(0xFFB8E8DB), width: 1.0)),
|
|
child: Row(
|
|
crossAxisAlignment: CrossAxisAlignment.center,
|
|
children: <Widget>[
|
|
Container(
|
|
width: 40,
|
|
height: 40,
|
|
decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle),
|
|
alignment: Alignment.center,
|
|
child: Icon(icon, color: const Color(0xFF168A89), size: 22),
|
|
),
|
|
const SizedBox(width: 12),
|
|
Expanded(
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: <Widget>[
|
|
title.toText14(isBold: true, color: const Color(0xFF1E293B), textAlign: isRtl ? TextAlign.right : TextAlign.left),
|
|
const SizedBox(height: 4),
|
|
subtitle.toText12(color: const Color(0xFF64748B)),
|
|
],
|
|
),
|
|
),
|
|
const SizedBox(width: 8),
|
|
Icon(isRtl ? Icons.chevron_left_rounded : Icons.chevron_right_rounded, color: const Color(0xFF64748B), size: 20),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildDependentCtaCard(BuildContext context) {
|
|
return _buildCtaCard(
|
|
context: context,
|
|
icon: Icons.person_outline_rounded,
|
|
title: LocaleKeys.joinMazaya.tr(),
|
|
subtitle: LocaleKeys.joinMazayaSubtitle.tr(),
|
|
onTap: () => _switchToMode(MemberType.dependent),
|
|
);
|
|
}
|
|
|
|
Widget _buildEmployeeCtaCard(BuildContext context) {
|
|
return _buildCtaCard(
|
|
context: context,
|
|
icon: Icons.badge_outlined,
|
|
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) {
|
|
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;
|
|
dobController.text = DateFormat('dd-MM-yyyy', 'en_US').format(picked);
|
|
});
|
|
}
|
|
}
|
|
|
|
String getFormattedBirthDate() {
|
|
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 "";
|
|
}
|
|
|
|
void _navigateToMazayaAccessRevoked([String? depName]) async {
|
|
String name = depName ?? AppState().dependentName ?? "";
|
|
if (name.isEmpty) {
|
|
name = await Utils.getStringFromPrefs("P_DEPENDENT_NAME");
|
|
}
|
|
if (!mounted) return;
|
|
Navigator.push(context, MaterialPageRoute(builder: (_) => MazayaAccessResultScreen(isGranted: false, dependentName: name)));
|
|
}
|
|
|
|
void performDependentLogin() async {
|
|
if (nationalId.text.trim().isEmpty) {
|
|
Utils.showToast(LocaleKeys.pleaseEnterNationalId.tr());
|
|
return;
|
|
}
|
|
String birthDateStr = getFormattedBirthDate();
|
|
if (birthDateStr.isEmpty) {
|
|
Utils.showToast(LocaleKeys.pleaseSelectDob.tr());
|
|
return;
|
|
}
|
|
|
|
Utils.showLoading(context);
|
|
try {
|
|
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,
|
|
deviceToken: devToken,
|
|
deviceType: devType,
|
|
context: context,
|
|
);
|
|
|
|
if (depLoginResponse?.errorMessage != null && depLoginResponse!.errorMessage!.isNotEmpty) {
|
|
Utils.hideLoading(context);
|
|
if (Utils.isMazayaAccessRevoked(depLoginResponse.errorMessage)) {
|
|
_navigateToMazayaAccessRevoked();
|
|
return;
|
|
}
|
|
Utils.showToast(depLoginResponse.errorMessage!);
|
|
return;
|
|
}
|
|
|
|
if (depLoginResponse?.getWalaplusDepInfoModel != null) {
|
|
AppState().setWalaplusDepInfoModel = depLoginResponse!.getWalaplusDepInfoModel;
|
|
String? depName = depLoginResponse.getWalaplusDepInfoModel?.pDependentName;
|
|
if (depName != null && depName.trim().isNotEmpty) {
|
|
AppState().setDependentName = depName.trim();
|
|
Utils.saveStringFromPrefs("P_DEPENDENT_NAME", depName.trim());
|
|
}
|
|
}
|
|
|
|
String? authToken = (depLoginResponse?.authenticationTokenID != null && depLoginResponse!.authenticationTokenID!.trim().isNotEmpty) ? depLoginResponse.authenticationTokenID!.trim() : null;
|
|
|
|
String? logInTokenID = depLoginResponse?.logInTokenID;
|
|
String? mobileNumber = depLoginResponse?.getWalaplusDepInfoModel?.pEmpMobileNumber;
|
|
|
|
// 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);
|
|
_completeDependentLogin(depLoginResponse, logInTokenID ?? authToken, mobileNumber ?? "", loginType: 1, navigateToDashboard: true);
|
|
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);
|
|
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 {
|
|
Utils.showToast(sendOtpResponse?.errorMessage ?? LocaleKeys.failedToSendOtp.tr());
|
|
}
|
|
} catch (ex) {
|
|
if (kDebugMode) print(ex);
|
|
Utils.hideLoading(context);
|
|
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) {
|
|
if (Utils.isMazayaAccessRevoked(checkOtpResponse.errorMessage)) {
|
|
Navigator.pop(context);
|
|
_navigateToMazayaAccessRevoked();
|
|
return;
|
|
}
|
|
Utils.showToast(checkOtpResponse.errorMessage!);
|
|
_pinPutController.clear();
|
|
otpFieldClear.value = "";
|
|
return;
|
|
}
|
|
|
|
Navigator.pop(context);
|
|
|
|
_completeDependentLogin(checkOtpResponse, logInTokenID, mobileNumber, loginType: 1, navigateToDashboard: true);
|
|
} catch (ex) {
|
|
if (kDebugMode) print(ex);
|
|
_pinPutController.clear();
|
|
otpFieldClear.value = "";
|
|
Utils.hideLoading(context);
|
|
if (Utils.isMazayaAccessRevoked(ex)) {
|
|
Navigator.pop(context);
|
|
_navigateToMazayaAccessRevoked();
|
|
return;
|
|
}
|
|
Utils.handleException(ex, context, null);
|
|
}
|
|
},
|
|
() {
|
|
Navigator.pop(context);
|
|
},
|
|
onResendCode: () async {
|
|
Utils.showLoading(context);
|
|
try {
|
|
await LoginApiClient().mohemmSendOTPDependent(nationalId: nationalId.text.trim(), mobileNumber: mobileNumber, logInTokenID: logInTokenID, context: context);
|
|
Utils.hideLoading(context);
|
|
Utils.showToast(LocaleKeys.verificationCodeResent.tr());
|
|
_showDependentOtpDialog(logInTokenID, mobileNumber);
|
|
} catch (ex) {
|
|
Utils.hideLoading(context);
|
|
if (Utils.isMazayaAccessRevoked(ex)) {
|
|
Navigator.pop(context);
|
|
_navigateToMazayaAccessRevoked();
|
|
return;
|
|
}
|
|
Utils.handleException(ex, context, null);
|
|
}
|
|
},
|
|
).displayDialog(context);
|
|
}
|
|
|
|
void _completeDependentLogin(GenericResponseModel? checkOtpResponse, String logInTokenID, String mobileNumber, {int loginType = 1, bool navigateToDashboard = true}) {
|
|
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));
|
|
|
|
AppState().postParamsObject?.setTokenID = effectiveToken;
|
|
AppState().setAuthenticationTokenID = effectiveToken;
|
|
AppState().postParamsObject?.setLogInTokenID = (checkOtpResponse?.logInTokenID != null && checkOtpResponse!.logInTokenID!.isNotEmpty) ? checkOtpResponse.logInTokenID! : logInTokenID;
|
|
AppState().postParamsObject?.setUserName = nationalId.text.trim();
|
|
AppState().postParamsObject?.setPUserName = nationalId.text.trim();
|
|
|
|
String resolvedMobile = mobileNumber.isNotEmpty ? mobileNumber : (checkOtpResponse?.getWalaplusDepInfoModel?.pEmpMobileNumber ?? "");
|
|
if (resolvedMobile.isNotEmpty) {
|
|
AppState().postParamsObject?.setMobileNumer = resolvedMobile;
|
|
Utils.saveStringFromPrefs("P_DEP_MOBILE_NUMBER", resolvedMobile);
|
|
}
|
|
|
|
AppState().postParamsObject?.channel = 31;
|
|
AppState().postParamsObject?.versionID = 20;
|
|
AppState().setUserName = nationalId.text.trim();
|
|
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 = getFormattedBirthDate();
|
|
|
|
Utils.saveStringFromPrefs("P_DEP_NATIONAL_ID", nationalId.text.trim());
|
|
Utils.saveStringFromPrefs("P_DEP_BIRTH_DATE", getFormattedBirthDate());
|
|
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());
|
|
}
|
|
Utils.saveStringFromPrefs("P_DEP_DEVICE_TOKEN", AppState().getIsHuawei ? AppState().getHuaweiPushToken : firebaseToken ?? "");
|
|
Utils.saveStringFromPrefs("P_DEP_LOGIN_TYPE", loginType.toString());
|
|
|
|
if (navigateToDashboard && ApiConsts.ISDependetLogin) {
|
|
Navigator.pushNamedAndRemoveUntil(context, AppRoutes.dashboardScreenForDependet, (route) => false);
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
if (isAppOpenBySystem == null) {
|
|
isAppOpenBySystem = (ModalRoute.of(context)!.settings.arguments ?? true) as bool;
|
|
if (!kReleaseMode) {
|
|
// username.text = "15444"; // Maha User
|
|
// username.text = "15153"; // Tamer User
|
|
// password.text = "Abcd@12345";
|
|
|
|
// username.text = "206535"; // Hashim User
|
|
// password.text = "Namira786";
|
|
|
|
// 13777
|
|
// Ab12345cd
|
|
}
|
|
if (isAppOpenBySystem!) checkFirebaseToken();
|
|
}
|
|
|
|
// 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"));
|
|
}),
|
|
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"));
|
|
}),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
Expanded(
|
|
child: LayoutBuilder(
|
|
builder: (context, constraints) {
|
|
return SingleChildScrollView(
|
|
physics: const BouncingScrollPhysics(),
|
|
child: ConstrainedBox(
|
|
constraints: BoxConstraints(minHeight: constraints.maxHeight),
|
|
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,
|
|
child: LocaleKeys.forgotPassword.tr().toText12(isUnderLine: true, color: MyColors.textMixColor).onPress(() {
|
|
performForgotPassword();
|
|
}),
|
|
),
|
|
20.height,
|
|
_buildDependentCtaCard(context),
|
|
] else ...[
|
|
InputWidget(LocaleKeys.nationalId.tr(), "1234567890", nationalId, isInputTypeNum: true),
|
|
12.height,
|
|
GestureDetector(
|
|
behavior: HitTestBehavior.opaque,
|
|
onTap: () => _selectDateOfBirth(context),
|
|
child: Stack(
|
|
alignment: AlignmentDirectional.centerEnd,
|
|
children: [
|
|
IgnorePointer(child: InputWidget(LocaleKeys.dateOfBirth.tr(), "DD-MM-YYYY", dobController)),
|
|
Positioned.directional(
|
|
textDirection: Directionality.of(context),
|
|
end: 16,
|
|
child: const Icon(Icons.calendar_today_outlined, size: 20, color: MyColors.grey70Color),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
20.height,
|
|
_buildEmployeeCtaCard(context),
|
|
],
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
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();
|
|
}
|
|
}
|