diff --git a/app/src/main/java/com/example/MainActivity.kt b/app/src/main/java/com/example/MainActivity.kt index 8e2f841..4a13cfe 100644 --- a/app/src/main/java/com/example/MainActivity.kt +++ b/app/src/main/java/com/example/MainActivity.kt @@ -24,7 +24,7 @@ import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.example.data.local.AppDatabase import com.example.data.repository.MaintenanceRepository -import com.example.ui.screens.DashboardStubScreen +import com.example.ui.screens.AnalyticsScreen import com.example.ui.screens.MaintenanceDashboardScreen import com.example.ui.screens.SettingsScreen import com.example.ui.theme.CargillGreen @@ -135,7 +135,14 @@ class MainActivity : ComponentActivity() { modifier = Modifier.padding(bottom = innerPadding.calculateBottomPadding()) ) { composable("dashboard") { - DashboardStubScreen() + AnalyticsScreen( + viewModel = viewModel, + onBackClick = { + navController.navigate("ordens") { + popUpTo("ordens") { inclusive = false } + } + } + ) } composable("ordens") { MaintenanceDashboardScreen( diff --git a/app/src/main/java/com/example/data/local/AppDatabase.kt b/app/src/main/java/com/example/data/local/AppDatabase.kt index 4b7fea8..905d10a 100644 --- a/app/src/main/java/com/example/data/local/AppDatabase.kt +++ b/app/src/main/java/com/example/data/local/AppDatabase.kt @@ -10,7 +10,7 @@ import com.example.data.model.SyncConflictLog @Database( entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class], - version = 3, + version = 4, exportSchema = false ) abstract class AppDatabase : RoomDatabase() { diff --git a/app/src/main/java/com/example/data/local/MaintenanceDao.kt b/app/src/main/java/com/example/data/local/MaintenanceDao.kt index 5c382d5..73dc11b 100644 --- a/app/src/main/java/com/example/data/local/MaintenanceDao.kt +++ b/app/src/main/java/com/example/data/local/MaintenanceDao.kt @@ -45,6 +45,9 @@ interface MaintenanceDao { @Query("SELECT * FROM os_update_history") suspend fun getAllHistoryList(): List + @Query("SELECT * FROM os_update_history ORDER BY timestamp ASC") + fun getAllHistoryFlow(): Flow> + @Query("DELETE FROM maintenance_activities") suspend fun clearAllActivities() diff --git a/app/src/main/java/com/example/data/model/MaintenanceActivity.kt b/app/src/main/java/com/example/data/model/MaintenanceActivity.kt index 1a78095..99b48d7 100644 --- a/app/src/main/java/com/example/data/model/MaintenanceActivity.kt +++ b/app/src/main/java/com/example/data/model/MaintenanceActivity.kt @@ -20,6 +20,7 @@ data class MaintenanceActivity( val observacoes: String? = null, val fotoPath: String? = null, val synced: Boolean = false, + val tag: String = "", val lastUpdated: Long = System.currentTimeMillis() ) { val status: ActivityStatus diff --git a/app/src/main/java/com/example/data/remote/GoogleSheetsSyncService.kt b/app/src/main/java/com/example/data/remote/GoogleSheetsSyncService.kt index b1f88d4..ba609df 100644 --- a/app/src/main/java/com/example/data/remote/GoogleSheetsSyncService.kt +++ b/app/src/main/java/com/example/data/remote/GoogleSheetsSyncService.kt @@ -538,7 +538,12 @@ class GoogleSheetsSyncService(private val context: Context) { } } - Log.d(tag, "Mapped Column Indices: taskName=$taskNameIdx, group=$groupIdx, resource=$resourceIdx, inicio=$inicioIdx, fim=$fimIdx, outline=$outlineIdx, id=$idIdx, resumo=$resumoIdx") + // 9. TAG: column mapping for asset tag + val tagIdx = headers.indexOfFirst { + it == "tag" || it.contains("tag") + } + + Log.d(tag, "Mapped Column Indices: taskName=$taskNameIdx, group=$groupIdx, resource=$resourceIdx, inicio=$inicioIdx, fim=$fimIdx, outline=$outlineIdx, id=$idIdx, resumo=$resumoIdx, tag=$tagIdx") // Step 1: Pre-build outline-to-name lookup map to extract Sector name from grandparent outline val outlineMap = mutableMapOf() @@ -603,6 +608,15 @@ class GoogleSheetsSyncService(private val context: Context) { val dataInicio = if (inicioIdx != -1 && inicioIdx < row.size) row[inicioIdx].trim() else "N/A" val dataFim = if (fimIdx != -1 && fimIdx < row.size) row[fimIdx].trim() else "N/A" + // Retrieve tag from column or fallback to parent task outline name + val actTag = if (tagIdx != -1 && tagIdx < row.size && row[tagIdx].isNotBlank()) { + row[tagIdx].trim() + } else { + val parentOutline = if (outlineParts.size >= 3) outlineParts.take(outlineParts.size - 1).joinToString(".") else "" + val parentTagName = outlineMap[parentOutline]?.trim() ?: "" + if (parentTagName.isNotBlank()) parentTagName else "Sem TAG" + } + activities.add( MaintenanceActivity( numeroOs = osNum, @@ -616,6 +630,7 @@ class GoogleSheetsSyncService(private val context: Context) { observacoes = null, fotoPath = null, synced = true, + tag = actTag, lastUpdated = 0L ) ) diff --git a/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt b/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt index a4f4d29..3000fb8 100644 --- a/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt +++ b/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt @@ -23,6 +23,8 @@ class MaintenanceRepository( val allActivities: Flow> = dao.getAllActivities() + val allHistory: Flow> = dao.getAllHistoryFlow() + fun getActivityByOs(numeroOs: String): Flow = dao.getActivityByOs(numeroOs) fun getHistoryForOs(numeroOs: String): Flow> = dao.getHistoryForOs(numeroOs) @@ -124,6 +126,7 @@ class MaintenanceRepository( val inicioIdx = headers.indexOfFirst { it.contains("inicio") || it.contains("início") || it.contains("start") } val fimIdx = headers.indexOfFirst { it.contains("fim") || it.contains("end") || it.contains("termino") || it.contains("término") } val pctIdx = headers.indexOfFirst { it.contains("pct") || it.contains("%") || it.contains("percent") || it.contains("exec") } + val tagIdx = headers.indexOfFirst { it.contains("tag") } if (osIdx == -1 || descIdx == -1) { return@withContext Result.failure(Exception("Colunas obrigatórias não encontradas. Certifique-se de ter ao menos 'Número da OS' e 'Descrição'.")) @@ -147,6 +150,7 @@ class MaintenanceRepository( val dataFim = if (fimIdx != -1 && fimIdx < rowCells.size) rowCells[fimIdx] else "N/A" val pctStr = if (pctIdx != -1 && pctIdx < rowCells.size) rowCells[pctIdx].replace("%", "").trim() else "0" val pct = pctStr.toIntOrNull() ?: 0 + val tag = if (tagIdx != -1 && tagIdx < rowCells.size) rowCells[tagIdx] else "Sem TAG" importedActivities.add( MaintenanceActivity( @@ -159,6 +163,7 @@ class MaintenanceRepository( dataFim = dataFim, percentualExecucao = pct.coerceIn(0, 100), synced = false, + tag = tag, lastUpdated = now ) ) diff --git a/app/src/main/java/com/example/ui/screens/AnalyticsScreen.kt b/app/src/main/java/com/example/ui/screens/AnalyticsScreen.kt new file mode 100644 index 0000000..20ab129 --- /dev/null +++ b/app/src/main/java/com/example/ui/screens/AnalyticsScreen.kt @@ -0,0 +1,552 @@ +package com.example.ui.screens + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.nativeCanvas +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +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.ui.theme.CargillBlack +import com.example.ui.theme.CargillGreen +import com.example.ui.theme.LightGrey +import com.example.ui.viewmodel.MaintenanceViewModel +import java.text.SimpleDateFormat +import java.util.Calendar +import java.util.Date +import java.util.Locale + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun AnalyticsScreen( + viewModel: MaintenanceViewModel, + onBackClick: () -> Unit, + modifier: Modifier = Modifier +) { + val activities by viewModel.allActivitiesState.collectAsStateWithLifecycle() + val historyLogs by viewModel.allHistoryState.collectAsStateWithLifecycle() + + Scaffold( + topBar = { + TopAppBar( + title = { + Text( + text = "Métricas Analíticas Avançadas", + fontSize = 18.sp, + fontWeight = FontWeight.Bold, + color = CargillBlack + ) + }, + navigationIcon = { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .clickable(onClick = onBackClick) + .padding(horizontal = 8.dp, vertical = 4.dp) + ) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = "Voltar", + tint = CargillGreen + ) + Spacer(modifier = Modifier.width(4.dp)) + Text( + text = "Voltar", + color = CargillGreen, + fontSize = 16.sp, + fontWeight = FontWeight.Medium + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.White), + modifier = Modifier.background(Color.White) + ) + }, + containerColor = LightGrey, + modifier = modifier + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + .verticalScroll(rememberScrollState()) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + if (activities.isEmpty()) { + Box( + modifier = Modifier + .fillMaxWidth() + .height(300.dp), + contentAlignment = Alignment.Center + ) { + Text( + text = "Nenhuma Ordem de Serviço encontrada para gerar métricas.", + color = Color.Gray, + textAlign = TextAlign.Center, + fontSize = 14.sp + ) + } + } else { + // Card 1: Produtividade da Equipe + TeamProductivityCard(activities) + + // Card 2: Progresso do Projeto: Planejado vs. Realizado + SCurveCard(activities, historyLogs) + + // Card 3: Atrasados por TAG + OverdueByTagCard(activities) + } + } + } +} + +/** + * Gráfico 1: Produtividade da Equipe + * Exibe a razão de OS concluídas sobre o total de OS por equipe + */ +@Composable +fun TeamProductivityCard(activities: List) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = Color.White), + elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), + shape = RoundedCornerShape(16.dp) + ) { + Column( + modifier = Modifier + .padding(16.dp) + .fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Text( + text = "Produtividade da Equipe", + fontSize = 16.sp, + fontWeight = FontWeight.Bold, + color = CargillBlack, + 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() + .height(200.dp) + .padding(horizontal = 8.dp), + horizontalArrangement = Arrangement.SpaceEvenly, + verticalAlignment = Alignment.Bottom + ) { + teamMetrics.forEach { (team, percentage) -> + val barColor = when (team) { + "Mecânica" -> Color(0xFF4CAF50) // Green + "Elétrica" -> Color(0xFF2196F3) // Blue + "Confiabilidade" -> Color(0xFFFF9800) // Orange + else -> Color(0xFF9C27B0) // Purple + } + + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Bottom, + modifier = Modifier.weight(1f) + ) { + Text( + text = "$percentage%", + fontSize = 12.sp, + fontWeight = FontWeight.Bold, + color = CargillBlack + ) + Spacer(modifier = Modifier.height(4.dp)) + Box( + modifier = Modifier + .fillMaxHeight(percentage.coerceIn(5, 100).toFloat() / 120f) + .width(40.dp) + .background(barColor, shape = RoundedCornerShape(topStart = 4.dp, topEnd = 4.dp)) + ) + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = if (team == "Confiabilidade") "Confiabil." else team, + fontSize = 11.sp, + fontWeight = FontWeight.Medium, + color = Color.Gray, + textAlign = TextAlign.Center + ) + } + } + } + } + } +} + +/** + * Gráfico 2: Curva-S de Progresso do Projeto + * Compara o avanço temporal Planejado com o Realizado + */ +@Composable +fun SCurveCard(activities: List, history: List) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = Color.White), + elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), + shape = RoundedCornerShape(16.dp) + ) { + Column( + modifier = Modifier + .padding(16.dp) + .fillMaxWidth() + ) { + Text( + text = "Progresso do Projeto: Planejado vs. Realizado", + fontSize = 16.sp, + fontWeight = FontWeight.Bold, + color = CargillBlack, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .padding(bottom = 12.dp) + ) + + // Calculate start and end bounds of the project + 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 + + // 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( + modifier = Modifier + .fillMaxWidth() + .height(180.dp) + .padding(top = 8.dp, bottom = 4.dp, start = 8.dp, end = 12.dp) + ) { + val canvasWidth = size.width + val canvasHeight = size.height + + // Draw Y axis lines (0%, 25%, 50%, 75%, 100%) + val yLevels = listOf(0f, 0.25f, 0.50f, 0.75f, 1.00f) + yLevels.forEach { yLevel -> + val y = canvasHeight * (1f - yLevel) + + // Grid lines + drawLine( + color = Color(0xFFE0E0E0), + start = Offset(40f, y), + end = Offset(canvasWidth, y), + strokeWidth = 1f + ) + + // Y axis label + drawContext.canvas.nativeCanvas.drawText( + "${(yLevel * 100).toInt()}%", + 5f, + y + 10f, + android.graphics.Paint().apply { + color = android.graphics.Color.GRAY + textSize = 30f + textAlign = android.graphics.Paint.Align.LEFT + } + ) + } + + // X axis points coordinates + val stepX = (canvasWidth - 60f) / (timelineSteps - 1) + val pointsX = (0 until timelineSteps).map { i -> 50f + i * stepX } + + // Draw curve: Planned (dashed grey) + val plannedPath = Path().apply { + val firstY = canvasHeight * (1f - (plannedProgressPoints[0] / 100f)) + moveTo(pointsX[0], firstY) + for (i in 1 until timelineSteps) { + val y = canvasHeight * (1f - (plannedProgressPoints[i] / 100f)) + lineTo(pointsX[i], y) + } + } + + drawPath( + path = plannedPath, + color = Color.LightGray, + style = Stroke( + width = 4f, + pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f) + ) + ) + + // Draw curve: Realized (solid green) + val realizedPath = Path().apply { + val firstY = canvasHeight * (1f - (realizedProgressPoints[0] / 100f)) + moveTo(pointsX[0], firstY) + for (i in 1 until timelineSteps) { + val y = canvasHeight * (1f - (realizedProgressPoints[i] / 100f)) + lineTo(pointsX[i], y) + } + } + + drawPath( + path = realizedPath, + color = Color(0xFF4CAF50), + style = Stroke(width = 5f) + ) + + // Draw X Axis dates + val axisSdf = SimpleDateFormat("MMM d", Locale.US) + timelineDates.forEachIndexed { index, date -> + val label = axisSdf.format(date) + val x = pointsX[index] + drawContext.canvas.nativeCanvas.drawText( + label, + x, + canvasHeight + 3f, + android.graphics.Paint().apply { + color = android.graphics.Color.GRAY + textSize = 28f + textAlign = android.graphics.Paint.Align.CENTER + } + ) + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + // Legend Row + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.Center, + verticalAlignment = Alignment.CenterVertically + ) { + // Planned Legend + Box( + modifier = Modifier + .size(width = 16.dp, height = 3.dp) + .background(Color.LightGray) + ) + Spacer(modifier = Modifier.width(6.dp)) + Text(text = "Planejado", fontSize = 12.sp, color = Color.Gray) + + Spacer(modifier = Modifier.width(24.dp)) + + // Realized Legend + Box( + modifier = Modifier + .size(width = 16.dp, height = 3.dp) + .background(Color(0xFF4CAF50)) + ) + Spacer(modifier = Modifier.width(6.dp)) + Text(text = "Realizado", fontSize = 12.sp, color = Color.Gray) + } + } + } +} + +/** + * Gráfico 3: OSs Atrasadas por TAG (Ativo) + * Lista as TAGs com maior volume de OSs pendentes e com prazo vencido + */ +@Composable +fun OverdueByTagCard(activities: List) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = Color.White), + elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), + shape = RoundedCornerShape(16.dp) + ) { + Column( + modifier = Modifier + .padding(16.dp) + .fillMaxWidth() + ) { + Text( + text = "Atrasados por TAG", + fontSize = 16.sp, + fontWeight = FontWeight.Bold, + color = CargillBlack, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .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()) { + Box( + modifier = Modifier + .fillMaxWidth() + .height(100.dp), + contentAlignment = Alignment.Center + ) { + Text( + text = "Parabéns! Nenhuma OS atrasada no momento.", + color = Color(0xFF2E7D32), + fontWeight = FontWeight.Medium, + fontSize = 13.sp + ) + } + } 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 maxCount = displayList.maxOfOrNull { it.second } ?: 1 + + Column( + verticalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth() + ) { + displayList.forEachIndexed { index, (tag, count) -> + val barColor = when (index) { + 0 -> Color(0xFF4CAF50) // Green + 1 -> Color(0xFF2196F3) // Blue + 2 -> Color(0xFFFF9800) // Orange + 3 -> Color(0xFFFFC107) // Amber/Yellow + else -> Color(0xFF9C27B0) // Purple + } + + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth() + ) { + // TAG Name + Text( + text = tag, + fontSize = 12.sp, + fontWeight = FontWeight.Bold, + color = CargillBlack, + modifier = Modifier.width(90.dp), + maxLines = 1 + ) + + // Bar Container + Box( + modifier = Modifier + .weight(1f) + .height(18.dp) + .background(Color(0xFFEEEEEE), shape = RoundedCornerShape(4.dp)) + ) { + Box( + modifier = Modifier + .fillMaxWidth(count.toFloat() / maxCount.toFloat()) + .fillMaxHeight() + .background(barColor, shape = RoundedCornerShape(4.dp)) + ) + } + + Spacer(modifier = Modifier.width(8.dp)) + + // Count number + Text( + text = count.toString(), + fontSize = 12.sp, + fontWeight = FontWeight.Bold, + color = CargillBlack, + modifier = Modifier.width(20.dp), + textAlign = TextAlign.End + ) + } + } + } + } + } + } +} 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 b1ecef1..407c158 100644 --- a/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt +++ b/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt @@ -76,6 +76,14 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View initialValue = emptyList() ) + // All history entries from repository + val allHistoryState: StateFlow> = repository.allHistory + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5000), + initialValue = emptyList() + ) + // Filtered activities list val filteredActivities: StateFlow> = combine( repository.allActivities, diff --git a/app/src/test/java/com/example/ExampleUnitTest.kt b/app/src/test/java/com/example/ExampleUnitTest.kt index 9f5a1b5..b7aa2fd 100644 --- a/app/src/test/java/com/example/ExampleUnitTest.kt +++ b/app/src/test/java/com/example/ExampleUnitTest.kt @@ -132,4 +132,46 @@ class ExampleUnitTest { val os5Remote = newRemoteLogs.filter { it.numeroOs == "OS5" }.maxByOrNull { it.timestamp }!! assertFalse(os5Local.timestamp >= os5Remote.timestamp) } + + @Test + fun testDashboardCalculations() { + val activities = listOf( + com.example.data.model.MaintenanceActivity( + numeroOs = "OS1", descricao = "Mec 1", setor = "Geral", equipe = "Mecânica", recurso = "A", + dataInicio = "01/08/2026", dataFim = "10/08/2026", percentualExecucao = 100, tag = "TAG1" + ), + com.example.data.model.MaintenanceActivity( + numeroOs = "OS2", descricao = "Mec 2", setor = "Geral", equipe = "Mecânica", recurso = "A", + dataInicio = "01/08/2026", dataFim = "10/08/2026", percentualExecucao = 50, tag = "TAG1" + ), + com.example.data.model.MaintenanceActivity( + numeroOs = "OS3", descricao = "Elec 1", setor = "Geral", equipe = "Elétrica", recurso = "B", + dataInicio = "01/08/2026", dataFim = "10/08/2026", percentualExecucao = 100, tag = "TAG2" + ) + ) + + // 1. Team productivity (ratio of completed 100% OSs over total OSs per team) + val mecActivities = activities.filter { it.equipe == "Mecânica" } + val mecTotal = mecActivities.size + val mecCompleted = mecActivities.count { it.percentualExecucao >= 100 } + val mecRatio = if (mecTotal > 0) (mecCompleted.toFloat() / mecTotal.toFloat() * 100f).toInt() else 0 + assertEquals(50, mecRatio) + + val elecActivities = activities.filter { it.equipe == "Elétrica" } + val elecTotal = elecActivities.size + val elecCompleted = elecActivities.count { it.percentualExecucao >= 100 } + val elecRatio = if (elecTotal > 0) (elecCompleted.toFloat() / elecTotal.toFloat() * 100f).toInt() else 0 + assertEquals(100, elecRatio) + + // 2. Overdue calculation + val referenceDate = parseDateOnly("15/08/2026")!! + val overdueActivities = activities.filter { act -> + val isNotCompleted = act.percentualExecucao < 100 + val endDate = parseDateOnly(act.dataFim) + isNotCompleted && endDate != null && endDate.before(referenceDate) + } + assertEquals(1, overdueActivities.size) + assertEquals("OS2", overdueActivities.first().numeroOs) + assertEquals("TAG1", overdueActivities.first().tag) + } }