diff --git a/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt b/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt index 6141c7a..81415a6 100644 --- a/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt +++ b/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt @@ -8,12 +8,18 @@ import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts 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.foundation.BorderStroke import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.clickable 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.DialogProperties import kotlinx.coroutines.delay @@ -1249,6 +1255,80 @@ fun EditActivityBottomSheet( var findingText by remember { mutableStateOf("") } var activeFindingForDialog by remember { mutableStateOf(null) } + var progressValue by remember(activity) { mutableStateOf(activity.percentualExecucao.toFloat()) } + var observationText by remember(activity) { mutableStateOf(activity.observacoes ?: findings.find { it.tipo == "OBS" }?.descricao ?: "") } + var showEditObsDialog by remember { mutableStateOf(false) } + var tempObsText by remember(observationText) { mutableStateOf(observationText) } + + val draftAddedFindings = remember(activity) { mutableStateListOf>() } + val draftUpdatedFindings = remember(activity) { mutableStateMapOf() } + val draftDeletedFindingIds = remember(activity) { mutableStateListOf() } + + val displayFindings = remember(findings, draftAddedFindings.toList(), draftUpdatedFindings.toMap(), draftDeletedFindingIds.toList()) { + val list = findings + .filter { !draftDeletedFindingIds.contains(it.id) } + .map { f -> + if (draftUpdatedFindings.containsKey(f.id)) { + f.copy(descricao = draftUpdatedFindings[f.id]!!) + } else { + f + } + }.toMutableList() + + draftAddedFindings.forEachIndexed { index, (tipo, desc) -> + list.add( + com.example.data.model.OSFinding( + id = "draft_new_$index", + numeroOs = activity.numeroOs, + tipo = tipo, + descricao = desc, + timestamp = System.currentTimeMillis(), + responsavel = currentUser?.displayName ?: "Encarregado Campo" + ) + ) + } + list + } + + val newPhotosList = remember { mutableStateListOf() } + var tempCameraPath by remember { mutableStateOf(null) } + var selectedPhotoForViewer by remember { mutableStateOf(null) } + var isSubmitting by remember { mutableStateOf(false) } + + val activePhotos = remember(activity, history) { + val list = mutableListOf() + fun processPath(raw: String?) { + if (!raw.isNullOrBlank()) { + raw.split("|").forEach { p -> + val trimmed = p.trim() + if (trimmed.isNotBlank() && !trimmed.endsWith("_DELETED") && !list.contains(trimmed)) { + list.add(trimmed) + } + } + } + } + processPath(activity.fotoPath) + history.forEach { processPath(it.fotoPath) } + list + } + + val cameraLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.TakePicture() + ) { success -> + if (success && tempCameraPath != null) { + newPhotosList.add(tempCameraPath!!) + } + } + + val galleryLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.GetContent() + ) { uri: Uri? -> + uri?.let { + val savedPath = onSavePhotoFromUri(it) + newPhotosList.add(savedPath) + } + } + Dialog( onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false) @@ -1276,675 +1356,555 @@ fun EditActivityBottomSheet( 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 isInlineSaveButtonVisible by remember { mutableStateOf(true) } - var progressValue by remember(activity) { mutableStateOf(activity.percentualExecucao.toFloat()) } - var observationText by remember(activity) { mutableStateOf(activity.observacoes ?: findings.find { it.tipo == "OBS" }?.descricao ?: "") } - var showEditObsDialog by remember { mutableStateOf(false) } - var tempObsText by remember(observationText) { mutableStateOf(observationText) } - - val draftAddedFindings = remember(activity) { mutableStateListOf>() } - val draftUpdatedFindings = remember(activity) { mutableStateMapOf() } - val draftDeletedFindingIds = remember(activity) { mutableStateListOf() } - - val displayFindings = remember(findings, draftAddedFindings.toList(), draftUpdatedFindings.toMap(), draftDeletedFindingIds.toList()) { - val list = findings - .filter { !draftDeletedFindingIds.contains(it.id) } - .map { f -> - if (draftUpdatedFindings.containsKey(f.id)) { - f.copy(descricao = draftUpdatedFindings[f.id]!!) - } else { - f - } - }.toMutableList() - - draftAddedFindings.forEachIndexed { index, (tipo, desc) -> - list.add( - com.example.data.model.OSFinding( - id = "draft_new_$index", - numeroOs = activity.numeroOs, - tipo = tipo, - descricao = desc, - timestamp = System.currentTimeMillis(), - responsavel = currentUser?.displayName ?: "Encarregado Campo" - ) - ) - } - list - } - - val newPhotosList = remember { mutableStateListOf() } - var tempCameraPath by remember { mutableStateOf(null) } - var selectedPhotoForViewer by remember { mutableStateOf(null) } - var isSubmitting by remember { mutableStateOf(false) } - - val activePhotos = remember(activity, history) { - val list = mutableListOf() - fun processPath(raw: String?) { - if (!raw.isNullOrBlank()) { - raw.split("|").forEach { p -> - val trimmed = p.trim() - if (trimmed.isNotBlank() && !trimmed.endsWith("_DELETED") && !list.contains(trimmed)) { - list.add(trimmed) - } - } - } - } - processPath(activity.fotoPath) - history.forEach { processPath(it.fotoPath) } - list - } - - val cameraLauncher = rememberLauncherForActivityResult( - contract = ActivityResultContracts.TakePicture() - ) { success -> - if (success && tempCameraPath != null) { - newPhotosList.add(tempCameraPath!!) - } - } - - val galleryLauncher = rememberLauncherForActivityResult( - contract = ActivityResultContracts.GetContent() - ) { uri: Uri? -> - uri?.let { - val savedPath = onSavePhotoFromUri(it) - newPhotosList.add(savedPath) - } - } - - // Header: OS + Close - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Column { - Text( - text = "ATUALIZAR ORDEM DE SERVIÇO", - fontSize = 11.sp, - fontWeight = FontWeight.Bold, - color = StatusGrey - ) - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp) - ) { - Text( - text = activity.numeroOs, - fontSize = 20.sp, - fontWeight = FontWeight.Black, - color = BrandBlack - ) - if (activity.tag.isNotBlank()) { - Box( - modifier = Modifier - .clip(RoundedCornerShape(4.dp)) - .background(Color(0xFFE3F2FD)) - .padding(horizontal = 6.dp, vertical = 2.dp) - ) { - Text( - text = activity.tag, - fontSize = 12.sp, - fontWeight = FontWeight.Bold, - color = Color(0xFF1976D2) - ) - } - } - } - } - - IconButton(onClick = onDismiss) { - Icon(Icons.Default.Close, contentDescription = "Fechar") - } - } - - // Description Box - Card( - colors = CardDefaults.cardColors(containerColor = BackgroundLight), - shape = RoundedCornerShape(8.dp) - ) { - Column(modifier = Modifier.padding(12.dp)) { - Text( - text = activity.formattedDescricao, - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - color = BrandBlack - ) - Spacer(modifier = Modifier.height(8.dp)) - Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { - Text("Setor: ${activity.setor}", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = BrandGreen) - Text("Equipe: ${activity.equipe}", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = StatusBlue) - Text("Recurso: ${activity.recurso}", fontSize = 11.sp, color = StatusGrey) - } - } - } - - // Card Interativo de Observação da OS - Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp) - ) { - Icon(Icons.Default.Comment, contentDescription = "Observação", tint = Color(0xFF6A1B9A), modifier = Modifier.size(18.dp)) - Text( - text = "Observação da OS", - fontWeight = FontWeight.Bold, - fontSize = 14.sp, - color = BrandBlack - ) - } - } - - Card( - colors = CardDefaults.cardColors(containerColor = Color(0xFFF3E5F5)), - border = BorderStroke(1.dp, Color(0xFFE1BEE7)), - shape = RoundedCornerShape(8.dp), - modifier = Modifier.fillMaxWidth() - ) { - Row( - modifier = Modifier.padding(10.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween - ) { - Text( - text = if (observationText.isBlank()) "Nenhuma observação registrada" else observationText, - fontSize = 12.sp, - fontWeight = if (observationText.isBlank()) FontWeight.Normal else FontWeight.Medium, - color = if (observationText.isBlank()) Color.Gray else BrandBlack, - modifier = Modifier.weight(1f) - ) - if (currentUser != null) { - IconButton( - onClick = { - tempObsText = observationText - showEditObsDialog = true - }, - modifier = Modifier.size(28.dp) - ) { - Icon(Icons.Default.Edit, contentDescription = "Editar Observação", tint = Color(0xFF6A1B9A), modifier = Modifier.size(16.dp)) - } - } - } - } - } - - if (showEditObsDialog) { - AlertDialog( - onDismissRequest = { showEditObsDialog = false }, - title = { - Text("Editar Observação da OS", fontWeight = FontWeight.Bold, fontSize = 16.sp) - }, - text = { - OutlinedTextField( - value = tempObsText, - onValueChange = { tempObsText = it }, - placeholder = { Text("Digite a observação da OS...", fontSize = 13.sp) }, - modifier = Modifier - .fillMaxWidth() - .height(100.dp), - maxLines = 4 - ) - }, - confirmButton = { - Button( - onClick = { - observationText = tempObsText.trim() - showEditObsDialog = false - }, - colors = ButtonDefaults.buttonColors(containerColor = BrandGreen) - ) { - Text("Confirmar") - } - }, - dismissButton = { - TextButton(onClick = { showEditObsDialog = false }) { - Text("Cancelar") - } - } - ) - } - - // 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 - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - HorizontalDivider(color = Color(0xFFF1F1F1)) - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp) - ) { - Icon(Icons.Default.Security, contentDescription = "Segurança", tint = Color(0xFFD84315), modifier = Modifier.size(18.dp)) - Text( - text = "Achados de Segurança (${displayFindings.count { it.tipo == "SEGURANCA" }})", - fontWeight = FontWeight.Bold, - fontSize = 14.sp, - color = BrandBlack - ) - } - if (currentUser != null) { - OutlinedButton( - onClick = { - activeFindingForDialog = null - dialogTipo = "SEGURANCA" - findingText = "" - showFindingDialog = true - }, - contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp), - modifier = Modifier.height(32.dp) - ) { - Icon(Icons.Default.Add, contentDescription = "Adicionar Achado", modifier = Modifier.size(14.dp)) - Spacer(modifier = Modifier.width(4.dp)) - Text("Novo Achado", fontSize = 11.sp) - } - } - } - - val segurancaFindings = displayFindings.filter { it.tipo == "SEGURANCA" } - if (segurancaFindings.isEmpty()) { - Text( - text = "Nenhum achado de segurança registrado para esta OS.", - fontSize = 11.sp, - color = Color.Gray - ) - } else { - Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { - segurancaFindings.forEach { finding -> - FindingItemCard( - finding = finding, - canEdit = currentUser != null, - onEdit = { - activeFindingForDialog = finding - dialogTipo = finding.tipo - findingText = finding.descricao - showFindingDialog = true - }, - onDelete = { - if (finding.id.startsWith("draft_new_")) { - val idx = finding.id.removePrefix("draft_new_").toIntOrNull() - if (idx != null && idx in draftAddedFindings.indices) { - draftAddedFindings.removeAt(idx) - } - } else { - draftDeletedFindingIds.add(finding.id) - } - } - ) - } - } - } - } - - // 🔧 Achados de Manutenção Section - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - HorizontalDivider(color = Color(0xFFF1F1F1)) - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp) - ) { - Icon(Icons.Default.Build, contentDescription = "Manutenção", tint = Color(0xFF0277BD), modifier = Modifier.size(18.dp)) - Text( - text = "Achados de Manutenção (${displayFindings.count { it.tipo == "MANUTENCAO" }})", - fontWeight = FontWeight.Bold, - fontSize = 14.sp, - color = BrandBlack - ) - } - if (currentUser != null) { - OutlinedButton( - onClick = { - activeFindingForDialog = null - dialogTipo = "MANUTENCAO" - findingText = "" - showFindingDialog = true - }, - contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp), - modifier = Modifier.height(32.dp) - ) { - Icon(Icons.Default.Add, contentDescription = "Adicionar Achado", modifier = Modifier.size(14.dp)) - Spacer(modifier = Modifier.width(4.dp)) - Text("Novo Achado", fontSize = 11.sp) - } - } - } - - val manutencaoFindings = displayFindings.filter { it.tipo == "MANUTENCAO" } - if (manutencaoFindings.isEmpty()) { - Text( - text = "Nenhum achado de manutenção registrado para esta OS.", - fontSize = 11.sp, - color = Color.Gray - ) - } else { - Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { - manutencaoFindings.forEach { finding -> - FindingItemCard( - finding = finding, - canEdit = currentUser != null, - onEdit = { - activeFindingForDialog = finding - dialogTipo = finding.tipo - findingText = finding.descricao - showFindingDialog = true - }, - onDelete = { - if (finding.id.startsWith("draft_new_")) { - val idx = finding.id.removePrefix("draft_new_").toIntOrNull() - if (idx != null && idx in draftAddedFindings.indices) { - draftAddedFindings.removeAt(idx) - } - } else { - draftDeletedFindingIds.add(finding.id) - } - } - ) - } - } - } - } - - // Photo Attachment & Horizontal Gallery Section - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - HorizontalDivider(color = Color(0xFFF1F1F1)) - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text( - text = "Fotos de Campo da OS", - fontWeight = FontWeight.Bold, - fontSize = 14.sp, - color = BrandBlack - ) - if (newPhotosList.isNotEmpty()) { - Text( - text = "${newPhotosList.size} foto(s) pendente(s)", - fontSize = 11.sp, - fontWeight = FontWeight.Bold, - color = BrandGreen - ) - } - } - - // Action buttons: Camera & Gallery - Row( - horizontalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.fillMaxWidth() - ) { - OutlinedButton( - onClick = { - if (currentUser != null) { - val (uri, path) = onCreateCameraUri() - tempCameraPath = path - cameraLauncher.launch(uri) - } - }, - enabled = currentUser != null, - modifier = Modifier.weight(1f) - ) { - Icon(Icons.Default.CameraAlt, contentDescription = "Tirar Foto", modifier = Modifier.size(16.dp)) - Spacer(modifier = Modifier.width(4.dp)) - Text("Tirar Foto", fontSize = 12.sp) - } - - OutlinedButton( - onClick = { - if (currentUser != null) { - galleryLauncher.launch("image/*") - } - }, - enabled = currentUser != null, - modifier = Modifier.weight(1f) - ) { - Icon(Icons.Default.PhotoLibrary, contentDescription = "Galeria", modifier = Modifier.size(16.dp)) - Spacer(modifier = Modifier.width(4.dp)) - Text("Galeria", fontSize = 12.sp) - } - } - - // Horizontal Gallery (LazyRow) - val displayPhotos = remember(activePhotos, newPhotosList.toList()) { - (newPhotosList + activePhotos).distinct() - } - - if (displayPhotos.isNotEmpty()) { - LazyRow( - horizontalArrangement = Arrangement.spacedBy(8.dp), + Box(modifier = Modifier.fillMaxWidth()) { + Column( modifier = Modifier .fillMaxWidth() - .padding(vertical = 4.dp) + .padding(horizontal = 20.dp, vertical = 12.dp) + .imePadding() + .navigationBarsPadding() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(16.dp) ) { - items(displayPhotos) { photoPath -> - val isNew = newPhotosList.contains(photoPath) - Card( + // Top Drag Handle Indicator + Box( + modifier = Modifier.fillMaxWidth(), + contentAlignment = Alignment.Center + ) { + Box( modifier = Modifier - .size(88.dp) - .clickable { selectedPhotoForViewer = photoPath }, - shape = RoundedCornerShape(8.dp), - border = BorderStroke(2.dp, if (isNew) BrandGreen else Color(0xFFE0E0E0)) - ) { - Box(modifier = Modifier.fillMaxSize()) { - coil.compose.AsyncImage( - model = photoPath, - contentDescription = "Miniatura da foto", - modifier = Modifier.fillMaxSize(), - contentScale = androidx.compose.ui.layout.ContentScale.Crop - ) - if (isNew) { - // Badge NOVA - Box( - modifier = Modifier - .align(Alignment.TopStart) - .background(BrandGreen) - .padding(horizontal = 4.dp, vertical = 2.dp) - ) { - Text("NOVA", color = Color.White, fontSize = 8.sp, fontWeight = FontWeight.Bold) - } + .width(32.dp) + .height(4.dp) + .clip(RoundedCornerShape(2.dp)) + .background(Color(0xFFE0E0E0)) + ) + } - // Close 'X' button to remove from draft - Box( - modifier = Modifier - .align(Alignment.TopEnd) - .padding(2.dp) - .size(20.dp) - .clip(CircleShape) - .background(Color.Black.copy(alpha = 0.65f)) - .clickable { newPhotosList.remove(photoPath) }, - contentAlignment = Alignment.Center - ) { - Icon( - imageVector = Icons.Default.Close, - contentDescription = "Remover Rascunho", - tint = Color.White, - modifier = Modifier.size(12.dp) - ) + // Header: OS + Close + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column { + Text( + text = "ATUALIZAR ORDEM DE SERVIÇO", + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + color = StatusGrey + ) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + Text( + text = activity.numeroOs, + fontSize = 20.sp, + fontWeight = FontWeight.Black, + color = BrandBlack + ) + if (activity.tag.isNotBlank()) { + Box( + modifier = Modifier + .clip(RoundedCornerShape(4.dp)) + .background(Color(0xFFE3F2FD)) + .padding(horizontal = 6.dp, vertical = 2.dp) + ) { + Text( + text = activity.tag, + fontSize = 12.sp, + fontWeight = FontWeight.Bold, + color = Color(0xFF1976D2) + ) + } + } + } + } + + IconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Fechar") + } + } + + // Description Box + Card( + colors = CardDefaults.cardColors(containerColor = BackgroundLight), + shape = RoundedCornerShape(8.dp) + ) { + Column(modifier = Modifier.padding(12.dp)) { + Text( + text = activity.formattedDescricao, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = BrandBlack + ) + Spacer(modifier = Modifier.height(8.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { + Text("Setor: ${activity.setor}", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = BrandGreen) + Text("Equipe: ${activity.equipe}", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = StatusBlue) + Text("Recurso: ${activity.recurso}", fontSize = 11.sp, color = StatusGrey) + } + } + } + + // 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)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) + ) { + Icon(Icons.Default.Comment, contentDescription = "Observação", tint = Color(0xFF6A1B9A), modifier = Modifier.size(18.dp)) + Text( + text = "Observação da OS", + fontWeight = FontWeight.Bold, + fontSize = 14.sp, + color = BrandBlack + ) + } + } + + Card( + colors = CardDefaults.cardColors(containerColor = Color(0xFFF3E5F5)), + border = BorderStroke(1.dp, Color(0xFFE1BEE7)), + shape = RoundedCornerShape(8.dp), + modifier = Modifier.fillMaxWidth() + ) { + Row( + modifier = Modifier.padding(10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Text( + text = if (observationText.isBlank()) "Nenhuma observação registrada" else observationText, + fontSize = 12.sp, + fontWeight = if (observationText.isBlank()) FontWeight.Normal else FontWeight.Medium, + color = if (observationText.isBlank()) Color.Gray else BrandBlack, + modifier = Modifier.weight(1f) + ) + if (currentUser != null) { + IconButton( + onClick = { + tempObsText = observationText + showEditObsDialog = true + }, + modifier = Modifier.size(28.dp) + ) { + Icon(Icons.Default.Edit, contentDescription = "Editar Observação", tint = Color(0xFF6A1B9A), modifier = Modifier.size(16.dp)) + } + } + } + } + } + + if (showEditObsDialog) { + AlertDialog( + onDismissRequest = { showEditObsDialog = false }, + title = { + Text("Editar Observação da OS", fontWeight = FontWeight.Bold, fontSize = 16.sp) + }, + text = { + OutlinedTextField( + value = tempObsText, + onValueChange = { tempObsText = it }, + placeholder = { Text("Digite a observação da OS...", fontSize = 13.sp) }, + modifier = Modifier + .fillMaxWidth() + .height(100.dp), + maxLines = 4 + ) + }, + confirmButton = { + Button( + onClick = { + observationText = tempObsText.trim() + showEditObsDialog = false + }, + colors = ButtonDefaults.buttonColors(containerColor = BrandGreen) + ) { + Text("Confirmar") + } + }, + dismissButton = { + TextButton(onClick = { showEditObsDialog = false }) { + Text("Cancelar") + } + } + ) + } + + // 🛡️ Achados de Segurança Section + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + HorizontalDivider(color = Color(0xFFF1F1F1)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) + ) { + Icon(Icons.Default.Security, contentDescription = "Segurança", tint = Color(0xFFD84315), modifier = Modifier.size(18.dp)) + Text( + text = "Achados de Segurança (${displayFindings.count { it.tipo == "SEGURANCA" }})", + fontWeight = FontWeight.Bold, + fontSize = 14.sp, + color = BrandBlack + ) + } + if (currentUser != null) { + OutlinedButton( + onClick = { + activeFindingForDialog = null + dialogTipo = "SEGURANCA" + findingText = "" + showFindingDialog = true + }, + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp), + modifier = Modifier.height(32.dp) + ) { + Icon(Icons.Default.Add, contentDescription = "Adicionar Achado", modifier = Modifier.size(14.dp)) + Spacer(modifier = Modifier.width(4.dp)) + Text("Novo Achado", fontSize = 11.sp) + } + } + } + + val segurancaFindings = displayFindings.filter { it.tipo == "SEGURANCA" } + if (segurancaFindings.isEmpty()) { + Text( + text = "Nenhum achado de segurança registrado para esta OS.", + fontSize = 11.sp, + color = Color.Gray + ) + } else { + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + segurancaFindings.forEach { finding -> + FindingItemCard( + finding = finding, + canEdit = currentUser != null, + onEdit = { + activeFindingForDialog = finding + dialogTipo = finding.tipo + findingText = finding.descricao + showFindingDialog = true + }, + onDelete = { + if (finding.id.startsWith("draft_new_")) { + val idx = finding.id.removePrefix("draft_new_").toIntOrNull() + if (idx != null && idx in draftAddedFindings.indices) { + draftAddedFindings.removeAt(idx) + } + } else { + draftDeletedFindingIds.add(finding.id) + } + } + ) + } + } + } + } + + // 🔧 Achados de Manutenção Section + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + HorizontalDivider(color = Color(0xFFF1F1F1)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) + ) { + Icon(Icons.Default.Build, contentDescription = "Manutenção", tint = Color(0xFF0277BD), modifier = Modifier.size(18.dp)) + Text( + text = "Achados de Manutenção (${displayFindings.count { it.tipo == "MANUTENCAO" }})", + fontWeight = FontWeight.Bold, + fontSize = 14.sp, + color = BrandBlack + ) + } + if (currentUser != null) { + OutlinedButton( + onClick = { + activeFindingForDialog = null + dialogTipo = "MANUTENCAO" + findingText = "" + showFindingDialog = true + }, + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp), + modifier = Modifier.height(32.dp) + ) { + Icon(Icons.Default.Add, contentDescription = "Adicionar Achado", modifier = Modifier.size(14.dp)) + Spacer(modifier = Modifier.width(4.dp)) + Text("Novo Achado", fontSize = 11.sp) + } + } + } + + val manutencaoFindings = displayFindings.filter { it.tipo == "MANUTENCAO" } + if (manutencaoFindings.isEmpty()) { + Text( + text = "Nenhum achado de manutenção registrado para esta OS.", + fontSize = 11.sp, + color = Color.Gray + ) + } else { + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + manutencaoFindings.forEach { finding -> + FindingItemCard( + finding = finding, + canEdit = currentUser != null, + onEdit = { + activeFindingForDialog = finding + dialogTipo = finding.tipo + findingText = finding.descricao + showFindingDialog = true + }, + onDelete = { + if (finding.id.startsWith("draft_new_")) { + val idx = finding.id.removePrefix("draft_new_").toIntOrNull() + if (idx != null && idx in draftAddedFindings.indices) { + draftAddedFindings.removeAt(idx) + } + } else { + draftDeletedFindingIds.add(finding.id) + } + } + ) + } + } + } + } + + // Photo Attachment & Horizontal Gallery Section + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + HorizontalDivider(color = Color(0xFFF1F1F1)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = "Fotos de Campo da OS", + fontWeight = FontWeight.Bold, + fontSize = 14.sp, + color = BrandBlack + ) + if (newPhotosList.isNotEmpty()) { + Text( + text = "${newPhotosList.size} foto(s) pendente(s)", + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + color = BrandGreen + ) + } + } + + // Action buttons: Camera & Gallery + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.fillMaxWidth() + ) { + OutlinedButton( + onClick = { + if (currentUser != null) { + val (uri, path) = onCreateCameraUri() + tempCameraPath = path + cameraLauncher.launch(uri) + } + }, + enabled = currentUser != null, + modifier = Modifier.weight(1f) + ) { + Icon(Icons.Default.CameraAlt, contentDescription = "Tirar Foto", modifier = Modifier.size(16.dp)) + Spacer(modifier = Modifier.width(4.dp)) + Text("Tirar Foto", fontSize = 12.sp) + } + + OutlinedButton( + onClick = { + if (currentUser != null) { + galleryLauncher.launch("image/*") + } + }, + enabled = currentUser != null, + modifier = Modifier.weight(1f) + ) { + Icon(Icons.Default.PhotoLibrary, contentDescription = "Galeria", modifier = Modifier.size(16.dp)) + Spacer(modifier = Modifier.width(4.dp)) + Text("Galeria", fontSize = 12.sp) + } + } + + // Horizontal Gallery (LazyRow) + val displayPhotos = remember(activePhotos, newPhotosList.toList()) { + (newPhotosList + activePhotos).distinct() + } + + if (displayPhotos.isNotEmpty()) { + LazyRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 4.dp) + ) { + items(displayPhotos) { photoPath -> + val isNew = newPhotosList.contains(photoPath) + Card( + modifier = Modifier + .size(88.dp) + .clickable { selectedPhotoForViewer = photoPath }, + shape = RoundedCornerShape(8.dp), + border = BorderStroke(2.dp, if (isNew) BrandGreen else Color(0xFFE0E0E0)) + ) { + Box(modifier = Modifier.fillMaxSize()) { + coil.compose.AsyncImage( + model = photoPath, + contentDescription = "Miniatura da foto", + modifier = Modifier.fillMaxSize(), + contentScale = androidx.compose.ui.layout.ContentScale.Crop + ) + if (isNew) { + // Badge NOVA + Box( + modifier = Modifier + .align(Alignment.TopStart) + .background(BrandGreen) + .padding(horizontal = 4.dp, vertical = 2.dp) + ) { + Text("NOVA", color = Color.White, fontSize = 8.sp, fontWeight = FontWeight.Bold) + } + + // Close 'X' button to remove from draft + Box( + modifier = Modifier + .align(Alignment.TopEnd) + .padding(2.dp) + .size(20.dp) + .clip(CircleShape) + .background(Color.Black.copy(alpha = 0.65f)) + .clickable { newPhotosList.remove(photoPath) }, + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = "Remover Rascunho", + tint = Color.White, + modifier = Modifier.size(12.dp) + ) + } } } } } } - } - } else { - Text( - text = "Nenhuma foto anexada a esta OS ainda.", - fontSize = 11.sp, - color = Color.Gray, - modifier = Modifier.padding(vertical = 4.dp) - ) - } - - // Fullscreen Viewer Dialog - if (selectedPhotoForViewer != null) { - FullscreenPhotoViewerDialog( - photoPath = selectedPhotoForViewer!!, - osNumber = activity.numeroOs, - onDismiss = { selectedPhotoForViewer = null }, - onDelete = { - val photoToDelete = selectedPhotoForViewer!! - selectedPhotoForViewer = null - if (newPhotosList.contains(photoToDelete)) { - newPhotosList.remove(photoToDelete) - } else { - onSoftDeletePhoto(photoToDelete) - } - } - ) - } - } - - // Save Action Button or Google Login Warning Banner - if (currentUser == null) { - Card( - colors = CardDefaults.cardColors(containerColor = Color(0xFFFCE8E6)), - border = BorderStroke(1.dp, Color(0xFFFAD2CF)), - shape = RoundedCornerShape(8.dp), - modifier = Modifier.fillMaxWidth() - ) { - Row( - modifier = Modifier.padding(12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp) - ) { - Icon( - imageVector = Icons.Default.Lock, - contentDescription = "Acesso Restrito", - tint = Color(0xFFC5221F), - modifier = Modifier.size(24.dp) + } else { + Text( + text = "Nenhuma foto anexada a esta OS ainda.", + fontSize = 11.sp, + color = Color.Gray, + modifier = Modifier.padding(vertical = 4.dp) + ) + } + + // Fullscreen Viewer Dialog + if (selectedPhotoForViewer != null) { + FullscreenPhotoViewerDialog( + photoPath = selectedPhotoForViewer!!, + osNumber = activity.numeroOs, + onDismiss = { selectedPhotoForViewer = null }, + onDelete = { + val photoToDelete = selectedPhotoForViewer!! + selectedPhotoForViewer = null + if (newPhotosList.contains(photoToDelete)) { + newPhotosList.remove(photoToDelete) + } else { + onSoftDeletePhoto(photoToDelete) + } + } ) - Column(modifier = Modifier.weight(1f)) { - Text( - text = "Acesso Restrito", - fontWeight = FontWeight.Bold, - fontSize = 13.sp, - color = Color(0xFFC5221F) - ) - Text( - text = "Você precisa fazer login com sua conta do Google para atualizar o progresso de qualquer OS.", - fontSize = 11.sp, - color = Color(0xFFC5221F) - ) - } } } - Button( - onClick = onGoogleLoginClick, - modifier = Modifier - .fillMaxWidth() - .height(48.dp) - .testTag("save_progress_button_disabled"), - colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF4285F4)), - shape = RoundedCornerShape(10.dp) - ) { - GoogleIcon(modifier = Modifier.size(18.dp)) - Spacer(modifier = Modifier.width(8.dp)) - Text("Conectar com o Google", fontWeight = FontWeight.Bold, color = Color.White) - } - } else { - val hasEditAccess = userAccessLevel?.trim()?.lowercase().let { it == "total" || it == "editor" } - if (!hasEditAccess) { + // Save Action Button or Google Login Warning Banner + if (currentUser == null) { Card( colors = CardDefaults.cardColors(containerColor = Color(0xFFFCE8E6)), border = BorderStroke(1.dp, Color(0xFFFAD2CF)), @@ -1970,7 +1930,7 @@ fun EditActivityBottomSheet( color = Color(0xFFC5221F) ) Text( - text = "Seu nível de acesso (${userAccessLevel ?: "nenhum"}) não possui permissão para editar OS.", + text = "Você precisa fazer login com sua conta do Google para atualizar o progresso de qualquer OS.", fontSize = 11.sp, color = Color(0xFFC5221F) ) @@ -1979,157 +1939,261 @@ fun EditActivityBottomSheet( } Button( - onClick = {}, - enabled = false, + onClick = onGoogleLoginClick, modifier = Modifier .fillMaxWidth() .height(48.dp) .testTag("save_progress_button_disabled"), - colors = ButtonDefaults.buttonColors( - containerColor = Color.Gray, - disabledContainerColor = Color.LightGray - ), + colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF4285F4)), 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) + GoogleIcon(modifier = Modifier.size(18.dp)) + Spacer(modifier = Modifier.width(8.dp)) + Text("Conectar com o Google", fontWeight = FontWeight.Bold, color = Color.White) } } else { - Button( - onClick = { - isSubmitting = true - // 1. Aplicar rascunhos de achados (adição, edição e exclusão) - draftAddedFindings.forEach { (tipo, desc) -> - onAddFinding(tipo, desc) - } - draftUpdatedFindings.forEach { (id, newDesc) -> - findings.find { it.id == id }?.let { original -> - onUpdateFinding(original.copy(descricao = newDesc)) + val hasEditAccess = userAccessLevel?.trim()?.lowercase().let { it == "total" || it == "editor" } + if (!hasEditAccess) { + Card( + colors = CardDefaults.cardColors(containerColor = Color(0xFFFCE8E6)), + border = BorderStroke(1.dp, Color(0xFFFAD2CF)), + shape = RoundedCornerShape(8.dp), + modifier = Modifier.fillMaxWidth() + ) { + Row( + modifier = Modifier.padding(12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + Icon( + imageVector = Icons.Default.Lock, + 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) + ) } } - draftDeletedFindingIds.forEach { id -> - findings.find { it.id == id }?.let { original -> - onDeleteFinding(original) - } - } - // 2. Salvar progresso, observação e fotos - val photoParam = if (newPhotosList.isNotEmpty()) newPhotosList.joinToString("|") else null - onUpdateProgress(progressValue.toInt(), observationText, photoParam) - onDismiss() - }, - modifier = Modifier - .fillMaxWidth() - .height(48.dp) - .testTag("save_progress_button"), - colors = ButtonDefaults.buttonColors(containerColor = BrandGreen), - 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) - } - } - } - - // Dialog for Adding / Editing Finding - if (showFindingDialog) { - AlertDialog( - onDismissRequest = { showFindingDialog = false }, - title = { - Text( - text = if (activeFindingForDialog == null) "Novo Achado de ${if (dialogTipo == "SEGURANCA") "Segurança" else "Manutenção"}" else "Editar Achado", - fontWeight = FontWeight.Bold, - fontSize = 16.sp - ) - }, - text = { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedTextField( - value = findingText, - onValueChange = { findingText = it }, - placeholder = { Text("Descreva os detalhes do achado...", fontSize = 13.sp) }, - modifier = Modifier - .fillMaxWidth() - .height(100.dp), - maxLines = 4 - ) } - }, - confirmButton = { + + 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 = { - if (findingText.isNotBlank()) { - if (activeFindingForDialog == null) { - draftAddedFindings.add(dialogTipo to findingText.trim()) - } else { - val target = activeFindingForDialog!! - if (target.id.startsWith("draft_new_")) { - val idx = target.id.removePrefix("draft_new_").toIntOrNull() - if (idx != null && idx in draftAddedFindings.indices) { - draftAddedFindings[idx] = target.tipo to findingText.trim() - } - } else { - draftUpdatedFindings[target.id] = findingText.trim() - } - } - showFindingDialog = false + isSubmitting = true + // 1. Aplicar rascunhos de achados (adição, edição e exclusão) + draftAddedFindings.forEach { (tipo, desc) -> + onAddFinding(tipo, desc) } + draftUpdatedFindings.forEach { (id, newDesc) -> + findings.find { it.id == id }?.let { original -> + onUpdateFinding(original.copy(descricao = newDesc)) + } + } + draftDeletedFindingIds.forEach { id -> + findings.find { it.id == id }?.let { original -> + onDeleteFinding(original) + } + } + // 2. Salvar progresso, observação e fotos + val photoParam = if (newPhotosList.isNotEmpty()) newPhotosList.joinToString("|") else null + onUpdateProgress(progressValue.toInt(), observationText, photoParam) + onDismiss() }, - enabled = findingText.isNotBlank(), - colors = ButtonDefaults.buttonColors(containerColor = BrandGreen) + modifier = Modifier + .fillMaxWidth() + .height(48.dp) + .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), + shape = RoundedCornerShape(10.dp) ) { - Text("Salvar") - } - }, - dismissButton = { - TextButton(onClick = { showFindingDialog = false }) { - Text("Cancelar") + Icon(Icons.Default.Save, contentDescription = "Salvar") + Spacer(modifier = Modifier.width(6.dp)) + Text("Salvar Atualizações (Salva Local Offline)", fontWeight = FontWeight.Black) } } - ) - } + } - // Chronological Audit Timeline Log / History Section - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - HorizontalDivider(color = Color(0xFFF1F1F1)) - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp) - ) { - Icon(Icons.Default.History, contentDescription = "Histórico", tint = BrandBlack, modifier = Modifier.size(18.dp)) - Text( - text = "Histórico de Atualizações da OS", - fontWeight = FontWeight.Bold, - fontSize = 14.sp, - color = BrandBlack + // Dialog for Adding / Editing Finding + if (showFindingDialog) { + AlertDialog( + onDismissRequest = { showFindingDialog = false }, + title = { + Text( + text = if (activeFindingForDialog == null) "Novo Achado de ${if (dialogTipo == "SEGURANCA") "Segurança" else "Manutenção"}" else "Editar Achado", + fontWeight = FontWeight.Bold, + fontSize = 16.sp + ) + }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + value = findingText, + onValueChange = { findingText = it }, + placeholder = { Text("Descreva os detalhes do achado...", fontSize = 13.sp) }, + modifier = Modifier + .fillMaxWidth() + .height(100.dp), + maxLines = 4 + ) + } + }, + confirmButton = { + Button( + onClick = { + if (findingText.isNotBlank()) { + if (activeFindingForDialog == null) { + draftAddedFindings.add(dialogTipo to findingText.trim()) + } else { + val target = activeFindingForDialog!! + if (target.id.startsWith("draft_new_")) { + val idx = target.id.removePrefix("draft_new_").toIntOrNull() + if (idx != null && idx in draftAddedFindings.indices) { + draftAddedFindings[idx] = target.tipo to findingText.trim() + } + } else { + draftUpdatedFindings[target.id] = findingText.trim() + } + } + showFindingDialog = false + } + }, + enabled = findingText.isNotBlank(), + colors = ButtonDefaults.buttonColors(containerColor = BrandGreen) + ) { + Text("Salvar") + } + }, + dismissButton = { + TextButton(onClick = { showFindingDialog = false }) { + Text("Cancelar") + } + } ) } - if (history.isEmpty()) { - Box( - modifier = Modifier - .fillMaxWidth() - .padding(vertical = 12.dp), - contentAlignment = Alignment.Center + // Chronological Audit Timeline Log / History Section + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + HorizontalDivider(color = Color(0xFFF1F1F1)) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) ) { + Icon(Icons.Default.History, contentDescription = "Histórico", tint = BrandBlack, modifier = Modifier.size(18.dp)) Text( - text = "Nenhuma atualização anterior registrada para esta OS.", - fontSize = 11.sp, - color = StatusGrey + text = "Histórico de Atualizações da OS", + fontWeight = FontWeight.Bold, + fontSize = 14.sp, + color = BrandBlack ) } - } else { - Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - history.forEach { log -> - TimelineLogItem(log = log) + + if (history.isEmpty()) { + Box( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 12.dp), + contentAlignment = Alignment.Center + ) { + Text( + text = "Nenhuma atualização anterior registrada para esta OS.", + fontSize = 11.sp, + color = StatusGrey + ) + } + } else { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + history.forEach { log -> + TimelineLogItem(log = log) + } } } } - } - // Espaçamento inferior reforçado para evitar sobreposição por botões nativos do Android - Spacer(modifier = Modifier.height(32.dp)) + // Espaçamento inferior reforçado para evitar sobreposição por botões nativos do Android + 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) + } + } + } } } } 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 8776ee4..32c8f88 100644 --- a/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt +++ b/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt @@ -284,12 +284,17 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View 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 -> - val p1 = a1.dataInicioMillis - val p2 = a2.dataInicioMillis + val p1 = if (a1.dataInicio.isNullOrBlank() || a1.dataInicioMillis == 0L) Long.MAX_VALUE else a1.dataInicioMillis + val p2 = if (a2.dataInicio.isNullOrBlank() || a2.dataInicioMillis == 0L) Long.MAX_VALUE else a2.dataInicioMillis 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 p2 == Long.MAX_VALUE -> -1 else -> { diff --git a/app/src/test/java/com/example/ExampleRobolectricTest.kt b/app/src/test/java/com/example/ExampleRobolectricTest.kt index f04fa0b..22d8f6f 100644 --- a/app/src/test/java/com/example/ExampleRobolectricTest.kt +++ b/app/src/test/java/com/example/ExampleRobolectricTest.kt @@ -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() + 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) @Test fun `test analytics state calculations in ViewModel`() {