Compare commits

...

2 Commits

3 changed files with 145 additions and 23 deletions

View File

@@ -811,7 +811,7 @@ class GoogleSheetsSyncService(
row[headerIndices["percentualanterior"] ?: 3] = history.percentualAnterior.toString()
row[headerIndices["percentualnovo"] ?: 4] = history.percentualNovo.toString()
row[headerIndices["observacao"] ?: 5] = history.observacao ?: ""
row[headerIndices["fotopath"] ?: 6] = history.fotoPath ?: ""
row[headerIndices["fotopath"] ?: 6] = filterRemoteOnlyPhotoPaths(history.fotoPath)
row[headerIndices["responsavel"] ?: 7] = history.recurso
row[headerIndices["email_editor"] ?: 8] = history.emailEditor ?: ""
row
@@ -930,7 +930,7 @@ class GoogleSheetsSyncService(
finding.timestamp.toString(),
finding.responsavel,
finding.emailEditor ?: "",
finding.fotoPath ?: ""
filterRemoteOnlyPhotoPaths(finding.fotoPath)
)
}.toMutableList()
@@ -948,5 +948,14 @@ class GoogleSheetsSyncService(
Log.d(tag, "Successfully updated 'achados' sheet with ${allActiveFindings.size} active findings.")
}
}
fun filterRemoteOnlyPhotoPaths(pathStr: String?): String {
if (pathStr.isNullOrBlank()) return ""
return pathStr.split("|")
.map { it.trim() }
.filter { it.isNotBlank() && !it.startsWith("/") }
.distinct()
.joinToString("|")
}
}

View File

@@ -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
val cleanObs = observacao?.trim().takeIf { !it.isNullOrBlank() }
if (cleanObs != null) {
val existingObs = dao.getLatestObservationForOsOneShot(numeroOs)
// Handle observation and photo update as an OSFinding of type OBS if filled or photo attached
val cleanObs = stripAuditTags(observacao)
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,
@@ -97,7 +97,7 @@ class MaintenanceRepository(
dao.insertFinding(findingObs)
}
val latestObsText = cleanObs ?: currentActivity.observacoes
val latestObsText = cleanObs ?: stripAuditTags(currentActivity.observacoes)
val updatedActivity = currentActivity.copy(
percentualExecucao = novoPercentual.coerceIn(0, 100),
@@ -151,7 +151,7 @@ class MaintenanceRepository(
if (tipo == "OBS" && currentActivity != null) {
dao.updateActivity(
currentActivity.copy(
observacoes = descricao.trim(),
observacoes = stripAuditTags(descricao),
synced = false,
lastUpdated = effectiveTimestamp
)
@@ -196,7 +196,7 @@ class MaintenanceRepository(
if (finding.tipo == "OBS" && currentActivity != null) {
dao.updateActivity(
currentActivity.copy(
observacoes = finding.descricao.trim(),
observacoes = stripAuditTags(finding.descricao),
synced = false,
lastUpdated = effectiveTimestamp
)
@@ -476,30 +476,44 @@ 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
}
val finalFotoPath = mergePreservingDeletedPhotos(localFotoPath, baseFotoPath)
val cleanLatestObs = stripAuditTags(latestLog.observacao) ?: stripAuditTags(activity.observacoes)
activity.copy(
percentualExecucao = latestLog.percentualNovo,
observacoes = latestLog.observacao ?: activity.observacoes,
observacoes = cleanLatestObs,
fotoPath = finalFotoPath,
synced = true,
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 +588,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 +743,46 @@ class MaintenanceRepository(
// Collect all local→URL replacements per OS to batch-update activity fotoPath
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()
for (history in historyList) {
val rawPath = history.fotoPath
@@ -716,7 +798,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
@@ -758,6 +839,14 @@ class MaintenanceRepository(
}
}
private fun stripAuditTags(text: String?): String? {
if (text.isNullOrBlank()) return null
var result = text.trim()
val regex = Regex("^(\\[[^\\]]+\\]\\s*)+")
result = regex.replace(result, "").trim()
return result.ifBlank { null }
}
private fun extractPhotoFileName(path: String): String {
val clean = path.trim().substringBefore("?").substringBefore("#")
// Handle both regular slashes and URL-encoded slashes (%2F)

View File

@@ -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)