refactor: support multiple photo attachments per maintenance entry using pipe-delimited paths and list-based UI management
This commit is contained in:
@@ -468,29 +468,47 @@ class MaintenanceRepository(
|
||||
|
||||
val historyList = dao.getAllHistoryList()
|
||||
for (history in historyList) {
|
||||
val path = history.fotoPath
|
||||
if (!path.isNullOrBlank() && !path.startsWith("http://") && !path.startsWith("https://") && !path.endsWith("_DELETED")) {
|
||||
val file = java.io.File(path)
|
||||
if (file.exists()) {
|
||||
try {
|
||||
val result = driveSyncService.uploadPhotoToDrive(file, history.numeroOs)
|
||||
val updatedHistory = history.copy(fotoPath = result.webViewLink)
|
||||
dao.insertHistory(updatedHistory)
|
||||
|
||||
val activity = dao.getActivityByOsOneShot(history.numeroOs)
|
||||
if (activity != null && activity.fotoPath == path) {
|
||||
dao.updateActivity(activity.copy(fotoPath = result.webViewLink))
|
||||
val rawPath = history.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")) {
|
||||
val file = java.io.File(trimmed)
|
||||
if (file.exists()) {
|
||||
try {
|
||||
val result = driveSyncService.uploadPhotoToDrive(file, history.numeroOs)
|
||||
changed = true
|
||||
result.webViewLink
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Drive: ${e.message}", e)
|
||||
trimmed
|
||||
}
|
||||
} else {
|
||||
trimmed
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto para o Drive: ${e.message}", e)
|
||||
} else {
|
||||
trimmed
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
val updatedJoinedPath = uploadedSubPaths.joinToString("|")
|
||||
val updatedHistory = history.copy(fotoPath = updatedJoinedPath)
|
||||
dao.insertHistory(updatedHistory)
|
||||
|
||||
val activity = dao.getActivityByOsOneShot(history.numeroOs)
|
||||
if (activity != null) {
|
||||
dao.updateActivity(activity.copy(fotoPath = updatedJoinedPath))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun softDeletePhoto(fotoPath: String, osNumber: String) = withContext(Dispatchers.IO) {
|
||||
val fileId = extractDriveFileId(fotoPath)
|
||||
suspend fun softDeletePhoto(targetPhotoPath: String, osNumber: String) = withContext(Dispatchers.IO) {
|
||||
val fileId = extractDriveFileId(targetPhotoPath)
|
||||
if (fileId != null && isCurrentlyConnected()) {
|
||||
try {
|
||||
val fileName = "OS_${osNumber}_photo.jpg"
|
||||
@@ -500,18 +518,26 @@ class MaintenanceRepository(
|
||||
}
|
||||
}
|
||||
|
||||
val deletedPath = if (fotoPath.endsWith("_DELETED")) fotoPath else "${fotoPath}_DELETED"
|
||||
val deletedTarget = if (targetPhotoPath.endsWith("_DELETED")) targetPhotoPath else "${targetPhotoPath}_DELETED"
|
||||
|
||||
// Update history entries by replacing target photo or appending _DELETED
|
||||
val historyList = dao.getHistoryForOsOneShot(osNumber)
|
||||
for (hist in historyList) {
|
||||
if (hist.fotoPath == fotoPath) {
|
||||
dao.insertHistory(hist.copy(fotoPath = deletedPath))
|
||||
val pathStr = hist.fotoPath
|
||||
if (!pathStr.isNullOrBlank() && pathStr.contains(targetPhotoPath)) {
|
||||
val updatedPaths = pathStr.split("|").map { p ->
|
||||
if (p.trim() == targetPhotoPath.trim()) deletedTarget else p
|
||||
}
|
||||
dao.insertHistory(hist.copy(fotoPath = updatedPaths.joinToString("|")))
|
||||
}
|
||||
}
|
||||
|
||||
val activity = dao.getActivityByOsOneShot(osNumber)
|
||||
if (activity != null && activity.fotoPath == fotoPath) {
|
||||
dao.updateActivity(activity.copy(fotoPath = deletedPath, synced = false))
|
||||
if (activity != null && !activity.fotoPath.isNullOrBlank() && activity.fotoPath.contains(targetPhotoPath)) {
|
||||
val updatedPaths = activity.fotoPath.split("|").map { p ->
|
||||
if (p.trim() == targetPhotoPath.trim()) deletedTarget else p
|
||||
}
|
||||
dao.updateActivity(activity.copy(fotoPath = updatedPaths.joinToString("|"), synced = false))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1261,21 +1261,25 @@ fun EditActivityBottomSheet(
|
||||
|
||||
var progressValue by remember(activity) { mutableStateOf(activity.percentualExecucao.toFloat()) }
|
||||
var observationText by remember { mutableStateOf("") }
|
||||
var selectedNewPhotoPath by remember { mutableStateOf<String?>(null) }
|
||||
val newPhotosList = remember { mutableStateListOf<String>() }
|
||||
var tempCameraPath by remember { mutableStateOf<String?>(null) }
|
||||
var selectedPhotoForViewer by remember { mutableStateOf<String?>(null) }
|
||||
var isSubmitting by remember { mutableStateOf(false) }
|
||||
|
||||
val activePhotos = remember(activity, history) {
|
||||
val list = mutableListOf<String>()
|
||||
activity.fotoPath?.let { if (it.isNotBlank() && !it.endsWith("_DELETED")) list.add(it) }
|
||||
history.forEach { log ->
|
||||
log.fotoPath?.let {
|
||||
if (it.isNotBlank() && !it.endsWith("_DELETED") && !list.contains(it)) {
|
||||
list.add(it)
|
||||
fun processPath(raw: String?) {
|
||||
if (!raw.isNullOrBlank()) {
|
||||
raw.split("|").forEach { p ->
|
||||
val trimmed = p.trim()
|
||||
if (trimmed.isNotBlank() && !trimmed.endsWith("_DELETED") && !list.contains(trimmed)) {
|
||||
list.add(trimmed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
processPath(activity.fotoPath)
|
||||
history.forEach { processPath(it.fotoPath) }
|
||||
list
|
||||
}
|
||||
|
||||
@@ -1283,7 +1287,7 @@ fun EditActivityBottomSheet(
|
||||
contract = ActivityResultContracts.TakePicture()
|
||||
) { success ->
|
||||
if (success && tempCameraPath != null) {
|
||||
selectedNewPhotoPath = tempCameraPath
|
||||
newPhotosList.add(tempCameraPath!!)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1292,7 +1296,7 @@ fun EditActivityBottomSheet(
|
||||
) { uri: Uri? ->
|
||||
uri?.let {
|
||||
val savedPath = onSavePhotoFromUri(it)
|
||||
selectedNewPhotoPath = savedPath
|
||||
newPhotosList.add(savedPath)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1435,12 +1439,26 @@ fun EditActivityBottomSheet(
|
||||
|
||||
// Photo Attachment & Horizontal Gallery Section
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(
|
||||
text = "Fotos de Campo da OS",
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 14.sp,
|
||||
color = BrandBlack
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = "Fotos de Campo da OS",
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 14.sp,
|
||||
color = BrandBlack
|
||||
)
|
||||
if (newPhotosList.isNotEmpty()) {
|
||||
Text(
|
||||
text = "${newPhotosList.size} foto(s) pendente(s)",
|
||||
fontSize = 11.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = BrandGreen
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Action buttons: Camera & Gallery
|
||||
Row(
|
||||
@@ -1479,12 +1497,8 @@ fun EditActivityBottomSheet(
|
||||
}
|
||||
|
||||
// Horizontal Gallery (LazyRow)
|
||||
val displayPhotos = remember(activePhotos, selectedNewPhotoPath) {
|
||||
if (selectedNewPhotoPath != null && !activePhotos.contains(selectedNewPhotoPath)) {
|
||||
listOf(selectedNewPhotoPath!!) + activePhotos
|
||||
} else {
|
||||
activePhotos
|
||||
}
|
||||
val displayPhotos = remember(activePhotos, newPhotosList.toList()) {
|
||||
(newPhotosList + activePhotos).distinct()
|
||||
}
|
||||
|
||||
if (displayPhotos.isNotEmpty()) {
|
||||
@@ -1495,7 +1509,7 @@ fun EditActivityBottomSheet(
|
||||
.padding(vertical = 4.dp)
|
||||
) {
|
||||
items(displayPhotos) { photoPath ->
|
||||
val isNew = photoPath == selectedNewPhotoPath
|
||||
val isNew = newPhotosList.contains(photoPath)
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.size(88.dp)
|
||||
@@ -1511,14 +1525,34 @@ fun EditActivityBottomSheet(
|
||||
contentScale = androidx.compose.ui.layout.ContentScale.Crop
|
||||
)
|
||||
if (isNew) {
|
||||
// Badge NOVA
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.align(Alignment.TopStart)
|
||||
.background(BrandGreen)
|
||||
.padding(horizontal = 4.dp, vertical = 2.dp)
|
||||
) {
|
||||
Text("NOVA", color = Color.White, fontSize = 8.sp, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
|
||||
// Close 'X' button to remove from draft
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(2.dp)
|
||||
.size(20.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Color.Black.copy(alpha = 0.65f))
|
||||
.clickable { newPhotosList.remove(photoPath) },
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Close,
|
||||
contentDescription = "Remover Rascunho",
|
||||
tint = Color.White,
|
||||
modifier = Modifier.size(12.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1542,10 +1576,11 @@ fun EditActivityBottomSheet(
|
||||
onDelete = {
|
||||
val photoToDelete = selectedPhotoForViewer!!
|
||||
selectedPhotoForViewer = null
|
||||
if (photoToDelete == selectedNewPhotoPath) {
|
||||
selectedNewPhotoPath = null
|
||||
if (newPhotosList.contains(photoToDelete)) {
|
||||
newPhotosList.remove(photoToDelete)
|
||||
} else {
|
||||
onSoftDeletePhoto(photoToDelete)
|
||||
}
|
||||
onSoftDeletePhoto(photoToDelete)
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -1656,7 +1691,8 @@ fun EditActivityBottomSheet(
|
||||
Button(
|
||||
onClick = {
|
||||
isSubmitting = true
|
||||
onUpdateProgress(progressValue.toInt(), observationText, selectedNewPhotoPath)
|
||||
val photoParam = if (newPhotosList.isNotEmpty()) newPhotosList.joinToString("|") else null
|
||||
onUpdateProgress(progressValue.toInt(), observationText, photoParam)
|
||||
onDismiss()
|
||||
},
|
||||
modifier = Modifier
|
||||
|
||||
@@ -166,7 +166,7 @@ A gestão e armazenamento de arquivos de mídia (fotos das ordens de serviço)
|
||||
|
||||
* **Chave de Acesso:** Service Account autenticada via `app/src/main/assets/drive-fotos-gestaoosparada.apikey.json` (`fotos-gestao-os@gestaoosparada.iam.gserviceaccount.com`).
|
||||
* **Pasta Destino na Nuvem:** Google Drive Folder ID `15WJIdzrykXWRSC5Xy4Ci5Cr7gq6FqMxK`.
|
||||
* **Estratégia Offline-First:** As fotos capturadas/selecionadas são inicialmente salvas em armazenamento local privado (`filesDir/os_photos/`). Durante o ciclo de sincronização, o app realiza o upload multipart HTTP POST para o Drive, ajusta as permissões do arquivo para leitura pública (`anyone with link`) e obtém a URL direta de visualização (`webViewLink`).
|
||||
* **Estratégia Offline-First & Múltiplas Fotos:** As fotos capturadas/selecionadas são salvas em armazenamento local privado (`filesDir/os_photos/`). O aplicativo suporta o anexo de **múltiplas fotos por atualização**, armazenando os caminhos/URLs concatenados pelo delimitador `|` (ex: `url1|url2|url3`), garantindo compatibilidade total com a Room DB e o Google Sheets. Durante a sincronização, o app realiza o upload multipart HTTP POST de cada foto para o Drive, ajusta as permissões do arquivo para leitura pública (`anyone with link`) e obtém as URLs diretas de visualização (`webViewLink`).
|
||||
* **Regra de Exclusão (Soft Delete):** A exclusão de uma foto não remove o arquivo da pasta remota no Google Drive. A API do Drive executa uma requisição `PATCH` alterando o nome do arquivo para incluir o sufixo `_DELETED` (ex: `OS_1001_1722780000_DELETED.jpg`), enquanto a aplicação remove o vínculo do registro ativo no banco de dados local e na planilha.
|
||||
|
||||
* Guarda o log sequencial de alterações feitas por todos os inspetores.
|
||||
|
||||
Reference in New Issue
Block a user