diff --git a/app/src/main/java/in/sminnovations/attendanceapp/screens/home/viewModel/homeVM.kt b/app/src/main/java/in/sminnovations/attendanceapp/screens/home/viewModel/homeVM.kt index 7c1e54e..a51e000 100644 --- a/app/src/main/java/in/sminnovations/attendanceapp/screens/home/viewModel/homeVM.kt +++ b/app/src/main/java/in/sminnovations/attendanceapp/screens/home/viewModel/homeVM.kt @@ -2,6 +2,7 @@ package `in`.sminnovations.attendanceapp.screens.home.viewModel import android.content.Context +import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.asFlow import androidx.lifecycle.viewModelScope @@ -22,10 +23,14 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.tasks.await import java.text.SimpleDateFormat +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoUnit import java.util.Date import java.util.Locale import java.util.concurrent.TimeUnit import javax.inject.Inject +import kotlin.math.abs @HiltViewModel class HomeViewModel @Inject constructor( @@ -50,13 +55,13 @@ class HomeViewModel @Inject constructor( fun checkForUpdates(context: Context) { viewModelScope.launch { UpdateChecker.checkForUpdate(context).onSuccess { updateInfo -> - if (updateInfo.isNew) { - _updateInfo.value = updateInfo - _isUpdateDialogVisible.value = true - } - }.onFailure { _ -> - // Handle error + if (updateInfo.isNew) { + _updateInfo.value = updateInfo + _isUpdateDialogVisible.value = true } + }.onFailure { _ -> + // Handle error + } } } @@ -98,10 +103,10 @@ class HomeViewModel @Inject constructor( init { networkMonitor.startMonitoring() networkMonitor.isConnected.asFlow().onEach { isConnected -> - _uiState.update { currentState -> - currentState.copy(isConnected = isConnected) - } - }.launchIn(viewModelScope) + _uiState.update { currentState -> + currentState.copy(isConnected = isConnected) + } + }.launchIn(viewModelScope) if (uiState.value.isConnected) { viewModelScope.launch { startScanning() @@ -186,7 +191,13 @@ class HomeViewModel @Inject constructor( val attendanceDoc = getAttendanceDocument(userId, currentDate) if (attendanceDoc?.exists() == true) { - handleExistingAttendance(attendanceDoc) + val checkIn = attendanceDoc.getString("checkIn") + if (isTimeDifferenceGreaterThanMinutes(givenTimeStr = checkIn!!, minutes = 5L)) { + handleExistingAttendance(attendanceDoc) + }else{ + handleError("Wait 5 minutes before logging off") + } + } else { handleNewAttendance(userId, currentDate) } @@ -213,9 +224,7 @@ class HomeViewModel @Inject constructor( private suspend fun handleExistingAttendance(document: DocumentSnapshot) { val checkOut = document.getString("checkOut") - val checkIn = document.getString("checkIn") - if (isTimeDifferenceGreaterThanN(inputTime = checkIn!!,n=5)){ when { checkOut == "NA" -> processCheckOut(document) checkOut != null -> { @@ -225,10 +234,9 @@ class HomeViewModel @Inject constructor( ) } } + else -> handleError("Invalid attendance record") } - handleError("Wait 5 minutes before logging off") - } } @@ -254,21 +262,23 @@ class HomeViewModel @Inject constructor( } private suspend fun processCheckOut(document: DocumentSnapshot) { - try { - val checkOutData = hashMapOf( - "checkOut" to formatTimestamp(Timestamp.now()), "DayCompleted" to true - ) - document.reference.update(checkOutData as Map).await() - - _uiState.update { - it.copy( - isCheckedOut = true, qrCodeValue = null + try { + val checkOutData = hashMapOf( + "checkOut" to formatTimestamp(Timestamp.now()), "DayCompleted" to true ) + + document.reference.update(checkOutData as Map).await() + + _uiState.update { + it.copy( + isCheckedOut = true, qrCodeValue = null + ) + } + } catch (e: Exception) { + handleError("Failed to check out: ${e.message}") } - } catch (e: Exception) { - handleError("Failed to check out: ${e.message}") - } + } private suspend fun getEmployeeDocument(userId: String): DocumentSnapshot? { @@ -307,23 +317,6 @@ class HomeViewModel @Inject constructor( ).format(timestamp.toDate()) } - private fun isJustCheckedIn(checkInTime: String): Boolean { - var finalValue = false - val currentTime = SimpleDateFormat("dd MMMM yyyy hh:mm:ss a", Locale.getDefault()).format(Timestamp.now().toDate()).toList() - val checkInTimeList = checkInTime.toList() - for (i in checkInTimeList.indices){ - for (j in currentTime.indices){ - val a = checkInTimeList[i].digitToInt() - val b = currentTime[j].digitToInt() - println(a) - if (a>= b){ - !finalValue - } - } - } - return true - - } // fun isAppDisabled(): Boolean { // val a = firebaseFirestore.collection("deviceState").document("state") @@ -331,22 +324,20 @@ class HomeViewModel @Inject constructor( // return true // } - fun isTimeDifferenceGreaterThanN(inputTime: String, n: Int): Boolean { - val dateFormat = SimpleDateFormat("dd MMMM yyyy hh:mm:ss a", Locale.ENGLISH) - val givenDate: Date? = dateFormat.parse(inputTime) + fun isTimeDifferenceGreaterThanMinutes(givenTimeStr: String, currentTimeStr: String = formatTimestamp(Timestamp.now()), minutes: Long): Boolean { + val formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy hh:mm:ss a") - if (givenDate == null) { - println("Invalid date format") - return false - } + val givenTime = LocalDateTime.parse(givenTimeStr, formatter) + val currentTime = LocalDateTime.parse(currentTimeStr, formatter) - val currentDate = Date() - val timeDifferenceMillis = givenDate.time - currentDate.time - val timeDifferenceMinutes = TimeUnit.MILLISECONDS.toMinutes(timeDifferenceMillis) + val timeDifference = abs(ChronoUnit.MINUTES.between(givenTime, currentTime)) - return timeDifferenceMinutes > n + return timeDifference > minutes } + + + override fun onCleared() { super.onCleared() networkMonitor.stopMonitoring()