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()
|
val historyList = dao.getAllHistoryList()
|
||||||
for (history in historyList) {
|
for (history in historyList) {
|
||||||
val path = history.fotoPath
|
val rawPath = history.fotoPath
|
||||||
if (!path.isNullOrBlank() && !path.startsWith("http://") && !path.startsWith("https://") && !path.endsWith("_DELETED")) {
|
if (!rawPath.isNullOrBlank()) {
|
||||||
val file = java.io.File(path)
|
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()) {
|
if (file.exists()) {
|
||||||
try {
|
try {
|
||||||
val result = driveSyncService.uploadPhotoToDrive(file, history.numeroOs)
|
val result = driveSyncService.uploadPhotoToDrive(file, history.numeroOs)
|
||||||
val updatedHistory = history.copy(fotoPath = result.webViewLink)
|
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
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
trimmed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (changed) {
|
||||||
|
val updatedJoinedPath = uploadedSubPaths.joinToString("|")
|
||||||
|
val updatedHistory = history.copy(fotoPath = updatedJoinedPath)
|
||||||
dao.insertHistory(updatedHistory)
|
dao.insertHistory(updatedHistory)
|
||||||
|
|
||||||
val activity = dao.getActivityByOsOneShot(history.numeroOs)
|
val activity = dao.getActivityByOsOneShot(history.numeroOs)
|
||||||
if (activity != null && activity.fotoPath == path) {
|
if (activity != null) {
|
||||||
dao.updateActivity(activity.copy(fotoPath = result.webViewLink))
|
dao.updateActivity(activity.copy(fotoPath = updatedJoinedPath))
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto para o Drive: ${e.message}", e)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun softDeletePhoto(fotoPath: String, osNumber: String) = withContext(Dispatchers.IO) {
|
suspend fun softDeletePhoto(targetPhotoPath: String, osNumber: String) = withContext(Dispatchers.IO) {
|
||||||
val fileId = extractDriveFileId(fotoPath)
|
val fileId = extractDriveFileId(targetPhotoPath)
|
||||||
if (fileId != null && isCurrentlyConnected()) {
|
if (fileId != null && isCurrentlyConnected()) {
|
||||||
try {
|
try {
|
||||||
val fileName = "OS_${osNumber}_photo.jpg"
|
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)
|
val historyList = dao.getHistoryForOsOneShot(osNumber)
|
||||||
for (hist in historyList) {
|
for (hist in historyList) {
|
||||||
if (hist.fotoPath == fotoPath) {
|
val pathStr = hist.fotoPath
|
||||||
dao.insertHistory(hist.copy(fotoPath = deletedPath))
|
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)
|
val activity = dao.getActivityByOsOneShot(osNumber)
|
||||||
if (activity != null && activity.fotoPath == fotoPath) {
|
if (activity != null && !activity.fotoPath.isNullOrBlank() && activity.fotoPath.contains(targetPhotoPath)) {
|
||||||
dao.updateActivity(activity.copy(fotoPath = deletedPath, synced = false))
|
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 progressValue by remember(activity) { mutableStateOf(activity.percentualExecucao.toFloat()) }
|
||||||
var observationText by remember { mutableStateOf("") }
|
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 tempCameraPath by remember { mutableStateOf<String?>(null) }
|
||||||
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) {
|
val activePhotos = remember(activity, history) {
|
||||||
val list = mutableListOf<String>()
|
val list = mutableListOf<String>()
|
||||||
activity.fotoPath?.let { if (it.isNotBlank() && !it.endsWith("_DELETED")) list.add(it) }
|
fun processPath(raw: String?) {
|
||||||
history.forEach { log ->
|
if (!raw.isNullOrBlank()) {
|
||||||
log.fotoPath?.let {
|
raw.split("|").forEach { p ->
|
||||||
if (it.isNotBlank() && !it.endsWith("_DELETED") && !list.contains(it)) {
|
val trimmed = p.trim()
|
||||||
list.add(it)
|
if (trimmed.isNotBlank() && !trimmed.endsWith("_DELETED") && !list.contains(trimmed)) {
|
||||||
|
list.add(trimmed)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
processPath(activity.fotoPath)
|
||||||
|
history.forEach { processPath(it.fotoPath) }
|
||||||
list
|
list
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1283,7 +1287,7 @@ fun EditActivityBottomSheet(
|
|||||||
contract = ActivityResultContracts.TakePicture()
|
contract = ActivityResultContracts.TakePicture()
|
||||||
) { success ->
|
) { success ->
|
||||||
if (success && tempCameraPath != null) {
|
if (success && tempCameraPath != null) {
|
||||||
selectedNewPhotoPath = tempCameraPath
|
newPhotosList.add(tempCameraPath!!)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1292,7 +1296,7 @@ fun EditActivityBottomSheet(
|
|||||||
) { uri: Uri? ->
|
) { uri: Uri? ->
|
||||||
uri?.let {
|
uri?.let {
|
||||||
val savedPath = onSavePhotoFromUri(it)
|
val savedPath = onSavePhotoFromUri(it)
|
||||||
selectedNewPhotoPath = savedPath
|
newPhotosList.add(savedPath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1435,12 +1439,26 @@ fun EditActivityBottomSheet(
|
|||||||
|
|
||||||
// Photo Attachment & Horizontal Gallery Section
|
// Photo Attachment & Horizontal Gallery Section
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = "Fotos de Campo da OS",
|
text = "Fotos de Campo da OS",
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
fontSize = 14.sp,
|
fontSize = 14.sp,
|
||||||
color = BrandBlack
|
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
|
// Action buttons: Camera & Gallery
|
||||||
Row(
|
Row(
|
||||||
@@ -1479,12 +1497,8 @@ fun EditActivityBottomSheet(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Horizontal Gallery (LazyRow)
|
// Horizontal Gallery (LazyRow)
|
||||||
val displayPhotos = remember(activePhotos, selectedNewPhotoPath) {
|
val displayPhotos = remember(activePhotos, newPhotosList.toList()) {
|
||||||
if (selectedNewPhotoPath != null && !activePhotos.contains(selectedNewPhotoPath)) {
|
(newPhotosList + activePhotos).distinct()
|
||||||
listOf(selectedNewPhotoPath!!) + activePhotos
|
|
||||||
} else {
|
|
||||||
activePhotos
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (displayPhotos.isNotEmpty()) {
|
if (displayPhotos.isNotEmpty()) {
|
||||||
@@ -1495,7 +1509,7 @@ fun EditActivityBottomSheet(
|
|||||||
.padding(vertical = 4.dp)
|
.padding(vertical = 4.dp)
|
||||||
) {
|
) {
|
||||||
items(displayPhotos) { photoPath ->
|
items(displayPhotos) { photoPath ->
|
||||||
val isNew = photoPath == selectedNewPhotoPath
|
val isNew = newPhotosList.contains(photoPath)
|
||||||
Card(
|
Card(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.size(88.dp)
|
.size(88.dp)
|
||||||
@@ -1511,14 +1525,34 @@ fun EditActivityBottomSheet(
|
|||||||
contentScale = androidx.compose.ui.layout.ContentScale.Crop
|
contentScale = androidx.compose.ui.layout.ContentScale.Crop
|
||||||
)
|
)
|
||||||
if (isNew) {
|
if (isNew) {
|
||||||
|
// Badge NOVA
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.align(Alignment.TopEnd)
|
.align(Alignment.TopStart)
|
||||||
.background(BrandGreen)
|
.background(BrandGreen)
|
||||||
.padding(horizontal = 4.dp, vertical = 2.dp)
|
.padding(horizontal = 4.dp, vertical = 2.dp)
|
||||||
) {
|
) {
|
||||||
Text("NOVA", color = Color.White, fontSize = 8.sp, fontWeight = FontWeight.Bold)
|
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,11 +1576,12 @@ fun EditActivityBottomSheet(
|
|||||||
onDelete = {
|
onDelete = {
|
||||||
val photoToDelete = selectedPhotoForViewer!!
|
val photoToDelete = selectedPhotoForViewer!!
|
||||||
selectedPhotoForViewer = null
|
selectedPhotoForViewer = null
|
||||||
if (photoToDelete == selectedNewPhotoPath) {
|
if (newPhotosList.contains(photoToDelete)) {
|
||||||
selectedNewPhotoPath = null
|
newPhotosList.remove(photoToDelete)
|
||||||
}
|
} else {
|
||||||
onSoftDeletePhoto(photoToDelete)
|
onSoftDeletePhoto(photoToDelete)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1656,7 +1691,8 @@ fun EditActivityBottomSheet(
|
|||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
isSubmitting = true
|
isSubmitting = true
|
||||||
onUpdateProgress(progressValue.toInt(), observationText, selectedNewPhotoPath)
|
val photoParam = if (newPhotosList.isNotEmpty()) newPhotosList.joinToString("|") else null
|
||||||
|
onUpdateProgress(progressValue.toInt(), observationText, photoParam)
|
||||||
onDismiss()
|
onDismiss()
|
||||||
},
|
},
|
||||||
modifier = Modifier
|
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`).
|
* **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`.
|
* **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.
|
* **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.
|
* Guarda o log sequencial de alterações feitas por todos os inspetores.
|
||||||
|
|||||||
Reference in New Issue
Block a user