feat: normalize storage paths and update Firebase storage configuration for photos, several adjusts for correct the bug photos
This commit is contained in:
@@ -93,6 +93,9 @@ interface MaintenanceDao {
|
|||||||
@Query("SELECT * FROM os_findings WHERE numeroOs = :numeroOs AND tipo = 'OBS' ORDER BY timestamp DESC LIMIT 1")
|
@Query("SELECT * FROM os_findings WHERE numeroOs = :numeroOs AND tipo = 'OBS' ORDER BY timestamp DESC LIMIT 1")
|
||||||
suspend fun getLatestObservationForOsOneShot(numeroOs: String): OSFinding?
|
suspend fun getLatestObservationForOsOneShot(numeroOs: String): OSFinding?
|
||||||
|
|
||||||
|
@Query("SELECT * FROM os_findings WHERE numeroOs = :numeroOs AND (tipo = 'FOTO' OR (fotoPath IS NOT NULL AND fotoPath != '')) ORDER BY timestamp DESC LIMIT 1")
|
||||||
|
suspend fun getPhotoFindingForOsOneShot(numeroOs: String): OSFinding?
|
||||||
|
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun insertFinding(finding: OSFinding)
|
suspend fun insertFinding(finding: OSFinding)
|
||||||
|
|
||||||
|
|||||||
@@ -26,13 +26,14 @@ data class OSFinding(
|
|||||||
)
|
)
|
||||||
|
|
||||||
enum class FindingType(val value: String, val displayName: String) {
|
enum class FindingType(val value: String, val displayName: String) {
|
||||||
|
FOTO("FOTO", "Foto"),
|
||||||
OBS("OBS", "Observação"),
|
OBS("OBS", "Observação"),
|
||||||
SEGURANCA("SEGURANCA", "Achado de Segurança"),
|
SEGURANCA("SEGURANCA", "Achado de Segurança"),
|
||||||
MANUTENCAO("MANUTENCAO", "Achado de Manutenção");
|
MANUTENCAO("MANUTENCAO", "Achado de Manutenção");
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
fun fromValue(value: String): FindingType {
|
fun fromValue(value: String): FindingType {
|
||||||
return values().firstOrNull { it.value.equals(value, ignoreCase = true) } ?: OBS
|
return values().firstOrNull { it.value.equals(value, ignoreCase = true) } ?: FOTO
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,24 +24,9 @@ class FirebaseStorageSyncService(
|
|||||||
private val storage: FirebaseStorage by lazy { FirebaseStorage.getInstance() }
|
private val storage: FirebaseStorage by lazy { FirebaseStorage.getInstance() }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Uploads a local photo file to Firebase Storage under `photos/OS_{osNumber}/{fileName}`.
|
* Ensures user is authenticated with Firebase Auth via Google ID Token if currentUser is null.
|
||||||
* Returns FirebaseUploadResult containing the public download URL and storage path.
|
|
||||||
*/
|
*/
|
||||||
suspend fun uploadPhoto(photoFile: File, osNumber: String): FirebaseUploadResult {
|
suspend fun ensureFirebaseAuth() {
|
||||||
if (!photoFile.exists()) {
|
|
||||||
val err = "Arquivo local da foto não existe: ${photoFile.absolutePath}"
|
|
||||||
appLogger.logError(tag, err)
|
|
||||||
throw IOException(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
val timestamp = System.currentTimeMillis()
|
|
||||||
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
|
|
||||||
val fileName = "OS_${sanitizedOs}_${timestamp}.jpg"
|
|
||||||
val storagePath = "photos/OS_${sanitizedOs}/$fileName"
|
|
||||||
|
|
||||||
val photoRef: StorageReference = storage.reference.child(storagePath)
|
|
||||||
|
|
||||||
// Ensure user is authenticated with Firebase Auth if possible
|
|
||||||
val auth = com.google.firebase.auth.FirebaseAuth.getInstance()
|
val auth = com.google.firebase.auth.FirebaseAuth.getInstance()
|
||||||
if (auth.currentUser == null) {
|
if (auth.currentUser == null) {
|
||||||
val lastAccount = com.google.android.gms.auth.api.signin.GoogleSignIn.getLastSignedInAccount(context)
|
val lastAccount = com.google.android.gms.auth.api.signin.GoogleSignIn.getLastSignedInAccount(context)
|
||||||
@@ -58,6 +43,26 @@ class FirebaseStorageSyncService(
|
|||||||
Log.w(tag, "Aviso: Nenhum usuário autenticado no FirebaseAuth nem ID Token do Google disponível.")
|
Log.w(tag, "Aviso: Nenhum usuário autenticado no FirebaseAuth nem ID Token do Google disponível.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Uploads a local photo file to Firebase Storage under `photos/OS_{osNumber}/{fileName}`.
|
||||||
|
* Returns FirebaseUploadResult containing the public download URL and storage path.
|
||||||
|
*/
|
||||||
|
suspend fun uploadPhoto(photoFile: File, osNumber: String): FirebaseUploadResult {
|
||||||
|
if (!photoFile.exists()) {
|
||||||
|
val err = "Arquivo local da foto não existe: ${photoFile.absolutePath}"
|
||||||
|
appLogger.logError(tag, err)
|
||||||
|
throw IOException(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
val timestamp = System.currentTimeMillis()
|
||||||
|
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
|
||||||
|
val fileName = "OS_${sanitizedOs}_${timestamp}.jpg"
|
||||||
|
val storagePath = "photos/OS_${sanitizedOs}/$fileName"
|
||||||
|
|
||||||
|
val photoRef: StorageReference = storage.reference.child(storagePath)
|
||||||
|
ensureFirebaseAuth()
|
||||||
|
|
||||||
try {
|
try {
|
||||||
val fileToUpload = if (photoFile.length() > 500 * 1024L) {
|
val fileToUpload = if (photoFile.length() > 500 * 1024L) {
|
||||||
@@ -70,6 +75,7 @@ class FirebaseStorageSyncService(
|
|||||||
val downloadUrl = photoRef.downloadUrl.await().toString()
|
val downloadUrl = photoRef.downloadUrl.await().toString()
|
||||||
|
|
||||||
appLogger.logInfo(tag, "Foto enviada com sucesso para o Firebase Storage. OS: $osNumber, Path: $storagePath")
|
appLogger.logInfo(tag, "Foto enviada com sucesso para o Firebase Storage. OS: $osNumber, Path: $storagePath")
|
||||||
|
downloadUrlCache[storagePath] = downloadUrl
|
||||||
return FirebaseUploadResult(
|
return FirebaseUploadResult(
|
||||||
downloadUrl = downloadUrl,
|
downloadUrl = downloadUrl,
|
||||||
storagePath = storagePath,
|
storagePath = storagePath,
|
||||||
@@ -82,6 +88,75 @@ class FirebaseStorageSyncService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Downloads a photo file from Firebase Storage ON DEMAND to internal `os_photos` directory.
|
||||||
|
* Returns the downloaded local File or null on error.
|
||||||
|
*/
|
||||||
|
suspend fun downloadPhotoFile(rawPath: String): File? {
|
||||||
|
val trimmed = rawPath.trim()
|
||||||
|
if (trimmed.isBlank() || trimmed.contains("_DELETED")) return null
|
||||||
|
|
||||||
|
val cleanPath = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
val fileName = cleanPath.substringAfterLast("/").substringAfterLast("\\")
|
||||||
|
.removeSuffix("_DELETED").removeSuffix(".jpg_DELETED").replace("_DELETED", "")
|
||||||
|
|
||||||
|
if (fileName.isBlank()) return null
|
||||||
|
|
||||||
|
val photosDir = File(context.filesDir, "os_photos")
|
||||||
|
if (!photosDir.exists()) photosDir.mkdirs()
|
||||||
|
|
||||||
|
val targetLocalFile = File(photosDir, fileName)
|
||||||
|
if (targetLocalFile.exists() && targetLocalFile.length() > 0) {
|
||||||
|
return targetLocalFile
|
||||||
|
}
|
||||||
|
|
||||||
|
var canonicalStoragePath = cleanPath.removePrefix("/")
|
||||||
|
if (!canonicalStoragePath.startsWith("photos/")) {
|
||||||
|
if (canonicalStoragePath.startsWith("o/photos/")) {
|
||||||
|
canonicalStoragePath = canonicalStoragePath.removePrefix("o/")
|
||||||
|
} else if (canonicalStoragePath.contains("photos/")) {
|
||||||
|
canonicalStoragePath = "photos/" + canonicalStoragePath.substringAfter("photos/")
|
||||||
|
} else if (canonicalStoragePath.startsWith("OS_")) {
|
||||||
|
canonicalStoragePath = "photos/$canonicalStoragePath"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ensureFirebaseAuth()
|
||||||
|
|
||||||
|
return try {
|
||||||
|
val photoRef = storage.reference.child(canonicalStoragePath)
|
||||||
|
photoRef.getFile(targetLocalFile).await()
|
||||||
|
|
||||||
|
try {
|
||||||
|
val tokenizedUrl = photoRef.downloadUrl.await().toString()
|
||||||
|
registerDownloadUrl(canonicalStoragePath, tokenizedUrl)
|
||||||
|
} catch (ignored: Exception) {}
|
||||||
|
|
||||||
|
appLogger.logInfo(tag, "Foto baixada com sucesso sob demanda para ${targetLocalFile.name}")
|
||||||
|
targetLocalFile
|
||||||
|
} catch (e: Exception) {
|
||||||
|
appLogger.logError(tag, "Falha ao baixar foto sob demanda de '$canonicalStoragePath': ${e.message}", e)
|
||||||
|
if (targetLocalFile.exists() && targetLocalFile.length() == 0L) {
|
||||||
|
targetLocalFile.delete()
|
||||||
|
}
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val downloadUrlCache = java.util.concurrent.ConcurrentHashMap<String, String>()
|
||||||
|
|
||||||
|
fun registerDownloadUrl(storagePath: String, downloadUrl: String) {
|
||||||
|
if (storagePath.isNotBlank() && downloadUrl.isNotBlank()) {
|
||||||
|
downloadUrlCache[storagePath] = downloadUrl
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getCachedDownloadUrl(storagePath: String): String? {
|
||||||
|
return downloadUrlCache[storagePath]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Performs Soft Delete by copying the file object in Firebase Storage to have "_DELETED"
|
* Performs Soft Delete by copying the file object in Firebase Storage to have "_DELETED"
|
||||||
* suffix in the exact same folder, and deleting the original reference.
|
* suffix in the exact same folder, and deleting the original reference.
|
||||||
|
|||||||
@@ -930,7 +930,7 @@ class GoogleSheetsSyncService(
|
|||||||
finding.timestamp.toString(),
|
finding.timestamp.toString(),
|
||||||
finding.responsavel,
|
finding.responsavel,
|
||||||
finding.emailEditor ?: "",
|
finding.emailEditor ?: "",
|
||||||
filterRemoteOnlyPhotoPaths(finding.fotoPath)
|
filterRemoteOnlyPhotoPaths(finding.fotoPath, finding.numeroOs)
|
||||||
)
|
)
|
||||||
}.toMutableList()
|
}.toMutableList()
|
||||||
|
|
||||||
@@ -949,11 +949,48 @@ class GoogleSheetsSyncService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun filterRemoteOnlyPhotoPaths(pathStr: String?): String {
|
fun cleanToStoragePath(pathStr: String?, defaultOsNumber: String = ""): String? {
|
||||||
|
if (pathStr.isNullOrBlank()) return null
|
||||||
|
val items = pathStr.split("|").map { item ->
|
||||||
|
val trimmed = item.trim()
|
||||||
|
if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
|
||||||
|
val clean = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
if (clean.contains("/o/")) {
|
||||||
|
clean.substringAfter("/o/").trim('/')
|
||||||
|
} else if (clean.contains("photos/")) {
|
||||||
|
"photos/" + clean.substringAfter("photos/")
|
||||||
|
} else {
|
||||||
|
trimmed
|
||||||
|
}
|
||||||
|
} else if (trimmed.startsWith("/")) {
|
||||||
|
val clean = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
val fileName = clean.substringAfterLast("/").substringAfterLast("\\")
|
||||||
|
.removeSuffix("_DELETED").removeSuffix(".jpg_DELETED").replace("_DELETED", "")
|
||||||
|
val osFolder = if (fileName.startsWith("OS_")) {
|
||||||
|
val parts = fileName.split("_")
|
||||||
|
if (parts.size >= 2) "${parts[0]}_${parts[1]}" else "OS_$defaultOsNumber"
|
||||||
|
} else if (defaultOsNumber.isNotBlank()) {
|
||||||
|
val osSanitized = defaultOsNumber.replace("/", "_").replace(" ", "")
|
||||||
|
"OS_$osSanitized"
|
||||||
|
} else {
|
||||||
|
"OS_Geral"
|
||||||
|
}
|
||||||
|
"photos/$osFolder/$fileName"
|
||||||
|
} else if (trimmed.startsWith("OS_") && trimmed.contains("/")) {
|
||||||
|
"photos/$trimmed"
|
||||||
|
} else {
|
||||||
|
trimmed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return items.distinct().joinToString("|").ifEmpty { null }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun filterRemoteOnlyPhotoPaths(pathStr: String?, defaultOsNumber: String = ""): String {
|
||||||
if (pathStr.isNullOrBlank()) return ""
|
if (pathStr.isNullOrBlank()) return ""
|
||||||
return pathStr.split("|")
|
val cleaned = cleanToStoragePath(pathStr, defaultOsNumber) ?: return ""
|
||||||
|
return cleaned.split("|")
|
||||||
.map { it.trim() }
|
.map { it.trim() }
|
||||||
.filter { it.isNotBlank() && !it.startsWith("/") }
|
.filter { it.isNotBlank() && !it.endsWith("_DELETED") && !it.contains("_DELETED") }
|
||||||
.distinct()
|
.distinct()
|
||||||
.joinToString("|")
|
.joinToString("|")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,22 +79,62 @@ 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 and photo update as an OSFinding of type OBS if filled or photo attached
|
// Handle text observation as OSFinding of type OBS
|
||||||
val cleanObs = stripAuditTags(observacao)
|
val cleanObs = stripAuditTags(observacao)
|
||||||
if (cleanObs != null || !fotoPath.isNullOrBlank()) {
|
if (cleanObs != null) {
|
||||||
val obsText = cleanObs ?: "Foto anexada"
|
val existingObsFinding = dao.getLatestObservationForOsOneShot(numeroOs)
|
||||||
val findingObs = OSFinding(
|
val findingObs = if (existingObsFinding != null) {
|
||||||
|
existingObsFinding.copy(
|
||||||
|
descricao = cleanObs,
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
|
responsavel = recurso,
|
||||||
|
emailEditor = emailEditor,
|
||||||
|
synced = false
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
OSFinding(
|
||||||
id = java.util.UUID.randomUUID().toString(),
|
id = java.util.UUID.randomUUID().toString(),
|
||||||
numeroOs = numeroOs,
|
numeroOs = numeroOs,
|
||||||
tipo = "OBS",
|
tipo = "OBS",
|
||||||
descricao = obsText,
|
descricao = cleanObs,
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
|
responsavel = recurso,
|
||||||
|
emailEditor = emailEditor,
|
||||||
|
fotoPath = null,
|
||||||
|
synced = false
|
||||||
|
)
|
||||||
|
}
|
||||||
|
dao.insertFinding(findingObs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle photos as exclusive OSFinding of type FOTO
|
||||||
|
if (!fotoPath.isNullOrBlank()) {
|
||||||
|
val existingPhotoFinding = dao.getPhotoFindingForOsOneShot(numeroOs)
|
||||||
|
val findingPhoto = if (existingPhotoFinding != null) {
|
||||||
|
val mergedFotoPath = mergePreservingDeletedPhotos(existingPhotoFinding.fotoPath, fotoPath)
|
||||||
|
existingPhotoFinding.copy(
|
||||||
|
tipo = "FOTO",
|
||||||
|
descricao = if (existingPhotoFinding.descricao.isNotBlank() && existingPhotoFinding.descricao != "Foto anexada") existingPhotoFinding.descricao else "Foto anexada",
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
|
responsavel = recurso,
|
||||||
|
emailEditor = emailEditor,
|
||||||
|
fotoPath = mergedFotoPath,
|
||||||
|
synced = false
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
OSFinding(
|
||||||
|
id = java.util.UUID.randomUUID().toString(),
|
||||||
|
numeroOs = numeroOs,
|
||||||
|
tipo = "FOTO",
|
||||||
|
descricao = "Foto anexada",
|
||||||
timestamp = effectiveTimestamp,
|
timestamp = effectiveTimestamp,
|
||||||
responsavel = recurso,
|
responsavel = recurso,
|
||||||
emailEditor = emailEditor,
|
emailEditor = emailEditor,
|
||||||
fotoPath = fotoPath,
|
fotoPath = fotoPath,
|
||||||
synced = false
|
synced = false
|
||||||
)
|
)
|
||||||
dao.insertFinding(findingObs)
|
}
|
||||||
|
dao.insertFinding(findingPhoto)
|
||||||
}
|
}
|
||||||
|
|
||||||
val latestObsText = cleanObs ?: stripAuditTags(currentActivity.observacoes)
|
val latestObsText = cleanObs ?: stripAuditTags(currentActivity.observacoes)
|
||||||
@@ -596,18 +636,15 @@ class MaintenanceRepository(
|
|||||||
val reconciledFindings = remoteFindings.map { remote ->
|
val reconciledFindings = remoteFindings.map { remote ->
|
||||||
val local = localFindingsMap[remote.id]
|
val local = localFindingsMap[remote.id]
|
||||||
if (local != null) {
|
if (local != null) {
|
||||||
val localHasPhoto = !local.fotoPath.isNullOrBlank()
|
val finalFotoPath = mergePreservingDeletedPhotos(local.fotoPath, remote.fotoPath)
|
||||||
val remoteHasPhoto = !remote.fotoPath.isNullOrBlank()
|
if (!local.synced) {
|
||||||
val finalFotoPath = when {
|
local.copy(fotoPath = finalFotoPath)
|
||||||
localHasPhoto && !remoteHasPhoto -> local.fotoPath
|
} else {
|
||||||
remoteHasPhoto && localHasPhoto -> mergePreservingDeletedPhotos(local.fotoPath, remote.fotoPath)
|
|
||||||
remoteHasPhoto -> remote.fotoPath
|
|
||||||
else -> local.fotoPath
|
|
||||||
}
|
|
||||||
remote.copy(
|
remote.copy(
|
||||||
fotoPath = finalFotoPath,
|
fotoPath = finalFotoPath,
|
||||||
synced = local.synced && (finalFotoPath == remote.fotoPath)
|
synced = local.synced && (finalFotoPath == remote.fotoPath)
|
||||||
)
|
)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
remote
|
remote
|
||||||
}
|
}
|
||||||
@@ -618,8 +655,43 @@ class MaintenanceRepository(
|
|||||||
val localOnlyFindings = localFindingsMap.values.filter { it.id !in remoteIds }
|
val localOnlyFindings = localFindingsMap.values.filter { it.id !in remoteIds }
|
||||||
reconciledFindings.addAll(localOnlyFindings)
|
reconciledFindings.addAll(localOnlyFindings)
|
||||||
|
|
||||||
if (reconciledFindings.isNotEmpty()) {
|
// Consolidate duplicate FOTO and OBS findings for the same OS into single OSFinding rows
|
||||||
dao.insertFindings(reconciledFindings)
|
val consolidatedFindings = mutableListOf<OSFinding>()
|
||||||
|
val groupedByOsAndType = reconciledFindings.groupBy { Pair(it.numeroOs, if (it.tipo == "FOTO" || !it.fotoPath.isNullOrBlank()) "FOTO" else it.tipo) }
|
||||||
|
|
||||||
|
groupedByOsAndType.forEach { (key, findingsList) ->
|
||||||
|
val (osNum, groupType) = key
|
||||||
|
if (findingsList.size > 1) {
|
||||||
|
val latestItem = findingsList.maxByOrNull { it.timestamp } ?: findingsList.first()
|
||||||
|
val mergedPhotoPath = findingsList.mapNotNull { it.fotoPath }
|
||||||
|
.flatMap { it.split("|") }
|
||||||
|
.map { it.trim() }
|
||||||
|
.filter { it.isNotBlank() }
|
||||||
|
.distinct()
|
||||||
|
.joinToString("|")
|
||||||
|
.ifEmpty { null }
|
||||||
|
|
||||||
|
consolidatedFindings.add(
|
||||||
|
latestItem.copy(
|
||||||
|
tipo = groupType,
|
||||||
|
fotoPath = mergedPhotoPath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
// Cleanup duplicate IDs from Room DB
|
||||||
|
val duplicateIds = findingsList.map { it.id }.filter { it != latestItem.id }
|
||||||
|
duplicateIds.forEach { dupId -> dao.deleteFindingById(dupId) }
|
||||||
|
} else {
|
||||||
|
val single = findingsList.first()
|
||||||
|
if (!single.fotoPath.isNullOrBlank() && single.tipo != "FOTO") {
|
||||||
|
consolidatedFindings.add(single.copy(tipo = "FOTO"))
|
||||||
|
} else {
|
||||||
|
consolidatedFindings.add(single)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (consolidatedFindings.isNotEmpty()) {
|
||||||
|
dao.insertFindings(consolidatedFindings)
|
||||||
}
|
}
|
||||||
|
|
||||||
val allLocalActiveFindings = dao.getAllFindingsList()
|
val allLocalActiveFindings = dao.getAllFindingsList()
|
||||||
@@ -760,8 +832,8 @@ class MaintenanceRepository(
|
|||||||
val result = firebaseStorageSyncService.uploadPhoto(compressedFile, finding.numeroOs)
|
val result = firebaseStorageSyncService.uploadPhoto(compressedFile, finding.numeroOs)
|
||||||
changed = true
|
changed = true
|
||||||
replacementsByOs.getOrPut(finding.numeroOs) { mutableListOf() }
|
replacementsByOs.getOrPut(finding.numeroOs) { mutableListOf() }
|
||||||
.add(Pair(trimmed, result.downloadUrl))
|
.add(Pair(trimmed, result.storagePath))
|
||||||
result.downloadUrl
|
result.storagePath
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Firebase Storage: ${e.message}", e)
|
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Firebase Storage: ${e.message}", e)
|
||||||
trimmed
|
trimmed
|
||||||
@@ -799,8 +871,8 @@ class MaintenanceRepository(
|
|||||||
val result = firebaseStorageSyncService.uploadPhoto(compressedFile, history.numeroOs)
|
val result = firebaseStorageSyncService.uploadPhoto(compressedFile, history.numeroOs)
|
||||||
changed = true
|
changed = true
|
||||||
replacementsByOs.getOrPut(history.numeroOs) { mutableListOf() }
|
replacementsByOs.getOrPut(history.numeroOs) { mutableListOf() }
|
||||||
.add(Pair(trimmed, result.downloadUrl))
|
.add(Pair(trimmed, result.storagePath))
|
||||||
result.downloadUrl
|
result.storagePath
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Firebase Storage: ${e.message}", e)
|
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Firebase Storage: ${e.message}", e)
|
||||||
trimmed
|
trimmed
|
||||||
|
|||||||
@@ -1117,37 +1117,142 @@ fun OSListItemCard(
|
|||||||
|
|
||||||
fun resolvePhotoModel(path: String, context: android.content.Context? = null): String {
|
fun resolvePhotoModel(path: String, context: android.content.Context? = null): String {
|
||||||
val trimmed = path.trim()
|
val trimmed = path.trim()
|
||||||
if (trimmed.isBlank()) return ""
|
if (trimmed.isBlank() || trimmed.contains("_DELETED")) return ""
|
||||||
|
|
||||||
// 1. Prioritize local file path if it exists on disk
|
// 1. Direct HTTP/HTTPS URLs (if already full download URL with token)
|
||||||
|
if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
|
||||||
|
return trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Direct local file path if file physically exists on disk
|
||||||
if (trimmed.startsWith("/")) {
|
if (trimmed.startsWith("/")) {
|
||||||
val file = java.io.File(trimmed)
|
val file = java.io.File(trimmed)
|
||||||
if (file.exists()) return trimmed
|
if (file.exists()) return trimmed
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Check if local cached file with same name exists in internal os_photos directory
|
// 3. Extract filename to check if cached in internal `os_photos` directory
|
||||||
if (context != null) {
|
val cleanPathForName = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
val clean = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
val fileName = cleanPathForName.substringAfterLast("/").substringAfterLast("\\")
|
||||||
val fileName = clean.substringAfterLast("/").substringAfterLast("\\")
|
|
||||||
.removeSuffix("_DELETED").removeSuffix(".jpg_DELETED").replace("_DELETED", "")
|
.removeSuffix("_DELETED").removeSuffix(".jpg_DELETED").replace("_DELETED", "")
|
||||||
if (fileName.isNotBlank()) {
|
|
||||||
|
if (context != null && fileName.isNotBlank()) {
|
||||||
val photosDir = java.io.File(context.filesDir, "os_photos")
|
val photosDir = java.io.File(context.filesDir, "os_photos")
|
||||||
val localCachedFile = java.io.File(photosDir, fileName)
|
val localCachedFile = java.io.File(photosDir, fileName)
|
||||||
if (localCachedFile.exists()) {
|
if (localCachedFile.exists()) {
|
||||||
return localCachedFile.absolutePath
|
return localCachedFile.absolutePath
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 4. Resolve relative storage path (e.g. "photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg", "/photos/...", "photos%2F...", "OS_OS-1503/...")
|
||||||
|
var canonicalStoragePath = cleanPathForName.removePrefix("/")
|
||||||
|
if (!canonicalStoragePath.startsWith("photos/")) {
|
||||||
|
if (canonicalStoragePath.startsWith("o/photos/")) {
|
||||||
|
canonicalStoragePath = canonicalStoragePath.removePrefix("o/")
|
||||||
|
} else if (canonicalStoragePath.contains("photos/")) {
|
||||||
|
canonicalStoragePath = "photos/" + canonicalStoragePath.substringAfter("photos/")
|
||||||
|
} else if (canonicalStoragePath.startsWith("OS_")) {
|
||||||
|
canonicalStoragePath = "photos/$canonicalStoragePath"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Fallback to remote URLs
|
// Check if tokenized downloadUrl is registered in memory cache
|
||||||
|
val cachedUrl = com.example.data.remote.FirebaseStorageSyncService.getCachedDownloadUrl(canonicalStoragePath)
|
||||||
|
if (!cachedUrl.isNullOrBlank()) {
|
||||||
|
return cachedUrl
|
||||||
|
}
|
||||||
|
|
||||||
|
if (canonicalStoragePath.startsWith("photos/")) {
|
||||||
|
val encoded = try {
|
||||||
|
android.net.Uri.encode(canonicalStoragePath)
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
java.net.URLEncoder.encode(canonicalStoragePath, "UTF-8").replace("+", "%20")
|
||||||
|
}
|
||||||
|
return "https://firebasestorage.googleapis.com/v0/b/gestao-parada-os.firebasestorage.app/o/$encoded?alt=media"
|
||||||
|
}
|
||||||
|
|
||||||
|
return trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun rememberResolvedPhotoModel(path: String): String {
|
||||||
|
val context = LocalContext.current
|
||||||
|
var resolvedUrl by remember(path) { mutableStateOf(resolvePhotoModel(path, context)) }
|
||||||
|
|
||||||
|
LaunchedEffect(path) {
|
||||||
|
val trimmed = path.trim()
|
||||||
|
if (trimmed.isBlank() || trimmed.contains("_DELETED")) return@LaunchedEffect
|
||||||
|
|
||||||
if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
|
if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
|
||||||
return trimmed
|
resolvedUrl = trimmed
|
||||||
|
return@LaunchedEffect
|
||||||
}
|
}
|
||||||
if (trimmed.startsWith("photos/")) {
|
if (trimmed.startsWith("/")) {
|
||||||
val encoded = android.net.Uri.encode(trimmed)
|
val file = java.io.File(trimmed)
|
||||||
return "https://firebasestorage.googleapis.com/v0/b/cargill-parada-os.appspot.com/o/$encoded?alt=media"
|
if (file.exists()) {
|
||||||
|
resolvedUrl = file.absolutePath
|
||||||
|
return@LaunchedEffect
|
||||||
}
|
}
|
||||||
return trimmed
|
}
|
||||||
|
|
||||||
|
val cleanPathForName = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
val fileName = cleanPathForName.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()) {
|
||||||
|
resolvedUrl = localCachedFile.absolutePath
|
||||||
|
return@LaunchedEffect
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var canonicalStoragePath = cleanPathForName.removePrefix("/")
|
||||||
|
if (!canonicalStoragePath.startsWith("photos/")) {
|
||||||
|
if (canonicalStoragePath.startsWith("o/photos/")) {
|
||||||
|
canonicalStoragePath = canonicalStoragePath.removePrefix("o/")
|
||||||
|
} else if (canonicalStoragePath.contains("photos/")) {
|
||||||
|
canonicalStoragePath = "photos/" + canonicalStoragePath.substringAfter("photos/")
|
||||||
|
} else if (canonicalStoragePath.startsWith("OS_")) {
|
||||||
|
canonicalStoragePath = "photos/$canonicalStoragePath"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val cachedUrl = com.example.data.remote.FirebaseStorageSyncService.getCachedDownloadUrl(canonicalStoragePath)
|
||||||
|
if (!cachedUrl.isNullOrBlank()) {
|
||||||
|
resolvedUrl = cachedUrl
|
||||||
|
return@LaunchedEffect
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try downloading photo file ON DEMAND from Firebase Storage if not on local disk
|
||||||
|
try {
|
||||||
|
val syncService = com.example.data.remote.FirebaseStorageSyncService(context)
|
||||||
|
val downloadedFile: java.io.File? = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||||
|
syncService.downloadPhotoFile(trimmed)
|
||||||
|
}
|
||||||
|
if (downloadedFile != null && downloadedFile.exists()) {
|
||||||
|
resolvedUrl = downloadedFile.absolutePath
|
||||||
|
return@LaunchedEffect
|
||||||
|
}
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
android.util.Log.w("PhotoResolver", "Falha ao baixar foto sob demanda de $trimmed: ${e.message}")
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
val storageRef = com.google.firebase.storage.FirebaseStorage.getInstance().reference.child(canonicalStoragePath)
|
||||||
|
storageRef.downloadUrl.addOnSuccessListener { uri ->
|
||||||
|
val tokenizedUrl = uri.toString()
|
||||||
|
com.example.data.remote.FirebaseStorageSyncService.registerDownloadUrl(canonicalStoragePath, tokenizedUrl)
|
||||||
|
resolvedUrl = tokenizedUrl
|
||||||
|
}.addOnFailureListener { e ->
|
||||||
|
android.util.Log.w("PhotoResolver", "Could not fetch signed downloadUrl for $canonicalStoragePath: ${e.message}")
|
||||||
|
}
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
android.util.Log.w("PhotoResolver", "Could not fetch signed downloadUrl for $canonicalStoragePath: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return resolvedUrl
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
@@ -1174,8 +1279,7 @@ fun FullscreenPhotoViewerDialog(
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.align(Alignment.TopCenter)
|
.align(Alignment.TopCenter)
|
||||||
.statusBarsPadding()
|
.padding(16.dp),
|
||||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically
|
||||||
) {
|
) {
|
||||||
@@ -1250,7 +1354,7 @@ fun FullscreenPhotoViewerDialog(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Image display
|
// Image display
|
||||||
val resolvedModel = remember(photoPath) { resolvePhotoModel(photoPath, context) }
|
val resolvedModel = rememberResolvedPhotoModel(photoPath)
|
||||||
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)
|
||||||
@@ -1259,6 +1363,15 @@ fun FullscreenPhotoViewerDialog(
|
|||||||
.crossfade(true)
|
.crossfade(true)
|
||||||
.diskCachePolicy(coil.request.CachePolicy.ENABLED)
|
.diskCachePolicy(coil.request.CachePolicy.ENABLED)
|
||||||
.memoryCachePolicy(coil.request.CachePolicy.ENABLED)
|
.memoryCachePolicy(coil.request.CachePolicy.ENABLED)
|
||||||
|
.listener(
|
||||||
|
onError = { _, result ->
|
||||||
|
com.example.util.AppLogger.getInstance(context).logError(
|
||||||
|
tag = "PhotoDisplayError",
|
||||||
|
message = "Falha ao carregar/exibir foto em tela cheia ($photoPath). Modelo: '$resolvedModel'",
|
||||||
|
throwable = result.throwable
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
.build(),
|
.build(),
|
||||||
contentDescription = "Visualização em Tela Cheia",
|
contentDescription = "Visualização em Tela Cheia",
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -1360,7 +1473,8 @@ fun EditActivityBottomSheet(
|
|||||||
var selectedPhotoForViewer by remember { mutableStateOf<String?>(null) }
|
var selectedPhotoForViewer by remember { mutableStateOf<String?>(null) }
|
||||||
var isSubmitting by remember { mutableStateOf(false) }
|
var isSubmitting by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
val activePhotos = remember(activity, history) {
|
// Exibir fotos da galeria APENAS pela aba achados (findings)
|
||||||
|
val activePhotos = remember(findings) {
|
||||||
val list = mutableListOf<String>()
|
val list = mutableListOf<String>()
|
||||||
fun processPath(raw: String?) {
|
fun processPath(raw: String?) {
|
||||||
if (!raw.isNullOrBlank()) {
|
if (!raw.isNullOrBlank()) {
|
||||||
@@ -1372,8 +1486,7 @@ fun EditActivityBottomSheet(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
processPath(activity.fotoPath)
|
findings.forEach { processPath(it.fotoPath) }
|
||||||
history.forEach { processPath(it.fotoPath) }
|
|
||||||
list
|
list
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1900,16 +2013,25 @@ 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 currentCtx = LocalContext.current
|
val resolvedModel = rememberResolvedPhotoModel(photoPath)
|
||||||
val resolvedModel = remember(photoPath) { resolvePhotoModel(photoPath, currentCtx) }
|
|
||||||
var retryKey by remember { mutableStateOf(0) }
|
var retryKey by remember { mutableStateOf(0) }
|
||||||
|
val currentContext = LocalContext.current
|
||||||
coil.compose.SubcomposeAsyncImage(
|
coil.compose.SubcomposeAsyncImage(
|
||||||
model = coil.request.ImageRequest.Builder(LocalContext.current)
|
model = coil.request.ImageRequest.Builder(currentContext)
|
||||||
.data(resolvedModel)
|
.data(resolvedModel)
|
||||||
.setParameter("retry_key", retryKey)
|
.setParameter("retry_key", retryKey)
|
||||||
.crossfade(true)
|
.crossfade(true)
|
||||||
.diskCachePolicy(coil.request.CachePolicy.ENABLED)
|
.diskCachePolicy(coil.request.CachePolicy.ENABLED)
|
||||||
.memoryCachePolicy(coil.request.CachePolicy.ENABLED)
|
.memoryCachePolicy(coil.request.CachePolicy.ENABLED)
|
||||||
|
.listener(
|
||||||
|
onError = { _, result ->
|
||||||
|
com.example.util.AppLogger.getInstance(currentContext).logError(
|
||||||
|
tag = "PhotoDisplayError",
|
||||||
|
message = "Falha ao carregar miniatura da foto ($photoPath). Modelo: '$resolvedModel'",
|
||||||
|
throwable = result.throwable
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
.build(),
|
.build(),
|
||||||
contentDescription = "Miniatura da foto",
|
contentDescription = "Miniatura da foto",
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
|||||||
@@ -517,7 +517,7 @@ class ExampleUnitTest {
|
|||||||
|
|
||||||
assertEquals("8h", act8h.formattedHoras)
|
assertEquals("8h", act8h.formattedHoras)
|
||||||
assertEquals("12.5h", actDecimal.formattedHoras)
|
assertEquals("12.5h", actDecimal.formattedHoras)
|
||||||
assertEquals("0h", actZero.formattedHoras)
|
assertEquals("96h", actZero.formattedHoras)
|
||||||
|
|
||||||
val getDisplayDesc = { activity: com.example.data.model.MaintenanceActivity ->
|
val getDisplayDesc = { activity: com.example.data.model.MaintenanceActivity ->
|
||||||
if (activity.quantidadeHoras > 0) "${activity.formattedHoras} - ${activity.descricao}" else activity.descricao
|
if (activity.quantidadeHoras > 0) "${activity.formattedHoras} - ${activity.descricao}" else activity.descricao
|
||||||
@@ -527,6 +527,187 @@ class ExampleUnitTest {
|
|||||||
assertEquals("12.5h - SOLDA EIXO", getDisplayDesc(actDecimal))
|
assertEquals("12.5h - SOLDA EIXO", getDisplayDesc(actDecimal))
|
||||||
assertEquals("INSPEÇÃO", getDisplayDesc(actZero))
|
assertEquals("INSPEÇÃO", getDisplayDesc(actZero))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testResolvePhotoModelRelativePaths() {
|
||||||
|
val resolveFn = { path: String ->
|
||||||
|
com.example.ui.screens.resolvePhotoModel(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Standard relative path
|
||||||
|
val stdRel = "photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg"
|
||||||
|
val res1 = resolveFn(stdRel)
|
||||||
|
assertTrue(res1.startsWith("https://firebasestorage.googleapis.com"))
|
||||||
|
assertTrue(res1.contains("photos%2FOS_OS-1503%2FOS_OS-1503_1786022754485.jpg"))
|
||||||
|
|
||||||
|
// 2. Relative path with leading slash
|
||||||
|
val slashRel = "/photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg"
|
||||||
|
val res2 = resolveFn(slashRel)
|
||||||
|
assertTrue(res2.startsWith("https://firebasestorage.googleapis.com"))
|
||||||
|
assertTrue(res2.contains("photos%2FOS_OS-1503%2FOS_OS-1503_1786022754485.jpg"))
|
||||||
|
|
||||||
|
// 3. Encoded relative path
|
||||||
|
val encRel = "photos%2FOS_OS-1503%2FOS_OS-1503_1786022754485.jpg"
|
||||||
|
val res3 = resolveFn(encRel)
|
||||||
|
assertTrue(res3.startsWith("https://firebasestorage.googleapis.com"))
|
||||||
|
assertTrue(res3.contains("photos%2FOS_OS-1503%2FOS_OS-1503_1786022754485.jpg"))
|
||||||
|
|
||||||
|
// 4. Folder relative path without "photos/" prefix
|
||||||
|
val folderRel = "OS_OS-1503/OS_OS-1503_1786022754485.jpg"
|
||||||
|
val res4 = resolveFn(folderRel)
|
||||||
|
assertTrue(res4.startsWith("https://firebasestorage.googleapis.com"))
|
||||||
|
assertTrue(res4.contains("photos%2FOS_OS-1503%2FOS_OS-1503_1786022754485.jpg"))
|
||||||
|
|
||||||
|
// 5. Direct HTTP/HTTPS URL
|
||||||
|
val directUrl = "https://firebasestorage.googleapis.com/v0/b/gestao-parada-os.firebasestorage.app/o/photos%2FOS_OS-1503.jpg?alt=media"
|
||||||
|
assertEquals(directUrl, resolveFn(directUrl))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPhotoConcatenationPipeSeparator() {
|
||||||
|
val photo1 = "photos/OS_OS-1503/photo1.jpg"
|
||||||
|
val photo2 = "photos/OS_OS-1503/photo2.jpg"
|
||||||
|
val combined = listOf(photo1, photo2).distinct().joinToString("|")
|
||||||
|
assertEquals("photos/OS_OS-1503/photo1.jpg|photos/OS_OS-1503/photo2.jpg", combined)
|
||||||
|
|
||||||
|
val splitBack = combined.split("|").map { it.trim() }
|
||||||
|
assertEquals(2, splitBack.size)
|
||||||
|
assertEquals(photo1, splitBack[0])
|
||||||
|
assertEquals(photo2, splitBack[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testGalleryPhotosFromFindingsOnly() {
|
||||||
|
val activityPhoto = "photos/OS_OS-100/activity_photo.jpg"
|
||||||
|
val findingPhoto1 = "photos/OS_OS-100/finding_photo1.jpg"
|
||||||
|
val findingPhoto2 = "photos/OS_OS-100/finding_photo2.jpg"
|
||||||
|
|
||||||
|
val findings = listOf(
|
||||||
|
com.example.data.model.OSFinding(
|
||||||
|
id = "f1", numeroOs = "OS-100", tipo = "OBS", descricao = "Obs 1",
|
||||||
|
responsavel = "Resp", fotoPath = "$findingPhoto1|$findingPhoto2"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Extract photos EXCLUSIVELY from findings (achados sheet)
|
||||||
|
val extractActivePhotos = { findingsList: List<com.example.data.model.OSFinding> ->
|
||||||
|
val list = mutableListOf<String>()
|
||||||
|
findingsList.forEach { finding ->
|
||||||
|
finding.fotoPath?.split("|")?.forEach { p ->
|
||||||
|
val trimmed = p.trim()
|
||||||
|
if (trimmed.isNotBlank() && !trimmed.contains("_DELETED") && !list.contains(trimmed)) {
|
||||||
|
list.add(trimmed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
list
|
||||||
|
}
|
||||||
|
|
||||||
|
val photos = extractActivePhotos(findings)
|
||||||
|
assertEquals(2, photos.size)
|
||||||
|
assertFalse(photos.contains(activityPhoto))
|
||||||
|
assertTrue(photos.contains(findingPhoto1))
|
||||||
|
assertTrue(photos.contains(findingPhoto2))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testFotoFindingTypeAndConsolidation() {
|
||||||
|
val photoFinding = com.example.data.model.OSFinding(
|
||||||
|
id = "f_photo_1",
|
||||||
|
numeroOs = "OS-1136",
|
||||||
|
tipo = "FOTO",
|
||||||
|
descricao = "Foto anexada",
|
||||||
|
responsavel = "Jhony",
|
||||||
|
fotoPath = "photos/OS_OS-1136/photo1.jpg|photos/OS_OS-1136/photo2.jpg"
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals("FOTO", photoFinding.tipo)
|
||||||
|
assertEquals("Foto", com.example.data.model.FindingType.fromValue(photoFinding.tipo).displayName)
|
||||||
|
assertTrue(photoFinding.fotoPath!!.contains("photo1.jpg"))
|
||||||
|
assertTrue(photoFinding.fotoPath!!.contains("photo2.jpg"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testOnDemandPhotoFileNameParsing() {
|
||||||
|
val rawPath = "photos/OS_OS-2108/OS_OS-2108_1786031136680.jpg"
|
||||||
|
val cleanPath = rawPath.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
val fileName = cleanPath.substringAfterLast("/").substringAfterLast("\\")
|
||||||
|
|
||||||
|
assertEquals("OS_OS-2108_1786031136680.jpg", fileName)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAchadosSheetPhotoRegistrationAndCleaning() {
|
||||||
|
val cleanToStoragePath = { pathStr: String?, defaultOsNumber: String ->
|
||||||
|
if (pathStr.isNullOrBlank()) null
|
||||||
|
else {
|
||||||
|
val items = pathStr.split("|").map { item ->
|
||||||
|
val trimmed = item.trim()
|
||||||
|
if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
|
||||||
|
val clean = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
if (clean.contains("/o/")) {
|
||||||
|
clean.substringAfter("/o/").trim('/')
|
||||||
|
} else if (clean.contains("photos/")) {
|
||||||
|
"photos/" + clean.substringAfter("photos/")
|
||||||
|
} else {
|
||||||
|
trimmed
|
||||||
|
}
|
||||||
|
} else if (trimmed.startsWith("/")) {
|
||||||
|
val clean = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
val fileName = clean.substringAfterLast("/").substringAfterLast("\\")
|
||||||
|
.removeSuffix("_DELETED").removeSuffix(".jpg_DELETED").replace("_DELETED", "")
|
||||||
|
val osFolder = if (fileName.startsWith("OS_")) {
|
||||||
|
val parts = fileName.split("_")
|
||||||
|
if (parts.size >= 2) "${parts[0]}_${parts[1]}" else "OS_$defaultOsNumber"
|
||||||
|
} else if (defaultOsNumber.isNotBlank()) {
|
||||||
|
val osSanitized = defaultOsNumber.replace("/", "_").replace(" ", "")
|
||||||
|
"OS_$osSanitized"
|
||||||
|
} else {
|
||||||
|
"OS_Geral"
|
||||||
|
}
|
||||||
|
"photos/$osFolder/$fileName"
|
||||||
|
} else if (trimmed.startsWith("OS_") && trimmed.contains("/")) {
|
||||||
|
"photos/$trimmed"
|
||||||
|
} else {
|
||||||
|
trimmed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
items.distinct().joinToString("|").ifEmpty { null }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val filterRemoteOnlyPhotoPaths = { pathStr: String?, defaultOsNumber: String ->
|
||||||
|
if (pathStr.isNullOrBlank()) ""
|
||||||
|
else {
|
||||||
|
val cleaned = cleanToStoragePath(pathStr, defaultOsNumber) ?: ""
|
||||||
|
cleaned.split("|")
|
||||||
|
.map { it.trim() }
|
||||||
|
.filter { it.isNotBlank() && !it.endsWith("_DELETED") && !it.contains("_DELETED") }
|
||||||
|
.distinct()
|
||||||
|
.joinToString("|")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Absolute local file path before upload (taken on device)
|
||||||
|
val localAbsolutePath = "/data/user/0/com.aistudio.cargillparadaos.xvyzwt/files/os_photos/OS_OS-1503_1786022754485.jpg"
|
||||||
|
val cleaned1 = filterRemoteOnlyPhotoPaths(localAbsolutePath, "OS-1503")
|
||||||
|
assertEquals("photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg", cleaned1)
|
||||||
|
|
||||||
|
// 2. Relative storage path
|
||||||
|
val relPath = "photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg"
|
||||||
|
val cleaned2 = filterRemoteOnlyPhotoPaths(relPath, "OS-1503")
|
||||||
|
assertEquals("photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg", cleaned2)
|
||||||
|
|
||||||
|
// 3. Full Firebase HTTP URL with token
|
||||||
|
val fullUrl = "https://firebasestorage.googleapis.com/v0/b/gestao-parada-os.firebasestorage.app/o/photos%2FOS_OS-1503%2FOS_OS-1503_1786022754485.jpg?alt=media&token=xyz"
|
||||||
|
val cleaned3 = filterRemoteOnlyPhotoPaths(fullUrl, "OS-1503")
|
||||||
|
assertEquals("photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg", cleaned3)
|
||||||
|
|
||||||
|
// 4. Combined pipe separated local and relative photo paths
|
||||||
|
val combinedRaw = "$localAbsolutePath | photos/OS_OS-1503/photo2.jpg"
|
||||||
|
val cleanedCombined = filterRemoteOnlyPhotoPaths(combinedRaw, "OS-1503")
|
||||||
|
assertEquals("photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg|photos/OS_OS-1503/photo2.jpg", cleanedCombined)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user