This commit is contained in:
sathwikcs
2025-01-30 18:18:42 +05:30
parent 6e2092a2b0
commit b49997889d

View File

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