diff --git a/.github/workflows/debug-apk.yml b/.github/workflows/debug-apk.yml index 92caada..58461a4 100644 --- a/.github/workflows/debug-apk.yml +++ b/.github/workflows/debug-apk.yml @@ -2,6 +2,7 @@ name: Debug APK on: workflow_dispatch: + pull_request: permissions: contents: read diff --git a/app/src/main/java/com/splitsmart/data/Fx.kt b/app/src/main/java/com/splitsmart/data/Fx.kt index f51da5f..bf5703b 100644 --- a/app/src/main/java/com/splitsmart/data/Fx.kt +++ b/app/src/main/java/com/splitsmart/data/Fx.kt @@ -95,11 +95,33 @@ fun unpricedNote(unpriced: List): 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, shared: List, groupId: Long): List { + 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, target: String, rates: List): 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}" diff --git a/app/src/main/java/com/splitsmart/data/Repository.kt b/app/src/main/java/com/splitsmart/data/Repository.kt index 66808ec..8159fe4 100644 --- a/app/src/main/java/com/splitsmart/data/Repository.kt +++ b/app/src/main/java/com/splitsmart/data/Repository.kt @@ -81,7 +81,7 @@ data class ExpenseBundle( val items: List ) -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() @@ -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> = + 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() diff --git a/app/src/main/java/com/splitsmart/data/SettingsPrefs.kt b/app/src/main/java/com/splitsmart/data/SettingsPrefs.kt index f2a5e9d..c75fedc 100644 --- a/app/src/main/java/com/splitsmart/data/SettingsPrefs.kt +++ b/app/src/main/java/com/splitsmart/data/SettingsPrefs.kt @@ -9,6 +9,9 @@ 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, @@ -16,11 +19,16 @@ enum class ThemeMode { 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 = emptyList(), ) class SettingsPrefsStore(private val store: DataStore) { @@ -28,6 +36,7 @@ class SettingsPrefsStore(private val store: DataStore) { 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 = store.data.map { it[lastGroupKey] ?: -1L }.catch { emit(-1L) } @@ -43,6 +52,7 @@ class SettingsPrefsStore(private val store: DataStore) { defaultCurrency = (p[currencyKey] ?: "USD").uppercase().takeIf { it.length == 3 } ?: "USD", billNotifs = p[notifKey] ?: true, + globalRates = readGlobalRates(p[globalRatesKey]), ) } .catch { emit(SettingsPrefs()) } @@ -61,6 +71,44 @@ class SettingsPrefsStore(private val store: DataStore) { store.edit { it[currencyKey] = v } } + private fun readGlobalRates(raw: String?): List = + runCatching { Json.decodeFromString>(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 } } diff --git a/app/src/main/java/com/splitsmart/di/Modules.kt b/app/src/main/java/com/splitsmart/di/Modules.kt index 486656d..cb59a8d 100644 --- a/app/src/main/java/com/splitsmart/di/Modules.kt +++ b/app/src/main/java/com/splitsmart/di/Modules.kt @@ -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") @@ -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 @@ -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 @@ -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() diff --git a/app/src/main/java/com/splitsmart/ui/screens/ExpenseEditor.kt b/app/src/main/java/com/splitsmart/ui/screens/ExpenseEditor.kt index 567a21f..7964b21 100644 --- a/app/src/main/java/com/splitsmart/ui/screens/ExpenseEditor.kt +++ b/app/src/main/java/com/splitsmart/ui/screens/ExpenseEditor.kt @@ -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 @@ -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) { @@ -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") @@ -690,7 +691,8 @@ fun ExpenseEditorScreen( touch("note") }, label = { Text("Note (optional)") }, - singleLine = true, + minLines = 2, + maxLines = 4, modifier = Modifier.fillMaxWidth()) } } diff --git a/app/src/main/java/com/splitsmart/ui/screens/FriendDetail.kt b/app/src/main/java/com/splitsmart/ui/screens/FriendDetail.kt index 928df84..cb42f7c 100644 --- a/app/src/main/java/com/splitsmart/ui/screens/FriendDetail.kt +++ b/app/src/main/java/com/splitsmart/ui/screens/FriendDetail.kt @@ -9,6 +9,8 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable @@ -20,6 +22,9 @@ import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.splitsmart.core.settle.Transfer import com.splitsmart.data.ExpenseBundle +import com.splitsmart.data.FxRate +import com.splitsmart.data.parseRate +import com.splitsmart.data.rateLine import com.splitsmart.data.unpricedNote import com.splitsmart.ui.shell.ChildShell import com.splitsmart.ui.vm.GroupDetailVm @@ -54,12 +59,17 @@ fun FriendDetailScreen( var settleErr by remember { mutableStateOf(null) } var settling by remember { mutableStateOf(false) } var share by remember { mutableStateOf(false) } + var rateOpen by rememberSaveable { mutableStateOf(false) } + var menu by remember { mutableStateOf(false) } + var confirmDelete by remember { mutableStateOf(false) } var detailOf by remember { mutableStateOf(null) } val cur = g?.currencyCode ?: "" val self = g?.selfMemberId val friend = members.firstOrNull { it.id != self } ?: members.firstOrNull() val net = self?.let { nets[it] } ?: 0L val rates by vm.rates.collectAsStateWithLifecycle() + val localRates by vm.localRates.collectAsStateWithLifecycle() + val sharedRates by vm.sharedRates.collectAsStateWithLifecycle() val totals = remember(expenses, self, cur, rates) { friendTotalsIn(expenses, self, cur, rates) } val unpriced = totals.unpriced ChildShell( @@ -70,6 +80,33 @@ fun FriendDetailScreen( IconButton(onClick = { g?.let { editGroup(it.id) } }) { Icon(Icons.Default.Edit, "Edit friend") } + Box { + IconButton(onClick = { menu = true }) { + Icon(Icons.Default.MoreVert, "More options") + } + DropdownMenu(menu, { menu = false }) { + DropdownMenuItem( + { Text("Edit friend") }, + { + menu = false + g?.let { editGroup(it.id) } + }, + leadingIcon = { Icon(Icons.Default.Edit, null) }) + DropdownMenuItem( + { Text(if (g?.archived == true) "Unarchive friend" else "Archive friend") }, + { + menu = false + vm.setArchived(g?.archived != true) { onBack() } + }) + DropdownMenuItem( + { Text("Delete friend") }, + { + menu = false + confirmDelete = true + }, + leadingIcon = { Icon(Icons.Default.Delete, null) }) + } + } }, ) { p -> LazyColumn( @@ -140,6 +177,53 @@ fun FriendDetailScreen( } } } + item { + ElevatedCard(Modifier.fillMaxWidth()) { + Column( + Modifier.padding(12.dp), + verticalArrangement = Arrangement.spacedBy(4.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + "Currency rates (manual)", + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.titleSmall) + TextButton(onClick = { rateOpen = true }) { Text("+ Add") } + } + Text( + "New rates are shared with all groups and friends. Existing friend-only rates take priority.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant) + if (localRates.isEmpty() && sharedRates.isEmpty()) + Text( + "Add a rate here or in Settings to convert other currencies into $cur.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant) + sharedRates.forEach { r -> + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text("App-wide · ${rateLine(r)}", + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.bodyMedium) + IconButton(onClick = { vm.deleteSharedRate(r.fromCode, r.toCode) }) { + Icon(Icons.Default.Delete, "Delete shared rate") + } + } + } + localRates.forEach { r -> + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically) { + Text( + rateLine(r), + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.bodyMedium) + IconButton(onClick = { vm.deleteRate(r.id) }) { + Icon(Icons.Default.Delete, "Delete rate") + } + } + } + } + } + } if (friend != null) item { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { @@ -169,6 +253,94 @@ fun FriendDetailScreen( } } } + if (confirmDelete) { + AlertDialog( + onDismissRequest = { confirmDelete = false }, + title = { Text("Delete friend?") }, + text = { Text("Removes this friend and all shared expenses. This cannot be undone.") }, + confirmButton = { + TextButton(onClick = { + confirmDelete = false + vm.deleteGroup { onBack() } + }) { Text("Delete") } + }, + dismissButton = { + TextButton(onClick = { confirmDelete = false }) { Text("Cancel") } + }) + } + if (rateOpen) { + var from by remember { mutableStateOf("") } + var to by remember(cur) { mutableStateOf(cur) } + var rate by remember { mutableStateOf("") } + var rateErr by remember { mutableStateOf(null) } + var savingRate by remember { mutableStateOf(false) } + AlertDialog( + onDismissRequest = { if (!savingRate) rateOpen = false }, + title = { Text("Add app-wide rate") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + "1 unit of currency A = ? units of currency B.", + style = MaterialTheme.typography.bodySmall) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + from, + { from = it.uppercase().take(3); rateErr = null }, + label = { Text("From") }, + singleLine = true, + modifier = Modifier.weight(1f)) + OutlinedTextField( + to, + { to = it.uppercase().take(3); rateErr = null }, + label = { Text("To") }, + singleLine = true, + modifier = Modifier.weight(1f)) + } + OutlinedTextField( + rate, + { rate = it; rateErr = null }, + label = { Text("Rate") }, + singleLine = true, + modifier = Modifier.fillMaxWidth()) + rateErr?.let { + Text(it, color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodySmall) + } + } + }, + confirmButton = { + TextButton( + enabled = !savingRate, + onClick = { + val parsed = parseRate(rate) + rateErr = + when { + from.length != 3 || to.length != 3 -> "Enter two 3-letter codes." + from == to -> "Choose two different currencies." + parsed == null -> "Enter a positive rate." + else -> null + } + if (rateErr == null && parsed != null) { + savingRate = true + scope.launch { + val problem = + vm.saveRate( + FxRate( + groupId = gid, + fromCode = from, + toCode = to, + rate = parsed, + timeEpoch = System.currentTimeMillis())) + savingRate = false + if (problem == null) rateOpen = false else rateErr = problem + } + } + }) { Text("Save") } + }, + dismissButton = { + TextButton(enabled = !savingRate, onClick = { rateOpen = false }) { Text("Cancel") } + }) + } settleOf?.let { (f, t, a) -> SettleDialog( names[f] ?: "?", diff --git a/app/src/main/java/com/splitsmart/ui/screens/GroupDetail.kt b/app/src/main/java/com/splitsmart/ui/screens/GroupDetail.kt index c164e81..5583354 100644 --- a/app/src/main/java/com/splitsmart/ui/screens/GroupDetail.kt +++ b/app/src/main/java/com/splitsmart/ui/screens/GroupDetail.kt @@ -100,6 +100,8 @@ fun GroupDetailScreen( val nets by vm.nets.collectAsStateWithLifecycle() val subgroups by vm.subgroups.collectAsStateWithLifecycle() val rates by vm.rates.collectAsStateWithLifecycle() + val localRates by vm.localRates.collectAsStateWithLifecycle() + val sharedRates by vm.sharedRates.collectAsStateWithLifecycle() val native by vm.netsNative.collectAsStateWithLifecycle() val customs by vm.customs.collectAsStateWithLifecycle() val customMap = remember(customs) { customs.associateBy { it.id } } @@ -385,12 +387,25 @@ fun GroupDetailScreen( modifier = Modifier.weight(1f)) TextButton(onClick = { rateOpen = true }) { Text("+ Add") } } - if (rates.isEmpty()) + Text( + "New rates are shared with all friends and groups. Existing group-only rates take priority.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant) + if (localRates.isEmpty() && sharedRates.isEmpty()) Text( - "No rates yet. Foreign expenses count 1:1 until you add one.", + "No rates yet. Add one here or in Settings.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - rates.forEach { r -> + sharedRates.forEach { r -> + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text("App-wide · ${rateLine(r)}", modifier = Modifier.weight(1f), + style = MaterialTheme.typography.bodyMedium) + IconButton(onClick = { vm.deleteSharedRate(r.fromCode, r.toCode) }) { + Icon(Icons.Default.Delete, "Delete shared rate") + } + } + } + localRates.forEach { r -> Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { @@ -705,7 +720,7 @@ fun GroupDetailScreen( var err by remember { mutableStateOf(null) } AlertDialog( onDismissRequest = { rateOpen = false }, - title = { Text("Add rate") }, + title = { Text("Add app-wide rate") }, text = { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( diff --git a/app/src/main/java/com/splitsmart/ui/screens/Settings.kt b/app/src/main/java/com/splitsmart/ui/screens/Settings.kt index 8327841..5f4e403 100644 --- a/app/src/main/java/com/splitsmart/ui/screens/Settings.kt +++ b/app/src/main/java/com/splitsmart/ui/screens/Settings.kt @@ -46,6 +46,7 @@ import androidx.core.app.ActivityCompat import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.splitsmart.data.CustomCategory +import com.splitsmart.data.parseRate import com.splitsmart.data.ThemeMode import com.splitsmart.ui.shell.DrawerDest import com.splitsmart.ui.shell.TopLevelShell @@ -70,6 +71,11 @@ fun SettingsScreen( val snackbar = remember { SnackbarHostState() } var currency by rememberSaveable(prefs.defaultCurrency) { mutableStateOf(prefs.defaultCurrency) } var msg by remember { mutableStateOf(null) } + var fxFrom by rememberSaveable { mutableStateOf("") } + var fxTo by rememberSaveable { mutableStateOf("") } + var fxValue by rememberSaveable { mutableStateOf("") } + var fxErr by remember { mutableStateOf(null) } + var savingFx by remember { mutableStateOf(false) } // Read from the system, not from the stored preference: the preference says the // user asked for reminders, the system decides whether any can be delivered. fun canPostNotifications(): Boolean = @@ -204,6 +210,87 @@ fun SettingsScreen( color = MaterialTheme.colorScheme.error) } } + item { SectionTitle("Currency conversion (app-wide)") } + item { + Text( + "Manual rates work offline for all friends and groups. Existing group-specific rates override shared rates for that currency pair.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant) + } + prefs.globalRates.forEach { r -> + item { + Row( + Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically) { + Text( + "1 ${r.fromCode} = ${r.rate} ${r.toCode}", + modifier = Modifier.weight(1f)) + IconButton(onClick = { + scope.launch { + vm.deleteGlobalRate(r.fromCode, r.toCode)?.let { + snackbar.showSnackbar(it) + } + } + }) { Icon(Icons.Default.Delete, "Delete shared rate ${r.fromCode} to ${r.toCode}") } + } + } + } + item { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + fxFrom, + { fxFrom = it.uppercase().take(3); fxErr = null }, + label = { Text("From") }, + singleLine = true, + modifier = Modifier.weight(1f)) + OutlinedTextField( + fxTo, + { fxTo = it.uppercase().take(3); fxErr = null }, + label = { Text("To") }, + singleLine = true, + modifier = Modifier.weight(1f)) + } + } + item { + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically) { + OutlinedTextField( + fxValue, + { fxValue = it; fxErr = null }, + label = { Text("Rate") }, + singleLine = true, + modifier = Modifier.weight(1f)) + TextButton( + enabled = !savingFx, + onClick = { + val parsed = parseRate(fxValue) + fxErr = + when { + fxFrom.length != 3 || fxTo.length != 3 || fxFrom == fxTo -> + "Enter two different 3-letter currencies." + parsed == null -> "Enter a positive rate." + else -> null + } + if (fxErr == null && parsed != null) { + savingFx = true + scope.launch { + val problem = vm.saveGlobalRate(fxFrom, fxTo, parsed) + savingFx = false + if (problem == null) { + fxFrom = "" + fxTo = "" + fxValue = "" + } else fxErr = problem + } + } + }) { Text("Save rate") } + } + fxErr?.let { + Text(it, color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodySmall) + } + } item { SectionTitle("Notifications") } item { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { diff --git a/app/src/main/java/com/splitsmart/ui/vm/GroupVms.kt b/app/src/main/java/com/splitsmart/ui/vm/GroupVms.kt index 6255ab7..3cfbac3 100644 --- a/app/src/main/java/com/splitsmart/ui/vm/GroupVms.kt +++ b/app/src/main/java/com/splitsmart/ui/vm/GroupVms.kt @@ -259,6 +259,10 @@ constructor( val nets: StateFlow> = watching(emptyMap()) { repo.nets(it) } val rates: StateFlow> = watching(emptyList()) { repo.rates(it) } + val localRates: StateFlow> = watching(emptyList()) { repo.localRates(it) } + val sharedRates: StateFlow> = + prefs.flow.map { it.globalRates } + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList()) /** * The plan is derived from expenses, settlements and rates, so all three @@ -281,10 +285,16 @@ constructor( .exceptionOrNull() ?.message + /** New rates are shared across groups and friends; old group-only quotes remain as overrides. */ suspend fun saveRate(r: FxRate): String? = - runCatching { withContext(NonCancellable) { repo.saveRate(r.copy(groupId = gid.value)) } } - .exceptionOrNull() - ?.message + runCatching { + withContext(NonCancellable) { + prefs.saveGlobalRate(r.fromCode, r.toCode, r.rate) + } + }.exceptionOrNull()?.message + + fun deleteSharedRate(from: String, to: String) = + viewModelScope.launch { withContext(NonCancellable) { prefs.deleteGlobalRate(from, to) } } fun deleteRate(id: Long) = viewModelScope.launch { withContext(NonCancellable) { repo.deleteRate(id) } } diff --git a/app/src/main/java/com/splitsmart/ui/vm/SettingsVm.kt b/app/src/main/java/com/splitsmart/ui/vm/SettingsVm.kt index 0ed9f85..0821919 100644 --- a/app/src/main/java/com/splitsmart/ui/vm/SettingsVm.kt +++ b/app/src/main/java/com/splitsmart/ui/vm/SettingsVm.kt @@ -47,6 +47,12 @@ constructor( } .getOrElse { it.message } + suspend fun saveGlobalRate(from: String, to: String, rate: Double): String? = + runCatching { prefs.saveGlobalRate(from, to, rate) }.exceptionOrNull()?.message + + suspend fun deleteGlobalRate(from: String, to: String): String? = + runCatching { prefs.deleteGlobalRate(from, to) }.exceptionOrNull()?.message + fun setThemeMode(m: ThemeMode) = viewModelScope.launch { prefs.setThemeMode(m) } fun setDynamicColor(b: Boolean) = viewModelScope.launch { prefs.setDynamicColor(b) } diff --git a/app/src/test/java/com/splitsmart/data/FxTest.kt b/app/src/test/java/com/splitsmart/data/FxTest.kt index 5662b6f..8ba03cf 100644 --- a/app/src/test/java/com/splitsmart/data/FxTest.kt +++ b/app/src/test/java/com/splitsmart/data/FxTest.kt @@ -112,6 +112,38 @@ class FxTest { .isEqualTo("1 EUR = 1.1 USD") } + @Test + fun `a shared rate converts expenses for both friends and groups`() { + val shared = listOf(AppFxRate("EUR", "USD", 1.2, 100L)) + val groupRates = effectiveFxRates(emptyList(), shared, 1L) + val friendRates = effectiveFxRates(emptyList(), shared, 2L) + assertThat(totalIn(listOf(ex("EUR")), "USD", groupRates)).isEqualTo(6000L) + assertThat(totalIn(listOf(ex("EUR")), "USD", friendRates)).isEqualTo(6000L) + assertThat(unconvertibleCurrencies(listOf(ex("EUR")), "USD", groupRates)).isEmpty() + } + + @Test + fun `group rates override shared quotes in either direction`() { + val shared = listOf(AppFxRate("EUR", "USD", 1.2, 100L)) + val local = listOf(FxRate(groupId = 1, fromCode = "USD", toCode = "EUR", + rate = 0.5, timeEpoch = 200L)) + val groupRates = effectiveFxRates(local, shared, 1L) + val friendRates = effectiveFxRates(emptyList(), shared, 2L) + assertThat(groupRates).hasSize(1) + assertThat(pickRate(groupRates, "EUR", "USD", 1000L)).isEqualTo(2.0) + assertThat(pickRate(friendRates, "EUR", "USD", 1000L)).isEqualTo(1.2) + } + + @Test + fun `unrelated local rates do not block app-wide conversion`() { + val shared = listOf(AppFxRate("EUR", "USD", 1.2, 100L)) + val local = listOf(FxRate(groupId = 1, fromCode = "GBP", toCode = "USD", + rate = 1.4, timeEpoch = 200L)) + val rates = effectiveFxRates(local, shared, 1L) + assertThat(rates).hasSize(2) + assertThat(pickRate(rates, "EUR", "USD", 1000L)).isEqualTo(1.2) + } + private fun ex(cur: String, at: Long = 1000) = Expense( groupId = 1, diff --git a/app/src/test/java/com/splitsmart/data/GlobalCurrencyRatesTest.kt b/app/src/test/java/com/splitsmart/data/GlobalCurrencyRatesTest.kt new file mode 100644 index 0000000..6455848 --- /dev/null +++ b/app/src/test/java/com/splitsmart/data/GlobalCurrencyRatesTest.kt @@ -0,0 +1,61 @@ +package com.splitsmart.data + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import com.google.common.truth.Truth.assertThat +import java.io.File +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class GlobalCurrencyRatesTest : DbTest() { + @Test + fun `shared rates apply to groups and friends and local rates override them`() = runTest { + val file = File.createTempFile("splitsmart-fx-", ".preferences_pb") + file.delete() // DataStore must create the file itself. + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + try { + val settings = + SettingsPrefsStore(PreferenceDataStoreFactory.create(scope = scope, produceFile = { file })) + val withSharedRates = SplitRepository(db, settings) + val group = withSharedRates.saveGroup( + Group(name = "Trip", currencyCode = "USD", createdAt = now)) + val friend = withSharedRates.friendGroup("Sam", "USD") + + settings.saveGlobalRate("EUR", "USD", 1.2) + assertThat(pickRate(withSharedRates.rates(group).first(), "EUR", "USD", now)) + .isEqualTo(1.2) + assertThat(pickRate(withSharedRates.rates(friend).first(), "EUR", "USD", now)) + .isEqualTo(1.2) + + withSharedRates.saveRate( + FxRate(groupId = group, fromCode = "USD", toCode = "EUR", + rate = 0.5, timeEpoch = now)) + assertThat(pickRate(withSharedRates.rates(group).first(), "EUR", "USD", now)) + .isEqualTo(2.0) + assertThat(pickRate(withSharedRates.rates(friend).first(), "EUR", "USD", now)) + .isEqualTo(1.2) + + settings.saveGlobalRate("USD", "EUR", 0.8) + assertThat(settings.flow.first().globalRates).hasSize(1) + assertThat(pickRate(withSharedRates.rates(friend).first(), "EUR", "USD", now)) + .isEqualTo(1.25) + settings.deleteGlobalRate("USD", "EUR") + assertThat(settings.flow.first().globalRates).isEmpty() + assertThat(unconvertibleCurrencies( + listOf(Expense(groupId = friend, payerId = 1, amountMinor = 100, + currencyCode = "EUR", category = Category.FOOD, + dateEpoch = now, createdAt = now)), + "USD", withSharedRates.rates(friend).first())).containsExactly("EUR") + } finally { + scope.cancel() + file.delete() + } + } +} diff --git a/app/src/test/java/com/splitsmart/ui/vm/FriendDetailTest.kt b/app/src/test/java/com/splitsmart/ui/vm/FriendDetailTest.kt index 8dbdd56..b38315d 100644 --- a/app/src/test/java/com/splitsmart/ui/vm/FriendDetailTest.kt +++ b/app/src/test/java/com/splitsmart/ui/vm/FriendDetailTest.kt @@ -3,6 +3,7 @@ package com.splitsmart.ui.vm import com.google.common.truth.Truth.assertThat import com.splitsmart.data.Category import com.splitsmart.data.Expense +import com.splitsmart.data.FxRate import org.junit.jupiter.api.Test class FriendDetailTest { @@ -39,4 +40,28 @@ class FriendDetailTest { assertThat(settleTriple(-500, 7, 9)).isEqualTo(Triple(7L, 9L, 500L)) assertThat(settleTriple(0, 7, 9)).isNull() } + @Test + fun `friend expenses use entered currency rates for totals`() { + val foreign = + ex(1, 7, 10000).copy(currencyCode = "EUR") + val rate = + FxRate( + groupId = 1, + fromCode = "EUR", + toCode = "USD", + rate = 1.2, + timeEpoch = 0) + val totals = friendTotalsIn(listOf(foreign), 7, "USD", listOf(rate)) + assertThat(totals.paidBySelf).isEqualTo(12000L) + assertThat(totals.paidByFriend).isEqualTo(0L) + assertThat(totals.unpriced).isEmpty() + } + + @Test + fun `friend expenses without rates remain flagged as unpriced`() { + val foreign = ex(1, 9, 10000).copy(currencyCode = "EUR") + val totals = friendTotalsIn(listOf(foreign), 7, "USD", emptyList()) + assertThat(totals.unpriced).containsExactly("EUR") + } + }