Compare commits
3 Commits
bc03351363
...
d0356573b9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0356573b9 | ||
|
|
a1ab21a5b9 | ||
|
|
4a4c151b14 |
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -492,7 +492,7 @@ class GoogleSheetsSyncService(
|
|||||||
it.contains("grupo de recursos") || it.contains("grupo_de_recursos")
|
it.contains("grupo de recursos") || it.contains("grupo_de_recursos")
|
||||||
}.let { idx ->
|
}.let { idx ->
|
||||||
if (idx != -1) idx else headers.indexOfFirst {
|
if (idx != -1) idx else headers.indexOfFirst {
|
||||||
it.contains("grupo") || it.contains("equipe") || it.contains("disciplina") || it.contains("setor")
|
it.contains("equipe") || it.contains("disciplina") || it.contains("grupo")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -660,7 +660,7 @@ class GoogleSheetsSyncService(
|
|||||||
val e = s.lowercase()
|
val e = s.lowercase()
|
||||||
return when {
|
return when {
|
||||||
e.contains("mec") -> "Mecânica"
|
e.contains("mec") -> "Mecânica"
|
||||||
e.contains("ele") -> "Elétrica"
|
e.contains("ele") || e.contains("elét") || e.contains("elet") -> "Elétrica"
|
||||||
e.contains("conf") -> "Confiabilidade"
|
e.contains("conf") -> "Confiabilidade"
|
||||||
e.contains("lub") -> "Lubrificação"
|
e.contains("lub") -> "Lubrificação"
|
||||||
else -> s
|
else -> s
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -149,7 +150,7 @@ class MaintenanceRepository(
|
|||||||
val osIdx = headers.indexOfFirst { it.contains("id exclusiva") || it == "id" || it.contains("numero da os") || it.contains("número da os") || (it.contains("os") && !it.contains("recursos")) || (it.contains("número") && !it.contains("tópicos")) }
|
val osIdx = headers.indexOfFirst { it.contains("id exclusiva") || it == "id" || it.contains("numero da os") || it.contains("número da os") || (it.contains("os") && !it.contains("recursos")) || (it.contains("número") && !it.contains("tópicos")) }
|
||||||
val descIdx = headers.indexOfFirst { it.contains("desc") || it.contains("atividade") || it.contains("ação") || it.contains("nome da tarefa") }
|
val descIdx = headers.indexOfFirst { it.contains("desc") || it.contains("atividade") || it.contains("ação") || it.contains("nome da tarefa") }
|
||||||
val setorIdx = headers.indexOfFirst { it.contains("setor") || it.contains("area") || it.contains("área") || it.contains("resumo da tarefa") }
|
val setorIdx = headers.indexOfFirst { it.contains("setor") || it.contains("area") || it.contains("área") || it.contains("resumo da tarefa") }
|
||||||
val eqIdx = headers.indexOfFirst { it.contains("equipe") || it.contains("eq") || it.contains("disc") || it.contains("tipo") || it.contains("grupo de recursos") }
|
val eqIdx = headers.indexOfFirst { it.contains("equipe") || it == "eq" || it.contains("disciplina") || it.contains("tipo") || it.contains("grupo de recursos") }
|
||||||
val respIdx = headers.indexOfFirst { it.contains("resp") || it.contains("encarregado") || it.contains("dono") || it.contains("nomes dos recursos") }
|
val respIdx = headers.indexOfFirst { it.contains("resp") || it.contains("encarregado") || it.contains("dono") || it.contains("nomes dos recursos") }
|
||||||
val inicioIdx = headers.indexOfFirst { it.contains("inicio") || it.contains("início") || it.contains("start") }
|
val inicioIdx = headers.indexOfFirst { it.contains("inicio") || it.contains("início") || it.contains("start") }
|
||||||
val fimIdx = headers.indexOfFirst { it.contains("fim") || it.contains("end") || it.contains("termino") || it.contains("término") }
|
val fimIdx = headers.indexOfFirst { it.contains("fim") || it.contains("end") || it.contains("termino") || it.contains("término") }
|
||||||
@@ -226,6 +227,13 @@ class MaintenanceRepository(
|
|||||||
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()
|
||||||
@@ -379,7 +387,7 @@ class MaintenanceRepository(
|
|||||||
val e = s.lowercase()
|
val e = s.lowercase()
|
||||||
return when {
|
return when {
|
||||||
e.contains("mec") -> "Mecânica"
|
e.contains("mec") -> "Mecânica"
|
||||||
e.contains("ele") -> "Elétrica"
|
e.contains("ele") || e.contains("elét") || e.contains("elet") -> "Elétrica"
|
||||||
e.contains("conf") -> "Confiabilidade"
|
e.contains("conf") -> "Confiabilidade"
|
||||||
e.contains("lub") -> "Lubrificação"
|
e.contains("lub") -> "Lubrificação"
|
||||||
else -> s
|
else -> s
|
||||||
@@ -429,6 +437,124 @@ 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 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
|
||||||
|
}
|
||||||
|
} 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(targetPhotoPath: String, osNumber: String) = withContext(Dispatchers.IO) {
|
||||||
|
val fileId = extractDriveFileId(targetPhotoPath)
|
||||||
|
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 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) {
|
||||||
|
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.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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
@@ -196,6 +197,11 @@ fun MaintenanceDashboardScreen(
|
|||||||
listOf("Todos") + sectors
|
listOf("Todos") + sectors
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val uniqueEquipes = remember(allActivities) {
|
||||||
|
val eqList = allActivities.map { it.equipe.trim() }.filter { it.isNotBlank() }.distinct().sorted()
|
||||||
|
listOf("Todas") + eqList
|
||||||
|
}
|
||||||
|
|
||||||
// Launcher for file picking (CSV Spreadsheet)
|
// Launcher for file picking (CSV Spreadsheet)
|
||||||
val filePickerLauncher = rememberLauncherForActivityResult(
|
val filePickerLauncher = rememberLauncherForActivityResult(
|
||||||
contract = ActivityResultContracts.GetContent()
|
contract = ActivityResultContracts.GetContent()
|
||||||
@@ -472,6 +478,7 @@ fun MaintenanceDashboardScreen(
|
|||||||
selectedDataInicio = selectedDataInicio,
|
selectedDataInicio = selectedDataInicio,
|
||||||
selectedRecurso = selectedRecurso,
|
selectedRecurso = selectedRecurso,
|
||||||
uniqueSectors = uniqueSectors,
|
uniqueSectors = uniqueSectors,
|
||||||
|
uniqueEquipes = uniqueEquipes,
|
||||||
uniqueDates = uniqueDates,
|
uniqueDates = uniqueDates,
|
||||||
uniqueRecursos = uniqueRecursos,
|
uniqueRecursos = uniqueRecursos,
|
||||||
onSetorSelected = { viewModel.setFilterSetor(it) },
|
onSetorSelected = { viewModel.setFilterSetor(it) },
|
||||||
@@ -592,16 +599,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)
|
||||||
}
|
}
|
||||||
@@ -744,6 +760,7 @@ fun FilterPillsRow(
|
|||||||
selectedDataInicio: String,
|
selectedDataInicio: String,
|
||||||
selectedRecurso: String,
|
selectedRecurso: String,
|
||||||
uniqueSectors: List<String>,
|
uniqueSectors: List<String>,
|
||||||
|
uniqueEquipes: List<String>,
|
||||||
uniqueDates: List<String>,
|
uniqueDates: List<String>,
|
||||||
uniqueRecursos: List<String>,
|
uniqueRecursos: List<String>,
|
||||||
onSetorSelected: (String) -> Unit,
|
onSetorSelected: (String) -> Unit,
|
||||||
@@ -753,7 +770,7 @@ fun FilterPillsRow(
|
|||||||
onRecursoSelected: (String) -> Unit
|
onRecursoSelected: (String) -> Unit
|
||||||
) {
|
) {
|
||||||
val setores = uniqueSectors
|
val setores = uniqueSectors
|
||||||
val equipes = listOf("Todas", "Mecânica", "Elétrica", "Confiabilidade", "Lubrificação")
|
val equipes = uniqueEquipes
|
||||||
val statusList = listOf("Todos", "Não iniciado", "Em andamento", "Concluído")
|
val statusList = listOf("Todos", "Não iniciado", "Em andamento", "Concluído")
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
@@ -1068,6 +1085,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 +1207,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 +1268,45 @@ 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) }
|
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) }
|
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",
|
fun processPath(raw: String?) {
|
||||||
"Fiação Elétrica" to "ic_electrical_mock",
|
if (!raw.isNullOrBlank()) {
|
||||||
"Mancal Engraxado" to "ic_gear_mock",
|
raw.split("|").forEach { p ->
|
||||||
"Caldeira Lavada" to "ic_boiler_mock"
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
val cameraLauncher = rememberLauncherForActivityResult(
|
||||||
|
contract = ActivityResultContracts.TakePicture()
|
||||||
|
) { success ->
|
||||||
|
if (success && tempCameraPath != null) {
|
||||||
|
newPhotosList.add(tempCameraPath!!)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val galleryLauncher = rememberLauncherForActivityResult(
|
||||||
|
contract = ActivityResultContracts.GetContent()
|
||||||
|
) { uri: Uri? ->
|
||||||
|
uri?.let {
|
||||||
|
val savedPath = onSavePhotoFromUri(it)
|
||||||
|
newPhotosList.add(savedPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Header: OS + Close
|
// Header: OS + Close
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
@@ -1285,80 +1444,154 @@ 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)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
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
|
||||||
)
|
)
|
||||||
|
if (newPhotosList.isNotEmpty()) {
|
||||||
Text(
|
Text(
|
||||||
text = "Selecione uma categoria de inspeção para simular o anexo fotográfico da atividade:",
|
text = "${newPhotosList.size} foto(s) pendente(s)",
|
||||||
fontSize = 11.sp,
|
fontSize = 11.sp,
|
||||||
color = StatusGrey
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = BrandGreen
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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, newPhotosList.toList()) {
|
||||||
Box(
|
(newPhotosList + activePhotos).distinct()
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = newPhotosList.contains(photoPath)
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(88.dp)
|
||||||
|
.clickable { selectedPhotoForViewer = photoPath },
|
||||||
|
shape = RoundedCornerShape(8.dp),
|
||||||
|
border = BorderStroke(2.dp, if (isNew) BrandGreen else Color(0xFFE0E0E0))
|
||||||
) {
|
) {
|
||||||
Icon(Icons.Default.Check, contentDescription = "Foto vinculada", tint = BrandGreen)
|
Box(modifier = Modifier.fillMaxSize()) {
|
||||||
Text(
|
coil.compose.AsyncImage(
|
||||||
text = "Foto do componente '$selectedMockPhotoPath' anexada com sucesso à OS localmente!",
|
model = photoPath,
|
||||||
fontSize = 11.sp,
|
contentDescription = "Miniatura da foto",
|
||||||
color = BrandGreen,
|
modifier = Modifier.fillMaxSize(),
|
||||||
fontWeight = FontWeight.Bold
|
contentScale = androidx.compose.ui.layout.ContentScale.Crop
|
||||||
|
)
|
||||||
|
if (isNew) {
|
||||||
|
// Badge NOVA
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.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)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} 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 (newPhotosList.contains(photoToDelete)) {
|
||||||
|
newPhotosList.remove(photoToDelete)
|
||||||
|
} else {
|
||||||
|
onSoftDeletePhoto(photoToDelete)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Save Action Button or Google Login Warning Banner
|
// Save Action Button or Google Login Warning Banner
|
||||||
if (currentUser == null) {
|
if (currentUser == null) {
|
||||||
@@ -1465,7 +1698,8 @@ fun EditActivityBottomSheet(
|
|||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
isSubmitting = true
|
isSubmitting = true
|
||||||
onUpdateProgress(progressValue.toInt(), observationText, selectedMockPhotoPath)
|
val photoParam = if (newPhotosList.isNotEmpty()) newPhotosList.joinToString("|") else null
|
||||||
|
onUpdateProgress(progressValue.toInt(), observationText, photoParam)
|
||||||
onDismiss()
|
onDismiss()
|
||||||
},
|
},
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
|
|||||||
@@ -132,7 +132,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
|
|
||||||
val filtered = activities.filter { activity ->
|
val filtered = activities.filter { activity ->
|
||||||
val matchSetor = setor == "Todos" || activity.setor == setor
|
val matchSetor = setor == "Todos" || activity.setor == setor
|
||||||
val matchEquipe = equipe == "Todas" || activity.equipe == equipe
|
val matchEquipe = equipe == "Todas" || activity.equipe.trim().equals(equipe.trim(), ignoreCase = true)
|
||||||
val matchStatus = status == "Todos" || when (status) {
|
val matchStatus = status == "Todos" || when (status) {
|
||||||
"Não iniciado" -> activity.status == ActivityStatus.NAO_INICIADO
|
"Não iniciado" -> activity.status == ActivityStatus.NAO_INICIADO
|
||||||
"Em andamento" -> activity.status == ActivityStatus.EM_ANDAMENTO
|
"Em andamento" -> activity.status == ActivityStatus.EM_ANDAMENTO
|
||||||
@@ -164,9 +164,9 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
"Em andamento" -> activity.status == ActivityStatus.EM_ANDAMENTO
|
"Em andamento" -> activity.status == ActivityStatus.EM_ANDAMENTO
|
||||||
"Não iniciado" -> activity.status == ActivityStatus.NAO_INICIADO
|
"Não iniciado" -> activity.status == ActivityStatus.NAO_INICIADO
|
||||||
"Mecânica" -> activity.equipe == "Mecânica"
|
"Mecânica" -> activity.equipe.equals("Mecânica", ignoreCase = true)
|
||||||
"Elétrica" -> activity.equipe == "Elétrica"
|
"Elétrica" -> activity.equipe.equals("Elétrica", ignoreCase = true)
|
||||||
"Confiabilidade" -> activity.equipe == "Confiabilidade"
|
"Confiabilidade" -> activity.equipe.equals("Confiabilidade", ignoreCase = true)
|
||||||
else -> true
|
else -> true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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())
|
||||||
@@ -500,7 +522,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 1. Team metrics
|
// 1. Team metrics
|
||||||
val teams = listOf("Mecânica", "Elétrica", "Confiabilidade", "Lubrificação")
|
val teams = activities.map { it.equipe.trim() }.filter { it.isNotBlank() }.distinct().sorted()
|
||||||
val teamMetrics = teams.map { team ->
|
val teamMetrics = teams.map { team ->
|
||||||
val teamActivities = activities.filter { it.equipe.equals(team, ignoreCase = true) }
|
val teamActivities = activities.filter { it.equipe.equals(team, ignoreCase = true) }
|
||||||
val total = teamActivities.size
|
val total = teamActivities.size
|
||||||
|
|||||||
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>
|
||||||
@@ -308,4 +308,39 @@ class ExampleUnitTest {
|
|||||||
assertFalse(hasWriteAccess("random@empresa.com"))
|
assertFalse(hasWriteAccess("random@empresa.com"))
|
||||||
assertFalse(hasWriteAccess("nonexistent@empresa.com"))
|
assertFalse(hasWriteAccess("nonexistent@empresa.com"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testDynamicEquipeFiltering() {
|
||||||
|
val activities = listOf(
|
||||||
|
com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "101", descricao = "Troca de Motor", setor = "Geral", equipe = "Elétrica", recurso = "Resp A",
|
||||||
|
dataInicio = "01/08/2026", dataFim = "05/08/2026", percentualExecucao = 100
|
||||||
|
),
|
||||||
|
com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "102", descricao = "Reparo de Painel", setor = "Geral", equipe = "elétrica", recurso = "Resp B",
|
||||||
|
dataInicio = "01/08/2026", dataFim = "05/08/2026", percentualExecucao = 50
|
||||||
|
),
|
||||||
|
com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "103", descricao = "Solda Estrutural", setor = "Geral", equipe = "Caldeiraria", recurso = "Resp C",
|
||||||
|
dataInicio = "01/08/2026", dataFim = "05/08/2026", percentualExecucao = 20
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Verify dynamic extraction
|
||||||
|
val eqList = activities.map { it.equipe.trim() }.filter { it.isNotBlank() }.distinct().sorted()
|
||||||
|
val uniqueEquipes = listOf("Todas") + eqList
|
||||||
|
assertTrue(uniqueEquipes.contains("Elétrica"))
|
||||||
|
assertTrue(uniqueEquipes.contains("elétrica"))
|
||||||
|
assertTrue(uniqueEquipes.contains("Caldeiraria"))
|
||||||
|
|
||||||
|
// Case-insensitive filtering check for Elétrica
|
||||||
|
val eletricaActivities = activities.filter { it.equipe.trim().equals("Elétrica", ignoreCase = true) }
|
||||||
|
assertEquals(2, eletricaActivities.size)
|
||||||
|
|
||||||
|
// Dynamic team filtering check for Caldeiraria
|
||||||
|
val caldeirariaActivities = activities.filter { it.equipe.trim().equals("Caldeiraria", ignoreCase = true) }
|
||||||
|
assertEquals(1, caldeirariaActivities.size)
|
||||||
|
assertEquals("103", caldeirariaActivities[0].numeroOs)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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 & 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.
|
* 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