Files
FiscusPublic/crates/fiscus-ledger/src/split.rs
T

35 lines
1.3 KiB
Rust

//! Splitting one payment among people: shares in haléře that always sum to the payment's amount.
use crate::money::{split, Haler, MoneyError};
use serde::{Deserialize, Serialize};
/// Someone a payment can be split with: an app user (their id is their Tessera root) or a contact.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Person {
pub id: String,
pub name: String,
}
/// One person's part of a split. Same sign as the payment (an outflow's shares are negative).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Share {
pub person: String,
pub name: String,
pub amount: Haler,
}
/// Equal shares. The people are sorted by id and deduplicated first, so every device gets the same shares
/// whatever order they were picked in; the leftover haléře go to the first people in that order (the day-1
/// largest-remainder [`split`]).
pub fn split_equal(total: Haler, people: &[Person]) -> Result<Vec<Share>, MoneyError> {
let mut sorted: Vec<&Person> = people.iter().collect();
sorted.sort_by(|a, b| a.id.cmp(&b.id));
sorted.dedup_by(|a, b| a.id == b.id);
let amounts = split(total, &vec![1; sorted.len()])?;
Ok(sorted
.into_iter()
.zip(amounts)
.map(|(p, amount)| Share { person: p.id.clone(), name: p.name.clone(), amount })
.collect())
}