[insight] Household duplicates from shared subscription names
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
//! 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 fiscus_ledger::merchant::merchant_key;
|
||||
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()
|
||||
}
|
||||
@@ -3,4 +3,5 @@
|
||||
|
||||
pub mod cancel;
|
||||
pub mod forecast;
|
||||
pub mod household;
|
||||
pub mod subscriptions;
|
||||
|
||||
Reference in New Issue
Block a user