From 274c3ce5425a2844ac64e7fae4ad5b7d99a040f9 Mon Sep 17 00:00:00 2001 From: Jhony Cesar Date: Thu, 6 Aug 2026 09:07:47 -0400 Subject: [PATCH] feat: implement OSFinding photo synchronization with Firebase and update local photo resolution logic to prioritize offline availability --- .../data/repository/MaintenanceRepository.kt | 104 ++++++++++++++++-- .../ui/screens/MaintenanceDashboardScreen.kt | 32 +++++- 2 files changed, 120 insertions(+), 16 deletions(-) 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 eb6fc40..727b69e 100644 --- a/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt +++ b/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt @@ -79,15 +79,15 @@ class MaintenanceRepository( val currentActivity = dao.getActivityByOsOneShot(numeroOs) ?: return@withContext val effectiveTimestamp = customTimestampMillis ?: System.currentTimeMillis() - // Handle observation update as an OSFinding of type OBS if filled + // Handle observation and photo update as an OSFinding of type OBS if filled or photo attached val cleanObs = observacao?.trim().takeIf { !it.isNullOrBlank() } - if (cleanObs != null) { - val existingObs = dao.getLatestObservationForOsOneShot(numeroOs) + if (cleanObs != null || !fotoPath.isNullOrBlank()) { + val obsText = cleanObs ?: "Foto anexada" val findingObs = OSFinding( - id = existingObs?.id ?: java.util.UUID.randomUUID().toString(), + id = java.util.UUID.randomUUID().toString(), numeroOs = numeroOs, tipo = "OBS", - descricao = cleanObs, + descricao = obsText, timestamp = effectiveTimestamp, responsavel = recurso, emailEditor = emailEditor, @@ -476,16 +476,24 @@ class MaintenanceRepository( android.util.Log.d("MaintenanceRepository", "Inserted ${missingLocalHistory.size} missing history logs locally.") } - // 6. For each remote activity, determine its current state based on the latest history log + // 6. For each remote activity, determine its current state based on findings (achados) and history log val reconciledActivities = remoteActivities.map { activity -> val osHistory = allHistories.filter { it.numeroOs == activity.numeroOs } + val osFindings = dao.getFindingsForOsOneShot(activity.numeroOs) val localAct = dao.getActivityByOsOneShot(activity.numeroOs) val localFotoPath = localAct?.fotoPath val localHasRemoteUrl = localFotoPath?.let { it.contains("http://") || it.contains("https://") } == true + val findingsFotoPaths = osFindings.mapNotNull { it.fotoPath } + .flatMap { it.split("|") } + .map { it.trim() } + .filter { it.isNotBlank() } + if (osHistory.isNotEmpty()) { val latestLog = osHistory.first() // sorted descending, so first is latest - val baseFotoPath = if (localHasRemoteUrl && latestLog.fotoPath?.startsWith("http") != true) { + val baseFotoPath = if (findingsFotoPaths.isNotEmpty()) { + findingsFotoPaths.distinct().joinToString("|") + } else if (localHasRemoteUrl && latestLog.fotoPath?.startsWith("http") != true) { localFotoPath } else { latestLog.fotoPath ?: activity.fotoPath @@ -499,7 +507,12 @@ class MaintenanceRepository( lastUpdated = latestLog.timestamp ) } else { - val finalFotoPath = mergePreservingDeletedPhotos(localFotoPath, activity.fotoPath) + val baseFotoPath = if (findingsFotoPaths.isNotEmpty()) { + findingsFotoPaths.distinct().joinToString("|") + } else { + activity.fotoPath + } + val finalFotoPath = mergePreservingDeletedPhotos(localFotoPath, baseFotoPath) activity.copy( fotoPath = finalFotoPath, synced = true @@ -574,12 +587,40 @@ class MaintenanceRepository( android.util.Log.d("MaintenanceRepository", "Uploaded ${historyToUpload.size} new local history logs to Google Sheet.") } - // 10. Sync 'achados' sheet with local OSFinding database + // 10. Sync 'achados' sheet with local OSFinding database safely preserving local/uploaded photo paths try { val remoteFindings = sheetsSyncService.fetchRemoteFindingsList() - if (remoteFindings.isNotEmpty()) { - dao.insertFindings(remoteFindings) + val localFindingsMap = dao.getAllFindingsList().associateBy { it.id } + + val reconciledFindings = remoteFindings.map { remote -> + val local = localFindingsMap[remote.id] + if (local != null) { + val localHasPhoto = !local.fotoPath.isNullOrBlank() + val remoteHasPhoto = !remote.fotoPath.isNullOrBlank() + val finalFotoPath = when { + localHasPhoto && !remoteHasPhoto -> local.fotoPath + remoteHasPhoto && localHasPhoto -> mergePreservingDeletedPhotos(local.fotoPath, remote.fotoPath) + remoteHasPhoto -> remote.fotoPath + else -> local.fotoPath + } + remote.copy( + fotoPath = finalFotoPath, + synced = local.synced && (finalFotoPath == remote.fotoPath) + ) + } else { + remote + } + }.toMutableList() + + // Keep local findings that do not exist on the remote sheet yet + val remoteIds = remoteFindings.map { it.id }.toSet() + val localOnlyFindings = localFindingsMap.values.filter { it.id !in remoteIds } + reconciledFindings.addAll(localOnlyFindings) + + if (reconciledFindings.isNotEmpty()) { + dao.insertFindings(reconciledFindings) } + val allLocalActiveFindings = dao.getAllFindingsList() sheetsSyncService.syncFindingsWithSheet(allLocalActiveFindings) android.util.Log.d("MaintenanceRepository", "Synced ${allLocalActiveFindings.size} active findings with Google Sheet.") @@ -701,6 +742,46 @@ class MaintenanceRepository( // Collect all local→URL replacements per OS to batch-update activity fotoPath val replacementsByOs = mutableMapOf>>() + // 1. Process local photos in OSFinding (achados) + val findingsList = dao.getAllFindingsList() + for (finding in findingsList) { + val rawPath = finding.fotoPath + if (!rawPath.isNullOrBlank()) { + val subPaths = rawPath.split("|") + var changed = false + val uploadedSubPaths = subPaths.map { path -> + val trimmed = path.trim() + if (trimmed.isNotBlank() && !trimmed.startsWith("http://") && !trimmed.startsWith("https://") && !trimmed.endsWith("_DELETED") && !trimmed.contains("_DELETED")) { + val file = java.io.File(trimmed) + if (file.exists()) { + try { + val compressedFile = com.example.util.ImageCompressor.compressImageFile(file, 500 * 1024L) + val result = firebaseStorageSyncService.uploadPhoto(compressedFile, finding.numeroOs) + changed = true + replacementsByOs.getOrPut(finding.numeroOs) { mutableListOf() } + .add(Pair(trimmed, result.downloadUrl)) + result.downloadUrl + } catch (e: Exception) { + android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Firebase Storage: ${e.message}", e) + trimmed + } + } else { + trimmed + } + } else { + trimmed + } + } + + if (changed) { + val updatedJoinedPath = uploadedSubPaths.joinToString("|") + val updatedFinding = finding.copy(fotoPath = updatedJoinedPath, synced = false) + dao.insertFinding(updatedFinding) + } + } + } + + // 2. Process local photos in OSUpdateHistory (history) val historyList = dao.getAllHistoryList() for (history in historyList) { val rawPath = history.fotoPath @@ -716,7 +797,6 @@ class MaintenanceRepository( val compressedFile = com.example.util.ImageCompressor.compressImageFile(file, 500 * 1024L) val result = firebaseStorageSyncService.uploadPhoto(compressedFile, history.numeroOs) changed = true - // Track the local→URL replacement for this OS replacementsByOs.getOrPut(history.numeroOs) { mutableListOf() } .add(Pair(trimmed, result.downloadUrl)) result.downloadUrl 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 ed74d3f..ab90308 100644 --- a/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt +++ b/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt @@ -1115,9 +1115,32 @@ fun OSListItemCard( } } -fun resolvePhotoModel(path: String): String { +fun resolvePhotoModel(path: String, context: android.content.Context? = null): String { val trimmed = path.trim() - if (trimmed.startsWith("http://") || trimmed.startsWith("https://") || trimmed.startsWith("/")) { + if (trimmed.isBlank()) return "" + + // 1. Prioritize local file path if it exists on disk + if (trimmed.startsWith("/")) { + val file = java.io.File(trimmed) + if (file.exists()) return trimmed + } + + // 2. Check if local cached file with same name exists in internal os_photos directory + if (context != null) { + val clean = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true) + val fileName = clean.substringAfterLast("/").substringAfterLast("\\") + .removeSuffix("_DELETED").removeSuffix(".jpg_DELETED").replace("_DELETED", "") + if (fileName.isNotBlank()) { + val photosDir = java.io.File(context.filesDir, "os_photos") + val localCachedFile = java.io.File(photosDir, fileName) + if (localCachedFile.exists()) { + return localCachedFile.absolutePath + } + } + } + + // 3. Fallback to remote URLs + if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) { return trimmed } if (trimmed.startsWith("photos/")) { @@ -1227,7 +1250,7 @@ fun FullscreenPhotoViewerDialog( } // Image display - val resolvedModel = remember(photoPath) { resolvePhotoModel(photoPath) } + val resolvedModel = remember(photoPath) { resolvePhotoModel(photoPath, context) } var retryKey by remember { mutableStateOf(0) } coil.compose.SubcomposeAsyncImage( model = coil.request.ImageRequest.Builder(context) @@ -1877,7 +1900,8 @@ fun EditActivityBottomSheet( border = BorderStroke(2.dp, if (isNew) BrandGreen else Color(0xFFE0E0E0)) ) { Box(modifier = Modifier.fillMaxSize()) { - val resolvedModel = remember(photoPath) { resolvePhotoModel(photoPath) } + val currentCtx = LocalContext.current + val resolvedModel = remember(photoPath) { resolvePhotoModel(photoPath, currentCtx) } var retryKey by remember { mutableStateOf(0) } coil.compose.SubcomposeAsyncImage( model = coil.request.ImageRequest.Builder(LocalContext.current)