Skip to content

Commit

Permalink
Fix the CSV parser
Browse files Browse the repository at this point in the history
  • Loading branch information
ILIYANGERMANOV committed Apr 17, 2023
1 parent bafd419 commit eb4f3fc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
5 changes: 4 additions & 1 deletion app/src/main/java/com/ivy/wallet/ui/csv/CSVViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -388,9 +388,12 @@ class CSVViewModel @Inject constructor(
private suspend fun handleFilePicked(event: CSVEvent.FilePicked): Unit =
withContext(Dispatchers.IO) {
importCSV(uri = event.uri, normalizeCSV = false)
if(columns?.values?.size?.let { it < 3 } == true) {
if (columns?.values?.size?.let { it < 3 } == true) {
importCSV(uri = event.uri, normalizeCSV = true)
}
csv = csv?.map { row ->
row.copy(values = row.values.map { it.trim() })
}
}

private fun importCSV(uri: Uri, normalizeCSV: Boolean): Unit = try {
Expand Down
23 changes: 22 additions & 1 deletion app/src/main/java/com/ivy/wallet/ui/csv/domain/ParseFields.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ import com.ivy.wallet.ui.csv.CSVRow
import com.ivy.wallet.ui.csv.ColumnMapping
import com.ivy.wallet.ui.csv.DateMetadata
import com.ivy.wallet.ui.csv.TrnTypeMetadata
import java.text.DecimalFormat
import java.text.NumberFormat
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import java.util.*
import kotlin.math.abs

// region Parse amount
fun parseAmount(
value: String,
metadata: Int // a broken multiplier
Expand All @@ -25,9 +29,26 @@ fun parseAmount(
1_0000 -> 10_000.0
else -> 1.0
}
abs(value.toDouble() * multiplier)
val double = parsePositiveDouble(value) ?: return@tryParse null
abs(double * multiplier)
}

private fun parsePositiveDouble(string: String): Double? {
val cleanedString = string
.replace("-", "")
.replace(" ", ".")
val numberFormat = NumberFormat.getInstance(Locale.getDefault())
return if (numberFormat is DecimalFormat) {
numberFormat.applyPattern("#,###.##")
val parsedNumber = numberFormat.parse(cleanedString)
parsedNumber?.toDouble()
} else {
string.toDoubleOrNull()
}
}

// endregion

fun parseTransactionType(
value: String,
metadata: TrnTypeMetadata
Expand Down

0 comments on commit eb4f3fc

Please sign in to comment.