Compare commits
5 Commits
fe3669a6a7
...
333f098045
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
333f098045 | ||
|
|
dc269dcec2 | ||
|
|
a8d1ea9f4b | ||
|
|
cd17f02e21 | ||
|
|
a7c2ed4abc |
@@ -7,10 +7,11 @@ import androidx.room.RoomDatabase
|
|||||||
import com.example.data.model.MaintenanceActivity
|
import com.example.data.model.MaintenanceActivity
|
||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
import com.example.data.model.SyncConflictLog
|
import com.example.data.model.SyncConflictLog
|
||||||
|
import com.example.data.model.UserAccess
|
||||||
|
|
||||||
@Database(
|
@Database(
|
||||||
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class],
|
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class],
|
||||||
version = 4,
|
version = 5,
|
||||||
exportSchema = false
|
exportSchema = false
|
||||||
)
|
)
|
||||||
abstract class AppDatabase : RoomDatabase() {
|
abstract class AppDatabase : RoomDatabase() {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import androidx.room.Update
|
|||||||
import com.example.data.model.MaintenanceActivity
|
import com.example.data.model.MaintenanceActivity
|
||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
import com.example.data.model.SyncConflictLog
|
import com.example.data.model.SyncConflictLog
|
||||||
|
import com.example.data.model.UserAccess
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
@Dao
|
@Dao
|
||||||
@@ -62,4 +63,13 @@ interface MaintenanceDao {
|
|||||||
|
|
||||||
@Query("DELETE FROM sync_conflict_logs")
|
@Query("DELETE FROM sync_conflict_logs")
|
||||||
suspend fun clearAllConflictLogs()
|
suspend fun clearAllConflictLogs()
|
||||||
|
|
||||||
|
@Query("SELECT * FROM user_access WHERE email = :email LIMIT 1")
|
||||||
|
suspend fun getUserAccess(email: String): UserAccess?
|
||||||
|
|
||||||
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
|
suspend fun insertUserAccessList(accessList: List<UserAccess>)
|
||||||
|
|
||||||
|
@Query("DELETE FROM user_access")
|
||||||
|
suspend fun clearUserAccess()
|
||||||
}
|
}
|
||||||
|
|||||||
13
app/src/main/java/com/example/data/model/AnalyticsState.kt
Normal file
13
app/src/main/java/com/example/data/model/AnalyticsState.kt
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
package com.example.data.model
|
||||||
|
|
||||||
|
import java.util.Date
|
||||||
|
|
||||||
|
data class AnalyticsState(
|
||||||
|
val teamMetrics: List<Pair<String, Int>> = emptyList(),
|
||||||
|
val projectStart: Date = Date(),
|
||||||
|
val projectEnd: Date = Date(),
|
||||||
|
val timelineDates: List<Date> = emptyList(),
|
||||||
|
val plannedProgressPoints: List<Float> = emptyList(),
|
||||||
|
val realizedProgressPoints: List<Float> = emptyList(),
|
||||||
|
val overdueByTag: List<Pair<String, Int>> = emptyList()
|
||||||
|
)
|
||||||
@@ -90,7 +90,7 @@ fun adjustTwoDigitYear(date: Date?): Date? {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun parseDateOnly(dateStr: String): Date? {
|
fun parseDateOnly(dateStr: String): Date? {
|
||||||
val clean = dateStr.trim()
|
val clean = extractDateOnly(dateStr).trim()
|
||||||
val formats = listOf(
|
val formats = listOf(
|
||||||
"dd/MM/yyyy",
|
"dd/MM/yyyy",
|
||||||
"dd/MM/yy",
|
"dd/MM/yy",
|
||||||
|
|||||||
10
app/src/main/java/com/example/data/model/UserAccess.kt
Normal file
10
app/src/main/java/com/example/data/model/UserAccess.kt
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package com.example.data.model
|
||||||
|
|
||||||
|
import androidx.room.Entity
|
||||||
|
import androidx.room.PrimaryKey
|
||||||
|
|
||||||
|
@Entity(tableName = "user_access")
|
||||||
|
data class UserAccess(
|
||||||
|
@PrimaryKey val email: String,
|
||||||
|
val nivelAcesso: String
|
||||||
|
)
|
||||||
@@ -4,6 +4,7 @@ import android.content.Context
|
|||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.example.data.model.MaintenanceActivity
|
import com.example.data.model.MaintenanceActivity
|
||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
|
import com.example.data.model.UserAccess
|
||||||
import com.squareup.moshi.JsonClass
|
import com.squareup.moshi.JsonClass
|
||||||
import com.squareup.moshi.Moshi
|
import com.squareup.moshi.Moshi
|
||||||
import com.google.auth.oauth2.GoogleCredentials
|
import com.google.auth.oauth2.GoogleCredentials
|
||||||
@@ -807,4 +808,33 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
appendValues("history!A:I", appendRows)
|
appendValues("history!A:I", appendRows)
|
||||||
Log.d(tag, "Successfully appended ${historyToAppend.size} logs to 'history' sheet.")
|
Log.d(tag, "Successfully appended ${historyToAppend.size} logs to 'history' sheet.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun fetchUserAccessList(): List<UserAccess> {
|
||||||
|
val rows = fetchValues("acesso!A:Z")
|
||||||
|
val accessList = mutableListOf<UserAccess>()
|
||||||
|
if (rows.size <= 1) return accessList
|
||||||
|
|
||||||
|
val headers = rows[0].map { it.trim().lowercase() }
|
||||||
|
val emailIdx = headers.indexOfFirst { it == "email" || it == "e-mail" || it.contains("email") }
|
||||||
|
val nivelIdx = headers.indexOfFirst { it == "nivel_acesso" || it == "nivel" || it.contains("nivel") || it.contains("nível") }
|
||||||
|
|
||||||
|
if (emailIdx == -1 || nivelIdx == -1) {
|
||||||
|
Log.e(tag, "Colunas de email ou nivel_acesso não encontradas na aba acesso. Headers: $headers")
|
||||||
|
return accessList
|
||||||
|
}
|
||||||
|
|
||||||
|
val getCell = { row: List<String>, idx: Int ->
|
||||||
|
if (idx >= 0 && idx < row.size) row[idx].trim() else ""
|
||||||
|
}
|
||||||
|
|
||||||
|
for (i in 1 until rows.size) {
|
||||||
|
val row = rows[i]
|
||||||
|
val email = getCell(row, emailIdx)
|
||||||
|
val nivel = getCell(row, nivelIdx)
|
||||||
|
if (email.isNotBlank()) {
|
||||||
|
accessList.add(UserAccess(email = email, nivelAcesso = nivel))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return accessList
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import com.example.data.model.MaintenanceActivity
|
|||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
import com.example.data.model.GoogleUser
|
import com.example.data.model.GoogleUser
|
||||||
import com.example.data.model.SyncConflictLog
|
import com.example.data.model.SyncConflictLog
|
||||||
|
import com.example.data.model.UserAccess
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
@@ -29,6 +30,10 @@ class MaintenanceRepository(
|
|||||||
|
|
||||||
fun getHistoryForOs(numeroOs: String): Flow<List<OSUpdateHistory>> = dao.getHistoryForOs(numeroOs)
|
fun getHistoryForOs(numeroOs: String): Flow<List<OSUpdateHistory>> = dao.getHistoryForOs(numeroOs)
|
||||||
|
|
||||||
|
suspend fun getUserAccess(email: String): UserAccess? = withContext(Dispatchers.IO) {
|
||||||
|
dao.getUserAccess(email)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates progress of an OS, auto-generates a history record, and marks as unsynced (offline-first).
|
* Updates progress of an OS, auto-generates a history record, and marks as unsynced (offline-first).
|
||||||
*/
|
*/
|
||||||
@@ -191,6 +196,18 @@ class MaintenanceRepository(
|
|||||||
try {
|
try {
|
||||||
android.util.Log.d("MaintenanceRepository", "Starting Google Sheets synchronization...")
|
android.util.Log.d("MaintenanceRepository", "Starting Google Sheets synchronization...")
|
||||||
|
|
||||||
|
// 0. Fetch user access list and store locally
|
||||||
|
try {
|
||||||
|
val remoteAccessList = sheetsSyncService.fetchUserAccessList()
|
||||||
|
dao.clearUserAccess()
|
||||||
|
if (remoteAccessList.isNotEmpty()) {
|
||||||
|
dao.insertUserAccessList(remoteAccessList)
|
||||||
|
android.util.Log.d("MaintenanceRepository", "Sincronizadas ${remoteAccessList.size} permissões de acesso.")
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("MaintenanceRepository", "Falha ao carregar lista de acessos da planilha", e)
|
||||||
|
}
|
||||||
|
|
||||||
// 1. Fetch remote OS definitions from the "project" sheet
|
// 1. Fetch remote OS definitions from the "project" sheet
|
||||||
val (remoteActivities, _) = sheetsSyncService.fetchRemoteActivities()
|
val (remoteActivities, _) = sheetsSyncService.fetchRemoteActivities()
|
||||||
|
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import com.example.data.model.ActivityStatus
|
|||||||
import com.example.data.model.MaintenanceActivity
|
import com.example.data.model.MaintenanceActivity
|
||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
import com.example.data.model.parseDateOnly
|
import com.example.data.model.parseDateOnly
|
||||||
|
import com.example.data.model.AnalyticsState
|
||||||
import com.example.ui.theme.CargillBlack
|
import com.example.ui.theme.CargillBlack
|
||||||
import com.example.ui.theme.CargillGreen
|
import com.example.ui.theme.CargillGreen
|
||||||
import com.example.ui.theme.LightGrey
|
import com.example.ui.theme.LightGrey
|
||||||
@@ -47,7 +48,7 @@ fun AnalyticsScreen(
|
|||||||
modifier: Modifier = Modifier
|
modifier: Modifier = Modifier
|
||||||
) {
|
) {
|
||||||
val activities by viewModel.allActivitiesState.collectAsStateWithLifecycle()
|
val activities by viewModel.allActivitiesState.collectAsStateWithLifecycle()
|
||||||
val historyLogs by viewModel.allHistoryState.collectAsStateWithLifecycle()
|
val analyticsState by viewModel.analyticsState.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = {
|
||||||
@@ -112,13 +113,13 @@ fun AnalyticsScreen(
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Card 1: Produtividade da Equipe
|
// Card 1: Produtividade da Equipe
|
||||||
TeamProductivityCard(activities)
|
TeamProductivityCard(analyticsState.teamMetrics)
|
||||||
|
|
||||||
// Card 2: Progresso do Projeto: Planejado vs. Realizado
|
// Card 2: Progresso do Projeto: Planejado vs. Realizado
|
||||||
SCurveCard(activities, historyLogs)
|
SCurveCard(analyticsState)
|
||||||
|
|
||||||
// Card 3: Atrasados por TAG
|
// Card 3: Atrasados por TAG
|
||||||
OverdueByTagCard(activities)
|
OverdueByTagCard(analyticsState.overdueByTag)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -129,7 +130,7 @@ fun AnalyticsScreen(
|
|||||||
* Exibe a razão de OS concluídas sobre o total de OS por equipe
|
* Exibe a razão de OS concluídas sobre o total de OS por equipe
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun TeamProductivityCard(activities: List<MaintenanceActivity>) {
|
fun TeamProductivityCard(teamMetrics: List<Pair<String, Int>>) {
|
||||||
Card(
|
Card(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
colors = CardDefaults.cardColors(containerColor = Color.White),
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
@@ -150,16 +151,6 @@ fun TeamProductivityCard(activities: List<MaintenanceActivity>) {
|
|||||||
modifier = Modifier.padding(bottom = 16.dp)
|
modifier = Modifier.padding(bottom = 16.dp)
|
||||||
)
|
)
|
||||||
|
|
||||||
// Group by team and calculate productivity
|
|
||||||
val teams = listOf("Mecânica", "Elétrica", "Confiabilidade", "Lubrificação")
|
|
||||||
val teamMetrics = teams.map { team ->
|
|
||||||
val teamActivities = activities.filter { it.equipe.equals(team, ignoreCase = true) }
|
|
||||||
val total = teamActivities.size
|
|
||||||
val completed = teamActivities.count { it.percentualExecucao >= 100 }
|
|
||||||
val ratio = if (total > 0) (completed.toFloat() / total.toFloat() * 100f).toInt() else 0
|
|
||||||
team to ratio
|
|
||||||
}
|
|
||||||
|
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
@@ -214,7 +205,7 @@ fun TeamProductivityCard(activities: List<MaintenanceActivity>) {
|
|||||||
* Compara o avanço temporal Planejado com o Realizado
|
* Compara o avanço temporal Planejado com o Realizado
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun SCurveCard(activities: List<MaintenanceActivity>, history: List<OSUpdateHistory>) {
|
fun SCurveCard(analyticsState: AnalyticsState) {
|
||||||
Card(
|
Card(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
colors = CardDefaults.cardColors(containerColor = Color.White),
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
@@ -237,62 +228,12 @@ fun SCurveCard(activities: List<MaintenanceActivity>, history: List<OSUpdateHist
|
|||||||
.padding(bottom = 12.dp)
|
.padding(bottom = 12.dp)
|
||||||
)
|
)
|
||||||
|
|
||||||
// Calculate start and end bounds of the project
|
val timelineDates = analyticsState.timelineDates
|
||||||
val parsedDates = activities.flatMap {
|
val plannedProgressPoints = analyticsState.plannedProgressPoints
|
||||||
listOfNotNull(parseDateOnly(it.dataInicio), parseDateOnly(it.dataFim))
|
val realizedProgressPoints = analyticsState.realizedProgressPoints
|
||||||
}
|
val timelineSteps = timelineDates.size
|
||||||
|
|
||||||
val projectStart = parsedDates.minOrNull() ?: Calendar.getInstance().apply { set(2026, Calendar.AUGUST, 1) }.time
|
if (timelineSteps > 0 && plannedProgressPoints.isNotEmpty() && realizedProgressPoints.isNotEmpty()) {
|
||||||
val projectEnd = parsedDates.maxOrNull() ?: Calendar.getInstance().apply { set(2026, Calendar.AUGUST, 29) }.time
|
|
||||||
|
|
||||||
// Generate timeline dates (e.g., 5 key check-points: start, 25%, 50%, 75%, end)
|
|
||||||
val durationMs = projectEnd.time - projectStart.time
|
|
||||||
val timelineSteps = 5
|
|
||||||
val timelineDates = (0 until timelineSteps).map { i ->
|
|
||||||
Date(projectStart.time + (durationMs * i / (timelineSteps - 1)))
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1. Calculate Planned progress points
|
|
||||||
val plannedProgressPoints = timelineDates.map { date ->
|
|
||||||
val dayTime = date.time
|
|
||||||
val totalActivities = activities.size
|
|
||||||
if (totalActivities == 0) 0f
|
|
||||||
else {
|
|
||||||
val sum = activities.sumOf { act ->
|
|
||||||
val start = parseDateOnly(act.dataInicio)?.time ?: dayTime
|
|
||||||
val end = parseDateOnly(act.dataFim)?.time ?: dayTime
|
|
||||||
when {
|
|
||||||
dayTime <= start -> 0
|
|
||||||
dayTime >= end -> 100
|
|
||||||
else -> {
|
|
||||||
val progress = ((dayTime - start).toDouble() / (end - start).toDouble() * 100.0).toInt()
|
|
||||||
progress.coerceIn(0, 100)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sum.toFloat() / totalActivities.toFloat()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Calculate Realized progress points
|
|
||||||
val realizedProgressPoints = timelineDates.map { date ->
|
|
||||||
val dayTime = date.time
|
|
||||||
val totalActivities = activities.size
|
|
||||||
if (totalActivities == 0) 0f
|
|
||||||
else {
|
|
||||||
val sum = activities.sumOf { act ->
|
|
||||||
val osLogs = history.filter { it.numeroOs == act.numeroOs && it.timestamp <= dayTime }
|
|
||||||
if (osLogs.isNotEmpty()) {
|
|
||||||
osLogs.last().percentualNovo
|
|
||||||
} else {
|
|
||||||
if (act.lastUpdated <= dayTime) act.percentualExecucao else 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sum.toFloat() / totalActivities.toFloat()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Let's draw the S-Curve Canvas
|
|
||||||
Canvas(
|
Canvas(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
@@ -383,7 +324,7 @@ fun SCurveCard(activities: List<MaintenanceActivity>, history: List<OSUpdateHist
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
} // Close Canvas
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
@@ -413,6 +354,7 @@ fun SCurveCard(activities: List<MaintenanceActivity>, history: List<OSUpdateHist
|
|||||||
Spacer(modifier = Modifier.width(6.dp))
|
Spacer(modifier = Modifier.width(6.dp))
|
||||||
Text(text = "Realizado", fontSize = 12.sp, color = Color.Gray)
|
Text(text = "Realizado", fontSize = 12.sp, color = Color.Gray)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -422,7 +364,7 @@ fun SCurveCard(activities: List<MaintenanceActivity>, history: List<OSUpdateHist
|
|||||||
* Lista as TAGs com maior volume de OSs pendentes e com prazo vencido
|
* Lista as TAGs com maior volume de OSs pendentes e com prazo vencido
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun OverdueByTagCard(activities: List<MaintenanceActivity>) {
|
fun OverdueByTagCard(overdueByTag: List<Pair<String, Int>>) {
|
||||||
Card(
|
Card(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
colors = CardDefaults.cardColors(containerColor = Color.White),
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
@@ -445,18 +387,7 @@ fun OverdueByTagCard(activities: List<MaintenanceActivity>) {
|
|||||||
.padding(bottom = 16.dp)
|
.padding(bottom = 16.dp)
|
||||||
)
|
)
|
||||||
|
|
||||||
// Determine reference date to decide what is overdue.
|
if (overdueByTag.isEmpty()) {
|
||||||
val projectEndDate = activities.mapNotNull { parseDateOnly(it.dataFim) }.maxOrNull() ?: Date()
|
|
||||||
val referenceDate = if (Date().before(projectEndDate)) projectEndDate else Date()
|
|
||||||
|
|
||||||
// Filter overdue activities
|
|
||||||
val overdueActivities = activities.filter { act ->
|
|
||||||
val isNotCompleted = act.percentualExecucao < 100
|
|
||||||
val endDate = parseDateOnly(act.dataFim)
|
|
||||||
isNotCompleted && endDate != null && endDate.before(referenceDate)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (overdueActivities.isEmpty()) {
|
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
@@ -471,23 +402,7 @@ fun OverdueByTagCard(activities: List<MaintenanceActivity>) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Group by TAG and count
|
val displayList = overdueByTag
|
||||||
val overdueByTag = overdueActivities
|
|
||||||
.groupBy { if (it.tag.isBlank()) "Sem TAG" else it.tag }
|
|
||||||
.mapValues { it.value.size }
|
|
||||||
.toList()
|
|
||||||
.sortedByDescending { it.second }
|
|
||||||
|
|
||||||
// Top 4 tags, combine others into "Outros"
|
|
||||||
val displayLimit = 4
|
|
||||||
val displayList = if (overdueByTag.size <= displayLimit) {
|
|
||||||
overdueByTag
|
|
||||||
} else {
|
|
||||||
val top = overdueByTag.take(displayLimit - 1)
|
|
||||||
val othersCount = overdueByTag.drop(displayLimit - 1).sumOf { it.second }
|
|
||||||
top + listOf("Outros" to othersCount)
|
|
||||||
}
|
|
||||||
|
|
||||||
val maxCount = displayList.maxOfOrNull { it.second } ?: 1
|
val maxCount = displayList.maxOfOrNull { it.second } ?: 1
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ fun MaintenanceDashboardScreen(
|
|||||||
val selectedDataInicio by viewModel.selectedDataInicio.collectAsStateWithLifecycle()
|
val selectedDataInicio by viewModel.selectedDataInicio.collectAsStateWithLifecycle()
|
||||||
val selectedRecurso by viewModel.selectedRecurso.collectAsStateWithLifecycle()
|
val selectedRecurso by viewModel.selectedRecurso.collectAsStateWithLifecycle()
|
||||||
val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()
|
val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()
|
||||||
|
val selectedQuickFilter by viewModel.selectedQuickFilter.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
|
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
|
||||||
val syncMessage by viewModel.syncStatusMessage.collectAsStateWithLifecycle()
|
val syncMessage by viewModel.syncStatusMessage.collectAsStateWithLifecycle()
|
||||||
@@ -86,11 +87,30 @@ fun MaintenanceDashboardScreen(
|
|||||||
val selectedActivity by viewModel.selectedActivity.collectAsStateWithLifecycle()
|
val selectedActivity by viewModel.selectedActivity.collectAsStateWithLifecycle()
|
||||||
val selectedActivityHistory by viewModel.selectedActivityHistory.collectAsStateWithLifecycle()
|
val selectedActivityHistory by viewModel.selectedActivityHistory.collectAsStateWithLifecycle()
|
||||||
val currentUser by viewModel.currentUser.collectAsStateWithLifecycle()
|
val currentUser by viewModel.currentUser.collectAsStateWithLifecycle()
|
||||||
|
val userAccessLevel by viewModel.userAccessLevel.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
var showEditSheet by remember { mutableStateOf(false) }
|
var showEditSheet by remember { mutableStateOf(false) }
|
||||||
var showImporterSheet by remember { mutableStateOf(false) }
|
var showImporterSheet by remember { mutableStateOf(false) }
|
||||||
var isListExpanded by remember { mutableStateOf(false) }
|
var isListExpanded by remember { mutableStateOf(false) }
|
||||||
var showProfileDropdown by remember { mutableStateOf(false) }
|
var showProfileDropdown by remember { mutableStateOf(false) }
|
||||||
|
var showAdvancedFilters by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
val pendingCount = remember(allActivities) {
|
||||||
|
allActivities.count { it.status != ActivityStatus.CONCLUIDO }
|
||||||
|
}
|
||||||
|
|
||||||
|
val quickFilters = remember(pendingCount) {
|
||||||
|
listOf(
|
||||||
|
"Todos" to "Todos",
|
||||||
|
"Pendentes $pendingCount" to "Pendentes",
|
||||||
|
"Hoje" to "Hoje",
|
||||||
|
"Em andamento" to "Em andamento",
|
||||||
|
"Não iniciado" to "Não iniciado",
|
||||||
|
"Mecânica" to "Mecânica",
|
||||||
|
"Elétrica" to "Elétrica",
|
||||||
|
"Confiabilidade" to "Confiabilidade"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
val gso = remember {
|
val gso = remember {
|
||||||
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
||||||
@@ -365,12 +385,7 @@ fun MaintenanceDashboardScreen(
|
|||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(innerPadding)
|
.padding(innerPadding)
|
||||||
) {
|
) {
|
||||||
// Summary Dashboard Metrics Block
|
// Search Bar & Filter Toggle Button
|
||||||
AnimatedVisibility(visible = !isListExpanded) {
|
|
||||||
DashboardMetrics(activities = allActivities)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Search Bar & Filter Button
|
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
@@ -404,24 +419,57 @@ fun MaintenanceDashboardScreen(
|
|||||||
),
|
),
|
||||||
singleLine = true
|
singleLine = true
|
||||||
)
|
)
|
||||||
|
|
||||||
|
IconButton(
|
||||||
|
onClick = { showAdvancedFilters = !showAdvancedFilters },
|
||||||
|
modifier = Modifier
|
||||||
|
.size(52.dp)
|
||||||
|
.clip(RoundedCornerShape(12.dp))
|
||||||
|
.background(if (showAdvancedFilters) CargillGreen else Color.White)
|
||||||
|
.testTag("toggle_filters_button")
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Tune,
|
||||||
|
contentDescription = "Filtros avançados",
|
||||||
|
tint = if (showAdvancedFilters) Color.White else CargillBlack
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Horizontally Scrollable Filters
|
// Horizontally Scrollable Quick Filters
|
||||||
FilterPillsRow(
|
LazyRow(
|
||||||
selectedSetor = selectedSetor,
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
selectedEquipe = selectedEquipe,
|
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 4.dp),
|
||||||
selectedStatus = selectedStatus,
|
modifier = Modifier.fillMaxWidth().testTag("quick_filters_row")
|
||||||
selectedDataInicio = selectedDataInicio,
|
) {
|
||||||
selectedRecurso = selectedRecurso,
|
items(quickFilters) { (label, value) ->
|
||||||
uniqueSectors = uniqueSectors,
|
val isSelected = selectedQuickFilter == value
|
||||||
uniqueDates = uniqueDates,
|
FilterChipWidget(
|
||||||
uniqueRecursos = uniqueRecursos,
|
text = label,
|
||||||
onSetorSelected = { viewModel.setFilterSetor(it) },
|
isSelected = isSelected,
|
||||||
onEquipeSelected = { viewModel.setFilterEquipe(it) },
|
onClick = { viewModel.setSelectedQuickFilter(value) }
|
||||||
onStatusSelected = { viewModel.setFilterStatus(it) },
|
)
|
||||||
onDataInicioSelected = { viewModel.setFilterDataInicio(it) },
|
}
|
||||||
onRecursoSelected = { viewModel.setFilterRecurso(it) }
|
}
|
||||||
)
|
|
||||||
|
// Horizontally Scrollable Advanced Filters (shown conditionally)
|
||||||
|
AnimatedVisibility(visible = showAdvancedFilters) {
|
||||||
|
FilterPillsRow(
|
||||||
|
selectedSetor = selectedSetor,
|
||||||
|
selectedEquipe = selectedEquipe,
|
||||||
|
selectedStatus = selectedStatus,
|
||||||
|
selectedDataInicio = selectedDataInicio,
|
||||||
|
selectedRecurso = selectedRecurso,
|
||||||
|
uniqueSectors = uniqueSectors,
|
||||||
|
uniqueDates = uniqueDates,
|
||||||
|
uniqueRecursos = uniqueRecursos,
|
||||||
|
onSetorSelected = { viewModel.setFilterSetor(it) },
|
||||||
|
onEquipeSelected = { viewModel.setFilterEquipe(it) },
|
||||||
|
onStatusSelected = { viewModel.setFilterStatus(it) },
|
||||||
|
onDataInicioSelected = { viewModel.setFilterDataInicio(it) },
|
||||||
|
onRecursoSelected = { viewModel.setFilterRecurso(it) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// List Title and Item Count
|
// List Title and Item Count
|
||||||
Row(
|
Row(
|
||||||
@@ -527,6 +575,7 @@ fun MaintenanceDashboardScreen(
|
|||||||
activity = selectedActivity!!,
|
activity = selectedActivity!!,
|
||||||
history = selectedActivityHistory,
|
history = selectedActivityHistory,
|
||||||
currentUser = currentUser,
|
currentUser = currentUser,
|
||||||
|
userAccessLevel = userAccessLevel,
|
||||||
onDismiss = {
|
onDismiss = {
|
||||||
showEditSheet = false
|
showEditSheet = false
|
||||||
viewModel.selectActivity(null)
|
viewModel.selectActivity(null)
|
||||||
@@ -1016,6 +1065,7 @@ fun EditActivityBottomSheet(
|
|||||||
activity: MaintenanceActivity,
|
activity: MaintenanceActivity,
|
||||||
history: List<OSUpdateHistory>,
|
history: List<OSUpdateHistory>,
|
||||||
currentUser: com.example.data.model.GoogleUser?,
|
currentUser: com.example.data.model.GoogleUser?,
|
||||||
|
userAccessLevel: String?,
|
||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onUpdateProgress: (Int, String, String?) -> Unit,
|
onUpdateProgress: (Int, String, String?) -> Unit,
|
||||||
onGoogleLoginClick: () -> Unit
|
onGoogleLoginClick: () -> Unit
|
||||||
@@ -1316,22 +1366,76 @@ fun EditActivityBottomSheet(
|
|||||||
Text("Conectar com o Google", fontWeight = FontWeight.Bold, color = Color.White)
|
Text("Conectar com o Google", fontWeight = FontWeight.Bold, color = Color.White)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Button(
|
val hasEditAccess = userAccessLevel?.trim()?.lowercase().let { it == "total" || it == "editor" }
|
||||||
onClick = {
|
if (!hasEditAccess) {
|
||||||
isSubmitting = true
|
Card(
|
||||||
onUpdateProgress(progressValue.toInt(), observationText, selectedMockPhotoPath)
|
colors = CardDefaults.cardColors(containerColor = Color(0xFFFCE8E6)),
|
||||||
onDismiss()
|
border = BorderStroke(1.dp, Color(0xFFFAD2CF)),
|
||||||
},
|
shape = RoundedCornerShape(8.dp),
|
||||||
modifier = Modifier
|
modifier = Modifier.fillMaxWidth()
|
||||||
.fillMaxWidth()
|
) {
|
||||||
.height(48.dp)
|
Row(
|
||||||
.testTag("save_progress_button"),
|
modifier = Modifier.padding(12.dp),
|
||||||
colors = ButtonDefaults.buttonColors(containerColor = CargillGreen),
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
shape = RoundedCornerShape(10.dp)
|
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||||
) {
|
) {
|
||||||
Icon(Icons.Default.Save, contentDescription = "Salvar")
|
Icon(
|
||||||
Spacer(modifier = Modifier.width(6.dp))
|
imageVector = Icons.Default.Lock,
|
||||||
Text("Salvar Atualizações (Salva Local Offline)", fontWeight = FontWeight.Black)
|
contentDescription = "Acesso Restrito",
|
||||||
|
tint = Color(0xFFC5221F),
|
||||||
|
modifier = Modifier.size(24.dp)
|
||||||
|
)
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = "Acesso Restrito",
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
fontSize = 13.sp,
|
||||||
|
color = Color(0xFFC5221F)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Seu nível de acesso (${userAccessLevel ?: "nenhum"}) não possui permissão para editar OS.",
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = Color(0xFFC5221F)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = {},
|
||||||
|
enabled = false,
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(48.dp)
|
||||||
|
.testTag("save_progress_button_disabled"),
|
||||||
|
colors = ButtonDefaults.buttonColors(
|
||||||
|
containerColor = Color.Gray,
|
||||||
|
disabledContainerColor = Color.LightGray
|
||||||
|
),
|
||||||
|
shape = RoundedCornerShape(10.dp)
|
||||||
|
) {
|
||||||
|
Icon(Icons.Default.Save, contentDescription = "Salvar", tint = Color.DarkGray)
|
||||||
|
Spacer(modifier = Modifier.width(6.dp))
|
||||||
|
Text("Salvar Atualizações (Acesso Negado)", fontWeight = FontWeight.Black, color = Color.DarkGray)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
isSubmitting = true
|
||||||
|
onUpdateProgress(progressValue.toInt(), observationText, selectedMockPhotoPath)
|
||||||
|
onDismiss()
|
||||||
|
},
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(48.dp)
|
||||||
|
.testTag("save_progress_button"),
|
||||||
|
colors = ButtonDefaults.buttonColors(containerColor = CargillGreen),
|
||||||
|
shape = RoundedCornerShape(10.dp)
|
||||||
|
) {
|
||||||
|
Icon(Icons.Default.Save, contentDescription = "Salvar")
|
||||||
|
Spacer(modifier = Modifier.width(6.dp))
|
||||||
|
Text("Salvar Atualizações (Salva Local Offline)", fontWeight = FontWeight.Black)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,8 +12,14 @@ import com.example.data.model.SyncConflictLog
|
|||||||
import com.example.data.model.extractDateOnly
|
import com.example.data.model.extractDateOnly
|
||||||
import com.example.data.model.formatToShortDate
|
import com.example.data.model.formatToShortDate
|
||||||
import com.example.data.model.parseFullDateTime
|
import com.example.data.model.parseFullDateTime
|
||||||
|
import com.example.data.model.AnalyticsState
|
||||||
|
import com.example.data.model.parseDateOnly
|
||||||
import com.example.data.repository.MaintenanceRepository
|
import com.example.data.repository.MaintenanceRepository
|
||||||
import com.example.data.repository.SyncResult
|
import com.example.data.repository.SyncResult
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.flowOn
|
||||||
|
import java.util.Calendar
|
||||||
|
import java.util.Date
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
@@ -46,10 +52,16 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
private val _searchQuery = MutableStateFlow("")
|
private val _searchQuery = MutableStateFlow("")
|
||||||
val searchQuery = _searchQuery.asStateFlow()
|
val searchQuery = _searchQuery.asStateFlow()
|
||||||
|
|
||||||
|
private val _selectedQuickFilter = MutableStateFlow("Todos")
|
||||||
|
val selectedQuickFilter = _selectedQuickFilter.asStateFlow()
|
||||||
|
|
||||||
// Google User authentication state
|
// Google User authentication state
|
||||||
private val _currentUser = MutableStateFlow<com.example.data.model.GoogleUser?>(null)
|
private val _currentUser = MutableStateFlow<com.example.data.model.GoogleUser?>(null)
|
||||||
val currentUser = _currentUser.asStateFlow()
|
val currentUser = _currentUser.asStateFlow()
|
||||||
|
|
||||||
|
private val _userAccessLevel = MutableStateFlow<String?>(null)
|
||||||
|
val userAccessLevel = _userAccessLevel.asStateFlow()
|
||||||
|
|
||||||
// UI Operation States
|
// UI Operation States
|
||||||
private val _isSyncing = MutableStateFlow(false)
|
private val _isSyncing = MutableStateFlow(false)
|
||||||
val isSyncing = _isSyncing.asStateFlow()
|
val isSyncing = _isSyncing.asStateFlow()
|
||||||
@@ -84,6 +96,19 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
initialValue = emptyList()
|
initialValue = emptyList()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
val analyticsState: StateFlow<AnalyticsState> = combine(
|
||||||
|
repository.allActivities,
|
||||||
|
repository.allHistory
|
||||||
|
) { activities, history ->
|
||||||
|
calculateAnalytics(activities, history)
|
||||||
|
}
|
||||||
|
.flowOn(Dispatchers.Default)
|
||||||
|
.stateIn(
|
||||||
|
scope = viewModelScope,
|
||||||
|
started = SharingStarted.WhileSubscribed(5000),
|
||||||
|
initialValue = AnalyticsState()
|
||||||
|
)
|
||||||
|
|
||||||
// Filtered activities list
|
// Filtered activities list
|
||||||
val filteredActivities: StateFlow<List<MaintenanceActivity>> = combine(
|
val filteredActivities: StateFlow<List<MaintenanceActivity>> = combine(
|
||||||
repository.allActivities,
|
repository.allActivities,
|
||||||
@@ -92,7 +117,8 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
_selectedStatus,
|
_selectedStatus,
|
||||||
_selectedDataInicio,
|
_selectedDataInicio,
|
||||||
_selectedRecurso,
|
_selectedRecurso,
|
||||||
_searchQuery
|
_searchQuery,
|
||||||
|
_selectedQuickFilter
|
||||||
) { flowsArray ->
|
) { flowsArray ->
|
||||||
@Suppress("UNCHECKED_CAST")
|
@Suppress("UNCHECKED_CAST")
|
||||||
val activities = flowsArray[0] as List<MaintenanceActivity>
|
val activities = flowsArray[0] as List<MaintenanceActivity>
|
||||||
@@ -102,6 +128,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
val dataInicio = flowsArray[4] as String
|
val dataInicio = flowsArray[4] as String
|
||||||
val recurso = flowsArray[5] as String
|
val recurso = flowsArray[5] as String
|
||||||
val query = flowsArray[6] as String
|
val query = flowsArray[6] as String
|
||||||
|
val quickFilter = flowsArray[7] as String
|
||||||
|
|
||||||
val filtered = activities.filter { activity ->
|
val filtered = activities.filter { activity ->
|
||||||
val matchSetor = setor == "Todos" || activity.setor == setor
|
val matchSetor = setor == "Todos" || activity.setor == setor
|
||||||
@@ -119,22 +146,44 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
activity.descricao.contains(query, ignoreCase = true) ||
|
activity.descricao.contains(query, ignoreCase = true) ||
|
||||||
activity.recurso.contains(query, ignoreCase = true)
|
activity.recurso.contains(query, ignoreCase = true)
|
||||||
|
|
||||||
matchSetor && matchEquipe && matchStatus && matchDataInicio && matchRecurso && matchQuery
|
val matchQuickFilter = when (quickFilter) {
|
||||||
|
"Todos" -> true
|
||||||
|
"Pendentes" -> activity.status != ActivityStatus.CONCLUIDO
|
||||||
|
"Hoje" -> {
|
||||||
|
val completionDate = parseFullDateTime(activity.dataFim)
|
||||||
|
if (completionDate == null) {
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
val calActivity = java.util.Calendar.getInstance()
|
||||||
|
calActivity.time = completionDate
|
||||||
|
|
||||||
|
val calToday = java.util.Calendar.getInstance()
|
||||||
|
calActivity.get(java.util.Calendar.YEAR) == calToday.get(java.util.Calendar.YEAR) &&
|
||||||
|
calActivity.get(java.util.Calendar.DAY_OF_YEAR) == calToday.get(java.util.Calendar.DAY_OF_YEAR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"Em andamento" -> activity.status == ActivityStatus.EM_ANDAMENTO
|
||||||
|
"Não iniciado" -> activity.status == ActivityStatus.NAO_INICIADO
|
||||||
|
"Mecânica" -> activity.equipe == "Mecânica"
|
||||||
|
"Elétrica" -> activity.equipe == "Elétrica"
|
||||||
|
"Confiabilidade" -> activity.equipe == "Confiabilidade"
|
||||||
|
else -> true
|
||||||
|
}
|
||||||
|
|
||||||
|
val result = matchSetor && matchEquipe && matchStatus && matchDataInicio && matchRecurso && matchQuery && matchQuickFilter
|
||||||
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
if (dataInicio != "Todas") {
|
// Always sort by dataFim (predicted completion date) ascending, oldest first
|
||||||
filtered.sortedWith { a1, a2 ->
|
filtered.sortedWith { a1, a2 ->
|
||||||
val p1 = parseFullDateTime(a1.dataInicio)
|
val p1 = parseFullDateTime(a1.dataFim)
|
||||||
val p2 = parseFullDateTime(a2.dataInicio)
|
val p2 = parseFullDateTime(a2.dataFim)
|
||||||
when {
|
when {
|
||||||
p1 == null && p2 == null -> a1.numeroOs.compareTo(a2.numeroOs)
|
p1 == null && p2 == null -> a1.numeroOs.compareTo(a2.numeroOs)
|
||||||
p1 == null -> 1
|
p1 == null -> 1 // Keep null/invalid date at the end
|
||||||
p2 == null -> -1
|
p2 == null -> -1
|
||||||
else -> p1.compareTo(p2)
|
else -> p1.compareTo(p2)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
filtered
|
|
||||||
}
|
}
|
||||||
}.stateIn(
|
}.stateIn(
|
||||||
scope = viewModelScope,
|
scope = viewModelScope,
|
||||||
@@ -158,7 +207,11 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
)
|
)
|
||||||
|
|
||||||
init {
|
init {
|
||||||
_currentUser.value = repository.getSavedUser()
|
val savedUser = repository.getSavedUser()
|
||||||
|
_currentUser.value = savedUser
|
||||||
|
savedUser?.let {
|
||||||
|
checkUserAccessLevel(it.email)
|
||||||
|
}
|
||||||
// Automatically check and pull service orders from Sheets on first launch.
|
// Automatically check and pull service orders from Sheets on first launch.
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val currentList = repository.allActivities.first()
|
val currentList = repository.allActivities.first()
|
||||||
@@ -170,6 +223,9 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
when (val result = repository.synchronizeWithBackend()) {
|
when (val result = repository.synchronizeWithBackend()) {
|
||||||
is SyncResult.Success -> {
|
is SyncResult.Success -> {
|
||||||
_syncStatusMessage.value = "Sincronização inicial concluída! ${result.syncedItems} OSs sincronizadas."
|
_syncStatusMessage.value = "Sincronização inicial concluída! ${result.syncedItems} OSs sincronizadas."
|
||||||
|
_currentUser.value?.let { user ->
|
||||||
|
checkUserAccessLevel(user.email)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
is SyncResult.Error -> {
|
is SyncResult.Error -> {
|
||||||
_syncStatusMessage.value = "Falha na sincronização inicial: ${result.message}"
|
_syncStatusMessage.value = "Falha na sincronização inicial: ${result.message}"
|
||||||
@@ -208,6 +264,10 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
_searchQuery.value = query
|
_searchQuery.value = query
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun setSelectedQuickFilter(filter: String) {
|
||||||
|
_selectedQuickFilter.value = filter
|
||||||
|
}
|
||||||
|
|
||||||
fun toggleInternet(available: Boolean) {
|
fun toggleInternet(available: Boolean) {
|
||||||
// App is always online.
|
// App is always online.
|
||||||
_internetAvailable.value = true
|
_internetAvailable.value = true
|
||||||
@@ -255,6 +315,9 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
_selectedActivity.value?.let { active ->
|
_selectedActivity.value?.let { active ->
|
||||||
_selectedActivity.value = allActivitiesState.value.find { it.numeroOs == active.numeroOs }
|
_selectedActivity.value = allActivitiesState.value.find { it.numeroOs == active.numeroOs }
|
||||||
}
|
}
|
||||||
|
_currentUser.value?.let { user ->
|
||||||
|
checkUserAccessLevel(user.email)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
is SyncResult.Error -> {
|
is SyncResult.Error -> {
|
||||||
_syncStatusMessage.value = "Falha na sincronização: ${result.message}"
|
_syncStatusMessage.value = "Falha na sincronização: ${result.message}"
|
||||||
@@ -268,11 +331,20 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
val user = com.example.data.model.GoogleUser(email, displayName)
|
val user = com.example.data.model.GoogleUser(email, displayName)
|
||||||
repository.saveUser(user)
|
repository.saveUser(user)
|
||||||
_currentUser.value = user
|
_currentUser.value = user
|
||||||
|
checkUserAccessLevel(email)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun logoutUser() {
|
fun logoutUser() {
|
||||||
repository.clearSavedUser()
|
repository.clearSavedUser()
|
||||||
_currentUser.value = null
|
_currentUser.value = null
|
||||||
|
_userAccessLevel.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun checkUserAccessLevel(email: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val access = repository.getUserAccess(email)
|
||||||
|
_userAccessLevel.value = access?.nivelAcesso
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -287,6 +359,13 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
emailEditor: String?
|
emailEditor: String?
|
||||||
) {
|
) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
|
val email = emailEditor ?: ""
|
||||||
|
val access = repository.getUserAccess(email)
|
||||||
|
val level = access?.nivelAcesso?.trim()?.lowercase()
|
||||||
|
if (level != "total" && level != "editor") {
|
||||||
|
_syncStatusMessage.value = "Erro: Nível de acesso '$level' não possui permissão para editar."
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
repository.updateProgress(numeroOs, novoPercentual, observacao, fotoPath, recurso, emailEditor)
|
repository.updateProgress(numeroOs, novoPercentual, observacao, fotoPath, recurso, emailEditor)
|
||||||
// Update selected activity model in state to refresh UI
|
// Update selected activity model in state to refresh UI
|
||||||
_selectedActivity.value?.let { active ->
|
_selectedActivity.value?.let { active ->
|
||||||
@@ -388,6 +467,113 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
repository.clearConflictLogs()
|
repository.clearConflictLogs()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun calculateAnalytics(
|
||||||
|
activities: List<MaintenanceActivity>,
|
||||||
|
history: List<OSUpdateHistory>
|
||||||
|
): AnalyticsState {
|
||||||
|
if (activities.isEmpty()) {
|
||||||
|
return AnalyticsState()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Team metrics
|
||||||
|
val teams = listOf("Mecânica", "Elétrica", "Confiabilidade", "Lubrificação")
|
||||||
|
val teamMetrics = teams.map { team ->
|
||||||
|
val teamActivities = activities.filter { it.equipe.equals(team, ignoreCase = true) }
|
||||||
|
val total = teamActivities.size
|
||||||
|
val completed = teamActivities.count { it.percentualExecucao >= 100 }
|
||||||
|
val ratio = if (total > 0) (completed.toFloat() / total.toFloat() * 100f).toInt() else 0
|
||||||
|
team to ratio
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. S-Curve bounds and steps
|
||||||
|
val parsedDates = activities.flatMap {
|
||||||
|
listOfNotNull(parseDateOnly(it.dataInicio), parseDateOnly(it.dataFim))
|
||||||
|
}
|
||||||
|
|
||||||
|
val projectStart = parsedDates.minOrNull() ?: Calendar.getInstance().apply { set(2026, Calendar.AUGUST, 1) }.time
|
||||||
|
val projectEnd = parsedDates.maxOrNull() ?: Calendar.getInstance().apply { set(2026, Calendar.AUGUST, 29) }.time
|
||||||
|
|
||||||
|
val durationMs = projectEnd.time - projectStart.time
|
||||||
|
val timelineSteps = 5
|
||||||
|
val timelineDates = (0 until timelineSteps).map { i ->
|
||||||
|
Date(projectStart.time + (durationMs * i / (timelineSteps - 1)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate Planned progress points
|
||||||
|
val plannedProgressPoints = timelineDates.map { date ->
|
||||||
|
val dayTime = date.time
|
||||||
|
val totalActivities = activities.size
|
||||||
|
if (totalActivities == 0) 0f
|
||||||
|
else {
|
||||||
|
val sum = activities.sumOf { act ->
|
||||||
|
val start = parseDateOnly(act.dataInicio)?.time ?: dayTime
|
||||||
|
val end = parseDateOnly(act.dataFim)?.time ?: dayTime
|
||||||
|
when {
|
||||||
|
dayTime <= start -> 0
|
||||||
|
dayTime >= end -> 100
|
||||||
|
else -> {
|
||||||
|
val progress = ((dayTime - start).toDouble() / (end - start).toDouble() * 100.0).toInt()
|
||||||
|
progress.coerceIn(0, 100)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sum.toFloat() / totalActivities.toFloat()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate Realized progress points
|
||||||
|
val realizedProgressPoints = timelineDates.map { date ->
|
||||||
|
val dayTime = date.time
|
||||||
|
val totalActivities = activities.size
|
||||||
|
if (totalActivities == 0) 0f
|
||||||
|
else {
|
||||||
|
val sum = activities.sumOf { act ->
|
||||||
|
val osLogs = history.filter { it.numeroOs == act.numeroOs && it.timestamp <= dayTime }
|
||||||
|
if (osLogs.isNotEmpty()) {
|
||||||
|
osLogs.last().percentualNovo
|
||||||
|
} else {
|
||||||
|
if (act.lastUpdated <= dayTime) act.percentualExecucao else 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sum.toFloat() / totalActivities.toFloat()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Overdue tags
|
||||||
|
val referenceDate = if (Date().before(projectEnd)) projectEnd else Date()
|
||||||
|
|
||||||
|
val overdueActivities = activities.filter { act ->
|
||||||
|
val isNotCompleted = act.percentualExecucao < 100
|
||||||
|
val endDate = parseDateOnly(act.dataFim)
|
||||||
|
isNotCompleted && endDate != null && endDate.before(referenceDate)
|
||||||
|
}
|
||||||
|
|
||||||
|
val overdueByTag = overdueActivities
|
||||||
|
.groupBy { if (it.tag.isBlank()) "Sem TAG" else it.tag }
|
||||||
|
.mapValues { it.value.size }
|
||||||
|
.toList()
|
||||||
|
.sortedByDescending { it.second }
|
||||||
|
|
||||||
|
val displayLimit = 4
|
||||||
|
val finalOverdueByTag = if (overdueByTag.size <= displayLimit) {
|
||||||
|
overdueByTag
|
||||||
|
} else {
|
||||||
|
val top = overdueByTag.take(displayLimit - 1)
|
||||||
|
val othersCount = overdueByTag.drop(displayLimit - 1).sumOf { it.second }
|
||||||
|
top + listOf("Outros" to othersCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
return AnalyticsState(
|
||||||
|
teamMetrics = teamMetrics,
|
||||||
|
projectStart = projectStart,
|
||||||
|
projectEnd = projectEnd,
|
||||||
|
timelineDates = timelineDates,
|
||||||
|
plannedProgressPoints = plannedProgressPoints,
|
||||||
|
realizedProgressPoints = realizedProgressPoints,
|
||||||
|
overdueByTag = finalOverdueByTag
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class MaintenanceViewModelFactory(private val repository: MaintenanceRepository) : ViewModelProvider.Factory {
|
class MaintenanceViewModelFactory(private val repository: MaintenanceRepository) : ViewModelProvider.Factory {
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ import org.robolectric.RobolectricTestRunner
|
|||||||
import org.robolectric.annotation.Config
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.test.setMain
|
||||||
|
import kotlinx.coroutines.test.resetMain
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
|
||||||
@RunWith(RobolectricTestRunner::class)
|
@RunWith(RobolectricTestRunner::class)
|
||||||
@Config(sdk = [34])
|
@Config(sdk = [34])
|
||||||
@@ -66,4 +70,280 @@ class ExampleRobolectricTest {
|
|||||||
println("--- END SYNCHRONIZE DIAGNOSTIC ---")
|
println("--- END SYNCHRONIZE DIAGNOSTIC ---")
|
||||||
db.close()
|
db.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
@Test
|
||||||
|
fun `test quick filters and sorting by predicted end date`() {
|
||||||
|
val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher()
|
||||||
|
kotlinx.coroutines.Dispatchers.setMain(testDispatcher)
|
||||||
|
try {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.setQueryExecutor { it.run() }
|
||||||
|
.setTransactionExecutor { it.run() }
|
||||||
|
.build()
|
||||||
|
val repository = com.example.data.repository.MaintenanceRepository(db.maintenanceDao(), context)
|
||||||
|
|
||||||
|
val todayStr = java.text.SimpleDateFormat("dd/MM/yyyy HH:mm", java.util.Locale.US).format(java.util.Date())
|
||||||
|
|
||||||
|
val act1 = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-FUTURE",
|
||||||
|
descricao = "Future OS",
|
||||||
|
setor = "Geral",
|
||||||
|
equipe = "Mecânica",
|
||||||
|
recurso = "Sem Recurso",
|
||||||
|
dataInicio = "27/08/2027 10:00",
|
||||||
|
dataFim = "27/08/2027 17:00",
|
||||||
|
percentualExecucao = 50,
|
||||||
|
synced = true
|
||||||
|
)
|
||||||
|
val act2 = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-OLDEST",
|
||||||
|
descricao = "Oldest OS",
|
||||||
|
setor = "Geral",
|
||||||
|
equipe = "Elétrica",
|
||||||
|
recurso = "Sem Recurso",
|
||||||
|
dataInicio = "25/07/2026 10:00",
|
||||||
|
dataFim = "25/07/2026 17:00",
|
||||||
|
percentualExecucao = 100,
|
||||||
|
synced = true
|
||||||
|
)
|
||||||
|
val act3 = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-TODAY",
|
||||||
|
descricao = "Today OS",
|
||||||
|
setor = "Geral",
|
||||||
|
equipe = "Confiabilidade",
|
||||||
|
recurso = "Sem Recurso",
|
||||||
|
dataInicio = todayStr,
|
||||||
|
dataFim = todayStr,
|
||||||
|
percentualExecucao = 0,
|
||||||
|
synced = true
|
||||||
|
)
|
||||||
|
|
||||||
|
kotlinx.coroutines.runBlocking {
|
||||||
|
db.maintenanceDao().insertActivities(listOf(act1, act2, act3))
|
||||||
|
|
||||||
|
val allLocal = db.maintenanceDao().getAllActivitiesList()
|
||||||
|
println("ALL LOCAL ACTIVITIES IN DB BEFORE VM: ${allLocal.size}")
|
||||||
|
for (a in allLocal) {
|
||||||
|
println(" - OS: ${a.numeroOs}, dataFim: ${a.dataFim}")
|
||||||
|
}
|
||||||
|
|
||||||
|
val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository)
|
||||||
|
|
||||||
|
// Start collection to activate stateIn subscription
|
||||||
|
val collectionJob = viewModel.viewModelScope.launch {
|
||||||
|
viewModel.filteredActivities.collect {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Let background threads run (like Room flow query)
|
||||||
|
Thread.sleep(200)
|
||||||
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||||
|
|
||||||
|
// 1. Test default sorting by dataFim (oldest first): OS-OLDEST -> OS-TODAY (current day) -> OS-FUTURE (next year)
|
||||||
|
val defaultList = viewModel.filteredActivities.value
|
||||||
|
assertEquals(3, defaultList.size)
|
||||||
|
assertEquals("OS-OLDEST", defaultList[0].numeroOs)
|
||||||
|
assertEquals("OS-TODAY", defaultList[1].numeroOs)
|
||||||
|
assertEquals("OS-FUTURE", defaultList[2].numeroOs)
|
||||||
|
|
||||||
|
// 2. Test "Pendentes" filter (should return act1 and act3, but not act2)
|
||||||
|
viewModel.setSelectedQuickFilter("Pendentes")
|
||||||
|
Thread.sleep(200)
|
||||||
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||||
|
val pendingList = viewModel.filteredActivities.value
|
||||||
|
assertEquals(2, pendingList.size)
|
||||||
|
assert(pendingList.any { it.numeroOs == "OS-FUTURE" })
|
||||||
|
assert(pendingList.any { it.numeroOs == "OS-TODAY" })
|
||||||
|
|
||||||
|
// 3. Test "Hoje" filter (should return act3 only)
|
||||||
|
viewModel.setSelectedQuickFilter("Hoje")
|
||||||
|
Thread.sleep(200)
|
||||||
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||||
|
val todayList = viewModel.filteredActivities.value
|
||||||
|
assertEquals(1, todayList.size)
|
||||||
|
assertEquals("OS-TODAY", todayList[0].numeroOs)
|
||||||
|
|
||||||
|
// 4. Test "Mecânica" filter (should return act1 only)
|
||||||
|
viewModel.setSelectedQuickFilter("Mecânica")
|
||||||
|
Thread.sleep(200)
|
||||||
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||||
|
val mechanicalList = viewModel.filteredActivities.value
|
||||||
|
assertEquals(1, mechanicalList.size)
|
||||||
|
assertEquals("OS-FUTURE", mechanicalList[0].numeroOs)
|
||||||
|
|
||||||
|
collectionJob.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
db.close()
|
||||||
|
} finally {
|
||||||
|
kotlinx.coroutines.Dispatchers.resetMain()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
@Test
|
||||||
|
fun `test analytics state calculations in ViewModel`() {
|
||||||
|
val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher()
|
||||||
|
kotlinx.coroutines.Dispatchers.setMain(testDispatcher)
|
||||||
|
try {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.setQueryExecutor { it.run() }
|
||||||
|
.setTransactionExecutor { it.run() }
|
||||||
|
.build()
|
||||||
|
val repository = com.example.data.repository.MaintenanceRepository(db.maintenanceDao(), context)
|
||||||
|
|
||||||
|
val act1 = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-1",
|
||||||
|
descricao = "Inspection 1",
|
||||||
|
setor = "Geral",
|
||||||
|
equipe = "Mecânica",
|
||||||
|
recurso = "Sem Recurso",
|
||||||
|
dataInicio = "Sex 14/08/26 07:00",
|
||||||
|
dataFim = "Sex 14/08/26 17:00",
|
||||||
|
percentualExecucao = 100,
|
||||||
|
tag = "TAG-MEC",
|
||||||
|
synced = true
|
||||||
|
)
|
||||||
|
val act2 = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-2",
|
||||||
|
descricao = "Repair 2",
|
||||||
|
setor = "Geral",
|
||||||
|
equipe = "Elétrica",
|
||||||
|
recurso = "Sem Recurso",
|
||||||
|
dataInicio = "14/08/2026 08:30",
|
||||||
|
dataFim = "15/08/2026 17:00",
|
||||||
|
percentualExecucao = 50,
|
||||||
|
tag = "TAG-ELE",
|
||||||
|
synced = true
|
||||||
|
)
|
||||||
|
|
||||||
|
kotlinx.coroutines.runBlocking {
|
||||||
|
db.maintenanceDao().insertActivities(listOf(act1, act2))
|
||||||
|
|
||||||
|
val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository)
|
||||||
|
|
||||||
|
// Start collection to activate stateIn subscription
|
||||||
|
val collectionJob = viewModel.viewModelScope.launch {
|
||||||
|
viewModel.analyticsState.collect {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow Room flow to emit
|
||||||
|
Thread.sleep(200)
|
||||||
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||||
|
|
||||||
|
val state = viewModel.analyticsState.value
|
||||||
|
|
||||||
|
// 1. Verify team metrics
|
||||||
|
val mecProductivity = state.teamMetrics.find { it.first == "Mecânica" }?.second
|
||||||
|
val eleProductivity = state.teamMetrics.find { it.first == "Elétrica" }?.second
|
||||||
|
assertEquals(100, mecProductivity)
|
||||||
|
assertEquals(0, eleProductivity) // OS-2 is only 50%, so not completed (>= 100)
|
||||||
|
|
||||||
|
// 2. Verify timeline dates size (should be 5 steps)
|
||||||
|
assertEquals(5, state.timelineDates.size)
|
||||||
|
|
||||||
|
// 3. Verify planned progress points has correct count
|
||||||
|
assertEquals(5, state.plannedProgressPoints.size)
|
||||||
|
|
||||||
|
// 4. Verify realized progress points has correct count
|
||||||
|
assertEquals(5, state.realizedProgressPoints.size)
|
||||||
|
|
||||||
|
collectionJob.cancel()
|
||||||
|
}
|
||||||
|
db.close()
|
||||||
|
} finally {
|
||||||
|
kotlinx.coroutines.Dispatchers.resetMain()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
@Test
|
||||||
|
fun `test user access control check in ViewModel`() {
|
||||||
|
val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher()
|
||||||
|
kotlinx.coroutines.Dispatchers.setMain(testDispatcher)
|
||||||
|
try {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.setQueryExecutor { it.run() }
|
||||||
|
.setTransactionExecutor { it.run() }
|
||||||
|
.build()
|
||||||
|
val repository = com.example.data.repository.MaintenanceRepository(db.maintenanceDao(), context)
|
||||||
|
|
||||||
|
val userAdmin = com.example.data.model.UserAccess("admin@cargill.com", "total")
|
||||||
|
val userEditor = com.example.data.model.UserAccess("editor@cargill.com", "editor")
|
||||||
|
val userViewer = com.example.data.model.UserAccess("viewer@cargill.com", "leitor")
|
||||||
|
|
||||||
|
kotlinx.coroutines.runBlocking {
|
||||||
|
db.maintenanceDao().insertUserAccessList(listOf(userAdmin, userEditor, userViewer))
|
||||||
|
|
||||||
|
val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository)
|
||||||
|
|
||||||
|
// Setup a dummy activity in database
|
||||||
|
val act = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-ACCESS",
|
||||||
|
descricao = "Access Test",
|
||||||
|
setor = "Geral",
|
||||||
|
equipe = "Mecânica",
|
||||||
|
recurso = "Sem Recurso",
|
||||||
|
dataInicio = "27/08/2026 10:00",
|
||||||
|
dataFim = "27/08/2026 17:00",
|
||||||
|
percentualExecucao = 0,
|
||||||
|
synced = true
|
||||||
|
)
|
||||||
|
db.maintenanceDao().insertActivity(act)
|
||||||
|
|
||||||
|
// Start collection to activate stateIn subscription
|
||||||
|
val collectionJob = viewModel.viewModelScope.launch {
|
||||||
|
viewModel.filteredActivities.collect {}
|
||||||
|
}
|
||||||
|
val collectionJob2 = viewModel.viewModelScope.launch {
|
||||||
|
viewModel.userAccessLevel.collect {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test 1: User not logged in
|
||||||
|
viewModel.selectActivity(act)
|
||||||
|
// Access level should be null
|
||||||
|
assertEquals(null, viewModel.userAccessLevel.value)
|
||||||
|
|
||||||
|
// Test 2: Log in as viewer (viewer@cargill.com)
|
||||||
|
viewModel.loginUser("viewer@cargill.com", "Viewer User")
|
||||||
|
Thread.sleep(100)
|
||||||
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||||
|
assertEquals("leitor", viewModel.userAccessLevel.value)
|
||||||
|
|
||||||
|
// Attempt to edit progress (should fail because access level is leitor, which is not total or editor)
|
||||||
|
viewModel.updateProgress("OS-ACCESS", 50, "Tentando editar", null, "Viewer User", "viewer@cargill.com")
|
||||||
|
Thread.sleep(100)
|
||||||
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||||
|
// OS percentualExecucao should remain 0
|
||||||
|
val actAfterViewer = db.maintenanceDao().getActivityByOsOneShot("OS-ACCESS")
|
||||||
|
assertEquals(0, actAfterViewer?.percentualExecucao)
|
||||||
|
|
||||||
|
// Test 3: Log in as editor (editor@cargill.com)
|
||||||
|
viewModel.loginUser("editor@cargill.com", "Editor User")
|
||||||
|
Thread.sleep(100)
|
||||||
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||||
|
assertEquals("editor", viewModel.userAccessLevel.value)
|
||||||
|
|
||||||
|
// Attempt to edit progress (should succeed because access level is editor)
|
||||||
|
viewModel.updateProgress("OS-ACCESS", 80, "Editando com editor", null, "Editor User", "editor@cargill.com")
|
||||||
|
Thread.sleep(100)
|
||||||
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||||
|
// OS percentualExecucao should now be 80
|
||||||
|
val actAfterEditor = db.maintenanceDao().getActivityByOsOneShot("OS-ACCESS")
|
||||||
|
assertEquals(80, actAfterEditor?.percentualExecucao)
|
||||||
|
|
||||||
|
collectionJob.cancel()
|
||||||
|
collectionJob2.cancel()
|
||||||
|
}
|
||||||
|
db.close()
|
||||||
|
} finally {
|
||||||
|
kotlinx.coroutines.Dispatchers.resetMain()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,6 +54,21 @@ class ExampleUnitTest {
|
|||||||
assertEquals(2026, cal3.get(Calendar.YEAR))
|
assertEquals(2026, cal3.get(Calendar.YEAR))
|
||||||
assertEquals(Calendar.AUGUST, cal3.get(Calendar.MONTH))
|
assertEquals(Calendar.AUGUST, cal3.get(Calendar.MONTH))
|
||||||
assertEquals(17, cal3.get(Calendar.DAY_OF_MONTH))
|
assertEquals(17, cal3.get(Calendar.DAY_OF_MONTH))
|
||||||
|
|
||||||
|
// Tests for dates containing weekdays or times
|
||||||
|
val date4 = parseDateOnly("Sex 14/08/26 07:00")
|
||||||
|
assertNotNull(date4)
|
||||||
|
val cal4 = Calendar.getInstance().apply { time = date4!! }
|
||||||
|
assertEquals(2026, cal4.get(Calendar.YEAR))
|
||||||
|
assertEquals(Calendar.AUGUST, cal4.get(Calendar.MONTH))
|
||||||
|
assertEquals(14, cal4.get(Calendar.DAY_OF_MONTH))
|
||||||
|
|
||||||
|
val date5 = parseDateOnly("14/08/2026 08:30")
|
||||||
|
assertNotNull(date5)
|
||||||
|
val cal5 = Calendar.getInstance().apply { time = date5!! }
|
||||||
|
assertEquals(2026, cal5.get(Calendar.YEAR))
|
||||||
|
assertEquals(Calendar.AUGUST, cal5.get(Calendar.MONTH))
|
||||||
|
assertEquals(14, cal5.get(Calendar.DAY_OF_MONTH))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -174,4 +189,47 @@ class ExampleUnitTest {
|
|||||||
assertEquals("OS2", overdueActivities.first().numeroOs)
|
assertEquals("OS2", overdueActivities.first().numeroOs)
|
||||||
assertEquals("TAG1", overdueActivities.first().tag)
|
assertEquals("TAG1", overdueActivities.first().tag)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testUserAccessParsingAndValidation() {
|
||||||
|
// Simulate user access lists matching dynamic headers
|
||||||
|
val rows = listOf(
|
||||||
|
listOf("E-mail", "Nível de Acesso"),
|
||||||
|
listOf("admin@cargill.com", "total"),
|
||||||
|
listOf("editor@cargill.com", "editor"),
|
||||||
|
listOf("viewer@cargill.com", "leitor"),
|
||||||
|
listOf("random@cargill.com", "outro")
|
||||||
|
)
|
||||||
|
|
||||||
|
val headers = rows[0].map { it.trim().lowercase() }
|
||||||
|
val emailIdx = headers.indexOfFirst { it == "email" || it == "e-mail" || it.contains("email") }
|
||||||
|
val nivelIdx = headers.indexOfFirst { it == "nivel_acesso" || it == "nivel" || it.contains("nivel") || it.contains("nível") }
|
||||||
|
|
||||||
|
assertEquals(0, emailIdx)
|
||||||
|
assertEquals(1, nivelIdx)
|
||||||
|
|
||||||
|
val accessMap = mutableMapOf<String, String>()
|
||||||
|
for (i in 1 until rows.size) {
|
||||||
|
val row = rows[i]
|
||||||
|
val email = row[emailIdx].trim()
|
||||||
|
val nivel = row[nivelIdx].trim()
|
||||||
|
accessMap[email] = nivel
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("total", accessMap["admin@cargill.com"])
|
||||||
|
assertEquals("editor", accessMap["editor@cargill.com"])
|
||||||
|
assertEquals("leitor", accessMap["viewer@cargill.com"])
|
||||||
|
|
||||||
|
// Function to check write permission
|
||||||
|
val hasWriteAccess = { email: String ->
|
||||||
|
val level = accessMap[email]?.trim()?.lowercase()
|
||||||
|
level == "total" || level == "editor"
|
||||||
|
}
|
||||||
|
|
||||||
|
assertTrue(hasWriteAccess("admin@cargill.com"))
|
||||||
|
assertTrue(hasWriteAccess("editor@cargill.com"))
|
||||||
|
assertFalse(hasWriteAccess("viewer@cargill.com"))
|
||||||
|
assertFalse(hasWriteAccess("random@cargill.com"))
|
||||||
|
assertFalse(hasWriteAccess("nonexistent@cargill.com"))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user