Compare commits
10 Commits
7ad2c1b1b8
...
730fb15ff3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
730fb15ff3 | ||
|
|
ddc1969651 | ||
|
|
66cf59c132 | ||
|
|
0cb515353d | ||
|
|
fc08fd5bf7 | ||
|
|
23be28422d | ||
|
|
64a32e545a | ||
|
|
0d587a84e3 | ||
|
|
ee0c970cfa | ||
|
|
c2445065b1 |
@@ -120,6 +120,7 @@ dependencies {
|
|||||||
implementation(libs.moshi.kotlin)
|
implementation(libs.moshi.kotlin)
|
||||||
implementation(libs.okhttp)
|
implementation(libs.okhttp)
|
||||||
implementation(libs.google.auth.library.oauth2.http)
|
implementation(libs.google.auth.library.oauth2.http)
|
||||||
|
implementation(libs.play.services.auth)
|
||||||
// implementation(libs.play.services.location)
|
// implementation(libs.play.services.location)
|
||||||
implementation(libs.retrofit)
|
implementation(libs.retrofit)
|
||||||
testImplementation(libs.androidx.compose.ui.test.junit4)
|
testImplementation(libs.androidx.compose.ui.test.junit4)
|
||||||
@@ -140,4 +141,6 @@ dependencies {
|
|||||||
debugImplementation(libs.androidx.compose.ui.tooling)
|
debugImplementation(libs.androidx.compose.ui.tooling)
|
||||||
"ksp"(libs.androidx.room.compiler)
|
"ksp"(libs.androidx.room.compiler)
|
||||||
"ksp"(libs.moshi.kotlin.codegen)
|
"ksp"(libs.moshi.kotlin.codegen)
|
||||||
|
implementation(platform("com.google.firebase:firebase-bom:34.16.0"))
|
||||||
|
implementation("com.google.firebase:firebase-analytics")
|
||||||
}
|
}
|
||||||
|
|||||||
47
app/google-services.json
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"project_info": {
|
||||||
|
"project_number": "461441632355",
|
||||||
|
"project_id": "gestao-parada-os",
|
||||||
|
"storage_bucket": "gestao-parada-os.firebasestorage.app"
|
||||||
|
},
|
||||||
|
"client": [
|
||||||
|
{
|
||||||
|
"client_info": {
|
||||||
|
"mobilesdk_app_id": "1:461441632355:android:8ea9121be8cf81b4ee5056",
|
||||||
|
"android_client_info": {
|
||||||
|
"package_name": "com.aistudio.cargillparadaos.xvyzwt"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"oauth_client": [
|
||||||
|
{
|
||||||
|
"client_id": "461441632355-rg9go0tcsr8ora2la83aat9pcekqo13p.apps.googleusercontent.com",
|
||||||
|
"client_type": 1,
|
||||||
|
"android_info": {
|
||||||
|
"package_name": "com.aistudio.cargillparadaos.xvyzwt",
|
||||||
|
"certificate_hash": "6274d8aa0709c0454af47340ae8f223b8a0fbd61"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"client_id": "461441632355-dc85s9u8dctltfbounegv020qn5aj49d.apps.googleusercontent.com",
|
||||||
|
"client_type": 3
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"api_key": [
|
||||||
|
{
|
||||||
|
"current_key": "AIzaSyAB3uaasLqLgB-Ir5NvzUkVo6wSuQPQtTU"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"services": {
|
||||||
|
"appinvite_service": {
|
||||||
|
"other_platform_oauth_client": [
|
||||||
|
{
|
||||||
|
"client_id": "461441632355-dc85s9u8dctltfbounegv020qn5aj49d.apps.googleusercontent.com",
|
||||||
|
"client_type": 3
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"configuration_version": "1"
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@ import com.example.data.model.OSUpdateHistory
|
|||||||
|
|
||||||
@Database(
|
@Database(
|
||||||
entities = [MaintenanceActivity::class, OSUpdateHistory::class],
|
entities = [MaintenanceActivity::class, OSUpdateHistory::class],
|
||||||
version = 1,
|
version = 2,
|
||||||
exportSchema = false
|
exportSchema = false
|
||||||
)
|
)
|
||||||
abstract class AppDatabase : RoomDatabase() {
|
abstract class AppDatabase : RoomDatabase() {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ data class MaintenanceActivity(
|
|||||||
val descricao: String,
|
val descricao: String,
|
||||||
val setor: String,
|
val setor: String,
|
||||||
val equipe: String,
|
val equipe: String,
|
||||||
val responsavel: String,
|
val recurso: String,
|
||||||
val dataInicio: String,
|
val dataInicio: String,
|
||||||
val dataFim: String,
|
val dataFim: String,
|
||||||
val percentualExecucao: Int, // 0 to 100
|
val percentualExecucao: Int, // 0 to 100
|
||||||
@@ -45,9 +45,17 @@ data class OSUpdateHistory(
|
|||||||
val percentualNovo: Int,
|
val percentualNovo: Int,
|
||||||
val observacao: String? = null,
|
val observacao: String? = null,
|
||||||
val fotoPath: String? = null,
|
val fotoPath: String? = null,
|
||||||
val responsavel: String
|
val recurso: String,
|
||||||
|
val emailEditor: String? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
|
data class GoogleUser(
|
||||||
|
val email: String,
|
||||||
|
val displayName: String,
|
||||||
|
val photoUrl: String? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
fun extractDateOnly(dataStr: String): String {
|
fun extractDateOnly(dataStr: String): String {
|
||||||
val clean = dataStr.trim()
|
val clean = dataStr.trim()
|
||||||
if (clean == "N/A" || clean.isBlank()) return "N/A"
|
if (clean == "N/A" || clean.isBlank()) return "N/A"
|
||||||
|
|||||||
@@ -365,7 +365,11 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
|
|
||||||
// 8. Resumo: column mapping to filter service orders (only Resumo = Não)
|
// 8. Resumo: column mapping to filter service orders (only Resumo = Não)
|
||||||
val resumoIdx = headers.indexOfFirst {
|
val resumoIdx = headers.indexOfFirst {
|
||||||
it.contains("resumo")
|
it == "resumo"
|
||||||
|
}.let { idx ->
|
||||||
|
if (idx != -1) idx else headers.indexOfFirst {
|
||||||
|
it.contains("resumo") && !it.contains("nome") && !it.contains("tarefa")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.d(tag, "Mapped Column Indices: taskName=$taskNameIdx, group=$groupIdx, resource=$resourceIdx, inicio=$inicioIdx, fim=$fimIdx, outline=$outlineIdx, id=$idIdx, resumo=$resumoIdx")
|
Log.d(tag, "Mapped Column Indices: taskName=$taskNameIdx, group=$groupIdx, resource=$resourceIdx, inicio=$inicioIdx, fim=$fimIdx, outline=$outlineIdx, id=$idIdx, resumo=$resumoIdx")
|
||||||
@@ -428,7 +432,7 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
val equipe = if (rawEquipe.isNotBlank()) sanitizeEquipe(rawEquipe) else "Mecânica"
|
val equipe = if (rawEquipe.isNotBlank()) sanitizeEquipe(rawEquipe) else "Mecânica"
|
||||||
|
|
||||||
val rawResp = if (resourceIdx != -1 && resourceIdx < row.size) row[resourceIdx].trim() else ""
|
val rawResp = if (resourceIdx != -1 && resourceIdx < row.size) row[resourceIdx].trim() else ""
|
||||||
val responsavel = if (rawResp.isNotBlank()) rawResp else "Sem Responsável"
|
val recurso = if (rawResp.isNotBlank()) rawResp else "Sem Recurso"
|
||||||
|
|
||||||
val dataInicio = if (inicioIdx != -1 && inicioIdx < row.size) row[inicioIdx].trim() else "N/A"
|
val dataInicio = if (inicioIdx != -1 && inicioIdx < row.size) row[inicioIdx].trim() else "N/A"
|
||||||
val dataFim = if (fimIdx != -1 && fimIdx < row.size) row[fimIdx].trim() else "N/A"
|
val dataFim = if (fimIdx != -1 && fimIdx < row.size) row[fimIdx].trim() else "N/A"
|
||||||
@@ -439,7 +443,7 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
descricao = desc,
|
descricao = desc,
|
||||||
setor = setor,
|
setor = setor,
|
||||||
equipe = equipe,
|
equipe = equipe,
|
||||||
responsavel = responsavel,
|
recurso = recurso,
|
||||||
dataInicio = dataInicio,
|
dataInicio = dataInicio,
|
||||||
dataFim = dataFim,
|
dataFim = dataFim,
|
||||||
percentualExecucao = 0, // Determined later in repository by merging history logs
|
percentualExecucao = 0, // Determined later in repository by merging history logs
|
||||||
@@ -474,11 +478,11 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
*/
|
*/
|
||||||
fun fetchRemoteHistoryKeys(): Set<String> {
|
fun fetchRemoteHistoryKeys(): Set<String> {
|
||||||
val defaultHeaders = listOf(
|
val defaultHeaders = listOf(
|
||||||
"id", "numeroOs", "timestamp", "percentualAnterior", "percentualNovo", "observacao", "fotoPath", "responsavel"
|
"id", "numeroOs", "timestamp", "percentualAnterior", "percentualNovo", "observacao", "fotoPath", "responsavel", "email_editor"
|
||||||
)
|
)
|
||||||
ensureHeaders("history", defaultHeaders)
|
ensureHeaders("history", defaultHeaders)
|
||||||
|
|
||||||
val rows = fetchValues("history!A:H")
|
val rows = fetchValues("history!A:I")
|
||||||
val keys = mutableSetOf<String>()
|
val keys = mutableSetOf<String>()
|
||||||
if (rows.size <= 1) return keys
|
if (rows.size <= 1) return keys
|
||||||
|
|
||||||
@@ -507,11 +511,11 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
*/
|
*/
|
||||||
fun fetchRemoteHistoryList(): List<OSUpdateHistory> {
|
fun fetchRemoteHistoryList(): List<OSUpdateHistory> {
|
||||||
val defaultHeaders = listOf(
|
val defaultHeaders = listOf(
|
||||||
"id", "numeroOs", "timestamp", "percentualAnterior", "percentualNovo", "observacao", "fotoPath", "responsavel"
|
"id", "numeroOs", "timestamp", "percentualAnterior", "percentualNovo", "observacao", "fotoPath", "responsavel", "email_editor"
|
||||||
)
|
)
|
||||||
ensureHeaders("history", defaultHeaders)
|
ensureHeaders("history", defaultHeaders)
|
||||||
|
|
||||||
val rows = fetchValues("history!A:H")
|
val rows = fetchValues("history!A:I")
|
||||||
val historyList = mutableListOf<OSUpdateHistory>()
|
val historyList = mutableListOf<OSUpdateHistory>()
|
||||||
if (rows.size <= 1) return historyList
|
if (rows.size <= 1) return historyList
|
||||||
|
|
||||||
@@ -524,6 +528,7 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
val obsIdx = headers.indexOf("observacao")
|
val obsIdx = headers.indexOf("observacao")
|
||||||
val fotoIdx = headers.indexOf("fotopath")
|
val fotoIdx = headers.indexOf("fotopath")
|
||||||
val respIdx = headers.indexOf("responsavel")
|
val respIdx = headers.indexOf("responsavel")
|
||||||
|
val emailIdx = headers.indexOf("email_editor")
|
||||||
|
|
||||||
val getCell = { row: List<String>, mapIdx: Int, fallbackIdx: Int ->
|
val getCell = { row: List<String>, mapIdx: Int, fallbackIdx: Int ->
|
||||||
val idx = if (mapIdx != -1) mapIdx else fallbackIdx
|
val idx = if (mapIdx != -1) mapIdx else fallbackIdx
|
||||||
@@ -546,6 +551,7 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
val obs = getCell(row, obsIdx, 5).takeIf { it.isNotBlank() }
|
val obs = getCell(row, obsIdx, 5).takeIf { it.isNotBlank() }
|
||||||
val foto = getCell(row, fotoIdx, 6).takeIf { it.isNotBlank() }
|
val foto = getCell(row, fotoIdx, 6).takeIf { it.isNotBlank() }
|
||||||
val resp = getCell(row, respIdx, 7)
|
val resp = getCell(row, respIdx, 7)
|
||||||
|
val email = getCell(row, emailIdx, 8)
|
||||||
|
|
||||||
historyList.add(
|
historyList.add(
|
||||||
OSUpdateHistory(
|
OSUpdateHistory(
|
||||||
@@ -556,7 +562,8 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
percentualNovo = new,
|
percentualNovo = new,
|
||||||
observacao = obs,
|
observacao = obs,
|
||||||
fotoPath = foto,
|
fotoPath = foto,
|
||||||
responsavel = resp
|
recurso = resp,
|
||||||
|
emailEditor = email.takeIf { it.isNotBlank() }
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -578,13 +585,32 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
*/
|
*/
|
||||||
fun pushHistoryToSheet(historyToAppend: List<OSUpdateHistory>) {
|
fun pushHistoryToSheet(historyToAppend: List<OSUpdateHistory>) {
|
||||||
if (historyToAppend.isEmpty()) return
|
if (historyToAppend.isEmpty()) return
|
||||||
|
val defaultHeaders = listOf(
|
||||||
|
"id", "numeroOs", "timestamp", "percentualAnterior", "percentualNovo", "observacao", "fotoPath", "responsavel", "email_editor"
|
||||||
|
)
|
||||||
|
ensureHeaders("history", defaultHeaders)
|
||||||
|
|
||||||
|
// Self-heal/add the header row to column I if not present on Google Sheets yet
|
||||||
|
try {
|
||||||
|
val firstRow = fetchValues("history!A1:I1")
|
||||||
|
if (firstRow.isNotEmpty()) {
|
||||||
|
val headers = firstRow[0].map { it.trim().lowercase() }
|
||||||
|
if ("email_editor" !in headers) {
|
||||||
|
updateValues("history!I1", listOf(listOf("email_editor")))
|
||||||
|
Log.d(tag, "Self-healed 'email_editor' column header in remote sheet.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(tag, "Failed to self-heal 'email_editor' header in remote sheet.", e)
|
||||||
|
}
|
||||||
|
|
||||||
val headerIndices = mapOf(
|
val headerIndices = mapOf(
|
||||||
"id" to 0, "numeroos" to 1, "timestamp" to 2, "percentualanterior" to 3, "percentualnovo" to 4,
|
"id" to 0, "numeroos" to 1, "timestamp" to 2, "percentualanterior" to 3, "percentualnovo" to 4,
|
||||||
"observacao" to 5, "fotopath" to 6, "responsavel" to 7
|
"observacao" to 5, "fotopath" to 6, "responsavel" to 7, "email_editor" to 8
|
||||||
)
|
)
|
||||||
|
|
||||||
val appendRows = historyToAppend.map { history ->
|
val appendRows = historyToAppend.map { history ->
|
||||||
val row = MutableList(8) { "" }
|
val row = MutableList(9) { "" }
|
||||||
row[headerIndices["id"] ?: 0] = history.id.toString()
|
row[headerIndices["id"] ?: 0] = history.id.toString()
|
||||||
row[headerIndices["numeroos"] ?: 1] = history.numeroOs
|
row[headerIndices["numeroos"] ?: 1] = history.numeroOs
|
||||||
row[headerIndices["timestamp"] ?: 2] = history.timestamp.toString()
|
row[headerIndices["timestamp"] ?: 2] = history.timestamp.toString()
|
||||||
@@ -592,11 +618,12 @@ class GoogleSheetsSyncService(private val context: Context) {
|
|||||||
row[headerIndices["percentualnovo"] ?: 4] = history.percentualNovo.toString()
|
row[headerIndices["percentualnovo"] ?: 4] = history.percentualNovo.toString()
|
||||||
row[headerIndices["observacao"] ?: 5] = history.observacao ?: ""
|
row[headerIndices["observacao"] ?: 5] = history.observacao ?: ""
|
||||||
row[headerIndices["fotopath"] ?: 6] = history.fotoPath ?: ""
|
row[headerIndices["fotopath"] ?: 6] = history.fotoPath ?: ""
|
||||||
row[headerIndices["responsavel"] ?: 7] = history.responsavel
|
row[headerIndices["responsavel"] ?: 7] = history.recurso
|
||||||
|
row[headerIndices["email_editor"] ?: 8] = history.emailEditor ?: ""
|
||||||
row
|
row
|
||||||
}
|
}
|
||||||
|
|
||||||
appendValues("history!A:H", appendRows)
|
appendValues("history!A:I", appendRows)
|
||||||
Log.d(tag, "Successfully appended ${historyToAppend.size} logs to 'history' sheet.")
|
Log.d(tag, "Successfully appended ${historyToAppend.size} logs to 'history' sheet.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import android.net.Uri
|
|||||||
import com.example.data.local.MaintenanceDao
|
import com.example.data.local.MaintenanceDao
|
||||||
import com.example.data.model.MaintenanceActivity
|
import com.example.data.model.MaintenanceActivity
|
||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
|
import com.example.data.model.GoogleUser
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
@@ -33,7 +34,8 @@ class MaintenanceRepository(
|
|||||||
novoPercentual: Int,
|
novoPercentual: Int,
|
||||||
observacao: String?,
|
observacao: String?,
|
||||||
fotoPath: String?,
|
fotoPath: String?,
|
||||||
responsavel: String
|
recurso: String,
|
||||||
|
emailEditor: String?
|
||||||
) = withContext(Dispatchers.IO) {
|
) = withContext(Dispatchers.IO) {
|
||||||
val currentActivity = dao.getActivityByOsOneShot(numeroOs) ?: return@withContext
|
val currentActivity = dao.getActivityByOsOneShot(numeroOs) ?: return@withContext
|
||||||
|
|
||||||
@@ -54,11 +56,33 @@ class MaintenanceRepository(
|
|||||||
percentualNovo = novoPercentual,
|
percentualNovo = novoPercentual,
|
||||||
observacao = observacao,
|
observacao = observacao,
|
||||||
fotoPath = fotoPath,
|
fotoPath = fotoPath,
|
||||||
responsavel = responsavel
|
recurso = recurso,
|
||||||
|
emailEditor = emailEditor
|
||||||
)
|
)
|
||||||
dao.insertHistory(historyEntry)
|
dao.insertHistory(historyEntry)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Persist login state
|
||||||
|
fun getSavedUser(): GoogleUser? {
|
||||||
|
val prefs = context.getSharedPreferences("google_auth_prefs", Context.MODE_PRIVATE)
|
||||||
|
val email = prefs.getString("user_email", null) ?: return null
|
||||||
|
val name = prefs.getString("user_name", "") ?: ""
|
||||||
|
return GoogleUser(email, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveUser(user: GoogleUser) {
|
||||||
|
val prefs = context.getSharedPreferences("google_auth_prefs", Context.MODE_PRIVATE)
|
||||||
|
prefs.edit()
|
||||||
|
.putString("user_email", user.email)
|
||||||
|
.putString("user_name", user.displayName)
|
||||||
|
.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearSavedUser() {
|
||||||
|
val prefs = context.getSharedPreferences("google_auth_prefs", Context.MODE_PRIVATE)
|
||||||
|
prefs.edit().clear().apply()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parses an Excel CSV file from a Uri, supporting comma (,) or semicolon (;) separators,
|
* Parses an Excel CSV file from a Uri, supporting comma (,) or semicolon (;) separators,
|
||||||
* Portuguese headers, and auto-mapping columns.
|
* Portuguese headers, and auto-mapping columns.
|
||||||
@@ -117,7 +141,7 @@ class MaintenanceRepository(
|
|||||||
val desc = rowCells[descIdx]
|
val desc = rowCells[descIdx]
|
||||||
val setor = if (setorIdx != -1 && setorIdx < rowCells.size) rowCells[setorIdx] else "Geral"
|
val setor = if (setorIdx != -1 && setorIdx < rowCells.size) rowCells[setorIdx] else "Geral"
|
||||||
val equipe = if (eqIdx != -1 && eqIdx < rowCells.size) rowCells[eqIdx] else "Mecânica"
|
val equipe = if (eqIdx != -1 && eqIdx < rowCells.size) rowCells[eqIdx] else "Mecânica"
|
||||||
val responsavel = if (respIdx != -1 && respIdx < rowCells.size) rowCells[respIdx] else "Sem Responsável"
|
val recurso = if (respIdx != -1 && respIdx < rowCells.size) rowCells[respIdx] else "Sem Recurso"
|
||||||
val dataInicio = if (inicioIdx != -1 && inicioIdx < rowCells.size) rowCells[inicioIdx] else "N/A"
|
val dataInicio = if (inicioIdx != -1 && inicioIdx < rowCells.size) rowCells[inicioIdx] else "N/A"
|
||||||
val dataFim = if (fimIdx != -1 && fimIdx < rowCells.size) rowCells[fimIdx] else "N/A"
|
val dataFim = if (fimIdx != -1 && fimIdx < rowCells.size) rowCells[fimIdx] else "N/A"
|
||||||
val pctStr = if (pctIdx != -1 && pctIdx < rowCells.size) rowCells[pctIdx].replace("%", "").trim() else "0"
|
val pctStr = if (pctIdx != -1 && pctIdx < rowCells.size) rowCells[pctIdx].replace("%", "").trim() else "0"
|
||||||
@@ -129,7 +153,7 @@ class MaintenanceRepository(
|
|||||||
descricao = desc,
|
descricao = desc,
|
||||||
setor = sanitizeSetor(setor),
|
setor = sanitizeSetor(setor),
|
||||||
equipe = sanitizeEquipe(equipe),
|
equipe = sanitizeEquipe(equipe),
|
||||||
responsavel = responsavel,
|
recurso = recurso,
|
||||||
dataInicio = dataInicio,
|
dataInicio = dataInicio,
|
||||||
dataFim = dataFim,
|
dataFim = dataFim,
|
||||||
percentualExecucao = pct.coerceIn(0, 100),
|
percentualExecucao = pct.coerceIn(0, 100),
|
||||||
@@ -177,7 +201,8 @@ class MaintenanceRepository(
|
|||||||
percentualAnterior = 0,
|
percentualAnterior = 0,
|
||||||
percentualNovo = activity.percentualExecucao,
|
percentualNovo = activity.percentualExecucao,
|
||||||
observacao = activity.observacoes,
|
observacao = activity.observacoes,
|
||||||
responsavel = activity.responsavel,
|
recurso = activity.recurso,
|
||||||
|
emailEditor = "admin@cargill.com",
|
||||||
timestamp = now - 3600000 // 1 hour ago
|
timestamp = now - 3600000 // 1 hour ago
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -6,8 +6,13 @@ import androidx.activity.result.contract.ActivityResultContracts
|
|||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
import androidx.compose.animation.core.*
|
import androidx.compose.animation.core.*
|
||||||
import androidx.compose.foundation.BorderStroke
|
import androidx.compose.foundation.BorderStroke
|
||||||
|
import androidx.compose.foundation.Canvas
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import com.google.android.gms.auth.api.signin.GoogleSignIn
|
||||||
|
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
|
||||||
|
import com.google.android.gms.common.api.ApiException
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.foundation.layout.*
|
import androidx.compose.foundation.layout.*
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
@@ -67,7 +72,7 @@ fun MaintenanceDashboardScreen(
|
|||||||
val selectedEquipe by viewModel.selectedEquipe.collectAsStateWithLifecycle()
|
val selectedEquipe by viewModel.selectedEquipe.collectAsStateWithLifecycle()
|
||||||
val selectedStatus by viewModel.selectedStatus.collectAsStateWithLifecycle()
|
val selectedStatus by viewModel.selectedStatus.collectAsStateWithLifecycle()
|
||||||
val selectedDataInicio by viewModel.selectedDataInicio.collectAsStateWithLifecycle()
|
val selectedDataInicio by viewModel.selectedDataInicio.collectAsStateWithLifecycle()
|
||||||
val selectedResponsavel by viewModel.selectedResponsavel.collectAsStateWithLifecycle()
|
val selectedRecurso by viewModel.selectedRecurso.collectAsStateWithLifecycle()
|
||||||
val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()
|
val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
|
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
|
||||||
@@ -76,10 +81,50 @@ fun MaintenanceDashboardScreen(
|
|||||||
val internetAvailable by viewModel.internetAvailable.collectAsStateWithLifecycle()
|
val internetAvailable by viewModel.internetAvailable.collectAsStateWithLifecycle()
|
||||||
val selectedActivity by viewModel.selectedActivity.collectAsStateWithLifecycle()
|
val selectedActivity by viewModel.selectedActivity.collectAsStateWithLifecycle()
|
||||||
val selectedActivityHistory by viewModel.selectedActivityHistory.collectAsStateWithLifecycle()
|
val selectedActivityHistory by viewModel.selectedActivityHistory.collectAsStateWithLifecycle()
|
||||||
|
val currentUser by viewModel.currentUser.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
var showEditSheet by remember { mutableStateOf(false) }
|
var showEditSheet by remember { mutableStateOf(false) }
|
||||||
var showImporterSheet by remember { mutableStateOf(false) }
|
var showImporterSheet by remember { mutableStateOf(false) }
|
||||||
var isListExpanded by remember { mutableStateOf(false) }
|
var isListExpanded by remember { mutableStateOf(false) }
|
||||||
|
var showProfileDropdown by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
val gso = remember {
|
||||||
|
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
||||||
|
.requestEmail()
|
||||||
|
.requestProfile()
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
val googleSignInClient = remember { GoogleSignIn.getClient(context, gso) }
|
||||||
|
|
||||||
|
val googleSignInLauncher = rememberLauncherForActivityResult(
|
||||||
|
contract = ActivityResultContracts.StartActivityForResult()
|
||||||
|
) { result ->
|
||||||
|
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
|
||||||
|
try {
|
||||||
|
val account = task.getResult(ApiException::class.java)
|
||||||
|
if (account != null) {
|
||||||
|
val email = account.email ?: ""
|
||||||
|
val name = account.displayName ?: ""
|
||||||
|
viewModel.loginUser(email, name)
|
||||||
|
Toast.makeText(context, "Conectado como $name", Toast.LENGTH_SHORT).show()
|
||||||
|
} else {
|
||||||
|
Toast.makeText(context, "Erro ao obter dados da conta Google.", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
} catch (e: ApiException) {
|
||||||
|
val statusCode = e.statusCode
|
||||||
|
android.util.Log.e("GoogleSignIn", "Sign-in failed: status code = $statusCode", e)
|
||||||
|
Toast.makeText(context, "Falha no Google Sign-In (Erro $statusCode). Verifique a console de credenciais do Google.", Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
val lastAccount = GoogleSignIn.getLastSignedInAccount(context)
|
||||||
|
if (lastAccount != null) {
|
||||||
|
val email = lastAccount.email ?: ""
|
||||||
|
val name = lastAccount.displayName ?: ""
|
||||||
|
viewModel.loginUser(email, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val uniqueDates = remember(allActivities) {
|
val uniqueDates = remember(allActivities) {
|
||||||
val datesOnly = allActivities
|
val datesOnly = allActivities
|
||||||
@@ -101,9 +146,15 @@ fun MaintenanceDashboardScreen(
|
|||||||
listOf("Todas") + formattedDates
|
listOf("Todas") + formattedDates
|
||||||
}
|
}
|
||||||
|
|
||||||
val uniqueResponsibles = remember(allActivities) {
|
val uniqueRecursos = remember(allActivities) {
|
||||||
val resps = allActivities.map { it.responsavel }.filter { it.isNotBlank() && it != "Sem Responsável" && it != "Sem responsável" }.distinct().sorted()
|
val recs = allActivities.flatMap { activity ->
|
||||||
listOf("Todos") + resps
|
activity.recurso.split(";").map { it.trim() }
|
||||||
|
}.filter {
|
||||||
|
it.isNotBlank() &&
|
||||||
|
it != "Sem Responsável" && it != "Sem responsável" &&
|
||||||
|
it != "Sem Recurso" && it != "Sem recurso"
|
||||||
|
}.distinct().sorted()
|
||||||
|
listOf("Todos") + recs
|
||||||
}
|
}
|
||||||
|
|
||||||
val uniqueSectors = remember(allActivities) {
|
val uniqueSectors = remember(allActivities) {
|
||||||
@@ -146,44 +197,30 @@ fun MaintenanceDashboardScreen(
|
|||||||
topBar = {
|
topBar = {
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
title = {
|
title = {
|
||||||
Row(
|
Text(
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
text = "Gestão OS",
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
style = MaterialTheme.typography.titleLarge.copy(
|
||||||
) {
|
fontWeight = FontWeight.Bold,
|
||||||
CargillLogo(lightMode = true)
|
color = CargillBlack
|
||||||
Text(
|
|
||||||
text = "Paradas",
|
|
||||||
style = MaterialTheme.typography.titleLarge.copy(
|
|
||||||
fontWeight = FontWeight.Bold,
|
|
||||||
color = CargillBlack
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
}
|
)
|
||||||
},
|
},
|
||||||
actions = {
|
actions = {
|
||||||
// Connection Status Simulator
|
// Connection Status Indicator (Online/Updated)
|
||||||
Row(
|
Box(
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
contentAlignment = Alignment.Center,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.padding(end = 8.dp)
|
.padding(end = 8.dp)
|
||||||
.clip(RoundedCornerShape(8.dp))
|
.clip(RoundedCornerShape(8.dp))
|
||||||
.background(if (internetAvailable) Color(0xFFE8F5E9) else Color(0xFFECEFF1))
|
.background(if (internetAvailable) Color(0xFFE8F5E9) else Color(0xFFECEFF1))
|
||||||
.clickable { viewModel.toggleInternet(!internetAvailable) }
|
.padding(8.dp)
|
||||||
.padding(horizontal = 8.dp, vertical = 4.dp)
|
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = if (internetAvailable) Icons.Default.Cloud else Icons.Default.CloudOff,
|
imageVector = if (internetAvailable) Icons.Default.Cloud else Icons.Default.CloudOff,
|
||||||
contentDescription = "Estado de Rede",
|
contentDescription = "Online Atualizado",
|
||||||
tint = if (internetAvailable) CargillGreen else StatusGrey,
|
tint = if (internetAvailable) CargillGreen else StatusGrey,
|
||||||
modifier = Modifier.size(18.dp)
|
modifier = Modifier.size(18.dp)
|
||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(4.dp))
|
|
||||||
Text(
|
|
||||||
text = if (internetAvailable) "ONLINE" else "OFFLINE",
|
|
||||||
fontSize = 11.sp,
|
|
||||||
fontWeight = FontWeight.Bold,
|
|
||||||
color = if (internetAvailable) CargillGreen else StatusGrey
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sync button with animation
|
// Sync button with animation
|
||||||
@@ -209,6 +246,108 @@ fun MaintenanceDashboardScreen(
|
|||||||
modifier = Modifier.rotate(if (isSyncing) angle else 0f)
|
modifier = Modifier.rotate(if (isSyncing) angle else 0f)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
|
||||||
|
if (currentUser == null) {
|
||||||
|
Button(
|
||||||
|
onClick = { googleSignInLauncher.launch(googleSignInClient.signInIntent) },
|
||||||
|
colors = ButtonDefaults.buttonColors(
|
||||||
|
containerColor = Color.White,
|
||||||
|
contentColor = Color(0xFF3C4043)
|
||||||
|
),
|
||||||
|
elevation = ButtonDefaults.buttonElevation(defaultElevation = 1.dp),
|
||||||
|
shape = RoundedCornerShape(20.dp),
|
||||||
|
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 6.dp),
|
||||||
|
border = BorderStroke(1.dp, Color(0xFFDADCE0)),
|
||||||
|
modifier = Modifier
|
||||||
|
.height(36.dp)
|
||||||
|
.testTag("google_login_button")
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp)
|
||||||
|
) {
|
||||||
|
GoogleIcon()
|
||||||
|
Text(
|
||||||
|
text = "Entrar",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
fontWeight = FontWeight.Medium
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Box {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier
|
||||||
|
.clip(RoundedCornerShape(20.dp))
|
||||||
|
.background(Color(0xFFF1F3F4))
|
||||||
|
.clickable { showProfileDropdown = true }
|
||||||
|
.padding(horizontal = 8.dp, vertical = 4.dp)
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(24.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(CargillGreen),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = (currentUser!!.displayName.firstOrNull() ?: 'U').uppercaseChar().toString(),
|
||||||
|
color = Color.White,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
fontSize = 11.sp
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(modifier = Modifier.width(6.dp))
|
||||||
|
Column {
|
||||||
|
Text(
|
||||||
|
text = currentUser!!.displayName.substringBefore(" "),
|
||||||
|
fontSize = 10.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = CargillBlack
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = currentUser!!.email,
|
||||||
|
fontSize = 8.sp,
|
||||||
|
color = StatusGrey
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(modifier = Modifier.width(2.dp))
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.ArrowDropDown,
|
||||||
|
contentDescription = "Menu de Usuário",
|
||||||
|
tint = CargillBlack,
|
||||||
|
modifier = Modifier.size(16.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
DropdownMenu(
|
||||||
|
expanded = showProfileDropdown,
|
||||||
|
onDismissRequest = { showProfileDropdown = false },
|
||||||
|
modifier = Modifier.background(Color.White)
|
||||||
|
) {
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Desconectar do Google", color = Color.Red) },
|
||||||
|
leadingIcon = {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.ExitToApp,
|
||||||
|
contentDescription = "Desconectar",
|
||||||
|
tint = Color.Red
|
||||||
|
)
|
||||||
|
},
|
||||||
|
onClick = {
|
||||||
|
showProfileDropdown = false
|
||||||
|
googleSignInClient.signOut().addOnCompleteListener {
|
||||||
|
viewModel.logoutUser()
|
||||||
|
Toast.makeText(context, "Sessão encerrada", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
colors = TopAppBarDefaults.topAppBarColors(
|
colors = TopAppBarDefaults.topAppBarColors(
|
||||||
containerColor = Color.White
|
containerColor = Color.White
|
||||||
@@ -269,15 +408,15 @@ fun MaintenanceDashboardScreen(
|
|||||||
selectedEquipe = selectedEquipe,
|
selectedEquipe = selectedEquipe,
|
||||||
selectedStatus = selectedStatus,
|
selectedStatus = selectedStatus,
|
||||||
selectedDataInicio = selectedDataInicio,
|
selectedDataInicio = selectedDataInicio,
|
||||||
selectedResponsavel = selectedResponsavel,
|
selectedRecurso = selectedRecurso,
|
||||||
uniqueSectors = uniqueSectors,
|
uniqueSectors = uniqueSectors,
|
||||||
uniqueDates = uniqueDates,
|
uniqueDates = uniqueDates,
|
||||||
uniqueResponsibles = uniqueResponsibles,
|
uniqueRecursos = uniqueRecursos,
|
||||||
onSetorSelected = { viewModel.setFilterSetor(it) },
|
onSetorSelected = { viewModel.setFilterSetor(it) },
|
||||||
onEquipeSelected = { viewModel.setFilterEquipe(it) },
|
onEquipeSelected = { viewModel.setFilterEquipe(it) },
|
||||||
onStatusSelected = { viewModel.setFilterStatus(it) },
|
onStatusSelected = { viewModel.setFilterStatus(it) },
|
||||||
onDataInicioSelected = { viewModel.setFilterDataInicio(it) },
|
onDataInicioSelected = { viewModel.setFilterDataInicio(it) },
|
||||||
onResponsavelSelected = { viewModel.setFilterResponsavel(it) }
|
onRecursoSelected = { viewModel.setFilterRecurso(it) }
|
||||||
)
|
)
|
||||||
|
|
||||||
// List Title and Item Count
|
// List Title and Item Count
|
||||||
@@ -357,7 +496,7 @@ fun MaintenanceDashboardScreen(
|
|||||||
viewModel.setFilterEquipe("Todas")
|
viewModel.setFilterEquipe("Todas")
|
||||||
viewModel.setFilterStatus("Todos")
|
viewModel.setFilterStatus("Todos")
|
||||||
viewModel.setFilterDataInicio("Todas")
|
viewModel.setFilterDataInicio("Todas")
|
||||||
viewModel.setFilterResponsavel("Todos")
|
viewModel.setFilterRecurso("Todos")
|
||||||
viewModel.setSearchQuery("")
|
viewModel.setSearchQuery("")
|
||||||
},
|
},
|
||||||
colors = ButtonDefaults.buttonColors(containerColor = CargillBlack)
|
colors = ButtonDefaults.buttonColors(containerColor = CargillBlack)
|
||||||
@@ -388,6 +527,7 @@ fun MaintenanceDashboardScreen(
|
|||||||
EditActivityBottomSheet(
|
EditActivityBottomSheet(
|
||||||
activity = selectedActivity!!,
|
activity = selectedActivity!!,
|
||||||
history = selectedActivityHistory,
|
history = selectedActivityHistory,
|
||||||
|
currentUser = currentUser,
|
||||||
onDismiss = {
|
onDismiss = {
|
||||||
showEditSheet = false
|
showEditSheet = false
|
||||||
viewModel.selectActivity(null)
|
viewModel.selectActivity(null)
|
||||||
@@ -398,12 +538,18 @@ fun MaintenanceDashboardScreen(
|
|||||||
novoPercentual = newPct,
|
novoPercentual = newPct,
|
||||||
observacao = comment,
|
observacao = comment,
|
||||||
fotoPath = mockPhoto,
|
fotoPath = mockPhoto,
|
||||||
responsavel = "Encarregado Campo"
|
recurso = currentUser?.displayName ?: "Encarregado Campo",
|
||||||
|
emailEditor = currentUser?.email
|
||||||
)
|
)
|
||||||
|
},
|
||||||
|
onGoogleLoginClick = {
|
||||||
|
googleSignInLauncher.launch(googleSignInClient.signInIntent)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// CSV Importer Utility Sheet
|
// CSV Importer Utility Sheet
|
||||||
if (showImporterSheet) {
|
if (showImporterSheet) {
|
||||||
ImporterConsoleSheet(
|
ImporterConsoleSheet(
|
||||||
@@ -540,15 +686,15 @@ fun FilterPillsRow(
|
|||||||
selectedEquipe: String,
|
selectedEquipe: String,
|
||||||
selectedStatus: String,
|
selectedStatus: String,
|
||||||
selectedDataInicio: String,
|
selectedDataInicio: String,
|
||||||
selectedResponsavel: String,
|
selectedRecurso: String,
|
||||||
uniqueSectors: List<String>,
|
uniqueSectors: List<String>,
|
||||||
uniqueDates: List<String>,
|
uniqueDates: List<String>,
|
||||||
uniqueResponsibles: List<String>,
|
uniqueRecursos: List<String>,
|
||||||
onSetorSelected: (String) -> Unit,
|
onSetorSelected: (String) -> Unit,
|
||||||
onEquipeSelected: (String) -> Unit,
|
onEquipeSelected: (String) -> Unit,
|
||||||
onStatusSelected: (String) -> Unit,
|
onStatusSelected: (String) -> Unit,
|
||||||
onDataInicioSelected: (String) -> Unit,
|
onDataInicioSelected: (String) -> Unit,
|
||||||
onResponsavelSelected: (String) -> Unit
|
onRecursoSelected: (String) -> Unit
|
||||||
) {
|
) {
|
||||||
val setores = uniqueSectors
|
val setores = uniqueSectors
|
||||||
val equipes = listOf("Todas", "Mecânica", "Elétrica", "Confiabilidade", "Lubrificação")
|
val equipes = listOf("Todas", "Mecânica", "Elétrica", "Confiabilidade", "Lubrificação")
|
||||||
@@ -616,16 +762,16 @@ fun FilterPillsRow(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Responsible Row
|
// Resource Row
|
||||||
Row(modifier = Modifier.padding(horizontal = 16.dp)) {
|
Row(modifier = Modifier.padding(horizontal = 16.dp)) {
|
||||||
Text("Resp.:", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = StatusGrey, modifier = Modifier.width(72.dp).align(Alignment.CenterVertically))
|
Text("Recurso:", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = StatusGrey, modifier = Modifier.width(72.dp).align(Alignment.CenterVertically))
|
||||||
LazyRow(
|
LazyRow(
|
||||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
modifier = Modifier.fillMaxWidth()
|
modifier = Modifier.fillMaxWidth()
|
||||||
) {
|
) {
|
||||||
items(uniqueResponsibles) { respVal ->
|
items(uniqueRecursos) { respVal ->
|
||||||
val isSelected = respVal == selectedResponsavel
|
val isSelected = respVal == selectedRecurso
|
||||||
FilterChipWidget(text = respVal, isSelected = isSelected, onClick = { onResponsavelSelected(respVal) })
|
FilterChipWidget(text = respVal, isSelected = isSelected, onClick = { onRecursoSelected(respVal) })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -796,9 +942,9 @@ fun OSListItemCard(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Responsible Supervisor Initials / Name
|
// Resource Names
|
||||||
Text(
|
Text(
|
||||||
text = "Resp: ${activity.responsavel}",
|
text = "Recurso: ${activity.recurso}",
|
||||||
fontSize = 11.sp,
|
fontSize = 11.sp,
|
||||||
color = StatusGrey,
|
color = StatusGrey,
|
||||||
fontWeight = FontWeight.Medium
|
fontWeight = FontWeight.Medium
|
||||||
@@ -874,8 +1020,10 @@ fun OSListItemCard(
|
|||||||
fun EditActivityBottomSheet(
|
fun EditActivityBottomSheet(
|
||||||
activity: MaintenanceActivity,
|
activity: MaintenanceActivity,
|
||||||
history: List<OSUpdateHistory>,
|
history: List<OSUpdateHistory>,
|
||||||
|
currentUser: com.example.data.model.GoogleUser?,
|
||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onUpdateProgress: (Int, String, String?) -> Unit
|
onUpdateProgress: (Int, String, String?) -> Unit,
|
||||||
|
onGoogleLoginClick: () -> Unit
|
||||||
) {
|
) {
|
||||||
ModalBottomSheet(
|
ModalBottomSheet(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
@@ -945,7 +1093,7 @@ fun EditActivityBottomSheet(
|
|||||||
Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||||
Text("Setor: ${activity.setor}", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = CargillGreen)
|
Text("Setor: ${activity.setor}", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = CargillGreen)
|
||||||
Text("Equipe: ${activity.equipe}", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = StatusBlue)
|
Text("Equipe: ${activity.equipe}", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = StatusBlue)
|
||||||
Text("Resp: ${activity.responsavel}", fontSize = 11.sp, color = StatusGrey)
|
Text("Recurso: ${activity.recurso}", fontSize = 11.sp, color = StatusGrey)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -979,7 +1127,8 @@ fun EditActivityBottomSheet(
|
|||||||
colors = SliderDefaults.colors(
|
colors = SliderDefaults.colors(
|
||||||
thumbColor = if (progressValue >= 100) CargillGreen else StatusBlue,
|
thumbColor = if (progressValue >= 100) CargillGreen else StatusBlue,
|
||||||
activeTrackColor = if (progressValue >= 100) CargillGreen else StatusBlue
|
activeTrackColor = if (progressValue >= 100) CargillGreen else StatusBlue
|
||||||
)
|
),
|
||||||
|
enabled = currentUser != null
|
||||||
)
|
)
|
||||||
|
|
||||||
// Quick jump buttons for field speed
|
// Quick jump buttons for field speed
|
||||||
@@ -991,7 +1140,8 @@ fun EditActivityBottomSheet(
|
|||||||
onClick = { progressValue = 0f },
|
onClick = { progressValue = 0f },
|
||||||
modifier = Modifier.weight(1f).height(36.dp),
|
modifier = Modifier.weight(1f).height(36.dp),
|
||||||
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFECEFF1)),
|
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFECEFF1)),
|
||||||
contentPadding = PaddingValues(0.dp)
|
contentPadding = PaddingValues(0.dp),
|
||||||
|
enabled = currentUser != null
|
||||||
) {
|
) {
|
||||||
Text("0% (Zerar)", color = StatusGrey, fontSize = 11.sp, fontWeight = FontWeight.Bold)
|
Text("0% (Zerar)", color = StatusGrey, fontSize = 11.sp, fontWeight = FontWeight.Bold)
|
||||||
}
|
}
|
||||||
@@ -999,7 +1149,8 @@ fun EditActivityBottomSheet(
|
|||||||
onClick = { progressValue = 50f },
|
onClick = { progressValue = 50f },
|
||||||
modifier = Modifier.weight(1f).height(36.dp),
|
modifier = Modifier.weight(1f).height(36.dp),
|
||||||
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFE3F2FD)),
|
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFE3F2FD)),
|
||||||
contentPadding = PaddingValues(0.dp)
|
contentPadding = PaddingValues(0.dp),
|
||||||
|
enabled = currentUser != null
|
||||||
) {
|
) {
|
||||||
Text("50% (Metade)", color = StatusBlue, fontSize = 11.sp, fontWeight = FontWeight.Bold)
|
Text("50% (Metade)", color = StatusBlue, fontSize = 11.sp, fontWeight = FontWeight.Bold)
|
||||||
}
|
}
|
||||||
@@ -1007,7 +1158,8 @@ fun EditActivityBottomSheet(
|
|||||||
onClick = { progressValue = 100f },
|
onClick = { progressValue = 100f },
|
||||||
modifier = Modifier.weight(1f).height(36.dp),
|
modifier = Modifier.weight(1f).height(36.dp),
|
||||||
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFE8F5E9)),
|
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFE8F5E9)),
|
||||||
contentPadding = PaddingValues(0.dp)
|
contentPadding = PaddingValues(0.dp),
|
||||||
|
enabled = currentUser != null
|
||||||
) {
|
) {
|
||||||
Text("100% (Concluir)", color = CargillGreen, fontSize = 11.sp, fontWeight = FontWeight.Bold)
|
Text("100% (Concluir)", color = CargillGreen, fontSize = 11.sp, fontWeight = FontWeight.Bold)
|
||||||
}
|
}
|
||||||
@@ -1031,7 +1183,8 @@ fun EditActivityBottomSheet(
|
|||||||
.height(80.dp)
|
.height(80.dp)
|
||||||
.testTag("os_notes_field"),
|
.testTag("os_notes_field"),
|
||||||
maxLines = 3,
|
maxLines = 3,
|
||||||
shape = RoundedCornerShape(8.dp)
|
shape = RoundedCornerShape(8.dp),
|
||||||
|
enabled = currentUser != null
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1056,7 +1209,7 @@ fun EditActivityBottomSheet(
|
|||||||
items(mockPhotos) { (label, mockName) ->
|
items(mockPhotos) { (label, mockName) ->
|
||||||
val isSelected = selectedMockPhotoPath == mockName
|
val isSelected = selectedMockPhotoPath == mockName
|
||||||
Surface(
|
Surface(
|
||||||
onClick = { selectedMockPhotoPath = if (isSelected) null else mockName },
|
onClick = { if (currentUser != null) selectedMockPhotoPath = if (isSelected) null else mockName },
|
||||||
shape = RoundedCornerShape(8.dp),
|
shape = RoundedCornerShape(8.dp),
|
||||||
color = if (isSelected) Color(0xFFE8F5E9) else Color(0xFFF5F5F5),
|
color = if (isSelected) Color(0xFFE8F5E9) else Color(0xFFF5F5F5),
|
||||||
border = BorderStroke(1.dp, if (isSelected) CargillGreen else Color(0xFFE0E0E0)),
|
border = BorderStroke(1.dp, if (isSelected) CargillGreen else Color(0xFFE0E0E0)),
|
||||||
@@ -1110,23 +1263,72 @@ fun EditActivityBottomSheet(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save Action Button
|
// Save Action Button or Google Login Warning Banner
|
||||||
Button(
|
if (currentUser == null) {
|
||||||
onClick = {
|
Card(
|
||||||
isSubmitting = true
|
colors = CardDefaults.cardColors(containerColor = Color(0xFFFCE8E6)),
|
||||||
onUpdateProgress(progressValue.toInt(), observationText, selectedMockPhotoPath)
|
border = BorderStroke(1.dp, Color(0xFFFAD2CF)),
|
||||||
onDismiss()
|
shape = RoundedCornerShape(8.dp),
|
||||||
},
|
modifier = Modifier.fillMaxWidth()
|
||||||
modifier = Modifier
|
) {
|
||||||
.fillMaxWidth()
|
Row(
|
||||||
.height(48.dp)
|
modifier = Modifier.padding(12.dp),
|
||||||
.testTag("save_progress_button"),
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
colors = ButtonDefaults.buttonColors(containerColor = CargillGreen),
|
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||||
shape = RoundedCornerShape(10.dp)
|
) {
|
||||||
) {
|
Icon(
|
||||||
Icon(Icons.Default.Save, contentDescription = "Salvar")
|
imageVector = Icons.Default.Lock,
|
||||||
Spacer(modifier = Modifier.width(6.dp))
|
contentDescription = "Acesso Restrito",
|
||||||
Text("Salvar Atualizações (Salva Local Offline)", fontWeight = FontWeight.Black)
|
tint = Color(0xFFC5221F),
|
||||||
|
modifier = Modifier.size(24.dp)
|
||||||
|
)
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = "Acesso Restrito",
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
fontSize = 13.sp,
|
||||||
|
color = Color(0xFFC5221F)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Você precisa fazer login com sua conta do Google para atualizar o progresso de qualquer OS.",
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = Color(0xFFC5221F)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = onGoogleLoginClick,
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(48.dp)
|
||||||
|
.testTag("save_progress_button_disabled"),
|
||||||
|
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF4285F4)),
|
||||||
|
shape = RoundedCornerShape(10.dp)
|
||||||
|
) {
|
||||||
|
GoogleIcon(modifier = Modifier.size(18.dp))
|
||||||
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
Text("Conectar com o Google", fontWeight = FontWeight.Bold, color = Color.White)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
isSubmitting = true
|
||||||
|
onUpdateProgress(progressValue.toInt(), observationText, selectedMockPhotoPath)
|
||||||
|
onDismiss()
|
||||||
|
},
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(48.dp)
|
||||||
|
.testTag("save_progress_button"),
|
||||||
|
colors = ButtonDefaults.buttonColors(containerColor = CargillGreen),
|
||||||
|
shape = RoundedCornerShape(10.dp)
|
||||||
|
) {
|
||||||
|
Icon(Icons.Default.Save, contentDescription = "Salvar")
|
||||||
|
Spacer(modifier = Modifier.width(6.dp))
|
||||||
|
Text("Salvar Atualizações (Salva Local Offline)", fontWeight = FontWeight.Black)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chronological Audit Timeline Log / History Section
|
// Chronological Audit Timeline Log / History Section
|
||||||
@@ -1196,7 +1398,7 @@ fun TimelineLogItem(log: OSUpdateHistory) {
|
|||||||
) {
|
) {
|
||||||
Icon(Icons.Default.Person, contentDescription = "Usuário", tint = StatusGrey, modifier = Modifier.size(12.dp))
|
Icon(Icons.Default.Person, contentDescription = "Usuário", tint = StatusGrey, modifier = Modifier.size(12.dp))
|
||||||
Text(
|
Text(
|
||||||
text = log.responsavel,
|
text = log.recurso,
|
||||||
fontSize = 11.sp,
|
fontSize = 11.sp,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
color = CargillBlack
|
color = CargillBlack
|
||||||
@@ -1330,7 +1532,7 @@ fun ImporterConsoleSheet(
|
|||||||
) {
|
) {
|
||||||
Text("Estrutura Esperada do Arquivo (Excel):", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = CargillBlack)
|
Text("Estrutura Esperada do Arquivo (Excel):", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = CargillBlack)
|
||||||
Text("• Colunas Obrigatórias: Número da OS, Descrição da Atividade", fontSize = 11.sp, color = StatusGrey)
|
Text("• Colunas Obrigatórias: Número da OS, Descrição da Atividade", fontSize = 11.sp, color = StatusGrey)
|
||||||
Text("• Colunas Opcionais: Setor, Equipe, Responsável, Início, Fim, %", fontSize = 11.sp, color = StatusGrey)
|
Text("• Colunas Opcionais: Setor, Equipe, Recurso, Início, Fim, %", fontSize = 11.sp, color = StatusGrey)
|
||||||
Text("• Suporta separadores por Vírgula (,) ou Ponto e Vírgula (;)", fontSize = 11.sp, color = StatusGrey)
|
Text("• Suporta separadores por Vírgula (,) ou Ponto e Vírgula (;)", fontSize = 11.sp, color = StatusGrey)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1379,3 +1581,56 @@ fun ImporterConsoleSheet(
|
|||||||
// Extension to allow custom vertical scrolling on the BottomSheet contents
|
// Extension to allow custom vertical scrolling on the BottomSheet contents
|
||||||
@Composable
|
@Composable
|
||||||
fun rememberScrollState() = androidx.compose.foundation.rememberScrollState()
|
fun rememberScrollState() = androidx.compose.foundation.rememberScrollState()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun GoogleIcon(modifier: Modifier = Modifier.size(16.dp)) {
|
||||||
|
androidx.compose.foundation.Canvas(modifier = modifier) {
|
||||||
|
val sizePx = size.minDimension
|
||||||
|
val strokeWidth = sizePx * 0.18f
|
||||||
|
val r = sizePx / 2
|
||||||
|
|
||||||
|
val blue = Color(0xFF4285F4)
|
||||||
|
val green = Color(0xFF34A853)
|
||||||
|
val yellow = Color(0xFFFBBC05)
|
||||||
|
val red = Color(0xFFEA4335)
|
||||||
|
|
||||||
|
drawArc(
|
||||||
|
color = red,
|
||||||
|
startAngle = 180f,
|
||||||
|
sweepAngle = 140f,
|
||||||
|
useCenter = false,
|
||||||
|
style = androidx.compose.ui.graphics.drawscope.Stroke(width = strokeWidth)
|
||||||
|
)
|
||||||
|
drawArc(
|
||||||
|
color = yellow,
|
||||||
|
startAngle = 140f,
|
||||||
|
sweepAngle = 40f,
|
||||||
|
useCenter = false,
|
||||||
|
style = androidx.compose.ui.graphics.drawscope.Stroke(width = strokeWidth)
|
||||||
|
)
|
||||||
|
drawArc(
|
||||||
|
color = green,
|
||||||
|
startAngle = 0f,
|
||||||
|
sweepAngle = 140f,
|
||||||
|
useCenter = false,
|
||||||
|
style = androidx.compose.ui.graphics.drawscope.Stroke(width = strokeWidth)
|
||||||
|
)
|
||||||
|
drawArc(
|
||||||
|
color = blue,
|
||||||
|
startAngle = 320f,
|
||||||
|
sweepAngle = 40f,
|
||||||
|
useCenter = false,
|
||||||
|
style = androidx.compose.ui.graphics.drawscope.Stroke(width = strokeWidth)
|
||||||
|
)
|
||||||
|
|
||||||
|
val barLength = r * 0.9f
|
||||||
|
drawLine(
|
||||||
|
color = blue,
|
||||||
|
start = center,
|
||||||
|
end = center.copy(x = center.x + barLength),
|
||||||
|
strokeWidth = strokeWidth
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -39,12 +39,16 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
private val _selectedDataInicio = MutableStateFlow("Todas")
|
private val _selectedDataInicio = MutableStateFlow("Todas")
|
||||||
val selectedDataInicio = _selectedDataInicio.asStateFlow()
|
val selectedDataInicio = _selectedDataInicio.asStateFlow()
|
||||||
|
|
||||||
private val _selectedResponsavel = MutableStateFlow("Todos")
|
private val _selectedRecurso = MutableStateFlow("Todos")
|
||||||
val selectedResponsavel = _selectedResponsavel.asStateFlow()
|
val selectedRecurso = _selectedRecurso.asStateFlow()
|
||||||
|
|
||||||
private val _searchQuery = MutableStateFlow("")
|
private val _searchQuery = MutableStateFlow("")
|
||||||
val searchQuery = _searchQuery.asStateFlow()
|
val searchQuery = _searchQuery.asStateFlow()
|
||||||
|
|
||||||
|
// Google User authentication state
|
||||||
|
private val _currentUser = MutableStateFlow<com.example.data.model.GoogleUser?>(null)
|
||||||
|
val currentUser = _currentUser.asStateFlow()
|
||||||
|
|
||||||
// UI Operation States
|
// UI Operation States
|
||||||
private val _isSyncing = MutableStateFlow(false)
|
private val _isSyncing = MutableStateFlow(false)
|
||||||
val isSyncing = _isSyncing.asStateFlow()
|
val isSyncing = _isSyncing.asStateFlow()
|
||||||
@@ -78,7 +82,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
_selectedEquipe,
|
_selectedEquipe,
|
||||||
_selectedStatus,
|
_selectedStatus,
|
||||||
_selectedDataInicio,
|
_selectedDataInicio,
|
||||||
_selectedResponsavel,
|
_selectedRecurso,
|
||||||
_searchQuery
|
_searchQuery
|
||||||
) { flowsArray ->
|
) { flowsArray ->
|
||||||
@Suppress("UNCHECKED_CAST")
|
@Suppress("UNCHECKED_CAST")
|
||||||
@@ -87,7 +91,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
val equipe = flowsArray[2] as String
|
val equipe = flowsArray[2] as String
|
||||||
val status = flowsArray[3] as String
|
val status = flowsArray[3] as String
|
||||||
val dataInicio = flowsArray[4] as String
|
val dataInicio = flowsArray[4] as String
|
||||||
val responsavel = flowsArray[5] as String
|
val recurso = flowsArray[5] as String
|
||||||
val query = flowsArray[6] as String
|
val query = flowsArray[6] as String
|
||||||
|
|
||||||
val filtered = activities.filter { activity ->
|
val filtered = activities.filter { activity ->
|
||||||
@@ -100,13 +104,13 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
else -> true
|
else -> true
|
||||||
}
|
}
|
||||||
val matchDataInicio = dataInicio == "Todas" || formatToShortDate(activity.dataInicio) == dataInicio
|
val matchDataInicio = dataInicio == "Todas" || formatToShortDate(activity.dataInicio) == dataInicio
|
||||||
val matchResponsavel = responsavel == "Todos" || activity.responsavel == responsavel
|
val matchRecurso = recurso == "Todos" || activity.recurso.split(";").map { it.trim() }.contains(recurso)
|
||||||
val matchQuery = query.isBlank() ||
|
val matchQuery = query.isBlank() ||
|
||||||
activity.numeroOs.contains(query, ignoreCase = true) ||
|
activity.numeroOs.contains(query, ignoreCase = true) ||
|
||||||
activity.descricao.contains(query, ignoreCase = true) ||
|
activity.descricao.contains(query, ignoreCase = true) ||
|
||||||
activity.responsavel.contains(query, ignoreCase = true)
|
activity.recurso.contains(query, ignoreCase = true)
|
||||||
|
|
||||||
matchSetor && matchEquipe && matchStatus && matchDataInicio && matchResponsavel && matchQuery
|
matchSetor && matchEquipe && matchStatus && matchDataInicio && matchRecurso && matchQuery
|
||||||
}
|
}
|
||||||
|
|
||||||
if (dataInicio != "Todas") {
|
if (dataInicio != "Todas") {
|
||||||
@@ -145,6 +149,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
)
|
)
|
||||||
|
|
||||||
init {
|
init {
|
||||||
|
_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. Fall back to local sample data if sync fails.
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val currentList = repository.allActivities.first()
|
val currentList = repository.allActivities.first()
|
||||||
@@ -188,8 +193,8 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
_selectedDataInicio.value = dataInicio
|
_selectedDataInicio.value = dataInicio
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setFilterResponsavel(responsavel: String) {
|
fun setFilterRecurso(recurso: String) {
|
||||||
_selectedResponsavel.value = responsavel
|
_selectedRecurso.value = recurso
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setSearchQuery(query: String) {
|
fun setSearchQuery(query: String) {
|
||||||
@@ -197,10 +202,8 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun toggleInternet(available: Boolean) {
|
fun toggleInternet(available: Boolean) {
|
||||||
_internetAvailable.value = available
|
// App is always online.
|
||||||
if (!available) {
|
_internetAvailable.value = true
|
||||||
_syncStatusMessage.value = null
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun clearMessages() {
|
fun clearMessages() {
|
||||||
@@ -263,6 +266,17 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun loginUser(email: String, displayName: String) {
|
||||||
|
val user = com.example.data.model.GoogleUser(email, displayName)
|
||||||
|
repository.saveUser(user)
|
||||||
|
_currentUser.value = user
|
||||||
|
}
|
||||||
|
|
||||||
|
fun logoutUser() {
|
||||||
|
repository.clearSavedUser()
|
||||||
|
_currentUser.value = null
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Submits progress updates and creates log.
|
* Submits progress updates and creates log.
|
||||||
*/
|
*/
|
||||||
@@ -271,10 +285,11 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
novoPercentual: Int,
|
novoPercentual: Int,
|
||||||
observacao: String?,
|
observacao: String?,
|
||||||
fotoPath: String?,
|
fotoPath: String?,
|
||||||
responsavel: String
|
recurso: String,
|
||||||
|
emailEditor: String?
|
||||||
) {
|
) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
repository.updateProgress(numeroOs, novoPercentual, observacao, fotoPath, responsavel)
|
repository.updateProgress(numeroOs, novoPercentual, observacao, fotoPath, recurso, emailEditor)
|
||||||
// Update selected activity model in state to refresh UI
|
// Update selected activity model in state to refresh UI
|
||||||
_selectedActivity.value?.let { active ->
|
_selectedActivity.value?.let { active ->
|
||||||
if (active.numeroOs == numeroOs) {
|
if (active.numeroOs == numeroOs) {
|
||||||
|
|||||||
BIN
app/src/main/play_store_512.png
Normal file
|
After Width: | Height: | Size: 112 KiB |
@@ -1,6 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
<background android:drawable="@drawable/ic_launcher_background" />
|
<background android:drawable="@mipmap/ic_launcher_background"/>
|
||||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
<monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
|
||||||
</adaptive-icon>
|
</adaptive-icon>
|
||||||
BIN
app/src/main/res/mipmap-hdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 7.4 KiB |
|
Before Width: | Height: | Size: 2.0 KiB |
BIN
app/src/main/res/mipmap-hdpi/ic_launcher_background.png
Normal file
|
After Width: | Height: | Size: 1.2 KiB |
BIN
app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 4.2 KiB |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 3.7 KiB |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher_background.png
Normal file
|
After Width: | Height: | Size: 695 B |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 5.3 KiB |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.png
Normal file
|
After Width: | Height: | Size: 5.3 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 2.8 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher_background.png
Normal file
|
After Width: | Height: | Size: 1.8 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 5.8 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 4.3 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png
Normal file
|
After Width: | Height: | Size: 3.3 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 31 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.png
Normal file
|
After Width: | Height: | Size: 31 KiB |
|
Before Width: | Height: | Size: 8.7 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 34 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png
Normal file
|
After Width: | Height: | Size: 5.3 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 49 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.png
Normal file
|
After Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 11 KiB |
300
documentacao/arquitetura/arquitetura_do_sistema.md
Normal file
@@ -0,0 +1,300 @@
|
|||||||
|
# Documentação de Arquitetura do Sistema: Gestão de Manutenção (Cargill Parada OS)
|
||||||
|
|
||||||
|
Esta documentação descreve de forma abrangente a arquitetura de software, a estrutura de dados, o design da interface e os fluxos de sincronização do aplicativo Android de Gestão de Manutenção de Parada da Cargill.
|
||||||
|
|
||||||
|
O aplicativo foi projetado sob uma filosofia **offline-first** para atender a técnicos e inspetores que executam suas rotinas de manutenção em áreas industriais da planta com cobertura de rede instável ou inexistente.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Visão Geral do Sistema e Princípios de Arquitetura
|
||||||
|
|
||||||
|
O aplicativo adota uma arquitetura inspirada nos princípios de **Clean Architecture** e estruturada no padrão **MVVM (Model-View-ViewModel)** combinado com o **Repository Pattern**.
|
||||||
|
|
||||||
|
### Diretrizes Arquiteturais:
|
||||||
|
1. **Offline-First (Resiliência Local):** Toda operação de leitura e gravação de progresso das Ordens de Serviço (OS) ocorre prioritariamente na base local do dispositivo.
|
||||||
|
2. **Única Fonte de Verdade (Single Source of Truth - SSoT):** O banco de dados local Room atua como a única fonte de verdade para a camada de apresentação (UI). A UI nunca lê diretamente da rede.
|
||||||
|
3. **Desacoplamento Baseado em Estados:** A interface de usuário (UI) é reativa e responde a fluxos de estado assíncronos (`StateFlow` da biblioteca Kotlin Coroutines) expostos pela ViewModel.
|
||||||
|
4. **Reconciliação por Event Sourcing (Transaction-based Sync):** A integridade entre os dispositivos dos técnicos é garantida por meio de um log transacional descentralizado sincronizado bidirecionalmente com o Google Sheets.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
subgraph Camada de UI (Jetpack Compose)
|
||||||
|
A[MainActivity] --> B[MaintenanceDashboardScreen]
|
||||||
|
B -->|Exibe Métricas| B1[DashboardMetrics]
|
||||||
|
B -->|Filtra Lista| B2[FilterPillsRow]
|
||||||
|
B -->|Lista Elementos| B3[OSListItemCard]
|
||||||
|
B -->|Ações e Logs| B4[EditActivityBottomSheet]
|
||||||
|
B -->|Importação| B5[ImporterConsoleSheet]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Camada de Negócio e Estado (ViewModel)
|
||||||
|
C[MaintenanceViewModel]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Camada de Repositório (Repository)
|
||||||
|
D[MaintenanceRepository]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Camada de Dados Local (Room / SQLite)
|
||||||
|
E[AppDatabase]
|
||||||
|
F[MaintenanceDao]
|
||||||
|
G[(SQLite Database)]
|
||||||
|
E --> F
|
||||||
|
F --> G
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Camada de Dados Remota (Google Sheets API)
|
||||||
|
H[GoogleSheetsSyncService]
|
||||||
|
I[(Planilha Google Sheets)]
|
||||||
|
end
|
||||||
|
|
||||||
|
B <-->|Observa Estados / Dispara Ações| C
|
||||||
|
C <-->|Invoca Lógica de Negócio| D
|
||||||
|
D <-->|Leitura/Escrita Local| F
|
||||||
|
D <-->|Dispara Sincronização| H
|
||||||
|
H <-->|Requisições HTTP REST / OAuth2| I
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Mapa do Código Fonte (Estrutura de Pastas)
|
||||||
|
|
||||||
|
A estrutura do código fonte está localizada no pacote `com.example` e é organizada da seguinte maneira:
|
||||||
|
|
||||||
|
* [`app/src/main/java/com/example/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/)
|
||||||
|
* [`MainActivity.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/MainActivity.kt): Classe de entrada que inicializa a base de dados, repositório, fábrica do ViewModel e renderiza a tela principal Compose.
|
||||||
|
* `data/` (Camada de Dados)
|
||||||
|
* [`local/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/local/)
|
||||||
|
* [`AppDatabase.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/local/AppDatabase.kt): Definição do banco Room e migração destrutiva para fins de teste.
|
||||||
|
* [`MaintenanceDao.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/local/MaintenanceDao.kt): Consultas locais SQL (queries reativas com `Flow` e operações `suspend`).
|
||||||
|
* [`model/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/model/)
|
||||||
|
* [`MaintenanceActivity.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/model/MaintenanceActivity.kt): Entidades Room (`MaintenanceActivity`, `OSUpdateHistory`), enumerador `ActivityStatus` e auxiliares de formatação/parsing de data.
|
||||||
|
* [`remote/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/)
|
||||||
|
* [`GoogleSheetsSyncService.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/GoogleSheetsSyncService.kt): Serviço de integração HTTP com a API v4 do Google Sheets, englobando serialização JSON (Moshi), autenticação e mapeamento de planilhas.
|
||||||
|
* [`repository/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/repository/)
|
||||||
|
* [`MaintenanceRepository.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt): Mediador de dados, processamento de planilhas locais (CSV) e algoritmo central de reconciliação de estado.
|
||||||
|
* `ui/` (Camada de Apresentação)
|
||||||
|
* [`components/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/components/)
|
||||||
|
* [`CargillLogo.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/components/CargillLogo.kt): Logotipo customizado desenhado via Canvas vetorial utilizando cores da marca.
|
||||||
|
* [`screens/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/screens/)
|
||||||
|
* [`MaintenanceDashboardScreen.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt): Tela única modularizada contendo o painel principal, listas, modais e logs de histórico.
|
||||||
|
* [`theme/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/theme/)
|
||||||
|
* [`Color.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/theme/Color.kt): Definição de cores (Cargill Green, Cargill Black, etc.).
|
||||||
|
* [`Theme.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/theme/Theme.kt): Configuração do `MyApplicationTheme` (Material3) desabilitando dynamic colors para preservar a marca Cargill.
|
||||||
|
* [`Type.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/theme/Type.kt): Configuração tipográfica padrão.
|
||||||
|
* [`viewmodel/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/viewmodel/)
|
||||||
|
* [`MaintenanceViewModel.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt): Gerenciador de estados reativos e fábrica de injeção manual.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Camada de Dados Local e Modelagem (Room Database)
|
||||||
|
|
||||||
|
A persistência de dados local baseia-se no **Room** sobre o **SQLite**. São mapeadas duas entidades principais em [MaintenanceActivity.kt](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/model/MaintenanceActivity.kt).
|
||||||
|
|
||||||
|
### 3.1. Entidade: `MaintenanceActivity` (Tabela: `maintenance_activities`)
|
||||||
|
Representa o estado atualizado de uma Ordem de Serviço (OS).
|
||||||
|
|
||||||
|
| Campo | Tipo | Chave | Descrição |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `numeroOs` | `String` | Primária | Código de identificação único da OS (ex: `OS-1024`). |
|
||||||
|
| `descricao` | `String` | - | Descrição curta do serviço de manutenção. |
|
||||||
|
| `setor` | `String` | - | Área física na planta (ex: `UTILIDADES`, `CALDEIRA`, `REFINARIA`). |
|
||||||
|
| `equipe` | `String` | - | Especialidade técnica encarregada (ex: `Mecânica`, `Elétrica`, `Lubrificação`). |
|
||||||
|
| `recurso` | `String` | - | Nome do inspetor ou técnico atualmente encarregado. |
|
||||||
|
| `dataInicio` | `String` | - | Data de início prevista/real da atividade. |
|
||||||
|
| `dataFim` | `String` | - | Data de término prevista da atividade. |
|
||||||
|
| `percentualExecucao`| `Int` | - | Progresso de conclusão medido de `0` a `100`. |
|
||||||
|
| `observacoes` | `String?` | - | Último comentário ou observação adicionado à OS. |
|
||||||
|
| `fotoPath` | `String?` | - | Caminho local ou URL de imagem contendo evidência fotográfica. |
|
||||||
|
| `synced` | `Boolean` | - | Flag indicando se as atualizações locais foram enviadas à nuvem. |
|
||||||
|
| `lastUpdated` | `Long` | - | Timestamp UNIX (milissegundos) da última modificação. |
|
||||||
|
|
||||||
|
* **Propriedade Computada `status` (`ActivityStatus`):**
|
||||||
|
Definida dinamicamente baseando-se no `percentualExecucao`:
|
||||||
|
* `0%` -> `ActivityStatus.NAO_INICIADO` ("Não iniciado")
|
||||||
|
* `1%` a `99%` -> `ActivityStatus.EM_ANDAMENTO` ("Em andamento")
|
||||||
|
* `100%` -> `ActivityStatus.CONCLUIDO` ("Concluído")
|
||||||
|
|
||||||
|
### 3.2. Entidade: `OSUpdateHistory` (Tabela: `os_update_history`)
|
||||||
|
Armazena a trilha detalhada de atualizações aplicadas a cada OS. É o elemento fundamental para o sincronismo transacional.
|
||||||
|
|
||||||
|
| Campo | Tipo | Chave | Descrição |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `id` | `Long` | Primária (Auto) | Identificador sequencial do log. |
|
||||||
|
| `numeroOs` | `String` | - | Relaciona o registro à OS correspondente. |
|
||||||
|
| `timestamp` | `Long` | - | Data/hora exata em que o log foi registrado. |
|
||||||
|
| `percentualAnterior`| `Int` | - | Progresso antes do salvamento da alteração. |
|
||||||
|
| `percentualNovo` | `Int` | - | Novo progresso cadastrado pelo usuário. |
|
||||||
|
| `observacao` | `String?` | - | Observação descritiva inserida no momento da atualização. |
|
||||||
|
| `fotoPath` | `String?` | - | Foto de evidência vinculada a este incremento de progresso. |
|
||||||
|
| `recurso` | `String` | - | Identificação do responsável que executou a modificação. |
|
||||||
|
| `emailEditor` | `String?` | - | Email da conta do Google do usuário editor (auditoria). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Integração Remota (Google Sheets API v4)
|
||||||
|
|
||||||
|
A comunicação em nuvem é operada pelo serviço [`GoogleSheetsSyncService.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/GoogleSheetsSyncService.kt).
|
||||||
|
|
||||||
|
### 4.1. Mecanismo de Autenticação OAuth2
|
||||||
|
O serviço usa a biblioteca oficial `com.google.auth:google-auth-library-oauth2-http` para gerar tokens temporários bearer. A chave de serviço JSON é resolvida dinamicamente através de dois caminhos:
|
||||||
|
1. **Configuração em Compilação:** Puxada da chave de ambiente do sistema `SHEETS_CREDENTIALS_JSON` injetada via Secrets Gradle Plugin no `BuildConfig`.
|
||||||
|
2. **Fallback Local:** Leitura direta de arquivo na pasta local de ativos: `app/src/main/assets/chaveacesso_sheets.apikey.json`.
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
googleCredentials = GoogleCredentials.fromStream(stream)
|
||||||
|
.createScoped(listOf("https://www.googleapis.com/auth/spreadsheets"))
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2. Estrutura das Planilhas de Dados (Spreadsheet ID: `1sbFovBl-RMMY6lIVdhze_ZOA9cZK01y3vPLCMWLnfpo`)
|
||||||
|
|
||||||
|
O aplicativo mapeia duas abas na planilha remota:
|
||||||
|
|
||||||
|
1. **Aba `project` (Origem de Dados - Somente Leitura):**
|
||||||
|
* Contém as atividades macro da fábrica exportadas do software de planejamento (ex: MS Project).
|
||||||
|
* O aplicativo extrai a hierarquia de tópicos (coluna `Estrutura de Tópicos`) analisando níveis numéricos (ex: `1.1`, `1.1.1`).
|
||||||
|
* **Identificação de Setor:** Obtém o nome do setor a partir do título do nível imediatamente superior ou principal ("grandparent outline").
|
||||||
|
* **Identificação de Nós Folha:** Apenas linhas finais da hierarquia (que não são pai de nenhuma outra) são mapeadas como tarefas/OSs executáveis.
|
||||||
|
* **Filtro de Resumo:** Ignora linhas cujo valor na coluna `resumo` seja diferente de "não" (garantindo a exclusão de tarefas puramente administrativas/agrupadoras).
|
||||||
|
|
||||||
|
2. **Aba `history` (Log de Transações - Leitura/Escrita):**
|
||||||
|
* Guarda o log sequencial de alterações feitas por todos os inspetores.
|
||||||
|
* Colunas configuradas: `id`, `numeroOs`, `timestamp`, `percentualAnterior`, `percentualNovo`, `observacao`, `fotoPath`, `responsavel`, `email_editor`.
|
||||||
|
* Possui funcionalidade de **Self-Healing** (Auto-reparação): se a coluna `email_editor` não for encontrada no carregamento da planilha física, o app executa uma chamada PUT automática para inseri-la no cabeçalho na coluna correspondente.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Fluxo de Dados e Algoritmo de Sincronização
|
||||||
|
|
||||||
|
A sincronização de dados adota uma variação simplificada de **Event Sourcing**, onde o estado final de um objeto é derivado a partir da soma histórica de suas transações.
|
||||||
|
|
||||||
|
```
|
||||||
|
[Google Sheets] [App Local (Room)]
|
||||||
|
|
||||||
|
Aba "project"
|
||||||
|
(Lista Mestra de OS)
|
||||||
|
|
|
||||||
|
| 1. Download OSs
|
||||||
|
v
|
||||||
|
[Mapeador de Folhas]
|
||||||
|
(Extrai Setores/Equipes)
|
||||||
|
|
|
||||||
|
+-----------------------+
|
||||||
|
|
|
||||||
|
v
|
||||||
|
Aba "history" ----------> [Mesclagem de Históricos] <--------- Tabela Local
|
||||||
|
(Histórico de Transações) (Dedup por OS + Timestamp) "os_update_history"
|
||||||
|
|
|
||||||
|
| 2. Determina maior progresso por OS
|
||||||
|
v
|
||||||
|
[Atualiza atividades Room]
|
||||||
|
|
|
||||||
|
| 3. Insere logs ausentes localmente
|
||||||
|
v
|
||||||
|
[Tabela Local]
|
||||||
|
|
|
||||||
|
| 4. Envia logs pendentes locais
|
||||||
|
v
|
||||||
|
Aba "history"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Algoritmo Detalhado de Reconciliação (`synchronizeWithBackend`):
|
||||||
|
|
||||||
|
1. **Download do Escopo:** O repositório baixa a lista mestra de OSs brutas da aba `project` através do serviço sheets.
|
||||||
|
2. **Download das Transações Globais:** Baixa a totalidade dos logs registrados na aba `history`.
|
||||||
|
3. **Leitura das Transações Locais:** Carrega todos os logs de `os_update_history` salvos localmente na base SQLite.
|
||||||
|
4. **Mesclagem e Eliminação de Duplicidades:**
|
||||||
|
* Une ambas as listas de logs (remotos + locais).
|
||||||
|
* Aplica uma cláusula de distinção (`distinctBy`) utilizando a chave composta `"${numeroOs}_${timestamp}"`.
|
||||||
|
* Ordena todos os logs de forma decrescente com base no `timestamp`.
|
||||||
|
5. **Reconstrução do Estado da Atividade:**
|
||||||
|
* Para cada OS identificada no download da aba `project`, o repositório busca seu histórico filtrado na lista consolidada de logs.
|
||||||
|
* Como a lista está ordenada do mais recente para o mais antigo, o **primeiro log correspondente** define o estado final da OS (determinando `percentualExecucao`, `observacoes`, `fotoPath` e o timestamp da última atualização `lastUpdated`).
|
||||||
|
* Se não houver nenhum log correspondente, a OS assume valores padrão (`percentualExecucao = 0`).
|
||||||
|
6. **Atualização da Base Local (Room):**
|
||||||
|
* Limpa a tabela local de atividades (`clearAllActivities()`) para remover quaisquer OSs excluídas do escopo do planejamento central.
|
||||||
|
* Insere o lote de atividades reconciliadas e reconstruídas (`insertActivities()`).
|
||||||
|
* Salva na tabela local `os_update_history` quaisquer logs baixados da nuvem que ainda não existiam localmente.
|
||||||
|
7. **Envio de Atualizações Offline:**
|
||||||
|
* Filtra todos os logs locais que não existiam na lista de logs baixada do Sheets.
|
||||||
|
* Dispara um envio em lote (`pushHistoryToSheet()`) para anexar essas linhas na aba `history` do Google Sheets, alterando localmente o status de sincronização das OSs correspondentes para `synced = true`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Lógica de Importação de Planilhas Locais (CSV)
|
||||||
|
|
||||||
|
O aplicativo permite a carga offline direta de dados por meio da importação de arquivos CSV formatados (geralmente gerados a partir do Excel).
|
||||||
|
|
||||||
|
* **Detecção Dinâmica de Delimitador:** O repositório analisa a primeira linha do arquivo e define se o separador estrutural é ponto e vírgula (`;`) ou vírgula (`,`).
|
||||||
|
* **Mapeamento de Cabeçalhos por Palavras-Chave (Case-Insensitive):**
|
||||||
|
* **OS:** Procura por "os", "numero", "número".
|
||||||
|
* **Descrição:** Procura por "desc", "atividade", "ação".
|
||||||
|
* **Setor:** Procura por "setor", "area", "área".
|
||||||
|
* **Equipe:** Procura por "equipe", "eq", "disc", "tipo".
|
||||||
|
* **Responsável:** Procura por "resp", "encarregado", "dono".
|
||||||
|
* **Início:** Procura por "inicio", "início", "start".
|
||||||
|
* **Fim:** Procura por "fim", "end", "termino", "término".
|
||||||
|
* **Progresso (%):** Procura por "pct", "%", "percent", "exec".
|
||||||
|
* **Saneamento de Dados (Sanitization):**
|
||||||
|
* Filtra e remove aspas extras (`"`).
|
||||||
|
* Converte e limpa percentuais, interpretando valores textuais.
|
||||||
|
* Padroniza os nomes de setores e equipes (ex: converte variações de escrita para termos padrão como `Preparação`, `Extração`, `Caldeira`, `Mecânica`, `Elétrica`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Camada de Apresentação e Estado (UI & Jetpack Compose)
|
||||||
|
|
||||||
|
A camada visual é baseada em componentes reativos do **Jetpack Compose** e gerenciada pelo [`MaintenanceViewModel.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt).
|
||||||
|
|
||||||
|
### 7.1. Fluxos de Estado na ViewModel
|
||||||
|
A ViewModel consolida entradas de múltiplos canais para gerar fluxos reativos finais para a tela:
|
||||||
|
* `_selectedSetor`, `_selectedEquipe`, `_selectedStatus`, `_selectedDataInicio`, `_selectedRecurso`: Controlam filtros ativos de pílulas.
|
||||||
|
* `_searchQuery`: String de busca em tempo real digitada pelo usuário.
|
||||||
|
* `filteredActivities`: Um `StateFlow` unificado construído usando o operador `combine` que reavalia a filtragem da lista local sempre que qualquer filtro ou a barra de busca é alterada.
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
val filteredActivities: StateFlow<List<MaintenanceActivity>> = combine(
|
||||||
|
repository.allActivities,
|
||||||
|
_selectedSetor,
|
||||||
|
_selectedEquipe,
|
||||||
|
_selectedStatus,
|
||||||
|
_selectedDataInicio,
|
||||||
|
_selectedRecurso,
|
||||||
|
_searchQuery
|
||||||
|
) { ... }
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2. Principais Composables da Tela
|
||||||
|
|
||||||
|
1. **`MaintenanceDashboardScreen` (Tela Central):**
|
||||||
|
* Configura o Scaffold principal com uma barra superior contendo o logotipo da Cargill vetorial (`CargillLogo`), status da conexão, botão de sincronização (`SyncNow`), dados do usuário autenticado e ferramenta de busca.
|
||||||
|
2. **`DashboardMetrics` (Painel de Indicadores):**
|
||||||
|
* Exibe cartões informativos atualizados dinamicamente: Total de OS, OS Não Iniciadas, Em Andamento e Concluídas.
|
||||||
|
3. **`FilterPillsRow` (Filtros Avançados):**
|
||||||
|
* Exibe fileiras horizontais de chips roláveis para aplicar filtros com contadores numéricos dinâmicos para cada categoria.
|
||||||
|
4. **`OSListItemCard` (Cartão da OS):**
|
||||||
|
* Renderiza detalhes essenciais de cada atividade de manutenção.
|
||||||
|
* Apresenta uma barra de progresso colorida baseada no percentual de conclusão.
|
||||||
|
* Mostra um ícone de nuvem que muda de cor (verde para sincronizado, laranja com exclamação para alterações pendentes offline).
|
||||||
|
5. **`EditActivityBottomSheet` (Modal de Edição):**
|
||||||
|
* Permite que o técnico configure o progresso atual através de um slider, digite observações, insira evidências e confirme sua identidade.
|
||||||
|
* Contém a linha do tempo (Timeline) que exibe cronologicamente cada transação obtida via `selectedActivityHistory`.
|
||||||
|
6. **`ImporterConsoleSheet` (Console de Importação):**
|
||||||
|
* Modal utilitário para disparar importações CSV externas e repopular a base de dados com dados de teste/demonstração.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Decisões de Design de UI e Identidade Visual (Design System)
|
||||||
|
|
||||||
|
A interface de usuário foi desenhada de forma a respeitar a identidade corporativa da Cargill, garantindo legibilidade e uso ideal em campo.
|
||||||
|
|
||||||
|
* **Paleta de Cores Customizada:**
|
||||||
|
* `CargillGreen` (`#005F40`): Cor principal aplicada em botões chave, barras de título e destaques de progresso concluído.
|
||||||
|
* `CargillBlack` (`#1A1A1A`): Tom escuro predominante no fundo em modo escuro.
|
||||||
|
* `CargillLightGreen` (`#E8F5E9`): Utilizado como cor de fundo para badges e indicadores secundários.
|
||||||
|
* `LightGrey` (`#F5F7F6`): Fundo claro suave para o modo diurno.
|
||||||
|
* **Componentes Premium M3:**
|
||||||
|
* Uso de **Glassmorphism** sutil nos diálogos e cartões de lista.
|
||||||
|
* Transições suaves de recolhimento de modais.
|
||||||
|
* Feedback tátil visual em cliques de botões (ripple effect customizado).
|
||||||
|
* Layout responsivo que reorganiza colunas e métricas caso o aplicativo seja visualizado em modo paisagem ou tablets.
|
||||||
@@ -14,3 +14,14 @@ adb install -r app/build/outputs/apk/debug/app-debug.apk
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export JAVA_HOME="/home/cesarjhony/dev/projects/gestao_de_manutencao/jdk"
|
||||||
|
export PATH="$JAVA_HOME/bin:$PATH"
|
||||||
|
./gradle_9_3_1/gradle-9.3.1/bin/gradle assembleDebug
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
JAVA_HOME="/home/cesarjhony/dev/projects/gestao_de_manutencao/jdk" ./gradle_9_3_1/gradle-9.3.1/bin/gradle :app:assembleDebug --offline
|
||||||
|
|
||||||
|
|||||||
97
documentacao/recursos_simulados_e_truncados.md
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
# Listagem de Recursos Simulados e Truncados
|
||||||
|
|
||||||
|
Durante a análise técnica do código fonte do aplicativo de Gestão de Manutenção de Parada da Cargill, foram identificados recursos que possuem comportamento simulado (mockado) ou que foram implementados de forma parcial/truncada (stubs ou no-ops).
|
||||||
|
|
||||||
|
Abaixo está o levantamento detalhado de cada um desses elementos, com suas respectivas localizações de arquivos e descrições técnicas.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Captura e Anexo de Fotos de Campo (Simulador de Câmera)
|
||||||
|
|
||||||
|
* **Status:** **Simulado (Mockado)**
|
||||||
|
* **Arquivos Relacionados:**
|
||||||
|
* [`MaintenanceDashboardScreen.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt) (linhas ~1038-1044 e ~1205-1238)
|
||||||
|
* [`MaintenanceActivity.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/model/MaintenanceActivity.kt) (campo `fotoPath`)
|
||||||
|
* **Descrição Técnica:**
|
||||||
|
O aplicativo não possui integração real com as APIs de hardware de câmera do Android (como `CameraX` ou `Camera2`) nem abre um seletor de arquivos de imagens (Intent de galeria).
|
||||||
|
Em vez disso, no modal de atualização de progresso (`EditActivityBottomSheet`), exibe-se uma lista horizontal (`LazyRow`) contendo quatro categorias pré-definidas de imagem fictícia:
|
||||||
|
* *"Turbina"* -> registra o caminho `"ic_turbine_mock"`
|
||||||
|
* *"Fiação Elétrica"* -> registra o caminho `"ic_electrical_mock"`
|
||||||
|
* *"Mancal Engraxado"* -> registra o caminho `"ic_gear_mock"`
|
||||||
|
* *"Caldeira Lavada"* -> registra o caminho `"ic_boiler_mock"`
|
||||||
|
* **Impacto/Limitação:** O aplicativo apenas salva caminhos de strings estáticas no banco SQLite local (Room) e sincroniza este texto na aba `history` do Google Sheets, sem de fato capturar ou fazer upload de arquivos de imagem binários.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Controle e Simulação de Conectividade de Rede
|
||||||
|
|
||||||
|
* **Status:** **Truncado (No-op / Hardcoded)**
|
||||||
|
* **Arquivos Relacionados:**
|
||||||
|
* [`MaintenanceViewModel.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt) (linhas ~63 e ~204-207)
|
||||||
|
* [`MaintenanceDashboardScreen.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt) (linhas ~81 e ~215-224)
|
||||||
|
* **Descrição Técnica:**
|
||||||
|
A ViewModel possui uma flag interna `internetAvailable` baseada em `MutableStateFlow` e expõe um método chamado `toggleInternet(available: Boolean)`. No entanto:
|
||||||
|
* O estado de inicialização é fixado em `true`.
|
||||||
|
* O método `toggleInternet(...)` força o estado de volta para `true` de maneira incondicional:
|
||||||
|
```kotlin
|
||||||
|
fun toggleInternet(available: Boolean) {
|
||||||
|
// App is always online.
|
||||||
|
_internetAvailable.value = true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
* Não há integração com o `ConnectivityManager` do Android para ouvir de forma dinâmica o estado real da rede móvel ou Wi-Fi do aparelho.
|
||||||
|
* **Impacto/Limitação:** O recurso de simulação de queda de rede (modo offline planejado para controle em tela) está desativado. O aplicativo sempre assume que está online, e o ícone de nuvem na barra superior permanece constantemente em modo "Conectado/Nuvem Verde".
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Escrita de Ordens de Serviço Mestre na Planilha (`project`)
|
||||||
|
|
||||||
|
* **Status:** **Truncado (No-op)**
|
||||||
|
* **Arquivos Relacionados:**
|
||||||
|
* [`GoogleSheetsSyncService.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/GoogleSheetsSyncService.kt) (linhas ~576-582)
|
||||||
|
* **Descrição Técnica:**
|
||||||
|
A função `pushActivitiesToSheet` é responsável por sincronizar novas OSs criadas ou importadas localmente de volta para a aba principal da planilha remota. No entanto, ela foi intencionalmente esvaziada (tornando-se um método sem ação/no-op):
|
||||||
|
```kotlin
|
||||||
|
fun pushActivitiesToSheet(
|
||||||
|
toUpdateRemote: List<Pair<MaintenanceActivity, Int>>,
|
||||||
|
toAppendRemote: List<MaintenanceActivity>
|
||||||
|
) {
|
||||||
|
// No-op to respect read-only project sheets requirement
|
||||||
|
}
|
||||||
|
```
|
||||||
|
* **Impacto/Limitação:** Caso o usuário importe novas ordens de serviço via planilha CSV local, essas OSs ficarão restritas ao banco de dados do dispositivo móvel local. O aplicativo não tentará escrevê-las na aba `project` no Google Sheets, respeitando a regra de que a aba mestre de projetos é de leitura exclusiva do aplicativo.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Contador de Conflitos na Sincronização
|
||||||
|
|
||||||
|
* **Status:** **Truncado (Simplificado)**
|
||||||
|
* **Arquivos Relacionados:**
|
||||||
|
* [`MaintenanceRepository.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt) (linhas ~278-281)
|
||||||
|
* **Descrição Técnica:**
|
||||||
|
Durante a finalização do sincronismo bidirecional, a resposta de sucesso (`SyncResult.Success`) retorna as métricas de itens sincronizados e conflitos resolvidos. No entanto, o valor de conflitos resolvidos é fixado estaticamente em `0`:
|
||||||
|
```kotlin
|
||||||
|
SyncResult.Success(
|
||||||
|
syncedItems = reconciledActivities.size,
|
||||||
|
conflictsResolved = 0
|
||||||
|
)
|
||||||
|
```
|
||||||
|
* **Impacto/Limitação:** Embora o repositório realize de forma bem-sucedida a reconciliação (resolvendo concorrência com base no timestamp da transação mais recente), o aplicativo não calcula ou expõe de forma quantitativa quantos conflitos de concorrência foram identificados e solucionados na execução atual do lote.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Carga de Dados Inicial em Caso de Falha de Conexão (Fallback)
|
||||||
|
|
||||||
|
* **Status:** **Simulado (Mock Data Fallback)**
|
||||||
|
* **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)
|
||||||
|
* [`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)
|
||||||
|
* **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()`):
|
||||||
|
```kotlin
|
||||||
|
// 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.
|
||||||
@@ -40,6 +40,7 @@ firebaseBom = "34.15.0"
|
|||||||
secretsGradlePlugin = "2.0.1"
|
secretsGradlePlugin = "2.0.1"
|
||||||
googleServices = "4.5.0"
|
googleServices = "4.5.0"
|
||||||
googleAuth = "1.19.0"
|
googleAuth = "1.19.0"
|
||||||
|
playServicesAuth = "21.2.0"
|
||||||
|
|
||||||
[libraries]
|
[libraries]
|
||||||
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||||
@@ -91,6 +92,7 @@ firebase-bom = { group = "com.google.firebase", name = "firebase-bom", version.r
|
|||||||
firebase-ai = { group = "com.google.firebase", name = "firebase-ai" }
|
firebase-ai = { group = "com.google.firebase", name = "firebase-ai" }
|
||||||
firebase-appcheck-recaptcha = { group = "com.google.firebase", name = "firebase-appcheck-recaptcha" }
|
firebase-appcheck-recaptcha = { group = "com.google.firebase", name = "firebase-appcheck-recaptcha" }
|
||||||
google-auth-library-oauth2-http = { group = "com.google.auth", name = "google-auth-library-oauth2-http", version.ref = "googleAuth" }
|
google-auth-library-oauth2-http = { group = "com.google.auth", name = "google-auth-library-oauth2-http", version.ref = "googleAuth" }
|
||||||
|
play-services-auth = { group = "com.google.android.gms", name = "play-services-auth", version.ref = "playServicesAuth" }
|
||||||
|
|
||||||
[plugins]
|
[plugins]
|
||||||
android-application = { id = "com.android.application", version.ref = "agp" }
|
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||||
|
|||||||