diff --git a/app/src/main/java/com/example/data/remote/FirebaseStorageSyncService.kt b/app/src/main/java/com/example/data/remote/FirebaseStorageSyncService.kt index 04449f9..2808ecc 100644 --- a/app/src/main/java/com/example/data/remote/FirebaseStorageSyncService.kt +++ b/app/src/main/java/com/example/data/remote/FirebaseStorageSyncService.kt @@ -116,6 +116,16 @@ class FirebaseStorageSyncService( Log.d(tag, "Arquivo $currentPath renomeado no Firebase Storage para $newPath (Soft Delete).") true + } catch (e: com.google.firebase.storage.StorageException) { + if (e.errorCode == com.google.firebase.storage.StorageException.ERROR_OBJECT_NOT_FOUND || + e.message?.contains("Object does not exist", ignoreCase = true) == true + ) { + Log.d(tag, "Arquivo não encontrado no Firebase Storage ao tentar deletar (já inexistente): ${e.message}") + true + } else { + Log.e(tag, "Falha ao executar soft delete no Firebase Storage: ${e.message}", e) + false + } } catch (e: Exception) { Log.e(tag, "Falha ao executar soft delete no Firebase Storage: ${e.message}", e) false 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 38ab667..a426a73 100644 --- a/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt +++ b/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt @@ -481,11 +481,12 @@ class MaintenanceRepository( if (osHistory.isNotEmpty()) { val latestLog = osHistory.first() // sorted descending, so first is latest - val finalFotoPath = if (localHasRemoteUrl && latestLog.fotoPath?.startsWith("http") != true) { + val baseFotoPath = if (localHasRemoteUrl && latestLog.fotoPath?.startsWith("http") != true) { localFotoPath } else { latestLog.fotoPath ?: activity.fotoPath } + val finalFotoPath = mergePreservingDeletedPhotos(localFotoPath, baseFotoPath) activity.copy( percentualExecucao = latestLog.percentualNovo, observacoes = latestLog.observacao ?: activity.observacoes, @@ -494,8 +495,9 @@ class MaintenanceRepository( lastUpdated = latestLog.timestamp ) } else { + val finalFotoPath = mergePreservingDeletedPhotos(localFotoPath, activity.fotoPath) activity.copy( - fotoPath = if (localHasRemoteUrl) localFotoPath else activity.fotoPath, + fotoPath = finalFotoPath, synced = true ) } @@ -734,6 +736,53 @@ class MaintenanceRepository( } } + private fun extractPhotoFileName(path: String): String { + val clean = path.trim().substringBefore("?").substringBefore("#") + val fileName = clean.substringAfterLast("/").substringAfterLast("\\") + return fileName.removeSuffix("_DELETED") + } + + private fun isSamePhoto(path1: String?, path2: String?): Boolean { + if (path1.isNullOrBlank() || path2.isNullOrBlank()) return false + val p1 = path1.trim() + val p2 = path2.trim() + if (p1 == p2) return true + val name1 = extractPhotoFileName(p1) + val name2 = extractPhotoFileName(p2) + return name1.isNotBlank() && name1 == name2 + } + + private fun mergePreservingDeletedPhotos(localPath: String?, remotePath: String?): String? { + if (localPath.isNullOrBlank()) return remotePath + if (remotePath.isNullOrBlank()) return localPath + + val localSubPaths = localPath.split("|").map { it.trim() }.filter { it.isNotBlank() } + val remoteSubPaths = remotePath.split("|").map { it.trim() }.filter { it.isNotBlank() } + + val result = mutableListOf() + for (remote in remoteSubPaths) { + val matchingLocal = localSubPaths.find { isSamePhoto(it, remote) } + if (matchingLocal != null && (matchingLocal.endsWith("_DELETED") || matchingLocal.contains("_DELETED"))) { + if (!result.contains(matchingLocal)) { + result.add(matchingLocal) + } + } else { + val photoToAdd = matchingLocal ?: remote + if (!result.contains(photoToAdd)) { + result.add(photoToAdd) + } + } + } + + for (local in localSubPaths) { + if (!result.any { isSamePhoto(it, local) }) { + result.add(local) + } + } + + return result.joinToString("|").ifEmpty { null } + } + suspend fun softDeletePhoto(targetPhotoPath: String, osNumber: String) = withContext(Dispatchers.IO) { if (isCurrentlyConnected() && (targetPhotoPath.startsWith("http://") || targetPhotoPath.startsWith("https://") || targetPhotoPath.startsWith("photos/"))) { try { @@ -743,27 +792,44 @@ class MaintenanceRepository( } } - val deletedTarget = if (targetPhotoPath.endsWith("_DELETED")) targetPhotoPath else "${targetPhotoPath}_DELETED" - // Update history entries by replacing target photo or appending _DELETED val historyList = dao.getHistoryForOsOneShot(osNumber) for (hist in historyList) { val pathStr = hist.fotoPath - if (!pathStr.isNullOrBlank() && pathStr.contains(targetPhotoPath)) { + if (!pathStr.isNullOrBlank() && pathStr.split("|").any { isSamePhoto(it, targetPhotoPath) }) { val updatedPaths = pathStr.split("|").map { p -> - if (p.trim() == targetPhotoPath.trim()) deletedTarget else p + if (isSamePhoto(p, targetPhotoPath)) { + if (p.contains("_DELETED")) p else "${p}_DELETED" + } else p } dao.insertHistory(hist.copy(fotoPath = updatedPaths.joinToString("|"))) } } + // Update OS Activity entry val activity = dao.getActivityByOsOneShot(osNumber) - if (activity != null && !activity.fotoPath.isNullOrBlank() && activity.fotoPath.contains(targetPhotoPath)) { + if (activity != null && !activity.fotoPath.isNullOrBlank() && activity.fotoPath.split("|").any { isSamePhoto(it, targetPhotoPath) }) { val updatedPaths = activity.fotoPath.split("|").map { p -> - if (p.trim() == targetPhotoPath.trim()) deletedTarget else p + if (isSamePhoto(p, targetPhotoPath)) { + if (p.contains("_DELETED")) p else "${p}_DELETED" + } else p } dao.updateActivity(activity.copy(fotoPath = updatedPaths.joinToString("|"), synced = false)) } + + // Update OSFinding entries + val findingsList = dao.getFindingsForOsOneShot(osNumber) + for (finding in findingsList) { + val fPath = finding.fotoPath + if (!fPath.isNullOrBlank() && fPath.split("|").any { isSamePhoto(it, targetPhotoPath) }) { + val updatedPaths = fPath.split("|").map { p -> + if (isSamePhoto(p, targetPhotoPath)) { + if (p.contains("_DELETED")) p else "${p}_DELETED" + } else p + } + dao.insertFinding(finding.copy(fotoPath = updatedPaths.joinToString("|"), synced = false)) + } + } } } 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 81415a6..f80a6fe 100644 --- a/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt +++ b/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt @@ -1119,6 +1119,7 @@ fun OSListItemCard( fun FullscreenPhotoViewerDialog( photoPath: String, osNumber: String, + canDelete: Boolean = true, onDismiss: () -> Unit, onDelete: () -> Unit ) { @@ -1201,12 +1202,14 @@ fun FullscreenPhotoViewerDialog( } // Deletar - IconButton(onClick = onDelete) { - Icon( - imageVector = Icons.Default.Delete, - contentDescription = "Deletar Foto", - tint = Color(0xFFFF5252) - ) + if (canDelete) { + IconButton(onClick = onDelete) { + Icon( + imageVector = Icons.Default.Delete, + contentDescription = "Deletar Foto", + tint = Color(0xFFFF5252) + ) + } } } } @@ -1301,7 +1304,7 @@ fun EditActivityBottomSheet( if (!raw.isNullOrBlank()) { raw.split("|").forEach { p -> val trimmed = p.trim() - if (trimmed.isNotBlank() && !trimmed.endsWith("_DELETED") && !list.contains(trimmed)) { + if (trimmed.isNotBlank() && !trimmed.endsWith("_DELETED") && !trimmed.contains("_DELETED") && !list.contains(trimmed)) { list.add(trimmed) } } @@ -1889,6 +1892,7 @@ fun EditActivityBottomSheet( FullscreenPhotoViewerDialog( photoPath = selectedPhotoForViewer!!, osNumber = activity.numeroOs, + canDelete = currentUser != null, onDismiss = { selectedPhotoForViewer = null }, onDelete = { val photoToDelete = selectedPhotoForViewer!! 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 32c8f88..5a32145 100644 --- a/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt +++ b/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt @@ -533,6 +533,21 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View } } + private suspend fun checkUserCanEdit(): Boolean { + val user = _currentUser.value + if (user == null) { + _syncStatusMessage.value = "Erro: É necessário fazer login com o Google para realizar alterações." + return false + } + val access = repository.getUserAccess(user.email) + val level = access?.nivelAcesso?.trim()?.lowercase() + if (level != "total" && level != "editor") { + _syncStatusMessage.value = "Erro: Nível de acesso '$level' não possui permissão para editar." + return false + } + return true + } + fun addFinding( numeroOs: String, tipo: String, @@ -540,9 +555,10 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View fotoPath: String? = null ) { viewModelScope.launch { - val user = _currentUser.value - val recurso = user?.displayName ?: "Encarregado Campo" - val emailEditor = user?.email + if (!checkUserCanEdit()) return@launch + val user = _currentUser.value!! + val recurso = user.displayName + val emailEditor = user.email try { repository.addFinding(numeroOs, tipo, descricao, recurso, emailEditor, fotoPath) _selectedActivity.value?.let { active -> @@ -561,9 +577,10 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View fun updateFinding(finding: com.example.data.model.OSFinding) { viewModelScope.launch { - val user = _currentUser.value - val recurso = user?.displayName ?: "Encarregado Campo" - val emailEditor = user?.email + if (!checkUserCanEdit()) return@launch + val user = _currentUser.value!! + val recurso = user.displayName + val emailEditor = user.email try { repository.updateFinding(finding, recurso, emailEditor) _selectedActivity.value?.let { active -> @@ -582,9 +599,10 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View fun deleteFinding(finding: com.example.data.model.OSFinding) { viewModelScope.launch { - val user = _currentUser.value - val recurso = user?.displayName ?: "Encarregado Campo" - val emailEditor = user?.email + if (!checkUserCanEdit()) return@launch + val user = _currentUser.value!! + val recurso = user.displayName + val emailEditor = user.email try { repository.deleteFinding(finding, recurso, emailEditor) _selectedActivity.value?.let { active -> @@ -601,7 +619,6 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View } } - fun saveLocalPhotoFromUri(uri: Uri, osNumber: String): String { return repository.saveLocalPhotoFromUri(uri, osNumber) } @@ -612,6 +629,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View fun softDeletePhoto(fotoPath: String, osNumber: String) { viewModelScope.launch { + if (!checkUserCanEdit()) return@launch try { repository.softDeletePhoto(fotoPath, osNumber) _syncStatusMessage.value = "Foto excluída com sucesso."