From a8d1ea9f4bf13cb42ce3854b9d66956de0c5f8b4 Mon Sep 17 00:00:00 2001 From: Jhony Cesar Date: Tue, 28 Jul 2026 00:18:35 -0400 Subject: [PATCH] feat: implement maintenance analytics state with team metrics and progress tracking in ViewModel and UI --- .../com/example/data/model/AnalyticsState.kt | 13 ++ .../com/example/ui/screens/AnalyticsScreen.kt | 167 +++++------------- .../ui/viewmodel/MaintenanceViewModel.kt | 126 +++++++++++++ .../com/example/ExampleRobolectricTest.kt | 78 ++++++++ 4 files changed, 257 insertions(+), 127 deletions(-) create mode 100644 app/src/main/java/com/example/data/model/AnalyticsState.kt diff --git a/app/src/main/java/com/example/data/model/AnalyticsState.kt b/app/src/main/java/com/example/data/model/AnalyticsState.kt new file mode 100644 index 0000000..414d9d2 --- /dev/null +++ b/app/src/main/java/com/example/data/model/AnalyticsState.kt @@ -0,0 +1,13 @@ +package com.example.data.model + +import java.util.Date + +data class AnalyticsState( + val teamMetrics: List> = emptyList(), + val projectStart: Date = Date(), + val projectEnd: Date = Date(), + val timelineDates: List = emptyList(), + val plannedProgressPoints: List = emptyList(), + val realizedProgressPoints: List = emptyList(), + val overdueByTag: List> = emptyList() +) diff --git a/app/src/main/java/com/example/ui/screens/AnalyticsScreen.kt b/app/src/main/java/com/example/ui/screens/AnalyticsScreen.kt index 20ab129..daebc38 100644 --- a/app/src/main/java/com/example/ui/screens/AnalyticsScreen.kt +++ b/app/src/main/java/com/example/ui/screens/AnalyticsScreen.kt @@ -30,6 +30,7 @@ import com.example.data.model.ActivityStatus import com.example.data.model.MaintenanceActivity import com.example.data.model.OSUpdateHistory import com.example.data.model.parseDateOnly +import com.example.data.model.AnalyticsState import com.example.ui.theme.CargillBlack import com.example.ui.theme.CargillGreen import com.example.ui.theme.LightGrey @@ -47,7 +48,7 @@ fun AnalyticsScreen( modifier: Modifier = Modifier ) { val activities by viewModel.allActivitiesState.collectAsStateWithLifecycle() - val historyLogs by viewModel.allHistoryState.collectAsStateWithLifecycle() + val analyticsState by viewModel.analyticsState.collectAsStateWithLifecycle() Scaffold( topBar = { @@ -112,13 +113,13 @@ fun AnalyticsScreen( } } else { // Card 1: Produtividade da Equipe - TeamProductivityCard(activities) + TeamProductivityCard(analyticsState.teamMetrics) // Card 2: Progresso do Projeto: Planejado vs. Realizado - SCurveCard(activities, historyLogs) + SCurveCard(analyticsState) // 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 */ @Composable -fun TeamProductivityCard(activities: List) { +fun TeamProductivityCard(teamMetrics: List>) { Card( modifier = Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = Color.White), @@ -150,16 +151,6 @@ fun TeamProductivityCard(activities: List) { 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( modifier = Modifier .fillMaxWidth() @@ -214,7 +205,7 @@ fun TeamProductivityCard(activities: List) { * Compara o avanço temporal Planejado com o Realizado */ @Composable -fun SCurveCard(activities: List, history: List) { +fun SCurveCard(analyticsState: AnalyticsState) { Card( modifier = Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = Color.White), @@ -237,62 +228,12 @@ fun SCurveCard(activities: List, history: List - 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 + if (timelineSteps > 0 && plannedProgressPoints.isNotEmpty() && realizedProgressPoints.isNotEmpty()) { Canvas( modifier = Modifier .fillMaxWidth() @@ -383,35 +324,34 @@ fun SCurveCard(activities: List, history: List, history: List) { +fun OverdueByTagCard(overdueByTag: List>) { Card( modifier = Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = Color.White), @@ -445,18 +385,7 @@ fun OverdueByTagCard(activities: List) { .padding(bottom = 16.dp) ) - // Determine reference date to decide what is overdue. - 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()) { + if (overdueByTag.isEmpty()) { Box( modifier = Modifier .fillMaxWidth() @@ -471,23 +400,7 @@ fun OverdueByTagCard(activities: List) { ) } } else { - // Group by TAG and count - 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 displayList = overdueByTag val maxCount = displayList.maxOfOrNull { it.second } ?: 1 Column( diff --git a/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt b/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt index a675adf..ab4f643 100644 --- a/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt +++ b/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt @@ -12,8 +12,14 @@ import com.example.data.model.SyncConflictLog import com.example.data.model.extractDateOnly import com.example.data.model.formatToShortDate 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.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.SharingStarted import kotlinx.coroutines.flow.StateFlow @@ -87,6 +93,19 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View initialValue = emptyList() ) + val analyticsState: StateFlow = 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 val filteredActivities: StateFlow> = combine( repository.allActivities, @@ -419,6 +438,113 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View repository.clearConflictLogs() } } + + private fun calculateAnalytics( + activities: List, + history: List + ): 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 { diff --git a/app/src/test/java/com/example/ExampleRobolectricTest.kt b/app/src/test/java/com/example/ExampleRobolectricTest.kt index 4a37ebf..55fb275 100644 --- a/app/src/test/java/com/example/ExampleRobolectricTest.kt +++ b/app/src/test/java/com/example/ExampleRobolectricTest.kt @@ -181,4 +181,82 @@ class ExampleRobolectricTest { 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() + 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() + } + } }