feat: implement role-based access control for maintenance actions and improve photo deletion synchronization logic

This commit is contained in:
Jhony Cesar
2026-08-06 06:29:49 -04:00
parent 9dcb30fd24
commit 824a64b22a
4 changed files with 123 additions and 25 deletions

View File

@@ -116,6 +116,16 @@ class FirebaseStorageSyncService(
Log.d(tag, "Arquivo $currentPath renomeado no Firebase Storage para $newPath (Soft Delete).") Log.d(tag, "Arquivo $currentPath renomeado no Firebase Storage para $newPath (Soft Delete).")
true 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) { } catch (e: Exception) {
Log.e(tag, "Falha ao executar soft delete no Firebase Storage: ${e.message}", e) Log.e(tag, "Falha ao executar soft delete no Firebase Storage: ${e.message}", e)
false false

View File

@@ -481,11 +481,12 @@ class MaintenanceRepository(
if (osHistory.isNotEmpty()) { if (osHistory.isNotEmpty()) {
val latestLog = osHistory.first() // sorted descending, so first is latest 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 localFotoPath
} else { } else {
latestLog.fotoPath ?: activity.fotoPath latestLog.fotoPath ?: activity.fotoPath
} }
val finalFotoPath = mergePreservingDeletedPhotos(localFotoPath, baseFotoPath)
activity.copy( activity.copy(
percentualExecucao = latestLog.percentualNovo, percentualExecucao = latestLog.percentualNovo,
observacoes = latestLog.observacao ?: activity.observacoes, observacoes = latestLog.observacao ?: activity.observacoes,
@@ -494,8 +495,9 @@ class MaintenanceRepository(
lastUpdated = latestLog.timestamp lastUpdated = latestLog.timestamp
) )
} else { } else {
val finalFotoPath = mergePreservingDeletedPhotos(localFotoPath, activity.fotoPath)
activity.copy( activity.copy(
fotoPath = if (localHasRemoteUrl) localFotoPath else activity.fotoPath, fotoPath = finalFotoPath,
synced = true 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<String>()
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) { suspend fun softDeletePhoto(targetPhotoPath: String, osNumber: String) = withContext(Dispatchers.IO) {
if (isCurrentlyConnected() && (targetPhotoPath.startsWith("http://") || targetPhotoPath.startsWith("https://") || targetPhotoPath.startsWith("photos/"))) { if (isCurrentlyConnected() && (targetPhotoPath.startsWith("http://") || targetPhotoPath.startsWith("https://") || targetPhotoPath.startsWith("photos/"))) {
try { 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 // Update history entries by replacing target photo or appending _DELETED
val historyList = dao.getHistoryForOsOneShot(osNumber) val historyList = dao.getHistoryForOsOneShot(osNumber)
for (hist in historyList) { for (hist in historyList) {
val pathStr = hist.fotoPath 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 -> 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("|"))) dao.insertHistory(hist.copy(fotoPath = updatedPaths.joinToString("|")))
} }
} }
// Update OS Activity entry
val activity = dao.getActivityByOsOneShot(osNumber) 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 -> 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)) 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))
}
}
} }
} }

View File

@@ -1119,6 +1119,7 @@ fun OSListItemCard(
fun FullscreenPhotoViewerDialog( fun FullscreenPhotoViewerDialog(
photoPath: String, photoPath: String,
osNumber: String, osNumber: String,
canDelete: Boolean = true,
onDismiss: () -> Unit, onDismiss: () -> Unit,
onDelete: () -> Unit onDelete: () -> Unit
) { ) {
@@ -1201,6 +1202,7 @@ fun FullscreenPhotoViewerDialog(
} }
// Deletar // Deletar
if (canDelete) {
IconButton(onClick = onDelete) { IconButton(onClick = onDelete) {
Icon( Icon(
imageVector = Icons.Default.Delete, imageVector = Icons.Default.Delete,
@@ -1210,6 +1212,7 @@ fun FullscreenPhotoViewerDialog(
} }
} }
} }
}
// Image display // Image display
coil.compose.AsyncImage( coil.compose.AsyncImage(
@@ -1301,7 +1304,7 @@ fun EditActivityBottomSheet(
if (!raw.isNullOrBlank()) { if (!raw.isNullOrBlank()) {
raw.split("|").forEach { p -> raw.split("|").forEach { p ->
val trimmed = p.trim() 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) list.add(trimmed)
} }
} }
@@ -1889,6 +1892,7 @@ fun EditActivityBottomSheet(
FullscreenPhotoViewerDialog( FullscreenPhotoViewerDialog(
photoPath = selectedPhotoForViewer!!, photoPath = selectedPhotoForViewer!!,
osNumber = activity.numeroOs, osNumber = activity.numeroOs,
canDelete = currentUser != null,
onDismiss = { selectedPhotoForViewer = null }, onDismiss = { selectedPhotoForViewer = null },
onDelete = { onDelete = {
val photoToDelete = selectedPhotoForViewer!! val photoToDelete = selectedPhotoForViewer!!

View File

@@ -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( fun addFinding(
numeroOs: String, numeroOs: String,
tipo: String, tipo: String,
@@ -540,9 +555,10 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
fotoPath: String? = null fotoPath: String? = null
) { ) {
viewModelScope.launch { viewModelScope.launch {
val user = _currentUser.value if (!checkUserCanEdit()) return@launch
val recurso = user?.displayName ?: "Encarregado Campo" val user = _currentUser.value!!
val emailEditor = user?.email val recurso = user.displayName
val emailEditor = user.email
try { try {
repository.addFinding(numeroOs, tipo, descricao, recurso, emailEditor, fotoPath) repository.addFinding(numeroOs, tipo, descricao, recurso, emailEditor, fotoPath)
_selectedActivity.value?.let { active -> _selectedActivity.value?.let { active ->
@@ -561,9 +577,10 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
fun updateFinding(finding: com.example.data.model.OSFinding) { fun updateFinding(finding: com.example.data.model.OSFinding) {
viewModelScope.launch { viewModelScope.launch {
val user = _currentUser.value if (!checkUserCanEdit()) return@launch
val recurso = user?.displayName ?: "Encarregado Campo" val user = _currentUser.value!!
val emailEditor = user?.email val recurso = user.displayName
val emailEditor = user.email
try { try {
repository.updateFinding(finding, recurso, emailEditor) repository.updateFinding(finding, recurso, emailEditor)
_selectedActivity.value?.let { active -> _selectedActivity.value?.let { active ->
@@ -582,9 +599,10 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
fun deleteFinding(finding: com.example.data.model.OSFinding) { fun deleteFinding(finding: com.example.data.model.OSFinding) {
viewModelScope.launch { viewModelScope.launch {
val user = _currentUser.value if (!checkUserCanEdit()) return@launch
val recurso = user?.displayName ?: "Encarregado Campo" val user = _currentUser.value!!
val emailEditor = user?.email val recurso = user.displayName
val emailEditor = user.email
try { try {
repository.deleteFinding(finding, recurso, emailEditor) repository.deleteFinding(finding, recurso, emailEditor)
_selectedActivity.value?.let { active -> _selectedActivity.value?.let { active ->
@@ -601,7 +619,6 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
} }
} }
fun saveLocalPhotoFromUri(uri: Uri, osNumber: String): String { fun saveLocalPhotoFromUri(uri: Uri, osNumber: String): String {
return repository.saveLocalPhotoFromUri(uri, osNumber) return repository.saveLocalPhotoFromUri(uri, osNumber)
} }
@@ -612,6 +629,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
fun softDeletePhoto(fotoPath: String, osNumber: String) { fun softDeletePhoto(fotoPath: String, osNumber: String) {
viewModelScope.launch { viewModelScope.launch {
if (!checkUserCanEdit()) return@launch
try { try {
repository.softDeletePhoto(fotoPath, osNumber) repository.softDeletePhoto(fotoPath, osNumber)
_syncStatusMessage.value = "Foto excluída com sucesso." _syncStatusMessage.value = "Foto excluída com sucesso."