feat: implement OSFinding photo synchronization with Firebase and update local photo resolution logic to prioritize offline availability
This commit is contained in:
@@ -79,15 +79,15 @@ class MaintenanceRepository(
|
|||||||
val currentActivity = dao.getActivityByOsOneShot(numeroOs) ?: return@withContext
|
val currentActivity = dao.getActivityByOsOneShot(numeroOs) ?: return@withContext
|
||||||
val effectiveTimestamp = customTimestampMillis ?: System.currentTimeMillis()
|
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() }
|
val cleanObs = observacao?.trim().takeIf { !it.isNullOrBlank() }
|
||||||
if (cleanObs != null) {
|
if (cleanObs != null || !fotoPath.isNullOrBlank()) {
|
||||||
val existingObs = dao.getLatestObservationForOsOneShot(numeroOs)
|
val obsText = cleanObs ?: "Foto anexada"
|
||||||
val findingObs = OSFinding(
|
val findingObs = OSFinding(
|
||||||
id = existingObs?.id ?: java.util.UUID.randomUUID().toString(),
|
id = java.util.UUID.randomUUID().toString(),
|
||||||
numeroOs = numeroOs,
|
numeroOs = numeroOs,
|
||||||
tipo = "OBS",
|
tipo = "OBS",
|
||||||
descricao = cleanObs,
|
descricao = obsText,
|
||||||
timestamp = effectiveTimestamp,
|
timestamp = effectiveTimestamp,
|
||||||
responsavel = recurso,
|
responsavel = recurso,
|
||||||
emailEditor = emailEditor,
|
emailEditor = emailEditor,
|
||||||
@@ -476,16 +476,24 @@ class MaintenanceRepository(
|
|||||||
android.util.Log.d("MaintenanceRepository", "Inserted ${missingLocalHistory.size} missing history logs locally.")
|
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 reconciledActivities = remoteActivities.map { activity ->
|
||||||
val osHistory = allHistories.filter { it.numeroOs == activity.numeroOs }
|
val osHistory = allHistories.filter { it.numeroOs == activity.numeroOs }
|
||||||
|
val osFindings = dao.getFindingsForOsOneShot(activity.numeroOs)
|
||||||
val localAct = dao.getActivityByOsOneShot(activity.numeroOs)
|
val localAct = dao.getActivityByOsOneShot(activity.numeroOs)
|
||||||
val localFotoPath = localAct?.fotoPath
|
val localFotoPath = localAct?.fotoPath
|
||||||
val localHasRemoteUrl = localFotoPath?.let { it.contains("http://") || it.contains("https://") } == true
|
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()) {
|
if (osHistory.isNotEmpty()) {
|
||||||
val latestLog = osHistory.first() // sorted descending, so first is latest
|
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
|
localFotoPath
|
||||||
} else {
|
} else {
|
||||||
latestLog.fotoPath ?: activity.fotoPath
|
latestLog.fotoPath ?: activity.fotoPath
|
||||||
@@ -499,7 +507,12 @@ class MaintenanceRepository(
|
|||||||
lastUpdated = latestLog.timestamp
|
lastUpdated = latestLog.timestamp
|
||||||
)
|
)
|
||||||
} else {
|
} 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(
|
activity.copy(
|
||||||
fotoPath = finalFotoPath,
|
fotoPath = finalFotoPath,
|
||||||
synced = true
|
synced = true
|
||||||
@@ -574,12 +587,40 @@ class MaintenanceRepository(
|
|||||||
android.util.Log.d("MaintenanceRepository", "Uploaded ${historyToUpload.size} new local history logs to Google Sheet.")
|
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 {
|
try {
|
||||||
val remoteFindings = sheetsSyncService.fetchRemoteFindingsList()
|
val remoteFindings = sheetsSyncService.fetchRemoteFindingsList()
|
||||||
if (remoteFindings.isNotEmpty()) {
|
val localFindingsMap = dao.getAllFindingsList().associateBy { it.id }
|
||||||
dao.insertFindings(remoteFindings)
|
|
||||||
|
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()
|
val allLocalActiveFindings = dao.getAllFindingsList()
|
||||||
sheetsSyncService.syncFindingsWithSheet(allLocalActiveFindings)
|
sheetsSyncService.syncFindingsWithSheet(allLocalActiveFindings)
|
||||||
android.util.Log.d("MaintenanceRepository", "Synced ${allLocalActiveFindings.size} active findings with Google Sheet.")
|
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
|
// Collect all local→URL replacements per OS to batch-update activity fotoPath
|
||||||
val replacementsByOs = mutableMapOf<String, MutableList<Pair<String, String>>>()
|
val replacementsByOs = mutableMapOf<String, MutableList<Pair<String, String>>>()
|
||||||
|
|
||||||
|
// 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()
|
val historyList = dao.getAllHistoryList()
|
||||||
for (history in historyList) {
|
for (history in historyList) {
|
||||||
val rawPath = history.fotoPath
|
val rawPath = history.fotoPath
|
||||||
@@ -716,7 +797,6 @@ class MaintenanceRepository(
|
|||||||
val compressedFile = com.example.util.ImageCompressor.compressImageFile(file, 500 * 1024L)
|
val compressedFile = com.example.util.ImageCompressor.compressImageFile(file, 500 * 1024L)
|
||||||
val result = firebaseStorageSyncService.uploadPhoto(compressedFile, history.numeroOs)
|
val result = firebaseStorageSyncService.uploadPhoto(compressedFile, history.numeroOs)
|
||||||
changed = true
|
changed = true
|
||||||
// Track the local→URL replacement for this OS
|
|
||||||
replacementsByOs.getOrPut(history.numeroOs) { mutableListOf() }
|
replacementsByOs.getOrPut(history.numeroOs) { mutableListOf() }
|
||||||
.add(Pair(trimmed, result.downloadUrl))
|
.add(Pair(trimmed, result.downloadUrl))
|
||||||
result.downloadUrl
|
result.downloadUrl
|
||||||
|
|||||||
@@ -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()
|
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
|
return trimmed
|
||||||
}
|
}
|
||||||
if (trimmed.startsWith("photos/")) {
|
if (trimmed.startsWith("photos/")) {
|
||||||
@@ -1227,7 +1250,7 @@ fun FullscreenPhotoViewerDialog(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Image display
|
// Image display
|
||||||
val resolvedModel = remember(photoPath) { resolvePhotoModel(photoPath) }
|
val resolvedModel = remember(photoPath) { resolvePhotoModel(photoPath, context) }
|
||||||
var retryKey by remember { mutableStateOf(0) }
|
var retryKey by remember { mutableStateOf(0) }
|
||||||
coil.compose.SubcomposeAsyncImage(
|
coil.compose.SubcomposeAsyncImage(
|
||||||
model = coil.request.ImageRequest.Builder(context)
|
model = coil.request.ImageRequest.Builder(context)
|
||||||
@@ -1877,7 +1900,8 @@ fun EditActivityBottomSheet(
|
|||||||
border = BorderStroke(2.dp, if (isNew) BrandGreen else Color(0xFFE0E0E0))
|
border = BorderStroke(2.dp, if (isNew) BrandGreen else Color(0xFFE0E0E0))
|
||||||
) {
|
) {
|
||||||
Box(modifier = Modifier.fillMaxSize()) {
|
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) }
|
var retryKey by remember { mutableStateOf(0) }
|
||||||
coil.compose.SubcomposeAsyncImage(
|
coil.compose.SubcomposeAsyncImage(
|
||||||
model = coil.request.ImageRequest.Builder(LocalContext.current)
|
model = coil.request.ImageRequest.Builder(LocalContext.current)
|
||||||
|
|||||||
Reference in New Issue
Block a user