feat: enhance date parsing with timestamp support, refine CSV import column mapping, and update overdue activity logic.
This commit is contained in:
@@ -107,7 +107,14 @@ class MaintenanceRepository(
|
|||||||
try {
|
try {
|
||||||
val contentResolver = context.contentResolver
|
val contentResolver = context.contentResolver
|
||||||
val inputStream = contentResolver.openInputStream(uri) ?: return@withContext Result.failure(Exception("Não foi possível abrir o arquivo."))
|
val inputStream = contentResolver.openInputStream(uri) ?: return@withContext Result.failure(Exception("Não foi possível abrir o arquivo."))
|
||||||
|
importCsvFromInputStream(inputStream)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Result.failure(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun importCsvFromInputStream(inputStream: java.io.InputStream): Result<Int> = withContext(Dispatchers.IO) {
|
||||||
|
try {
|
||||||
val reader = BufferedReader(InputStreamReader(inputStream, "UTF-8"))
|
val reader = BufferedReader(InputStreamReader(inputStream, "UTF-8"))
|
||||||
val lines = mutableListOf<String>()
|
val lines = mutableListOf<String>()
|
||||||
var line: String? = reader.readLine()
|
var line: String? = reader.readLine()
|
||||||
@@ -131,15 +138,15 @@ class MaintenanceRepository(
|
|||||||
val headers = firstLine.split(separator).map { it.replace("\"", "").trim().lowercase() }
|
val headers = firstLine.split(separator).map { it.replace("\"", "").trim().lowercase() }
|
||||||
|
|
||||||
// Find column indexes based on keywords
|
// Find column indexes based on keywords
|
||||||
val osIdx = headers.indexOfFirst { it.contains("os") || it.contains("numero") || it.contains("número") }
|
val osIdx = headers.indexOfFirst { it.contains("id exclusiva") || it == "id" || it.contains("numero da os") || it.contains("número da os") || (it.contains("os") && !it.contains("recursos")) || (it.contains("número") && !it.contains("tópicos")) }
|
||||||
val descIdx = headers.indexOfFirst { it.contains("desc") || it.contains("atividade") || it.contains("ação") }
|
val descIdx = headers.indexOfFirst { it.contains("desc") || it.contains("atividade") || it.contains("ação") || it.contains("nome da tarefa") }
|
||||||
val setorIdx = headers.indexOfFirst { it.contains("setor") || it.contains("area") || it.contains("área") }
|
val setorIdx = headers.indexOfFirst { it.contains("setor") || it.contains("area") || it.contains("área") || it.contains("resumo da tarefa") }
|
||||||
val eqIdx = headers.indexOfFirst { it.contains("equipe") || it.contains("eq") || it.contains("disc") || it.contains("tipo") }
|
val eqIdx = headers.indexOfFirst { it.contains("equipe") || it.contains("eq") || it.contains("disc") || it.contains("tipo") || it.contains("grupo de recursos") }
|
||||||
val respIdx = headers.indexOfFirst { it.contains("resp") || it.contains("encarregado") || it.contains("dono") }
|
val respIdx = headers.indexOfFirst { it.contains("resp") || it.contains("encarregado") || it.contains("dono") || it.contains("nomes dos recursos") }
|
||||||
val inicioIdx = headers.indexOfFirst { it.contains("inicio") || it.contains("início") || it.contains("start") }
|
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 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") }
|
val pctIdx = headers.indexOfFirst { it.contains("pct") || it.contains("%") || it.contains("percent") || it.contains("exec") }
|
||||||
val tagIdx = headers.indexOfFirst { it.contains("tag") }
|
val tagIdx = headers.indexOfFirst { it == "tag" || it.contains("tag") }
|
||||||
|
|
||||||
if (osIdx == -1 || descIdx == -1) {
|
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'."))
|
return@withContext Result.failure(Exception("Colunas obrigatórias não encontradas. Certifique-se de ter ao menos 'Número da OS' e 'Descrição'."))
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ import com.example.data.model.ActivityStatus
|
|||||||
import com.example.data.model.MaintenanceActivity
|
import com.example.data.model.MaintenanceActivity
|
||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
import com.example.data.model.parseDateOnly
|
import com.example.data.model.parseDateOnly
|
||||||
|
import com.example.data.model.parseFullDateTime
|
||||||
import com.example.data.model.AnalyticsState
|
import com.example.data.model.AnalyticsState
|
||||||
import com.example.ui.theme.BrandBlack
|
import com.example.ui.theme.BrandBlack
|
||||||
import com.example.ui.theme.BrandGreen
|
import com.example.ui.theme.BrandGreen
|
||||||
@@ -646,14 +647,12 @@ fun OverdueActivitiesListModal(
|
|||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onActivityClick: (MaintenanceActivity) -> Unit
|
onActivityClick: (MaintenanceActivity) -> Unit
|
||||||
) {
|
) {
|
||||||
val referenceDate = remember(projectEnd) {
|
val referenceDate = remember { Date() }
|
||||||
if (Date().before(projectEnd)) projectEnd else Date()
|
|
||||||
}
|
|
||||||
|
|
||||||
val filteredActivities = remember(group, allActivities, referenceDate, topSectors) {
|
val filteredActivities = remember(group, allActivities, referenceDate, topSectors) {
|
||||||
allActivities.filter { act ->
|
allActivities.filter { act ->
|
||||||
val isNotCompleted = act.percentualExecucao < 100
|
val isNotCompleted = act.percentualExecucao < 100
|
||||||
val endDate = parseDateOnly(act.dataFim)
|
val endDate = parseFullDateTime(act.dataFim) ?: parseDateOnly(act.dataFim)
|
||||||
val isOverdue = isNotCompleted && endDate != null && endDate.before(referenceDate)
|
val isOverdue = isNotCompleted && endDate != null && endDate.before(referenceDate)
|
||||||
|
|
||||||
if (!isOverdue) return@filter false
|
if (!isOverdue) return@filter false
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
repository.allActivities,
|
repository.allActivities,
|
||||||
repository.allHistory
|
repository.allHistory
|
||||||
) { activities, history ->
|
) { activities, history ->
|
||||||
calculateAnalytics(activities, history)
|
calculateAnalyticsState(activities, history)
|
||||||
}
|
}
|
||||||
.flowOn(Dispatchers.Default)
|
.flowOn(Dispatchers.Default)
|
||||||
.stateIn(
|
.stateIn(
|
||||||
@@ -485,9 +485,10 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun calculateAnalytics(
|
fun calculateAnalyticsState(
|
||||||
activities: List<MaintenanceActivity>,
|
activities: List<MaintenanceActivity>,
|
||||||
history: List<OSUpdateHistory>
|
history: List<OSUpdateHistory>,
|
||||||
|
referenceDateOverride: Date? = null
|
||||||
): AnalyticsState {
|
): AnalyticsState {
|
||||||
if (activities.isEmpty()) {
|
if (activities.isEmpty()) {
|
||||||
return AnalyticsState()
|
return AnalyticsState()
|
||||||
@@ -505,7 +506,10 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
|
|
||||||
// 2. S-Curve bounds and steps
|
// 2. S-Curve bounds and steps
|
||||||
val parsedDates = activities.flatMap {
|
val parsedDates = activities.flatMap {
|
||||||
listOfNotNull(parseDateOnly(it.dataInicio), parseDateOnly(it.dataFim))
|
listOfNotNull(
|
||||||
|
parseFullDateTime(it.dataInicio) ?: parseDateOnly(it.dataInicio),
|
||||||
|
parseFullDateTime(it.dataFim) ?: parseDateOnly(it.dataFim)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
val projectStart = parsedDates.minOrNull() ?: Calendar.getInstance().apply { set(2026, Calendar.AUGUST, 1) }.time
|
val projectStart = parsedDates.minOrNull() ?: Calendar.getInstance().apply { set(2026, Calendar.AUGUST, 1) }.time
|
||||||
@@ -524,11 +528,12 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
if (totalActivities == 0) 0f
|
if (totalActivities == 0) 0f
|
||||||
else {
|
else {
|
||||||
val sum = activities.sumOf { act ->
|
val sum = activities.sumOf { act ->
|
||||||
val start = parseDateOnly(act.dataInicio)?.time ?: dayTime
|
val start = (parseFullDateTime(act.dataInicio) ?: parseDateOnly(act.dataInicio))?.time ?: dayTime
|
||||||
val end = parseDateOnly(act.dataFim)?.time ?: dayTime
|
val end = (parseFullDateTime(act.dataFim) ?: parseDateOnly(act.dataFim))?.time ?: dayTime
|
||||||
when {
|
when {
|
||||||
dayTime <= start -> 0
|
dayTime <= start -> 0
|
||||||
dayTime >= end -> 100
|
dayTime >= end -> 100
|
||||||
|
end <= start -> 100
|
||||||
else -> {
|
else -> {
|
||||||
val progress = ((dayTime - start).toDouble() / (end - start).toDouble() * 100.0).toInt()
|
val progress = ((dayTime - start).toDouble() / (end - start).toDouble() * 100.0).toInt()
|
||||||
progress.coerceIn(0, 100)
|
progress.coerceIn(0, 100)
|
||||||
@@ -557,12 +562,12 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Overdue tags and sectors
|
// 3. Overdue tags and sectors (OSs em atraso consideram a data/hora atual real ou override de testes)
|
||||||
val referenceDate = if (Date().before(projectEnd)) projectEnd else Date()
|
val referenceDate = referenceDateOverride ?: Date()
|
||||||
|
|
||||||
val overdueActivities = activities.filter { act ->
|
val overdueActivities = activities.filter { act ->
|
||||||
val isNotCompleted = act.percentualExecucao < 100
|
val isNotCompleted = act.percentualExecucao < 100
|
||||||
val endDate = parseDateOnly(act.dataFim)
|
val endDate = parseFullDateTime(act.dataFim) ?: parseDateOnly(act.dataFim)
|
||||||
isNotCompleted && endDate != null && endDate.before(referenceDate)
|
isNotCompleted && endDate != null && endDate.before(referenceDate)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,8 +4,10 @@ import android.content.Context
|
|||||||
import androidx.test.core.app.ApplicationProvider
|
import androidx.test.core.app.ApplicationProvider
|
||||||
import com.example.data.local.AppDatabase
|
import com.example.data.local.AppDatabase
|
||||||
import com.example.data.remote.GoogleSheetsSyncService
|
import com.example.data.remote.GoogleSheetsSyncService
|
||||||
|
import com.example.data.repository.MaintenanceRepository
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
import org.junit.Assert.assertNotNull
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
import org.junit.runner.RunWith
|
import org.junit.runner.RunWith
|
||||||
import org.robolectric.RobolectricTestRunner
|
import org.robolectric.RobolectricTestRunner
|
||||||
@@ -424,4 +426,90 @@ class ExampleRobolectricTest {
|
|||||||
kotlinx.coroutines.Dispatchers.resetMain()
|
kotlinx.coroutines.Dispatchers.resetMain()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
@Test
|
||||||
|
fun `test analytics calculation and interactions with project CSV file`() {
|
||||||
|
val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher()
|
||||||
|
kotlinx.coroutines.Dispatchers.setMain(testDispatcher)
|
||||||
|
try {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).build()
|
||||||
|
val repository = MaintenanceRepository(db.maintenanceDao(), context)
|
||||||
|
|
||||||
|
val csvFile = java.io.File("/home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao/exemplo_testes/GestaoOS_Parada_project.csv")
|
||||||
|
assertTrue(csvFile.exists())
|
||||||
|
|
||||||
|
val inputStream = csvFile.inputStream()
|
||||||
|
|
||||||
|
kotlinx.coroutines.runBlocking {
|
||||||
|
val result = repository.importCsvFromInputStream(inputStream)
|
||||||
|
assertTrue("Import CSV failed: ${result.exceptionOrNull()?.message}", result.isSuccess)
|
||||||
|
|
||||||
|
val activitiesList = db.maintenanceDao().getAllActivitiesList()
|
||||||
|
println("IMPORTED ACTIVITIES COUNT: ${activitiesList.size}")
|
||||||
|
if (activitiesList.isNotEmpty()) {
|
||||||
|
println("FIRST ACTIVITY: ${activitiesList.first()}")
|
||||||
|
}
|
||||||
|
|
||||||
|
val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository)
|
||||||
|
|
||||||
|
val collectionJob = viewModel.viewModelScope.launch {
|
||||||
|
viewModel.analyticsState.collect {}
|
||||||
|
}
|
||||||
|
val historyJob = viewModel.viewModelScope.launch {
|
||||||
|
viewModel.allHistoryState.collect {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Thread.sleep(500)
|
||||||
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||||
|
Thread.sleep(200)
|
||||||
|
|
||||||
|
val state = viewModel.analyticsState.value
|
||||||
|
println("ANALYTICS STATE TIMELINE DATES: ${state.timelineDates.size}")
|
||||||
|
assertNotNull(state)
|
||||||
|
assertEquals(5, state.timelineDates.size)
|
||||||
|
assertEquals(5, state.plannedProgressPoints.size)
|
||||||
|
assertEquals(5, state.realizedProgressPoints.size)
|
||||||
|
|
||||||
|
// 1. Current Date (July 2026): 0 overdue OSs because all CSV activities are in Aug/Sep 2026
|
||||||
|
val overdueJuly = state.overdueBySector.sumOf { it.second }
|
||||||
|
assertEquals(0, overdueJuly)
|
||||||
|
|
||||||
|
// 2. Simulated Future Date (August 20, 2026): OSs due before Aug 20 start appearing as overdue
|
||||||
|
val aug20 = com.example.data.model.parseFullDateTime("20/08/26 18:00")!!
|
||||||
|
val stateAug20 = viewModel.calculateAnalyticsState(activitiesList, emptyList(), referenceDateOverride = aug20)
|
||||||
|
val overdueAug20 = stateAug20.overdueBySector.sumOf { it.second }
|
||||||
|
assertTrue("Expected overdue activities on Aug 20, 2026, got: $overdueAug20", overdueAug20 > 0)
|
||||||
|
|
||||||
|
// 3. Simulated Future Date (September 15, 2026): All incomplete activities in project are overdue
|
||||||
|
val sep15 = com.example.data.model.parseFullDateTime("15/09/26 18:00")!!
|
||||||
|
val stateSep15 = viewModel.calculateAnalyticsState(activitiesList, emptyList(), referenceDateOverride = sep15)
|
||||||
|
val overdueSep15 = stateSep15.overdueBySector.sumOf { it.second }
|
||||||
|
assertTrue("Expected most CSV activities to be overdue on Sep 15, got: $overdueSep15", overdueSep15 > 400)
|
||||||
|
|
||||||
|
val targetOs = db.maintenanceDao().getAllActivitiesList().firstOrNull()?.numeroOs ?: "1024"
|
||||||
|
repository.updateProgress(
|
||||||
|
numeroOs = targetOs,
|
||||||
|
novoPercentual = 100,
|
||||||
|
observacao = "Test OS completed",
|
||||||
|
fotoPath = null,
|
||||||
|
recurso = "GTEC 1",
|
||||||
|
emailEditor = "test@empresa.com"
|
||||||
|
)
|
||||||
|
|
||||||
|
Thread.sleep(200)
|
||||||
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||||
|
|
||||||
|
val historyList = db.maintenanceDao().getAllHistoryList()
|
||||||
|
assertTrue("History list size: ${historyList.size}", historyList.any { it.numeroOs == targetOs && it.percentualNovo == 100 })
|
||||||
|
|
||||||
|
collectionJob.cancel()
|
||||||
|
historyJob.cancel()
|
||||||
|
}
|
||||||
|
db.close()
|
||||||
|
} finally {
|
||||||
|
kotlinx.coroutines.Dispatchers.resetMain()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user