Compare commits
4 Commits
57dff9f819
...
aaa5871292
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aaa5871292 | ||
|
|
8f557b0581 | ||
|
|
4fbebd08de | ||
|
|
09bfc92e1c |
9
.agents/AGENTS.md
Normal file
9
.agents/AGENTS.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# Diretrizes do Projeto - Gestão de Manutenção
|
||||
|
||||
## Leitura Obrigatória da Documentação
|
||||
- **Consulta Prévia**: Antes de planejar, pesquisar ou implementar qualquer alteração, a IA deve sempre consultar a documentação relevante contida no diretório [`documentacao/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao) (como [`arquitetura_do_sistema.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao/arquitetura/arquitetura_do_sistema.md), [`fluxo_de_dados_e_sincronizacao.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao/fluxo_de_dados_e_sincronizacao.md), [`recursos_simulados_e_truncados.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao/recursos_simulados_e_truncados.md)) e no [`README.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/README.md).
|
||||
- **Alinhamento Arquitetural**: Certifique-se de compreender os padrões arquiteturais offline-first, sincronização, modelos de dados e restrições descritas na documentação antes de propor ou alterar o código.
|
||||
|
||||
## Atualização Pós-Modificação
|
||||
- **Manutenção da Documentação**: Sempre que forem feitas modificações importantes no código (ex.: novas funcionalidades, refatoração de arquitetura, novos fluxos de sincronização, alterações em modelos de dados ou Room DAO/Database, adição de configurações), a IA deve obrigatoriamente atualizar os documentos correspondentes no diretório [`documentacao/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao) ou no [`README.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/README.md).
|
||||
- **Sincronia Código x Docs**: A documentação deve refletir com exatidão as mudanças realizadas para evitar inconsistências e garantir a evolução contínua do projeto.
|
||||
@@ -7,10 +7,11 @@ Aplicativo Android **offline-first** desenvolvido em Kotlin e Jetpack Compose pa
|
||||
## 📚 Documentação Técnica do Projeto
|
||||
|
||||
- **[Documentação de Fluxo de Dados, Salvamento e Sincronização](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao/fluxo_de_dados_e_sincronizacao.md)**:
|
||||
- Estrutura completa das 6 tabelas do banco de dados local Room (`maintenance_activities`, `os_findings`, `os_update_history`, `app_logs`, `sync_conflict_logs`, `user_access`).
|
||||
- Estrutura completa das 7 tabelas do banco de dados local Room (`maintenance_activities`, `os_findings`, `os_update_history`, `app_logs`, `sync_conflict_logs`, `user_access`, `app_config`).
|
||||
- Fluxo detalhado de salvamento de progresso e achados com tipo exclusivo `FOTO`.
|
||||
- Processo de compactação (<= 500KB) e upload para Firebase Storage.
|
||||
- Sincronização bidirecional com Google Sheets (abas `project`, `history`, `achados` e `usage_history`).
|
||||
- Sincronização bidirecional com Google Sheets (abas `project`, `history`, `achados`, `config` e `usage_history`).
|
||||
- Sincronização de links úteis da aba `config` para a Tela de Informações Importantes (posicionada à esquerda do Dashboard).
|
||||
- Rastreamento em tempo real do último acesso por dispositivo, e-mail de Google Sign-In e versão do sistema na aba `usage_history`.
|
||||
- Carregamento e download de fotos **sob demanda** (On-Demand Loading) para múltiplos celulares sem erros HTTP 403.
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Assignment
|
||||
import androidx.compose.material.icons.filled.Dashboard
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -25,6 +26,7 @@ import androidx.navigation.compose.rememberNavController
|
||||
import com.example.data.local.AppDatabase
|
||||
import com.example.data.repository.MaintenanceRepository
|
||||
import com.example.ui.screens.AnalyticsScreen
|
||||
import com.example.ui.screens.ImportantInfoScreen
|
||||
import com.example.ui.screens.MaintenanceDashboardScreen
|
||||
import com.example.ui.screens.SettingsScreen
|
||||
import com.example.ui.theme.BrandGreen
|
||||
@@ -57,6 +59,29 @@ class MainActivity : ComponentActivity() {
|
||||
containerColor = Color.White,
|
||||
modifier = Modifier.shadow(8.dp)
|
||||
) {
|
||||
// Tab 0: Informações Importantes (Página de Links)
|
||||
NavigationBarItem(
|
||||
selected = currentRoute == "info",
|
||||
onClick = {
|
||||
if (currentRoute != "info") {
|
||||
navController.navigate("info") {
|
||||
popUpTo(navController.graph.startDestinationId) { saveState = true }
|
||||
launchSingleTop = true
|
||||
restoreState = true
|
||||
}
|
||||
}
|
||||
},
|
||||
icon = { Icon(Icons.Default.Info, contentDescription = "Informações") },
|
||||
label = { Text("Informações", fontSize = 10.sp) },
|
||||
colors = NavigationBarItemDefaults.colors(
|
||||
selectedIconColor = BrandGreen,
|
||||
selectedTextColor = BrandGreen,
|
||||
unselectedIconColor = Color.Gray,
|
||||
unselectedTextColor = Color.Gray,
|
||||
indicatorColor = BrandLightGreen
|
||||
)
|
||||
)
|
||||
|
||||
// Tab 1: Dashboard (Stub)
|
||||
NavigationBarItem(
|
||||
selected = currentRoute == "dashboard",
|
||||
@@ -70,7 +95,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
},
|
||||
icon = { Icon(Icons.Default.Dashboard, contentDescription = "Dashboard") },
|
||||
label = { Text("Dashboard", fontSize = 11.sp) },
|
||||
label = { Text("Dashboard", fontSize = 10.sp) },
|
||||
colors = NavigationBarItemDefaults.colors(
|
||||
selectedIconColor = BrandGreen,
|
||||
selectedTextColor = BrandGreen,
|
||||
@@ -93,7 +118,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
},
|
||||
icon = { Icon(Icons.Default.Assignment, contentDescription = "Ordens") },
|
||||
label = { Text("Ordens", fontSize = 11.sp) },
|
||||
label = { Text("Ordens", fontSize = 10.sp) },
|
||||
colors = NavigationBarItemDefaults.colors(
|
||||
selectedIconColor = BrandGreen,
|
||||
selectedTextColor = BrandGreen,
|
||||
@@ -116,7 +141,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
},
|
||||
icon = { Icon(Icons.Default.Settings, contentDescription = "Configurações") },
|
||||
label = { Text("Configurações", fontSize = 11.sp) },
|
||||
label = { Text("Configurações", fontSize = 10.sp) },
|
||||
colors = NavigationBarItemDefaults.colors(
|
||||
selectedIconColor = BrandGreen,
|
||||
selectedTextColor = BrandGreen,
|
||||
@@ -134,6 +159,11 @@ class MainActivity : ComponentActivity() {
|
||||
startDestination = "ordens",
|
||||
modifier = Modifier.padding(bottom = innerPadding.calculateBottomPadding())
|
||||
) {
|
||||
composable("info") {
|
||||
ImportantInfoScreen(
|
||||
viewModel = viewModel
|
||||
)
|
||||
}
|
||||
composable("dashboard") {
|
||||
AnalyticsScreen(
|
||||
viewModel = viewModel,
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.content.Context
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import com.example.data.model.AppConfig
|
||||
import com.example.data.model.AppLog
|
||||
import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSFinding
|
||||
@@ -12,8 +13,8 @@ import com.example.data.model.SyncConflictLog
|
||||
import com.example.data.model.UserAccess
|
||||
|
||||
@Database(
|
||||
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class, AppLog::class, OSFinding::class],
|
||||
version = 8,
|
||||
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class, AppLog::class, OSFinding::class, AppConfig::class],
|
||||
version = 10,
|
||||
exportSchema = false
|
||||
)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
|
||||
@@ -5,6 +5,7 @@ import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Update
|
||||
import com.example.data.model.AppConfig
|
||||
import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSFinding
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
@@ -113,5 +114,40 @@ interface MaintenanceDao {
|
||||
|
||||
@Query("DELETE FROM os_findings")
|
||||
suspend fun clearAllFindings()
|
||||
|
||||
// Additional Synced and Epoch Purge Helpers
|
||||
@Query("SELECT * FROM os_update_history WHERE synced = 0")
|
||||
suspend fun getUnsyncedHistory(): List<OSUpdateHistory>
|
||||
|
||||
@Query("UPDATE os_update_history SET synced = 1 WHERE id IN (:ids)")
|
||||
suspend fun markHistorySynced(ids: List<Long>)
|
||||
|
||||
@Query("UPDATE os_update_history SET synced = 1 WHERE numeroOs = :numeroOs AND timestamp = :timestamp")
|
||||
suspend fun markHistorySyncedByOsAndTimestamp(numeroOs: String, timestamp: Long)
|
||||
|
||||
@Query("DELETE FROM os_update_history WHERE synced = 1 AND numeroOs NOT IN (:activeOsNumbers)")
|
||||
suspend fun deleteStaleSyncedHistory(activeOsNumbers: List<String>)
|
||||
|
||||
@Query("DELETE FROM os_update_history WHERE synced = 1")
|
||||
suspend fun deleteAllSyncedHistory()
|
||||
|
||||
@Query("DELETE FROM os_findings WHERE synced = 1 AND numeroOs NOT IN (:activeOsNumbers)")
|
||||
suspend fun deleteStaleSyncedFindings(activeOsNumbers: List<String>)
|
||||
|
||||
@Query("DELETE FROM os_findings WHERE synced = 1")
|
||||
suspend fun deleteAllSyncedFindings()
|
||||
|
||||
// AppConfig queries
|
||||
@Query("SELECT * FROM app_config")
|
||||
fun getAllConfigsFlow(): kotlinx.coroutines.flow.Flow<List<AppConfig>>
|
||||
|
||||
@Query("SELECT * FROM app_config")
|
||||
suspend fun getAllConfigs(): List<AppConfig>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertConfigs(configs: List<AppConfig>)
|
||||
|
||||
@Query("DELETE FROM app_config")
|
||||
suspend fun clearConfigs()
|
||||
}
|
||||
|
||||
|
||||
18
app/src/main/java/com/example/data/model/AppConfig.kt
Normal file
18
app/src/main/java/com/example/data/model/AppConfig.kt
Normal file
@@ -0,0 +1,18 @@
|
||||
package com.example.data.model
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
@Entity(tableName = "app_config")
|
||||
data class AppConfig(
|
||||
@PrimaryKey val key: String,
|
||||
val value: String,
|
||||
val description: String? = null
|
||||
)
|
||||
|
||||
data class ImportantLink(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val url: String,
|
||||
val description: String? = null
|
||||
)
|
||||
@@ -82,7 +82,13 @@ enum class ActivityStatus(val displayName: String) {
|
||||
CONCLUIDO("Concluído")
|
||||
}
|
||||
|
||||
@Entity(tableName = "os_update_history")
|
||||
@Entity(
|
||||
tableName = "os_update_history",
|
||||
indices = [
|
||||
Index("numeroOs"),
|
||||
Index("synced")
|
||||
]
|
||||
)
|
||||
data class OSUpdateHistory(
|
||||
@PrimaryKey(autoGenerate = true) val id: Long = 0,
|
||||
val numeroOs: String,
|
||||
@@ -92,7 +98,8 @@ data class OSUpdateHistory(
|
||||
val observacao: String? = null,
|
||||
val fotoPath: String? = null,
|
||||
val recurso: String,
|
||||
val emailEditor: String? = null
|
||||
val emailEditor: String? = null,
|
||||
val synced: Boolean = false
|
||||
)
|
||||
|
||||
data class GoogleUser(
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.example.data.remote
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.example.data.model.AppConfig
|
||||
import com.example.data.model.DeviceAccessInfo
|
||||
import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
@@ -758,13 +759,67 @@ class GoogleSheetsSyncService(
|
||||
observacao = obs,
|
||||
fotoPath = foto,
|
||||
recurso = resp,
|
||||
emailEditor = email.takeIf { it.isNotBlank() }
|
||||
emailEditor = email.takeIf { it.isNotBlank() },
|
||||
synced = true
|
||||
)
|
||||
)
|
||||
}
|
||||
return historyList
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads database_epoch from 'config' tab (cell B2 or key 'database_epoch').
|
||||
* Defaults to 1 if tab or value is missing/invalid.
|
||||
*/
|
||||
fun fetchDatabaseEpoch(): Int {
|
||||
return try {
|
||||
val rows = fetchValues("config!A:B")
|
||||
if (rows.isEmpty()) return 1
|
||||
for (row in rows) {
|
||||
if (row.isNotEmpty() && row[0].trim().lowercase() == "database_epoch") {
|
||||
if (row.size > 1) {
|
||||
val epochVal = row[1].trim().toIntOrNull()
|
||||
if (epochVal != null && epochVal > 0) {
|
||||
return epochVal
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fallback: check row 2 col 2 (B2)
|
||||
if (rows.size >= 2 && rows[1].size >= 2) {
|
||||
rows[1][1].trim().toIntOrNull() ?: 1
|
||||
} else {
|
||||
1
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.d(tag, "Tab 'config' não encontrada ou sem chave 'database_epoch'. Usando epoch padrão = 1.")
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads all key-value-description configuration rows from 'config' tab (config!A:C).
|
||||
*/
|
||||
fun fetchRemoteConfigs(): List<AppConfig> {
|
||||
return try {
|
||||
val rows = fetchValues("config!A:C")
|
||||
if (rows.isEmpty()) return emptyList()
|
||||
val result = mutableListOf<AppConfig>()
|
||||
for (row in rows) {
|
||||
if (row.isEmpty()) continue
|
||||
val key = row[0].trim()
|
||||
if (key.isEmpty() || key.lowercase() == "chave" || key.lowercase() == "key") continue
|
||||
val value = if (row.size > 1) row[1].trim() else ""
|
||||
val desc = if (row.size > 2 && row[2].trim().isNotBlank()) row[2].trim() else null
|
||||
result.add(AppConfig(key = key, value = value, description = desc))
|
||||
}
|
||||
result
|
||||
} catch (e: Exception) {
|
||||
Log.e(tag, "Erro ao carregar configurações da aba 'config'", e)
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stubs out direct activities editing since 'project' is now read-only.
|
||||
*/
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.example.data.model.OSFinding
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
import com.example.data.model.GoogleUser
|
||||
import com.example.data.model.SyncConflictLog
|
||||
import com.example.data.model.AppConfig
|
||||
import com.example.data.model.UserAccess
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
@@ -39,6 +40,8 @@ class MaintenanceRepository(
|
||||
|
||||
val allActivities: Flow<List<MaintenanceActivity>> = dao.getAllActivities()
|
||||
|
||||
val allConfigs: Flow<List<AppConfig>> = dao.getAllConfigsFlow()
|
||||
|
||||
val allHistory: Flow<List<OSUpdateHistory>> = dao.getAllHistoryFlow()
|
||||
|
||||
fun getActivityByOs(numeroOs: String): Flow<MaintenanceActivity?> = dao.getActivityByOs(numeroOs)
|
||||
@@ -468,6 +471,30 @@ class MaintenanceRepository(
|
||||
android.util.Log.e("MaintenanceRepository", "Falha ao carregar lista de acessos da planilha", e)
|
||||
}
|
||||
|
||||
// 0.01 Fetch remote configs and store locally
|
||||
try {
|
||||
val remoteConfigs = sheetsSyncService.fetchRemoteConfigs()
|
||||
if (remoteConfigs.isNotEmpty()) {
|
||||
dao.insertConfigs(remoteConfigs)
|
||||
android.util.Log.d("MaintenanceRepository", "Sincronizadas ${remoteConfigs.size} configurações da planilha.")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("MaintenanceRepository", "Falha ao carregar configurações da planilha", e)
|
||||
}
|
||||
|
||||
// 0.1 Check Remote Database Epoch for reset/cleanup signals
|
||||
val remoteEpoch = try { sheetsSyncService.fetchDatabaseEpoch() } catch (e: Exception) { 1 }
|
||||
val prefs = context.getSharedPreferences("google_auth_prefs", Context.MODE_PRIVATE)
|
||||
val localEpoch = prefs.getInt("database_epoch", 0)
|
||||
|
||||
if (remoteEpoch > localEpoch) {
|
||||
android.util.Log.d("MaintenanceRepository", "Database epoch mudou de $localEpoch para $remoteEpoch. Purgando todo o histórico e achados sincronizados locais para substituir completamente pela nova base remota...")
|
||||
// Completely clear previously synced history and findings so local database is replaced by the new remote database
|
||||
dao.deleteAllSyncedHistory()
|
||||
dao.deleteAllSyncedFindings()
|
||||
prefs.edit().putInt("database_epoch", remoteEpoch).apply()
|
||||
}
|
||||
|
||||
// 1. Fetch remote OS definitions from the "project" sheet
|
||||
val (remoteActivities, _) = sheetsSyncService.fetchRemoteActivities()
|
||||
|
||||
@@ -511,9 +538,9 @@ class MaintenanceRepository(
|
||||
val missingLocalHistory = remoteHistory.filter { "${it.numeroOs}_${it.timestamp}" !in localHistoryKeys }
|
||||
if (missingLocalHistory.isNotEmpty()) {
|
||||
for (hist in missingLocalHistory) {
|
||||
dao.insertHistory(hist)
|
||||
dao.insertHistory(hist.copy(synced = true))
|
||||
}
|
||||
android.util.Log.d("MaintenanceRepository", "Inserted ${missingLocalHistory.size} missing history logs locally.")
|
||||
android.util.Log.d("MaintenanceRepository", "Inserted ${missingLocalHistory.size} missing history logs locally as synced.")
|
||||
}
|
||||
|
||||
// 6. For each remote activity, determine its current state based on findings (achados) and history log
|
||||
@@ -574,7 +601,7 @@ class MaintenanceRepository(
|
||||
}
|
||||
|
||||
// 8. Identify and resolve sync conflicts (LWW)
|
||||
val unuploadedLocalLogs = localHistory.filter { "${it.numeroOs}_${it.timestamp}" !in remoteHistoryKeys }
|
||||
val unuploadedLocalLogs = localHistory.filter { !it.synced && "${it.numeroOs}_${it.timestamp}" !in remoteHistoryKeys }
|
||||
val ossWithUnuploadedLogs = unuploadedLocalLogs.map { it.numeroOs }.toSet()
|
||||
|
||||
val newRemoteLogs = remoteHistory.filter { "${it.numeroOs}_${it.timestamp}" !in localHistoryKeys }
|
||||
@@ -621,11 +648,18 @@ class MaintenanceRepository(
|
||||
android.util.Log.d("MaintenanceRepository", "Inserted ${conflictLogsToInsert.size} resolved conflict logs.")
|
||||
}
|
||||
|
||||
// 9. Upload any local history logs that are not on Google Sheets yet
|
||||
val historyToUpload = localHistory.filter { "${it.numeroOs}_${it.timestamp}" !in remoteHistoryKeys }
|
||||
// 9. Upload any local history logs that are not on Google Sheets yet (only unsynced)
|
||||
val historyToUpload = localHistory.filter { !it.synced && "${it.numeroOs}_${it.timestamp}" !in remoteHistoryKeys }
|
||||
if (historyToUpload.isNotEmpty()) {
|
||||
sheetsSyncService.pushHistoryToSheet(historyToUpload)
|
||||
android.util.Log.d("MaintenanceRepository", "Uploaded ${historyToUpload.size} new local history logs to Google Sheet.")
|
||||
val uploadedIds = historyToUpload.map { it.id }.filter { it != 0L }
|
||||
if (uploadedIds.isNotEmpty()) {
|
||||
dao.markHistorySynced(uploadedIds)
|
||||
}
|
||||
for (h in historyToUpload) {
|
||||
dao.markHistorySyncedByOsAndTimestamp(h.numeroOs, h.timestamp)
|
||||
}
|
||||
android.util.Log.d("MaintenanceRepository", "Uploaded ${historyToUpload.size} new local history logs to Google Sheet and marked as synced.")
|
||||
}
|
||||
|
||||
// 10. Sync 'achados' sheet with local OSFinding database safely preserving local/uploaded photo paths
|
||||
@@ -1061,6 +1095,35 @@ class MaintenanceRepository(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun seedDefaultConfigsIfEmpty() = withContext(Dispatchers.IO) {
|
||||
val existing = dao.getAllConfigs()
|
||||
if (existing.isEmpty()) {
|
||||
val defaults = listOf(
|
||||
com.example.data.model.AppConfig("database_epoch", "3", "Versão da base de dados. Incremente em +1 ao alterar/limpar a planilha"),
|
||||
com.example.data.model.AppConfig("Link1", "https://forms.office.com/Pages/ResponsePage.aspx?id=IYw2V8-4z0K9C0Ps1LxirnRboL6yMAxJn4T7PLeH0KtURjNLNlNJQTdHU0JMVlVNMlJISlNTSFJFRyQlQCN0PWcu&origin=APPgestaoos", "Link para ser exibido na tela de informações"),
|
||||
com.example.data.model.AppConfig("DescricaoLink1", "Link do RDS (Relato de Segurança)", "Link do RDS (Relato de Segurança)"),
|
||||
com.example.data.model.AppConfig("Link2", "https://exemple.com", "Link de informações de privacidade do app"),
|
||||
com.example.data.model.AppConfig("DescricaoLink2", "Informações de privacidade do APP", "Informações de privacidade"),
|
||||
com.example.data.model.AppConfig("Link3", "https://exemple.com", null),
|
||||
com.example.data.model.AppConfig("DescricaoLink3", "Termos de uso deste APP", "Termos de uso do APP")
|
||||
)
|
||||
dao.insertConfigs(defaults)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun refreshConfigs(): List<com.example.data.model.AppConfig> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val configs = sheetsSyncService.fetchRemoteConfigs()
|
||||
if (configs.isNotEmpty()) {
|
||||
dao.insertConfigs(configs)
|
||||
}
|
||||
configs
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("MaintenanceRepository", "Erro ao atualizar configs", e)
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sealed interface SyncResult {
|
||||
|
||||
289
app/src/main/java/com/example/ui/screens/ImportantInfoScreen.kt
Normal file
289
app/src/main/java/com/example/ui/screens/ImportantInfoScreen.kt
Normal file
@@ -0,0 +1,289 @@
|
||||
package com.example.ui.screens
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowForward
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.Lock
|
||||
import androidx.compose.material.icons.filled.OpenInNew
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.Security
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.example.data.model.ImportantLink
|
||||
import com.example.ui.theme.BrandBlack
|
||||
import com.example.ui.theme.BrandGreen
|
||||
import com.example.ui.theme.BrandLightGreen
|
||||
import com.example.ui.theme.LightGrey
|
||||
import com.example.ui.viewmodel.MaintenanceViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ImportantInfoScreen(
|
||||
viewModel: MaintenanceViewModel,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val links by viewModel.importantLinks.collectAsStateWithLifecycle()
|
||||
val isNetworkConnected by viewModel.isNetworkConnected.collectAsStateWithLifecycle(initialValue = true)
|
||||
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
|
||||
|
||||
val openUrl: (String) -> Unit = { urlString ->
|
||||
try {
|
||||
val formattedUrl = if (!urlString.startsWith("http://") && !urlString.startsWith("https://")) {
|
||||
"https://$urlString"
|
||||
} else urlString
|
||||
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(formattedUrl))
|
||||
context.startActivity(intent)
|
||||
} catch (e: Exception) {
|
||||
Toast.makeText(context, "Não foi possível abrir o link: ${e.message}", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = {
|
||||
Column {
|
||||
Text(
|
||||
text = "Informações Importantes",
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 20.sp,
|
||||
color = BrandBlack
|
||||
)
|
||||
Text(
|
||||
text = "Links da aba config da planilha online",
|
||||
fontSize = 12.sp,
|
||||
color = Color.Gray
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (!isSyncing) {
|
||||
viewModel.syncNow()
|
||||
Toast.makeText(context, "Atualizando informações da planilha...", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
) {
|
||||
if (isSyncing) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(20.dp),
|
||||
color = BrandGreen,
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
} else {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Refresh,
|
||||
contentDescription = "Atualizar Links",
|
||||
tint = BrandGreen
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.White)
|
||||
)
|
||||
},
|
||||
modifier = modifier
|
||||
) { innerPadding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(innerPadding)
|
||||
.background(LightGrey)
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp)
|
||||
) {
|
||||
// Status Card
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(bottom = 16.dp),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.background(BrandLightGreen),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Info,
|
||||
contentDescription = "Informações",
|
||||
tint = BrandGreen
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "Central de Links do Sistema",
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = BrandBlack
|
||||
)
|
||||
Spacer(modifier = Modifier.height(2.dp))
|
||||
Text(
|
||||
text = if (isNetworkConnected) "Sincronizado com a planilha online (Aba config)" else "Modo Offline (Links armazenados localmente)",
|
||||
fontSize = 12.sp,
|
||||
color = if (isNetworkConnected) BrandGreen else Color(0xFFD97706)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Links List Title
|
||||
Text(
|
||||
text = "LINKS ÚTEIS E DOCUMENTOS",
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = Color.Gray,
|
||||
modifier = Modifier.padding(start = 4.dp, bottom = 8.dp)
|
||||
)
|
||||
|
||||
// Links List
|
||||
LazyColumn(
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
items(links, key = { it.id }) { linkItem ->
|
||||
ImportantLinkCard(
|
||||
link = linkItem,
|
||||
onOpenUrl = { openUrl(linkItem.url) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ImportantLinkCard(
|
||||
link: ImportantLink,
|
||||
onOpenUrl: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val (icon, badgeColor) = when (link.id) {
|
||||
"1" -> Icons.Default.Security to Color(0xFF0284C7)
|
||||
"2" -> Icons.Default.Lock to Color(0xFF7C3AED)
|
||||
"3" -> Icons.Default.Description to Color(0xFF059669)
|
||||
else -> Icons.Default.OpenInNew to BrandGreen
|
||||
}
|
||||
|
||||
Card(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onOpenUrl() },
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(48.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(badgeColor.copy(alpha = 0.1f)),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = link.title,
|
||||
tint = badgeColor,
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(14.dp))
|
||||
|
||||
Column(
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text(
|
||||
text = link.title,
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = BrandBlack,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
|
||||
if (!link.description.isNullOrBlank()) {
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = link.description,
|
||||
fontSize = 12.sp,
|
||||
color = Color.Gray,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(6.dp))
|
||||
|
||||
Text(
|
||||
text = link.url,
|
||||
fontSize = 11.sp,
|
||||
color = badgeColor,
|
||||
fontWeight = FontWeight.Medium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
|
||||
IconButton(
|
||||
onClick = onOpenUrl,
|
||||
modifier = Modifier
|
||||
.size(36.dp)
|
||||
.clip(CircleShape)
|
||||
.background(LightGrey)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.OpenInNew,
|
||||
contentDescription = "Abrir Link",
|
||||
tint = BrandBlack,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,79 @@ import kotlinx.coroutines.launch
|
||||
|
||||
class MaintenanceViewModel(private val repository: MaintenanceRepository) : ViewModel() {
|
||||
|
||||
init {
|
||||
viewModelScope.launch {
|
||||
repository.seedDefaultConfigsIfEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
val importantLinks: StateFlow<List<com.example.data.model.ImportantLink>> = repository.allConfigs
|
||||
.map { configs -> parseImportantLinks(configs) }
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000),
|
||||
initialValue = getDefaultImportantLinks()
|
||||
)
|
||||
|
||||
private fun parseImportantLinks(configs: List<com.example.data.model.AppConfig>): List<com.example.data.model.ImportantLink> {
|
||||
if (configs.isEmpty()) return getDefaultImportantLinks()
|
||||
val configMap = configs.associateBy { it.key }
|
||||
val defaultLinks = getDefaultImportantLinks()
|
||||
val result = mutableListOf<com.example.data.model.ImportantLink>()
|
||||
|
||||
for (i in 1..3) {
|
||||
val linkKey = "Link$i"
|
||||
val descKey = "DescricaoLink$i"
|
||||
val defaultItem = defaultLinks.getOrNull(i - 1)
|
||||
|
||||
val url = configMap[linkKey]?.value?.trim()?.takeIf { it.isNotBlank() }
|
||||
?: defaultItem?.url
|
||||
?: "https://exemple.com"
|
||||
|
||||
val title = configMap[descKey]?.value?.trim()?.takeIf { it.isNotBlank() }
|
||||
?: configMap[descKey]?.description?.trim()?.takeIf { it.isNotBlank() }
|
||||
?: defaultItem?.title
|
||||
?: "Link $i"
|
||||
|
||||
val description = configMap[linkKey]?.description?.trim()?.takeIf { it.isNotBlank() }
|
||||
?: configMap[descKey]?.description?.trim()?.takeIf { it.isNotBlank() }
|
||||
?: defaultItem?.description
|
||||
|
||||
result.add(
|
||||
com.example.data.model.ImportantLink(
|
||||
id = i.toString(),
|
||||
title = title,
|
||||
url = url,
|
||||
description = description
|
||||
)
|
||||
)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun getDefaultImportantLinks(): List<com.example.data.model.ImportantLink> {
|
||||
return listOf(
|
||||
com.example.data.model.ImportantLink(
|
||||
id = "1",
|
||||
title = "Link do RDS (Relato de Segurança)",
|
||||
url = "https://forms.office.com/Pages/ResponsePage.aspx?id=IYw2V8-4z0K9C0Ps1LxirnRboL6yMAxJn4T7PLeH0KtURjNLNlNJQTdHU0JMVlVNMlJISlNTSFJFRyQlQCN0PWcu&origin=APPgestaoos",
|
||||
description = "Link para ser exibido na tela de informações"
|
||||
),
|
||||
com.example.data.model.ImportantLink(
|
||||
id = "2",
|
||||
title = "Informações de privacidade do APP",
|
||||
url = "https://exemple.com",
|
||||
description = "Informações de privacidade"
|
||||
),
|
||||
com.example.data.model.ImportantLink(
|
||||
id = "3",
|
||||
title = "Termos de uso deste APP",
|
||||
url = "https://exemple.com",
|
||||
description = "Termos de uso do APP"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
// Filtering inputs
|
||||
private val _selectedSetor = MutableStateFlow("Todos")
|
||||
val selectedSetor = _selectedSetor.asStateFlow()
|
||||
@@ -68,6 +141,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
||||
// UI Operation States
|
||||
private val _isSyncing = MutableStateFlow(false)
|
||||
val isSyncing = _isSyncing.asStateFlow()
|
||||
val isNetworkConnected = repository.isNetworkConnected
|
||||
|
||||
private val _syncStatusMessage = MutableStateFlow<String?>(null)
|
||||
val syncStatusMessage = _syncStatusMessage.asStateFlow()
|
||||
|
||||
38
app/src/test/java/com/example/AppConfigTest.kt
Normal file
38
app/src/test/java/com/example/AppConfigTest.kt
Normal file
@@ -0,0 +1,38 @@
|
||||
package com.example
|
||||
|
||||
import com.example.data.model.AppConfig
|
||||
import com.example.data.model.ImportantLink
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Test
|
||||
|
||||
class AppConfigTest {
|
||||
|
||||
@Test
|
||||
fun testAppConfigCreation() {
|
||||
val config = AppConfig(
|
||||
key = "Link1",
|
||||
value = "https://forms.office.com/test",
|
||||
description = "Link do RDS"
|
||||
)
|
||||
|
||||
assertEquals("Link1", config.key)
|
||||
assertEquals("https://forms.office.com/test", config.value)
|
||||
assertEquals("Link do RDS", config.description)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testImportantLinkModel() {
|
||||
val link = ImportantLink(
|
||||
id = "1",
|
||||
title = "Link do RDS (Relato de Segurança)",
|
||||
url = "https://forms.office.com/test",
|
||||
description = "Link para ser exibido na tela de informações"
|
||||
)
|
||||
|
||||
assertEquals("1", link.id)
|
||||
assertEquals("Link do RDS (Relato de Segurança)", link.title)
|
||||
assertEquals("https://forms.office.com/test", link.url)
|
||||
assertEquals("Link para ser exibido na tela de informações", link.description)
|
||||
}
|
||||
}
|
||||
@@ -578,4 +578,99 @@ class ExampleRobolectricTest {
|
||||
kotlinx.coroutines.Dispatchers.resetMain()
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
@Test
|
||||
fun `test database epoch reconciliation and synced flag purge rules`() {
|
||||
val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher()
|
||||
kotlinx.coroutines.Dispatchers.setMain(testDispatcher)
|
||||
try {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||
.allowMainThreadQueries()
|
||||
.setQueryExecutor { it.run() }
|
||||
.setTransactionExecutor { it.run() }
|
||||
.build()
|
||||
val dao = db.maintenanceDao()
|
||||
|
||||
kotlinx.coroutines.runBlocking {
|
||||
dao.clearAllActivities()
|
||||
dao.clearAllHistory()
|
||||
dao.clearAllFindings()
|
||||
|
||||
// 1. Create active activity OS-100 and OS-200
|
||||
val act1 = com.example.data.model.MaintenanceActivity(
|
||||
numeroOs = "OS-100", descricao = "Tarefa 100", setor = "Mecânica", equipe = "Mecânica",
|
||||
recurso = "Eng 1", dataInicio = "01/08/2026", dataFim = "02/08/2026", percentualExecucao = 50, synced = true
|
||||
)
|
||||
dao.insertActivity(act1)
|
||||
|
||||
// 2. Insert synced history for OS-999 (which is stale/removed remotely)
|
||||
val staleSyncedHistory = com.example.data.model.OSUpdateHistory(
|
||||
numeroOs = "OS-999", timestamp = 1000L, percentualAnterior = 0, percentualNovo = 50,
|
||||
observacao = "Histórico antigo sincronizado", recurso = "Eng 1", synced = true
|
||||
)
|
||||
dao.insertHistory(staleSyncedHistory)
|
||||
|
||||
// 3. Insert unsynced history for OS-100 (pending offline change created by user)
|
||||
val offlinePendingHistory = com.example.data.model.OSUpdateHistory(
|
||||
numeroOs = "OS-100", timestamp = 2000L, percentualAnterior = 50, percentualNovo = 100,
|
||||
observacao = "Histórico novo offline", recurso = "Eng 1", synced = false
|
||||
)
|
||||
dao.insertHistory(offlinePendingHistory)
|
||||
|
||||
// 4. Insert synced finding for OS-999 (stale) and unsynced finding for OS-100 (pending)
|
||||
val staleSyncedFinding = com.example.data.model.OSFinding(
|
||||
id = "finding-stale", numeroOs = "OS-999", tipo = "OBS", descricao = "Achado antigo",
|
||||
timestamp = 1000L, responsavel = "Eng 1", synced = true
|
||||
)
|
||||
val offlinePendingFinding = com.example.data.model.OSFinding(
|
||||
id = "finding-offline", numeroOs = "OS-100", tipo = "OBS", descricao = "Achado novo offline",
|
||||
timestamp = 2000L, responsavel = "Eng 1", synced = false
|
||||
)
|
||||
dao.insertFinding(staleSyncedFinding)
|
||||
dao.insertFinding(offlinePendingFinding)
|
||||
|
||||
// Verify initial state before epoch purge
|
||||
assertEquals(2, dao.getAllHistoryList().size)
|
||||
assertEquals(2, dao.getAllFindingsList().size)
|
||||
assertEquals(1, dao.getUnsyncedHistory().size)
|
||||
|
||||
// 5. Execute Epoch purge (deleteAllSyncedHistory and deleteAllSyncedFindings)
|
||||
dao.deleteAllSyncedHistory()
|
||||
dao.deleteAllSyncedFindings()
|
||||
|
||||
// 6. Verify that ALL synced entries (OS-999) were purged, while unsynced entries (OS-100) were preserved
|
||||
val historyAfterPurge = dao.getAllHistoryList()
|
||||
assertEquals(1, historyAfterPurge.size)
|
||||
assertEquals("OS-100", historyAfterPurge.first().numeroOs)
|
||||
assertEquals(false, historyAfterPurge.first().synced)
|
||||
|
||||
val findingsAfterPurge = dao.getAllFindingsList()
|
||||
assertEquals(1, findingsAfterPurge.size)
|
||||
assertEquals("OS-100", findingsAfterPurge.first().numeroOs)
|
||||
assertEquals(false, findingsAfterPurge.first().synced)
|
||||
|
||||
// 7. Test marking history as synced
|
||||
val unsyncedHist = historyAfterPurge.first()
|
||||
dao.markHistorySyncedByOsAndTimestamp(unsyncedHist.numeroOs, unsyncedHist.timestamp)
|
||||
|
||||
val historyFinal = dao.getAllHistoryList()
|
||||
assertEquals(true, historyFinal.first().synced)
|
||||
assertEquals(0, dao.getUnsyncedHistory().size)
|
||||
}
|
||||
db.close()
|
||||
} finally {
|
||||
kotlinx.coroutines.Dispatchers.resetMain()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `test fetchDatabaseEpoch graceful fallback`() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val service = GoogleSheetsSyncService(context)
|
||||
val epoch = service.fetchDatabaseEpoch()
|
||||
assertTrue("Epoch default should be >= 1, got $epoch", epoch >= 1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -171,6 +171,15 @@ Gerencia o nível de acesso e permissões das contas de usuário autenticadas no
|
||||
| `nivelAcesso` | `String` | - | Permissão: `"ADMIN"`, `"ENCO"` ou `"VISUALIZADOR"`. |
|
||||
| `lastUpdated` | `Long` | - | Timestamp da atualização de acesso. |
|
||||
|
||||
### 3.7. Entidade: `AppConfig` (Tabela: `app_config`)
|
||||
Armazena configurações globais, links úteis e versão da base de dados (`database_epoch`) lidos da aba `config` da planilha online Google Sheets.
|
||||
|
||||
| Campo | Tipo | Chave | Descrição |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `key` | `String` | Primária | Identificador único da chave (ex: `Link1`, `DescricaoLink1`, `database_epoch`). |
|
||||
| `value` | `String` | - | Valor da chave de configuração (ex: URL ou texto). |
|
||||
| `description` | `String?` | - | Descrição complementar da chave de configuração. |
|
||||
|
||||
---
|
||||
|
||||
## 4. Integração Remota (Google Sheets API v4)
|
||||
|
||||
@@ -109,7 +109,14 @@ Para expandir o aplicativo de sua estrutura atual de tela única ("Single Screen
|
||||
* *Recurso:* Formulário para alterar dinamicamente o ID da Planilha Google Sheets ativa.
|
||||
* *Recurso:* Status de cota e conexão da API do Google, permitindo testar credenciais em tempo real.
|
||||
* *Recurso:* Console para forçar limpezas na base SQLite ou exportar backup do banco de dados local.
|
||||
5. **Módulo de Simulação de Data do Sistema (`SettingsScreen` / `DateSimulationSection`):**
|
||||
5. **Tela de Informações Importantes (`ImportantInfoScreen`):**
|
||||
* *Navegação:* Acessível via barra inferior (`NavigationBar`), posicionada à **esquerda** do botão Dashboard (**Informações | Dashboard | Ordens | Configurações**).
|
||||
* *Recurso:* Exibe 3 links dinâmicos sincronizados da aba `config` da planilha online (Google Sheets):
|
||||
1. **Link1**: RDS (Relato de Segurança)
|
||||
2. **Link2**: Informações de Privacidade do APP
|
||||
3. **Link3**: Termos de Uso do APP
|
||||
* *Recurso:* Possui modo offline-first (exibindo os links armazenados no banco local Room), botão de atualização manual dos links da planilha e acionamento direto via navegador web nativo.
|
||||
6. **Módulo de Simulação de Data do Sistema (`SettingsScreen` / `DateSimulationSection`):**
|
||||
* *Recurso:* Painel com controle de permissão por **Nível Total**. Permite escolher a data simulada (Material3 `DatePickerDialog`) e o modo (*Somente Visualização* vs *Edição do Progresso das Ordens*).
|
||||
* *Recurso:* Possui encerramento automático após **15 minutos** de simulação contínua e exibe banner de alerta no topo do Dashboard indicando a data simulada, modo ativo e ação de desativação rápida.
|
||||
|
||||
|
||||
@@ -140,9 +140,20 @@ Armazena o nível de permissão associado aos e-mails cadastrados.
|
||||
|
||||
| Campo | Tipo | Chave | Descrição |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **`email`** | `String` | Primária | E-mail do usuário da conta Google. |
|
||||
| **`nivelAcesso`** | `String` | - | Permissão: `"ADMIN"`, `"ENCO"` (Encarregado) ou `"VISUALIZADOR"`. |
|
||||
| **`lastUpdated`** | `Long` | - | Data de atualização da regra. |
|
||||
| **`email`** | `String` | Primária | E-mail da conta Google. |
|
||||
| **`nivelAcesso`** | `String` | - | Nível de acesso: `"ADMIN"`, `"ENCO"` ou `"VISUALIZADOR"`. |
|
||||
| **`lastUpdated`** | `Long` | - | Timestamp da atualização de acesso. |
|
||||
|
||||
---
|
||||
|
||||
### 2.7. Tabela: `app_config` (Configurações e Links Úteis)
|
||||
Armazena as configurações dinâmicas e links sincronizados da aba `config` da planilha online Google Sheets.
|
||||
|
||||
| Campo | Tipo | Chave | Descrição / Regras |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **`key`** | `String` | Primária | Chave de configuração (ex: `Link1`, `DescricaoLink1`, `database_epoch`). |
|
||||
| **`value`** | `String` | - | Valor associado à chave (ex: URL ou versão). |
|
||||
| **`description`** | `String?` | - | Descrição informativa da chave lida da coluna C (`descricao`). |
|
||||
|
||||
---
|
||||
|
||||
|
||||
Reference in New Issue
Block a user