reworked percent split to fraction split

This commit is contained in:
sora committed 2026-12-02 00:26:42 +01:00
1 parent a1a7092318
commit 5846a98870
3 files changed
+137 -129

No files matched your search

@@ -445,13 +445,14 @@ class EditBillActivity : AppCompatActivity() {
val uiAmount = viewModel.parseAmountFromUi(it.value) val uiAmount = viewModel.parseAmountFromUi(it.value)
SupportUtil.round2(uiAmount * viewModel.selectedCurrencyRate) SupportUtil.round2(uiAmount * viewModel.selectedCurrencyRate)
} }
} else { // PERCENT } else { // FRACTION
val totalAmount = viewModel.amountAsDouble val totalAmount = viewModel.amountAsDouble
viewModel.owersPercentSplit.filter { (id, percentStr) -> val fractionTotal = viewModel.getFractionTotal()
viewModel.owersSelection[id] == true && viewModel.parseAmountFromUi(percentStr) > 0 viewModel.owersFractionSplit.filter { (id, fraction) ->
viewModel.owersSelection[id] == true && (fraction.toIntOrNull() ?: 0) > 0
}.mapValues { }.mapValues {
val percent = viewModel.parseAmountFromUi(it.value) val fraction = it.value.toInt()
val uiAmount = SupportUtil.round2(totalAmount * percent / 100.0) val uiAmount = SupportUtil.round2(totalAmount * fraction / fractionTotal)
SupportUtil.round2(uiAmount * viewModel.selectedCurrencyRate) SupportUtil.round2(uiAmount * viewModel.selectedCurrencyRate)
} }
} }
@@ -79,10 +79,10 @@ fun EditBillScreen(
val whatFirst = remember(context) { val whatFirst = remember(context) {
val preferences = PreferenceManager.getDefaultSharedPreferences(context) val preferences = PreferenceManager.getDefaultSharedPreferences(context)
preferences.getBoolean(context.getString(R.string.pref_key_extra_features), false) && preferences.getBoolean(context.getString(R.string.pref_key_extra_features), false) &&
preferences.getString( preferences.getString(
context.getString(R.string.pref_key_bill_field_order), context.getString(R.string.pref_key_bill_field_order),
context.getString(R.string.pref_value_bill_amount_first) context.getString(R.string.pref_value_bill_amount_first)
) == context.getString(R.string.pref_value_bill_what_first) ) == context.getString(R.string.pref_value_bill_what_first)
} }
var amountFocused by remember { mutableStateOf(false) } var amountFocused by remember { mutableStateOf(false) }
var amountSelection by remember { mutableStateOf(TextRange(viewModel.amount.length)) } var amountSelection by remember { mutableStateOf(TextRange(viewModel.amount.length)) }
@@ -309,18 +309,18 @@ private fun keyboardColors(): KeyboardColors {
val (tray, edge) = when { val (tray, edge) = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE -> if (dark) { Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE -> if (dark) {
colorResource(android.R.color.system_surface_container_dark) to colorResource(android.R.color.system_surface_container_dark) to
colorResource(android.R.color.system_surface_container_high_dark) colorResource(android.R.color.system_surface_container_high_dark)
} else { } else {
colorResource(android.R.color.system_surface_container_light) to colorResource(android.R.color.system_surface_container_light) to
colorResource(android.R.color.system_surface_container_high_light) colorResource(android.R.color.system_surface_container_high_light)
} }
else -> if (dark) { else -> if (dark) {
colorResource(android.R.color.system_neutral1_900) to colorResource(android.R.color.system_neutral1_900) to
colorResource(android.R.color.system_neutral1_800) colorResource(android.R.color.system_neutral1_800)
} else { } else {
colorResource(android.R.color.system_neutral1_50) to colorResource(android.R.color.system_neutral1_50) to
colorResource(android.R.color.system_neutral1_100) colorResource(android.R.color.system_neutral1_100)
} }
} }
if (dark) KeyboardColors( if (dark) KeyboardColors(
@@ -402,88 +402,88 @@ fun BillBasicInfoSection(
stringResource(R.string.currency_dialog_title, viewModel.mainCurrencyName) stringResource(R.string.currency_dialog_title, viewModel.mainCurrencyName)
val amountField: @Composable () -> Unit = { val amountField: @Composable () -> Unit = {
OutlinedTextField( OutlinedTextField(
value = TextFieldValue( value = TextFieldValue(
text = viewModel.amount, text = viewModel.amount,
selection = TextRange( selection = TextRange(
amountSelection.start.coerceIn(0, viewModel.amount.length), amountSelection.start.coerceIn(0, viewModel.amount.length),
amountSelection.end.coerceIn(0, viewModel.amount.length) amountSelection.end.coerceIn(0, viewModel.amount.length)
) )
), ),
onValueChange = { nv -> onValueChange = { nv ->
val filteredValue = nv.text.filter { it in "0123456789.,+-*/()" } val filteredValue = nv.text.filter { it in "0123456789.,+-*/()" }
onAmountSelectionChange( onAmountSelectionChange(
if (filteredValue == nv.text) nv.selection else TextRange(filteredValue.length) if (filteredValue == nv.text) nv.selection else TextRange(filteredValue.length)
) )
if (filteredValue != viewModel.amount) { if (filteredValue != viewModel.amount) {
viewModel.amount = filteredValue viewModel.amount = filteredValue
viewModel.updateSplits() viewModel.updateSplits()
}
},
enabled = canEdit,
placeholder = { Text("0") },
modifier = Modifier
.fillMaxWidth()
.focusRequester(amountFocusRequester)
.onFocusChanged { onAmountFocusChange(it.isFocused) },
leadingIcon = {
val currencyToShow = viewModel.selectedCurrencyName.ifEmpty {
viewModel.mainCurrencyName.ifEmpty { "$" }
}
TextIconDisplay(
textIcon = TextIcon.Symbol(currencyToShow),
tint = MaterialTheme.colors.onSurface.copy(alpha = 0.6f)
)
},
trailingIcon = {
IconButton(
enabled = canEdit,
onClick = {
val mainLabel = viewModel.mainCurrencyName.ifEmpty { "$" }
val options = listOf("$mainLabel | Base") + viewModel.currencies.map {
"${it.name} | 1 $mainLabel = ${it.exchangeRate} ${it.name}"
}
viewModel.showDialog(
title = currencyDialogTitle,
items = options,
onItemSelected = { index ->
if (index == 0) {
viewModel.resetCurrency()
} else {
viewModel.convertCurrency(viewModel.currencies[index - 1])
}
}
)
} }
) { },
Icon(Icons.Default.SwapHoriz, contentDescription = "Change Currency") enabled = canEdit,
} placeholder = { Text("0") },
}, modifier = Modifier
keyboardOptions = KeyboardOptions( .fillMaxWidth()
keyboardType = KeyboardType.Decimal, .focusRequester(amountFocusRequester)
imeAction = if (whatFirst) ImeAction.Done else ImeAction.Next .onFocusChanged { onAmountFocusChange(it.isFocused) },
), leadingIcon = {
keyboardActions = KeyboardActions( val currencyToShow = viewModel.selectedCurrencyName.ifEmpty {
onNext = { focusManager.moveFocus(FocusDirection.Next) }, viewModel.mainCurrencyName.ifEmpty { "$" }
onDone = { focusManager.clearFocus() } }
TextIconDisplay(
textIcon = TextIcon.Symbol(currencyToShow),
tint = MaterialTheme.colors.onSurface.copy(alpha = 0.6f)
)
},
trailingIcon = {
IconButton(
enabled = canEdit,
onClick = {
val mainLabel = viewModel.mainCurrencyName.ifEmpty { "$" }
val options = listOf("$mainLabel | Base") + viewModel.currencies.map {
"${it.name} | 1 $mainLabel = ${it.exchangeRate} ${it.name}"
}
viewModel.showDialog(
title = currencyDialogTitle,
items = options,
onItemSelected = { index ->
if (index == 0) {
viewModel.resetCurrency()
} else {
viewModel.convertCurrency(viewModel.currencies[index - 1])
}
}
)
}
) {
Icon(Icons.Default.SwapHoriz, contentDescription = "Change Currency")
}
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Decimal,
imeAction = if (whatFirst) ImeAction.Done else ImeAction.Next
),
keyboardActions = KeyboardActions(
onNext = { focusManager.moveFocus(FocusDirection.Next) },
onDone = { focusManager.clearFocus() }
)
) )
)
} }
val whatField: @Composable () -> Unit = { val whatField: @Composable () -> Unit = {
OutlinedTextField( OutlinedTextField(
value = viewModel.what, value = viewModel.what,
onValueChange = { viewModel.updateWhat(it) }, onValueChange = { viewModel.updateWhat(it) },
enabled = canEdit, enabled = canEdit,
placeholder = { Text(stringResource(R.string.label_what)) }, placeholder = { Text(stringResource(R.string.label_what)) },
modifier = Modifier.fillMaxWidth().focusRequester(whatFocusRequester), modifier = Modifier.fillMaxWidth().focusRequester(whatFocusRequester),
leadingIcon = { Icon(Icons.Default.Title, contentDescription = null) }, leadingIcon = { Icon(Icons.Default.Title, contentDescription = null) },
keyboardOptions = KeyboardOptions(imeAction = if (whatFirst) ImeAction.Next else ImeAction.Done), keyboardOptions = KeyboardOptions(imeAction = if (whatFirst) ImeAction.Next else ImeAction.Done),
keyboardActions = KeyboardActions( keyboardActions = KeyboardActions(
onNext = { focusManager.moveFocus(FocusDirection.Next) }, onNext = { focusManager.moveFocus(FocusDirection.Next) },
onDone = { focusManager.clearFocus() } onDone = { focusManager.clearFocus() }
)
) )
)
} }
if (whatFirst) { if (whatFirst) {
@@ -619,14 +619,13 @@ fun OwerSelectionSection(
) )
Spacer(Modifier.weight(1f)) Spacer(Modifier.weight(1f))
if (viewModel.splitMode != SplitMode.EVEN) { if (viewModel.splitMode != SplitMode.EVEN && viewModel.splitMode != SplitMode.FRACTION) {
val diff = viewModel.getDiffSplit() val diff = viewModel.getDiffSplit()
if (abs(diff) > 0.01) { if (abs(diff) > 0.01) {
val unit = if (viewModel.splitMode == SplitMode.PERCENT) "%" else ""
val diffText = val diffText =
if (diff > 0) "Missing: ${SupportUtil.normalNumberFormat.format(diff)}$unit" else "Excess: ${ if (diff > 0) "Missing: ${SupportUtil.normalNumberFormat.format(diff)}" else "Excess: ${
SupportUtil.normalNumberFormat.format(-diff) SupportUtil.normalNumberFormat.format(-diff)
}$unit" }"
Text( Text(
diffText, diffText,
color = MaterialTheme.colors.error, color = MaterialTheme.colors.error,
@@ -636,7 +635,7 @@ fun OwerSelectionSection(
} }
} }
val splitOptions = listOf(SplitMode.EVEN, SplitMode.CUSTOM, SplitMode.PERCENT) val splitOptions = listOf(SplitMode.EVEN, SplitMode.CUSTOM, SplitMode.FRACTION)
Row( Row(
modifier = Modifier modifier = Modifier
.padding(start = 8.dp) .padding(start = 8.dp)
@@ -658,7 +657,7 @@ fun OwerSelectionSection(
text = when (mode) { text = when (mode) {
SplitMode.EVEN -> "=" SplitMode.EVEN -> "="
SplitMode.CUSTOM -> "#" SplitMode.CUSTOM -> "#"
SplitMode.PERCENT -> "%" SplitMode.FRACTION -> "÷"
}, },
color = if (isSelected) MaterialTheme.colors.onPrimary else MaterialTheme.colors.onSurface, color = if (isSelected) MaterialTheme.colors.onPrimary else MaterialTheme.colors.onSurface,
fontSize = 14.sp, fontSize = 14.sp,
@@ -698,18 +697,23 @@ fun OwerSelectionSection(
if (isSelected || viewModel.splitMode != SplitMode.EVEN) { if (isSelected || viewModel.splitMode != SplitMode.EVEN) {
val focusManager = LocalFocusManager.current val focusManager = LocalFocusManager.current
val interactionSource = remember { MutableInteractionSource() } val interactionSource = remember { MutableInteractionSource() }
val value = if (viewModel.splitMode == SplitMode.PERCENT) { val value = if (viewModel.splitMode == SplitMode.FRACTION) {
viewModel.owersPercentSplit[member.id] ?: "" viewModel.owersFractionSplit[member.id] ?: ""
} else { } else {
viewModel.owersCustomSplit[member.id] ?: "" viewModel.owersCustomSplit[member.id] ?: ""
} }
val fractionTotal = viewModel.getFractionTotal()
BasicTextField( BasicTextField(
value = value, value = value,
onValueChange = { nv -> onValueChange = { nv ->
val filteredValue = nv.filter { it in "0123456789,.+-*/" } val filteredValue = if (viewModel.splitMode == SplitMode.FRACTION) {
if (viewModel.splitMode == SplitMode.PERCENT) { nv.filter { it.isDigit() }
viewModel.owersPercentSplit[member.id] = filteredValue } else {
nv.filter { it in "0123456789,.+-*/" }
}
if (viewModel.splitMode == SplitMode.FRACTION) {
viewModel.owersFractionSplit[member.id] = filteredValue
} else { } else {
viewModel.owersCustomSplit[member.id] = filteredValue viewModel.owersCustomSplit[member.id] = filteredValue
} }
@@ -717,7 +721,7 @@ fun OwerSelectionSection(
}, },
modifier = Modifier modifier = Modifier
.width(80.dp) .width(80.dp)
.height(46.dp), .height(40.dp),
interactionSource = interactionSource, interactionSource = interactionSource,
singleLine = true, singleLine = true,
enabled = viewModel.splitMode != SplitMode.EVEN && canEdit, enabled = viewModel.splitMode != SplitMode.EVEN && canEdit,
@@ -737,12 +741,16 @@ fun OwerSelectionSection(
enabled = viewModel.splitMode != SplitMode.EVEN && canEdit, enabled = viewModel.splitMode != SplitMode.EVEN && canEdit,
interactionSource = interactionSource, interactionSource = interactionSource,
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp), contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp),
colors = TextFieldDefaults.textFieldColors( colors = TextFieldDefaults.outlinedTextFieldColors(
cursorColor = MaterialTheme.colors.onSurface, cursorColor = MaterialTheme.colors.onSurface,
backgroundColor = Color.Transparent, backgroundColor = MaterialTheme.colors.onSurface.copy(alpha = 0.02f),
unfocusedIndicatorColor = Color.Transparent, unfocusedBorderColor = MaterialTheme.colors.onSurface.copy(alpha = 0.2f),
disabledIndicatorColor = Color.Transparent focusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.7f),
) disabledBorderColor = MaterialTheme.colors.onSurface.copy(alpha = 0.14f)
),
trailingIcon = if (viewModel.splitMode == SplitMode.FRACTION && isSelected && fractionTotal > 0) {
{ Text("/$fractionTotal", color = MaterialTheme.colors.onSurface.copy(alpha = 0.65f)) }
} else null
) )
} }
} }
@@ -1011,24 +1019,24 @@ fun EditBillScreenCustomPreview() {
} }
@SuppressLint("ViewModelConstructorInComposable") @SuppressLint("ViewModelConstructorInComposable")
@Preview(showBackground = true, name = "Percent Split (%)") @Preview(showBackground = true, name = "Fraction Split")
@Composable @Composable
fun EditBillScreenPercentPreview() { fun EditBillScreenFractionPreview() {
MaterialTheme { MaterialTheme {
EditBillScreen( EditBillScreen(
viewModel = EditBillViewModel().apply { viewModel = EditBillViewModel().apply {
what = "Percent Split Pizza" what = "Fraction Split Pizza"
amount = "100.00" amount = "100.00"
mainCurrencyName = "EUR" mainCurrencyName = "EUR"
members = listOf( members = listOf(
DBMember(1, 0, 0, "Alice", true, 1.0, 0, null, null, null, null, null), DBMember(1, 0, 0, "Alice", true, 1.0, 0, null, null, null, null, null),
DBMember(2, 0, 0, "Bob", true, 1.0, 0, null, null, null, null, null) DBMember(2, 0, 0, "Bob", true, 1.0, 0, null, null, null, null, null)
) )
splitMode = SplitMode.PERCENT splitMode = SplitMode.FRACTION
owersSelection[1] = true owersSelection[1] = true
owersSelection[2] = true owersSelection[2] = true
owersPercentSplit[1] = "70" owersFractionSplit[1] = "1"
owersPercentSplit[2] = "30" owersFractionSplit[2] = "3"
}, },
categories = emptyList(), categories = emptyList(),
paymentModes = emptyList(), paymentModes = emptyList(),
@@ -18,7 +18,7 @@ import net.helcel.cowspent.util.SupportUtil
import net.helcel.cowspent.util.evalMath import net.helcel.cowspent.util.evalMath
enum class SplitMode { enum class SplitMode {
EVEN, CUSTOM, PERCENT EVEN, CUSTOM, FRACTION
} }
class EditBillViewModel : ViewModel() { class EditBillViewModel : ViewModel() {
@@ -55,7 +55,7 @@ class EditBillViewModel : ViewModel() {
var owersSelection = mutableStateMapOf<Long, Boolean>() var owersSelection = mutableStateMapOf<Long, Boolean>()
var splitMode by mutableStateOf(SplitMode.EVEN) var splitMode by mutableStateOf(SplitMode.EVEN)
var owersCustomSplit = mutableStateMapOf<Long, String>() var owersCustomSplit = mutableStateMapOf<Long, String>()
var owersPercentSplit = mutableStateMapOf<Long, String>() var owersFractionSplit = mutableStateMapOf<Long, String>()
var dialogState by mutableStateOf<DialogState?>(null) var dialogState by mutableStateOf<DialogState?>(null)
@@ -93,18 +93,16 @@ class EditBillViewModel : ViewModel() {
owersCustomSplit.remove(m.id) owersCustomSplit.remove(m.id)
} }
} }
} else if (splitMode == SplitMode.PERCENT) { } else if (splitMode == SplitMode.FRACTION) {
val selectedCount = owersSelection.count { it.value } val selectedCount = owersSelection.count { it.value }
if (selectedCount > 0) { if (selectedCount > 0) {
val evenPercent = 100.0 / selectedCount
val evenPercentStr = SupportUtil.round2(evenPercent).toString()
members.forEach { m -> members.forEach { m ->
if (owersSelection[m.id] == true) { if (owersSelection[m.id] == true) {
if (owersPercentSplit[m.id].isNullOrEmpty()) { if (owersFractionSplit[m.id].isNullOrEmpty()) {
owersPercentSplit[m.id] = evenPercentStr owersFractionSplit[m.id] = "1"
} }
} else { } else {
owersPercentSplit.remove(m.id) owersFractionSplit.remove(m.id)
} }
} }
} }
@@ -117,12 +115,12 @@ class EditBillViewModel : ViewModel() {
if (selected) { if (selected) {
if (splitMode == SplitMode.CUSTOM && owersCustomSplit[id].isNullOrEmpty()) { if (splitMode == SplitMode.CUSTOM && owersCustomSplit[id].isNullOrEmpty()) {
owersCustomSplit[id] = "0" owersCustomSplit[id] = "0"
} else if (splitMode == SplitMode.PERCENT && owersPercentSplit[id].isNullOrEmpty()) { } else if (splitMode == SplitMode.FRACTION && owersFractionSplit[id].isNullOrEmpty()) {
owersPercentSplit[id] = "0" owersFractionSplit[id] = "1"
} }
} else { } else {
owersCustomSplit.remove(id) owersCustomSplit.remove(id)
owersPercentSplit.remove(id) owersFractionSplit.remove(id)
} }
} else { } else {
updateSplits() updateSplits()
@@ -130,11 +128,8 @@ class EditBillViewModel : ViewModel() {
} }
fun getDiffSplit(): Double { fun getDiffSplit(): Double {
return if (splitMode == SplitMode.PERCENT) { return if (splitMode == SplitMode.FRACTION) {
val customTotal = owersPercentSplit.entries 0.0
.filter { owersSelection[it.key] == true }
.sumOf { parseAmountFromUi(it.value) }
SupportUtil.round2(100.0 - customTotal)
} else { } else {
val customTotal = owersCustomSplit.entries val customTotal = owersCustomSplit.entries
.filter { owersSelection[it.key] == true } .filter { owersSelection[it.key] == true }
@@ -143,6 +138,10 @@ class EditBillViewModel : ViewModel() {
} }
} }
fun getFractionTotal(): Int = owersFractionSplit.entries
.filter { owersSelection[it.key] == true }
.sumOf { it.value.toIntOrNull()?.coerceAtLeast(0) ?: 0 }
fun getOwersIds(): List<Long> { fun getOwersIds(): List<Long> {
return owersSelection.filter { it.value }.keys.toList() return owersSelection.filter { it.value }.keys.toList()
} }
@@ -258,7 +257,7 @@ class EditBillViewModel : ViewModel() {
owersSelection.clear() owersSelection.clear()
owersCustomSplit.clear() owersCustomSplit.clear()
owersPercentSplit.clear() owersFractionSplit.clear()
if (customSplits != null) { if (customSplits != null) {
splitMode = SplitMode.CUSTOM splitMode = SplitMode.CUSTOM