marco.pms.mobileapp/lib/controller/auth/otp_controller.dart
Vaibhav Surve e6d05e247e Refactor logging implementation across controllers and services
- Replaced instances of the Logger package with a custom appLogger for consistent logging.
- Introduced app_logger.dart to manage logging with file output and storage permissions.
- Updated all controllers (e.g., DashboardController, EmployeesScreenController, etc.) to use appLogger for logging messages.
- Ensured that logging messages are appropriately categorized (info, warning, error) throughout the application.
- Implemented a file logging mechanism to store logs in a designated directory.
- Cleaned up old log files to maintain only the most recent logs.
2025-06-24 13:11:22 +05:30

198 lines
5.3 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:marco/helpers/widgets/my_snackbar.dart';
import 'package:marco/helpers/services/auth_service.dart';
import 'package:marco/helpers/services/storage/local_storage.dart';
import 'package:marco/helpers/services/app_logger.dart';
class OTPController extends GetxController {
final formKey = GlobalKey<FormState>();
final RxString email = ''.obs;
final RxBool isOTPSent = false.obs;
final RxBool isSending = false.obs;
final RxBool isResending = false.obs;
final RxInt timer = 0.obs;
Timer? _countdownTimer;
final TextEditingController emailController = TextEditingController();
final List<TextEditingController> otpControllers =
List.generate(4, (_) => TextEditingController());
final List<FocusNode> focusNodes = List.generate(4, (_) => FocusNode());
@override
void onInit() {
super.onInit();
timer.value = 0;
appLogger.i("[OTPController] Initialized");
}
@override
void onClose() {
_countdownTimer?.cancel();
emailController.dispose();
for (final controller in otpControllers) {
controller.dispose();
}
for (final node in focusNodes) {
node.dispose();
}
appLogger.i("[OTPController] Disposed");
super.onClose();
}
Future<bool> _sendOTP(String email) async {
appLogger.i("[OTPController] Sending OTP to $email");
final result = await AuthService.generateOtp(email);
if (result == null) {
appLogger.i("[OTPController] OTP sent successfully to $email");
return true;
} else {
appLogger.w("[OTPController] OTP send failed: ${result['error']}");
showAppSnackbar(
title: "Error",
message: result['error'] ?? "Failed to send OTP",
type: SnackbarType.error,
);
return false;
}
}
Future<void> sendOTP() async {
final userEmail = emailController.text.trim();
appLogger.i("[OTPController] sendOTP called for $userEmail");
if (!_validateEmail(userEmail)) {
appLogger.w("[OTPController] Invalid email format: $userEmail");
showAppSnackbar(
title: "Error",
message: "Please enter a valid email address",
type: SnackbarType.error,
);
return;
}
if (isSending.value) return;
isSending.value = true;
final success = await _sendOTP(userEmail);
if (success) {
email.value = userEmail;
isOTPSent.value = true;
_startTimer();
_clearOTPFields();
}
isSending.value = false;
}
Future<void> onResendOTP() async {
if (isResending.value) return;
appLogger.i("[OTPController] Resending OTP to ${email.value}");
isResending.value = true;
_clearOTPFields();
final success = await _sendOTP(email.value);
if (success) {
_startTimer();
}
isResending.value = false;
}
void onOTPChanged(String value, int index) {
appLogger.d("[OTPController] OTP field changed: index=$index, value=$value");
if (value.isNotEmpty) {
if (index < otpControllers.length - 1) {
focusNodes[index + 1].requestFocus();
} else {
focusNodes[index].unfocus();
}
} else {
if (index > 0) {
focusNodes[index - 1].requestFocus();
}
}
}
Future<void> verifyOTP() async {
final enteredOTP = otpControllers.map((c) => c.text).join();
appLogger.i("[OTPController] Verifying OTP: $enteredOTP for email: ${email.value}");
final result = await AuthService.verifyOtp(
email: email.value,
otp: enteredOTP,
);
if (result == null) {
appLogger.i("[OTPController] OTP verified successfully");
showAppSnackbar(
title: "Success",
message: "OTP verified successfully",
type: SnackbarType.success,
);
final bool isMpinEnabled = LocalStorage.getIsMpin();
appLogger.i("[OTPController] MPIN Enabled: $isMpinEnabled");
if (isMpinEnabled) {
Get.offAllNamed('/home');
} else {
Get.offAllNamed('/home');
}
} else {
final error = result['error'] ?? "Failed to verify OTP";
appLogger.w("[OTPController] OTP verification failed: $error");
showAppSnackbar(
title: "Error",
message: error,
type: SnackbarType.error,
);
}
}
void _clearOTPFields() {
appLogger.d("[OTPController] Clearing OTP input fields");
for (final controller in otpControllers) {
controller.clear();
}
focusNodes[0].requestFocus();
}
void _startTimer() {
appLogger.i("[OTPController] Starting resend timer");
timer.value = 60;
_countdownTimer?.cancel();
_countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (this.timer.value > 0) {
this.timer.value--;
} else {
timer.cancel();
}
});
}
void resetForChangeEmail() {
appLogger.i("[OTPController] Resetting OTP form for change email");
isOTPSent.value = false;
email.value = '';
emailController.clear();
_clearOTPFields();
timer.value = 0;
isSending.value = false;
isResending.value = false;
for (final node in focusNodes) {
node.unfocus();
}
}
bool _validateEmail(String email) {
final regex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,}$');
return regex.hasMatch(email);
}
}