Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/debug-apk.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ name: Debug APK

on:
workflow_dispatch:
pull_request:

permissions:
contents: read
Expand Down
22 changes: 22 additions & 0 deletions app/src/main/java/com/splitsmart/data/Fx.kt
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,33 @@ fun unpricedNote(unpriced: List<String>): String =
"No rate${if (unpriced.size == 1) "" else "s"} entered for ${unpriced.joinToString(" and ")}" +
", so this figure is not converted"

/**
* App-wide rates supply a default for every group and friend. Any local quote for a
* currency pair (including the reverse direction) takes priority over the shared quote.
* Keep group-specific history intact; the shared quote has no Room id to delete here.
*/
fun effectiveFxRates(local: List<FxRate>, shared: List<AppFxRate>, groupId: Long): List<FxRate> {
val overridden = local.map { setOf(it.fromCode.uppercase(), it.toCode.uppercase()) }.toSet()
return local + shared
.filterNot { setOf(it.fromCode.uppercase(), it.toCode.uppercase()) in overridden }
.map {
FxRate(
groupId = groupId,
fromCode = it.fromCode,
toCode = it.toCode,
rate = it.rate,
timeEpoch = it.timeEpoch)
}
}

/** Sums expenses converted into [target] currency. */
fun totalIn(expenses: List<Expense>, target: String, rates: List<FxRate>): Long =
expenses.sumOf {
convertMinor(it.amountMinor, pickRate(rates, it.currencyCode, target, it.dateEpoch))
}

fun rateLine(r: AppFxRate): String =
"1 ${r.fromCode} = ${BigDecimal(r.rate.toString()).stripTrailingZeros().toPlainString()} ${r.toCode}"

fun rateLine(r: FxRate): String =
"1 ${r.fromCode} = ${BigDecimal(r.rate.toString()).stripTrailingZeros().toPlainString()} ${r.toCode}"
12 changes: 10 additions & 2 deletions app/src/main/java/com/splitsmart/data/Repository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ data class ExpenseBundle(
val items: List<ExpenseItem>
)

open class SplitRepository(private val db: AppDatabase) {
open class SplitRepository(private val db: AppDatabase, private val prefs: SettingsPrefsStore? = null) {
private val g = db.groups()
private val m = db.members()
private val e = db.expenses()
Expand Down Expand Up @@ -233,7 +233,15 @@ open class SplitRepository(private val db: AppDatabase) {
}
}

fun rates(gid: Long) = db.rates().rates(gid)
fun localRates(gid: Long) = db.rates().rates(gid)

/** Shared settings rates affect every balance, settlement, dashboard and friend total. */
fun rates(gid: Long): Flow<List<FxRate>> =
prefs?.let { settings ->
combine(localRates(gid), settings.flow) { local, p ->
effectiveFxRates(local, p.globalRates, gid)
}
} ?: localRates(gid)

suspend fun saveRate(r: FxRate): Long {
val f = r.fromCode.uppercase()
Expand Down
48 changes: 48 additions & 0 deletions app/src/main/java/com/splitsmart/data/SettingsPrefs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,34 @@ import androidx.datastore.preferences.core.stringPreferencesKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

enum class ThemeMode {
SYSTEM,
LIGHT,
DARK
}

/** A manual conversion rate shared by every friend and group. */
@Serializable
data class AppFxRate(val fromCode: String, val toCode: String, val rate: Double, val timeEpoch: Long)

data class SettingsPrefs(
val themeMode: ThemeMode = ThemeMode.SYSTEM,
val dynamicColor: Boolean = true,
val defaultCurrency: String = "USD",
val billNotifs: Boolean = true,
val globalRates: List<AppFxRate> = emptyList(),
)

class SettingsPrefsStore(private val store: DataStore<Preferences>) {
private val themeKey = stringPreferencesKey("ui_theme")
private val dynamicKey = booleanPreferencesKey("ui_dynamic")
private val currencyKey = stringPreferencesKey("default_currency")
private val notifKey = booleanPreferencesKey("bill_notifs")
private val globalRatesKey = stringPreferencesKey("global_fx_rates_v1")
private val lastGroupKey = longPreferencesKey("last_group_id")

val lastGroupId: Flow<Long> = store.data.map { it[lastGroupKey] ?: -1L }.catch { emit(-1L) }
Expand All @@ -43,6 +52,7 @@ class SettingsPrefsStore(private val store: DataStore<Preferences>) {
defaultCurrency =
(p[currencyKey] ?: "USD").uppercase().takeIf { it.length == 3 } ?: "USD",
billNotifs = p[notifKey] ?: true,
globalRates = readGlobalRates(p[globalRatesKey]),
)
}
.catch { emit(SettingsPrefs()) }
Expand All @@ -61,6 +71,44 @@ class SettingsPrefsStore(private val store: DataStore<Preferences>) {
store.edit { it[currencyKey] = v }
}

private fun readGlobalRates(raw: String?): List<AppFxRate> =
runCatching { Json.decodeFromString<List<AppFxRate>>(raw ?: "[]") }
.getOrDefault(emptyList())
.filter { r ->
r.fromCode.length == 3 && r.toCode.length == 3 &&
r.fromCode != r.toCode && r.rate.isFinite() && r.rate > 0
}

/** Replaces a currency pair's shared rate; never changes any group-specific rates. */
suspend fun saveGlobalRate(from: String, to: String, rate: Double) {
val f = from.trim().uppercase()
val t = to.trim().uppercase()
require(f.length == 3 && t.length == 3 && f != t && f.all(Char::isLetter) &&
t.all(Char::isLetter)) { "Enter two different 3-letter currency codes." }
require(rate.isFinite() && rate > 0) { "Enter a positive rate." }
store.edit { p ->
val existing = readGlobalRates(p[globalRatesKey])
val newRate = AppFxRate(f, t, rate, System.currentTimeMillis())
// An inverse quote is for the same pair: keep only the new quote so conversion
// never depends on which direction was entered first.
p[globalRatesKey] =
Json.encodeToString(
existing.filterNot {
(it.fromCode == f && it.toCode == t) ||
(it.fromCode == t && it.toCode == f)
} + newRate)
}
}

suspend fun deleteGlobalRate(from: String, to: String) {
store.edit { p ->
p[globalRatesKey] =
Json.encodeToString(
readGlobalRates(p[globalRatesKey])
.filterNot { it.fromCode == from && it.toCode == to })
}
}

suspend fun setBillNotifs(b: Boolean) {
store.edit { it[notifKey] = b }
}
Expand Down
15 changes: 13 additions & 2 deletions app/src/main/java/com/splitsmart/di/Modules.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.collect

val Context.store by preferencesDataStore("settings")

Expand All @@ -57,7 +61,7 @@ object Modules {
MIGRATION_11_12)
.build()

@Provides @Singleton fun repo(db: AppDatabase) = SplitRepository(db)
@Provides @Singleton fun repo(db: AppDatabase, prefs: SettingsPrefsStore) = SplitRepository(db, prefs)

/**
* The balance widget has no update period, so it would otherwise show whatever it
Expand All @@ -77,7 +81,8 @@ object Modules {
@Singleton
fun watchWidget(
db: AppDatabase,
@ApplicationContext c: Context
@ApplicationContext c: Context,
prefs: SettingsPrefsStore
): Closeable {
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
var pending: Job? = null
Expand All @@ -96,6 +101,12 @@ object Modules {
}
}
db.invalidationTracker.addObserver(observer)
// Changing an app-wide rate changes balances without writing a Room table.
scope.launch {
prefs.flow.map { it.globalRates }.distinctUntilChanged().drop(1).collect {
BalanceWidget().refreshAll(c)
}
}
return Closeable {
db.invalidationTracker.removeObserver(observer)
scope.cancel()
Expand Down
10 changes: 6 additions & 4 deletions app/src/main/java/com/splitsmart/ui/screens/ExpenseEditor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.listSaver
Expand Down Expand Up @@ -418,7 +419,7 @@ fun ExpenseEditorScreen(
actions = { TextButton(onClick = doSave, enabled = canSave && !saving) { Text("Save") } },
) { p ->
Column(
Modifier.fillMaxSize().padding(p).padding(16.dp),
Modifier.fillMaxSize().padding(p).imePadding().verticalScroll(rememberScrollState()).padding(16.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (itemized) {
Expand Down Expand Up @@ -595,8 +596,8 @@ fun ExpenseEditorScreen(
}
}
ExpenseMembersPicker(rows, itemized, type, preview, cur) { touch("rows") }
LazyColumn(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
items(rows, key = { it.id }) { r ->
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
rows.forEach { r ->
ExpenseMemberRow(
r, itemized, type, preview?.get(r.id)?.let { money(it, cur) } ?: "") {
touch("rows")
Expand Down Expand Up @@ -690,7 +691,8 @@ fun ExpenseEditorScreen(
touch("note")
},
label = { Text("Note (optional)") },
singleLine = true,
minLines = 2,
maxLines = 4,
modifier = Modifier.fillMaxWidth())
}
}
Expand Down
Loading
Loading