[ledger] Household: profile.named, household.sharing_set, member.named, subscriptions.shared; shared_names sends only service keys; v0.3.0
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
//! 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};
|
||||
|
||||
@@ -34,3 +36,16 @@ pub fn household_duplicates(shared: &[(String, Vec<String>)]) -> Vec<Duplicate>
|
||||
.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()
|
||||
}
|
||||
|
||||
@@ -23,6 +23,44 @@ fn two_members_paying_the_same_service_is_a_duplicate() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_shared_is_the_service_key_of_each_subscription_still_paid() {
|
||||
use fiscus_insight::household::shared_names;
|
||||
use fiscus_ledger::{Date, Decision, Event, EventBody, Haler, State, Timestamp};
|
||||
let d = |s: &str| s.parse::<Date>().unwrap();
|
||||
let mut log = Vec::new();
|
||||
for (i, m) in [1u32, 2, 3, 4].iter().enumerate() {
|
||||
for (j, merchant) in ["PAYPAL *SPOTIFY 4029357733", "NETFLIX.COM", "WEDOS INTERNET A.S.", "TV"].iter().enumerate() {
|
||||
log.push(Event::new(
|
||||
format!("p{i}{j}"),
|
||||
Timestamp(0),
|
||||
EventBody::PaymentAdded {
|
||||
payment: format!("p{i}{j}"),
|
||||
amount: Haler(-19_900),
|
||||
date: d(&format!("2026-{:02}-0{}", m + 6, j + 1)),
|
||||
merchant: merchant.to_string(),
|
||||
category: None,
|
||||
note: None,
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
let today = d("2026-10-20");
|
||||
let state = State::replay(&log);
|
||||
// Only the first word of the merchant key, so a reference number never leaves; "TV" is too short to say anything.
|
||||
assert_eq!(shared_names(&state, today), names(&["netflix", "spotify", "wedos"]));
|
||||
|
||||
log.push(Event::new(
|
||||
"cancel",
|
||||
Timestamp(0),
|
||||
EventBody::SubscriptionDecided { subscription: "netflix com".into(), decision: Decision::Cancel, amount: Haler(19_900), on: d("2026-10-05") },
|
||||
));
|
||||
let state = State::replay(&log);
|
||||
let key = fiscus_insight::subscriptions::analyse(&state, today).subscriptions.iter().find(|s| s.merchant.starts_with("NETFLIX")).map(|s| s.key.clone());
|
||||
assert_eq!(key.as_deref(), Some("netflix com"), "the decision above names Netflix's subscription key");
|
||||
assert_eq!(shared_names(&state, today), names(&["spotify", "wedos"]), "a cancelled one is not paid any more");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_member_alone_or_nobody_sharing_is_nothing() {
|
||||
assert!(household_duplicates(&[]).is_empty());
|
||||
|
||||
@@ -128,4 +128,17 @@ pub enum EventBody {
|
||||
/// The account people pay back to by QR Platba.
|
||||
#[serde(rename = "account.set")]
|
||||
AccountSet { iban: String, name: String },
|
||||
/// The name this person shows to the members of their shared budgets (the personal log).
|
||||
#[serde(rename = "profile.named")]
|
||||
ProfileNamed { name: String },
|
||||
/// Share my subscription names with this shared budget's members, or stop (the personal log).
|
||||
#[serde(rename = "household.sharing_set")]
|
||||
HouseholdSharingSet { budget: BudgetId, on: bool },
|
||||
/// A shared budget's log: the name its author shows there. The latest per author counts.
|
||||
#[serde(rename = "member.named")]
|
||||
MemberNamed { budget: BudgetId, name: String },
|
||||
/// A shared budget's log: every subscription its author pays, as service keys (`spotify`). The latest per
|
||||
/// author replaces the earlier ones; an empty list withdraws them.
|
||||
#[serde(rename = "subscriptions.shared")]
|
||||
SubscriptionsShared { budget: BudgetId, names: Vec<String> },
|
||||
}
|
||||
|
||||
@@ -171,6 +171,10 @@ pub struct State {
|
||||
/// SHA-256 (hex) of a share link's token → the link.
|
||||
pub share_links: BTreeMap<String, ShareLink>,
|
||||
pub account: Option<Account>,
|
||||
/// The name shown to the members of my shared budgets (`profile.named`).
|
||||
pub profile_name: Option<String>,
|
||||
/// The shared budgets I share my subscription names with (`household.sharing_set`).
|
||||
pub household_sharing: BTreeSet<BudgetId>,
|
||||
pub rejected: Vec<Rejection>,
|
||||
}
|
||||
|
||||
@@ -208,6 +212,10 @@ pub struct EffectivePayment {
|
||||
pub trial_ends: Option<Date>,
|
||||
}
|
||||
|
||||
/// A person's name, or one shared subscription name.
|
||||
const MAX_PERSON: usize = 40;
|
||||
const MAX_SHARED_NAMES: usize = 100;
|
||||
|
||||
fn text_ok(s: &str) -> bool {
|
||||
s.chars().count() <= MAX_TEXT && !s.chars().any(|c| c.is_control())
|
||||
}
|
||||
@@ -586,6 +594,44 @@ impl State {
|
||||
}
|
||||
self.account = Some(Account { iban: iban.as_str().into(), name: name.trim().into() });
|
||||
}
|
||||
EventBody::ProfileNamed { name } => {
|
||||
if !name_ok(name, MAX_PERSON) {
|
||||
return Err("a name must be 1-40 characters");
|
||||
}
|
||||
self.profile_name = Some(name.trim().into());
|
||||
}
|
||||
EventBody::HouseholdSharingSet { budget, on } => {
|
||||
if !self.budgets.contains_key(budget) || self.default_budget.as_ref() == Some(budget) {
|
||||
return Err("subscription names are shared only with a shared budget");
|
||||
}
|
||||
if *on {
|
||||
self.household_sharing.insert(budget.clone());
|
||||
} else {
|
||||
self.household_sharing.remove(budget);
|
||||
}
|
||||
}
|
||||
EventBody::MemberNamed { budget, name } => {
|
||||
if !self.budgets.contains_key(budget) {
|
||||
return Err("no such budget");
|
||||
}
|
||||
if !name_ok(name, MAX_PERSON) {
|
||||
return Err("a name must be 1-40 characters");
|
||||
}
|
||||
}
|
||||
EventBody::SubscriptionsShared { budget, names } => {
|
||||
if !self.budgets.contains_key(budget) {
|
||||
return Err("no such budget");
|
||||
}
|
||||
if names.len() > MAX_SHARED_NAMES {
|
||||
return Err("at most 100 subscription names");
|
||||
}
|
||||
if names.iter().any(|n| !name_ok(n, MAX_PERSON) || n.trim() != n) {
|
||||
return Err("a subscription name must be 1-40 characters");
|
||||
}
|
||||
if names.iter().collect::<BTreeSet<_>>().len() != names.len() {
|
||||
return Err("a subscription name appears twice");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
//! v1 close: the name a person shows to the members of their shared budgets, the opt-in to share
|
||||
//! subscription names with a shared budget, and what a shared budget's log may hold of either.
|
||||
|
||||
use fiscus_ledger::{Event, EventBody, Haler, State, Timestamp};
|
||||
|
||||
fn ev(id: &str, body: EventBody) -> Event {
|
||||
Event::new(id, Timestamp(0), body)
|
||||
}
|
||||
|
||||
fn budgets() -> Vec<Event> {
|
||||
vec![
|
||||
ev("e1", EventBody::BudgetCreated { budget: "b-mine".into(), name: "Mine".into(), limit: Haler(1_000_000) }),
|
||||
ev("e2", EventBody::BudgetShared { budget: "b-home".into(), name: "Home".into(), limit: Haler(2_000_000) }),
|
||||
]
|
||||
}
|
||||
|
||||
fn rejected(log: &[Event]) -> Vec<String> {
|
||||
State::replay(log).rejected.iter().map(|r| r.reason.clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_profile_name_is_the_latest_trimmed_and_bounded() {
|
||||
let mut log = budgets();
|
||||
log.push(ev("n1", EventBody::ProfileNamed { name: " Mark ".into() }));
|
||||
log.push(ev("n2", EventBody::ProfileNamed { name: "Marek".into() }));
|
||||
assert_eq!(State::replay(&log).profile_name.as_deref(), Some("Marek"));
|
||||
|
||||
for bad in ["", " ", "a\u{7}b", &"x".repeat(41)] {
|
||||
let mut log = budgets();
|
||||
log.push(ev("n", EventBody::ProfileNamed { name: bad.into() }));
|
||||
assert_eq!(rejected(&log).len(), 1, "{bad:?} is not a name");
|
||||
assert_eq!(State::replay(&log).profile_name, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subscription_sharing_is_an_opt_in_per_shared_budget() {
|
||||
let mut log = budgets();
|
||||
log.push(ev("h1", EventBody::HouseholdSharingSet { budget: "b-home".into(), on: true }));
|
||||
assert!(State::replay(&log).household_sharing.contains("b-home"));
|
||||
log.push(ev("h2", EventBody::HouseholdSharingSet { budget: "b-home".into(), on: false }));
|
||||
assert!(State::replay(&log).household_sharing.is_empty(), "opting out takes it back");
|
||||
|
||||
let mut log = budgets();
|
||||
log.push(ev("h1", EventBody::HouseholdSharingSet { budget: "b-mine".into(), on: true }));
|
||||
log.push(ev("h2", EventBody::HouseholdSharingSet { budget: "b-none".into(), on: true }));
|
||||
assert_eq!(rejected(&log).len(), 2, "never the default budget, never an unknown one");
|
||||
assert!(State::replay(&log).household_sharing.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_name_and_shared_subscription_names_need_the_budget_and_are_bounded() {
|
||||
let group = vec![ev("g1", EventBody::BudgetCreated { budget: "b-home".into(), name: "Home".into(), limit: Haler(0) })];
|
||||
let ok = |body: EventBody| {
|
||||
let mut log = group.clone();
|
||||
log.push(ev("x", body));
|
||||
rejected(&log).is_empty()
|
||||
};
|
||||
let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
|
||||
assert!(ok(EventBody::MemberNamed { budget: "b-home".into(), name: "Jana".into() }));
|
||||
assert!(!ok(EventBody::MemberNamed { budget: "b-other".into(), name: "Jana".into() }));
|
||||
assert!(!ok(EventBody::MemberNamed { budget: "b-home".into(), name: " ".into() }));
|
||||
|
||||
assert!(ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: names(&["spotify", "netflix"]) }));
|
||||
assert!(ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: vec![] }), "an empty list withdraws them");
|
||||
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-other".into(), names: names(&["spotify"]) }));
|
||||
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: names(&["spotify", "spotify"]) }));
|
||||
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: names(&[""]) }));
|
||||
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: vec!["x".repeat(41)] }));
|
||||
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: (0..101).map(|i| format!("s{i}")).collect() }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_events_round_trip_as_json_with_their_type_tags() {
|
||||
for (body, tag) in [
|
||||
(EventBody::ProfileNamed { name: "Mark".into() }, "profile.named"),
|
||||
(EventBody::HouseholdSharingSet { budget: "b".into(), on: true }, "household.sharing_set"),
|
||||
(EventBody::MemberNamed { budget: "b".into(), name: "Mark".into() }, "member.named"),
|
||||
(EventBody::SubscriptionsShared { budget: "b".into(), names: vec!["spotify".into()] }, "subscriptions.shared"),
|
||||
] {
|
||||
let json = serde_json::to_value(&body).unwrap();
|
||||
assert_eq!(json["type"], tag);
|
||||
assert_eq!(serde_json::from_value::<EventBody>(json).unwrap(), body);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user