Snapshot: Filtro de data corrigido para dd/mm/aa
1
app/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/build
|
||||
143
app/build.gradle.kts
Normal file
@@ -0,0 +1,143 @@
|
||||
import com.google.gms.googleservices.GoogleServicesPlugin.MissingGoogleServicesStrategy
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.google.devtools.ksp)
|
||||
alias(libs.plugins.roborazzi)
|
||||
alias(libs.plugins.secrets)
|
||||
alias(libs.plugins.google.services)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.example"
|
||||
compileSdk { version = release(36) { minorApiLevel = 1 } }
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.aistudio.cargillparadaos.xvyzwt"
|
||||
minSdk = 24
|
||||
targetSdk = 36
|
||||
versionCode = 1
|
||||
versionName = "1.0"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
val keystorePath = System.getenv("KEYSTORE_PATH") ?: "${rootDir}/my-upload-key.jks"
|
||||
storeFile = file(keystorePath)
|
||||
storePassword = System.getenv("STORE_PASSWORD")
|
||||
keyAlias = "upload"
|
||||
keyPassword = System.getenv("KEY_PASSWORD")
|
||||
}
|
||||
create("debugConfig") {
|
||||
storeFile = file("${rootDir}/debug.keystore")
|
||||
storePassword = "android"
|
||||
keyAlias = "androiddebugkey"
|
||||
keyPassword = "android"
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isCrunchPngs = false
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
debug {
|
||||
signingConfig = signingConfigs.getByName("debugConfig")
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_11
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
}
|
||||
packaging {
|
||||
resources {
|
||||
excludes += "META-INF/DEPENDENCIES"
|
||||
excludes += "META-INF/LICENSE"
|
||||
excludes += "META-INF/LICENSE.txt"
|
||||
excludes += "META-INF/license.txt"
|
||||
excludes += "META-INF/NOTICE"
|
||||
excludes += "META-INF/NOTICE.txt"
|
||||
excludes += "META-INF/notice.txt"
|
||||
excludes += "META-INF/ASL2.0"
|
||||
}
|
||||
}
|
||||
buildFeatures {
|
||||
compose = true
|
||||
buildConfig = true
|
||||
}
|
||||
testOptions { unitTests { isIncludeAndroidResources = true } }
|
||||
}
|
||||
|
||||
// Configure the Secrets Gradle Plugin to use .env and .env.example files
|
||||
// to match the convention used in Web projects.
|
||||
secrets {
|
||||
propertiesFileName = ".env"
|
||||
defaultPropertiesFileName = ".env.example"
|
||||
}
|
||||
|
||||
googleServices {
|
||||
missingGoogleServicesStrategy = MissingGoogleServicesStrategy.WARN
|
||||
}
|
||||
|
||||
|
||||
// Some unused dependencies are commented out below instead of being removed.
|
||||
// This makes it easy to add them back in the future if needed.
|
||||
dependencies {
|
||||
implementation(platform(libs.androidx.compose.bom))
|
||||
implementation(platform(libs.firebase.bom))
|
||||
// implementation(libs.accompanist.permissions)
|
||||
implementation(libs.androidx.activity.compose)
|
||||
// implementation(libs.androidx.camera.camera2)
|
||||
// implementation(libs.androidx.camera.core)
|
||||
// implementation(libs.androidx.camera.lifecycle)
|
||||
// implementation(libs.androidx.camera.view)
|
||||
implementation(libs.androidx.compose.material.icons.core)
|
||||
implementation(libs.androidx.compose.material.icons.extended)
|
||||
implementation(libs.androidx.compose.material3)
|
||||
implementation(libs.androidx.compose.ui)
|
||||
implementation(libs.androidx.compose.ui.graphics)
|
||||
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||
implementation(libs.androidx.core.ktx)
|
||||
// implementation(libs.androidx.datastore.preferences)
|
||||
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
// implementation(libs.androidx.navigation.compose)
|
||||
implementation(libs.androidx.room.ktx)
|
||||
implementation(libs.androidx.room.runtime)
|
||||
implementation(libs.coil.compose)
|
||||
implementation(libs.converter.moshi)
|
||||
implementation(libs.firebase.ai)
|
||||
implementation(libs.firebase.appcheck.recaptcha)
|
||||
implementation(libs.kotlinx.coroutines.android)
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
implementation(libs.logging.interceptor)
|
||||
implementation(libs.moshi.kotlin)
|
||||
implementation(libs.okhttp)
|
||||
implementation(libs.google.auth.library.oauth2.http)
|
||||
// implementation(libs.play.services.location)
|
||||
implementation(libs.retrofit)
|
||||
testImplementation(libs.androidx.compose.ui.test.junit4)
|
||||
testImplementation(libs.androidx.core)
|
||||
testImplementation(libs.androidx.junit)
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.kotlinx.coroutines.test)
|
||||
testImplementation(libs.robolectric)
|
||||
testImplementation(libs.roborazzi)
|
||||
testImplementation(libs.roborazzi.compose)
|
||||
testImplementation(libs.roborazzi.junit.rule)
|
||||
androidTestImplementation(platform(libs.androidx.compose.bom))
|
||||
androidTestImplementation(libs.androidx.compose.ui.test.junit4)
|
||||
androidTestImplementation(libs.androidx.espresso.core)
|
||||
androidTestImplementation(libs.androidx.junit)
|
||||
androidTestImplementation(libs.androidx.runner)
|
||||
debugImplementation(libs.androidx.compose.ui.test.manifest)
|
||||
debugImplementation(libs.androidx.compose.ui.tooling)
|
||||
"ksp"(libs.androidx.room.compiler)
|
||||
"ksp"(libs.moshi.kotlin.codegen)
|
||||
}
|
||||
21
app/proguard-rules.pro
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.example
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
/**
|
||||
* Instrumented test, which will execute on an Android device.
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class ExampleInstrumentedTest {
|
||||
@Test
|
||||
fun useAppContext() {
|
||||
// Context of the app under test.
|
||||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
assertEquals("com.example", appContext.packageName)
|
||||
}
|
||||
}
|
||||
29
app/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="@xml/backup_rules"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.MyApplication">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.MyApplication">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
44
app/src/main/java/com/example/MainActivity.kt
Normal file
@@ -0,0 +1,44 @@
|
||||
package com.example
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import com.example.data.local.AppDatabase
|
||||
import com.example.data.repository.MaintenanceRepository
|
||||
import com.example.ui.screens.MaintenanceDashboardScreen
|
||||
import com.example.ui.theme.MyApplicationTheme
|
||||
import com.example.ui.viewmodel.MaintenanceViewModel
|
||||
import com.example.ui.viewmodel.MaintenanceViewModelFactory
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
|
||||
// Initialize Database, Repository, and ViewModel using standard provider factory
|
||||
val database = AppDatabase.getDatabase(applicationContext)
|
||||
val repository = MaintenanceRepository(database.maintenanceDao(), applicationContext)
|
||||
val viewModel = ViewModelProvider(
|
||||
this,
|
||||
MaintenanceViewModelFactory(repository)
|
||||
)[MaintenanceViewModel::class.java]
|
||||
|
||||
setContent {
|
||||
MyApplicationTheme {
|
||||
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
|
||||
MaintenanceDashboardScreen(
|
||||
viewModel = viewModel,
|
||||
modifier = Modifier.padding(innerPadding)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
36
app/src/main/java/com/example/data/local/AppDatabase.kt
Normal file
@@ -0,0 +1,36 @@
|
||||
package com.example.data.local
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
|
||||
@Database(
|
||||
entities = [MaintenanceActivity::class, OSUpdateHistory::class],
|
||||
version = 1,
|
||||
exportSchema = false
|
||||
)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
abstract fun maintenanceDao(): MaintenanceDao
|
||||
|
||||
companion object {
|
||||
@Volatile
|
||||
private var INSTANCE: AppDatabase? = null
|
||||
|
||||
fun getDatabase(context: Context): AppDatabase {
|
||||
return INSTANCE ?: synchronized(this) {
|
||||
val instance = Room.databaseBuilder(
|
||||
context.applicationContext,
|
||||
AppDatabase::class.java,
|
||||
"cargill_maintenance_db"
|
||||
)
|
||||
.fallbackToDestructiveMigration()
|
||||
.build()
|
||||
INSTANCE = instance
|
||||
instance
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
52
app/src/main/java/com/example/data/local/MaintenanceDao.kt
Normal file
@@ -0,0 +1,52 @@
|
||||
package com.example.data.local
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Update
|
||||
import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface MaintenanceDao {
|
||||
@Query("SELECT * FROM maintenance_activities ORDER BY numeroOs ASC")
|
||||
fun getAllActivities(): Flow<List<MaintenanceActivity>>
|
||||
|
||||
@Query("SELECT * FROM maintenance_activities WHERE numeroOs = :numeroOs LIMIT 1")
|
||||
fun getActivityByOs(numeroOs: String): Flow<MaintenanceActivity?>
|
||||
|
||||
@Query("SELECT * FROM maintenance_activities WHERE numeroOs = :numeroOs LIMIT 1")
|
||||
suspend fun getActivityByOsOneShot(numeroOs: String): MaintenanceActivity?
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertActivities(activities: List<MaintenanceActivity>)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertActivity(activity: MaintenanceActivity)
|
||||
|
||||
@Update
|
||||
suspend fun updateActivity(activity: MaintenanceActivity)
|
||||
|
||||
@Query("SELECT * FROM os_update_history WHERE numeroOs = :numeroOs ORDER BY timestamp DESC")
|
||||
fun getHistoryForOs(numeroOs: String): Flow<List<OSUpdateHistory>>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertHistory(history: OSUpdateHistory)
|
||||
|
||||
@Query("SELECT * FROM maintenance_activities WHERE synced = 0")
|
||||
suspend fun getUnsyncedActivities(): List<MaintenanceActivity>
|
||||
|
||||
@Query("SELECT * FROM maintenance_activities")
|
||||
suspend fun getAllActivitiesList(): List<MaintenanceActivity>
|
||||
|
||||
@Query("SELECT * FROM os_update_history")
|
||||
suspend fun getAllHistoryList(): List<OSUpdateHistory>
|
||||
|
||||
@Query("DELETE FROM maintenance_activities")
|
||||
suspend fun clearAllActivities()
|
||||
|
||||
@Query("DELETE FROM os_update_history")
|
||||
suspend fun clearAllHistory()
|
||||
}
|
||||
160
app/src/main/java/com/example/data/model/MaintenanceActivity.kt
Normal file
@@ -0,0 +1,160 @@
|
||||
package com.example.data.model
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Calendar
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
@Entity(tableName = "maintenance_activities")
|
||||
data class MaintenanceActivity(
|
||||
@PrimaryKey val numeroOs: String,
|
||||
val descricao: String,
|
||||
val setor: String,
|
||||
val equipe: String,
|
||||
val responsavel: String,
|
||||
val dataInicio: String,
|
||||
val dataFim: String,
|
||||
val percentualExecucao: Int, // 0 to 100
|
||||
val observacoes: String? = null,
|
||||
val fotoPath: String? = null,
|
||||
val synced: Boolean = false,
|
||||
val lastUpdated: Long = System.currentTimeMillis()
|
||||
) {
|
||||
val status: ActivityStatus
|
||||
get() = when {
|
||||
percentualExecucao == 0 -> ActivityStatus.NAO_INICIADO
|
||||
percentualExecucao >= 100 -> ActivityStatus.CONCLUIDO
|
||||
else -> ActivityStatus.EM_ANDAMENTO
|
||||
}
|
||||
}
|
||||
|
||||
enum class ActivityStatus(val displayName: String) {
|
||||
NAO_INICIADO("Não iniciado"),
|
||||
EM_ANDAMENTO("Em andamento"),
|
||||
CONCLUIDO("Concluído")
|
||||
}
|
||||
|
||||
@Entity(tableName = "os_update_history")
|
||||
data class OSUpdateHistory(
|
||||
@PrimaryKey(autoGenerate = true) val id: Long = 0,
|
||||
val numeroOs: String,
|
||||
val timestamp: Long = System.currentTimeMillis(),
|
||||
val percentualAnterior: Int,
|
||||
val percentualNovo: Int,
|
||||
val observacao: String? = null,
|
||||
val fotoPath: String? = null,
|
||||
val responsavel: String
|
||||
)
|
||||
|
||||
fun extractDateOnly(dataStr: String): String {
|
||||
val clean = dataStr.trim()
|
||||
if (clean == "N/A" || clean.isBlank()) return "N/A"
|
||||
|
||||
// Split by whitespace or 'T'
|
||||
val parts = clean.split(Regex("[\\sT]+"))
|
||||
for (part in parts) {
|
||||
val trimmedPart = part.trim()
|
||||
if (trimmedPart.contains('/') || trimmedPart.contains('-')) {
|
||||
return trimmedPart
|
||||
}
|
||||
}
|
||||
|
||||
val tIndex = clean.indexOf('T')
|
||||
if (tIndex != -1) return clean.substring(0, tIndex).trim()
|
||||
val spaceIndex = clean.indexOf(' ')
|
||||
if (spaceIndex != -1) return clean.substring(0, spaceIndex).trim()
|
||||
return clean
|
||||
}
|
||||
|
||||
fun adjustTwoDigitYear(date: Date?): Date? {
|
||||
if (date == null) return null
|
||||
val cal = Calendar.getInstance(Locale.US)
|
||||
cal.time = date
|
||||
val year = cal.get(Calendar.YEAR)
|
||||
if (year < 2000) {
|
||||
cal.set(Calendar.YEAR, 2000 + (year % 100))
|
||||
return cal.time
|
||||
}
|
||||
return date
|
||||
}
|
||||
|
||||
fun parseDateOnly(dateStr: String): Date? {
|
||||
val clean = dateStr.trim()
|
||||
val formats = listOf(
|
||||
"dd/MM/yyyy",
|
||||
"dd/MM/yy",
|
||||
"yyyy-MM-dd",
|
||||
"yy-MM-dd",
|
||||
"dd-MM-yyyy",
|
||||
"dd-MM-yy",
|
||||
"MM/dd/yyyy",
|
||||
"MM/dd/yy"
|
||||
)
|
||||
for (format in formats) {
|
||||
try {
|
||||
val sdf = SimpleDateFormat(format, Locale.US)
|
||||
sdf.isLenient = false
|
||||
val parsed = sdf.parse(clean)
|
||||
if (parsed != null) {
|
||||
return adjustTwoDigitYear(parsed)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Try next
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun parseFullDateTime(dateTimeStr: String): Date? {
|
||||
val clean = dateTimeStr.trim()
|
||||
val formats = listOf(
|
||||
"dd/MM/yyyy HH:mm:ss",
|
||||
"dd/MM/yyyy HH:mm",
|
||||
"dd/MM/yy HH:mm:ss",
|
||||
"dd/MM/yy HH:mm",
|
||||
"yyyy-MM-dd HH:mm:ss",
|
||||
"yyyy-MM-dd HH:mm",
|
||||
"yy-MM-dd HH:mm:ss",
|
||||
"yy-MM-dd HH:mm",
|
||||
"yyyy-MM-dd'T'HH:mm:ss",
|
||||
"yyyy-MM-dd'T'HH:mm",
|
||||
"yy-MM-dd'T'HH:mm:ss",
|
||||
"yy-MM-dd'T'HH:mm",
|
||||
"dd/MM/yyyy",
|
||||
"dd/MM/yy",
|
||||
"yyyy-MM-dd",
|
||||
"yy-MM-dd",
|
||||
"dd-MM-yyyy",
|
||||
"dd-MM-yy",
|
||||
"MM/dd/yyyy",
|
||||
"MM/dd/yy"
|
||||
)
|
||||
for (format in formats) {
|
||||
try {
|
||||
val sdf = SimpleDateFormat(format, Locale.US)
|
||||
sdf.isLenient = false
|
||||
val parsed = sdf.parse(clean)
|
||||
if (parsed != null) {
|
||||
return adjustTwoDigitYear(parsed)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Try next
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun formatToShortDate(dataStr: String): String {
|
||||
val clean = dataStr.trim()
|
||||
if (clean == "N/A" || clean.isBlank() || clean == "Todas") return clean
|
||||
val extracted = extractDateOnly(clean)
|
||||
val parsed = parseDateOnly(extracted) ?: return extracted
|
||||
return try {
|
||||
val sdf = SimpleDateFormat("dd/MM/yy", Locale.US)
|
||||
sdf.format(parsed)
|
||||
} catch (e: Exception) {
|
||||
extracted
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,602 @@
|
||||
package com.example.data.remote
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
import com.squareup.moshi.JsonClass
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.google.auth.oauth2.GoogleCredentials
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.IOException
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class SheetValuesResponse(
|
||||
val range: String,
|
||||
val majorDimension: String,
|
||||
val values: List<List<String>>? = null
|
||||
)
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class BatchUpdateBody(
|
||||
val valueInputOption: String = "RAW",
|
||||
val data: List<ValueRange>
|
||||
)
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class ValueRange(
|
||||
val range: String,
|
||||
val values: List<List<String>>,
|
||||
val majorDimension: String = "ROWS"
|
||||
)
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class AppendBody(
|
||||
val range: String,
|
||||
val majorDimension: String = "ROWS",
|
||||
val values: List<List<String>>
|
||||
)
|
||||
|
||||
class GoogleSheetsSyncService(private val context: Context) {
|
||||
private val tag = "GoogleSheetsSync"
|
||||
private val spreadsheetId = "1sbFovBl-RMMY6lIVdhze_ZOA9cZK01y3vPLCMWLnfpo"
|
||||
|
||||
private val client = OkHttpClient.Builder()
|
||||
.addInterceptor(okhttp3.logging.HttpLoggingInterceptor().apply {
|
||||
level = okhttp3.logging.HttpLoggingInterceptor.Level.BASIC
|
||||
})
|
||||
.build()
|
||||
|
||||
private val moshi = Moshi.Builder()
|
||||
.add(com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory())
|
||||
.build()
|
||||
|
||||
private var googleCredentials: GoogleCredentials? = null
|
||||
|
||||
@Synchronized
|
||||
private fun getCredentials(): GoogleCredentials {
|
||||
if (googleCredentials == null) {
|
||||
val jsonFromEnv = try {
|
||||
com.example.BuildConfig.SHEETS_CREDENTIALS_JSON
|
||||
} catch (e: Throwable) {
|
||||
""
|
||||
}
|
||||
|
||||
val hasValidEnvJson = jsonFromEnv.isNotBlank() &&
|
||||
jsonFromEnv != "SHEETS_CREDENTIALS_JSON" &&
|
||||
jsonFromEnv.trim().startsWith("{")
|
||||
|
||||
val stream = if (hasValidEnvJson) {
|
||||
Log.d(tag, "Carregando credenciais do Google Sheets da variável de ambiente SHEETS_CREDENTIALS_JSON")
|
||||
java.io.ByteArrayInputStream(jsonFromEnv.toByteArray())
|
||||
} else {
|
||||
Log.d(tag, "Carregando credenciais do Google Sheets da pasta assets (chaveacesso_sheets.apikey.json)")
|
||||
try {
|
||||
context.assets.open("chaveacesso_sheets.apikey.json")
|
||||
} catch (e: Exception) {
|
||||
val msg = "Arquivo de credenciais 'chaveacesso_sheets.apikey.json' não encontrado na pasta 'assets' e chave 'SHEETS_CREDENTIALS_JSON' não configurada nos Secrets do AI Studio."
|
||||
Log.e(tag, msg, e)
|
||||
throw IOException(msg, e)
|
||||
}
|
||||
}
|
||||
|
||||
googleCredentials = GoogleCredentials.fromStream(stream)
|
||||
.createScoped(listOf("https://www.googleapis.com/auth/spreadsheets"))
|
||||
}
|
||||
googleCredentials!!.refreshIfExpired()
|
||||
return googleCredentials!!
|
||||
}
|
||||
|
||||
private fun getAccessToken(): String {
|
||||
val creds = getCredentials()
|
||||
val token = creds.accessToken?.tokenValue
|
||||
if (token != null) return token
|
||||
|
||||
// Force refresh if the token is null for any reason
|
||||
creds.refresh()
|
||||
return creds.accessToken?.tokenValue
|
||||
?: throw IOException("Falha ao obter token de acesso para a Sheets API.")
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to perform GET request on sheet values
|
||||
*/
|
||||
fun fetchValues(range: String): List<List<String>> {
|
||||
val accessToken = getAccessToken()
|
||||
val url = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$range"
|
||||
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.addHeader("Authorization", "Bearer $accessToken")
|
||||
.get()
|
||||
.build()
|
||||
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val errBody = response.body?.string() ?: ""
|
||||
Log.e(tag, "Fetch failed for range $range: Code ${response.code}, Msg: $errBody")
|
||||
throw IOException("Erro ao ler dados da planilha ($range): ${response.message}")
|
||||
}
|
||||
val bodyString = response.body?.string() ?: ""
|
||||
val adapter = moshi.adapter(SheetValuesResponse::class.java)
|
||||
val result = adapter.fromJson(bodyString)
|
||||
return result?.values ?: emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to perform PUT request to update sheet values
|
||||
*/
|
||||
private fun updateValues(range: String, values: List<List<String>>) {
|
||||
val accessToken = getAccessToken()
|
||||
val url = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$range?valueInputOption=RAW"
|
||||
|
||||
val bodyObj = ValueRange(range = range, values = values)
|
||||
val json = moshi.adapter(ValueRange::class.java).toJson(bodyObj)
|
||||
|
||||
val requestBody = json.toRequestBody("application/json".toMediaType())
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.addHeader("Authorization", "Bearer $accessToken")
|
||||
.put(requestBody)
|
||||
.build()
|
||||
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val errBody = response.body?.string() ?: ""
|
||||
Log.e(tag, "Update failed for range $range: Code ${response.code}, Msg: $errBody")
|
||||
throw IOException("Erro ao atualizar dados na planilha ($range): ${response.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to perform POST request to append sheet values
|
||||
*/
|
||||
fun appendValues(range: String, values: List<List<String>>) {
|
||||
if (values.isEmpty()) return
|
||||
val accessToken = getAccessToken()
|
||||
val url = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$range:append?valueInputOption=RAW"
|
||||
|
||||
val bodyObj = AppendBody(range = range, values = values)
|
||||
val json = moshi.adapter(AppendBody::class.java).toJson(bodyObj)
|
||||
|
||||
val requestBody = json.toRequestBody("application/json".toMediaType())
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.addHeader("Authorization", "Bearer $accessToken")
|
||||
.post(requestBody)
|
||||
.build()
|
||||
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val errBody = response.body?.string() ?: ""
|
||||
Log.e(tag, "Append failed for range $range: Code ${response.code}, Msg: $errBody")
|
||||
throw IOException("Erro ao anexar dados na planilha ($range): ${response.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to perform POST request for batch updating multiple cells/rows
|
||||
*/
|
||||
private fun batchUpdateValues(data: List<ValueRange>) {
|
||||
if (data.isEmpty()) return
|
||||
val accessToken = getAccessToken()
|
||||
val url = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values:batchUpdate"
|
||||
|
||||
val bodyObj = BatchUpdateBody(data = data)
|
||||
val json = moshi.adapter(BatchUpdateBody::class.java).toJson(bodyObj)
|
||||
|
||||
val requestBody = json.toRequestBody("application/json".toMediaType())
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.addHeader("Authorization", "Bearer $accessToken")
|
||||
.post(requestBody)
|
||||
.build()
|
||||
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val errBody = response.body?.string() ?: ""
|
||||
Log.e(tag, "Batch update failed: Code ${response.code}, Msg: $errBody")
|
||||
throw IOException("Erro ao sincronizar lote de dados com a planilha: ${response.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new sheet tab in the spreadsheet if it does not exist.
|
||||
*/
|
||||
fun createSheet(sheetName: String) {
|
||||
val accessToken = getAccessToken()
|
||||
val url = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId:batchUpdate"
|
||||
|
||||
val jsonPayload = """
|
||||
{
|
||||
"requests": [
|
||||
{
|
||||
"addSheet": {
|
||||
"properties": {
|
||||
"title": "$sheetName"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val requestBody = jsonPayload.toRequestBody("application/json".toMediaType())
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.addHeader("Authorization", "Bearer $accessToken")
|
||||
.post(requestBody)
|
||||
.build()
|
||||
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (response.isSuccessful) {
|
||||
Log.d(tag, "Sheet '$sheetName' created successfully.")
|
||||
} else {
|
||||
val errBody = response.body?.string() ?: ""
|
||||
Log.e(tag, "Failed to create sheet '$sheetName': Code ${response.code}, Msg: $errBody")
|
||||
// If it already exists, we can safely ignore the error
|
||||
if (!errBody.contains("already exists") && !errBody.contains("já existe")) {
|
||||
throw IOException("Erro ao criar aba '$sheetName' na planilha: ${response.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the sheet is initialized with a header row if it is empty.
|
||||
*/
|
||||
fun ensureHeaders(sheetName: String, defaultHeaders: List<String>) {
|
||||
try {
|
||||
val existingRows = fetchValues("$sheetName!A1:A2")
|
||||
if (existingRows.isEmpty()) {
|
||||
Log.d(tag, "Sheet $sheetName is empty, initializing headers...")
|
||||
updateValues("$sheetName!A1:${getColumnLetter(defaultHeaders.size)}1", listOf(defaultHeaders))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(tag, "Failed to ensure headers for $sheetName, attempting to create sheet and write them...", e)
|
||||
try {
|
||||
createSheet(sheetName)
|
||||
updateValues("$sheetName!A1:${getColumnLetter(defaultHeaders.size)}1", listOf(defaultHeaders))
|
||||
} catch (e2: Exception) {
|
||||
Log.e(tag, "Critical fail initializing headers for $sheetName", e2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun getColumnLetter(count: Int): String {
|
||||
return if (count <= 26) ('A'.code + count - 1).toChar().toString() else "Z"
|
||||
}
|
||||
|
||||
private fun normalizeOutlineNum(outline: String): String {
|
||||
var s = outline.trim()
|
||||
while (s.endsWith(".")) {
|
||||
s = s.substring(0, s.length - 1).trim()
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches remote activities and returns a list of activities along with their 1-based sheet row numbers.
|
||||
*/
|
||||
fun fetchRemoteActivities(): Pair<List<MaintenanceActivity>, Map<String, Int>> {
|
||||
val rows = fetchValues("project!A:Z")
|
||||
val activities = mutableListOf<MaintenanceActivity>()
|
||||
val rowMap = mutableMapOf<String, Int>()
|
||||
|
||||
Log.d(tag, "fetchRemoteActivities: Fetched ${rows.size} total rows from 'project' sheet.")
|
||||
|
||||
if (rows.isEmpty()) {
|
||||
return Pair(activities, rowMap)
|
||||
}
|
||||
|
||||
val headers = rows[0].map { it.trim().lowercase() }
|
||||
Log.d(tag, "Headers found: $headers")
|
||||
|
||||
// 1. Task Name: Match specific task name header first, then fall back
|
||||
val taskNameIdx = headers.indexOfFirst {
|
||||
it.contains("nome da tarefa") || it.contains("nome_da_tarefa")
|
||||
}.let { idx ->
|
||||
if (idx != -1) idx else headers.indexOfFirst {
|
||||
it.contains("tarefa") || it.contains("descrição") || it.contains("descricao") || it.contains("atividade") || it.contains("nome")
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Resource Group (Equipe): Match resource group/team
|
||||
val groupIdx = headers.indexOfFirst {
|
||||
it.contains("grupo de recursos") || it.contains("grupo_de_recursos")
|
||||
}.let { idx ->
|
||||
if (idx != -1) idx else headers.indexOfFirst {
|
||||
it.contains("grupo") || it.contains("equipe") || it.contains("disciplina") || it.contains("setor")
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Resource Names (Responsável)
|
||||
val resourceIdx = headers.indexOfFirst {
|
||||
it.contains("nomes dos recursos") || it.contains("nomes_dos_recursos")
|
||||
}.let { idx ->
|
||||
if (idx != -1) idx else headers.indexOfFirst {
|
||||
it.contains("recurso") || it.contains("responsável") || it.contains("responsavel") || it.contains("executor")
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Start Date (Início)
|
||||
val inicioIdx = headers.indexOfFirst {
|
||||
it.contains("início") || it.contains("inicio")
|
||||
}.let { idx ->
|
||||
if (idx != -1) idx else headers.indexOfFirst {
|
||||
it.contains("start") || it.contains("data")
|
||||
}
|
||||
}
|
||||
|
||||
// 5. End Date (Término)
|
||||
val fimIdx = headers.indexOfFirst {
|
||||
it.contains("término") || it.contains("termino")
|
||||
}.let { idx ->
|
||||
if (idx != -1) idx else headers.indexOfFirst {
|
||||
it.contains("end") || it.contains("conclusão") || it.contains("conclusao")
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Outline Structure (Estrutura de Tópicos): Highly specific first, then fall back to "número" (avoiding "id" / "os")
|
||||
val outlineIdx = headers.indexOfFirst {
|
||||
it.contains("estrutura de tópicos") || it.contains("topicos") || it.contains("tópicos")
|
||||
}.let { idx ->
|
||||
if (idx != -1) idx else headers.indexOfFirst {
|
||||
(it.contains("número") || it.contains("numero")) &&
|
||||
!it.contains("id") && !it.contains(" os") && !it.startsWith("os") && it != "os" && !it.contains("resumo")
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Exclusive ID (Id exclusiva): Highly specific first, then fallback to "id"
|
||||
val idIdx = headers.indexOfFirst {
|
||||
it.contains("id exclusiva") || it.contains("idexclusiva")
|
||||
}.let { idx ->
|
||||
if (idx != -1) idx else headers.indexOfFirst {
|
||||
it == "id" || it == "id_exclusiva" || it.contains("id")
|
||||
}
|
||||
}
|
||||
|
||||
// 8. Resumo: column mapping to filter service orders (only Resumo = Não)
|
||||
val resumoIdx = headers.indexOfFirst {
|
||||
it.contains("resumo")
|
||||
}
|
||||
|
||||
Log.d(tag, "Mapped Column Indices: taskName=$taskNameIdx, group=$groupIdx, resource=$resourceIdx, inicio=$inicioIdx, fim=$fimIdx, outline=$outlineIdx, id=$idIdx, resumo=$resumoIdx")
|
||||
|
||||
// Step 1: Pre-build outline-to-name lookup map to extract Sector name from grandparent outline
|
||||
val outlineMap = mutableMapOf<String, String>()
|
||||
val allOutlineNums = mutableSetOf<String>()
|
||||
for (i in 1 until rows.size) {
|
||||
val row = rows[i]
|
||||
val rawOutline = if (outlineIdx != -1 && outlineIdx < row.size) row[outlineIdx] else ""
|
||||
val outlineNum = normalizeOutlineNum(rawOutline)
|
||||
val taskName = if (taskNameIdx != -1 && taskNameIdx < row.size) row[taskNameIdx].trim() else ""
|
||||
if (outlineNum.isNotBlank()) {
|
||||
allOutlineNums.add(outlineNum)
|
||||
if (taskName.isNotBlank()) {
|
||||
outlineMap[outlineNum] = taskName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Identify parent outlines. An outline num is a parent if another outline starts with "outlineNum."
|
||||
val parentOutlines = allOutlineNums.filter { outline ->
|
||||
allOutlineNums.any { other -> other.startsWith("$outline.") }
|
||||
}.toSet()
|
||||
|
||||
Log.d(tag, "Found ${allOutlineNums.size} unique outline numbers. ${parentOutlines.size} identified as structural/parent headings.")
|
||||
|
||||
// Step 2: Build actual leaf activities
|
||||
for (i in 1 until rows.size) {
|
||||
val row = rows[i]
|
||||
val rawOutline = if (outlineIdx != -1 && outlineIdx < row.size) row[outlineIdx] else ""
|
||||
val outlineNum = normalizeOutlineNum(rawOutline)
|
||||
val idExclusiva = if (idIdx != -1 && idIdx < row.size) row[idIdx].trim() else ""
|
||||
|
||||
if (outlineNum.isBlank() || idExclusiva.isBlank()) continue
|
||||
|
||||
// Filter out if 'resumo' column is present and value is NOT 'não'/'nao' (as instructed: only count as service orders if 'resumo' is 'não')
|
||||
if (resumoIdx != -1) {
|
||||
val resumoVal = if (resumoIdx < row.size) row[resumoIdx].trim().lowercase() else ""
|
||||
if (resumoVal != "não" && resumoVal != "nao") {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// If this outline number is parent to another task, it is a grouping/structural heading (like Project, Sector or TAG), not a leaf activity
|
||||
if (outlineNum in parentOutlines) {
|
||||
continue
|
||||
}
|
||||
|
||||
val outlineParts = outlineNum.split(".")
|
||||
val osNum = "OS-$idExclusiva"
|
||||
val desc = if (taskNameIdx != -1 && taskNameIdx < row.size) row[taskNameIdx].trim() else ""
|
||||
|
||||
// Reconstruct grandparent Sector name (e.g., outline parts 1.1 -> "UTILIDADES")
|
||||
val grandparentOutline = if (outlineParts.size >= 2) outlineParts.take(2).joinToString(".") else ""
|
||||
val setor = outlineMap[grandparentOutline]?.trim() ?: "Geral"
|
||||
|
||||
// Reconstruct team (equipe) and technical responsible
|
||||
val rawEquipe = if (groupIdx != -1 && groupIdx < row.size) row[groupIdx].trim() else ""
|
||||
val equipe = if (rawEquipe.isNotBlank()) sanitizeEquipe(rawEquipe) else "Mecânica"
|
||||
|
||||
val rawResp = if (resourceIdx != -1 && resourceIdx < row.size) row[resourceIdx].trim() else ""
|
||||
val responsavel = if (rawResp.isNotBlank()) rawResp else "Sem Responsável"
|
||||
|
||||
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"
|
||||
|
||||
activities.add(
|
||||
MaintenanceActivity(
|
||||
numeroOs = osNum,
|
||||
descricao = desc,
|
||||
setor = setor,
|
||||
equipe = equipe,
|
||||
responsavel = responsavel,
|
||||
dataInicio = dataInicio,
|
||||
dataFim = dataFim,
|
||||
percentualExecucao = 0, // Determined later in repository by merging history logs
|
||||
observacoes = null,
|
||||
fotoPath = null,
|
||||
synced = true,
|
||||
lastUpdated = 0L
|
||||
)
|
||||
)
|
||||
rowMap[osNum] = i + 1
|
||||
}
|
||||
|
||||
Log.d(tag, "Finished building remote activities. Total leaf activities reconstructed: ${activities.size}.")
|
||||
return Pair(activities, rowMap)
|
||||
}
|
||||
|
||||
private fun sanitizeEquipe(equipe: String): String {
|
||||
val s = equipe.trim()
|
||||
if (s.isBlank()) return "Mecânica"
|
||||
val e = s.lowercase()
|
||||
return when {
|
||||
e.contains("mec") -> "Mecânica"
|
||||
e.contains("ele") -> "Elétrica"
|
||||
e.contains("conf") -> "Confiabilidade"
|
||||
e.contains("lub") -> "Lubrificação"
|
||||
else -> s
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches remote history logs to reconstruct OS progress and avoid duplicates.
|
||||
*/
|
||||
fun fetchRemoteHistoryKeys(): Set<String> {
|
||||
val defaultHeaders = listOf(
|
||||
"id", "numeroOs", "timestamp", "percentualAnterior", "percentualNovo", "observacao", "fotoPath", "responsavel"
|
||||
)
|
||||
ensureHeaders("history", defaultHeaders)
|
||||
|
||||
val rows = fetchValues("history!A:H")
|
||||
val keys = mutableSetOf<String>()
|
||||
if (rows.size <= 1) return keys
|
||||
|
||||
val headers = rows[0].map { it.trim().lowercase() }
|
||||
val osIdx = headers.indexOf("numeroos")
|
||||
val tsIdx = headers.indexOf("timestamp")
|
||||
|
||||
val getCell = { row: List<String>, mapIdx: Int, fallbackIdx: Int ->
|
||||
val idx = if (mapIdx != -1) mapIdx else fallbackIdx
|
||||
if (idx < row.size) row[idx].trim() else ""
|
||||
}
|
||||
|
||||
for (i in 1 until rows.size) {
|
||||
val row = rows[i]
|
||||
val os = getCell(row, osIdx, 1)
|
||||
val ts = getCell(row, tsIdx, 2)
|
||||
if (os.isNotBlank() && ts.isNotBlank()) {
|
||||
keys.add("${os}_${ts}")
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches all remote history logs to reconstruct latest state.
|
||||
*/
|
||||
fun fetchRemoteHistoryList(): List<OSUpdateHistory> {
|
||||
val defaultHeaders = listOf(
|
||||
"id", "numeroOs", "timestamp", "percentualAnterior", "percentualNovo", "observacao", "fotoPath", "responsavel"
|
||||
)
|
||||
ensureHeaders("history", defaultHeaders)
|
||||
|
||||
val rows = fetchValues("history!A:H")
|
||||
val historyList = mutableListOf<OSUpdateHistory>()
|
||||
if (rows.size <= 1) return historyList
|
||||
|
||||
val headers = rows[0].map { it.trim().lowercase() }
|
||||
val idIdx = headers.indexOf("id")
|
||||
val osIdx = headers.indexOf("numeroos")
|
||||
val tsIdx = headers.indexOf("timestamp")
|
||||
val prevIdx = headers.indexOf("percentualanterior")
|
||||
val newIdx = headers.indexOf("percentualnovo")
|
||||
val obsIdx = headers.indexOf("observacao")
|
||||
val fotoIdx = headers.indexOf("fotopath")
|
||||
val respIdx = headers.indexOf("responsavel")
|
||||
|
||||
val getCell = { row: List<String>, mapIdx: Int, fallbackIdx: Int ->
|
||||
val idx = if (mapIdx != -1) mapIdx else fallbackIdx
|
||||
if (idx < row.size) row[idx].trim() else ""
|
||||
}
|
||||
|
||||
for (i in 1 until rows.size) {
|
||||
val row = rows[i]
|
||||
val idStr = getCell(row, idIdx, 0)
|
||||
val id = idStr.toLongOrNull() ?: 0L
|
||||
val os = getCell(row, osIdx, 1)
|
||||
if (os.isBlank()) continue
|
||||
|
||||
val tsStr = getCell(row, tsIdx, 2)
|
||||
val ts = tsStr.toLongOrNull() ?: 0L
|
||||
val prevStr = getCell(row, prevIdx, 3)
|
||||
val prev = prevStr.toIntOrNull() ?: 0
|
||||
val newStr = getCell(row, newIdx, 4)
|
||||
val new = newStr.toIntOrNull() ?: 0
|
||||
val obs = getCell(row, obsIdx, 5).takeIf { it.isNotBlank() }
|
||||
val foto = getCell(row, fotoIdx, 6).takeIf { it.isNotBlank() }
|
||||
val resp = getCell(row, respIdx, 7)
|
||||
|
||||
historyList.add(
|
||||
OSUpdateHistory(
|
||||
id = id,
|
||||
numeroOs = os,
|
||||
timestamp = ts,
|
||||
percentualAnterior = prev,
|
||||
percentualNovo = new,
|
||||
observacao = obs,
|
||||
fotoPath = foto,
|
||||
responsavel = resp
|
||||
)
|
||||
)
|
||||
}
|
||||
return historyList
|
||||
}
|
||||
|
||||
/**
|
||||
* Stubs out direct activities editing since 'project' is now read-only.
|
||||
*/
|
||||
fun pushActivitiesToSheet(
|
||||
toUpdateRemote: List<Pair<MaintenanceActivity, Int>>,
|
||||
toAppendRemote: List<MaintenanceActivity>
|
||||
) {
|
||||
// No-op to respect read-only project sheets requirement
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends history entries that do not already exist on the remote sheet.
|
||||
*/
|
||||
fun pushHistoryToSheet(historyToAppend: List<OSUpdateHistory>) {
|
||||
if (historyToAppend.isEmpty()) return
|
||||
val headerIndices = mapOf(
|
||||
"id" to 0, "numeroos" to 1, "timestamp" to 2, "percentualanterior" to 3, "percentualnovo" to 4,
|
||||
"observacao" to 5, "fotopath" to 6, "responsavel" to 7
|
||||
)
|
||||
|
||||
val appendRows = historyToAppend.map { history ->
|
||||
val row = MutableList(8) { "" }
|
||||
row[headerIndices["id"] ?: 0] = history.id.toString()
|
||||
row[headerIndices["numeroos"] ?: 1] = history.numeroOs
|
||||
row[headerIndices["timestamp"] ?: 2] = history.timestamp.toString()
|
||||
row[headerIndices["percentualanterior"] ?: 3] = history.percentualAnterior.toString()
|
||||
row[headerIndices["percentualnovo"] ?: 4] = history.percentualNovo.toString()
|
||||
row[headerIndices["observacao"] ?: 5] = history.observacao ?: ""
|
||||
row[headerIndices["fotopath"] ?: 6] = history.fotoPath ?: ""
|
||||
row[headerIndices["responsavel"] ?: 7] = history.responsavel
|
||||
row
|
||||
}
|
||||
|
||||
appendValues("history!A:H", appendRows)
|
||||
Log.d(tag, "Successfully appended ${historyToAppend.size} logs to 'history' sheet.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
package com.example.data.repository
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import com.example.data.local.MaintenanceDao
|
||||
import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
|
||||
class MaintenanceRepository(
|
||||
private val dao: MaintenanceDao,
|
||||
private val context: Context
|
||||
) {
|
||||
|
||||
private val sheetsSyncService = com.example.data.remote.GoogleSheetsSyncService(context)
|
||||
|
||||
val allActivities: Flow<List<MaintenanceActivity>> = dao.getAllActivities()
|
||||
|
||||
fun getActivityByOs(numeroOs: String): Flow<MaintenanceActivity?> = dao.getActivityByOs(numeroOs)
|
||||
|
||||
fun getHistoryForOs(numeroOs: String): Flow<List<OSUpdateHistory>> = dao.getHistoryForOs(numeroOs)
|
||||
|
||||
/**
|
||||
* Updates progress of an OS, auto-generates a history record, and marks as unsynced (offline-first).
|
||||
*/
|
||||
suspend fun updateProgress(
|
||||
numeroOs: String,
|
||||
novoPercentual: Int,
|
||||
observacao: String?,
|
||||
fotoPath: String?,
|
||||
responsavel: String
|
||||
) = withContext(Dispatchers.IO) {
|
||||
val currentActivity = dao.getActivityByOsOneShot(numeroOs) ?: return@withContext
|
||||
|
||||
val updatedActivity = currentActivity.copy(
|
||||
percentualExecucao = novoPercentual.coerceIn(0, 100),
|
||||
observacoes = observacao ?: currentActivity.observacoes,
|
||||
fotoPath = fotoPath ?: currentActivity.fotoPath,
|
||||
synced = false, // Must sync later
|
||||
lastUpdated = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
dao.updateActivity(updatedActivity)
|
||||
|
||||
// Log to history
|
||||
val historyEntry = OSUpdateHistory(
|
||||
numeroOs = numeroOs,
|
||||
percentualAnterior = currentActivity.percentualExecucao,
|
||||
percentualNovo = novoPercentual,
|
||||
observacao = observacao,
|
||||
fotoPath = fotoPath,
|
||||
responsavel = responsavel
|
||||
)
|
||||
dao.insertHistory(historyEntry)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an Excel CSV file from a Uri, supporting comma (,) or semicolon (;) separators,
|
||||
* Portuguese headers, and auto-mapping columns.
|
||||
*/
|
||||
suspend fun importCsvFromUri(context: Context, uri: Uri): Result<Int> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val contentResolver = context.contentResolver
|
||||
val inputStream = contentResolver.openInputStream(uri) ?: return@withContext Result.failure(Exception("Não foi possível abrir o arquivo."))
|
||||
|
||||
val reader = BufferedReader(InputStreamReader(inputStream, "UTF-8"))
|
||||
val lines = mutableListOf<String>()
|
||||
var line: String? = reader.readLine()
|
||||
while (line != null) {
|
||||
if (line.isNotBlank()) {
|
||||
lines.add(line)
|
||||
}
|
||||
line = reader.readLine()
|
||||
}
|
||||
inputStream.close()
|
||||
|
||||
if (lines.isEmpty()) {
|
||||
return@withContext Result.failure(Exception("O arquivo está vazio."))
|
||||
}
|
||||
|
||||
// Determine separator by checking first line
|
||||
val firstLine = lines.first()
|
||||
val separator = if (firstLine.contains(";")) ";" else ","
|
||||
|
||||
// Split headers and clean up quotes/spaces
|
||||
val headers = firstLine.split(separator).map { it.replace("\"", "").trim().lowercase() }
|
||||
|
||||
// Find column indexes based on keywords
|
||||
val osIdx = headers.indexOfFirst { it.contains("os") || it.contains("numero") || it.contains("número") }
|
||||
val descIdx = headers.indexOfFirst { it.contains("desc") || it.contains("atividade") || it.contains("ação") }
|
||||
val setorIdx = headers.indexOfFirst { it.contains("setor") || it.contains("area") || it.contains("área") }
|
||||
val eqIdx = headers.indexOfFirst { it.contains("equipe") || it.contains("eq") || it.contains("disc") || it.contains("tipo") }
|
||||
val respIdx = headers.indexOfFirst { it.contains("resp") || it.contains("encarregado") || it.contains("dono") }
|
||||
val inicioIdx = headers.indexOfFirst { it.contains("inicio") || it.contains("início") || it.contains("start") }
|
||||
val fimIdx = headers.indexOfFirst { it.contains("fim") || it.contains("end") || it.contains("termino") || it.contains("término") }
|
||||
val pctIdx = headers.indexOfFirst { it.contains("pct") || it.contains("%") || it.contains("percent") || it.contains("exec") }
|
||||
|
||||
if (osIdx == -1 || descIdx == -1) {
|
||||
return@withContext Result.failure(Exception("Colunas obrigatórias não encontradas. Certifique-se de ter ao menos 'Número da OS' e 'Descrição'."))
|
||||
}
|
||||
|
||||
val importedActivities = mutableListOf<MaintenanceActivity>()
|
||||
val now = System.currentTimeMillis()
|
||||
|
||||
for (i in 1 until lines.size) {
|
||||
val rowCells = lines[i].split(separator).map { it.replace("\"", "").trim() }
|
||||
if (rowCells.size <= osIdx || rowCells.size <= descIdx) continue
|
||||
|
||||
val osNum = rowCells[osIdx]
|
||||
if (osNum.isBlank()) continue
|
||||
|
||||
val desc = rowCells[descIdx]
|
||||
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 responsavel = if (respIdx != -1 && respIdx < rowCells.size) rowCells[respIdx] else "Sem Responsável"
|
||||
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 pctStr = if (pctIdx != -1 && pctIdx < rowCells.size) rowCells[pctIdx].replace("%", "").trim() else "0"
|
||||
val pct = pctStr.toIntOrNull() ?: 0
|
||||
|
||||
importedActivities.add(
|
||||
MaintenanceActivity(
|
||||
numeroOs = osNum,
|
||||
descricao = desc,
|
||||
setor = sanitizeSetor(setor),
|
||||
equipe = sanitizeEquipe(equipe),
|
||||
responsavel = responsavel,
|
||||
dataInicio = dataInicio,
|
||||
dataFim = dataFim,
|
||||
percentualExecucao = pct.coerceIn(0, 100),
|
||||
synced = false,
|
||||
lastUpdated = now
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
if (importedActivities.isEmpty()) {
|
||||
return@withContext Result.failure(Exception("Nenhuma linha válida pôde ser importada."))
|
||||
}
|
||||
|
||||
dao.insertActivities(importedActivities)
|
||||
Result.success(importedActivities.size)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts a static sample dataset for quick testing and demonstration.
|
||||
*/
|
||||
suspend fun loadSampleData() = withContext(Dispatchers.IO) {
|
||||
val now = System.currentTimeMillis()
|
||||
val sampleActivities = listOf(
|
||||
MaintenanceActivity("OS-2", "SUBSTITUIÇÃO DO EIXO E ROTOR DO EXAUSTOR", "UTILIDADES", "Mecânica", "Carlos Silva", "14/08/2026", "18/08/2026", 0, lastUpdated = now),
|
||||
MaintenanceActivity("OS-5", "REVISÃO NO FLAP DE ENTRADA DO EXAUSTOR DA CALDEIRA", "UTILIDADES", "Mecânica", "Carlos Silva", "14/08/2026", "20/08/2026", 0, lastUpdated = now),
|
||||
MaintenanceActivity("OS-6", "REFORÇAR ESTRUTURA DO MANCAL DO VENTILADOR", "UTILIDADES", "Mecânica", "Carlos Silva", "15/08/2026", "17/08/2026", 0, lastUpdated = now),
|
||||
MaintenanceActivity("OS-8", "TROCA DOS EMBUCHAMENTOS DOS DUMPERS DO VENTILADOR PRIMARIO", "UTILIDADES", "Mecânica", "João Pedro", "14/08/2026", "14/08/2026", 0, lastUpdated = now),
|
||||
MaintenanceActivity("OS-10", "TROCA DA ROSCA CV-111014", "UTILIDADES", "Mecânica", "Marcos Rocha", "14/08/2026", "14/08/2026", 0, lastUpdated = now),
|
||||
MaintenanceActivity("OS-11", "ALINHAMENTO DA FIXAÇÃO DA BOBINA ENRROLADORA", "UTILIDADES", "Mecânica", "Marcos Rocha", "14/08/2026", "14/08/2026", 0, lastUpdated = now),
|
||||
MaintenanceActivity("OS-1024", "SUBSTITUIÇÃO DA CHAPA DE FIXAÇÃO DOS APARADORES", "UTILIDADES", "Mecânica", "GTEC 1", "17/08/2026", "18/08/2026", 50, "Iniciada a desmontagem da chapa antiga.", lastUpdated = now),
|
||||
MaintenanceActivity("OS-16", "ADEQUAÇÃO NA ALIMENTAÇÃO DA CORREIA", "UTILIDADES", "Mecânica", "GTEC 1", "19/08/2026", "21/08/2026", 10, lastUpdated = now)
|
||||
)
|
||||
dao.clearAllActivities()
|
||||
dao.insertActivities(sampleActivities)
|
||||
|
||||
// Pre-populate some history
|
||||
for (activity in sampleActivities) {
|
||||
if (activity.percentualExecucao > 0) {
|
||||
dao.insertHistory(
|
||||
OSUpdateHistory(
|
||||
numeroOs = activity.numeroOs,
|
||||
percentualAnterior = 0,
|
||||
percentualNovo = activity.percentualExecucao,
|
||||
observacao = activity.observacoes,
|
||||
responsavel = activity.responsavel,
|
||||
timestamp = now - 3600000 // 1 hour ago
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a fully functional bidirectional synchronization with the central Google Sheet.
|
||||
* Uses 'project' sheet as the read-only source of OS definitions and reconciles progress
|
||||
* dynamically using event-sourcing with the 'history' logs sheet.
|
||||
*/
|
||||
suspend fun synchronizeWithBackend(): SyncResult = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
android.util.Log.d("MaintenanceRepository", "Starting Google Sheets synchronization...")
|
||||
|
||||
// 1. Fetch remote OS definitions from the "project" sheet
|
||||
val (remoteActivities, _) = sheetsSyncService.fetchRemoteActivities()
|
||||
|
||||
// 2. Fetch remote history logs from the "history" sheet
|
||||
val remoteHistory = sheetsSyncService.fetchRemoteHistoryList()
|
||||
val remoteHistoryKeys = remoteHistory.map { "${it.numeroOs}_${it.timestamp}" }.toSet()
|
||||
|
||||
// 3. Fetch local history logs from Room DB
|
||||
val localHistory = dao.getAllHistoryList()
|
||||
|
||||
// 4. Reconcile and merge all history logs
|
||||
val allHistories = (remoteHistory + localHistory)
|
||||
.distinctBy { "${it.numeroOs}_${it.timestamp}" }
|
||||
.sortedByDescending { it.timestamp }
|
||||
|
||||
// 5. Update local Room DB with any remote history logs we don't have
|
||||
val localHistoryKeys = localHistory.map { "${it.numeroOs}_${it.timestamp}" }.toSet()
|
||||
val missingLocalHistory = remoteHistory.filter { "${it.numeroOs}_${it.timestamp}" !in localHistoryKeys }
|
||||
if (missingLocalHistory.isNotEmpty()) {
|
||||
for (hist in missingLocalHistory) {
|
||||
dao.insertHistory(hist)
|
||||
}
|
||||
android.util.Log.d("MaintenanceRepository", "Inserted ${missingLocalHistory.size} missing history logs locally.")
|
||||
}
|
||||
|
||||
// 6. For each remote activity, determine its current state based on the latest history log
|
||||
val reconciledActivities = remoteActivities.map { activity ->
|
||||
val osHistory = allHistories.filter { it.numeroOs == activity.numeroOs }
|
||||
if (osHistory.isNotEmpty()) {
|
||||
val latestLog = osHistory.first() // sorted descending, so first is latest
|
||||
activity.copy(
|
||||
percentualExecucao = latestLog.percentualNovo,
|
||||
observacoes = latestLog.observacao ?: activity.observacoes,
|
||||
fotoPath = latestLog.fotoPath ?: activity.fotoPath,
|
||||
synced = true,
|
||||
lastUpdated = latestLog.timestamp
|
||||
)
|
||||
} else {
|
||||
activity.copy(synced = true)
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Save updated OS activities to local Room DB
|
||||
if (reconciledActivities.isNotEmpty()) {
|
||||
dao.clearAllActivities() // Clear old ones since project sheet is the unique source of truth
|
||||
dao.insertActivities(reconciledActivities)
|
||||
android.util.Log.d("MaintenanceRepository", "Reconciled and saved ${reconciledActivities.size} OS activities from Google Sheet.")
|
||||
}
|
||||
|
||||
// 8. Upload any local history logs that are not on Google Sheets yet
|
||||
val historyToUpload = localHistory.filter { "${it.numeroOs}_${it.timestamp}" !in remoteHistoryKeys }
|
||||
if (historyToUpload.isNotEmpty()) {
|
||||
sheetsSyncService.pushHistoryToSheet(historyToUpload)
|
||||
android.util.Log.d("MaintenanceRepository", "Uploaded ${historyToUpload.size} new local history logs to Google Sheet.")
|
||||
}
|
||||
|
||||
SyncResult.Success(
|
||||
syncedItems = reconciledActivities.size,
|
||||
conflictsResolved = 0
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("MaintenanceRepository", "Synchronization failed", e)
|
||||
SyncResult.Error(e.message ?: "Erro de comunicação de rede com o Google Sheets.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun sanitizeSetor(setor: String): String {
|
||||
val s = setor.trim()
|
||||
if (s.isBlank()) return "Preparação"
|
||||
val lower = s.lowercase()
|
||||
return when {
|
||||
lower.contains("prepar") -> "Preparação"
|
||||
lower.contains("extra") -> "Extração"
|
||||
lower.contains("calde") -> "Caldeira"
|
||||
lower.contains("coger") || lower.contains("gira") -> "Cogeração"
|
||||
lower.contains("refin") -> "Refinaria"
|
||||
lower.contains("envas") -> "Envase"
|
||||
lower.contains("utilid") -> "Utilidades"
|
||||
else -> s
|
||||
}
|
||||
}
|
||||
|
||||
private fun sanitizeEquipe(equipe: String): String {
|
||||
val s = equipe.trim()
|
||||
if (s.isBlank()) return "Mecânica"
|
||||
val e = s.lowercase()
|
||||
return when {
|
||||
e.contains("mec") -> "Mecânica"
|
||||
e.contains("ele") -> "Elétrica"
|
||||
e.contains("conf") -> "Confiabilidade"
|
||||
e.contains("lub") -> "Lubrificação"
|
||||
else -> s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sealed interface SyncResult {
|
||||
data class Success(val syncedItems: Int, val conflictsResolved: Int) : SyncResult
|
||||
data class Error(val message: String) : SyncResult
|
||||
}
|
||||
85
app/src/main/java/com/example/ui/components/CargillLogo.kt
Normal file
@@ -0,0 +1,85 @@
|
||||
package com.example.ui.components
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.drawscope.Fill
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
// Official Cargill Colors for Theme Integration
|
||||
val CargillGreen = Color(0xFF005F40) // Beautiful forest/leaf green
|
||||
val CargillBlack = Color(0xFF1A1A1A) // High contrast premium charcoal-black
|
||||
|
||||
@Composable
|
||||
fun CargillLogo(
|
||||
modifier: Modifier = Modifier,
|
||||
showText: Boolean = true,
|
||||
lightMode: Boolean = true
|
||||
) {
|
||||
Row(
|
||||
modifier = modifier.height(48.dp),
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
// Draw the iconic curved leaf logo using Compose Canvas
|
||||
Canvas(
|
||||
modifier = Modifier
|
||||
.width(52.dp)
|
||||
.fillMaxHeight()
|
||||
.padding(vertical = 4.dp)
|
||||
) {
|
||||
val w = size.width
|
||||
val h = size.height
|
||||
|
||||
// High precision path modeling Cargill's leaf swoosh
|
||||
val path = Path().apply {
|
||||
// Outer arch
|
||||
moveTo(w * 0.05f, h * 0.85f)
|
||||
cubicTo(
|
||||
w * 0.20f, h * 0.05f, // Control 1
|
||||
w * 0.80f, h * 0.05f, // Control 2
|
||||
w * 0.95f, h * 0.85f // End
|
||||
)
|
||||
// Bottom inner curve to create a leaf shape thickness
|
||||
cubicTo(
|
||||
w * 0.75f, h * 0.35f, // Control 1 (tighter)
|
||||
w * 0.25f, h * 0.35f, // Control 2 (tighter)
|
||||
w * 0.05f, h * 0.85f // Back to start
|
||||
)
|
||||
close()
|
||||
}
|
||||
|
||||
drawPath(
|
||||
path = path,
|
||||
color = CargillGreen,
|
||||
style = Fill
|
||||
)
|
||||
}
|
||||
|
||||
if (showText) {
|
||||
Text(
|
||||
text = "Cargill",
|
||||
color = if (lightMode) CargillBlack else Color.White,
|
||||
fontSize = 24.sp,
|
||||
fontFamily = FontFamily.SansSerif,
|
||||
fontWeight = FontWeight.Black,
|
||||
fontStyle = FontStyle.Italic,
|
||||
modifier = Modifier.padding(start = 4.dp, bottom = 2.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
12
app/src/main/java/com/example/ui/theme/Color.kt
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.example.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
val CargillGreen = Color(0xFF005F40)
|
||||
val CargillBlack = Color(0xFF1A1A1A)
|
||||
val CargillLightGreen = Color(0xFFE8F5E9)
|
||||
|
||||
val DarkGreen = Color(0xFF003D28)
|
||||
val Charcoal = Color(0xFF2C2C2C)
|
||||
val LightGrey = Color(0xFFF5F7F6)
|
||||
|
||||
51
app/src/main/java/com/example/ui/theme/Theme.kt
Normal file
@@ -0,0 +1,51 @@
|
||||
package com.example.ui.theme
|
||||
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.material3.dynamicLightColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
private val DarkColorScheme =
|
||||
darkColorScheme(
|
||||
primary = CargillGreen,
|
||||
secondary = Charcoal,
|
||||
tertiary = CargillLightGreen,
|
||||
background = CargillBlack,
|
||||
surface = Charcoal
|
||||
)
|
||||
|
||||
private val LightColorScheme =
|
||||
lightColorScheme(
|
||||
primary = CargillGreen,
|
||||
secondary = CargillBlack,
|
||||
tertiary = CargillLightGreen,
|
||||
background = LightGrey,
|
||||
surface = Color.White
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun MyApplicationTheme(
|
||||
darkTheme: Boolean = isSystemInDarkTheme(),
|
||||
// Set dynamic color to false by default to strictly preserve our Cargill green identity
|
||||
dynamicColor: Boolean = false,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
val colorScheme =
|
||||
when {
|
||||
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||
val context = LocalContext.current
|
||||
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
||||
}
|
||||
|
||||
darkTheme -> DarkColorScheme
|
||||
else -> LightColorScheme
|
||||
}
|
||||
|
||||
MaterialTheme(colorScheme = colorScheme, typography = Typography, content = content)
|
||||
}
|
||||
36
app/src/main/java/com/example/ui/theme/Type.kt
Normal file
@@ -0,0 +1,36 @@
|
||||
package com.example.ui.theme
|
||||
|
||||
import androidx.compose.material3.Typography
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
// Set of Material typography styles to start with
|
||||
val Typography =
|
||||
Typography(
|
||||
bodyLarge =
|
||||
TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 24.sp,
|
||||
letterSpacing = 0.5.sp,
|
||||
)
|
||||
/* Other default text styles to override
|
||||
titleLarge = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 22.sp,
|
||||
lineHeight = 28.sp,
|
||||
letterSpacing = 0.sp
|
||||
),
|
||||
labelSmall = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Medium,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
letterSpacing = 0.5.sp
|
||||
)
|
||||
*/
|
||||
)
|
||||
@@ -0,0 +1,297 @@
|
||||
package com.example.ui.viewmodel
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.example.data.model.ActivityStatus
|
||||
import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
import com.example.data.model.extractDateOnly
|
||||
import com.example.data.model.formatToShortDate
|
||||
import com.example.data.model.parseFullDateTime
|
||||
import com.example.data.repository.MaintenanceRepository
|
||||
import com.example.data.repository.SyncResult
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class MaintenanceViewModel(private val repository: MaintenanceRepository) : ViewModel() {
|
||||
|
||||
// Filtering inputs
|
||||
private val _selectedSetor = MutableStateFlow("Todos")
|
||||
val selectedSetor = _selectedSetor.asStateFlow()
|
||||
|
||||
private val _selectedEquipe = MutableStateFlow("Todas")
|
||||
val selectedEquipe = _selectedEquipe.asStateFlow()
|
||||
|
||||
private val _selectedStatus = MutableStateFlow("Todos")
|
||||
val selectedStatus = _selectedStatus.asStateFlow()
|
||||
|
||||
private val _selectedDataInicio = MutableStateFlow("Todas")
|
||||
val selectedDataInicio = _selectedDataInicio.asStateFlow()
|
||||
|
||||
private val _selectedResponsavel = MutableStateFlow("Todos")
|
||||
val selectedResponsavel = _selectedResponsavel.asStateFlow()
|
||||
|
||||
private val _searchQuery = MutableStateFlow("")
|
||||
val searchQuery = _searchQuery.asStateFlow()
|
||||
|
||||
// UI Operation States
|
||||
private val _isSyncing = MutableStateFlow(false)
|
||||
val isSyncing = _isSyncing.asStateFlow()
|
||||
|
||||
private val _syncStatusMessage = MutableStateFlow<String?>(null)
|
||||
val syncStatusMessage = _syncStatusMessage.asStateFlow()
|
||||
|
||||
private val _importStatusMessage = MutableStateFlow<String?>(null)
|
||||
val importStatusMessage = _importStatusMessage.asStateFlow()
|
||||
|
||||
// Simulator Toggle: Allows users to simulate online/offline state explicitly in the UI
|
||||
private val _internetAvailable = MutableStateFlow(true) // Default online to ensure immediate network connectivity on launch
|
||||
val internetAvailable = _internetAvailable.asStateFlow()
|
||||
|
||||
// Selected OS for Detail and Updates
|
||||
private val _selectedActivity = MutableStateFlow<MaintenanceActivity?>(null)
|
||||
val selectedActivity = _selectedActivity.asStateFlow()
|
||||
|
||||
// All activities from repository
|
||||
val allActivitiesState: StateFlow<List<MaintenanceActivity>> = repository.allActivities
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000),
|
||||
initialValue = emptyList()
|
||||
)
|
||||
|
||||
// Filtered activities list
|
||||
val filteredActivities: StateFlow<List<MaintenanceActivity>> = combine(
|
||||
repository.allActivities,
|
||||
_selectedSetor,
|
||||
_selectedEquipe,
|
||||
_selectedStatus,
|
||||
_selectedDataInicio,
|
||||
_selectedResponsavel,
|
||||
_searchQuery
|
||||
) { flowsArray ->
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val activities = flowsArray[0] as List<MaintenanceActivity>
|
||||
val setor = flowsArray[1] as String
|
||||
val equipe = flowsArray[2] as String
|
||||
val status = flowsArray[3] as String
|
||||
val dataInicio = flowsArray[4] as String
|
||||
val responsavel = flowsArray[5] as String
|
||||
val query = flowsArray[6] as String
|
||||
|
||||
val filtered = activities.filter { activity ->
|
||||
val matchSetor = setor == "Todos" || activity.setor == setor
|
||||
val matchEquipe = equipe == "Todas" || activity.equipe == equipe
|
||||
val matchStatus = status == "Todos" || when (status) {
|
||||
"Não iniciado" -> activity.status == ActivityStatus.NAO_INICIADO
|
||||
"Em andamento" -> activity.status == ActivityStatus.EM_ANDAMENTO
|
||||
"Concluído" -> activity.status == ActivityStatus.CONCLUIDO
|
||||
else -> true
|
||||
}
|
||||
val matchDataInicio = dataInicio == "Todas" || formatToShortDate(activity.dataInicio) == dataInicio
|
||||
val matchResponsavel = responsavel == "Todos" || activity.responsavel == responsavel
|
||||
val matchQuery = query.isBlank() ||
|
||||
activity.numeroOs.contains(query, ignoreCase = true) ||
|
||||
activity.descricao.contains(query, ignoreCase = true) ||
|
||||
activity.responsavel.contains(query, ignoreCase = true)
|
||||
|
||||
matchSetor && matchEquipe && matchStatus && matchDataInicio && matchResponsavel && matchQuery
|
||||
}
|
||||
|
||||
if (dataInicio != "Todas") {
|
||||
filtered.sortedWith { a1, a2 ->
|
||||
val p1 = parseFullDateTime(a1.dataInicio)
|
||||
val p2 = parseFullDateTime(a2.dataInicio)
|
||||
when {
|
||||
p1 == null && p2 == null -> a1.numeroOs.compareTo(a2.numeroOs)
|
||||
p1 == null -> 1
|
||||
p2 == null -> -1
|
||||
else -> p1.compareTo(p2)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
filtered
|
||||
}
|
||||
}.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000),
|
||||
initialValue = emptyList()
|
||||
)
|
||||
|
||||
// Reactive Flow for the current activity's edit history
|
||||
val selectedActivityHistory: StateFlow<List<OSUpdateHistory>> = _selectedActivity
|
||||
.flatMapLatest { activity ->
|
||||
if (activity != null) {
|
||||
repository.getHistoryForOs(activity.numeroOs)
|
||||
} else {
|
||||
flowOf(emptyList())
|
||||
}
|
||||
}
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000),
|
||||
initialValue = emptyList()
|
||||
)
|
||||
|
||||
init {
|
||||
// Automatically check and pull service orders from Sheets on first launch. Fall back to local sample data if sync fails.
|
||||
viewModelScope.launch {
|
||||
val currentList = repository.allActivities.first()
|
||||
if (currentList.isEmpty()) {
|
||||
_internetAvailable.value = true
|
||||
_isSyncing.value = true
|
||||
_syncStatusMessage.value = "Conectando ao servidor Cargill para baixar ordens de serviço..."
|
||||
|
||||
when (val result = repository.synchronizeWithBackend()) {
|
||||
is SyncResult.Success -> {
|
||||
_syncStatusMessage.value = "Sincronização inicial concluída! ${result.syncedItems} OSs sincronizadas."
|
||||
}
|
||||
is SyncResult.Error -> {
|
||||
// Safe offline fallback in case of no connectivity or invalid credentials
|
||||
_syncStatusMessage.value = "Usando dados modelo: ${result.message}"
|
||||
repository.loadSampleData()
|
||||
}
|
||||
}
|
||||
_isSyncing.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun selectActivity(activity: MaintenanceActivity?) {
|
||||
_selectedActivity.value = activity
|
||||
}
|
||||
|
||||
fun setFilterSetor(setor: String) {
|
||||
_selectedSetor.value = setor
|
||||
}
|
||||
|
||||
fun setFilterEquipe(equipe: String) {
|
||||
_selectedEquipe.value = equipe
|
||||
}
|
||||
|
||||
fun setFilterStatus(status: String) {
|
||||
_selectedStatus.value = status
|
||||
}
|
||||
|
||||
fun setFilterDataInicio(dataInicio: String) {
|
||||
_selectedDataInicio.value = dataInicio
|
||||
}
|
||||
|
||||
fun setFilterResponsavel(responsavel: String) {
|
||||
_selectedResponsavel.value = responsavel
|
||||
}
|
||||
|
||||
fun setSearchQuery(query: String) {
|
||||
_searchQuery.value = query
|
||||
}
|
||||
|
||||
fun toggleInternet(available: Boolean) {
|
||||
_internetAvailable.value = available
|
||||
if (!available) {
|
||||
_syncStatusMessage.value = null
|
||||
}
|
||||
}
|
||||
|
||||
fun clearMessages() {
|
||||
_syncStatusMessage.value = null
|
||||
_importStatusMessage.value = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Triggers a PCM spreadsheet (CSV) import.
|
||||
*/
|
||||
fun importSpreadsheet(context: Context, uri: Uri) {
|
||||
viewModelScope.launch {
|
||||
_importStatusMessage.value = "Importando..."
|
||||
val result = repository.importCsvFromUri(context, uri)
|
||||
result.onSuccess { count ->
|
||||
_importStatusMessage.value = "Sucesso: $count ordens de serviço importadas/atualizadas!"
|
||||
}.onFailure { error ->
|
||||
_importStatusMessage.value = "Erro na importação: ${error.localizedMessage}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to preload sample data on-demand.
|
||||
*/
|
||||
fun resetToSampleData() {
|
||||
viewModelScope.launch {
|
||||
_importStatusMessage.value = "Carregando planilha modelo..."
|
||||
repository.loadSampleData()
|
||||
_importStatusMessage.value = "Ordens de serviço padrão carregadas com sucesso!"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs synchronized check.
|
||||
*/
|
||||
fun syncNow() {
|
||||
if (!_internetAvailable.value) {
|
||||
_syncStatusMessage.value = "Sincronização impossível: Sem conectividade de rede na área atual."
|
||||
return
|
||||
}
|
||||
|
||||
viewModelScope.launch {
|
||||
_isSyncing.value = true
|
||||
_syncStatusMessage.value = "Conectando ao servidor central da Cargill..."
|
||||
|
||||
when (val result = repository.synchronizeWithBackend()) {
|
||||
is SyncResult.Success -> {
|
||||
_syncStatusMessage.value = "Sincronização concluída! ${result.syncedItems} OSs sincronizadas com sucesso. Conflitos resolvidos: ${result.conflictsResolved}."
|
||||
// Refresh selected activity if active to show sync badge
|
||||
_selectedActivity.value?.let { active ->
|
||||
_selectedActivity.value = allActivitiesState.value.find { it.numeroOs == active.numeroOs }
|
||||
}
|
||||
}
|
||||
is SyncResult.Error -> {
|
||||
_syncStatusMessage.value = "Falha na sincronização: ${result.message}"
|
||||
}
|
||||
}
|
||||
_isSyncing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits progress updates and creates log.
|
||||
*/
|
||||
fun updateProgress(
|
||||
numeroOs: String,
|
||||
novoPercentual: Int,
|
||||
observacao: String?,
|
||||
fotoPath: String?,
|
||||
responsavel: String
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
repository.updateProgress(numeroOs, novoPercentual, observacao, fotoPath, responsavel)
|
||||
// Update selected activity model in state to refresh UI
|
||||
_selectedActivity.value?.let { active ->
|
||||
if (active.numeroOs == numeroOs) {
|
||||
val updatedList = allActivitiesState.value
|
||||
_selectedActivity.value = updatedList.find { it.numeroOs == numeroOs }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MaintenanceViewModelFactory(private val repository: MaintenanceRepository) : ViewModelProvider.Factory {
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): T {
|
||||
if (modelClass.isAssignableFrom(MaintenanceViewModel::class.java)) {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return MaintenanceViewModel(repository) as T
|
||||
}
|
||||
throw IllegalArgumentException("Unknown ViewModel class")
|
||||
}
|
||||
}
|
||||
170
app/src/main/res/drawable/ic_launcher_background.xml
Normal file
@@ -0,0 +1,170 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#3DDC84"
|
||||
android:pathData="M0,0h108v108h-108z" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M9,0L9,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,0L19,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M29,0L29,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M39,0L39,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M49,0L49,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M59,0L59,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M69,0L69,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M79,0L79,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M89,0L89,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M99,0L99,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,9L108,9"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,19L108,19"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,29L108,29"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,39L108,39"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,49L108,49"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,59L108,59"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,69L108,69"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,79L108,79"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,89L108,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,99L108,99"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,29L89,29"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,39L89,39"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,49L89,49"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,59L89,59"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,69L89,69"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,79L89,79"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M29,19L29,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M39,19L39,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M49,19L49,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M59,19L59,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M69,19L69,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M79,19L79,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
</vector>
|
||||
30
app/src/main/res/drawable/ic_launcher_foreground.xml
Normal file
@@ -0,0 +1,30 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:aapt="http://schemas.android.com/aapt"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
|
||||
<aapt:attr name="android:fillColor">
|
||||
<gradient
|
||||
android:endX="85.84757"
|
||||
android:endY="92.4963"
|
||||
android:startX="42.9492"
|
||||
android:startY="49.59793"
|
||||
android:type="linear">
|
||||
<item
|
||||
android:color="#44000000"
|
||||
android:offset="0.0" />
|
||||
<item
|
||||
android:color="#00000000"
|
||||
android:offset="1.0" />
|
||||
</gradient>
|
||||
</aapt:attr>
|
||||
</path>
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:fillType="nonZero"
|
||||
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
|
||||
android:strokeWidth="1"
|
||||
android:strokeColor="#00000000" />
|
||||
</vector>
|
||||
6
app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
6
app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
BIN
app/src/main/res/mipmap-hdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 2.0 KiB |
BIN
app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 4.2 KiB |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher.webp
Normal file
BIN
app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
Normal file
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 2.8 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 5.8 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 4.3 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 8.7 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
Normal file
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 11 KiB |
10
app/src/main/res/values/colors.xml
Normal file
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="purple_200">#FFBB86FC</color>
|
||||
<color name="purple_500">#FF6200EE</color>
|
||||
<color name="purple_700">#FF3700B3</color>
|
||||
<color name="teal_200">#FF03DAC5</color>
|
||||
<color name="teal_700">#FF018786</color>
|
||||
<color name="black">#FF000000</color>
|
||||
<color name="white">#FFFFFFFF</color>
|
||||
</resources>
|
||||
3
app/src/main/res/values/strings.xml
Normal file
@@ -0,0 +1,3 @@
|
||||
<resources>
|
||||
<string name="app_name">Cargill Parada OS</string>
|
||||
</resources>
|
||||
5
app/src/main/res/values/themes.xml
Normal file
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
|
||||
<style name="Theme.MyApplication" parent="android:Theme.DeviceDefault.NoActionBar" />
|
||||
</resources>
|
||||
13
app/src/main/res/xml/backup_rules.xml
Normal file
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?><!--
|
||||
Sample backup rules file; uncomment and customize as necessary.
|
||||
See https://developer.android.com/guide/topics/data/autobackup
|
||||
for details.
|
||||
Note: This file is ignored for devices older than API 31
|
||||
See https://developer.android.com/about/versions/12/backup-restore
|
||||
-->
|
||||
<full-backup-content>
|
||||
<!--
|
||||
<include domain="sharedpref" path="."/>
|
||||
<exclude domain="sharedpref" path="device.xml"/>
|
||||
-->
|
||||
</full-backup-content>
|
||||
19
app/src/main/res/xml/data_extraction_rules.xml
Normal file
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="utf-8"?><!--
|
||||
Sample data extraction rules file; uncomment and customize as necessary.
|
||||
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
|
||||
for details.
|
||||
-->
|
||||
<data-extraction-rules>
|
||||
<cloud-backup>
|
||||
<!-- TODO: Use <include> and <exclude> to control what is backed up.
|
||||
<include .../>
|
||||
<exclude .../>
|
||||
-->
|
||||
</cloud-backup>
|
||||
<!--
|
||||
<device-transfer>
|
||||
<include .../>
|
||||
<exclude .../>
|
||||
</device-transfer>
|
||||
-->
|
||||
</data-extraction-rules>
|
||||
69
app/src/test/java/com/example/ExampleRobolectricTest.kt
Normal file
@@ -0,0 +1,69 @@
|
||||
package com.example
|
||||
|
||||
import android.content.Context
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.example.data.local.AppDatabase
|
||||
import com.example.data.remote.GoogleSheetsSyncService
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
import kotlinx.coroutines.flow.first
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class ExampleRobolectricTest {
|
||||
|
||||
@Test
|
||||
fun `read string from context`() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val appName = context.getString(R.string.app_name)
|
||||
assertEquals("Cargill Parada OS", appName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `inspect project sheet`() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val service = GoogleSheetsSyncService(context)
|
||||
println("--- INSPECTING PROJECT SHEET ---")
|
||||
try {
|
||||
val values = service.fetchValues("project!A1:Z50")
|
||||
println("Fetched ${values.size} rows with columns up to Z")
|
||||
for ((index, row) in values.withIndex()) {
|
||||
println("Row $index: $row")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
println("Failed to fetch sheet: ${e.message}")
|
||||
e.printStackTrace()
|
||||
}
|
||||
println("--- END INSPECTING ---")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `diagnose synchronization backend`() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).build()
|
||||
val repository = com.example.data.repository.MaintenanceRepository(db.maintenanceDao(), context)
|
||||
|
||||
println("--- STARTING SYNCHRONIZE DIAGNOSTIC UPDATED ---")
|
||||
try {
|
||||
val result = kotlinx.coroutines.runBlocking {
|
||||
val r = repository.synchronizeWithBackend()
|
||||
println("Sync Result: $r")
|
||||
val list = repository.allActivities.first()
|
||||
println("Total activities in database: ${list.size}")
|
||||
list.forEach { act ->
|
||||
println(" OS: ${act.numeroOs}, Desc: ${act.descricao}, Setor: ${act.setor}, Equipe: ${act.equipe}, Pct: ${act.percentualExecucao}")
|
||||
}
|
||||
r
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
println("Sync threw exception: ${e.message}")
|
||||
e.printStackTrace()
|
||||
}
|
||||
println("--- END SYNCHRONIZE DIAGNOSTIC ---")
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
85
app/src/test/java/com/example/ExampleUnitTest.kt
Normal file
@@ -0,0 +1,85 @@
|
||||
package com.example
|
||||
|
||||
import com.example.data.model.extractDateOnly
|
||||
import com.example.data.model.formatToShortDate
|
||||
import com.example.data.model.parseDateOnly
|
||||
import com.example.data.model.parseFullDateTime
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.util.Calendar
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
class ExampleUnitTest {
|
||||
@Test
|
||||
fun addition_isCorrect() {
|
||||
assertEquals(4, 2 + 2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testExtractDateOnly() {
|
||||
assertEquals("14/08/2026", extractDateOnly("14/08/2026 08:30"))
|
||||
assertEquals("14/08/2026", extractDateOnly("14/08/2026"))
|
||||
assertEquals("2026-08-14", extractDateOnly("2026-08-14T10:15:00"))
|
||||
assertEquals("N/A", extractDateOnly("N/A"))
|
||||
assertEquals("N/A", extractDateOnly(""))
|
||||
assertEquals("14/08/26", extractDateOnly("Sex 14/08/26 07:00"))
|
||||
assertEquals("17/08/26", extractDateOnly("Seg 17/08/26"))
|
||||
assertEquals("2026-08-15", extractDateOnly("2026-08-15"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testParseDateOnly() {
|
||||
val date1 = parseDateOnly("14/08/2026")
|
||||
assertNotNull(date1)
|
||||
val cal1 = Calendar.getInstance().apply { time = date1!! }
|
||||
assertEquals(2026, cal1.get(Calendar.YEAR))
|
||||
assertEquals(Calendar.AUGUST, cal1.get(Calendar.MONTH))
|
||||
assertEquals(14, cal1.get(Calendar.DAY_OF_MONTH))
|
||||
|
||||
val date2 = parseDateOnly("2026-08-15")
|
||||
assertNotNull(date2)
|
||||
val cal2 = Calendar.getInstance().apply { time = date2!! }
|
||||
assertEquals(2026, cal2.get(Calendar.YEAR))
|
||||
assertEquals(Calendar.AUGUST, cal2.get(Calendar.MONTH))
|
||||
assertEquals(15, cal2.get(Calendar.DAY_OF_MONTH))
|
||||
|
||||
// 2-digit years support tests
|
||||
val date3 = parseDateOnly("17/08/26")
|
||||
assertNotNull(date3)
|
||||
val cal3 = Calendar.getInstance().apply { time = date3!! }
|
||||
assertEquals(2026, cal3.get(Calendar.YEAR))
|
||||
assertEquals(Calendar.AUGUST, cal3.get(Calendar.MONTH))
|
||||
assertEquals(17, cal3.get(Calendar.DAY_OF_MONTH))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testParseFullDateTime() {
|
||||
val date1 = parseFullDateTime("14/08/2026 08:30")
|
||||
assertNotNull(date1)
|
||||
val cal1 = Calendar.getInstance().apply { time = date1!! }
|
||||
assertEquals(2026, cal1.get(Calendar.YEAR))
|
||||
assertEquals(8, cal1.get(Calendar.HOUR_OF_DAY))
|
||||
assertEquals(30, cal1.get(Calendar.MINUTE))
|
||||
|
||||
val date2 = parseFullDateTime("17/08/26 14:15")
|
||||
assertNotNull(date2)
|
||||
val cal2 = Calendar.getInstance().apply { time = date2!! }
|
||||
assertEquals(2026, cal2.get(Calendar.YEAR))
|
||||
assertEquals(14, cal2.get(Calendar.HOUR_OF_DAY))
|
||||
assertEquals(15, cal2.get(Calendar.MINUTE))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testFormatToShortDate() {
|
||||
assertEquals("14/08/26", formatToShortDate("Sex 14/08/26 07:00"))
|
||||
assertEquals("14/08/26", formatToShortDate("14/08/2026 08:30"))
|
||||
assertEquals("14/08/26", formatToShortDate("14/08/2026"))
|
||||
assertEquals("15/08/26", formatToShortDate("2026-08-15"))
|
||||
assertEquals("Todas", formatToShortDate("Todas"))
|
||||
assertEquals("N/A", formatToShortDate("N/A"))
|
||||
}
|
||||
}
|
||||
33
app/src/test/java/com/example/GreetingScreenshotTest.kt
Normal file
@@ -0,0 +1,33 @@
|
||||
package com.example
|
||||
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import com.example.ui.components.CargillLogo
|
||||
import com.example.ui.theme.MyApplicationTheme
|
||||
import com.github.takahirom.roborazzi.RobolectricDeviceQualifiers
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(qualifiers = RobolectricDeviceQualifiers.Pixel8, sdk = [36])
|
||||
class GreetingScreenshotTest {
|
||||
|
||||
@get:Rule val composeTestRule = createComposeRule()
|
||||
|
||||
@Test
|
||||
fun greeting_screenshot() {
|
||||
composeTestRule.setContent {
|
||||
MyApplicationTheme {
|
||||
CargillLogo()
|
||||
}
|
||||
}
|
||||
|
||||
composeTestRule.onRoot().captureRoboImage(filePath = "src/test/screenshots/greeting.png")
|
||||
}
|
||||
}
|
||||