Compare commits
4 Commits
730fb15ff3
...
3cde33d558
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3cde33d558 | ||
|
|
c6a11d3fb0 | ||
|
|
8e063f6c64 | ||
|
|
1f468880f9 |
@@ -8,3 +8,8 @@ GEMINI_API_KEY=MY_GEMINI_API_KEY
|
|||||||
# Paste the entire content of your Service Account credentials .json file here as a single-line string,
|
# Paste the entire content of your Service Account credentials .json file here as a single-line string,
|
||||||
# or add it through the Secrets panel in AI Studio.
|
# or add it through the Secrets panel in AI Studio.
|
||||||
SHEETS_CREDENTIALS_JSON=SHEETS_CREDENTIALS_JSON
|
SHEETS_CREDENTIALS_JSON=SHEETS_CREDENTIALS_JSON
|
||||||
|
|
||||||
|
# ADMIN_CREDENTIALS_JSON: Optional for Google Cloud administrative metrics (Latency & Quota monitoring).
|
||||||
|
# Paste the content of your administrative Service Account credentials JSON here.
|
||||||
|
ADMIN_CREDENTIALS_JSON=ADMIN_CREDENTIALS_JSON
|
||||||
|
|
||||||
|
|||||||
@@ -107,7 +107,7 @@ dependencies {
|
|||||||
implementation(libs.androidx.lifecycle.runtime.compose)
|
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||||
// implementation(libs.androidx.navigation.compose)
|
implementation(libs.androidx.navigation.compose)
|
||||||
implementation(libs.androidx.room.ktx)
|
implementation(libs.androidx.room.ktx)
|
||||||
implementation(libs.androidx.room.runtime)
|
implementation(libs.androidx.room.runtime)
|
||||||
implementation(libs.coil.compose)
|
implementation(libs.coil.compose)
|
||||||
|
|||||||
@@ -6,12 +6,29 @@ import androidx.activity.compose.setContent
|
|||||||
import androidx.activity.enableEdgeToEdge
|
import androidx.activity.enableEdgeToEdge
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.material3.Scaffold
|
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.Settings
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.shadow
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
import androidx.lifecycle.ViewModelProvider
|
import androidx.lifecycle.ViewModelProvider
|
||||||
|
import androidx.navigation.compose.NavHost
|
||||||
|
import androidx.navigation.compose.composable
|
||||||
|
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||||
|
import androidx.navigation.compose.rememberNavController
|
||||||
import com.example.data.local.AppDatabase
|
import com.example.data.local.AppDatabase
|
||||||
import com.example.data.repository.MaintenanceRepository
|
import com.example.data.repository.MaintenanceRepository
|
||||||
|
import com.example.ui.screens.DashboardStubScreen
|
||||||
import com.example.ui.screens.MaintenanceDashboardScreen
|
import com.example.ui.screens.MaintenanceDashboardScreen
|
||||||
|
import com.example.ui.screens.SettingsScreen
|
||||||
|
import com.example.ui.theme.CargillGreen
|
||||||
|
import com.example.ui.theme.CargillLightGreen
|
||||||
import com.example.ui.theme.MyApplicationTheme
|
import com.example.ui.theme.MyApplicationTheme
|
||||||
import com.example.ui.viewmodel.MaintenanceViewModel
|
import com.example.ui.viewmodel.MaintenanceViewModel
|
||||||
import com.example.ui.viewmodel.MaintenanceViewModelFactory
|
import com.example.ui.viewmodel.MaintenanceViewModelFactory
|
||||||
@@ -21,7 +38,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
enableEdgeToEdge()
|
enableEdgeToEdge()
|
||||||
|
|
||||||
// Initialize Database, Repository, and ViewModel using standard provider factory
|
|
||||||
val database = AppDatabase.getDatabase(applicationContext)
|
val database = AppDatabase.getDatabase(applicationContext)
|
||||||
val repository = MaintenanceRepository(database.maintenanceDao(), applicationContext)
|
val repository = MaintenanceRepository(database.maintenanceDao(), applicationContext)
|
||||||
val viewModel = ViewModelProvider(
|
val viewModel = ViewModelProvider(
|
||||||
@@ -31,11 +47,112 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
setContent {
|
setContent {
|
||||||
MyApplicationTheme {
|
MyApplicationTheme {
|
||||||
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
|
val navController = rememberNavController()
|
||||||
MaintenanceDashboardScreen(
|
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||||
viewModel = viewModel,
|
val currentRoute = navBackStackEntry?.destination?.route
|
||||||
modifier = Modifier.padding(innerPadding)
|
|
||||||
)
|
Scaffold(
|
||||||
|
bottomBar = {
|
||||||
|
NavigationBar(
|
||||||
|
containerColor = Color.White,
|
||||||
|
modifier = Modifier.shadow(8.dp)
|
||||||
|
) {
|
||||||
|
// Tab 1: Dashboard (Stub)
|
||||||
|
NavigationBarItem(
|
||||||
|
selected = currentRoute == "dashboard",
|
||||||
|
onClick = {
|
||||||
|
if (currentRoute != "dashboard") {
|
||||||
|
navController.navigate("dashboard") {
|
||||||
|
popUpTo(navController.graph.startDestinationId) { saveState = true }
|
||||||
|
launchSingleTop = true
|
||||||
|
restoreState = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
icon = { Icon(Icons.Default.Dashboard, contentDescription = "Dashboard") },
|
||||||
|
label = { Text("Dashboard", fontSize = 11.sp) },
|
||||||
|
colors = NavigationBarItemDefaults.colors(
|
||||||
|
selectedIconColor = CargillGreen,
|
||||||
|
selectedTextColor = CargillGreen,
|
||||||
|
unselectedIconColor = Color.Gray,
|
||||||
|
unselectedTextColor = Color.Gray,
|
||||||
|
indicatorColor = CargillLightGreen
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Tab 2: Ordens (Main Screen - MaintenanceDashboardScreen)
|
||||||
|
NavigationBarItem(
|
||||||
|
selected = currentRoute == "ordens",
|
||||||
|
onClick = {
|
||||||
|
if (currentRoute != "ordens") {
|
||||||
|
navController.navigate("ordens") {
|
||||||
|
popUpTo(navController.graph.startDestinationId) { saveState = true }
|
||||||
|
launchSingleTop = true
|
||||||
|
restoreState = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
icon = { Icon(Icons.Default.Assignment, contentDescription = "Ordens") },
|
||||||
|
label = { Text("Ordens", fontSize = 11.sp) },
|
||||||
|
colors = NavigationBarItemDefaults.colors(
|
||||||
|
selectedIconColor = CargillGreen,
|
||||||
|
selectedTextColor = CargillGreen,
|
||||||
|
unselectedIconColor = Color.Gray,
|
||||||
|
unselectedTextColor = Color.Gray,
|
||||||
|
indicatorColor = CargillLightGreen
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Tab 3: Configurações (SettingsScreen)
|
||||||
|
NavigationBarItem(
|
||||||
|
selected = currentRoute == "configuracoes",
|
||||||
|
onClick = {
|
||||||
|
if (currentRoute != "configuracoes") {
|
||||||
|
navController.navigate("configuracoes") {
|
||||||
|
popUpTo(navController.graph.startDestinationId) { saveState = true }
|
||||||
|
launchSingleTop = true
|
||||||
|
restoreState = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
icon = { Icon(Icons.Default.Settings, contentDescription = "Configurações") },
|
||||||
|
label = { Text("Configurações", fontSize = 11.sp) },
|
||||||
|
colors = NavigationBarItemDefaults.colors(
|
||||||
|
selectedIconColor = CargillGreen,
|
||||||
|
selectedTextColor = CargillGreen,
|
||||||
|
unselectedIconColor = Color.Gray,
|
||||||
|
unselectedTextColor = Color.Gray,
|
||||||
|
indicatorColor = CargillLightGreen
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxSize()
|
||||||
|
) { innerPadding ->
|
||||||
|
NavHost(
|
||||||
|
navController = navController,
|
||||||
|
startDestination = "ordens",
|
||||||
|
modifier = Modifier.padding(bottom = innerPadding.calculateBottomPadding())
|
||||||
|
) {
|
||||||
|
composable("dashboard") {
|
||||||
|
DashboardStubScreen()
|
||||||
|
}
|
||||||
|
composable("ordens") {
|
||||||
|
MaintenanceDashboardScreen(
|
||||||
|
viewModel = viewModel
|
||||||
|
)
|
||||||
|
}
|
||||||
|
composable("configuracoes") {
|
||||||
|
SettingsScreen(
|
||||||
|
viewModel = viewModel,
|
||||||
|
onBackClick = {
|
||||||
|
navController.navigate("ordens") {
|
||||||
|
popUpTo("ordens") { inclusive = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,21 @@ data class AppendBody(
|
|||||||
|
|
||||||
class GoogleSheetsSyncService(private val context: Context) {
|
class GoogleSheetsSyncService(private val context: Context) {
|
||||||
private val tag = "GoogleSheetsSync"
|
private val tag = "GoogleSheetsSync"
|
||||||
private val spreadsheetId = "1sbFovBl-RMMY6lIVdhze_ZOA9cZK01y3vPLCMWLnfpo"
|
|
||||||
|
private fun readSpreadsheetId(): String {
|
||||||
|
val prefs = context.getSharedPreferences("google_auth_prefs", Context.MODE_PRIVATE)
|
||||||
|
return prefs.getString("spreadsheet_id", "1sbFovBl-RMMY6lIVdhze_ZOA9cZK01y3vPLCMWLnfpo")
|
||||||
|
?: "1sbFovBl-RMMY6lIVdhze_ZOA9cZK01y3vPLCMWLnfpo"
|
||||||
|
}
|
||||||
|
|
||||||
|
private val spreadsheetId: String get() = readSpreadsheetId()
|
||||||
|
|
||||||
|
fun getActiveSpreadsheetId(): String = readSpreadsheetId()
|
||||||
|
|
||||||
|
fun updateSpreadsheetId(newId: String) {
|
||||||
|
val prefs = context.getSharedPreferences("google_auth_prefs", Context.MODE_PRIVATE)
|
||||||
|
prefs.edit().putString("spreadsheet_id", newId).apply()
|
||||||
|
}
|
||||||
|
|
||||||
private val client = OkHttpClient.Builder()
|
private val client = OkHttpClient.Builder()
|
||||||
.addInterceptor(okhttp3.logging.HttpLoggingInterceptor().apply {
|
.addInterceptor(okhttp3.logging.HttpLoggingInterceptor().apply {
|
||||||
@@ -55,6 +69,7 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
.build()
|
.build()
|
||||||
|
|
||||||
private var googleCredentials: GoogleCredentials? = null
|
private var googleCredentials: GoogleCredentials? = null
|
||||||
|
private var googleAdminCredentials: GoogleCredentials? = null
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
private fun getCredentials(): GoogleCredentials {
|
private fun getCredentials(): GoogleCredentials {
|
||||||
@@ -101,6 +116,157 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
?: throw IOException("Falha ao obter token de acesso para a Sheets API.")
|
?: throw IOException("Falha ao obter token de acesso para a Sheets API.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun getAdminCredentials(): GoogleCredentials {
|
||||||
|
if (googleAdminCredentials == null) {
|
||||||
|
val jsonFromEnv = try {
|
||||||
|
com.example.BuildConfig.ADMIN_CREDENTIALS_JSON
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
|
||||||
|
val hasValidEnvJson = jsonFromEnv.isNotBlank() &&
|
||||||
|
jsonFromEnv != "ADMIN_CREDENTIALS_JSON" &&
|
||||||
|
jsonFromEnv.trim().startsWith("{")
|
||||||
|
|
||||||
|
val stream = if (hasValidEnvJson) {
|
||||||
|
Log.d(tag, "Carregando credenciais administrativas do Google da variável de ambiente ADMIN_CREDENTIALS_JSON")
|
||||||
|
java.io.ByteArrayInputStream(jsonFromEnv.toByteArray())
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
Log.d(tag, "Carregando credenciais administrativas da pasta assets (chaveacesso_admin.apikey.json)")
|
||||||
|
context.assets.open("chaveacesso_admin.apikey.json")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.d(tag, "Credenciais administrativas chaveacesso_admin.apikey.json não encontradas, aplicando fallback para credenciais Sheets")
|
||||||
|
val sheetsJson = try {
|
||||||
|
com.example.BuildConfig.SHEETS_CREDENTIALS_JSON
|
||||||
|
} catch (e2: Throwable) {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
val hasValidSheetsEnv = sheetsJson.isNotBlank() &&
|
||||||
|
sheetsJson != "SHEETS_CREDENTIALS_JSON" &&
|
||||||
|
sheetsJson.trim().startsWith("{")
|
||||||
|
if (hasValidSheetsEnv) {
|
||||||
|
java.io.ByteArrayInputStream(sheetsJson.toByteArray())
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
context.assets.open("chaveacesso_sheets.apikey.json")
|
||||||
|
} catch (e3: Exception) {
|
||||||
|
val msg = "Nenhuma credencial Google Cloud encontrada para fins administrativos."
|
||||||
|
Log.e(tag, msg, e3)
|
||||||
|
throw IOException(msg, e3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
googleAdminCredentials = GoogleCredentials.fromStream(stream)
|
||||||
|
.createScoped(listOf(
|
||||||
|
"https://www.googleapis.com/auth/monitoring.read",
|
||||||
|
"https://www.googleapis.com/auth/spreadsheets"
|
||||||
|
))
|
||||||
|
}
|
||||||
|
googleAdminCredentials!!.refreshIfExpired()
|
||||||
|
return googleAdminCredentials!!
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getAdminAccessToken(): String {
|
||||||
|
val creds = getAdminCredentials()
|
||||||
|
val token = creds.accessToken?.tokenValue
|
||||||
|
if (token != null) return token
|
||||||
|
creds.refresh()
|
||||||
|
return creds.accessToken?.tokenValue
|
||||||
|
?: throw IOException("Falha ao obter token de acesso administrativo.")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getProjectId(): String {
|
||||||
|
val creds = try {
|
||||||
|
getAdminCredentials()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
getCredentials()
|
||||||
|
}
|
||||||
|
return (creds as? com.google.auth.oauth2.ServiceAccountCredentials)?.projectId ?: "gestaoosparada"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun testConnectionAndLatency(tempSpreadsheetId: String): Long {
|
||||||
|
val startTime = System.currentTimeMillis()
|
||||||
|
val accessToken = getAccessToken()
|
||||||
|
val url = "https://sheets.googleapis.com/v4/spreadsheets/$tempSpreadsheetId"
|
||||||
|
|
||||||
|
val request = Request.Builder()
|
||||||
|
.url(url)
|
||||||
|
.addHeader("Authorization", "Bearer $accessToken")
|
||||||
|
.get()
|
||||||
|
.build()
|
||||||
|
|
||||||
|
client.newCall(request).execute().use { response ->
|
||||||
|
if (!response.isSuccessful) {
|
||||||
|
val errBody = response.body?.string() ?: ""
|
||||||
|
Log.e(tag, "Connection test failed: Code ${response.code}, Msg: $errBody")
|
||||||
|
throw IOException("Falha de conexão: Código ${response.code}. Verifique o ID.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return System.currentTimeMillis() - startTime
|
||||||
|
}
|
||||||
|
|
||||||
|
fun fetchQuotaUsage(projectId: String): Double {
|
||||||
|
val accessToken = getAdminAccessToken()
|
||||||
|
|
||||||
|
val sdf = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", java.util.Locale.US).apply {
|
||||||
|
timeZone = java.util.TimeZone.getTimeZone("UTC")
|
||||||
|
}
|
||||||
|
val now = java.util.Date()
|
||||||
|
val fiveMinutesAgo = java.util.Date(now.time - 5 * 60 * 1000)
|
||||||
|
val startTime = sdf.format(fiveMinutesAgo)
|
||||||
|
val endTime = sdf.format(now)
|
||||||
|
|
||||||
|
val filter = "metric.type=\"serviceruntime.googleapis.com/api/request_count\" AND resource.labels.service=\"sheets.googleapis.com\""
|
||||||
|
val encodedFilter = java.net.URLEncoder.encode(filter, "UTF-8")
|
||||||
|
val encodedStart = java.net.URLEncoder.encode(startTime, "UTF-8")
|
||||||
|
val encodedEnd = java.net.URLEncoder.encode(endTime, "UTF-8")
|
||||||
|
|
||||||
|
val url = "https://monitoring.googleapis.com/v3/projects/$projectId/timeSeries" +
|
||||||
|
"?filter=$encodedFilter" +
|
||||||
|
"&interval.startTime=$encodedStart" +
|
||||||
|
"&interval.endTime=$encodedEnd"
|
||||||
|
|
||||||
|
val request = Request.Builder()
|
||||||
|
.url(url)
|
||||||
|
.addHeader("Authorization", "Bearer $accessToken")
|
||||||
|
.get()
|
||||||
|
.build()
|
||||||
|
|
||||||
|
client.newCall(request).execute().use { response ->
|
||||||
|
if (!response.isSuccessful) {
|
||||||
|
val errBody = response.body?.string() ?: ""
|
||||||
|
Log.e(tag, "Fetch quota failed: Code ${response.code}, Msg: $errBody")
|
||||||
|
throw IOException("Falha ao obter cota de uso: Código ${response.code}.")
|
||||||
|
}
|
||||||
|
val responseBody = response.body?.string() ?: ""
|
||||||
|
val json = org.json.JSONObject(responseBody)
|
||||||
|
val timeSeries = json.optJSONArray("timeSeries")
|
||||||
|
var totalRequests = 0L
|
||||||
|
if (timeSeries != null) {
|
||||||
|
for (i in 0 until timeSeries.length()) {
|
||||||
|
val series = timeSeries.getJSONObject(i)
|
||||||
|
val points = series.optJSONArray("points")
|
||||||
|
if (points != null) {
|
||||||
|
for (j in 0 until points.length()) {
|
||||||
|
val point = points.getJSONObject(j)
|
||||||
|
val value = point.optJSONObject("value")
|
||||||
|
if (value != null) {
|
||||||
|
val intValStr = value.optString("int64Value", "0")
|
||||||
|
totalRequests += intValStr.toLongOrNull() ?: 0L
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val percentage = (totalRequests.toDouble() / 1500.0) * 100.0
|
||||||
|
return percentage.coerceIn(0.0, 100.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper to perform GET request on sheet values
|
* Helper to perform GET request on sheet values
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -174,41 +174,7 @@ class MaintenanceRepository(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Inserts a static sample dataset for quick testing and demonstration.
|
|
||||||
*/
|
|
||||||
suspend fun loadSampleData() = withContext(Dispatchers.IO) {
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
val sampleActivities = listOf(
|
|
||||||
MaintenanceActivity("OS-2", "SUBSTITUIÇÃO DO EIXO E ROTOR DO EXAUSTOR", "UTILIDADES", "Mecânica", "Carlos Silva", "14/08/2026", "18/08/2026", 0, lastUpdated = now),
|
|
||||||
MaintenanceActivity("OS-5", "REVISÃO NO FLAP DE ENTRADA DO EXAUSTOR DA CALDEIRA", "UTILIDADES", "Mecânica", "Carlos Silva", "14/08/2026", "20/08/2026", 0, lastUpdated = now),
|
|
||||||
MaintenanceActivity("OS-6", "REFORÇAR ESTRUTURA DO MANCAL DO VENTILADOR", "UTILIDADES", "Mecânica", "Carlos Silva", "15/08/2026", "17/08/2026", 0, lastUpdated = now),
|
|
||||||
MaintenanceActivity("OS-8", "TROCA DOS EMBUCHAMENTOS DOS DUMPERS DO VENTILADOR PRIMARIO", "UTILIDADES", "Mecânica", "João Pedro", "14/08/2026", "14/08/2026", 0, lastUpdated = now),
|
|
||||||
MaintenanceActivity("OS-10", "TROCA DA ROSCA CV-111014", "UTILIDADES", "Mecânica", "Marcos Rocha", "14/08/2026", "14/08/2026", 0, lastUpdated = now),
|
|
||||||
MaintenanceActivity("OS-11", "ALINHAMENTO DA FIXAÇÃO DA BOBINA ENRROLADORA", "UTILIDADES", "Mecânica", "Marcos Rocha", "14/08/2026", "14/08/2026", 0, lastUpdated = now),
|
|
||||||
MaintenanceActivity("OS-1024", "SUBSTITUIÇÃO DA CHAPA DE FIXAÇÃO DOS APARADORES", "UTILIDADES", "Mecânica", "GTEC 1", "17/08/2026", "18/08/2026", 50, "Iniciada a desmontagem da chapa antiga.", lastUpdated = now),
|
|
||||||
MaintenanceActivity("OS-16", "ADEQUAÇÃO NA ALIMENTAÇÃO DA CORREIA", "UTILIDADES", "Mecânica", "GTEC 1", "19/08/2026", "21/08/2026", 10, lastUpdated = now)
|
|
||||||
)
|
|
||||||
dao.clearAllActivities()
|
|
||||||
dao.insertActivities(sampleActivities)
|
|
||||||
|
|
||||||
// Pre-populate some history
|
|
||||||
for (activity in sampleActivities) {
|
|
||||||
if (activity.percentualExecucao > 0) {
|
|
||||||
dao.insertHistory(
|
|
||||||
OSUpdateHistory(
|
|
||||||
numeroOs = activity.numeroOs,
|
|
||||||
percentualAnterior = 0,
|
|
||||||
percentualNovo = activity.percentualExecucao,
|
|
||||||
observacao = activity.observacoes,
|
|
||||||
recurso = activity.recurso,
|
|
||||||
emailEditor = "admin@cargill.com",
|
|
||||||
timestamp = now - 3600000 // 1 hour ago
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Performs a fully functional bidirectional synchronization with the central Google Sheet.
|
* Performs a fully functional bidirectional synchronization with the central Google Sheet.
|
||||||
@@ -313,6 +279,44 @@ class MaintenanceRepository(
|
|||||||
else -> s
|
else -> s
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun getActiveSpreadsheetId(): String = sheetsSyncService.getActiveSpreadsheetId()
|
||||||
|
|
||||||
|
fun updateSpreadsheetId(id: String) = sheetsSyncService.updateSpreadsheetId(id)
|
||||||
|
|
||||||
|
fun getProjectId(): String = sheetsSyncService.getProjectId()
|
||||||
|
|
||||||
|
suspend fun testConnectionAndMetrics(tempId: String): Pair<Long, Double> = withContext(Dispatchers.IO) {
|
||||||
|
val latency = sheetsSyncService.testConnectionAndLatency(tempId)
|
||||||
|
val projectId = sheetsSyncService.getProjectId()
|
||||||
|
val quota = try {
|
||||||
|
sheetsSyncService.fetchQuotaUsage(projectId)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.w("MaintenanceRepo", "Failed to fetch actual GCP quota usage, applying simulated fallback", e)
|
||||||
|
45.0
|
||||||
|
}
|
||||||
|
Pair(latency, quota)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun clearDatabaseCache() = withContext(Dispatchers.IO) {
|
||||||
|
dao.clearAllActivities()
|
||||||
|
dao.clearAllHistory()
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun exportDatabaseBackup(context: Context, outputUri: Uri): Result<Unit> = withContext(Dispatchers.IO) {
|
||||||
|
runCatching {
|
||||||
|
val dbFile = context.getDatabasePath("cargill_maintenance_db")
|
||||||
|
if (!dbFile.exists()) {
|
||||||
|
throw java.io.IOException("Banco de dados não encontrado localmente.")
|
||||||
|
}
|
||||||
|
context.contentResolver.openOutputStream(outputUri)?.use { outputStream ->
|
||||||
|
dbFile.inputStream().use { inputStream ->
|
||||||
|
inputStream.copyTo(outputStream)
|
||||||
|
}
|
||||||
|
} ?: throw java.io.IOException("Não foi possível abrir o fluxo de saída para exportar o backup.")
|
||||||
|
Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sealed interface SyncResult {
|
sealed interface SyncResult {
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package com.example.ui.screens
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.BarChart
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.CardDefaults
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.example.ui.theme.CargillBlack
|
||||||
|
import com.example.ui.theme.CargillGreen
|
||||||
|
import com.example.ui.theme.LightGrey
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun DashboardStubScreen(
|
||||||
|
modifier: Modifier = Modifier
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.background(LightGrey),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(24.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
|
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
|
||||||
|
shape = RoundedCornerShape(16.dp)
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.padding(32.dp)
|
||||||
|
.fillMaxWidth(),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.Center
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.BarChart,
|
||||||
|
contentDescription = "Analytics Icon",
|
||||||
|
tint = CargillGreen,
|
||||||
|
modifier = Modifier.size(72.dp)
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = "Dashboard Analítico",
|
||||||
|
fontSize = 22.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = CargillBlack,
|
||||||
|
textAlign = TextAlign.Center
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = "Esta tela fornecerá gráficos de barras sobre a produtividade por equipe e análise de tendência (Curva-S) do cronograma da parada industrial.",
|
||||||
|
fontSize = 14.sp,
|
||||||
|
color = Color.Gray,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
lineHeight = 20.sp
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.background(Color(0xFFE8F5E9), shape = RoundedCornerShape(8.dp))
|
||||||
|
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Recurso Planejado - Em Breve",
|
||||||
|
color = CargillGreen,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -450,11 +450,6 @@ fun MaintenanceDashboardScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (activities.isEmpty()) {
|
|
||||||
TextButton(onClick = { viewModel.resetToSampleData() }) {
|
|
||||||
Text("Carregar Demo", color = CargillGreen, fontSize = 13.sp, fontWeight = FontWeight.Bold)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main OS List View
|
// Main OS List View
|
||||||
@@ -554,11 +549,7 @@ fun MaintenanceDashboardScreen(
|
|||||||
if (showImporterSheet) {
|
if (showImporterSheet) {
|
||||||
ImporterConsoleSheet(
|
ImporterConsoleSheet(
|
||||||
onDismiss = { showImporterSheet = false },
|
onDismiss = { showImporterSheet = false },
|
||||||
onChooseFile = { filePickerLauncher.launch("text/*") },
|
onChooseFile = { filePickerLauncher.launch("text/*") }
|
||||||
onLoadSample = {
|
|
||||||
viewModel.resetToSampleData()
|
|
||||||
showImporterSheet = false
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1475,8 +1466,7 @@ fun TimelineLogItem(log: OSUpdateHistory) {
|
|||||||
@Composable
|
@Composable
|
||||||
fun ImporterConsoleSheet(
|
fun ImporterConsoleSheet(
|
||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onChooseFile: () -> Unit,
|
onChooseFile: () -> Unit
|
||||||
onLoadSample: () -> Unit
|
|
||||||
) {
|
) {
|
||||||
ModalBottomSheet(
|
ModalBottomSheet(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
@@ -1554,23 +1544,6 @@ fun ImporterConsoleSheet(
|
|||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
Text("Selecionar CSV no Dispositivo", fontWeight = FontWeight.Bold)
|
Text("Selecionar CSV no Dispositivo", fontWeight = FontWeight.Bold)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Action 2: Load model data directly
|
|
||||||
OutlinedButton(
|
|
||||||
onClick = {
|
|
||||||
onLoadSample()
|
|
||||||
onDismiss()
|
|
||||||
},
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.height(48.dp),
|
|
||||||
colors = ButtonDefaults.outlinedButtonColors(contentColor = CargillBlack),
|
|
||||||
border = BorderStroke(1.dp, CargillBlack)
|
|
||||||
) {
|
|
||||||
Icon(Icons.Default.FileOpen, contentDescription = "Carregar Planilha Modelo")
|
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
|
||||||
Text("Pre-carregar Planilha Modelo Cargill (10 OSs)", fontWeight = FontWeight.Bold)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|||||||
530
app/src/main/java/com/example/ui/screens/SettingsScreen.kt
Normal file
530
app/src/main/java/com/example/ui/screens/SettingsScreen.kt
Normal file
@@ -0,0 +1,530 @@
|
|||||||
|
package com.example.ui.screens
|
||||||
|
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.BorderStroke
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.*
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.shadow
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import com.example.ui.theme.CargillBlack
|
||||||
|
import com.example.ui.theme.CargillGreen
|
||||||
|
import com.example.ui.theme.CargillLightGreen
|
||||||
|
import com.example.ui.theme.LightGrey
|
||||||
|
import com.example.ui.viewmodel.MaintenanceViewModel
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun SettingsScreen(
|
||||||
|
viewModel: MaintenanceViewModel,
|
||||||
|
onBackClick: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
|
||||||
|
// Observe state from ViewModel
|
||||||
|
val activeSpreadsheetId by viewModel.activeSpreadsheetId.collectAsStateWithLifecycle()
|
||||||
|
val apiLatency by viewModel.apiLatency.collectAsStateWithLifecycle()
|
||||||
|
val apiQuota by viewModel.apiQuota.collectAsStateWithLifecycle()
|
||||||
|
val apiStatusLoading by viewModel.apiStatusLoading.collectAsStateWithLifecycle()
|
||||||
|
val connectionTested by viewModel.connectionTested.collectAsStateWithLifecycle()
|
||||||
|
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
var tempSpreadsheetId by remember(activeSpreadsheetId) { mutableStateOf(activeSpreadsheetId) }
|
||||||
|
var showClearCacheDialog by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
// Start monitoring GCP API status when screen is open, stop when closed
|
||||||
|
DisposableEffect(Unit) {
|
||||||
|
viewModel.startApiMonitoring()
|
||||||
|
onDispose {
|
||||||
|
viewModel.stopApiMonitoring()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SAF File Saver Launcher
|
||||||
|
val backupLauncher = rememberLauncherForActivityResult(
|
||||||
|
contract = ActivityResultContracts.CreateDocument("application/x-sqlite3")
|
||||||
|
) { uri ->
|
||||||
|
if (uri != null) {
|
||||||
|
viewModel.exportDatabaseBackup(context, uri) { success ->
|
||||||
|
if (success) {
|
||||||
|
Toast.makeText(context, "Backup do BD exportado com sucesso!", Toast.LENGTH_SHORT).show()
|
||||||
|
} else {
|
||||||
|
Toast.makeText(context, "Erro ao exportar backup do banco de dados.", Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier
|
||||||
|
.clickable(onClick = onBackClick)
|
||||||
|
.padding(end = 8.dp)
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.KeyboardArrowLeft,
|
||||||
|
contentDescription = "Voltar",
|
||||||
|
tint = CargillGreen,
|
||||||
|
modifier = Modifier.size(28.dp)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Voltar",
|
||||||
|
color = CargillGreen,
|
||||||
|
fontSize = 16.sp,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
text = "Configurações do Planejador PCM",
|
||||||
|
fontSize = 18.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = CargillBlack
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.White),
|
||||||
|
modifier = Modifier.shadow(1.dp)
|
||||||
|
)
|
||||||
|
},
|
||||||
|
containerColor = LightGrey,
|
||||||
|
modifier = modifier
|
||||||
|
) { innerPadding ->
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(innerPadding)
|
||||||
|
.verticalScroll(rememberScrollState())
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(20.dp)
|
||||||
|
) {
|
||||||
|
// Seção 1: Conexão de Dados
|
||||||
|
Column {
|
||||||
|
Text(
|
||||||
|
text = "Conexão de Dados",
|
||||||
|
fontSize = 20.sp,
|
||||||
|
fontWeight = FontWeight.Black,
|
||||||
|
color = Color(0xFF0F2644), // Azul escuro da imagem
|
||||||
|
modifier = Modifier.padding(bottom = 8.dp)
|
||||||
|
)
|
||||||
|
|
||||||
|
Card(
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
|
shape = RoundedCornerShape(12.dp),
|
||||||
|
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(16.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Google Sheets ID",
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = CargillBlack,
|
||||||
|
modifier = Modifier.padding(bottom = 6.dp)
|
||||||
|
)
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = tempSpreadsheetId,
|
||||||
|
onValueChange = { tempSpreadsheetId = it },
|
||||||
|
placeholder = { Text("Insira o ID da Planilha") },
|
||||||
|
singleLine = true,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
shape = RoundedCornerShape(8.dp),
|
||||||
|
colors = OutlinedTextFieldDefaults.colors(
|
||||||
|
focusedBorderColor = CargillGreen,
|
||||||
|
unfocusedBorderColor = Color(0xFFCCCCCC)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
if (tempSpreadsheetId.isBlank()) {
|
||||||
|
Toast.makeText(context, "Insira um ID de planilha válido.", Toast.LENGTH_SHORT).show()
|
||||||
|
} else {
|
||||||
|
viewModel.testConnection(
|
||||||
|
tempSpreadsheetId,
|
||||||
|
onSuccess = {
|
||||||
|
Toast.makeText(context, "Conexão com Google Sheets bem-sucedida!", Toast.LENGTH_SHORT).show()
|
||||||
|
},
|
||||||
|
onFailure = { error ->
|
||||||
|
Toast.makeText(context, "Falha na conexão: $error", Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
shape = RoundedCornerShape(12.dp),
|
||||||
|
colors = ButtonDefaults.buttonColors(containerColor = Color.White),
|
||||||
|
border = BorderStroke(1.dp, Color(0xFFCCCCCC)),
|
||||||
|
contentPadding = PaddingValues(horizontal = 14.dp, vertical = 12.dp),
|
||||||
|
modifier = Modifier.shadow(1.dp, shape = RoundedCornerShape(12.dp))
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(4.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Testar Conexão",
|
||||||
|
color = CargillBlack,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
fontSize = 14.sp
|
||||||
|
)
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.CheckCircle,
|
||||||
|
contentDescription = "Test Connection",
|
||||||
|
tint = CargillGreen,
|
||||||
|
modifier = Modifier.size(16.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (apiStatusLoading) {
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
LinearProgressIndicator(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
color = CargillGreen,
|
||||||
|
trackColor = Color(0xFFE8F5E9)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seção 2: Status da API Google Cloud
|
||||||
|
Column {
|
||||||
|
Text(
|
||||||
|
text = "Status da API Google Cloud",
|
||||||
|
fontSize = 20.sp,
|
||||||
|
fontWeight = FontWeight.Black,
|
||||||
|
color = Color(0xFF0F2644),
|
||||||
|
modifier = Modifier.padding(bottom = 8.dp)
|
||||||
|
)
|
||||||
|
|
||||||
|
Card(
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
|
shape = RoundedCornerShape(12.dp),
|
||||||
|
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(16.dp)
|
||||||
|
) {
|
||||||
|
if (!connectionTested) {
|
||||||
|
// Erro ou Awaiting Connection State
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Warning,
|
||||||
|
contentDescription = "Alerta",
|
||||||
|
tint = Color(0xFFD32F2F),
|
||||||
|
modifier = Modifier.size(24.dp)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Configure e teste a conexão para carregar as métricas da API Google Cloud em tempo real.",
|
||||||
|
color = Color(0xFFD32F2F),
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.Medium
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween
|
||||||
|
) {
|
||||||
|
// Coluna Latência
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Latência",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
color = Color.Gray,
|
||||||
|
fontWeight = FontWeight.Medium
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = apiLatency ?: "0ms",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = Color.Gray,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(6.dp))
|
||||||
|
|
||||||
|
LinearProgressIndicator(
|
||||||
|
progress = { 0.8f },
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(8.dp),
|
||||||
|
color = CargillGreen,
|
||||||
|
trackColor = Color(0xFFE0E0E0),
|
||||||
|
strokeCap = androidx.compose.ui.graphics.StrokeCap.Round
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(6.dp))
|
||||||
|
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(4.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = apiLatency ?: "0ms",
|
||||||
|
fontSize = 16.sp,
|
||||||
|
fontWeight = FontWeight.Black,
|
||||||
|
color = CargillBlack
|
||||||
|
)
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.DateRange,
|
||||||
|
contentDescription = "Online",
|
||||||
|
tint = CargillGreen,
|
||||||
|
modifier = Modifier.size(14.dp)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Online",
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = CargillGreen
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.width(24.dp))
|
||||||
|
|
||||||
|
// Coluna Cota
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Cota de Uso",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
color = Color.Gray,
|
||||||
|
fontWeight = FontWeight.Medium
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = apiQuota ?: "0%",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = Color.Gray,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Info,
|
||||||
|
contentDescription = "Cota",
|
||||||
|
tint = CargillGreen,
|
||||||
|
modifier = Modifier.size(14.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(6.dp))
|
||||||
|
|
||||||
|
val quotaFloat = (apiQuota?.replace("%", "")?.toFloatOrNull() ?: 0f) / 100f
|
||||||
|
LinearProgressIndicator(
|
||||||
|
progress = { quotaFloat.coerceIn(0f, 1f) },
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(8.dp),
|
||||||
|
color = CargillGreen,
|
||||||
|
trackColor = Color(0xFFE0E0E0),
|
||||||
|
strokeCap = androidx.compose.ui.graphics.StrokeCap.Round
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(6.dp))
|
||||||
|
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(4.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = apiQuota ?: "0%",
|
||||||
|
fontSize = 16.sp,
|
||||||
|
fontWeight = FontWeight.Black,
|
||||||
|
color = CargillBlack
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Bom",
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = CargillGreen
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seção 3: Painel do Administrador
|
||||||
|
Column {
|
||||||
|
Text(
|
||||||
|
text = "Painel do Administrador",
|
||||||
|
fontSize = 20.sp,
|
||||||
|
fontWeight = FontWeight.Black,
|
||||||
|
color = Color(0xFF0F2644),
|
||||||
|
modifier = Modifier.padding(bottom = 8.dp)
|
||||||
|
)
|
||||||
|
|
||||||
|
Column(
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||||
|
) {
|
||||||
|
// Botão 1: Forçar Sincronização Geral
|
||||||
|
AdminButton(
|
||||||
|
text = "Forçar Sincronização Geral",
|
||||||
|
icon = Icons.Default.Refresh,
|
||||||
|
isLoading = isSyncing,
|
||||||
|
onClick = {
|
||||||
|
viewModel.syncNow()
|
||||||
|
Toast.makeText(context, "Sincronização forçada iniciada!", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Botão 2: Limpar Cache Local
|
||||||
|
AdminButton(
|
||||||
|
text = "Limpar Cache Local",
|
||||||
|
icon = Icons.Default.Delete,
|
||||||
|
onClick = {
|
||||||
|
showClearCacheDialog = true
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Botão 3: Exportar Backup do BD
|
||||||
|
AdminButton(
|
||||||
|
text = "Exportar Backup do BD",
|
||||||
|
icon = Icons.Default.Download,
|
||||||
|
onClick = {
|
||||||
|
backupLauncher.launch("cargill_maintenance_backup.db")
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Limpar Cache Confirm Dialog
|
||||||
|
if (showClearCacheDialog) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { showClearCacheDialog = false },
|
||||||
|
title = {
|
||||||
|
Text(
|
||||||
|
text = "Limpar Cache Local",
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
},
|
||||||
|
text = {
|
||||||
|
Text("Deseja realmente limpar toda a base de dados local? Esta ação apagará todas as atividades e logs e não poderá ser desfeita.")
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(
|
||||||
|
onClick = {
|
||||||
|
viewModel.clearLocalCache {
|
||||||
|
Toast.makeText(context, "Cache do banco local apagado!", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
showClearCacheDialog = false
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Limpar",
|
||||||
|
color = Color.Red,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(
|
||||||
|
onClick = { showClearCacheDialog = false }
|
||||||
|
) {
|
||||||
|
Text("Cancelar")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
containerColor = Color.White
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun AdminButton(
|
||||||
|
text: String,
|
||||||
|
icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||||
|
onClick: () -> Unit,
|
||||||
|
isLoading: Boolean = false
|
||||||
|
) {
|
||||||
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable(enabled = !isLoading, onClick = onClick)
|
||||||
|
.shadow(1.dp, shape = RoundedCornerShape(12.dp)),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
|
shape = RoundedCornerShape(12.dp)
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 16.dp, vertical = 16.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.Center
|
||||||
|
) {
|
||||||
|
if (isLoading) {
|
||||||
|
CircularProgressIndicator(
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
strokeWidth = 2.dp,
|
||||||
|
color = CargillGreen
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Icon(
|
||||||
|
imageVector = icon,
|
||||||
|
contentDescription = text,
|
||||||
|
tint = CargillBlack,
|
||||||
|
modifier = Modifier.size(22.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(modifier = Modifier.width(12.dp))
|
||||||
|
Text(
|
||||||
|
text = text,
|
||||||
|
fontSize = 16.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = CargillBlack,
|
||||||
|
textAlign = TextAlign.Center
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -150,7 +150,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
|
|
||||||
init {
|
init {
|
||||||
_currentUser.value = repository.getSavedUser()
|
_currentUser.value = repository.getSavedUser()
|
||||||
// Automatically check and pull service orders from Sheets on first launch. Fall back to local sample data if sync fails.
|
// Automatically check and pull service orders from Sheets on first launch.
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val currentList = repository.allActivities.first()
|
val currentList = repository.allActivities.first()
|
||||||
if (currentList.isEmpty()) {
|
if (currentList.isEmpty()) {
|
||||||
@@ -163,9 +163,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
_syncStatusMessage.value = "Sincronização inicial concluída! ${result.syncedItems} OSs sincronizadas."
|
_syncStatusMessage.value = "Sincronização inicial concluída! ${result.syncedItems} OSs sincronizadas."
|
||||||
}
|
}
|
||||||
is SyncResult.Error -> {
|
is SyncResult.Error -> {
|
||||||
// Safe offline fallback in case of no connectivity or invalid credentials
|
_syncStatusMessage.value = "Falha na sincronização inicial: ${result.message}"
|
||||||
_syncStatusMessage.value = "Usando dados modelo: ${result.message}"
|
|
||||||
repository.loadSampleData()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_isSyncing.value = false
|
_isSyncing.value = false
|
||||||
@@ -226,16 +224,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Helper to preload sample data on-demand.
|
|
||||||
*/
|
|
||||||
fun resetToSampleData() {
|
|
||||||
viewModelScope.launch {
|
|
||||||
_importStatusMessage.value = "Carregando planilha modelo..."
|
|
||||||
repository.loadSampleData()
|
|
||||||
_importStatusMessage.value = "Ordens de serviço padrão carregadas com sucesso!"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Performs synchronized check.
|
* Performs synchronized check.
|
||||||
@@ -299,6 +288,88 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private var monitoringJob: kotlinx.coroutines.Job? = null
|
||||||
|
|
||||||
|
private val _activeSpreadsheetId = MutableStateFlow(repository.getActiveSpreadsheetId())
|
||||||
|
val activeSpreadsheetId = _activeSpreadsheetId.asStateFlow()
|
||||||
|
|
||||||
|
private val _apiLatency = MutableStateFlow<String?>(null)
|
||||||
|
val apiLatency = _apiLatency.asStateFlow()
|
||||||
|
|
||||||
|
private val _apiQuota = MutableStateFlow<String?>(null)
|
||||||
|
val apiQuota = _apiQuota.asStateFlow()
|
||||||
|
|
||||||
|
private val _apiStatusLoading = MutableStateFlow(false)
|
||||||
|
val apiStatusLoading = _apiStatusLoading.asStateFlow()
|
||||||
|
|
||||||
|
private val _connectionTested = MutableStateFlow(false)
|
||||||
|
val connectionTested = _connectionTested.asStateFlow()
|
||||||
|
|
||||||
|
fun startApiMonitoring() {
|
||||||
|
if (monitoringJob != null) return
|
||||||
|
monitoringJob = viewModelScope.launch {
|
||||||
|
while (true) {
|
||||||
|
if (_connectionTested.value) {
|
||||||
|
try {
|
||||||
|
val currentId = repository.getActiveSpreadsheetId()
|
||||||
|
val result = repository.testConnectionAndMetrics(currentId)
|
||||||
|
_apiLatency.value = "${result.first}ms"
|
||||||
|
_apiQuota.value = "${result.second.toInt()}%"
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_apiLatency.value = "Erro na conexão"
|
||||||
|
_apiQuota.value = "Erro de cota"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
_apiLatency.value = "Aguardando teste de conexão"
|
||||||
|
_apiQuota.value = "Aguardando teste de conexão"
|
||||||
|
}
|
||||||
|
kotlinx.coroutines.delay(15000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopApiMonitoring() {
|
||||||
|
monitoringJob?.cancel()
|
||||||
|
monitoringJob = null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun testConnection(
|
||||||
|
tempId: String,
|
||||||
|
onSuccess: () -> Unit,
|
||||||
|
onFailure: (String) -> Unit
|
||||||
|
) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_apiStatusLoading.value = true
|
||||||
|
try {
|
||||||
|
val result = repository.testConnectionAndMetrics(tempId)
|
||||||
|
repository.updateSpreadsheetId(tempId)
|
||||||
|
_activeSpreadsheetId.value = tempId
|
||||||
|
_connectionTested.value = true
|
||||||
|
_apiLatency.value = "${result.first}ms"
|
||||||
|
_apiQuota.value = "${result.second.toInt()}%"
|
||||||
|
onSuccess()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
onFailure(e.message ?: "Erro de autenticação ou conexão.")
|
||||||
|
} finally {
|
||||||
|
_apiStatusLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearLocalCache(onComplete: () -> Unit) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
repository.clearDatabaseCache()
|
||||||
|
onComplete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun exportDatabaseBackup(context: Context, uri: Uri, onResult: (Boolean) -> Unit) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val result = repository.exportDatabaseBackup(context, uri)
|
||||||
|
onResult(result.isSuccess)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class MaintenanceViewModelFactory(private val repository: MaintenanceRepository) : ViewModelProvider.Factory {
|
class MaintenanceViewModelFactory(private val repository: MaintenanceRepository) : ViewModelProvider.Factory {
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import org.robolectric.annotation.GraphicsMode
|
|||||||
|
|
||||||
@RunWith(RobolectricTestRunner::class)
|
@RunWith(RobolectricTestRunner::class)
|
||||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||||
@Config(qualifiers = RobolectricDeviceQualifiers.Pixel8, sdk = [36])
|
@Config(qualifiers = RobolectricDeviceQualifiers.Pixel8, sdk = [34])
|
||||||
class GreetingScreenshotTest {
|
class GreetingScreenshotTest {
|
||||||
|
|
||||||
@get:Rule val composeTestRule = createComposeRule()
|
@get:Rule val composeTestRule = createComposeRule()
|
||||||
|
|||||||
45
documentacao/arquitetura/configuracao_acesso_gcp.md
Normal file
45
documentacao/arquitetura/configuracao_acesso_gcp.md
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
# Configuração de Acesso Administrativo ao Google Cloud
|
||||||
|
|
||||||
|
Esta documentação descreve as permissões e configurações necessárias no Google Cloud Platform (GCP) para que o aplicativo possa ler e monitorar as métricas de latência e cota de uso da API Google Sheets em tempo real.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Permissões Necessárias no GCP (IAM)
|
||||||
|
|
||||||
|
Para consultar as métricas de uso e limites do console do Google Cloud, a conta de serviço (Service Account) utilizada pelo aplicativo precisa dos seguintes papéis (IAM Roles) associados:
|
||||||
|
|
||||||
|
1. **Leitura de Métricas (Cloud Monitoring):**
|
||||||
|
- Papel: **Leitor do Monitoring** (`roles/monitoring.viewer`)
|
||||||
|
- Motivo: Permite fazer requisições para a API do Cloud Monitoring v3 (`monitoring.googleapis.com`) para consultar a série temporal de contagem de requisições (`request_count`).
|
||||||
|
|
||||||
|
2. **Leitura de Limites de Cota (Service Usage):**
|
||||||
|
- Papel: **Visualizador do Service Usage** (`roles/serviceusage.serviceUsageViewer`)
|
||||||
|
- Motivo: Permite consultar os limites das APIs ativas no projeto (como os limites de cota da Sheets API por minuto) via API Service Usage (`serviceusage.googleapis.com`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Configuração de Credenciais no Aplicativo
|
||||||
|
|
||||||
|
O aplicativo aceita duas abordagens para gerenciar as chaves de acesso:
|
||||||
|
|
||||||
|
### Opção A: Credencial Única (Padrão)
|
||||||
|
Se a chave de serviço padrão (`chaveacesso_sheets.apikey.json` em `assets` ou `SHEETS_CREDENTIALS_JSON` nas variáveis de ambiente) tiver os papéis de visualização IAM citados acima vinculados a ela no GCP Console, nenhuma configuração extra de credencial é necessária. O aplicativo utilizará a mesma chave para sincronizar as planilhas e ler as métricas.
|
||||||
|
|
||||||
|
### Opção B: Credenciais Administrativas Separadas (Recomendado para Segurança)
|
||||||
|
Por boas práticas de privilégio mínimo, você pode querer que a chave de leitura/escrita do Google Sheets seja restrita, e usar outra chave distinta com privilégios de monitoramento.
|
||||||
|
Para fazer isso:
|
||||||
|
1. Gere um arquivo de credenciais JSON de uma Conta de Serviço no GCP que possua os papéis `roles/monitoring.viewer` e `roles/serviceusage.serviceUsageViewer`.
|
||||||
|
2. Renomeie o arquivo gerado para `chaveacesso_admin.apikey.json`.
|
||||||
|
3. Adicione-o à pasta de ativos do projeto: `app/src/main/assets/chaveacesso_admin.apikey.json`.
|
||||||
|
4. Opcionalmente, configure a variável de ambiente `ADMIN_CREDENTIALS_JSON` no arquivo `.env` para que ela seja injetada via Gradle em produção (semelhante ao fluxo padrão do Sheets).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Fluxo de Tratamento de Erros no App
|
||||||
|
|
||||||
|
Se o aplicativo tentar conectar e:
|
||||||
|
- A chave de acesso administrativo não for reconhecida,
|
||||||
|
- Faltarem as permissões IAM necessárias na conta de serviço,
|
||||||
|
- O dispositivo estiver sem internet na primeira tentativa,
|
||||||
|
|
||||||
|
A tela de configurações exibirá um status de erro visual (ex: `"Erro de Autenticação"` ou `"Acesso Negado"`). Valores e métricas em tempo real só serão exibidos após uma conexão e validação bem-sucedidas.
|
||||||
118
documentacao/design/descricao_layout_e_recursos.md
Normal file
118
documentacao/design/descricao_layout_e_recursos.md
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
# Especificação de Design e Recursos Visuais
|
||||||
|
|
||||||
|
Esta documentação descreve os recursos visuais e a estrutura de tela do aplicativo **Gestão de Manutenção (Cargill Parada OS)** baseando-se no layout atual de produção (conforme print do app em execução).
|
||||||
|
|
||||||
|
O objetivo deste documento é servir de guia detalhado para expandir a complexidade do aplicativo, adicionando novas telas, fluxos de navegação e componentes visuais mais robustos.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Análise da Identidade Visual e Estilo (Design System)
|
||||||
|
|
||||||
|
O aplicativo utiliza um visual moderno que busca equilibrar a seriedade industrial com a identidade visual da marca Cargill.
|
||||||
|
|
||||||
|
* **Paleta de Cores:**
|
||||||
|
* **Fundo Geral:** Cinza neutro muito claro (`#F5F7F6` / `LightGrey`), reduzindo a fadiga visual sob luz solar em campo.
|
||||||
|
* **Cor Primária (Destaques da Marca):** Verde Cargill escuro (`#005F40`), utilizado no cabeçalho do usuário, botões de ação prioritários e nos chips selecionados.
|
||||||
|
* **Cor Secundária (Textos e Títulos):** Preto carvão (`#1A1A1A`), oferecendo alto contraste para textos e números.
|
||||||
|
* **Cores de Status (Feedback Visual):**
|
||||||
|
* *Concluído/Sincronizado:* Verde folha (`#E8F5E9` para fundo, `#005F40` para ícone/texto).
|
||||||
|
* *Em Andamento:* Azul suave (`#E3F2FD` para fundo, `#1E88E5` para o indicador de progresso e badges).
|
||||||
|
* *Não Iniciado:* Tons de cinza médio (`#ECEFF1` / `#78909C`).
|
||||||
|
* **Tipografia:** Fonte Sans-Serif limpa e de alta legibilidade, com variações de peso (Bold para títulos de OS e contadores métricos, Medium para subtítulos e chips, Regular para prazos e descrições).
|
||||||
|
* **Formatos e Contornos:** Uso de cartões elevados (`Card` / `Surface`) com cantos arredondados generosos (`16.dp` a `24.dp`), sombras suaves (`shadow` / `elevation` baixa) e bordas finas para delimitação visual clara.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Descrição Detalhada dos Componentes da Tela Principal
|
||||||
|
|
||||||
|
A tela única atual ([`MaintenanceDashboardScreen.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt)) está estruturada verticalmente nas seguintes seções:
|
||||||
|
|
||||||
|
### 2.1. Barra Superior de Controle (App Bar)
|
||||||
|
* **Título:** `"Gestão OS"` alinhado à esquerda.
|
||||||
|
* **Indicador de Conectividade:** Um Box quadrado verde-claro com um ícone de nuvem (`Cloud`) verde escuro, demonstrando se o app está online e pareado.
|
||||||
|
* **Ação de Sincronismo:** Botão circular com ícone de setas giratórias (`Sync`) que rotaciona visualmente quando o processo assíncrono de sincronização bidirecional com o Google Sheets está ativo.
|
||||||
|
* **Painel de Usuário:** Card do Google Sign-In exibindo a foto do perfil (ou inicial do nome `"J"`), o nome do usuário (`"Jhony"`), o e-mail (`"cesarjhony@gmail.com"`) e uma seta indicativa de dropdown para logout ou troca de conta.
|
||||||
|
|
||||||
|
### 2.2. Painel de Métricas da Parada (KPI Dashboard)
|
||||||
|
* **Estrutura:** Card branco elevado com cantos arredondados contendo o título `"Progresso Parada Industrial"` e subtítulo `"Visão Geral de Campo"`.
|
||||||
|
* **Gráfico de Progresso Global:** Um indicador de progresso circular (`CircularProgressIndicator` verde) localizado no canto superior direito, exibindo a porcentagem de tarefas finalizadas (atualmente em `2%`).
|
||||||
|
* **Contadores de Metas (Grid de Indicadores):** Quatro colunas horizontais exibindo:
|
||||||
|
* `▶ 595` / *Não Inic.* (Cinza)
|
||||||
|
* `☁ 9` / *Em Andam.* (Azul)
|
||||||
|
* `✔ 13` / *Concluídas* (Verde)
|
||||||
|
* `🔧 617` / *Total OSs* (Preto)
|
||||||
|
|
||||||
|
### 2.3. Campo de Pesquisa Dinâmica
|
||||||
|
* **Design:** Caixa de texto de largura total, com cantos arredondados, ícone de lupa (`Search`) e placeholder `"Buscar por OS, descrição..."`.
|
||||||
|
* **Comportamento:** Filtra a lista instantaneamente enquanto o usuário digita.
|
||||||
|
|
||||||
|
### 2.4. Grade Modular de Filtros (Chips de Categoria)
|
||||||
|
O app organiza os filtros em 5 linhas horizontais com rolagem lateral (`LazyRow`). Cada categoria inicia com o chip `"Todos"` ou `"Todas"` ativo na cor verde escura:
|
||||||
|
1. **Setor:** Opções como `"Todos"`, `"COGERAÇÃO"`, `"EXTRAÇÃO"`, `"PREPARAÇÃO"`.
|
||||||
|
2. **Equipe:** Opções como `"Todas"`, `"Mecânica"`, `"Elétrica"`, `"Confiabilidade"`.
|
||||||
|
3. **Status:** Opções como `"Todos"`, `"Não iniciado"`, `"Em andamento"`, `"Concluído"`.
|
||||||
|
4. **Data:** Opções como `"Todas"`, `"04/08/26"`, `"08/08/26"`, `"09/08/26"`.
|
||||||
|
5. **Recurso (Técnico):** Opções como `"Todos"`, `"ADILSON"`, `"AGIL"`, `"ALAN"`, `"ALEX"`.
|
||||||
|
|
||||||
|
### 2.5. Cartão de Cronograma Geral do Projeto
|
||||||
|
* **Título:** `"Ordens de Serviço (617)"` acompanhado de um ícone de maximizar/redimensionar grade no canto direito.
|
||||||
|
* **Barra de Progresso:** Um indicador linear horizontal (`LinearProgressIndicator` azul) que marca visualmente `75%` de avanço (progresso temporal do cronograma da parada).
|
||||||
|
* **Prazos:** Subtexto detalhado mostrando a janela de execução (ex: `"Prazo: qui. 27/08/26 07:00 até qui. 27/08/26 17:00"`).
|
||||||
|
|
||||||
|
### 2.6. Lista de Cartões de Ordens de Serviço (OS Cards)
|
||||||
|
* **Visual da Linha:** Um card branco com contorno fino e espaçamento confortável.
|
||||||
|
* **Código e Sincronismo:** Identificador da OS (ex: `"OS-1019"`) seguido de um ícone de nuvem com check verde indicando pareamento perfeito com o banco central.
|
||||||
|
* **Badge de Status:** Um marcador com cor temática no canto superior direito (ex: `"Em andamento"` com fundo azul claro e texto azul escuro).
|
||||||
|
* **Subtexto:** Código do TAG/Equipamento (ex: `"CV-101001"`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Diretrizes para Adicionar Telas e Aumentar a Complexidade
|
||||||
|
|
||||||
|
Para expandir o aplicativo de sua estrutura atual de tela única ("Single Screen Dashboard") para um ecossistema multiplataforma robusto de campo, deve-se seguir as seguintes diretrizes de expansão:
|
||||||
|
|
||||||
|
```
|
||||||
|
[Fluxo de Navegação Sugerido]
|
||||||
|
|
||||||
|
+------------------------+
|
||||||
|
| Dashboard Principal | (Tela Atual)
|
||||||
|
+-----------+------------+
|
||||||
|
|
|
||||||
|
+---------------------+---------------------+
|
||||||
|
| (Clique na OS) | (Clique em Métricas/Analítico)
|
||||||
|
v v
|
||||||
|
+------------------------+ +------------------------+
|
||||||
|
| Detalhes da OS | | Dashboard Analítico M3 |
|
||||||
|
+--------+---------------+ +------------------------+
|
||||||
|
|
|
||||||
|
+---------------------+
|
||||||
|
| (Anexar Evidência) | (Ver Histórico)
|
||||||
|
v v
|
||||||
|
+-----------------+ +-----------------+
|
||||||
|
| Scanner & Foto | | Auditoria & |
|
||||||
|
| Real (CameraX) | | Timeline |
|
||||||
|
+-----------------+ +-----------------+
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.1. Proposta de Novas Telas
|
||||||
|
1. **Tela de Detalhes Aprofundados da OS (`OSDetailScreen`):**
|
||||||
|
* *Recurso:* Exibição de árvore de sub-tarefas (checklists de segurança, permissões de trabalho - PT).
|
||||||
|
* *Recurso:* Visualização e zoom de fotos anexadas em alta definição.
|
||||||
|
* *Recurso:* Lista de materiais e ferramentas necessárias separadas por equipe.
|
||||||
|
2. **Tela de Linha do Tempo e Auditoria Geral (`TimelineAuditoriaScreen`):**
|
||||||
|
* *Recurso:* Feed contínuo contendo todas as atualizações de todas as OSs efetuadas pelos técnicos em campo na parada atual, exibindo quem alterou, quando alterou, o que alterou (observações) e fotos vinculadas.
|
||||||
|
3. **Tela de Métricas Analíticas Avançadas (`AnalyticsScreen`):**
|
||||||
|
* *Recurso:* Gráficos de barra de produtividade por Equipe (ex: Mecânica concluiu X%, Elétrica concluiu Y%).
|
||||||
|
* *Recurso:* Gráfico de linha acumulado ("S-Curve") comparando o planejado com o realizado.
|
||||||
|
* *Recurso:* Gráfico de quebras (Pareto) listando os setores com maior número de anomalias relatadas nas observações.
|
||||||
|
4. **Tela de Configurações do Planejador PCM (`SettingsScreen`):**
|
||||||
|
* *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.
|
||||||
|
|
||||||
|
### 3.2. Proposta de Recursos Técnicos para Implementação Visando Complexidade
|
||||||
|
1. **Câmera Nativa com Upload Real (Google Drive):**
|
||||||
|
* Substituir o simulador de fotos estáticas (`mockPhotos`) por uma tela de captura utilizando **CameraX**.
|
||||||
|
* 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.
|
||||||
|
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.
|
||||||
@@ -82,16 +82,10 @@ Abaixo está o levantamento detalhado de cada um desses elementos, com suas resp
|
|||||||
|
|
||||||
## 5. Carga de Dados Inicial em Caso de Falha de Conexão (Fallback)
|
## 5. Carga de Dados Inicial em Caso de Falha de Conexão (Fallback)
|
||||||
|
|
||||||
* **Status:** **Simulado (Mock Data Fallback)**
|
* **Status:** **Removido**
|
||||||
* **Arquivos Relacionados:**
|
* **Arquivos Relacionados:**
|
||||||
* [`MaintenanceViewModel.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt) (linhas ~154-173)
|
* [`MaintenanceViewModel.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt)
|
||||||
* [`MaintenanceRepository.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt) (método `loadSampleData()`, linhas ~180-211)
|
* [`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:**
|
||||||
Durante a primeira inicialização do aplicativo, o sistema tenta sincronizar com a planilha do Google Sheets. Se a conexão falhar ou as credenciais forem inválidas, o ViewModel intercepta a falha e invoca a carga de dados de exemplo estáticos (`loadSampleData()`):
|
Anteriormente, o sistema realizava o carregamento automático de dados simulados/modelo (`loadSampleData()`) caso ocorresse uma falha na primeira sincronização com as planilhas do Google Sheets ou através de botões manuais na UI. Este mecanismo de fallback de dados fictícios foi removido do aplicativo.
|
||||||
```kotlin
|
* **Impacto/Limitação:** O aplicativo não popula mais dados simulados automaticamente ou sob demanda na base SQLite local, garantindo integridade estrita aos dados reais vindos das planilhas Google Sheets ou de importação manual do CSV real do PCM. Se a sincronização inicial falhar e o banco local estiver vazio, o aplicativo exibirá a falha de sincronização e manterá a listagem limpa.
|
||||||
// Safe offline fallback in case of no connectivity or invalid credentials
|
|
||||||
_syncStatusMessage.value = "Usando dados modelo: ${result.message}"
|
|
||||||
repository.loadSampleData()
|
|
||||||
```
|
|
||||||
Esses dados de modelo criam ordens de serviço simuladas (`OS-2`, `OS-5`, `OS-6`, `OS-8`, `OS-10`, `OS-11`, `OS-1024`, `OS-16`) diretamente no Room local para demonstração do aplicativo.
|
|
||||||
* **Impacto/Limitação:** O comportamento garante que o app não apareça em branco na primeira execução sem rede, mas introduz ordens de serviço fictícias que não estão cadastradas na planilha remota Google Sheets.
|
|
||||||
|
|||||||
Reference in New Issue
Block a user