commit 928ca5ec706375677fb0b15fcd00db2c5f8b6965 Author: Gabriel Pizzinatto Date: Wed Jul 15 17:11:40 2026 +0000 Snapshot: Filtro de data corrigido para dd/mm/aa diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..f8b24e8 --- /dev/null +++ b/.env.example @@ -0,0 +1,10 @@ +# GEMINI_API_KEY: Required for Gemini AI API calls. +# This is a placeholder key. +# AI Studio automatically injects this at runtime from user secrets. +# Users configure this via the Secrets panel in the AI Studio UI. +GEMINI_API_KEY=MY_GEMINI_API_KEY + +# SHEETS_CREDENTIALS_JSON: Required for Google Sheets synchronization. +# Paste the entire content of your Service Account credentials .json file here as a single-line string, +# or add it through the Secrets panel in AI Studio. +SHEETS_CREDENTIALS_JSON=SHEETS_CREDENTIALS_JSON diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f6ed34e --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +*.iml +.gradle +.kotlin +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties +.env +debug.keystore +chaveacesso_sheets.apikey.json +plantops_-gestao-de-manutencao.zip diff --git a/README.md b/README.md new file mode 100644 index 0000000..72fa90c --- /dev/null +++ b/README.md @@ -0,0 +1,21 @@ +
+GHBanner +
+ +# Run and deploy your AI Studio app + +This contains everything you need to run your app locally. + +View your app in AI Studio: https://ai.studio/apps/d5626d9c-db6d-4067-9ba1-e80d37ea164f + +## Run Locally + +**Prerequisites:** [Android Studio](https://developer.android.com/studio) + + +1. Open Android Studio +2. Select **Open** and choose the directory containing this project +3. Allow Android Studio to fix any incompatibilities as it imports the project. +4. Create a file named `.env` in the project directory and set `GEMINI_API_KEY` in that file to your Gemini API key (see `.env.example` for an example) +5. Remove this line from the app's `build.gradle.kts` file: `signingConfig = signingConfigs.getByName("debugConfig")` +6. Run the app on an emulator or physical device diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..4044cc8 --- /dev/null +++ b/app/build.gradle.kts @@ -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) +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/app/proguard-rules.pro @@ -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 diff --git a/app/src/androidTest/java/com/example/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/example/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..6436111 --- /dev/null +++ b/app/src/androidTest/java/com/example/ExampleInstrumentedTest.kt @@ -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) + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..f4e5c65 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/com/example/MainActivity.kt b/app/src/main/java/com/example/MainActivity.kt new file mode 100644 index 0000000..1aa059b --- /dev/null +++ b/app/src/main/java/com/example/MainActivity.kt @@ -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) + ) + } + } + } + } +} + diff --git a/app/src/main/java/com/example/data/local/AppDatabase.kt b/app/src/main/java/com/example/data/local/AppDatabase.kt new file mode 100644 index 0000000..62607b7 --- /dev/null +++ b/app/src/main/java/com/example/data/local/AppDatabase.kt @@ -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 + } + } + } +} diff --git a/app/src/main/java/com/example/data/local/MaintenanceDao.kt b/app/src/main/java/com/example/data/local/MaintenanceDao.kt new file mode 100644 index 0000000..e7a03d7 --- /dev/null +++ b/app/src/main/java/com/example/data/local/MaintenanceDao.kt @@ -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> + + @Query("SELECT * FROM maintenance_activities WHERE numeroOs = :numeroOs LIMIT 1") + fun getActivityByOs(numeroOs: String): Flow + + @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) + + @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> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertHistory(history: OSUpdateHistory) + + @Query("SELECT * FROM maintenance_activities WHERE synced = 0") + suspend fun getUnsyncedActivities(): List + + @Query("SELECT * FROM maintenance_activities") + suspend fun getAllActivitiesList(): List + + @Query("SELECT * FROM os_update_history") + suspend fun getAllHistoryList(): List + + @Query("DELETE FROM maintenance_activities") + suspend fun clearAllActivities() + + @Query("DELETE FROM os_update_history") + suspend fun clearAllHistory() +} diff --git a/app/src/main/java/com/example/data/model/MaintenanceActivity.kt b/app/src/main/java/com/example/data/model/MaintenanceActivity.kt new file mode 100644 index 0000000..ccff2cb --- /dev/null +++ b/app/src/main/java/com/example/data/model/MaintenanceActivity.kt @@ -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 + } +} diff --git a/app/src/main/java/com/example/data/remote/GoogleSheetsSyncService.kt b/app/src/main/java/com/example/data/remote/GoogleSheetsSyncService.kt new file mode 100644 index 0000000..e1a762d --- /dev/null +++ b/app/src/main/java/com/example/data/remote/GoogleSheetsSyncService.kt @@ -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>? = null +) + +@JsonClass(generateAdapter = true) +data class BatchUpdateBody( + val valueInputOption: String = "RAW", + val data: List +) + +@JsonClass(generateAdapter = true) +data class ValueRange( + val range: String, + val values: List>, + val majorDimension: String = "ROWS" +) + +@JsonClass(generateAdapter = true) +data class AppendBody( + val range: String, + val majorDimension: String = "ROWS", + val values: List> +) + +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> { + 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>) { + 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>) { + 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) { + 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) { + 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, Map> { + val rows = fetchValues("project!A:Z") + val activities = mutableListOf() + val rowMap = mutableMapOf() + + 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() + val allOutlineNums = mutableSetOf() + 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 { + val defaultHeaders = listOf( + "id", "numeroOs", "timestamp", "percentualAnterior", "percentualNovo", "observacao", "fotoPath", "responsavel" + ) + ensureHeaders("history", defaultHeaders) + + val rows = fetchValues("history!A:H") + val keys = mutableSetOf() + 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, 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 { + val defaultHeaders = listOf( + "id", "numeroOs", "timestamp", "percentualAnterior", "percentualNovo", "observacao", "fotoPath", "responsavel" + ) + ensureHeaders("history", defaultHeaders) + + val rows = fetchValues("history!A:H") + val historyList = mutableListOf() + 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, 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>, + toAppendRemote: List + ) { + // 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) { + 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.") + } +} diff --git a/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt b/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt new file mode 100644 index 0000000..4623bca --- /dev/null +++ b/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt @@ -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> = dao.getAllActivities() + + fun getActivityByOs(numeroOs: String): Flow = dao.getActivityByOs(numeroOs) + + fun getHistoryForOs(numeroOs: String): Flow> = 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 = 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() + 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() + 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 +} diff --git a/app/src/main/java/com/example/ui/components/CargillLogo.kt b/app/src/main/java/com/example/ui/components/CargillLogo.kt new file mode 100644 index 0000000..b78829b --- /dev/null +++ b/app/src/main/java/com/example/ui/components/CargillLogo.kt @@ -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) + ) + } + } +} diff --git a/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt b/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt new file mode 100644 index 0000000..f531850 --- /dev/null +++ b/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt @@ -0,0 +1,1381 @@ +package com.example.ui.screens + +import android.widget.Toast +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.* +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.example.data.model.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.parseDateOnly +import com.example.ui.components.CargillBlack +import com.example.ui.components.CargillGreen +import com.example.ui.components.CargillLogo +import com.example.ui.viewmodel.MaintenanceViewModel +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +// Custom theme-friendly colors for indicators +val StatusGrey = Color(0xFF757575) +val StatusBlue = Color(0xFF1976D2) +val BackgroundLight = Color(0xFFF5F7F6) +val SurfaceCardLight = Color(0xFFFFFFFF) + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MaintenanceDashboardScreen( + viewModel: MaintenanceViewModel, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + + // Core states observed reactively from ViewModel + val activities by viewModel.filteredActivities.collectAsStateWithLifecycle() + val allActivities by viewModel.allActivitiesState.collectAsStateWithLifecycle() + + val selectedSetor by viewModel.selectedSetor.collectAsStateWithLifecycle() + val selectedEquipe by viewModel.selectedEquipe.collectAsStateWithLifecycle() + val selectedStatus by viewModel.selectedStatus.collectAsStateWithLifecycle() + val selectedDataInicio by viewModel.selectedDataInicio.collectAsStateWithLifecycle() + val selectedResponsavel by viewModel.selectedResponsavel.collectAsStateWithLifecycle() + val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle() + + val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle() + val syncMessage by viewModel.syncStatusMessage.collectAsStateWithLifecycle() + val importMessage by viewModel.importStatusMessage.collectAsStateWithLifecycle() + val internetAvailable by viewModel.internetAvailable.collectAsStateWithLifecycle() + val selectedActivity by viewModel.selectedActivity.collectAsStateWithLifecycle() + val selectedActivityHistory by viewModel.selectedActivityHistory.collectAsStateWithLifecycle() + + var showEditSheet by remember { mutableStateOf(false) } + var showImporterSheet by remember { mutableStateOf(false) } + var isListExpanded by remember { mutableStateOf(false) } + + val uniqueDates = remember(allActivities) { + val datesOnly = allActivities + .map { extractDateOnly(it.dataInicio) } + .filter { it.isNotBlank() && it != "N/A" } + .distinct() + + val sortedDates = datesOnly.sortedWith { d1, d2 -> + val parsed1 = parseDateOnly(d1) + val parsed2 = parseDateOnly(d2) + when { + parsed1 == null && parsed2 == null -> d1.compareTo(d2) + parsed1 == null -> 1 + parsed2 == null -> -1 + else -> parsed1.compareTo(parsed2) + } + } + val formattedDates = sortedDates.map { formatToShortDate(it) }.distinct() + listOf("Todas") + formattedDates + } + + val uniqueResponsibles = remember(allActivities) { + val resps = allActivities.map { it.responsavel }.filter { it.isNotBlank() && it != "Sem Responsável" && it != "Sem responsável" }.distinct().sorted() + listOf("Todos") + resps + } + + val uniqueSectors = remember(allActivities) { + val sectors = allActivities.map { it.setor }.filter { it.isNotBlank() }.distinct().sorted() + listOf("Todos") + sectors + } + + // Launcher for file picking (CSV Spreadsheet) + val filePickerLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.GetContent() + ) { uri -> + if (uri != null) { + viewModel.importSpreadsheet(context, uri) + } + } + + // React to messages using Toast notifications + LaunchedEffect(syncMessage) { + syncMessage?.let { + Toast.makeText(context, it, Toast.LENGTH_LONG).show() + viewModel.clearMessages() + } + } + + LaunchedEffect(importMessage) { + importMessage?.let { + Toast.makeText(context, it, Toast.LENGTH_LONG).show() + viewModel.clearMessages() + } + } + + LaunchedEffect(selectedActivity) { + if (selectedActivity != null) { + showEditSheet = true + } + } + + Scaffold( + modifier = modifier.testTag("dashboard_scaffold"), + topBar = { + TopAppBar( + title = { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + CargillLogo(lightMode = true) + Text( + text = "Paradas", + style = MaterialTheme.typography.titleLarge.copy( + fontWeight = FontWeight.Bold, + color = CargillBlack + ) + ) + } + }, + actions = { + // Connection Status Simulator + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .padding(end = 8.dp) + .clip(RoundedCornerShape(8.dp)) + .background(if (internetAvailable) Color(0xFFE8F5E9) else Color(0xFFECEFF1)) + .clickable { viewModel.toggleInternet(!internetAvailable) } + .padding(horizontal = 8.dp, vertical = 4.dp) + ) { + Icon( + imageVector = if (internetAvailable) Icons.Default.Cloud else Icons.Default.CloudOff, + contentDescription = "Estado de Rede", + tint = if (internetAvailable) CargillGreen else StatusGrey, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(4.dp)) + Text( + text = if (internetAvailable) "ONLINE" else "OFFLINE", + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + color = if (internetAvailable) CargillGreen else StatusGrey + ) + } + + // Sync button with animation + val rotationTransition = rememberInfiniteTransition(label = "sync_rotation") + val angle by rotationTransition.animateFloat( + initialValue = 0f, + targetValue = 360f, + animationSpec = infiniteRepeatable( + animation = tween(1200, easing = LinearEasing), + repeatMode = RepeatMode.Restart + ), + label = "sync_rotation_angle" + ) + + IconButton( + onClick = { viewModel.syncNow() }, + modifier = Modifier.testTag("sync_button") + ) { + Icon( + imageVector = Icons.Default.Sync, + contentDescription = "Sincronizar dados", + tint = CargillGreen, + modifier = Modifier.rotate(if (isSyncing) angle else 0f) + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = Color.White + ) + ) + }, + containerColor = BackgroundLight + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + ) { + // Summary Dashboard Metrics Block + AnimatedVisibility(visible = !isListExpanded) { + DashboardMetrics(activities = allActivities) + } + + // Search Bar & Filter Button + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + TextField( + value = searchQuery, + onValueChange = { viewModel.setSearchQuery(it) }, + placeholder = { Text("Buscar por OS, descrição...", fontSize = 14.sp) }, + leadingIcon = { Icon(Icons.Default.Search, contentDescription = "Buscar") }, + trailingIcon = { + if (searchQuery.isNotEmpty()) { + IconButton(onClick = { viewModel.setSearchQuery("") }) { + Icon(Icons.Default.Close, contentDescription = "Limpar busca") + } + } + }, + modifier = Modifier + .weight(1f) + .height(52.dp) + .testTag("search_input"), + shape = RoundedCornerShape(12.dp), + colors = TextFieldDefaults.colors( + focusedContainerColor = Color.White, + unfocusedContainerColor = Color.White, + disabledContainerColor = Color.White, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent + ), + singleLine = true + ) + } + + // Horizontally Scrollable Filters + FilterPillsRow( + selectedSetor = selectedSetor, + selectedEquipe = selectedEquipe, + selectedStatus = selectedStatus, + selectedDataInicio = selectedDataInicio, + selectedResponsavel = selectedResponsavel, + uniqueSectors = uniqueSectors, + uniqueDates = uniqueDates, + uniqueResponsibles = uniqueResponsibles, + onSetorSelected = { viewModel.setFilterSetor(it) }, + onEquipeSelected = { viewModel.setFilterEquipe(it) }, + onStatusSelected = { viewModel.setFilterStatus(it) }, + onDataInicioSelected = { viewModel.setFilterDataInicio(it) }, + onResponsavelSelected = { viewModel.setFilterResponsavel(it) } + ) + + // List Title and Item Count + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + Text( + text = "Ordens de Serviço (${activities.size})", + fontSize = 15.sp, + fontWeight = FontWeight.Bold, + color = CargillBlack + ) + IconButton( + onClick = { isListExpanded = !isListExpanded }, + modifier = Modifier.size(24.dp).testTag("toggle_expand_list_button") + ) { + Icon( + imageVector = if (isListExpanded) Icons.Default.FullscreenExit else Icons.Default.Fullscreen, + contentDescription = if (isListExpanded) "Recolher visualização" else "Expandir listagem", + tint = CargillGreen, + modifier = Modifier.size(20.dp) + ) + } + } + + if (activities.isEmpty()) { + TextButton(onClick = { viewModel.resetToSampleData() }) { + Text("Carregar Demo", color = CargillGreen, fontSize = 13.sp, fontWeight = FontWeight.Bold) + } + } + } + + // Main OS List View + if (activities.isEmpty()) { + Box( + modifier = Modifier + .fillMaxWidth() + .weight(1f) + .padding(32.dp), + contentAlignment = Alignment.Center + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + Icon( + imageVector = Icons.Default.FilterList, + contentDescription = "Sem atividades", + tint = StatusGrey.copy(alpha = 0.5f), + modifier = Modifier.size(64.dp) + ) + Text( + text = "Nenhuma OS corresponde aos filtros", + fontSize = 16.sp, + fontWeight = FontWeight.SemiBold, + color = StatusGrey + ) + Text( + text = "Experimente limpar os filtros ou pre-carregar a planilha de testes do PCM.", + fontSize = 13.sp, + color = StatusGrey, + modifier = Modifier.padding(horizontal = 16.dp), + lineHeight = 18.sp + ) + Spacer(modifier = Modifier.height(8.dp)) + Button( + onClick = { + viewModel.setFilterSetor("Todos") + viewModel.setFilterEquipe("Todas") + viewModel.setFilterStatus("Todos") + viewModel.setFilterDataInicio("Todas") + viewModel.setFilterResponsavel("Todos") + viewModel.setSearchQuery("") + }, + colors = ButtonDefaults.buttonColors(containerColor = CargillBlack) + ) { + Text("Limpar Todos os Filtros") + } + } + } + } else { + LazyColumn( + modifier = Modifier + .weight(1f) + .fillMaxWidth(), + contentPadding = PaddingValues(bottom = 16.dp) + ) { + items(activities, key = { it.numeroOs }) { activity -> + OSListItemCard( + activity = activity, + onClick = { viewModel.selectActivity(activity) } + ) + } + } + } + } + + // Details & Edit bottom sheet + if (showEditSheet && selectedActivity != null) { + EditActivityBottomSheet( + activity = selectedActivity!!, + history = selectedActivityHistory, + onDismiss = { + showEditSheet = false + viewModel.selectActivity(null) + }, + onUpdateProgress = { newPct, comment, mockPhoto -> + viewModel.updateProgress( + numeroOs = selectedActivity!!.numeroOs, + novoPercentual = newPct, + observacao = comment, + fotoPath = mockPhoto, + responsavel = "Encarregado Campo" + ) + } + ) + } + + // CSV Importer Utility Sheet + if (showImporterSheet) { + ImporterConsoleSheet( + onDismiss = { showImporterSheet = false }, + onChooseFile = { filePickerLauncher.launch("text/*") }, + onLoadSample = { + viewModel.resetToSampleData() + showImporterSheet = false + } + ) + } + } +} + +/** + * KPI Performance cards layout + */ +@Composable +fun DashboardMetrics(activities: List) { + val totalCount = activities.size + val completedCount = activities.count { it.status == ActivityStatus.CONCLUIDO } + val inProgressCount = activities.count { it.status == ActivityStatus.EM_ANDAMENTO } + val notStartedCount = activities.count { it.status == ActivityStatus.NAO_INICIADO } + + // Average overall completion percentage + val avgProgress = if (totalCount > 0) { + activities.sumOf { it.percentualExecucao } / totalCount + } else { + 0 + } + + Card( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp), + colors = CardDefaults.cardColors(containerColor = Color.White), + elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), + shape = RoundedCornerShape(16.dp) + ) { + Column( + modifier = Modifier.padding(16.dp) + ) { + // Top Row: Title & Overall Progress Circle Indicator + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column { + Text( + text = "Progresso Parada Industrial", + fontSize = 12.sp, + fontWeight = FontWeight.Bold, + color = StatusGrey + ) + Text( + text = "Visão Geral de Campo", + fontSize = 18.sp, + fontWeight = FontWeight.Black, + color = CargillBlack + ) + } + + // Overall Circular Progress Gauge + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.size(54.dp) + ) { + CircularProgressIndicator( + progress = { avgProgress.toFloat() / 100f }, + modifier = Modifier.fillMaxSize(), + color = CargillGreen, + strokeWidth = 6.dp, + trackColor = Color(0xFFE8F5E9) + ) + Text( + text = "$avgProgress%", + fontSize = 12.sp, + fontWeight = FontWeight.Black, + color = CargillGreen + ) + } + } + + Spacer(modifier = Modifier.height(12.dp)) + HorizontalDivider(color = Color(0xFFF1F1F1)) + Spacer(modifier = Modifier.height(12.dp)) + + // Lower metrics grid split in three columns + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween + ) { + MetricColumn(value = "$notStartedCount", label = "Não Inic.", color = StatusGrey, icon = Icons.Default.PlayArrow) + MetricColumn(value = "$inProgressCount", label = "Em Andam.", color = StatusBlue, icon = Icons.Default.Speed) + MetricColumn(value = "$completedCount", label = "Concluídas", color = CargillGreen, icon = Icons.Default.CheckCircle) + MetricColumn(value = "$totalCount", label = "Total OSs", color = CargillBlack, icon = Icons.Default.Build) + } + } + } +} + +@Composable +fun MetricColumn(value: String, label: String, color: Color, icon: androidx.compose.ui.graphics.vector.ImageVector) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Icon(imageVector = icon, contentDescription = label, tint = color, modifier = Modifier.size(14.dp)) + Text( + text = value, + fontSize = 18.sp, + fontWeight = FontWeight.Black, + color = color + ) + } + Text( + text = label, + fontSize = 11.sp, + color = StatusGrey, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(top = 2.dp) + ) + } +} + +/** + * Horizontally Scrollable Filters Segment + */ +@Composable +fun FilterPillsRow( + selectedSetor: String, + selectedEquipe: String, + selectedStatus: String, + selectedDataInicio: String, + selectedResponsavel: String, + uniqueSectors: List, + uniqueDates: List, + uniqueResponsibles: List, + onSetorSelected: (String) -> Unit, + onEquipeSelected: (String) -> Unit, + onStatusSelected: (String) -> Unit, + onDataInicioSelected: (String) -> Unit, + onResponsavelSelected: (String) -> Unit +) { + val setores = uniqueSectors + val equipes = listOf("Todas", "Mecânica", "Elétrica", "Confiabilidade", "Lubrificação") + val statusList = listOf("Todos", "Não iniciado", "Em andamento", "Concluído") + + Column( + modifier = Modifier + .fillMaxWidth() + .padding(bottom = 8.dp), + verticalArrangement = Arrangement.spacedBy(6.dp) + ) { + // Sectors Row + Row(modifier = Modifier.padding(horizontal = 16.dp)) { + Text("Setor:", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = StatusGrey, modifier = Modifier.width(72.dp).align(Alignment.CenterVertically)) + LazyRow( + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.fillMaxWidth() + ) { + items(setores) { setor -> + val isSelected = setor == selectedSetor + FilterChipWidget(text = setor, isSelected = isSelected, onClick = { onSetorSelected(setor) }) + } + } + } + + // Equipes Row + Row(modifier = Modifier.padding(horizontal = 16.dp)) { + Text("Equipe:", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = StatusGrey, modifier = Modifier.width(72.dp).align(Alignment.CenterVertically)) + LazyRow( + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.fillMaxWidth() + ) { + items(equipes) { eq -> + val isSelected = eq == selectedEquipe + FilterChipWidget(text = eq, isSelected = isSelected, onClick = { onEquipeSelected(eq) }) + } + } + } + + // Status Row + Row(modifier = Modifier.padding(horizontal = 16.dp)) { + Text("Status:", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = StatusGrey, modifier = Modifier.width(72.dp).align(Alignment.CenterVertically)) + LazyRow( + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.fillMaxWidth() + ) { + items(statusList) { stat -> + val isSelected = stat == selectedStatus + FilterChipWidget(text = stat, isSelected = isSelected, onClick = { onStatusSelected(stat) }) + } + } + } + + // Execution Date Row + Row(modifier = Modifier.padding(horizontal = 16.dp)) { + Text("Data:", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = StatusGrey, modifier = Modifier.width(72.dp).align(Alignment.CenterVertically)) + LazyRow( + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.fillMaxWidth() + ) { + items(uniqueDates) { dateVal -> + val isSelected = dateVal == selectedDataInicio + FilterChipWidget(text = dateVal, isSelected = isSelected, onClick = { onDataInicioSelected(dateVal) }) + } + } + } + + // Responsible Row + Row(modifier = Modifier.padding(horizontal = 16.dp)) { + Text("Resp.:", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = StatusGrey, modifier = Modifier.width(72.dp).align(Alignment.CenterVertically)) + LazyRow( + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.fillMaxWidth() + ) { + items(uniqueResponsibles) { respVal -> + val isSelected = respVal == selectedResponsavel + FilterChipWidget(text = respVal, isSelected = isSelected, onClick = { onResponsavelSelected(respVal) }) + } + } + } + } +} + +@Composable +fun FilterChipWidget(text: String, isSelected: Boolean, onClick: () -> Unit) { + Surface( + onClick = onClick, + shape = RoundedCornerShape(20.dp), + color = if (isSelected) CargillGreen else Color.White, + border = BorderStroke(1.dp, if (isSelected) Color.Transparent else Color(0xFFE0E0E0)), + modifier = Modifier.height(28.dp) + ) { + Box( + modifier = Modifier.padding(horizontal = 10.dp), + contentAlignment = Alignment.Center + ) { + Text( + text = text, + color = if (isSelected) Color.White else CargillBlack, + fontSize = 11.sp, + fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium + ) + } + } +} + +/** + * Beautiful Individual OS Card + */ +@Composable +fun OSListItemCard( + activity: MaintenanceActivity, + onClick: () -> Unit +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 6.dp) + .clickable(onClick = onClick) + .testTag("os_card_${activity.numeroOs}"), + colors = CardDefaults.cardColors(containerColor = SurfaceCardLight), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp), + shape = RoundedCornerShape(12.dp) + ) { + Column( + modifier = Modifier.padding(14.dp) + ) { + // Header Row: OS Number + Sync Icon + Status Badge + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) + ) { + Text( + text = activity.numeroOs, + fontWeight = FontWeight.Black, + fontSize = 15.sp, + color = CargillBlack + ) + + // Sync Status Badge + Icon( + imageVector = if (activity.synced) Icons.Default.CloudDone else Icons.Default.CloudQueue, + contentDescription = if (activity.synced) "Sincronizado" else "Salvo localmente offline", + tint = if (activity.synced) CargillGreen else Color(0xFFFF9100), + modifier = Modifier.size(16.dp) + ) + } + + // Completion status pill + val badgeColor = when (activity.status) { + ActivityStatus.NAO_INICIADO -> Color(0xFFECEFF1) + ActivityStatus.EM_ANDAMENTO -> Color(0xFFE3F2FD) + ActivityStatus.CONCLUIDO -> Color(0xFFE8F5E9) + } + val badgeTextColor = when (activity.status) { + ActivityStatus.NAO_INICIADO -> StatusGrey + ActivityStatus.EM_ANDAMENTO -> StatusBlue + ActivityStatus.CONCLUIDO -> CargillGreen + } + + Box( + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .background(badgeColor) + .padding(horizontal = 8.dp, vertical = 3.dp) + ) { + Text( + text = activity.status.displayName, + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + color = badgeTextColor + ) + } + } + + Spacer(modifier = Modifier.height(6.dp)) + + // Title Description + Text( + text = activity.descricao, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = CargillBlack, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + + Spacer(modifier = Modifier.height(10.dp)) + + // Subtitle Row: Sector + Discipline Tags + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + // Sector Tag + Box( + modifier = Modifier + .clip(RoundedCornerShape(4.dp)) + .background(Color(0xFFF0F4F2)) + .padding(horizontal = 6.dp, vertical = 2.dp) + ) { + Text( + text = activity.setor, + fontSize = 10.sp, + fontWeight = FontWeight.Bold, + color = CargillGreen + ) + } + + // Equipe Tag + val eqBg = when (activity.equipe) { + "Mecânica" -> Color(0xFFFFEBEE) + "Elétrica" -> Color(0xFFE8EAF6) + "Confiabilidade" -> Color(0xFFE8F5E9) + "Lubrificação" -> Color(0xFFFFF3E0) + else -> Color(0xFFF5F5F5) + } + val eqColor = when (activity.equipe) { + "Mecânica" -> Color(0xFFC62828) + "Elétrica" -> Color(0xFF283593) + "Confiabilidade" -> Color(0xFF2E7D32) + "Lubrificação" -> Color(0xFFEF6C00) + else -> StatusGrey + } + + Box( + modifier = Modifier + .clip(RoundedCornerShape(4.dp)) + .background(eqBg) + .padding(horizontal = 6.dp, vertical = 2.dp) + ) { + Text( + text = activity.equipe, + fontSize = 10.sp, + fontWeight = FontWeight.Bold, + color = eqColor + ) + } + } + + // Responsible Supervisor Initials / Name + Text( + text = "Resp: ${activity.responsavel}", + fontSize = 11.sp, + color = StatusGrey, + fontWeight = FontWeight.Medium + ) + } + + Spacer(modifier = Modifier.height(12.dp)) + + // Bottom Row: Completion Slider Graphic & Dates + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + // Progress Bar Line + Box( + modifier = Modifier + .weight(1f) + .height(8.dp) + .clip(CircleShape) + .background(Color(0xFFEEEEEE)) + ) { + Box( + modifier = Modifier + .fillMaxWidth(activity.percentualExecucao.toFloat() / 100f) + .height(8.dp) + .clip(CircleShape) + .background(if (activity.percentualExecucao >= 100) CargillGreen else StatusBlue) + ) + } + + // Percent Text + Text( + text = "${activity.percentualExecucao}%", + fontSize = 12.sp, + fontWeight = FontWeight.Black, + color = if (activity.percentualExecucao >= 100) CargillGreen else StatusBlue + ) + } + + Spacer(modifier = Modifier.height(4.dp)) + + // Dates Label + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween + ) { + Text( + text = "Prazo: ${activity.dataInicio} até ${activity.dataFim}", + fontSize = 10.sp, + color = StatusGrey + ) + + if (activity.observacoes != null) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(2.dp) + ) { + Icon(Icons.Default.Notes, contentDescription = "Possui notas", tint = StatusGrey, modifier = Modifier.size(10.dp)) + Text("Nota", fontSize = 10.sp, color = StatusGrey, fontWeight = FontWeight.Bold) + } + } + } + } + } +} + +/** + * Modal Bottom Sheet for OS Details, Editing and Timeline History + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun EditActivityBottomSheet( + activity: MaintenanceActivity, + history: List, + onDismiss: () -> Unit, + onUpdateProgress: (Int, String, String?) -> Unit +) { + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + containerColor = Color.White + ) { + var progressValue by remember(activity) { mutableStateOf(activity.percentualExecucao.toFloat()) } + var observationText by remember { mutableStateOf("") } + var selectedMockPhotoPath by remember { mutableStateOf(null) } + var isSubmitting by remember { mutableStateOf(false) } + + // Mock photos available in the field for maintenance logs + val mockPhotos = listOf( + "Turbina" to "ic_turbine_mock", + "Fiação Elétrica" to "ic_electrical_mock", + "Mancal Engraxado" to "ic_gear_mock", + "Caldeira Lavada" to "ic_boiler_mock" + ) + + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp, vertical = 8.dp) + .verticalScroll(rememberScrollState()) // Allow full content scrolling on small screens + .navigationBarsPadding(), // Prevent covering by standard bottom navigation buttons + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + // Header: OS + Close + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column { + Text( + text = "ATUALIZAR ORDEM DE SERVIÇO", + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + color = StatusGrey + ) + Text( + text = activity.numeroOs, + fontSize = 20.sp, + fontWeight = FontWeight.Black, + color = CargillBlack + ) + } + + IconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Fechar") + } + } + + // Description Box + Card( + colors = CardDefaults.cardColors(containerColor = BackgroundLight), + shape = RoundedCornerShape(8.dp) + ) { + Column(modifier = Modifier.padding(12.dp)) { + Text( + text = activity.descricao, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = CargillBlack + ) + Spacer(modifier = Modifier.height(8.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { + Text("Setor: ${activity.setor}", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = CargillGreen) + Text("Equipe: ${activity.equipe}", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = StatusBlue) + Text("Resp: ${activity.responsavel}", fontSize = 11.sp, color = StatusGrey) + } + } + } + + // Slider Progress Update Panel + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = "Percentual de Execução", + fontWeight = FontWeight.Bold, + fontSize = 14.sp, + color = CargillBlack + ) + Text( + text = "${progressValue.toInt()}%", + fontWeight = FontWeight.Black, + fontSize = 18.sp, + color = if (progressValue >= 100) CargillGreen else StatusBlue + ) + } + + Slider( + value = progressValue, + onValueChange = { progressValue = it }, + valueRange = 0f..100f, + steps = 19, // Splits in 5% increments for rapid tactile field logging + colors = SliderDefaults.colors( + thumbColor = if (progressValue >= 100) CargillGreen else StatusBlue, + activeTrackColor = if (progressValue >= 100) CargillGreen else StatusBlue + ) + ) + + // Quick jump buttons for field speed + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + Button( + onClick = { progressValue = 0f }, + modifier = Modifier.weight(1f).height(36.dp), + colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFECEFF1)), + contentPadding = PaddingValues(0.dp) + ) { + Text("0% (Zerar)", color = StatusGrey, fontSize = 11.sp, fontWeight = FontWeight.Bold) + } + Button( + onClick = { progressValue = 50f }, + modifier = Modifier.weight(1f).height(36.dp), + colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFE3F2FD)), + contentPadding = PaddingValues(0.dp) + ) { + Text("50% (Metade)", color = StatusBlue, fontSize = 11.sp, fontWeight = FontWeight.Bold) + } + Button( + onClick = { progressValue = 100f }, + modifier = Modifier.weight(1f).height(36.dp), + colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFE8F5E9)), + contentPadding = PaddingValues(0.dp) + ) { + Text("100% (Concluir)", color = CargillGreen, fontSize = 11.sp, fontWeight = FontWeight.Bold) + } + } + } + + // Text Observation Entry + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text( + text = "Observações de Campo", + fontWeight = FontWeight.Bold, + fontSize = 14.sp, + color = CargillBlack + ) + OutlinedTextField( + value = observationText, + onValueChange = { observationText = it }, + placeholder = { Text("Descreva anomalias, materiais usados ou causas de atraso...", fontSize = 13.sp) }, + modifier = Modifier + .fillMaxWidth() + .height(80.dp) + .testTag("os_notes_field"), + maxLines = 3, + shape = RoundedCornerShape(8.dp) + ) + } + + // Photo Attachment Section (Simulating Field Camera Capture) + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text( + text = "Anexar Foto de Campo (Simulador de Câmera)", + fontWeight = FontWeight.Bold, + fontSize = 14.sp, + color = CargillBlack + ) + Text( + text = "Selecione uma categoria de inspeção para simular o anexo fotográfico da atividade:", + fontSize = 11.sp, + color = StatusGrey + ) + + LazyRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.fillMaxWidth() + ) { + items(mockPhotos) { (label, mockName) -> + val isSelected = selectedMockPhotoPath == mockName + Surface( + onClick = { selectedMockPhotoPath = if (isSelected) null else mockName }, + shape = RoundedCornerShape(8.dp), + color = if (isSelected) Color(0xFFE8F5E9) else Color(0xFFF5F5F5), + border = BorderStroke(1.dp, if (isSelected) CargillGreen else Color(0xFFE0E0E0)), + modifier = Modifier.height(48.dp) + ) { + Row( + modifier = Modifier.padding(horizontal = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Icon( + imageVector = Icons.Default.CameraAlt, + contentDescription = label, + tint = if (isSelected) CargillGreen else StatusGrey, + modifier = Modifier.size(16.dp) + ) + Text( + text = label, + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + color = if (isSelected) CargillGreen else CargillBlack + ) + } + } + } + } + + // Show Selected Photo Preview Simulation + if (selectedMockPhotoPath != null) { + Box( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .background(Color(0xFFE8F5E9)) + .padding(8.dp), + contentAlignment = Alignment.CenterStart + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + Icon(Icons.Default.Check, contentDescription = "Foto vinculada", tint = CargillGreen) + Text( + text = "Foto do componente '$selectedMockPhotoPath' anexada com sucesso à OS localmente!", + fontSize = 11.sp, + color = CargillGreen, + fontWeight = FontWeight.Bold + ) + } + } + } + } + + // Save Action Button + Button( + onClick = { + isSubmitting = true + onUpdateProgress(progressValue.toInt(), observationText, selectedMockPhotoPath) + onDismiss() + }, + modifier = Modifier + .fillMaxWidth() + .height(48.dp) + .testTag("save_progress_button"), + colors = ButtonDefaults.buttonColors(containerColor = CargillGreen), + shape = RoundedCornerShape(10.dp) + ) { + Icon(Icons.Default.Save, contentDescription = "Salvar") + Spacer(modifier = Modifier.width(6.dp)) + Text("Salvar Atualizações (Salva Local Offline)", fontWeight = FontWeight.Black) + } + + // Chronological Audit Timeline Log / History Section + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + HorizontalDivider(color = Color(0xFFF1F1F1)) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) + ) { + Icon(Icons.Default.History, contentDescription = "Histórico", tint = CargillBlack, modifier = Modifier.size(18.dp)) + Text( + text = "Histórico de Atualizações da OS", + fontWeight = FontWeight.Bold, + fontSize = 14.sp, + color = CargillBlack + ) + } + + if (history.isEmpty()) { + Box( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 12.dp), + contentAlignment = Alignment.Center + ) { + Text( + text = "Nenhuma atualização anterior registrada para esta OS.", + fontSize = 11.sp, + color = StatusGrey + ) + } + } else { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + history.forEach { log -> + TimelineLogItem(log = log) + } + } + } + } + } + } +} + +@Composable +fun TimelineLogItem(log: OSUpdateHistory) { + val dateStr = remember(log.timestamp) { + val sdf = SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault()) + sdf.format(Date(log.timestamp)) + } + + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = Color(0xFFFAFAFA)), + border = BorderStroke(1.dp, Color(0xFFEEEEEE)), + shape = RoundedCornerShape(6.dp) + ) { + Column(modifier = Modifier.padding(10.dp)) { + // Header Row: User, timestamp and progress jump + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Icon(Icons.Default.Person, contentDescription = "Usuário", tint = StatusGrey, modifier = Modifier.size(12.dp)) + Text( + text = log.responsavel, + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + color = CargillBlack + ) + } + Text( + text = dateStr, + fontSize = 10.sp, + color = StatusGrey + ) + } + + Spacer(modifier = Modifier.height(4.dp)) + + // Progress Jump Badge + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) + ) { + Text( + text = "Avanço:", + fontSize = 11.sp, + color = StatusGrey + ) + Text( + text = "${log.percentualAnterior}% ➜ ${log.percentualNovo}%", + fontSize = 11.sp, + fontWeight = FontWeight.Black, + color = if (log.percentualNovo >= 100) CargillGreen else StatusBlue + ) + } + + // Remarks/Observations + if (!log.observacao.isNullOrBlank()) { + Spacer(modifier = Modifier.height(4.dp)) + Box( + modifier = Modifier + .fillMaxWidth() + .background(Color(0xFFF1F1F1)) + .padding(6.dp) + .clip(RoundedCornerShape(4.dp)) + ) { + Text( + text = "\"${log.observacao}\"", + fontSize = 11.sp, + color = CargillBlack + ) + } + } + + // If photo was attached + if (!log.fotoPath.isNullOrBlank()) { + Spacer(modifier = Modifier.height(4.dp)) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier + .clip(RoundedCornerShape(4.dp)) + .background(Color(0xFFE8F5E9)) + .padding(horizontal = 6.dp, vertical = 2.dp) + ) { + Icon(Icons.Default.CameraAlt, contentDescription = "Foto", tint = CargillGreen, modifier = Modifier.size(10.dp)) + Text("Foto Anexa: ${log.fotoPath}", fontSize = 9.sp, color = CargillGreen, fontWeight = FontWeight.Bold) + } + } + } + } +} + +/** + * Importer Console Sheet for loading spreadsheets and managing datasets + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ImporterConsoleSheet( + onDismiss: () -> Unit, + onChooseFile: () -> Unit, + onLoadSample: () -> Unit +) { + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = rememberModalBottomSheetState(), + containerColor = Color.White + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp, vertical = 12.dp) + .navigationBarsPadding(), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column { + Text( + text = "PCM PLANILHAS", + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + color = StatusGrey + ) + Text( + text = "Importar Planilha do PCM", + fontSize = 18.sp, + fontWeight = FontWeight.Black, + color = CargillBlack + ) + } + IconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Fechar") + } + } + + Text( + text = "Integração facilitada offline com arquivos de ordens de serviço exportados diretamente do Excel em formato CSV/Planilha.", + fontSize = 13.sp, + color = StatusGrey, + lineHeight = 18.sp + ) + + // Dynamic specifications for CSV + Card( + colors = CardDefaults.cardColors(containerColor = BackgroundLight), + shape = RoundedCornerShape(8.dp) + ) { + Column( + modifier = Modifier.padding(12.dp), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + Text("Estrutura Esperada do Arquivo (Excel):", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = CargillBlack) + Text("• Colunas Obrigatórias: Número da OS, Descrição da Atividade", fontSize = 11.sp, color = StatusGrey) + Text("• Colunas Opcionais: Setor, Equipe, Responsável, Início, Fim, %", fontSize = 11.sp, color = StatusGrey) + Text("• Suporta separadores por Vírgula (,) ou Ponto e Vírgula (;)", fontSize = 11.sp, color = StatusGrey) + } + } + + // Main Actions + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + // Action 1: Upload real device CSV + Button( + onClick = { + onChooseFile() + onDismiss() + }, + modifier = Modifier + .fillMaxWidth() + .height(48.dp), + colors = ButtonDefaults.buttonColors(containerColor = CargillGreen) + ) { + Icon(Icons.Default.UploadFile, contentDescription = "Upload CSV") + Spacer(modifier = Modifier.width(8.dp)) + Text("Selecionar CSV no Dispositivo", fontWeight = FontWeight.Bold) + } + + // Action 2: Load model data directly + OutlinedButton( + onClick = { + onLoadSample() + onDismiss() + }, + modifier = Modifier + .fillMaxWidth() + .height(48.dp), + colors = ButtonDefaults.outlinedButtonColors(contentColor = CargillBlack), + border = BorderStroke(1.dp, CargillBlack) + ) { + Icon(Icons.Default.FileOpen, contentDescription = "Carregar Planilha Modelo") + Spacer(modifier = Modifier.width(8.dp)) + Text("Pre-carregar Planilha Modelo Cargill (10 OSs)", fontWeight = FontWeight.Bold) + } + } + + Spacer(modifier = Modifier.height(16.dp)) + } + } +} + +// Extension to allow custom vertical scrolling on the BottomSheet contents +@Composable +fun rememberScrollState() = androidx.compose.foundation.rememberScrollState() diff --git a/app/src/main/java/com/example/ui/theme/Color.kt b/app/src/main/java/com/example/ui/theme/Color.kt new file mode 100644 index 0000000..b710d16 --- /dev/null +++ b/app/src/main/java/com/example/ui/theme/Color.kt @@ -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) + diff --git a/app/src/main/java/com/example/ui/theme/Theme.kt b/app/src/main/java/com/example/ui/theme/Theme.kt new file mode 100644 index 0000000..097100a --- /dev/null +++ b/app/src/main/java/com/example/ui/theme/Theme.kt @@ -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) +} diff --git a/app/src/main/java/com/example/ui/theme/Type.kt b/app/src/main/java/com/example/ui/theme/Type.kt new file mode 100644 index 0000000..b631a6b --- /dev/null +++ b/app/src/main/java/com/example/ui/theme/Type.kt @@ -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 + ) + */ + ) diff --git a/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt b/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt new file mode 100644 index 0000000..c24c82d --- /dev/null +++ b/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt @@ -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(null) + val syncStatusMessage = _syncStatusMessage.asStateFlow() + + private val _importStatusMessage = MutableStateFlow(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(null) + val selectedActivity = _selectedActivity.asStateFlow() + + // All activities from repository + val allActivitiesState: StateFlow> = repository.allActivities + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5000), + initialValue = emptyList() + ) + + // Filtered activities list + val filteredActivities: StateFlow> = combine( + repository.allActivities, + _selectedSetor, + _selectedEquipe, + _selectedStatus, + _selectedDataInicio, + _selectedResponsavel, + _searchQuery + ) { flowsArray -> + @Suppress("UNCHECKED_CAST") + val activities = flowsArray[0] as List + 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> = _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 create(modelClass: Class): T { + if (modelClass.isAssignableFrom(MaintenanceViewModel::class.java)) { + @Suppress("UNCHECKED_CAST") + return MaintenanceViewModel(repository) as T + } + throw IllegalArgumentException("Unknown ViewModel class") + } +} diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..7706ab9 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..b3e26b4 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..b3e26b4 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..22a7139 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..390f9b5 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..97cbbb1 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..313d7c3 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..3ae3972 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..449a793 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..1081450 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..cefa5e4 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..a351935 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..4046ce1 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..ca1931b --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..3110b01 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Cargill Parada OS + diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..839cd48 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,5 @@ + + + +