Compare commits
2 Commits
d0356573b9
...
6b8653fad3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b8653fad3 | ||
|
|
0d1991337a |
@@ -114,6 +114,8 @@ dependencies {
|
|||||||
implementation(libs.converter.moshi)
|
implementation(libs.converter.moshi)
|
||||||
implementation(libs.firebase.ai)
|
implementation(libs.firebase.ai)
|
||||||
implementation(libs.firebase.appcheck.recaptcha)
|
implementation(libs.firebase.appcheck.recaptcha)
|
||||||
|
implementation(libs.firebase.auth)
|
||||||
|
implementation(libs.firebase.storage)
|
||||||
implementation(libs.kotlinx.coroutines.android)
|
implementation(libs.kotlinx.coroutines.android)
|
||||||
implementation(libs.kotlinx.coroutines.core)
|
implementation(libs.kotlinx.coroutines.core)
|
||||||
implementation(libs.logging.interceptor)
|
implementation(libs.logging.interceptor)
|
||||||
|
|||||||
@@ -4,18 +4,20 @@ import android.content.Context
|
|||||||
import androidx.room.Database
|
import androidx.room.Database
|
||||||
import androidx.room.Room
|
import androidx.room.Room
|
||||||
import androidx.room.RoomDatabase
|
import androidx.room.RoomDatabase
|
||||||
|
import com.example.data.model.AppLog
|
||||||
import com.example.data.model.MaintenanceActivity
|
import com.example.data.model.MaintenanceActivity
|
||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
import com.example.data.model.SyncConflictLog
|
import com.example.data.model.SyncConflictLog
|
||||||
import com.example.data.model.UserAccess
|
import com.example.data.model.UserAccess
|
||||||
|
|
||||||
@Database(
|
@Database(
|
||||||
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class],
|
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class, AppLog::class],
|
||||||
version = 5,
|
version = 6,
|
||||||
exportSchema = false
|
exportSchema = false
|
||||||
)
|
)
|
||||||
abstract class AppDatabase : RoomDatabase() {
|
abstract class AppDatabase : RoomDatabase() {
|
||||||
abstract fun maintenanceDao(): MaintenanceDao
|
abstract fun maintenanceDao(): MaintenanceDao
|
||||||
|
abstract fun appLogDao(): AppLogDao
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
@Volatile
|
@Volatile
|
||||||
|
|||||||
23
app/src/main/java/com/example/data/local/AppLogDao.kt
Normal file
23
app/src/main/java/com/example/data/local/AppLogDao.kt
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
package com.example.data.local
|
||||||
|
|
||||||
|
import androidx.room.Dao
|
||||||
|
import androidx.room.Insert
|
||||||
|
import androidx.room.OnConflictStrategy
|
||||||
|
import androidx.room.Query
|
||||||
|
import com.example.data.model.AppLog
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
|
@Dao
|
||||||
|
interface AppLogDao {
|
||||||
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
|
suspend fun insertLog(log: AppLog)
|
||||||
|
|
||||||
|
@Query("SELECT * FROM app_logs ORDER BY timestamp DESC LIMIT 500")
|
||||||
|
fun getAllLogsFlow(): Flow<List<AppLog>>
|
||||||
|
|
||||||
|
@Query("SELECT * FROM app_logs ORDER BY timestamp DESC LIMIT 500")
|
||||||
|
suspend fun getAllLogsList(): List<AppLog>
|
||||||
|
|
||||||
|
@Query("DELETE FROM app_logs")
|
||||||
|
suspend fun clearAllLogs()
|
||||||
|
}
|
||||||
23
app/src/main/java/com/example/data/model/AppLog.kt
Normal file
23
app/src/main/java/com/example/data/model/AppLog.kt
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
package com.example.data.model
|
||||||
|
|
||||||
|
import androidx.room.Entity
|
||||||
|
import androidx.room.PrimaryKey
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
@Entity(tableName = "app_logs")
|
||||||
|
data class AppLog(
|
||||||
|
@PrimaryKey(autoGenerate = true) val id: Long = 0,
|
||||||
|
val timestamp: Long = System.currentTimeMillis(),
|
||||||
|
val level: String, // "ERROR", "WARN", "INFO"
|
||||||
|
val tag: String,
|
||||||
|
val message: String,
|
||||||
|
val stackTrace: String? = null
|
||||||
|
) {
|
||||||
|
val formattedTimestamp: String
|
||||||
|
get() {
|
||||||
|
val sdf = SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault())
|
||||||
|
return sdf.format(Date(timestamp))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package com.example.data.remote
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import android.util.Log
|
||||||
|
import com.example.util.AppLogger
|
||||||
|
import com.google.firebase.storage.FirebaseStorage
|
||||||
|
import com.google.firebase.storage.StorageReference
|
||||||
|
import kotlinx.coroutines.tasks.await
|
||||||
|
import java.io.File
|
||||||
|
import java.io.IOException
|
||||||
|
|
||||||
|
data class FirebaseUploadResult(
|
||||||
|
val downloadUrl: String,
|
||||||
|
val storagePath: String,
|
||||||
|
val fileName: String
|
||||||
|
)
|
||||||
|
|
||||||
|
class FirebaseStorageSyncService(
|
||||||
|
private val context: Context
|
||||||
|
) {
|
||||||
|
private val tag = "FirebaseStorageSync"
|
||||||
|
private val appLogger = AppLogger.getInstance(context)
|
||||||
|
private val storage: FirebaseStorage by lazy { FirebaseStorage.getInstance() }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Uploads a local photo file to Firebase Storage under `photos/OS_{osNumber}/{fileName}`.
|
||||||
|
* Returns FirebaseUploadResult containing the public download URL and storage path.
|
||||||
|
*/
|
||||||
|
suspend fun uploadPhoto(photoFile: File, osNumber: String): FirebaseUploadResult {
|
||||||
|
if (!photoFile.exists()) {
|
||||||
|
val err = "Arquivo local da foto não existe: ${photoFile.absolutePath}"
|
||||||
|
appLogger.logError(tag, err)
|
||||||
|
throw IOException(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
val timestamp = System.currentTimeMillis()
|
||||||
|
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
|
||||||
|
val fileName = "OS_${sanitizedOs}_${timestamp}.jpg"
|
||||||
|
val storagePath = "photos/OS_${sanitizedOs}/$fileName"
|
||||||
|
|
||||||
|
val photoRef: StorageReference = storage.reference.child(storagePath)
|
||||||
|
|
||||||
|
// Ensure user is authenticated with Firebase Auth if possible
|
||||||
|
val auth = com.google.firebase.auth.FirebaseAuth.getInstance()
|
||||||
|
if (auth.currentUser == null) {
|
||||||
|
val lastAccount = com.google.android.gms.auth.api.signin.GoogleSignIn.getLastSignedInAccount(context)
|
||||||
|
val idToken = lastAccount?.idToken
|
||||||
|
if (!idToken.isNullOrBlank()) {
|
||||||
|
try {
|
||||||
|
val credential = com.google.firebase.auth.GoogleAuthProvider.getCredential(idToken, null)
|
||||||
|
auth.signInWithCredential(credential).await()
|
||||||
|
Log.d(tag, "Sincronização silenciosa do FirebaseAuth concluída para ${lastAccount.email}")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(tag, "Tentativa de login silencioso no FirebaseAuth falhou: ${e.message}")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Log.w(tag, "Aviso: Nenhum usuário autenticado no FirebaseAuth nem ID Token do Google disponível.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
val fileUri = Uri.fromFile(photoFile)
|
||||||
|
photoRef.putFile(fileUri).await()
|
||||||
|
val downloadUrl = photoRef.downloadUrl.await().toString()
|
||||||
|
|
||||||
|
appLogger.logInfo(tag, "Foto enviada com sucesso para o Firebase Storage. OS: $osNumber, Path: $storagePath")
|
||||||
|
return FirebaseUploadResult(
|
||||||
|
downloadUrl = downloadUrl,
|
||||||
|
storagePath = storagePath,
|
||||||
|
fileName = fileName
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
val msg = "Erro ao enviar foto da OS $osNumber para o Firebase Storage: ${e.message}"
|
||||||
|
appLogger.logError(tag, msg, e)
|
||||||
|
throw IOException(msg, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Performs Soft Delete by copying the file object in Firebase Storage to have "_DELETED"
|
||||||
|
* suffix in the exact same folder, and deleting the original reference.
|
||||||
|
*/
|
||||||
|
suspend fun softDeletePhoto(photoUrlOrPath: String, osNumber: String): Boolean {
|
||||||
|
return try {
|
||||||
|
val ref = if (photoUrlOrPath.startsWith("http://") || photoUrlOrPath.startsWith("https://")) {
|
||||||
|
storage.getReferenceFromUrl(photoUrlOrPath)
|
||||||
|
} else {
|
||||||
|
storage.reference.child(photoUrlOrPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
val currentPath = ref.path
|
||||||
|
if (currentPath.contains("_DELETED")) {
|
||||||
|
Log.d(tag, "Arquivo $currentPath já está marcado como deletado.")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
val dotIndex = currentPath.lastIndexOf('.')
|
||||||
|
val newPath = if (dotIndex != -1) {
|
||||||
|
val base = currentPath.substring(0, dotIndex)
|
||||||
|
val ext = currentPath.substring(dotIndex)
|
||||||
|
"${base}_DELETED$ext"
|
||||||
|
} else {
|
||||||
|
"${currentPath}_DELETED"
|
||||||
|
}
|
||||||
|
|
||||||
|
val newRef = storage.reference.child(newPath)
|
||||||
|
val bytes = ref.getBytes(10 * 1024 * 1024).await() // Max 10MB photo limit
|
||||||
|
newRef.putBytes(bytes).await()
|
||||||
|
ref.delete().await()
|
||||||
|
|
||||||
|
Log.d(tag, "Arquivo $currentPath renomeado no Firebase Storage para $newPath (Soft Delete).")
|
||||||
|
true
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(tag, "Falha ao executar soft delete no Firebase Storage: ${e.message}", e)
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,202 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -21,9 +21,17 @@ class MaintenanceRepository(
|
|||||||
val timeGuardManager: com.example.util.TimeGuardManager = com.example.util.TimeGuardManager()
|
val timeGuardManager: com.example.util.TimeGuardManager = com.example.util.TimeGuardManager()
|
||||||
) {
|
) {
|
||||||
|
|
||||||
|
private val appDatabase = com.example.data.local.AppDatabase.getDatabase(context)
|
||||||
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 firebaseStorageSyncService = com.example.data.remote.FirebaseStorageSyncService(context)
|
||||||
private val networkMonitor = com.example.util.NetworkMonitor(context)
|
private val networkMonitor = com.example.util.NetworkMonitor(context)
|
||||||
|
private val appLogDao = appDatabase.appLogDao()
|
||||||
|
|
||||||
|
val allAppLogs: Flow<List<com.example.data.model.AppLog>> = appLogDao.getAllLogsFlow()
|
||||||
|
|
||||||
|
suspend fun clearAppLogs() = withContext(Dispatchers.IO) {
|
||||||
|
appLogDao.clearAllLogs()
|
||||||
|
}
|
||||||
|
|
||||||
val isNetworkConnected: Flow<Boolean> = networkMonitor.isConnected
|
val isNetworkConnected: Flow<Boolean> = networkMonitor.isConnected
|
||||||
fun isCurrentlyConnected(): Boolean = networkMonitor.isCurrentlyConnected()
|
fun isCurrentlyConnected(): Boolean = networkMonitor.isCurrentlyConnected()
|
||||||
@@ -478,11 +486,11 @@ class MaintenanceRepository(
|
|||||||
val file = java.io.File(trimmed)
|
val file = java.io.File(trimmed)
|
||||||
if (file.exists()) {
|
if (file.exists()) {
|
||||||
try {
|
try {
|
||||||
val result = driveSyncService.uploadPhotoToDrive(file, history.numeroOs)
|
val result = firebaseStorageSyncService.uploadPhoto(file, history.numeroOs)
|
||||||
changed = true
|
changed = true
|
||||||
result.webViewLink
|
result.downloadUrl
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Drive: ${e.message}", e)
|
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Firebase Storage: ${e.message}", e)
|
||||||
trimmed
|
trimmed
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -508,13 +516,11 @@ class MaintenanceRepository(
|
|||||||
}
|
}
|
||||||
|
|
||||||
suspend fun softDeletePhoto(targetPhotoPath: String, osNumber: String) = withContext(Dispatchers.IO) {
|
suspend fun softDeletePhoto(targetPhotoPath: String, osNumber: String) = withContext(Dispatchers.IO) {
|
||||||
val fileId = extractDriveFileId(targetPhotoPath)
|
if (isCurrentlyConnected() && (targetPhotoPath.startsWith("http://") || targetPhotoPath.startsWith("https://") || targetPhotoPath.startsWith("photos/"))) {
|
||||||
if (fileId != null && isCurrentlyConnected()) {
|
|
||||||
try {
|
try {
|
||||||
val fileName = "OS_${osNumber}_photo.jpg"
|
firebaseStorageSyncService.softDeletePhoto(targetPhotoPath, osNumber)
|
||||||
driveSyncService.softDeletePhotoOnDrive(fileId, fileName)
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
android.util.Log.e("MaintenanceRepository", "Erro ao executar soft delete no Google Drive: ${e.message}", e)
|
android.util.Log.e("MaintenanceRepository", "Erro ao executar soft delete no Firebase Storage: ${e.message}", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -540,21 +546,6 @@ class MaintenanceRepository(
|
|||||||
dao.updateActivity(activity.copy(fotoPath = updatedPaths.joinToString("|"), synced = false))
|
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 {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import androidx.compose.foundation.shape.CircleShape
|
|||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.tasks.await
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||||
import androidx.compose.material3.*
|
import androidx.compose.material3.*
|
||||||
@@ -80,8 +81,18 @@ fun AnalyticsScreen(
|
|||||||
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
|
||||||
val gso = remember {
|
val defaultWebClientId = remember(context) {
|
||||||
|
try {
|
||||||
|
val resId = context.resources.getIdentifier("default_web_client_id", "string", context.packageName)
|
||||||
|
if (resId != 0) context.getString(resId) else "461441632355-rg9go0tcsr8ora2la83aat9pcekqo13p.apps.googleusercontent.com"
|
||||||
|
} catch (e: Exception) {
|
||||||
|
"461441632355-rg9go0tcsr8ora2la83aat9pcekqo13p.apps.googleusercontent.com"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val gso = remember(defaultWebClientId) {
|
||||||
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
||||||
|
.requestIdToken(defaultWebClientId)
|
||||||
.requestEmail()
|
.requestEmail()
|
||||||
.requestProfile()
|
.requestProfile()
|
||||||
.build()
|
.build()
|
||||||
@@ -98,6 +109,18 @@ fun AnalyticsScreen(
|
|||||||
val email = account.email ?: ""
|
val email = account.email ?: ""
|
||||||
val name = account.displayName ?: ""
|
val name = account.displayName ?: ""
|
||||||
viewModel.loginUser(email, name)
|
viewModel.loginUser(email, name)
|
||||||
|
|
||||||
|
val idToken = account.idToken
|
||||||
|
if (!idToken.isNullOrBlank()) {
|
||||||
|
kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO).launch {
|
||||||
|
try {
|
||||||
|
val credential = com.google.firebase.auth.GoogleAuthProvider.getCredential(idToken, null)
|
||||||
|
com.google.firebase.auth.FirebaseAuth.getInstance().signInWithCredential(credential).await()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("FirebaseAuth", "Erro ao autenticar no Firebase Auth: ${e.message}", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Toast.makeText(context, "Conectado como $name", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, "Conectado como $name", Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
} catch (e: ApiException) {
|
} catch (e: ApiException) {
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import androidx.compose.ui.window.Dialog
|
|||||||
import androidx.compose.ui.window.DialogProperties
|
import androidx.compose.ui.window.DialogProperties
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.tasks.await
|
||||||
import com.google.android.gms.auth.api.signin.GoogleSignIn
|
import com.google.android.gms.auth.api.signin.GoogleSignIn
|
||||||
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
|
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
|
||||||
import com.google.android.gms.common.api.ApiException
|
import com.google.android.gms.common.api.ApiException
|
||||||
@@ -123,8 +124,18 @@ fun MaintenanceDashboardScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
val gso = remember {
|
val defaultWebClientId = remember(context) {
|
||||||
|
try {
|
||||||
|
val resId = context.resources.getIdentifier("default_web_client_id", "string", context.packageName)
|
||||||
|
if (resId != 0) context.getString(resId) else "461441632355-rg9go0tcsr8ora2la83aat9pcekqo13p.apps.googleusercontent.com"
|
||||||
|
} catch (e: Exception) {
|
||||||
|
"461441632355-rg9go0tcsr8ora2la83aat9pcekqo13p.apps.googleusercontent.com"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val gso = remember(defaultWebClientId) {
|
||||||
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
||||||
|
.requestIdToken(defaultWebClientId)
|
||||||
.requestEmail()
|
.requestEmail()
|
||||||
.requestProfile()
|
.requestProfile()
|
||||||
.build()
|
.build()
|
||||||
@@ -141,6 +152,19 @@ fun MaintenanceDashboardScreen(
|
|||||||
val email = account.email ?: ""
|
val email = account.email ?: ""
|
||||||
val name = account.displayName ?: ""
|
val name = account.displayName ?: ""
|
||||||
viewModel.loginUser(email, name)
|
viewModel.loginUser(email, name)
|
||||||
|
|
||||||
|
val idToken = account.idToken
|
||||||
|
if (!idToken.isNullOrBlank()) {
|
||||||
|
kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO).launch {
|
||||||
|
try {
|
||||||
|
val credential = com.google.firebase.auth.GoogleAuthProvider.getCredential(idToken, null)
|
||||||
|
com.google.firebase.auth.FirebaseAuth.getInstance().signInWithCredential(credential).await()
|
||||||
|
android.util.Log.d("FirebaseAuth", "Autenticado no Firebase Auth com sucesso!")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("FirebaseAuth", "Erro ao autenticar no Firebase Auth: ${e.message}", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Toast.makeText(context, "Conectado como $name", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, "Conectado como $name", Toast.LENGTH_SHORT).show()
|
||||||
} else {
|
} else {
|
||||||
Toast.makeText(context, "Erro ao obter dados da conta Google.", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, "Erro ao obter dados da conta Google.", Toast.LENGTH_SHORT).show()
|
||||||
@@ -158,6 +182,19 @@ fun MaintenanceDashboardScreen(
|
|||||||
val email = lastAccount.email ?: ""
|
val email = lastAccount.email ?: ""
|
||||||
val name = lastAccount.displayName ?: ""
|
val name = lastAccount.displayName ?: ""
|
||||||
viewModel.loginUser(email, name)
|
viewModel.loginUser(email, name)
|
||||||
|
|
||||||
|
val idToken = lastAccount.idToken
|
||||||
|
if (!idToken.isNullOrBlank() && com.google.firebase.auth.FirebaseAuth.getInstance().currentUser == null) {
|
||||||
|
kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||||
|
try {
|
||||||
|
val credential = com.google.firebase.auth.GoogleAuthProvider.getCredential(idToken, null)
|
||||||
|
com.google.firebase.auth.FirebaseAuth.getInstance().signInWithCredential(credential).await()
|
||||||
|
android.util.Log.d("FirebaseAuth", "Reautenticado no Firebase Auth com sucesso!")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("FirebaseAuth", "Erro ao reautenticar no Firebase Auth: ${e.message}", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.example.ui.screens
|
package com.example.ui.screens
|
||||||
|
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
|
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
@@ -63,9 +64,11 @@ fun SettingsScreen(
|
|||||||
val connectionTested by viewModel.connectionTested.collectAsStateWithLifecycle()
|
val connectionTested by viewModel.connectionTested.collectAsStateWithLifecycle()
|
||||||
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
|
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
|
||||||
val conflictLogs by viewModel.conflictLogs.collectAsStateWithLifecycle()
|
val conflictLogs by viewModel.conflictLogs.collectAsStateWithLifecycle()
|
||||||
|
val appLogs by viewModel.appLogsState.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
var showClearCacheDialog by remember { mutableStateOf(false) }
|
var showClearCacheDialog by remember { mutableStateOf(false) }
|
||||||
var showConflictsDialog by remember { mutableStateOf(false) }
|
var showConflictsDialog by remember { mutableStateOf(false) }
|
||||||
|
var showLogsDialog by remember { mutableStateOf(false) }
|
||||||
var activeTestModal by remember { mutableStateOf<Int?>(null) }
|
var activeTestModal by remember { mutableStateOf<Int?>(null) }
|
||||||
|
|
||||||
// Start monitoring GCP API status when screen is open, stop when closed
|
// Start monitoring GCP API status when screen is open, stop when closed
|
||||||
@@ -364,6 +367,15 @@ fun SettingsScreen(
|
|||||||
showConflictsDialog = true
|
showConflictsDialog = true
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Botão 5: Histórico de Logs do App
|
||||||
|
AdminButton(
|
||||||
|
text = "Histórico de Logs",
|
||||||
|
icon = Icons.Default.ListAlt,
|
||||||
|
onClick = {
|
||||||
|
showLogsDialog = true
|
||||||
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -416,6 +428,14 @@ fun SettingsScreen(
|
|||||||
onDismiss = { showConflictsDialog = false }
|
onDismiss = { showConflictsDialog = false }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (showLogsDialog) {
|
||||||
|
AppLogsHistoryDialog(
|
||||||
|
logs = appLogs,
|
||||||
|
onClear = { viewModel.clearAppLogs() },
|
||||||
|
onDismiss = { showLogsDialog = false }
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@@ -740,4 +760,189 @@ fun AdminButton(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun AppLogsHistoryDialog(
|
||||||
|
logs: List<com.example.data.model.AppLog>,
|
||||||
|
onClear: () -> Unit,
|
||||||
|
onDismiss: () -> Unit
|
||||||
|
) {
|
||||||
|
Dialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||||
|
) {
|
||||||
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth(0.92f)
|
||||||
|
.fillMaxHeight(0.85f),
|
||||||
|
shape = RoundedCornerShape(16.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.White)
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(16.dp)
|
||||||
|
) {
|
||||||
|
// Header
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.ListAlt,
|
||||||
|
contentDescription = "Logs",
|
||||||
|
tint = BrandGreen
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Histórico de Logs do App",
|
||||||
|
fontSize = 18.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = BrandBlack
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
IconButton(onClick = onDismiss) {
|
||||||
|
Icon(Icons.Default.Close, contentDescription = "Fechar")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
|
||||||
|
// Subtitle
|
||||||
|
Text(
|
||||||
|
text = "Falhas, avisos de sincronização e logs de execução. É possível selecionar e copiar qualquer trecho de texto.",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = Color.Gray
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
// SelectionContainer wrapping the LazyColumn for selectable text!
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.fillMaxWidth()
|
||||||
|
.background(Color(0xFFF8F9FA), shape = RoundedCornerShape(8.dp))
|
||||||
|
.padding(8.dp)
|
||||||
|
) {
|
||||||
|
if (logs.isEmpty()) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Nenhum log registrado até o momento.",
|
||||||
|
color = Color.Gray,
|
||||||
|
fontSize = 13.sp
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
SelectionContainer {
|
||||||
|
LazyColumn(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
|
) {
|
||||||
|
items(logs) { log ->
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
shape = RoundedCornerShape(6.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
|
border = BorderStroke(
|
||||||
|
1.dp,
|
||||||
|
when (log.level) {
|
||||||
|
"ERROR" -> Color(0xFFFFCDD2)
|
||||||
|
"WARN" -> Color(0xFFFFE0B2)
|
||||||
|
else -> Color(0xFFE0E0E0)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(10.dp)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Surface(
|
||||||
|
color = when (log.level) {
|
||||||
|
"ERROR" -> Color(0xFFD32F2F)
|
||||||
|
"WARN" -> Color(0xFFF57C00)
|
||||||
|
else -> BrandGreen
|
||||||
|
},
|
||||||
|
shape = RoundedCornerShape(4.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "[${log.level}] ${log.tag}",
|
||||||
|
color = Color.White,
|
||||||
|
fontSize = 10.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = log.formattedTimestamp,
|
||||||
|
fontSize = 10.sp,
|
||||||
|
color = Color.Gray
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(6.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = log.message,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
color = BrandBlack
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!log.stackTrace.isNullOrBlank()) {
|
||||||
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
|
Text(
|
||||||
|
text = log.stackTrace,
|
||||||
|
fontSize = 10.sp,
|
||||||
|
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
|
||||||
|
color = Color(0xFFC62828)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
// Footer
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
TextButton(
|
||||||
|
onClick = onClear,
|
||||||
|
enabled = logs.isNotEmpty()
|
||||||
|
) {
|
||||||
|
Icon(Icons.Default.Delete, contentDescription = "Limpar", modifier = Modifier.size(16.dp), tint = Color.Red)
|
||||||
|
Spacer(modifier = Modifier.width(4.dp))
|
||||||
|
Text("Limpar Histórico", color = Color.Red, fontSize = 12.sp)
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = onDismiss,
|
||||||
|
colors = ButtonDefaults.buttonColors(containerColor = BrandGreen)
|
||||||
|
) {
|
||||||
|
Text("Fechar", fontWeight = FontWeight.Bold)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -96,6 +96,19 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
initialValue = emptyList()
|
initialValue = emptyList()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
val appLogsState: StateFlow<List<com.example.data.model.AppLog>> = repository.allAppLogs
|
||||||
|
.stateIn(
|
||||||
|
scope = viewModelScope,
|
||||||
|
started = SharingStarted.WhileSubscribed(5000),
|
||||||
|
initialValue = emptyList()
|
||||||
|
)
|
||||||
|
|
||||||
|
fun clearAppLogs() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
repository.clearAppLogs()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val analyticsState: StateFlow<AnalyticsState> = combine(
|
val analyticsState: StateFlow<AnalyticsState> = combine(
|
||||||
repository.allActivities,
|
repository.allActivities,
|
||||||
repository.allHistory
|
repository.allHistory
|
||||||
|
|||||||
82
app/src/main/java/com/example/util/AppLogger.kt
Normal file
82
app/src/main/java/com/example/util/AppLogger.kt
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
package com.example.util
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import com.example.data.local.AppDatabase
|
||||||
|
import com.example.data.model.AppLog
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
class AppLogger private constructor(context: Context) {
|
||||||
|
|
||||||
|
private val db = AppDatabase.getDatabase(context)
|
||||||
|
private val appLogDao = db.appLogDao()
|
||||||
|
private val scope = CoroutineScope(Dispatchers.IO)
|
||||||
|
|
||||||
|
fun logError(tag: String, message: String, throwable: Throwable? = null) {
|
||||||
|
Log.e(tag, message, throwable)
|
||||||
|
val stackTrace = throwable?.stackTraceToString()
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
appLogDao.insertLog(
|
||||||
|
AppLog(
|
||||||
|
level = "ERROR",
|
||||||
|
tag = tag,
|
||||||
|
message = message,
|
||||||
|
stackTrace = stackTrace
|
||||||
|
)
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e("AppLogger", "Falha ao gravar log no Room", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun logWarning(tag: String, message: String) {
|
||||||
|
Log.w(tag, message)
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
appLogDao.insertLog(
|
||||||
|
AppLog(
|
||||||
|
level = "WARN",
|
||||||
|
tag = tag,
|
||||||
|
message = message
|
||||||
|
)
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e("AppLogger", "Falha ao gravar log no Room", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun logInfo(tag: String, message: String) {
|
||||||
|
Log.i(tag, message)
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
appLogDao.insertLog(
|
||||||
|
AppLog(
|
||||||
|
level = "INFO",
|
||||||
|
tag = tag,
|
||||||
|
message = message
|
||||||
|
)
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e("AppLogger", "Falha ao gravar log no Room", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
@Volatile
|
||||||
|
private var INSTANCE: AppLogger? = null
|
||||||
|
|
||||||
|
fun getInstance(context: Context): AppLogger {
|
||||||
|
return INSTANCE ?: synchronized(this) {
|
||||||
|
val instance = AppLogger(context.applicationContext)
|
||||||
|
INSTANCE = instance
|
||||||
|
instance
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -160,18 +160,22 @@ O aplicativo mapeia duas abas na planilha remota:
|
|||||||
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).
|
* 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`)
|
### 4.3. Integração com o Firebase Storage (`FirebaseStorageSyncService.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).
|
A gestão e armazenamento de arquivos de mídia (fotos das ordens de serviço) é centralizada no Firebase Storage através do serviço [`FirebaseStorageSyncService.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/FirebaseStorageSyncService.kt).
|
||||||
|
|
||||||
* **Chave de Acesso:** Service Account autenticada via `app/src/main/assets/drive-fotos-gestaoosparada.apikey.json` (`fotos-gestao-os@gestaoosparada.iam.gserviceaccount.com`).
|
* **Projeto e Bucket Firebase:** `gestao-parada-os.firebasestorage.app` (autenticado com Google Sign-in / Firebase SDK).
|
||||||
* **Pasta Destino na Nuvem:** Google Drive Folder ID `15WJIdzrykXWRSC5Xy4Ci5Cr7gq6FqMxK`.
|
* **Pasta Destino na Nuvem:** Diretórios organizados por OS (`photos/OS_{numeroOs}/`).
|
||||||
* **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`).
|
* **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 assíncrono para o Firebase Storage e obtém a URL pública/assinada de download (`downloadUrl`).
|
||||||
* **Regra de Exclusão (Soft Delete):** A exclusão de uma foto não remove o arquivo da pasta remota no Google Drive. A API do Drive executa uma requisição `PATCH` alterando o nome do arquivo para incluir o sufixo `_DELETED` (ex: `OS_1001_1722780000_DELETED.jpg`), enquanto a aplicação remove o vínculo do registro ativo no banco de dados local e na planilha.
|
* **Regra de Exclusão (Soft Delete):** A exclusão de uma foto executa um Soft Delete no Firebase Storage, renomeando o arquivo na mesma pasta para incluir o sufixo `_DELETED` (ex: `OS_1001_1722780000_DELETED.jpg`), mantendo a rastreabilidade enquanto atualiza os registros da aplicação.
|
||||||
|
|
||||||
* Guarda o log sequencial de alterações feitas por todos os inspetores.
|
### 4.4. Sistema de Registro e Histórico de Logs (`AppLogger.kt`)
|
||||||
* 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.
|
O aplicativo dispõe de um subsistema de auditoria e diagnóstico local para registro de falhas, erros de rede, problemas no Google Drive/Sheets e avisos de sincronização:
|
||||||
|
|
||||||
|
* **Tabela Room DB (`app_logs`):** Armazena os eventos com `timestamp`, `level` (`ERROR`, `WARN`, `INFO`), `tag`, `message` e `stackTrace`.
|
||||||
|
* **Utilitário `AppLogger.kt`:** Gerencia a gravação assíncrona thread-safe no banco local e emissão no Logcat.
|
||||||
|
* **Interface de Diagnóstico (`SettingsScreen.kt`):** Botão **"Histórico de Logs"** exibe os logs em um modal dialog envolvido por `SelectionContainer` do Jetpack Compose, permitindo a seleção e cópia de textos pelo usuário.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -111,8 +111,8 @@ Para expandir o aplicativo de sua estrutura atual de tela única ("Single Screen
|
|||||||
* *Recurso:* Console para forçar limpezas na base SQLite ou exportar backup do banco de dados local.
|
* *Recurso:* Console para forçar limpezas na base SQLite ou exportar backup do banco de dados local.
|
||||||
|
|
||||||
### 3.2. Proposta de Recursos Técnicos para Implementação Visando Complexidade
|
### 3.2. Proposta de Recursos Técnicos para Implementação Visando Complexidade
|
||||||
1. **Câmera Nativa com Upload Real (Google Drive):**
|
1. **Câmera Nativa com Upload Real (Firebase Storage):**
|
||||||
* Substituir o simulador de fotos estáticas (`mockPhotos`) por uma tela de captura utilizando **CameraX**.
|
* Substituir o simulador de fotos estáticas (`mockPhotos`) por captura real utilizando câmera nativa do Android.
|
||||||
* A imagem tirada deve ser armazenada localmente temporizada em cache, e enviada ao Google Drive por meio de uma API assíncrona. O link público direto gerado pelo Drive deve ser gravado no campo `fotoPath` no banco local e subido para a aba `history` do Sheets.
|
* A imagem tirada é armazenada localmente e enviada ao Firebase Storage (`photos/OS_{numeroOs}/`) por meio do SDK assíncrono. A URL de download obtida é gravada no campo `fotoPath` no banco local e subida para a aba `history` do Sheets.
|
||||||
2. **Sincronização em Segundo Plano Resiliente (WorkManager):**
|
2. **Sincronização em Segundo Plano Resiliente (WorkManager):**
|
||||||
* Substituir o clique manual em "Sincronizar" por um agendador automático em segundo plano que detecta conectividade Wi-Fi e envia logs pendentes sem travar ou exigir ação do inspetor.
|
* Substituir o clique manual em "Sincronizar" por um agendador automático em segundo plano que detecta conectividade Wi-Fi e envia logs pendentes sem travar ou exigir ação do inspetor.
|
||||||
|
|||||||
@@ -49,16 +49,16 @@ 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á real e funcionalmente implementada?
|
### A sincronização remota está real e funcionalmente implementada?
|
||||||
**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`.
|
**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 o **Firebase Storage SDK** (`FirebaseStorageSyncService.kt`) para upload de fotos das OSs no Firebase Storage.
|
||||||
|
|
||||||
### Como o fluxo de sincronização e envio de fotos funciona?
|
### Como o fluxo de sincronização e envio de fotos funciona?
|
||||||
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. **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.
|
||||||
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. **Upload para o Firebase Storage:** No momento do sync, o `MaintenanceRepository.kt` lê as fotos pendentes e aciona o `FirebaseStorageSyncService.kt`, que faz o upload seguro para o Firebase Storage na pasta `photos/OS_{numeroOs}/`.
|
||||||
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. **URL de Download e Sincronismo com Google Sheets:** O serviço obtém a `downloadUrl` do Firebase Storage, atualizando a Room DB e a aba `history` do Google Sheets.
|
||||||
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. **Soft Delete:** A exclusão de fotos no app executa um Soft Delete no Firebase Storage (renomeando a referência no mesmo diretório adicionando o sufixo `_DELETED`) e atualiza os registros locais.
|
||||||
|
|
||||||
### Arquivos responsáveis pela conexão e sincronização:
|
### Arquivos responsáveis pela conexão e sincronização:
|
||||||
* **`com.example.data.remote.GoogleDriveSyncService`:** Gerencia autenticação via Service Account, upload multipart de fotos e soft delete no Google Drive.
|
* **`com.example.data.remote.FirebaseStorageSyncService`:** Gerencia upload seguro de fotos e soft delete no Firebase Storage.
|
||||||
* **`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.remote.GoogleSheetsSyncService`:** Gerencia autenticação via Service Account e reconciliação bidirecional com a planilha central do Google Sheets.
|
||||||
* **`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.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`:** Gerencia os estados de sync na UI, disparos assíncronos e callbacks de gerenciamento de fotos.
|
* **`com.example.ui.viewmodel.MaintenanceViewModel`:** Gerencia os estados de sync na UI, disparos assíncronos e callbacks de gerenciamento de fotos.
|
||||||
|
|||||||
@@ -6,18 +6,18 @@ Abaixo está o levantamento detalhado de cada um desses elementos, com suas resp
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Captura, Anexo e Armazenamento de Fotos no Google Drive
|
## 1. Captura, Anexo e Armazenamento de Fotos no Firebase Storage
|
||||||
|
|
||||||
* **Status:** **IMPLEMENTADO (Produção)**
|
* **Status:** **IMPLEMENTADO (Produção)**
|
||||||
* **Arquivos Relacionados:**
|
* **Arquivos Relacionados:**
|
||||||
* [`GoogleDriveSyncService.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/GoogleDriveSyncService.kt)
|
* [`FirebaseStorageSyncService.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/FirebaseStorageSyncService.kt)
|
||||||
* [`MaintenanceDashboardScreen.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt)
|
* [`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)
|
* [`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:**
|
||||||
A simulação fotográfica foi completamente substituída por funcionalidade real de produção:
|
A simulação fotográfica foi completamente substituída por funcionalidade real de produção:
|
||||||
* **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()`.
|
* **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()`.
|
||||||
* **Google Drive Sync:** Envio de imagens para a pasta remota ID `15WJIdzrykXWRSC5Xy4Ci5Cr7gq6FqMxK` usando a Service Account `drive-fotos-gestaoosparada.apikey.json`.
|
* **Firebase Storage Sync:** Envio de imagens para o bucket do Firebase Storage sob o diretório `photos/OS_{numeroOs}/`.
|
||||||
* **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).
|
* **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` na referência do Firebase Storage).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -91,6 +91,8 @@ roborazzi-junit-rule = { group = "io.github.takahirom.roborazzi", name = "robora
|
|||||||
firebase-bom = { group = "com.google.firebase", name = "firebase-bom", version.ref = "firebaseBom" }
|
firebase-bom = { group = "com.google.firebase", name = "firebase-bom", version.ref = "firebaseBom" }
|
||||||
firebase-ai = { group = "com.google.firebase", name = "firebase-ai" }
|
firebase-ai = { group = "com.google.firebase", name = "firebase-ai" }
|
||||||
firebase-appcheck-recaptcha = { group = "com.google.firebase", name = "firebase-appcheck-recaptcha" }
|
firebase-appcheck-recaptcha = { group = "com.google.firebase", name = "firebase-appcheck-recaptcha" }
|
||||||
|
firebase-auth = { group = "com.google.firebase", name = "firebase-auth" }
|
||||||
|
firebase-storage = { group = "com.google.firebase", name = "firebase-storage" }
|
||||||
google-auth-library-oauth2-http = { group = "com.google.auth", name = "google-auth-library-oauth2-http", version.ref = "googleAuth" }
|
google-auth-library-oauth2-http = { group = "com.google.auth", name = "google-auth-library-oauth2-http", version.ref = "googleAuth" }
|
||||||
play-services-auth = { group = "com.google.android.gms", name = "play-services-auth", version.ref = "playServicesAuth" }
|
play-services-auth = { group = "com.google.android.gms", name = "play-services-auth", version.ref = "playServicesAuth" }
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user