feat: implement synchronization and UI display for application configuration links via new AppConfig entity
This commit is contained in:
@@ -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 = 9,
|
||||
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
|
||||
@@ -135,5 +136,18 @@ interface MaintenanceDao {
|
||||
|
||||
@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
|
||||
)
|
||||
@@ -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
|
||||
@@ -796,6 +797,29 @@ class GoogleSheetsSyncService(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,17 @@ 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)
|
||||
@@ -1081,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)
|
||||
}
|
||||
}
|
||||
@@ -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