52 lines
2.1 KiB
Rust
52 lines
2.1 KiB
Rust
//! Household duplicates: two or more members paying for the same service ("You both pay Spotify"). Runs only
|
|
//! on the subscription names members chose to share into the household budget.
|
|
|
|
use crate::subscriptions::{analyse, Status};
|
|
use fiscus_ledger::merchant::merchant_key;
|
|
use fiscus_ledger::{Date, State};
|
|
use serde::Serialize;
|
|
use std::collections::{BTreeMap, BTreeSet};
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
|
pub struct Duplicate {
|
|
/// The service: the first word of the merchant key (`PAYPAL *SPOTIFY`, `Spotify AB` → `spotify`).
|
|
pub key: String,
|
|
/// Who pays it, sorted.
|
|
pub members: Vec<String>,
|
|
}
|
|
|
|
/// The first word of the merchant key, if it is at least three letters long.
|
|
pub fn service_key(name: &str) -> Option<String> {
|
|
let key = merchant_key(name);
|
|
let first = key.split(' ').next()?;
|
|
(first.chars().count() >= 3).then(|| first.to_string())
|
|
}
|
|
|
|
/// `(member, the subscription names they shared)` → every service two or more members pay, by key.
|
|
pub fn household_duplicates(shared: &[(String, Vec<String>)]) -> Vec<Duplicate> {
|
|
let mut by_key: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
|
|
for (member, names) in shared {
|
|
for key in names.iter().filter_map(|n| service_key(n)) {
|
|
by_key.entry(key).or_default().insert(member.clone());
|
|
}
|
|
}
|
|
by_key
|
|
.into_iter()
|
|
.filter(|(_, m)| m.len() >= 2)
|
|
.map(|(key, m)| Duplicate { key, members: m.into_iter().collect() })
|
|
.collect()
|
|
}
|
|
|
|
/// What a member who opted in shares: the service key of every subscription they still pay (active, or charged
|
|
/// after a cancel), sorted, at most 100. Only the key leaves, never the merchant text with its references.
|
|
pub fn shared_names(state: &State, today: Date) -> Vec<String> {
|
|
let keys: BTreeSet<String> = analyse(state, today)
|
|
.subscriptions
|
|
.iter()
|
|
.filter(|s| matches!(s.status, Status::Active | Status::ChargedAfterCancel))
|
|
.filter_map(|s| service_key(&s.merchant))
|
|
.filter(|k| k.chars().count() <= 40)
|
|
.collect();
|
|
keys.into_iter().take(100).collect()
|
|
}
|