feat: implement real Google Drive photo synchronization and replace camera mocks with native file handling
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -12,6 +12,7 @@ local.properties
|
|||||||
.env
|
.env
|
||||||
debug.keystore
|
debug.keystore
|
||||||
**/chaveacesso_sheets.apikey.json
|
**/chaveacesso_sheets.apikey.json
|
||||||
|
app/src/main/assets/drive-fotos-gestaoosparada.apikey.json
|
||||||
plantops_-gestao-de-manutencao.zip
|
plantops_-gestao-de-manutencao.zip
|
||||||
/jdk/
|
/jdk/
|
||||||
/gradle_9_3_1/
|
/gradle_9_3_1/
|
||||||
|
|||||||
@@ -26,6 +26,16 @@
|
|||||||
<category android:name="android.intent.category.LAUNCHER" />
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
|
<provider
|
||||||
|
android:name="androidx.core.content.FileProvider"
|
||||||
|
android:authorities="${applicationId}.fileprovider"
|
||||||
|
android:exported="false"
|
||||||
|
android:grantUriPermissions="true">
|
||||||
|
<meta-data
|
||||||
|
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||||
|
android:resource="@xml/file_paths" />
|
||||||
|
</provider>
|
||||||
</application>
|
</application>
|
||||||
|
|
||||||
</manifest>
|
</manifest>
|
||||||
|
|||||||
@@ -34,6 +34,9 @@ interface MaintenanceDao {
|
|||||||
@Query("SELECT * FROM os_update_history WHERE numeroOs = :numeroOs ORDER BY timestamp DESC")
|
@Query("SELECT * FROM os_update_history WHERE numeroOs = :numeroOs ORDER BY timestamp DESC")
|
||||||
fun getHistoryForOs(numeroOs: String): Flow<List<OSUpdateHistory>>
|
fun getHistoryForOs(numeroOs: String): Flow<List<OSUpdateHistory>>
|
||||||
|
|
||||||
|
@Query("SELECT * FROM os_update_history WHERE numeroOs = :numeroOs ORDER BY timestamp DESC")
|
||||||
|
suspend fun getHistoryForOsOneShot(numeroOs: String): List<OSUpdateHistory>
|
||||||
|
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun insertHistory(history: OSUpdateHistory)
|
suspend fun insertHistory(history: OSUpdateHistory)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,202 @@
|
|||||||
|
package com.example.data.remote
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import com.google.auth.oauth2.GoogleCredentials
|
||||||
|
import com.squareup.moshi.JsonClass
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.RequestBody.Companion.asRequestBody
|
||||||
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
|
import java.io.File
|
||||||
|
import java.io.IOException
|
||||||
|
|
||||||
|
@JsonClass(generateAdapter = true)
|
||||||
|
data class DriveFileResponse(
|
||||||
|
val id: String? = null,
|
||||||
|
val name: String? = null,
|
||||||
|
val webViewLink: String? = null,
|
||||||
|
val webContentLink: String? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
data class DriveUploadResult(
|
||||||
|
val fileId: String,
|
||||||
|
val webViewLink: String,
|
||||||
|
val fileName: String
|
||||||
|
)
|
||||||
|
|
||||||
|
class GoogleDriveSyncService(
|
||||||
|
private val context: Context,
|
||||||
|
private val folderId: String = "15WJIdzrykXWRSC5Xy4Ci5Cr7gq6FqMxK"
|
||||||
|
) {
|
||||||
|
private val tag = "GoogleDriveSync"
|
||||||
|
|
||||||
|
private val client = OkHttpClient.Builder()
|
||||||
|
.addInterceptor(okhttp3.logging.HttpLoggingInterceptor().apply {
|
||||||
|
level = okhttp3.logging.HttpLoggingInterceptor.Level.BASIC
|
||||||
|
})
|
||||||
|
.build()
|
||||||
|
|
||||||
|
private val moshi = Moshi.Builder()
|
||||||
|
.add(com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory())
|
||||||
|
.build()
|
||||||
|
|
||||||
|
private var googleCredentials: GoogleCredentials? = null
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun getCredentials(): GoogleCredentials {
|
||||||
|
if (googleCredentials == null) {
|
||||||
|
val stream = try {
|
||||||
|
Log.d(tag, "Carregando credenciais do Google Drive de drive-fotos-gestaoosparada.apikey.json")
|
||||||
|
context.assets.open("drive-fotos-gestaoosparada.apikey.json")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
val msg = "Arquivo de credenciais 'drive-fotos-gestaoosparada.apikey.json' não encontrado na pasta assets."
|
||||||
|
Log.e(tag, msg, e)
|
||||||
|
throw IOException(msg, e)
|
||||||
|
}
|
||||||
|
|
||||||
|
googleCredentials = GoogleCredentials.fromStream(stream)
|
||||||
|
.createScoped(listOf("https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file"))
|
||||||
|
}
|
||||||
|
googleCredentials!!.refreshIfExpired()
|
||||||
|
return googleCredentials!!
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getAccessToken(): String {
|
||||||
|
val creds = getCredentials()
|
||||||
|
val token = creds.accessToken?.tokenValue
|
||||||
|
if (token != null) return token
|
||||||
|
|
||||||
|
creds.refresh()
|
||||||
|
return creds.accessToken?.tokenValue
|
||||||
|
?: throw IOException("Falha ao obter token de acesso para a Google Drive API.")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Uploads a photo file to Google Drive in the specified folder.
|
||||||
|
* Sets public read permission and returns the DriveUploadResult containing webViewLink and fileId.
|
||||||
|
*/
|
||||||
|
fun uploadPhotoToDrive(photoFile: File, osNumber: String): DriveUploadResult {
|
||||||
|
if (!photoFile.exists()) {
|
||||||
|
throw IOException("Arquivo local da foto não existe: ${photoFile.absolutePath}")
|
||||||
|
}
|
||||||
|
|
||||||
|
val token = getAccessToken()
|
||||||
|
val timestamp = System.currentTimeMillis()
|
||||||
|
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
|
||||||
|
val fileName = "OS_${sanitizedOs}_${timestamp}.jpg"
|
||||||
|
|
||||||
|
val metadataJson = """
|
||||||
|
{
|
||||||
|
"name": "$fileName",
|
||||||
|
"parents": ["$folderId"]
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val multipartBody = MultipartBody.Builder()
|
||||||
|
.setType(MultipartBody.FORM)
|
||||||
|
.addPart(
|
||||||
|
metadataJson.toRequestBody("application/json; charset=UTF-8".toMediaType())
|
||||||
|
)
|
||||||
|
.addPart(
|
||||||
|
MultipartBody.Part.createFormData(
|
||||||
|
"file",
|
||||||
|
fileName,
|
||||||
|
photoFile.asRequestBody("image/jpeg".toMediaType())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val uploadRequest = Request.Builder()
|
||||||
|
.url("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,webViewLink,webContentLink")
|
||||||
|
.header("Authorization", "Bearer $token")
|
||||||
|
.post(multipartBody)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val response = client.newCall(uploadRequest).execute()
|
||||||
|
val responseBody = response.body?.string()
|
||||||
|
|
||||||
|
if (!response.isSuccessful || responseBody.isNullOrBlank()) {
|
||||||
|
val errorMsg = "Erro no upload para o Google Drive: HTTP ${response.code} - $responseBody"
|
||||||
|
Log.e(tag, errorMsg)
|
||||||
|
throw IOException(errorMsg)
|
||||||
|
}
|
||||||
|
|
||||||
|
val adapter = moshi.adapter(DriveFileResponse::class.java)
|
||||||
|
val driveFile = adapter.fromJson(responseBody)
|
||||||
|
?: throw IOException("Resposta inválida da API do Google Drive ao criar arquivo.")
|
||||||
|
|
||||||
|
val fileId = driveFile.id ?: throw IOException("Id do arquivo não retornado pelo Google Drive.")
|
||||||
|
|
||||||
|
// Make file publicly viewable
|
||||||
|
try {
|
||||||
|
setFilePublicPermission(fileId, token)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(tag, "Falha ao definir permissão pública do arquivo $fileId: ${e.message}")
|
||||||
|
}
|
||||||
|
|
||||||
|
val directViewUrl = "https://lh3.googleusercontent.com/d/$fileId"
|
||||||
|
Log.d(tag, "Foto enviada com sucesso para o Drive. File ID: $fileId, Link: $directViewUrl")
|
||||||
|
|
||||||
|
return DriveUploadResult(
|
||||||
|
fileId = fileId,
|
||||||
|
webViewLink = directViewUrl,
|
||||||
|
fileName = fileName
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets permission on Google Drive file so anyone with link can view.
|
||||||
|
*/
|
||||||
|
private fun setFilePublicPermission(fileId: String, token: String) {
|
||||||
|
val permJson = """{"role":"reader","type":"anyone"}"""
|
||||||
|
val req = Request.Builder()
|
||||||
|
.url("https://www.googleapis.com/drive/v3/files/$fileId/permissions")
|
||||||
|
.header("Authorization", "Bearer $token")
|
||||||
|
.post(permJson.toRequestBody("application/json; charset=UTF-8".toMediaType()))
|
||||||
|
.build()
|
||||||
|
|
||||||
|
client.newCall(req).execute().close()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Performs Soft Delete by renaming the file on Google Drive to include "_DELETED" suffix before extension.
|
||||||
|
*/
|
||||||
|
fun softDeletePhotoOnDrive(fileId: String, currentFileName: String): Boolean {
|
||||||
|
val token = getAccessToken()
|
||||||
|
|
||||||
|
val dotIndex = currentFileName.lastIndexOf('.')
|
||||||
|
val newName = if (dotIndex != -1) {
|
||||||
|
val base = currentFileName.substring(0, dotIndex)
|
||||||
|
val ext = currentFileName.substring(dotIndex)
|
||||||
|
if (base.endsWith("_DELETED")) {
|
||||||
|
currentFileName
|
||||||
|
} else {
|
||||||
|
"${base}_DELETED$ext"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (currentFileName.endsWith("_DELETED")) currentFileName else "${currentFileName}_DELETED"
|
||||||
|
}
|
||||||
|
|
||||||
|
val patchJson = """{"name":"$newName"}"""
|
||||||
|
val req = Request.Builder()
|
||||||
|
.url("https://www.googleapis.com/drive/v3/files/$fileId")
|
||||||
|
.header("Authorization", "Bearer $token")
|
||||||
|
.patch(patchJson.toRequestBody("application/json; charset=UTF-8".toMediaType()))
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val response = client.newCall(req).execute()
|
||||||
|
val success = response.isSuccessful
|
||||||
|
response.close()
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
Log.d(tag, "Arquivo $fileId renomeado no Google Drive para $newName (Soft Delete).")
|
||||||
|
} else {
|
||||||
|
Log.e(tag, "Falha ao renomear arquivo $fileId no Google Drive: HTTP ${response.code}")
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,6 +22,7 @@ class MaintenanceRepository(
|
|||||||
) {
|
) {
|
||||||
|
|
||||||
private val sheetsSyncService = com.example.data.remote.GoogleSheetsSyncService(context, timeGuardManager)
|
private val sheetsSyncService = com.example.data.remote.GoogleSheetsSyncService(context, timeGuardManager)
|
||||||
|
private val driveSyncService = com.example.data.remote.GoogleDriveSyncService(context)
|
||||||
private val networkMonitor = com.example.util.NetworkMonitor(context)
|
private val networkMonitor = com.example.util.NetworkMonitor(context)
|
||||||
|
|
||||||
val isNetworkConnected: Flow<Boolean> = networkMonitor.isConnected
|
val isNetworkConnected: Flow<Boolean> = networkMonitor.isConnected
|
||||||
@@ -225,7 +226,14 @@ class MaintenanceRepository(
|
|||||||
android.util.Log.e("MaintenanceRepository", "Synchronization blocked: ${timeValidation.message}")
|
android.util.Log.e("MaintenanceRepository", "Synchronization blocked: ${timeValidation.message}")
|
||||||
return@withContext SyncResult.Error(timeValidation.message)
|
return@withContext SyncResult.Error(timeValidation.message)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Upload any pending local photos to Google Drive
|
||||||
|
try {
|
||||||
|
uploadPendingPhotos()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("MaintenanceRepository", "Erro ao enviar fotos pendentes para o Drive", e)
|
||||||
|
}
|
||||||
|
|
||||||
// 0. Fetch user access list and store locally
|
// 0. Fetch user access list and store locally
|
||||||
try {
|
try {
|
||||||
val remoteAccessList = sheetsSyncService.fetchUserAccessList()
|
val remoteAccessList = sheetsSyncService.fetchUserAccessList()
|
||||||
@@ -429,6 +437,98 @@ class MaintenanceRepository(
|
|||||||
suspend fun clearConflictLogs() = withContext(Dispatchers.IO) {
|
suspend fun clearConflictLogs() = withContext(Dispatchers.IO) {
|
||||||
dao.clearAllConflictLogs()
|
dao.clearAllConflictLogs()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun saveLocalPhotoFromUri(uri: Uri, osNumber: String): String {
|
||||||
|
val photosDir = java.io.File(context.filesDir, "os_photos").apply { mkdirs() }
|
||||||
|
val timestamp = System.currentTimeMillis()
|
||||||
|
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
|
||||||
|
val targetFile = java.io.File(photosDir, "OS_${sanitizedOs}_${timestamp}.jpg")
|
||||||
|
|
||||||
|
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||||
|
targetFile.outputStream().use { output ->
|
||||||
|
input.copyTo(output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return targetFile.absolutePath
|
||||||
|
}
|
||||||
|
|
||||||
|
fun createTempCameraPhotoUri(osNumber: String): Pair<Uri, String> {
|
||||||
|
val photosDir = java.io.File(context.filesDir, "os_photos").apply { mkdirs() }
|
||||||
|
val timestamp = System.currentTimeMillis()
|
||||||
|
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
|
||||||
|
val targetFile = java.io.File(photosDir, "OS_${sanitizedOs}_${timestamp}.jpg")
|
||||||
|
|
||||||
|
val authority = "${context.packageName}.fileprovider"
|
||||||
|
val uri = androidx.core.content.FileProvider.getUriForFile(context, authority, targetFile)
|
||||||
|
return Pair(uri, targetFile.absolutePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun uploadPendingPhotos() = withContext(Dispatchers.IO) {
|
||||||
|
if (!isCurrentlyConnected()) return@withContext
|
||||||
|
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
} 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) {
|
||||||
|
val fileId = extractDriveFileId(fotoPath)
|
||||||
|
if (fileId != null && isCurrentlyConnected()) {
|
||||||
|
try {
|
||||||
|
val fileName = "OS_${osNumber}_photo.jpg"
|
||||||
|
driveSyncService.softDeletePhotoOnDrive(fileId, fileName)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("MaintenanceRepository", "Erro ao executar soft delete no Google Drive: ${e.message}", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val deletedPath = if (fotoPath.endsWith("_DELETED")) fotoPath else "${fotoPath}_DELETED"
|
||||||
|
|
||||||
|
val historyList = dao.getHistoryForOsOneShot(osNumber)
|
||||||
|
for (hist in historyList) {
|
||||||
|
if (hist.fotoPath == fotoPath) {
|
||||||
|
dao.insertHistory(hist.copy(fotoPath = deletedPath))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val activity = dao.getActivityByOsOneShot(osNumber)
|
||||||
|
if (activity != null && activity.fotoPath == fotoPath) {
|
||||||
|
dao.updateActivity(activity.copy(fotoPath = deletedPath, synced = false))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun extractDriveFileId(url: String): String? {
|
||||||
|
if (url.contains("/d/")) {
|
||||||
|
val parts = url.split("/d/")
|
||||||
|
if (parts.size > 1) {
|
||||||
|
return parts[1].split("/").firstOrNull()?.split("?")?.firstOrNull()
|
||||||
|
}
|
||||||
|
} else if (url.contains("id=")) {
|
||||||
|
val parts = url.split("id=")
|
||||||
|
if (parts.size > 1) {
|
||||||
|
return parts[1].split("&").firstOrNull()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sealed interface SyncResult {
|
sealed interface SyncResult {
|
||||||
|
|||||||
@@ -221,6 +221,15 @@ fun AnalyticsScreen(
|
|||||||
emailEditor = currentUser?.email
|
emailEditor = currentUser?.email
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
onSavePhotoFromUri = { uri ->
|
||||||
|
viewModel.saveLocalPhotoFromUri(uri, activity.numeroOs)
|
||||||
|
},
|
||||||
|
onCreateCameraUri = {
|
||||||
|
viewModel.createTempCameraPhotoUri(activity.numeroOs)
|
||||||
|
},
|
||||||
|
onSoftDeletePhoto = { path ->
|
||||||
|
viewModel.softDeletePhoto(path, activity.numeroOs)
|
||||||
|
},
|
||||||
onGoogleLoginClick = {
|
onGoogleLoginClick = {
|
||||||
googleSignInLauncher.launch(googleSignInClient.signInIntent)
|
googleSignInLauncher.launch(googleSignInClient.signInIntent)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.example.ui.screens
|
package com.example.ui.screens
|
||||||
|
|
||||||
|
import android.net.Uri
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
@@ -592,16 +593,25 @@ fun MaintenanceDashboardScreen(
|
|||||||
showEditSheet = false
|
showEditSheet = false
|
||||||
viewModel.selectActivity(null)
|
viewModel.selectActivity(null)
|
||||||
},
|
},
|
||||||
onUpdateProgress = { newPct, comment, mockPhoto ->
|
onUpdateProgress = { newPct, comment, photo ->
|
||||||
viewModel.updateProgress(
|
viewModel.updateProgress(
|
||||||
numeroOs = selectedActivity!!.numeroOs,
|
numeroOs = selectedActivity!!.numeroOs,
|
||||||
novoPercentual = newPct,
|
novoPercentual = newPct,
|
||||||
observacao = comment,
|
observacao = comment,
|
||||||
fotoPath = mockPhoto,
|
fotoPath = photo,
|
||||||
recurso = currentUser?.displayName ?: "Encarregado Campo",
|
recurso = currentUser?.displayName ?: "Encarregado Campo",
|
||||||
emailEditor = currentUser?.email
|
emailEditor = currentUser?.email
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
onSavePhotoFromUri = { uri ->
|
||||||
|
viewModel.saveLocalPhotoFromUri(uri, selectedActivity!!.numeroOs)
|
||||||
|
},
|
||||||
|
onCreateCameraUri = {
|
||||||
|
viewModel.createTempCameraPhotoUri(selectedActivity!!.numeroOs)
|
||||||
|
},
|
||||||
|
onSoftDeletePhoto = { path ->
|
||||||
|
viewModel.softDeletePhoto(path, selectedActivity!!.numeroOs)
|
||||||
|
},
|
||||||
onGoogleLoginClick = {
|
onGoogleLoginClick = {
|
||||||
googleSignInLauncher.launch(googleSignInClient.signInIntent)
|
googleSignInLauncher.launch(googleSignInClient.signInIntent)
|
||||||
}
|
}
|
||||||
@@ -1068,6 +1078,116 @@ fun OSListItemCard(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun FullscreenPhotoViewerDialog(
|
||||||
|
photoPath: String,
|
||||||
|
osNumber: String,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onDelete: () -> Unit
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
Dialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.background(Color.Black.copy(alpha = 0.95f)),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
// Header Top Bar
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.align(Alignment.TopCenter)
|
||||||
|
.statusBarsPadding()
|
||||||
|
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
IconButton(onClick = onDismiss) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Close,
|
||||||
|
contentDescription = "Fechar",
|
||||||
|
tint = Color.White
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = "Foto OS $osNumber",
|
||||||
|
color = Color.White,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
fontSize = 16.sp
|
||||||
|
)
|
||||||
|
|
||||||
|
Row {
|
||||||
|
// Compartilhar
|
||||||
|
IconButton(
|
||||||
|
onClick = {
|
||||||
|
try {
|
||||||
|
if (photoPath.startsWith("/")) {
|
||||||
|
val file = java.io.File(photoPath)
|
||||||
|
if (file.exists()) {
|
||||||
|
val uri = androidx.core.content.FileProvider.getUriForFile(
|
||||||
|
context,
|
||||||
|
"${context.packageName}.fileprovider",
|
||||||
|
file
|
||||||
|
)
|
||||||
|
val shareIntent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
|
||||||
|
type = "image/jpeg"
|
||||||
|
putExtra(android.content.Intent.EXTRA_STREAM, uri)
|
||||||
|
addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
|
}
|
||||||
|
context.startActivity(android.content.Intent.createChooser(shareIntent, "Compartilhar Foto OS"))
|
||||||
|
} else {
|
||||||
|
Toast.makeText(context, "Arquivo local não encontrado", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val shareIntent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
|
||||||
|
type = "text/plain"
|
||||||
|
putExtra(android.content.Intent.EXTRA_SUBJECT, "Foto OS $osNumber")
|
||||||
|
putExtra(android.content.Intent.EXTRA_TEXT, photoPath)
|
||||||
|
}
|
||||||
|
context.startActivity(android.content.Intent.createChooser(shareIntent, "Compartilhar Link da Foto"))
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Toast.makeText(context, "Erro ao compartilhar: ${e.message}", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Share,
|
||||||
|
contentDescription = "Compartilhar",
|
||||||
|
tint = Color.White
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deletar
|
||||||
|
IconButton(onClick = onDelete) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Delete,
|
||||||
|
contentDescription = "Deletar Foto",
|
||||||
|
tint = Color(0xFFFF5252)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Image display
|
||||||
|
coil.compose.AsyncImage(
|
||||||
|
model = photoPath,
|
||||||
|
contentDescription = "Visualização em Tela Cheia",
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.fillMaxHeight(0.82f)
|
||||||
|
.padding(16.dp),
|
||||||
|
contentScale = androidx.compose.ui.layout.ContentScale.Fit
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Modal Bottom Sheet for OS Details, Editing and Timeline History
|
* Modal Bottom Sheet for OS Details, Editing and Timeline History
|
||||||
*/
|
*/
|
||||||
@@ -1080,6 +1200,9 @@ fun EditActivityBottomSheet(
|
|||||||
userAccessLevel: String?,
|
userAccessLevel: String?,
|
||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onUpdateProgress: (Int, String, String?) -> Unit,
|
onUpdateProgress: (Int, String, String?) -> Unit,
|
||||||
|
onSavePhotoFromUri: (Uri) -> String,
|
||||||
|
onCreateCameraUri: () -> Pair<Uri, String>,
|
||||||
|
onSoftDeletePhoto: (String) -> Unit,
|
||||||
onGoogleLoginClick: () -> Unit
|
onGoogleLoginClick: () -> Unit
|
||||||
) {
|
) {
|
||||||
val focusManager = LocalFocusManager.current
|
val focusManager = LocalFocusManager.current
|
||||||
@@ -1138,16 +1261,41 @@ 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 selectedMockPhotoPath by remember { mutableStateOf<String?>(null) }
|
var selectedNewPhotoPath by remember { mutableStateOf<String?>(null) }
|
||||||
|
var tempCameraPath by remember { mutableStateOf<String?>(null) }
|
||||||
|
var selectedPhotoForViewer by remember { mutableStateOf<String?>(null) }
|
||||||
var isSubmitting by remember { mutableStateOf(false) }
|
var isSubmitting by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
// Mock photos available in the field for maintenance logs
|
val activePhotos = remember(activity, history) {
|
||||||
val mockPhotos = listOf(
|
val list = mutableListOf<String>()
|
||||||
"Turbina" to "ic_turbine_mock",
|
activity.fotoPath?.let { if (it.isNotBlank() && !it.endsWith("_DELETED")) list.add(it) }
|
||||||
"Fiação Elétrica" to "ic_electrical_mock",
|
history.forEach { log ->
|
||||||
"Mancal Engraxado" to "ic_gear_mock",
|
log.fotoPath?.let {
|
||||||
"Caldeira Lavada" to "ic_boiler_mock"
|
if (it.isNotBlank() && !it.endsWith("_DELETED") && !list.contains(it)) {
|
||||||
)
|
list.add(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
list
|
||||||
|
}
|
||||||
|
|
||||||
|
val cameraLauncher = rememberLauncherForActivityResult(
|
||||||
|
contract = ActivityResultContracts.TakePicture()
|
||||||
|
) { success ->
|
||||||
|
if (success && tempCameraPath != null) {
|
||||||
|
selectedNewPhotoPath = tempCameraPath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val galleryLauncher = rememberLauncherForActivityResult(
|
||||||
|
contract = ActivityResultContracts.GetContent()
|
||||||
|
) { uri: Uri? ->
|
||||||
|
uri?.let {
|
||||||
|
val savedPath = onSavePhotoFromUri(it)
|
||||||
|
selectedNewPhotoPath = savedPath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Header: OS + Close
|
// Header: OS + Close
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
@@ -1285,78 +1433,121 @@ fun EditActivityBottomSheet(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Photo Attachment Section (Simulating Field Camera Capture)
|
// Photo Attachment & Horizontal Gallery Section
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
Text(
|
Text(
|
||||||
text = "Anexar Foto de Campo (Simulador de Câmera)",
|
text = "Fotos de Campo da OS",
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
fontSize = 14.sp,
|
fontSize = 14.sp,
|
||||||
color = BrandBlack
|
color = BrandBlack
|
||||||
)
|
)
|
||||||
Text(
|
|
||||||
text = "Selecione uma categoria de inspeção para simular o anexo fotográfico da atividade:",
|
|
||||||
fontSize = 11.sp,
|
|
||||||
color = StatusGrey
|
|
||||||
)
|
|
||||||
|
|
||||||
LazyRow(
|
// Action buttons: Camera & Gallery
|
||||||
|
Row(
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
modifier = Modifier.fillMaxWidth()
|
modifier = Modifier.fillMaxWidth()
|
||||||
) {
|
) {
|
||||||
items(mockPhotos) { (label, mockName) ->
|
OutlinedButton(
|
||||||
val isSelected = selectedMockPhotoPath == mockName
|
onClick = {
|
||||||
Surface(
|
if (currentUser != null) {
|
||||||
onClick = { if (currentUser != null) selectedMockPhotoPath = if (isSelected) null else mockName },
|
val (uri, path) = onCreateCameraUri()
|
||||||
shape = RoundedCornerShape(8.dp),
|
tempCameraPath = path
|
||||||
color = if (isSelected) Color(0xFFE8F5E9) else Color(0xFFF5F5F5),
|
cameraLauncher.launch(uri)
|
||||||
border = BorderStroke(1.dp, if (isSelected) BrandGreen else Color(0xFFE0E0E0)),
|
|
||||||
modifier = Modifier.height(48.dp)
|
|
||||||
) {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.padding(horizontal = 10.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(4.dp)
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
imageVector = Icons.Default.CameraAlt,
|
|
||||||
contentDescription = label,
|
|
||||||
tint = if (isSelected) BrandGreen else StatusGrey,
|
|
||||||
modifier = Modifier.size(16.dp)
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = label,
|
|
||||||
fontSize = 11.sp,
|
|
||||||
fontWeight = FontWeight.Bold,
|
|
||||||
color = if (isSelected) BrandGreen else BrandBlack
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
enabled = currentUser != null,
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Icon(Icons.Default.CameraAlt, contentDescription = "Tirar Foto", modifier = Modifier.size(16.dp))
|
||||||
|
Spacer(modifier = Modifier.width(4.dp))
|
||||||
|
Text("Tirar Foto", fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = {
|
||||||
|
if (currentUser != null) {
|
||||||
|
galleryLauncher.launch("image/*")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
enabled = currentUser != null,
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Icon(Icons.Default.PhotoLibrary, contentDescription = "Galeria", modifier = Modifier.size(16.dp))
|
||||||
|
Spacer(modifier = Modifier.width(4.dp))
|
||||||
|
Text("Galeria", fontSize = 12.sp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show Selected Photo Preview Simulation
|
// Horizontal Gallery (LazyRow)
|
||||||
if (selectedMockPhotoPath != null) {
|
val displayPhotos = remember(activePhotos, selectedNewPhotoPath) {
|
||||||
Box(
|
if (selectedNewPhotoPath != null && !activePhotos.contains(selectedNewPhotoPath)) {
|
||||||
|
listOf(selectedNewPhotoPath!!) + activePhotos
|
||||||
|
} else {
|
||||||
|
activePhotos
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (displayPhotos.isNotEmpty()) {
|
||||||
|
LazyRow(
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.clip(RoundedCornerShape(8.dp))
|
.padding(vertical = 4.dp)
|
||||||
.background(Color(0xFFE8F5E9))
|
|
||||||
.padding(8.dp),
|
|
||||||
contentAlignment = Alignment.CenterStart
|
|
||||||
) {
|
) {
|
||||||
Row(
|
items(displayPhotos) { photoPath ->
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
val isNew = photoPath == selectedNewPhotoPath
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
Card(
|
||||||
) {
|
modifier = Modifier
|
||||||
Icon(Icons.Default.Check, contentDescription = "Foto vinculada", tint = BrandGreen)
|
.size(88.dp)
|
||||||
Text(
|
.clickable { selectedPhotoForViewer = photoPath },
|
||||||
text = "Foto do componente '$selectedMockPhotoPath' anexada com sucesso à OS localmente!",
|
shape = RoundedCornerShape(8.dp),
|
||||||
fontSize = 11.sp,
|
border = BorderStroke(2.dp, if (isNew) BrandGreen else Color(0xFFE0E0E0))
|
||||||
color = BrandGreen,
|
) {
|
||||||
fontWeight = FontWeight.Bold
|
Box(modifier = Modifier.fillMaxSize()) {
|
||||||
)
|
coil.compose.AsyncImage(
|
||||||
|
model = photoPath,
|
||||||
|
contentDescription = "Miniatura da foto",
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
contentScale = androidx.compose.ui.layout.ContentScale.Crop
|
||||||
|
)
|
||||||
|
if (isNew) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.align(Alignment.TopEnd)
|
||||||
|
.background(BrandGreen)
|
||||||
|
.padding(horizontal = 4.dp, vertical = 2.dp)
|
||||||
|
) {
|
||||||
|
Text("NOVA", color = Color.White, fontSize = 8.sp, fontWeight = FontWeight.Bold)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
Text(
|
||||||
|
text = "Nenhuma foto anexada a esta OS ainda.",
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = Color.Gray,
|
||||||
|
modifier = Modifier.padding(vertical = 4.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fullscreen Viewer Dialog
|
||||||
|
if (selectedPhotoForViewer != null) {
|
||||||
|
FullscreenPhotoViewerDialog(
|
||||||
|
photoPath = selectedPhotoForViewer!!,
|
||||||
|
osNumber = activity.numeroOs,
|
||||||
|
onDismiss = { selectedPhotoForViewer = null },
|
||||||
|
onDelete = {
|
||||||
|
val photoToDelete = selectedPhotoForViewer!!
|
||||||
|
selectedPhotoForViewer = null
|
||||||
|
if (photoToDelete == selectedNewPhotoPath) {
|
||||||
|
selectedNewPhotoPath = null
|
||||||
|
}
|
||||||
|
onSoftDeletePhoto(photoToDelete)
|
||||||
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1465,7 +1656,7 @@ fun EditActivityBottomSheet(
|
|||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
isSubmitting = true
|
isSubmitting = true
|
||||||
onUpdateProgress(progressValue.toInt(), observationText, selectedMockPhotoPath)
|
onUpdateProgress(progressValue.toInt(), observationText, selectedNewPhotoPath)
|
||||||
onDismiss()
|
onDismiss()
|
||||||
},
|
},
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
|
|||||||
@@ -399,6 +399,28 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun saveLocalPhotoFromUri(uri: Uri, osNumber: String): String {
|
||||||
|
return repository.saveLocalPhotoFromUri(uri, osNumber)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun createTempCameraPhotoUri(osNumber: String): Pair<Uri, String> {
|
||||||
|
return repository.createTempCameraPhotoUri(osNumber)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun softDeletePhoto(fotoPath: String, osNumber: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
repository.softDeletePhoto(fotoPath, osNumber)
|
||||||
|
_syncStatusMessage.value = "Foto excluída com sucesso."
|
||||||
|
if (_internetAvailable.value) {
|
||||||
|
syncNow()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_syncStatusMessage.value = "Erro ao excluir foto: ${e.message}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private var monitoringJob: kotlinx.coroutines.Job? = null
|
private var monitoringJob: kotlinx.coroutines.Job? = null
|
||||||
|
|
||||||
private val _activeSpreadsheetId = MutableStateFlow(repository.getActiveSpreadsheetId())
|
private val _activeSpreadsheetId = MutableStateFlow(repository.getActiveSpreadsheetId())
|
||||||
|
|||||||
6
app/src/main/res/xml/file_paths.xml
Normal file
6
app/src/main/res/xml/file_paths.xml
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<files-path name="os_photos" path="os_photos/" />
|
||||||
|
<cache-path name="cache_photos" path="." />
|
||||||
|
<external-files-path name="external_photos" path="." />
|
||||||
|
</paths>
|
||||||
@@ -158,6 +158,17 @@ O aplicativo mapeia duas abas na planilha remota:
|
|||||||
* **Filtro de Resumo:** Ignora linhas cujo valor na coluna `resumo` seja diferente de "não" (garantindo a exclusão de tarefas puramente administrativas/agrupadoras).
|
* **Filtro de Resumo:** Ignora linhas cujo valor na coluna `resumo` seja diferente de "não" (garantindo a exclusão de tarefas puramente administrativas/agrupadoras).
|
||||||
|
|
||||||
2. **Aba `history` (Log de Transações - Leitura/Escrita):**
|
2. **Aba `history` (Log de Transações - Leitura/Escrita):**
|
||||||
|
* Registra auditavelmente cada modificação efetuada por usuários (progresso, observação, foto, responsável e email).
|
||||||
|
|
||||||
|
### 4.3. Integração com o Google Drive (`GoogleDriveSyncService.kt`)
|
||||||
|
|
||||||
|
A gestão e armazenamento de arquivos de mídia (fotos das ordens de serviço) é centralizada no Google Drive através do serviço [`GoogleDriveSyncService.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/GoogleDriveSyncService.kt).
|
||||||
|
|
||||||
|
* **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`).
|
||||||
|
* **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.
|
||||||
* Colunas configuradas: `id`, `numeroOs`, `timestamp`, `percentualAnterior`, `percentualNovo`, `observacao`, `fotoPath`, `responsavel`, `email_editor`.
|
* Colunas configuradas: `id`, `numeroOs`, `timestamp`, `percentualAnterior`, `percentualNovo`, `observacao`, `fotoPath`, `responsavel`, `email_editor`.
|
||||||
* Possui funcionalidade de **Self-Healing** (Auto-reparação): se a coluna `email_editor` não for encontrada no carregamento da planilha física, o app executa uma chamada PUT automática para inseri-la no cabeçalho na coluna correspondente.
|
* Possui funcionalidade de **Self-Healing** (Auto-reparação): se a coluna `email_editor` não for encontrada no carregamento da planilha física, o app executa uma chamada PUT automática para inseri-la no cabeçalho na coluna correspondente.
|
||||||
|
|||||||
@@ -48,22 +48,20 @@ O armazenamento é realizado por meio do **Room Database**, que é uma camada de
|
|||||||
|
|
||||||
## 2. Análise da Sincronização Remota
|
## 2. Análise da Sincronização Remota
|
||||||
|
|
||||||
### A sincronização remota está realmente implementada?
|
### A sincronização remota está real e funcionalmente implementada?
|
||||||
**Atualmente, a sincronização é SIMULADA (Mocked).** Não há nenhuma conexão real HTTP, REST API, Firebase ou WebSocket ativa enviando dados para um servidor externo. O código simula perfeitamente o comportamento que um fluxo de rede real teria.
|
**Sim, a sincronização é REAL e BIDIRECIONAL.** O aplicativo utiliza a **Google Sheets API v4** (`GoogleSheetsSyncService.kt`) para sincronizar a estrutura do projeto e logs de alteração, e a **Google Drive API v3** (`GoogleDriveSyncService.kt`) para upload de fotos das OSs na pasta do Google Drive `15WJIdzrykXWRSC5Xy4Ci5Cr7gq6FqMxK`.
|
||||||
|
|
||||||
### Como a simulação funciona?
|
### Como o fluxo de sincronização e envio de fotos funciona?
|
||||||
No método `synchronizeWithBackend()` dentro de `MaintenanceRepository.kt`:
|
1. **Captura e Armazenamento Local (Offline-First):** As fotos capturadas pela Câmera ou selecionadas da Galeria são armazenadas em `filesDir/os_photos/` e registradas na Room DB.
|
||||||
1. O repositório busca do banco local todas as atividades de manutenção que possuem a flag `synced = false` (obtidas por `dao.getUnsyncedActivities()`).
|
2. **Upload para o Google Drive:** No momento do sync, o `MaintenanceRepository.kt` lê as fotos pendentes e aciona o `GoogleDriveSyncService.kt`, que faz o upload multipart usando a Service Account `drive-fotos-gestaoosparada.apikey.json` para a pasta do Drive `15WJIdzrykXWRSC5Xy4Ci5Cr7gq6FqMxK`.
|
||||||
2. Aplica um atraso artificial de 2,5 segundos (`delay(2500)`) usando Corrotinas para emular a latência de uma chamada de rede real.
|
3. **Link Público e Sincronismo com Google Sheets:** O serviço define a permissão pública (`anyone with link - reader`) e obtém o `webViewLink`, atualizando a Room DB e a aba `history` do Google Sheets.
|
||||||
3. Executa um algoritmo matemático simples de resolução de conflitos em cerca de 15% das ordens de serviço (usando o resto da divisão do hash do número da OS por 7).
|
4. **Soft Delete:** A exclusão de fotos no app não remove os arquivos fisicamente da pasta do Google Drive, mas executa uma chamada `PATCH` adicionando o sufixo `_DELETED` ao arquivo e atualiza os registros locais.
|
||||||
4. No cenário simulado de conflito, adota a estratégia **"Last-Write-Wins"** (Última escrita vence), assumindo que a alteração local feita no campo pelo inspetor é a mais recente e deve sobrescrever o "servidor".
|
|
||||||
5. Atualiza todos os registros modificados localmente no banco Room para `synced = true`.
|
|
||||||
|
|
||||||
### Arquivos responsáveis por essa conexão e sincronização:
|
### Arquivos responsáveis pela conexão e sincronização:
|
||||||
* **`com.example.data.model.MaintenanceActivity`:** Contém os atributos `synced: Boolean` (indica se a OS local está pareada com o servidor) e `lastUpdated: Long` (carimbo de data/hora em milissegundos para resolver conflitos de alteração concorrente).
|
* **`com.example.data.remote.GoogleDriveSyncService`:** Gerencia autenticação via Service Account, upload multipart de fotos e soft delete no Google Drive.
|
||||||
* **`com.example.data.local.MaintenanceDao`:** Contém a consulta SQL `@Query("SELECT * FROM maintenance_activities WHERE synced = 0")` para extrair apenas o que foi alterado offline e precisa subir.
|
* **`com.example.data.remote.GoogleSheetsSyncService`:** Gerencia autenticação via Service Account e reconciliação bidirecional com a planilha central do Google Sheets.
|
||||||
* **`com.example.data.repository.MaintenanceRepository`:** Contém o método `synchronizeWithBackend()`, que centraliza toda a lógica de preparação do lote de envio, simulação de rede e marcação de sincronizado.
|
* **`com.example.data.repository.MaintenanceRepository`:** Centraliza a orquestração do sync, upload de mídias pendentes, resolução de conflitos (LWW) e soft delete.
|
||||||
* **`com.example.ui.viewmodel.MaintenanceViewModel`:** Contém o método `syncWithBackend()`, que executa a chamada ao repositório dentro de um escopo de Coroutine, altera o estado da tela para "Carregando" (Loading), lida com o resultado de sucesso ou falha, e atualiza a UI.
|
* **`com.example.ui.viewmodel.MaintenanceViewModel`:** Gerencia os estados de sync na UI, disparos assíncronos e callbacks de gerenciamento de fotos.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,10 @@ adb install -r app/build/outputs/apk/debug/app-debug.apk
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export JAVA_HOME="/home/cesarjhony/dev/projects/gestao_de_manutencao/jdk"
|
||||||
|
export PATH="$JAVA_HOME/bin:$PATH"
|
||||||
|
./gradle_9_3_1/gradle-9.3.1/bin/gradle assembleDebug
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export JAVA_HOME="/home/cesarjhony/dev/projects/gestao_de_manutencao/jdk"
|
export JAVA_HOME="/home/cesarjhony/dev/projects/gestao_de_manutencao/jdk"
|
||||||
|
|||||||
@@ -6,20 +6,18 @@ Abaixo está o levantamento detalhado de cada um desses elementos, com suas resp
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Captura e Anexo de Fotos de Campo (Simulador de Câmera)
|
## 1. Captura, Anexo e Armazenamento de Fotos no Google Drive
|
||||||
|
|
||||||
* **Status:** **Simulado (Mockado)**
|
* **Status:** **IMPLEMENTADO (Produção)**
|
||||||
* **Arquivos Relacionados:**
|
* **Arquivos Relacionados:**
|
||||||
* [`MaintenanceDashboardScreen.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt) (linhas ~1038-1044 e ~1205-1238)
|
* [`GoogleDriveSyncService.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/GoogleDriveSyncService.kt)
|
||||||
* [`MaintenanceActivity.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/model/MaintenanceActivity.kt) (campo `fotoPath`)
|
* [`MaintenanceDashboardScreen.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt)
|
||||||
|
* [`MaintenanceRepository.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt)
|
||||||
* **Descrição Técnica:**
|
* **Descrição Técnica:**
|
||||||
O aplicativo não possui integração real com as APIs de hardware de câmera do Android (como `CameraX` ou `Camera2`) nem abre um seletor de arquivos de imagens (Intent de galeria).
|
A simulação fotográfica foi completamente substituída por funcionalidade real de produção:
|
||||||
Em vez disso, no modal de atualização de progresso (`EditActivityBottomSheet`), exibe-se uma lista horizontal (`LazyRow`) contendo quatro categorias pré-definidas de imagem fictícia:
|
* **Câmera & Galeria:** Suporte a disparo de câmera nativa do Android via `ActivityResultContracts.TakePicture()` e seleção de arquivos de imagem via `ActivityResultContracts.GetContent()`.
|
||||||
* *"Turbina"* -> registra o caminho `"ic_turbine_mock"`
|
* **Google Drive Sync:** Envio de imagens para a pasta remota ID `15WJIdzrykXWRSC5Xy4Ci5Cr7gq6FqMxK` usando a Service Account `drive-fotos-gestaoosparada.apikey.json`.
|
||||||
* *"Fiação Elétrica"* -> registra o caminho `"ic_electrical_mock"`
|
* **Galeria & Tela Cheia:** Exibição em carrossel horizontal (`LazyRow`) no modal da OS e visualização em tela cheia com botões de **Compartilhar** e **Deletar** (Soft Delete adicionando sufixo `_DELETED` no Google Drive).
|
||||||
* *"Mancal Engraxado"* -> registra o caminho `"ic_gear_mock"`
|
|
||||||
* *"Caldeira Lavada"* -> registra o caminho `"ic_boiler_mock"`
|
|
||||||
* **Impacto/Limitação:** O aplicativo apenas salva caminhos de strings estáticas no banco SQLite local (Room) e sincroniza este texto na aba `history` do Google Sheets, sem de fato capturar ou fazer upload de arquivos de imagem binários.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user