refactor: update activity sorting logic and expand dashboard screen functionality with new state management and media handling

This commit is contained in:
Jhony Cesar
2026-08-06 00:11:34 -04:00
parent 4595e81798
commit 9dcb30fd24
3 changed files with 910 additions and 780 deletions

View File

@@ -8,12 +8,18 @@ import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.core.* import androidx.compose.animation.core.*
import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable import androidx.compose.foundation.focusable
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInParent
import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties import androidx.compose.ui.window.DialogProperties
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
@@ -1249,56 +1255,6 @@ fun EditActivityBottomSheet(
var findingText by remember { mutableStateOf("") } var findingText by remember { mutableStateOf("") }
var activeFindingForDialog by remember { mutableStateOf<com.example.data.model.OSFinding?>(null) } var activeFindingForDialog by remember { mutableStateOf<com.example.data.model.OSFinding?>(null) }
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
BackHandler(enabled = true) {
if (isImeVisible) {
focusManager.clearFocus(force = true)
keyboardController?.hide()
} else {
onDismiss()
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black.copy(alpha = 0.5f))
.clickable(onClick = onDismiss),
contentAlignment = Alignment.BottomCenter
) {
Card(
modifier = Modifier
.fillMaxWidth()
.clickable(enabled = false) {}, // Prevent card content click from dismissing
shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
colors = CardDefaults.cardColors(containerColor = Color.White)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 12.dp)
.imePadding()
.navigationBarsPadding()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// Top Drag Handle Indicator
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
Box(
modifier = Modifier
.width(32.dp)
.height(4.dp)
.clip(RoundedCornerShape(2.dp))
.background(Color(0xFFE0E0E0))
)
}
var progressValue by remember(activity) { mutableStateOf(activity.percentualExecucao.toFloat()) } var progressValue by remember(activity) { mutableStateOf(activity.percentualExecucao.toFloat()) }
var observationText by remember(activity) { mutableStateOf(activity.observacoes ?: findings.find { it.tipo == "OBS" }?.descricao ?: "") } var observationText by remember(activity) { mutableStateOf(activity.observacoes ?: findings.find { it.tipo == "OBS" }?.descricao ?: "") }
var showEditObsDialog by remember { mutableStateOf(false) } var showEditObsDialog by remember { mutableStateOf(false) }
@@ -1373,6 +1329,59 @@ fun EditActivityBottomSheet(
} }
} }
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
BackHandler(enabled = true) {
if (isImeVisible) {
focusManager.clearFocus(force = true)
keyboardController?.hide()
} else {
onDismiss()
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black.copy(alpha = 0.5f))
.clickable(onClick = onDismiss),
contentAlignment = Alignment.BottomCenter
) {
Card(
modifier = Modifier
.fillMaxWidth()
.clickable(enabled = false) {}, // Prevent card content click from dismissing
shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
colors = CardDefaults.cardColors(containerColor = Color.White)
) {
var isInlineSaveButtonVisible by remember { mutableStateOf(true) }
Box(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 12.dp)
.imePadding()
.navigationBarsPadding()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// Top Drag Handle Indicator
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
Box(
modifier = Modifier
.width(32.dp)
.height(4.dp)
.clip(RoundedCornerShape(2.dp))
.background(Color(0xFFE0E0E0))
)
}
// Header: OS + Close // Header: OS + Close
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@@ -1440,7 +1449,75 @@ fun EditActivityBottomSheet(
} }
} }
// Card Interativo de Observação da OS // Slider Progress Update Panel (Percentual de Execução)
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Percentual de Execução",
fontWeight = FontWeight.Bold,
fontSize = 14.sp,
color = BrandBlack
)
Text(
text = "${progressValue.toInt()}%",
fontWeight = FontWeight.Black,
fontSize = 18.sp,
color = if (progressValue >= 100) BrandGreen else StatusBlue
)
}
Slider(
value = progressValue,
onValueChange = { progressValue = it },
valueRange = 0f..100f,
steps = 19, // 5% increments
enabled = currentUser != null,
colors = SliderDefaults.colors(
thumbColor = if (progressValue >= 100) BrandGreen else StatusBlue,
activeTrackColor = if (progressValue >= 100) BrandGreen else StatusBlue
)
)
// Quick jump buttons for field speed
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Button(
onClick = { progressValue = 0f },
modifier = Modifier.weight(1f).height(36.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFECEFF1)),
contentPadding = PaddingValues(0.dp),
enabled = currentUser != null
) {
Text("0% (Zerar)", color = StatusGrey, fontSize = 11.sp, fontWeight = FontWeight.Bold)
}
Button(
onClick = { progressValue = 50f },
modifier = Modifier.weight(1f).height(36.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFE3F2FD)),
contentPadding = PaddingValues(0.dp),
enabled = currentUser != null
) {
Text("50% (Metade)", color = StatusBlue, fontSize = 11.sp, fontWeight = FontWeight.Bold)
}
Button(
onClick = { progressValue = 100f },
modifier = Modifier.weight(1f).height(36.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFE8F5E9)),
contentPadding = PaddingValues(0.dp),
enabled = currentUser != null
) {
Text("100% (Concluir)", color = BrandGreen, fontSize = 11.sp, fontWeight = FontWeight.Bold)
}
}
}
// Card Interativo de Observação da OS (Posicionado após Percentual de Execução)
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@@ -1530,74 +1607,6 @@ fun EditActivityBottomSheet(
) )
} }
// Slider Progress Update Panel
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Percentual de Execução",
fontWeight = FontWeight.Bold,
fontSize = 14.sp,
color = BrandBlack
)
Text(
text = "${progressValue.toInt()}%",
fontWeight = FontWeight.Black,
fontSize = 18.sp,
color = if (progressValue >= 100) BrandGreen else StatusBlue
)
}
Slider(
value = progressValue,
onValueChange = { progressValue = it },
valueRange = 0f..100f,
steps = 19, // 5% increments
enabled = currentUser != null,
colors = SliderDefaults.colors(
thumbColor = if (progressValue >= 100) BrandGreen else StatusBlue,
activeTrackColor = if (progressValue >= 100) BrandGreen else StatusBlue
)
)
// Quick jump buttons for field speed
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Button(
onClick = { progressValue = 0f },
modifier = Modifier.weight(1f).height(36.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFECEFF1)),
contentPadding = PaddingValues(0.dp),
enabled = currentUser != null
) {
Text("0% (Zerar)", color = StatusGrey, fontSize = 11.sp, fontWeight = FontWeight.Bold)
}
Button(
onClick = { progressValue = 50f },
modifier = Modifier.weight(1f).height(36.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFE3F2FD)),
contentPadding = PaddingValues(0.dp),
enabled = currentUser != null
) {
Text("50% (Metade)", color = StatusBlue, fontSize = 11.sp, fontWeight = FontWeight.Bold)
}
Button(
onClick = { progressValue = 100f },
modifier = Modifier.weight(1f).height(36.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFE8F5E9)),
contentPadding = PaddingValues(0.dp),
enabled = currentUser != null
) {
Text("100% (Concluir)", color = BrandGreen, fontSize = 11.sp, fontWeight = FontWeight.Bold)
}
}
}
// 🛡️ Achados de Segurança Section // 🛡️ Achados de Segurança Section
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
HorizontalDivider(color = Color(0xFFF1F1F1)) HorizontalDivider(color = Color(0xFFF1F1F1))
@@ -2021,7 +2030,16 @@ fun EditActivityBottomSheet(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.height(48.dp) .height(48.dp)
.testTag("save_progress_button"), .testTag("save_progress_button")
.onGloballyPositioned { coordinates ->
val parentLayoutCoordinates = coordinates.parentLayoutCoordinates
if (parentLayoutCoordinates != null) {
val topInParent = coordinates.positionInParent().y
val bottomInParent = topInParent + coordinates.size.height
val parentHeight = parentLayoutCoordinates.size.height
isInlineSaveButtonVisible = topInParent < parentHeight && bottomInParent > 0
}
},
colors = ButtonDefaults.buttonColors(containerColor = BrandGreen), colors = ButtonDefaults.buttonColors(containerColor = BrandGreen),
shape = RoundedCornerShape(10.dp) shape = RoundedCornerShape(10.dp)
) { ) {
@@ -2131,6 +2149,52 @@ fun EditActivityBottomSheet(
// Espaçamento inferior reforçado para evitar sobreposição por botões nativos do Android // Espaçamento inferior reforçado para evitar sobreposição por botões nativos do Android
Spacer(modifier = Modifier.height(32.dp)) Spacer(modifier = Modifier.height(32.dp))
} }
// Floating Action Button (FAB) de Salvar exibido quando o botão inline de Salvar está fora da tela por rolagem
val hasEditAccess = userAccessLevel?.trim()?.lowercase().let { it == "total" || it == "editor" }
androidx.compose.animation.AnimatedVisibility(
visible = !isInlineSaveButtonVisible && currentUser != null && hasEditAccess,
enter = fadeIn() + slideInVertically { it / 2 },
exit = fadeOut() + slideOutVertically { it / 2 },
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(end = 20.dp, bottom = 24.dp)
) {
FloatingActionButton(
onClick = {
isSubmitting = true
draftAddedFindings.forEach { item ->
onAddFinding(item.first, item.second)
}
draftUpdatedFindings.forEach { entry ->
findings.find { it.id == entry.key }?.let { original ->
onUpdateFinding(original.copy(descricao = entry.value))
}
}
draftDeletedFindingIds.forEach { id ->
findings.find { it.id == id }?.let { original ->
onDeleteFinding(original)
}
}
val photoParam = if (newPhotosList.isNotEmpty()) newPhotosList.joinToString("|") else null
onUpdateProgress(progressValue.toInt(), observationText, photoParam)
onDismiss()
},
containerColor = BrandGreen,
contentColor = Color.White,
shape = RoundedCornerShape(24.dp)
) {
Row(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(Icons.Default.Save, contentDescription = "Salvar")
Spacer(modifier = Modifier.width(6.dp))
Text("Salvar Atualizações", fontWeight = FontWeight.Bold)
}
}
}
}
} }
} }
} }

View File

@@ -284,12 +284,17 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
result result
} }
// Always sort by dataInicio (start date) ascending, oldest first using dataInicioMillis O(1) // Always sort by dataInicio (start date) ascending, oldest first. OSs without start date appear at the very end.
filtered.sortedWith { a1, a2 -> filtered.sortedWith { a1, a2 ->
val p1 = a1.dataInicioMillis val p1 = if (a1.dataInicio.isNullOrBlank() || a1.dataInicioMillis == 0L) Long.MAX_VALUE else a1.dataInicioMillis
val p2 = a2.dataInicioMillis val p2 = if (a2.dataInicio.isNullOrBlank() || a2.dataInicioMillis == 0L) Long.MAX_VALUE else a2.dataInicioMillis
when { when {
p1 == Long.MAX_VALUE && p2 == Long.MAX_VALUE -> a1.numeroOs.compareTo(a2.numeroOs) p1 == Long.MAX_VALUE && p2 == Long.MAX_VALUE -> {
val f1 = a1.dataFimMillis
val f2 = a2.dataFimMillis
val endComp = f1.compareTo(f2)
if (endComp != 0) endComp else a1.numeroOs.compareTo(a2.numeroOs)
}
p1 == Long.MAX_VALUE -> 1 p1 == Long.MAX_VALUE -> 1
p2 == Long.MAX_VALUE -> -1 p2 == Long.MAX_VALUE -> -1
else -> { else -> {

View File

@@ -185,6 +185,67 @@ class ExampleRobolectricTest {
} }
} }
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
@Test
fun `test sorting OSs without start date appear at the very end of list`() {
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 actNoStart = com.example.data.model.MaintenanceActivity(
numeroOs = "OS-NO-START",
descricao = "OS without start date",
setor = "Geral",
equipe = "Mecânica",
recurso = "Sem Recurso",
dataInicio = "",
dataFim = "27/08/2026 17:00",
percentualExecucao = 0,
synced = true
)
val actValidStart = com.example.data.model.MaintenanceActivity(
numeroOs = "OS-VALID-START",
descricao = "OS with valid start date",
setor = "Geral",
equipe = "Elétrica",
recurso = "Sem Recurso",
dataInicio = "01/01/2026 08:00",
dataFim = "01/01/2026 17:00",
percentualExecucao = 0,
synced = true
)
kotlinx.coroutines.runBlocking {
db.maintenanceDao().insertActivities(listOf(actNoStart, actValidStart))
val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository)
val job = viewModel.viewModelScope.launch {
viewModel.filteredActivities.collect {}
}
Thread.sleep(200)
org.robolectric.shadows.ShadowLooper.idleMainLooper()
val list = viewModel.filteredActivities.value
assertEquals(2, list.size)
assertEquals("OS-VALID-START", list[0].numeroOs)
assertEquals("OS-NO-START", list[1].numeroOs)
job.cancel()
}
db.close()
} finally {
kotlinx.coroutines.Dispatchers.resetMain()
}
}
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
@Test @Test
fun `test analytics state calculations in ViewModel`() { fun `test analytics state calculations in ViewModel`() {